Compare commits

..
Author SHA1 Message Date
BaaRai 46751cfb9e fix(intercept): gate ExecuteExtraTool and Monitor by default
The default intercept-enabled set left out ExecuteExtraTool (the dispatcher for MCP and deferred tools) and Monitor (background commands), so calls through them bypassed every rule unless the operator had saved their own enabled-tools list.

A malformed intercept_enabled_tools value also produced an empty set, which turned the rule system off; it now falls back to the defaults, and GetEnabledTools reports the parse error instead of pretending nothing is gated.
2026-11-20 01:48:50 +01:00
5 changed files with 80 additions and 111 deletions
+1 -5
View File
@@ -302,11 +302,7 @@ func (b *whereBuilder) build(node *astNode) (string, error) {
}
parts = append(parts, "("+clause+")")
}
// The whole disjunction must be parenthesised: callers append their own
// clauses with AND (the task scope in QueryDSLInScope, the type filter),
// and AND binds tighter than OR, so "(a) OR (b) AND scope" would let the
// first branch escape the scope.
return "(" + strings.Join(parts, " OR ") + ")", nil
return strings.Join(parts, " OR "), nil
case "leaf":
return b.buildLeaf(*node.expr)
}
-86
View File
@@ -1,86 +0,0 @@
package db
import (
"fmt"
"strings"
"testing"
"time"
)
// A top-level OR must be parenthesised as a whole. QueryDSLInScope appends the
// task-scope clause with AND, and AND binds tighter than OR, so an unparenthesised
// disjunction lets the first branch return rows from outside the task scope.
func TestBuildDSLWhereWrapsOr(t *testing.T) {
node, err := ParseDSL("domain=alpha OR domain=beta")
if err != nil {
t.Fatal(err)
}
where, _, err := buildDSLWhereBase(node, 0)
if err != nil {
t.Fatal(err)
}
if !strings.HasPrefix(where, "((") || !strings.HasSuffix(where, "))") {
t.Fatalf("compiled to %q: the whole OR group must be parenthesised", where)
}
}
// TestQueryDSLInScopeOrDoesNotEscape is the behavioural form: an OR query whose
// first branch matches every row must not return an asset outside the task scope.
func TestQueryDSLInScopeOrDoesNotEscape(t *testing.T) {
d, assets, _ := testSetup(t)
t.Cleanup(func() { d.Close() })
task, err := d.CreateTask("or scope", "goal", nil, 0, 0)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { cleanupErr(t, "task", d.DeleteTask(task.ID)) })
stamp := time.Now().UnixNano()
root := fmt.Sprintf("in%d.invalid", stamp)
out := fmt.Sprintf("x%d.invalid", stamp)
marker := fmt.Sprintf("or%d", stamp)
if err := assets.upsertTaskScope(TaskScope{TaskID: task.ID, Kind: "root_domain", Domain: root}); err != nil {
t.Fatalf("seed scope: %v", err)
}
var inID, outID int64
for _, r := range []struct {
domain, root string
id *int64
}{
{"a." + root, root, &inID},
{out, out, &outID},
} {
if err := d.QueryRow(`INSERT INTO assets(type,domain,root_domain,page_title,last_seen)
VALUES ('subdomain',$1,$2,$3,now()) RETURNING id`, r.domain, r.root, marker).Scan(r.id); err != nil {
t.Fatalf("insert %s: %v", r.domain, err)
}
}
t.Cleanup(func() {
cleanupExec(t, d, `DELETE FROM assets WHERE id=ANY($1::bigint[])`, []int64{inID, outID})
})
// The bare marker matches both rows; the second branch names the out-of-scope
// host. Only the in-scope row may come back.
got, err := assets.QueryDSLInScope(marker+" OR domain="+out, "", task.ID, 50, 0)
if err != nil {
t.Fatal(err)
}
var sawIn, sawOut bool
for _, a := range got {
switch a.ID {
case inID:
sawIn = true
case outID:
sawOut = true
}
}
if !sawIn {
t.Fatalf("in-scope asset %d missing from %+v", inID, got)
}
if sawOut {
t.Fatalf("out-of-scope asset %d leaked through an OR query", outID)
}
}
+3 -1
View File
@@ -530,7 +530,9 @@ func TestGateOffLeavesEveryBranchUnchanged(t *testing.T) {
for name, ctx := range off {
before := len(g.rows())
// 1. A tool outside the enabled set: passes, nothing is written.
for _, c := range []struct{ tool, input string }{{"Monitor", curl(deny)}, {"mcp__scan__run", `{"target":"203.0.113.7","note":"` + deny + `"}`}} {
// Monitor and ExecuteExtraTool are in the default set now, so use read-only
// tools and an MCP name (inner names are not in the set).
for _, c := range []struct{ tool, input string }{{"list_assets", curl(deny)}, {"mcp__scan__run", `{"target":"203.0.113.7","note":"` + deny + `"}`}} {
if block, msg := pre(guard, ctx, c.tool, c.input); block {
t.Fatalf("%s: %s blocked: %s", name, c.tool, msg)
}
+48
View File
@@ -0,0 +1,48 @@
package intercept
import "testing"
// TestDefaultEnabledToolsCoverExecutors pins the tools that must be gated when no
// intercept_enabled_tools setting has been saved. ExecuteExtraTool and Monitor
// dispatch MCP / deferred tools and background commands, so leaving them out let
// those calls bypass every rule.
func TestDefaultEnabledToolsCoverExecutors(t *testing.T) {
got := map[string]bool{}
for _, name := range defaultEnabledTools {
got[name] = true
}
for _, want := range []string{"Bash", "Write", "Edit", "MultiEdit", "ExecuteExtraTool", "Monitor"} {
if !got[want] {
t.Errorf("defaultEnabledTools must include %q", want)
}
}
for _, readOnly := range []string{"list_assets", "traffic_search", "Read"} {
if got[readOnly] {
t.Errorf("defaultEnabledTools must not gate the read-only tool %q by default", readOnly)
}
}
}
// TestEnabledToolsFromSettingNeverDisablesTheGate: an unset or malformed setting
// must keep the defaults, not turn the rule system off.
func TestEnabledToolsFromSettingNeverDisablesTheGate(t *testing.T) {
for _, tc := range []struct {
name string
val string
ok bool
}{
{"unset", "", false},
{"malformed", "{not json", true},
{"wrong shape", `"Bash"`, true},
} {
got := enabledToolsFromSetting(tc.val, tc.ok)
if !got["Bash"] || !got["ExecuteExtraTool"] || !got["Monitor"] {
t.Errorf("%s: enabled tools %v, want the defaults", tc.name, got)
}
}
// A valid explicit list replaces the defaults.
got := enabledToolsFromSetting(`["Bash"]`, true)
if !got["Bash"] || got["WebFetch"] {
t.Fatalf("explicit list: %v, want only Bash", got)
}
}
+28 -19
View File
@@ -266,6 +266,10 @@ var defaultEnabledTools = []string{
"Bash", "WebFetch", "web_search",
"shell_open", "shell_send",
"Write", "Edit", "MultiEdit",
// ExecuteExtraTool dispatches MCP and deferred tools, and Monitor starts a
// background command; both execute third-party or shell commands, so they
// belong in the default gate with the rest.
"ExecuteExtraTool", "Monitor",
}
// New creates an Interceptor backed by d. The rule cache is lazy-loaded on
@@ -305,27 +309,32 @@ func (i *Interceptor) loadLocked() error {
// Load enabled-tools set from settings, falling back to hard-coded defaults.
val, ok, _ := i.db.GetSetting("intercept_enabled_tools")
if !ok {
m := make(map[string]bool, len(defaultEnabledTools))
for _, n := range defaultEnabledTools {
m[n] = true
}
i.enabledTools = m
} else {
var names []string
if json.Unmarshal([]byte(val), &names) != nil {
i.enabledTools = map[string]bool{}
} else {
m := make(map[string]bool, len(names))
for _, n := range names {
m[n] = true
}
i.enabledTools = m
}
}
i.enabledTools = enabledToolsFromSetting(val, ok)
return nil
}
// enabledToolsFromSetting maps the stored intercept_enabled_tools value to the
// gate's set. A malformed value must not silently disable the gate, so it falls
// back to the same defaults as an unset setting.
func enabledToolsFromSetting(val string, ok bool) map[string]bool {
m := make(map[string]bool, len(defaultEnabledTools))
for _, n := range defaultEnabledTools {
m[n] = true
}
if !ok {
return m
}
var names []string
if json.Unmarshal([]byte(val), &names) != nil {
return m
}
m = make(map[string]bool, len(names))
for _, n := range names {
m[n] = true
}
return m
}
func (i *Interceptor) rules() ([]compiledRule, error) {
i.mu.RLock()
if i.cached != nil {
@@ -381,7 +390,7 @@ func (i *Interceptor) GetEnabledTools() ([]string, error) {
}
var names []string
if err := json.Unmarshal([]byte(val), &names); err != nil {
return []string{}, nil
return nil, fmt.Errorf("intercept_enabled_tools is not valid JSON: %w", err)
}
return names, nil
}