fix: bind reproductions and harden trusted check gates
8 files changed,
+448
−38
internal/equipo/artifacts.go+11 −6internal/equipotest/artifacts_test.go+39 −0internal/runner/checks/definition.go+42 −7internal/runner/checks/executor.go+34 −7internal/runner/checks/fixes_r1_test.go+177 −0internal/runner/checks/goresults.go+19 −1internal/runner/checks/sandbox.go+40 −9internal/runner/checks/sandbox_test.go+86 −8
CI failed — run details
diff --git a/internal/equipo/artifacts.go b/internal/equipo/artifacts.go| index 6ed5f17a..88930a6a 100644 |
| --- a/internal/equipo/artifacts.go |
| +++ b/internal/equipo/artifacts.go |
| @@ -99,15 +99,20 @@ func (s *Store) Blob(ctx context.Context, p RunnerPrincipal, scope team.Scope, d |
| if _, err := runnerPrincipalAt(tx, p, s.runnerClock.Now().UTC()); err != nil { |
| return err |
| } |
| - var assignments []runnerAssignment |
| - if err := tx.Where("team_id=? AND job_id=? AND runner_id=? AND person=?", scope.Account, scope.Job, p.RunnerID, p.Person).Find(&assignments).Error; err != nil { |
| + var a runnerAssignment |
| + // Only a live claimed step can read; ordering is stable across query plans. |
| + err := tx.Where("team_id=? AND job_id=? AND runner_id=? AND person=? AND state=? AND kind=?", scope.Account, scope.Job, p.RunnerID, p.Person, "claimed", "step").Order("attempt_id DESC, fence DESC, revision DESC, id DESC").First(&a).Error |
| + if errors.Is(err, gorm.ErrRecordNotFound) { |
| + return ErrForbidden |
| + } |
| + if err != nil { |
| return storeError(err) |
| } |
| - if len(assignments) == 0 { |
| - return ErrForbidden |
| + if _, err := s.execution.assignmentCurrent(ctx, tx, p, a); err != nil { |
| + return err |
| } |
| - // The reader must still have current project, person and connection authority. |
| - if _, err := s.execution.assignmentCurrent(ctx, tx, p, assignments[len(assignments)-1]); err != nil { |
| + h := team.Handle{Attempt: team.AttemptID(a.AttemptID), Fence: a.Fence, Runner: a.RunnerID} |
| + if err := s.execution.Core.ValidateHandle(ctx, scope, h); err != nil { |
| return err |
| } |
| var row artifactBlob |
diff --git a/internal/equipotest/artifacts_test.go b/internal/equipotest/artifacts_test.go| index ae3e04ce..f2dd4a77 100644 |
| --- a/internal/equipotest/artifacts_test.go |
| +++ b/internal/equipotest/artifacts_test.go |
| @@ -123,3 +123,42 @@ func TestArtifactRegistrationStaysCore(t *testing.T) { |
| t.Fatal("revoked runner read blob") |
| } |
| } |
| + |
| +func TestArtifactReadRequiresCurrentClaim(t *testing.T) { |
| + for _, change := range []string{"state", "kind", "fence", "expired"} { |
| + t.Run(change, func(t *testing.T) { |
| + f := runnerFixtureNew(t, true) |
| + b := []byte("current claim") |
| + digest := fmt.Sprintf("%x", sha256.Sum256(b)) |
| + executionMust(t, f.s.PutBlob(connectionContext, f.principal, f.claim.Scope, f.claim.Handle, digest, b)) |
| + query := map[string]string{ |
| + "state": "UPDATE runner_assignments SET state='contained' WHERE attempt_id=?", |
| + "kind": "UPDATE runner_assignments SET kind='prepare' WHERE attempt_id=?", |
| + "fence": "UPDATE runner_assignments SET fence=fence+1 WHERE attempt_id=?", |
| + "expired": "UPDATE attempts SET lease_deadline='2000-01-01T00:00:00Z' WHERE id=?", |
| + }[change] |
| + _, err := f.d.Writer().Exec(query, f.claim.Handle.Attempt) |
| + executionMust(t, err) |
| + if _, err := f.s.Blob(connectionContext, f.principal, f.claim.Scope, digest); err == nil { |
| + t.Fatal("blob read without current claimed attempt") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestArtifactReadAssignmentOrder(t *testing.T) { |
| + f := runnerFixtureNew(t, true) |
| + b := []byte("ordered claim") |
| + digest := fmt.Sprintf("%x", sha256.Sum256(b)) |
| + executionMust(t, f.s.PutBlob(connectionContext, f.principal, f.claim.Scope, f.claim.Handle, digest, b)) |
| + _, err := f.d.Writer().Exec(`INSERT INTO runner_assignments |
| + (id,task_id,step_key,team_id,runner_id,person,selection,isolation,kind,state,revision,job_id,attempt_id,fence) |
| + SELECT '000-old-late-row',task_id,step_key,team_id,runner_id,person,'{}',isolation,kind,state,revision+100,job_id,attempt_id,fence-1 |
| + FROM runner_assignments WHERE attempt_id=?`, f.claim.Handle.Attempt) |
| + executionMust(t, err) |
| + got, err := f.s.Blob(connectionContext, f.principal, f.claim.Scope, digest) |
| + executionMust(t, err) |
| + if !bytes.Equal(got, b) { |
| + t.Fatal("current claim did not read blob") |
| + } |
| +} |
diff --git a/internal/runner/checks/definition.go b/internal/runner/checks/definition.go| index 249a06a8..a42af780 100644 |
| --- a/internal/runner/checks/definition.go |
| +++ b/internal/runner/checks/definition.go |
| @@ -49,7 +49,7 @@ func commandValid(c Command, measured bool) bool { |
| } |
| } |
| if c.Parser == "exit" { |
| - return !measured |
| + return !measured && !(len(c.Argv) > 1 && filepath.Base(c.Argv[0]) == "go" && c.Argv[1] == "test") |
| } |
| if c.Parser != "go-test-json" || len(c.Argv) < 4 || c.Argv[0] != "go" || c.Argv[1] != "test" { |
| return false |
| @@ -395,7 +395,7 @@ func CandidateHash(c team.GitCandidate) string { |
| return Digest(encode(map[string]string{"repository": c.Repository, "base_commit": c.BaseCommit, "commit": c.Commit, "tree": c.Tree})) |
| } |
| -var baseMaterialPaths = []string{".equipo/checks.json", "go.mod", "go.sum", "go.work", "go.work.sum", "Makefile", ".amadan/ci", ".amadan/ci.d"} |
| +var baseMaterialPaths = []string{".equipo/checks.json", "go.mod", "go.sum", "go.work", "go.work.sum", "Makefile", "GNUmakefile", "makefile", ".amadan/ci", ".amadan/ci.d"} |
| func materialPaths(d Definition) []string { |
| return append(append([]string(nil), baseMaterialPaths...), d.TrustedPaths...) |
| @@ -414,17 +414,52 @@ func exitMaterialDeclared(d Definition, c Command) bool { |
| return true |
| } |
| program := filepath.Base(c.Argv[0]) |
| + if c.Argv[0] != program && c.Argv[0] != "/bin/"+program && c.Argv[0] != "/usr/bin/"+program { |
| + return false |
| + } |
| switch program { |
| case "sh", "bash", "python", "python3", "node": |
| - if len(c.Argv) < 2 || strings.HasPrefix(c.Argv[1], "-") { |
| + if len(c.Argv) < 2 || strings.HasPrefix(c.Argv[1], "-") || !frozenArgument(d, c.Dir, c.Argv[1]) { |
| return false |
| } |
| - return trustedMaterial(d, filepath.Clean(filepath.Join(c.Dir, c.Argv[1]))) |
| + case "make": |
| + // Default makefiles are pinned at the repository root. No option or variable overrides. |
| + if c.Dir != "." { |
| + return false |
| + } |
| + for _, arg := range c.Argv[1:] { |
| + if strings.HasPrefix(arg, "-") || strings.Contains(arg, "=") { |
| + return false |
| + } |
| + } |
| case "go": |
| - return len(c.Argv) > 1 && (c.Argv[1] == "vet" || c.Argv[1] == "test") |
| + // vet uses its default package. Explicit path operands must be frozen below. |
| + if len(c.Argv) < 2 || c.Argv[1] != "vet" { |
| + return false |
| + } |
| + for _, arg := range c.Argv[2:] { |
| + if strings.HasPrefix(arg, "-") || !frozenArgument(d, c.Dir, arg) { |
| + return false |
| + } |
| + } |
| + return true |
| + default: |
| + return false |
| } |
| - if !filepath.IsAbs(c.Argv[0]) && strings.Contains(c.Argv[0], "/") { |
| - return trustedMaterial(d, filepath.Clean(filepath.Join(c.Dir, c.Argv[0]))) |
| + for _, arg := range c.Argv[1:] { |
| + value := arg |
| + if _, after, ok := strings.Cut(arg, "="); ok { |
| + value = after |
| + } |
| + if strings.ContainsAny(value, "/\\") || strings.HasPrefix(value, ".") || filepath.Ext(value) != "" { |
| + if !frozenArgument(d, c.Dir, value) { |
| + return false |
| + } |
| + } |
| } |
| return true |
| } |
| + |
| +func frozenArgument(d Definition, dir, arg string) bool { |
| + return relative(arg) && trustedMaterial(d, filepath.Join(dir, arg)) |
| +} |
diff --git a/internal/runner/checks/executor.go b/internal/runner/checks/executor.go| index dcc78240..24d68701 100644 |
| --- a/internal/runner/checks/executor.go |
| +++ b/internal/runner/checks/executor.go |
| @@ -4,7 +4,6 @@ import ( |
| "bytes" |
| "context" |
| "database/sql" |
| - "encoding/json" |
| "io" |
| "os" |
| "path/filepath" |
| @@ -42,7 +41,7 @@ type Executor struct { |
| } |
| func New(cfg Config, sandbox *CodexSandbox) (*Executor, error) { |
| - if sandbox == nil || !filepath.IsAbs(sandbox.binary) || sandbox.version != CodexVersion || len(sandbox.protected) < 9 { |
| + if sandbox == nil || !filepath.IsAbs(sandbox.binary) || sandbox.version != CodexVersion || !filepath.IsAbs(sandbox.goBinary) || !filepath.IsAbs(sandbox.goRoot) || sandbox.goVersion != GoVersion || len(sandbox.protected) < 9 { |
| return nil, paseo.ErrContract |
| } |
| e, err := newExecutor(cfg, sandbox) |
| @@ -222,7 +221,10 @@ func (e *Executor) CaptureBaseline(ctx context.Context, d Definition) (TestBasel |
| } |
| if c.Parser == "go-test-json" { |
| names = append(names, r.names...) |
| - for p := range r.packages { |
| + for p, status := range r.packages { |
| + if status == "no-tests" { |
| + continue |
| + } |
| names = append(names, TestIdentity{Package: p}) |
| } |
| } |
| @@ -241,6 +243,7 @@ func (e *Executor) isolation(ctx context.Context) (team.IsolationSnapshot, error |
| if iso.Status != "confined" && iso.Status != "unconfined" || len(iso.ObservedTuples) == 0 { |
| return iso, paseo.ErrIdentity |
| } |
| + iso = canonicalIsolation(iso) |
| e.mu.Lock() |
| defer e.mu.Unlock() |
| iso.RunnerTainted = iso.RunnerTainted || e.exposure.RunnerTainted |
| @@ -263,9 +266,17 @@ func (e *Executor) isolation(ctx context.Context) (team.IsolationSnapshot, error |
| if iso.Status == "unconfined" && len(iso.AcknowledgementIDs) == 0 { |
| return iso, paseo.ErrIdentity |
| } |
| - _ = json.Unmarshal(encode(iso), &e.exposure) |
| + iso = canonicalIsolation(iso) |
| + e.exposure = canonicalIsolation(iso) |
| return iso, nil |
| } |
| +func canonicalIsolation(iso team.IsolationSnapshot) team.IsolationSnapshot { |
| + iso.AcknowledgementIDs = slices.Clone(iso.AcknowledgementIDs) |
| + iso.ObservedTuples = slices.Clone(iso.ObservedTuples) |
| + slices.Sort(iso.AcknowledgementIDs) |
| + slices.SortFunc(iso.ObservedTuples, func(a, b team.IsolationTuple) int { return bytes.Compare(encode(a), encode(b)) }) |
| + return iso |
| +} |
| func (e *Executor) attest(role team.Role, value any, iso team.IsolationSnapshot) { |
| e.mu.Lock() |
| defer e.mu.Unlock() |
| @@ -329,17 +340,30 @@ func (e *Executor) Reproduce(ctx context.Context, d Definition, r Reproduction, |
| subject = d.Base |
| role = team.RoleBaseResult |
| outcome = team.CheckFail |
| - if run.failed <= 0 || !run.matched { |
| + matched := false |
| + for _, id := range namesSorted(r.TestNames) { |
| + state := run.tests[id] |
| + if state == nil || !state.done || !state.failed { |
| + return result, paseo.ErrIdentity |
| + } |
| + matched = matched || state.matched |
| + } |
| + if !matched { |
| return result, paseo.ErrIdentity |
| } |
| } else if run.failed != 0 { |
| return result, paseo.ErrIdentity |
| } |
| + testsRun, testsFailed := run.run, run.failed |
| + if candidateHash == "" { |
| + testsRun = len(namesSorted(r.TestNames)) |
| + testsFailed = testsRun |
| + } |
| iso, err := e.isolation(ctx) |
| if err != nil { |
| return result, err |
| } |
| - result = team.CheckResult{ExitCode: code, LogHash: logHash, ReproductionHash: e.cfg.ReproductionHash, SubjectHash: subject, CheckDefinitionHash: e.cfg.DefinitionHash, Outcome: outcome, TestsRun: run.run, TestsFailed: run.failed, SubjectCommit: subjectCommit, OverlayHash: Digest(encode(r.Files)), CollisionChecked: true, ObservedNames: namesSorted(run.names), Isolation: iso, ExecutorBinary: e.binary, ExecutorVersion: e.version} |
| + result = team.CheckResult{ExitCode: code, LogHash: logHash, ReproductionHash: e.cfg.ReproductionHash, SubjectHash: subject, CheckDefinitionHash: e.cfg.DefinitionHash, Outcome: outcome, TestsRun: testsRun, TestsFailed: testsFailed, SubjectCommit: subjectCommit, OverlayHash: Digest(encode(r.Files)), CollisionChecked: true, ObservedNames: namesSorted(run.names), Isolation: iso, ExecutorBinary: e.binary, ExecutorVersion: e.version} |
| if outcome == team.CheckFail { |
| result.FailureMessage = r.ExpectedSymptom |
| } |
| @@ -376,7 +400,10 @@ func (e *Executor) RepositoryChecks(ctx context.Context, d Definition, candidate |
| logs = append(logs, log) |
| count += run.run |
| names = append(names, run.names...) |
| - for p := range run.packages { |
| + for p, status := range run.packages { |
| + if status == "no-tests" { |
| + continue |
| + } |
| names = append(names, TestIdentity{Package: p}) |
| } |
| } |
diff --git a/internal/runner/checks/fixes_r1_test.go b/internal/runner/checks/fixes_r1_test.go| new file mode 100644 |
| index 00000000..0f4f86cb |
| --- /dev/null |
| +++ b/internal/runner/checks/fixes_r1_test.go |
| @@ -0,0 +1,177 @@ |
| +package checks |
| + |
| +import ( |
| + "context" |
| + "slices" |
| + "testing" |
| + |
| + "amadan.net/oficina/equipo/internal/equipo/team" |
| +) |
| + |
| +func TestFrozenReproductionOwnFailure(t *testing.T) { |
| + for _, kind := range []string{"passing", "mixed", "unrelated_symptom", "counts"} { |
| + t.Run(kind, func(t *testing.T) { |
| + f := newFixture(t) |
| + put(t, f.base, "unrelated_test.go", `package fixture |
| +import "testing" |
| +func TestUnrelated(t *testing.T){t.Fatal("wrong value")} |
| +`) |
| + switch kind { |
| + case "passing": |
| + f.r.Files[0].Bytes = []byte("package fixture\nimport \"testing\"\nfunc TestBug(t *testing.T){}\n") |
| + case "mixed": |
| + f.r.TestNames = append(f.r.TestNames, TestIdentity{Package: "fixture", Name: "TestOld"}) |
| + case "unrelated_symptom": |
| + f.r.Files[0].Bytes = []byte("package fixture\nimport \"testing\"\nfunc TestBug(t *testing.T){t.Fatal(\"different\")}\n") |
| + } |
| + f.e.cfg.ReproductionHash = Digest(raw(f.r)) |
| + result, err := f.e.Reproduce(context.Background(), f.d, f.r, baseID, "") |
| + if kind == "counts" { |
| + must(t, err) |
| + if result.TestsRun != 1 || result.TestsFailed != 1 { |
| + t.Fatalf("counts include unrelated tests: %d/%d", result.TestsRun, result.TestsFailed) |
| + } |
| + } else if err == nil { |
| + t.Fatal("unrelated failure accepted as reproduction") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestRepositoryTestPackagesWithoutTests(t *testing.T) { |
| + f := newFixture(t) |
| + for _, root := range []string{f.base, f.candidate} { |
| + put(t, root, "types/value.go", "package types\ntype Value int\n") |
| + } |
| + baseline, err := f.e.CaptureBaseline(context.Background(), f.d) |
| + must(t, err) |
| + if slices.Contains(baseline.Names, TestIdentity{Package: "fixture/types"}) { |
| + t.Fatal("empty package entered baseline") |
| + } |
| + f.d.Baseline = baseline |
| + f.e.cfg.DefinitionHash = Digest(raw(f.d)) |
| + result, err := f.e.RepositoryChecks(context.Background(), f.d, f.c, f.hash) |
| + must(t, err) |
| + if slices.Contains(result.ObservedNames, TestIdentity{Package: "fixture/types"}) { |
| + t.Fatal("empty package entered observed identities") |
| + } |
| +} |
| + |
| +func TestTrustedMakefilePrecedence(t *testing.T) { |
| + for _, name := range []string{"GNUmakefile", "makefile"} { |
| + t.Run(name, func(t *testing.T) { |
| + f := newFixture(t) |
| + put(t, f.base, "Makefile", "check:\n\texit 1\n") |
| + put(t, f.candidate, name, "check:\n\texit 0\n") |
| + d, err := FreezeMaterial(context.Background(), f.d, f.base) |
| + must(t, err) |
| + d.Commands = append(d.Commands, Command{Argv: []string{"make", "check"}, Dir: ".", Parser: "exit", TimeoutSeconds: 10}) |
| + f.e.cfg.DefinitionHash = Digest(raw(d)) |
| + if _, err := f.e.RepositoryChecks(context.Background(), d, f.c, f.hash); err == nil { |
| + t.Fatal("candidate makefile replaced trusted gate") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestTrustedExitAllowlist(t *testing.T) { |
| + f := newFixture(t) |
| + for _, argv := range [][]string{ |
| + {"make", "-f", "other.mk"}, {"make", "--file=other.mk"}, {"make", "--makefile", "other.mk"}, |
| + {"make", "-Csub"}, {"make", "--directory=sub"}, {"make", "-I", "sub"}, |
| + {"perl", "gate.pl"}, {"ruby", "gate.rb"}, {"python3.12", "gate.py"}, {"env", "sh", "gate.sh"}, |
| + {"unknown"}, {"go", "test", "./..."}, {"go", "vet", "./..."}, {"/candidate/sh", "gate.sh"}, {"sh", "gate.sh", "untrusted/file"}, |
| + } { |
| + t.Run(argv[0]+"_"+argv[len(argv)-1], func(t *testing.T) { |
| + d := f.d |
| + d.TrustedPaths = []string{"gate.sh", "other.mk", "sub"} |
| + d.Commands = append(slices.Clone(d.Commands), Command{Argv: argv, Dir: ".", Parser: "exit", TimeoutSeconds: 10}) |
| + if _, err := ParseDefinition(context.Background(), raw(d), repoID, baseID); err == nil { |
| + t.Fatalf("unsafe exit gate accepted: %v", argv) |
| + } |
| + }) |
| + } |
| + d := f.d |
| + d.Commands = append(slices.Clone(d.Commands), Command{Argv: []string{"go", "vet"}, Dir: ".", Parser: "exit", TimeoutSeconds: 10}) |
| + _, err := ParseDefinition(context.Background(), raw(d), repoID, baseID) |
| + must(t, err) |
| +} |
| + |
| +func TestExecutorIsolationOrderAndOwnership(t *testing.T) { |
| + f := newFixture(t) |
| + iso := team.IsolationSnapshot{Status: "unconfined", RunnerTainted: true, AcknowledgementIDs: []string{"z", "a"}, ObservedTuples: []team.IsolationTuple{{Provider: "codex"}, {Provider: "claude"}}} |
| + f.e.cfg.Isolation = func(context.Context) (team.IsolationSnapshot, error) { return iso, nil } |
| + result, err := f.e.Reproduce(context.Background(), f.d, f.r, baseID, "") |
| + must(t, err) |
| + slices.Reverse(iso.AcknowledgementIDs) |
| + slices.Reverse(iso.ObservedTuples) |
| + _, err = f.e.ValidateEvidence(context.Background(), nil, f.e.cfg.Scope, f.e.cfg.Handle, team.ArtifactSpec{Role: team.RoleBaseResult, Payload: raw(result)}) |
| + must(t, err) |
| + snapshot, err := f.e.isolation(context.Background()) |
| + must(t, err) |
| + snapshot.AcknowledgementIDs[0] = "changed" |
| + snapshot.ObservedTuples[0].Provider = "changed" |
| + if slices.Contains(f.e.exposure.AcknowledgementIDs, "changed") || f.e.exposure.ObservedTuples[0].Provider == "changed" { |
| + t.Fatal("historical exposure aliases returned snapshot") |
| + } |
| + if slices.Contains(iso.AcknowledgementIDs, "changed") { |
| + t.Fatal("snapshot aliases callback") |
| + } |
| +} |
| + |
| +func TestExecutorNoTestPackageSkipGuard(t *testing.T) { |
| + for _, kind := range []string{"valid", "missing_output", "test_events", "test_output", "output_after_skip"} { |
| + t.Run(kind, func(t *testing.T) { |
| + g := newGoResults() |
| + event := func(action, pkg, test, output string) { |
| + g.event(append(raw(map[string]string{"Action": action, "Package": pkg, "Test": test, "Output": output}), '\n')) |
| + } |
| + event("start", "tested", "", "") |
| + event("run", "tested", "TestOne", "") |
| + event("pass", "tested", "TestOne", "") |
| + event("pass", "tested", "", "") |
| + event("start", "empty", "", "") |
| + if kind == "test_events" { |
| + event("run", "empty", "TestGone", "") |
| + event("pass", "empty", "TestGone", "") |
| + } |
| + if kind == "test_output" { |
| + event("output", "empty", "TestGone", "orphan output") |
| + } |
| + if kind != "missing_output" && kind != "output_after_skip" { |
| + event("output", "empty", "", "? \tempty\t[no test files]\n") |
| + } |
| + event("skip", "empty", "", "") |
| + if kind == "output_after_skip" { |
| + event("output", "empty", "", "? \tempty\t[no test files]\n") |
| + } |
| + err := g.finish(0, nil) |
| + if kind == "valid" { |
| + must(t, err) |
| + } else if err == nil { |
| + t.Fatal("invalid package skip accepted") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestTrustedExitParser(t *testing.T) { |
| + c := Command{Argv: []string{"go", "test", "./..."}, Dir: ".", Parser: "exit", TimeoutSeconds: 10} |
| + if commandValid(c, false) { |
| + t.Fatal("exit parser accepted go test") |
| + } |
| + c.Argv[1] = "vet" |
| + if !commandValid(c, false) { |
| + t.Fatal("exit parser refused go vet") |
| + } |
| +} |
| + |
| +func TestFrozenHashBoundary(t *testing.T) { |
| + f := newFixture(t) |
| + r := f.r |
| + r.Files = slices.Clone(r.Files) |
| + r.Files[0].Bytes = []byte(bugTest + "\n") |
| + if _, err := f.e.Reproduce(context.Background(), f.d, r, fixID, f.hash); err == nil { |
| + t.Fatal("changed valid frozen bytes accepted") |
| + } |
| +} |
diff --git a/internal/runner/checks/goresults.go b/internal/runner/checks/goresults.go| index 6329d7c0..a482077b 100644 |
| --- a/internal/runner/checks/goresults.go |
| +++ b/internal/runner/checks/goresults.go |
| @@ -46,6 +46,8 @@ type goResults struct { |
| log boundedLog |
| bad bool |
| packages map[string]string |
| + noTests map[string]bool |
| + testEvents map[string]bool |
| tests map[TestIdentity]*testState |
| names []TestIdentity |
| run, failed int |
| @@ -54,7 +56,7 @@ type goResults struct { |
| } |
| func newGoResults() *goResults { |
| - return &goResults{packages: map[string]string{}, tests: map[TestIdentity]*testState{}} |
| + return &goResults{packages: map[string]string{}, noTests: map[string]bool{}, testEvents: map[string]bool{}, tests: map[TestIdentity]*testState{}} |
| } |
| func (g *goResults) Write(p []byte) (int, error) { |
| n := len(p) |
| @@ -101,11 +103,24 @@ func (g *goResults) event(line []byte) { |
| } |
| g.packages[e.Package] = e.Action |
| case "output": |
| + fields := strings.Fields(e.Output) |
| + if len(fields) == 5 && fields[0] == "?" && fields[1] == e.Package && strings.Join(fields[2:], " ") == "[no test files]" && g.packages[e.Package] == "running" { |
| + g.noTests[e.Package] = true |
| + } |
| + case "skip": |
| + if g.packages[e.Package] != "running" || !g.noTests[e.Package] { |
| + g.bad = true |
| + } |
| + if g.testEvents[e.Package] { |
| + g.bad = true |
| + } |
| + g.packages[e.Package] = "no-tests" |
| default: |
| g.bad = true |
| } |
| return |
| } |
| + g.testEvents[e.Package] = true |
| switch e.Action { |
| case "run": |
| if g.packages[e.Package] != "running" || g.tests[id] != nil { |
| @@ -157,6 +172,9 @@ func (g *goResults) finish(exit int, err error) error { |
| } |
| } |
| for p, status := range g.packages { |
| + if status == "no-tests" { |
| + continue |
| + } |
| if status != "pass" && status != "fail" { |
| return paseo.ErrContract |
| } |
diff --git a/internal/runner/checks/sandbox.go b/internal/runner/checks/sandbox.go| index 9b8187b5..4ea63acd 100644 |
| --- a/internal/runner/checks/sandbox.go |
| +++ b/internal/runner/checks/sandbox.go |
| @@ -19,14 +19,17 @@ import ( |
| ) |
| const CodexVersion = "codex-cli 0.165.0" |
| +const GoVersion = "go1.26.10" |
| type SandboxConfig struct { |
| Binary, ScratchRoot string |
| + GoRoot, GoBinary string |
| Protected workspace.SecurityPaths |
| } |
| type CodexSandbox struct { |
| binary, version, scratch, home string |
| protected []string |
| + goRoot, goBinary, goVersion string |
| } |
| func NewCodexSandbox(ctx context.Context, cfg SandboxConfig) (*CodexSandbox, error) { |
| @@ -56,7 +59,28 @@ func NewCodexSandbox(ctx context.Context, cfg SandboxConfig) (*CodexSandbox, err |
| if err != nil || strings.TrimSpace(string(b)) != CodexVersion { |
| return nil, paseo.ErrContract |
| } |
| - return &CodexSandbox{binary: binary, version: CodexVersion, scratch: cfg.ScratchRoot, home: home, protected: paths}, nil |
| + if !filepath.IsAbs(cfg.GoRoot) || !filepath.IsAbs(cfg.GoBinary) { |
| + return nil, paseo.ErrContract |
| + } |
| + goRoot, err := filepath.EvalSymlinks(cfg.GoRoot) |
| + if err != nil { |
| + return nil, err |
| + } |
| + info, err := os.Stat(goRoot) |
| + if err != nil || !info.IsDir() { |
| + return nil, paseo.ErrContract |
| + } |
| + goBinary, err := filepath.EvalSymlinks(cfg.GoBinary) |
| + if err != nil || goBinary != filepath.Join(goRoot, "bin/go") { |
| + return nil, paseo.ErrContract |
| + } |
| + cmd = exec.CommandContext(ctx, goBinary, "version") |
| + cmd.Env = []string{"PATH=/usr/bin:/bin", "GOROOT=" + goRoot, "GOTOOLCHAIN=local", "GOENV=off"} |
| + b, err = cmd.Output() |
| + if err != nil || strings.TrimSpace(string(b)) != "go version "+GoVersion+" "+runtime.GOOS+"/"+runtime.GOARCH { |
| + return nil, paseo.ErrContract |
| + } |
| + return &CodexSandbox{binary: binary, version: CodexVersion, scratch: cfg.ScratchRoot, home: home, protected: paths, goRoot: goRoot, goBinary: goBinary, goVersion: GoVersion}, nil |
| } |
| func canonicalPath(path string) (string, error) { |
| if !filepath.IsAbs(path) || filepath.Clean(path) != path || strings.ContainsAny(path, "*?[\x00") { |
| @@ -109,16 +133,23 @@ func (s *CodexSandbox) Run(ctx context.Context, c Command, work string, policy p |
| defer os.RemoveAll(control) |
| // A fresh config home prevents user/project profiles and login state entering the command. |
| cfgHome := filepath.Join(control, "codex") |
| - temp := filepath.Join(work, ".equipo-check-tmp") |
| - if err = os.Mkdir(cfgHome, 0700); err != nil { |
| + temp, err := os.MkdirTemp(work, ".equipo-check-") |
| + if err != nil { |
| return -1, err |
| } |
| - if err = os.Mkdir(temp, 0700); err != nil { |
| + defer os.RemoveAll(temp) |
| + cache := filepath.Join(temp, "go-build") |
| + goTemp := filepath.Join(temp, "go-tmp") |
| + for _, path := range []string{cache, goTemp} { |
| + if err := os.Mkdir(path, 0700); err != nil { |
| + return -1, err |
| + } |
| + } |
| + if err = os.Mkdir(cfgHome, 0700); err != nil { |
| return -1, err |
| } |
| - defer os.RemoveAll(temp) |
| - roots := map[string]string{":minimal": "read", s.binary: "read", runtime.GOROOT(): "read", work: "write", filepath.Join(s.home, ".cache/go-build"): "write", filepath.Join(s.home, "go/pkg/mod"): "read"} |
| - for _, p := range []string{runtime.GOROOT(), filepath.Join(s.home, "go/pkg/mod"), filepath.Join(s.home, ".cache/go-build")} { |
| + roots := map[string]string{":minimal": "read", s.binary: "read", s.goRoot: "read", work: "write", filepath.Join(s.home, ".cache/go-build"): "deny", filepath.Join(s.home, "go/pkg/mod"): "read"} |
| + for _, p := range []string{s.goRoot, filepath.Join(s.home, "go/pkg/mod"), filepath.Join(s.home, ".cache/go-build")} { |
| r, err := canonicalPath(p) |
| if err != nil { |
| return -1, err |
| @@ -143,14 +174,14 @@ func (s *CodexSandbox) Run(ctx context.Context, c Command, work string, policy p |
| args := []string{"sandbox", "-P", "equipo-checks", "-C", filepath.Join(work, c.Dir), "-c", "permissions.equipo-checks.filesystem={" + strings.Join(entries, ",") + "}", "-c", "permissions.equipo-checks.network.enabled=false", "--"} |
| argv := append([]string(nil), c.Argv...) |
| if argv[0] == "go" { |
| - argv[0] = filepath.Join(runtime.GOROOT(), "bin/go") |
| + argv[0] = s.goBinary |
| } |
| args = append(args, argv...) |
| ctx, cancel := context.WithTimeout(ctx, time.Duration(c.TimeoutSeconds)*time.Second) |
| defer cancel() |
| cmd := exec.CommandContext(ctx, s.binary, args...) |
| cmd.Dir = control |
| - cmd.Env = []string{"PATH=" + filepath.Join(runtime.GOROOT(), "bin") + ":/usr/bin:/bin", "HOME=" + s.home, "CODEX_HOME=" + cfgHome, "TMPDIR=" + temp, "CGO_ENABLED=0", "GOTOOLCHAIN=local", "GOWORK=off", "GOENV=off", "GOFLAGS=", "GOPROXY=off", "GOSUMDB=off", "LANG=C", "LC_ALL=C"} |
| + cmd.Env = []string{"PATH=" + filepath.Join(s.goRoot, "bin") + ":/usr/bin:/bin", "HOME=" + s.home, "CODEX_HOME=" + cfgHome, "TMPDIR=" + temp, "GOCACHE=" + cache, "GOTMPDIR=" + goTemp, "GOROOT=" + s.goRoot, "CGO_ENABLED=0", "GOTOOLCHAIN=local", "GOWORK=off", "GOENV=off", "GOFLAGS=", "GOPROXY=off", "GOSUMDB=off", "LANG=C", "LC_ALL=C"} |
| cmd.Stdout = stdout |
| cmd.Stderr = stderr |
| cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} |
diff --git a/internal/runner/checks/sandbox_test.go b/internal/runner/checks/sandbox_test.go| index 151ba569..ba3b41d1 100644 |
| --- a/internal/runner/checks/sandbox_test.go |
| +++ b/internal/runner/checks/sandbox_test.go |
| @@ -19,19 +19,25 @@ func TestCheckSandboxDeniedPaths(t *testing.T) { |
| work := filepath.Join(root, "work") |
| must(t, os.Mkdir(work, 0700)) |
| put(t, work, "control", "readable") |
| + protectedRoot := filepath.Join(root, "go/pkg/mod") |
| var denied []string |
| for _, name := range []string{"state", "config", "journal", "bearer", "cleanup", "amadan", "paseo", "codex", "claude", "ssh", "resolved"} { |
| - p := filepath.Join(root, name) |
| - put(t, root, name+"/sentinel", "secret-"+name) |
| + p := filepath.Join(protectedRoot, name) |
| + put(t, protectedRoot, name+"/sentinel", "secret-"+name) |
| denied = append(denied, p) |
| } |
| must(t, os.Symlink(denied[len(denied)-1], filepath.Join(root, "alias"))) |
| denied = append(denied, filepath.Join(root, "alias")) |
| binary, err := exec.LookPath("codex") |
| must(t, err) |
| - s, err := NewCodexSandbox(context.Background(), testSandboxConfig(binary, root)) |
| + cfg := testSandboxConfig(t, binary, protectedRoot) |
| + cfg.ScratchRoot = root |
| + cfg.Protected.ProviderHomes[len(cfg.Protected.ProviderHomes)-1] = filepath.Join(root, "alias") |
| + s, err := NewCodexSandbox(context.Background(), cfg) |
| must(t, err) |
| - policy := paseo.ReadPolicy{ConfigHash: "sentinel", DeniedPaths: denied} |
| + // Sentinels sit beneath an allowed read root so each explicit deny is necessary. |
| + s.home = root |
| + policy := paseo.ReadPolicy{ConfigHash: "sentinel", DeniedPaths: []string{filepath.Join(root, "policy-only")}} |
| for _, path := range denied { |
| t.Run(filepath.Base(path), func(t *testing.T) { |
| var out, errout bytes.Buffer |
| @@ -69,7 +75,7 @@ func TestCheckSandboxDeniedPathsGoFixture(t *testing.T) { |
| put(t, root, "secret", "secret") |
| binary, err := exec.LookPath("codex") |
| must(t, err) |
| - s, err := NewCodexSandbox(context.Background(), testSandboxConfig(binary, root)) |
| + s, err := NewCodexSandbox(context.Background(), testSandboxConfig(t, binary, root)) |
| must(t, err) |
| policy := paseo.ReadPolicy{ConfigHash: "policy", DeniedPaths: []string{secret}} |
| var out, stderr bytes.Buffer |
| @@ -94,7 +100,7 @@ func TestCheckSandboxDeniedPathsTampering(t *testing.T) { |
| t.Setenv("EQUIPO_TEST_CREDENTIAL", "must-not-leak") |
| binary, err := exec.LookPath("codex") |
| must(t, err) |
| - s, err := NewCodexSandbox(context.Background(), testSandboxConfig(binary, root)) |
| + s, err := NewCodexSandbox(context.Background(), testSandboxConfig(t, binary, root)) |
| must(t, err) |
| policy := paseo.ReadPolicy{ConfigHash: "policy", DeniedPaths: []string{secret}} |
| var out, stderr bytes.Buffer |
| @@ -123,7 +129,79 @@ func TestCheckSandboxDeniedPathsRequired(t *testing.T) { |
| } |
| } |
| -func testSandboxConfig(binary, root string) SandboxConfig { |
| +func testSandboxConfig(t *testing.T, binary, root string) SandboxConfig { |
| + t.Helper() |
| + goBinary, err := exec.LookPath("go") |
| + must(t, err) |
| + goBinary, err = filepath.EvalSymlinks(goBinary) |
| + must(t, err) |
| + goRoot := filepath.Dir(filepath.Dir(goBinary)) |
| p := func(s string) string { return filepath.Join(root, s) } |
| - return SandboxConfig{Binary: binary, ScratchRoot: root, Protected: workspace.SecurityPaths{RunnerState: p("state"), RunnerConfig: p("config"), Journal: p("journal"), Bearer: p("bearer"), Cleanup: p("cleanup"), ForgeCredential: p("amadan"), PaseoHome: p("paseo"), SSH: p("ssh"), ProviderHomes: []string{p("codex"), p("claude")}}} |
| + return SandboxConfig{Binary: binary, ScratchRoot: root, GoRoot: goRoot, GoBinary: goBinary, Protected: workspace.SecurityPaths{RunnerState: p("state"), RunnerConfig: p("config"), Journal: p("journal"), Bearer: p("bearer"), Cleanup: p("cleanup"), ForgeCredential: p("amadan"), PaseoHome: p("paseo"), SSH: p("ssh"), ProviderHomes: []string{p("codex"), p("claude"), p("alias")}}} |
| +} |
| + |
| +func TestCheckSandboxDeniedPathsCache(t *testing.T) { |
| + root := t.TempDir() |
| + work := filepath.Join(root, "work") |
| + must(t, os.Mkdir(work, 0700)) |
| + binary, err := exec.LookPath("codex") |
| + must(t, err) |
| + s, err := NewCodexSandbox(context.Background(), testSandboxConfig(t, binary, root)) |
| + must(t, err) |
| + cache := filepath.Join(s.home, ".cache/go-build") |
| + probe, err := os.CreateTemp(cache, "equipo-cache-probe-") |
| + must(t, err) |
| + must(t, probe.Close()) |
| + defer os.Remove(probe.Name()) |
| + policy := paseo.ReadPolicy{ConfigHash: "cache", DeniedPaths: []string{filepath.Join(root, "secret")}} |
| + var previous string |
| + for range 2 { |
| + var out, stderr bytes.Buffer |
| + code, err := s.Run(context.Background(), Command{Argv: []string{"/bin/sh", "-c", `printf '%s\n' "$GOCACHE"; test -n "$GOCACHE" && test -d "$GOCACHE" && touch "$GOCACHE/probe" && ! (echo poison > "$1")`, "probe", probe.Name()}, Dir: ".", TimeoutSeconds: 10}, work, policy, &out, &stderr) |
| + must(t, err) |
| + if code != 0 { |
| + t.Fatalf("cache isolation failed: %d %s %s", code, &out, &stderr) |
| + } |
| + path := strings.TrimSpace(out.String()) |
| + if !within(root, path) || path == previous { |
| + t.Fatalf("cache not fresh inside scratch: %q", path) |
| + } |
| + if _, err := os.Stat(path); !os.IsNotExist(err) { |
| + t.Fatal("cache scratch retained") |
| + } |
| + previous = path |
| + } |
| +} |
| + |
| +func TestCheckSandboxToolchain(t *testing.T) { |
| + root := t.TempDir() |
| + binary, err := exec.LookPath("codex") |
| + must(t, err) |
| + for _, kind := range []string{"missing", "relative", "nonexistent", "binary_missing", "binary_relative", "binary_nonexistent", "wrong_version"} { |
| + t.Run(kind, func(t *testing.T) { |
| + cfg := testSandboxConfig(t, binary, root) |
| + switch kind { |
| + case "missing": |
| + cfg.GoRoot = "" |
| + case "relative": |
| + cfg.GoRoot = "go" |
| + case "nonexistent": |
| + cfg.GoRoot = filepath.Join(root, "absent") |
| + case "binary_missing": |
| + cfg.GoBinary = "" |
| + case "binary_relative": |
| + cfg.GoBinary = "go" |
| + case "binary_nonexistent": |
| + cfg.GoBinary = filepath.Join(cfg.GoRoot, "bin/absent") |
| + case "wrong_version": |
| + cfg.GoRoot = filepath.Join(root, "fake-go") |
| + cfg.GoBinary = filepath.Join(cfg.GoRoot, "bin/go") |
| + put(t, cfg.GoRoot, "bin/go", "#!/bin/sh\necho 'go version go1.1 linux/amd64'\n") |
| + must(t, os.Chmod(cfg.GoBinary, 0700)) |
| + } |
| + if _, err := NewCodexSandbox(context.Background(), cfg); err == nil { |
| + t.Fatal("invalid toolchain accepted") |
| + } |
| + }) |
| + } |
| } |