oficina / equipo Public

feat: restrict provider egress outside the host network

codex agent, operated by paul@keymail.dev pushed by claude agent, operated by paul@keymail.dev e06320a8ef6cc1204c7396e1e173a7e5c0df7de5 parent 855f439
12 files changed, +2,755 −24
  • cmd/equipo-runner/namespace.go +2 −0
  • docs/superpowers/plans/CONTROLLER-REPORT-plan-2b.md +1,331 −0
  • internal/runner/containment/egress.go +159 −0
  • internal/runner/containment/egress_test.go +263 −0
  • internal/runner/containment/linux.go +101 −24
  • internal/runner/containment/mounts.go +2 −0
  • internal/runner/containment/recovery.go +1 −0
  • internal/runner/egress/budget_test.go +9 −0
  • internal/runner/egress/policy.go +110 −0
  • internal/runner/egress/proxy.go +280 −0
  • internal/runner/egress/proxy_test.go +489 −0
  • internal/runner/provider/types.go +8 −0

CI passed — run details

diff --git a/cmd/equipo-runner/namespace.go b/cmd/equipo-runner/namespace.go
index 19e9b3a2..02380bbd 100644
--- a/cmd/equipo-runner/namespace.go
+++ b/cmd/equipo-runner/namespace.go
@@ -2,4 +2,6 @@ package main
import "amadan.net/oficina/equipo/internal/runner/containment"
+// NamespaceMain also owns the fixed loopback-to-Unix relay when the trusted
+// launcher supplies --egress. PID 1 exit ends the relay and every harness child.
func namespace(args []string) int { return containment.NamespaceMain(args) }
diff --git a/docs/superpowers/plans/CONTROLLER-REPORT-plan-2b.md b/docs/superpowers/plans/CONTROLLER-REPORT-plan-2b.md
index dd938505..15282226 100644
--- a/docs/superpowers/plans/CONTROLLER-REPORT-plan-2b.md
+++ b/docs/superpowers/plans/CONTROLLER-REPORT-plan-2b.md
@@ -2882,3 +2882,1334 @@ No UI text, README prose or copy.go entries were added. New internal strings are
The existing test-helper EINTR failure occurred once and is recorded above; the final covering gates pass. The controller still owns remote CI verification and independent review. No push, merge, deployment, provider prompt, sign-in, enrolment, credential home, agent or subagent was used. No full suite or make ci ran.
All test-owned processes and scratch were cleaned up. The mutation evidence directory is removed after transferring its contents into both reports. No server or watcher was started. The branch is ready for controller review.
+
+
+## Task 3: Provider egress without host services
+
+Status: DONE.
+Commit subject: `feat: restrict provider egress outside the host network`.
+Branch: `plan-2b`. No push, merge or deployment.
+
+### What changed
+
+Each provider attempt now owns a private Unix CONNECT endpoint and a Go relay inside its private network namespace. The relay binds `127.0.0.1:18080`, dials only `/egress/proxy.sock`, and runs as goroutines in the existing nondumpable PID 1 helper. The helper starts it before the harness and still reaps orphaned children. Production needs no Python or socat.
+
+The host endpoint accepts only exact allowed DNS names on port 443. It rejects numeric addresses, aliases, wildcard matches, other methods, framing headers, duplicate headers, conflicting Host values, queued requests and malformed HTTP. Each connection resolves once, rejects the entire answer if any address is nonpublic, and dials the validated numeric address. Loopback, private, LAN, link-local, metadata, Tailscale `100.64.0.0/10`, multicast, documentation and reserved address ranges are denied. IPv6 is restricted to public global unicast and excludes transition and special ranges. TLS bytes pass through unchanged; the local fixture verifies the certificate and completes an HTTPS request through the tunnel.
+
+Limits are 8 KiB of request headers, 16 concurrent connections including unfinished headers, a 15-second connect deadline covering resolution and dialing, and 60 seconds of tunnel inactivity. Header intake also has a 15-second deadline. Traffic in either direction renews the idle deadline. The namespace relay has its own 16-connection bound. The host has no TCP proxy listener.
+
+The endpoint closes accepted and upstream sockets on cancellation, listener failure and explicit close. The Manager closes it on normal exit, stop and failed startup, and kills the exact init through its existing pidfd when the proxy fails. PID 1 exits if its relay fails. Socket cleanup and proof publication finish before Wait acknowledges exit. The private directory is mode 0700, the socket is mode 0600, and only the pinned socket is mounted read-only. Existing arbitrary socket imports and caller-supplied proxy environment entries remain forbidden.
+
+### Interfaces and files
+
+- `internal/runner/egress/policy.go`: `Policy{Provider string; Hosts []string}`, exact policy hashing, provider defaults and public-address validation.
+- `internal/runner/egress/proxy.go`: `Open(context.Context, string, Policy) (*Proxy, error)`, `Proxy.Close() error`, `Proxy.SocketPath() string`, failure notification through `Done()`, strict parsing and bounded tunnels.
+- `internal/runner/egress/{proxy,budget}_test.go`: owned TLS fixtures, injected resolver and dialer, parser, address, timeout, concurrency, lifecycle and policy tests; repository budget TestMain.
+- `internal/runner/provider/types.go`: typed `NetworkContract{Provider, AuthHost string}` and `Binding.DedicatedHome`, false by default.
+- `internal/runner/containment/egress.go`: trusted contract selection, endpoint creation, pinned socket mount, fixed proxy environment and namespace relay.
+- `internal/runner/containment/egress_test.go`: real namespace host-service controls, endpoint lifetime, mount protection, installed contract, staged-home and failed-startup tests.
+- `internal/runner/containment/linux.go`: immutable installed contracts, proxy lifecycle and failure handling, relay startup and concurrent child reaping.
+- `internal/runner/containment/mounts.go`: retained per-attempt proxy ownership alongside the mount plan.
+- `internal/runner/containment/recovery.go`: additive `Record.EgressHash`, included in the existing durable record and exact-record comparison.
+- `cmd/equipo-runner/namespace.go`: documents the command wrapper's relay ownership through `containment.NamespaceMain`.
+- This section in `docs/superpowers/plans/CONTROLLER-REPORT-plan-2b.md`; the requested local report under `.superpowers/sdd/2026-11-03-equipo-plan-2b-direct/task-3-report.md`.
+
+### Interpretations
+
+1. The string argument to `egress.Open` is an existing private directory. It creates `proxy.sock` there and refuses to replace an existing socket. Containment creates a separate directory inside each durable attempt directory. Callers must keep paths within Linux's Unix socket path limit; these tests use the short on-disk TMPDIR requested by the controller.
+2. Task 2's reusable helper lives in `containment.NamespaceMain`, with the command wrapper in `cmd/equipo-runner/namespace.go`. The implementation extends that shared helper, keeping tests on the production implementation. The extra containment file keeps the socket import and relay separate from general mount handling.
+3. Provider names follow Task 1: `claude` starts with `api.anthropic.com`; `codex` starts with `chatgpt.com`. `Config.ProviderNetworks` accepts typed installed contracts, copies them at construction and rejects duplicates. No auth host is supplied by default. Only a dedicated, staged home may use an explicit contract auth host. Shared homes exclude it. Task 4 must establish `DedicatedHome` from verified home provenance; Task 11b must certify each actual auth hostname before installing it. Tests use only `refresh.example` and do not create credential homes.
+4. The exact sorted host set and provider are hashed with SHA-256 and saved as `Record.EgressHash`. The caller's existing `ManifestHash` is preserved. Later manifest/preflight work can bind this network hash into its effective-policy evidence; this task does not invent a provider attestation.
+5. Launches with no selected provider retain their disconnected network namespace and receive no proxy. Unknown selected providers fail closed. There is no permission-answer input to the installed network contract, relay address or socket path.
+6. Resolver, dialer and shortened deadline injection are unexported package implementation parameters, used only by local tests. Production `Open` always uses the real public-address validator and fixed limits. The TLS test presents a public DNS answer to that validator, then its private test dialer connects to its owned loopback TLS server. Neither configuration nor model input can select these dependencies.
+7. The shared-network positive controls connect to test-owned loopback TCP and abstract Unix listeners from the test process's host network namespace. The final launch fails both connections. Removing only `--unshare-net` makes both controls reachable from the same launch. No test or mutation contacts a provider or the real Internet.
+8. The task's explicit instructions override generic writing/delegation workflows: no copy-review skill or server, no subagents and no model calls. The report is written directly. `.superpowers/` is already ignored by the repository; the local task report stays there, and the full evidence is committed in the controller report.
+
+### RED and GREEN evidence
+
+All commands ran from `/home/paulca/amadan.net/oficina/equipo-plan-2b`, with `CGO_ENABLED=0`, the existing on-disk TMPDIR and default Go caches. No full suite, `make ci`, live gate, credential operation or provider prompt ran.
+
+Tests were written before implementation. Initial RED:
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/egress ./internal/runner/containment -run 'TestEgress|TestNamespaceHidesHostControl' -count=1
+```
+
+```text
+amadan.net/oficina/equipo/internal/runner/egress: no non-test Go files in /home/paulca/amadan.net/oficina/equipo-plan-2b/internal/runner/egress
+# amadan.net/oficina/equipo/internal/runner/egress [amadan.net/oficina/equipo/internal/runner/egress.test]
+internal/runner/egress/proxy_test.go:31:116: undefined: Proxy
+internal/runner/egress/proxy_test.go:33:7: undefined: defaults
+internal/runner/egress/proxy_test.go:36:12: undefined: open
+internal/runner/egress/proxy_test.go:36:49: undefined: Policy
+internal/runner/egress/proxy_test.go:41:30: undefined: Proxy
+internal/runner/egress/proxy_test.go:70:5: undefined: defaults
+internal/runner/egress/proxy_test.go:71:7: undefined: open
+internal/runner/egress/proxy_test.go:71:44: undefined: Policy
+internal/runner/egress/proxy_test.go:79:5: undefined: defaults
+internal/runner/egress/proxy_test.go:89:7: undefined: open
+internal/runner/egress/proxy_test.go:89:7: too many errors
+FAIL amadan.net/oficina/equipo/internal/runner/egress [build failed]
+FAIL amadan.net/oficina/equipo/internal/runner/containment [build failed]
+FAIL
+```
+
+The first implementation run exposed a fixture setup error: the TLS client had trusted roots but no ServerName. The fixture now supplies `127.0.0.1`, verifies the owned certificate, and retains end-to-end TLS. No production check was weakened.
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/egress ./internal/runner/containment -run 'TestEgress|TestNamespaceHidesHostControl' -count=1
+```
+
+```text
+2026/11/03 11:49:52 http: TLS handshake error from 127.0.0.1:52548: EOF
+--- FAIL: TestEgressAllowsOnlyProviderTLS (0.00s)
+ proxy_test.go:144: tls: either ServerName or InsecureSkipVerify must be specified in the tls.Config
+FAIL
+rastrillo-budget/v1 ran 3.198s
+FAIL amadan.net/oficina/equipo/internal/runner/egress 3.214s
+ok amadan.net/oficina/equipo/internal/runner/containment 1.315s
+FAIL
+```
+
+The corrected fixture and initial implementation passed the exact brief command:
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/egress ./internal/runner/containment -run 'TestEgress|TestNamespaceHidesHostControl' -count=1
+```
+
+```text
+ok amadan.net/oficina/equipo/internal/runner/egress 3.201s
+ok amadan.net/oficina/equipo/internal/runner/containment 0.864s
+```
+
+A later failing test showed that setting the dedicated-home flag without a staged home could qualify for refresh. The guard was added after this RED:
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/egress ./internal/runner/containment -run 'TestEgressActiveTunnelClose|TestEgressPolicyFrozen|TestEgressHeaderTimeout|TestEgressInstalledContract|TestEgressRefreshRequiresStagedHome' -count=1
+```
+
+```text
+ok amadan.net/oficina/equipo/internal/runner/egress 0.087s
+--- FAIL: TestEgressRefreshRequiresStagedHome (0.06s)
+ egress_test.go:220: unstaged home qualified for refresh
+FAIL
+rastrillo-budget/v1 ran 68ms
+FAIL amadan.net/oficina/equipo/internal/runner/containment 0.071s
+FAIL
+```
+
+GREEN after requiring a staged home and strengthening read-only socket checks:
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/egress ./internal/runner/containment -run 'TestEgress|TestNamespaceHidesHostControl' -count=1
+```
+
+```text
+ok amadan.net/oficina/equipo/internal/runner/egress 3.263s
+ok amadan.net/oficina/equipo/internal/runner/containment 0.550s
+```
+
+Additional lifecycle and parser checks passed before their mutations:
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/egress ./internal/runner/containment -run 'TestEgressDiesWithAttempt|TestEgressActiveTunnelClose|TestEgressStartupFailureClosesProxy' -count=1
+```
+
+```text
+ok amadan.net/oficina/equipo/internal/runner/egress 0.004s
+ok amadan.net/oficina/equipo/internal/runner/containment 0.516s
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/egress -run 'TestEgressRejectsSmuggling|TestEgressRejectsHostServices/resolver_error' -count=1
+```
+
+```text
+ok amadan.net/oficina/equipo/internal/runner/egress 3.005s
+```
+
+Final GREEN after restoring all mutations, including the helper regression checks:
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/egress ./internal/runner/containment -run 'TestEgress|TestNamespaceHidesHostControl|TestNamespaceReapsOrphans|TestNamespaceHelperProtocolPrivate|TestNamespaceHelperBarrier|TestNamespaceExitStatus|TestNamespaceCancellation|TestNamespaceStartupFailure|TestNamespaceSocketImport|TestNamespacePinnedMountSwap|TestNamespaceKillsDetachedChildren|TestNamespaceNestedUserNamespace' -count=1
+```
+
+```text
+ok amadan.net/oficina/equipo/internal/runner/egress 3.268s
+ok amadan.net/oficina/equipo/internal/runner/containment 1.236s
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/provider ./cmd/equipo-runner -run 'TestDirect|TestToolVerbClosed|TestRunnerServiceVerbs|TestRunnerDiagnosticIsCredentialFree' -count=1
+```
+
+```text
+ok amadan.net/oficina/equipo/internal/runner/provider 0.007s
+ok amadan.net/oficina/equipo/cmd/equipo-runner 0.060s
+```
+
+```sh
+CGO_ENABLED=0 go vet ./internal/runner/egress ./internal/runner/containment ./internal/runner/provider ./cmd/equipo-runner
+```
+
+```text
+Exit 0, no output.
+```
+
+```sh
+CGO_ENABLED=0 go run honnef.co/go/tools/cmd/staticcheck@v0.7.0 ./internal/runner/egress ./internal/runner/containment ./internal/runner/provider ./cmd/equipo-runner
+```
+
+```text
+Exit 0, no output.
+```
+
+```sh
+CGO_ENABLED=0 go build -o /home/paulca/t/e2b/t3-evidence/equipo-runner ./cmd/equipo-runner
+```
+
+```text
+Exit 0, no output.
+```
+
+`git diff --check` and `gofmt -l` on every changed Go file both produced no output. The build artifact was confined to owned on-disk scratch.
+
+### Independent guard mutations
+
+Each mutation below was applied alone to green production source, compiled, produced the named failing test and was restored in a `finally` block before the next mutation. All 37 exited 1 with a named test failure; none failed to compile. The patch and command identify each mutation. Diff indentation is rendered with spaces for the report. Output excerpts retain failure diagnostics; the network-isolation failure also printed `HOST REACHABLE` for both owned controls.
+
+#### 1. network-unsharing
+
+```diff
+--- internal/runner/containment/linux.go
++++ internal/runner/containment/linux.go
+@@ -241,7 +241,7 @@
+ result <- startResult{err: e}
+ return
+ }
+- args := []string{"--unshare-user", "--unshare-pid", "--unshare-ipc", "--unshare-uts", "--unshare-cgroup", "--unshare-net", "--die-with-parent", "--new-session", "--as-pid-1", "--cap-drop", "ALL", "--json-status-fd", "3"}
++ args := []string{"--unshare-user", "--unshare-pid", "--unshare-ipc", "--unshare-uts", "--unshare-cgroup", "--die-with-parent", "--new-session", "--as-pid-1", "--cap-drop", "ALL", "--json-status-fd", "3"}
+ args = append(args, mounts.args...)
+ args = append(args, "--", "/equipo-namespace", "__namespace")
+ if mounts.proxy != nil {
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/containment -run '^TestEgressRejectsHostServices$' -count=1 -timeout=25s
+```
+
+```text
+--- FAIL: TestEgressRejectsHostServices (0.17s)
+FAIL
+rastrillo-budget/v1 ran 173ms
+FAIL amadan.net/oficina/equipo/internal/runner/containment 0.192s
+FAIL
+```
+
+#### 2. exact-host
+
+```diff
+--- internal/runner/egress/proxy.go
++++ internal/runner/egress/proxy.go
+@@ -213,7 +213,7 @@
+ c.SetDeadline(time.Now().Add(p.deps.connect))
+ r := bufio.NewReaderSize(c, MaxHeaders+1)
+ host, e := authority(r)
+- if e != nil || !p.hosts[host] {
++ if e != nil || false {
+ io.WriteString(c, "HTTP/1.1 403 Forbidden\r\n\r\n")
+ return
+ }
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/egress -run '^TestEgressRejectsHostServices$' -count=1 -timeout=25s
+```
+
+```text
+--- FAIL: TestEgressRejectsHostServices (0.01s)
+ proxy_test.go:80: denied request reached dialer
+FAIL
+rastrillo-budget/v1 ran 13ms
+FAIL amadan.net/oficina/equipo/internal/runner/egress 0.028s
+FAIL
+```
+
+#### 3. public-address
+
+```diff
+--- internal/runner/egress/proxy.go
++++ internal/runner/egress/proxy.go
+@@ -226,7 +226,7 @@
+ }
+ // Reject the whole answer if any address is unsafe. Never resolve again in Dial.
+ for _, a := range addresses {
+- if !publicAddress(a) {
++ if false && !publicAddress(a) {
+ io.WriteString(c, "HTTP/1.1 403 Forbidden\r\n\r\n")
+ return
+ }
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/egress -run '^TestEgressRejectsHostServices$' -count=1 -timeout=25s
+```
+
+```text
+--- FAIL: TestEgressRejectsHostServices (0.01s)
+ --- FAIL: TestEgressRejectsHostServices/127.0.0.1 (0.00s)
+ proxy_test.go:88: nonpublic DNS answer reached dialer
+ --- FAIL: TestEgressRejectsHostServices/10.0.0.1 (0.00s)
+ proxy_test.go:88: nonpublic DNS answer reached dialer
+ --- FAIL: TestEgressRejectsHostServices/172.16.0.1 (0.00s)
+ proxy_test.go:88: nonpublic DNS answer reached dialer
+ --- FAIL: TestEgressRejectsHostServices/192.168.0.1 (0.00s)
+ proxy_test.go:88: nonpublic DNS answer reached dialer
+...
+FAIL
+rastrillo-budget/v1 ran 10ms
+FAIL amadan.net/oficina/equipo/internal/runner/egress 0.019s
+FAIL
+```
+
+#### 4. validated-dial
+
+```diff
+--- internal/runner/egress/proxy.go
++++ internal/runner/egress/proxy.go
+@@ -231,7 +231,7 @@
+ return
+ }
+ }
+- upstream, e := p.deps.dial(ctx, "tcp", net.JoinHostPort(addresses[0].Unmap().String(), "443"))
++ upstream, e := p.deps.dial(ctx, "tcp", net.JoinHostPort(host, "443"))
+ if e != nil {
+ io.WriteString(c, "HTTP/1.1 502 Bad Gateway\r\n\r\n")
+ return
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/egress -run '^TestEgressAllowsOnlyProviderTLS$' -count=1 -timeout=25s
+```
+
+```text
+--- FAIL: TestEgressAllowsOnlyProviderTLS (0.00s)
+ proxy_test.go:126: unvalidated dial: tcp fixture.example:443
+FAIL
+rastrillo-budget/v1 ran 5ms
+FAIL amadan.net/oficina/equipo/internal/runner/egress 0.010s
+FAIL
+```
+
+#### 5. port-443
+
+```diff
+--- internal/runner/egress/proxy.go
++++ internal/runner/egress/proxy.go
+@@ -181,7 +181,7 @@
+ return "", errPolicy
+ }
+ host, port, e := net.SplitHostPort(first[1])
+- if e != nil || port != "443" || !hostname(host) {
++ if e != nil || port == "" || !hostname(host) {
+ return "", errPolicy
+ }
+ seen := map[string]bool{}
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/egress -run '^TestEgressRejectsHostServices$' -count=1 -timeout=25s
+```
+
+```text
+--- FAIL: TestEgressRejectsHostServices (0.00s)
+ proxy_test.go:80: denied request reached dialer
+FAIL
+rastrillo-budget/v1 ran 2ms
+FAIL amadan.net/oficina/equipo/internal/runner/egress 0.009s
+FAIL
+```
+
+#### 6. connect-method
+
+```diff
+--- internal/runner/egress/proxy.go
++++ internal/runner/egress/proxy.go
+@@ -177,7 +177,7 @@
+ }
+ lines := strings.Split(string(data), "\r\n")
+ first := strings.Split(lines[0], " ")
+- if len(first) != 3 || first[0] != "CONNECT" || (first[2] != "HTTP/1.1" && first[2] != "HTTP/1.0") {
++ if len(first) != 3 || false || (first[2] != "HTTP/1.1" && first[2] != "HTTP/1.0") {
+ return "", errPolicy
+ }
+ host, port, e := net.SplitHostPort(first[1])
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/egress -run '^TestEgressRejectsSmuggling$' -count=1 -timeout=25s
+```
+
+```text
+--- FAIL: TestEgressRejectsSmuggling (3.00s)
+ --- FAIL: TestEgressRejectsSmuggling/case037 (0.00s)
+ proxy_test.go:179: smuggling reached dial: "POST fixture.example:443 HTTP/1.1\r\n\r\n"
+FAIL
+rastrillo-budget/v1 ran 3.003s
+FAIL amadan.net/oficina/equipo/internal/runner/egress 3.009s
+FAIL
+```
+
+#### 7. http-version
+
+```diff
+--- internal/runner/egress/proxy.go
++++ internal/runner/egress/proxy.go
+@@ -177,7 +177,7 @@
+ }
+ lines := strings.Split(string(data), "\r\n")
+ first := strings.Split(lines[0], " ")
+- if len(first) != 3 || first[0] != "CONNECT" || (first[2] != "HTTP/1.1" && first[2] != "HTTP/1.0") {
++ if len(first) != 3 || first[0] != "CONNECT" || false {
+ return "", errPolicy
+ }
+ host, port, e := net.SplitHostPort(first[1])
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/egress -run '^TestEgressRejectsSmuggling$' -count=1 -timeout=25s
+```
+
+```text
+--- FAIL: TestEgressRejectsSmuggling (3.00s)
+ --- FAIL: TestEgressRejectsSmuggling/case040 (0.00s)
+ proxy_test.go:179: smuggling reached dial: "CONNECT fixture.example:443 HTTP/2.0\r\n\r\n"
+FAIL
+rastrillo-budget/v1 ran 3.002s
+FAIL amadan.net/oficina/equipo/internal/runner/egress 3.005s
+FAIL
+```
+
+#### 8. queued-request
+
+```diff
+--- internal/runner/egress/proxy.go
++++ internal/runner/egress/proxy.go
+@@ -172,7 +172,7 @@
+ break
+ }
+ }
+- if !bytes.HasSuffix(data, []byte("\r\n\r\n")) || r.Buffered() != 0 {
++ if !bytes.HasSuffix(data, []byte("\r\n\r\n")) || false {
+ return "", errPolicy
+ }
+ lines := strings.Split(string(data), "\r\n")
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/egress -run '^TestEgressRejectsSmuggling$' -count=1 -timeout=25s
+```
+
+```text
+--- FAIL: TestEgressRejectsSmuggling (3.01s)
+ --- FAIL: TestEgressRejectsSmuggling/case085 (0.00s)
+ proxy_test.go:179: smuggling reached dial: "CONNECT fixture.example:443 HTTP/1.1\r\nHost: fixture.example:443\r\n\r\nGET / HTTP/1.1\r\n\r\n"
+FAIL
+rastrillo-budget/v1 ran 3.006s
+FAIL amadan.net/oficina/equipo/internal/runner/egress 3.009s
+FAIL
+```
+
+#### 9. framing-headers
+
+```diff
+--- internal/runner/egress/proxy.go
++++ internal/runner/egress/proxy.go
+@@ -199,7 +199,7 @@
+ }
+ case "user-agent", "proxy-connection", "connection":
+ default:
+- return "", errPolicy
++ continue
+ }
+ }
+ req, e := http.ReadRequest(bufio.NewReader(bytes.NewReader(data)))
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/egress -run '^TestEgressRejectsSmuggling$' -count=1 -timeout=25s
+```
+
+```text
+--- FAIL: TestEgressRejectsSmuggling (3.00s)
+ --- FAIL: TestEgressRejectsSmuggling/case059 (0.00s)
+ proxy_test.go:179: smuggling reached dial: "CONNECT fixture.example:443 HTTP/1.1\r\nContent-Length: 0\r\n\r\n"
+ --- FAIL: TestEgressRejectsSmuggling/case168 (0.00s)
+ proxy_test.go:179: smuggling reached dial: "CONNECT fixture.example:443 HTTP/1.1\r\nTransfer-Encoding: chunked\r\n\r\n"
+FAIL
+rastrillo-budget/v1 ran 3.004s
+FAIL amadan.net/oficina/equipo/internal/runner/egress 3.007s
+FAIL
+```
+
+#### 10. host-header
+
+```diff
+--- internal/runner/egress/proxy.go
++++ internal/runner/egress/proxy.go
+@@ -194,7 +194,7 @@
+ seen[key] = true
+ switch key {
+ case "host":
+- if strings.TrimSpace(value) != first[1] {
++ if false && strings.TrimSpace(value) != first[1] {
+ return "", errPolicy
+ }
+ case "user-agent", "proxy-connection", "connection":
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/egress -run '^TestEgressRejectsSmuggling$' -count=1 -timeout=25s
+```
+
+```text
+--- FAIL: TestEgressRejectsSmuggling (3.00s)
+ --- FAIL: TestEgressRejectsSmuggling/case065 (0.00s)
+ proxy_test.go:179: smuggling reached dial: "CONNECT fixture.example:443 HTTP/1.1\r\nHost: other.example:443\r\n\r\n"
+FAIL
+rastrillo-budget/v1 ran 3.004s
+FAIL amadan.net/oficina/equipo/internal/runner/egress 3.008s
+FAIL
+```
+
+#### 11. header-cap
+
+```diff
+--- internal/runner/egress/proxy.go
++++ internal/runner/egress/proxy.go
+@@ -162,7 +162,7 @@
+ // destination. Framing headers and queued requests are rejected before dialing.
+ func authority(r *bufio.Reader) (string, error) {
+ data := make([]byte, 0, MaxHeaders)
+- for len(data) < MaxHeaders {
++ for len(data) < MaxHeaders*2 {
+ b, e := r.ReadByte()
+ if e != nil {
+ return "", e
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/egress -run '^TestEgressLimits/headers$' -count=1 -timeout=25s
+```
+
+```text
+--- FAIL: TestEgressLimits (0.00s)
+ --- FAIL: TestEgressLimits/headers (0.00s)
+ proxy_test.go:231: oversized headers dialled
+FAIL
+rastrillo-budget/v1 ran 1ms
+FAIL amadan.net/oficina/equipo/internal/runner/egress 0.005s
+FAIL
+```
+
+#### 12. socket-cap
+
+```diff
+--- internal/runner/egress/proxy.go
++++ internal/runner/egress/proxy.go
+@@ -142,7 +142,7 @@
+ return
+ }
+ p.mu.Lock()
+- if p.closed || len(p.clients) >= MaxTunnels {
++ if p.closed || false {
+ p.mu.Unlock()
+ c.Close()
+ continue
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/egress -run '^TestEgressLimits/concurrent$' -count=1 -timeout=25s
+```
+
+```text
+--- FAIL: TestEgressLimits (1.01s)
+ --- FAIL: TestEgressLimits/concurrent (1.00s)
+ proxy_test.go:267: extra socket remained open
+FAIL
+rastrillo-budget/v1 ran 1.005s
+FAIL amadan.net/oficina/equipo/internal/runner/egress 1.010s
+FAIL
+```
+
+#### 13. connect-timeout
+
+```diff
+--- internal/runner/egress/proxy.go
++++ internal/runner/egress/proxy.go
+@@ -217,7 +217,7 @@
+ io.WriteString(c, "HTTP/1.1 403 Forbidden\r\n\r\n")
+ return
+ }
+- ctx, cancel := context.WithTimeout(p.ctx, p.deps.connect)
++ ctx, cancel := context.WithCancel(p.ctx)
+ defer cancel()
+ addresses, e := p.deps.lookup(ctx, host)
+ if e != nil || len(addresses) == 0 {
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/egress -run '^TestEgressLimits/connect$' -count=1 -timeout=25s
+```
+
+```text
+--- FAIL: TestEgressLimits (3.00s)
+ --- FAIL: TestEgressLimits/connect (3.00s)
+ proxy_test.go:315: connect timeout missing
+FAIL
+rastrillo-budget/v1 ran 3.001s
+FAIL amadan.net/oficina/equipo/internal/runner/egress 3.011s
+FAIL
+```
+
+#### 14. header-timeout
+
+```diff
+--- internal/runner/egress/proxy.go
++++ internal/runner/egress/proxy.go
+@@ -210,7 +210,7 @@
+ return host, nil
+ }
+ func (p *Proxy) handle(c net.Conn) {
+- c.SetDeadline(time.Now().Add(p.deps.connect))
++ c.SetDeadline(time.Time{})
+ r := bufio.NewReaderSize(c, MaxHeaders+1)
+ host, e := authority(r)
+ if e != nil || !p.hosts[host] {
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/egress -run '^TestEgressHeaderTimeout$' -count=1 -timeout=25s
+```
+
+```text
+--- FAIL: TestEgressHeaderTimeout (1.00s)
+ proxy_test.go:469: incomplete header kept socket open
+FAIL
+rastrillo-budget/v1 ran 1.001s
+FAIL amadan.net/oficina/equipo/internal/runner/egress 1.006s
+FAIL
+```
+
+#### 15. idle-timeout
+
+```diff
+--- internal/runner/egress/proxy.go
++++ internal/runner/egress/proxy.go
+@@ -254,7 +254,7 @@
+ // Tunnel copies opaque TLS bytes. Traffic in either direction renews the idle
+ // deadline for both sockets; closing either side releases both copying goroutines.
+ func Tunnel(a, b net.Conn, idle time.Duration) {
+- touch := func() { deadline := time.Now().Add(idle); a.SetDeadline(deadline); b.SetDeadline(deadline) }
++ touch := func() { deadline := time.Now().Add(time.Hour); a.SetDeadline(deadline); b.SetDeadline(deadline) }
+ touch()
+ copyTo := func(dst, src net.Conn) {
+ buffer := make([]byte, 32*1024)
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/egress -run '^TestEgressLimits/idle$' -count=1 -timeout=25s
+```
+
+```text
+--- FAIL: TestEgressLimits (1.00s)
+ --- FAIL: TestEgressLimits/idle (1.00s)
+ proxy_test.go:297: idle tunnel not closed
+FAIL
+rastrillo-budget/v1 ran 1.001s
+FAIL amadan.net/oficina/equipo/internal/runner/egress 1.008s
+FAIL
+```
+
+#### 16. private-directory
+
+```diff
+--- internal/runner/egress/proxy.go
++++ internal/runner/egress/proxy.go
+@@ -83,7 +83,7 @@
+ if e = unix.Fstat(fd, &st); e != nil {
+ return nil, e
+ }
+- if st.Mode&0777 != 0700 || st.Uid != uint32(os.Geteuid()) {
++ if false || st.Uid != uint32(os.Geteuid()) {
+ return nil, errPolicy
+ }
+ path := filepath.Join(dir, "proxy.sock")
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/egress -run '^TestEgressPrivateSocket$' -count=1 -timeout=25s
+```
+
+```text
+--- FAIL: TestEgressPrivateSocket (0.00s)
+ proxy_test.go:371: nonprivate directory accepted
+FAIL
+rastrillo-budget/v1 ran 1ms
+FAIL amadan.net/oficina/equipo/internal/runner/egress 0.003s
+FAIL
+```
+
+#### 17. symlink-directory
+
+```diff
+--- internal/runner/egress/proxy.go
++++ internal/runner/egress/proxy.go
+@@ -74,7 +74,7 @@
+ if !filepath.IsAbs(dir) || filepath.Clean(dir) != dir {
+ return nil, errPolicy
+ }
+- fd, e := unix.Openat2(unix.AT_FDCWD, dir, &unix.OpenHow{Flags: unix.O_PATH | unix.O_DIRECTORY | unix.O_CLOEXEC, Resolve: unix.RESOLVE_NO_SYMLINKS | unix.RESOLVE_NO_MAGICLINKS})
++ fd, e := unix.Openat2(unix.AT_FDCWD, dir, &unix.OpenHow{Flags: unix.O_PATH | unix.O_DIRECTORY | unix.O_CLOEXEC, Resolve: 0})
+ if e != nil {
+ return nil, e
+ }
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/egress -run '^TestEgressPrivateSocket$' -count=1 -timeout=25s
+```
+
+```text
+--- FAIL: TestEgressPrivateSocket (0.00s)
+ proxy_test.go:377: symlink directory accepted
+FAIL
+rastrillo-budget/v1 ran 1ms
+FAIL amadan.net/oficina/equipo/internal/runner/egress 0.003s
+FAIL
+```
+
+#### 18. private-socket
+
+```diff
+--- internal/runner/egress/proxy.go
++++ internal/runner/egress/proxy.go
+@@ -91,7 +91,7 @@
+ if e != nil {
+ return nil, e
+ }
+- if e = os.Chmod(path, 0600); e != nil {
++ if e = os.Chmod(path, 0666); e != nil {
+ ln.Close()
+ return nil, e
+ }
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/egress -run '^TestEgressPrivateSocket$' -count=1 -timeout=25s
+```
+
+```text
+--- FAIL: TestEgressPrivateSocket (0.00s)
+ proxy_test.go:362: socket mode: &{proxy.sock 0 16777654 {200480172 63929303677 0xb493a0} {66306 45383338 1 49590 1001 1001 0 0 0 4096 0 {1793706877 200480172} {1793706877 200480172} {1793706877 200480172} [0 0 0]}} <nil>
+FAIL
+rastrillo-budget/v1 ran 1ms
+FAIL amadan.net/oficina/equipo/internal/runner/egress 0.003s
+FAIL
+```
+
+#### 19. dedicated-refresh
+
+```diff
+--- internal/runner/egress/policy.go
++++ internal/runner/egress/policy.go
+@@ -36,7 +36,7 @@
+ if !hostname(c.AuthHost) {
+ return Policy{}, errPolicy
+ }
+- if dedicated && c.AuthHost != p.Hosts[0] {
++ if c.AuthHost != p.Hosts[0] {
+ p.Hosts = append(p.Hosts, c.AuthHost)
+ }
+ }
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/egress -run '^TestEgressPolicy$' -count=1 -timeout=25s
+```
+
+```text
+--- FAIL: TestEgressPolicy (0.00s)
+ proxy_test.go:332: shared home got refresh
+FAIL
+rastrillo-budget/v1 ran 0s
+FAIL amadan.net/oficina/equipo/internal/runner/egress 0.003s
+FAIL
+```
+
+#### 20. policy-provider-hash
+
+```diff
+--- internal/runner/egress/policy.go
++++ internal/runner/egress/policy.go
+@@ -75,7 +75,7 @@
+ return "", errPolicy
+ }
+ }
+- b, _ := json.Marshal(Policy{Provider: p.Provider, Hosts: hosts})
++ b, _ := json.Marshal(Policy{Hosts: hosts})
+ hash := sha256.Sum256(b)
+ return hex.EncodeToString(hash[:]), nil
+ }
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/egress -run '^TestEgressPolicy$' -count=1 -timeout=25s
+```
+
+```text
+--- FAIL: TestEgressPolicy (0.00s)
+ proxy_test.go:349: policy hash does not bind exact host set and provider
+FAIL
+rastrillo-budget/v1 ran 0s
+FAIL amadan.net/oficina/equipo/internal/runner/egress 0.003s
+FAIL
+```
+
+#### 21. policy-host-hash
+
+```diff
+--- internal/runner/egress/policy.go
++++ internal/runner/egress/policy.go
+@@ -75,7 +75,7 @@
+ return "", errPolicy
+ }
+ }
+- b, _ := json.Marshal(Policy{Provider: p.Provider, Hosts: hosts})
++ b, _ := json.Marshal(Policy{Provider: p.Provider})
+ hash := sha256.Sum256(b)
+ return hex.EncodeToString(hash[:]), nil
+ }
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/egress -run '^TestEgressPolicy$' -count=1 -timeout=25s
+```
+
+```text
+--- FAIL: TestEgressPolicy (0.00s)
+ proxy_test.go:349: policy hash does not bind exact host set and provider
+FAIL
+rastrillo-budget/v1 ran 0s
+FAIL amadan.net/oficina/equipo/internal/runner/egress 0.003s
+FAIL
+```
+
+#### 22. policy-duplicates
+
+```diff
+--- internal/runner/egress/policy.go
++++ internal/runner/egress/policy.go
+@@ -71,7 +71,7 @@
+ hosts := append([]string(nil), p.Hosts...)
+ sort.Strings(hosts)
+ for i, h := range hosts {
+- if !hostname(h) || (i > 0 && h == hosts[i-1]) {
++ if !hostname(h) || (false && i > 0 && h == hosts[i-1]) {
+ return "", errPolicy
+ }
+ }
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/egress -run '^TestEgressPolicy$' -count=1 -timeout=25s
+```
+
+```text
+--- FAIL: TestEgressPolicy (0.00s)
+ proxy_test.go:341: invalid policy accepted: {Provider:claude Hosts:[fixture.example fixture.example]}
+FAIL
+rastrillo-budget/v1 ran 0s
+FAIL amadan.net/oficina/equipo/internal/runner/egress 0.002s
+FAIL
+```
+
+#### 23. contract-duplicates
+
+```diff
+--- internal/runner/containment/linux.go
++++ internal/runner/containment/linux.go
+@@ -96,7 +96,7 @@
+ }
+ seen := map[string]bool{}
+ for _, c := range cfg.ProviderNetworks {
+- if seen[c.Provider] {
++ if false && seen[c.Provider] {
+ return nil, errStartup
+ }
+ if _, e := egress.ProviderPolicy(c, true); e != nil {
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/containment -run '^TestEgressInstalledContract$' -count=1 -timeout=25s
+```
+
+```text
+--- FAIL: TestEgressInstalledContract (0.01s)
+ egress_test.go:204: invalid installed contracts accepted: [{Provider:claude AuthHost:} {Provider:claude AuthHost:refresh.example}]
+FAIL
+rastrillo-budget/v1 ran 6ms
+FAIL amadan.net/oficina/equipo/internal/runner/containment 0.010s
+FAIL
+```
+
+#### 24. contract-freeze
+
+```diff
+--- internal/runner/containment/linux.go
++++ internal/runner/containment/linux.go
+@@ -104,7 +104,7 @@
+ }
+ seen[c.Provider] = true
+ }
+- cfg.ProviderNetworks = append([]provider.NetworkContract(nil), cfg.ProviderNetworks...)
++ cfg.ProviderNetworks = cfg.ProviderNetworks
+ return &Manager{cfg: cfg, processes: make(map[string]*process)}, nil
+ }
+ func (m *Manager) Start(ctx context.Context, l provider.Launch, argv []string) (provider.Process, error) {
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/containment -run '^TestEgressInstalledContract$' -count=1 -timeout=25s
+```
+
+```text
+--- FAIL: TestEgressInstalledContract (0.01s)
+ egress_test.go:216: installed contract changed after New
+FAIL
+rastrillo-budget/v1 ran 8ms
+FAIL amadan.net/oficina/equipo/internal/runner/containment 0.011s
+FAIL
+```
+
+#### 25. staged-home
+
+```diff
+--- internal/runner/containment/egress.go
++++ internal/runner/containment/egress.go
+@@ -17,7 +17,7 @@
+ if l.Selection.Provider == "" {
+ return "", nil
+ }
+- if l.Binding.DedicatedHome && l.Binding.Home == "" {
++ if false && l.Binding.DedicatedHome && l.Binding.Home == "" {
+ return "", errMount
+ }
+ contract := provider.NetworkContract{Provider: l.Selection.Provider}
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/containment -run '^TestEgressRefreshRequiresStagedHome$' -count=1 -timeout=25s
+```
+
+```text
+--- FAIL: TestEgressRefreshRequiresStagedHome (0.10s)
+ egress_test.go:225: unstaged home qualified for refresh
+FAIL
+rastrillo-budget/v1 ran 102ms
+FAIL amadan.net/oficina/equipo/internal/runner/containment 0.106s
+FAIL
+```
+
+#### 26. socket-readonly
+
+```diff
+--- internal/runner/containment/egress.go
++++ internal/runner/containment/egress.go
+@@ -59,7 +59,7 @@
+ }
+ // This is the sole socket import. The parent directory and other host sockets
+ // remain absent; the retained O_PATH descriptor pins this exact endpoint.
+- p.args = append(p.args, "--ro-bind-fd", strconv.Itoa(6+len(p.files)), egress.NamespaceSocket)
++ p.args = append(p.args, "--bind-fd", strconv.Itoa(6+len(p.files)), egress.NamespaceSocket)
+ p.files = append(p.files, f)
+ for _, key := range []string{"HTTPS_PROXY", "HTTP_PROXY", "https_proxy", "http_proxy"} {
+ p.args = append(p.args, "--setenv", key, egress.ProxyURL)
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/containment -run '^TestEgressRejectsHostServices$' -count=1 -timeout=25s
+```
+
+```text
+--- FAIL: TestEgressRejectsHostServices (0.14s)
+FAIL
+rastrillo-budget/v1 ran 138ms
+FAIL amadan.net/oficina/equipo/internal/runner/containment 0.142s
+FAIL
+```
+
+#### 27. durable-host-hash
+
+```diff
+--- internal/runner/containment/linux.go
++++ internal/runner/containment/linux.go
+@@ -140,6 +140,7 @@
+ return nil, e
+ }
+ egressHash, e := m.openEgress(ctx, l, dir, mounts)
++ _ = egressHash
+ if e != nil {
+ mounts.close()
+ return nil, e
+@@ -155,7 +156,7 @@
+ mounts.close()
+ return nil, e
+ }
+- r := Record{ID: id, AttemptKey: l.AttemptKey, BootID: boot, ManifestHash: l.Policy.Hash, EgressHash: egressHash}
++ r := Record{ID: id, AttemptKey: l.AttemptKey, BootID: boot, ManifestHash: l.Policy.Hash, EgressHash: ""}
+ if e = m.persist(r); e != nil {
+ mounts.close()
+ return nil, e
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/containment -run '^TestEgressMountPolicy$' -count=1 -timeout=25s
+```
+
+```text
+--- FAIL: TestEgressMountPolicy (0.11s)
+ egress_test.go:190: missing exact host-policy hash: "" want "394fd26429f90b51179904566a234b2ab48d63341e623f85f1a80c6d0d9220c5"
+FAIL
+rastrillo-budget/v1 ran 110ms
+FAIL amadan.net/oficina/equipo/internal/runner/containment 0.114s
+FAIL
+```
+
+#### 28. proxy-failure-stops
+
+```diff
+--- internal/runner/containment/linux.go
++++ internal/runner/containment/linux.go
+@@ -360,7 +360,7 @@
+ case <-ctx.Done():
+ p.kill()
+ case <-proxyDone:
+- p.kill()
++ // mutation: no stop
+ case <-lifecycleDone:
+ }
+ }()
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/containment -run '^TestEgressDiesWithAttempt/proxy_failure$' -count=1 -timeout=25s
+```
+
+```text
+--- FAIL: TestEgressDiesWithAttempt (3.14s)
+ --- FAIL: TestEgressDiesWithAttempt/proxy_failure (3.14s)
+ egress_test.go:142: context deadline exceeded
+FAIL
+rastrillo-budget/v1 ran 3.137s
+FAIL amadan.net/oficina/equipo/internal/runner/containment 3.146s
+FAIL
+```
+
+#### 29. close-on-stop
+
+```diff
+--- internal/runner/containment/linux.go
++++ internal/runner/containment/linux.go
+@@ -196,7 +196,7 @@
+ }()
+ defer mounts.close()
+ if mounts.proxy != nil {
+- defer mounts.proxy.Close()
++ // mutation: no deferred proxy close
+ }
+ var files []*os.File
+ pipe := func() (*os.File, *os.File, error) {
+@@ -397,7 +397,7 @@
+ }
+ }
+ if p.egress != nil {
+- p.egress.Close()
++ // mutation: no proxy close on stop
+ }
+ var cleanupErr error
+ p.proof, cleanupErr = m.finishRecovery(p.proof)
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/containment -run '^TestEgressDiesWithAttempt/stop$' -count=1 -timeout=25s
+```
+
+```text
+--- FAIL: TestEgressDiesWithAttempt (0.16s)
+ --- FAIL: TestEgressDiesWithAttempt/stop (0.16s)
+ egress_test.go:151: proxy outlived attempt
+FAIL
+rastrillo-budget/v1 ran 164ms
+FAIL amadan.net/oficina/equipo/internal/runner/containment 0.170s
+FAIL
+```
+
+#### 30. duplicate-header
+
+```diff
+--- internal/runner/egress/proxy.go
++++ internal/runner/egress/proxy.go
+@@ -188,7 +188,7 @@
+ for _, line := range lines[1 : len(lines)-2] {
+ key, value, ok := strings.Cut(line, ":")
+ key = strings.ToLower(key)
+- if !ok || seen[key] {
++ if !ok || false {
+ return "", errPolicy
+ }
+ seen[key] = true
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/egress -run '^TestEgressRejectsSmuggling$' -count=1 -timeout=25s
+```
+
+```text
+--- FAIL: TestEgressRejectsSmuggling (3.00s)
+ --- FAIL: TestEgressRejectsSmuggling/case070 (0.00s)
+ proxy_test.go:182: smuggling reached dial: "CONNECT fixture.example:443 HTTP/1.1\r\nUser-Agent: a\r\nUser-Agent: b\r\n\r\n"
+FAIL
+rastrillo-budget/v1 ran 3.002s
+FAIL amadan.net/oficina/equipo/internal/runner/egress 3.004s
+FAIL
+```
+
+#### 31. resolver-error
+
+```diff
+--- internal/runner/egress/proxy.go
++++ internal/runner/egress/proxy.go
+@@ -220,7 +220,7 @@
+ ctx, cancel := context.WithTimeout(p.ctx, p.deps.connect)
+ defer cancel()
+ addresses, e := p.deps.lookup(ctx, host)
+- if e != nil || len(addresses) == 0 {
++ if false || len(addresses) == 0 {
+ io.WriteString(c, "HTTP/1.1 502 Bad Gateway\r\n\r\n")
+ return
+ }
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/egress -run '^TestEgressRejectsHostServices/resolver_error$' -count=1 -timeout=25s
+```
+
+```text
+--- FAIL: TestEgressRejectsHostServices (0.00s)
+ --- FAIL: TestEgressRejectsHostServices/resolver_error (0.00s)
+ proxy_test.go:106: DNS error dialled
+FAIL
+rastrillo-budget/v1 ran 1ms
+FAIL amadan.net/oficina/equipo/internal/runner/egress 0.003s
+FAIL
+```
+
+#### 32. context-closes
+
+```diff
+--- internal/runner/egress/proxy.go
++++ internal/runner/egress/proxy.go
+@@ -105,7 +105,7 @@
+ go func() {
+ select {
+ case <-ctx.Done():
+- p.shutdown()
++ // mutation: ignore cancellation
+ case <-p.done:
+ }
+ }()
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/egress -run '^TestEgressDiesWithAttempt$' -count=1 -timeout=25s
+```
+
+```text
+--- FAIL: TestEgressDiesWithAttempt (1.00s)
+ proxy_test.go:220: proxy outlived context
+FAIL
+rastrillo-budget/v1 ran 1.001s
+FAIL amadan.net/oficina/equipo/internal/runner/egress 1.003s
+FAIL
+```
+
+#### 33. listener-failure
+
+```diff
+--- internal/runner/egress/proxy.go
++++ internal/runner/egress/proxy.go
+@@ -135,7 +135,7 @@
+ func (p *Proxy) active() int { p.mu.Lock(); defer p.mu.Unlock(); return len(p.clients) }
+ func (p *Proxy) serve() {
+ defer p.wg.Done()
+- defer p.shutdown()
++ // mutation: no shutdown on listener failure
+ for {
+ c, e := p.listener.Accept()
+ if e != nil {
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/egress -run '^TestEgressActiveTunnelClose/listener_failure$' -count=1 -timeout=25s
+```
+
+```text
+--- FAIL: TestEgressActiveTunnelClose (1.00s)
+ --- FAIL: TestEgressActiveTunnelClose/listener_failure (1.00s)
+ proxy_test.go:432: proxy failure not reported
+FAIL
+rastrillo-budget/v1 ran 1.001s
+FAIL amadan.net/oficina/equipo/internal/runner/egress 1.003s
+FAIL
+```
+
+#### 34. active-socket-close
+
+```diff
+--- internal/runner/egress/proxy.go
++++ internal/runner/egress/proxy.go
+@@ -121,12 +121,7 @@
+ p.closed = true
+ p.cancel()
+ p.listener.Close()
+- for c := range p.clients {
+- c.Close()
+- }
+- for c := range p.upstreams {
+- c.Close()
+- }
++ // mutation: retain active sockets
+ p.mu.Unlock()
+ close(p.done)
+ })
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/egress -run '^TestEgressActiveTunnelClose/close$' -count=1 -timeout=25s
+```
+
+```text
+--- FAIL: TestEgressActiveTunnelClose (1.00s)
+ --- FAIL: TestEgressActiveTunnelClose/close (1.00s)
+ proxy_test.go:423: proxy close did not interrupt sockets
+FAIL
+rastrillo-budget/v1 ran 1.001s
+FAIL amadan.net/oficina/equipo/internal/runner/egress 1.003s
+FAIL
+```
+
+#### 35. startup-proxy-close
+
+```diff
+--- internal/runner/containment/linux.go
++++ internal/runner/containment/linux.go
+@@ -196,7 +196,7 @@
+ }()
+ defer mounts.close()
+ if mounts.proxy != nil {
+- defer mounts.proxy.Close()
++ // mutation: no close on failed startup
+ }
+ var files []*os.File
+ pipe := func() (*os.File, *os.File, error) {
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/containment -run '^TestEgressStartupFailureClosesProxy$' -count=1 -timeout=25s
+```
+
+```text
+--- FAIL: TestEgressStartupFailureClosesProxy (0.03s)
+ egress_test.go:252: startup failure leaked sockets: before=0 after=1
+FAIL
+rastrillo-budget/v1 ran 28ms
+FAIL amadan.net/oficina/equipo/internal/runner/containment 0.030s
+FAIL
+```
+
+#### 36. fixed-unix-endpoint
+
+```diff
+--- internal/runner/containment/egress.go
++++ internal/runner/containment/egress.go
+@@ -128,7 +128,7 @@
+ go func() {
+ defer r.wg.Done()
+ defer func() { <-slots; r.remove(c) }()
+- upstream, e := net.DialTimeout("unix", egress.NamespaceSocket, egress.ConnectTimeout)
++ upstream, e := net.DialTimeout("unix", "/egress/other.sock", egress.ConnectTimeout)
+ if e != nil {
+ r.shutdown()
+ return
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/containment -run '^TestEgressRejectsHostServices$' -count=1 -timeout=25s
+```
+
+```text
+--- FAIL: TestEgressRejectsHostServices (0.10s)
+ egress_test.go:91: isolation/relay: "blocked\nblocked\n" exit={Code:-1 Signal:0 ObservedAt:2026-11-03 11:59:00.793600523 +0000 UTC} err=<nil> stderr=
+FAIL
+rastrillo-budget/v1 ran 98ms
+FAIL amadan.net/oficina/equipo/internal/runner/containment 0.100s
+FAIL
+```
+
+#### 37. fixed-loopback
+
+```diff
+--- internal/runner/containment/egress.go
++++ internal/runner/containment/egress.go
+@@ -82,7 +82,7 @@
+ }
+
+ func startRelay() (*namespaceRelay, error) {
+- ln, e := net.Listen("tcp4", egress.RelayAddress)
++ ln, e := net.Listen("tcp4", "127.0.0.2:18080")
+ if e != nil {
+ return nil, e
+ }
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/containment -run '^TestEgressRejectsHostServices$' -count=1 -timeout=25s
+```
+
+```text
+--- FAIL: TestEgressRejectsHostServices (0.10s)
+ egress_test.go:91: isolation/relay: "blocked\nblocked\n" exit={Code:1 Signal:0 ObservedAt:2026-11-03 11:59:01.262723234 +0000 UTC} err=<nil> stderr=Traceback (most recent call last):
+ File "<string>", line 10, in <module>
+ s=socket.create_connection(('127.0.0.1',18080),1)
+ File "/usr/lib/python3.13/socket.py", line 864, in create_connection
+ raise exceptions[0]
+ File "/usr/lib/python3.13/socket.py", line 849, in create_connection
+ sock.connect(sa)
+ ~~~~~~~~~~~~^^^^
+...
+FAIL
+rastrillo-budget/v1 ran 97ms
+FAIL amadan.net/oficina/equipo/internal/runner/containment 0.099s
+FAIL
+```
+
+### User-facing strings
+
+No UI text, README prose or `copy.go` entries were added. The new internal diagnostic is `egress_policy_rejected`. If the application later displays this condition, it needs an individually pending `copy.go` entry and a copy pass before release. The proxy emits standard protocol status lines: `HTTP/1.1 200 Connection Established`, `HTTP/1.1 403 Forbidden` and `HTTP/1.1 502 Bad Gateway`. Test assertion messages and code comments are developer-facing. No copy-review skill or server was invoked.
+
+### Concerns and handback
+
+No known failing implementation gate remains. Real provider compatibility, refresh hostnames and complete deployed-policy certification remain Task 11b release work; this run claims local fixture and namespace evidence only. The actual auth-host fields remain empty by default. The strict CONNECT parser permits only Host, User-Agent, Proxy-Connection and Connection headers; Task 11b should verify the pinned provider transports against that grammar without relaxing framing or destination checks. Full CI and controller review remain outside this task's requested gate list.
+
+All fixture listeners and processes finished or were stopped. Scratch created for test evidence and the runner build is removed after copying it into both reports. No server, watcher, provider session, credential home or background command is left running. No other worktree was touched. The controller owns review and push.
diff --git a/internal/runner/containment/egress.go b/internal/runner/containment/egress.go
new file mode 100644
index 00000000..82f7c431
--- /dev/null
+++ b/internal/runner/containment/egress.go
@@ -0,0 +1,159 @@
+package containment
+
+import (
+ "context"
+ "net"
+ "os"
+ "path/filepath"
+ "strconv"
+ "sync"
+
+ "amadan.net/oficina/equipo/internal/runner/egress"
+ "amadan.net/oficina/equipo/internal/runner/provider"
+)
+
+func (m *Manager) openEgress(ctx context.Context, l provider.Launch, dir string, p *mounts) (string, error) {
+ // Check jobs have no provider and retain a completely disconnected namespace.
+ if l.Selection.Provider == "" {
+ return "", nil
+ }
+ if l.Binding.DedicatedHome && l.Binding.Home == "" {
+ return "", errMount
+ }
+ contract := provider.NetworkContract{Provider: l.Selection.Provider}
+ for _, c := range m.cfg.ProviderNetworks {
+ if c.Provider == contract.Provider {
+ contract = c
+ }
+ }
+ policy, e := egress.ProviderPolicy(contract, l.Binding.DedicatedHome)
+ if e != nil {
+ return "", e
+ }
+ hash, e := policy.Hash()
+ if e != nil {
+ return "", e
+ }
+ private := filepath.Join(dir, "egress")
+ if e = os.Mkdir(private, 0700); e != nil {
+ return "", e
+ }
+ proxy, e := egress.Open(ctx, private, policy)
+ if e != nil {
+ return "", e
+ }
+ ok := false
+ defer func() {
+ if !ok {
+ proxy.Close()
+ }
+ }()
+ f, e := pin(proxy.SocketPath())
+ if e != nil {
+ return "", e
+ }
+ info, e := f.Stat()
+ if e != nil || info.Mode()&os.ModeSocket == 0 || info.Mode().Perm() != 0600 {
+ f.Close()
+ return "", errMount
+ }
+ // This is the sole socket import. The parent directory and other host sockets
+ // remain absent; the retained O_PATH descriptor pins this exact endpoint.
+ p.args = append(p.args, "--ro-bind-fd", strconv.Itoa(6+len(p.files)), egress.NamespaceSocket)
+ p.files = append(p.files, f)
+ for _, key := range []string{"HTTPS_PROXY", "HTTP_PROXY", "https_proxy", "http_proxy"} {
+ p.args = append(p.args, "--setenv", key, egress.ProxyURL)
+ }
+ p.proxy = proxy
+ ok = true
+ return hash, nil
+}
+
+// The relay runs in PID 1's Go process. It cannot select a host socket or remote
+// address, and starts before the harness. No subprocess or external binary is used.
+type namespaceRelay struct {
+ listener net.Listener
+ failed chan struct{}
+ once sync.Once
+ mu sync.Mutex
+ closed bool
+ connections map[net.Conn]struct{}
+ wg sync.WaitGroup
+}
+
+func startRelay() (*namespaceRelay, error) {
+ ln, e := net.Listen("tcp4", egress.RelayAddress)
+ if e != nil {
+ return nil, e
+ }
+ r := &namespaceRelay{listener: ln, failed: make(chan struct{}), connections: map[net.Conn]struct{}{}}
+ r.wg.Add(1)
+ go r.serve()
+ return r, nil
+}
+func (r *namespaceRelay) shutdown() {
+ r.once.Do(func() {
+ r.mu.Lock()
+ r.closed = true
+ r.listener.Close()
+ for c := range r.connections {
+ c.Close()
+ }
+ r.mu.Unlock()
+ close(r.failed)
+ })
+}
+func (r *namespaceRelay) close() { r.shutdown(); r.wg.Wait() }
+func (r *namespaceRelay) serve() {
+ defer r.wg.Done()
+ defer r.shutdown()
+ slots := make(chan struct{}, egress.MaxTunnels)
+ for {
+ c, e := r.listener.Accept()
+ if e != nil {
+ return
+ }
+ select {
+ case slots <- struct{}{}:
+ default:
+ c.Close()
+ continue
+ }
+ if !r.add(c) {
+ c.Close()
+ <-slots
+ return
+ }
+ r.wg.Add(1)
+ go func() {
+ defer r.wg.Done()
+ defer func() { <-slots; r.remove(c) }()
+ upstream, e := net.DialTimeout("unix", egress.NamespaceSocket, egress.ConnectTimeout)
+ if e != nil {
+ r.shutdown()
+ return
+ }
+ if !r.add(upstream) {
+ upstream.Close()
+ return
+ }
+ defer r.remove(upstream)
+ egress.Tunnel(c, upstream, egress.IdleTimeout)
+ }()
+ }
+}
+func (r *namespaceRelay) add(c net.Conn) bool {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ if r.closed {
+ return false
+ }
+ r.connections[c] = struct{}{}
+ return true
+}
+func (r *namespaceRelay) remove(c net.Conn) {
+ c.Close()
+ r.mu.Lock()
+ delete(r.connections, c)
+ r.mu.Unlock()
+}
diff --git a/internal/runner/containment/egress_test.go b/internal/runner/containment/egress_test.go
new file mode 100644
index 00000000..16915538
--- /dev/null
+++ b/internal/runner/containment/egress_test.go
@@ -0,0 +1,263 @@
+package containment
+
+import (
+ "bufio"
+ "context"
+ "fmt"
+ "io"
+ "net"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/runner/egress"
+ "amadan.net/oficina/equipo/internal/runner/provider"
+)
+
+func egressFixture(t *testing.T) (*Manager, provider.Launch) {
+ t.Helper()
+ root, e := os.MkdirTemp(os.Getenv("TMPDIR"), "e3-")
+ if e != nil {
+ t.Fatal(e)
+ }
+ t.Cleanup(func() { os.RemoveAll(root) })
+ state := filepath.Join(root, "s")
+ workspace := filepath.Join(root, "w")
+ if e = os.Mkdir(state, 0700); e != nil {
+ t.Fatal(e)
+ }
+ if e = os.Mkdir(workspace, 0700); e != nil {
+ t.Fatal(e)
+ }
+ binary, e := os.Executable()
+ if e != nil {
+ t.Fatal(e)
+ }
+ m, e := New(Config{Binary: "/usr/bin/bwrap", RunnerBinary: binary, ScratchRoot: state})
+ if e != nil {
+ t.Fatal(e)
+ }
+ return m, provider.Launch{AttemptKey: "egress", Workspace: workspace, Selection: provider.Selection{Provider: "claude"}, Policy: provider.Policy{Hash: "fixture-policy"}}
+}
+
+func TestEgressRejectsHostServices(t *testing.T) {
+ tcp, e := net.Listen("tcp", "127.0.0.1:0")
+ if e != nil {
+ t.Fatal(e)
+ }
+ defer tcp.Close()
+ abstract, e := net.Listen("unix", fmt.Sprintf("@equipo-egress-%d-%d", os.Getpid(), time.Now().UnixNano()))
+ if e != nil {
+ t.Fatal(e)
+ }
+ defer abstract.Close()
+ // Shared-network controls prove both services exist before private launch.
+ for _, ln := range []net.Listener{tcp, abstract} {
+ c, e := net.Dial(ln.Addr().Network(), ln.Addr().String())
+ if e != nil {
+ t.Fatal(e)
+ }
+ c.Close()
+ }
+ m, l := egressFixture(t)
+ script := fmt.Sprintf(`import socket, os
+for family, address in [(socket.AF_INET, ('127.0.0.1', %d)), (socket.AF_UNIX, '\0%s')]:
+ s=socket.socket(family); s.settimeout(1)
+ try:
+ s.connect(address)
+ print('HOST REACHABLE')
+ except OSError:
+ print('blocked')
+ s.close()
+s=socket.create_connection(('127.0.0.1',18080),1)
+s.sendall(b'CONNECT localhost:443 HTTP/1.1\r\nHost: localhost:443\r\n\r\n')
+print(s.recv(1024).decode().strip())
+print(os.environ['HTTPS_PROXY'], os.environ['https_proxy'], os.environ['HTTP_PROXY'], os.environ['http_proxy'])
+print('socket', os.path.exists('/egress/proxy.sock'))
+print('only-socket', os.listdir('/egress') == ['proxy.sock'])
+try:
+ os.chmod('/egress/proxy.sock', 0o666)
+ print('SOCKET WRITABLE')
+except OSError:
+ print('socket-readonly')
+`, tcp.Addr().(*net.TCPAddr).Port, strings.TrimPrefix(abstract.Addr().String(), "@"))
+ p := launch(t, m, l, script)
+ b, _ := io.ReadAll(p.Stdout())
+ exit, e := p.Wait(context.Background())
+ if e != nil || exit.Code != 0 || strings.Count(string(b), "blocked") != 2 || !strings.Contains(string(b), "403") || !strings.Contains(string(b), "socket True") || strings.Count(string(b), "http://127.0.0.1:18080") != 4 || !strings.Contains(string(b), "only-socket True") || !strings.Contains(string(b), "socket-readonly") {
+ errout, _ := io.ReadAll(p.Stderr())
+ t.Fatalf("isolation/relay: %q exit=%+v err=%v stderr=%s", b, exit, e, errout)
+ }
+}
+
+func TestEgressDiesWithAttempt(t *testing.T) {
+ for _, mode := range []string{"stop", "context", "proxy_failure", "exit"} {
+ t.Run(mode, func(t *testing.T) {
+ m, l := egressFixture(t)
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ p, e := m.Start(ctx, l, []string{"/usr/bin/python3", "-u", "-c", `import socket,sys,time
+s=socket.create_connection(('127.0.0.1',18080),1)
+s.sendall(b'CONNECT localhost:443 HTTP/1.1\r\n\r\n')
+assert b'403' in s.recv(1024)
+s.close()
+print('ready',flush=True)
+sys.stdin.read(1)
+`})
+ if e != nil {
+ t.Fatal(e)
+ }
+ defer p.Stdin().Close()
+ defer p.Stdout().Close()
+ defer p.Stderr().Close()
+ t.Cleanup(func() { m.Stop(context.Background(), p.ID()) })
+ line, e := bufio.NewReader(p.Stdout()).ReadString('\n')
+ if e != nil || line != "ready\n" {
+ t.Fatalf("relay readiness: %q %v", line, e)
+ }
+ impl := p.(*process)
+ if impl.egress == nil {
+ t.Fatal("attempt lacks proxy")
+ }
+ path := impl.egress.SocketPath()
+ fd := descriptor(t, record(t, m, p).HostPID)
+ switch mode {
+ case "stop":
+ _, e = m.Stop(context.Background(), p.ID())
+ case "context":
+ cancel()
+ case "proxy_failure":
+ e = impl.egress.Close()
+ case "exit":
+ _, e = p.Stdin().Write([]byte{'x'})
+ }
+ if e != nil {
+ t.Fatal(e)
+ }
+ wait, c := context.WithTimeout(context.Background(), 3*time.Second)
+ defer c()
+ if _, e = p.Wait(wait); e != nil {
+ t.Fatal(e)
+ }
+ exited(t, fd)
+ if _, e = os.Stat(path); !os.IsNotExist(e) {
+ t.Fatalf("socket outlived attempt: %v", e)
+ }
+ select {
+ case <-impl.egress.Done():
+ default:
+ t.Fatal("proxy outlived attempt")
+ }
+ if c, e := net.Dial("unix", path); e == nil {
+ c.Close()
+ t.Fatal("listener outlived attempt")
+ }
+ })
+ }
+}
+
+func TestEgressMountPolicy(t *testing.T) {
+ m, l := egressFixture(t)
+ for _, key := range []string{"HTTPS_PROXY", "HTTP_PROXY", "https_proxy", "http_proxy", "ALL_PROXY", "NO_PROXY", "EQUIPO_EGRESS"} {
+ t.Run(key, func(t *testing.T) {
+ bad := l
+ bad.Policy.Env = map[string]string{key: "http://127.0.0.1:1"}
+ if p, e := m.Start(context.Background(), bad, []string{"/usr/bin/true"}); e == nil {
+ m.Stop(context.Background(), p.ID())
+ t.Fatal("caller replaced fixed relay environment")
+ }
+ })
+ }
+ l.Selection.Provider = "unknown"
+ if p, e := m.Start(context.Background(), l, []string{"/usr/bin/true"}); e == nil {
+ m.Stop(context.Background(), p.ID())
+ t.Fatal("unknown provider accepted")
+ }
+ l.Selection.Provider = "claude"
+ p := launch(t, m, l, "pass")
+ r := record(t, m, p)
+ policy, e := egress.ProviderPolicy(provider.NetworkContract{Provider: "claude"}, false)
+ if e != nil {
+ t.Fatal(e)
+ }
+ hash, e := policy.Hash()
+ if e != nil {
+ t.Fatal(e)
+ }
+ if r.EgressHash != hash {
+ t.Fatalf("missing exact host-policy hash: %q want %q", r.EgressHash, hash)
+ }
+}
+
+func TestEgressInstalledContract(t *testing.T) {
+ m, _ := egressFixture(t)
+ for _, contracts := range [][]provider.NetworkContract{
+ {{Provider: "other"}},
+ {{Provider: "claude", AuthHost: "*.example"}},
+ {{Provider: "claude"}, {Provider: "claude", AuthHost: "refresh.example"}},
+ } {
+ cfg := m.cfg
+ cfg.ProviderNetworks = contracts
+ if _, e := New(cfg); e == nil {
+ t.Fatalf("invalid installed contracts accepted: %+v", contracts)
+ }
+ }
+ cfg := m.cfg
+ contracts := []provider.NetworkContract{{Provider: "claude", AuthHost: "refresh.example"}}
+ cfg.ProviderNetworks = contracts
+ manager, e := New(cfg)
+ if e != nil {
+ t.Fatal(e)
+ }
+ contracts[0].AuthHost = "changed.example"
+ if manager.cfg.ProviderNetworks[0].AuthHost != "refresh.example" {
+ t.Fatal("installed contract changed after New")
+ }
+}
+
+func TestEgressRefreshRequiresStagedHome(t *testing.T) {
+ m, l := egressFixture(t)
+ l.Binding.DedicatedHome = true
+ if p, e := m.Start(context.Background(), l, []string{"/usr/bin/true"}); e == nil {
+ m.Stop(context.Background(), p.ID())
+ t.Fatal("unstaged home qualified for refresh")
+ }
+}
+
+func TestEgressStartupFailureClosesProxy(t *testing.T) {
+ m, l := egressFixture(t)
+ m.cfg.RunnerBinary = "/usr/bin/true"
+ sockets := func() int {
+ entries, e := os.ReadDir("/proc/self/fd")
+ if e != nil {
+ t.Fatal(e)
+ }
+ count := 0
+ for _, entry := range entries {
+ target, _ := os.Readlink("/proc/self/fd/" + entry.Name())
+ if strings.HasPrefix(target, "socket:[") {
+ count++
+ }
+ }
+ return count
+ }
+ before := sockets()
+ if p, e := m.Start(context.Background(), l, []string{"/usr/bin/true"}); e == nil {
+ m.Stop(context.Background(), p.ID())
+ t.Fatal("invalid helper started")
+ }
+ if after := sockets(); after != before {
+ t.Fatalf("startup failure leaked sockets: before=%d after=%d", before, after)
+ }
+ entries, e := os.ReadDir(m.cfg.ScratchRoot)
+ if e != nil {
+ t.Fatal(e)
+ }
+ for _, entry := range entries {
+ if entry.IsDir() {
+ t.Fatalf("startup scratch survived: %s", entry.Name())
+ }
+ }
+}
diff --git a/internal/runner/containment/linux.go b/internal/runner/containment/linux.go
index f863b1e2..0426b8ae 100644
--- a/internal/runner/containment/linux.go
+++ b/internal/runner/containment/linux.go
@@ -17,11 +17,15 @@ import (
"syscall"
"time"
+ "amadan.net/oficina/equipo/internal/runner/egress"
"amadan.net/oficina/equipo/internal/runner/provider"
"golang.org/x/sys/unix"
)
-type Config struct{ Binary, RunnerBinary, ScratchRoot string }
+type Config struct {
+ Binary, RunnerBinary, ScratchRoot string
+ ProviderNetworks []provider.NetworkContract
+}
type Manager struct {
cfg Config
mu sync.Mutex
@@ -33,6 +37,7 @@ var errStartup = errors.New("namespace_startup_failed")
type process struct {
killed bool
+ egress *egress.Proxy
record Record
stdin *os.File
stdout, stderr *os.File
@@ -89,6 +94,17 @@ func New(cfg Config) (*Manager, error) {
if e != nil || string(version) != "bubblewrap 0.11.0\n" {
return nil, errors.New("namespace_bubblewrap_version")
}
+ seen := map[string]bool{}
+ for _, c := range cfg.ProviderNetworks {
+ if seen[c.Provider] {
+ return nil, errStartup
+ }
+ if _, e := egress.ProviderPolicy(c, true); e != nil {
+ return nil, e
+ }
+ seen[c.Provider] = true
+ }
+ cfg.ProviderNetworks = append([]provider.NetworkContract(nil), cfg.ProviderNetworks...)
return &Manager{cfg: cfg, processes: make(map[string]*process)}, nil
}
func (m *Manager) Start(ctx context.Context, l provider.Launch, argv []string) (provider.Process, error) {
@@ -123,12 +139,23 @@ func (m *Manager) Start(ctx context.Context, l provider.Launch, argv []string) (
if e != nil {
return nil, e
}
+ egressHash, e := m.openEgress(ctx, l, dir, mounts)
+ if e != nil {
+ mounts.close()
+ return nil, e
+ }
+ transferred := false
+ defer func() {
+ if !transferred && mounts.proxy != nil {
+ mounts.proxy.Close()
+ }
+ }()
boot, e := bootID()
if e != nil {
mounts.close()
return nil, e
}
- r := Record{ID: id, AttemptKey: l.AttemptKey, BootID: boot, ManifestHash: l.Policy.Hash}
+ r := Record{ID: id, AttemptKey: l.AttemptKey, BootID: boot, ManifestHash: l.Policy.Hash, EgressHash: egressHash}
if e = m.persist(r); e != nil {
mounts.close()
return nil, e
@@ -139,6 +166,7 @@ func (m *Manager) Start(ctx context.Context, l provider.Launch, argv []string) (
finished := make(chan struct{})
go func() { m.lifecycle(ctx, r, argv, mounts, dir, result); close(finished) }()
cleanup = false
+ transferred = true
resultValue := <-result
if resultValue.err != nil {
<-finished
@@ -167,6 +195,9 @@ func (m *Manager) lifecycle(ctx context.Context, r Record, argv []string, mounts
}
}()
defer mounts.close()
+ if mounts.proxy != nil {
+ defer mounts.proxy.Close()
+ }
var files []*os.File
pipe := func() (*os.File, *os.File, error) {
a, b, e := pipePair()
@@ -213,6 +244,9 @@ func (m *Manager) lifecycle(ctx context.Context, r Record, argv []string, mounts
args := []string{"--unshare-user", "--unshare-pid", "--unshare-ipc", "--unshare-uts", "--unshare-cgroup", "--unshare-net", "--die-with-parent", "--new-session", "--as-pid-1", "--cap-drop", "ALL", "--json-status-fd", "3"}
args = append(args, mounts.args...)
args = append(args, "--", "/equipo-namespace", "__namespace")
+ if mounts.proxy != nil {
+ args = append(args, "--egress")
+ }
args = append(args, argv...)
cmd := exec.Command(m.cfg.Binary, args...)
cmd.Env = []string{}
@@ -296,7 +330,7 @@ func (m *Manager) lifecycle(ctx context.Context, r Record, argv []string, mounts
result <- startResult{err: fmt.Errorf("%w: %s", s.err, diagnostic)}
return
}
- p := &process{record: s.record, stdin: inputW, stdout: outputR, stderr: errorR, done: make(chan struct{}), fd: s.fd}
+ p := &process{record: s.record, stdin: inputW, stdout: outputR, stderr: errorR, done: make(chan struct{}), fd: s.fd, egress: mounts.proxy}
// Identity is durable before the helper can fork the harness or read input.
if e = m.persist(s.record); e == nil {
_, e = releaseW.Write([]byte{1})
@@ -317,10 +351,16 @@ func (m *Manager) lifecycle(ctx context.Context, r Record, argv []string, mounts
files = []*os.File{statusR, statusW, releaseR, releaseW, readyR, readyW, inputR, outputW, errorW}
result <- startResult{p: p}
lifecycleDone := make(chan struct{})
+ var proxyDone <-chan struct{}
+ if p.egress != nil {
+ proxyDone = p.egress.Done()
+ }
go func() {
select {
case <-ctx.Done():
p.kill()
+ case <-proxyDone:
+ p.kill()
case <-lifecycleDone:
}
}()
@@ -356,6 +396,9 @@ func (m *Manager) lifecycle(ctx context.Context, r Record, argv []string, mounts
p.proof.Verified = false
}
}
+ if p.egress != nil {
+ p.egress.Close()
+ }
var cleanupErr error
p.proof, cleanupErr = m.finishRecovery(p.proof)
p.err = errors.Join(p.err, cleanupErr)
@@ -414,6 +457,20 @@ func NamespaceMain(argv []string) int {
if e = unix.CloseRange(3, ^uint(0), unix.CLOSE_RANGE_CLOEXEC); e != nil {
return 125
}
+ var relay *namespaceRelay
+ var relayFailed <-chan struct{}
+ if argv[0] == "--egress" {
+ argv = argv[1:]
+ if len(argv) == 0 {
+ return 125
+ }
+ relay, e = startRelay()
+ if e != nil {
+ return 125
+ }
+ defer relay.close()
+ relayFailed = relay.failed
+ }
cmd := exec.Command(argv[0], argv[1:]...)
cmd.Env = os.Environ()
cmd.Stdin = os.Stdin
@@ -422,30 +479,50 @@ func NamespaceMain(argv []string) int {
if e = cmd.Start(); e != nil {
return 127
}
- for {
- var status unix.WaitStatus
- pid, e := unix.Wait4(-1, &status, 0, nil)
- if e == unix.EINTR {
- continue
- }
- if e != nil {
- return 125
- }
- if pid == cmd.Process.Pid {
- _ = cmd.Process.Release()
- outcome := provider.Exit{Code: status.ExitStatus()}
- if status.Signaled() {
- outcome.Code = -1
- outcome.Signal = int(status.Signal())
+ type waited struct {
+ status unix.WaitStatus
+ err error
+ }
+ harnessExit := make(chan waited, 1)
+ go func() {
+ for {
+ var status unix.WaitStatus
+ pid, e := unix.Wait4(-1, &status, 0, nil)
+ if e == unix.EINTR {
+ continue
}
- if json.NewEncoder(ready).Encode(outcome) != nil {
- return 125
+ if e != nil {
+ harnessExit <- waited{err: e}
+ return
}
- ready.Close()
- if status.Signaled() {
- return 128 + int(status.Signal())
+ if pid == cmd.Process.Pid {
+ harnessExit <- waited{status: status}
+ return
}
- return status.ExitStatus()
}
+ }()
+ var status unix.WaitStatus
+ select {
+ case <-relayFailed:
+ return 125
+ case w := <-harnessExit:
+ if w.err != nil {
+ return 125
+ }
+ status = w.status
+ }
+ _ = cmd.Process.Release()
+ outcome := provider.Exit{Code: status.ExitStatus()}
+ if status.Signaled() {
+ outcome.Code = -1
+ outcome.Signal = int(status.Signal())
+ }
+ if json.NewEncoder(ready).Encode(outcome) != nil {
+ return 125
+ }
+ ready.Close()
+ if status.Signaled() {
+ return 128 + int(status.Signal())
}
+ return status.ExitStatus()
}
diff --git a/internal/runner/containment/mounts.go b/internal/runner/containment/mounts.go
index 11197bef..489421de 100644
--- a/internal/runner/containment/mounts.go
+++ b/internal/runner/containment/mounts.go
@@ -10,6 +10,7 @@ import (
"strconv"
"strings"
+ "amadan.net/oficina/equipo/internal/runner/egress"
"amadan.net/oficina/equipo/internal/runner/provider"
"golang.org/x/sys/unix"
)
@@ -17,6 +18,7 @@ import (
var errMount = errors.New("namespace_mount_rejected")
type mounts struct {
+ proxy *egress.Proxy
args []string
files []*os.File
}
diff --git a/internal/runner/containment/recovery.go b/internal/runner/containment/recovery.go
index def9c643..31aea388 100644
--- a/internal/runner/containment/recovery.go
+++ b/internal/runner/containment/recovery.go
@@ -18,6 +18,7 @@ import (
type Record struct {
ID, AttemptKey, BootID, NamespaceID, ManifestHash string
+ EgressHash string
HostPID int
StartTicks uint64
}
diff --git a/internal/runner/egress/budget_test.go b/internal/runner/egress/budget_test.go
new file mode 100644
index 00000000..b182a1bc
--- /dev/null
+++ b/internal/runner/egress/budget_test.go
@@ -0,0 +1,9 @@
+package egress
+
+import (
+ "amadan.net/rastrillo/rastrillo/budget"
+ "os"
+ "testing"
+)
+
+func TestMain(m *testing.M) { os.Exit(budget.Main(m)) }
diff --git a/internal/runner/egress/policy.go b/internal/runner/egress/policy.go
new file mode 100644
index 00000000..16f179ba
--- /dev/null
+++ b/internal/runner/egress/policy.go
@@ -0,0 +1,110 @@
+// Package egress provides the attempt's private, restricted CONNECT endpoint.
+package egress
+
+import (
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "net/netip"
+ "sort"
+ "strings"
+
+ "amadan.net/oficina/equipo/internal/runner/provider"
+)
+
+type Policy struct {
+ Provider string
+ Hosts []string
+}
+
+var errPolicy = errors.New("egress_policy_rejected")
+
+// ProviderPolicy consumes an installed contract, never model or permission input.
+// AuthHost remains empty until refresh certification pins an exact hostname.
+func ProviderPolicy(c provider.NetworkContract, dedicated bool) (Policy, error) {
+ p := Policy{Provider: c.Provider}
+ switch c.Provider {
+ case "claude":
+ p.Hosts = []string{"api.anthropic.com"}
+ case "codex":
+ p.Hosts = []string{"chatgpt.com"}
+ default:
+ return Policy{}, errPolicy
+ }
+ if c.AuthHost != "" {
+ if !hostname(c.AuthHost) {
+ return Policy{}, errPolicy
+ }
+ if dedicated && c.AuthHost != p.Hosts[0] {
+ p.Hosts = append(p.Hosts, c.AuthHost)
+ }
+ }
+ return p, nil
+}
+
+func hostname(s string) bool {
+ if len(s) > 253 || !strings.Contains(s, ".") || s != strings.ToLower(s) {
+ return false
+ }
+ if _, e := netip.ParseAddr(s); e == nil {
+ return false
+ }
+ for _, label := range strings.Split(s, ".") {
+ if len(label) == 0 || len(label) > 63 || label[0] == '-' || label[len(label)-1] == '-' {
+ return false
+ }
+ for _, c := range label {
+ if !(c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '-') {
+ return false
+ }
+ }
+ }
+ return true
+}
+
+// Hash binds the exact host set and provider. The caller's slice is never retained.
+func (p Policy) Hash() (string, error) {
+ if (p.Provider != "claude" && p.Provider != "codex") || len(p.Hosts) == 0 {
+ return "", errPolicy
+ }
+ hosts := append([]string(nil), p.Hosts...)
+ sort.Strings(hosts)
+ for i, h := range hosts {
+ if !hostname(h) || (i > 0 && h == hosts[i-1]) {
+ return "", errPolicy
+ }
+ }
+ b, _ := json.Marshal(Policy{Provider: p.Provider, Hosts: hosts})
+ hash := sha256.Sum256(b)
+ return hex.EncodeToString(hash[:]), nil
+}
+
+var blocked = func() []netip.Prefix {
+ var out []netip.Prefix
+ for _, s := range []string{
+ "0.0.0.0/8", "10.0.0.0/8", "100.64.0.0/10", "127.0.0.0/8", "169.254.0.0/16", "172.16.0.0/12",
+ "192.0.0.0/24", "192.0.2.0/24", "192.88.99.0/24", "192.168.0.0/16", "198.18.0.0/15", "198.51.100.0/24", "203.0.113.0/24", "224.0.0.0/4", "240.0.0.0/4",
+ "2001::/23", "2001:db8::/32", "2002::/16", "3fff::/20",
+ } {
+ out = append(out, netip.MustParsePrefix(s))
+ }
+ return out
+}()
+var publicV6 = netip.MustParsePrefix("2000::/3")
+
+func publicAddress(a netip.Addr) bool {
+ a = a.Unmap()
+ if !a.IsValid() || a.Zone() != "" || !a.IsGlobalUnicast() || a.IsPrivate() || a.IsLoopback() || a.IsLinkLocalUnicast() {
+ return false
+ }
+ if a.Is6() && !publicV6.Contains(a) {
+ return false
+ }
+ for _, p := range blocked {
+ if p.Contains(a) {
+ return false
+ }
+ }
+ return true
+}
diff --git a/internal/runner/egress/proxy.go b/internal/runner/egress/proxy.go
new file mode 100644
index 00000000..df2f11d9
--- /dev/null
+++ b/internal/runner/egress/proxy.go
@@ -0,0 +1,280 @@
+package egress
+
+import (
+ "bufio"
+ "bytes"
+ "context"
+ "io"
+ "net"
+ "net/http"
+ "net/netip"
+ "os"
+ "path/filepath"
+ "strings"
+ "sync"
+ "time"
+
+ "golang.org/x/sys/unix"
+)
+
+const (
+ MaxHeaders = 8 * 1024
+ MaxTunnels = 16
+ ConnectTimeout = 15 * time.Second
+ IdleTimeout = 60 * time.Second
+ NamespaceSocket = "/egress/proxy.sock"
+ RelayAddress = "127.0.0.1:18080"
+ ProxyURL = "http://127.0.0.1:18080"
+)
+
+type dependencies struct {
+ lookup func(context.Context, string) ([]netip.Addr, error)
+ dial func(context.Context, string, string) (net.Conn, error)
+ connect, idle time.Duration
+}
+
+func defaults() dependencies {
+ return dependencies{
+ lookup: func(ctx context.Context, host string) ([]netip.Addr, error) {
+ return net.DefaultResolver.LookupNetIP(ctx, "ip", host)
+ },
+ dial: (&net.Dialer{}).DialContext,
+ connect: ConnectTimeout, idle: IdleTimeout,
+ }
+}
+
+type Proxy struct {
+ listener net.Listener
+ path string
+ hosts map[string]bool
+ deps dependencies
+ ctx context.Context
+ cancel context.CancelFunc
+ done chan struct{}
+ once sync.Once
+ mu sync.Mutex
+ closed bool
+ clients map[net.Conn]struct{}
+ upstreams map[net.Conn]struct{}
+ wg sync.WaitGroup
+}
+
+// Open requires an existing private, symlink-free directory owned by the runner.
+// It creates no TCP listener. Each attempt must have a different directory.
+func Open(ctx context.Context, dir string, policy Policy) (*Proxy, error) {
+ return open(ctx, dir, policy, defaults())
+}
+func open(ctx context.Context, dir string, policy Policy, d dependencies) (*Proxy, error) {
+ if _, e := policy.Hash(); e != nil {
+ return nil, e
+ }
+ if e := ctx.Err(); e != nil {
+ return nil, e
+ }
+ if !filepath.IsAbs(dir) || filepath.Clean(dir) != dir {
+ return nil, errPolicy
+ }
+ fd, e := unix.Openat2(unix.AT_FDCWD, dir, &unix.OpenHow{Flags: unix.O_PATH | unix.O_DIRECTORY | unix.O_CLOEXEC, Resolve: unix.RESOLVE_NO_SYMLINKS | unix.RESOLVE_NO_MAGICLINKS})
+ if e != nil {
+ return nil, e
+ }
+ defer unix.Close(fd)
+ var st unix.Stat_t
+ if e = unix.Fstat(fd, &st); e != nil {
+ return nil, e
+ }
+ if st.Mode&0777 != 0700 || st.Uid != uint32(os.Geteuid()) {
+ return nil, errPolicy
+ }
+ path := filepath.Join(dir, "proxy.sock")
+ ln, e := net.Listen("unix", path)
+ if e != nil {
+ return nil, e
+ }
+ if e = os.Chmod(path, 0600); e != nil {
+ ln.Close()
+ return nil, e
+ }
+ ctx, cancel := context.WithCancel(ctx)
+ p := &Proxy{listener: ln, path: path, hosts: map[string]bool{}, deps: d, ctx: ctx, cancel: cancel, done: make(chan struct{}), clients: map[net.Conn]struct{}{}, upstreams: map[net.Conn]struct{}{}}
+ for _, h := range policy.Hosts {
+ p.hosts[h] = true
+ }
+ p.wg.Add(1)
+ go p.serve()
+ go func() {
+ select {
+ case <-ctx.Done():
+ p.shutdown()
+ case <-p.done:
+ }
+ }()
+ return p, nil
+}
+func (p *Proxy) SocketPath() string { return p.path }
+
+// Done closes on endpoint loss, cancellation or Close. Owners stop the attempt.
+func (p *Proxy) Done() <-chan struct{} { return p.done }
+func (p *Proxy) shutdown() {
+ p.once.Do(func() {
+ p.mu.Lock()
+ p.closed = true
+ p.cancel()
+ p.listener.Close()
+ for c := range p.clients {
+ c.Close()
+ }
+ for c := range p.upstreams {
+ c.Close()
+ }
+ p.mu.Unlock()
+ close(p.done)
+ })
+}
+func (p *Proxy) Close() error { p.shutdown(); p.wg.Wait(); return nil }
+func (p *Proxy) active() int { p.mu.Lock(); defer p.mu.Unlock(); return len(p.clients) }
+func (p *Proxy) serve() {
+ defer p.wg.Done()
+ defer p.shutdown()
+ for {
+ c, e := p.listener.Accept()
+ if e != nil {
+ return
+ }
+ p.mu.Lock()
+ if p.closed || len(p.clients) >= MaxTunnels {
+ p.mu.Unlock()
+ c.Close()
+ continue
+ }
+ p.clients[c] = struct{}{}
+ p.wg.Add(1)
+ p.mu.Unlock()
+ go func() {
+ defer p.wg.Done()
+ defer func() { c.Close(); p.mu.Lock(); delete(p.clients, c); p.mu.Unlock() }()
+ p.handle(c)
+ }()
+ }
+}
+
+// Read exactly one bounded CONNECT header. No HTTP request is forwarded to the
+// destination. Framing headers and queued requests are rejected before dialing.
+func authority(r *bufio.Reader) (string, error) {
+ data := make([]byte, 0, MaxHeaders)
+ for len(data) < MaxHeaders {
+ b, e := r.ReadByte()
+ if e != nil {
+ return "", e
+ }
+ data = append(data, b)
+ if bytes.HasSuffix(data, []byte("\r\n\r\n")) {
+ break
+ }
+ }
+ if !bytes.HasSuffix(data, []byte("\r\n\r\n")) || r.Buffered() != 0 {
+ return "", errPolicy
+ }
+ lines := strings.Split(string(data), "\r\n")
+ first := strings.Split(lines[0], " ")
+ if len(first) != 3 || first[0] != "CONNECT" || (first[2] != "HTTP/1.1" && first[2] != "HTTP/1.0") {
+ return "", errPolicy
+ }
+ host, port, e := net.SplitHostPort(first[1])
+ if e != nil || port != "443" || !hostname(host) {
+ return "", errPolicy
+ }
+ seen := map[string]bool{}
+ for _, line := range lines[1 : len(lines)-2] {
+ key, value, ok := strings.Cut(line, ":")
+ key = strings.ToLower(key)
+ if !ok || seen[key] {
+ return "", errPolicy
+ }
+ seen[key] = true
+ switch key {
+ case "host":
+ if strings.TrimSpace(value) != first[1] {
+ return "", errPolicy
+ }
+ case "user-agent", "proxy-connection", "connection":
+ default:
+ return "", errPolicy
+ }
+ }
+ req, e := http.ReadRequest(bufio.NewReader(bytes.NewReader(data)))
+ if e != nil {
+ return "", errPolicy
+ }
+ req.Body.Close()
+ return host, nil
+}
+func (p *Proxy) handle(c net.Conn) {
+ c.SetDeadline(time.Now().Add(p.deps.connect))
+ r := bufio.NewReaderSize(c, MaxHeaders+1)
+ host, e := authority(r)
+ if e != nil || !p.hosts[host] {
+ io.WriteString(c, "HTTP/1.1 403 Forbidden\r\n\r\n")
+ return
+ }
+ ctx, cancel := context.WithTimeout(p.ctx, p.deps.connect)
+ defer cancel()
+ addresses, e := p.deps.lookup(ctx, host)
+ if e != nil || len(addresses) == 0 {
+ io.WriteString(c, "HTTP/1.1 502 Bad Gateway\r\n\r\n")
+ return
+ }
+ // Reject the whole answer if any address is unsafe. Never resolve again in Dial.
+ for _, a := range addresses {
+ if !publicAddress(a) {
+ io.WriteString(c, "HTTP/1.1 403 Forbidden\r\n\r\n")
+ return
+ }
+ }
+ upstream, e := p.deps.dial(ctx, "tcp", net.JoinHostPort(addresses[0].Unmap().String(), "443"))
+ if e != nil {
+ io.WriteString(c, "HTTP/1.1 502 Bad Gateway\r\n\r\n")
+ return
+ }
+ defer upstream.Close()
+ p.mu.Lock()
+ if p.closed {
+ p.mu.Unlock()
+ return
+ }
+ p.upstreams[upstream] = struct{}{}
+ p.mu.Unlock()
+ defer func() { p.mu.Lock(); delete(p.upstreams, upstream); p.mu.Unlock() }()
+ if _, e = io.WriteString(c, "HTTP/1.1 200 Connection Established\r\n\r\n"); e != nil {
+ return
+ }
+ Tunnel(c, upstream, p.deps.idle)
+}
+
+// Tunnel copies opaque TLS bytes. Traffic in either direction renews the idle
+// deadline for both sockets; closing either side releases both copying goroutines.
+func Tunnel(a, b net.Conn, idle time.Duration) {
+ touch := func() { deadline := time.Now().Add(idle); a.SetDeadline(deadline); b.SetDeadline(deadline) }
+ touch()
+ copyTo := func(dst, src net.Conn) {
+ buffer := make([]byte, 32*1024)
+ for {
+ n, e := src.Read(buffer)
+ if n > 0 {
+ touch()
+ if _, writeErr := dst.Write(buffer[:n]); writeErr != nil {
+ return
+ }
+ }
+ if e != nil {
+ return
+ }
+ }
+ }
+ done := make(chan struct{})
+ go func() { defer close(done); copyTo(a, b); a.Close(); b.Close() }()
+ copyTo(b, a)
+ a.Close()
+ b.Close()
+ <-done
+}
diff --git a/internal/runner/egress/proxy_test.go b/internal/runner/egress/proxy_test.go
new file mode 100644
index 00000000..00881ade
--- /dev/null
+++ b/internal/runner/egress/proxy_test.go
@@ -0,0 +1,489 @@
+package egress
+
+import (
+ "bufio"
+ "context"
+ "crypto/tls"
+ "errors"
+ "fmt"
+ "io"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "net/netip"
+ "os"
+ "path/filepath"
+ "strings"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/runner/provider"
+)
+
+func scratch(t *testing.T) string {
+ t.Helper()
+ dir, err := os.MkdirTemp(os.Getenv("TMPDIR"), "e3-")
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { os.RemoveAll(dir) })
+ return dir
+}
+func fixtureProxy(t *testing.T, addresses []netip.Addr, dial func(context.Context, string, string) (net.Conn, error)) *Proxy {
+ t.Helper()
+ d := defaults()
+ d.lookup = func(context.Context, string) ([]netip.Addr, error) { return addresses, nil }
+ d.dial = dial
+ p, err := open(context.Background(), scratch(t), Policy{Provider: "claude", Hosts: []string{"fixture.example"}}, d)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { p.Close() })
+ return p
+}
+func connect(t *testing.T, p *Proxy, request string) (net.Conn, *bufio.Reader, string) {
+ t.Helper()
+ c, err := net.Dial("unix", p.SocketPath())
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { c.Close() })
+ c.SetDeadline(time.Now().Add(3 * time.Second))
+ if _, err = io.WriteString(c, request); err != nil {
+ t.Fatal(err)
+ }
+ r := bufio.NewReader(c)
+ line, _ := r.ReadString('\n')
+ return c, r, line
+}
+func request(host string) string {
+ return "CONNECT " + host + " HTTP/1.1\r\nHost: " + host + "\r\n\r\n"
+}
+
+func TestEgressRejectsHostServices(t *testing.T) {
+ var calls atomic.Int32
+ dial := func(context.Context, string, string) (net.Conn, error) {
+ calls.Add(1)
+ return nil, errors.New("unexpected dial")
+ }
+ p := fixtureProxy(t, []netip.Addr{netip.MustParseAddr("8.8.8.8")}, dial)
+ for _, host := range []string{"localhost:443", "127.0.0.1:443", "[::1]:443", "100.76.110.54:443", "192.168.1.1:443", "169.254.169.254:443", "metadata.google.internal:443", "fixture.example:80", "other.example:443", "sub.fixture.example:443", "fixture.example.evil:443", "fixture.example.:443", "FIXTURE.EXAMPLE:443", "fixture.example:0443", "fixture.example:443@other.example:443"} {
+ t.Run(host, func(t *testing.T) {
+ _, _, line := connect(t, p, request(host))
+ if strings.Contains(line, "200") {
+ t.Fatal("forbidden authority accepted")
+ }
+ })
+ }
+ if calls.Load() != 0 {
+ t.Fatal("denied request reached dialer")
+ }
+ for _, ip := range []string{"127.0.0.1", "10.0.0.1", "172.16.0.1", "192.168.0.1", "100.64.0.1", "100.127.255.254", "169.254.169.254", "0.0.0.0", "224.0.0.1", "240.0.0.1", "192.0.0.8", "198.18.0.1", "192.0.2.1", "198.51.100.1", "203.0.113.1", "::1", "::", "fc00::1", "fe80::1", "ff02::1", "::ffff:127.0.0.1", "64:ff9b::7f00:1", "2002:7f00:1::", "2001:db8::1"} {
+ t.Run(ip, func(t *testing.T) {
+ before := calls.Load()
+ q := fixtureProxy(t, []netip.Addr{netip.MustParseAddr("8.8.8.8"), netip.MustParseAddr(ip)}, dial)
+ _, _, line := connect(t, q, request("fixture.example:443"))
+ if strings.Contains(line, "200") || calls.Load() != before {
+ t.Fatal("nonpublic DNS answer reached dialer")
+ }
+ })
+ }
+ t.Run("resolver_error", func(t *testing.T) {
+ d := defaults()
+ d.lookup = func(context.Context, string) ([]netip.Addr, error) {
+ return []netip.Addr{netip.MustParseAddr("8.8.8.8")}, errors.New("dns unavailable")
+ }
+ d.dial = dial
+ q, e := open(context.Background(), scratch(t), Policy{Provider: "claude", Hosts: []string{"fixture.example"}}, d)
+ if e != nil {
+ t.Fatal(e)
+ }
+ defer q.Close()
+ before := calls.Load()
+ connect(t, q, request("fixture.example:443"))
+ if calls.Load() != before {
+ t.Fatal("DNS error dialled")
+ }
+ })
+}
+
+func TestEgressAllowsOnlyProviderTLS(t *testing.T) {
+ server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { io.WriteString(w, "fixture TLS") }))
+ defer server.Close()
+ var lookups, dials atomic.Int32
+ d := defaults()
+ d.lookup = func(_ context.Context, host string) ([]netip.Addr, error) {
+ if host != "fixture.example" {
+ t.Errorf("unexpected lookup: %s", host)
+ }
+ if lookups.Add(1) > 1 {
+ return []netip.Addr{netip.MustParseAddr("127.0.0.1")}, nil
+ }
+ return []netip.Addr{netip.MustParseAddr("8.8.8.8")}, nil
+ }
+ d.dial = func(ctx context.Context, network, address string) (net.Conn, error) {
+ dials.Add(1)
+ if network != "tcp" || address != "8.8.8.8:443" {
+ t.Errorf("unvalidated dial: %s %s", network, address)
+ }
+ return (&net.Dialer{}).DialContext(ctx, "tcp", server.Listener.Addr().String())
+ }
+ p, e := open(context.Background(), scratch(t), Policy{Provider: "claude", Hosts: []string{"fixture.example"}}, d)
+ if e != nil {
+ t.Fatal(e)
+ }
+ defer p.Close()
+ c, r, line := connect(t, p, request("fixture.example:443"))
+ if !strings.Contains(line, "200") {
+ t.Fatalf("CONNECT: %q", line)
+ }
+ if line, e = r.ReadString('\n'); e != nil || line != "\r\n" {
+ t.Fatalf("response headers: %q %v", line, e)
+ }
+ tlsConfig := server.Client().Transport.(*http.Transport).TLSClientConfig.Clone()
+ tlsConfig.ServerName = "127.0.0.1"
+ tlsConn := tls.Client(c, tlsConfig)
+ if e = tlsConn.Handshake(); e != nil {
+ t.Fatal(e)
+ }
+ io.WriteString(tlsConn, "GET / HTTP/1.1\r\nHost: fixture.example\r\nConnection: close\r\n\r\n")
+ b, e := io.ReadAll(tlsConn)
+ if e != nil || !strings.Contains(string(b), "fixture TLS") {
+ t.Fatalf("TLS tunnel: %q %v", b, e)
+ }
+ connect(t, p, request("fixture.example:443"))
+ if lookups.Load() != 2 || dials.Load() != 1 {
+ t.Fatalf("rebinding guard: lookups=%d dials=%d", lookups.Load(), dials.Load())
+ }
+}
+
+func TestEgressRejectsSmuggling(t *testing.T) {
+ var calls atomic.Int32
+ p := fixtureProxy(t, []netip.Addr{netip.MustParseAddr("8.8.8.8")}, func(context.Context, string, string) (net.Conn, error) { calls.Add(1); return nil, errors.New("dial") })
+ for _, raw := range []string{
+ "GET https://fixture.example/ HTTP/1.1\r\n\r\n",
+ "POST fixture.example:443 HTTP/1.1\r\n\r\n",
+ "CONNECT fixture.example:443 HTTP/1.1\r\nContent-Length: 0\r\n\r\n",
+ "CONNECT fixture.example:443 HTTP/1.1\r\nTransfer-Encoding: chunked\r\n\r\n",
+ "CONNECT fixture.example:443 HTTP/1.1\r\nHost: other.example:443\r\n\r\n",
+ "CONNECT fixture.example:443 HTTP/1.1\r\nHost: fixture.example:443\r\nHost: fixture.example:443\r\n\r\n",
+ "CONNECT fixture.example:443 HTTP/1.1\r\nUser-Agent: a\r\nUser-Agent: b\r\n\r\n",
+ "CONNECT fixture.example:443 HTTP/1.1\r\n Host: fixture.example:443\r\n\r\n",
+ "CONNECT fixture.example:443 HTTP/1.1\r\nX: a\x00b\r\n\r\n",
+ "CONNECT fixture.example:443 HTTP/1.1\n\n",
+ "CONNECT fixture.example:443 HTTP/2.0\r\n\r\n",
+ request("fixture.example:443") + "GET / HTTP/1.1\r\n\r\n",
+ } {
+ t.Run(fmt.Sprintf("case%d", calls.Load())+fmt.Sprint(len(raw)), func(t *testing.T) {
+ before := calls.Load()
+ _, _, line := connect(t, p, raw)
+ if strings.Contains(line, "200") || calls.Load() != before {
+ t.Fatalf("smuggling reached dial: %q", raw)
+ }
+ })
+ }
+}
+
+func closePromptly(t *testing.T, p *Proxy, connections ...net.Conn) {
+ t.Helper()
+ done := make(chan struct{})
+ go func() { p.Close(); close(done) }()
+ select {
+ case <-done:
+ case <-time.After(time.Second):
+ for _, c := range connections {
+ c.Close()
+ }
+ <-done
+ t.Fatal("proxy close did not interrupt sockets")
+ }
+}
+
+func TestEgressDiesWithAttempt(t *testing.T) {
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ p, e := Open(ctx, scratch(t), Policy{Provider: "claude", Hosts: []string{"api.anthropic.com"}})
+ if e != nil {
+ t.Fatal(e)
+ }
+ defer p.Close()
+ c, e := net.Dial("unix", p.SocketPath())
+ if e != nil {
+ t.Fatal(e)
+ }
+ defer c.Close()
+ cancel()
+ select {
+ case <-p.Done():
+ case <-time.After(time.Second):
+ t.Fatal("proxy outlived context")
+ }
+ closePromptly(t, p, c)
+ c.SetReadDeadline(time.Now().Add(time.Second))
+ b := make([]byte, 1)
+ if _, e = c.Read(b); e == nil {
+ t.Fatal("connection survived close")
+ }
+ if _, e = os.Stat(p.SocketPath()); !os.IsNotExist(e) {
+ t.Fatalf("socket survived: %v", e)
+ }
+ if c, e = net.Dial("unix", p.SocketPath()); e == nil {
+ c.Close()
+ t.Fatal("listener survived")
+ }
+}
+
+func TestEgressLimits(t *testing.T) {
+ if MaxHeaders != 8*1024 || MaxTunnels != 16 || ConnectTimeout != 15*time.Second || IdleTimeout != 60*time.Second {
+ t.Fatal("limits differ from brief")
+ }
+ t.Run("headers", func(t *testing.T) {
+ var called atomic.Bool
+ p := fixtureProxy(t, []netip.Addr{netip.MustParseAddr("8.8.8.8")}, func(context.Context, string, string) (net.Conn, error) {
+ called.Store(true)
+ return nil, errors.New("dial")
+ })
+ _, _, line := connect(t, p, "CONNECT fixture.example:443 HTTP/1.1\r\nUser-Agent: "+strings.Repeat("x", MaxHeaders)+"\r\n\r\n")
+ if strings.Contains(line, "200") || called.Load() {
+ t.Fatal("oversized headers dialled")
+ }
+ })
+ t.Run("concurrent", func(t *testing.T) {
+ p := fixtureProxy(t, nil, nil)
+ var cs []net.Conn
+ defer func() {
+ for _, c := range cs {
+ c.Close()
+ }
+ }()
+ for i := 0; i < MaxTunnels; i++ {
+ c, e := net.Dial("unix", p.SocketPath())
+ if e != nil {
+ t.Fatal(e)
+ }
+ cs = append(cs, c)
+ }
+ deadline := time.Now().Add(time.Second)
+ for p.active() != MaxTunnels && time.Now().Before(deadline) {
+ time.Sleep(time.Millisecond)
+ }
+ if p.active() != MaxTunnels {
+ t.Fatal("slots not occupied")
+ }
+ c, e := net.Dial("unix", p.SocketPath())
+ if e != nil {
+ t.Fatal(e)
+ }
+ defer c.Close()
+ c.SetReadDeadline(time.Now().Add(time.Second))
+ _, e = c.Read(make([]byte, 1))
+ if e == nil {
+ t.Fatal("extra connection survived")
+ }
+ if ne, ok := e.(net.Error); ok && ne.Timeout() {
+ t.Fatal("extra socket remained open")
+ }
+ })
+ t.Run("idle", func(t *testing.T) {
+ d := defaults()
+ d.idle = 80 * time.Millisecond
+ d.lookup = func(context.Context, string) ([]netip.Addr, error) {
+ return []netip.Addr{netip.MustParseAddr("8.8.8.8")}, nil
+ }
+ d.dial = func(context.Context, string, string) (net.Conn, error) {
+ a, b := net.Pipe()
+ t.Cleanup(func() { b.Close() })
+ return a, nil
+ }
+ p, e := open(context.Background(), scratch(t), Policy{Provider: "claude", Hosts: []string{"fixture.example"}}, d)
+ if e != nil {
+ t.Fatal(e)
+ }
+ defer p.Close()
+ c, r, line := connect(t, p, request("fixture.example:443"))
+ if !strings.Contains(line, "200") {
+ t.Fatal(line)
+ }
+ r.ReadString('\n')
+ c.SetReadDeadline(time.Now().Add(time.Second))
+ _, e = r.ReadByte()
+ if e == nil {
+ t.Fatal("idle tunnel survived")
+ }
+ if ne, ok := e.(net.Error); ok && ne.Timeout() {
+ t.Fatal("idle tunnel not closed")
+ }
+ })
+ t.Run("connect", func(t *testing.T) {
+ d := defaults()
+ d.connect = 80 * time.Millisecond
+ d.lookup = func(context.Context, string) ([]netip.Addr, error) {
+ return []netip.Addr{netip.MustParseAddr("8.8.8.8")}, nil
+ }
+ d.dial = func(ctx context.Context, _, _ string) (net.Conn, error) { <-ctx.Done(); return nil, ctx.Err() }
+ p, e := open(context.Background(), scratch(t), Policy{Provider: "claude", Hosts: []string{"fixture.example"}}, d)
+ if e != nil {
+ t.Fatal(e)
+ }
+ defer p.Close()
+ start := time.Now()
+ connect(t, p, request("fixture.example:443"))
+ if time.Since(start) > time.Second {
+ t.Fatal("connect timeout missing")
+ }
+ })
+}
+
+func TestEgressPolicy(t *testing.T) {
+ for _, name := range []string{"claude", "codex"} {
+ want := "api.anthropic.com"
+ if name == "codex" {
+ want = "chatgpt.com"
+ }
+ p, e := ProviderPolicy(provider.NetworkContract{Provider: name}, false)
+ if e != nil || len(p.Hosts) != 1 || p.Hosts[0] != want {
+ t.Fatalf("default: %+v %v", p, e)
+ }
+ p, e = ProviderPolicy(provider.NetworkContract{Provider: name, AuthHost: "refresh.example"}, false)
+ if e != nil || len(p.Hosts) != 1 {
+ t.Fatal("shared home got refresh")
+ }
+ p, e = ProviderPolicy(provider.NetworkContract{Provider: name, AuthHost: "refresh.example"}, true)
+ if e != nil || len(p.Hosts) != 2 {
+ t.Fatal("dedicated refresh missing")
+ }
+ }
+ for _, p := range []Policy{{Provider: "other", Hosts: []string{"fixture.example"}}, {Provider: "claude"}, {Provider: "claude", Hosts: []string{"*.example"}}, {Provider: "claude", Hosts: []string{"127.0.0.1"}}, {Provider: "claude", Hosts: []string{"localhost"}}, {Provider: "claude", Hosts: []string{"fixture.example", "fixture.example"}}} {
+ if _, e := p.Hash(); e == nil {
+ t.Fatalf("invalid policy accepted: %+v", p)
+ }
+ }
+ a, _ := (Policy{Provider: "claude", Hosts: []string{"a.example", "b.example"}}).Hash()
+ b, _ := (Policy{Provider: "claude", Hosts: []string{"b.example", "a.example"}}).Hash()
+ c, _ := (Policy{Provider: "claude", Hosts: []string{"a.example"}}).Hash()
+ d, _ := (Policy{Provider: "codex", Hosts: []string{"a.example", "b.example"}}).Hash()
+ if len(a) != 64 || a != b || a == c || a == d {
+ t.Fatal("policy hash does not bind exact host set and provider")
+ }
+}
+
+func TestEgressPrivateSocket(t *testing.T) {
+ dir := scratch(t)
+ p, e := Open(context.Background(), dir, Policy{Provider: "claude", Hosts: []string{"api.anthropic.com"}})
+ if e != nil {
+ t.Fatal(e)
+ }
+ defer p.Close()
+ info, e := os.Stat(p.SocketPath())
+ if e != nil || info.Mode().Perm() != 0600 {
+ t.Fatalf("socket mode: %v %v", info, e)
+ }
+ if _, e = Open(context.Background(), dir, Policy{Provider: "claude", Hosts: []string{"api.anthropic.com"}}); e == nil {
+ t.Fatal("existing socket replaced")
+ }
+ bad := scratch(t)
+ os.Chmod(bad, 0755)
+ if q, e := Open(context.Background(), bad, Policy{Provider: "claude", Hosts: []string{"api.anthropic.com"}}); e == nil {
+ q.Close()
+ t.Fatal("nonprivate directory accepted")
+ }
+ link := filepath.Join(scratch(t), "link")
+ os.Symlink(scratch(t), link)
+ if q, e := Open(context.Background(), link, Policy{Provider: "claude", Hosts: []string{"api.anthropic.com"}}); e == nil {
+ q.Close()
+ t.Fatal("symlink directory accepted")
+ }
+}
+
+func TestEgressActiveTunnelClose(t *testing.T) {
+ for _, mode := range []string{"close", "cancel", "listener_failure"} {
+ t.Run(mode, func(t *testing.T) {
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ a, b := net.Pipe()
+ defer b.Close()
+ d := defaults()
+ d.lookup = func(context.Context, string) ([]netip.Addr, error) {
+ return []netip.Addr{netip.MustParseAddr("8.8.8.8")}, nil
+ }
+ d.dial = func(context.Context, string, string) (net.Conn, error) { return a, nil }
+ p, e := open(ctx, scratch(t), Policy{Provider: "claude", Hosts: []string{"fixture.example"}}, d)
+ if e != nil {
+ t.Fatal(e)
+ }
+ defer p.Close()
+ c, r, line := connect(t, p, request("fixture.example:443"))
+ if !strings.Contains(line, "200") {
+ t.Fatal(line)
+ }
+ r.ReadString('\n')
+ switch mode {
+ case "close":
+ closePromptly(t, p, c, b)
+ case "cancel":
+ cancel()
+ case "listener_failure":
+ p.listener.Close()
+ }
+ select {
+ case <-p.Done():
+ case <-time.After(time.Second):
+ t.Fatal("proxy failure not reported")
+ }
+ closePromptly(t, p, c, b)
+ for _, conn := range []net.Conn{c, b} {
+ conn.SetReadDeadline(time.Now().Add(time.Second))
+ _, e := conn.Read(make([]byte, 1))
+ if e == nil {
+ t.Fatal("socket survived shutdown")
+ }
+ if ne, ok := e.(net.Error); ok && ne.Timeout() {
+ t.Fatal("socket not closed")
+ }
+ }
+ })
+ }
+}
+
+func TestEgressPolicyFrozen(t *testing.T) {
+ hosts := []string{"fixture.example"}
+ var called atomic.Bool
+ d := defaults()
+ d.lookup = func(context.Context, string) ([]netip.Addr, error) { called.Store(true); return nil, errors.New("dns") }
+ p, e := open(context.Background(), scratch(t), Policy{Provider: "claude", Hosts: hosts}, d)
+ if e != nil {
+ t.Fatal(e)
+ }
+ defer p.Close()
+ hosts[0] = "other.example"
+ connect(t, p, request("other.example:443"))
+ if called.Load() {
+ t.Fatal("policy changed after open")
+ }
+ for _, ip := range []string{"8.8.8.8", "2606:4700:4700::1111", "::ffff:8.8.8.8"} {
+ if !publicAddress(netip.MustParseAddr(ip)) {
+ t.Fatalf("public address rejected: %s", ip)
+ }
+ }
+}
+
+func TestEgressHeaderTimeout(t *testing.T) {
+ d := defaults()
+ d.connect = 80 * time.Millisecond
+ p, e := open(context.Background(), scratch(t), Policy{Provider: "claude", Hosts: []string{"fixture.example"}}, d)
+ if e != nil {
+ t.Fatal(e)
+ }
+ defer p.Close()
+ c, e := net.Dial("unix", p.SocketPath())
+ if e != nil {
+ t.Fatal(e)
+ }
+ defer c.Close()
+ c.SetReadDeadline(time.Now().Add(time.Second))
+ _, e = io.ReadAll(c)
+ if ne, ok := e.(net.Error); ok && ne.Timeout() {
+ t.Fatal("incomplete header kept socket open")
+ }
+}
diff --git a/internal/runner/provider/types.go b/internal/runner/provider/types.go
index 872acfa6..f01b8916 100644
--- a/internal/runner/provider/types.go
+++ b/internal/runner/provider/types.go
@@ -16,6 +16,14 @@ type Selection struct {
type Binding struct {
ID, Home, AccountID, Provider string
+ DedicatedHome bool
+}
+
+// NetworkContract is installed by the runner, never supplied by a permission answer.
+// AuthHost is empty until Task 11b certifies refresh for this provider.
+type NetworkContract struct {
+ Provider string
+ AuthHost string
}
type Identity struct {