diff --git a/CHANGELOG.md b/CHANGELOG.md index 47e5437ec..68a5af775 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ All notable changes to this project are documented in this file. The format is b ### Security - **The target gate honors operator-approved egress grants.** The gate compared every target with pins only, while the sandbox proxy allowed every port of an operator-approved CIDR grant: a host already inside a granted task or company scope still raised per-port and bare-host approval prompts (pins match `host:port`, and a request naming the host without a port is covered only by a port-0 pin). `CheckTargets` now also consults the grants the operator approved for the task (its approved, unexpanded `task_scope` rows and the entries frozen into `task_scope_egress` by approved company grants, normalized as the proxy allowlist is): a domain matching a granted domain, an address inside a granted CIDR, or a range fully inside one passes as covered by `scope_grant`, recorded once per process and target key as a system-decided allowed row with the target outcome `scope_grant`. Pins, stored exemptions, block rules and human approvals are unchanged: anything outside a grant is decided as before, and task allow rules play no role, as everywhere in the gate. Related to #830, the mirror gap on the network side. +- **Chat-spawned tasks inherit fully operator-approved companies (#830).** Migration `0025_company_scope_approved.sql` made company scope an explicit operator decision, but `spawn_task` still stamped the whole company link `approved_by_operator=false`, so a chat-spawned task started with an empty egress allowlist and every connection was denied until an operator approved scope again per task (the trap #833 warns about). `CreateTaskWithOptions` now checks each LLM-selected company: one whose scope inventory exists and is entirely operator-approved and to which the calling task itself holds an operator-approved link carries standing consent, so its task link is inserted approved (a spawn with no task caller - chat session or direct API - inherits nothing, per review on #841) and its grant frozen into `task_scope_egress`, exactly as an operator selection does; a company holding any agent-written (unapproved) row, and one with no scope rows, stay coverage-only, so `add_company_scope`, the ScopeSentry sync and invented ids still grant nothing without a fresh operator decision. Provenance is preserved: `source` stays `agent` and the approval column records the inherited consent row by row. Related: #830, #833. - **Company egress is promoted only from operator-approved company scope.** A sandboxed worker could register assets with `insert_assets` (an attacker IP or domain attributed to the company through its domain or ICP rule), and the agent could add rules with `add_company_scope`; the next operator selection or re-approval of the company copied those hosts into `task_scope_egress`, persistently widening the approved sandbox egress. The approval snapshot now copies only `company_scope` domain and IP/CIDR rules with the new `approved_by_operator` flag (migration `0025_company_scope_approved.sql`), which only the operator company API sets; `add_company_scope` and the ScopeSentry sync store rules with the flag off. Existing rules are backfilled as approved. Behaviour change: a domain or IP discovered only in assets is no longer reachable from the sandbox until it is added explicitly to the company scope (operator) or to the task scope. Egress rows already frozen by earlier approvals are not purged by this change, and re-approving the company does not remove them (the snapshot only adds rows); removing the company from the task scope drops its rows, and approving it again rebuilds them from approved rules only. - **Session tokens accept only HS256 and carry an issuer and audience.** Token checks accepted any HMAC algorithm (HS384, HS512) signed with the session key; they now accept only HS256. New tokens have `iss: artex` and `aud: artex-api`, and a token that has either claim with another value is rejected. Tokens issued by earlier releases have neither claim and stay valid until they expire, so upgrading does not sign anyone out. diff --git a/db/company_scope_approval_test.go b/db/company_scope_approval_test.go index ad5a1022a..cd95fcb21 100644 --- a/db/company_scope_approval_test.go +++ b/db/company_scope_approval_test.go @@ -63,3 +63,167 @@ RETURNING approved_by_operator`, companyID).Scan(&fresh); err != nil { t.Fatal("a row written after the migration defaulted to approved_by_operator=true") } } + +// TestSpawnInheritsFullyApprovedCompany (#830, #841): a task created by the +// LLM (CompanyScopeByAgent=true) stamps the company link operator-approved and +// freezes the egress grant for a company whose entire scope inventory the +// operator approved - but only within the caller's trust boundary (review +// 6154399166): the caller task must itself hold an operator-approved link to +// that company. A company holding any unapproved row, one with no scope rows +// at all, and one the caller cannot reach stay coverage-only, so +// add_company_scope and invented ids still grant nothing without a fresh +// operator decision. +func TestSpawnInheritsFullyApprovedCompany(t *testing.T) { + dsn := scratchDSN(t, "spawn_inherit_830") + d, err := Open(dsn) + if err != nil { + t.Fatalf("initial Open: %v", err) + } + defer d.Close() + mk := func(name string) int64 { + var id int64 + if err := d.QueryRow(`INSERT INTO companies(name, nkey) VALUES ($1, lower($1)) RETURNING id`, name).Scan(&id); err != nil { + t.Fatalf("insert company %s: %v", name, err) + } + return id + } + exec := func(stmt string, args ...any) { + t.Helper() + if _, err := d.Exec(stmt, args...); err != nil { + t.Fatalf("seed (%s): %v", stmt, err) + } + } + fullID := mk("SpawnFull Co") + exec(`INSERT INTO company_scope(company_id, kind, domain, raw, approved_by_operator) VALUES ($1, 'domain', 'full830.test', 'full830.test', TRUE)`, fullID) + exec(`INSERT INTO company_scope(company_id, kind, net, raw, approved_by_operator) VALUES ($1, 'ip', '198.51.100.9/32', '198.51.100.9', TRUE)`, fullID) + halfID := mk("SpawnHalf Co") + exec(`INSERT INTO company_scope(company_id, kind, domain, raw, approved_by_operator) VALUES ($1, 'domain', 'half830.test', 'half830.test', TRUE)`, halfID) + exec(`INSERT INTO company_scope(company_id, kind, domain, raw, approved_by_operator) VALUES ($1, 'domain', 'agent830.test', 'agent830.test', FALSE)`, halfID) + emptyID := mk("SpawnEmpty Co") + // A second fully approved company the caller cannot reach: inheritance must + // stop at the trust boundary (#841, review 6154399166). + otherID := mk("SpawnOther Co") + exec(`INSERT INTO company_scope(company_id, kind, domain, raw, approved_by_operator) VALUES ($1, 'domain', 'other841.test', 'other841.test', TRUE)`, otherID) + // Operator caller: linked, approved, to the full company only. + caller, err := d.CreateTaskWithOptions("caller841", "goal", TaskCreateOptions{ + CompanyIDs: []int64{fullID}, + }) + if err != nil { + t.Fatalf("CreateTaskWithOptions caller: %v", err) + } + task, err := d.CreateTaskWithOptions("spawn830", "goal", TaskCreateOptions{ + CompanyIDs: []int64{fullID, halfID, emptyID, otherID}, + CompanyScopeByAgent: true, + CompanyScopeCallerID: caller.ID, + }) + if err != nil { + t.Fatalf("CreateTaskWithOptions: %v", err) + } + want := map[int64]bool{fullID: true, halfID: false, emptyID: false, otherID: false} + rows, err := d.Query(`SELECT company_id, approved_by_operator, source FROM task_scope WHERE task_id=$1 AND kind='company'`, task.ID) + if err != nil { + t.Fatalf("read task_scope: %v", err) + } + seen := map[int64]bool{} + for rows.Next() { + var cid int64 + var approved bool + var source string + if err := rows.Scan(&cid, &approved, &source); err != nil { + t.Fatalf("scan task_scope: %v", err) + } + seen[cid] = true + if approved != want[cid] { + t.Errorf("company %d: approved_by_operator=%v, want %v", cid, approved, want[cid]) + } + if source != "agent" { + t.Errorf("company %d: source=%q, want agent (provenance must survive inheritance)", cid, source) + } + } + rows.Close() + for cid := range want { + if !seen[cid] { + t.Errorf("company %d has no task_scope link", cid) + } + } + // The snapshot holds exactly the inherited company's approved rows: the + // half company's approved row must not be frozen while its link is + // unapproved, and nothing comes from the empty company. + grants, err := d.CompanyEgressForTask(task.ID, fullID) + if err != nil { + t.Fatalf("CompanyEgressForTask: %v", err) + } + if len(grants) != 2 { + t.Fatalf("full company egress %v, want the approved domain and IP", grants) + } + for _, g := range grants { + if !(g.Kind == "domain" && g.Value == "full830.test") && !(g.Kind == "cidr" && (g.Value == "198.51.100.9/32" || g.Value == "198.51.100.9")) { + t.Errorf("unexpected grant %+v", g) + } + } + if halfGrants, err := d.CompanyEgressForTask(task.ID, halfID); err != nil || len(halfGrants) != 0 { + t.Errorf("half company egress %v (%v), want none", halfGrants, err) + } + // The unreachable-but-fully-approved company crossed no trust boundary: it + // froze nothing. + if otherGrants, err := d.CompanyEgressForTask(task.ID, otherID); err != nil || len(otherGrants) != 0 { + t.Errorf("unreachable company egress %v (%v), want none", otherGrants, err) + } + if _, err := d.Exec(`DELETE FROM task_scope_egress WHERE task_id=$1 AND company_id IS NULL`, task.ID); err != nil { + t.Fatalf("cleanup probe: %v", err) + } + var stray int + if err := d.QueryRow(`SELECT count(*) FROM task_scope_egress WHERE task_id=$1`, task.ID).Scan(&stray); err != nil { + t.Fatalf("count egress: %v", err) + } + if stray != 2 { + t.Errorf("task holds %d egress rows, want only the two inherited ones", stray) + } +} + +// TestSpawnWithoutTaskCallerDoesNotAutoApprove (review 6154399166): a +// CompanyScopeByAgent spawn with no task caller - a chat session or direct API +// use - must not silently auto-approve even a fully operator-approved company. +// The trust boundary between caller and child has nothing to inherit through, +// so the link stays coverage-only until the operator confirms it on the task +// scope; the child starts with an empty allowlist, as before #830. +func TestSpawnWithoutTaskCallerDoesNotAutoApprove(t *testing.T) { + dsn := scratchDSN(t, "spawn_nocaller_841") + d, err := Open(dsn) + if err != nil { + t.Fatalf("initial Open: %v", err) + } + defer d.Close() + var fullID int64 + if err := d.QueryRow(`INSERT INTO companies(name, nkey) VALUES ('NoCaller Co', 'nocaller co') RETURNING id`).Scan(&fullID); err != nil { + t.Fatalf("insert company: %v", err) + } + if _, err := d.Exec(`INSERT INTO company_scope(company_id, kind, domain, raw, approved_by_operator) VALUES ($1, 'domain', 'nocaller841.test', 'nocaller841.test', TRUE)`, fullID); err != nil { + t.Fatalf("seed approved company_scope row: %v", err) + } + task, err := d.CreateTaskWithOptions("nocaller841", "goal", TaskCreateOptions{ + CompanyIDs: []int64{fullID}, + CompanyScopeByAgent: true, + }) + if err != nil { + t.Fatalf("CreateTaskWithOptions: %v", err) + } + var approved bool + var source string + if err := d.QueryRow(`SELECT approved_by_operator, source FROM task_scope WHERE task_id=$1 AND kind='company' AND company_id=$2`, task.ID, fullID).Scan(&approved, &source); err != nil { + t.Fatalf("read task_scope link: %v", err) + } + if approved { + t.Error("spawn with no task caller auto-approved the company link; want coverage-only pending operator confirmation") + } + if source != "agent" { + t.Errorf("source=%q, want agent (provenance must survive either way)", source) + } + grants, err := d.CompanyEgressForTask(task.ID, fullID) + if err != nil { + t.Fatalf("CompanyEgressForTask: %v", err) + } + if len(grants) != 0 { + t.Errorf("no-caller spawn inherited grants %v, want none", grants) + } +} diff --git a/db/tasks.go b/db/tasks.go index 905fe9e11..3506bdbb8 100644 --- a/db/tasks.go +++ b/db/tasks.go @@ -182,9 +182,21 @@ type TaskCreateOptions struct { // OFF for unscoped tasks; pass an explicit false pointer to opt out. TargetGate *bool // CompanyScopeByAgent marks CompanyIDs supplied by an LLM orchestration tool - // (spawn_task) rather than an authenticated operator, leaving task_scope - // approved_by_operator=false (coverage-only) to prevent scope drift. + // (spawn_task) rather than an authenticated operator. The link is inserted + // approved_by_operator=false (coverage-only), except for a company whose + // whole scope inventory the operator approved AND to which the calling + // task itself holds an operator-approved link (CompanyScopeCallerID): that + // standing consent is inherited, so chat-spawned tasks stop starting with + // an empty allowlist against companies the operator configured (#830) + // while the caller boundary keeps the agent from self-widening reach + // (#841). CompanyScopeByAgent bool + // CompanyScopeCallerID is the id of the task running spawn_task when + // CompanyScopeByAgent is set (0 = no task caller: chat session or direct + // API use). Standing company consent is inherited only for companies the + // caller task itself holds operator-approved links to; with no task caller + // nothing is auto-approved (#841, review 6154399166). + CompanyScopeCallerID int64 } // CreateTaskWithOptions creates an exploration, task, direct source relations, @@ -281,7 +293,7 @@ RETURNING id, status, paused, created_at`, opts.Name, opts.CategoryID, descripti if err := insertTaskRelations(tx, t.ID, opts.SourceTaskIDs); err != nil { return nil, err } - if err := insertTaskCompanies(tx, t.ID, opts.CompanyIDs, !opts.CompanyScopeByAgent); err != nil { + if err := insertTaskCompanies(tx, t.ID, opts.CompanyIDs, !opts.CompanyScopeByAgent, opts.CompanyScopeCallerID); err != nil { return nil, err } if err := insertTaskLLMProfiles(tx, t.ID, opts.LLMProfileIDs); err != nil { @@ -298,7 +310,7 @@ RETURNING id, status, paused, created_at`, opts.Name, opts.CategoryID, descripti return t, tx.Commit() } -func insertTaskCompanies(tx *sql.Tx, taskID int64, companyIDs []int64, approvedByOperator bool) error { +func insertTaskCompanies(tx *sql.Tx, taskID int64, companyIDs []int64, approvedByOperator bool, callerTaskID int64) error { if len(companyIDs) == 0 { return nil } @@ -311,6 +323,36 @@ func insertTaskCompanies(tx *sql.Tx, taskID int64, companyIDs []int64, approvedB if !approvedByOperator { src = "agent" } + // #830: migration 0025 made each company-scope row an explicit operator + // decision, so a company whose whole inventory is operator-approved carries + // standing operator consent. An LLM-selected company of that kind grants + // nothing new at spawn: its task link is inserted approved and its grant + // frozen, exactly as an operator selection would, and chat-spawned tasks + // stop starting with an empty allowlist against a company the operator + // configured. A company holding any agent-written (unapproved) row, or with + // no scope rows at all, stays coverage-only: add_company_scope and invented + // ids still cannot self-grant. Provenance is kept either way: source stays + // agent, the approval column records who consented. + // #841 review 6154399166 adds the trust boundary: that consent only flows + // to a child through a caller that already reaches the company, so an + // agent spawn inherits only within the calling task's operator-approved + // companies, and a spawn with no task caller (chat session, direct API) + // inherits nothing silently. + var inherited []int64 + if !approvedByOperator { + var err error + inherited, err = companiesInheritableByCallerTx(tx, companyIDs, callerTaskID) + if err != nil { + return err + } + } + grantIDs := companyIDs + if !approvedByOperator { + grantIDs = inherited + } + if grantIDs == nil { + grantIDs = []int64{} + } var inserted int err := tx.QueryRow(` WITH requested(company_id, position) AS ( @@ -318,13 +360,14 @@ WITH requested(company_id, position) AS ( FROM unnest($2::bigint[]) WITH ORDINALITY AS requested(company_id, position) ), inserted AS ( INSERT INTO task_scope(task_id, kind, company_id, source, reason, approved_by_operator) - SELECT $1, 'company', companies.id, $3, 'associated with company at task creation', $4 + SELECT $1, 'company', companies.id, $3, 'associated with company at task creation', + $4::boolean OR requested.company_id = ANY($5::bigint[]) FROM requested JOIN companies ON companies.id=requested.company_id ORDER BY requested.position RETURNING company_id ) -SELECT count(*) FROM inserted`, taskID, companyIDs, src, approvedByOperator).Scan(&inserted) +SELECT count(*) FROM inserted`, taskID, companyIDs, src, approvedByOperator, grantIDs).Scan(&inserted) if err != nil { return err } @@ -357,16 +400,62 @@ SET source=EXCLUDED.source, source_node_id=NULL`, taskID, companyIDs, taskCompanyAssetSource); err != nil { return err } - if approvedByOperator { - // Freeze the company inventory this operator decision covers: the sandbox - // proxy reads the snapshot, not live company_scope/assets. - if err := snapshotCompanyEgress(tx, taskID, companyIDs); err != nil { + if len(grantIDs) > 0 { + // Freeze the company inventory this operator decision covers: the + // sandbox proxy reads the snapshot, not live company_scope/assets. For + // an agent spawn that is only the inherited companies; the snapshot + // itself copies 0025-approved rows only. + if err := snapshotCompanyEgress(tx, taskID, grantIDs); err != nil { return err } } return nil } +// companiesInheritableByCallerTx returns the requested companies whose egress +// inheritance is consented twice over: the company's company_scope inventory +// exists and is entirely operator-approved (the company-level consent +// migration 0025 introduced), AND the calling task holds its own +// operator-approved link to that company (#841, review 6154399166). Selecting +// such a company at spawn introduces no address the operator has not already +// approved for it and no reach the caller did not already have; companies +// without scope rows (an id the LLM invented, or an empty inventory), +// companies holding any unapproved row, and companies the caller cannot reach +// are excluded - promoting those would let the agent widen its own sandbox. A +// callerTaskID of 0 (chat session, direct API) inherits nothing: the child +// starts coverage-only until the operator confirms the link on the task scope. +func companiesInheritableByCallerTx(tx *sql.Tx, companyIDs []int64, callerTaskID int64) ([]int64, error) { + if len(companyIDs) == 0 || callerTaskID <= 0 { + return nil, nil + } + rows, err := tx.Query(` +SELECT ids.id +FROM unnest($1::bigint[]) AS ids(id) +WHERE EXISTS (SELECT 1 FROM company_scope cs WHERE cs.company_id = ids.id) + AND NOT EXISTS (SELECT 1 FROM company_scope cs + WHERE cs.company_id = ids.id + AND cs.approved_by_operator IS DISTINCT FROM TRUE) + AND EXISTS (SELECT 1 FROM task_scope ts + WHERE ts.task_id = $2 + AND ts.kind = 'company' + AND ts.company_id = ids.id + AND ts.approved_by_operator IS TRUE) +ORDER BY ids.id`, companyIDs, callerTaskID) + if err != nil { + return nil, err + } + defer rows.Close() + var out []int64 + for rows.Next() { + var id int64 + if err := rows.Scan(&id); err != nil { + return nil, err + } + out = append(out, id) + } + return out, rows.Err() +} + func insertTaskRelations(tx *sql.Tx, taskID int64, sourceIDs []int64) error { seen := map[int64]bool{} for _, sourceID := range sourceIDs { diff --git a/docs/SANDBOX.md b/docs/SANDBOX.md index 6ebc1a650..255f84976 100644 --- a/docs/SANDBOX.md +++ b/docs/SANDBOX.md @@ -121,7 +121,7 @@ ARTEX_SANDBOX_DOCKER_TEST=1 go test ./sandbox -run TestDockerTimeoutRemovesDetac | `POST /api/tasks/{id}/retarget` (`db.RetargetTask`) | `true` | Operator retarget to a newly provisioned target host | | `add_task_scope` (`AddAgentScope`) | `false` | Agent coverage-only (even if `source="manual"` is passed) | | `insert_assets` (`AddAutoScope`) | `false` | Auto-discovered coverage-only | -| `spawn_task` (`CompanyScopeByAgent: true`) | `false` | Agent-spawned subtask company links require operator approval before granting sandbox egress | +| `spawn_task` (`CompanyScopeByAgent: true`) | `false`; `true` only for a company whose whole inventory the operator approved **and** the calling task is itself operator-approved for | Standing consent inherits only through the caller's trust boundary (#841); a spawn with no task caller (chat session, direct API) stays coverage-only pending operator confirmation (#830) | | Archive restore (`restoreTaskScopes`) | preserved (`false` if absent) | Post-0023 archives preserve `approved_by_operator`; legacy pre-0023 archives default to `false` (fail-closed — operators must re-approve scope rows before sandbox egress is granted) | ### Target-Gate Approval vs. Worker Egress (MVP Behavior) diff --git a/server/orchestration.go b/server/orchestration.go index d3f9bf788..a62888069 100644 --- a/server/orchestration.go +++ b/server/orchestration.go @@ -341,18 +341,28 @@ func (s *Server) toolSpawnTask() actool.CoreTool { // the block rules of the calling task. Read from the caller's scope, never // from parent_ref (optional and written by the model). Pins and allow rules // are never copied. Gate-off caller or no scope: created as before. + // The caller id is read whether or not the gate is on (#841, review + // 6154399166): it is the trust boundary for company-grant inheritance, + // and a chat session (ConversationID, no TaskID) leaves it 0 so nothing + // is auto-approved for the child. var gate *bool var blockRules []db.TaskInterceptRuleInput - if scope, ok := intercept.TargetScopeFromContext(ctx); ok && scope.Enabled != nil && scope.Enabled() { - on := true - gate = &on - if callerID, err := strconv.ParseInt(scope.TaskID, 10, 64); err == nil && callerID > 0 { - block, _, err := s.m.Assets().TaskInterceptRulesSplit(callerID) - if err != nil { - return actool.Errorf("read the block rules of the calling task: " + err.Error()), nil - } - for _, r := range block { - blockRules = append(blockRules, db.TaskInterceptRuleInput{Enabled: r.Enabled, Action: r.Action, Kind: r.Kind, Pattern: r.Pattern, Note: r.Note}) + var callerID int64 + if scope, ok := intercept.TargetScopeFromContext(ctx); ok { + if id, err := strconv.ParseInt(scope.TaskID, 10, 64); err == nil && id > 0 { + callerID = id + } + if scope.Enabled != nil && scope.Enabled() { + on := true + gate = &on + if callerID > 0 { + block, _, err := s.m.Assets().TaskInterceptRulesSplit(callerID) + if err != nil { + return actool.Errorf("read the block rules of the calling task: " + err.Error()), nil + } + for _, r := range block { + blockRules = append(blockRules, db.TaskInterceptRuleInput{Enabled: r.Enabled, Action: r.Action, Kind: r.Kind, Pattern: r.Pattern, Note: r.Note}) + } } } } @@ -360,6 +370,7 @@ func (s *Server) toolSpawnTask() actool.CoreTool { SourceTaskIDs: sourceIDs, CompanyIDs: companyIDs, CompanyScopeByAgent: true, + CompanyScopeCallerID: callerID, LLMProfileIDs: llmIDs, TimeoutSeconds: a.TimeoutSeconds, PlanHeartbeatSeconds: a.PlanHeartbeatSeconds, diff --git a/server/sandbox_scope_drift_test.go b/server/sandbox_scope_drift_test.go index 19c107a36..7b939f2b4 100644 --- a/server/sandbox_scope_drift_test.go +++ b/server/sandbox_scope_drift_test.go @@ -332,19 +332,122 @@ func TestSandboxScopeDriftBlockedAcrossProxyWebFetchAndBrowser(t *testing.T) { } assertAllDenied(t, "old-retargeted-host-removed", "http://"+oldRetargetHost+"/", proxy4, wf4, br4) - // Agent-spawned task (spawn_task sets CompanyScopeByAgent=true) must NOT mint - // operator-approved egress for an arbitrary company. + // Agent-spawned task (spawn_task sets CompanyScopeByAgent=true) inherits a + // company whose whole inventory the operator approved (#830, on top of + // migration 0025) through the caller's trust boundary (#841, review + // 6154399166): tCaller holds the operator-approved link to opComp, so its + // spawn carries opComp's operator-entered domain and canary IP instead of + // the empty allowlist that made every connection from a chat-spawned task + // 403. Provenance stays agent; the approval column records that the + // consent predates the spawn. + tCaller, err := pg.CreateTaskWithOptions("caller-"+suffix, "goal", db.TaskCreateOptions{ + CompanyIDs: []int64{opCompID}, + }) + if err != nil { + t.Fatalf("CreateTaskWithOptions caller: %v", err) + } tAgentSpawn, err := pg.CreateTaskWithOptions("agent-spawn-"+suffix, "goal", db.TaskCreateOptions{ + CompanyIDs: []int64{opCompID}, + CompanyScopeByAgent: true, + CompanyScopeCallerID: tCaller.ID, + }) + if err != nil { + t.Fatalf("CreateTaskWithOptions agent-spawn: %v", err) + } + info5, proxy5, wf5, _ := buildEnforcers(t, tAgentSpawn.ID) + if !containsStr(info5.ScopeDomains, opCompDom) || !containsStr(info5.ScopeCIDRs, canaryHost+"/32") { + t.Fatalf("agent-spawned task must inherit the fully approved company: domains=%v cidrs=%v", info5.ScopeDomains, info5.ScopeCIDRs) + } + if code, err := proxy5("http://api." + opCompDom + "/v1"); err != nil || code != http.StatusOK { + t.Fatalf("proxy should allow the inherited company subdomain, got code=%d err=%v", code, err) + } + if ok, body := wf5(canaryURL); !ok || !strings.Contains(body, "CANARY_REACHED") { + t.Fatalf("WebFetch should allow the inherited company IP, got ok=%v body=%q", ok, body) + } + + // The inheritance requires ALL of the company's scope rows to be approved: + // one agent-written row (add_company_scope, ScopeSentry sync) keeps the + // whole company coverage-only, so the agent can never self-widen a spawn + // grant by appending one row to an operator company. + halfDom := "half-co-" + suffix + ".test" + halfID, _, _, _, _, err := pg.Companies().CreateCompanyWithScope("HalfApprovedCo-"+suffix, "", + []db.ScopeInput{{Kind: "domain", Value: halfDom}}, "test", true) + if err != nil { + t.Fatalf("CreateCompanyWithScope halfComp: %v", err) + } + if _, err := pg.Exec(`INSERT INTO company_scope(company_id, kind, domain, raw, approved_by_operator) +VALUES ($1, 'domain', $2, $2, false)`, halfID, "agent-row-"+suffix+".test"); err != nil { + t.Fatalf("seed agent company_scope row: %v", err) + } + // Keep the trust boundary satisfied here, so this case tests the + // half-approved inventory itself and not an unreachable company. + tHalfCaller, err := pg.CreateTaskWithOptions("half-caller-"+suffix, "goal", db.TaskCreateOptions{ + CompanyIDs: []int64{halfID}, + }) + if err != nil { + t.Fatalf("CreateTaskWithOptions half-caller: %v", err) + } + tHalf, err := pg.CreateTaskWithOptions("half-spawn-"+suffix, "goal", db.TaskCreateOptions{ + CompanyIDs: []int64{halfID}, + CompanyScopeByAgent: true, + CompanyScopeCallerID: tHalfCaller.ID, + }) + if err != nil { + t.Fatalf("CreateTaskWithOptions half-spawn: %v", err) + } + info6, proxy6, wf6, br6 := buildEnforcers(t, tHalf.ID) + if len(info6.ScopeDomains) != 0 || len(info6.ScopeCIDRs) != 0 { + t.Fatalf("company holding an agent row must stay coverage-only: domains=%v cidrs=%v", info6.ScopeDomains, info6.ScopeCIDRs) + } + assertAllDenied(t, "half-approved-company", "http://"+halfDom+"/", proxy6, wf6, br6) + // A company with no scope rows at all grants nothing: an id the LLM + // invented, or an empty inventory, is not standing consent. + emptyID, _, _, _, _, err := pg.Companies().CreateCompanyWithScope("EmptyCo-"+suffix, "", nil, "test", true) + if err != nil { + t.Fatalf("CreateCompanyWithScope emptyComp: %v", err) + } + tEmptyCaller, err := pg.CreateTaskWithOptions("empty-caller-"+suffix, "goal", db.TaskCreateOptions{ + CompanyIDs: []int64{emptyID}, + }) + if err != nil { + t.Fatalf("CreateTaskWithOptions empty-caller: %v", err) + } + tEmpty, err := pg.CreateTaskWithOptions("empty-spawn-"+suffix, "goal", db.TaskCreateOptions{ + CompanyIDs: []int64{emptyID}, + CompanyScopeByAgent: true, + CompanyScopeCallerID: tEmptyCaller.ID, + }) + if err != nil { + t.Fatalf("CreateTaskWithOptions empty-spawn: %v", err) + } + info7, _, _, _ := buildEnforcers(t, tEmpty.ID) + if len(info7.ScopeDomains) != 0 || len(info7.ScopeCIDRs) != 0 { + t.Fatalf("company without scope rows must grant no egress: domains=%v cidrs=%v", info7.ScopeDomains, info7.ScopeCIDRs) + } + // Same fully approved company as case 4, spawn with no task caller (chat + // session or direct API): the trust boundary has nothing to inherit + // through, so nothing is auto-approved silently - the child keeps the + // empty allowlist until the operator confirms the link (#841, review + // 6154399166). + tNoCaller, err := pg.CreateTaskWithOptions("nocaller-"+suffix, "goal", db.TaskCreateOptions{ CompanyIDs: []int64{opCompID}, CompanyScopeByAgent: true, }) if err != nil { - t.Fatalf("CreateTaskWithOptions agent-spawn: %v", err) + t.Fatalf("CreateTaskWithOptions nocaller-spawn: %v", err) } - info5, proxy5, wf5, br5 := buildEnforcers(t, tAgentSpawn.ID) - if len(info5.ScopeDomains) != 0 || len(info5.ScopeCIDRs) != 0 { - t.Fatalf("agent-spawned task leaked company scope into sandbox allowlist: domains=%v cidrs=%v", info5.ScopeDomains, info5.ScopeCIDRs) + info8, proxy8, wf8, br8 := buildEnforcers(t, tNoCaller.ID) + if len(info8.ScopeDomains) != 0 || len(info8.ScopeCIDRs) != 0 { + t.Fatalf("spawn without a task caller must stay coverage-only: domains=%v cidrs=%v", info8.ScopeDomains, info8.ScopeCIDRs) + } + assertAllDenied(t, "no-caller-spawn", "http://api."+opCompDom+"/v1", proxy8, wf8, br8) +} + +func containsStr(list []string, want string) bool { + for _, s := range list { + if s == want { + return true + } } - assertAllDenied(t, "agent-spawned-company", "http://"+opCompDom+"/", proxy5, wf5, br5) - assertAllDenied(t, "agent-spawned-company-ip", canaryURL, proxy5, wf5, br5) + return false }