Compare commits

..
Author SHA1 Message Date
BaaRai e666a0ac95 Merge pull request #775 from thecorporatetractor/fix/task-scope-approved-flag
fix(db): return approved_by_operator and expanded in the task scope list
2026-12-01 21:21:37 +01:00
BaaRai 51045c0622 Merge pull request #779 from BaaRai/sec/company-scope-operator-approval
security: promote company scope egress only when approved by the operator
2026-12-01 21:06:53 +01:00
Marco Azarmaneche f9b534cfde fix(db): return approved_by_operator and expanded in the task scope list
ListTaskScopeWithSources, used by GET /api/tasks/{id}/scope, did not
select approved_by_operator or expanded, so every row was reported as
not approved and not expanded. Select both columns, as ListTaskScope
already does, and add a test that covers the task's own rows and a
source task's rows.
2026-12-01 22:01:09 +02:00
BaaRai ed70ea3220 security: promote company scope egress only when approved by the operator
An operator company approval froze the company's whole inventory into
task_scope_egress: every company_scope domain and IP/CIDR row plus the
root_domain, domain and ip of every asset attributed to the company. The
agent writes both (insert_assets, add_company_scope), so the next operator
selection or re-approval promoted worker-chosen hosts into the sandbox
egress allowlist for the life of the task.

The snapshot now reads only company_scope domain and IP/CIDR rules with
approved_by_operator = TRUE; the asset branches are gone. Migration 0025
adds the column and backfills existing rows as approved. The flag is an
explicit parameter of insertScopeRulesTx and the CompanyStore scope
writers: the operator company API passes true, add_company_scope and the
ScopeSentry sync pass false. An operator write of a rule the agent stored
first approves the existing row.

AddOperatorScope outside a transaction now commits the task_scope row and
the egress snapshot together.

Existing task_scope_egress rows are not purged.
2026-12-01 20:44:37 +01:00
BaaRai 8ad85ed3ac Merge pull request #769 from BaaRai/sec/ca-key-lockdown-fd
security: lock down the CA key through an fd-based root (fix symlink/hardlink TOCTOU)
2026-12-01 20:09:38 +01:00
BaaRai 0f2211242a Merge pull request #666 from BaaRai/dependabot/docker/golang-ea47ee4
deps(docker): bump golang from `dc40a13` to `ea47ee4`
2026-12-01 17:55:12 +01:00
dependabot[bot] a75ff74aac deps(docker): bump golang from dc40a13 to ea47ee4
Bumps golang from `dc40a13` to `ea47ee4`.

---
updated-dependencies:
- dependency-name: golang
  dependency-version: 1.26.11-bookworm
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-11-30 20:38:34 +00:00
31 changed files with 622 additions and 111 deletions
+5
View File
@@ -4,8 +4,13 @@ All notable changes to this project are documented in this file. The format is b
## [Unreleased]
### Security
- **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.
### Fixed
- **`GET /api/tasks/{id}/scope` reports scope approval**: the query behind it did not select `approved_by_operator` or `expanded`, so every row came back with `approved_by_operator: false` and `expanded: false`, including operator-approved rows that grant sandbox egress. The rows now carry both columns as stored, for the task's own scope and for its source tasks' scope.
- **`start.sh` stops during a crash backoff**: a SIGTERM or SIGINT that arrived while the supervisor slept before a restart was handled only after the sleep, and the loop then started `artex` again and waited on it, so `docker stop` waited out its grace period and SIGKILLed a freshly started server. The backoff sleep can now be interrupted, and the loop checks for a pending stop before each launch. `scripts/test-start-sh.sh` covers it in CI.
## [0.7.1] - 2026-12-01
+1 -1
View File
@@ -26,7 +26,7 @@ RUN npm run build:static
# GOTOOLCHAIN=local, so a floating 1.26 tag that lags go.mod fails the build;
# bump this together with the go line in go.mod. The binary is CGO-free, so this
# stage runs on the build platform and cross-compiles to $TARGETARCH without QEMU.
FROM --platform=$BUILDPLATFORM golang:1.26.11-bookworm@sha256:dc40a13b61304647ed7e5d581d246b86413dfc29d63c6d018310feb93cd98fc0 AS build
FROM --platform=$BUILDPLATFORM golang:1.26.11-bookworm@sha256:ea47ee45f1284d60f9cc09cb2c3bb4f508c256b640bd8bb30342ff13d1adcb52 AS build
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
+1 -1
View File
@@ -1,5 +1,5 @@
# ARTEX per-task egress allowlist proxy (HTTP/CONNECT :3128 + SOCKS5 :1080, CONTRACT.md §5).
FROM --platform=$BUILDPLATFORM golang:1.26.11-bookworm@sha256:dc40a13b61304647ed7e5d581d246b86413dfc29d63c6d018310feb93cd98fc0 AS build
FROM --platform=$BUILDPLATFORM golang:1.26.11-bookworm@sha256:ea47ee45f1284d60f9cc09cb2c3bb4f508c256b640bd8bb30342ff13d1adcb52 AS build
WORKDIR /src
COPY go.mod go.sum ./
COPY sandbox/ ./sandbox/
+1 -1
View File
@@ -1,6 +1,6 @@
# ARTEX sandbox runner service (CONTRACT.md §2).
# The ONLY component that mounts /var/run/docker.sock.
FROM --platform=$BUILDPLATFORM golang:1.26.11-bookworm@sha256:dc40a13b61304647ed7e5d581d246b86413dfc29d63c6d018310feb93cd98fc0 AS build
FROM --platform=$BUILDPLATFORM golang:1.26.11-bookworm@sha256:ea47ee45f1284d60f9cc09cb2c3bb4f508c256b640bd8bb30342ff13d1adcb52 AS build
WORKDIR /src
COPY go.mod go.sum ./
COPY sandbox/ ./sandbox/
+1 -1
View File
@@ -2,7 +2,7 @@
# Runs as uid/gid 10001, read-only rootfs, cap_drop ALL, no-new-privileges,
# mounted ONLY with /app/data/tasks/<id>:/workspace:rw and connected ONLY to
# the per-task internal network artex-task-<id>.
FROM --platform=$BUILDPLATFORM golang:1.26.11-bookworm@sha256:dc40a13b61304647ed7e5d581d246b86413dfc29d63c6d018310feb93cd98fc0 AS wrap-build
FROM --platform=$BUILDPLATFORM golang:1.26.11-bookworm@sha256:ea47ee45f1284d60f9cc09cb2c3bb4f508c256b640bd8bb30342ff13d1adcb52 AS wrap-build
WORKDIR /src
COPY go.mod go.sum ./
COPY cmd/artex-exec-wrap/ ./cmd/artex-exec-wrap/
+1 -1
View File
@@ -48,7 +48,7 @@ func TestGraphOverviewIncludesAssociatedCompanyAssets(t *testing.T) {
{Kind: "icp", Value: icp},
{Kind: "keyword", Value: keyword},
}
added, skipped, invalid, scopeErrors := companies.AddScopeInputs(companyID, inputs, "task context test")
added, skipped, invalid, scopeErrors := companies.AddScopeInputs(companyID, inputs, "task context test", true)
if added != len(inputs) || skipped != 0 || invalid != 0 || len(scopeErrors) != 0 {
t.Fatalf("add company scope: added=%d skipped=%d invalid=%d errors=%v", added, skipped, invalid, scopeErrors)
}
+3 -1
View File
@@ -475,7 +475,9 @@ func (t *ToolSet) addCompanyScope() actool.CoreTool {
return actool.Errorf("failed to create/get company: " + err.Error()), nil
}
lines := splitLines(a.Scope)
added, skipped, invalid, errMsgs := t.cs.AddScope(companyID, lines, a.Reason)
// Agent-written rules attribute assets but are never copied into a
// task's sandbox egress by an operator company approval.
added, skipped, invalid, errMsgs := t.cs.AddScope(companyID, lines, a.Reason, false)
out := map[string]any{
"company_id": companyID,
"added": added,
+3 -3
View File
@@ -697,7 +697,7 @@ func TestQueryByCompany(t *testing.T) {
}
defer cleanupCompany(d, companyID)
cs.AddScope(companyID, []string{"qbc-test.io"}, "test")
cs.AddScope(companyID, []string{"qbc-test.io"}, "test", true)
id, err := av2.UpsertRootDomain(UpsertRootDomainReq{Domain: "qbc-test.io"})
if err != nil {
@@ -752,7 +752,7 @@ func TestQueryByCompanyPaging(t *testing.T) {
}
defer cleanupCompany(d, companyID)
if added, _, _, errs := cs.AddScope(companyID, []string{"qbc-paging.io"}, "test"); added != 1 {
if added, _, _, errs := cs.AddScope(companyID, []string{"qbc-paging.io"}, "test", true); added != 1 {
t.Fatalf("AddScope: added=%d, errors=%v", added, errs)
}
@@ -828,7 +828,7 @@ func TestCompanyAttributionAtInsertTime(t *testing.T) {
}
defer cleanupCompany(d, companyID)
cs.AddScope(companyID, []string{"insertattr.com"}, "test")
cs.AddScope(companyID, []string{"insertattr.com"}, "test", true)
// Now insert a root domain — should be auto-attributed
assetID, err := av2.UpsertRootDomain(UpsertRootDomainReq{Domain: "insertattr.com"})
+45 -32
View File
@@ -120,7 +120,8 @@ RETURNING id, (xmax = 0)`, name, nkey, logoVal).Scan(&id, &created)
// The company, its valid initial scope rules, and derived asset attribution are
// committed atomically. Invalid inputs retain the legacy partial-validation
// contract and are reported without preventing valid rules from being stored.
func (s *CompanyStore) CreateCompanyWithScope(name, logo string, inputs []ScopeInput, reason string) (
// approved records whether an operator entered the rules (see insertScopeRulesTx).
func (s *CompanyStore) CreateCompanyWithScope(name, logo string, inputs []ScopeInput, reason string, approved bool) (
id int64, added, skipped, invalid int, validationErrors []string, err error,
) {
if err := ValidateCompanyScopeInputBounds(inputs); err != nil {
@@ -155,7 +156,7 @@ RETURNING id`, name, nkey, logoVal).Scan(&id); err != nil {
return 0, 0, 0, invalid, validationErrors, err
}
added, skipped, needsAttribution, err := insertScopeRulesTx(tx, id, rules, reason)
added, skipped, needsAttribution, err := insertScopeRulesTx(tx, id, rules, reason, approved)
if err != nil {
return 0, 0, 0, invalid, validationErrors, err
}
@@ -320,18 +321,18 @@ ORDER BY id`, companyID)
// AddScope parses and inserts scope lines for a company, then reattributes assets.
// Returns counts of added, skipped, and invalid lines.
func (s *CompanyStore) AddScope(companyID int64, lines []string, reason string) (added, skipped, invalid int, errors []string) {
func (s *CompanyStore) AddScope(companyID int64, lines []string, reason string, approved bool) (added, skipped, invalid int, errors []string) {
inputs := make([]ScopeInput, 0, len(lines))
for _, line := range lines {
inputs = append(inputs, ScopeInput{Value: line})
}
return s.AddScopeInputs(companyID, inputs, reason)
return s.AddScopeInputs(companyID, inputs, reason, approved)
}
// AddScopeInputs inserts structured scope rules. Empty kinds use the automatic
// CIDR/IP/ICP/domain/keyword classification used by AddScope.
func (s *CompanyStore) AddScopeInputs(companyID int64, inputs []ScopeInput, reason string) (added, skipped, invalid int, errors []string) {
added, skipped, invalid, validationErrors, err := s.AddScopeInputsChecked(companyID, inputs, reason)
func (s *CompanyStore) AddScopeInputs(companyID int64, inputs []ScopeInput, reason string, approved bool) (added, skipped, invalid int, errors []string) {
added, skipped, invalid, validationErrors, err := s.AddScopeInputsChecked(companyID, inputs, reason, approved)
if err != nil {
validationErrors = append(validationErrors, err.Error())
}
@@ -339,8 +340,9 @@ func (s *CompanyStore) AddScopeInputs(companyID int64, inputs []ScopeInput, reas
}
// AddScopeInputsChecked inserts structured scope rules while keeping input
// validation separate from storage and transaction errors.
func (s *CompanyStore) AddScopeInputsChecked(companyID int64, inputs []ScopeInput, reason string) (
// validation separate from storage and transaction errors. approved records
// whether an operator entered the rules (see insertScopeRulesTx).
func (s *CompanyStore) AddScopeInputsChecked(companyID int64, inputs []ScopeInput, reason string, approved bool) (
added, skipped, invalid int, validationErrors []string, err error,
) {
if err := ValidateCompanyScopeInputBounds(inputs); err != nil {
@@ -367,7 +369,7 @@ func (s *CompanyStore) AddScopeInputsChecked(companyID int64, inputs []ScopeInpu
}
return 0, 0, invalid, errors, nil
}
added, skipped, needsAttribution, err := insertScopeRulesTx(tx, companyID, rules, reason)
added, skipped, needsAttribution, err := insertScopeRulesTx(tx, companyID, rules, reason, approved)
if err != nil {
return 0, 0, invalid, errors, err
}
@@ -430,11 +432,15 @@ func lockCompanyScopeMutation(tx *sql.Tx) error {
return err
}
func insertScopeRulesTx(tx *sql.Tx, companyID int64, rules []ParsedScope, reason string) (
// insertScopeRulesTx stores rules with approved_by_operator=approved. Pass true
// only from an operator path: approved domain and IP/CIDR rules are what a later
// operator company approval copies into task_scope_egress. Agent and sync writes
// pass false, so they keep attributing assets but never widen sandbox egress.
func insertScopeRulesTx(tx *sql.Tx, companyID int64, rules []ParsedScope, reason string, approved bool) (
added, skipped int, needsAttribution bool, err error,
) {
for _, rule := range rules {
inserted, insertErr := insertScopeRuleTx(tx, companyID, rule, reason)
inserted, insertErr := insertScopeRuleTx(tx, companyID, rule, reason, approved)
if insertErr != nil {
return 0, 0, false, insertErr
}
@@ -449,28 +455,34 @@ func insertScopeRulesTx(tx *sql.Tx, companyID int64, rules []ParsedScope, reason
}
// insertScopeRuleTx inserts a scope rule. inserted=false means a duplicate was
// ignored by ON CONFLICT, not an error.
func insertScopeRuleTx(tx *sql.Tx, companyID int64, rule ParsedScope, reason string) (inserted bool, err error) {
// ignored by ON CONFLICT, not an error. An operator write of a rule an agent
// already stored approves the existing row and counts as inserted; an agent
// write never clears an operator approval.
func insertScopeRuleTx(tx *sql.Tx, companyID int64, rule ParsedScope, reason string, approved bool) (inserted bool, err error) {
onConflict := "DO NOTHING"
if approved {
onConflict = "DO UPDATE SET approved_by_operator = TRUE WHERE NOT company_scope.approved_by_operator"
}
var res interface{ RowsAffected() (int64, error) }
switch rule.Kind {
case "domain":
res, err = tx.Exec(`
INSERT INTO company_scope(company_id, kind, domain, raw, reason)
VALUES ($1, 'domain', $2, $3, $4)
ON CONFLICT ON CONSTRAINT uq_sv2_domain DO NOTHING`,
companyID, rule.Domain, rule.Raw, reason)
INSERT INTO company_scope(company_id, kind, domain, raw, reason, approved_by_operator)
VALUES ($1, 'domain', $2, $3, $4, $5)
ON CONFLICT ON CONSTRAINT uq_sv2_domain `+onConflict,
companyID, rule.Domain, rule.Raw, reason, approved)
case "ip", "cidr":
res, err = tx.Exec(`
INSERT INTO company_scope(company_id, kind, net, raw, reason)
VALUES ($1, $2, $3::cidr, $4, $5)
ON CONFLICT ON CONSTRAINT uq_sv2_net DO NOTHING`,
companyID, rule.Kind, rule.Net, rule.Raw, reason)
INSERT INTO company_scope(company_id, kind, net, raw, reason, approved_by_operator)
VALUES ($1, $2, $3::cidr, $4, $5, $6)
ON CONFLICT ON CONSTRAINT uq_sv2_net `+onConflict,
companyID, rule.Kind, rule.Net, rule.Raw, reason, approved)
case "icp", "keyword":
res, err = tx.Exec(`
INSERT INTO company_scope(company_id, kind, value, raw, reason)
VALUES ($1, $2, $3, $4, $5)
ON CONFLICT (company_id, kind, value) WHERE kind IN ('icp','keyword') DO NOTHING`,
companyID, rule.Kind, rule.Value, rule.Raw, reason)
INSERT INTO company_scope(company_id, kind, value, raw, reason, approved_by_operator)
VALUES ($1, $2, $3, $4, $5, $6)
ON CONFLICT (company_id, kind, value) WHERE kind IN ('icp','keyword') `+onConflict,
companyID, rule.Kind, rule.Value, rule.Raw, reason, approved)
default:
return false, fmt.Errorf("unsupported company scope kind %q", rule.Kind)
}
@@ -650,17 +662,17 @@ func malformedIPAssetWarningText(total int, samples []string) string {
}
// UpdateScope replaces all scope rules for a company and reattributes.
func (s *CompanyStore) UpdateScope(companyID int64, lines []string, reason string) (added, invalid int, errs []string) {
func (s *CompanyStore) UpdateScope(companyID int64, lines []string, reason string, approved bool) (added, invalid int, errs []string) {
inputs := make([]ScopeInput, 0, len(lines))
for _, line := range lines {
inputs = append(inputs, ScopeInput{Value: line})
}
return s.UpdateScopeInputs(companyID, inputs, reason)
return s.UpdateScopeInputs(companyID, inputs, reason, approved)
}
// UpdateScopeInputs replaces all rules with a structured set.
func (s *CompanyStore) UpdateScopeInputs(companyID int64, inputs []ScopeInput, reason string) (added, invalid int, errs []string) {
added, invalid, validationErrors, err := s.UpdateScopeInputsChecked(companyID, inputs, reason)
func (s *CompanyStore) UpdateScopeInputs(companyID int64, inputs []ScopeInput, reason string, approved bool) (added, invalid int, errs []string) {
added, invalid, validationErrors, err := s.UpdateScopeInputsChecked(companyID, inputs, reason, approved)
if err != nil {
validationErrors = append(validationErrors, err.Error())
}
@@ -668,8 +680,9 @@ func (s *CompanyStore) UpdateScopeInputs(companyID int64, inputs []ScopeInput, r
}
// UpdateScopeInputsChecked replaces all rules while separating validation
// feedback from storage and transaction failures.
func (s *CompanyStore) UpdateScopeInputsChecked(companyID int64, inputs []ScopeInput, reason string) (
// feedback from storage and transaction failures. approved records whether an
// operator entered the rules (see insertScopeRulesTx).
func (s *CompanyStore) UpdateScopeInputsChecked(companyID int64, inputs []ScopeInput, reason string, approved bool) (
added, invalid int, validationErrors []string, err error,
) {
if err := ValidateCompanyScopeInputBounds(inputs); err != nil {
@@ -698,7 +711,7 @@ func (s *CompanyStore) UpdateScopeInputsChecked(companyID int64, inputs []ScopeI
if _, err := tx.Exec(`DELETE FROM company_scope WHERE company_id = $1`, companyID); err != nil {
return 0, invalid, errs, err
}
added, _, _, err = insertScopeRulesTx(tx, companyID, rules, reason)
added, _, _, err = insertScopeRulesTx(tx, companyID, rules, reason, approved)
if err != nil {
return 0, invalid, errs, err
}
+14 -13
View File
@@ -73,7 +73,7 @@ func TestCreateCompanyWithScopeRejectsNormalizedDuplicate(t *testing.T) {
name := fmt.Sprintf("Strict Company %d", stamp)
id, added, _, _, validationErrors, err := cs.CreateCompanyWithScope(name, "", []ScopeInput{
{Kind: "domain", Value: fmt.Sprintf("strict-%d.example", stamp)},
}, "test")
}, "test", true)
if err != nil {
t.Fatal(err)
}
@@ -87,6 +87,7 @@ func TestCreateCompanyWithScopeRejectsNormalizedDuplicate(t *testing.T) {
"",
[]ScopeInput{{Kind: "domain", Value: fmt.Sprintf("replacement-%d.example", stamp)}},
"test",
true,
)
if !errors.Is(err, ErrCompanyNameConflict) {
t.Fatalf("duplicate create error=%v want ErrCompanyNameConflict", err)
@@ -111,7 +112,7 @@ func TestCreateCompanyWithScopeRollsBackOnScopeWriteFailure(t *testing.T) {
name := fmt.Sprintf("Atomic Create %d", time.Now().UnixNano())
_, _, _, _, _, err = cs.CreateCompanyWithScope(name, "", []ScopeInput{
{Kind: "keyword", Value: "invalid\x00postgres-text"},
}, "test")
}, "test", true)
if err == nil {
t.Fatal("expected scope database write to fail")
}
@@ -140,7 +141,7 @@ func TestCompanyScope(t *testing.T) {
defer cleanupCompany(d, id)
lines := []string{"example.com", "192.168.1.0/24", "10.0.0.1"}
added, skipped, invalid, errs := cs.AddScope(id, lines, "test")
added, skipped, invalid, errs := cs.AddScope(id, lines, "test", true)
if added != 3 {
t.Errorf("want 3 added, got %d (errs: %v)", added, errs)
}
@@ -149,7 +150,7 @@ func TestCompanyScope(t *testing.T) {
}
// Adding again should skip (duplicate)
added2, skipped2, invalid2, _ := cs.AddScope(id, lines, "test")
added2, skipped2, invalid2, _ := cs.AddScope(id, lines, "test", true)
if added2 != 0 || skipped2 != 3 {
t.Errorf("want 0 added 3 skipped, got %d added %d skipped %d invalid", added2, skipped2, invalid2)
}
@@ -183,7 +184,7 @@ func TestCompanyScopeInvalid(t *testing.T) {
{Kind: "domain", Value: "com"},
{Kind: "cidr", Value: "1.2.3.4/8"},
}
added, _, invalid, _ := cs.AddScopeInputs(id, inputs, "test")
added, _, invalid, _ := cs.AddScopeInputs(id, inputs, "test", true)
if added != 0 {
t.Errorf("want 0 added for invalid lines, got %d", added)
}
@@ -206,7 +207,7 @@ func TestResolveCompany(t *testing.T) {
}
defer cleanupCompany(d, id)
cs.AddScope(id, []string{"resolve-test.io", "10.20.0.0/16"}, "test")
cs.AddScope(id, []string{"resolve-test.io", "10.20.0.0/16"}, "test", true)
// domain match
cid, err := cs.ResolveCompany("resolve-test.io", "")
@@ -247,10 +248,10 @@ func TestUpdateScope(t *testing.T) {
}
defer cleanupCompany(d, id)
cs.AddScope(id, []string{"old-domain.com"}, "initial")
cs.AddScope(id, []string{"old-domain.com"}, "initial", true)
// UpdateScope replaces
added, invalid, errs := cs.UpdateScope(id, []string{"new-domain.com"}, "replacement")
added, invalid, errs := cs.UpdateScope(id, []string{"new-domain.com"}, "replacement", true)
if added != 1 || invalid != 0 || len(errs) != 0 {
t.Errorf("UpdateScope: added=%d invalid=%d errs=%v", added, invalid, errs)
}
@@ -264,7 +265,7 @@ func TestUpdateScope(t *testing.T) {
// a destructive replacement of the existing rules.
added, invalid, validationErrors, err := cs.UpdateScopeInputsChecked(id, []ScopeInput{
{Kind: "domain", Value: "co.uk"},
}, "invalid replacement")
}, "invalid replacement", true)
var validationErr *CompanyScopeValidationError
if added != 0 || invalid != 1 || len(validationErrors) != 1 || !errors.As(err, &validationErr) {
t.Fatalf("invalid replacement: added=%d invalid=%d validation=%v err=%v", added, invalid, validationErrors, err)
@@ -293,14 +294,14 @@ func TestUpdateScopeRollsBackOnInsertFailure(t *testing.T) {
}
defer cleanupCompany(d, id)
oldDomain := fmt.Sprintf("old-%d.example", time.Now().UnixNano())
added, _, invalid, addErrors := cs.AddScopeInputs(id, []ScopeInput{{Kind: "domain", Value: oldDomain}}, "initial")
added, _, invalid, addErrors := cs.AddScopeInputs(id, []ScopeInput{{Kind: "domain", Value: oldDomain}}, "initial", true)
if added != 1 || invalid != 0 || len(addErrors) != 0 {
t.Fatalf("seed scope: added=%d invalid=%d errors=%v", added, invalid, addErrors)
}
added, invalid, updateErrors := cs.UpdateScopeInputs(id, []ScopeInput{
{Kind: "keyword", Value: "invalid\x00postgres-text"},
}, "replacement")
}, "replacement", true)
if added != 0 || invalid != 0 || len(updateErrors) == 0 {
t.Fatalf("failed update result: added=%d invalid=%d errors=%v", added, invalid, updateErrors)
}
@@ -325,7 +326,7 @@ func TestDeleteCompany(t *testing.T) {
if err != nil {
t.Fatal(err)
}
cs.AddScope(id, []string{"deletetest.com"}, "test")
cs.AddScope(id, []string{"deletetest.com"}, "test", true)
if err := cs.DeleteCompany(id); err != nil {
t.Fatal(err)
@@ -419,7 +420,7 @@ func TestRecomputeAttribution(t *testing.T) {
}
// add scope and recompute
cs.AddScope(id, []string{"attr-test.com"}, "test")
cs.AddScope(id, []string{"attr-test.com"}, "test", true)
if err := cs.RecomputeAttribution(); err != nil {
t.Fatal(err)
}
+65
View File
@@ -0,0 +1,65 @@
package db
import "testing"
// TestCompanyScopeApprovalBackfillMigration0025 runs migration 0025 against a
// company_scope table without approved_by_operator (the pre-0025 schema): every
// existing row must end up approved, so upgraded installations keep their
// current company egress, while a row written afterwards defaults to false.
func TestCompanyScopeApprovalBackfillMigration0025(t *testing.T) {
dsn := scratchDSN(t, "cs_approval_0025")
d, err := Open(dsn)
if err != nil {
t.Fatalf("initial Open: %v", err)
}
var companyID int64
if err := d.QueryRow(`INSERT INTO companies(name, nkey) VALUES ('Mig25 Corp', 'mig25 corp') RETURNING id`).Scan(&companyID); err != nil {
t.Fatalf("insert company: %v", err)
}
stmts := []string{
`ALTER TABLE company_scope DROP COLUMN IF EXISTS approved_by_operator`,
`INSERT INTO company_scope(company_id, kind, domain, raw) VALUES ($1, 'domain', 'mig25.test', 'mig25.test')`,
`INSERT INTO company_scope(company_id, kind, net, raw) VALUES ($1, 'ip', '192.0.2.25/32', '192.0.2.25')`,
`INSERT INTO company_scope(company_id, kind, net, raw) VALUES ($1, 'cidr', '198.51.100.0/24', '198.51.100.0/24')`,
`INSERT INTO company_scope(company_id, kind, value, raw) VALUES ($1, 'icp', 'icp25', 'ICP 25')`,
`INSERT INTO company_scope(company_id, kind, value, raw) VALUES ($1, 'keyword', 'mig25', 'Mig25')`,
`DELETE FROM schema_migrations WHERE version >= 25`,
}
for _, st := range stmts {
var args []any
if st[:6] == "INSERT" {
args = []any{companyID}
}
if _, err := d.Exec(st, args...); err != nil {
t.Fatalf("seed pre-0025 state (%s): %v", st, err)
}
}
d.Close()
d2, err := Open(dsn)
if err != nil {
t.Fatalf("re-Open with migration 0025: %v", err)
}
defer d2.Close()
var approved, total int
if err := d2.QueryRow(`
SELECT count(*) FILTER (WHERE approved_by_operator), count(*)
FROM company_scope WHERE company_id = $1`, companyID).Scan(&approved, &total); err != nil {
t.Fatalf("read approved_by_operator after migration: %v", err)
}
if total != 5 || approved != 5 {
t.Fatalf("backfill: approved=%d total=%d, want 5/5", approved, total)
}
var fresh bool
if err := d2.QueryRow(`
INSERT INTO company_scope(company_id, kind, domain, raw) VALUES ($1, 'domain', 'after25.test', 'after25.test')
RETURNING approved_by_operator`, companyID).Scan(&fresh); err != nil {
t.Fatalf("insert after migration: %v", err)
}
if fresh {
t.Fatal("a row written after the migration defaulted to approved_by_operator=true")
}
}
+8 -8
View File
@@ -29,7 +29,7 @@ func TestAssetUpsertWaitsForCompanyScopeMutation(t *testing.T) {
})
if added, _, invalid, validationErrors, err := companies.AddScopeInputsChecked(oldCompany, []ScopeInput{
{Kind: "domain", Value: domain},
}, "test"); err != nil || added != 1 || invalid != 0 || len(validationErrors) != 0 {
}, "test", true); err != nil || added != 1 || invalid != 0 || len(validationErrors) != 0 {
t.Fatalf("seed old scope: added=%d invalid=%d validation=%v err=%v", added, invalid, validationErrors, err)
}
@@ -46,7 +46,7 @@ func TestAssetUpsertWaitsForCompanyScopeMutation(t *testing.T) {
}
if _, err := insertScopeRuleTx(mutation, newCompany, ParsedScope{
Kind: "domain", Domain: domain, Raw: domain,
}, "test"); err != nil {
}, "test", true); err != nil {
t.Fatal(err)
}
@@ -121,7 +121,7 @@ func TestResolveAndRecomputeUseStableCompanyIDTieBreak(t *testing.T) {
{Kind: "icp", Value: icp},
}
for _, companyID := range []int64{second, first} {
if added, _, invalid, validationErrors, err := companies.AddScopeInputsChecked(companyID, rules, "test"); err != nil || added != len(rules) || invalid != 0 || len(validationErrors) != 0 {
if added, _, invalid, validationErrors, err := companies.AddScopeInputsChecked(companyID, rules, "test", true); err != nil || added != len(rules) || invalid != 0 || len(validationErrors) != 0 {
t.Fatalf("add company %d rules: added=%d invalid=%d validation=%v err=%v", companyID, added, invalid, validationErrors, err)
}
}
@@ -202,12 +202,12 @@ func TestCompanyScopeLimitsAndCheckedErrors(t *testing.T) {
for i := range rules {
rules[i] = ScopeInput{Kind: "keyword", Value: fmt.Sprintf("limit-%d-%d", stamp, i)}
}
if added, _, _, _, err := companies.AddScopeInputsChecked(companyID, rules, "test"); err != nil || added != bulk {
if added, _, _, _, err := companies.AddScopeInputsChecked(companyID, rules, "test", true); err != nil || added != bulk {
t.Fatalf("bulk scope insert: added=%d want=%d err=%v", added, bulk, err)
}
if added, _, _, _, err := companies.AddScopeInputsChecked(companyID, []ScopeInput{
{Kind: "keyword", Value: fmt.Sprintf("limit-%d-extra", stamp)},
}, "test"); added != 1 || err != nil {
}, "test", true); added != 1 || err != nil {
t.Fatalf("append past the old cap: added=%d err=%v", added, err)
}
var count int
@@ -219,10 +219,10 @@ func TestCompanyScopeLimitsAndCheckedErrors(t *testing.T) {
}
missingID := companyID + 1_000_000_000
if _, _, _, _, err := companies.AddScopeInputsChecked(missingID, nil, "test"); !errors.Is(err, ErrCompanyNotFound) {
if _, _, _, _, err := companies.AddScopeInputsChecked(missingID, nil, "test", true); !errors.Is(err, ErrCompanyNotFound) {
t.Fatalf("missing add error=%v want ErrCompanyNotFound", err)
}
if _, _, _, err := companies.UpdateScopeInputsChecked(missingID, nil, "test"); !errors.Is(err, ErrCompanyNotFound) {
if _, _, _, err := companies.UpdateScopeInputsChecked(missingID, nil, "test", true); !errors.Is(err, ErrCompanyNotFound) {
t.Fatalf("missing update error=%v want ErrCompanyNotFound", err)
}
if _, err := companies.DeleteCompanyWithAssets(missingID, true); !errors.Is(err, ErrCompanyNotFound) {
@@ -239,7 +239,7 @@ func TestCompanyScopeCheckedReturnsSystemErrorSeparately(t *testing.T) {
if err := d.Close(); err != nil {
t.Fatal(err)
}
_, _, _, validationErrors, err := companies.AddScopeInputsChecked(1, nil, "test")
_, _, _, validationErrors, err := companies.AddScopeInputsChecked(1, nil, "test", true)
if err == nil {
t.Fatal("closed database did not return a system error")
}
+6 -6
View File
@@ -166,7 +166,7 @@ func TestExplicitCompanyAttributionSurvivesScopeRebuild(t *testing.T) {
{Kind: "icp", Value: icp},
{Kind: "cidr", Value: network},
}
if added, _, invalid, errs := cs.AddScopeInputs(autoCompany, rules, "test"); added != len(rules) || invalid != 0 {
if added, _, invalid, errs := cs.AddScopeInputs(autoCompany, rules, "test", true); added != len(rules) || invalid != 0 {
t.Fatalf("AddScopeInputs: added=%d invalid=%d errors=%v", added, invalid, errs)
}
@@ -188,7 +188,7 @@ func TestExplicitCompanyAttributionSurvivesScopeRebuild(t *testing.T) {
// Replacing every matching rule detaches only the automatically-owned row.
if _, invalid, errs := cs.UpdateScopeInputs(autoCompany, []ScopeInput{
{Kind: "domain", Value: fmt.Sprintf("replacement-%d.invalid", stamp)},
}, "test"); invalid != 0 || len(errs) != 0 {
}, "test", true); invalid != 0 || len(errs) != 0 {
t.Fatalf("UpdateScopeInputs: invalid=%d errors=%v", invalid, errs)
}
assertCompany(assetID, explicitCompany, "explicit")
@@ -213,7 +213,7 @@ func TestExplicitCompanyAttributionSurvivesScopeRebuild(t *testing.T) {
if _, invalid, errs := cs.UpdateScopeInputs(autoCompany, []ScopeInput{
{Kind: "domain", Value: domain},
{Kind: "icp", Value: icp},
}, "test"); invalid != 0 || len(errs) != 0 {
}, "test", true); invalid != 0 || len(errs) != 0 {
t.Fatalf("restore fallback scope: invalid=%d errors=%v", invalid, errs)
}
if err := cs.DeleteCompany(explicitCompany); err != nil {
@@ -286,7 +286,7 @@ func TestCompanyICPAttribution(t *testing.T) {
added, _, invalid, errs := cs.AddScopeInputs(companyID, []ScopeInput{
{Kind: "icp", Value: "Beijing ICP filing 998877"},
{Kind: "keyword", Value: "ICP Scope"},
}, "unit test")
}, "unit test", true)
if added != 2 || invalid != 0 || len(errs) != 0 {
t.Fatalf("add structured scope: added=%d invalid=%d errors=%v", added, invalid, errs)
}
@@ -390,7 +390,7 @@ func TestCompanyScopeAttribution(t *testing.T) {
t.Fatalf("pre-scope asset should be unattributed, got %v", *preCompanyID)
}
cs.AddScope(cid, []string{root, cidr}, "unit test")
cs.AddScope(cid, []string{root, cidr}, "unit test", true)
mustCid := func(id int64, want int64, label string) {
var cID *int64
@@ -474,7 +474,7 @@ func TestCompanyScopeWildcardAttribution(t *testing.T) {
if err != nil {
t.Fatalf("UpsertCompany: %v", err)
}
cs.AddScope(cid, []string{"*." + root}, "unit test")
cs.AddScope(cid, []string{"*." + root}, "unit test", true)
var domain string
if err := d.QueryRow(`SELECT domain FROM company_scope WHERE company_id = $1 AND kind = 'domain'`, cid).Scan(&domain); err != nil {
+66
View File
@@ -433,3 +433,69 @@ func TestTaskAssetContextUsesDirectSourceScopeAndAnchors(t *testing.T) {
t.Fatalf("anchored-only source asset missing from coverage graph: %+v", graph.Nodes)
}
}
// TestListTaskScopeWithSourcesReportsApproval guards GET /api/tasks/{id}/scope:
// the rows must carry approved_by_operator and expanded as stored, for the
// task's own scope and for a direct source task's scope.
func TestListTaskScopeWithSourcesReportsApproval(t *testing.T) {
d, err := Open(testDSN(t))
if err != nil {
SkipPGUnavailable(t, err)
}
t.Cleanup(func() { d.Close() })
source, err := d.CreateTask("approval source", "goal", nil, 0, 0)
if err != nil {
t.Fatal(err)
}
current, err := d.CreateTaskWithOptions("approval current", "goal", TaskCreateOptions{SourceTaskIDs: []int64{source.ID}})
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
cleanupErr(t, "current task", d.DeleteTask(current.ID))
cleanupErr(t, "source task", d.DeleteTask(source.ID))
})
assets := d.Assets()
approved := fmt.Sprintf("approved-%d.invalid", current.ID)
coverage := fmt.Sprintf("coverage-%d.invalid", current.ID)
sourceApproved := fmt.Sprintf("source-approved-%d.invalid", source.ID)
if _, err := assets.AddOperatorScope(current.ID, "root_domain", approved, "operator"); err != nil {
t.Fatal(err)
}
if _, err := assets.AddAgentScope(current.ID, "root_domain", coverage, "agent", "agent"); err != nil {
t.Fatal(err)
}
if _, err := assets.AddOperatorScope(source.ID, "root_domain", sourceApproved, "operator"); err != nil {
t.Fatal(err)
}
got := map[string]TaskScope{}
scopes, err := assets.ListTaskScopeWithSources(current.ID)
if err != nil {
t.Fatal(err)
}
for _, s := range scopes {
got[s.Domain] = s
}
for domain, want := range map[string]bool{approved: true, coverage: false, sourceApproved: true} {
s, ok := got[domain]
if !ok {
t.Fatalf("scope %s missing from %+v", domain, scopes)
}
if s.ApprovedByOperator != want {
t.Errorf("scope %s approved_by_operator = %v, want %v", domain, s.ApprovedByOperator, want)
}
}
// Same flags as the single-task listing for the task's own rows.
own, err := assets.ListTaskScope(current.ID)
if err != nil {
t.Fatal(err)
}
for _, s := range own {
if g := got[s.Domain]; g.ApprovedByOperator != s.ApprovedByOperator || g.Expanded != s.Expanded {
t.Errorf("scope %s: with-sources %+v, single-task %+v", s.Domain, g, s)
}
}
}
@@ -0,0 +1,18 @@
-- Operator-only approval flag on company_scope rows.
--
-- An operator company approval copies the company's inventory into
-- task_scope_egress. That inventory used to include company-attributed assets
-- and every company_scope row, both of which the agent can write
-- (insert_assets, add_company_scope), so the next operator selection or
-- re-approval promoted agent-chosen hosts into the sandbox egress allowlist.
-- The snapshot now copies only company_scope domain and IP/CIDR rows with
-- approved_by_operator=true. Operator API writes set it; add_company_scope and
-- the ScopeSentry sync leave it false.
ALTER TABLE company_scope ADD COLUMN IF NOT EXISTS approved_by_operator BOOLEAN NOT NULL DEFAULT FALSE;
-- Backfill: rows that exist before this migration keep granting egress on the
-- next approval, as they did before. Their origin is not recorded, so they are
-- all treated as operator-approved.
UPDATE company_scope
SET approved_by_operator = TRUE
WHERE approved_by_operator = FALSE;
+3
View File
@@ -122,6 +122,9 @@ CREATE TABLE IF NOT EXISTS company_scope (
value TEXT,
raw TEXT NOT NULL,
reason TEXT,
-- true only for operator-entered rules; only those reach task_scope_egress
-- (migration 0025 adds it on existing installations).
approved_by_operator BOOLEAN NOT NULL DEFAULT FALSE,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
CONSTRAINT uq_sv2_domain UNIQUE (company_id, domain),
CONSTRAINT uq_sv2_net UNIQUE (company_id, net),
+1 -1
View File
@@ -134,7 +134,7 @@ func TestTaskTargetGateDefaultsOnWhenScoped(t *testing.T) {
// Task scoped with CompanyIDs defaults ON.
compName := fmt.Sprintf("Scoped Target Gate Co %d", time.Now().UnixNano())
compID, _, _, _, _, err := d.Companies().CreateCompanyWithScope(compName, "", []ScopeInput{{Kind: "domain", Value: "co.example.test"}}, "test")
compID, _, _, _, _, err := d.Companies().CreateCompanyWithScope(compName, "", []ScopeInput{{Kind: "domain", Value: "co.example.test"}}, "test", true)
if err != nil {
t.Fatal(err)
}
+1 -1
View File
@@ -16,7 +16,7 @@ func TestTargetGateBackfillMigration0022(t *testing.T) {
if err != nil {
t.Fatalf("initial Open: %v", err)
}
coID, _, _, _, _, err := d.Companies().CreateCompanyWithScope("Backfill Target Corp", "", []ScopeInput{{Kind: "domain", Value: "backfill.example.com"}}, "test")
coID, _, _, _, _, err := d.Companies().CreateCompanyWithScope("Backfill Target Corp", "", []ScopeInput{{Kind: "domain", Value: "backfill.example.com"}}, "test", true)
if err != nil {
t.Fatalf("create company: %v", err)
}
+3 -2
View File
@@ -95,7 +95,8 @@ target AS (
func (s *AssetStore) ListTaskScopeWithSources(taskID int64) ([]TaskScope, error) {
rows, err := s.db.Query(`WITH `+directTaskContextCTE+`
SELECT ts.id, ts.task_id, ts.kind, COALESCE(ts.company_id,0), COALESCE(c.name,''), COALESCE(ts.domain,''),
COALESCE(ts.net::text,''), COALESCE(ts.value,''), ts.source, COALESCE(ts.reason,'')
COALESCE(ts.net::text,''), COALESCE(ts.value,''), ts.source, COALESCE(ts.reason,''), COALESCE(ts.expanded,false),
COALESCE(ts.approved_by_operator,false)
FROM task_scope ts
JOIN context_tasks ctx ON ctx.task_id=ts.task_id
LEFT JOIN companies c ON c.id=ts.company_id
@@ -108,7 +109,7 @@ ORDER BY CASE WHEN ts.task_id=$1 THEN 0 ELSE 1 END, ts.id`, taskID)
for rows.Next() {
var scope TaskScope
var companyID int64
if err := rows.Scan(&scope.ID, &scope.TaskID, &scope.Kind, &companyID, &scope.CompanyName, &scope.Domain, &scope.Net, &scope.Value, &scope.Source, &scope.Reason); err != nil {
if err := rows.Scan(&scope.ID, &scope.TaskID, &scope.Kind, &companyID, &scope.CompanyName, &scope.Domain, &scope.Net, &scope.Value, &scope.Source, &scope.Reason, &scope.Expanded, &scope.ApprovedByOperator); err != nil {
return nil, err
}
if companyID > 0 {
+15 -1
View File
@@ -169,8 +169,22 @@ func (s *AssetStore) AddAutoScope(taskID int64, assetType, domain, rawURL, ip st
// authenticated operator API/UI path. This is the ONLY scope-addition helper
// that sets approved_by_operator=true (in addition to TaskCreateOptions.CompanyIDs
// at task creation). AddAgentScope and AddAutoScope always leave it false.
// The task_scope row and a company grant's egress snapshot commit together.
func (s *AssetStore) AddOperatorScope(taskID int64, kind, value, reason string) (TaskScope, error) {
return s.addScopeInternal(taskID, kind, value, reason, "manual", true)
if s.tx != nil {
return s.addScopeInternal(taskID, kind, value, reason, "manual", true)
}
tx, err := s.db.Begin()
if err != nil {
return TaskScope{TaskID: taskID, Kind: kind, Source: "manual", Reason: reason, ApprovedByOperator: true}, err
}
defer tx.Rollback() //nolint:errcheck
scoped := &AssetStore{db: s.db, company: s.company, tx: tx}
ts, err := scoped.addScopeInternal(taskID, kind, value, reason, "manual", true)
if err != nil {
return ts, err
}
return ts, tx.Commit()
}
// AddAgentScope parses a (kind,value) pair and records it as coverage-only task
+1 -1
View File
@@ -14,7 +14,7 @@ func TestTaskScopeOperatorApprovalBackfillMigration0023(t *testing.T) {
if err != nil {
t.Fatalf("initial Open: %v", err)
}
coID, _, _, _, _, err := d.Companies().CreateCompanyWithScope("Mig23 Corp", "", []ScopeInput{{Kind: "domain", Value: "mig23.test"}}, "test")
coID, _, _, _, _, err := d.Companies().CreateCompanyWithScope("Mig23 Corp", "", []ScopeInput{{Kind: "domain", Value: "mig23.test"}}, "test", true)
if err != nil {
t.Fatalf("CreateCompanyWithScope: %v", err)
}
+1 -1
View File
@@ -15,7 +15,7 @@ func TestAddAgentScopeUnderDeclaredCompanyIsNotExpansion(t *testing.T) {
stamp := time.Now().UnixNano()
root := fmt.Sprintf("acme%d.com", stamp)
companyID, _, _, _, _, err := companies.CreateCompanyWithScope(fmt.Sprintf("acme-%d", stamp), "",
[]ScopeInput{{Value: root}}, "test")
[]ScopeInput{{Value: root}}, "test", true)
if err != nil {
t.Fatal(err)
}
+6 -17
View File
@@ -14,9 +14,11 @@ type ScopeEgress struct {
}
// snapshotCompanyEgressSQL freezes the domains and CIDRs a company grant covers
// right now: its company_scope rows plus the domains/IPs attributed to it. The
// right now: its operator-approved company_scope domain and IP/CIDR rules. The
// sandbox proxy reads task_scope_egress, so inventory written after this point
// (add_company_scope, new attributed assets) cannot widen an approved task.
// cannot widen an approved task. Assets and agent-written company_scope rows
// (add_company_scope, ScopeSentry sync) are never copied: a worker controls
// both, and the next operator approval would otherwise promote them.
const snapshotCompanyEgressSQL = `
INSERT INTO task_scope_egress(task_id, kind, value, company_id)
SELECT $1, e.kind, e.value, e.company_id
@@ -25,26 +27,13 @@ FROM (
FROM company_scope cs
JOIN unnest($2::bigint[]) AS ids(id) ON ids.id = cs.company_id
WHERE cs.kind = 'domain' AND COALESCE(cs.domain, '') <> ''
AND cs.approved_by_operator = TRUE
UNION ALL
SELECT 'cidr', cs.net::text, cs.company_id
FROM company_scope cs
JOIN unnest($2::bigint[]) AS ids(id) ON ids.id = cs.company_id
WHERE cs.kind IN ('ip', 'cidr') AND cs.net IS NOT NULL
UNION ALL
SELECT 'domain', lower(trim(a.root_domain)), a.company_id
FROM assets a
JOIN unnest($2::bigint[]) AS ids(id) ON ids.id = a.company_id
WHERE COALESCE(a.root_domain, '') <> ''
UNION ALL
SELECT 'domain', lower(trim(a.domain)), a.company_id
FROM assets a
JOIN unnest($2::bigint[]) AS ids(id) ON ids.id = a.company_id
WHERE COALESCE(a.domain, '') <> ''
UNION ALL
SELECT 'cidr', trim(a.ip), a.company_id
FROM assets a
JOIN unnest($2::bigint[]) AS ids(id) ON ids.id = a.company_id
WHERE COALESCE(a.ip, '') <> ''
AND cs.approved_by_operator = TRUE
) e
WHERE e.value <> ''
ON CONFLICT DO NOTHING`
+5 -3
View File
@@ -142,7 +142,8 @@ func (s *Server) createCompany(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusBadRequest, err.Error())
return
}
id, added, skipped, invalid, scopeErrs, err := cs.CreateCompanyWithScope(req.Name, req.Logo, req.Scope, "api")
// Operator API: the rules are an operator decision and may grant egress.
id, added, skipped, invalid, scopeErrs, err := cs.CreateCompanyWithScope(req.Name, req.Logo, req.Scope, "api", true)
if err != nil {
if errors.Is(err, db.ErrCompanyNameConflict) {
writeErr(w, http.StatusConflict, "Company name already exists")
@@ -231,10 +232,11 @@ func (s *Server) addCompanyScope(w http.ResponseWriter, r *http.Request) {
var added, skipped, invalid int
var errs []string
var mutationErr error
// Operator API: the rules are an operator decision and may grant egress.
if req.Reset {
added, invalid, errs, mutationErr = cs.UpdateScopeInputsChecked(id, req.Scope, req.Reason)
added, invalid, errs, mutationErr = cs.UpdateScopeInputsChecked(id, req.Scope, req.Reason, true)
} else {
added, skipped, invalid, errs, mutationErr = cs.AddScopeInputsChecked(id, req.Scope, req.Reason)
added, skipped, invalid, errs, mutationErr = cs.AddScopeInputsChecked(id, req.Scope, req.Reason, true)
}
if mutationErr != nil {
if errors.Is(mutationErr, db.ErrCompanyNotFound) {
+1 -1
View File
@@ -47,7 +47,7 @@ func TestCreateCompanyRejectsNormalizedDuplicateWithoutChangingScope(t *testing.
name := fmt.Sprintf("HTTP Strict Company %d", stamp)
companyID, _, _, _, _, err := m.pg.Companies().CreateCompanyWithScope(name, "", []db.ScopeInput{
{Kind: "domain", Value: fmt.Sprintf("existing-%d.example", stamp)},
}, "test")
}, "test", true)
if err != nil {
t.Fatal(err)
}
@@ -0,0 +1,310 @@
package server
import (
"bytes"
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strconv"
"testing"
"time"
"github.com/Autumn-27/artex/agent"
"github.com/Autumn-27/artex/db"
)
// Company egress is promoted into task_scope_egress only from company_scope
// rules an operator entered. These tests drive the real entry points: the
// operator company API handlers, the agent add_company_scope and insert_assets
// tools, and the operator company approval paths (task creation and
// AddOperatorScope).
type companyEgressFixture struct {
t *testing.T
m *Manager
s *Server
pg *db.DB
as *db.AssetStore
}
func newCompanyEgressFixture(t *testing.T) *companyEgressFixture {
t.Helper()
m, err := NewManager(t.TempDir(), "")
if err != nil {
db.SkipPGUnavailable(t, err)
}
t.Cleanup(func() { _ = m.Close() })
return &companyEgressFixture{t: t, m: m, s: &Server{m: m}, pg: m.pg, as: m.pg.Assets()}
}
func (f *companyEgressFixture) operatorCreateCompany(name string, scope []map[string]string) int64 {
f.t.Helper()
body, _ := json.Marshal(map[string]any{"name": name, "scope": scope})
rec := httptest.NewRecorder()
f.s.createCompany(rec, httptest.NewRequest(http.MethodPost, "/api/companies", bytes.NewReader(body)))
if rec.Code != http.StatusCreated {
f.t.Fatalf("operator create company: status=%d body=%s", rec.Code, rec.Body.String())
}
var out struct {
ID int64 `json:"id"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil || out.ID <= 0 {
f.t.Fatalf("operator create company: id=%d err=%v body=%s", out.ID, err, rec.Body.String())
}
f.t.Cleanup(func() { _ = f.pg.Companies().DeleteCompany(out.ID) })
return out.ID
}
func (f *companyEgressFixture) operatorAddScope(companyID int64, scope []map[string]string) {
f.t.Helper()
body, _ := json.Marshal(map[string]any{"scope": scope, "reason": "operator"})
req := httptest.NewRequest(http.MethodPost, "/api/companies/x/scope", bytes.NewReader(body))
req.SetPathValue("id", strconv.FormatInt(companyID, 10))
rec := httptest.NewRecorder()
f.s.addCompanyScope(rec, req)
if rec.Code != http.StatusOK {
f.t.Fatalf("operator add company scope: status=%d body=%s", rec.Code, rec.Body.String())
}
}
// agentTool runs one agent tool by name, the way the planner or a worker does.
func (f *companyEgressFixture) agentTool(role, name string, taskID int64, input any) string {
f.t.Helper()
ts := agent.NewToolSet(nil, role)
ts.SetAssetStore(f.as, f.pg.Companies())
if taskID > 0 {
ts.SetTaskID(taskID)
}
tools := ts.PlannerTools()
if role == "worker" {
tools = ts.WorkerTools()
}
raw, _ := json.Marshal(input)
for _, tool := range tools {
if tool.Name() != name {
continue
}
res, err := tool.Call(context.Background(), raw, nil)
if err != nil {
f.t.Fatalf("%s: %v", name, err)
}
return res.Flatten()
}
f.t.Fatalf("%s tool not found for role %s", name, role)
return ""
}
func (f *companyEgressFixture) operatorApproveCompany(taskID, companyID int64) {
f.t.Helper()
if ts, err := f.as.AddOperatorScope(taskID, "company", strconv.FormatInt(companyID, 10), "operator approval"); err != nil || !ts.ApprovedByOperator {
f.t.Fatalf("AddOperatorScope company: ts=%+v err=%v", ts, err)
}
}
func (f *companyEgressFixture) newTask(name string, companyIDs ...int64) int64 {
f.t.Helper()
task, err := f.pg.CreateTaskWithOptions(name, "goal", db.TaskCreateOptions{CompanyIDs: companyIDs})
if err != nil {
f.t.Fatalf("CreateTaskWithOptions: %v", err)
}
f.t.Cleanup(func() { _ = f.pg.DeleteTask(task.ID) })
return task.ID
}
// egress returns the frozen task_scope_egress values of one company grant plus
// what the sandbox run info hands the egress proxy for the task.
func (f *companyEgressFixture) egress(taskID, companyID int64) (frozen, proxy []string) {
f.t.Helper()
entries, err := f.pg.CompanyEgressForTask(taskID, companyID)
if err != nil {
f.t.Fatalf("CompanyEgressForTask: %v", err)
}
for _, e := range entries {
frozen = append(frozen, e.Value)
}
info := taskSandboxRunInfo(f.pg, f.t.TempDir(), strconv.FormatInt(taskID, 10))
proxy = append(append(proxy, info.ScopeDomains...), info.ScopeCIDRs...)
return frozen, proxy
}
func egressHasAny(list []string, values ...string) string {
for _, v := range list {
for _, want := range values {
if v == want {
return v
}
}
}
return ""
}
// (a) A rule the agent writes with add_company_scope is not promoted by the
// operator's next approval of the company.
func TestAgentCompanyScopeNotPromotedOnOperatorReapproval(t *testing.T) {
f := newCompanyEgressFixture(t)
sfx := strconv.FormatInt(time.Now().UnixNano(), 36)
name := "AgentScopeCo-" + sfx
opDom := "op-a-" + sfx + ".test"
companyID := f.operatorCreateCompany(name, []map[string]string{{"kind": "domain", "value": opDom}})
taskID := f.newTask("agent-scope-"+sfx, companyID)
agentDom := "attacker-a-" + sfx + ".test"
agentIP := "203.0.113.71"
out := f.agentTool("planner", "add_company_scope", taskID, map[string]any{
"company": name,
"scope": agentDom + "\n" + agentIP,
"reason": "whois",
})
var res struct {
Added int `json:"added"`
}
if err := json.Unmarshal([]byte(out), &res); err != nil || res.Added != 2 {
t.Fatalf("add_company_scope did not store both rules: %s", out)
}
f.operatorApproveCompany(taskID, companyID)
frozen, proxy := f.egress(taskID, companyID)
if egressHasAny(frozen, opDom) == "" || egressHasAny(proxy, opDom) == "" {
t.Fatalf("operator-approved domain missing: frozen=%v proxy=%v", frozen, proxy)
}
bad := []string{agentDom, agentIP, agentIP + "/32"}
if v := egressHasAny(frozen, bad...); v != "" {
t.Fatalf("operator re-approval promoted agent add_company_scope rule %q into task_scope_egress: %v", v, frozen)
}
if v := egressHasAny(proxy, bad...); v != "" {
t.Fatalf("agent add_company_scope rule %q reached the sandbox egress allowlist: %v", v, proxy)
}
}
// (b) Rules the operator enters through the company API are promoted, including
// a rule the agent stored first and the operator then entered again.
func TestOperatorCompanyScopePromotedOnApproval(t *testing.T) {
f := newCompanyEgressFixture(t)
sfx := strconv.FormatInt(time.Now().UnixNano(), 36)
name := "OperatorScopeCo-" + sfx
createDom := "op-b-" + sfx + ".test"
companyID := f.operatorCreateCompany(name, []map[string]string{{"kind": "domain", "value": createDom}})
sharedDom := "shared-b-" + sfx + ".test"
f.agentTool("planner", "add_company_scope", 0, map[string]any{
"company": name, "scope": sharedDom, "reason": "agent first",
})
addDom := "op-b2-" + sfx + ".test"
addCIDR := "198.51.100.64/26"
f.operatorAddScope(companyID, []map[string]string{
{"kind": "domain", "value": addDom},
{"kind": "cidr", "value": addCIDR},
{"kind": "domain", "value": sharedDom},
})
taskID := f.newTask("operator-scope-"+sfx, companyID)
frozen, proxy := f.egress(taskID, companyID)
for _, want := range []string{createDom, addDom, addCIDR, sharedDom} {
if egressHasAny(frozen, want) == "" || egressHasAny(proxy, want) == "" {
t.Fatalf("operator rule %q not promoted: frozen=%v proxy=%v", want, frozen, proxy)
}
}
}
// (c) Hosts a worker registers with insert_assets, attributed to the company by
// its approved domain or ICP rule, are not promoted by the operator selecting
// or re-approving the company.
func TestInsertAssetsHostsNotPromotedOnOperatorSelection(t *testing.T) {
f := newCompanyEgressFixture(t)
sfx := strconv.FormatInt(time.Now().UnixNano(), 36)
opRoot := "corp-c-" + sfx + ".test"
icp := "ICP filing " + sfx
companyID := f.operatorCreateCompany("AssetsCo-"+sfx, []map[string]string{
{"kind": "domain", "value": opRoot},
{"kind": "icp", "value": icp},
})
attackerIPv4 := "203.0.113.66"
attackerIPv6 := "2001:db8:66::66"
attackerRoot := "evil-c-" + sfx + ".test"
attackerSubRoot := "evil2-c-" + sfx + ".test"
attackerSub := "www." + attackerSubRoot
t.Cleanup(func() {
_, _ = f.pg.Exec(`DELETE FROM assets WHERE ip IN ($1,$2) OR root_domain IN ($3,$4,$5)`,
attackerIPv4, attackerIPv6, opRoot, attackerRoot, attackerSubRoot)
})
workerTask := f.newTask("worker-" + sfx)
out := f.agentTool("worker", "insert_assets", workerTask, map[string]any{"assets": []any{
map[string]any{"type": "subdomain", "domain": "a." + opRoot, "record_type": "A", "record_value": []string{attackerIPv4}},
map[string]any{"type": "subdomain", "domain": "b." + opRoot, "record_type": "AAAA", "record_value": []string{attackerIPv6}},
map[string]any{"type": "root_domain", "domain": attackerRoot, "icp": icp},
map[string]any{"type": "subdomain", "domain": attackerSub, "icp": icp},
}})
var res struct {
Results []any `json:"results"`
Errors []any `json:"errors"`
}
if err := json.Unmarshal([]byte(out), &res); err != nil || len(res.Errors) != 0 || len(res.Results) != 4 {
t.Fatalf("insert_assets: err=%v out=%s", err, out)
}
// The attack precondition: every attacker host is attributed to the company.
var attributed int
if err := f.pg.QueryRow(`
SELECT count(*) FROM assets
WHERE company_id=$1 AND (ip IN ($2,$3) OR domain IN ($4,$5))`,
companyID, attackerIPv4, attackerIPv6, attackerRoot, attackerSub).Scan(&attributed); err != nil || attributed < 4 {
t.Fatalf("attacker assets not attributed to the company (precondition): n=%d err=%v", attributed, err)
}
bad := []string{
attackerIPv4, attackerIPv4 + "/32",
attackerIPv6, attackerIPv6 + "/128",
attackerRoot, attackerSub, attackerSubRoot,
}
check := func(label string, taskID int64) {
t.Helper()
frozen, proxy := f.egress(taskID, companyID)
if egressHasAny(frozen, opRoot) == "" {
t.Fatalf("%s: operator-approved domain missing: frozen=%v", label, frozen)
}
if v := egressHasAny(frozen, bad...); v != "" {
t.Fatalf("%s: insert_assets host %q promoted into task_scope_egress: %v", label, v, frozen)
}
if v := egressHasAny(proxy, bad...); v != "" {
t.Fatalf("%s: insert_assets host %q reached the sandbox egress allowlist: %v", label, v, proxy)
}
}
selected := f.newTask("selected-"+sfx, companyID)
check("operator selection at task creation", selected)
f.operatorApproveCompany(selected, companyID)
check("operator re-approval", selected)
}
// (e) Revoking the company grant drops its frozen egress rows.
func TestOperatorCompanyRevocationDropsEgress(t *testing.T) {
f := newCompanyEgressFixture(t)
sfx := strconv.FormatInt(time.Now().UnixNano(), 36)
opDom := "op-e-" + sfx + ".test"
companyID := f.operatorCreateCompany("RevokeCo-"+sfx, []map[string]string{
{"kind": "domain", "value": opDom},
{"kind": "cidr", "value": "198.51.100.128/26"},
})
taskID := f.newTask("revoke-" + sfx)
f.operatorApproveCompany(taskID, companyID)
if frozen, _ := f.egress(taskID, companyID); egressHasAny(frozen, opDom) == "" {
t.Fatalf("approval did not promote the operator domain: %v", frozen)
}
rows, err := f.as.ListTaskScope(taskID)
if err != nil {
t.Fatalf("ListTaskScope: %v", err)
}
var scopeID int64
for _, r := range rows {
if r.Kind == "company" && r.CompanyID != nil && *r.CompanyID == companyID {
scopeID = r.ID
}
}
if ok, err := f.as.DeleteTaskScope(taskID, scopeID); err != nil || !ok {
t.Fatalf("DeleteTaskScope: ok=%v err=%v", ok, err)
}
frozen, proxy := f.egress(taskID, companyID)
if len(frozen) != 0 || len(proxy) != 0 {
t.Fatalf("revoked company grant still grants egress: frozen=%v proxy=%v", frozen, proxy)
}
}
+16 -4
View File
@@ -47,6 +47,7 @@ func TestSandboxCompanyEgressFrozenAtApproval(t *testing.T) {
{Kind: "cidr", Value: approvedCIDR},
},
"test fixture",
true,
)
if err != nil {
t.Fatalf("CreateCompanyWithScope: %v", err)
@@ -74,7 +75,7 @@ func TestSandboxCompanyEgressFrozenAtApproval(t *testing.T) {
// The planner (prompt-injected or not) widens the company after approval,
// exactly as add_company_scope does.
injectedDom := "frozen-b-" + suffix + ".test"
if added, _, _, errs := pg.Companies().AddScope(compID, []string{injectedDom}, "agent widen after approval"); added != 1 {
if added, _, _, errs := pg.Companies().AddScope(compID, []string{injectedDom}, "agent widen after approval", false); added != 1 {
t.Fatalf("agent company scope write: added=%d errs=%v", added, errs)
}
@@ -87,14 +88,22 @@ func TestSandboxCompanyEgressFrozenAtApproval(t *testing.T) {
}
// Re-approving the company is a new operator decision and refreshes the
// snapshot, so the new inventory is reachable from then on.
// snapshot with the operator-approved rules added since. The agent-written
// rule is still not promoted.
operatorDom := "frozen-c-" + suffix + ".test"
if added, _, _, errs := pg.Companies().AddScope(compID, []string{operatorDom}, "operator widen after approval", true); added != 1 {
t.Fatalf("operator company scope write: added=%d errs=%v", added, errs)
}
if ts, err := as.AddOperatorScope(task.ID, "company", strconv.FormatInt(compID, 10), "operator re-approval"); err != nil || !ts.ApprovedByOperator {
t.Fatalf("AddOperatorScope company: ts=%+v err=%v", ts, err)
}
domains, _ = runInfo(t, task.ID)
if !scopeHas(domains, injectedDom) {
if !scopeHas(domains, operatorDom) {
t.Fatalf("re-approval did not refresh the egress snapshot: domains=%v", domains)
}
if scopeHas(domains, injectedDom) {
t.Fatalf("re-approval promoted an agent-written company scope rule: domains=%v", domains)
}
// AddOperatorScope on a task that did not select the company also snapshots.
task2, err := pg.CreateTaskWithOptions("frozen-late-"+suffix, "goal", db.TaskCreateOptions{})
@@ -106,9 +115,12 @@ func TestSandboxCompanyEgressFrozenAtApproval(t *testing.T) {
t.Fatalf("AddOperatorScope on existing task: %v", err)
}
domains, cidrs = runInfo(t, task2.ID)
if !scopeHas(domains, approvedDom) || !scopeHas(domains, injectedDom) || !scopeHas(cidrs, approvedCIDR) {
if !scopeHas(domains, approvedDom) || !scopeHas(domains, operatorDom) || !scopeHas(cidrs, approvedCIDR) {
t.Fatalf("approval snapshot incomplete: domains=%v cidrs=%v", domains, cidrs)
}
if scopeHas(domains, injectedDom) {
t.Fatalf("approval promoted an agent-written company scope rule: domains=%v", domains)
}
// Removing the company grant revokes the materialized egress, so the proxy
// does not stay open after the operator deletes the scope row.
+2
View File
@@ -175,6 +175,7 @@ func TestSandboxScopeDriftBlockedAcrossProxyWebFetchAndBrowser(t *testing.T) {
{Kind: "cidr", Value: canaryHost + "/32"},
},
"test",
true,
)
if err != nil {
t.Fatalf("CreateCompanyWithScope agentComp: %v", err)
@@ -273,6 +274,7 @@ func TestSandboxScopeDriftBlockedAcrossProxyWebFetchAndBrowser(t *testing.T) {
{Kind: "cidr", Value: canaryHost + "/32"},
},
"test",
true,
)
if err != nil {
t.Fatalf("CreateCompanyWithScope opComp: %v", err)
+15 -9
View File
@@ -224,8 +224,9 @@ func TestSandboxSharedBrowserBlocksNonScopeNavigation(t *testing.T) {
}
// TestTaskSandboxRunInfoIncludesCompanyScope verifies that task_scope.kind='company'
// rows expand company_scope domains/CIDRs and attributed company assets into the
// task's sandbox egress allowlist.
// rows expand the operator-approved company_scope domains/CIDRs into the task's
// sandbox egress allowlist, and that attributed company assets do not: the agent
// can write assets, so an asset host needs its own company or task scope rule.
func TestTaskSandboxRunInfoIncludesCompanyScope(t *testing.T) {
dsn := strings.TrimSpace(os.Getenv("ARTEX_PG_DSN"))
if dsn == "" {
@@ -249,6 +250,7 @@ func TestTaskSandboxRunInfoIncludesCompanyScope(t *testing.T) {
{Kind: "cidr", Value: "198.51.100.0/24"},
},
"test",
true,
)
if err != nil {
t.Fatalf("CreateCompanyWithScope: %v", err)
@@ -267,15 +269,19 @@ func TestTaskSandboxRunInfoIncludesCompanyScope(t *testing.T) {
info := taskSandboxRunInfo(pg, t.TempDir(), strconv.FormatInt(task.ID, 10))
domJoined := strings.Join(info.ScopeDomains, ",")
cidrJoined := strings.Join(info.ScopeCIDRs, ",")
for _, wantDom := range []string{scopeDom, subDom, rootDom} {
if !strings.Contains(domJoined, wantDom) {
t.Fatalf("expected company domain %q in ScopeDomains=%v", wantDom, info.ScopeDomains)
if !strings.Contains(domJoined, scopeDom) {
t.Fatalf("expected company domain %q in ScopeDomains=%v", scopeDom, info.ScopeDomains)
}
if !strings.Contains(cidrJoined, "198.51.100.0/24") {
t.Fatalf("expected company CIDR %q in ScopeCIDRs=%v", "198.51.100.0/24", info.ScopeCIDRs)
}
for _, asset := range []string{subDom, rootDom} {
if strings.Contains(domJoined, asset) {
t.Fatalf("attributed asset domain %q reached ScopeDomains=%v", asset, info.ScopeDomains)
}
}
for _, wantCIDR := range []string{"198.51.100.0/24", "203.0.113.42"} {
if !strings.Contains(cidrJoined, wantCIDR) {
t.Fatalf("expected company CIDR/IP %q in ScopeCIDRs=%v", wantCIDR, info.ScopeCIDRs)
}
if strings.Contains(cidrJoined, "203.0.113.42") {
t.Fatalf("attributed asset IP reached ScopeCIDRs=%v", info.ScopeCIDRs)
}
}
+1 -1
View File
@@ -39,7 +39,7 @@ func TestSpawnTaskCompanyIDsScopeAndFilter(t *testing.T) {
// 2. Create two companies; acme has a declared domain scope.
acmeID, _, _, _, _, err := m.pg.Companies().CreateCompanyWithScope("spawn-acme", "", []db.ScopeInput{
{Kind: "domain", Value: "acme.example.test"},
}, "test")
}, "test", true)
if err != nil {
t.Fatal(err)
}
+3 -1
View File
@@ -317,7 +317,9 @@ func (s *Server) syncSSRun(w http.ResponseWriter, r *http.Request) {
companies = append(companies, name)
madeCompany = true
if len(roots) > 0 {
cs.AddScope(cid, roots, "scopesentry:"+name)
// Imported from ScopeSentry, not entered by the operator:
// attributes assets but grants no sandbox egress.
cs.AddScope(cid, roots, "scopesentry:"+name, false)
}
}
}