feat: execute frozen reproductions and base-pinned checks
16 files changed,
+2,302
−18
.rastrillo/budgets.txt+1 −0internal/equipo/artifacts.go+124 −0internal/equipo/migrations/0014_artifact_blobs.sql+2 −0internal/equipo/migrations/schema.sql+2 −0internal/equipo/models.go+1 −1internal/equipo/runner_api.go+42 −0internal/equipo/team/git_evidence.go+19 −10internal/equipo/team/model.go+16 −7internal/equipotest/artifacts_test.go+125 −0internal/runner/checks/definition.go+430 −0internal/runner/checks/executor.go+429 −0internal/runner/checks/executor_test.go+575 −0internal/runner/checks/goresults.go+181 −0internal/runner/checks/sandbox.go+180 −0internal/runner/checks/sandbox_test.go+129 −0internal/runnerproto/types.go+46 −0
CI failed — run details
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt| index 9f56bd1f..16c96a6f 100644 |
| --- a/.rastrillo/budgets.txt |
| +++ b/.rastrillo/budgets.txt |
| @@ -16,3 +16,4 @@ time internal/equipotest 25s Task 6 keeps the mandated connections tests in this |
| size internal/equipo 6500 - Task 8 keeps the mandated runner API, assignment, credential rotation and provenance adapters in the app package alongside the shared transaction and roster checks. |
| size internal/equipotest - 8300 Task 8 keeps the mandated runner_api_test.go route, ticket, containment, provenance and failure tests beside the existing activation database fixtures; they add coverage across all runner endpoints and cross-job concurrency. |
| +time internal/runner/checks 15s Task 11 runs real Go fixtures and Codex sandbox sentinels, including timeout and child-process cleanup; the targeted suite took 10.710s on the shared machine. |
diff --git a/internal/equipo/artifacts.go b/internal/equipo/artifacts.go| new file mode 100644 |
| index 00000000..6ed5f17a |
| --- /dev/null |
| +++ b/internal/equipo/artifacts.go |
| @@ -0,0 +1,124 @@ |
| +package equipo |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "crypto/sha256" |
| + "encoding/hex" |
| + "errors" |
| + |
| + "amadan.net/oficina/equipo/internal/equipo/team" |
| + "gorm.io/gorm" |
| +) |
| + |
| +const MaxBlobBytes = 1 << 20 |
| +const MaxAttemptBlobBytes = 128 << 20 |
| + |
| +type artifactBlob struct { |
| + TeamID string `gorm:"primaryKey"` |
| + JobID int64 `gorm:"primaryKey;autoIncrement:false"` |
| + Digest string `gorm:"primaryKey"` |
| + Bytes []byte |
| +} |
| + |
| +func (artifactBlob) TableName() string { return "artifact_blobs" } |
| + |
| +type artifactBlobUpload struct { |
| + AttemptID int64 `gorm:"primaryKey;autoIncrement:false"` |
| + Digest string `gorm:"primaryKey"` |
| + Size int64 |
| +} |
| + |
| +func (artifactBlobUpload) TableName() string { return "artifact_blob_uploads" } |
| +func blobDigest(b []byte) string { sum := sha256.Sum256(b); return hex.EncodeToString(sum[:]) } |
| +func (s *Store) PutBlob(ctx context.Context, p RunnerPrincipal, scope team.Scope, h team.Handle, digest string, data []byte) error { |
| + if len(data) == 0 || len(data) > MaxBlobBytes || blobDigest(data) != digest { |
| + return ErrInvalid |
| + } |
| + if s.execution == nil { |
| + return ErrUnavailable |
| + } |
| + return s.execution.atomic(ctx, func(ctx context.Context, tx *gorm.DB) error { |
| + var a runnerAssignment |
| + if err := tx.First(&a, "team_id=? AND job_id=? AND attempt_id=? AND fence=? AND runner_id=?", scope.Account, scope.Job, h.Attempt, h.Fence, h.Runner).Error; err != nil { |
| + return storeError(err) |
| + } |
| + if _, err := s.execution.assignmentCurrent(ctx, tx, p, a); err != nil { |
| + return err |
| + } |
| + if a.State != "claimed" || a.Kind != "step" { |
| + return ErrForbidden |
| + } |
| + if err := s.execution.Core.ValidateHandle(ctx, scope, h); err != nil { |
| + return err |
| + } |
| + var old artifactBlob |
| + err := tx.First(&old, "team_id=? AND job_id=? AND digest=?", scope.Account, scope.Job, digest).Error |
| + if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) { |
| + return storeError(err) |
| + } |
| + exists := err == nil |
| + if exists && (!bytes.Equal(old.Bytes, data) || blobDigest(old.Bytes) != digest) { |
| + return ErrConflict |
| + } |
| + var upload artifactBlobUpload |
| + err = tx.First(&upload, "attempt_id=? AND digest=?", h.Attempt, digest).Error |
| + if err == nil { |
| + if !exists || upload.Size != int64(len(data)) { |
| + return ErrConflict |
| + } |
| + return nil |
| + } |
| + if !errors.Is(err, gorm.ErrRecordNotFound) { |
| + return storeError(err) |
| + } |
| + var total int64 |
| + if err := tx.Model(&artifactBlobUpload{}).Where("attempt_id=?", h.Attempt).Select("COALESCE(SUM(size),0)").Scan(&total).Error; err != nil { |
| + return storeError(err) |
| + } |
| + if total < 0 || total > MaxAttemptBlobBytes-int64(len(data)) { |
| + return ErrInvalid |
| + } |
| + if !exists { |
| + if err := tx.Create(&artifactBlob{TeamID: string(scope.Account), JobID: int64(scope.Job), Digest: digest, Bytes: append([]byte(nil), data...)}).Error; err != nil { |
| + return storeError(err) |
| + } |
| + } |
| + if err := tx.Create(&artifactBlobUpload{AttemptID: int64(h.Attempt), Digest: digest, Size: int64(len(data))}).Error; err != nil { |
| + return storeError(err) |
| + } |
| + return appendAudit(tx, Actor{Address: p.Person}, "artifact.blob", digest) |
| + }) |
| +} |
| +func (s *Store) Blob(ctx context.Context, p RunnerPrincipal, scope team.Scope, digest string) ([]byte, error) { |
| + if s.execution == nil { |
| + return nil, ErrUnavailable |
| + } |
| + var result []byte |
| + err := s.execution.atomic(ctx, func(ctx context.Context, tx *gorm.DB) error { |
| + 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 { |
| + return storeError(err) |
| + } |
| + if len(assignments) == 0 { |
| + return ErrForbidden |
| + } |
| + // 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 { |
| + return err |
| + } |
| + var row artifactBlob |
| + if err := tx.First(&row, "team_id=? AND job_id=? AND digest=?", scope.Account, scope.Job, digest).Error; err != nil { |
| + return storeError(err) |
| + } |
| + if len(row.Bytes) == 0 || len(row.Bytes) > MaxBlobBytes || blobDigest(row.Bytes) != digest { |
| + return ErrConflict |
| + } |
| + result = append([]byte(nil), row.Bytes...) |
| + return nil |
| + }) |
| + return result, err |
| +} |
diff --git a/internal/equipo/migrations/0014_artifact_blobs.sql b/internal/equipo/migrations/0014_artifact_blobs.sql| new file mode 100644 |
| index 00000000..39c961b4 |
| --- /dev/null |
| +++ b/internal/equipo/migrations/0014_artifact_blobs.sql |
| @@ -0,0 +1,2 @@ |
| +CREATE TABLE artifact_blobs (team_id text, job_id integer, digest text, bytes blob, PRIMARY KEY(team_id, job_id, digest)); |
| +CREATE TABLE artifact_blob_uploads (attempt_id integer, digest text, size integer, PRIMARY KEY(attempt_id, digest)); |
diff --git a/internal/equipo/migrations/schema.sql b/internal/equipo/migrations/schema.sql| index 243d843c..5913eeb2 100644 |
| --- a/internal/equipo/migrations/schema.sql |
| +++ b/internal/equipo/migrations/schema.sql |
| @@ -330,3 +330,5 @@ CREATE TABLE runner_cleanups (id text, assignment_id text, runner_id text, perso |
| CREATE UNIQUE INDEX runner_cleanup_token ON runner_cleanups(token_hash); |
| CREATE TABLE runner_observations (assignment_id text, request_id text, operation text, payload_hash text, payload text, at datetime, PRIMARY KEY(assignment_id, request_id)); |
| CREATE TABLE runner_rotations (runner_id text, assignment_id text, request_id text, state text, credential_id text, PRIMARY KEY(runner_id)); |
| +CREATE TABLE artifact_blobs (team_id text, job_id integer, digest text, bytes blob, PRIMARY KEY(team_id, job_id, digest)); |
| +CREATE TABLE artifact_blob_uploads (attempt_id integer, digest text, size integer, PRIMARY KEY(attempt_id, digest)); |
diff --git a/internal/equipo/models.go b/internal/equipo/models.go| index 13b55b62..4c25d2af 100644 |
| --- a/internal/equipo/models.go |
| +++ b/internal/equipo/models.go |
| @@ -2,7 +2,7 @@ package equipo |
| import "time" |
| -var Models = append([]any{&runnerAssignment{}, &runnerCleanup{}, &runnerObservation{}, &runnerRotation{}, &executionAdmissionTicket{}, &Task{}, &taskOutbox{}, &Team{}, &Member{}, &AuditEvent{}, &Account{}, &Project{}, &DecisionOwner{}, &projectRequest{}, &budgetRecord{}, &Specialist{}, &runnerRecord{}, &runnerEnrolment{}, &runnerCredentialRecord{}, &runnerRate{}, &connectionRecord{}, &connectionChoiceRecord{}, &isolationAcknowledgementRecord{}, &ConnectionInvalidation{}}, executionModels...) |
| +var Models = append([]any{&artifactBlob{}, &artifactBlobUpload{}, &runnerAssignment{}, &runnerCleanup{}, &runnerObservation{}, &runnerRotation{}, &executionAdmissionTicket{}, &Task{}, &taskOutbox{}, &Team{}, &Member{}, &AuditEvent{}, &Account{}, &Project{}, &DecisionOwner{}, &projectRequest{}, &budgetRecord{}, &Specialist{}, &runnerRecord{}, &runnerEnrolment{}, &runnerCredentialRecord{}, &runnerRate{}, &connectionRecord{}, &connectionChoiceRecord{}, &isolationAcknowledgementRecord{}, &ConnectionInvalidation{}}, executionModels...) |
| type Role string |
diff --git a/internal/equipo/runner_api.go b/internal/equipo/runner_api.go| index dcdd7ed1..e621643e 100644 |
| --- a/internal/equipo/runner_api.go |
| +++ b/internal/equipo/runner_api.go |
| @@ -16,6 +16,8 @@ import ( |
| func (s *Store) RunnerHandler() http.Handler { |
| r := chi.NewRouter() |
| r.Post("/poll", s.runnerPoll) |
| + r.Post("/blobs", s.runnerPutBlob) |
| + r.Post("/blobs/read", s.runnerReadBlob) |
| r.Post("/claim", s.runnerClaim) |
| for _, op := range []string{"renew", "prepare", "events", "artifacts", "intend", "admit", "receipts", "lost", "complete", "release", "stop", "contained"} { |
| r.Post("/"+op, s.runnerMutation(op)) |
| @@ -213,3 +215,43 @@ func (s *Store) runnerArtifact(w http.ResponseWriter, r *http.Request) { |
| } |
| runnerJSON(w, 200, runnerproto.WorkResponse{Version: 1, Result: value}) |
| } |
| + |
| +func (s *Store) runnerPutBlob(w http.ResponseWriter, r *http.Request) { |
| + p, _, ok := s.runnerBearer(w, r) |
| + if !ok { |
| + return |
| + } |
| + var q runnerproto.BlobRequest |
| + if !runnerBody(w, r, &q, 2*MaxBlobBytes) { |
| + return |
| + } |
| + if q.Version != 1 { |
| + runnerFailure(w, ErrInvalid) |
| + return |
| + } |
| + if err := s.PutBlob(r.Context(), p, q.Scope, q.Handle, q.Digest, q.Bytes); err != nil { |
| + runnerFailure(w, err) |
| + return |
| + } |
| + runnerJSON(w, 200, runnerproto.WorkResponse{Version: 1, Result: struct{}{}}) |
| +} |
| +func (s *Store) runnerReadBlob(w http.ResponseWriter, r *http.Request) { |
| + p, _, ok := s.runnerBearer(w, r) |
| + if !ok { |
| + return |
| + } |
| + var q runnerproto.BlobReadRequest |
| + if !runnerBody(w, r, &q, 8192) { |
| + return |
| + } |
| + if q.Version != 1 { |
| + runnerFailure(w, ErrInvalid) |
| + return |
| + } |
| + b, err := s.Blob(r.Context(), p, q.Scope, q.Digest) |
| + if err != nil { |
| + runnerFailure(w, err) |
| + return |
| + } |
| + runnerJSON(w, 200, runnerproto.WorkResponse{Version: 1, Result: b}) |
| +} |
diff --git a/internal/equipo/team/git_evidence.go b/internal/equipo/team/git_evidence.go| index b30ac0c3..db2c6bfd 100644 |
| --- a/internal/equipo/team/git_evidence.go |
| +++ b/internal/equipo/team/git_evidence.go |
| @@ -17,17 +17,26 @@ type GitCandidate struct { |
| Tree string `json:"tree"` |
| } |
| +type TestIdentity struct { |
| + Package string `json:"package"` |
| + Name string `json:"name"` |
| +} |
| + |
| type RepositoryCheckResult struct { |
| - CandidateHash string `json:"candidate_hash"` |
| - Commit string `json:"commit"` |
| - CheckDefinitionHash string `json:"check_definition_hash"` |
| - BaselineTestSetHash string `json:"baseline_test_set_hash"` |
| - ObservedTestSetHash string `json:"observed_test_set_hash"` |
| - Outcome CheckOutcome `json:"outcome"` |
| - ExitCode int `json:"exit_code"` |
| - TestsRun int `json:"tests_run"` |
| - TestsFailed int `json:"tests_failed"` |
| - LogHash string `json:"log_hash"` |
| + ObservedNames []TestIdentity `json:"observed_names,omitempty"` |
| + Isolation IsolationSnapshot `json:"isolation,omitzero"` |
| + ExecutorBinary string `json:"executor_binary,omitempty"` |
| + ExecutorVersion string `json:"executor_version,omitempty"` |
| + CandidateHash string `json:"candidate_hash"` |
| + Commit string `json:"commit"` |
| + CheckDefinitionHash string `json:"check_definition_hash"` |
| + BaselineTestSetHash string `json:"baseline_test_set_hash"` |
| + ObservedTestSetHash string `json:"observed_test_set_hash"` |
| + Outcome CheckOutcome `json:"outcome"` |
| + ExitCode int `json:"exit_code"` |
| + TestsRun int `json:"tests_run"` |
| + TestsFailed int `json:"tests_failed"` |
| + LogHash string `json:"log_hash"` |
| } |
| type IsolationTuple struct { |
diff --git a/internal/equipo/team/model.go b/internal/equipo/team/model.go| index 67206508..80de3fc6 100644 |
| --- a/internal/equipo/team/model.go |
| +++ b/internal/equipo/team/model.go |
| @@ -770,13 +770,22 @@ func (c CheckOutcome) Valid() bool { |
| // artifacts: which reproduction ran, on what, under which check |
| // definition, and what happened. |
| type CheckResult struct { |
| - ReproductionHash string `json:"reproduction_hash"` |
| - SubjectHash string `json:"subject_hash"` |
| - CheckDefinitionHash string `json:"check_definition_hash"` |
| - Outcome CheckOutcome `json:"outcome"` |
| - TestsRun int `json:"tests_run"` |
| - TestsFailed int `json:"tests_failed"` |
| - FailureMessage string `json:"failure_message,omitempty"` |
| + ExitCode int `json:"exit_code,omitempty"` |
| + LogHash string `json:"log_hash,omitempty"` |
| + SubjectCommit string `json:"subject_commit,omitempty"` |
| + OverlayHash string `json:"overlay_hash,omitempty"` |
| + CollisionChecked bool `json:"collision_checked,omitempty"` |
| + ObservedNames []TestIdentity `json:"observed_names,omitempty"` |
| + Isolation IsolationSnapshot `json:"isolation,omitzero"` |
| + ExecutorBinary string `json:"executor_binary,omitempty"` |
| + ExecutorVersion string `json:"executor_version,omitempty"` |
| + ReproductionHash string `json:"reproduction_hash"` |
| + SubjectHash string `json:"subject_hash"` |
| + CheckDefinitionHash string `json:"check_definition_hash"` |
| + Outcome CheckOutcome `json:"outcome"` |
| + TestsRun int `json:"tests_run"` |
| + TestsFailed int `json:"tests_failed"` |
| + FailureMessage string `json:"failure_message,omitempty"` |
| } |
| // Verdict closes a review's answer. |
diff --git a/internal/equipotest/artifacts_test.go b/internal/equipotest/artifacts_test.go| new file mode 100644 |
| index 00000000..ae3e04ce |
| --- /dev/null |
| +++ b/internal/equipotest/artifacts_test.go |
| @@ -0,0 +1,125 @@ |
| +package equipotest |
| + |
| +import ( |
| + "amadan.net/oficina/equipo/internal/equipo/team" |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| + "bytes" |
| + "context" |
| + "crypto/sha256" |
| + "fmt" |
| + "net/http/httptest" |
| + "testing" |
| + |
| + "amadan.net/oficina/equipo/internal/equipo" |
| +) |
| + |
| +func TestArtifactScopeAndLimits(t *testing.T) { |
| + f := runnerFixtureNew(t, true) |
| + ctx := connectionContext |
| + p := f.principal |
| + s := f.claim.Scope |
| + h := f.claim.Handle |
| + b := []byte("frozen artifact") |
| + digest := fmt.Sprintf("%x", sha256.Sum256(b)) |
| + executionMust(t, f.s.PutBlob(ctx, p, s, h, digest, b)) |
| + executionMust(t, f.s.PutBlob(ctx, p, s, h, digest, b)) |
| + got, err := f.s.Blob(ctx, p, s, digest) |
| + executionMust(t, err) |
| + if !bytes.Equal(got, b) { |
| + t.Fatal("blob bytes changed") |
| + } |
| + for _, kind := range []string{"digest", "new_digest", "oversize", "fence", "person", "job", "team", "runner"} { |
| + t.Run(kind, func(t *testing.T) { |
| + pp := p |
| + ss := s |
| + hh := h |
| + dd := digest |
| + bb := b |
| + switch kind { |
| + case "digest": |
| + bb = []byte("corrupt") |
| + case "new_digest": |
| + dd = fmt.Sprintf("%x", sha256.Sum256([]byte("different bytes"))) |
| + case "oversize": |
| + bb = make([]byte, equipo.MaxBlobBytes+1) |
| + dd = fmt.Sprintf("%x", sha256.Sum256(bb)) |
| + case "fence": |
| + hh.Fence++ |
| + case "person": |
| + pp.Person = "other@example.com" |
| + case "job": |
| + ss.Job++ |
| + case "team": |
| + ss.Account = "other" |
| + case "runner": |
| + pp.RunnerID = "other" |
| + } |
| + if err := f.s.PutBlob(ctx, pp, ss, hh, dd, bb); err == nil { |
| + t.Fatal("unsafe blob upload accepted") |
| + } |
| + if kind == "person" || kind == "job" || kind == "team" || kind == "runner" { |
| + if _, err := f.s.Blob(ctx, pp, ss, digest); err == nil { |
| + t.Fatal("foreign blob read accepted") |
| + } |
| + } |
| + }) |
| + } |
| + // Exercise the cumulative limit without writing 128 MiB into each fixture. |
| + _, err = f.d.Writer().Exec(`UPDATE artifact_blob_uploads SET size=? WHERE attempt_id=?`, equipo.MaxAttemptBlobBytes, h.Attempt) |
| + executionMust(t, err) |
| + other := []byte("another") |
| + if err := f.s.PutBlob(ctx, p, s, h, fmt.Sprintf("%x", sha256.Sum256(other)), other); err == nil { |
| + t.Fatal("attempt upload limit ignored") |
| + } |
| + _, err = f.d.Writer().Exec(`UPDATE artifact_blobs SET bytes=? WHERE digest=?`, []byte("corrupt"), digest) |
| + executionMust(t, err) |
| + if _, err := f.s.Blob(ctx, p, s, digest); err == nil { |
| + t.Fatal("corrupt stored blob returned") |
| + } |
| +} |
| + |
| +func TestArtifactProtocol(t *testing.T) { |
| + f := runnerFixtureNew(t, true) |
| + payload := []byte("protocol artifact") |
| + digest := fmt.Sprintf("%x", sha256.Sum256(payload)) |
| + body, _ := runnerproto.Marshal(runnerproto.BlobRequest{Version: 1, Scope: f.claim.Scope, Handle: f.claim.Handle, Digest: digest, Bytes: payload}) |
| + req := httptest.NewRequest("POST", "/blobs", bytes.NewReader(body)) |
| + req.Header.Set("Content-Type", "application/json") |
| + req.Header.Set("Authorization", "Bearer "+runnerBearerFor(t, f)) |
| + rec := httptest.NewRecorder() |
| + f.s.RunnerHandler().ServeHTTP(rec, req) |
| + if rec.Code != 200 { |
| + t.Fatalf("blob upload: %d %s", rec.Code, rec.Body.String()) |
| + } |
| + body, _ = runnerproto.Marshal(runnerproto.BlobReadRequest{Version: 1, Scope: f.claim.Scope, Digest: digest}) |
| + req = httptest.NewRequest("POST", "/blobs/read", bytes.NewReader(body)) |
| + req.Header.Set("Content-Type", "application/json") |
| + req.Header.Set("Authorization", "Bearer "+runnerBearerFor(t, f)) |
| + rec = httptest.NewRecorder() |
| + f.s.RunnerHandler().ServeHTTP(rec, req) |
| + if rec.Code != 200 { |
| + t.Fatalf("blob read: %d %s", rec.Code, rec.Body.String()) |
| + } |
| +} |
| + |
| +func TestArtifactRegistrationStaysCore(t *testing.T) { |
| + f := runnerFixtureNew(t, true) |
| + b := []byte("blob only") |
| + digest := fmt.Sprintf("%x", sha256.Sum256(b)) |
| + executionMust(t, f.s.PutBlob(connectionContext, f.principal, f.claim.Scope, f.claim.Handle, digest, b)) |
| + var count int |
| + executionMust(t, f.d.Writer().QueryRow(`SELECT count(*) FROM artifacts`).Scan(&count)) |
| + if count != 0 { |
| + t.Fatal("blob upload bypassed core registration") |
| + } |
| + f.x.SetRunnerValidators(equipo.RunnerValidators{Artifact: func(context.Context, equipo.Assignment, equipo.RunnerRequest) error { return nil }}) |
| + q := f.request() |
| + q.Artifact = &team.ArtifactSpec{Role: team.RoleBaseResult, MediaType: "application/json", Payload: []byte(`{"outcome":"fail","tests_run":1,"tests_failed":1}`)} |
| + if _, err := f.x.Mutate(connectionContext, f.principal, "artifacts", q); err == nil { |
| + t.Fatal("agent submitted executor evidence") |
| + } |
| + executionMust(t, f.s.RevokeRunner(connectionContext, ownerActor, f.principal.RunnerID, 1)) |
| + if _, err := f.s.Blob(connectionContext, f.principal, f.claim.Scope, digest); err == nil { |
| + t.Fatal("revoked runner read blob") |
| + } |
| +} |
diff --git a/internal/runner/checks/definition.go b/internal/runner/checks/definition.go| new file mode 100644 |
| index 00000000..249a06a8 |
| --- /dev/null |
| +++ b/internal/runner/checks/definition.go |
| @@ -0,0 +1,430 @@ |
| +package checks |
| + |
| +import ( |
| + "amadan.net/oficina/equipo/internal/runner/workspace" |
| + "bytes" |
| + "context" |
| + "crypto/sha256" |
| + "encoding/hex" |
| + "encoding/json" |
| + "io" |
| + "io/fs" |
| + "os" |
| + "os/exec" |
| + "path/filepath" |
| + "reflect" |
| + "runtime" |
| + "slices" |
| + "strings" |
| + |
| + "amadan.net/oficina/equipo/internal/equipo/team" |
| + "amadan.net/oficina/equipo/internal/runner/paseo" |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| +) |
| + |
| +type Command = runnerproto.CheckCommand |
| +type File = runnerproto.CheckFile |
| +type Definition = runnerproto.CheckDefinition |
| +type Reproduction = runnerproto.Reproduction |
| +type TestBaseline = runnerproto.TestBaseline |
| +type TestIdentity = team.TestIdentity |
| + |
| +func Digest(b []byte) string { h := sha256.Sum256(b); return hex.EncodeToString(h[:]) } |
| +func encode(v any) []byte { b, _ := json.Marshal(v); return b } |
| +func hexID(s string, n int) bool { |
| + b, e := hex.DecodeString(s) |
| + return e == nil && len(b)*2 == n && s == strings.ToLower(s) |
| +} |
| +func objectID(s string) bool { return hexID(s, 40) || hexID(s, 64) } |
| +func relative(p string) bool { |
| + return p != "" && p != "." && filepath.IsLocal(p) && filepath.Clean(p) == p && !strings.ContainsAny(p, "\\\x00") && p != ".git" && !strings.HasPrefix(p, ".git/") |
| +} |
| +func commandValid(c Command, measured bool) bool { |
| + if len(c.Argv) == 0 || c.TimeoutSeconds < 1 || c.TimeoutSeconds > 1200 || !(c.Dir == "." || relative(c.Dir)) { |
| + return false |
| + } |
| + for _, arg := range c.Argv { |
| + if arg == "" || strings.ContainsRune(arg, 0) { |
| + return false |
| + } |
| + } |
| + if c.Parser == "exit" { |
| + return !measured |
| + } |
| + if c.Parser != "go-test-json" || len(c.Argv) < 4 || c.Argv[0] != "go" || c.Argv[1] != "test" { |
| + return false |
| + } |
| + jsonFlag, count, packages := false, false, false |
| + // Only flags that preserve complete discovery are accepted in v1. |
| + for _, arg := range c.Argv[2:] { |
| + switch { |
| + case arg == "-json": |
| + jsonFlag = true |
| + case arg == "-count=1": |
| + count = true |
| + case arg == "./..." || arg == "." || relative(arg) && !strings.HasPrefix(arg, "-"): |
| + packages = true |
| + case strings.HasPrefix(arg, "-tags="): |
| + case arg == "-short": |
| + default: |
| + return false |
| + } |
| + } |
| + return jsonFlag && count && packages |
| +} |
| +func ParseDefinition(ctx context.Context, b []byte, repo, base string) (Definition, error) { |
| + var d Definition |
| + if ctx.Err() != nil { |
| + return d, ctx.Err() |
| + } |
| + if runnerproto.DecodeLimit(bytes.NewReader(b), &d, team.MaxArtifactBytes) != nil { |
| + return d, paseo.ErrContract |
| + } |
| + if d.Repository == "" { |
| + d.Repository = repo |
| + } |
| + if d.Base == "" { |
| + d.Base = base |
| + } |
| + if d.Version != 1 || repo == "" || d.Repository != repo || d.Base != base || !objectID(base) || len(d.Commands) == 0 || !commandValid(d.Reproduction, true) { |
| + return d, paseo.ErrContract |
| + } |
| + measured := false |
| + for _, c := range d.Commands { |
| + if !commandValid(c, false) || !exitMaterialDeclared(d, c) { |
| + return d, paseo.ErrContract |
| + } |
| + if c.Parser == "go-test-json" { |
| + measured = true |
| + if !reflect.DeepEqual(c, d.Reproduction) { |
| + return d, paseo.ErrContract |
| + } |
| + } |
| + } |
| + if !measured { |
| + return d, paseo.ErrContract |
| + } |
| + if d.GOOS == "" { |
| + d.GOOS = runtime.GOOS |
| + } |
| + if d.GOARCH == "" { |
| + d.GOARCH = runtime.GOARCH |
| + } |
| + if d.GOOS != runtime.GOOS || d.GOARCH != runtime.GOARCH { |
| + return d, paseo.ErrContract |
| + } |
| + if len(d.Baseline.Names) > 0 && d.Baseline.Hash != setHash(d.Baseline.Names) { |
| + return d, paseo.ErrIdentity |
| + } |
| + for _, p := range d.TrustedPaths { |
| + if !relative(p) || strings.HasSuffix(p, "_test.go") { |
| + return d, paseo.ErrContract |
| + } |
| + } |
| + for _, f := range d.Files { |
| + if !trustedMaterial(d, f.Path) || strings.HasSuffix(f.Path, "_test.go") { |
| + return d, paseo.ErrContract |
| + } |
| + } |
| + if err := filesValid(d.Files, false); err != nil { |
| + return d, err |
| + } |
| + seen := map[string]bool{} |
| + for _, p := range d.TestFiles { |
| + if !relative(p) || !strings.HasSuffix(p, "_test.go") || seen[p] { |
| + return d, paseo.ErrContract |
| + } |
| + seen[p] = true |
| + } |
| + return d, nil |
| +} |
| +func filesValid(files []File, tests bool) error { |
| + seen := map[string]bool{} |
| + total := 0 |
| + for _, f := range files { |
| + total += len(f.Bytes) |
| + if !relative(f.Path) || seen[f.Path] || tests && !strings.HasSuffix(f.Path, "_test.go") || total > team.MaxArtifactBytes { |
| + return paseo.ErrContract |
| + } |
| + seen[f.Path] = true |
| + } |
| + return nil |
| +} |
| +func namesSorted(names []TestIdentity) []TestIdentity { |
| + out := append([]TestIdentity(nil), names...) |
| + slices.SortFunc(out, func(a, b TestIdentity) int { |
| + if c := strings.Compare(a.Package, b.Package); c != 0 { |
| + return c |
| + } |
| + return strings.Compare(a.Name, b.Name) |
| + }) |
| + return slices.Compact(out) |
| +} |
| +func setHash(names []TestIdentity) string { return Digest(encode(namesSorted(names))) } |
| +func superset(observed, required []TestIdentity) bool { |
| + if len(required) == 0 { |
| + return false |
| + } |
| + for _, r := range required { |
| + if r.Package == "" || !slices.Contains(observed, r) { |
| + return false |
| + } |
| + } |
| + return true |
| +} |
| + |
| +func FreezeMaterial(ctx context.Context, d Definition, base string) (Definition, error) { |
| + d.Files = nil |
| + d.TestFiles = nil |
| + var total int64 |
| + for _, p := range d.TrustedPaths { |
| + if err := safePath(base, p, false); err != nil { |
| + return d, err |
| + } |
| + } |
| + err := filepath.WalkDir(base, func(path string, entry fs.DirEntry, err error) error { |
| + if err != nil { |
| + return err |
| + } |
| + if ctx.Err() != nil { |
| + return ctx.Err() |
| + } |
| + rel, e := filepath.Rel(base, path) |
| + if e != nil { |
| + return e |
| + } |
| + if rel == ".git" { |
| + return filepath.SkipDir |
| + } |
| + if entry.Type()&os.ModeSymlink != 0 { |
| + return paseo.ErrPolicy |
| + } |
| + if entry.IsDir() { |
| + return nil |
| + } |
| + if !entry.Type().IsRegular() { |
| + return paseo.ErrPolicy |
| + } |
| + if strings.HasSuffix(rel, "_test.go") { |
| + d.TestFiles = append(d.TestFiles, rel) |
| + } |
| + if trustedMaterial(d, rel) { |
| + if strings.HasSuffix(rel, "_test.go") { |
| + return paseo.ErrContract |
| + } |
| + info, e := entry.Info() |
| + if e != nil { |
| + return paseo.ErrContract |
| + } |
| + total += info.Size() |
| + if total > team.MaxArtifactBytes { |
| + return paseo.ErrContract |
| + } |
| + b, e := os.ReadFile(path) |
| + if e != nil { |
| + return e |
| + } |
| + d.Files = append(d.Files, File{Path: rel, Bytes: b}) |
| + } |
| + return nil |
| + }) |
| + if err != nil { |
| + return d, err |
| + } |
| + if filesValid(d.Files, false) != nil || len(encode(d)) > team.MaxArtifactBytes { |
| + return d, paseo.ErrContract |
| + } |
| + return d, nil |
| +} |
| +func LoadDefinition(ctx context.Context, baseRoot, repo, base string) (Definition, error) { |
| + p := filepath.Join(baseRoot, ".equipo/checks.json") |
| + if err := safePath(baseRoot, ".equipo/checks.json", false); err != nil { |
| + return Definition{}, err |
| + } |
| + b, err := os.ReadFile(p) |
| + if err != nil { |
| + return Definition{}, paseo.ErrContract |
| + } |
| + d, err := ParseDefinition(ctx, b, repo, base) |
| + if err != nil { |
| + return d, err |
| + } |
| + return FreezeMaterial(ctx, d, baseRoot) |
| +} |
| +func safePath(root, rel string, missing bool) error { |
| + if !relative(rel) { |
| + return paseo.ErrPolicy |
| + } |
| + cur := root |
| + for _, part := range strings.Split(rel, string(filepath.Separator)) { |
| + cur = filepath.Join(cur, part) |
| + st, err := os.Lstat(cur) |
| + if os.IsNotExist(err) && missing { |
| + return nil |
| + } |
| + if err != nil { |
| + return paseo.ErrPolicy |
| + } |
| + if st.Mode()&os.ModeSymlink != 0 { |
| + return paseo.ErrPolicy |
| + } |
| + } |
| + return nil |
| +} |
| +func copyTree(src, dst string) error { |
| + if err := os.Mkdir(dst, 0700); err != nil { |
| + return err |
| + } |
| + return filepath.WalkDir(src, func(path string, d fs.DirEntry, err error) error { |
| + if err != nil { |
| + return err |
| + } |
| + rel, e := filepath.Rel(src, path) |
| + if e != nil { |
| + return e |
| + } |
| + if rel == "." { |
| + return nil |
| + } |
| + if rel == ".git" { |
| + return filepath.SkipDir |
| + } |
| + if d.Type()&os.ModeSymlink != 0 { |
| + return paseo.ErrPolicy |
| + } |
| + to := filepath.Join(dst, rel) |
| + if d.IsDir() { |
| + return os.Mkdir(to, 0700) |
| + } |
| + if !d.Type().IsRegular() { |
| + return paseo.ErrPolicy |
| + } |
| + b, e := os.ReadFile(path) |
| + if e != nil { |
| + return e |
| + } |
| + info, e := d.Info() |
| + if e != nil { |
| + return e |
| + } |
| + return os.WriteFile(to, b, info.Mode().Perm()&0700) |
| + }) |
| +} |
| + |
| +func gitBytes(ctx context.Context, repo string, args ...string) ([]byte, error) { |
| + cmd := exec.CommandContext(ctx, "/usr/bin/git", args...) |
| + cmd.Dir = repo |
| + cmd.Env = []string{"HOME=/nonexistent"} |
| + for k, v := range workspace.GitEnvironment() { |
| + cmd.Env = append(cmd.Env, k+"="+v) |
| + } |
| + cmd.Stderr = io.Discard |
| + b, err := cmd.Output() |
| + if err != nil { |
| + return nil, paseo.ErrIdentity |
| + } |
| + return b, nil |
| +} |
| +func ExportBase(ctx context.Context, repo, commit, dest string) error { |
| + if !objectID(commit) { |
| + return paseo.ErrIdentity |
| + } |
| + kind, err := gitBytes(ctx, repo, "cat-file", "-t", commit) |
| + if err != nil || string(kind) != "commit\n" { |
| + return paseo.ErrIdentity |
| + } |
| + tree, err := gitBytes(ctx, repo, "ls-tree", "-rz", "--full-tree", commit) |
| + if err != nil { |
| + return err |
| + } |
| + if err = os.Mkdir(dest, 0700); err != nil { |
| + return err |
| + } |
| + ok := false |
| + defer func() { |
| + if !ok { |
| + _ = os.RemoveAll(dest) |
| + } |
| + }() |
| + for _, entry := range bytes.Split(tree, []byte{0}) { |
| + if len(entry) == 0 { |
| + continue |
| + } |
| + parts := bytes.SplitN(entry, []byte{'\t'}, 2) |
| + if len(parts) != 2 { |
| + return paseo.ErrIdentity |
| + } |
| + fields := strings.Fields(string(parts[0])) |
| + path := string(parts[1]) |
| + if len(fields) != 3 || fields[1] != "blob" || (fields[0] != "100644" && fields[0] != "100755") || !objectID(fields[2]) || !relative(path) { |
| + return paseo.ErrIdentity |
| + } |
| + b, err := gitBytes(ctx, repo, "cat-file", "blob", fields[2]) |
| + if err != nil { |
| + return err |
| + } |
| + p := filepath.Join(dest, path) |
| + if err = os.MkdirAll(filepath.Dir(p), 0700); err != nil { |
| + return err |
| + } |
| + mode := os.FileMode(0600) |
| + if fields[0] == "100755" { |
| + mode = 0700 |
| + } |
| + if err = os.WriteFile(p, b, mode); err != nil { |
| + return err |
| + } |
| + } |
| + ok = true |
| + return nil |
| +} |
| +func LoadBaseDefinition(ctx context.Context, repoDir, repository, base, scratchRoot string) (Definition, error) { |
| + dir, err := os.MkdirTemp(scratchRoot, "definition-") |
| + if err != nil { |
| + return Definition{}, err |
| + } |
| + defer os.RemoveAll(dir) |
| + work := filepath.Join(dir, "base") |
| + if err = ExportBase(ctx, repoDir, base, work); err != nil { |
| + return Definition{}, err |
| + } |
| + return LoadDefinition(ctx, work, repository, base) |
| +} |
| + |
| +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"} |
| + |
| +func materialPaths(d Definition) []string { |
| + return append(append([]string(nil), baseMaterialPaths...), d.TrustedPaths...) |
| +} |
| +func trustedMaterial(d Definition, path string) bool { |
| + for _, p := range materialPaths(d) { |
| + if within(p, path) { |
| + return true |
| + } |
| + } |
| + return false |
| +} |
| + |
| +func exitMaterialDeclared(d Definition, c Command) bool { |
| + if c.Parser != "exit" { |
| + return true |
| + } |
| + program := filepath.Base(c.Argv[0]) |
| + switch program { |
| + case "sh", "bash", "python", "python3", "node": |
| + if len(c.Argv) < 2 || strings.HasPrefix(c.Argv[1], "-") { |
| + return false |
| + } |
| + return trustedMaterial(d, filepath.Clean(filepath.Join(c.Dir, c.Argv[1]))) |
| + case "go": |
| + return len(c.Argv) > 1 && (c.Argv[1] == "vet" || c.Argv[1] == "test") |
| + } |
| + if !filepath.IsAbs(c.Argv[0]) && strings.Contains(c.Argv[0], "/") { |
| + return trustedMaterial(d, filepath.Clean(filepath.Join(c.Dir, c.Argv[0]))) |
| + } |
| + return true |
| +} |
diff --git a/internal/runner/checks/executor.go b/internal/runner/checks/executor.go| new file mode 100644 |
| index 00000000..dcc78240 |
| --- /dev/null |
| +++ b/internal/runner/checks/executor.go |
| @@ -0,0 +1,429 @@ |
| +package checks |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "database/sql" |
| + "encoding/json" |
| + "io" |
| + "os" |
| + "path/filepath" |
| + "slices" |
| + "sync" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/equipo/team" |
| + "amadan.net/oficina/equipo/internal/runner/paseo" |
| +) |
| + |
| +type CommandSandbox interface { |
| + Run(context.Context, Command, string, paseo.ReadPolicy, io.Writer, io.Writer) (int, error) |
| +} |
| +type Config struct { |
| + ResolveCandidate func(context.Context, string) (team.GitCandidate, error) |
| + Reproduction func(context.Context, string) (Reproduction, error) |
| + ScratchRoot string |
| + Scope team.Scope |
| + Handle team.Handle |
| + Deadline time.Time |
| + Policy paseo.ReadPolicy |
| + DefinitionHash, ReproductionHash string |
| + Export func(context.Context, string, string) error |
| + Isolation func(context.Context) (team.IsolationSnapshot, error) |
| +} |
| +type Executor struct { |
| + exposure team.IsolationSnapshot |
| + logs map[string][]byte |
| + cfg Config |
| + sandbox CommandSandbox |
| + mu sync.Mutex |
| + attested map[string]team.Provenance |
| + binary, version string |
| +} |
| + |
| +func New(cfg Config, sandbox *CodexSandbox) (*Executor, error) { |
| + if sandbox == nil || !filepath.IsAbs(sandbox.binary) || sandbox.version != CodexVersion || len(sandbox.protected) < 9 { |
| + return nil, paseo.ErrContract |
| + } |
| + e, err := newExecutor(cfg, sandbox) |
| + if err == nil { |
| + e.binary = sandbox.binary |
| + e.version = sandbox.version |
| + } |
| + return e, err |
| +} |
| +func newExecutor(cfg Config, sandbox CommandSandbox) (*Executor, error) { |
| + if sandbox == nil || cfg.Export == nil || cfg.ResolveCandidate == nil || cfg.Reproduction == nil || cfg.Isolation == nil || !filepath.IsAbs(cfg.ScratchRoot) || cfg.Policy.ConfigHash == "" || len(cfg.Policy.DeniedPaths) == 0 || cfg.Deadline.IsZero() { |
| + return nil, paseo.ErrContract |
| + } |
| + return &Executor{cfg: cfg, sandbox: sandbox, attested: map[string]team.Provenance{}, logs: map[string][]byte{}}, nil |
| +} |
| +func (e *Executor) scratch(ctx context.Context, commit string) (string, func(), error) { |
| + root, err := os.MkdirTemp(e.cfg.ScratchRoot, "checks-") |
| + if err != nil { |
| + return "", nil, err |
| + } |
| + cleanup := func() { _ = os.RemoveAll(root) } |
| + work := filepath.Join(root, "work") |
| + if err = e.cfg.Export(ctx, commit, work); err != nil { |
| + cleanup() |
| + return "", nil, err |
| + } |
| + // Reject symlinks anywhere in an immutable export, before installing any trusted bytes. |
| + err = filepath.WalkDir(work, func(_ string, d os.DirEntry, err error) error { |
| + if err != nil { |
| + return err |
| + } |
| + if d.Type()&os.ModeSymlink != 0 || !d.IsDir() && !d.Type().IsRegular() { |
| + return paseo.ErrPolicy |
| + } |
| + return nil |
| + }) |
| + if err != nil { |
| + cleanup() |
| + return "", nil, err |
| + } |
| + return work, cleanup, nil |
| +} |
| +func (e *Executor) definition(ctx context.Context, d Definition, pinned bool) error { |
| + parsed, err := ParseDefinition(ctx, encode(d), d.Repository, d.Base) |
| + if err != nil { |
| + return err |
| + } |
| + if pinned && (Digest(encode(parsed)) != e.cfg.DefinitionHash || d.Baseline.Hash != setHash(d.Baseline.Names) || len(d.Baseline.Names) == 0) { |
| + return paseo.ErrIdentity |
| + } |
| + return nil |
| +} |
| +func (e *Executor) material(d Definition, work string) error { |
| + for _, p := range d.TestFiles { |
| + if err := safePath(work, p, false); err != nil { |
| + return err |
| + } |
| + st, err := os.Stat(filepath.Join(work, p)) |
| + if err != nil || !st.Mode().IsRegular() { |
| + return paseo.ErrIdentity |
| + } |
| + } |
| + for _, path := range materialPaths(d) { |
| + if err := safePath(work, path, true); err != nil { |
| + return err |
| + } |
| + if err := os.RemoveAll(filepath.Join(work, path)); err != nil { |
| + return err |
| + } |
| + } |
| + for _, f := range d.Files { |
| + if err := safePath(work, f.Path, true); err != nil { |
| + return err |
| + } |
| + p := filepath.Join(work, f.Path) |
| + if err := os.MkdirAll(filepath.Dir(p), 0700); err != nil { |
| + return err |
| + } |
| + if err := os.WriteFile(p, f.Bytes, 0700); err != nil { |
| + return err |
| + } |
| + } |
| + return nil |
| +} |
| +func (e *Executor) overlay(ctx context.Context, d Definition, r Reproduction, work string) error { |
| + if len(r.Files) == 0 || len(r.TestNames) == 0 || len(r.ExpectedSymptom) == 0 || len(r.ExpectedSymptom) > 4096 || len(encode(r)) > team.MaxArtifactBytes || Digest(encode(r)) != e.cfg.ReproductionHash { |
| + return paseo.ErrIdentity |
| + } |
| + if err := filesValid(r.Files, true); err != nil { |
| + return err |
| + } |
| + base, cleanup, err := e.scratch(ctx, d.Base) |
| + if err != nil { |
| + return err |
| + } |
| + defer cleanup() |
| + for _, f := range r.Files { |
| + if err := safePath(work, f.Path, true); err != nil { |
| + return err |
| + } |
| + if err := safePath(base, f.Path, true); err != nil { |
| + return err |
| + } |
| + p := filepath.Join(work, f.Path) |
| + current, err := os.ReadFile(p) |
| + if err == nil && !bytes.Equal(current, f.Bytes) { |
| + original, err := os.ReadFile(filepath.Join(base, f.Path)) |
| + if err != nil || !bytes.Equal(original, current) { |
| + return paseo.ErrIdentity |
| + } |
| + } else if err != nil && !os.IsNotExist(err) { |
| + return err |
| + } |
| + if err := os.MkdirAll(filepath.Dir(p), 0700); err != nil { |
| + return err |
| + } |
| + if err := os.WriteFile(p, f.Bytes, 0600); err != nil { |
| + return err |
| + } |
| + } |
| + return nil |
| +} |
| +func (e *Executor) run(ctx context.Context, c Command, work, symptom string) (*goResults, int, string, error) { |
| + end := time.Now().Add(time.Duration(c.TimeoutSeconds) * time.Second) |
| + if e.cfg.Deadline.Before(end) { |
| + end = e.cfg.Deadline |
| + } |
| + ctx, cancel := context.WithDeadline(ctx, end) |
| + defer cancel() |
| + if err := safeDir(work, c.Dir); err != nil { |
| + return nil, 0, "", err |
| + } |
| + result := newGoResults() |
| + result.symptom = symptom |
| + var out, stderr boundedLog |
| + var writer io.Writer = &out |
| + if c.Parser == "go-test-json" { |
| + writer = io.MultiWriter(result, &out) |
| + } |
| + code, err := e.sandbox.Run(ctx, c, work, e.cfg.Policy, writer, &stderr) |
| + if ctx.Err() != nil { |
| + err = ctx.Err() |
| + } |
| + logHash := e.saveLog(encode(struct { |
| + Stdout, Stderr []byte |
| + StdoutHash, StderrHash string |
| + }{out.Bytes(), stderr.Bytes(), out.digest(), stderr.digest()})) |
| + if c.Parser == "go-test-json" { |
| + err = result.finish(code, err) |
| + } else if err == nil && code != 0 { |
| + err = paseo.ErrContract |
| + } |
| + return result, code, logHash, err |
| +} |
| +func safeDir(root, rel string) error { |
| + if rel == "." { |
| + return nil |
| + } |
| + if err := safePath(root, rel, false); err != nil { |
| + return err |
| + } |
| + st, err := os.Stat(filepath.Join(root, rel)) |
| + if err != nil || !st.IsDir() { |
| + return paseo.ErrPolicy |
| + } |
| + return nil |
| +} |
| +func (e *Executor) CaptureBaseline(ctx context.Context, d Definition) (TestBaseline, error) { |
| + if err := e.definition(ctx, d, false); err != nil { |
| + return TestBaseline{}, err |
| + } |
| + var names []TestIdentity |
| + for _, c := range d.Commands { |
| + r, _, _, err := e.freshRun(ctx, d, nil, d.Base, c) |
| + if err != nil { |
| + return TestBaseline{}, err |
| + } |
| + if c.Parser == "go-test-json" { |
| + names = append(names, r.names...) |
| + for p := range r.packages { |
| + names = append(names, TestIdentity{Package: p}) |
| + } |
| + } |
| + } |
| + if len(names) == 0 { |
| + return TestBaseline{}, paseo.ErrContract |
| + } |
| + names = namesSorted(names) |
| + return TestBaseline{Names: names, Hash: setHash(names)}, nil |
| +} |
| +func (e *Executor) isolation(ctx context.Context) (team.IsolationSnapshot, error) { |
| + iso, err := e.cfg.Isolation(ctx) |
| + if err != nil { |
| + return iso, err |
| + } |
| + if iso.Status != "confined" && iso.Status != "unconfined" || len(iso.ObservedTuples) == 0 { |
| + return iso, paseo.ErrIdentity |
| + } |
| + e.mu.Lock() |
| + defer e.mu.Unlock() |
| + iso.RunnerTainted = iso.RunnerTainted || e.exposure.RunnerTainted |
| + if e.exposure.Status == "unconfined" { |
| + iso.Status = "unconfined" |
| + } |
| + for _, id := range e.exposure.AcknowledgementIDs { |
| + if !slices.Contains(iso.AcknowledgementIDs, id) { |
| + iso.AcknowledgementIDs = append(iso.AcknowledgementIDs, id) |
| + } |
| + } |
| + for _, tuple := range e.exposure.ObservedTuples { |
| + if !slices.Contains(iso.ObservedTuples, tuple) { |
| + iso.ObservedTuples = append(iso.ObservedTuples, tuple) |
| + } |
| + } |
| + if iso.RunnerTainted { |
| + iso.Status = "unconfined" |
| + } |
| + if iso.Status == "unconfined" && len(iso.AcknowledgementIDs) == 0 { |
| + return iso, paseo.ErrIdentity |
| + } |
| + _ = json.Unmarshal(encode(iso), &e.exposure) |
| + return iso, nil |
| +} |
| +func (e *Executor) attest(role team.Role, value any, iso team.IsolationSnapshot) { |
| + e.mu.Lock() |
| + defer e.mu.Unlock() |
| + e.attested[string(role)+Digest(encode(value))] = team.Provenance{Producer: "equipo-checks", Provider: "executor", Context: string(e.cfg.Handle.Runner), Isolation: iso} |
| +} |
| +func (e *Executor) ValidateEvidence(ctx context.Context, _ *sql.Tx, scope team.Scope, h team.Handle, spec team.ArtifactSpec) (team.Provenance, error) { |
| + current, err := e.isolation(ctx) |
| + if err != nil { |
| + return team.Provenance{}, err |
| + } |
| + e.mu.Lock() |
| + defer e.mu.Unlock() |
| + if ctx.Err() != nil { |
| + return team.Provenance{}, ctx.Err() |
| + } |
| + if scope.Account == "" || scope.Job <= 0 || h.Attempt <= 0 || h.Fence <= 0 || scope != e.cfg.Scope || h.Attempt != e.cfg.Handle.Attempt || h.Fence != e.cfg.Handle.Fence || h.Runner != e.cfg.Handle.Runner { |
| + return team.Provenance{}, paseo.ErrIdentity |
| + } |
| + p, ok := e.attested[string(spec.Role)+Digest(spec.Payload)] |
| + if !ok || !bytes.Equal(encode(p.Isolation), encode(current)) { |
| + return p, paseo.ErrIdentity |
| + } |
| + return p, nil |
| +} |
| +func (e *Executor) Reproduce(ctx context.Context, d Definition, r Reproduction, subjectCommit, candidateHash string) (team.CheckResult, error) { |
| + result := team.CheckResult{} |
| + if err := e.definition(ctx, d, true); err != nil { |
| + return result, err |
| + } |
| + if candidateHash != "" { |
| + candidate, err := e.cfg.ResolveCandidate(ctx, candidateHash) |
| + if err != nil || candidate.Repository != d.Repository || candidate.BaseCommit != d.Base || candidate.Commit != subjectCommit || !objectID(candidate.Tree) || CandidateHash(candidate) != candidateHash { |
| + return result, paseo.ErrIdentity |
| + } |
| + } |
| + if !objectID(subjectCommit) || (candidateHash == "" && subjectCommit != d.Base) || (candidateHash != "" && !hexID(candidateHash, 64)) { |
| + return result, paseo.ErrIdentity |
| + } |
| + work, cleanup, err := e.scratch(ctx, subjectCommit) |
| + if err != nil { |
| + return result, err |
| + } |
| + defer cleanup() |
| + if err = e.material(d, work); err != nil { |
| + return result, err |
| + } |
| + if err = e.overlay(ctx, d, r, work); err != nil { |
| + return result, err |
| + } |
| + run, code, logHash, err := e.run(ctx, d.Reproduction, work, r.ExpectedSymptom) |
| + if err != nil { |
| + return result, err |
| + } |
| + if !superset(run.names, r.TestNames) { |
| + return result, paseo.ErrIdentity |
| + } |
| + outcome := team.CheckPass |
| + subject := candidateHash |
| + role := team.RoleCandidateResult |
| + if candidateHash == "" { |
| + subject = d.Base |
| + role = team.RoleBaseResult |
| + outcome = team.CheckFail |
| + if run.failed <= 0 || !run.matched { |
| + return result, paseo.ErrIdentity |
| + } |
| + } else if run.failed != 0 { |
| + return result, paseo.ErrIdentity |
| + } |
| + 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} |
| + if outcome == team.CheckFail { |
| + result.FailureMessage = r.ExpectedSymptom |
| + } |
| + e.attest(role, result, iso) |
| + return result, nil |
| +} |
| +func (e *Executor) RepositoryChecks(ctx context.Context, d Definition, candidate team.GitCandidate, candidateHash string) (team.RepositoryCheckResult, error) { |
| + result := team.RepositoryCheckResult{} |
| + r, err := e.cfg.Reproduction(ctx, e.cfg.ReproductionHash) |
| + if err != nil { |
| + return result, err |
| + } |
| + verified, err := e.cfg.ResolveCandidate(ctx, candidateHash) |
| + if err != nil || verified != candidate { |
| + return result, paseo.ErrIdentity |
| + } |
| + if err := e.definition(ctx, d, true); err != nil { |
| + return result, err |
| + } |
| + if candidate.Repository != d.Repository || candidate.BaseCommit != d.Base || !objectID(candidate.Commit) || !objectID(candidate.Tree) || !hexID(candidateHash, 64) || CandidateHash(candidate) != candidateHash { |
| + return result, paseo.ErrIdentity |
| + } |
| + var names []TestIdentity |
| + var logs []string |
| + count := 0 |
| + for _, c := range d.Commands { |
| + run, code, log, err := e.freshRun(ctx, d, &r, candidate.Commit, c) |
| + if err != nil { |
| + return result, err |
| + } |
| + if code != 0 || run.failed != 0 { |
| + return result, paseo.ErrIdentity |
| + } |
| + logs = append(logs, log) |
| + count += run.run |
| + names = append(names, run.names...) |
| + for p := range run.packages { |
| + names = append(names, TestIdentity{Package: p}) |
| + } |
| + } |
| + if count == 0 || !superset(names, d.Baseline.Names) || !superset(names, r.TestNames) { |
| + return result, paseo.ErrIdentity |
| + } |
| + iso, err := e.isolation(ctx) |
| + if err != nil { |
| + return result, err |
| + } |
| + result = team.RepositoryCheckResult{CandidateHash: candidateHash, Commit: candidate.Commit, CheckDefinitionHash: e.cfg.DefinitionHash, BaselineTestSetHash: d.Baseline.Hash, ObservedTestSetHash: setHash(names), Outcome: team.CheckPass, TestsRun: count, LogHash: e.saveLog(encode(logs)), ObservedNames: namesSorted(names), Isolation: iso, ExecutorBinary: e.binary, ExecutorVersion: e.version} |
| + e.attest(team.RoleRepositoryChecks, result, iso) |
| + return result, nil |
| +} |
| + |
| +func (e *Executor) freshRun(ctx context.Context, d Definition, r *Reproduction, commit string, c Command) (*goResults, int, string, error) { |
| + work, cleanup, err := e.scratch(ctx, commit) |
| + if err != nil { |
| + return nil, 0, "", err |
| + } |
| + defer cleanup() |
| + if err = e.material(d, work); err != nil { |
| + return nil, 0, "", err |
| + } |
| + if r != nil { |
| + if err = e.overlay(ctx, d, *r, work); err != nil { |
| + return nil, 0, "", err |
| + } |
| + } |
| + return e.run(ctx, c, work, "") |
| +} |
| +func (e *Executor) saveLog(b []byte) string { |
| + e.mu.Lock() |
| + defer e.mu.Unlock() |
| + hash := Digest(b) |
| + e.logs[hash] = append([]byte(nil), b...) |
| + return hash |
| +} |
| +func (e *Executor) Log(ctx context.Context, hash string) ([]byte, error) { |
| + e.mu.Lock() |
| + defer e.mu.Unlock() |
| + if ctx.Err() != nil { |
| + return nil, ctx.Err() |
| + } |
| + b, ok := e.logs[hash] |
| + if !ok || Digest(b) != hash { |
| + return nil, paseo.ErrIdentity |
| + } |
| + return append([]byte(nil), b...), nil |
| +} |
diff --git a/internal/runner/checks/executor_test.go b/internal/runner/checks/executor_test.go| new file mode 100644 |
| index 00000000..35ee5a7c |
| --- /dev/null |
| +++ b/internal/runner/checks/executor_test.go |
| @@ -0,0 +1,575 @@ |
| +package checks |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "encoding/json" |
| + "io" |
| + "os" |
| + "os/exec" |
| + "path/filepath" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/equipo/team" |
| + "amadan.net/oficina/equipo/internal/runner/paseo" |
| +) |
| + |
| +func must(t *testing.T, err error) { |
| + t.Helper() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| +func put(t *testing.T, root, name, content string) { |
| + t.Helper() |
| + must(t, os.MkdirAll(filepath.Dir(filepath.Join(root, name)), 0700)) |
| + must(t, os.WriteFile(filepath.Join(root, name), []byte(content), 0600)) |
| +} |
| +func raw(v any) []byte { b, _ := json.Marshal(v); return b } |
| + |
| +const baseID = "1111111111111111111111111111111111111111" |
| +const fixID = "2222222222222222222222222222222222222222" |
| +const repoID = "https://example.test/team/repo" |
| +const bugTest = `package fixture |
| +import "testing" |
| +func TestBug(t *testing.T) { if Value()!=2 {t.Fatal("wrong value")} } |
| +` |
| +const oldTest = `package fixture |
| +import "testing" |
| +func TestOld(t *testing.T) {t.Run("child",func(t *testing.T){})} |
| +` |
| + |
| +type localSandbox struct{} |
| + |
| +func (localSandbox) Run(ctx context.Context, c Command, w string, _ paseo.ReadPolicy, out, errout io.Writer) (int, error) { |
| + cmd := exec.CommandContext(ctx, c.Argv[0], c.Argv[1:]...) |
| + cmd.Dir = filepath.Join(w, c.Dir) |
| + cmd.Env = testEnv() |
| + cmd.Stdout = out |
| + cmd.Stderr = errout |
| + err := cmd.Run() |
| + if x, ok := err.(*exec.ExitError); ok { |
| + return x.ExitCode(), nil |
| + } |
| + return 0, err |
| +} |
| +func testEnv() []string { |
| + return append(os.Environ(), "CGO_ENABLED=0", "GOWORK=off", "GOFLAGS=", "GOTOOLCHAIN=local", "GOPROXY=off") |
| +} |
| + |
| +type fixture struct { |
| + e *Executor |
| + d Definition |
| + r Reproduction |
| + base, candidate string |
| + c team.GitCandidate |
| + hash string |
| +} |
| + |
| +func newFixture(t *testing.T) fixture { |
| + t.Helper() |
| + b := t.TempDir() |
| + c := t.TempDir() |
| + for _, root := range []string{b, c} { |
| + put(t, root, "go.mod", "module fixture\n\ngo 1.26\n") |
| + put(t, root, "old_test.go", oldTest) |
| + } |
| + put(t, b, "value.go", "package fixture\nfunc Value() int {return 1}\n") |
| + put(t, c, "value.go", "package fixture\nfunc Value() int {return 2}\n") |
| + command := Command{Argv: []string{"go", "test", "-json", "-count=1", "./..."}, Dir: ".", Parser: "go-test-json", TimeoutSeconds: 30} |
| + d, err := ParseDefinition(context.Background(), raw(Definition{Version: 1, Repository: repoID, Base: baseID, Commands: []Command{command}, Reproduction: command}), repoID, baseID) |
| + must(t, err) |
| + d, err = FreezeMaterial(context.Background(), d, b) |
| + must(t, err) |
| + r := Reproduction{ExpectedSymptom: "wrong value", Files: []File{{Path: "bug_test.go", Bytes: []byte(bugTest)}}, TestNames: []TestIdentity{{Package: "fixture", Name: "TestBug"}}} |
| + cand := team.GitCandidate{Repository: repoID, BaseCommit: baseID, Commit: fixID, Tree: strings.Repeat("3", 40)} |
| + cfg := Config{ResolveCandidate: func(_ context.Context, hash string) (team.GitCandidate, error) { |
| + if hash != CandidateHash(cand) { |
| + return team.GitCandidate{}, paseo.ErrIdentity |
| + } |
| + return cand, nil |
| + }, Reproduction: func(context.Context, string) (Reproduction, error) { return r, nil }, ScratchRoot: t.TempDir(), Scope: team.Scope{Account: "team", Job: 1}, Handle: team.Handle{Attempt: 1, Fence: 1, Runner: "runner"}, Deadline: time.Now().Add(time.Minute), Policy: paseo.ReadPolicy{ConfigHash: "policy", DeniedPaths: []string{t.TempDir()}}, Export: func(ctx context.Context, commit, dest string) error { |
| + src := c |
| + if commit == baseID { |
| + src = b |
| + } |
| + return copyTree(src, dest) |
| + }, Isolation: func(context.Context) (team.IsolationSnapshot, error) { |
| + return team.IsolationSnapshot{Status: "confined", RunnerTainted: true, AcknowledgementIDs: []string{"ack"}, ObservedTuples: []team.IsolationTuple{{Provider: "codex"}}}, nil |
| + }} |
| + e, err := newExecutor(cfg, localSandbox{}) |
| + must(t, err) |
| + baseline, err := e.CaptureBaseline(context.Background(), d) |
| + must(t, err) |
| + d.Baseline = baseline |
| + e.cfg.DefinitionHash = Digest(raw(d)) |
| + e.cfg.ReproductionHash = Digest(raw(r)) |
| + return fixture{e, d, r, b, c, cand, CandidateHash(cand)} |
| +} |
| +func TestFrozenReproduction(t *testing.T) { |
| + f := newFixture(t) |
| + base, err := f.e.Reproduce(context.Background(), f.d, f.r, baseID, "") |
| + must(t, err) |
| + if base.Outcome != team.CheckFail || base.SubjectHash != baseID || base.TestsRun < 1 || base.TestsFailed < 1 || !base.CollisionChecked { |
| + t.Fatalf("bad base evidence: %+v", base) |
| + } |
| + log, err := f.e.Log(context.Background(), base.LogHash) |
| + must(t, err) |
| + if Digest(log) != base.LogHash { |
| + t.Fatal("log digest mismatch") |
| + } |
| + pass, err := f.e.Reproduce(context.Background(), f.d, f.r, fixID, f.hash) |
| + must(t, err) |
| + if pass.Outcome != team.CheckPass || pass.SubjectHash != f.hash || pass.OverlayHash != base.OverlayHash { |
| + t.Fatalf("bad candidate evidence: %+v", pass) |
| + } |
| + for _, change := range []string{"bytes", "symptom", "names", "command", "definition_command", "definition_bytes", "hash", "base"} { |
| + t.Run(change, func(t *testing.T) { |
| + d := f.d |
| + r := f.r |
| + r.Files = append([]File(nil), r.Files...) |
| + subject := fixID |
| + hash := f.hash |
| + switch change { |
| + case "bytes": |
| + r.Files[0].Bytes = []byte("changed") |
| + case "symptom": |
| + r.ExpectedSymptom = "other" |
| + case "names": |
| + r.TestNames = nil |
| + case "definition_command": |
| + d.Commands = append([]Command(nil), d.Commands...) |
| + d.Commands[0].TimeoutSeconds-- |
| + d.Reproduction.TimeoutSeconds-- |
| + case "definition_bytes": |
| + d.Files = append([]File(nil), d.Files...) |
| + d.Files[0].Bytes = []byte("changed frozen file") |
| + case "command": |
| + d.Reproduction.Argv = []string{"true"} |
| + case "hash": |
| + hash = "" |
| + case "base": |
| + subject = "bad" |
| + } |
| + if _, err := f.e.Reproduce(context.Background(), d, r, subject, hash); err == nil { |
| + t.Fatal("changed frozen evidence accepted") |
| + } |
| + }) |
| + } |
| + entries, err := os.ReadDir(f.e.cfg.ScratchRoot) |
| + must(t, err) |
| + if len(entries) != 0 { |
| + t.Fatal("scratch retained") |
| + } |
| +} |
| +func TestTrustedBaseCheckDefinitions(t *testing.T) { |
| + f := newFixture(t) |
| + for _, change := range []string{"wrong_base", "unknown", "duplicate", "no_test", "timeout", "parser", "traversal", "filter", "baseline", "platform", "tags"} { |
| + t.Run(change, func(t *testing.T) { |
| + d := f.d |
| + d.Commands = append([]Command(nil), d.Commands...) |
| + b := raw(d) |
| + switch change { |
| + case "baseline": |
| + d.Baseline.Hash = strings.Repeat("a", 64) |
| + case "platform": |
| + d.GOOS = "other" |
| + case "tags": |
| + d.Reproduction.Argv = append(append([]string(nil), d.Reproduction.Argv...), "-tags=other") |
| + case "wrong_base": |
| + d.Base = fixID |
| + case "unknown": |
| + b = append([]byte(`{"bogus":1,`), b[1:]...) |
| + case "duplicate": |
| + b = append([]byte(`{"version":1,`), b[1:]...) |
| + case "no_test": |
| + d.Commands = nil |
| + case "timeout": |
| + d.Commands[0].TimeoutSeconds = 1201 |
| + case "parser": |
| + d.Commands[0].Parser = "exit" |
| + case "traversal": |
| + d.Commands[0].Dir = "../" |
| + case "filter": |
| + d.Commands[0].Argv = []string{"go", "test", "-json", "-run=TestOld"} |
| + } |
| + if change != "unknown" && change != "duplicate" { |
| + b = raw(d) |
| + } |
| + if _, err := ParseDefinition(context.Background(), b, repoID, baseID); err == nil { |
| + t.Fatal("unsafe definition accepted") |
| + } |
| + }) |
| + } |
| + put(t, f.base, "scripts/gate.sh", "echo trusted\n") |
| + trusted := f.d |
| + trusted.TrustedPaths = []string{"scripts"} |
| + d, err := FreezeMaterial(context.Background(), trusted, f.base) |
| + must(t, err) |
| + if len(d.Files) < 2 { |
| + t.Fatal("transitive material not frozen") |
| + } |
| +} |
| +func TestReproductionOverlayCollision(t *testing.T) { |
| + for _, kind := range []string{"edited", "traversal", "absolute", "symlink", "duplicate", "non_test", "unchanged", "frozen"} { |
| + t.Run(kind, func(t *testing.T) { |
| + f := newFixture(t) |
| + r := f.r |
| + switch kind { |
| + case "edited": |
| + put(t, f.candidate, "bug_test.go", "candidate fix") |
| + case "traversal": |
| + r.Files[0].Path = "../bad_test.go" |
| + case "absolute": |
| + r.Files[0].Path = "/bad_test.go" |
| + case "symlink": |
| + must(t, os.Symlink(f.base, filepath.Join(f.candidate, "link"))) |
| + r.Files[0].Path = "link/bug_test.go" |
| + case "duplicate": |
| + r.Files = append(r.Files, r.Files[0]) |
| + case "non_test": |
| + r.Files[0].Path = "value.go" |
| + case "unchanged": |
| + put(t, f.base, "bug_test.go", "package fixture\n") |
| + put(t, f.candidate, "bug_test.go", "package fixture\n") |
| + case "frozen": |
| + put(t, f.candidate, "bug_test.go", bugTest) |
| + } |
| + f.e.cfg.ReproductionHash = Digest(raw(r)) |
| + _, err := f.e.Reproduce(context.Background(), f.d, r, fixID, f.hash) |
| + if kind == "unchanged" || kind == "frozen" { |
| + must(t, err) |
| + } else if err == nil { |
| + t.Fatal("unsafe overlay accepted") |
| + } |
| + if kind == "edited" { |
| + b, err := os.ReadFile(filepath.Join(f.candidate, "bug_test.go")) |
| + must(t, err) |
| + if string(b) != "candidate fix" { |
| + t.Fatal("fix overwritten") |
| + } |
| + } |
| + }) |
| + } |
| +} |
| +func TestRepositoryTestSetSuperset(t *testing.T) { |
| + f := newFixture(t) |
| + put(t, f.candidate, "extra_test.go", "package fixture\nimport \"testing\"\nfunc TestExtra(t *testing.T){}\n") |
| + result, err := f.e.RepositoryChecks(context.Background(), f.d, f.c, f.hash) |
| + must(t, err) |
| + if result.Outcome != team.CheckPass || result.ObservedTestSetHash == result.BaselineTestSetHash || len(result.ObservedNames) < 4 { |
| + t.Fatalf("extra tests rejected: %+v", result) |
| + } |
| + if !result.Isolation.RunnerTainted || result.Isolation.Status != "unconfined" { |
| + t.Fatal("repository checks lost runner taint") |
| + } |
| + spec := team.ArtifactSpec{Role: team.RoleRepositoryChecks, Payload: raw(result)} |
| + _, err = f.e.ValidateEvidence(context.Background(), nil, f.e.cfg.Scope, f.e.cfg.Handle, spec) |
| + must(t, err) |
| + result.Isolation.RunnerTainted = false |
| + spec.Payload = raw(result) |
| + if _, err = f.e.ValidateEvidence(context.Background(), nil, f.e.cfg.Scope, f.e.cfg.Handle, spec); err == nil { |
| + t.Fatal("stripped repository taint registered") |
| + } |
| + put(t, f.candidate, "old_test.go", strings.ReplaceAll(oldTest, "TestOld", "TestRenamed")) |
| + if _, err = f.e.RepositoryChecks(context.Background(), f.d, f.c, f.hash); err == nil { |
| + t.Fatal("renamed baseline accepted") |
| + } |
| +} |
| +func TestRepositoryDeletedTestFile(t *testing.T) { |
| + f := newFixture(t) |
| + must(t, os.Remove(filepath.Join(f.candidate, "old_test.go"))) |
| + put(t, f.candidate, "renamed_test.go", oldTest) |
| + if _, err := f.e.RepositoryChecks(context.Background(), f.d, f.c, f.hash); err == nil { |
| + t.Fatal("deleted test file accepted") |
| + } |
| +} |
| +func TestRepositoryTSkipRejected(t *testing.T) { |
| + f := newFixture(t) |
| + put(t, f.candidate, "old_test.go", strings.ReplaceAll(oldTest, "func(t *testing.T){}", "func(t *testing.T){t.Skip(\"skip\")}")) |
| + if _, err := f.e.RepositoryChecks(context.Background(), f.d, f.c, f.hash); err == nil { |
| + t.Fatal("skipped subtest accepted") |
| + } |
| +} |
| +func TestExecutorEvidenceOutcomes(t *testing.T) { |
| + f := newFixture(t) |
| + for _, kind := range []string{"compile", "skip", "zero", "symptom"} { |
| + t.Run(kind, func(t *testing.T) { |
| + r := f.r |
| + r.Files = append([]File(nil), r.Files...) |
| + switch kind { |
| + case "compile": |
| + r.Files[0].Bytes = []byte("bad go") |
| + case "skip": |
| + r.Files[0].Bytes = []byte(strings.ReplaceAll(bugTest, "t.Fatal(\"wrong value\")", "t.Skip(\"wrong value\")")) |
| + case "zero": |
| + r.Files[0].Bytes = []byte("package fixture") |
| + case "symptom": |
| + r.ExpectedSymptom = "different symptom" |
| + } |
| + f.e.cfg.ReproductionHash = Digest(raw(r)) |
| + if _, err := f.e.Reproduce(context.Background(), f.d, r, baseID, ""); err == nil { |
| + t.Fatal("invalid evidence accepted") |
| + } |
| + }) |
| + } |
| + f.e.cfg.ReproductionHash = Digest(raw(f.r)) |
| + r, err := f.e.Reproduce(context.Background(), f.d, f.r, baseID, "") |
| + must(t, err) |
| + if !r.Isolation.RunnerTainted || r.Isolation.Status != "unconfined" { |
| + t.Fatal("executor erased concurrent runner exposure") |
| + } |
| + spec := team.ArtifactSpec{Role: team.RoleBaseResult, Payload: raw(r)} |
| + _, err = f.e.ValidateEvidence(context.Background(), nil, f.e.cfg.Scope, f.e.cfg.Handle, spec) |
| + must(t, err) |
| + stale := f.e.cfg.Handle |
| + stale.Fence++ |
| + if _, err = f.e.ValidateEvidence(context.Background(), nil, f.e.cfg.Scope, stale, spec); err == nil { |
| + t.Fatal("executor attestation crossed current fence") |
| + } |
| + r.Isolation.RunnerTainted = false |
| + r.Isolation.Status = "confined" |
| + spec.Payload = raw(r) |
| + if _, err = f.e.ValidateEvidence(context.Background(), nil, f.e.cfg.Scope, f.e.cfg.Handle, spec); err == nil { |
| + t.Fatal("stripped taint registered") |
| + } |
| + spec.Payload = []byte(`{"outcome":"pass"}`) |
| + if _, err = f.e.ValidateEvidence(context.Background(), nil, f.e.cfg.Scope, f.e.cfg.Handle, spec); err == nil { |
| + t.Fatal("agent fabricated executor result") |
| + } |
| +} |
| +func TestExecutorStreaming(t *testing.T) { |
| + for _, kind := range []string{"complete", "incomplete", "truncated", "no_tests", "skip", "build", "timeout", "large"} { |
| + t.Run(kind, func(t *testing.T) { |
| + s := newGoResults() |
| + data := `{"Action":"start","Package":"p"}` + "\n" + `{"Action":"run","Package":"p","Test":"TestOne"}` + "\n" |
| + switch kind { |
| + case "no_tests": |
| + data = `{"Action":"start","Package":"p"}` + "\n" |
| + case "skip": |
| + data += `{"Action":"skip","Package":"p","Test":"TestOne"}` + "\n" |
| + case "build": |
| + data += `{"Action":"build-fail","Package":"p"}` + "\n" |
| + case "large": |
| + for range 1000 { |
| + data += `{"Action":"output","Package":"p","Test":"TestOne","Output":"` + strings.Repeat("x", 100) + `"}` + "\n" |
| + } |
| + } |
| + if kind == "incomplete" { |
| + data += `{"Action":"pass","Package":"p"}` + "\n" |
| + } else if kind == "no_tests" { |
| + data += `{"Action":"pass","Package":"p"}` + "\n" |
| + } else if kind != "incomplete" { |
| + data += `{"Action":"pass","Package":"p","Test":"TestOne"}` + "\n" + `{"Action":"pass","Package":"p"}` + "\n" |
| + } |
| + if kind == "truncated" { |
| + data += `{"Action":` |
| + } |
| + for _, chunk := range bytes.SplitAfter([]byte(data), []byte("\n")) { |
| + _, err := s.Write(chunk) |
| + must(t, err) |
| + } |
| + err := s.finish(0, nil) |
| + if kind == "complete" || kind == "large" { |
| + must(t, err) |
| + if len(s.log.Bytes()) > 65536 { |
| + t.Fatal("unbounded retained output") |
| + } |
| + } else if kind != "timeout" && err == nil { |
| + t.Fatal("invalid stream accepted") |
| + } |
| + if kind == "timeout" && s.finish(0, context.DeadlineExceeded) == nil { |
| + t.Fatal("timeout accepted") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestExecutorCandidateBinding(t *testing.T) { |
| + f := newFixture(t) |
| + if _, err := f.e.Reproduce(context.Background(), f.d, f.r, fixID, strings.Repeat("a", 64)); err == nil { |
| + t.Fatal("unverified candidate hash accepted") |
| + } |
| + if _, err := f.e.Reproduce(context.Background(), f.d, f.r, baseID, f.hash); err == nil { |
| + t.Fatal("candidate hash bound to wrong commit") |
| + } |
| +} |
| +func TestTrustedGateAndBaseline(t *testing.T) { |
| + f := newFixture(t) |
| + put(t, f.base, "gate.sh", "#!/bin/sh\nexit 1\n") |
| + put(t, f.candidate, "gate.sh", "#!/bin/sh\nexit 0\n") |
| + trusted := f.d |
| + trusted.TrustedPaths = []string{"gate.sh"} |
| + d, err := FreezeMaterial(context.Background(), trusted, f.base) |
| + must(t, err) |
| + d.Commands = append(d.Commands, Command{Argv: []string{"/bin/sh", "gate.sh"}, 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 replaced trusted gate") |
| + } |
| + put(t, f.base, "known_test.go", bugTest) |
| + d, err = FreezeMaterial(context.Background(), f.d, f.base) |
| + must(t, err) |
| + baseline, err := f.e.CaptureBaseline(context.Background(), d) |
| + must(t, err) |
| + if !superset(baseline.Names, []TestIdentity{{Package: "fixture", Name: "TestBug"}}) { |
| + t.Fatal("known failing test omitted from baseline") |
| + } |
| + put(t, f.base, "known_test.go", "invalid Go") |
| + if _, err = f.e.CaptureBaseline(context.Background(), d); err == nil { |
| + t.Fatal("incomplete baseline accepted") |
| + } |
| +} |
| + |
| +func TestTrustedBaseImmutableDefinition(t *testing.T) { |
| + root := t.TempDir() |
| + cmd := Command{Argv: []string{"go", "test", "-json", "-count=1", "./..."}, Dir: ".", Parser: "go-test-json", TimeoutSeconds: 30} |
| + put(t, root, ".equipo/checks.json", string(raw(map[string]any{"version": 1, "commands": []Command{cmd}, "reproduction": cmd}))) |
| + put(t, root, "go.mod", "module fixture\n\ngo 1.26\n") |
| + put(t, root, "old_test.go", oldTest) |
| + git := func(args ...string) string { |
| + t.Helper() |
| + c := exec.Command("git", args...) |
| + c.Dir = root |
| + c.Env = append(testEnv(), "GIT_CONFIG_NOSYSTEM=1", "GIT_CONFIG_GLOBAL=/dev/null") |
| + b, err := c.CombinedOutput() |
| + if err != nil { |
| + t.Fatalf("git %v: %s", args, b) |
| + } |
| + return strings.TrimSpace(string(b)) |
| + } |
| + git("init", "-q") |
| + git("add", ".") |
| + git("-c", "user.name=fixture", "-c", "user.email=fixture@example.test", "-c", "commit.gpgSign=false", "commit", "-qm", "fixture") |
| + commit := git("rev-parse", "HEAD") |
| + put(t, root, ".equipo/checks.json", "changed after base") |
| + d, err := LoadBaseDefinition(context.Background(), root, repoID, commit, t.TempDir()) |
| + must(t, err) |
| + if d.Base != commit || len(d.Commands) != 1 || len(d.TestFiles) != 1 { |
| + t.Fatal("definition was not read from base") |
| + } |
| + if _, err = LoadBaseDefinition(context.Background(), root, repoID, fixID, t.TempDir()); err == nil { |
| + t.Fatal("unknown base accepted") |
| + } |
| + must(t, os.Remove(filepath.Join(root, ".equipo/checks.json"))) |
| + put(t, root, ".amadan/ci", "go test ./...\n") |
| + git("add", ".") |
| + git("-c", "user.name=fixture", "-c", "user.email=fixture@example.test", "-c", "commit.gpgSign=false", "commit", "-qm", "no adapter") |
| + commit = git("rev-parse", "HEAD") |
| + if _, err = LoadBaseDefinition(context.Background(), root, repoID, commit, t.TempDir()); err == nil { |
| + t.Fatal("unreviewed CI adapter accepted") |
| + } |
| +} |
| + |
| +func TestTrustedGatesFreshCopies(t *testing.T) { |
| + f := newFixture(t) |
| + put(t, f.base, "gate.sh", "#!/bin/sh\ntest ! -f modified\n") |
| + put(t, f.base, "touch.sh", "touch modified\n") |
| + put(t, f.candidate, "gate.sh", "#!/bin/sh\nexit 0\n") |
| + trusted := f.d |
| + trusted.TrustedPaths = []string{"gate.sh", "touch.sh"} |
| + d, err := FreezeMaterial(context.Background(), trusted, f.base) |
| + must(t, err) |
| + d.Commands = append(d.Commands, Command{Argv: []string{"/bin/sh", "touch.sh"}, Dir: ".", Parser: "exit", TimeoutSeconds: 10}, Command{Argv: []string{"/bin/sh", "gate.sh"}, 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("earlier command changed a later gate's workspace", err) |
| + } |
| +} |
| +func TestExecutorHistoricalExposure(t *testing.T) { |
| + f := newFixture(t) |
| + r, err := f.e.Reproduce(context.Background(), f.d, f.r, baseID, "") |
| + must(t, err) |
| + f.e.cfg.Isolation = func(context.Context) (team.IsolationSnapshot, error) { |
| + return team.IsolationSnapshot{Status: "confined", ObservedTuples: []team.IsolationTuple{{Provider: "claude"}}}, nil |
| + } |
| + again, err := f.e.Reproduce(context.Background(), f.d, f.r, baseID, "") |
| + must(t, err) |
| + if !again.Isolation.RunnerTainted || again.Isolation.Status != "unconfined" { |
| + t.Fatal("historical runner taint erased") |
| + } |
| + h := f.e.cfg.Handle |
| + h.Fence++ |
| + if _, err = f.e.ValidateEvidence(context.Background(), nil, f.e.cfg.Scope, h, team.ArtifactSpec{Role: team.RoleBaseResult, Payload: raw(r)}); err == nil { |
| + t.Fatal("attestation crossed fence") |
| + } |
| +} |
| + |
| +func TestReproductionOverlayPathValidation(t *testing.T) { |
| + root := t.TempDir() |
| + outside := t.TempDir() |
| + must(t, os.Symlink(outside, filepath.Join(root, "link"))) |
| + for _, path := range []string{"../escape_test.go", "/escape_test.go", "link/escape_test.go"} { |
| + if err := safePath(root, path, true); err == nil { |
| + t.Fatal("unsafe path accepted", path) |
| + } |
| + } |
| + if err := filesValid([]File{{Path: "same_test.go"}, {Path: "same_test.go"}}, true); err == nil { |
| + t.Fatal("duplicate overlay accepted") |
| + } |
| +} |
| + |
| +func TestExecutorCanonicalCandidateHash(t *testing.T) { |
| + f := newFixture(t) |
| + canonical := []byte(`{"base_commit":"1111111111111111111111111111111111111111","commit":"2222222222222222222222222222222222222222","repository":"https://example.test/team/repo","tree":"3333333333333333333333333333333333333333"}`) |
| + hash := Digest(canonical) |
| + f.e.cfg.ResolveCandidate = func(context.Context, string) (team.GitCandidate, error) { return f.c, nil } |
| + r, err := f.e.Reproduce(context.Background(), f.d, f.r, fixID, hash) |
| + must(t, err) |
| + if r.SubjectHash != hash { |
| + t.Fatal("candidate subject does not use canonical artifact hash") |
| + } |
| + if _, err = f.e.RepositoryChecks(context.Background(), f.d, f.c, hash); err != nil { |
| + t.Fatal("repository checks rejected canonical artifact", err) |
| + } |
| +} |
| +func TestExecutorProductionDependencies(t *testing.T) { |
| + f := newFixture(t) |
| + if _, err := New(f.e.cfg, &CodexSandbox{}); err == nil { |
| + t.Fatal("empty production sandbox accepted") |
| + } |
| +} |
| + |
| +func TestTrustedMaterialPreservesCandidateData(t *testing.T) { |
| + f := newFixture(t) |
| + put(t, f.base, "data.json", "old") |
| + put(t, f.candidate, "data.json", "fixed") |
| + put(t, f.candidate, "data_test.go", `package fixture |
| +import("testing";"os") |
| +func TestData(t *testing.T){b,e:=os.ReadFile("data.json");if e!=nil||string(b)!="fixed"{t.Fatal("candidate data was replaced")}} |
| +`) |
| + d, err := FreezeMaterial(context.Background(), f.d, f.base) |
| + must(t, err) |
| + f.e.cfg.DefinitionHash = Digest(raw(d)) |
| + if _, err = f.e.RepositoryChecks(context.Background(), d, f.c, f.hash); err != nil { |
| + t.Fatal("candidate data changed by trusted overlay", err) |
| + } |
| +} |
| + |
| +func TestTrustedMaterialDirectory(t *testing.T) { |
| + f := newFixture(t) |
| + put(t, f.base, "controls/helper.sh", "value=trusted\n") |
| + put(t, f.base, "controls/gate.sh", ". controls/helper.sh\ntest \"$value\" = trusted && test ! -e controls/extra.sh\n") |
| + put(t, f.candidate, "controls/helper.sh", "value=changed\n") |
| + put(t, f.candidate, "controls/extra.sh", "injected\n") |
| + d := f.d |
| + d.TrustedPaths = []string{"controls"} |
| + d, err := FreezeMaterial(context.Background(), d, f.base) |
| + must(t, err) |
| + d.Commands = append(d.Commands, Command{Argv: []string{"/bin/sh", "controls/gate.sh"}, 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("trusted dependency tree was not restored", err) |
| + } |
| +} |
| + |
| +func TestTrustedUndeclaredScript(t *testing.T) { |
| + f := newFixture(t) |
| + d := f.d |
| + d.Commands = append(d.Commands, Command{Argv: []string{"/bin/sh", "gate.sh"}, Dir: ".", Parser: "exit", TimeoutSeconds: 10}) |
| + if _, err := ParseDefinition(context.Background(), raw(d), repoID, baseID); err == nil { |
| + t.Fatal("undeclared command material accepted") |
| + } |
| +} |
diff --git a/internal/runner/checks/goresults.go b/internal/runner/checks/goresults.go| new file mode 100644 |
| index 00000000..6329d7c0 |
| --- /dev/null |
| +++ b/internal/runner/checks/goresults.go |
| @@ -0,0 +1,181 @@ |
| +package checks |
| + |
| +import ( |
| + "bytes" |
| + "crypto/sha256" |
| + "encoding/hex" |
| + "encoding/json" |
| + "hash" |
| + "io" |
| + "strings" |
| + |
| + "amadan.net/oficina/equipo/internal/runner/paseo" |
| +) |
| + |
| +const logLimit = 64 * 1024 |
| + |
| +type boundedLog struct { |
| + bytes.Buffer |
| + hash hash.Hash |
| +} |
| + |
| +func (l *boundedLog) Write(p []byte) (int, error) { |
| + if l.hash == nil { |
| + l.hash = sha256.New() |
| + } |
| + _, _ = l.hash.Write(p) |
| + n := len(p) |
| + if left := logLimit - l.Len(); left > 0 { |
| + _, _ = l.Buffer.Write(p[:min(left, n)]) |
| + } |
| + return n, nil |
| +} |
| +func (l *boundedLog) digest() string { |
| + if l.hash == nil { |
| + return Digest(nil) |
| + } |
| + return hex.EncodeToString(l.hash.Sum(nil)) |
| +} |
| + |
| +type testState struct { |
| + done, failed, matched bool |
| + tail string |
| +} |
| +type goResults struct { |
| + pending []byte |
| + log boundedLog |
| + bad bool |
| + packages map[string]string |
| + tests map[TestIdentity]*testState |
| + names []TestIdentity |
| + run, failed int |
| + symptom string |
| + matched bool |
| +} |
| + |
| +func newGoResults() *goResults { |
| + return &goResults{packages: map[string]string{}, tests: map[TestIdentity]*testState{}} |
| +} |
| +func (g *goResults) Write(p []byte) (int, error) { |
| + n := len(p) |
| + for len(p) > 0 { |
| + i := bytes.IndexByte(p, '\n') |
| + if i < 0 { |
| + i = len(p) - 1 |
| + } |
| + chunk := p[:i+1] |
| + p = p[i+1:] |
| + if len(g.pending)+len(chunk) > 1024*1024 { |
| + g.bad = true |
| + g.pending = nil |
| + } else { |
| + g.pending = append(g.pending, chunk...) |
| + if chunk[len(chunk)-1] == '\n' { |
| + g.event(g.pending) |
| + g.pending = nil |
| + } |
| + } |
| + } |
| + // Parsing always precedes bounded retention. |
| + // The caller's full chunk is hashed separately by the command collector. |
| + return n, nil |
| +} |
| +func (g *goResults) event(line []byte) { |
| + defer g.log.Write(line) |
| + var e struct{ Action, Package, Test, Output string } |
| + if json.Unmarshal(line, &e) != nil || e.Package == "" { |
| + g.bad = true |
| + return |
| + } |
| + id := TestIdentity{Package: e.Package, Name: e.Test} |
| + if e.Test == "" { |
| + switch e.Action { |
| + case "start": |
| + if _, ok := g.packages[e.Package]; ok { |
| + g.bad = true |
| + } |
| + g.packages[e.Package] = "running" |
| + case "pass", "fail": |
| + if g.packages[e.Package] != "running" { |
| + g.bad = true |
| + } |
| + g.packages[e.Package] = e.Action |
| + case "output": |
| + default: |
| + g.bad = true |
| + } |
| + return |
| + } |
| + switch e.Action { |
| + case "run": |
| + if g.packages[e.Package] != "running" || g.tests[id] != nil { |
| + g.bad = true |
| + return |
| + } |
| + g.tests[id] = &testState{} |
| + g.run++ |
| + g.names = append(g.names, id) |
| + case "pass", "fail": |
| + s := g.tests[id] |
| + if s == nil || s.done { |
| + g.bad = true |
| + return |
| + } |
| + s.done = true |
| + s.failed = e.Action == "fail" |
| + if s.failed { |
| + g.failed++ |
| + g.matched = g.matched || s.matched |
| + } |
| + case "output": |
| + if s := g.tests[id]; s != nil && g.symptom != "" { |
| + text := s.tail + e.Output |
| + s.matched = s.matched || strings.Contains(text, g.symptom) |
| + if len(text) > len(g.symptom) { |
| + text = text[len(text)-len(g.symptom):] |
| + } |
| + s.tail = text |
| + } |
| + case "pause", "cont": |
| + if g.tests[id] == nil { |
| + g.bad = true |
| + } |
| + default: |
| + g.bad = true |
| + } |
| +} |
| +func (g *goResults) finish(exit int, err error) error { |
| + if err != nil { |
| + return err |
| + } |
| + if g.bad || len(g.pending) != 0 || g.run == 0 || len(g.packages) == 0 || exit < 0 { |
| + return paseo.ErrContract |
| + } |
| + for _, s := range g.tests { |
| + if !s.done { |
| + return paseo.ErrContract |
| + } |
| + } |
| + for p, status := range g.packages { |
| + if status != "pass" && status != "fail" { |
| + return paseo.ErrContract |
| + } |
| + found := false |
| + failed := false |
| + for id, s := range g.tests { |
| + if id.Package == p { |
| + found = true |
| + failed = failed || s.failed |
| + } |
| + } |
| + if !found || status == "fail" && !failed || status == "pass" && failed { |
| + return paseo.ErrContract |
| + } |
| + } |
| + if exit == 0 && g.failed > 0 || exit != 0 && g.failed == 0 { |
| + return paseo.ErrContract |
| + } |
| + return nil |
| +} |
| + |
| +var _ io.Writer = (*goResults)(nil) |
diff --git a/internal/runner/checks/sandbox.go b/internal/runner/checks/sandbox.go| new file mode 100644 |
| index 00000000..9b8187b5 |
| --- /dev/null |
| +++ b/internal/runner/checks/sandbox.go |
| @@ -0,0 +1,180 @@ |
| +package checks |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "io" |
| + "os" |
| + "os/exec" |
| + "path/filepath" |
| + "runtime" |
| + "sort" |
| + "strings" |
| + "syscall" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/runner/paseo" |
| + "amadan.net/oficina/equipo/internal/runner/workspace" |
| +) |
| + |
| +const CodexVersion = "codex-cli 0.165.0" |
| + |
| +type SandboxConfig struct { |
| + Binary, ScratchRoot string |
| + Protected workspace.SecurityPaths |
| +} |
| +type CodexSandbox struct { |
| + binary, version, scratch, home string |
| + protected []string |
| +} |
| + |
| +func NewCodexSandbox(ctx context.Context, cfg SandboxConfig) (*CodexSandbox, error) { |
| + paths := append([]string{cfg.Protected.RunnerState, cfg.Protected.RunnerConfig, cfg.Protected.Journal, cfg.Protected.Bearer, cfg.Protected.Cleanup, cfg.Protected.ForgeCredential, cfg.Protected.PaseoHome, cfg.Protected.SSH}, cfg.Protected.ProviderHomes...) |
| + if len(cfg.Protected.ProviderHomes) == 0 { |
| + return nil, paseo.ErrPolicy |
| + } |
| + for _, p := range paths { |
| + if _, err := canonicalPath(p); err != nil { |
| + return nil, err |
| + } |
| + } |
| + if !filepath.IsAbs(cfg.Binary) || !filepath.IsAbs(cfg.ScratchRoot) { |
| + return nil, paseo.ErrContract |
| + } |
| + binary, err := filepath.EvalSymlinks(cfg.Binary) |
| + if err != nil { |
| + return nil, err |
| + } |
| + home, err := os.UserHomeDir() |
| + if err != nil { |
| + return nil, err |
| + } |
| + cmd := exec.CommandContext(ctx, binary, "--version") |
| + cmd.Env = []string{"PATH=/usr/bin:/bin"} |
| + b, err := cmd.Output() |
| + 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 |
| +} |
| +func canonicalPath(path string) (string, error) { |
| + if !filepath.IsAbs(path) || filepath.Clean(path) != path || strings.ContainsAny(path, "*?[\x00") { |
| + return "", paseo.ErrPolicy |
| + } |
| + p, err := filepath.EvalSymlinks(path) |
| + if err == nil { |
| + return p, nil |
| + } |
| + if !os.IsNotExist(err) { |
| + return "", err |
| + } |
| + parent := filepath.Dir(path) |
| + if parent == path { |
| + return "", err |
| + } |
| + p, err = canonicalPath(parent) |
| + if err != nil { |
| + return "", err |
| + } |
| + return filepath.Join(p, filepath.Base(path)), nil |
| +} |
| +func within(root, path string) bool { |
| + return root == path || strings.HasPrefix(path, root+string(filepath.Separator)) |
| +} |
| +func (s *CodexSandbox) Run(ctx context.Context, c Command, work string, policy paseo.ReadPolicy, stdout, stderr io.Writer) (int, error) { |
| + if policy.ConfigHash == "" || len(policy.DeniedPaths) == 0 || len(c.Argv) == 0 || c.TimeoutSeconds < 1 || c.TimeoutSeconds > 1200 { |
| + return -1, paseo.ErrPolicy |
| + } |
| + resolved, err := canonicalPath(work) |
| + if err != nil || resolved != work { |
| + return -1, paseo.ErrPolicy |
| + } |
| + if err = safeDir(work, c.Dir); err != nil { |
| + return -1, err |
| + } |
| + denies := map[string]bool{} |
| + for _, p := range append(append([]string(nil), s.protected...), policy.DeniedPaths...) { |
| + r, err := canonicalPath(p) |
| + if err != nil || within(p, work) || within(r, work) { |
| + return -1, paseo.ErrPolicy |
| + } |
| + denies[p] = true |
| + denies[r] = true |
| + } |
| + control, err := os.MkdirTemp(s.scratch, "sandbox-") |
| + if err != nil { |
| + return -1, err |
| + } |
| + 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 { |
| + return -1, err |
| + } |
| + if err = os.Mkdir(temp, 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")} { |
| + r, err := canonicalPath(p) |
| + if err != nil { |
| + return -1, err |
| + } |
| + roots[r] = roots[p] |
| + } |
| + denies[cfgHome] = true |
| + for p := range denies { |
| + roots[p] = "deny" |
| + } |
| + keys := make([]string, 0, len(roots)) |
| + for k := range roots { |
| + keys = append(keys, k) |
| + } |
| + sort.Strings(keys) |
| + var entries []string |
| + for _, k := range keys { |
| + key, _ := json.Marshal(k) |
| + v, _ := json.Marshal(roots[k]) |
| + entries = append(entries, string(key)+"="+string(v)) |
| + } |
| + 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") |
| + } |
| + 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.Stdout = stdout |
| + cmd.Stderr = stderr |
| + cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} |
| + cmd.WaitDelay = time.Second |
| + cmd.Cancel = func() error { |
| + if cmd.Process == nil { |
| + return nil |
| + } |
| + return syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL) |
| + } |
| + if err = cmd.Start(); err != nil { |
| + return -1, paseo.ErrContract |
| + } |
| + defer syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL) |
| + err = cmd.Wait() |
| + if ctx.Err() != nil { |
| + return -1, ctx.Err() |
| + } |
| + if err == nil { |
| + return 0, nil |
| + } |
| + var exit *exec.ExitError |
| + if errors.As(err, &exit) { |
| + return exit.ExitCode(), nil |
| + } |
| + return -1, paseo.ErrContract |
| +} |
diff --git a/internal/runner/checks/sandbox_test.go b/internal/runner/checks/sandbox_test.go| new file mode 100644 |
| index 00000000..151ba569 |
| --- /dev/null |
| +++ b/internal/runner/checks/sandbox_test.go |
| @@ -0,0 +1,129 @@ |
| +package checks |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "os" |
| + "os/exec" |
| + "path/filepath" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/runner/paseo" |
| + "amadan.net/oficina/equipo/internal/runner/workspace" |
| +) |
| + |
| +func TestCheckSandboxDeniedPaths(t *testing.T) { |
| + root := t.TempDir() |
| + work := filepath.Join(root, "work") |
| + must(t, os.Mkdir(work, 0700)) |
| + put(t, work, "control", "readable") |
| + 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) |
| + 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)) |
| + must(t, err) |
| + policy := paseo.ReadPolicy{ConfigHash: "sentinel", DeniedPaths: denied} |
| + for _, path := range denied { |
| + t.Run(filepath.Base(path), func(t *testing.T) { |
| + var out, errout bytes.Buffer |
| + code, err := s.Run(context.Background(), Command{Argv: []string{"/bin/sh", "-c", `cat control; cat "$1/sentinel"`, "check", path}, Dir: ".", TimeoutSeconds: 10}, work, policy, &out, &errout) |
| + must(t, err) |
| + if code == 0 || !strings.Contains(out.String(), "readable") || strings.Contains(out.String(), "secret-") { |
| + t.Fatalf("sandbox failed: %d %s %s", code, &out, &errout) |
| + } |
| + }) |
| + } |
| + var out, errout bytes.Buffer |
| + _, err = s.Run(context.Background(), Command{Argv: []string{"/bin/sleep", "30"}, Dir: ".", TimeoutSeconds: 1}, work, policy, &out, &errout) |
| + if err == nil { |
| + t.Fatal("command timeout ignored") |
| + } |
| + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond) |
| + defer cancel() |
| + _, err = s.Run(ctx, Command{Argv: []string{"/bin/sleep", "30"}, Dir: ".", TimeoutSeconds: 30}, work, policy, &out, &errout) |
| + if err == nil { |
| + t.Fatal("remaining attempt time ignored") |
| + } |
| + if _, err = s.Run(context.Background(), Command{Argv: []string{"true"}, Dir: ".", TimeoutSeconds: 1}, work, paseo.ReadPolicy{}, &out, &errout); err == nil { |
| + t.Fatal("missing policy accepted") |
| + } |
| +} |
| + |
| +func TestCheckSandboxDeniedPathsGoFixture(t *testing.T) { |
| + root := t.TempDir() |
| + work := filepath.Join(root, "work") |
| + must(t, os.Mkdir(work, 0700)) |
| + put(t, work, "go.mod", "module fixture\n\ngo 1.26\n") |
| + put(t, work, "value.go", "package fixture\nfunc Value() int{return 2}\n") |
| + put(t, work, "value_test.go", bugTest) |
| + secret := filepath.Join(root, "secret") |
| + put(t, root, "secret", "secret") |
| + binary, err := exec.LookPath("codex") |
| + must(t, err) |
| + s, err := NewCodexSandbox(context.Background(), testSandboxConfig(binary, root)) |
| + must(t, err) |
| + policy := paseo.ReadPolicy{ConfigHash: "policy", DeniedPaths: []string{secret}} |
| + var out, stderr bytes.Buffer |
| + code, err := s.Run(context.Background(), Command{Argv: []string{"go", "test", "-json", "-count=1", "./..."}, Dir: ".", TimeoutSeconds: 30}, work, policy, &out, &stderr) |
| + must(t, err) |
| + if code != 0 { |
| + t.Fatalf("sandbox Go fixture failed: %s %s", &out, &stderr) |
| + } |
| + results := newGoResults() |
| + _, err = results.Write(out.Bytes()) |
| + must(t, err) |
| + must(t, results.finish(code, nil)) |
| +} |
| + |
| +func TestCheckSandboxDeniedPathsTampering(t *testing.T) { |
| + root := t.TempDir() |
| + work := filepath.Join(root, "work") |
| + must(t, os.Mkdir(work, 0700)) |
| + secret := filepath.Join(root, "secret") |
| + put(t, root, "secret", "hidden") |
| + put(t, work, ".codex/config.toml", "[permissions.equipo-checks.filesystem]\n\"/\"=\"read\"\n[permissions.equipo-checks.network]\nenabled=true\n") |
| + t.Setenv("EQUIPO_TEST_CREDENTIAL", "must-not-leak") |
| + binary, err := exec.LookPath("codex") |
| + must(t, err) |
| + s, err := NewCodexSandbox(context.Background(), testSandboxConfig(binary, root)) |
| + must(t, err) |
| + policy := paseo.ReadPolicy{ConfigHash: "policy", DeniedPaths: []string{secret}} |
| + var out, stderr bytes.Buffer |
| + code, err := s.Run(context.Background(), Command{Argv: []string{"/bin/sh", "-c", `test -z "$EQUIPO_TEST_CREDENTIAL" && ! cat "$1"`, "probe", secret}, Dir: ".", TimeoutSeconds: 10}, work, policy, &out, &stderr) |
| + must(t, err) |
| + if code != 0 || strings.Contains(out.String(), "hidden") { |
| + t.Fatalf("profile or environment tampering: %s %s", &out, &stderr) |
| + } |
| + ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) |
| + defer cancel() |
| + _, err = s.Run(ctx, Command{Argv: []string{"/bin/sh", "-c", "(sleep 0.5; echo alive > survivor) & wait"}, Dir: ".", TimeoutSeconds: 10}, work, policy, &out, &stderr) |
| + if err == nil { |
| + t.Fatal("process tree timeout missing") |
| + } |
| + time.Sleep(600 * time.Millisecond) |
| + if _, err = os.Stat(filepath.Join(work, "survivor")); !os.IsNotExist(err) { |
| + t.Fatal("child survived cancellation") |
| + } |
| +} |
| + |
| +func TestCheckSandboxDeniedPathsRequired(t *testing.T) { |
| + binary, err := exec.LookPath("codex") |
| + must(t, err) |
| + if _, err = NewCodexSandbox(context.Background(), SandboxConfig{Binary: binary, ScratchRoot: t.TempDir()}); err == nil { |
| + t.Fatal("missing runner protected paths accepted") |
| + } |
| +} |
| + |
| +func testSandboxConfig(binary, root string) SandboxConfig { |
| + 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")}}} |
| +} |
diff --git a/internal/runnerproto/types.go b/internal/runnerproto/types.go| index 16cf5a4e..389a48cf 100644 |
| --- a/internal/runnerproto/types.go |
| +++ b/internal/runnerproto/types.go |
| @@ -174,3 +174,49 @@ type PreparedBug struct { |
| CheckDefinition []byte |
| CheckDefinitionHash, BaselineTestSetHash string |
| } |
| + |
| +type CheckCommand struct { |
| + Argv []string `json:"argv"` |
| + Dir string `json:"dir"` |
| + Parser string `json:"parser"` |
| + TimeoutSeconds int `json:"timeout_seconds"` |
| +} |
| +type CheckFile struct { |
| + Path string `json:"path"` |
| + Bytes []byte `json:"bytes"` |
| +} |
| +type TestBaseline struct { |
| + Names []team.TestIdentity `json:"names"` |
| + Hash string `json:"hash"` |
| +} |
| +type CheckDefinition struct { |
| + TrustedPaths []string `json:"trusted_paths"` |
| + Version int `json:"version"` |
| + Repository string `json:"repository"` |
| + Base string `json:"base"` |
| + Commands []CheckCommand `json:"commands"` |
| + Reproduction CheckCommand `json:"reproduction"` |
| + Baseline TestBaseline `json:"baseline"` |
| + Files []CheckFile `json:"files"` |
| + TestFiles []string `json:"test_files"` |
| + GOOS string `json:"goos"` |
| + GOARCH string `json:"goarch"` |
| +} |
| +type Reproduction struct { |
| + ExpectedSymptom string `json:"expected_symptom"` |
| + Files []CheckFile `json:"files"` |
| + TestNames []team.TestIdentity `json:"test_names"` |
| +} |
| +type BlobRequest struct { |
| + Version int `json:"version"` |
| + Scope team.Scope `json:"scope"` |
| + Handle team.Handle `json:"handle"` |
| + Digest string `json:"digest"` |
| + Bytes []byte `json:"bytes"` |
| +} |
| + |
| +type BlobReadRequest struct { |
| + Version int `json:"version"` |
| + Scope team.Scope `json:"scope"` |
| + Digest string `json:"digest"` |
| +} |