WeKnora/internal/handler/session/resolve_agent_test.go

231 lines
8.6 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"
"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)
}
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
func TestTerminalProvisionConfigID_UsesSharedAgentSandboxConfig(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&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"},
}},
}
require.Equal(t, "", h.terminalProvisionConfigID(ctx, c, false),
"lookup-only connects must not resolve an agent config")
require.Equal(t, "shared-cfg", h.terminalProvisionConfigID(ctx, c, true))
}