← Back to Pull requests

feat(substrate): install an egress policy on the session actor before it starts #265

Merged
aramase merged 18 files (2244 lines) on Nov 16, 2026 01:53 UTC
View on GitHub
aramase aramase commented on Nov 13, 2026 02:56 UTC
Author

Part of #251.

A harness that reaches the network without going through a mediating proxy needs its actor's egress policy in place before the actor's compute first runs. Substrate denies all egress for an actor that has no policy, so installing it late means the first turn runs with nothing allowed.

  • substrate.WithEgressPolicy takes a function of the session spec and returns the rules for that session's actor. The rule type is neutral and lives in runtime/substrate (http, https and tls_passthrough rules, including credential-header effects from a credential URI or an actor JWT), so the root module does not import the Substrate API. The integrations/substrate adapter converts it to the Substrate default policy.

  • The backend installs the policy after CreateActor and before the first ResumeActor, before any later resume of a suspended actor, and on a fork child's clone before it resumes. If the install fails the call fails and the actor stays suspended (a fork clone is torn down).

  • The calls sit on a new optional EgressPolicyClient interface, checked by type assertion like SnapshotCloner; ControlClient is unchanged. With a policy configured and a client that lacks the interface, the call is refused before any actor is created. That refusal, and a policy Substrate rejects as invalid, reach callers as FAILED_PRECONDITION with reason COMPUTE_CONFIG_INVALID; the text does not include Substrate's message.

  • If the actor already has a policy it is kept. A changed policy reaches only actors created after the change; converging existing actors is not part of this PR, and neither is replacing or removing a policy on a running actor.

  • agentsessionsd (substrate build) gets -substrate-egress-policy-file, a protojson EgressPolicy read once at startup.

  • Without the option the backend makes no egress call.
  • Tested with fake ControlClient tests for install order, the fork child (stateful and stateless), a failed install leaving the actor suspended, no policy leaving the call sequence unchanged, the missing-interface refusal and the already-exists keep path. The public status code and reason are checked over gRPC for Exec, Resume and Fork. Adapter conversion and daemon flag tests are included, and go test -race passes in the root module and in integrations/substrate.

    The new e2e tests (TestEgressPolicy*, run by the substrate e2e workflow) read back the installed policy at create, resume and fork. I have not run them against a live Substrate, and nothing here exercises gateway enforcement or credential injection end to end, so this is Part of rather than closing the issue.

    Diff: 2244 lines (+2190 / -54) across 18 files Reviewer: gambtho Review duration: 4257m
    All Vouch review confidence checks passed
    Residual risk 0.20 = Change Risk (0.72) × (1 − Review Confidence (0.72)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.72 · 2244 lines diff across 18 files
    0.72
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.55 · 2 substantive comment(s)
    0.55
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    71%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.400
    Mass File Touch mass_file_touch
    0.080
    Real PR Conversation Timeline
    5 items
    Copilot Copilot commented on code on Nov 13, 2026 03:10 UTC
    Code Review
    integrations/substrate/cmd/agentsessionsd/substrate.go:1
    @@ -316,10 +343,60 @@ func (f *substrateFlags) logConfig(logger *slog.Logger) {
     			"atenet_router_server_name", f.routerCreds.ServerName(),
     			"ateapi_token_file", *f.tokenFile,
     			"ateapi_insecure_skip_verify", *f.insecureVerify,
    +			"egress_policy_file", *f.egressFile,
    +			"egress_policy_rules", egressRules(f.egressPolicy),
     		)
     	}
     }
     
    +// egressRules is the number of rules in policy, or -1 with no policy, so the log tells no policy
    +// from a deny-all one without recording the rules.
    +func egressRules(policy *substrate.EgressPolicy) int {
    +	if policy == nil {
    +		return -1
    +	}
    +	return len(policy.Rules)
    +}
    +
    +// maxEgressPolicyFile bounds what readEgressPolicy reads, well above what substrate accepts in one
    +// policy.
    +const maxEgressPolicyFile = 1 << 20
    +
    +// readEgressPolicy reads the -substrate-egress-policy-file policy: a substrate ateapi.v1
    +// EgressPolicy in protojson. Unknown fields are refused, so a misspelled rule field is not silently
    +// dropped from what the actor is allowed. metadata is refused: the backend names the policy and the
    +// actor it belongs to. Substrate validates the rules themselves when it creates each actor's
    +// policy, so a rule it refuses passes startup and fails each Exec, Resume and Fork that would
    +// start an actor's compute with FAILED_PRECONDITION (COMPUTE_CONFIG_INVALID). Errors name the
    +// file. A parse error can quote the offending JSON token; it is a startup error, which only the
    +// operator sees.
    +func readEgressPolicy(path string) (substrate.EgressPolicy, error) {
    +	file, err := os.Open(path)
    +	if err != nil {
    +		return substrate.EgressPolicy{}, err
    +	}
    +	defer func() { _ = file.Close() }()
    +	data, err := io.ReadAll(io.LimitReader(file, maxEgressPolicyFile+1))
    +	if err != nil {
    +		return substrate.EgressPolicy{}, err
    +	}
    +	if len(data) > maxEgressPolicyFile {
    +		return substrate.EgressPolicy{}, fmt.Errorf("%s: larger than %d bytes", path, maxEgressPolicyFile)
    +	}
    +	var p atepb.EgressPolicy
    +	if err := protojson.Unmarshal(data, &p); err != nil {
    +		return substrate.EgressPolicy{}, fmt.Errorf("%s: not an ateapi.v1 EgressPolicy in JSON: %w", path, err)

    Wrapping the raw protojson error can expose policy contents in startup diagnostics: for example, a hostname supplied as a string instead of an array can be quoted in the decoder error. Startup errors may be collected in container logs, so they are not necessarily an operator-only channel. Omit the raw decoder message (or retain only a sanitized location) and add a malformed-input case with a private hostname to the startup checks.

    copilot-pull-request-reviewer[bot] copilot-pull-request-reviewer[bot] commented on Nov 13, 2026 03:10 UTC
    Reviewer

    <!-- ccr-overview-v2 -->

    🟡 Changes recommended

    Raw protojson errors can expose private policy contents in collected startup logs, requiring sanitized diagnostics and a malformed-input regression check with a private hostname.

    <details open>
    <summary><strong>1 open issue</strong></summary>

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture> Sanitize protojson errors to avoid leaking policy contents · New

  • </details>

    <details>
    <summary><strong>What changed in this PR</strong></summary>

    Adds pre-start egress policy installation to the Substrate backend, advancing #251 while keeping Substrate API dependencies in the integration module. Live gateway enforcement and credential injection remain unverified.

    Changes:

  • Adds neutral policy types and an optional client interface, with installation before create, resume, and fork compute starts.

  • Adds adapter conversion and the daemon’s -substrate-egress-policy-file flag.

  • Adds lifecycle, error-handling, and policy readback tests, plus documentation and CI coverage.
  • | File | Description |
    | ---- | ----------- |
    | spec.md | Defines policy configuration semantics and remaining verification gaps. |
    | session/​egress_policy_error_test.go | Tests public error codes and sanitized policy refusals. |
    | runtime/​substrate/​substrate.go | Installs policies at actor lifecycle transitions. |
    | runtime/​substrate/​substrate_test.go | Allows backend options in the memory-tier test helper. |
    | runtime/​substrate/​egress.go | Defines neutral policy types, optional interface, and installation logic. |
    | runtime/​substrate/​egress_test.go | Tests ordering, failures, existing policies, and logging. |
    | integrations/​substrate/​egress.go | Implements policy RPCs and neutral-to-protobuf conversion. |
    | integrations/​substrate/​egress_test.go | Tests conversion, validation, and error mapping. |
    | integrations/​substrate/​e2e/​egress_test.go | Adds lifecycle policy readback and failed-install checks. |
    | integrations/​substrate/​cmd/​agentsessionsd/​substrate.go | Loads and configures a static policy file. |
    | integrations/​substrate/​cmd/​agentsessionsd/​main_test.go | Checks adapter support for the optional interface. |
    | integrations/​substrate/​cmd/​agentsessionsd/​egress_test.go | Tests startup checks and daemon policy installation. |
    | hack/​provision-e2e-access.sh | Provisions access for egress tests. |
    | docs/​substrate-conformance.md | Documents configuration, lifecycle behavior, and test scope. |
    | docs/​security.md | Explains policy security guarantees and limitations. |
    | changelog/​unreleased/​egress-policy.md | Records the new backend option and daemon flag. |
    | changelog/​unreleased/​egress-policy-compat.md | Records compatibility and failure behavior. |
    | .github/​workflows/​substrate-e2e.yml | Includes egress tests in the existing e2e job. |
    </details>

    <sub>Review effort: Balanced</sub>

    aramase aramase commented on code on Nov 13, 2026 20:07 UTC
    Code Review
    integrations/substrate/cmd/agentsessionsd/substrate.go:1
    @@ -316,10 +343,60 @@ func (f *substrateFlags) logConfig(logger *slog.Logger) {
     			"atenet_router_server_name", f.routerCreds.ServerName(),
     			"ateapi_token_file", *f.tokenFile,
     			"ateapi_insecure_skip_verify", *f.insecureVerify,
    +			"egress_policy_file", *f.egressFile,
    +			"egress_policy_rules", egressRules(f.egressPolicy),
     		)
     	}
     }
     
    +// egressRules is the number of rules in policy, or -1 with no policy, so the log tells no policy
    +// from a deny-all one without recording the rules.
    +func egressRules(policy *substrate.EgressPolicy) int {
    +	if policy == nil {
    +		return -1
    +	}
    +	return len(policy.Rules)
    +}
    +
    +// maxEgressPolicyFile bounds what readEgressPolicy reads, well above what substrate accepts in one
    +// policy.
    +const maxEgressPolicyFile = 1 << 20
    +
    +// readEgressPolicy reads the -substrate-egress-policy-file policy: a substrate ateapi.v1
    +// EgressPolicy in protojson. Unknown fields are refused, so a misspelled rule field is not silently
    +// dropped from what the actor is allowed. metadata is refused: the backend names the policy and the
    +// actor it belongs to. Substrate validates the rules themselves when it creates each actor's
    +// policy, so a rule it refuses passes startup and fails each Exec, Resume and Fork that would
    +// start an actor's compute with FAILED_PRECONDITION (COMPUTE_CONFIG_INVALID). Errors name the
    +// file. A parse error can quote the offending JSON token; it is a startup error, which only the
    +// operator sees.
    +func readEgressPolicy(path string) (substrate.EgressPolicy, error) {
    +	file, err := os.Open(path)
    +	if err != nil {
    +		return substrate.EgressPolicy{}, err
    +	}
    +	defer func() { _ = file.Close() }()
    +	data, err := io.ReadAll(io.LimitReader(file, maxEgressPolicyFile+1))
    +	if err != nil {
    +		return substrate.EgressPolicy{}, err
    +	}
    +	if len(data) > maxEgressPolicyFile {
    +		return substrate.EgressPolicy{}, fmt.Errorf("%s: larger than %d bytes", path, maxEgressPolicyFile)
    +	}
    +	var p atepb.EgressPolicy
    +	if err := protojson.Unmarshal(data, &p); err != nil {
    +		return substrate.EgressPolicy{}, fmt.Errorf("%s: not an ateapi.v1 EgressPolicy in JSON: %w", path, err)

    Keeping this as is: the egress policy file is operator-supplied config, not a secret, and the error goes only to the operator starting the daemon. Quoting the bad value makes the misconfiguration easier to find.

    gambtho gambtho approved these changes on Nov 16, 2026 01:52 UTC
    Approved Reviewer

    Approved these changes.

    Reviewers
    Assignees
    aramase aramase
    Labels
    risk: low confidence: 71.7% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 71.5% (HIGH) · Higher = larger blast radius
    71.5%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 71.7% · Lower = rushed or shallow review
    71.7%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 20.2% · Safe to merge
    20.2%