oficina / equipo Public

Reuse Go root pins and keep module caches path-pinned

Paul Campbell pushed by paul@keymail.dev a184424186c4f4ba0bcff20cea7c378c605d648f parent 9fe335a
19 files changed, +719 −196
  • .rastrillo/budgets.txt +2 −2
  • docs/superpowers/specs/2026-11-13-engineering-toolchain.md +64 −25
  • internal/runner/containment/engineering_git_test.go +40 −0
  • internal/runner/containment/engineering_go_test.go +152 −79
  • internal/runner/containment/engineering_settings_test.go +67 −0
  • internal/runner/containment/engineering_shell_test.go +4 −1
  • internal/runner/containment/engineering_token_test.go +78 −0
  • internal/runner/containment/linux.go +15 −3
  • internal/runner/containment/mounts.go +13 −10
  • internal/runner/policy_inputs.go +5 −1
  • internal/runner/policy_inputs_test.go +21 −4
  • internal/runner/provider/accounts.go +10 −0
  • internal/runner/provider/check_policy.go +1 −16
  • internal/runner/provider/claude/go_policy_test.go +1 −1
  • internal/runner/provider/codex/go_policy_test.go +1 −1
  • internal/runner/provider/go_policy.go +82 −19
  • internal/runner/provider/go_policy_test.go +137 −26
  • internal/runner/provider/gotoolchain/tree.go +17 −4
  • internal/runner/provider/policy.go +9 −4

CI failed — run details

diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt
index 6a8b9b2d..faddedcd 100644
--- a/.rastrillo/budgets.txt
+++ b/.rastrillo/budgets.txt
@@ -21,12 +21,12 @@ time internal/runner/checks 90s CI worker measured 44.553s (44.6s rounded);
time internal/runner 330s Plan 3 CI repair measured 292.120s for the full package (controller CI 472.184s).
perf GET /api/runner/v2/artifacts/{assignment}/{artifact} skip Authenticated runner artifact download, not a browser GET screen. Runner long-poll and blob downloads use POST and are outside the screen inventory.
-size internal/runner 9926 9200 Runner configuration and provider seams, including Engineering Go mounts. Measured 9926 source lines.
+size internal/runner 9930 9200 Runner configuration and provider seams, including optional Engineering module mounts. Measured 9930 source lines.
time internal/runner/provider/claude 45s Task 5 measured 32.430s for fake CLI sessions and fsynced account, policy, capture and refresh checks; 45s gives 38 percent headroom on the shared runner.
time internal/runner/provider/codex 35s Plan 3 CI repair measured 24.464s for the full package (controller CI 27.908s).
time internal/runner/provider/pi 60s The real pinned Pi in bubblewrap against a fake TensorX: probes P1 to P5 (a hundred RPC turns), the hostile repository, and the pinned tree checked whole (about 160 MB); measured 22s locally.
time internal/runner/provider/opencode 90s The real pinned OpenCode in bubblewrap against a fake Go: probes, the hostile repository per source, termination, resume; the 260 MB binary hashed per launch. Measured 40s.
-size internal/runner/provider 5298 - Shared policy attestation now pins Go directory contents for Checks and Engineering. Tree traversal lives in gotoolchain. Measured 5298 source lines.
+size internal/runner/provider 5362 - Engineering retains Go tree descriptors and reuses one root digest per lease. Checks keep path pins. Tree traversal lives in gotoolchain. Measured 5362 source lines.
time internal/plan3test 300s Initial cap for combined browser and runner acceptance; measure at both usable stops.
diff --git a/docs/superpowers/specs/2026-11-13-engineering-toolchain.md b/docs/superpowers/specs/2026-11-13-engineering-toolchain.md
index a3c654a1..8e3241a9 100644
--- a/docs/superpowers/specs/2026-11-13-engineering-toolchain.md
+++ b/docs/superpowers/specs/2026-11-13-engineering-toolchain.md
@@ -5,15 +5,21 @@ targeted tests and repository gates before Equipo publishes its candidate.
Claude and Codex Engineering launches mount the runner's configured Go tree at
`/opt/go` and module cache at `/opt/go-mod`, both read-only. They use the same
-sources as Checks. Review keeps its existing policy; Pi Review has no shell,
+sources as Checks. A missing module-cache directory omits that mount, including
+for non-Go projects; an existing invalid or symlinked source is refused.
+`EQUIPO_GO_MODULE_CACHE` remains an optional override. Review keeps its existing policy; Pi Review has no shell,
and changing its tools would extend this work beyond adding read-only trees.
The shared Go environment sets `GOPROXY=off`, `GOSUMDB=off`,
`GOTOOLCHAIN=local`, `GOFLAGS=` and `CGO_ENABLED=0`. `GOROOT` and `GOMODCACHE`
name those mounts. `GOCACHE` and `GOTMPDIR` are directories under the attempt's
private `/tmp`, backed by the runner's scratch directory and removed with the
-attempt. `GOENV` and `GOWORK` are off, as is telemetry. `PATH` starts with
-`/opt/go/bin`. Repository Makefiles that override the toolchain version need
+attempt. Claude uses `/tmp/claude-${uid}/go-build` and `go-tmp`, under its
+`CLAUDE_CODE_TMPDIR=/tmp` temp root. Codex uses `/tmp/go-build` and `/tmp/go-tmp`.
+`GOENV` and `GOWORK` are off, as is telemetry. Provider launches receive no
+`XDG_CONFIG_HOME`; Git's global config is `/dev/null` and system config is
+disabled. `PATH` is `/opt/go/bin:/usr/bin:/bin:/opt`, including the pinned
+bubblewrap helper. Repository Makefiles that override the toolchain version need
`GOTOOLCHAIN=local` on the make command line.
## Bounds and pins
@@ -27,30 +33,65 @@ only their existing provider relay; Claude and Codex shell commands retain
their own network isolation. No sandbox setting or permission callback is
relaxed. Native file tools still obey their existing path restrictions.
-Checks previously recorded only these directory paths. This change adds a
-shared content digest: paths, modes and file bytes enter the policy's existing
-file-digest list. Symlinks and special files are refused. Launch attestation
-rehashes the sources; containment rehashes the retained directory descriptors
-before binding them read-only. A changed tree or a directory swapped after
-attestation stops the launch. Neither chmod nor a writable host directory
-makes the in-sandbox mounts writable.
+Engineering hashes the Go root once for the launch's account lease. Paths,
+modes and file bytes enter the policy's file-digest list. Validation, adapter
+policy rebuilds, source attestation and containment reuse that digest and the
+same retained directory descriptor. The lease closes it on cleanup; containment
+owns a duplicate until its mount plan closes. Replacing the source path does
+not substitute a different tree. Symlinks inside the Go root and special files
+are refused. The configured root must be canonical: a symlinked distro Go root
+is refused by the provider policy, so configure its resolved directory.
-These are launch-time pins, not immutable snapshots of a running host cache.
-A trusted host process can still change a source after launch. Adding a module
-changes the policy digest, and the existing certificate checks must accept
-that new policy before a certified launch can use it. Hashing both complete
-trees also adds launch work. No shared cache is copied or made writable.
+The module cache is pinned by path, opened without following symlinks, owned by
+the runner user and bound read-only through a retained descriptor using
+`--ro-bind-fd`. Trees cannot overlap scratch, workspace or protected paths, or
+contain the runner's home. The module cache is never content-hashed. Checks
+keep their previous path pins and containment traversal, with no content scan
+of either tree. On this box, hashing the pinned Go 1.26.11 root took 1.137 seconds;
+hashing the 14 GB module cache previously took 90.096 seconds.
+
+Agents cannot write the mounted trees. Host processes running as the runner
+user are already trusted; they could replace the runner binary itself. They
+can also update the live source trees. No snapshot or dedicated quiescent cache
+is required. Adding modules leaves the policy hash unchanged. The adapter
+compares its rebuilt policy and manifest hashes with the supplied policy;
+source validation compares the Go root's recorded digest with the lease's pin.
+No certificate is compared against a new module-cache content digest.
+
+Engineering can read every cached module, including private modules from the
+owner's other projects. Paul accepts this for v1 on a single owner's runner.
+Per-project caches remain later work for multi-person teams.
## Shell evidence and limits
-On this Linux host, real bubblewrap nesting and the existing Claude token
-isolation probe pass. Fake CLIs also start Bash through the pinned Claude and
-Codex namespace layouts; Pi starts Bash directly in outer containment. These
-probes make no provider calls. They do not establish the exact reason for the
-historical phrase “the shell was blocked”: the commits contain no Bash error
-or provider transcript. The absent toolchain mounts and offline environment
-are reproducible. Claude's `failIfUnavailable`, fresh PID namespace and token
-scrubbing remain required; weaker nested sandbox settings are not enabled.
+The offline build test invokes the real pinned Codex sandbox with filesystem
+and network permissions generated by `codex.PolicyInputs`. Claude 2.1.312 has
+no offline command or exported API for invoking its bundled sandbox builder.
+Its test therefore reproduces the namespace setup, consumes generated
+filesystem settings, and grants only the working directory and its own temp
+directory. It does not grant all of `/tmp`. In the pinned executable, byte
+239371446 selects `CLAUDE_CODE_TMPDIR`, byte 239373000 derives `claude-${uid}`,
+bytes 244230927 and 244231106 resolve temp paths, and byte 246036346 adds the
+working directory and those paths to the write grants. These probes make no
+provider calls and do not replace provider release certification.
+
+Both the shell probe and a Go-built probe fail to read the CLI's token through
+process files. Each has a direct control that can read the synthetic token's
+variable; neither prints its value. Claude's `failIfUnavailable`, fresh PID
+namespace and token scrubbing remain required. Weaker nested sandbox settings
+are not enabled. The historical Bash failure still lacks a raw tool response.
+
+The real Codex sandbox, using generated Engineering permissions, refuses writes
+to `/workspace/.git/config`. Claude's pinned shell builder protects `.git/config`
+and hooks (bytes 245813355 and 245845913). Its internal Git calls also neutralize
+executable config features: status arguments clear `core.fsmonitor` near byte
+239543350, and the Git helper at byte 240094865 disables hooks, fsmonitor,
+askpass and external protocols. Equipo's native file permission callback can
+allow a workspace config write; the shell test does not prove native-tool
+behavior. No route from that write to execution beside a real CLI token was
+established. A generic unsandboxed Git invocation would be vulnerable, but that
+is not evidence that either pinned CLI uses such an invocation. No additional
+Git configuration restriction is added in this branch.
An unversioned cache miss reports `module lookup disabled by GOPROXY=off`.
For an explicitly required missing version, Go first tries to create a cache
@@ -69,5 +110,3 @@ these directory file-digest entries rather than silently accepting the new
policy. Roll back by installing the previous versioned release and using its
matching certificates; Engineering then loses these Go mounts. No data needs
downgrading. Existing certifications are not regenerated by these offline tests.
-
-COPY ACCEPTED BY DELEGATION (Astra, 2026-11-13)
diff --git a/internal/runner/containment/engineering_git_test.go b/internal/runner/containment/engineering_git_test.go
new file mode 100644
index 00000000..252db1e8
--- /dev/null
+++ b/internal/runner/containment/engineering_git_test.go
@@ -0,0 +1,40 @@
+//go:build linux
+
+package containment
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "strings"
+ "testing"
+)
+
+func TestEngineeringGitConfig(t *testing.T) {
+ for _, name := range []string{"codex"} {
+ t.Run(name, func(t *testing.T) {
+ m, l := egressFixture(t)
+ shell := engineeringShell(t, name, `import os
+try:
+ with open('/workspace/.git/config','a') as f: f.write('\n[core]\n fsmonitor = "touch /home/runner/git-route-marker"\n')
+ print('git-config-write-allowed')
+except OSError: print('git-config-write-denied')
+`)
+ quoted, _ := json.Marshal(shell)
+ script := fmt.Sprintf("import subprocess,os\nsubprocess.run(['git','init','/workspace'],check=True,capture_output=True)\nexec(%s)\nsubprocess.run(['git','status','--porcelain'],capture_output=True)\nprint('parent-git-hook-ran='+str(os.path.exists('/home/runner/git-route-marker')),flush=True)\n", quoted)
+ l, argv, _ := engineeringGoPolicy(t, m, l, script)
+ p, err := m.Start(context.Background(), l, argv)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer p.Stdin().Close()
+ defer p.Stdout().Close()
+ defer p.Stderr().Close()
+ out, stderr := engineeringOutput(p)
+ exit, err := p.Wait(context.Background())
+ if err != nil || exit.Code != 0 || !strings.Contains(string(out), "git-config-write-denied") || !strings.Contains(string(out), "parent-git-hook-ran=False") {
+ t.Fatalf("Git config route: %s %+v %v %s", out, exit, err, stderr)
+ }
+ })
+ }
+}
diff --git a/internal/runner/containment/engineering_go_test.go b/internal/runner/containment/engineering_go_test.go
index 7db62238..c9fad835 100644
--- a/internal/runner/containment/engineering_go_test.go
+++ b/internal/runner/containment/engineering_go_test.go
@@ -17,9 +17,11 @@ import (
"time"
"amadan.net/oficina/equipo/internal/runner/provider"
+ "amadan.net/oficina/equipo/internal/runner/provider/codex"
+ "crypto/sha256"
)
-func engineeringGoPolicy(t *testing.T, m *Manager, l provider.Launch, script string) (provider.Launch, []string, string) {
+func engineeringGoPolicy(t *testing.T, m *Manager, l provider.Launch, script string, missing ...bool) (provider.Launch, []string, string) {
t.Helper()
mods := t.TempDir()
for name, body := range map[string]string{"go.mod": "module fixture.invalid/app\n\ngo 1.26\n\nrequire fixture.invalid/cached v1.0.0\n", "app_test.go": "package app\nimport (\"testing\"; dep \"fixture.invalid/cached\")\nfunc TestCached(t *testing.T) { if dep.Value != 42 { t.Fatal(dep.Value) } }\n"} {
@@ -61,13 +63,41 @@ func engineeringGoPolicy(t *testing.T, m *Manager, l provider.Launch, script str
t.Fatal(err)
}
}
+ codexPath, err := exec.LookPath("codex")
+ if err != nil {
+ t.Fatal(err)
+ }
+ codexPath, err = filepath.EvalSymlinks(codexPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ raw, err = os.ReadFile(codexPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if fmt.Sprintf("%x", sha256.Sum256(raw)) != codex.ExecutableSHA256 {
+ t.Fatal("Codex executable pin mismatch")
+ }
+ codexPath = filepath.Join(t.TempDir(), "codex")
+ if err = os.WriteFile(codexPath, raw, 0700); err != nil {
+ t.Fatal(err)
+ }
+ roots := "['/opt/go','/opt/go-mod']"
+ if len(missing) > 0 && missing[0] {
+ roots = "['/opt/go']"
+ }
+ script = "import os\nfor root in " + roots + ": assert os.statvfs(root).f_flag & os.ST_RDONLY,root\n" + script
argv := []string{"/opt/harness", "-u", "-c", script}
in := provider.PolicyInputs{Action: "implement", RuntimeFiles: []provider.Mount{
{Source: binary, Target: "/opt/harness", ReadOnly: true},
+ {Source: codexPath, Target: "/opt/codex", ReadOnly: true},
{Source: m.cfg.Binary, Target: "/opt/bwrap", ReadOnly: true},
{Source: goroot, Target: "/opt/go", ReadOnly: true},
{Source: mods, Target: "/opt/go-mod", ReadOnly: true},
}, ProviderVersion: provider.ClaudeVersion, LauncherVersion: "test", BwrapVersion: "0.11.0", EgressHosts: []string{"api.anthropic.com"}, Settings: json.RawMessage(`{}`), MCP: json.RawMessage(`{}`), Workspace: l.Workspace, Scratch: t.TempDir(), Argv: argv}
+ if len(missing) > 0 && missing[0] {
+ in.RuntimeFiles = in.RuntimeFiles[:len(in.RuntimeFiles)-1]
+ }
l.Policy, err = provider.BuildPolicy(l.Binding, in)
if err != nil {
t.Fatal(err)
@@ -76,16 +106,20 @@ func engineeringGoPolicy(t *testing.T, m *Manager, l provider.Launch, script str
}
func TestEngineeringOfflineGo(t *testing.T) {
- m, l := egressFixture(t)
- listener, err := net.Listen("tcp", "127.0.0.1:0")
- if err != nil {
- t.Fatal(err)
- }
- defer listener.Close()
- script := fmt.Sprintf(`import os,socket,subprocess
-expected={'GOPROXY':'off','GOSUMDB':'off','GOTOOLCHAIN':'local','GOFLAGS':'','CGO_ENABLED':'0','GOCACHE':'/tmp/go-build','GOTMPDIR':'/tmp/go-tmp','GOROOT':'/opt/go','GOMODCACHE':'/opt/go-mod','GOENV':'off','GOWORK':'off','GOTELEMETRY':'off'}
+ for _, name := range []string{"claude", "codex"} {
+ t.Run(name, func(t *testing.T) {
+ m, l := egressFixture(t)
+ listener, err := net.Listen("tcp", "127.0.0.1:0")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer listener.Close()
+ script := fmt.Sprintf(`import os,socket,subprocess
+expected={'GOPROXY':'off','GOSUMDB':'off','GOTOOLCHAIN':'local','GOFLAGS':'','CGO_ENABLED':'0','GOCACHE':'/tmp/claude-'+str(os.getuid())+'/go-build','GOTMPDIR':'/tmp/claude-'+str(os.getuid())+'/go-tmp','GOROOT':'/opt/go','GOMODCACHE':'/opt/go-mod','GOENV':'off','GOWORK':'off','GOTELEMETRY':'off'}
for k,v in expected.items(): assert os.environ.get(k)==v,(k,os.environ.get(k))
-assert os.environ['PATH'].split(':')[0]=='/opt/go/bin'
+assert os.environ['PATH'].endswith('/opt/go/bin:/usr/bin:/bin:/opt')
+assert 'XDG_CONFIG_HOME' not in os.environ
+assert os.environ['GIT_CONFIG_GLOBAL']=='/dev/null' and os.environ['GIT_CONFIG_NOSYSTEM']=='1'
subprocess.run(['go','version'],check=True)
# Opening for write must fail even without changing any source bytes.
for path in ['/opt/go/VERSION','/opt/go-mod/fixture.invalid/cached@v1.0.0/dep.go']:
@@ -100,89 +134,128 @@ else: raise AssertionError('host network reachable')
r=subprocess.run(['go','test','-mod=mod','-run','^TestCached$','.'],capture_output=True,text=True)
assert r.returncode==0,(r.stdout,r.stderr)
print(r.stdout,flush=True)
-os.mkdir('/tmp/missing')
-open('/tmp/missing/go.mod','w').write('module missing.invalid/app\n\ngo 1.26\n')
-open('/tmp/missing/app.go','w').write('package app\nimport _ "missing.invalid/uncached"\n')
-r=subprocess.run(['go','test','-mod=mod','-run','^TestMissing$','.'],cwd='/tmp/missing',capture_output=True,text=True)
+os.mkdir('/workspace/missing')
+open('/workspace/missing/go.mod','w').write('module missing.invalid/app\n\ngo 1.26\n')
+open('/workspace/missing/app.go','w').write('package app\nimport _ "missing.invalid/uncached"\n')
+r=subprocess.run(['go','test','-mod=mod','-run','^TestMissing$','.'],cwd='/workspace/missing',capture_output=True,text=True)
assert r.returncode!=0 and 'module lookup disabled by GOPROXY=off' in r.stderr,(r.returncode,r.stderr)
print('offline-cache-miss',flush=True)
# A pinned missing version fails at the read-only cache lock before Go's
# proxy lookup. The 'downloading' progress line does not mean a fetch ran.
-open('/tmp/missing/go.mod','a').write('\nrequire missing.invalid/uncached v1.0.0\n')
-r=subprocess.run(['go','test','-mod=mod','-run','^TestMissing$','.'],cwd='/tmp/missing',capture_output=True,text=True)
+open('/workspace/missing/go.mod','a').write('\nrequire missing.invalid/uncached v1.0.0\n')
+r=subprocess.run(['go','test','-mod=mod','-run','^TestMissing$','.'],cwd='/workspace/missing',capture_output=True,text=True)
assert r.returncode!=0 and 'read-only file system' in r.stderr,(r.returncode,r.stderr)
print('pinned-cache-miss-read-only',flush=True)
`, listener.Addr().(*net.TCPAddr).Port)
- // The fake Claude CLI executes the probe as a sandboxed Bash child would.
- // The toolchain must survive the second mount and network namespace too.
- prefix := append([]string{}, toolSandbox[:len(toolSandbox)-1]...)
- prefix = append(prefix, "--bind", "/workspace", "/workspace", "--bind", "/tmp", "/tmp", "--")
- shell, _ := json.Marshal(prefix)
- body, _ := json.Marshal(script)
- script = fmt.Sprintf("import json,subprocess\nsubprocess.run(json.loads(%q)+['/usr/bin/python3','-c',json.loads(%q)],check=True)", string(shell), string(body))
- l, argv, _ := engineeringGoPolicy(t, m, l, script)
- ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second)
- defer cancel()
- p, err := m.Start(ctx, l, argv)
- if err != nil {
- t.Fatal(err)
- }
- defer p.Stdin().Close()
- defer p.Stdout().Close()
- defer p.Stderr().Close()
- out, err := io.ReadAll(p.Stdout())
- if err != nil {
- t.Fatal(err)
- }
- stderr, _ := io.ReadAll(p.Stderr())
- exit, err := p.Wait(ctx)
- if err != nil || exit.Code != 0 {
- t.Fatalf("Go probe: %+v %v\n%s\n%s", exit, err, out, stderr)
+ script = engineeringShell(t, name, script)
+ l, argv, _ := engineeringGoPolicy(t, m, l, script)
+ ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second)
+ defer cancel()
+ p, err := m.Start(ctx, l, argv)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer p.Stdin().Close()
+ defer p.Stdout().Close()
+ defer p.Stderr().Close()
+ out, err := io.ReadAll(p.Stdout())
+ if err != nil {
+ t.Fatal(err)
+ }
+ stderr, _ := io.ReadAll(p.Stderr())
+ exit, err := p.Wait(ctx)
+ if err != nil || exit.Code != 0 {
+ t.Fatalf("Go probe: %+v %v\n%s\n%s", exit, err, out, stderr)
+ }
+ t.Log(string(out))
+ })
}
- t.Log(string(out))
}
func TestEngineeringGoDigest(t *testing.T) {
for _, target := range []string{"/opt/go", "/opt/go-mod"} {
t.Run(filepath.Base(target), func(t *testing.T) {
- for _, swap := range []bool{false, true} {
- t.Run(fmt.Sprint("after-attestation=", swap), func(t *testing.T) {
- m, l := egressFixture(t)
- l, argv, _ := engineeringGoPolicy(t, m, l, "print('must not run')")
- var source string
- for _, mount := range l.Policy.Mounts {
- if mount.Target == target {
- source = mount.Source
- }
- }
- mutate := func() {
- if swap {
- if err := os.Rename(source, source+"-old"); err != nil {
- t.Fatal(err)
- }
- t.Cleanup(func() { os.RemoveAll(source + "-old") })
- if err := os.Mkdir(source, 0700); err != nil {
- t.Fatal(err)
- }
- }
- if err := os.WriteFile(filepath.Join(source, "unexpected"), []byte("changed"), 0600); err != nil {
- t.Fatal(err)
- }
- }
- if swap {
- m.beforePin = mutate
- } else {
- mutate()
- if _, err := provider.AttestLaunch(l, argv); err == nil {
- t.Fatal("changed Go tree passed source attestation")
- }
- }
- p, err := m.Start(context.Background(), l, argv)
- if err == nil {
- m.Stop(context.Background(), p.ID())
- t.Fatal("changed Go tree launched")
+ m, l := egressFixture(t)
+ l, argv, _ := engineeringGoPolicy(t, m, l, "print('must not run')")
+ var source string
+ for _, mount := range l.Policy.Mounts {
+ if mount.Target == target {
+ source = mount.Source
+ }
+ }
+ // Replace the path after attestation. Containment must bind the original
+ // descriptor, never the replacement. Trusted in-place host edits are allowed.
+ if err := os.WriteFile(filepath.Join(source, "original"), []byte("original"), 0600); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := provider.AttestLaunch(l, argv); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Rename(source, source+"-old"); err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { os.RemoveAll(source + "-old") })
+ if err := os.Mkdir(source, 0700); err != nil {
+ t.Fatal(err)
+ }
+ dir := t.TempDir()
+ for _, part := range []string{"home", "tmp"} {
+ if err := os.Mkdir(filepath.Join(dir, part), 0700); err != nil {
+ t.Fatal(err)
+ }
+ }
+ plan, err := m.mountPlan(l, dir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer plan.close()
+ found := false
+ for i, arg := range plan.args {
+ if arg == target && i >= 2 && plan.args[i-2] == "--ro-bind-fd" {
+ var fd int
+ fmt.Sscanf(plan.args[i-1], "%d", &fd)
+ path := fmt.Sprintf("/proc/self/fd/%d/original", plan.files[fd-6].Fd())
+ if _, err := os.Stat(path); err != nil {
+ t.Fatal("replacement directory mounted", err)
}
- })
+ found = true
+ }
+ }
+ if !found {
+ t.Fatal("read-only retained descriptor missing")
+ }
+ })
+ }
+}
+
+func TestEngineeringMissingModuleCache(t *testing.T) {
+ for _, project := range []string{"go", "non-go"} {
+ t.Run(project, func(t *testing.T) {
+ m, l := egressFixture(t)
+ script := `import os,subprocess
+assert not os.path.exists('/opt/go-mod')
+subprocess.run(['/usr/bin/bash','-c','printf non-go-ok'],check=True)
+`
+ if project == "go" {
+ script += `open('/workspace/go.mod','w').write('module fixture.invalid/app\n\ngo 1.26\n')
+open('/workspace/app_test.go','w').write('package app\nimport "testing"\nfunc TestLocal(t *testing.T) {}\n')
+subprocess.run(['go','test','-run','^TestLocal$','.'],check=True)
+`
+ }
+ l, argv, _ := engineeringGoPolicy(t, m, l, engineeringShell(t, "claude", script), true)
+ ctx, cancel := context.WithTimeout(context.Background(), 45*time.Second)
+ defer cancel()
+ p, err := m.Start(ctx, l, argv)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer p.Stdin().Close()
+ defer p.Stdout().Close()
+ defer p.Stderr().Close()
+ out, stderr := engineeringOutput(p)
+ exit, err := p.Wait(ctx)
+ if err != nil || exit.Code != 0 {
+ t.Fatalf("missing cache: %+v %v %s %s", exit, err, out, stderr)
}
})
}
diff --git a/internal/runner/containment/engineering_settings_test.go b/internal/runner/containment/engineering_settings_test.go
new file mode 100644
index 00000000..778a1188
--- /dev/null
+++ b/internal/runner/containment/engineering_settings_test.go
@@ -0,0 +1,67 @@
+//go:build linux
+
+package containment
+
+import (
+ "amadan.net/oficina/equipo/internal/runner/provider"
+ "amadan.net/oficina/equipo/internal/runner/provider/claude"
+ "amadan.net/oficina/equipo/internal/runner/provider/codex"
+ "encoding/json"
+ "fmt"
+ "io"
+ "testing"
+)
+
+// Claude has no offline entry point for its bundled sandbox builder. This
+// reproduction consumes the generated filesystem settings and its pinned
+// defaults: cwd and CLAUDE_CODE_TMPDIR/claude-${uid}, never all of /tmp.
+// Codex exposes `sandbox`, so that branch invokes the real pinned executable.
+func engineeringShell(t *testing.T, name, body string) string {
+ t.Helper()
+ b := provider.Binding{Provider: name, Home: "/fake-runtime", CredentialHome: "/fake-source", RuntimeRoot: "/fake-homes"}
+ profile, _ := provider.Profile("implement")
+ in := provider.PolicyInputs{Action: "implement", Tools: profile.MCPTools()}
+ var err error
+ if name == "claude" {
+ in, err = claude.PolicyInputs(b, in, "Engineering", "claude-opus-5-5")
+ } else {
+ in, err = codex.PolicyInputs(b, in, "gpt-6-luna")
+ }
+ if err != nil {
+ t.Fatal(err)
+ }
+ settings, _ := json.Marshal(string(in.Settings))
+ script, _ := json.Marshal(body)
+ return fmt.Sprintf(`import json,os,subprocess
+settings=json.loads(%s)
+if %q=='claude':
+ s=settings['sandbox']; fs=s['filesystem']
+ assert s['enabled'] and s['failIfUnavailable'] and not s['allowUnsandboxedCommands'] and not s.get('enableWeakerNestedSandbox',False)
+ temp=os.path.join(os.environ.get('CLAUDE_CODE_TMPDIR','/tmp'),'claude-'+str(os.getuid()))
+ os.makedirs(temp,exist_ok=True)
+ prefix=['/opt/bwrap','--new-session','--die-with-parent','--unshare-net','--ro-bind','/','/']
+ for path in [os.getcwd(),temp]+fs.get('allowWrite',[]): prefix+=['--bind',path,path]
+ for path in fs['denyRead']:
+ if os.path.isdir(path) and path not in ['/proc','/dev/fd']: prefix+=['--tmpfs',path,'--remount-ro',path]
+ for path in fs['denyWrite']:
+ if os.path.isdir(path) and path not in fs['denyRead']: prefix+=['--ro-bind',path,path]
+ for path in ['/workspace/.git/config','/workspace/.git/hooks']:
+ if os.path.exists(path): prefix+=['--ro-bind',path,path]
+ prefix+=['--dev','/dev','--unshare-pid','--unshare-user','--proc','/proc','--disable-userns','--']
+else:
+ p=settings['permissions']['equipo']
+ fs=','.join(json.dumps(k)+'='+json.dumps(v) for k,v in sorted(p['filesystem'].items()))
+ prefix=['/opt/codex','sandbox','-P','equipo','-C','/workspace','-c','permissions.equipo.filesystem={'+fs+'}','-c','permissions.equipo.network.enabled='+str(p['network']['enabled']).lower(),'--']
+child={k:v for k,v in os.environ.items() if k!='CLAUDE_CODE_OAUTH_TOKEN'}
+r=subprocess.run(prefix+['/usr/bin/python3','-c',%s],env=child,capture_output=True,text=True)
+print(r.stdout,flush=True)
+assert r.returncode==0,(r.returncode,r.stderr)
+`, settings, name, script)
+}
+
+func engineeringOutput(p provider.Process) ([]byte, []byte) {
+ stderr := make(chan []byte, 1)
+ go func() { raw, _ := io.ReadAll(p.Stderr()); stderr <- raw }()
+ stdout, _ := io.ReadAll(p.Stdout())
+ return stdout, <-stderr
+}
diff --git a/internal/runner/containment/engineering_shell_test.go b/internal/runner/containment/engineering_shell_test.go
index 362d76ff..0c2b07de 100644
--- a/internal/runner/containment/engineering_shell_test.go
+++ b/internal/runner/containment/engineering_shell_test.go
@@ -7,6 +7,8 @@ import (
"encoding/json"
"fmt"
"io"
+ "os"
+ "strconv"
"strings"
"testing"
@@ -45,7 +47,7 @@ func TestEngineeringShellNesting(t *testing.T) {
if !settings.Sandbox.Enabled || !settings.Sandbox.FailIfUnavailable || settings.Sandbox.AllowUnsandboxedCommands || settings.Sandbox.EnableWeakerNestedSandbox {
t.Fatal("unsafe Bash settings")
}
- prefix = []string{"/usr/bin/bwrap", "--new-session", "--die-with-parent", "--unshare-net", "--ro-bind", "/", "/", "--bind", "/workspace", "/workspace", "--bind", "/tmp", "/tmp"}
+ prefix = []string{"/usr/bin/bwrap", "--new-session", "--die-with-parent", "--unshare-net", "--ro-bind", "/", "/", "--bind", "/workspace", "/workspace", "--bind", "/tmp/claude-" + strconv.Itoa(os.Getuid()), "/tmp/claude-" + strconv.Itoa(os.Getuid())}
// The pinned CLI applies deny masks before its fresh /dev and /proc.
for _, path := range settings.Sandbox.Filesystem.DenyRead {
if path == "/home" || path == "/proc" || path == "/config" || path == "/tool" || path == "/egress" {
@@ -79,6 +81,7 @@ func TestEngineeringShellNesting(t *testing.T) {
}
raw, _ := json.Marshal(prefix)
p := launch(t, m, l, fmt.Sprintf(`import json,subprocess,os
+os.makedirs("/tmp/claude-"+str(os.getuid()),exist_ok=True)
raw=json.loads(%q) or []
prefix=[]; i=0
while i<len(raw):
diff --git a/internal/runner/containment/engineering_token_test.go b/internal/runner/containment/engineering_token_test.go
new file mode 100644
index 00000000..a7555648
--- /dev/null
+++ b/internal/runner/containment/engineering_token_test.go
@@ -0,0 +1,78 @@
+//go:build linux
+
+package containment
+
+import (
+ "amadan.net/oficina/equipo/internal/runner/provider"
+ "context"
+ "encoding/json"
+ "fmt"
+ "strings"
+ "testing"
+ "time"
+)
+
+const goProcProbe = `package main
+import("bytes";"fmt";"os";"path/filepath";"strings")
+func main(){
+ holder,start:=os.Args[1],os.Args[2];tried:=0
+ try:=func(path string){tried++;raw,_:=os.ReadFile(path);if bytes.Contains(raw,[]byte("CLAUDE_CODE_OAUTH_TOKEN=")){fmt.Println("exposed",path)}}
+ procs,_:=filepath.Glob("/proc/[0-9]*")
+ for _,p:=range append(procs,"/proc/"+holder){
+ try(p+"/environ");try("/proc/self/../"+filepath.Base(p)+"/environ");try(p+"/root/proc/"+holder+"/environ")
+ threads,_:=filepath.Glob(p+"/task/*/environ");for _,t:=range threads{try(t)}
+ raw,_:=os.ReadFile(p+"/stat");parts:=strings.SplitAfterN(string(raw),") ",2)
+ if len(parts)==2 {fields:=strings.Fields(parts[1]);if len(fields)>19&&fields[19]==start{fmt.Println("visible",p)}}
+ }
+ for _,p:=range []string{"/proc/self/root/proc/","/proc/1/root/proc/"}{try(p+holder+"/environ")}
+ fmt.Println("tried",tried)
+}
+`
+
+func TestEngineeringGoTokenIsolation(t *testing.T) {
+ m, l := egressFixture(t)
+ m.secretEnv = func(provider.Launch) (map[string]string, error) {
+ return map[string]string{provider.OAuthTokenEnv: canary, provider.ScrubEnv: "1"}, nil
+ }
+ source, _ := json.Marshal(goProcProbe)
+ build := engineeringShell(t, "claude", fmt.Sprintf(`import subprocess
+open('/workspace/probe.go','w').write(%s)
+subprocess.run(['go','build','-o','/workspace/probe','/workspace/probe.go'],check=True)
+`, source))
+ buildJSON, _ := json.Marshal(build)
+ sandbox := engineeringShell(t, "claude", `import os,subprocess
+r=subprocess.run(['/workspace/probe',os.environ['HOLDER_PID'],os.environ['HOLDER_START']],capture_output=True,text=True)
+assert r.returncode==0
+assert 'exposed ' not in r.stdout and 'visible ' not in r.stdout,r.stdout
+assert 'tried ' in r.stdout
+print('go-token-isolation-ok')
+`)
+ sandboxJSON, _ := json.Marshal(sandbox)
+ script := fmt.Sprintf(`import os,subprocess
+exec(%s)
+os.environ['HOLDER_PID']=str(os.getpid())
+os.environ['HOLDER_START']=open('/proc/self/stat').read().rsplit(')',1)[1].split()[19]
+env={k:v for k,v in os.environ.items() if k!='CLAUDE_CODE_OAUTH_TOKEN'}
+r=subprocess.run(['/workspace/probe',os.environ['HOLDER_PID'],os.environ['HOLDER_START']],env=env,capture_output=True,text=True)
+assert r.returncode==0 and 'exposed /proc/'+os.environ['HOLDER_PID']+'/environ' in r.stdout
+exec(%s)
+`, buildJSON, sandboxJSON)
+ l, argv, _ := engineeringGoPolicy(t, m, l, script)
+ ctx, cancel := context.WithTimeout(context.Background(), 45*time.Second)
+ defer cancel()
+ p, err := m.Start(ctx, l, argv)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer p.Stdin().Close()
+ defer p.Stdout().Close()
+ defer p.Stderr().Close()
+ out, stderr := engineeringOutput(p)
+ exit, err := p.Wait(ctx)
+ if strings.Contains(string(out)+string(stderr), canary) {
+ t.Fatal("probe leaked token value")
+ }
+ if err != nil || exit.Code != 0 || !strings.Contains(string(out), "go-token-isolation-ok") {
+ t.Fatalf("Go probe: %+v %v %s %s", exit, err, out, stderr)
+ }
+}
diff --git a/internal/runner/containment/linux.go b/internal/runner/containment/linux.go
index 68ea76d8..e5400326 100644
--- a/internal/runner/containment/linux.go
+++ b/internal/runner/containment/linux.go
@@ -15,6 +15,7 @@ import (
"path/filepath"
"runtime"
"strconv"
+ "strings"
"sync"
"syscall"
"time"
@@ -218,12 +219,23 @@ func (m *Manager) startRecorded(ctx context.Context, l provider.Launch, argv []s
}
}
if l.Policy.IsCheck() || l.Policy.GoToolchain() {
- for _, name := range []string{"go-build", "go-tmp", "xdg/go/telemetry"} {
- if e = os.MkdirAll(filepath.Join(dir, "tmp", name), 0700); e != nil {
+ for _, key := range []string{"GOCACHE", "GOTMPDIR"} {
+ path := l.Policy.Env[key]
+ if !strings.HasPrefix(path, "/tmp/") || filepath.Clean(path) != path {
+ return nil, errMount
+ }
+ if e = os.MkdirAll(filepath.Join(dir, "tmp", strings.TrimPrefix(path, "/tmp/")), 0700); e != nil {
return nil, e
}
}
- if e = os.WriteFile(filepath.Join(dir, "tmp/xdg/go/telemetry/mode"), []byte("off\n"), 0600); e != nil {
+ }
+
+ if l.Policy.IsCheck() {
+ path := filepath.Join(dir, "tmp/xdg/go/telemetry")
+ if e = os.MkdirAll(path, 0700); e != nil {
+ return nil, e
+ }
+ if e = os.WriteFile(filepath.Join(path, "mode"), []byte("off\n"), 0600); e != nil {
return nil, e
}
}
diff --git a/internal/runner/containment/mounts.go b/internal/runner/containment/mounts.go
index 85ce63f6..3ce1c15d 100644
--- a/internal/runner/containment/mounts.go
+++ b/internal/runner/containment/mounts.go
@@ -289,17 +289,20 @@ func (m *Manager) mountPlan(l provider.Launch, dir string) (_ *mounts, err error
// A Pi launch's package tree is a directory, its digest checked by
// the attestation; every other mount is a pinned file.
tree := gotoolchain.Target(target) || l.Policy.IsPi() && target == provider.PiTree
- if err = p.bind(mount.Source, target, true, tree); err != nil {
- return nil, err
- }
+
if gotoolchain.Target(target) {
- pin, ok := l.Policy.GoTreePin(mount.Source, target)
- mounted := p.files[len(p.files)-1]
- sum, e := gotoolchain.Digest(fmt.Sprintf("/proc/self/fd/%d/.", mounted.Fd()))
- if !ok || e != nil || sum != pin {
- return nil, errMount
+ f, e := l.Policy.OpenGoTree(l.Binding, mount)
+ if e != nil {
+ return nil, e
}
+ err = p.bindPinned(f, mount.Source, target, true, tree)
+ } else {
+ err = p.bind(mount.Source, target, true, tree)
}
+ if err != nil {
+ return nil, err
+ }
+
if l.Policy.IsPi() && target == provider.PiTree {
// The tree as mounted, through the descriptor bubblewrap
// mounts, not by its path again: one replaced after the
@@ -344,7 +347,7 @@ func (m *Manager) mountPlan(l provider.Launch, dir string) (_ *mounts, err error
}
}
p.args = append(p.args, "--clearenv", "--setenv", "PATH", "/usr/bin:/bin:/opt", "--setenv", "HOME", "/home/runner", "--setenv", "TMPDIR", "/tmp", "--setenv", "LANG", "C.UTF-8")
- allowed := map[string]bool{"LANG": true, "LC_ALL": true, "TERM": true, "CODEX_HOME": true, "CLAUDE_CONFIG_DIR": true, "CLAUDE_SECURESTORAGE_CONFIG_DIR": true, "CLAUDE_TMPDIR": true, "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC": true, "DISABLE_AUTOUPDATER": true}
+ allowed := map[string]bool{"GIT_CONFIG_GLOBAL": l.Policy.Env["GIT_CONFIG_GLOBAL"] == "/dev/null", "GIT_CONFIG_NOSYSTEM": l.Policy.Env["GIT_CONFIG_NOSYSTEM"] == "1", "LANG": true, "LC_ALL": true, "TERM": true, "CODEX_HOME": true, "CLAUDE_CONFIG_DIR": true, "CLAUDE_SECURESTORAGE_CONFIG_DIR": true, "CLAUDE_TMPDIR": true, "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC": true, "DISABLE_AUTOUPDATER": true}
if signIn {
// The sign-in's browser opens nothing.
if l.Policy.Env["BROWSER"] != provider.SignInBrowser {
@@ -379,7 +382,7 @@ func (m *Manager) mountPlan(l provider.Launch, dir string) (_ *mounts, err error
allowed["NODE_EXTRA_CA_CERTS"] = provider.TestCAAllowed()
}
if l.Policy.IsCheck() || l.Policy.GoToolchain() {
- for k, v := range gotoolchain.Environment() {
+ for k, v := range gotoolchain.Environment(l.Selection.Provider) {
if l.Policy.Env[k] != v {
return nil, errMount
}
diff --git a/internal/runner/policy_inputs.go b/internal/runner/policy_inputs.go
index df53e1e1..579fcc1a 100644
--- a/internal/runner/policy_inputs.go
+++ b/internal/runner/policy_inputs.go
@@ -6,6 +6,7 @@ import (
"amadan.net/oficina/equipo/internal/runner/provider/claude"
"amadan.net/oficina/equipo/internal/runner/provider/codex"
"context"
+ "os"
"path/filepath"
)
@@ -43,7 +44,10 @@ func PolicyInputs(ctx context.Context, c Config, s provider.Selection, binding p
runtimeFiles = append(runtimeFiles, provider.Mount{Source: r.cfg.CodexCodeModeHostPath, Target: "/opt/codex-code-mode-host", ReadOnly: true})
}
if step == "implement" && c.GoRoot != "" {
- runtimeFiles = append(runtimeFiles, provider.Mount{Source: c.GoRoot, Target: "/opt/go", ReadOnly: true}, provider.Mount{Source: c.moduleCache(), Target: "/opt/go-mod", ReadOnly: true})
+ runtimeFiles = append(runtimeFiles, provider.Mount{Source: c.GoRoot, Target: "/opt/go", ReadOnly: true})
+ if _, err := os.Lstat(c.moduleCache()); !os.IsNotExist(err) {
+ runtimeFiles = append(runtimeFiles, provider.Mount{Source: c.moduleCache(), Target: "/opt/go-mod", ReadOnly: true})
+ }
}
profile, err := provider.Profile(step)
if err != nil {
diff --git a/internal/runner/policy_inputs_test.go b/internal/runner/policy_inputs_test.go
index 576f923a..59c23bbc 100644
--- a/internal/runner/policy_inputs_test.go
+++ b/internal/runner/policy_inputs_test.go
@@ -50,7 +50,8 @@ func TestRuntimeMountsStandaloneToolProxy(t *testing.T) {
binding := AccountBinding{ID: b.ID, LocalID: b.ID, Provider: b.Provider, Family: "gpt", Model: "model", AccountID: b.AccountID, ProviderHome: b.CredentialHome, ExpectedIdentity: b.Expected, Kind: "subscription"}
mustJournal(t, os.WriteFile(c.AccountBindingsPath, marshal([]AccountBinding{binding}), 0600))
r := Runtime{cfg: c}
- build := func() provider.Policy {
+ build := func(t *testing.T) provider.Policy {
+ r.cfg = c
source, err := c.DirectBinding(binding)
mustJournal(t, err)
account, err := provider.OpenAccount(context.Background(), source)
@@ -76,13 +77,29 @@ func TestRuntimeMountsStandaloneToolProxy(t *testing.T) {
}
return l.Policy
}
- first := build()
+ for _, project := range []string{"go", "non-go"} {
+ t.Run("missing-modules-"+project, func(t *testing.T) {
+ saved := c.ModuleCache
+ c.ModuleCache = filepath.Join(t.TempDir(), "absent")
+ defer func() { c.ModuleCache = saved }()
+ if project == "go" {
+ mustJournal(t, os.WriteFile(filepath.Join(c.WorkspaceRoot, "go.mod"), []byte("module fixture\n\ngo 1.26\n"), 0600))
+ defer os.Remove(filepath.Join(c.WorkspaceRoot, "go.mod"))
+ }
+ for _, m := range build(t).Mounts {
+ if m.Target == "/opt/go-mod" {
+ t.Fatal("missing cache mounted")
+ }
+ }
+ })
+ }
+ first := build(t)
mustJournal(t, os.WriteFile(c.Executable, []byte("another runner build"), 0700))
- if build().Hash != first.Hash {
+ if build(t).Hash != first.Hash {
t.Fatal("the runner executable changed the provider policy hash")
}
mustJournal(t, os.WriteFile(c.ToolProxyPath, []byte("changed helper"), 0700))
- if build().Hash == first.Hash {
+ if build(t).Hash == first.Hash {
t.Fatal("helper digest not bound to policy")
}
}
diff --git a/internal/runner/provider/accounts.go b/internal/runner/provider/accounts.go
index cab316b0..edd6a829 100644
--- a/internal/runner/provider/accounts.go
+++ b/internal/runner/provider/accounts.go
@@ -106,6 +106,9 @@ func privateDirectory(f *os.File) bool {
// all turns. Claude's identity is trust-on-first-use: Paul
// confirms CLI-observed metadata at enrolment. It is not remote attestation.
type AccountLease struct {
+ goMu sync.Mutex
+ goPins map[Mount]goPin
+ goClosed bool
mu sync.Mutex
sourceFreshUntil time.Time
source Binding
@@ -734,6 +737,13 @@ func (l *AccountLease) Close() error {
return nil
}
l.closed = true
+ l.goMu.Lock()
+ l.goClosed = true
+ for _, pin := range l.goPins {
+ pin.file.Close()
+ }
+ l.goPins = nil
+ l.goMu.Unlock()
l.ready = false
clear(l.token)
l.token = nil
diff --git a/internal/runner/provider/check_policy.go b/internal/runner/provider/check_policy.go
index 6f795a7f..0af25533 100644
--- a/internal/runner/provider/check_policy.go
+++ b/internal/runner/provider/check_policy.go
@@ -60,15 +60,7 @@ func BuildCheckPolicy(in CheckPolicyInputs) (Policy, error) {
if in.ModuleCache != "" {
m.OuterMounts = append(m.OuterMounts, Mount{Source: in.ModuleCache, Target: "/opt/go-mod", ReadOnly: true})
}
- for _, mount := range m.OuterMounts {
- if gotoolchain.Target(mount.Target) {
- pin, err := goTree(mount)
- if err != nil {
- return Policy{}, err
- }
- m.Files = append(m.Files, pin)
- }
- }
+
if in.Env != nil {
for k, v := range gotoolchain.Environment() {
if supplied, ok := in.Env[k]; ok && supplied != v {
@@ -119,13 +111,6 @@ func attestCheck(l Launch, argv []string) (string, error) {
return "", ErrPolicy
}
for _, f := range m.Files {
- if gotoolchain.Target(f.Mount.Target) {
- current, err := goTree(f.Mount)
- if err != nil || current.SHA256 != f.SHA256 {
- return "", ErrPolicy
- }
- continue
- }
raw, err := os.ReadFile(f.Mount.Source)
if err != nil || digest(raw) != f.SHA256 {
return "", ErrPolicy
diff --git a/internal/runner/provider/claude/go_policy_test.go b/internal/runner/provider/claude/go_policy_test.go
index fc0d8528..3623ef73 100644
--- a/internal/runner/provider/claude/go_policy_test.go
+++ b/internal/runner/provider/claude/go_policy_test.go
@@ -28,7 +28,7 @@ func TestEngineeringGoPolicyRoundTrip(t *testing.T) {
if _, err = f.l.validatePolicy(f.launch.Binding, p); err != nil {
t.Fatal(err)
}
- if p.Env["GOPROXY"] != "off" || p.Env["PATH"] != "/opt/go/bin:/usr/bin:/bin" {
+ if p.Env["GOPROXY"] != "off" || p.Env["PATH"] != "/opt/go/bin:/usr/bin:/bin:/opt" {
t.Fatal("offline Go environment missing")
}
}
diff --git a/internal/runner/provider/codex/go_policy_test.go b/internal/runner/provider/codex/go_policy_test.go
index e56dccef..a12188f3 100644
--- a/internal/runner/provider/codex/go_policy_test.go
+++ b/internal/runner/provider/codex/go_policy_test.go
@@ -28,7 +28,7 @@ func TestEngineeringGoPolicyRoundTrip(t *testing.T) {
if _, err = f.l.validatePolicy(f.launch.Binding, p); err != nil {
t.Fatal(err)
}
- if p.Env["GOPROXY"] != "off" || p.Env["PATH"] != "/opt/go/bin:/usr/bin:/bin" {
+ if p.Env["GOCACHE"] != "/tmp/go-build" || p.Env["GOTMPDIR"] != "/tmp/go-tmp" || p.Env["GOPROXY"] != "off" || p.Env["PATH"] != "/opt/go/bin:/usr/bin:/bin:/opt" {
t.Fatal("offline Go environment missing")
}
}
diff --git a/internal/runner/provider/go_policy.go b/internal/runner/provider/go_policy.go
index 6a5f75d7..280f4b4c 100644
--- a/internal/runner/provider/go_policy.go
+++ b/internal/runner/provider/go_policy.go
@@ -2,12 +2,13 @@ package provider
import (
"encoding/json"
+ "fmt"
"os"
"amadan.net/oficina/equipo/internal/runner/provider/gotoolchain"
+ "golang.org/x/sys/unix"
)
-// GoToolchain reports whether this policy mounts the offline Go trees.
func (p Policy) GoToolchain() bool {
for _, m := range p.Mounts {
if gotoolchain.Target(m.Target) {
@@ -17,33 +18,95 @@ func (p Policy) GoToolchain() bool {
return false
}
-// GoTreePin is the expected digest for the descriptor containment will mount.
-func (p Policy) GoTreePin(source, target string) (string, bool) {
- var m effectiveManifest
- if !gotoolchain.Target(target) || json.Unmarshal(p.Manifest, &m) != nil || digest(p.Manifest) != p.ManifestHash {
- return "", false
- }
- for _, f := range m.Files {
- if f.Mount.Source == source && f.Mount.Target == target && f.Mount.ReadOnly {
- return f.SHA256, true
- }
- }
- return "", false
+type goPin struct {
+ file *os.File
+ sum string
}
-func goTree(m Mount) (fileDigest, error) {
+// Go trees belong to the account lease, which spans policy builds, preflight
+// and launch. Only the Go root is hashed. The module cache is trusted host
+// state, mounted read-only; updates by the runner user do not change its pin.
+func goTree(m Mount, b Binding) (fileDigest, error) {
home, err := os.UserHomeDir()
if err != nil || !m.ReadOnly || !gotoolchain.Target(m.Target) || !cleanPath(m.Source) || m.Source == "/tmp" || withinPath(home, m.Source) {
return fileDigest{}, ErrPolicy
}
- f, err := pinDirectory(m.Source)
- if err != nil {
- return fileDigest{}, err
+ if b.provenance == nil {
+ return fileDigest{}, ErrPolicy
}
- defer f.Close()
- sum, err := gotoolchain.Digest(m.Source)
+ l := b.provenance
+ l.goMu.Lock()
+ defer l.goMu.Unlock()
+ if l.goClosed {
+ return fileDigest{}, ErrPolicy
+ }
+ if pin, ok := l.goPins[m]; ok {
+ return fileDigest{Mount: m, SHA256: pin.sum}, nil
+ }
+ f, err := openGoDirectory(m)
if err != nil {
return fileDigest{}, err
}
+ sum := ""
+ if m.Target == "/opt/go" {
+ sum, err = gotoolchain.Digest(fmt.Sprintf("/proc/self/fd/%d/.", f.Fd()))
+ if err != nil {
+ f.Close()
+ return fileDigest{}, err
+ }
+ }
+ if l.goPins == nil {
+ l.goPins = map[Mount]goPin{}
+ }
+ l.goPins[m] = goPin{f, sum}
return fileDigest{Mount: m, SHA256: sum}, nil
}
+
+func openGoDirectory(m Mount) (*os.File, error) {
+ f, err := pinDirectory(m.Source)
+ if err != nil {
+ return nil, err
+ }
+ var st unix.Stat_t
+ if unix.Fstat(int(f.Fd()), &st) != nil || (m.Target == "/opt/go-mod" && st.Uid != uint32(os.Getuid())) {
+ f.Close()
+ return nil, ErrPolicy
+ }
+ return f, nil
+}
+
+// OpenGoTree returns a duplicate of the validated launch descriptor. The
+// caller owns the duplicate; the account lease closes the original.
+func (p Policy) OpenGoTree(b Binding, mount Mount) (*os.File, error) {
+ var m effectiveManifest
+ if digest(p.Manifest) != p.ManifestHash || json.Unmarshal(p.Manifest, &m) != nil {
+ return nil, ErrPolicy
+ }
+ if p.IsCheck() {
+ return openGoDirectory(mount)
+ }
+ l := b.provenance
+ if l == nil {
+ return nil, ErrPolicy
+ }
+ l.goMu.Lock()
+ defer l.goMu.Unlock()
+ pin, ok := l.goPins[mount]
+ if !ok || l.goClosed {
+ return nil, ErrPolicy
+ }
+ found := false
+ for _, f := range m.Files {
+ if f.Mount == mount && f.SHA256 == pin.sum {
+ found = true
+ }
+ }
+ if !found {
+ return nil, ErrPolicy
+ }
+ fd, err := unix.FcntlInt(pin.file.Fd(), unix.F_DUPFD_CLOEXEC, 0)
+ if err != nil {
+ return nil, err
+ }
+ return os.NewFile(uintptr(fd), mount.Source), nil
+}
diff --git a/internal/runner/provider/go_policy_test.go b/internal/runner/provider/go_policy_test.go
index 336e619b..fec568b7 100644
--- a/internal/runner/provider/go_policy_test.go
+++ b/internal/runner/provider/go_policy_test.go
@@ -1,12 +1,14 @@
package provider
import (
+ "encoding/json"
"os"
"path/filepath"
+ "strings"
"testing"
)
-func TestCheckGoTreeDigest(t *testing.T) {
+func TestCheckGoPathPins(t *testing.T) {
for _, target := range []string{"root", "modules"} {
t.Run(target, func(t *testing.T) {
root, mods := t.TempDir(), t.TempDir()
@@ -26,8 +28,8 @@ func TestCheckGoTreeDigest(t *testing.T) {
if err = os.WriteFile(filepath.Join(dir, "changed"), []byte("changed"), 0600); err != nil {
t.Fatal(err)
}
- if _, err = AttestLaunch(l, in.Argv); err == nil {
- t.Fatal("changed Go tree accepted")
+ if _, err = AttestLaunch(l, in.Argv); err != nil {
+ t.Fatal("trusted host cache update refused", err)
}
})
}
@@ -44,33 +46,142 @@ func TestEngineeringGoScope(t *testing.T) {
}
})
}
- for _, source := range []string{"workspace", "scratch", "account", "ancestor", "symlink", "writable"} {
- t.Run(source, func(t *testing.T) {
+ for _, target := range []string{"/opt/go", "/opt/go-mod"} {
+ for _, source := range []string{"workspace", "scratch", "account", "ancestor", "symlink", "internal-symlink", "writable", "owner"} {
+ t.Run(filepath.Base(target)+"/"+source, func(t *testing.T) {
+ b, in := policyFixture(t)
+ in.Action = "implement"
+ path := t.TempDir()
+ ro := true
+ switch source {
+ case "workspace":
+ path = in.Workspace
+ case "scratch":
+ path = in.Scratch
+ case "account":
+ path = b.CredentialHome
+ case "ancestor":
+ path = filepath.Dir(b.CredentialHome)
+ case "symlink":
+ link := filepath.Join(t.TempDir(), "link")
+ if err := os.Symlink(path, link); err != nil {
+ t.Fatal(err)
+ }
+ path = link
+ case "owner":
+ if target == "/opt/go" {
+ t.Skip("Go may be installed by root")
+ }
+ if os.Getuid() == 0 {
+ t.Skip("needs a directory owned by another user")
+ }
+ path = "/usr/share"
+ case "internal-symlink":
+ if target == "/opt/go-mod" {
+ t.Skip("module cache is path pinned")
+ }
+ writeFake(t, filepath.Join(path, "VERSION"), "fixture")
+ if err := os.Symlink("VERSION", filepath.Join(path, "link")); err != nil {
+ t.Fatal(err)
+ }
+ case "writable":
+ ro = false
+ }
+ in.RuntimeFiles = append(in.RuntimeFiles, Mount{Source: path, Target: target, ReadOnly: ro})
+ if _, err := BuildPolicy(b, in); err == nil {
+ t.Fatal("unsafe Go tree admitted")
+ }
+ })
+ }
+ }
+
+}
+
+func TestEngineeringGitEnvironment(t *testing.T) {
+ b, in := policyFixture(t)
+ in.Action = "implement"
+ in.RuntimeFiles = append(in.RuntimeFiles, Mount{Source: t.TempDir(), Target: "/opt/go", ReadOnly: true})
+ p := mustPolicy(t, b, in)
+ for k, want := range map[string]string{"GIT_CONFIG_GLOBAL": "/dev/null", "GIT_CONFIG_NOSYSTEM": "1", "PATH": "/opt/go/bin:/usr/bin:/bin:/opt"} {
+ if p.Env[k] != want {
+ t.Errorf("%s=%q, want %q", k, p.Env[k], want)
+ }
+ }
+ if _, ok := p.Env["XDG_CONFIG_HOME"]; ok {
+ t.Error("provider receives writable Git config home")
+ }
+}
+
+func TestEngineeringGoPinReuse(t *testing.T) {
+ b, in := policyFixture(t)
+ in.Action = "implement"
+ root, mods := t.TempDir(), t.TempDir()
+ in.RuntimeFiles = append(in.RuntimeFiles, Mount{root, "/opt/go", true}, Mount{mods, "/opt/go-mod", true})
+ p := mustPolicy(t, b, in)
+ var manifest effectiveManifest
+ if err := json.Unmarshal(p.Manifest, &manifest); err != nil {
+ t.Fatal(err)
+ }
+ for _, f := range manifest.Files {
+ if f.Mount.Target == "/opt/go-mod" && f.SHA256 != "" {
+ t.Fatal("module cache was content hashed")
+ }
+ }
+ // Trusted host edits do not trigger another content scan in this launch.
+ writeFake(t, filepath.Join(root, "new"), "host update")
+ writeFake(t, filepath.Join(mods, "new"), "host update")
+ if err := p.ValidateSources(b); err != nil {
+ t.Fatal("rehashed launch sources", err)
+ }
+ if q := mustPolicy(t, b, in); q.ManifestHash != p.ManifestHash {
+ t.Fatal("rehashed policy rebuild")
+ }
+ held := b.provenance.goPins[in.RuntimeFiles[len(in.RuntimeFiles)-2]].file
+ if err := b.provenance.Close(); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := held.Stat(); err == nil {
+ t.Fatal("lease leaked its Go descriptor")
+ }
+ if f, err := p.OpenGoTree(b, in.RuntimeFiles[len(in.RuntimeFiles)-2]); err == nil {
+ f.Close()
+ t.Fatal("closed lease supplied a Go tree")
+ }
+
+}
+
+func TestEngineeringGoManifestTampering(t *testing.T) {
+ for _, field := range []string{"PATH", "digest"} {
+ t.Run(field, func(t *testing.T) {
b, in := policyFixture(t)
in.Action = "implement"
- path := t.TempDir()
- ro := true
- switch source {
- case "workspace":
- path = in.Workspace
- case "scratch":
- path = in.Scratch
- case "account":
- path = b.CredentialHome
- case "ancestor":
- path = filepath.Dir(b.CredentialHome)
- case "symlink":
- link := filepath.Join(t.TempDir(), "link")
- if err := os.Symlink(path, link); err != nil {
- t.Fatal(err)
+ in.RuntimeFiles = append(in.RuntimeFiles, Mount{t.TempDir(), "/opt/go", true})
+ p := mustPolicy(t, b, in)
+ var m effectiveManifest
+ if err := json.Unmarshal(p.Manifest, &m); err != nil {
+ t.Fatal(err)
+ }
+ if field == "PATH" {
+ m.Env["PATH"] = "/workspace:/usr/bin"
+ p.Env["PATH"] = m.Env["PATH"]
+ } else {
+ for i := range m.Files {
+ if m.Files[i].Mount.Target == "/opt/go" {
+ m.Files[i].SHA256 = strings.Repeat("0", 64)
+ }
}
- path = link
- case "writable":
- ro = false
}
- in.RuntimeFiles = append(in.RuntimeFiles, Mount{Source: path, Target: "/opt/go", ReadOnly: ro})
- if _, err := BuildPolicy(b, in); err == nil {
- t.Fatal("unsafe Go tree admitted")
+ p.Manifest, p.ManifestHash, _ = hashJSON(m)
+ _, p.Hash, _ = hashJSON(policyTemplate(m))
+ l := Launch{AttemptKey: "tamper", Workspace: in.Workspace, Binding: b, Selection: Selection{Provider: b.Provider, AccountID: b.AccountID}, Policy: p}
+ if _, err := AttestLaunch(l, in.Argv); err == nil {
+ t.Fatal("forged " + field + " accepted")
+ }
+ if field == "digest" {
+ if f, err := p.OpenGoTree(b, in.RuntimeFiles[len(in.RuntimeFiles)-1]); err == nil {
+ f.Close()
+ t.Fatal("forged descriptor digest accepted")
+ }
}
})
}
diff --git a/internal/runner/provider/gotoolchain/tree.go b/internal/runner/provider/gotoolchain/tree.go
index 64ac8ff2..bfd9ebb6 100644
--- a/internal/runner/provider/gotoolchain/tree.go
+++ b/internal/runner/provider/gotoolchain/tree.go
@@ -8,17 +8,30 @@ import (
"io"
"io/fs"
"os"
+ "strconv"
)
func Target(path string) bool { return path == "/opt/go" || path == "/opt/go-mod" }
-func Environment() map[string]string {
- return map[string]string{"GOCACHE": "/tmp/go-build", "GOTMPDIR": "/tmp/go-tmp", "GOMODCACHE": "/opt/go-mod", "GOROOT": "/opt/go", "GOTOOLCHAIN": "local", "GOWORK": "off", "GOENV": "off", "GOFLAGS": "", "GOTELEMETRY": "off", "GOPROXY": "off", "GOSUMDB": "off", "CGO_ENABLED": "0", "XDG_CONFIG_HOME": "/tmp/xdg", "PATH": "/opt/go/bin:/usr/bin:/bin"}
+func Environment(provider ...string) map[string]string {
+ tmp := "/tmp"
+ if len(provider) > 0 && provider[0] == "claude" {
+ tmp += "/claude-" + strconv.Itoa(os.Getuid())
+ }
+ env := map[string]string{"GOCACHE": tmp + "/go-build", "GOTMPDIR": tmp + "/go-tmp", "GOMODCACHE": "/opt/go-mod", "GOROOT": "/opt/go", "GOTOOLCHAIN": "local", "GOWORK": "off", "GOENV": "off", "GOFLAGS": "", "GOTELEMETRY": "off", "GOPROXY": "off", "GOSUMDB": "off", "CGO_ENABLED": "0", "PATH": "/opt/go/bin:/usr/bin:/bin:/opt"}
+ if len(provider) > 0 && provider[0] == "claude" {
+ env["CLAUDE_CODE_TMPDIR"] = "/tmp"
+ }
+ if len(provider) == 0 || provider[0] == "" {
+ env["XDG_CONFIG_HOME"] = "/tmp/xdg"
+ env["PATH"] = "/opt/go/bin:/usr/bin:/bin"
+ }
+ return env
}
// Digest includes every path, mode and file byte. No symlink or special file
-// can introduce content outside the approved tree. Host caches may be writable;
-// containment mounts the checked descriptor read-only and checks it again.
+// can introduce content outside the approved Go root. The caller retains the
+// root descriptor and reuses this digest for the launch.
func Digest(root string) (string, error) {
dir, err := os.OpenRoot(root)
if err != nil {
diff --git a/internal/runner/provider/policy.go b/internal/runner/provider/policy.go
index d12922e3..bb2bd0e3 100644
--- a/internal/runner/provider/policy.go
+++ b/internal/runner/provider/policy.go
@@ -213,7 +213,7 @@ func hashFiles(mounts []Mount, b Binding) ([]fileDigest, error) {
return nil, ErrPolicy
}
if gotoolchain.Target(m.Target) {
- f, e := goTree(m)
+ f, e := goTree(m, b)
if e != nil {
return nil, e
}
@@ -300,7 +300,7 @@ func BuildPolicy(b Binding, in PolicyInputs) (Policy, error) {
return Policy{}, ErrPolicy
}
}
- env := map[string]string{"LANG": "C.UTF-8"}
+ env := map[string]string{"LANG": "C.UTF-8", "GIT_CONFIG_GLOBAL": "/dev/null", "GIT_CONFIG_NOSYSTEM": "1"}
if b.Provider == "codex" {
env["CODEX_HOME"] = "/home/runner"
} else {
@@ -331,7 +331,7 @@ func BuildPolicy(b Binding, in PolicyInputs) (Policy, error) {
return Policy{}, ErrPolicy
}
}
- for k, v := range gotoolchain.Environment() {
+ for k, v := range gotoolchain.Environment(b.Provider) {
env[k] = v
}
}
@@ -585,7 +585,12 @@ func AttestLaunch(l Launch, argv []string) (string, error) {
}
}
if p.GoToolchain() {
- expectedEnv["PATH"] = m.Env["PATH"]
+ for k, v := range gotoolchain.Environment(l.Binding.Provider) {
+ if m.Env[k] != v {
+ return "", ErrPolicy
+ }
+ expectedEnv[k] = v
+ }
}
if !reflect.DeepEqual(expectedEnv, p.Env) {
return "", ErrPolicy