Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
164 changes: 164 additions & 0 deletions db/company_scope_approval_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}
109 changes: 99 additions & 10 deletions db/tasks.go
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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 {
Expand All @@ -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
}
Expand All @@ -311,20 +323,51 @@ 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 (
SELECT company_id, position
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
}
Expand Down Expand Up @@ -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 {
Expand Down
Loading