diff --git a/internal/agent/tools/data_analysis.go b/internal/agent/tools/data_analysis.go index 237f500d..8a45be76 100644 --- a/internal/agent/tools/data_analysis.go +++ b/internal/agent/tools/data_analysis.go @@ -125,12 +125,17 @@ type DataAnalysisTool struct { localBaseDir string storageResolver interfaces.StorageBackendResolver searchTargets types.SearchTargets + scopeEnforced bool } // WithSearchTargets enables the Agent-only authorization boundary. Other // internal data-analysis callers retain their existing service-owned scope. +// The flag is set independently of the slice length: an Agent turn that ended +// up with no search target must reject every document, not fall back to +// unrestricted access. func (t *DataAnalysisTool) WithSearchTargets(searchTargets types.SearchTargets) *DataAnalysisTool { t.searchTargets = searchTargets + t.scopeEnforced = true return t } @@ -209,7 +214,7 @@ func (t *DataAnalysisTool) Execute(ctx context.Context, args json.RawMessage) (* Error: fmt.Sprintf("Failed to parse input args: %v", err), }, err } - if len(t.searchTargets) > 0 { + if t.scopeEnforced { if _, err := authorizeKnowledgeInSearchTargets(ctx, t.searchTargets, input.KnowledgeID, t.knowledgeService); err != nil { return &types.ToolResult{Success: false, Error: err.Error()}, err } diff --git a/internal/agent/tools/data_schema.go b/internal/agent/tools/data_schema.go index ffb21900..c4b00a78 100644 --- a/internal/agent/tools/data_schema.go +++ b/internal/agent/tools/data_schema.go @@ -26,11 +26,15 @@ type DataSchemaTool struct { chunkRepo interfaces.ChunkRepository targetChunkTypes []types.ChunkType searchTargets types.SearchTargets + scopeEnforced bool } -// WithSearchTargets enables Agent request-scope authorization. +// WithSearchTargets enables Agent request-scope authorization. An Agent turn +// with no search target must reject every document rather than fall back to +// the unrestricted service-owned lookup. func (t *DataSchemaTool) WithSearchTargets(searchTargets types.SearchTargets) *DataSchemaTool { t.searchTargets = searchTargets + t.scopeEnforced = true return t } @@ -59,7 +63,7 @@ func (t *DataSchemaTool) Execute(ctx context.Context, args json.RawMessage) (*ty // Get knowledge to get TenantID (use IDOnly to support cross-tenant shared KB) var knowledge *types.Knowledge var err error - if len(t.searchTargets) > 0 { + if t.scopeEnforced { knowledge, err = authorizeKnowledgeInSearchTargets(ctx, t.searchTargets, input.KnowledgeID, t.knowledgeService) } else { knowledge, err = t.knowledgeService.GetKnowledgeByIDOnly(ctx, input.KnowledgeID) diff --git a/internal/agent/tools/database_query.go b/internal/agent/tools/database_query.go index f364daf7..ea66595f 100644 --- a/internal/agent/tools/database_query.go +++ b/internal/agent/tools/database_query.go @@ -283,15 +283,13 @@ func searchScopesFromTargets(searchTargets types.SearchTargets) []utils.SearchSc if target == nil || target.KnowledgeBaseID == "" { continue } - tagIDs := effectiveSearchTargetTagIDs(target) - wholeKB := target.Type == types.SearchTargetTypeKnowledgeBase && - len(target.KnowledgeIDs) == 0 && len(tagIDs) == 0 - if !wholeKB && len(target.KnowledgeIDs) == 0 && len(tagIDs) == 0 { + knowledgeIDs, tagIDs := searchTargetScope(target) + if !searchTargetIsWholeKB(target) && len(knowledgeIDs) == 0 && len(tagIDs) == 0 { continue } scopes = append(scopes, utils.SearchScope{ KnowledgeBaseID: target.KnowledgeBaseID, - KnowledgeIDs: append([]string(nil), target.KnowledgeIDs...), + KnowledgeIDs: knowledgeIDs, TagIDs: tagIDs, }) } diff --git a/internal/agent/tools/grep_chunks.go b/internal/agent/tools/grep_chunks.go index 1449bdd8..9f5dc05e 100644 --- a/internal/agent/tools/grep_chunks.go +++ b/internal/agent/tools/grep_chunks.go @@ -263,13 +263,18 @@ func (t *GrepChunksTool) resolveGrepScope() (fullKBIDs, knowledgeIDs []string, t if target == nil || target.KnowledgeBaseID == "" { continue } + // A target that carries a resolved document whitelist is already the + // intersection of its mention and any tag scope, so it must be grepped + // by knowledge ID. Falling back to the tag branch would widen the + // search to every document carrying the tag. + targetKnowledgeIDs, targetTagIDs := searchTargetScope(target) switch { - case len(effectiveSearchTargetTagIDs(target)) > 0: + case len(targetTagIDs) > 0: tenantID := target.TenantID if tenantID == 0 { tenantID = t.searchTargets.GetTenantIDForKB(target.KnowledgeBaseID) } - tagIDs := effectiveSearchTargetTagIDs(target) + tagIDs := targetTagIDs if len(tagIDs) == 0 || tenantID == 0 { continue } @@ -284,9 +289,9 @@ func (t *GrepChunksTool) resolveGrepScope() (fullKBIDs, knowledgeIDs []string, t TenantID: tenantID, TagIDs: tagIDs, }) - case len(target.KnowledgeIDs) > 0: - for _, kid := range target.KnowledgeIDs { - if kid != "" && !seenKnowledge[kid] { + case len(targetKnowledgeIDs) > 0: + for _, kid := range targetKnowledgeIDs { + if !seenKnowledge[kid] { seenKnowledge[kid] = true knowledgeIDs = append(knowledgeIDs, kid) } diff --git a/internal/agent/tools/query_knowledge_graph.go b/internal/agent/tools/query_knowledge_graph.go index 327e6b18..313ead57 100644 --- a/internal/agent/tools/query_knowledge_graph.go +++ b/internal/agent/tools/query_knowledge_graph.go @@ -71,6 +71,7 @@ type QueryKnowledgeGraphTool struct { knowledgeService interfaces.KnowledgeBaseService scopeKnowledgeService interfaces.KnowledgeService searchTargets types.SearchTargets + scopeEnforced bool } // WithKnowledgeScope enables document/tag-level result filtering for Agent @@ -92,8 +93,11 @@ func NewQueryKnowledgeGraphTool( BaseTool: queryKnowledgeGraphTool, knowledgeService: knowledgeService, } + // Presence of the variadic argument — not its length — enables the Agent + // authorization boundary, so an empty scope fails closed. if len(searchTargets) > 0 { tool.searchTargets = searchTargets[0] + tool.scopeEnforced = true } return tool } @@ -124,7 +128,7 @@ func (t *QueryKnowledgeGraphTool) Execute(ctx context.Context, args json.RawMess Error: "knowledge_base_ids must contain at most 10 KB IDs", }, fmt.Errorf("too many KB IDs") } - if len(t.searchTargets) > 0 { + if t.scopeEnforced { if err := validateKnowledgeBaseIDsInSearchTargets(t.searchTargets, input.KnowledgeBaseIDs); err != nil { return &types.ToolResult{Success: false, Error: err.Error()}, err } @@ -185,7 +189,7 @@ func (t *QueryKnowledgeGraphTool) Execute(ctx context.Context, args json.RawMess mu.Unlock() return } - if len(t.searchTargets) > 0 { + if t.scopeEnforced { results, err = filterSearchResultsInSearchTargets( ctx, t.searchTargets, id, results, t.scopeKnowledgeService, ) diff --git a/internal/agent/tools/scope_authorization.go b/internal/agent/tools/scope_authorization.go index 8c0fa223..62f4b1be 100644 --- a/internal/agent/tools/scope_authorization.go +++ b/internal/agent/tools/scope_authorization.go @@ -18,6 +18,40 @@ func effectiveSearchTargetTagIDs(target *types.SearchTarget) []string { )) } +// searchTargetScope returns what a SINGLE search target authorizes. +// +// Inside one target, KnowledgeIDs and tags are an intersection, never a union. +// A tag-scoped mention is built by resolving the tag relation table into +// KnowledgeIDs and intersecting that with any explicitly mentioned documents; +// TagIDs/ScopeTagIDs are kept alongside as the physical index filter and as +// the logical scope record. Treating them as an independent way to authorize a +// document would re-admit every document carrying the tag and silently undo +// that intersection. Tags therefore only authorize when the target carries no +// resolved document whitelist. +// +// Alternatives ACROSS targets remain a union; that merge happens in callers. +func searchTargetScope(target *types.SearchTarget) (knowledgeIDs, tagIDs []string) { + if target == nil { + return nil, nil + } + knowledgeIDs = dedupNonEmptyStrings(target.KnowledgeIDs) + if len(knowledgeIDs) > 0 { + return knowledgeIDs, nil + } + return nil, effectiveSearchTargetTagIDs(target) +} + +// searchTargetIsWholeKB reports whether a target grants unrestricted access to +// its knowledge base. +func searchTargetIsWholeKB(target *types.SearchTarget) bool { + if target == nil { + return false + } + knowledgeIDs, tagIDs := searchTargetScope(target) + return target.Type == types.SearchTargetTypeKnowledgeBase && + len(knowledgeIDs) == 0 && len(tagIDs) == 0 +} + // authorizeKnowledgeInSearchTargets is the shared authorization boundary for // every Agent tool that accepts a model-visible dN/knowledge_id. Handle // decoding is necessary but never sufficient: the durable document must also @@ -165,12 +199,11 @@ func searchTargetsAllowKnowledgeID( continue } matchedKB = true - targetTagIDs := effectiveSearchTargetTagIDs(target) - if target.Type == types.SearchTargetTypeKnowledgeBase && - len(target.KnowledgeIDs) == 0 && len(targetTagIDs) == 0 { + if searchTargetIsWholeKB(target) { return true, nil } - for _, allowedID := range target.KnowledgeIDs { + targetKnowledgeIDs, targetTagIDs := searchTargetScope(target) + for _, allowedID := range targetKnowledgeIDs { if allowedID == knowledgeID { return true, nil } @@ -207,12 +240,11 @@ func filterSearchResultsInSearchTargets( continue } matchedKB = true - targetTagIDs := effectiveSearchTargetTagIDs(target) - if target.Type == types.SearchTargetTypeKnowledgeBase && - len(target.KnowledgeIDs) == 0 && len(targetTagIDs) == 0 { + if searchTargetIsWholeKB(target) { return results, nil } - explicitIDs = append(explicitIDs, target.KnowledgeIDs...) + targetKnowledgeIDs, targetTagIDs := searchTargetScope(target) + explicitIDs = append(explicitIDs, targetKnowledgeIDs...) tagIDs = append(tagIDs, targetTagIDs...) } if !matchedKB { diff --git a/internal/agent/tools/scope_authorization_test.go b/internal/agent/tools/scope_authorization_test.go index 966d2155..c90debc6 100644 --- a/internal/agent/tools/scope_authorization_test.go +++ b/internal/agent/tools/scope_authorization_test.go @@ -11,12 +11,25 @@ import ( type scopeKnowledgeService struct { interfaces.KnowledgeService knowledge *types.Knowledge + tags map[string][]*types.KnowledgeTag } func (s *scopeKnowledgeService) GetKnowledgeByIDOnly(context.Context, string) (*types.Knowledge, error) { return s.knowledge, nil } +func (s *scopeKnowledgeService) GetKnowledgeTags( + _ context.Context, ids []string, +) (map[string][]*types.KnowledgeTag, error) { + out := make(map[string][]*types.KnowledgeTag, len(ids)) + for _, id := range ids { + if tags, ok := s.tags[id]; ok { + out[id] = tags + } + } + return out, nil +} + func testKnowledgeTag(id string) *types.KnowledgeTag { return &types.KnowledgeTag{ID: id} } @@ -68,6 +81,74 @@ func TestAuthorizeKnowledgeInSearchTargetsAllowsBoundDocument(t *testing.T) { } } +// A tag-scoped mention is resolved into KnowledgeIDs (intersected with any +// explicitly mentioned documents) while the tag is retained as the logical +// scope record. Re-admitting every document carrying that tag would undo the +// intersection and leak documents the user never mentioned. +func TestAuthorizeKnowledgeInSearchTargetsDoesNotWidenResolvedScopeByTag(t *testing.T) { + service := &scopeKnowledgeService{ + knowledge: &types.Knowledge{ID: "doc-tagged", KnowledgeBaseID: "kb-1"}, + tags: map[string][]*types.KnowledgeTag{"doc-tagged": {testKnowledgeTag("tag-a")}}, + } + targets := types.SearchTargets{{ + Type: types.SearchTargetTypeKnowledge, + KnowledgeBaseID: "kb-1", + KnowledgeIDs: []string{"doc-mentioned"}, + ScopeTagIDs: []string{"tag-a"}, + }} + if _, err := authorizeKnowledgeInSearchTargets( + context.Background(), targets, "doc-tagged", service, + ); err == nil { + t.Fatal("a document outside the resolved whitelist must not be authorized by its tag alone") + } + + got, err := authorizeKnowledgeInSearchTargets( + context.Background(), + targets, + "doc-mentioned", + &scopeKnowledgeService{knowledge: &types.Knowledge{ID: "doc-mentioned", KnowledgeBaseID: "kb-1"}}, + ) + if err != nil || got == nil { + t.Fatalf("the resolved document must stay authorized: got=%+v err=%v", got, err) + } +} + +// The intersection is per target. Two separate mentions of the same KB remain +// alternatives, so a tag-only target still authorizes on its own. +func TestAuthorizeKnowledgeInSearchTargetsKeepsCrossTargetUnion(t *testing.T) { + service := &scopeKnowledgeService{ + knowledge: &types.Knowledge{ID: "doc-tagged", KnowledgeBaseID: "kb-1"}, + tags: map[string][]*types.KnowledgeTag{"doc-tagged": {testKnowledgeTag("tag-a")}}, + } + targets := types.SearchTargets{ + {Type: types.SearchTargetTypeKnowledge, KnowledgeBaseID: "kb-1", KnowledgeIDs: []string{"doc-mentioned"}}, + {Type: types.SearchTargetTypeKnowledgeBase, KnowledgeBaseID: "kb-1", TagIDs: []string{"tag-a"}}, + } + got, err := authorizeKnowledgeInSearchTargets(context.Background(), targets, "doc-tagged", service) + if err != nil || got == nil { + t.Fatalf("a tag-only alternative target must still authorize: got=%+v err=%v", got, err) + } +} + +func TestNewWikiScopesDropsTagsOfResolvedDocumentTargets(t *testing.T) { + targets := types.SearchTargets{{ + Type: types.SearchTargetTypeKnowledge, + KnowledgeBaseID: "kb-1", + KnowledgeIDs: []string{"doc-mentioned"}, + ScopeTagIDs: []string{"tag-a"}, + }} + scopes := NewWikiScopesFromSearchTargets(targets, []string{"kb-1"}) + if len(scopes) != 1 { + t.Fatalf("scope count = %d, want 1: %+v", len(scopes), scopes) + } + if len(scopes[0].TagIDs) != 0 { + t.Fatalf("resolved document target must not contribute a standalone tag filter: %+v", scopes[0]) + } + if len(scopes[0].KnowledgeIDs) != 1 || scopes[0].KnowledgeIDs[0] != "doc-mentioned" { + t.Fatalf("resolved document whitelist was lost: %+v", scopes[0]) + } +} + func TestValidateKnowledgeBaseIDsInSearchTargetsRejectsMixedScope(t *testing.T) { targets := types.SearchTargets{{ Type: types.SearchTargetTypeKnowledgeBase, diff --git a/internal/agent/tools/tool_policy_coverage_test.go b/internal/agent/tools/tool_policy_coverage_test.go new file mode 100644 index 00000000..942d7279 --- /dev/null +++ b/internal/agent/tools/tool_policy_coverage_test.go @@ -0,0 +1,57 @@ +package tools + +import ( + "testing" + + "github.com/Tencent/WeKnora/internal/modelcontext" +) + +// Every built-in tool must declare a model-handle policy. Without an entry, +// modelcontext treats the tool's output like dynamic MCP output: durable chunk +// IDs, knowledge IDs and KB IDs are passed through to the model verbatim, +// which the source protocol prompt explicitly forbids. An empty policy is a +// valid answer ("compact known IDs, render nothing structured"); silence is +// not, because a newly added tool would opt out by accident. +func TestEveryBuiltInToolDeclaresAModelHandlePolicy(t *testing.T) { + builtIns := []string{ + ToolThinking, + ToolTodoWrite, + ToolGrepChunks, + ToolKnowledgeSearch, + ToolListKnowledgeChunks, + ToolQueryKnowledgeGraph, + ToolGetDocumentInfo, + ToolDatabaseQuery, + ToolDataAnalysis, + ToolDataSchema, + ToolWebSearch, + ToolWebFetch, + ToolExecuteSkillScript, + ToolReadSkill, + ToolWikiReadPage, + ToolWikiWritePage, + ToolWikiReplaceText, + ToolWikiRenamePage, + ToolWikiDeletePage, + ToolWikiSearch, + ToolWikiReadSourceDoc, + ToolWikiFlagIssue, + ToolWikiReadIssue, + ToolWikiUpdateIssue, + } + for _, name := range builtIns { + if !modelcontext.HasToolPolicy(name) { + t.Errorf("built-in tool %q has no entry in modelcontext.toolHandlePolicies", name) + } + } +} + +// AvailableToolDefinitions drives the settings UI, so anything listed there is +// a built-in the Agent can register and must also carry a policy. +func TestAvailableToolDefinitionsDeclareModelHandlePolicies(t *testing.T) { + for _, definition := range AvailableToolDefinitions() { + if !modelcontext.HasToolPolicy(definition.Name) { + t.Errorf("tool %q is exposed to the UI but has no model-handle policy", definition.Name) + } + } +} diff --git a/internal/agent/tools/wiki_flag_issue.go b/internal/agent/tools/wiki_flag_issue.go index 76959192..b71fb11c 100644 --- a/internal/agent/tools/wiki_flag_issue.go +++ b/internal/agent/tools/wiki_flag_issue.go @@ -17,6 +17,7 @@ type wikiFlagIssueTool struct { routes *WikiRouteResolver knowledgeService interfaces.KnowledgeService searchTargets types.SearchTargets + scopeEnforced bool } func NewWikiFlagIssueTool( @@ -67,6 +68,7 @@ func (t *wikiFlagIssueTool) WithKnowledgeScope( ) *wikiFlagIssueTool { t.knowledgeService = knowledgeService t.searchTargets = searchTargets + t.scopeEnforced = true return t } @@ -97,7 +99,7 @@ func (t *wikiFlagIssueTool) Execute(ctx context.Context, args json.RawMessage) ( return &types.ToolResult{Success: false, Error: err.Error()}, nil } suspectedKnowledgeIDs := params.SuspectedKnowledgeIDs - if len(t.searchTargets) > 0 && len(suspectedKnowledgeIDs) > 0 { + if t.scopeEnforced && len(suspectedKnowledgeIDs) > 0 { resolved, scopeErr := resolveAuthorizedSourceRefs( ctx, t.searchTargets, suspectedKnowledgeIDs, t.knowledgeService, ) diff --git a/internal/agent/tools/wiki_read_source_doc.go b/internal/agent/tools/wiki_read_source_doc.go index 963c12ec..723ac2f1 100644 --- a/internal/agent/tools/wiki_read_source_doc.go +++ b/internal/agent/tools/wiki_read_source_doc.go @@ -17,6 +17,7 @@ type wikiReadSourceDocTool struct { knowledgeService interfaces.KnowledgeService chunkService interfaces.ChunkService searchTargets types.SearchTargets + scopeEnforced bool } func NewWikiReadSourceDocTool( @@ -57,8 +58,11 @@ If neither query nor range is provided, it returns the beginning of the document knowledgeService: knowledgeService, chunkService: chunkService, } + // Presence of the variadic argument — not its length — enables the Agent + // authorization boundary, so an empty scope fails closed. if len(searchTargets) > 0 { tool.searchTargets = searchTargets[0] + tool.scopeEnforced = true } return tool } @@ -134,7 +138,7 @@ func (t *wikiReadSourceDocTool) Execute(ctx context.Context, args json.RawMessag var knowledge *types.Knowledge var err error - if len(t.searchTargets) > 0 { + if t.scopeEnforced { knowledge, err = authorizeKnowledgeInSearchTargets(ctx, t.searchTargets, knowledgeID, t.knowledgeService) } else { knowledge, err = t.knowledgeService.GetKnowledgeByIDOnly(ctx, knowledgeID) diff --git a/internal/agent/tools/wiki_replace_text.go b/internal/agent/tools/wiki_replace_text.go index 9d19024f..8a86efa3 100644 --- a/internal/agent/tools/wiki_replace_text.go +++ b/internal/agent/tools/wiki_replace_text.go @@ -17,6 +17,7 @@ type wikiReplaceTextTool struct { kbIDs []string routes *WikiRouteResolver searchTargets types.SearchTargets + scopeEnforced bool } // NewWikiReplaceTextTool creates a new wiki_replace_text tool @@ -61,8 +62,11 @@ func NewWikiReplaceTextTool( } } +// WithSearchTargets enables the Agent authorization boundary for source_refs. +// An Agent turn with no search target must reject every source document. func (t *wikiReplaceTextTool) WithSearchTargets(searchTargets types.SearchTargets) *wikiReplaceTextTool { t.searchTargets = searchTargets + t.scopeEnforced = true return t } @@ -103,7 +107,7 @@ func (t *wikiReplaceTextTool) Execute(ctx context.Context, args json.RawMessage) existingPage.Content = strings.Replace(existingPage.Content, params.OldText, params.NewText, 1) if params.SourceRefs != nil { - if len(t.searchTargets) > 0 { + if t.scopeEnforced { resolvedRefs, scopeErr := resolveAuthorizedSourceRefs(ctx, t.searchTargets, *params.SourceRefs, t.knowledgeService) if scopeErr != nil { return &types.ToolResult{Success: false, Error: "Invalid source_refs: " + scopeErr.Error()}, nil diff --git a/internal/agent/tools/wiki_tools.go b/internal/agent/tools/wiki_tools.go index 661a5c8f..3aaeadd9 100644 --- a/internal/agent/tools/wiki_tools.go +++ b/internal/agent/tools/wiki_tools.go @@ -144,10 +144,9 @@ func NewWikiScopesFromSearchTargets(searchTargets types.SearchTargets, wikiKBIDs if _, ok := allowed[target.KnowledgeBaseID]; !ok { continue } - targetTagIDs := effectiveSearchTargetTagIDs(target) - wholeKB := target.Type == types.SearchTargetTypeKnowledgeBase && - len(target.KnowledgeIDs) == 0 && len(targetTagIDs) == 0 - if !wholeKB && len(target.KnowledgeIDs) == 0 && len(targetTagIDs) == 0 { + targetKnowledgeIDs, targetTagIDs := searchTargetScope(target) + wholeKB := searchTargetIsWholeKB(target) + if !wholeKB && len(targetKnowledgeIDs) == 0 && len(targetTagIDs) == 0 { // A malformed empty document target must not silently become // whole-KB authorization. continue @@ -161,7 +160,7 @@ func NewWikiScopesFromSearchTargets(searchTargets types.SearchTargets, wikiKBIDs scope.unrestricted = true continue } - scope.KnowledgeIDs = append(scope.KnowledgeIDs, target.KnowledgeIDs...) + scope.KnowledgeIDs = append(scope.KnowledgeIDs, targetKnowledgeIDs...) scope.TagIDs = append(scope.TagIDs, targetTagIDs...) } @@ -268,28 +267,15 @@ func registerLinkedSlugs(foundKBs map[string][]string, page *types.WikiPage, kbI } } -// pageIntersectsKnowledgeIDs reports whether the page should pass the -// knowledge-ID scope filter. -// -// - Empty allowed set = "no filter" → always true. -// - Structural pages (index/log) are always surfaced so the model can still -// navigate wiki topology under a pinned-doc scope. -// - Pages with no SourceRefs at all are conservatively allowed through: the -// filter is meant to narrow document-derived content, not hide metadata -// pages that happen to have empty refs. -// - Otherwise, at least one of the page's SourceRefs must be in allowed. +// pageIntersectsKnowledgeIDs reports whether at least one of the page's source +// documents is in the allowed whitelist. Callers must already have established +// that the page has attributable provenance; pagePassesWikiScope owns the +// fail-closed handling of structural and uncited pages. func pageIntersectsKnowledgeIDs(page *types.WikiPage, allowed map[string]bool) bool { if len(allowed) == 0 { return true } - if isStructuralPage(page) { - return true - } - ids := extractSourceKnowledgeIDs(page) - if len(ids) == 0 { - return true - } - for _, kid := range ids { + for _, kid := range extractSourceKnowledgeIDs(page) { if allowed[kid] { return true } diff --git a/internal/agent/tools/wiki_write_page.go b/internal/agent/tools/wiki_write_page.go index 6933c082..f29f7510 100644 --- a/internal/agent/tools/wiki_write_page.go +++ b/internal/agent/tools/wiki_write_page.go @@ -18,6 +18,7 @@ type wikiWritePageTool struct { kbIDs []string routes *WikiRouteResolver searchTargets types.SearchTargets + scopeEnforced bool } // NewWikiWritePageTool creates a new wiki_write_page tool @@ -75,8 +76,11 @@ func NewWikiWritePageTool( } } +// WithSearchTargets enables the Agent authorization boundary for source_refs. +// An Agent turn with no search target must reject every source document. func (t *wikiWritePageTool) WithSearchTargets(searchTargets types.SearchTargets) *wikiWritePageTool { t.searchTargets = searchTargets + t.scopeEnforced = true return t } @@ -117,7 +121,7 @@ func (t *wikiWritePageTool) Execute(ctx context.Context, args json.RawMessage) ( var resolvedRefs []string var err error if params.SourceRefs != nil { - if len(t.searchTargets) > 0 { + if t.scopeEnforced { resolvedRefs, err = resolveAuthorizedSourceRefs(ctx, t.searchTargets, *params.SourceRefs, t.knowledgeService) if err != nil { return &types.ToolResult{Success: false, Error: "Invalid source_refs: " + err.Error()}, nil diff --git a/internal/application/service/agent_service.go b/internal/application/service/agent_service.go index 6d5cfc78..d6182af2 100644 --- a/internal/application/service/agent_service.go +++ b/internal/application/service/agent_service.go @@ -460,10 +460,14 @@ func (s *agentService) registerTools( } wikiKBIDs = dedupStrings(wikiKBIDs) wikiScopes := tools.NewWikiScopesFromSearchTargets(config.SearchTargets, wikiKBIDs) - wikiKBIDs = wikiKBIDs[:0] + // Narrow to the KBs that survived scope resolution. Build a fresh slice + // rather than truncating in place, so the argument passed above can never + // be overwritten through a shared backing array. + scopedWikiKBIDs := make([]string, 0, len(wikiScopes)) for _, scope := range wikiScopes { - wikiKBIDs = append(wikiKBIDs, scope.KnowledgeBaseID) + scopedWikiKBIDs = append(scopedWikiKBIDs, scope.KnowledgeBaseID) } + wikiKBIDs = scopedWikiKBIDs hasWikiKB := len(wikiKBIDs) > 0 // Filter out knowledge base tools if no knowledge scope is configured for this turn. diff --git a/internal/modelcontext/handle_table.go b/internal/modelcontext/handle_table.go index 72c3d7f2..f138ff9b 100644 --- a/internal/modelcontext/handle_table.go +++ b/internal/modelcontext/handle_table.go @@ -2,6 +2,7 @@ package modelcontext import ( "fmt" + "regexp" "sync" ) @@ -26,14 +27,19 @@ type handleTable[M any] struct { } type handleEntry[M any] struct { - value string // durable value a handle decodes back to - meta M + value string // durable value a handle decodes back to + meta M + wordBounded *regexp.Regexp } // handlePair is a snapshot row for text codecs (compaction/decoding). type handlePair struct { value string handle string + // wordBounded matches the handle only on word boundaries. It is compiled + // once at registration because DecodeKnownText runs on every streamed + // chunk, where recompiling per handle per chunk dominated the cost. + wordBounded *regexp.Regexp } // newHandleTable creates a handle space such as c1 (prefix="c", width=0, @@ -71,7 +77,11 @@ func (t *handleTable[M]) register(key, value string, meta M, merge func(dst *M, t.next++ handle := t.prefix + number t.handleByKey[key] = handle - t.entryByHandle[handle] = &handleEntry[M]{value: value, meta: meta} + t.entryByHandle[handle] = &handleEntry[M]{ + value: value, + meta: meta, + wordBounded: regexp.MustCompile(`\b` + regexp.QuoteMeta(handle) + `\b`), + } return handle } @@ -131,7 +141,11 @@ func (t *handleTable[M]) pairs() []handlePair { defer t.mu.RUnlock() out := make([]handlePair, 0, len(t.entryByHandle)) for handle, entry := range t.entryByHandle { - out = append(out, handlePair{value: entry.value, handle: handle}) + out = append(out, handlePair{ + value: entry.value, + handle: handle, + wordBounded: entry.wordBounded, + }) } return out } diff --git a/internal/modelcontext/handles.go b/internal/modelcontext/handles.go index edb63e7f..5eb6608d 100644 --- a/internal/modelcontext/handles.go +++ b/internal/modelcontext/handles.go @@ -1,7 +1,6 @@ package modelcontext import ( - "regexp" "sort" "strings" ) @@ -85,11 +84,13 @@ func (t *HandleTable) DecodeKnownText(value string) string { pairs := t.table.pairs() sort.SliceStable(pairs, func(i, j int) bool { return len(pairs[i].handle) > len(pairs[j].handle) }) for _, item := range pairs { - pattern := regexp.MustCompile(`\b` + regexp.QuoteMeta(item.handle) + `\b`) + if item.wordBounded == nil { + continue + } // A durable value may legally contain '$'. ReplaceAllString would // interpret it as a regexp expansion, so use a literal callback. durable := item.value - value = pattern.ReplaceAllStringFunc(value, func(string) string { return durable }) + value = item.wordBounded.ReplaceAllStringFunc(value, func(string) string { return durable }) } return value } diff --git a/internal/modelcontext/registry.go b/internal/modelcontext/registry.go index 7dde7dcf..591e1f61 100644 --- a/internal/modelcontext/registry.go +++ b/internal/modelcontext/registry.go @@ -256,9 +256,11 @@ func (r *Registry) ModelToolResultForTool(toolName string, result *types.ToolRes // source codec sees any embedded document IDs. Encode once more afterwards // for resource references rendered from structured ToolResult.Data. copyResult := *result - copyResult.Output = r.encodeToolPrivateResult(toolName, result.Output) - copyResult.Output = r.resources.EncodeText(copyResult.Output) - copyResult.Error = r.resources.EncodeText(result.Error) + // Error text is encoded on the same path as Output: a failed tool call + // routinely echoes the offending argument, so a raw durable ID would leak + // through the error branch of an otherwise handle-only tool. + copyResult.Output = r.resources.EncodeText(r.encodeToolPrivateResult(toolName, result.Output)) + copyResult.Error = r.resources.EncodeText(r.encodeToolPrivateResult(toolName, result.Error)) var modelOutput string if sourceOutputAllowed(toolName) { modelOutput = r.sources.ModelOutput(©Result) diff --git a/internal/modelcontext/tool_policy.go b/internal/modelcontext/tool_policy.go index fd1b082b..867a64ef 100644 --- a/internal/modelcontext/tool_policy.go +++ b/internal/modelcontext/tool_policy.go @@ -125,6 +125,34 @@ var toolHandlePolicies = map[string]toolHandlePolicy{ decodedIssueIDKeys: map[string]struct{}{"issue_id": {}}, encodeKnownIssueIDs: true, }, + // Mutation tools echo the slug they acted on and surface validation errors + // that can quote a durable KB or document ID. They own no source arguments, + // but their output must still be compacted before the model sees it. + "wiki_rename_page": { + sourceOutput: true, + }, + "wiki_delete_page": { + sourceOutput: true, + }, + // Agent-private bookkeeping tools echo model-authored text. They need + // compaction so a durable ID quoted back by the model is re-compacted, but + // never structured source rendering. + "thinking": {}, + "todo_write": {}, + // Skill output is user-authored content of unknown shape. Compact known + // durable IDs, but do not mine it for source keys: a skill's JSON may use + // "url"/"knowledge_id" with unrelated semantics. + "read_skill": {}, + "execute_skill_script": {}, +} + +// HasToolPolicy reports whether a tool has an explicit model-handle policy. +// Built-in tools must declare one (even an empty policy) so that adding a tool +// is a deliberate decision about what the model may see, rather than a silent +// fall-through to fully opaque output. +func HasToolPolicy(toolName string) bool { + _, ok := toolHandlePolicies[toolName] + return ok } func sourceArgumentAllowed(toolName, key string) bool { diff --git a/internal/utils/inject.go b/internal/utils/inject.go index 782de8a6..8c57adce 100644 --- a/internal/utils/inject.go +++ b/internal/utils/inject.go @@ -1110,26 +1110,40 @@ func buildKnowledgeBaseScopeCondition(alias string, scopes []SearchScope) string return fmt.Sprintf("%s.id IN (%s)", alias, strings.Join(quoteStringSlice(kbIDs), ", ")) } +// buildScopeClause renders one scope. A scope's document whitelist and tag +// filter are ANDed: each is an independent narrowing of the same KB, so +// applying only one of them would admit rows the other excludes. Scopes are +// ORed against each other by joinOrClauses because they are alternatives. +func buildScopeClause(alias, knowledgeIDColumn string, scope SearchScope) string { + if scope.KnowledgeBaseID == "" { + return "" + } + conditions := []string{ + fmt.Sprintf("%s.knowledge_base_id = %s", alias, quoteString(scope.KnowledgeBaseID)), + } + if len(scope.KnowledgeIDs) > 0 { + conditions = append(conditions, fmt.Sprintf( + "%s.%s IN (%s)", + alias, knowledgeIDColumn, strings.Join(quoteStringSlice(scope.KnowledgeIDs), ", "), + )) + } + if len(scope.TagIDs) > 0 { + conditions = append(conditions, fmt.Sprintf( + "EXISTS (SELECT 1 FROM knowledge_tag_relations ktr WHERE ktr.knowledge_id = %s.%s AND ktr.tag_id IN (%s))", + alias, knowledgeIDColumn, strings.Join(quoteStringSlice(scope.TagIDs), ", "), + )) + } + if len(conditions) == 1 { + return conditions[0] + } + return "(" + strings.Join(conditions, " AND ") + ")" +} + func buildKnowledgeScopeCondition(alias string, scopes []SearchScope) string { clauses := make([]string, 0, len(scopes)) for _, scope := range scopes { - if scope.KnowledgeBaseID == "" { - continue - } - kbID := quoteString(scope.KnowledgeBaseID) - switch { - case len(scope.TagIDs) > 0: - clauses = append(clauses, fmt.Sprintf( - "(%s.knowledge_base_id = %s AND EXISTS (SELECT 1 FROM knowledge_tag_relations ktr WHERE ktr.knowledge_id = %s.id AND ktr.tag_id IN (%s)))", - alias, kbID, alias, strings.Join(quoteStringSlice(scope.TagIDs), ", "), - )) - case len(scope.KnowledgeIDs) > 0: - clauses = append(clauses, fmt.Sprintf( - "(%s.knowledge_base_id = %s AND %s.id IN (%s))", - alias, kbID, alias, strings.Join(quoteStringSlice(scope.KnowledgeIDs), ", "), - )) - default: - clauses = append(clauses, fmt.Sprintf("%s.knowledge_base_id = %s", alias, kbID)) + if clause := buildScopeClause(alias, "id", scope); clause != "" { + clauses = append(clauses, clause) } } return joinOrClauses(clauses) @@ -1138,23 +1152,8 @@ func buildKnowledgeScopeCondition(alias string, scopes []SearchScope) string { func buildChunkScopeCondition(alias string, scopes []SearchScope) string { clauses := make([]string, 0, len(scopes)) for _, scope := range scopes { - if scope.KnowledgeBaseID == "" { - continue - } - kbID := quoteString(scope.KnowledgeBaseID) - switch { - case len(scope.TagIDs) > 0: - clauses = append(clauses, fmt.Sprintf( - "(%s.knowledge_base_id = %s AND EXISTS (SELECT 1 FROM knowledge_tag_relations ktr WHERE ktr.knowledge_id = %s.knowledge_id AND ktr.tag_id IN (%s)))", - alias, kbID, alias, strings.Join(quoteStringSlice(scope.TagIDs), ", "), - )) - case len(scope.KnowledgeIDs) > 0: - clauses = append(clauses, fmt.Sprintf( - "(%s.knowledge_base_id = %s AND %s.knowledge_id IN (%s))", - alias, kbID, alias, strings.Join(quoteStringSlice(scope.KnowledgeIDs), ", "), - )) - default: - clauses = append(clauses, fmt.Sprintf("%s.knowledge_base_id = %s", alias, kbID)) + if clause := buildScopeClause(alias, "knowledge_id", scope); clause != "" { + clauses = append(clauses, clause) } } return joinOrClauses(clauses) diff --git a/internal/utils/inject_test.go b/internal/utils/inject_test.go index 8bf6437c..b3a89663 100644 --- a/internal/utils/inject_test.go +++ b/internal/utils/inject_test.go @@ -481,6 +481,35 @@ func TestValidateAndSecureSQL_WithStructuredSearchScopes(t *testing.T) { } } +// A scope carrying both a document whitelist and a tag filter must apply both. +// Emitting only one of them would admit rows the other excludes. +func TestValidateAndSecureSQL_ScopeCombinesDocumentAndTagFilters(t *testing.T) { + securedSQL, validation, err := ValidateAndSecureSQL( + "SELECT id FROM chunks", + WithSearchScopes([]SearchScope{ + {KnowledgeBaseID: "kb-1", KnowledgeIDs: []string{"doc-1"}, TagIDs: []string{"tag-a"}}, + }), + ) + if err != nil { + t.Fatalf("ValidateAndSecureSQL() error = %v", err) + } + if !validation.Valid { + t.Fatalf("expected validation to pass, got %#v", validation.Errors) + } + for _, want := range []string{ + "chunks.knowledge_base_id = 'kb-1'", + "chunks.knowledge_id IN ('doc-1')", + "ktr.tag_id IN ('tag-a')", + } { + if !strings.Contains(securedSQL, want) { + t.Fatalf("secured SQL missing %q:\n%s", want, securedSQL) + } + } + if strings.Contains(securedSQL, " OR ") { + t.Fatalf("a single scope must not be split into alternatives:\n%s", securedSQL) + } +} + // TestValidateSQL_JSONNodeBypass verifies that PG17 SQL/JSON expression nodes // cannot be used to smuggle dangerous functions past the blacklist. These were // previously accepted because validateNode had no handler for them and fell