oficina / equipo Public

feat: publish verified commits to qualified review refs

Add qualified-ref publication, immutable description provenance, scoped tickets, durable receipt reconciliation and offline fault tests.

The production Amadan description transport remains blocked: installed help documents writes but no description readback contract. No live forge command was run. Controller Opus review is pending.
codex agent, operated by paul@keymail.dev pushed by claude agent, operated by paul@keymail.dev b1d451e04dd325fe03ff700d535494ca5c4f0c04 parent 254c24b
22 files changed, +1,639 −25
  • .rastrillo/budgets.txt +2 −2
  • internal/equipo/runner_adapters.go +92 −0
  • internal/equipo/runner_api.go +1 −1
  • internal/equipo/runner_events.go +1 −1
  • internal/equipo/runner_mutations.go +12 −2
  • internal/equipo/runner_provenance.go +1 −0
  • internal/equipo/team/actions.go +38 −6
  • internal/equipo/team/admission.go +5 −1
  • internal/equipo/team/evidence.go +1 −0
  • internal/equipo/team/fixture.go +6 −0
  • internal/equipo/team/git_evidence.go +2 −0
  • internal/equipo/team/git_evidence_test.go +1 −1
  • internal/equipo/team/model.go +7 −6
  • internal/equipo/team/publication.go +176 −0
  • internal/equipo/team/publication_test.go +155 −0
  • internal/equipotest/publish_test.go +94 −0
  • internal/equipotest/runner_api_test.go +4 −4
  • internal/runner/forge/git.go +136 −0
  • internal/runner/forge/publisher.go +362 −0
  • internal/runner/forge/publisher_test.go +539 −0
  • internal/runnerproto/journal.go +1 −1
  • internal/runnerproto/types.go +3 −0

CI failed — run details

diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt
index 9d5bd752..02af385b 100644
--- a/.rastrillo/budgets.txt
+++ b/.rastrillo/budgets.txt
@@ -9,11 +9,11 @@
# time <dir> <duration> <reason>
# perf <METHOD> <path> <duration>|skip <reason>
# boot <duration> <reason>
-size internal/equipo/team 7900 - Preserve the plan-mandated core layout; Tasks 2-4 add recovery and evidence checks, and Task 8 adds atomic admission tickets and shared transaction composition.
+size internal/equipo/team 8200 - Preserve the plan-mandated core layout; Task 14 raises 7900 after adding publication description provenance, receipt guards and scoped admission authorization (7931 lines).
perf GET /* skip Unknown private paths render 404; this fallback contains no screens.
time internal/equipo/team 15s Copied core crash, recovery and concurrency tests take about 7.7s idle and 13.6s on the loaded shared machine.
time internal/equipotest 25s Task 6 keeps the mandated connections tests in this package; its focused authority, isolation, atomic-write and real-session checks took 15.5s on the shared machine, above the prior 15s allowance.
-size internal/equipo 7000 - Task 12 adds the mandated transactional event inbox, timeline projections and artifact request deduplication beside the Task 8 runner API and authority checks.
+size internal/equipo 7400 - Task 14 raises 7000 after adding the mandated runner adapters, validated durable receipt lookup and publication protocol routes beside the existing runner API (7087 lines).
size internal/equipotest - 9100 Task 12 keeps runner_events_test.go beside the existing activation fixtures to verify crash replay, atomic settlement, epoch replacement, authority, HTTP ingestion and migration reopen.
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/runner_adapters.go b/internal/equipo/runner_adapters.go
new file mode 100644
index 00000000..deee4243
--- /dev/null
+++ b/internal/equipo/runner_adapters.go
@@ -0,0 +1,92 @@
+package equipo
+
+import (
+ "context"
+ "encoding/json"
+
+ "amadan.net/oficina/equipo/internal/equipo/team"
+ "gorm.io/gorm"
+)
+
+type runnerAdapter struct {
+ store *Store
+ operation team.Operation
+}
+
+func (s *Store) RunnerAdapter(op team.Operation) team.Adapter {
+ return runnerAdapter{store: s, operation: op}
+}
+func (a runnerAdapter) Classify(op team.Operation) (team.ReplayClass, error) {
+ if op != a.operation {
+ return "", team.ErrUnknownKind
+ }
+ switch op {
+ case team.OpForgePublish:
+ return team.ReplayReconcilable, nil
+ case team.OpProviderCall:
+ return team.ReplayUnsafe, nil
+ }
+ return "", team.ErrUnknownKind
+}
+func (a runnerAdapter) Execute(context.Context, team.Dispatch) (team.Receipt, error) {
+ return team.Receipt{}, team.ErrState
+}
+func (a runnerAdapter) Reconcile(ctx context.Context, d team.Dispatch) (team.ReconcileResult, error) {
+ if _, err := a.Classify(d.Operation); err != nil {
+ return team.ReconcileResult{}, err
+ }
+ var action executionActions
+ // The action's stored payload and attempt bind every lookup, including after
+ // cancellation. Raw runner observations are never receipts.
+ if err := a.store.db.G.WithContext(ctx).First(&action, "id=?", d.Action).Error; err != nil {
+ return team.ReconcileResult{}, storeError(err)
+ }
+ if action.Key != d.Key || action.Operation != string(d.Operation) || action.PayloadHash != d.Hash || string(action.Payload) != string(d.Payload) {
+ return team.ReconcileResult{}, ErrConflict
+ }
+ var rows []runnerObservation
+ err := a.store.db.G.WithContext(ctx).Where("operation=? AND assignment_id IN (SELECT id FROM runner_assignments WHERE job_id=? AND attempt_id=? AND fence=?)", "verified_receipt", action.JobID, action.AttemptID, action.Fence).Order("at, request_id").Find(&rows).Error
+ if err != nil {
+ return team.ReconcileResult{}, storeError(err)
+ }
+ var found *team.Receipt
+ for _, row := range rows {
+ var q RunnerRequest
+ if json.Unmarshal([]byte(row.Payload), &q) != nil {
+ return team.ReconcileResult{}, ErrUnavailable
+ }
+ if q.ActionID != d.Action {
+ continue
+ }
+ var assignment runnerAssignment
+ if err := a.store.db.G.WithContext(ctx).First(&assignment, "id=?", row.AssignmentID).Error; err != nil {
+ return team.ReconcileResult{}, storeError(err)
+ }
+ if !binding(assignment, q) || q.Scope.Job != team.JobID(action.JobID) || q.Handle.Attempt != team.AttemptID(action.AttemptID) || q.Handle.Fence != action.Fence || q.Receipt == nil {
+ return team.ReconcileResult{}, ErrConflict
+ }
+ if d.Operation == team.OpForgePublish {
+ if err := team.ValidatePublicationReceipt(d.Payload, *q.Receipt); err != nil {
+ return team.ReconcileResult{}, err
+ }
+ }
+ if found != nil {
+ before, _ := json.Marshal(found)
+ after, _ := json.Marshal(q.Receipt)
+ if string(before) != string(after) {
+ return team.ReconcileResult{}, team.ErrReceiptConflict
+ }
+ }
+ found = q.Receipt
+ }
+ return team.ReconcileResult{Receipt: found, Definitive: found != nil}, nil
+}
+func (e *Execution) recordVerifiedReceipt(ctx context.Context, tx *gorm.DB, a runnerAssignment, q RunnerRequest, receipt team.Receipt) error {
+ verified := q
+ verified.RequestID = "verified/" + q.RequestID
+ verified.Receipt = &receipt
+ if _, err := observeRunner(tx, a, "verified_receipt", verified, e.store.runnerClock.Now().UTC()); err != nil {
+ return err
+ }
+ return e.Core.Record(ctx, q.Scope, q.ActionID, receipt)
+}
diff --git a/internal/equipo/runner_api.go b/internal/equipo/runner_api.go
index b99af79a..11661ff7 100644
--- a/internal/equipo/runner_api.go
+++ b/internal/equipo/runner_api.go
@@ -19,7 +19,7 @@ func (s *Store) RunnerHandler() http.Handler {
r.Post("/blobs", s.runnerPutBlob)
r.Post("/blobs/read", s.runnerReadBlob)
r.Post("/claim", s.runnerClaim)
- for _, op := range []string{"question_resolved", "questions", "answers", "renew", "prepare", "events", "artifacts", "intend", "admit", "receipts", "lost", "complete", "release", "stop", "contained"} {
+ for _, op := range []string{"publication_ready", "publication_authorize", "question_resolved", "questions", "answers", "renew", "prepare", "events", "artifacts", "intend", "admit", "receipts", "lost", "complete", "release", "stop", "contained"} {
r.Post("/"+op, s.runnerMutation(op))
}
r.Post("/connections", s.runnerConnections)
diff --git a/internal/equipo/runner_events.go b/internal/equipo/runner_events.go
index 39ab31d1..f138683e 100644
--- a/internal/equipo/runner_events.go
+++ b/internal/equipo/runner_events.go
@@ -133,7 +133,7 @@ func (e *Execution) ingestEventAt(ctx context.Context, tx *gorm.DB, a runnerAssi
if err != nil {
return err
}
- if err = e.Core.Record(ctx, event.Scope, event.ActionID, receipt); err != nil {
+ if err = e.recordVerifiedReceipt(ctx, tx, a, q, receipt); err != nil {
return err
}
}
diff --git a/internal/equipo/runner_mutations.go b/internal/equipo/runner_mutations.go
index 8300e9f0..12216056 100644
--- a/internal/equipo/runner_mutations.go
+++ b/internal/equipo/runner_mutations.go
@@ -160,7 +160,7 @@ func observeRunner(tx *gorm.DB, a runnerAssignment, op string, q RunnerRequest,
}
func (e *Execution) mutateAt(ctx context.Context, tx *gorm.DB, a runnerAssignment, value Assignment, op string, q RunnerRequest, cleanup bool) (any, error) {
now := e.store.runnerClock.Now().UTC()
- if op == "intend" || op == "admit" {
+ if op == "intend" || op == "admit" || op == "publication_ready" || op == "publication_authorize" {
if err := runnerTimelineAvailable(tx, a.ID); err != nil {
return nil, err
}
@@ -182,6 +182,16 @@ func (e *Execution) mutateAt(ctx context.Context, tx *gorm.DB, a runnerAssignmen
}
}
return deadline, storeError(tx.Model(&runnerAssignment{}).Where("id=?", a.ID).Select("LeaseDeadline").Updates(&runnerAssignment{LeaseDeadline: deadline}).Error)
+ case "publication_ready":
+ if a.Kind != "step" {
+ return nil, ErrInvalid
+ }
+ return e.Core.Publication(ctx, q.Scope, q.Handle)
+ case "publication_authorize":
+ if a.Kind != "step" {
+ return nil, ErrInvalid
+ }
+ return e.Core.AuthorizePublication(ctx, q.Scope, q.Handle, q.ActionID, q.RequestID)
case "intend":
if a.Kind != "step" || q.Intent == nil {
return nil, ErrInvalid
@@ -218,7 +228,7 @@ func (e *Execution) mutateAt(ctx context.Context, tx *gorm.DB, a runnerAssignmen
if err != nil {
return nil, err
}
- return nil, e.Core.Record(ctx, q.Scope, q.ActionID, receipt)
+ return nil, e.recordVerifiedReceipt(ctx, tx, a, q, receipt)
}
return nil, nil
case "contained":
diff --git a/internal/equipo/runner_provenance.go b/internal/equipo/runner_provenance.go
index a3892ade..87ce1b69 100644
--- a/internal/equipo/runner_provenance.go
+++ b/internal/equipo/runner_provenance.go
@@ -35,6 +35,7 @@ func (s *Store) runnerProvenance(observe team.ProvenanceResolver) team.Provenanc
if p.Provider != value.Selection.Provider || p.ModelFamily != value.Selection.Family {
return p, ErrForbidden
}
+ p.ConnectionID = value.Selection.ConnectionID
p.Isolation = value.Selection.Isolation
return p, nil
}
diff --git a/internal/equipo/team/actions.go b/internal/equipo/team/actions.go
index fb2a014d..fafc0892 100644
--- a/internal/equipo/team/actions.go
+++ b/internal/equipo/team/actions.go
@@ -184,6 +184,15 @@ func (s *Store) Intend(ctx context.Context, scope Scope, h Handle, in IntentSpec
return fail(CodeInvalid, "publication_invalid")
}
p.Isolation = observed.Isolation
+ description, err := publicationDescription(ctx, tx, hd.job, p.Isolation)
+ if err != nil {
+ return err
+ }
+ if (p.Description != "" && p.Description != description) || (p.DescriptionHash != "" && p.DescriptionHash != hashBytes([]byte(description))) {
+ return ErrEvidence
+ }
+ p.Description = description
+ p.DescriptionHash = hashBytes([]byte(description))
raw, err := json.Marshal(p)
if err != nil {
return err
@@ -246,12 +255,16 @@ func (s *Store) Intend(ctx context.Context, scope Scope, h Handle, in IntentSpec
}
// publication is the forge.publish_branch payload.
-type publication struct {
- CandidateHash string `json:"candidate_hash,omitempty"`
- Isolation IsolationSnapshot `json:"isolation,omitzero"`
- Repository string `json:"repository"`
- Ref string `json:"ref"`
- Head string `json:"head"`
+type publication = Publication
+
+type Publication struct {
+ Description string `json:"description,omitempty"`
+ DescriptionHash string `json:"description_hash,omitempty"`
+ CandidateHash string `json:"candidate_hash,omitempty"`
+ Isolation IsolationSnapshot `json:"isolation,omitzero"`
+ Repository string `json:"repository"`
+ Ref string `json:"ref"`
+ Head string `json:"head"`
}
// checkPublication refuses a publication whose repository, ref or head is
@@ -283,6 +296,13 @@ func checkPublication(ctx context.Context, tx *sql.Tx, j jobRow, payload []byte)
if err != nil {
return err
}
+ description, err := publicationDescription(ctx, tx, j, p.Isolation)
+ if err != nil {
+ return err
+ }
+ if p.Description != description || p.DescriptionHash != hashBytes([]byte(description)) {
+ return ErrEvidence
+ }
if !rep.Satisfied || !isolationContains(p.Isolation, rep.Isolation) {
return fail(CodeEvidence, "publication_evidence_invalid")
}
@@ -430,6 +450,13 @@ func (s *Store) Record(ctx context.Context, scope Scope, id ActionID, rc Receipt
switch a.State {
case ActionSucceeded, ActionFailed:
if a.Receipt != nil && a.Receipt.ID == rc.ID && a.Receipt.Outcome == rc.Outcome {
+ if a.Operation == OpForgePublish && j.Policy.Version == 2 {
+ saved, _ := json.Marshal(a.Receipt.Fields)
+ offered, _ := json.Marshal(rc.Fields)
+ if a.Receipt.Provider != rc.Provider || !bytes.Equal(saved, offered) {
+ return ErrReceiptConflict
+ }
+ }
return settle(ctx, tx, a.Reservation, rc, now)
}
return fail(CodeReceiptConflict, "action %d already holds receipt %q", id, a.Receipt.ID)
@@ -437,6 +464,11 @@ func (s *Store) Record(ctx context.Context, scope Scope, id ActionID, rc Receipt
default:
return fail(CodeState, "action %d is %s; no dispatch to receipt", id, a.State)
}
+ if a.Operation == OpForgePublish && j.Policy.Version == 2 {
+ if err := ValidatePublicationReceipt(a.Payload, rc); err != nil {
+ return err
+ }
+ }
if err := settle(ctx, tx, a.Reservation, rc, now); err != nil {
return err
}
diff --git a/internal/equipo/team/admission.go b/internal/equipo/team/admission.go
index cfa03195..4acec03a 100644
--- a/internal/equipo/team/admission.go
+++ b/internal/equipo/team/admission.go
@@ -25,6 +25,8 @@ UPDATE service SET schema_version=7 WHERE id=1;
`
type AdmissionTicket struct {
+ Scope Scope `json:"scope"`
+ Handle Handle `json:"handle"`
Dispatch Dispatch `json:"dispatch"`
ExpiresAt time.Time `json:"expires_at"`
Incarnation int64 `json:"incarnation"`
@@ -99,7 +101,7 @@ func (s *Store) AdmitOnce(ctx context.Context, scope Scope, h Handle, id ActionI
if max := s.clock.Now().Add(5 * time.Second); deadline.After(max) {
deadline = max
}
- ticket = AdmissionTicket{dispatch, deadline, s.incarnation}
+ ticket = AdmissionTicket{Dispatch: dispatch, Scope: scope, Handle: h, ExpiresAt: deadline, Incarnation: s.incarnation}
data, err := json.Marshal(dispatch)
if err != nil {
return err
@@ -160,6 +162,8 @@ func (s *Store) AdmitOnce(ctx context.Context, scope Scope, h Handle, id ActionI
}
}
}
+ ticket.Scope = scope
+ ticket.Handle = h
ticket.ExpiresAt = parseTS(expiry)
ticket.Incarnation = inc
return nil
diff --git a/internal/equipo/team/evidence.go b/internal/equipo/team/evidence.go
index 19d2df1c..e424caf4 100644
--- a/internal/equipo/team/evidence.go
+++ b/internal/equipo/team/evidence.go
@@ -115,6 +115,7 @@ func (s *Store) Register(ctx context.Context, scope Scope, h Handle, spec Artifa
return err
}
// Exposure comes from the instance observation, even for executor evidence.
+ executor.ConnectionID = spec.Provenance.ConnectionID
executor.Isolation = spec.Provenance.Isolation
spec.Provenance = executor
}
diff --git a/internal/equipo/team/fixture.go b/internal/equipo/team/fixture.go
index f1de9746..03e61c40 100644
--- a/internal/equipo/team/fixture.go
+++ b/internal/equipo/team/fixture.go
@@ -338,6 +338,12 @@ func (f *FakeForge) Execute(ctx context.Context, d Dispatch) (Receipt, error) {
}
r := Receipt{ID: "forge-" + short(d.Hash), Outcome: OutcomeSuccess, Provider: "fake-forge", Usage: &Usage{Calls: 1},
Fields: map[string]string{"repository": p.Repository, "ref": p.Ref, "head": p.Head, "review_url": "fake://" + p.Repository + "/review/" + short(p.Head)}}
+ if p.DescriptionHash != "" {
+ r.Fields["description_hash"] = p.DescriptionHash
+ r.Fields["candidate_hash"] = p.CandidateHash
+ r.Fields["qualified_ref"] = "refs/heads/" + p.Ref
+ r.Fields["agent"] = "fixture~operator@example.test"
+ }
f.published[d.Key] = r
if f.loseReply {
return Receipt{}, fmt.Errorf("connection reset after publish")
diff --git a/internal/equipo/team/git_evidence.go b/internal/equipo/team/git_evidence.go
index db2c6bfd..1076fde1 100644
--- a/internal/equipo/team/git_evidence.go
+++ b/internal/equipo/team/git_evidence.go
@@ -84,6 +84,8 @@ func gitCandidate(a *Artifact, j jobRow) (GitCandidate, error) {
}
return c, nil
}
+func (p IsolationSnapshot) Valid() bool { return p.valid() }
+
func (p IsolationSnapshot) valid() bool {
if p.Status != "confined" && p.Status != "unconfined" {
return false
diff --git a/internal/equipo/team/git_evidence_test.go b/internal/equipo/team/git_evidence_test.go
index 6eb5f38a..bef23eb5 100644
--- a/internal/equipo/team/git_evidence_test.go
+++ b/internal/equipo/team/git_evidence_test.go
@@ -21,7 +21,7 @@ func newGitEnv(t *testing.T) *gitEnv { return newGitEnvObject(t, 40) }
func newGitEnvObject(t *testing.T, objectLength int) *gitEnv {
e := newEnv(t)
g := &gitEnv{env: e}
- g.observed = Provenance{Producer: "builder", Provider: "provider-a", Context: "session-a", ModelFamily: "gpt", Isolation: IsolationSnapshot{Status: "unconfined", RunnerTainted: true, AcknowledgementIDs: []string{"ack-1"}, ObservedTuples: []IsolationTuple{{Provider: "provider-a", ProviderVersion: "1", PaseoVersion: "0.14.0", IsolationConfigHash: hashBytes([]byte("config"))}}}}
+ g.observed = Provenance{ConnectionID: "observed-connection", Producer: "builder", Provider: "provider-a", Context: "session-a", ModelFamily: "gpt", Isolation: IsolationSnapshot{Status: "unconfined", RunnerTainted: true, AcknowledgementIDs: []string{"ack-1"}, ObservedTuples: []IsolationTuple{{Provider: "provider-a", ProviderVersion: "1", PaseoVersion: "0.14.0", IsolationConfigHash: hashBytes([]byte("config"))}}}}
must(t, e.store.Close())
opts := e.options()
opts.Provenance = func(context.Context, *sql.Tx, Scope, Handle) (Provenance, error) { return g.observed, nil }
diff --git a/internal/equipo/team/model.go b/internal/equipo/team/model.go
index 80de3fc6..3b263ff1 100644
--- a/internal/equipo/team/model.go
+++ b/internal/equipo/team/model.go
@@ -706,12 +706,13 @@ func roleAllowed(c Capability, r Role) bool {
// provider and model behind it and the context (conversation or session)
// it came from. V2 also requires different observed model families.
type Provenance struct {
- ModelFamily string `json:"model_family,omitempty"`
- Isolation IsolationSnapshot `json:"isolation,omitzero"`
- Producer string `json:"producer"`
- Provider string `json:"provider"`
- Model string `json:"model,omitempty"`
- Context string `json:"context"`
+ ConnectionID string `json:"connection_id,omitempty"`
+ ModelFamily string `json:"model_family,omitempty"`
+ Isolation IsolationSnapshot `json:"isolation,omitzero"`
+ Producer string `json:"producer"`
+ Provider string `json:"provider"`
+ Model string `json:"model,omitempty"`
+ Context string `json:"context"`
}
func (p Provenance) validate() error {
diff --git a/internal/equipo/team/publication.go b/internal/equipo/team/publication.go
new file mode 100644
index 00000000..20b9bc62
--- /dev/null
+++ b/internal/equipo/team/publication.go
@@ -0,0 +1,176 @@
+package team
+
+import (
+ "context"
+ "database/sql"
+ "encoding/json"
+ "regexp"
+)
+
+var publicationAgent = regexp.MustCompile(`^[A-Za-z0-9_-]+~[^\s~@]+@[^\s~@]+$`)
+
+type PublicationEvidence struct {
+ Step StepID `json:"step"`
+ Attempt AttemptID `json:"attempt"`
+ Role Role `json:"role"`
+ Hash string `json:"hash"`
+ Label string `json:"label"`
+ Provenance Provenance `json:"provenance"`
+ ExecutorBinary string `json:"executor_binary,omitempty"`
+ ExecutorVersion string `json:"executor_version,omitempty"`
+}
+
+type PublicationDescription struct {
+ Version int `json:"version"`
+ Target TargetBinding `json:"target"`
+ Label string `json:"label"`
+ Isolation IsolationSnapshot `json:"isolation"`
+ Evidence []PublicationEvidence `json:"evidence"`
+}
+
+func publicationDescription(ctx context.Context, tx *sql.Tx, j jobRow, isolation IsolationSnapshot) (string, error) {
+ if !isolation.valid() {
+ return "", ErrEvidence
+ }
+ desc := PublicationDescription{Version: 1, Target: j.Target, Label: isolation.Status, Isolation: isolation}
+ if isolation.RunnerTainted {
+ desc.Label = "unconfined"
+ }
+ rows, err := tx.QueryContext(ctx, `SELECT `+artifactColumns+` FROM artifacts WHERE job_id=? ORDER BY id`, j.ID)
+ if err != nil {
+ return "", err
+ }
+ defer rows.Close()
+ for rows.Next() {
+ a, err := scanArtifact(rows)
+ if err != nil {
+ return "", err
+ }
+ if a.Provenance.ConnectionID == "" || a.Provenance.validate() != nil || !a.Provenance.Isolation.valid() {
+ return "", ErrEvidence
+ }
+ e := PublicationEvidence{Step: a.Step, Attempt: a.Attempt, Role: a.Role, Hash: a.Hash, Provenance: a.Provenance, Label: a.Provenance.Isolation.Status}
+ if isolation.RunnerTainted || a.Provenance.Isolation.RunnerTainted {
+ e.Label = "unconfined"
+ }
+ if a.Role == RoleBaseResult || a.Role == RoleCandidateResult || a.Role == RoleRepositoryChecks {
+ var executor struct {
+ Binary string `json:"executor_binary"`
+ Version string `json:"executor_version"`
+ }
+ if json.Unmarshal(a.Payload, &executor) != nil {
+ return "", ErrEvidence
+ }
+ e.ExecutorBinary = executor.Binary
+ e.ExecutorVersion = executor.Version
+ }
+ desc.Evidence = append(desc.Evidence, e)
+ }
+ if err = rows.Err(); err != nil {
+ return "", err
+ }
+ raw, err := json.Marshal(desc)
+ if err != nil {
+ return "", err
+ }
+ return string(raw), nil
+}
+
+func (s *Store) Publication(ctx context.Context, scope Scope, h Handle) (Publication, error) {
+ var p Publication
+ err := s.read(ctx, func(tx *sql.Tx) error {
+ hd, err := current(ctx, tx, scope, h, s.clock.Now())
+ if err != nil {
+ return err
+ }
+ if hd.job.Policy.Version != 2 || hd.step.Capability != CapPublish {
+ return ErrScope
+ }
+ rep, err := evaluateEvidence(ctx, tx, hd.job, true)
+ if err != nil {
+ return err
+ }
+ if !rep.Satisfied {
+ return ErrEvidence
+ }
+ a, err := latestArtifact(ctx, tx, scope.Job, RoleCandidate)
+ if err != nil {
+ return err
+ }
+ c, err := gitCandidate(a, hd.job)
+ if err != nil {
+ return err
+ }
+ observed, err := s.observedProvenance(ctx, tx, scope, h)
+ if err != nil {
+ return err
+ }
+ description, err := publicationDescription(ctx, tx, hd.job, observed.Isolation)
+ if err != nil {
+ return err
+ }
+ p = Publication{Repository: hd.job.Target.Repository, Ref: hd.job.Target.Ref, Head: c.Commit, CandidateHash: a.Hash, Isolation: observed.Isolation, Description: description, DescriptionHash: hashBytes([]byte(description))}
+ return checkPublication(ctx, tx, hd.job, mustPublicationJSON(p))
+ })
+ return p, err
+}
+func mustPublicationJSON(p Publication) []byte { raw, _ := json.Marshal(p); return raw }
+
+func ValidatePublicationReceipt(payload []byte, receipt Receipt) error {
+ if receipt.Outcome != OutcomeSuccess {
+ return nil
+ }
+ var p Publication
+ if strictJSON(payload, &p) != nil || p.Description == "" || p.DescriptionHash != hashBytes([]byte(p.Description)) {
+ return ErrEvidence
+ }
+ for key, want := range map[string]string{"repository": p.Repository, "ref": p.Ref, "qualified_ref": "refs/heads/" + p.Ref, "head": p.Head, "candidate_hash": p.CandidateHash, "description_hash": p.DescriptionHash} {
+ if want == "" || receipt.Fields[key] != want {
+ return ErrEvidence
+ }
+ }
+ if !publicationAgent.MatchString(receipt.Fields["agent"]) {
+ return ErrEvidence
+ }
+ return nil
+}
+
+type PublicationAuthorization struct {
+ Ticket AdmissionTicket `json:"ticket"`
+ Target TargetBinding `json:"target"`
+ Candidate GitCandidate `json:"candidate"`
+ Publication Publication `json:"publication"`
+}
+
+func (s *Store) AuthorizePublication(ctx context.Context, scope Scope, h Handle, id ActionID, requestID string) (PublicationAuthorization, error) {
+ var a PublicationAuthorization
+ err := s.Atomic(ctx, func(ctx context.Context, tx *sql.Tx) error {
+ p, err := s.Publication(ctx, scope, h)
+ if err != nil {
+ return err
+ }
+ ticket, err := s.AdmitOnce(ctx, scope, h, id, requestID)
+ if err != nil {
+ return err
+ }
+ var saved Publication
+ if ticket.Dispatch.Operation != OpForgePublish || strictJSON(ticket.Dispatch.Payload, &saved) != nil || string(mustPublicationJSON(saved)) != string(mustPublicationJSON(p)) {
+ return ErrEvidence
+ }
+ j, err := loadJob(ctx, tx, scope)
+ if err != nil {
+ return err
+ }
+ art, err := latestArtifact(ctx, tx, scope.Job, RoleCandidate)
+ if err != nil {
+ return err
+ }
+ candidate, err := gitCandidate(art, j)
+ if err != nil {
+ return err
+ }
+ a = PublicationAuthorization{Ticket: ticket, Target: j.Target, Candidate: candidate, Publication: p}
+ return nil
+ })
+ return a, err
+}
diff --git a/internal/equipo/team/publication_test.go b/internal/equipo/team/publication_test.go
new file mode 100644
index 00000000..ebf794fb
--- /dev/null
+++ b/internal/equipo/team/publication_test.go
@@ -0,0 +1,155 @@
+package team
+
+import (
+ "encoding/json"
+ "strings"
+ "testing"
+)
+
+func TestPublishDescriptionProvenance(t *testing.T) {
+ g := newGitEnv(t)
+ g.build()
+ g.review()
+ g.verify(true)
+ h := g.claimStep("publish")
+ p, err := g.store.Publication(g.ctx, g.scope, h)
+ must(t, err)
+ if p.DescriptionHash != hashBytes([]byte(p.Description)) || !strings.Contains(p.Description, "unconfined") || !strings.Contains(p.Description, "repository_checks") || !strings.Contains(p.Description, "provider_version") {
+ t.Fatal("description missing persisted evidence", p.Description)
+ }
+ id, err := g.store.Intend(g.ctx, g.scope, h, IntentSpec{Key: "publish", Operation: OpForgePublish, Payload: mustJSON(p), Reserve: Usage{Calls: 1}})
+ must(t, err)
+ ticket, err := g.store.AdmitOnce(g.ctx, g.scope, h, id, "publish-admit")
+ must(t, err)
+ retry, err := g.store.AdmitOnce(g.ctx, g.scope, h, id, "publish-admit")
+ must(t, err)
+ if string(mustJSON(ticket)) != string(mustJSON(retry)) || ticket.Scope != g.scope || ticket.Handle != h {
+ t.Fatal("admission retry changed ticket")
+ }
+ var saved Publication
+ must(t, json.Unmarshal(ticket.Dispatch.Payload, &saved))
+ if saved.Description != p.Description {
+ t.Fatal("description changed at admission")
+ }
+}
+
+func TestPublishReceiptRequiresDescription(t *testing.T) {
+ g := newGitEnv(t)
+ g.build()
+ g.review()
+ g.verify(true)
+ h := g.claimStep("publish")
+ id, err := g.store.Intend(g.ctx, g.scope, h, IntentSpec{Key: "publish", Operation: OpForgePublish, Payload: mustJSON(g.publication()), Reserve: Usage{Calls: 1}})
+ must(t, err)
+ d, err := g.store.Admit(g.ctx, g.scope, id)
+ must(t, err)
+ receipt, err := g.forge.Execute(g.ctx, d)
+ must(t, err)
+ for _, field := range []string{"description_hash", "agent", "head", "candidate_hash", "qualified_ref"} {
+ wrong := receipt
+ wrong.Fields = map[string]string{}
+ for k, v := range receipt.Fields {
+ wrong.Fields[k] = v
+ }
+ delete(wrong.Fields, field)
+ if g.store.Record(g.ctx, g.scope, id, wrong) == nil {
+ t.Fatal("incomplete publication receipt accepted", field)
+ }
+ }
+ must(t, g.store.Record(g.ctx, g.scope, id, receipt))
+ receipt.Fields["description_hash"] = strings.Repeat("f", 64)
+ if err := g.store.Record(g.ctx, g.scope, id, receipt); err == nil {
+ t.Fatal("changed duplicate description receipt accepted")
+ }
+}
+
+func TestPublishAuthorization(t *testing.T) {
+ g := newGitEnv(t)
+ g.build()
+ g.review()
+ g.verify(true)
+ h := g.claimStep("publish")
+ p, err := g.store.Publication(g.ctx, g.scope, h)
+ must(t, err)
+ id, err := g.store.Intend(g.ctx, g.scope, h, IntentSpec{Key: "publish", Operation: OpForgePublish, Payload: mustJSON(p), Reserve: Usage{Calls: 1}})
+ must(t, err)
+ a, err := g.store.AuthorizePublication(g.ctx, g.scope, h, id, "authorize")
+ must(t, err)
+ if a.Candidate != g.candidate || a.Publication.Description != p.Description || a.Ticket.Handle != h {
+ t.Fatal("authorization lost immutable binding")
+ }
+ h.Runner = "wrong"
+ if _, err = g.store.AuthorizePublication(g.ctx, g.scope, h, id, "authorize"); err == nil {
+ t.Fatal("wrong runner authorized")
+ }
+}
+
+func TestPublishExactEvidence(t *testing.T) {
+ g := newGitEnv(t)
+ g.observed.Isolation.Status = "confined"
+ g.observed.ConnectionID = "confined-on-tainted-runner"
+ g.build()
+ g.review()
+ h := g.claimStep("verify")
+ _, err := g.register(h, RoleCandidateResult, mustJSON(CheckResult{ReproductionHash: hashBytes(FixtureReproduction), SubjectHash: g.artifact.Hash, CheckDefinitionHash: CheckDefinitionHash, Outcome: CheckPass, TestsRun: 3}))
+ must(t, err)
+ checks := g.checks()
+ checks.ExecutorBinary = "equipo-checks"
+ checks.ExecutorVersion = "1"
+ checks.Isolation = g.observed.Isolation
+ _, err = g.register(h, RoleRepositoryChecks, mustJSON(checks))
+ must(t, err)
+ g.finish(h)
+ p, err := g.store.Publication(g.ctx, g.scope, g.claimStep("publish"))
+ must(t, err)
+ var description PublicationDescription
+ must(t, json.Unmarshal([]byte(p.Description), &description))
+ if description.Label != "unconfined" || description.Isolation.Status != "confined" || !description.Isolation.RunnerTainted {
+ t.Fatal("runner exposure replaced capability", description)
+ }
+ found := false
+ for _, e := range description.Evidence {
+ if e.Label != "unconfined" || e.Provenance.ConnectionID != "confined-on-tainted-runner" || e.Provenance.Isolation.Status != "confined" {
+ t.Fatal("confined connection lost exposure", e)
+ }
+ if e.Role == RoleRepositoryChecks {
+ found = true
+ if e.ExecutorBinary != "equipo-checks" || e.ExecutorVersion != "1" {
+ t.Fatal("executor identity missing", e)
+ }
+ }
+ }
+ if !found {
+ t.Fatal("executor evidence missing")
+ }
+}
+
+func TestPublishMissingConnectionProvenance(t *testing.T) {
+ g := newGitEnv(t)
+ g.build()
+ g.review()
+ g.verify(true)
+ h := g.claimStep("publish")
+ _, err := g.store.Publication(g.ctx, g.scope, h)
+ must(t, err)
+ _, err = g.store.db.Exec(`UPDATE artifacts SET provenance=json_remove(provenance,'$.connection_id') WHERE id=?`, g.artifact.ID)
+ must(t, err)
+ if _, err = g.store.Publication(g.ctx, g.scope, h); err == nil {
+ t.Fatal("stripped connection provenance published")
+ }
+}
+
+func TestPublishDescriptionChangedAtAdmit(t *testing.T) {
+ g := newGitEnv(t)
+ g.build()
+ g.review()
+ g.verify(true)
+ h := g.claimStep("publish")
+ id, err := g.store.Intend(g.ctx, g.scope, h, IntentSpec{Key: "publish", Operation: OpForgePublish, Payload: mustJSON(g.publication()), Reserve: Usage{Calls: 1}})
+ must(t, err)
+ _, err = g.store.db.Exec(`UPDATE artifacts SET provenance=json_set(provenance,'$.connection_id','changed') WHERE id=?`, g.artifact.ID)
+ must(t, err)
+ if _, err = g.store.AdmitOnce(g.ctx, g.scope, h, id, "publish-admit"); err == nil {
+ t.Fatal("changed description provenance admitted")
+ }
+}
diff --git a/internal/equipotest/publish_test.go b/internal/equipotest/publish_test.go
new file mode 100644
index 00000000..d0d9dc90
--- /dev/null
+++ b/internal/equipotest/publish_test.go
@@ -0,0 +1,94 @@
+package equipotest
+
+import (
+ "amadan.net/oficina/equipo/internal/equipo"
+ "context"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/equipo/team"
+ "amadan.net/oficina/equipo/internal/runnerproto"
+)
+
+func TestPublishTicketBinding(t *testing.T) {
+ now := time.Now().UTC()
+ q := runnerproto.RunnerRequest{Version: 1, RequestID: "publish", ActionID: 42, Scope: team.Scope{Account: "team", Job: 7}, Handle: team.Handle{Attempt: 3, Fence: 2, Runner: "runner"}}
+ ticket := team.AdmissionTicket{Dispatch: team.Dispatch{Action: 42}, Scope: q.Scope, Handle: q.Handle, Incarnation: 5, ExpiresAt: now.Add(5 * time.Second)}
+ for _, name := range []string{"scope", "job", "attempt", "fence", "runner", "valid"} {
+ t.Run(name, func(t *testing.T) {
+ dir := t.TempDir()
+ executionMust(t, runnerproto.JournalAdmission(dir, q))
+ changed := ticket
+ switch name {
+ case "scope":
+ changed.Scope.Account = "other"
+ case "job":
+ changed.Scope.Job++
+ case "attempt":
+ changed.Handle.Attempt++
+ case "fence":
+ changed.Handle.Fence++
+ case "runner":
+ changed.Handle.Runner = "other"
+ }
+ err := runnerproto.ConsumeTicket(dir, q.RequestID, changed, now, 5)
+ if name == "valid" {
+ executionMust(t, err)
+ } else if err == nil {
+ t.Fatal("foreign publication ticket consumed")
+ }
+ })
+ }
+}
+
+func TestPublishInstanceAdapter(t *testing.T) {
+ f := runnerFixtureNew(t, true)
+ adapter := f.s.RunnerAdapter(team.OpForgePublish)
+ if class, err := adapter.Classify(team.OpForgePublish); err != nil || class != team.ReplayReconcilable {
+ t.Fatal("forge replay class", class, err)
+ }
+ if _, err := adapter.Execute(connectionContext, team.Dispatch{}); err == nil {
+ t.Fatal("instance performed runner effect")
+ }
+ provider := f.s.RunnerAdapter(team.OpProviderCall)
+ if class, err := provider.Classify(team.OpProviderCall); err != nil || class != team.ReplayUnsafe {
+ t.Fatal("provider replay class", class, err)
+ }
+ q := f.request()
+ q.Intent = &team.IntentSpec{Key: "call", Operation: team.OpProviderCall, Payload: []byte(`{"turn":1}`), Reserve: team.Usage{InputTokens: 10, OutputTokens: 10}}
+ result, err := f.x.Mutate(connectionContext, f.principal, "intend", q)
+ executionMust(t, err)
+ q.ActionID = result.(team.ActionID)
+ q.Intent = nil
+ q.RequestID = "admit"
+ result, err = f.x.Mutate(connectionContext, f.principal, "admit", q)
+ executionMust(t, err)
+ ticket := result.(team.AdmissionTicket)
+ if ticket.Scope != q.Scope || ticket.Handle != q.Handle {
+ t.Fatal("issued ticket has no binding")
+ }
+ r, err := provider.Reconcile(connectionContext, ticket.Dispatch)
+ executionMust(t, err)
+ if r.Receipt != nil || r.Definitive {
+ t.Fatal("missing observation proved absence")
+ }
+ q.RequestID = "receipt"
+ q.Receipt = &team.Receipt{ID: "unvalidated", Outcome: team.OutcomeSuccess}
+ _, err = f.x.Mutate(connectionContext, f.principal, "receipts", q)
+ executionMust(t, err)
+ r, err = provider.Reconcile(connectionContext, ticket.Dispatch)
+ executionMust(t, err)
+ if r.Receipt != nil {
+ t.Fatal("raw runner report became receipt")
+ }
+ f.x.SetRunnerValidators(equipo.RunnerValidators{Receipt: func(context.Context, equipo.Assignment, equipo.RunnerRequest) (team.Receipt, error) {
+ return team.Receipt{ID: "verified", Outcome: team.OutcomeSuccess, Usage: &team.Usage{Calls: 1}}, nil
+ }})
+ _, err = f.x.Mutate(connectionContext, f.principal, "receipts", q)
+ executionMust(t, err)
+ r, err = provider.Reconcile(connectionContext, ticket.Dispatch)
+ executionMust(t, err)
+ if r.Receipt == nil || r.Receipt.ID != "verified" {
+ t.Fatal("verified durable observation lost")
+ }
+}
diff --git a/internal/equipotest/runner_api_test.go b/internal/equipotest/runner_api_test.go
index f0778efc..65d5f66a 100644
--- a/internal/equipotest/runner_api_test.go
+++ b/internal/equipotest/runner_api_test.go
@@ -91,7 +91,7 @@ func TestRunnerCannotClaimOthersWork(t *testing.T) {
}
func TestRunnerFenceEveryMutation(t *testing.T) {
f := runnerFixtureNew(t, true)
- for _, op := range []string{"renew", "prepare", "events", "artifacts", "intend", "admit", "receipts", "lost", "complete", "release", "stop", "contained"} {
+ for _, op := range []string{"publication_ready", "publication_authorize", "renew", "prepare", "events", "artifacts", "intend", "admit", "receipts", "lost", "complete", "release", "stop", "contained"} {
t.Run(op, func(t *testing.T) {
q := f.request()
q.Handle.Fence++
@@ -223,7 +223,7 @@ func TestRunnerFenceHTTPBindings(t *testing.T) {
f := runnerFixtureNew(t, true)
token := runnerBearerFor(t, f)
f.x.SetRunnerValidators(equipo.RunnerValidators{Events: func(context.Context, equipo.Assignment, equipo.RunnerRequest) error { return nil }})
- for _, op := range []string{"renew", "prepare", "events", "artifacts", "intend", "admit", "receipts", "lost", "complete", "release", "stop", "contained"} {
+ for _, op := range []string{"publication_ready", "publication_authorize", "renew", "prepare", "events", "artifacts", "intend", "admit", "receipts", "lost", "complete", "release", "stop", "contained"} {
for _, field := range []string{"scope", "job", "attempt", "runner", "fence", "assignment", "version"} {
t.Run(op+"/"+field, func(t *testing.T) {
q := f.request()
@@ -632,7 +632,7 @@ func TestRunnerWireAndJournal(t *testing.T) {
}
}
now := time.Now().UTC()
- ticket := team.AdmissionTicket{Dispatch: team.Dispatch{Action: 1}, Incarnation: 3, ExpiresAt: now.Add(5 * time.Second)}
+ ticket := team.AdmissionTicket{Scope: q.Scope, Handle: q.Handle, Dispatch: team.Dispatch{Action: 1}, Incarnation: 3, ExpiresAt: now.Add(5 * time.Second)}
dir := t.TempDir()
q.Intent = nil
q.ActionID = 1
@@ -714,7 +714,7 @@ func TestRunnerEndpointForeignPrincipal(t *testing.T) {
approveDevice(t, f.s, code, "member@example.com")
credential := claimDevice(t, f.s, code, key)
f.x.SetRunnerValidators(equipo.RunnerValidators{Containment: func(context.Context, equipo.Assignment, equipo.RunnerRequest) error { return nil }})
- for _, op := range []string{"renew", "prepare", "events", "artifacts", "intend", "admit", "receipts", "lost", "complete", "release", "stop", "contained"} {
+ for _, op := range []string{"publication_ready", "publication_authorize", "renew", "prepare", "events", "artifacts", "intend", "admit", "receipts", "lost", "complete", "release", "stop", "contained"} {
t.Run(op, func(t *testing.T) {
q := f.request()
q.Event = fixtureEventRequest(t, f, q)
diff --git a/internal/runner/forge/git.go b/internal/runner/forge/git.go
new file mode 100644
index 00000000..572dac9d
--- /dev/null
+++ b/internal/runner/forge/git.go
@@ -0,0 +1,136 @@
+package forge
+
+import (
+ "context"
+ "io"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+
+ "amadan.net/oficina/equipo/internal/equipo/team"
+ "amadan.net/oficina/equipo/internal/runner/workspace"
+)
+
+func (p *Publisher) git(ctx context.Context, dir string, cred *Credential, args ...string) (string, error) {
+ protocol := "https"
+ if p.localRemote != nil {
+ protocol = "file"
+ if p.localReceivePack != "" && len(args) > 0 && args[0] == "push" {
+ args = append([]string{"push", "--receive-pack=" + p.localReceivePack}, args[1:]...)
+ }
+ }
+ args = append([]string{"-c", "protocol." + protocol + ".allow=always", "-c", "http.followRedirects=false", "-c", "maintenance.auto=false", "-c", "gc.auto=0"}, args...)
+ cmd := exec.CommandContext(ctx, p.cfg.GitPath, args...)
+ cmd.Dir = dir
+ env := workspace.GitEnvironment()
+ env["HOME"] = "/nonexistent"
+ env["GIT_CEILING_DIRECTORIES"] = filepath.Dir(dir)
+ if cred != nil && p.localRemote == nil {
+ env["GIT_CONFIG_COUNT"] = "8"
+ env["GIT_CONFIG_KEY_7"] = "http.extraHeader"
+ env["GIT_CONFIG_VALUE_7"] = "Authorization: Bearer " + cred.Bearer
+ }
+ for k, v := range env {
+ cmd.Env = append(cmd.Env, k+"="+v)
+ }
+ cmd.Stderr = io.Discard
+ b, e := cmd.Output()
+ if e != nil {
+ return "", team.ErrUncertain
+ }
+ return strings.TrimSpace(string(b)), nil
+}
+func (p *Publisher) stage(ctx context.Context, dir string, c team.GitCandidate) (string, error) {
+ exported := filepath.Join(dir, "export")
+ if e := p.cfg.Export(ctx, c, exported); e != nil {
+ return "", e
+ }
+ repo := filepath.Join(dir, "git")
+ format := "sha1"
+ if len(c.Commit) == 64 {
+ format = "sha256"
+ }
+ if _, e := p.git(ctx, dir, nil, "init", "--bare", "--template=", "--object-format="+format, repo); e != nil {
+ return "", e
+ }
+ source := filepath.Join(exported, ".git", "objects")
+ actual, e := filepath.EvalSymlinks(source)
+ if e != nil || actual != source {
+ return "", team.ErrEvidence
+ }
+ e = filepath.WalkDir(source, func(path string, d os.DirEntry, err error) error {
+ if err != nil {
+ return err
+ }
+ rel, e := filepath.Rel(source, path)
+ if e != nil {
+ return e
+ }
+ if rel == "." {
+ return nil
+ }
+ if d.Type()&os.ModeSymlink != 0 {
+ return team.ErrEvidence
+ }
+ if d.IsDir() {
+ if rel != "info" && rel != "pack" && !(len(rel) == 2 && strings.Trim(rel, "0123456789abcdef") == "") {
+ return team.ErrEvidence
+ }
+ return os.MkdirAll(filepath.Join(repo, "objects", rel), 0700)
+ }
+ parts := strings.Split(rel, string(filepath.Separator))
+ if !d.Type().IsRegular() || len(parts) != 2 {
+ return team.ErrEvidence
+ }
+ valid := len(parts[0]) == 2 && object.MatchString(parts[0]+parts[1])
+ if parts[0] == "pack" {
+ name := parts[1]
+ ext := filepath.Ext(name)
+ hash := strings.TrimSuffix(strings.TrimPrefix(name, "pack-"), ext)
+ valid = strings.HasPrefix(name, "pack-") && object.MatchString(hash) && (ext == ".pack" || ext == ".idx" || ext == ".rev")
+ }
+ if !valid {
+ return team.ErrEvidence
+ }
+ in, e := os.Open(path)
+ if e != nil {
+ return e
+ }
+ defer in.Close()
+ out, e := os.OpenFile(filepath.Join(repo, "objects", rel), os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0600)
+ if e != nil {
+ return e
+ }
+ _, e = io.Copy(out, in)
+ ce := out.Close()
+ if e != nil {
+ return e
+ }
+ return ce
+ })
+ if e != nil {
+ return "", team.ErrEvidence
+ }
+ if e = p.verifyObjects(ctx, repo, c); e != nil {
+ return "", e
+ }
+ return repo, nil
+}
+func (p *Publisher) verifyObjects(ctx context.Context, repo string, c team.GitCandidate) error {
+ id, e := p.git(ctx, repo, nil, "rev-parse", "--verify", c.Commit+"^{commit}")
+ if e != nil || id != c.Commit {
+ return team.ErrEvidence
+ }
+ tree, e := p.git(ctx, repo, nil, "rev-parse", "--verify", c.Commit+"^{tree}")
+ if e != nil || tree != c.Tree {
+ return team.ErrEvidence
+ }
+ if _, e = p.git(ctx, repo, nil, "merge-base", "--is-ancestor", c.BaseCommit, c.Commit); e != nil {
+ return team.ErrEvidence
+ }
+ if _, e = p.git(ctx, repo, nil, "fsck", "--strict", "--no-reflogs", c.Commit); e != nil {
+ return team.ErrEvidence
+ }
+ return nil
+}
diff --git a/internal/runner/forge/publisher.go b/internal/runner/forge/publisher.go
new file mode 100644
index 00000000..f8ef548f
--- /dev/null
+++ b/internal/runner/forge/publisher.go
@@ -0,0 +1,362 @@
+package forge
+
+import (
+ "bytes"
+ "context"
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "io"
+ "net/url"
+ "os"
+ "path/filepath"
+ "reflect"
+ "regexp"
+ "strconv"
+ "strings"
+ "syscall"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/equipo/team"
+ "amadan.net/oficina/equipo/internal/runnerproto"
+)
+
+type Authorization = runnerproto.PublicationAuthorization
+
+type Credential struct{ Remote, Agent, Bearer string }
+type Description struct{ Repository, Ref, Agent, Body, Digest string }
+
+// DescriptionTransport must confirm the stored body and its attributed agent.
+// The installed CLI help does not supply a readback contract. No production
+// implementation is enabled until the owning product supplies that contract.
+type DescriptionTransport interface {
+ BeforePush() bool
+ Set(context.Context, Credential, Description) error
+ Read(context.Context, Credential, string, string) (Description, error)
+}
+type Config struct {
+ Root, GitPath, Runner string
+ Incarnation int64
+ Clock func() time.Time
+ Authorize func(context.Context, team.Dispatch) (Authorization, error)
+ Revalidate func(context.Context, Authorization) error
+ Export func(context.Context, team.GitCandidate, string) error
+ Credential func(context.Context, string) (Credential, error)
+ Description DescriptionTransport
+}
+type Publisher struct {
+ cfg Config
+ localRemote func(string) string
+ localReceivePack string
+ beforePush func()
+}
+
+var _ team.Adapter = (*Publisher)(nil)
+var object = regexp.MustCompile(`^(?:[0-9a-f]{40}|[0-9a-f]{64})$`)
+var repoName = regexp.MustCompile(`^amadan\.net/[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$`)
+var agentName = regexp.MustCompile(`^[A-Za-z0-9_-]+~[^\s~@]+@[^\s~@]+$`)
+
+func New(cfg Config) (*Publisher, error) { return newPublisher(cfg, nil) }
+func newPublisher(cfg Config, local func(string) string) (*Publisher, error) {
+ if cfg.Authorize == nil || cfg.Revalidate == nil || cfg.Export == nil || cfg.Credential == nil || cfg.Description == nil || cfg.Clock == nil || cfg.Runner == "" || cfg.Incarnation <= 0 || !filepath.IsAbs(cfg.GitPath) || !filepath.IsAbs(cfg.Root) || filepath.Clean(cfg.Root) != cfg.Root {
+ return nil, team.ErrInvalid
+ }
+ if err := os.MkdirAll(cfg.Root, 0700); err != nil {
+ return nil, team.ErrUncertain
+ }
+ actual, err := filepath.EvalSymlinks(cfg.Root)
+ if err != nil || actual != cfg.Root {
+ return nil, team.ErrInvalid
+ }
+ info, err := os.Stat(cfg.Root)
+ if err != nil || info.Mode().Perm()&0077 != 0 {
+ return nil, team.ErrInvalid
+ }
+ if _, err := os.Lstat(filepath.Join(cfg.Root, ".git")); !os.IsNotExist(err) {
+ return nil, team.ErrInvalid
+ }
+ return &Publisher{cfg: cfg, localRemote: local}, nil
+}
+func (*Publisher) Classify(op team.Operation) (team.ReplayClass, error) {
+ if op != team.OpForgePublish {
+ return "", team.ErrUnknownKind
+ }
+ return team.ReplayReconcilable, nil
+}
+func Digest(b []byte) string { s := sha256.Sum256(b); return hex.EncodeToString(s[:]) }
+func Canonical(raw []byte) ([]byte, string, error) {
+ if len(raw) > team.MaxPayloadBytes {
+ return nil, "", team.ErrSize
+ }
+ var v map[string]any
+ d := json.NewDecoder(bytes.NewReader(raw))
+ d.UseNumber()
+ if d.Decode(&v) != nil || v == nil {
+ return nil, "", team.ErrInvalid
+ }
+ var extra any
+ if d.Decode(&extra) != io.EOF {
+ return nil, "", team.ErrInvalid
+ }
+ b, e := json.Marshal(v)
+ return b, Digest(b), e
+}
+func CanonicalHash(v any) string { raw, _ := json.Marshal(v); _, h, _ := Canonical(raw); return h }
+func validRef(ref string) bool {
+ if ref == "" || ref == "HEAD" || ref == "@" || strings.HasPrefix(ref, "-") || strings.HasPrefix(ref, "refs/") || strings.ContainsAny(ref, " ~^:?*[\\\x00\r\n\t") || strings.Contains(ref, "..") || strings.Contains(ref, "@{") || strings.HasSuffix(ref, ".") {
+ return false
+ }
+ for _, s := range strings.Split(ref, "/") {
+ if s == "" || strings.HasPrefix(s, ".") || strings.HasSuffix(s, ".lock") {
+ return false
+ }
+ for _, c := range s {
+ if c < 32 || c == 127 {
+ return false
+ }
+ }
+ }
+ return true
+}
+func validateDispatch(d team.Dispatch) error {
+ b, h, err := Canonical(d.Payload)
+ if err != nil || !bytes.Equal(b, d.Payload) || h != d.Hash || d.Action <= 0 || d.Key == "" || d.Operation != team.OpForgePublish {
+ return team.ErrInvalid
+ }
+ return nil
+}
+func (p *Publisher) validate(a Authorization, d team.Dispatch) error {
+ t := a.Ticket
+ c := a.Candidate
+ v := a.Publication
+ target := a.Target
+ now := p.cfg.Clock()
+ if validateDispatch(d) != nil || !reflect.DeepEqual(t.Dispatch, d) || t.Scope.Account == "" || t.Scope.Job <= 0 || t.Handle.Runner != p.cfg.Runner || t.Handle.Attempt <= 0 || t.Handle.Fence <= 0 || t.Incarnation != p.cfg.Incarnation || !now.Before(t.ExpiresAt) || t.ExpiresAt.Sub(now) > 5*time.Second {
+ return team.ErrFence
+ }
+ if target.Kind != team.TargetRepository || !validRepository(target.Repository) || !validRef(target.Ref) || !validRef(target.DefaultRef) || target.Ref == target.DefaultRef || v.Repository != target.Repository || v.Ref != target.Ref || c.Repository != target.Repository || c.BaseCommit != target.BaseRevision || v.Head != c.Commit || !object.MatchString(c.Commit) || !object.MatchString(c.Tree) || !object.MatchString(c.BaseCommit) || len(c.Commit) != len(c.Tree) || len(c.Commit) != len(c.BaseCommit) || v.CandidateHash != CanonicalHash(c) {
+ return team.ErrEvidence
+ }
+ var saved team.Publication
+ dec := json.NewDecoder(bytes.NewReader(d.Payload))
+ dec.DisallowUnknownFields()
+ if dec.Decode(&saved) != nil || !reflect.DeepEqual(saved, v) || v.Description == "" || v.DescriptionHash != Digest([]byte(v.Description)) {
+ return team.ErrEvidence
+ }
+ iso := v.Isolation
+ if !iso.Valid() || ((iso.RunnerTainted || iso.Status == "unconfined") && !strings.Contains(v.Description, "unconfined")) {
+ return team.ErrEvidence
+ }
+ return nil
+}
+func (p *Publisher) credential(ctx context.Context, repository string) (Credential, error) {
+ c, err := p.cfg.Credential(ctx, repository)
+ if err != nil {
+ return Credential{}, team.ErrUncertain
+ }
+ u, e := url.Parse(c.Remote)
+ if e != nil || !agentName.MatchString(c.Agent) || c.Bearer == "" || strings.ContainsAny(c.Bearer+c.Remote, "\r\n\x00") || u.Scheme != "https" || u.Host == "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" || u.RawPath != "" || c.Remote != "https://"+repository || u.String() != c.Remote {
+ return Credential{}, team.ErrInvalid
+ }
+ return c, nil
+}
+
+type record struct {
+ Authorization Authorization
+ Description Description
+ Remote string
+}
+
+func (p *Publisher) path(d team.Dispatch) string {
+ return filepath.Join(p.cfg.Root, "publish-"+strconv.FormatInt(int64(d.Action), 10)+".json")
+}
+func (p *Publisher) lock() (func(), error) {
+ f, e := os.OpenFile(filepath.Join(p.cfg.Root, "publish.lock"), os.O_CREATE|os.O_RDWR|syscall.O_NOFOLLOW, 0600)
+ if e != nil {
+ return nil, team.ErrUncertain
+ }
+ if syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB) != nil {
+ f.Close()
+ return nil, team.ErrUncertain
+ }
+ return func() { _ = syscall.Flock(int(f.Fd()), syscall.LOCK_UN); _ = f.Close() }, nil
+}
+func (p *Publisher) load(d team.Dispatch) (record, error) {
+ var r record
+ b, e := os.ReadFile(p.path(d))
+ if e != nil {
+ return r, e
+ }
+ if json.Unmarshal(b, &r) != nil || !reflect.DeepEqual(r.Authorization.Ticket.Dispatch, d) {
+ return r, team.ErrConflict
+ }
+ return r, nil
+}
+func (p *Publisher) Execute(ctx context.Context, d team.Dispatch) (team.Receipt, error) {
+ if validateDispatch(d) != nil {
+ return team.Receipt{}, team.ErrInvalid
+ }
+ unlock, e := p.lock()
+ if e != nil {
+ return team.Receipt{}, e
+ }
+ defer unlock()
+ if r, err := p.load(d); err == nil {
+ return p.reconcile(ctx, r)
+ } else if !os.IsNotExist(err) {
+ return team.Receipt{}, err
+ }
+ a, e := p.cfg.Authorize(ctx, d)
+ if e != nil {
+ return team.Receipt{}, e
+ }
+ if e = p.validate(a, d); e != nil {
+ return team.Receipt{}, e
+ }
+ if e = p.cfg.Revalidate(ctx, a); e != nil {
+ return team.Receipt{}, e
+ }
+ cred, e := p.credential(ctx, a.Publication.Repository)
+ if e != nil {
+ return team.Receipt{}, e
+ }
+ dir, e := os.MkdirTemp(p.cfg.Root, "objects-")
+ if e != nil {
+ return team.Receipt{}, team.ErrUncertain
+ }
+ defer os.RemoveAll(dir)
+ repo, e := p.stage(ctx, dir, a.Candidate)
+ if e != nil {
+ return team.Receipt{}, e
+ }
+ desc := Description{Repository: a.Publication.Repository, Ref: a.Publication.Ref, Agent: cred.Agent, Body: a.Publication.Description, Digest: a.Publication.DescriptionHash}
+ r := record{Authorization: a, Description: desc, Remote: cred.Remote}
+ if e = runnerproto.JournalCredentials(p.path(d), r); e != nil {
+ return team.Receipt{}, team.ErrUncertain
+ }
+ head, err := p.remoteHead(ctx, cred, a.Publication.Ref)
+ if err != nil {
+ return team.Receipt{}, err
+ }
+ if head != "" {
+ if head != a.Candidate.Commit {
+ return team.Receipt{}, team.ErrConflict
+ }
+ return p.reconcile(ctx, r)
+ }
+ if p.cfg.Description.BeforePush() {
+ if e = p.confirmDescription(ctx, cred, desc); e != nil {
+ return team.Receipt{}, e
+ }
+ }
+ if e = p.verifyObjects(ctx, repo, a.Candidate); e != nil {
+ return team.Receipt{}, e
+ }
+ if e = p.validate(a, d); e != nil {
+ return team.Receipt{}, e
+ }
+ if e = p.cfg.Revalidate(ctx, a); e != nil {
+ return team.Receipt{}, e
+ }
+ if p.beforePush != nil {
+ p.beforePush()
+ }
+ _, e = p.git(ctx, repo, &cred, "push", "--porcelain", "--no-verify", "--recurse-submodules=no", "--force-with-lease=refs/heads/"+a.Publication.Ref+":", "--", p.remote(cred.Remote), a.Candidate.Commit+":refs/heads/"+a.Publication.Ref)
+ if e != nil {
+ return team.Receipt{}, team.ErrUncertain
+ }
+ return p.reconcile(ctx, r)
+}
+func (p *Publisher) remote(remote string) string {
+ if p.localRemote != nil {
+ return p.localRemote(remote)
+ }
+ return remote
+}
+func (p *Publisher) confirmDescription(ctx context.Context, cred Credential, desc Description) error {
+ got, e := p.cfg.Description.Read(ctx, cred, desc.Repository, desc.Ref)
+ if e == nil && got == desc {
+ return nil
+ }
+ if e = p.cfg.Description.Set(ctx, cred, desc); e != nil {
+ return team.ErrUncertain
+ }
+ got, e = p.cfg.Description.Read(ctx, cred, desc.Repository, desc.Ref)
+ if e != nil || got != desc {
+ return team.ErrUncertain
+ }
+ return nil
+}
+func (p *Publisher) reconcile(ctx context.Context, r record) (team.Receipt, error) {
+ v := r.Authorization.Publication
+ cred, e := p.credential(ctx, v.Repository)
+ if e != nil {
+ return team.Receipt{}, e
+ }
+ if cred.Agent != r.Description.Agent || cred.Remote != r.Remote || r.Description.Body != v.Description || r.Description.Digest != v.DescriptionHash {
+ return team.Receipt{}, team.ErrConflict
+ }
+ ref := "refs/heads/" + v.Ref
+ head, e := p.remoteHead(ctx, cred, v.Ref)
+ if e != nil || head == "" {
+ return team.Receipt{}, team.ErrUncertain
+ }
+ if head != v.Head {
+ return team.Receipt{}, team.ErrConflict
+ }
+ if e = p.confirmDescription(ctx, cred, r.Description); e != nil {
+ return team.Receipt{}, e
+ }
+ label := v.Isolation.Status
+ if v.Isolation.RunnerTainted {
+ label = "unconfined"
+ }
+ return team.Receipt{ID: "forge-" + Digest([]byte(r.Authorization.Ticket.Dispatch.Hash+"/"+v.DescriptionHash+"/"+cred.Agent)), Outcome: team.OutcomeSuccess, Provider: "amadan", Usage: &team.Usage{Calls: 1}, Fields: map[string]string{"label": label, "repository": v.Repository, "ref": v.Ref, "qualified_ref": ref, "head": v.Head, "candidate_hash": v.CandidateHash, "description_hash": v.DescriptionHash, "agent": cred.Agent, "isolation": v.Isolation.Status, "runner_tainted": strconv.FormatBool(v.Isolation.RunnerTainted)}}, nil
+}
+func (p *Publisher) Reconcile(ctx context.Context, d team.Dispatch) (team.ReconcileResult, error) {
+ if validateDispatch(d) != nil {
+ return team.ReconcileResult{}, team.ErrInvalid
+ }
+ unlock, e := p.lock()
+ if e != nil {
+ return team.ReconcileResult{}, e
+ }
+ defer unlock()
+ r, e := p.load(d)
+ if e != nil {
+ return team.ReconcileResult{}, team.ErrUncertain
+ }
+ receipt, e := p.reconcile(ctx, r)
+ if e != nil {
+ return team.ReconcileResult{}, e
+ }
+ return team.ReconcileResult{Receipt: &receipt, Definitive: true}, nil
+}
+
+func (p *Publisher) remoteHead(ctx context.Context, cred Credential, branch string) (string, error) {
+ ref := "refs/heads/" + branch
+ out, err := p.git(ctx, p.cfg.Root, &cred, "ls-remote", "--refs", "--", p.remote(cred.Remote), ref)
+ if err != nil {
+ return "", team.ErrUncertain
+ }
+ fields := strings.Fields(out)
+ if len(fields) == 0 {
+ return "", nil
+ }
+ if len(fields) != 2 || !object.MatchString(fields[0]) || fields[1] != ref {
+ return "", team.ErrUncertain
+ }
+ return fields[0], nil
+}
+
+func validRepository(repository string) bool {
+ if !repoName.MatchString(repository) {
+ return false
+ }
+ for _, part := range strings.Split(repository, "/")[1:] {
+ if part == "." || part == ".." {
+ return false
+ }
+ }
+ return true
+}
diff --git a/internal/runner/forge/publisher_test.go b/internal/runner/forge/publisher_test.go
new file mode 100644
index 00000000..864068f6
--- /dev/null
+++ b/internal/runner/forge/publisher_test.go
@@ -0,0 +1,539 @@
+package forge
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/equipo/team"
+)
+
+var ctx = context.Background()
+
+func must(t *testing.T, err error) {
+ t.Helper()
+ if err != nil {
+ t.Fatal(err)
+ }
+}
+func gitTest(t *testing.T, dir string, args ...string) string {
+ t.Helper()
+ c := exec.Command("git", args...)
+ c.Dir = dir
+ c.Env = append(os.Environ(), "GIT_CONFIG_NOSYSTEM=1", "GIT_CONFIG_GLOBAL=/dev/null", "GIT_AUTHOR_NAME=fixture", "GIT_AUTHOR_EMAIL=fixture@example.test", "GIT_COMMITTER_NAME=fixture", "GIT_COMMITTER_EMAIL=fixture@example.test")
+ b, e := c.CombinedOutput()
+ if e != nil {
+ t.Fatalf("git %v: %v %s", args, e, b)
+ }
+ return strings.TrimSpace(string(b))
+}
+
+type fakeDescription struct {
+ value Description
+ fail, requiresRef bool
+ lostSet, wrongRead bool
+ calls int
+ before func()
+}
+
+func (f *fakeDescription) BeforePush() bool { return !f.requiresRef }
+func (f *fakeDescription) Set(_ context.Context, credential Credential, d Description) error {
+ if credential.Agent != d.Agent || credential.Bearer != "agent-canary" {
+ return team.ErrScope
+ }
+ f.calls++
+ if f.before != nil {
+ f.before()
+ }
+ if f.fail {
+ return team.ErrUncertain
+ }
+ f.value = d
+ if f.lostSet {
+ return team.ErrUncertain
+ }
+ return nil
+}
+func (f *fakeDescription) Read(context.Context, Credential, string, string) (Description, error) {
+ if f.fail {
+ return Description{}, team.ErrUncertain
+ }
+ if f.wrongRead {
+ got := f.value
+ got.Agent = "person@example.test"
+ return got, nil
+ }
+ return f.value, nil
+}
+
+type fixture struct {
+ p *Publisher
+ auth Authorization
+ desc *fakeDescription
+ remote, source, root string
+ cancelled bool
+ pushes int
+}
+
+func newFixture(t *testing.T) *fixture {
+ t.Helper()
+ root := t.TempDir()
+ source := filepath.Join(root, "source")
+ remote := filepath.Join(root, "remote.git")
+ must(t, os.Mkdir(source, 0700))
+ gitTest(t, source, "init", "--template=")
+ must(t, os.WriteFile(filepath.Join(source, "file"), []byte("base"), 0600))
+ gitTest(t, source, "add", "file")
+ gitTest(t, source, "commit", "-m", "base")
+ base := gitTest(t, source, "rev-parse", "HEAD")
+ must(t, os.WriteFile(filepath.Join(source, "file"), []byte("fixed"), 0600))
+ gitTest(t, source, "commit", "-am", "candidate")
+ head := gitTest(t, source, "rev-parse", "HEAD")
+ tree := gitTest(t, source, "rev-parse", "HEAD^{tree}")
+ gitTest(t, root, "init", "--bare", "--template=", remote)
+ iso := team.IsolationSnapshot{Status: "confined", RunnerTainted: true, AcknowledgementIDs: []string{"ack"}, ObservedTuples: []team.IsolationTuple{{Provider: "codex", ProviderVersion: "0.165.0", PaseoVersion: "0.14.0", IsolationConfigHash: strings.Repeat("a", 64)}}}
+ c := team.GitCandidate{Repository: "amadan.net/example/repo", BaseCommit: base, Commit: head, Tree: tree}
+ pub := team.Publication{Repository: c.Repository, Ref: "heads/main", Head: head, CandidateHash: CanonicalHash(c), Isolation: iso, Description: `{"status":"unconfined","executor":"checks","connection":"confined"}`}
+ pub.DescriptionHash = Digest([]byte(pub.Description))
+ raw, _ := json.Marshal(pub)
+ raw, hash, _ := Canonical(raw)
+ d := team.Dispatch{Action: 1, Key: "publish", Operation: team.OpForgePublish, Payload: raw, Hash: hash}
+ f := &fixture{source: source, remote: remote, root: root, desc: &fakeDescription{}}
+ now := time.Now().UTC()
+ f.auth = Authorization{Ticket: team.AdmissionTicket{Dispatch: d, Scope: team.Scope{Account: "team", Job: 1}, Handle: team.Handle{Attempt: 1, Fence: 1, Runner: "runner"}, Incarnation: 1, ExpiresAt: now.Add(5 * time.Second)}, Target: team.TargetBinding{Kind: team.TargetRepository, Repository: c.Repository, BaseRevision: base, Ref: pub.Ref, DefaultRef: "main"}, Candidate: c, Publication: pub}
+ cfg := Config{Root: filepath.Join(root, "private"), GitPath: "/usr/bin/git", Runner: "runner", Incarnation: 1, Clock: func() time.Time { return now }, Authorize: func(context.Context, team.Dispatch) (Authorization, error) {
+ if f.cancelled {
+ return Authorization{}, team.ErrFence
+ }
+ return f.auth, nil
+ }, Revalidate: func(context.Context, Authorization) error {
+ if f.cancelled {
+ return team.ErrFence
+ }
+ return nil
+ }, Export: func(_ context.Context, c team.GitCandidate, dir string) error {
+ gitTest(t, root, "clone", "--no-local", "--template=", source, dir)
+ return nil
+ }, Credential: func(context.Context, string) (Credential, error) {
+ return Credential{Remote: "https://amadan.net/example/repo", Agent: "equipo~operator@example.test", Bearer: "agent-canary"}, nil
+ }, Description: f.desc}
+ var err error
+ f.p, err = newPublisher(cfg, func(_ string) string { return remote })
+ must(t, err)
+ f.p.beforePush = func() { f.pushes++ }
+ return f
+}
+func TestPublishQualifiedRef(t *testing.T) {
+ f := newFixture(t)
+ r, err := f.p.Execute(ctx, f.auth.Ticket.Dispatch)
+ must(t, err)
+ if r.Outcome != team.OutcomeSuccess || r.Fields["agent"] != "equipo~operator@example.test" {
+ t.Fatal("missing disclosed receipt", r)
+ }
+ got := gitTest(t, f.root, "--git-dir="+f.remote, "rev-parse", "refs/heads/heads/main")
+ if got != f.auth.Candidate.Commit {
+ t.Fatal("wrong qualified commit")
+ }
+ if f.desc.calls != 1 {
+ t.Fatal("description missing")
+ }
+ for _, name := range []string{"default", "repo", "ref", "tags", "candidate", "ticket", "runner", "evidence"} {
+ t.Run(name, func(t *testing.T) {
+ f := newFixture(t)
+ d := f.auth.Ticket.Dispatch
+ switch name {
+ case "default":
+ f.auth.Target.DefaultRef = f.auth.Target.Ref
+ case "repo":
+ f.auth.Target.Repository = "forged/repo"
+ case "ref":
+ f.auth.Target.Ref = "other"
+ case "tuple_identity":
+ f.auth.Publication.Isolation.ObservedTuples[0].ProviderVersion = ""
+ case "tags":
+ f.auth.Target.Ref = "refs/tags/x"
+ case "candidate":
+ f.auth.Candidate.Commit = strings.Repeat("b", 40)
+ case "ticket":
+ f.auth.Ticket.Incarnation++
+ case "runner":
+ f.auth.Ticket.Handle.Runner = "other"
+ case "evidence":
+ f.auth.Publication.Description = ""
+ }
+ if _, err := f.p.Execute(ctx, d); err == nil {
+ t.Fatal("invalid publication accepted")
+ }
+ if f.pushes != 0 {
+ t.Fatal("invalid publication reached Git push")
+ }
+ })
+ }
+}
+func TestPublishExactEvidence(t *testing.T) {
+ f := newFixture(t)
+ f.desc.before = func() {
+ if f.pushes != 0 {
+ t.Fatal("description must precede push")
+ }
+ }
+ _, err := f.p.Execute(ctx, f.auth.Ticket.Dispatch)
+ must(t, err)
+ if !strings.Contains(f.desc.value.Body, "unconfined") || f.desc.value.Digest != f.auth.Publication.DescriptionHash {
+ t.Fatal("lost immutable label")
+ }
+ t.Run("remote_first", func(t *testing.T) {
+ f := newFixture(t)
+ f.desc.requiresRef = true
+ f.desc.fail = true
+ if _, e := f.p.Execute(ctx, f.auth.Ticket.Dispatch); e == nil {
+ t.Fatal("pushed ref without description delivered success")
+ }
+ if f.pushes != 1 {
+ t.Fatal("no push window exercised")
+ }
+ r, e := f.p.Reconcile(ctx, f.auth.Ticket.Dispatch)
+ if e == nil && r.Receipt != nil {
+ t.Fatal("unconfirmed description reconciled success")
+ }
+ f.desc.fail = false
+ r, e = f.p.Reconcile(ctx, f.auth.Ticket.Dispatch)
+ must(t, e)
+ if r.Receipt == nil || f.pushes != 1 {
+ t.Fatal("description recovery duplicated push")
+ }
+ })
+}
+func TestPublishLostReceipt(t *testing.T) {
+ f := newFixture(t)
+ _, err := f.p.Execute(ctx, f.auth.Ticket.Dispatch)
+ must(t, err)
+ for i := 0; i < 2; i++ {
+ _, err = f.p.Execute(ctx, f.auth.Ticket.Dispatch)
+ must(t, err)
+ }
+ if f.pushes != 1 {
+ t.Fatal("duplicate dispatch")
+ }
+ r, err := f.p.Reconcile(ctx, f.auth.Ticket.Dispatch)
+ must(t, err)
+ if r.Receipt == nil {
+ t.Fatal("receipt lost")
+ }
+ gitTest(t, f.root, "--git-dir="+f.remote, "update-ref", "refs/heads/heads/main", f.auth.Candidate.BaseCommit)
+ if _, err = f.p.Reconcile(ctx, f.auth.Ticket.Dispatch); err == nil {
+ t.Fatal("remote mismatch accepted")
+ }
+ must(t, os.Rename(f.remote, f.remote+"-hidden"))
+ r, err = f.p.Reconcile(ctx, f.auth.Ticket.Dispatch)
+ if err == nil || r.Definitive {
+ t.Fatal("query failure became absence")
+ }
+}
+func TestPublishCredentialIsolation(t *testing.T) {
+ f := newFixture(t)
+ t.Setenv("PERSON_SECRET", "person-canary")
+ t.Setenv("GIT_CONFIG_COUNT", "1")
+ t.Setenv("GIT_CONFIG_KEY_0", "url.file:///invalid.insteadOf")
+ t.Setenv("GIT_CONFIG_VALUE_0", "https://amadan.net/")
+ marker := filepath.Join(f.root, "hook-ran")
+ must(t, os.MkdirAll(filepath.Join(f.source, ".git", "hooks"), 0700))
+ must(t, os.WriteFile(filepath.Join(f.source, ".git", "hooks", "pre-push"), []byte("#!/bin/sh\ntouch "+marker+"\n"), 0700))
+ _, err := f.p.Execute(ctx, f.auth.Ticket.Dispatch)
+ must(t, err)
+ if _, e := os.Stat(marker); !os.IsNotExist(e) {
+ t.Fatal("source hook executed")
+ }
+ must(t, filepath.WalkDir(f.p.cfg.Root, func(path string, d os.DirEntry, e error) error {
+ if e != nil {
+ return e
+ }
+ if !d.IsDir() {
+ b, e := os.ReadFile(path)
+ if e != nil {
+ return e
+ }
+ if strings.Contains(string(b), "agent-canary") || strings.Contains(string(b), "person-canary") {
+ t.Fatal("credential persisted", path)
+ }
+ }
+ return nil
+ }))
+}
+func TestPublishCancelRace(t *testing.T) {
+ f := newFixture(t)
+ f.cancelled = true
+ if _, e := f.p.Execute(ctx, f.auth.Ticket.Dispatch); e == nil || f.pushes != 0 {
+ t.Fatal("cancelled dispatch pushed")
+ }
+ f.cancelled = false
+ f.desc.requiresRef = true
+ f.desc.before = func() { f.cancelled = true }
+ _, e := f.p.Execute(ctx, f.auth.Ticket.Dispatch)
+ must(t, e)
+ r, e := f.p.Reconcile(ctx, f.auth.Ticket.Dispatch)
+ must(t, e)
+ if r.Receipt == nil || f.pushes != 1 {
+ t.Fatal("in-flight cancellation lost publication")
+ }
+ if gitTest(t, f.root, "--git-dir="+f.remote, "rev-parse", "refs/heads/heads/main") != f.auth.Candidate.Commit {
+ t.Fatal("cancel deleted branch")
+ }
+}
+
+func TestPublishLostPushReply(t *testing.T) {
+ f := newFixture(t)
+ seen := filepath.Join(f.root, "seen")
+ receiver := filepath.Join(f.root, "receive")
+ must(t, os.WriteFile(receiver, []byte("#!/bin/sh\nexec /usr/bin/env -i PATH=/usr/bin:/bin /usr/bin/git receive-pack \"$@\"\n"), 0700))
+ f.p.localReceivePack = receiver
+ hook := filepath.Join(f.remote, "hooks", "pre-receive")
+ must(t, os.MkdirAll(filepath.Dir(hook), 0700))
+ must(t, os.WriteFile(hook, []byte("#!/bin/sh\nread old new ref\necho \"$new $ref\" > "+seen+"\ntest \"$old\" = 0000000000000000000000000000000000000000 && test \"$new\" = "+f.auth.Candidate.Commit+" && test \"$ref\" = refs/heads/heads/main\n"), 0700))
+ wrapper := filepath.Join(f.root, "git-lost")
+ must(t, os.WriteFile(wrapper, []byte("#!/bin/sh\n/usr/bin/git \"$@\"\ncode=$?\nfor arg do\n if [ \"$arg\" = push ] && [ \"$code\" = 0 ]; then exit 79; fi\ndone\nexit \"$code\"\n"), 0700))
+ f.p.cfg.GitPath = wrapper
+ if _, e := f.p.Execute(ctx, f.auth.Ticket.Dispatch); e == nil {
+ t.Fatal("lost push reply became success")
+ }
+ observed, err := os.ReadFile(seen)
+ must(t, err)
+ if strings.TrimSpace(string(observed)) != f.auth.Candidate.Commit+" refs/heads/heads/main" {
+ t.Fatal("receive hook missed exact commit", string(observed))
+ }
+ restarted, e := newPublisher(f.p.cfg, f.p.localRemote)
+ must(t, e)
+ restarted.beforePush = func() { t.Fatal("restart pushed twice") }
+ r, e := restarted.Reconcile(ctx, f.auth.Ticket.Dispatch)
+ must(t, e)
+ if r.Receipt == nil || r.Receipt.Fields["head"] != f.auth.Candidate.Commit {
+ t.Fatal("lost exact commit receipt")
+ }
+ _, e = restarted.Execute(ctx, f.auth.Ticket.Dispatch)
+ must(t, e)
+}
+
+func TestPublishOccupiedRef(t *testing.T) {
+ f := newFixture(t)
+ gitTest(t, f.root, "--git-dir="+f.remote, "fetch", f.source, f.auth.Candidate.BaseCommit)
+ gitTest(t, f.root, "--git-dir="+f.remote, "update-ref", "refs/heads/heads/main", f.auth.Candidate.BaseCommit)
+ if _, e := f.p.Execute(ctx, f.auth.Ticket.Dispatch); e == nil {
+ t.Fatal("existing branch replaced")
+ }
+ if got := gitTest(t, f.root, "--git-dir="+f.remote, "rev-parse", "refs/heads/heads/main"); got != f.auth.Candidate.BaseCommit {
+ t.Fatal("absence lease did not protect existing branch")
+ }
+ if _, e := f.p.Reconcile(ctx, f.auth.Ticket.Dispatch); e == nil {
+ t.Fatal("occupied ref reconciled")
+ }
+}
+
+func TestPublishDeadlineAndPrePushAuthority(t *testing.T) {
+ for _, name := range []string{"expired", "cancel_during_description", "expired_during_export", "changed_local_objects"} {
+ t.Run(name, func(t *testing.T) {
+ f := newFixture(t)
+ switch name {
+ case "expired":
+ f.p.cfg.Clock = func() time.Time { return f.auth.Ticket.ExpiresAt }
+ case "cancel_during_description":
+ f.desc.before = func() { f.cancelled = true }
+ case "expired_during_export":
+ original := f.p.cfg.Export
+ f.p.cfg.Export = func(ctx context.Context, c team.GitCandidate, dir string) error {
+ e := original(ctx, c, dir)
+ f.p.cfg.Clock = func() time.Time { return f.auth.Ticket.ExpiresAt }
+ return e
+ }
+ case "changed_local_objects":
+ f.auth.Candidate.Tree = strings.Repeat("c", 40)
+ f.auth.Publication.CandidateHash = CanonicalHash(f.auth.Candidate)
+ raw, _ := json.Marshal(f.auth.Publication)
+ f.auth.Ticket.Dispatch.Payload, f.auth.Ticket.Dispatch.Hash, _ = Canonical(raw)
+ }
+ if _, e := f.p.Execute(ctx, f.auth.Ticket.Dispatch); e == nil || f.pushes != 0 {
+ t.Fatal("stale authority or objects reached push")
+ }
+ })
+ }
+}
+
+func TestPublishOccupiedRefKeepsDescription(t *testing.T) {
+ f := newFixture(t)
+ gitTest(t, f.root, "--git-dir="+f.remote, "fetch", f.source, f.auth.Candidate.BaseCommit)
+ gitTest(t, f.root, "--git-dir="+f.remote, "update-ref", "refs/heads/heads/main", f.auth.Candidate.BaseCommit)
+ if _, e := f.p.Execute(ctx, f.auth.Ticket.Dispatch); e == nil {
+ t.Fatal("existing branch accepted")
+ }
+ if f.desc.calls != 0 {
+ t.Fatal("other commit description overwritten")
+ }
+}
+
+func TestPublishAbsentLeaseRace(t *testing.T) {
+ f := newFixture(t)
+ f.p.beforePush = func() {
+ gitTest(t, f.root, "--git-dir="+f.remote, "fetch", f.source, f.auth.Candidate.BaseCommit)
+ gitTest(t, f.root, "--git-dir="+f.remote, "update-ref", "refs/heads/heads/main", f.auth.Candidate.BaseCommit)
+ }
+ if _, e := f.p.Execute(ctx, f.auth.Ticket.Dispatch); e == nil {
+ t.Fatal("racing branch replaced")
+ }
+ if got := gitTest(t, f.root, "--git-dir="+f.remote, "rev-parse", "refs/heads/heads/main"); got != f.auth.Candidate.BaseCommit {
+ t.Fatal("absence lease failed during race")
+ }
+}
+
+func TestPublishDescriptionIdentity(t *testing.T) {
+ t.Run("readback", func(t *testing.T) {
+ f := newFixture(t)
+ f.desc.wrongRead = true
+ if _, e := f.p.Execute(ctx, f.auth.Ticket.Dispatch); e == nil || f.pushes != 0 {
+ t.Fatal("wrong description attribution confirmed")
+ }
+ })
+ t.Run("lost_description_reply", func(t *testing.T) {
+ f := newFixture(t)
+ f.desc.requiresRef = true
+ f.desc.lostSet = true
+ if _, e := f.p.Execute(ctx, f.auth.Ticket.Dispatch); e == nil {
+ t.Fatal("lost description reply delivered success")
+ }
+ r, e := f.p.Reconcile(ctx, f.auth.Ticket.Dispatch)
+ must(t, e)
+ if r.Receipt == nil || f.pushes != 1 || f.desc.calls != 1 {
+ t.Fatal("lost label or duplicated effect")
+ }
+ })
+}
+
+func TestPublishLostReceiptNoRedispatch(t *testing.T) {
+ f := newFixture(t)
+ _, err := f.p.Execute(ctx, f.auth.Ticket.Dispatch)
+ must(t, err)
+ gitTest(t, f.root, "--git-dir="+f.remote, "update-ref", "-d", "refs/heads/heads/main")
+ if _, err = f.p.Execute(ctx, f.auth.Ticket.Dispatch); err == nil || f.pushes != 1 {
+ t.Fatal("missing visibility caused redispatch")
+ }
+}
+
+func TestPublishEvidenceAndCredentialGuards(t *testing.T) {
+ for _, name := range []string{"description", "digest", "taint", "acknowledgement", "tuple", "tuple_identity", "tags", "person", "http", "foreign_remote", "header"} {
+ t.Run(name, func(t *testing.T) {
+ f := newFixture(t)
+ switch name {
+ case "description":
+ f.auth.Publication.Description = ""
+ f.auth.Publication.DescriptionHash = Digest(nil)
+ case "digest":
+ f.auth.Publication.DescriptionHash = strings.Repeat("a", 64)
+ case "taint":
+ f.auth.Publication.Description = `{"label":"confined"}`
+ f.auth.Publication.DescriptionHash = Digest([]byte(f.auth.Publication.Description))
+ case "acknowledgement":
+ f.auth.Publication.Isolation.AcknowledgementIDs = nil
+ case "tuple":
+ f.auth.Publication.Isolation.ObservedTuples = nil
+ case "tuple_identity":
+ f.auth.Publication.Isolation.ObservedTuples[0].ProviderVersion = ""
+ case "tags":
+ f.auth.Target.Ref = "refs/tags/tag"
+ f.auth.Publication.Ref = f.auth.Target.Ref
+ default:
+ original := f.p.cfg.Credential
+ f.p.cfg.Credential = func(ctx context.Context, r string) (Credential, error) {
+ c, e := original(ctx, r)
+ switch name {
+ case "person":
+ c.Agent = "person@example.test"
+ case "http":
+ c.Remote = "http://amadan.net/example/repo.git"
+ case "foreign_remote":
+ c.Remote = "https://amadan.net/foreign/repo.git"
+ case "header":
+ c.Bearer = "token\r\nHeader: value"
+ }
+ return c, e
+ }
+ }
+ raw, _ := json.Marshal(f.auth.Publication)
+ f.auth.Ticket.Dispatch.Payload, f.auth.Ticket.Dispatch.Hash, _ = Canonical(raw)
+ if _, e := f.p.Execute(ctx, f.auth.Ticket.Dispatch); e == nil || f.pushes != 0 {
+ t.Fatal("invalid evidence or credential reached push")
+ }
+ })
+ }
+}
+
+func TestPublishCanonicalRepository(t *testing.T) {
+ f := newFixture(t)
+ f.auth.Target.Repository = "amadan.net/example/repo"
+ f.auth.Candidate.Repository = f.auth.Target.Repository
+ f.auth.Publication.Repository = f.auth.Target.Repository
+ f.auth.Publication.CandidateHash = CanonicalHash(f.auth.Candidate)
+ raw, _ := json.Marshal(f.auth.Publication)
+ f.auth.Ticket.Dispatch.Payload, f.auth.Ticket.Dispatch.Hash, _ = Canonical(raw)
+ f.p.cfg.Credential = func(context.Context, string) (Credential, error) {
+ return Credential{Remote: "https://amadan.net/example/repo", Agent: "equipo~operator@example.test", Bearer: "agent-canary"}, nil
+ }
+ if _, err := f.p.Execute(ctx, f.auth.Ticket.Dispatch); err != nil {
+ t.Fatal("saved canonical project repository rejected", err)
+ }
+}
+
+func TestPublishCredentialIsolationHTTPS(t *testing.T) {
+ f := newFixture(t)
+ t.Setenv("PERSON_SECRET", "person-canary")
+ spy := filepath.Join(f.root, "git-spy")
+ log := filepath.Join(f.root, "git-observations")
+ script := fmt.Sprintf(`#!/usr/bin/python3
+import os,sys,json
+args=sys.argv[1:]
+with open(%q,'a') as out:
+ out.write(json.dumps({'args':args,'env':dict(os.environ)})+'\n')
+if 'https://amadan.net/example/repo' in args:
+ args[args.index('https://amadan.net/example/repo')]=%q
+ args=['-c','protocol.file.allow=always']+args
+os.execve('/usr/bin/git',['/usr/bin/git']+args,dict(os.environ))
+`, log, f.remote)
+ must(t, os.WriteFile(spy, []byte(script), 0700))
+ f.p.localRemote = nil
+ f.p.cfg.GitPath = spy
+ _, err := f.p.Execute(ctx, f.auth.Ticket.Dispatch)
+ must(t, err)
+ raw, err := os.ReadFile(log)
+ must(t, err)
+ pushes := 0
+ remoteCalls := 0
+ for _, line := range strings.Split(strings.TrimSpace(string(raw)), "\n") {
+ var row struct {
+ Args []string
+ Env map[string]string
+ }
+ must(t, json.Unmarshal([]byte(line), &row))
+ args := strings.Join(row.Args, " ")
+ if strings.Contains(args, "agent-canary") || row.Env["PERSON_SECRET"] != "" {
+ t.Fatal("credential escaped allowed environment")
+ }
+ remote := strings.Contains(args, "https://amadan.net/example/repo")
+ if remote {
+ remoteCalls++
+ if row.Env["GIT_CONFIG_VALUE_7"] != "Authorization: Bearer agent-canary" {
+ t.Fatal("runner credential missing")
+ }
+ } else if strings.Contains(fmt.Sprint(row.Env), "agent-canary") {
+ t.Fatal("credential exposed to local Git")
+ }
+ if strings.Contains(args, " push ") {
+ pushes++
+ }
+ }
+ if pushes != 1 || remoteCalls < 3 {
+ t.Fatal("HTTPS command path not exercised", pushes, remoteCalls)
+ }
+}
diff --git a/internal/runnerproto/journal.go b/internal/runnerproto/journal.go
index 3525b2c9..0bc47828 100644
--- a/internal/runnerproto/journal.go
+++ b/internal/runnerproto/journal.go
@@ -24,7 +24,7 @@ func ConsumeTicket(dir, requestID string, ticket team.AdmissionTicket, now time.
return err
}
var request RunnerRequest
- if json.Unmarshal(rawRequest, &request) != nil || request.RequestID != requestID || request.ActionID != ticket.Dispatch.Action {
+ if json.Unmarshal(rawRequest, &request) != nil || request.RequestID != requestID || request.ActionID != ticket.Dispatch.Action || request.Scope != ticket.Scope || request.Handle != ticket.Handle {
return ErrInvalid
}
if err := os.MkdirAll(dir, 0700); err != nil {
diff --git a/internal/runnerproto/types.go b/internal/runnerproto/types.go
index 51165efb..9a29a3a6 100644
--- a/internal/runnerproto/types.go
+++ b/internal/runnerproto/types.go
@@ -221,3 +221,6 @@ type BlobReadRequest struct {
Scope team.Scope `json:"scope"`
Digest string `json:"digest"`
}
+
+type DispatchTicket = team.AdmissionTicket
+type PublicationAuthorization = team.PublicationAuthorization