WeKnora/internal/handler/session/resolve_agent_test.go

262 lines
9.8 KiB
Go
Raw Normal View History

package session
import (
"context"
fix(security): close cross-workspace access paths in shared spaces (#3408) * fix(security): close cross-workspace access paths in shared spaces A review of how shared-space (organization) members reach each other's resources found six paths that bypass the org-share permission model: - presigned-preview signed any resource handle or storage path, turning a known resource:// handle into an anonymous /r/ URL that outlives share revocation. It now requires the path to belong to the caller's tenant, like /files. - POST /initialization/initialize let a shared-KB editor rewrite the owner workspace's models (base URL, API key) in place. Only the KB's own workspace may call it, and rewriting a stored model needs the same authority as PUT /models/:id. - KB JSON carried the legacy inline credentials (storage_config secret_id/secret_key, which initialization fills with the MinIO env keys, and vlm_config api_key) to every share receiver. They are withheld from JSON; their DB columns are unchanged. - A chat without agent_source_tenant_id resolved shares before the caller's own agent, so a member sharing a same-ID built-in agent took over other workspaces' default agent. Own agents now win, built-in agents can no longer be shared (existing such shares no longer resolve), and embed channels drop a visitor-supplied source workspace. - Any org-admin tenant (even a tenant Viewer inside it) could raise another workspace's KB share to editor/admin, and the route guard was bypassable via an unrelated :id. Share management is now: the sharer from the source tenant (Contributor+), source-tenant Admin+, or an org-admin tenant's Admin+ that may only remove or lower. share_id must belong to :id. - Wiki write tools were registered for every wiki KB in the search targets, which only need read access, so a viewer share (e.g. via the built-in wiki fixer) could edit or delete another workspace's wiki pages. They now act only on KBs the caller may edit. * fix(security): close the KB settings path and owner details for share receivers Follow-up to the shared-space review: - PUT /initialization/config shares the route guard that admits share editors, so an editor could still rebind the owner's KB models, chunking and storage, and storage backends resolved against the caller's workspace let it bind the owner's KB to its own backend. Another workspace now needs an admin share (the only share level the frontend offers settings to) and may not change the storage binding at all. - GET /initialization/config showed model base URLs and bucket locations to any admin of the caller's own workspace, including share receivers. They now only see whether credentials are configured. - Wiki write tools on the caller's own KBs had no role floor, so a tenant Viewer (and the IM, embed and MCP endpoint principals that run as Viewer) could write through an agent what the HTTP routes deny. Writes now need Contributor+, or the ingest capability for a scoped API key, following the RBAC rollout switch. - resolveAgent logs the share lookup error instead of a nil own-agent error when a shared selector fails. * fix(security): close the medium shared-space access findings Follow-up to the high-risk fixes, from the same review: - Wiki fixer moved into a shared KB's workspace ran with the caller's own config there: an unset MCP mode registered all of the owner's MCP services, and an "all" KB scope reached the owner's other KBs. The scoped run now uses the built-in config pinned to that one KB, without MCP, skills, sandbox or web search, and falls back to the KB's own model. - An unset MCP mode means "all" at runtime but is shown as none in the share scope; shared runs now treat it as none. - Quick-answer mode used the request's web_search_enabled alone, so a receiver could turn on search the agent disables and spend the owner's provider quota. It now requires the agent setting too, as agent mode does. - summary_model_id picked any model of the workspace a run executes in. It is ignored for shared agents and the relocated wiki fixer. - A workspace that left or was removed from an organization kept sharing its KBs and agents. Its shares are revoked on departure, and share queries and permission checks require the source workspace's membership and a live organization, which also covers rows left behind earlier. - Sharing an agent exposes its KB scope to all members, so a Contributor could share colleagues' KBs (or "all") through an agent. The sharer must now be able to share each KB directly (creator or Admin+; "all" needs Admin+), also when a shared agent's scope is widened later. - A scoped API key with manage_channels could mint an MCP endpoint token wider than itself. Endpoints it creates, updates or rotates must stay within its KB allow-list and capabilities. - A shared agent's run indexed the receiver's Q&A into the owner's chat history KB; indexing now uses the session owner's configuration. - Sharing an agent with skills keeps injecting the owner's skill environment values (product decision); the share panel now warns that members can read them. Preview of originals through read-only shares is kept as designed and documented.
2026-09-18 14:00:02 +00:00
"errors"
"net/http"
"net/http/httptest"
"testing"
fix(sandbox): resolve a session's pinned sandbox in the workspace that owns it (#3471) * fix(sandbox): resolve a session's pinned sandbox in the workspace that owns it tenant_sandbox_configs is keyed by (tenant_id, id), so a config id is not an address on its own. sessions.sandbox_config_id stored only the id and every reader took the workspace from the ambient request context. That holds inside a chat turn, which already runs under the agent's workspace (WithExecutionTenant in the QA handler). It breaks for a shared agent everywhere else, because a shared agent runs on ITS OWNER's sandbox config while the session belongs to the borrower, and these paths run from plain requests whose only tenant is the session owner's: * DeleteSession resolved nothing and returned after a warning. Cube and E2B create session sandboxes with onTimeout=pause, so the MicroVM was not reclaimed later either: it stayed paused, billing, with nobody holding its id. ReapOrphanSandboxes has no production caller, so nothing recovered it. * The terminal and desktop panels failed on both branches - attaching to the pinned sandbox and provisioning a new one - with ErrSandboxConfigNotFound, which terminalErrorFrame maps to a bare INTERNAL close reason. The panel is offered unconditionally and already forwards agent_source_tenant_id, so this was a dead end the user could reach in one click. * Fork read the pin through PinnedSessionSandbox, got no manager, and silently degraded to SNAPSHOT_UNSUPPORTED, losing the sandbox state. * The fork snapshot lease recorded the session's workspace next to the lending workspace's config id, so the reaper could not resolve it either. Record the owning workspace beside the pin and make the pair travel together as SandboxPin. Readers now take the workspace from the pin and fall back to the session's own, which is what every non-borrowed pin (and every row written before this column) resolves to - so behaviour for own agents is unchanged. The provision path has no pin yet, so the WebSocket handler passes the agent's workspace along with its config: terminalProvisionPin already resolved the shared agent, it just discarded the tenant resolveAgent handed back. Backfill in the migration is limited to sessions whose pinned config does not exist in their own workspace - the only ones that can have borrowed it - using the lending workspace recorded on their newest shared-agent message. Lite has no shared spaces, so the SQLite mirror adds the column without a backfill. * fix(sandbox): backfill the pin owner from the config row and self-heal legacy pins Three gaps in the session sandbox pin owner: Backfilling from messages.agent_tenant_id names the wrong workspace. The pin is sticky to the session's FIRST sandbox, while the newest message carrying agent_tenant_id may belong to a later shared agent from another workspace. Writing that tenant leaves teardown resolving a config the workspace does not own - the very failure the column exists to fix. tenant_sandbox_configs.id is a global UUID primary key, so joining the config row itself names the workspace that actually owns the pin. The column was INTEGER while every other tenant id is BIGINT/uint64. Postgres INTEGER is 32-bit signed, so a large tenant id would not fit. Rows the SQL backfill cannot reach keep sandbox_config_tenant_id = 0 forever: the reader falls back to the caller's workspace but never records what it learned. The next chat turn already runs under the workspace that can resolve the config, so persisting it there is what lets a later DELETE, panel open or fork find the sandbox. recordOwner only writes when the lookup actually succeeded and the stored owner is still unset - stamping the caller's tenant onto a failed lookup would brand a sticky pin left by a previous shared agent with the wrong workspace. Also renames the lentSandboxConfg typo and corrects the fork degrade reason in a comment: a lent config that resolves to nil fails BoundSandboxID, so the fork degrades to SANDBOX_GONE, not SNAPSHOT_UNSUPPORTED. * fix(sandbox): require a named backend before recording a pin's owner The self-heal wants to persist an owner "that actually resolved this config", but a nil error does not prove that. resolveTenantSandboxForConfig returns a disabled manager with no error twice before it ever reads the config row: for the workspace kill switch, and for an empty or deployment-default config id. That reopens the leak this column exists to close. The SQL backfill correctly leaves sandbox_config_tenant_id at 0 whenever the pinned config belongs to the session's own workspace, which is most existing rows. One turn of a shared agent lent by a workspace whose admin has script execution turned off then short-circuits on the kill switch, returns nil, and stamps that lending workspace onto a config it does not own. The next DELETE resolves the pin there, finds nothing, and strands the paused MicroVM. The pin branch runs before agentConfigID is read, so the shared agent does not even need a sandbox config of its own to trigger it. A named backend (Cube/E2B/Docker) is the proof, and it is the same condition that is already allowed to CREATE a pin further down: what may write a pin may update whose it is. A config that exists but resolves to type "disabled" is skipped as well - ownership is genuine there, but such a config never creates a sandbox, so no teardown can go missing. The deployment-default pin was inert either way (both workspaces short-circuit to a manager with no DestroySession), but it is covered too so a later relaxation of the proof cannot quietly reopen the kill-switch case. Both tests fail without the guard. --------- Co-authored-by: hailongzhao <hailongzhao@tencent.com>
2026-09-21 07:38:39 +00:00
"github.com/Tencent/WeKnora/internal/application/service"
"github.com/Tencent/WeKnora/internal/types"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
)
type resolveAgentShareStub struct {
agent *types.CustomAgent
err error
}
func (s *resolveAgentShareStub) GetSharedAgentForTenant(
_ context.Context,
_ uint64,
_ types.TenantRole,
_ string,
_ ...uint64,
) (*types.CustomAgent, error) {
return s.agent, s.err
}
func (s *resolveAgentShareStub) ShareAgent(context.Context, string, string, string, uint64, types.OrgMemberRole) (*types.AgentShare, error) {
panic("not implemented")
}
func (s *resolveAgentShareStub) RemoveShare(context.Context, string, string, uint64) error {
panic("not implemented")
}
func (s *resolveAgentShareStub) ListSharesByAgent(context.Context, string, uint64) ([]*types.AgentShare, error) {
panic("not implemented")
}
func (s *resolveAgentShareStub) ListSharesByOrganization(context.Context, string) ([]*types.AgentShare, error) {
panic("not implemented")
}
func (s *resolveAgentShareStub) ListSharedAgents(context.Context, uint64, types.TenantRole) ([]*types.SharedAgentInfo, error) {
panic("not implemented")
}
func (s *resolveAgentShareStub) ListSharedAgentsInOrganization(context.Context, string, uint64, types.TenantRole) ([]*types.OrganizationSharedAgentItem, error) {
panic("not implemented")
}
func (s *resolveAgentShareStub) ListSharedAgentsInOrganizations(context.Context, []string, uint64, types.TenantRole) (map[string][]*types.OrganizationSharedAgentItem, error) {
panic("not implemented")
}
func (s *resolveAgentShareStub) SetSharedAgentDisabledByMe(context.Context, uint64, string, uint64, bool) error {
panic("not implemented")
}
func (s *resolveAgentShareStub) TenantCanAccessKBViaSomeSharedAgent(context.Context, uint64, types.TenantRole, *types.KnowledgeBase) (bool, error) {
panic("not implemented")
}
func (s *resolveAgentShareStub) GetShare(context.Context, string) (*types.AgentShare, error) {
panic("not implemented")
}
func (s *resolveAgentShareStub) GetShareByAgentAndOrg(context.Context, string, string) (*types.AgentShare, error) {
panic("not implemented")
}
func (s *resolveAgentShareStub) GetShareByAgentIDForTenant(context.Context, uint64, string, uint64) (*types.AgentShare, error) {
panic("not implemented")
}
func (s *resolveAgentShareStub) CountByOrganizations(context.Context, []string) (map[string]int64, error) {
panic("not implemented")
}
type resolveOwnAgentStub struct {
agent *types.CustomAgent
err error
}
func (s *resolveOwnAgentStub) GetAgentByID(context.Context, string) (*types.CustomAgent, error) {
return s.agent, s.err
}
func (s *resolveOwnAgentStub) CreateAgent(context.Context, *types.CustomAgent) (*types.CustomAgent, error) {
panic("not implemented")
}
func (s *resolveOwnAgentStub) GetAgentByIDAndTenant(context.Context, string, uint64) (*types.CustomAgent, error) {
panic("not implemented")
}
func (s *resolveOwnAgentStub) ListAgents(context.Context) ([]*types.CustomAgent, error) {
panic("not implemented")
}
fix(agent): PUT no longer erases the avatar, and driver errors stay server-side (#3230) * fix(agent): PUT no longer erases the avatar, and driver errors stay server-side Two defects in the custom-agent API, both of which surface as a successful or misleading response. 1. A config-only PUT wiped the avatar. UpdateAgentRequest.Avatar was a plain string, so "field omitted" and "explicit clear" were indistinguishable, and UpdateAgent assigned it unconditionally. Any caller that updated only the config — which is what an edit form or an SDK client does when it sends the config it changed — silently zeroed the avatar and still received 200. Avatar now travels as *string end to end: nil keeps the stored value, a pointer to "" is an explicit clear. The service takes it as a separate argument because *types.CustomAgent cannot express the difference. 2. Raw repository/driver errors reached the client. The fallback branches forwarded err.Error() verbatim, so a postgres message — for example "ERROR: value too long for type character varying(64) (SQLSTATE 22001)" — was returned in the API response. That leaks schema details and tells the caller nothing actionable. Each fallback now returns a fixed message naming the operation; the full error is still logged immediately above, so nothing is lost for diagnosis. The same oversized-avatar case is now rejected earlier, by ValidateAvatar, as a 400 that names the varchar(64) limit instead of a 500 produced by the database. Typed sentinels and *errors.AppError keep their existing behaviour — only the untyped fallbacks changed. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(agent): complete avatar preservation and regression coverage --------- Co-authored-by: Claude Opus 5 <noreply@anthropic.com> Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-09-14 12:50:15 +00:00
func (s *resolveOwnAgentStub) UpdateAgent(
context.Context, *types.CustomAgent, *string,
) (*types.CustomAgent, error) {
panic("not implemented")
}
func (s *resolveOwnAgentStub) DeleteAgent(context.Context, string) error {
panic("not implemented")
}
func (s *resolveOwnAgentStub) CopyAgent(context.Context, string) (*types.CustomAgent, error) {
panic("not implemented")
}
func (s *resolveOwnAgentStub) GetSuggestedQuestions(context.Context, string, []string, []string, []types.TagScope, int) ([]types.SuggestedQuestion, error) {
panic("not implemented")
}
func (s *resolveOwnAgentStub) GetKnowledgeSuggestedQuestions(context.Context, string, []string, []string, []types.TagScope, int) ([]types.SuggestedQuestion, error) {
panic("not implemented")
}
func newResolveAgentTestContext(tenantID uint64) (*gin.Context, context.Context) {
gin.SetMode(gin.TestMode)
rec := httptest.NewRecorder()
c, _ := gin.CreateTestContext(rec)
c.Request = httptest.NewRequest(http.MethodPost, "/", nil)
c.Set(types.UserIDContextKey.String(), "user-1")
c.Set(types.TenantIDContextKey.String(), tenantID)
ctx := context.WithValue(c.Request.Context(), types.TenantIDContextKey, tenantID)
c.Request = c.Request.WithContext(ctx)
return c, ctx
}
func TestResolveAgent_RejectsInvalidSharedSelectorWithoutLocalFallback(t *testing.T) {
c, ctx := newResolveAgentTestContext(7)
localAgent := &types.CustomAgent{ID: "builtin-smart-reasoning", TenantID: 7, Name: "Local"}
h := &Handler{
agentShareService: &resolveAgentShareStub{},
customAgentService: &resolveOwnAgentStub{agent: localAgent},
}
agent, effectiveTenantID, sharedReadOnly := h.resolveAgent(ctx, c, "builtin-smart-reasoning", 84)
require.Nil(t, agent)
require.Equal(t, uint64(0), effectiveTenantID)
require.False(t, sharedReadOnly)
}
func TestResolveAgent_UsesSharedAgentWhenSourceSelectorMatches(t *testing.T) {
c, ctx := newResolveAgentTestContext(7)
sharedAgent := &types.CustomAgent{ID: "builtin-smart-reasoning", TenantID: 84, Name: "Shared"}
h := &Handler{
agentShareService: &resolveAgentShareStub{agent: sharedAgent},
customAgentService: &resolveOwnAgentStub{agent: &types.CustomAgent{ID: "builtin-smart-reasoning", TenantID: 7}},
}
agent, effectiveTenantID, sharedReadOnly := h.resolveAgent(ctx, c, "builtin-smart-reasoning", 84)
require.Equal(t, sharedAgent, agent)
require.Equal(t, uint64(84), effectiveTenantID)
require.True(t, sharedReadOnly)
}
func TestResolveAgent_FallsBackToLocalAgentWithoutSourceSelector(t *testing.T) {
c, ctx := newResolveAgentTestContext(7)
localAgent := &types.CustomAgent{ID: "builtin-smart-reasoning", TenantID: 7, Name: "Local"}
h := &Handler{
agentShareService: &resolveAgentShareStub{},
customAgentService: &resolveOwnAgentStub{agent: localAgent},
}
agent, effectiveTenantID, sharedReadOnly := h.resolveAgent(ctx, c, "builtin-smart-reasoning", 0)
require.Equal(t, localAgent, agent)
require.Equal(t, uint64(0), effectiveTenantID)
require.False(t, sharedReadOnly)
}
feat(sandbox): add an interactive terminal and files tab beside chat (#3110) * feat(sandbox): stream interactive PTYs from Cube and E2B Give session sandboxes a provider-neutral terminal capability so a later WebSocket layer can attach without knowing Cube vs E2B. Long-lived streams use a timeout-free client; idle terminals keep the sandbox alive by refreshing TTL, and a workspace can set how long to wait before disconnect. * feat(session): bridge browser terminals to the session sandbox Mint a short-lived ticket over a normal authenticated POST so the browser WebSocket never puts the access JWT in the query string. After upgrade, recheck the bound token, membership, and session ownership so logout or revocation tears the PTY down. Provisioning stays opt-in: a GET handshake only creates a sandbox when the client sends provision=1. * feat(chat): add a sandbox terminal panel beside the conversation Open a side panel with an xterm attached to the session sandbox. Starting the terminal is an explicit click so merely opening the panel does not create or resume a microVM; reconnects stay lookup-only until the user confirms create-and-start. Persist the remote shell PID in sessionStorage so a refresh reattaches instead of spawning an orphan. * feat(sandbox): let workspaces set terminal idle disconnect Expose the idle-disconnect duration in the sandbox config editor so an operator can close unused terminals and let the provider TTL pause the sandbox, instead of leaving PTYs open for the built-in 15 minutes. * feat(chat): show generated files in the sandbox side panel Move the per-message artifact list into the first tab of the right-hand panel so generated files stay in view with the terminal. Keep the old drawer only for embedded chat. * fix(sandbox-terminal): keep tickets out of logs and live PTYs across refresh Gin was copying the handshake JWT into response_body logs, silent access-token rotation dropped open terminals as AUTH_REVOKED, and first-use provisioning missed shared agents. Local echo now skips password prompts. --------- Co-authored-by: hailongzhao <hailongzhao@tencent.com> Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-09-08 09:43:15 +00:00
fix(security): close cross-workspace access paths in shared spaces (#3408) * fix(security): close cross-workspace access paths in shared spaces A review of how shared-space (organization) members reach each other's resources found six paths that bypass the org-share permission model: - presigned-preview signed any resource handle or storage path, turning a known resource:// handle into an anonymous /r/ URL that outlives share revocation. It now requires the path to belong to the caller's tenant, like /files. - POST /initialization/initialize let a shared-KB editor rewrite the owner workspace's models (base URL, API key) in place. Only the KB's own workspace may call it, and rewriting a stored model needs the same authority as PUT /models/:id. - KB JSON carried the legacy inline credentials (storage_config secret_id/secret_key, which initialization fills with the MinIO env keys, and vlm_config api_key) to every share receiver. They are withheld from JSON; their DB columns are unchanged. - A chat without agent_source_tenant_id resolved shares before the caller's own agent, so a member sharing a same-ID built-in agent took over other workspaces' default agent. Own agents now win, built-in agents can no longer be shared (existing such shares no longer resolve), and embed channels drop a visitor-supplied source workspace. - Any org-admin tenant (even a tenant Viewer inside it) could raise another workspace's KB share to editor/admin, and the route guard was bypassable via an unrelated :id. Share management is now: the sharer from the source tenant (Contributor+), source-tenant Admin+, or an org-admin tenant's Admin+ that may only remove or lower. share_id must belong to :id. - Wiki write tools were registered for every wiki KB in the search targets, which only need read access, so a viewer share (e.g. via the built-in wiki fixer) could edit or delete another workspace's wiki pages. They now act only on KBs the caller may edit. * fix(security): close the KB settings path and owner details for share receivers Follow-up to the shared-space review: - PUT /initialization/config shares the route guard that admits share editors, so an editor could still rebind the owner's KB models, chunking and storage, and storage backends resolved against the caller's workspace let it bind the owner's KB to its own backend. Another workspace now needs an admin share (the only share level the frontend offers settings to) and may not change the storage binding at all. - GET /initialization/config showed model base URLs and bucket locations to any admin of the caller's own workspace, including share receivers. They now only see whether credentials are configured. - Wiki write tools on the caller's own KBs had no role floor, so a tenant Viewer (and the IM, embed and MCP endpoint principals that run as Viewer) could write through an agent what the HTTP routes deny. Writes now need Contributor+, or the ingest capability for a scoped API key, following the RBAC rollout switch. - resolveAgent logs the share lookup error instead of a nil own-agent error when a shared selector fails. * fix(security): close the medium shared-space access findings Follow-up to the high-risk fixes, from the same review: - Wiki fixer moved into a shared KB's workspace ran with the caller's own config there: an unset MCP mode registered all of the owner's MCP services, and an "all" KB scope reached the owner's other KBs. The scoped run now uses the built-in config pinned to that one KB, without MCP, skills, sandbox or web search, and falls back to the KB's own model. - An unset MCP mode means "all" at runtime but is shown as none in the share scope; shared runs now treat it as none. - Quick-answer mode used the request's web_search_enabled alone, so a receiver could turn on search the agent disables and spend the owner's provider quota. It now requires the agent setting too, as agent mode does. - summary_model_id picked any model of the workspace a run executes in. It is ignored for shared agents and the relocated wiki fixer. - A workspace that left or was removed from an organization kept sharing its KBs and agents. Its shares are revoked on departure, and share queries and permission checks require the source workspace's membership and a live organization, which also covers rows left behind earlier. - Sharing an agent exposes its KB scope to all members, so a Contributor could share colleagues' KBs (or "all") through an agent. The sharer must now be able to share each KB directly (creator or Admin+; "all" needs Admin+), also when a shared agent's scope is widened later. - A scoped API key with manage_channels could mint an MCP endpoint token wider than itself. Endpoints it creates, updates or rotates must stay within its KB allow-list and capabilities. - A shared agent's run indexed the receiver's Q&A into the owner's chat history KB; indexing now uses the session owner's configuration. - Sharing an agent with skills keeps injecting the owner's skill environment values (product decision); the share panel now warns that members can read them. Preview of originals through read-only shares is kept as designed and documented.
2026-09-18 14:00:02 +00:00
// Built-in IDs exist in every workspace. Without a source selector a share of
// the same ID must not replace the caller's own agent.
func TestResolveAgent_PrefersOwnAgentOverSameIDShareWithoutSourceSelector(t *testing.T) {
c, ctx := newResolveAgentTestContext(7)
localAgent := &types.CustomAgent{ID: "builtin-quick-answer", TenantID: 7, Name: "Local"}
h := &Handler{
agentShareService: &resolveAgentShareStub{
agent: &types.CustomAgent{ID: "builtin-quick-answer", TenantID: 84, Name: "Shared"},
},
customAgentService: &resolveOwnAgentStub{agent: localAgent},
}
agent, effectiveTenantID, sharedReadOnly := h.resolveAgent(ctx, c, "builtin-quick-answer", 0)
require.Equal(t, localAgent, agent)
require.Equal(t, uint64(0), effectiveTenantID)
require.False(t, sharedReadOnly)
}
// A shared agent without the source selector (e.g. a restored selection) still
// resolves when the caller has no agent of that ID.
func TestResolveAgent_UsesShareWhenNoOwnAgentMatches(t *testing.T) {
c, ctx := newResolveAgentTestContext(7)
sharedAgent := &types.CustomAgent{ID: "3f0c2d9e-shared", TenantID: 84, Name: "Shared"}
h := &Handler{
agentShareService: &resolveAgentShareStub{agent: sharedAgent},
customAgentService: &resolveOwnAgentStub{err: errors.New("agent not found")},
}
agent, effectiveTenantID, sharedReadOnly := h.resolveAgent(ctx, c, sharedAgent.ID, 0)
require.Equal(t, sharedAgent, agent)
require.Equal(t, uint64(84), effectiveTenantID)
require.True(t, sharedReadOnly)
}
fix(sandbox): resolve a session's pinned sandbox in the workspace that owns it (#3471) * fix(sandbox): resolve a session's pinned sandbox in the workspace that owns it tenant_sandbox_configs is keyed by (tenant_id, id), so a config id is not an address on its own. sessions.sandbox_config_id stored only the id and every reader took the workspace from the ambient request context. That holds inside a chat turn, which already runs under the agent's workspace (WithExecutionTenant in the QA handler). It breaks for a shared agent everywhere else, because a shared agent runs on ITS OWNER's sandbox config while the session belongs to the borrower, and these paths run from plain requests whose only tenant is the session owner's: * DeleteSession resolved nothing and returned after a warning. Cube and E2B create session sandboxes with onTimeout=pause, so the MicroVM was not reclaimed later either: it stayed paused, billing, with nobody holding its id. ReapOrphanSandboxes has no production caller, so nothing recovered it. * The terminal and desktop panels failed on both branches - attaching to the pinned sandbox and provisioning a new one - with ErrSandboxConfigNotFound, which terminalErrorFrame maps to a bare INTERNAL close reason. The panel is offered unconditionally and already forwards agent_source_tenant_id, so this was a dead end the user could reach in one click. * Fork read the pin through PinnedSessionSandbox, got no manager, and silently degraded to SNAPSHOT_UNSUPPORTED, losing the sandbox state. * The fork snapshot lease recorded the session's workspace next to the lending workspace's config id, so the reaper could not resolve it either. Record the owning workspace beside the pin and make the pair travel together as SandboxPin. Readers now take the workspace from the pin and fall back to the session's own, which is what every non-borrowed pin (and every row written before this column) resolves to - so behaviour for own agents is unchanged. The provision path has no pin yet, so the WebSocket handler passes the agent's workspace along with its config: terminalProvisionPin already resolved the shared agent, it just discarded the tenant resolveAgent handed back. Backfill in the migration is limited to sessions whose pinned config does not exist in their own workspace - the only ones that can have borrowed it - using the lending workspace recorded on their newest shared-agent message. Lite has no shared spaces, so the SQLite mirror adds the column without a backfill. * fix(sandbox): backfill the pin owner from the config row and self-heal legacy pins Three gaps in the session sandbox pin owner: Backfilling from messages.agent_tenant_id names the wrong workspace. The pin is sticky to the session's FIRST sandbox, while the newest message carrying agent_tenant_id may belong to a later shared agent from another workspace. Writing that tenant leaves teardown resolving a config the workspace does not own - the very failure the column exists to fix. tenant_sandbox_configs.id is a global UUID primary key, so joining the config row itself names the workspace that actually owns the pin. The column was INTEGER while every other tenant id is BIGINT/uint64. Postgres INTEGER is 32-bit signed, so a large tenant id would not fit. Rows the SQL backfill cannot reach keep sandbox_config_tenant_id = 0 forever: the reader falls back to the caller's workspace but never records what it learned. The next chat turn already runs under the workspace that can resolve the config, so persisting it there is what lets a later DELETE, panel open or fork find the sandbox. recordOwner only writes when the lookup actually succeeded and the stored owner is still unset - stamping the caller's tenant onto a failed lookup would brand a sticky pin left by a previous shared agent with the wrong workspace. Also renames the lentSandboxConfg typo and corrects the fork degrade reason in a comment: a lent config that resolves to nil fails BoundSandboxID, so the fork degrades to SANDBOX_GONE, not SNAPSHOT_UNSUPPORTED. * fix(sandbox): require a named backend before recording a pin's owner The self-heal wants to persist an owner "that actually resolved this config", but a nil error does not prove that. resolveTenantSandboxForConfig returns a disabled manager with no error twice before it ever reads the config row: for the workspace kill switch, and for an empty or deployment-default config id. That reopens the leak this column exists to close. The SQL backfill correctly leaves sandbox_config_tenant_id at 0 whenever the pinned config belongs to the session's own workspace, which is most existing rows. One turn of a shared agent lent by a workspace whose admin has script execution turned off then short-circuits on the kill switch, returns nil, and stamps that lending workspace onto a config it does not own. The next DELETE resolves the pin there, finds nothing, and strands the paused MicroVM. The pin branch runs before agentConfigID is read, so the shared agent does not even need a sandbox config of its own to trigger it. A named backend (Cube/E2B/Docker) is the proof, and it is the same condition that is already allowed to CREATE a pin further down: what may write a pin may update whose it is. A config that exists but resolves to type "disabled" is skipped as well - ownership is genuine there, but such a config never creates a sandbox, so no teardown can go missing. The deployment-default pin was inert either way (both workspaces short-circuit to a manager with no DestroySession), but it is covered too so a later relaxation of the proof cannot quietly reopen the kill-switch case. Both tests fail without the guard. --------- Co-authored-by: hailongzhao <hailongzhao@tencent.com>
2026-09-21 07:38:39 +00:00
func TestTerminalProvisionPin_UsesSharedAgentSandboxConfig(t *testing.T) {
feat(sandbox): add an interactive terminal and files tab beside chat (#3110) * feat(sandbox): stream interactive PTYs from Cube and E2B Give session sandboxes a provider-neutral terminal capability so a later WebSocket layer can attach without knowing Cube vs E2B. Long-lived streams use a timeout-free client; idle terminals keep the sandbox alive by refreshing TTL, and a workspace can set how long to wait before disconnect. * feat(session): bridge browser terminals to the session sandbox Mint a short-lived ticket over a normal authenticated POST so the browser WebSocket never puts the access JWT in the query string. After upgrade, recheck the bound token, membership, and session ownership so logout or revocation tears the PTY down. Provisioning stays opt-in: a GET handshake only creates a sandbox when the client sends provision=1. * feat(chat): add a sandbox terminal panel beside the conversation Open a side panel with an xterm attached to the session sandbox. Starting the terminal is an explicit click so merely opening the panel does not create or resume a microVM; reconnects stay lookup-only until the user confirms create-and-start. Persist the remote shell PID in sessionStorage so a refresh reattaches instead of spawning an orphan. * feat(sandbox): let workspaces set terminal idle disconnect Expose the idle-disconnect duration in the sandbox config editor so an operator can close unused terminals and let the provider TTL pause the sandbox, instead of leaving PTYs open for the built-in 15 minutes. * feat(chat): show generated files in the sandbox side panel Move the per-message artifact list into the first tab of the right-hand panel so generated files stay in view with the terminal. Keep the old drawer only for embedded chat. * fix(sandbox-terminal): keep tickets out of logs and live PTYs across refresh Gin was copying the handshake JWT into response_body logs, silent access-token rotation dropped open terminals as AUTH_REVOKED, and first-use provisioning missed shared agents. Local echo now skips password prompts. --------- Co-authored-by: hailongzhao <hailongzhao@tencent.com> Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-09-08 09:43:15 +00:00
gin.SetMode(gin.TestMode)
rec := httptest.NewRecorder()
c, _ := gin.CreateTestContext(rec)
c.Request = httptest.NewRequest(
http.MethodGet,
"/?agent_id=builtin-smart-reasoning&agent_source_tenant_id=84",
nil,
)
c.Set(types.UserIDContextKey.String(), "user-1")
c.Set(types.TenantIDContextKey.String(), uint64(7))
ctx := context.WithValue(c.Request.Context(), types.TenantIDContextKey, uint64(7))
c.Request = c.Request.WithContext(ctx)
sharedAgent := &types.CustomAgent{
ID: "builtin-smart-reasoning",
TenantID: 84,
Config: types.CustomAgentConfig{SandboxConfigID: "shared-cfg"},
}
h := &Handler{
agentShareService: &resolveAgentShareStub{agent: sharedAgent},
customAgentService: &resolveOwnAgentStub{agent: &types.CustomAgent{
ID: "builtin-smart-reasoning",
TenantID: 7,
Config: types.CustomAgentConfig{SandboxConfigID: "local-cfg"},
}},
}
fix(sandbox): resolve a session's pinned sandbox in the workspace that owns it (#3471) * fix(sandbox): resolve a session's pinned sandbox in the workspace that owns it tenant_sandbox_configs is keyed by (tenant_id, id), so a config id is not an address on its own. sessions.sandbox_config_id stored only the id and every reader took the workspace from the ambient request context. That holds inside a chat turn, which already runs under the agent's workspace (WithExecutionTenant in the QA handler). It breaks for a shared agent everywhere else, because a shared agent runs on ITS OWNER's sandbox config while the session belongs to the borrower, and these paths run from plain requests whose only tenant is the session owner's: * DeleteSession resolved nothing and returned after a warning. Cube and E2B create session sandboxes with onTimeout=pause, so the MicroVM was not reclaimed later either: it stayed paused, billing, with nobody holding its id. ReapOrphanSandboxes has no production caller, so nothing recovered it. * The terminal and desktop panels failed on both branches - attaching to the pinned sandbox and provisioning a new one - with ErrSandboxConfigNotFound, which terminalErrorFrame maps to a bare INTERNAL close reason. The panel is offered unconditionally and already forwards agent_source_tenant_id, so this was a dead end the user could reach in one click. * Fork read the pin through PinnedSessionSandbox, got no manager, and silently degraded to SNAPSHOT_UNSUPPORTED, losing the sandbox state. * The fork snapshot lease recorded the session's workspace next to the lending workspace's config id, so the reaper could not resolve it either. Record the owning workspace beside the pin and make the pair travel together as SandboxPin. Readers now take the workspace from the pin and fall back to the session's own, which is what every non-borrowed pin (and every row written before this column) resolves to - so behaviour for own agents is unchanged. The provision path has no pin yet, so the WebSocket handler passes the agent's workspace along with its config: terminalProvisionPin already resolved the shared agent, it just discarded the tenant resolveAgent handed back. Backfill in the migration is limited to sessions whose pinned config does not exist in their own workspace - the only ones that can have borrowed it - using the lending workspace recorded on their newest shared-agent message. Lite has no shared spaces, so the SQLite mirror adds the column without a backfill. * fix(sandbox): backfill the pin owner from the config row and self-heal legacy pins Three gaps in the session sandbox pin owner: Backfilling from messages.agent_tenant_id names the wrong workspace. The pin is sticky to the session's FIRST sandbox, while the newest message carrying agent_tenant_id may belong to a later shared agent from another workspace. Writing that tenant leaves teardown resolving a config the workspace does not own - the very failure the column exists to fix. tenant_sandbox_configs.id is a global UUID primary key, so joining the config row itself names the workspace that actually owns the pin. The column was INTEGER while every other tenant id is BIGINT/uint64. Postgres INTEGER is 32-bit signed, so a large tenant id would not fit. Rows the SQL backfill cannot reach keep sandbox_config_tenant_id = 0 forever: the reader falls back to the caller's workspace but never records what it learned. The next chat turn already runs under the workspace that can resolve the config, so persisting it there is what lets a later DELETE, panel open or fork find the sandbox. recordOwner only writes when the lookup actually succeeded and the stored owner is still unset - stamping the caller's tenant onto a failed lookup would brand a sticky pin left by a previous shared agent with the wrong workspace. Also renames the lentSandboxConfg typo and corrects the fork degrade reason in a comment: a lent config that resolves to nil fails BoundSandboxID, so the fork degrades to SANDBOX_GONE, not SNAPSHOT_UNSUPPORTED. * fix(sandbox): require a named backend before recording a pin's owner The self-heal wants to persist an owner "that actually resolved this config", but a nil error does not prove that. resolveTenantSandboxForConfig returns a disabled manager with no error twice before it ever reads the config row: for the workspace kill switch, and for an empty or deployment-default config id. That reopens the leak this column exists to close. The SQL backfill correctly leaves sandbox_config_tenant_id at 0 whenever the pinned config belongs to the session's own workspace, which is most existing rows. One turn of a shared agent lent by a workspace whose admin has script execution turned off then short-circuits on the kill switch, returns nil, and stamps that lending workspace onto a config it does not own. The next DELETE resolves the pin there, finds nothing, and strands the paused MicroVM. The pin branch runs before agentConfigID is read, so the shared agent does not even need a sandbox config of its own to trigger it. A named backend (Cube/E2B/Docker) is the proof, and it is the same condition that is already allowed to CREATE a pin further down: what may write a pin may update whose it is. A config that exists but resolves to type "disabled" is skipped as well - ownership is genuine there, but such a config never creates a sandbox, so no teardown can go missing. The deployment-default pin was inert either way (both workspaces short-circuit to a manager with no DestroySession), but it is covered too so a later relaxation of the proof cannot quietly reopen the kill-switch case. Both tests fail without the guard. --------- Co-authored-by: hailongzhao <hailongzhao@tencent.com>
2026-09-21 07:38:39 +00:00
require.Equal(t, service.SandboxPin{}, h.terminalProvisionPin(ctx, c, false),
feat(sandbox): add an interactive terminal and files tab beside chat (#3110) * feat(sandbox): stream interactive PTYs from Cube and E2B Give session sandboxes a provider-neutral terminal capability so a later WebSocket layer can attach without knowing Cube vs E2B. Long-lived streams use a timeout-free client; idle terminals keep the sandbox alive by refreshing TTL, and a workspace can set how long to wait before disconnect. * feat(session): bridge browser terminals to the session sandbox Mint a short-lived ticket over a normal authenticated POST so the browser WebSocket never puts the access JWT in the query string. After upgrade, recheck the bound token, membership, and session ownership so logout or revocation tears the PTY down. Provisioning stays opt-in: a GET handshake only creates a sandbox when the client sends provision=1. * feat(chat): add a sandbox terminal panel beside the conversation Open a side panel with an xterm attached to the session sandbox. Starting the terminal is an explicit click so merely opening the panel does not create or resume a microVM; reconnects stay lookup-only until the user confirms create-and-start. Persist the remote shell PID in sessionStorage so a refresh reattaches instead of spawning an orphan. * feat(sandbox): let workspaces set terminal idle disconnect Expose the idle-disconnect duration in the sandbox config editor so an operator can close unused terminals and let the provider TTL pause the sandbox, instead of leaving PTYs open for the built-in 15 minutes. * feat(chat): show generated files in the sandbox side panel Move the per-message artifact list into the first tab of the right-hand panel so generated files stay in view with the terminal. Keep the old drawer only for embedded chat. * fix(sandbox-terminal): keep tickets out of logs and live PTYs across refresh Gin was copying the handshake JWT into response_body logs, silent access-token rotation dropped open terminals as AUTH_REVOKED, and first-use provisioning missed shared agents. Local echo now skips password prompts. --------- Co-authored-by: hailongzhao <hailongzhao@tencent.com> Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-09-08 09:43:15 +00:00
"lookup-only connects must not resolve an agent config")
fix(sandbox): resolve a session's pinned sandbox in the workspace that owns it (#3471) * fix(sandbox): resolve a session's pinned sandbox in the workspace that owns it tenant_sandbox_configs is keyed by (tenant_id, id), so a config id is not an address on its own. sessions.sandbox_config_id stored only the id and every reader took the workspace from the ambient request context. That holds inside a chat turn, which already runs under the agent's workspace (WithExecutionTenant in the QA handler). It breaks for a shared agent everywhere else, because a shared agent runs on ITS OWNER's sandbox config while the session belongs to the borrower, and these paths run from plain requests whose only tenant is the session owner's: * DeleteSession resolved nothing and returned after a warning. Cube and E2B create session sandboxes with onTimeout=pause, so the MicroVM was not reclaimed later either: it stayed paused, billing, with nobody holding its id. ReapOrphanSandboxes has no production caller, so nothing recovered it. * The terminal and desktop panels failed on both branches - attaching to the pinned sandbox and provisioning a new one - with ErrSandboxConfigNotFound, which terminalErrorFrame maps to a bare INTERNAL close reason. The panel is offered unconditionally and already forwards agent_source_tenant_id, so this was a dead end the user could reach in one click. * Fork read the pin through PinnedSessionSandbox, got no manager, and silently degraded to SNAPSHOT_UNSUPPORTED, losing the sandbox state. * The fork snapshot lease recorded the session's workspace next to the lending workspace's config id, so the reaper could not resolve it either. Record the owning workspace beside the pin and make the pair travel together as SandboxPin. Readers now take the workspace from the pin and fall back to the session's own, which is what every non-borrowed pin (and every row written before this column) resolves to - so behaviour for own agents is unchanged. The provision path has no pin yet, so the WebSocket handler passes the agent's workspace along with its config: terminalProvisionPin already resolved the shared agent, it just discarded the tenant resolveAgent handed back. Backfill in the migration is limited to sessions whose pinned config does not exist in their own workspace - the only ones that can have borrowed it - using the lending workspace recorded on their newest shared-agent message. Lite has no shared spaces, so the SQLite mirror adds the column without a backfill. * fix(sandbox): backfill the pin owner from the config row and self-heal legacy pins Three gaps in the session sandbox pin owner: Backfilling from messages.agent_tenant_id names the wrong workspace. The pin is sticky to the session's FIRST sandbox, while the newest message carrying agent_tenant_id may belong to a later shared agent from another workspace. Writing that tenant leaves teardown resolving a config the workspace does not own - the very failure the column exists to fix. tenant_sandbox_configs.id is a global UUID primary key, so joining the config row itself names the workspace that actually owns the pin. The column was INTEGER while every other tenant id is BIGINT/uint64. Postgres INTEGER is 32-bit signed, so a large tenant id would not fit. Rows the SQL backfill cannot reach keep sandbox_config_tenant_id = 0 forever: the reader falls back to the caller's workspace but never records what it learned. The next chat turn already runs under the workspace that can resolve the config, so persisting it there is what lets a later DELETE, panel open or fork find the sandbox. recordOwner only writes when the lookup actually succeeded and the stored owner is still unset - stamping the caller's tenant onto a failed lookup would brand a sticky pin left by a previous shared agent with the wrong workspace. Also renames the lentSandboxConfg typo and corrects the fork degrade reason in a comment: a lent config that resolves to nil fails BoundSandboxID, so the fork degrades to SANDBOX_GONE, not SNAPSHOT_UNSUPPORTED. * fix(sandbox): require a named backend before recording a pin's owner The self-heal wants to persist an owner "that actually resolved this config", but a nil error does not prove that. resolveTenantSandboxForConfig returns a disabled manager with no error twice before it ever reads the config row: for the workspace kill switch, and for an empty or deployment-default config id. That reopens the leak this column exists to close. The SQL backfill correctly leaves sandbox_config_tenant_id at 0 whenever the pinned config belongs to the session's own workspace, which is most existing rows. One turn of a shared agent lent by a workspace whose admin has script execution turned off then short-circuits on the kill switch, returns nil, and stamps that lending workspace onto a config it does not own. The next DELETE resolves the pin there, finds nothing, and strands the paused MicroVM. The pin branch runs before agentConfigID is read, so the shared agent does not even need a sandbox config of its own to trigger it. A named backend (Cube/E2B/Docker) is the proof, and it is the same condition that is already allowed to CREATE a pin further down: what may write a pin may update whose it is. A config that exists but resolves to type "disabled" is skipped as well - ownership is genuine there, but such a config never creates a sandbox, so no teardown can go missing. The deployment-default pin was inert either way (both workspaces short-circuit to a manager with no DestroySession), but it is covered too so a later relaxation of the proof cannot quietly reopen the kill-switch case. Both tests fail without the guard. --------- Co-authored-by: hailongzhao <hailongzhao@tencent.com>
2026-09-21 07:38:39 +00:00
// The lending workspace travels with the config id: sandbox configs are
// keyed by (tenant, id), so "shared-cfg" does not exist in workspace 7.
require.Equal(t,
service.SandboxPin{ConfigID: "shared-cfg", TenantID: 84},
h.terminalProvisionPin(ctx, c, true))
}
// An own agent's config already lives in the caller's workspace, so the pin
// carries no owner and SandboxPin.TenantOr falls back to the request tenant.
func TestTerminalProvisionPin_OwnAgentCarriesNoWorkspace(t *testing.T) {
gin.SetMode(gin.TestMode)
rec := httptest.NewRecorder()
c, _ := gin.CreateTestContext(rec)
c.Request = httptest.NewRequest(
http.MethodGet, "/?agent_id=builtin-smart-reasoning", nil)
c.Set(types.UserIDContextKey.String(), "user-1")
c.Set(types.TenantIDContextKey.String(), uint64(7))
ctx := context.WithValue(c.Request.Context(), types.TenantIDContextKey, uint64(7))
c.Request = c.Request.WithContext(ctx)
h := &Handler{
customAgentService: &resolveOwnAgentStub{agent: &types.CustomAgent{
ID: "builtin-smart-reasoning",
TenantID: 7,
Config: types.CustomAgentConfig{SandboxConfigID: "local-cfg"},
}},
}
pin := h.terminalProvisionPin(ctx, c, true)
require.Equal(t, service.SandboxPin{ConfigID: "local-cfg"}, pin)
require.Equal(t, uint64(7), pin.TenantOr(7))
feat(sandbox): add an interactive terminal and files tab beside chat (#3110) * feat(sandbox): stream interactive PTYs from Cube and E2B Give session sandboxes a provider-neutral terminal capability so a later WebSocket layer can attach without knowing Cube vs E2B. Long-lived streams use a timeout-free client; idle terminals keep the sandbox alive by refreshing TTL, and a workspace can set how long to wait before disconnect. * feat(session): bridge browser terminals to the session sandbox Mint a short-lived ticket over a normal authenticated POST so the browser WebSocket never puts the access JWT in the query string. After upgrade, recheck the bound token, membership, and session ownership so logout or revocation tears the PTY down. Provisioning stays opt-in: a GET handshake only creates a sandbox when the client sends provision=1. * feat(chat): add a sandbox terminal panel beside the conversation Open a side panel with an xterm attached to the session sandbox. Starting the terminal is an explicit click so merely opening the panel does not create or resume a microVM; reconnects stay lookup-only until the user confirms create-and-start. Persist the remote shell PID in sessionStorage so a refresh reattaches instead of spawning an orphan. * feat(sandbox): let workspaces set terminal idle disconnect Expose the idle-disconnect duration in the sandbox config editor so an operator can close unused terminals and let the provider TTL pause the sandbox, instead of leaving PTYs open for the built-in 15 minutes. * feat(chat): show generated files in the sandbox side panel Move the per-message artifact list into the first tab of the right-hand panel so generated files stay in view with the terminal. Keep the old drawer only for embedded chat. * fix(sandbox-terminal): keep tickets out of logs and live PTYs across refresh Gin was copying the handshake JWT into response_body logs, silent access-token rotation dropped open terminals as AUTH_REVOKED, and first-use provisioning missed shared agents. Local echo now skips password prompts. --------- Co-authored-by: hailongzhao <hailongzhao@tencent.com> Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-09-08 09:43:15 +00:00
}