mirror of
https://github.com/BaaRai/ARTEX.git
synced 2026-12-02 20:53:56 +08:00
Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c8f057a039 | ||
|
|
51045c0622 | ||
|
|
ed70ea3220 | ||
|
|
8ad85ed3ac | ||
|
|
0f2211242a | ||
|
|
a75ff74aac |
@@ -4,6 +4,10 @@ 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
|
||||
|
||||
- **`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.
|
||||
|
||||
+1
-1
@@ -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,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
@@ -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
@@ -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/
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
+22
-3
@@ -183,23 +183,42 @@ func formatSandboxExecResult(resp sandbox.ExecResponse, tc *actool.ToolContext)
|
||||
return actool.Text(out)
|
||||
}
|
||||
|
||||
// SandboxEgressPolicy is the task's sandbox.EgressPolicy for ctx, the one
|
||||
// WebFetch enforces in ARTEX_SANDBOX=required mode: the scope domains and CIDRs
|
||||
// of the run, or, when they do not parse or the run carries none, a policy that
|
||||
// allows nothing.
|
||||
func SandboxEgressPolicy(ctx context.Context) *sandbox.EgressPolicy {
|
||||
info, _ := SandboxRunInfoFromContext(ctx)
|
||||
pol, err := sandbox.NewEgressPolicy(info.TaskID, info.ScopeDomains, info.ScopeCIDRs, nil)
|
||||
if err != nil {
|
||||
pol, _ = sandbox.NewEgressPolicy(info.TaskID, nil, nil, nil)
|
||||
}
|
||||
return pol
|
||||
}
|
||||
|
||||
// sandboxScopeDialContext wraps baseDial so every TCP connection made by panel
|
||||
// WebFetch in ARTEX_SANDBOX=required mode validates and pins the target IP via
|
||||
// the task's sandbox.EgressPolicy (blocking non-scope IPs, IMDS, loopback,
|
||||
// RFC1918, and IPv6 across all hops and redirects).
|
||||
func sandboxScopeDialContext(policy *sandbox.EgressPolicy, baseDial func(ctx context.Context, network, addr string) (net.Conn, error)) func(ctx context.Context, network, addr string) (net.Conn, error) {
|
||||
return SandboxScopeDialContext("WebFetch", policy, baseDial)
|
||||
}
|
||||
|
||||
// SandboxScopeDialContext is the WebFetch sandbox dialer for another panel tool
|
||||
// that connects out from the panel process; label names the tool in a refusal.
|
||||
func SandboxScopeDialContext(label string, policy *sandbox.EgressPolicy, baseDial func(ctx context.Context, network, addr string) (net.Conn, error)) func(ctx context.Context, network, addr string) (net.Conn, error) {
|
||||
return func(ctx context.Context, network, addr string) (net.Conn, error) {
|
||||
host, portStr, err := net.SplitHostPort(addr)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("sandbox WebFetch blocked invalid target %q: %w", addr, err)
|
||||
return nil, fmt.Errorf("sandbox %s blocked invalid target %q: %w", label, addr, err)
|
||||
}
|
||||
port, err := strconv.Atoi(portStr)
|
||||
if err != nil || port <= 0 || port > 65535 {
|
||||
return nil, fmt.Errorf("sandbox WebFetch blocked invalid port %q", portStr)
|
||||
return nil, fmt.Errorf("sandbox %s blocked invalid port %q", label, portStr)
|
||||
}
|
||||
pinnedIP, err := policy.ResolveAndCheck(ctx, host)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("sandbox WebFetch blocked: %w", err)
|
||||
return nil, fmt.Errorf("sandbox %s blocked: %w", label, err)
|
||||
}
|
||||
pinnedAddr := net.JoinHostPort(pinnedIP.String(), strconv.Itoa(port))
|
||||
if baseDial != nil {
|
||||
|
||||
@@ -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,
|
||||
|
||||
+1
-5
@@ -30,11 +30,7 @@ func withWebFetch(ctx context.Context, tools []actool.CoreTool, proxy, caCert st
|
||||
disableDirect := gated
|
||||
var sbPolicy *sandbox.EgressPolicy
|
||||
if SandboxRequired() {
|
||||
info, _ := SandboxRunInfoFromContext(ctx)
|
||||
pol, err := sandbox.NewEgressPolicy(info.TaskID, info.ScopeDomains, info.ScopeCIDRs, nil)
|
||||
if err != nil {
|
||||
pol, _ = sandbox.NewEgressPolicy(info.TaskID, nil, nil, nil)
|
||||
}
|
||||
pol := SandboxEgressPolicy(ctx)
|
||||
sbPolicy = pol
|
||||
dialer = sandboxScopeDialContext(pol, dialer)
|
||||
disableDirect = true
|
||||
|
||||
+3
-3
@@ -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
@@ -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
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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;
|
||||
@@ -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),
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
+15
-1
@@ -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
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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
@@ -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
@@ -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) {
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
+51
-1
@@ -698,6 +698,18 @@ func (s *Server) runHTTPTool(ctx context.Context, key string, execRaw json.RawMe
|
||||
if strings.TrimSpace(rawURL) == "" {
|
||||
return actool.Errorf("http url is empty"), nil
|
||||
}
|
||||
// ARTEX_SANDBOX=required: the request leaves from the panel process, not from
|
||||
// the task's worker container and its egress proxy. The task's egress policy,
|
||||
// the one WebFetch enforces, applies here to the URL, to every redirect hop
|
||||
// and to every connection (see sandboxHTTPTransport); a refusal is final,
|
||||
// there is no direct fallback.
|
||||
var sbPolicy *sandbox.EgressPolicy
|
||||
if agent.SandboxRequired() {
|
||||
sbPolicy = agent.SandboxEgressPolicy(ctx)
|
||||
if err := sbPolicy.CheckURL(ctx, rawURL); err != nil {
|
||||
return actool.Errorf("sandbox http tool blocked: " + err.Error()), nil
|
||||
}
|
||||
}
|
||||
// The hook saw the parameters, not the URL they render (nor a URL written in
|
||||
// the template): the target gate reads the rendered URL here, before the
|
||||
// tool's own timeout starts, so a wait for an approval does not consume it.
|
||||
@@ -726,11 +738,18 @@ func (s *Server) runHTTPTool(ctx context.Context, key string, execRaw json.RawMe
|
||||
if intercept.ApplyAssessmentUserAgent(req) {
|
||||
client.CheckRedirect = assessmentRedirectCheck(client.CheckRedirect)
|
||||
}
|
||||
if sbPolicy != nil {
|
||||
client.CheckRedirect = sandboxRedirectCheck(sbPolicy, client.CheckRedirect)
|
||||
}
|
||||
// The current egress governor paces every request and redirect hop per host
|
||||
// under the noise profile (off by default: the base transport itself). It is
|
||||
// resolved per request, so a changed profile applies to the next call.
|
||||
var base http.RoundTripper = http.DefaultTransport
|
||||
if tr := s.httpToolTransport(ctx, key, spec); tr != nil {
|
||||
tr := s.httpToolTransport(ctx, key, spec)
|
||||
if sbPolicy != nil {
|
||||
tr = sandboxHTTPTransport(tr, sbPolicy)
|
||||
}
|
||||
if tr != nil {
|
||||
base = tr
|
||||
}
|
||||
client.Transport = egress.Current().Transport(key, base)
|
||||
@@ -759,6 +778,37 @@ func assessmentRedirectCheck(check func(*http.Request, []*http.Request) error) f
|
||||
}
|
||||
}
|
||||
|
||||
// sandboxRedirectCheck refuses a redirect hop to a URL the task's egress policy
|
||||
// does not allow, before check runs: the call fails instead of following it.
|
||||
func sandboxRedirectCheck(policy *sandbox.EgressPolicy, check func(*http.Request, []*http.Request) error) func(*http.Request, []*http.Request) error {
|
||||
return func(req *http.Request, via []*http.Request) error {
|
||||
if err := policy.CheckURL(req.Context(), req.URL.String()); err != nil {
|
||||
return fmt.Errorf("sandbox http tool blocked redirect: %w", err)
|
||||
}
|
||||
return check(req, via)
|
||||
}
|
||||
}
|
||||
|
||||
// sandboxHTTPTransport makes every connection of an http tool call go through
|
||||
// the WebFetch sandbox dialer, which checks the host against the policy and
|
||||
// dials only the IP it resolved and allowed. tr is httpToolTransport's result:
|
||||
// with a proxy, the proxy is the connection checked; a direct call drops the
|
||||
// environment proxy so the dialer sees the target, and keeps the pinned dialer
|
||||
// of a gated scope underneath.
|
||||
func sandboxHTTPTransport(tr *http.Transport, policy *sandbox.EgressPolicy) *http.Transport {
|
||||
if tr == nil {
|
||||
base, ok := http.DefaultTransport.(*http.Transport)
|
||||
if !ok {
|
||||
base = &http.Transport{}
|
||||
}
|
||||
tr = base.Clone()
|
||||
tr.Proxy = nil
|
||||
tr.DisableKeepAlives = true
|
||||
}
|
||||
tr.DialContext = agent.SandboxScopeDialContext("http tool", policy, tr.DialContext)
|
||||
return tr
|
||||
}
|
||||
|
||||
// httpToolTransport is the transport of one http tool call, or nil
|
||||
// (http.DefaultTransport). A call through a proxy keeps httpProxyTransport: it
|
||||
// dials the proxy, which makes the connection to the target. A direct call in
|
||||
|
||||
@@ -0,0 +1,266 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
|
||||
"github.com/Autumn-27/artex/agent"
|
||||
"github.com/Autumn-27/artex/db"
|
||||
"github.com/Autumn-27/artex/sandbox"
|
||||
actool "github.com/Autumn-27/norma/tool"
|
||||
)
|
||||
|
||||
// sandboxRequired puts the process in ARTEX_SANDBOX=required mode for one test.
|
||||
func sandboxRequired(t *testing.T) {
|
||||
t.Helper()
|
||||
prev := agent.CurrentSandboxExecutor()
|
||||
agent.SetSandboxExecutor(&agent.SandboxExecutor{Mode: sandbox.ModeRequired})
|
||||
t.Cleanup(func() { agent.SetSandboxExecutor(prev) })
|
||||
}
|
||||
|
||||
// canaryServer counts every request it receives. ip is the loopback address it
|
||||
// listens on (127.0.0.1 or 127.0.0.2, both on lo).
|
||||
func canaryServer(t *testing.T, ip string, h http.HandlerFunc) (*httptest.Server, *atomic.Int32) {
|
||||
t.Helper()
|
||||
hits := new(atomic.Int32)
|
||||
srv := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
hits.Add(1)
|
||||
if h != nil {
|
||||
h(w, r)
|
||||
return
|
||||
}
|
||||
_, _ = w.Write([]byte("CANARY_BODY"))
|
||||
}))
|
||||
ln, err := net.Listen("tcp", ip+":0")
|
||||
if err != nil {
|
||||
t.Fatalf("listen %s: %v", ip, err)
|
||||
}
|
||||
srv.Listener = ln
|
||||
srv.Start()
|
||||
t.Cleanup(srv.Close)
|
||||
return srv, hits
|
||||
}
|
||||
|
||||
func sandboxCtx(domains, cidrs []string) context.Context {
|
||||
return agent.WithSandboxRunInfo(context.Background(), agent.SandboxRunInfo{
|
||||
TaskID: "custom-http-egress", ScopeDomains: domains, ScopeCIDRs: cidrs,
|
||||
})
|
||||
}
|
||||
|
||||
func runHTTPSpec(t *testing.T, ctx context.Context, spec map[string]any) actool.Result {
|
||||
t.Helper()
|
||||
raw, _ := json.Marshal(spec)
|
||||
res, err := (&Server{}).runHTTPTool(ctx, "probe", raw, map[string]any{}, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("runHTTPTool: %v", err)
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
// A URL outside the task scope is refused before any request leaves.
|
||||
func TestSandboxHTTPToolRefusesOutOfScopeURL(t *testing.T) {
|
||||
sandboxRequired(t)
|
||||
srv, hits := canaryServer(t, "127.0.0.1", nil)
|
||||
ctx := sandboxCtx([]string{"allowed.example"}, nil)
|
||||
|
||||
res := runHTTPSpec(t, ctx, map[string]any{"method": "GET", "url": srv.URL + "/secret"})
|
||||
if !res.IsError || !strings.Contains(res.Flatten(), "egress denied") {
|
||||
t.Fatalf("out-of-scope URL not refused: isError=%v text=%q", res.IsError, res.Flatten())
|
||||
}
|
||||
if n := hits.Load(); n != 0 {
|
||||
t.Fatalf("out-of-scope server received %d request(s)", n)
|
||||
}
|
||||
}
|
||||
|
||||
// A name in scope that resolves only to loopback is not dialed: the policy
|
||||
// treats it as WebFetch does (loopback is denied unless listed in the CIDRs).
|
||||
func TestSandboxHTTPToolRefusesScopedNameResolvingToLoopback(t *testing.T) {
|
||||
sandboxRequired(t)
|
||||
srv, hits := canaryServer(t, "127.0.0.1", nil)
|
||||
_, port, _ := net.SplitHostPort(srv.Listener.Addr().String())
|
||||
ctx := sandboxCtx([]string{"localhost"}, nil)
|
||||
|
||||
res := runHTTPSpec(t, ctx, map[string]any{"method": "GET", "url": "http://localhost:" + port + "/"})
|
||||
if !res.IsError || !strings.Contains(res.Flatten(), "egress denied") {
|
||||
t.Fatalf("scoped name resolving to loopback not refused: isError=%v text=%q", res.IsError, res.Flatten())
|
||||
}
|
||||
if n := hits.Load(); n != 0 {
|
||||
t.Fatalf("loopback server received %d request(s)", n)
|
||||
}
|
||||
}
|
||||
|
||||
// A redirect from an in-scope URL to a host outside the scope fails; the
|
||||
// outside host never receives the request.
|
||||
func TestSandboxHTTPToolRefusesRedirectOutOfScope(t *testing.T) {
|
||||
sandboxRequired(t)
|
||||
outside, outsideHits := canaryServer(t, "127.0.0.2", nil)
|
||||
inScope, inHits := canaryServer(t, "127.0.0.1", func(w http.ResponseWriter, r *http.Request) {
|
||||
http.Redirect(w, r, outside.URL+"/stolen", http.StatusFound)
|
||||
})
|
||||
ctx := sandboxCtx(nil, []string{"127.0.0.1/32"})
|
||||
|
||||
res := runHTTPSpec(t, ctx, map[string]any{"method": "GET", "url": inScope.URL + "/start"})
|
||||
if !res.IsError || !strings.Contains(res.Flatten(), "egress denied") {
|
||||
t.Fatalf("out-of-scope redirect not refused: isError=%v text=%q", res.IsError, res.Flatten())
|
||||
}
|
||||
if n := inHits.Load(); n != 1 {
|
||||
t.Fatalf("in-scope server hits = %d, want 1", n)
|
||||
}
|
||||
if n := outsideHits.Load(); n != 0 {
|
||||
t.Fatalf("out-of-scope redirect target received %d request(s)", n)
|
||||
}
|
||||
}
|
||||
|
||||
// A proxy configured on the tool is a connection the panel opens too: a proxy
|
||||
// outside the scope is not dialed, even for an in-scope target.
|
||||
func TestSandboxHTTPToolRefusesOutOfScopeProxy(t *testing.T) {
|
||||
sandboxRequired(t)
|
||||
target, targetHits := canaryServer(t, "127.0.0.1", nil)
|
||||
proxy, proxyHits := canaryServer(t, "127.0.0.2", nil)
|
||||
ctx := sandboxCtx(nil, []string{"127.0.0.1/32"})
|
||||
|
||||
res := runHTTPSpec(t, ctx, map[string]any{"method": "GET", "url": target.URL + "/", "proxy": proxy.URL})
|
||||
if !res.IsError || !strings.Contains(res.Flatten(), "egress denied") {
|
||||
t.Fatalf("out-of-scope proxy not refused: isError=%v text=%q", res.IsError, res.Flatten())
|
||||
}
|
||||
if n := proxyHits.Load(); n != 0 {
|
||||
t.Fatalf("out-of-scope proxy received %d request(s)", n)
|
||||
}
|
||||
if n := targetHits.Load(); n != 0 {
|
||||
t.Fatalf("target received %d request(s) around the proxy", n)
|
||||
}
|
||||
}
|
||||
|
||||
// An in-scope URL still works under the sandbox (loopback listed in the scope
|
||||
// CIDRs, the seam the WebFetch sandbox test uses).
|
||||
func TestSandboxHTTPToolAllowsInScopeURL(t *testing.T) {
|
||||
sandboxRequired(t)
|
||||
srv, hits := canaryServer(t, "127.0.0.1", nil)
|
||||
ctx := sandboxCtx(nil, []string{"127.0.0.1/32"})
|
||||
|
||||
res := runHTTPSpec(t, ctx, map[string]any{"method": "GET", "url": srv.URL + "/ok"})
|
||||
if res.IsError || !strings.Contains(res.Flatten(), "CANARY_BODY") {
|
||||
t.Fatalf("in-scope URL refused: isError=%v text=%q", res.IsError, res.Flatten())
|
||||
}
|
||||
if n := hits.Load(); n != 1 {
|
||||
t.Fatalf("in-scope server hits = %d, want 1", n)
|
||||
}
|
||||
}
|
||||
|
||||
// Sandbox off: the tool behaves as before, a loopback URL with no task scope
|
||||
// and a redirect to another loopback host both go through.
|
||||
func TestHTTPToolSandboxOffUnchanged(t *testing.T) {
|
||||
prev := agent.CurrentSandboxExecutor()
|
||||
agent.SetSandboxExecutor(nil)
|
||||
t.Cleanup(func() { agent.SetSandboxExecutor(prev) })
|
||||
other, otherHits := canaryServer(t, "127.0.0.2", nil)
|
||||
srv, hits := canaryServer(t, "127.0.0.1", func(w http.ResponseWriter, r *http.Request) {
|
||||
http.Redirect(w, r, other.URL+"/next", http.StatusFound)
|
||||
})
|
||||
|
||||
res := runHTTPSpec(t, context.Background(), map[string]any{"method": "GET", "url": srv.URL + "/"})
|
||||
if res.IsError || !strings.Contains(res.Flatten(), "CANARY_BODY") {
|
||||
t.Fatalf("sandbox-off call changed: isError=%v text=%q", res.IsError, res.Flatten())
|
||||
}
|
||||
if hits.Load() != 1 || otherHits.Load() != 1 {
|
||||
t.Fatalf("hits = %d/%d, want 1/1", hits.Load(), otherHits.Load())
|
||||
}
|
||||
}
|
||||
|
||||
// customHTTPToolRow creates a Kind:"http" custom tool bound to the worker only,
|
||||
// removed when the test ends.
|
||||
func customHTTPToolRow(t *testing.T, pg *db.DB, key, rawURL string) *db.Tool {
|
||||
t.Helper()
|
||||
execRaw, _ := json.Marshal(map[string]any{"method": "GET", "url": rawURL})
|
||||
row := &db.Tool{
|
||||
Key: key, Description: "custom http egress probe", Kind: "http", Enabled: true,
|
||||
Agents: []string{"worker"}, Exec: execRaw,
|
||||
Schema: json.RawMessage(`{"type":"object","properties":{"q":{"type":"string"}}}`),
|
||||
}
|
||||
_ = pg.DeleteCustomTool(key)
|
||||
if err := pg.CreateCustomTool(row); err != nil {
|
||||
t.Fatalf("create custom tool: %v", err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
_ = pg.DeleteCustomTool(key)
|
||||
_, _ = pg.Exec(`DELETE FROM tool_usage WHERE tool_key=$1`, key)
|
||||
})
|
||||
return row
|
||||
}
|
||||
|
||||
func openToolsPG(t *testing.T) *db.DB {
|
||||
t.Helper()
|
||||
dsn, _, err := db.DSN()
|
||||
if err != nil {
|
||||
db.SkipPGUnavailable(t, err)
|
||||
}
|
||||
pg, err := db.Open(dsn)
|
||||
if err != nil {
|
||||
db.SkipPGUnavailable(t, err)
|
||||
}
|
||||
t.Cleanup(func() { pg.Close() })
|
||||
if err := pg.InitSecrets(t.TempDir()); err != nil {
|
||||
t.Fatalf("init secrets: %v", err)
|
||||
}
|
||||
return pg
|
||||
}
|
||||
|
||||
// The planner never receives a Kind:"http" custom tool bound to the worker,
|
||||
// sandbox on or off; the worker does.
|
||||
func TestCustomHTTPToolNotResolvedForPlanner(t *testing.T) {
|
||||
pg := openToolsPG(t)
|
||||
t.Setenv("AGENT_CORE_DISABLE_INTERACTIVE_SHELL", "1")
|
||||
wireTools(pg, nil)
|
||||
t.Cleanup(func() { agent.SetToolResolve(nil) })
|
||||
s := &Server{m: &Manager{pg: pg}}
|
||||
row := customHTTPToolRow(t, pg, "sec_http_egress_planner_probe", "http://127.0.0.1:1/")
|
||||
base := []actool.CoreTool{s.buildCustomTool(row)}
|
||||
|
||||
for _, required := range []bool{false, true} {
|
||||
if required {
|
||||
sandboxRequired(t)
|
||||
}
|
||||
ctx := context.Background()
|
||||
if _, ok := names(agent.ToolResolve()(ctx, "planner", base))[row.Key]; ok {
|
||||
t.Fatalf("sandbox required=%v: planner received the Kind:http tool", required)
|
||||
}
|
||||
if _, ok := names(agent.ToolResolve()(ctx, "worker", base))[row.Key]; !ok {
|
||||
t.Fatalf("sandbox required=%v: worker lost the Kind:http tool", required)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// End to end, as the worker gets it: the tool the worker resolves refuses a URL
|
||||
// outside the task scope under the sandbox, and the target is never reached.
|
||||
func TestCustomHTTPToolWorkerSandboxRefusesOutOfScope(t *testing.T) {
|
||||
pg := openToolsPG(t)
|
||||
t.Setenv("AGENT_CORE_DISABLE_INTERACTIVE_SHELL", "1")
|
||||
wireTools(pg, nil)
|
||||
t.Cleanup(func() { agent.SetToolResolve(nil) })
|
||||
sandboxRequired(t)
|
||||
srv, hits := canaryServer(t, "127.0.0.1", nil)
|
||||
s := &Server{m: &Manager{pg: pg}}
|
||||
row := customHTTPToolRow(t, pg, "sec_http_egress_worker_probe", srv.URL+"/secret?q={q}")
|
||||
|
||||
ctx := sandboxCtx([]string{"allowed.example"}, nil)
|
||||
tool, ok := names(agent.ToolResolve()(ctx, "worker", []actool.CoreTool{s.buildCustomTool(row)}))[row.Key]
|
||||
if !ok {
|
||||
t.Fatal("worker did not receive the Kind:http tool")
|
||||
}
|
||||
res, err := tool.Call(ctx, json.RawMessage(`{"q":"x"}`), &actool.ToolContext{})
|
||||
if err != nil {
|
||||
t.Fatalf("call: %v", err)
|
||||
}
|
||||
if !res.IsError || !strings.Contains(res.Flatten(), "egress denied") {
|
||||
t.Fatalf("worker Kind:http call outside the scope not refused: isError=%v text=%q", res.IsError, res.Flatten())
|
||||
}
|
||||
if n := hits.Load(); n != 0 {
|
||||
t.Fatalf("out-of-scope server received %d request(s)", n)
|
||||
}
|
||||
}
|
||||
@@ -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.
|
||||
|
||||
@@ -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
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user