fix: report no-effect publication failures definitively
12 files changed,
+661
−60
internal/equipo/team/actions.go+24 −3internal/equipo/team/budget.go+15 −0internal/equipo/team/git_evidence_test.go+4 −0internal/equipo/team/model.go+2 −0internal/equipo/team/publication.go+10 −1internal/equipo/team/publication_forge_test.go+55 −0internal/equipo/team/publication_no_effect_test.go+78 −0internal/equipo/team/publication_test.go+16 −0internal/runner/forge/credential_test.go+103 −0internal/runner/forge/no_effect_test.go+274 −0internal/runner/forge/publisher.go+59 −38internal/runner/forge/publisher_test.go+21 −18
CI failed — run details
diff --git a/internal/equipo/team/actions.go b/internal/equipo/team/actions.go| index fafc0892..a4d12b56 100644 |
| --- a/internal/equipo/team/actions.go |
| +++ b/internal/equipo/team/actions.go |
| @@ -9,6 +9,7 @@ import ( |
| "encoding/json" |
| "errors" |
| "sort" |
| + "strconv" |
| "time" |
| ) |
| @@ -434,6 +435,9 @@ func (s *Store) Admit(ctx context.Context, scope Scope, id ActionID) (Dispatch, |
| // delivery of the same receipt is a no-op; a different receipt for a |
| // finished action is ErrReceiptConflict. |
| func (s *Store) Record(ctx context.Context, scope Scope, id ActionID, rc Receipt) error { |
| + return s.record(ctx, scope, id, rc, false) |
| +} |
| +func (s *Store) record(ctx context.Context, scope Scope, id ActionID, rc Receipt, notDispatched bool) error { |
| if err := rc.validate(); err != nil { |
| return err |
| } |
| @@ -469,7 +473,11 @@ func (s *Store) Record(ctx context.Context, scope Scope, id ActionID, rc Receipt |
| return err |
| } |
| } |
| - if err := settle(ctx, tx, a.Reservation, rc, now); err != nil { |
| + settlement := settle |
| + if notDispatched { |
| + settlement = releaseNotDispatched |
| + } |
| + if err := settlement(ctx, tx, a.Reservation, rc, now); err != nil { |
| return err |
| } |
| state := ActionSucceeded |
| @@ -559,13 +567,17 @@ func (s *Store) Dispatch(ctx context.Context, scope Scope, id ActionID) (Receipt |
| return Receipt{}, err |
| } |
| rc, execErr := ad.Execute(ctx, d) |
| + notDispatched := errors.Is(execErr, ErrNotDispatched) |
| + if notDispatched { |
| + rc, execErr = notDispatchedReceipt(d), nil |
| + } |
| if execErr != nil { |
| if err := s.Lost(context.WithoutCancel(ctx), scope, id, execErr.Error()); err != nil { |
| return Receipt{}, err |
| } |
| return Receipt{}, fail(CodeUncertain, "action %d: %v", id, execErr) |
| } |
| - if err := s.Record(context.WithoutCancel(ctx), scope, id, rc); err != nil { |
| + if err := s.record(context.WithoutCancel(ctx), scope, id, rc, notDispatched); err != nil { |
| return Receipt{}, err |
| } |
| return rc, nil |
| @@ -603,8 +615,13 @@ func (s *Store) Reconcile(ctx context.Context, scope Scope, id ActionID) (Action |
| } |
| d := Dispatch{Action: a.ID, Key: a.Key, Operation: a.Operation, Payload: a.Payload, Hash: a.PayloadHash} |
| res, rerr := ad.Reconcile(ctx, d) |
| + notDispatched := errors.Is(rerr, ErrNotDispatched) |
| + if notDispatched { |
| + rc := notDispatchedReceipt(d) |
| + res, rerr = ReconcileResult{Receipt: &rc, Definitive: true}, nil |
| + } |
| if rerr == nil && res.Receipt != nil { |
| - if err := s.Record(ctx, scope, id, *res.Receipt); err != nil { |
| + if err := s.record(ctx, scope, id, *res.Receipt, notDispatched); err != nil { |
| return a, err |
| } |
| return s.GetAction(ctx, scope, id) |
| @@ -672,3 +689,7 @@ func unresolvedTurn(ctx context.Context, tx *sql.Tx, job JobID, except ActionID) |
| } |
| return nil |
| } |
| + |
| +func notDispatchedReceipt(d Dispatch) Receipt { |
| + return Receipt{ID: "not-dispatched-" + strconv.FormatInt(int64(d.Action), 10) + "-" + d.Hash, Outcome: OutcomeFailure, Usage: &Usage{}} |
| +} |
diff --git a/internal/equipo/team/budget.go b/internal/equipo/team/budget.go| index abd4196a..9aa13e3c 100644 |
| --- a/internal/equipo/team/budget.go |
| +++ b/internal/equipo/team/budget.go |
| @@ -202,6 +202,9 @@ func settle(ctx context.Context, tx *sql.Tx, id ReservationID, rc Receipt, now t |
| case ReservationSettledAudited: |
| return fail(CodeReceiptConflict, "reservation %d settled by audit (%s)", id, r.SettledBy) |
| case ReservationReleased: |
| + if r.ReceiptID == rc.ID && rc.Outcome == OutcomeFailure && rc.Usage != nil && *rc.Usage == (Usage{}) { |
| + return nil |
| + } |
| return fail(CodeState, "reservation %d released", id) |
| } |
| return fail(CodeUnknownKind, "reservation state %q", r.State) |
| @@ -433,3 +436,15 @@ func boundedTurn(ctx context.Context, tx *sql.Tx, j jobRow, now time.Time) (Usag |
| } |
| return want, nil |
| } |
| + |
| +func releaseNotDispatched(ctx context.Context, tx *sql.Tx, id ReservationID, rc Receipt, now time.Time) error { |
| + r, err := loadReservation(ctx, tx, id) |
| + if err != nil { |
| + return err |
| + } |
| + if r.State != ReservationOpen { |
| + return settle(ctx, tx, id, rc, now) |
| + } |
| + _, err = tx.ExecContext(ctx, `UPDATE reservations SET state='released', receipt_id=?, settled_by=?, settled_at=? WHERE id=? AND state='open'`, rc.ID, "adapter:not_dispatched", ts(now), int64(id)) |
| + return err |
| +} |
diff --git a/internal/equipo/team/git_evidence_test.go b/internal/equipo/team/git_evidence_test.go| index bef23eb5..57711553 100644 |
| --- a/internal/equipo/team/git_evidence_test.go |
| +++ b/internal/equipo/team/git_evidence_test.go |
| @@ -19,6 +19,9 @@ type gitEnv struct { |
| func newGitEnv(t *testing.T) *gitEnv { return newGitEnvObject(t, 40) } |
| func newGitEnvObject(t *testing.T, objectLength int) *gitEnv { |
| + return newGitEnvRepository(t, objectLength, "example/shop") |
| +} |
| +func newGitEnvRepository(t *testing.T, objectLength int, repository string) *gitEnv { |
| e := newEnv(t) |
| g := &gitEnv{env: e} |
| 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"))}}}} |
| @@ -36,6 +39,7 @@ func newGitEnvObject(t *testing.T, objectLength int) *gitEnv { |
| } |
| steps = append(steps, StepSpec{Key: "rework", Capability: CapImplement, Version: 1}) |
| spec := softwareSpec(steps) |
| + spec.Target.Repository = repository |
| spec.Policy = runnerPolicy(t, "subscription") |
| spec.Target.BaseRevision = strings.Repeat("a", objectLength) |
| spec.Evidence.BaselineTestSetHash = hashBytes([]byte("tests")) |
diff --git a/internal/equipo/team/model.go b/internal/equipo/team/model.go| index 3b263ff1..1e070561 100644 |
| --- a/internal/equipo/team/model.go |
| +++ b/internal/equipo/team/model.go |
| @@ -46,6 +46,7 @@ const ( |
| CodeGrantStale Code = "grant_stale" // authority version or epoch differs from the stored snapshot |
| CodeAuthorityUnavailable Code = "authority_unavailable" // authority could not answer; nothing was decided |
| CodeReceiptConflict Code = "receipt_conflict" // a different receipt or usage for a settled reservation |
| + CodeNotDispatched Code = "not_dispatched" // adapter proves no dispatch or usage; releases the reservation |
| CodeUncertain Code = "uncertain" // external outcome unknown; reconcile before replaying |
| CodeReplayUnsafe Code = "replay_unsafe" // operation class forbids replay without a definitive answer |
| CodeEvidence Code = "evidence" // success predicate not satisfied |
| @@ -107,6 +108,7 @@ var ( |
| ErrGrantStale = &Error{Code: CodeGrantStale} |
| ErrAuthorityUnavailable = &Error{Code: CodeAuthorityUnavailable} |
| ErrReceiptConflict = &Error{Code: CodeReceiptConflict} |
| + ErrNotDispatched = &Error{Code: CodeNotDispatched} |
| ErrUncertain = &Error{Code: CodeUncertain} |
| ErrReplayUnsafe = &Error{Code: CodeReplayUnsafe} |
| ErrEvidence = &Error{Code: CodeEvidence} |
diff --git a/internal/equipo/team/publication.go b/internal/equipo/team/publication.go| index 20b9bc62..1bd202df 100644 |
| --- a/internal/equipo/team/publication.go |
| +++ b/internal/equipo/team/publication.go |
| @@ -9,6 +9,15 @@ import ( |
| var publicationAgent = regexp.MustCompile(`^[A-Za-z0-9_-]+~[^\s~@]+@[^\s~@]+$`) |
| +// CanonicalJSON shares the core payload identity with runner adapters. |
| +func CanonicalJSON(raw []byte) ([]byte, string, error) { return canonical(raw) } |
| + |
| +// ContentDigest hashes immutable artifact and description bytes. |
| +func ContentDigest(raw []byte) string { return hashBytes(raw) } |
| + |
| +// ValidPublicationAgent checks the disclosed agent spelling used in receipts. |
| +func ValidPublicationAgent(agent string) bool { return publicationAgent.MatchString(agent) } |
| + |
| type PublicationEvidence struct { |
| Step StepID `json:"step"` |
| Attempt AttemptID `json:"attempt"` |
| @@ -129,7 +138,7 @@ func ValidatePublicationReceipt(payload []byte, receipt Receipt) error { |
| return ErrEvidence |
| } |
| } |
| - if !publicationAgent.MatchString(receipt.Fields["agent"]) { |
| + if !ValidPublicationAgent(receipt.Fields["agent"]) { |
| return ErrEvidence |
| } |
| return nil |
diff --git a/internal/equipo/team/publication_forge_test.go b/internal/equipo/team/publication_forge_test.go| new file mode 100644 |
| index 00000000..b1c6f3ca |
| --- /dev/null |
| +++ b/internal/equipo/team/publication_forge_test.go |
| @@ -0,0 +1,55 @@ |
| +package team_test |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "path/filepath" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/equipo/team" |
| + "amadan.net/oficina/equipo/internal/runner/forge" |
| +) |
| + |
| +type noDescription struct{ t *testing.T } |
| + |
| +func (noDescription) BeforePush() bool { return true } |
| +func (n noDescription) Set(context.Context, forge.Credential, forge.Description) error { |
| + n.t.Fatal("description reached") |
| + return nil |
| +} |
| +func (n noDescription) Read(context.Context, forge.Credential, string, string) (forge.Description, error) { |
| + n.t.Fatal("description reached") |
| + return forge.Description{}, nil |
| +} |
| + |
| +func TestPublishCoreAuthorizationContract(t *testing.T) { |
| + a, now := team.PublicationAuthorizationFixture(t) |
| + raw, h, err := forge.Canonical(a.Ticket.Dispatch.Payload) |
| + if err != nil || !bytes.Equal(raw, a.Ticket.Dispatch.Payload) || h != a.Ticket.Dispatch.Hash || forge.CanonicalHash(a.Candidate) != a.Publication.CandidateHash || forge.Digest([]byte(a.Publication.Description)) != a.Publication.DescriptionHash { |
| + t.Fatal("core publication hashes drifted", err) |
| + } |
| + for _, agent := range []string{"equipo~operator@example.test", "bot_1-2~person+tag@example.test", "person@example.test", "bot~a@b@c", "bot~space here@example.test", "bot~a@example.test\n"} { |
| + t.Run(agent, func(t *testing.T) { |
| + exported := false |
| + p, err := forge.New(forge.Config{Root: filepath.Join(t.TempDir(), "private"), GitPath: "/usr/bin/git", Runner: a.Ticket.Handle.Runner, Incarnation: a.Ticket.Incarnation, Clock: func() time.Time { return now }, Authorize: func(context.Context, team.Dispatch) (forge.Authorization, error) { return a, nil }, Revalidate: func(context.Context, forge.Authorization) error { return nil }, Credential: func(context.Context, string) (forge.Credential, error) { |
| + return forge.Credential{Remote: "https://" + a.Target.Repository, Agent: agent, Bearer: "offline-fixture"}, nil |
| + }, Export: func(context.Context, team.GitCandidate, string) error { exported = true; return team.ErrNotDispatched }, Description: noDescription{t}}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + _, err = p.Execute(context.Background(), a.Ticket.Dispatch) |
| + if !errors.Is(err, team.ErrNotDispatched) { |
| + t.Fatal("export boundary class", err) |
| + } |
| + receipt := team.Receipt{Outcome: team.OutcomeSuccess, Fields: map[string]string{"repository": a.Publication.Repository, "ref": a.Publication.Ref, "qualified_ref": "refs/heads/" + a.Publication.Ref, "head": a.Publication.Head, "candidate_hash": a.Publication.CandidateHash, "description_hash": a.Publication.DescriptionHash, "agent": agent}} |
| + payload, _ := json.Marshal(a.Publication) |
| + accepted := team.ValidatePublicationReceipt(payload, receipt) == nil |
| + if accepted != exported { |
| + t.Fatalf("core/forge identity mismatch for %q: receipt=%v export=%v", agent, accepted, exported) |
| + } |
| + }) |
| + } |
| +} |
diff --git a/internal/equipo/team/publication_no_effect_test.go b/internal/equipo/team/publication_no_effect_test.go| new file mode 100644 |
| index 00000000..40d2cb55 |
| --- /dev/null |
| +++ b/internal/equipo/team/publication_no_effect_test.go |
| @@ -0,0 +1,78 @@ |
| +package team |
| + |
| +import ( |
| + "context" |
| + "testing" |
| +) |
| + |
| +type noPublicationEffect struct{ *FakeForge } |
| + |
| +func (noPublicationEffect) Execute(context.Context, Dispatch) (Receipt, error) { |
| + return Receipt{}, ErrNotDispatched |
| +} |
| +func (noPublicationEffect) Reconcile(context.Context, Dispatch) (ReconcileResult, error) { |
| + return ReconcileResult{}, ErrNotDispatched |
| +} |
| + |
| +func TestPublishNoEffectSettlement(t *testing.T) { |
| + for _, recover := range []bool{false, true} { |
| + t.Run(map[bool]string{false: "dispatch", true: "reconcile"}[recover], func(t *testing.T) { |
| + g := newGitEnv(t) |
| + g.build() |
| + g.review() |
| + g.verify(true) |
| + g.store.adapters[OpForgePublish] = noPublicationEffect{NewFakeForge()} |
| + 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) |
| + if recover { |
| + _, err = g.store.Admit(g.ctx, g.scope, id) |
| + must(t, err) |
| + must(t, g.store.Lost(g.ctx, g.scope, id, "reply lost")) |
| + _, err = g.store.Reconcile(g.ctx, g.scope, id) |
| + must(t, err) |
| + } else { |
| + r, e := g.store.Dispatch(g.ctx, g.scope, id) |
| + must(t, e) |
| + if r.Outcome != OutcomeFailure { |
| + t.Fatal("no dispatch was not failed", r) |
| + } |
| + } |
| + a, err := g.store.GetAction(g.ctx, g.scope, id) |
| + must(t, err) |
| + if a.State != ActionFailed || a.Receipt == nil || a.Receipt.Usage == nil || *a.Receipt.Usage != (Usage{}) { |
| + t.Fatalf("no dispatch stayed charged or unknown: %+v", a) |
| + } |
| + rows, err := g.store.Reservations(g.ctx, g.scope) |
| + must(t, err) |
| + for _, r := range rows { |
| + if r.ID == a.Reservation && (r.State != ReservationReleased || r.Settled.Calls != 0 || r.Settled.CostMicros != 0) { |
| + t.Fatalf("no dispatch retained charge: %+v", r) |
| + } |
| + } |
| + must(t, g.store.Record(g.ctx, g.scope, id, *a.Receipt)) |
| + }) |
| + } |
| +} |
| + |
| +func TestPublishZeroReceiptDoesNotProveNoDispatch(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) |
| + d, err := g.store.Admit(g.ctx, g.scope, id) |
| + must(t, err) |
| + must(t, g.store.Record(g.ctx, g.scope, id, notDispatchedReceipt(d))) |
| + rows, err := g.store.Reservations(g.ctx, g.scope) |
| + must(t, err) |
| + if len(rows) != 1 || rows[0].State != ReservationSettled || rows[0].Settled.Calls != 1 { |
| + t.Fatal("ordinary zero receipt released charge", rows) |
| + } |
| +} |
diff --git a/internal/equipo/team/publication_test.go b/internal/equipo/team/publication_test.go| index ebf794fb..687b8e1a 100644 |
| --- a/internal/equipo/team/publication_test.go |
| +++ b/internal/equipo/team/publication_test.go |
| @@ -4,6 +4,7 @@ import ( |
| "encoding/json" |
| "strings" |
| "testing" |
| + "time" |
| ) |
| func TestPublishDescriptionProvenance(t *testing.T) { |
| @@ -153,3 +154,18 @@ func TestPublishDescriptionChangedAtAdmit(t *testing.T) { |
| t.Fatal("changed description provenance admitted") |
| } |
| } |
| + |
| +func PublicationAuthorizationFixture(t *testing.T) (PublicationAuthorization, time.Time) { |
| + g := newGitEnvRepository(t, 40, "amadan.net/example/repo") |
| + 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, "cross-package") |
| + must(t, err) |
| + return a, g.clock.Now() |
| +} |
diff --git a/internal/runner/forge/credential_test.go b/internal/runner/forge/credential_test.go| new file mode 100644 |
| index 00000000..79b6eaf0 |
| --- /dev/null |
| +++ b/internal/runner/forge/credential_test.go |
| @@ -0,0 +1,103 @@ |
| +package forge |
| + |
| +import ( |
| + "encoding/json" |
| + "fmt" |
| + "os" |
| + "os/exec" |
| + "path/filepath" |
| + "strings" |
| + "testing" |
| +) |
| + |
| +func hostileGitEnvironment(t *testing.T, f *fixture) func() { |
| + t.Helper() |
| + template := filepath.Join(f.root, "template") |
| + hooks := filepath.Join(template, "hooks") |
| + marker := filepath.Join(f.root, "hook-ran") |
| + helperMarker := filepath.Join(f.root, "helper-ran") |
| + must(t, os.MkdirAll(hooks, 0700)) |
| + must(t, os.WriteFile(filepath.Join(hooks, "pre-push"), []byte("#!/bin/sh\ntouch "+marker+"\nexit 1\n"), 0700)) |
| + helper := filepath.Join(f.root, "credential-helper") |
| + must(t, os.WriteFile(helper, []byte("#!/bin/sh\ntouch "+helperMarker+"\nprintf 'username=fixture\\npassword=canary\\n'\n"), 0700)) |
| + config := filepath.Join(f.root, "hostile.config") |
| + must(t, os.WriteFile(config, []byte(fmt.Sprintf("[init]\n templateDir = %s\n[core]\n hooksPath = %s\n[credential]\n helper = %s\n[url \"file:///nonexistent/forged\"]\n insteadOf = %s\n insteadOf = https://amadan.net/\n", template, hooks, helper, f.remote)), 0600)) |
| + // Positive controls stay local and prove the planted template/helper work. |
| + control := filepath.Join(f.root, "control.git") |
| + gitTest(t, f.root, "init", "--bare", "--template="+template, control) |
| + if _, err := os.Stat(filepath.Join(control, "hooks", "pre-push")); err != nil { |
| + t.Fatal("template control", err) |
| + } |
| + c := exec.Command("git", "-c", "credential.helper="+helper, "credential", "fill") |
| + c.Env = []string{"PATH=/usr/bin:/bin", "HOME=/nonexistent", "GIT_CONFIG_GLOBAL=/dev/null", "GIT_CONFIG_NOSYSTEM=1", "GIT_TERMINAL_PROMPT=0"} |
| + c.Stdin = strings.NewReader("protocol=https\nhost=example.invalid\n\n") |
| + if _, err := c.Output(); err != nil { |
| + t.Fatal("helper control", err) |
| + } |
| + if _, err := os.Stat(helperMarker); err != nil { |
| + t.Fatal("helper control missed marker", err) |
| + } |
| + must(t, os.Remove(helperMarker)) |
| + c = exec.Command("git", "-c", "core.hooksPath="+hooks, "push", f.remote, f.auth.Candidate.Commit+":refs/heads/probe") |
| + c.Dir = f.source |
| + c.Env = []string{"PATH=/usr/bin:/bin", "HOME=/nonexistent", "GIT_CONFIG_GLOBAL=/dev/null", "GIT_CONFIG_NOSYSTEM=1", "GIT_TERMINAL_PROMPT=0"} |
| + if err := c.Run(); err == nil { |
| + t.Fatal("hook control did not refuse push") |
| + } |
| + if _, err := os.Stat(marker); err != nil { |
| + t.Fatal("hook control missed marker", err) |
| + } |
| + must(t, os.Remove(marker)) |
| + t.Setenv("PERSON_SECRET", "person-canary") |
| + t.Setenv("GIT_TEMPLATE_DIR", template) |
| + t.Setenv("GIT_CONFIG_GLOBAL", config) |
| + t.Setenv("GIT_CONFIG_SYSTEM", config) |
| + t.Setenv("GIT_CONFIG_NOSYSTEM", "0") |
| + t.Setenv("GIT_CONFIG_COUNT", "1") |
| + t.Setenv("GIT_CONFIG_KEY_0", "url.file:///nonexistent/forged.insteadOf") |
| + t.Setenv("GIT_CONFIG_VALUE_0", f.remote) |
| + log := filepath.Join(f.root, "git-environment") |
| + spy := filepath.Join(f.root, "git-hostile-spy") |
| + script := fmt.Sprintf(`#!/usr/bin/python3 |
| +import os,sys,json,subprocess |
| +args=sys.argv[1:] |
| +with open(%q,'a') as out: |
| + out.write(json.dumps({'args':args,'env':dict(os.environ)})+'\n') |
| +if 'push' in args: |
| + subprocess.run(['/usr/bin/git','credential','fill'],input=b'protocol=https\nhost=example.invalid\n\n',stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL,env=dict(os.environ)) |
| +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 |
| + return func() { |
| + for _, path := range []string{marker, helperMarker} { |
| + if _, err := os.Stat(path); !os.IsNotExist(err) { |
| + t.Fatal("hostile Git extension ran", path, err) |
| + } |
| + } |
| + b, err := os.ReadFile(log) |
| + must(t, err) |
| + for _, line := range strings.Split(strings.TrimSpace(string(b)), "\n") { |
| + var row struct { |
| + Args []string |
| + Env map[string]string |
| + } |
| + must(t, json.Unmarshal([]byte(line), &row)) |
| + env := row.Env |
| + if env["GIT_CONFIG_GLOBAL"] != "/dev/null" || env["GIT_CONFIG_SYSTEM"] != "/dev/null" || env["GIT_CONFIG_NOSYSTEM"] != "1" || env["GIT_TEMPLATE_DIR"] != "" || env["GIT_CONFIG_VALUE_0"] != "/dev/null" || env["GIT_CONFIG_KEY_1"] != "credential.helper" || env["GIT_CONFIG_VALUE_1"] != "" || env["PERSON_SECRET"] != "" { |
| + t.Fatal("unsafe Git environment", env) |
| + } |
| + args := " " + strings.Join(row.Args, " ") + " " |
| + if strings.Contains(args, " init ") && !strings.Contains(args, " --template= ") { |
| + t.Fatal("staging template not disabled") |
| + } |
| + if strings.Contains(args, " push ") && !strings.Contains(args, " --no-verify ") { |
| + t.Fatal("push hooks not disabled") |
| + } |
| + } |
| + } |
| +} |
diff --git a/internal/runner/forge/no_effect_test.go b/internal/runner/forge/no_effect_test.go| new file mode 100644 |
| index 00000000..a108dcfd |
| --- /dev/null |
| +++ b/internal/runner/forge/no_effect_test.go |
| @@ -0,0 +1,274 @@ |
| +package forge |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "fmt" |
| + "os" |
| + "path/filepath" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/equipo/team" |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| +) |
| + |
| +func assertNoEffect(t *testing.T, f *fixture, err error) { |
| + t.Helper() |
| + if !errors.Is(err, team.ErrNotDispatched) || errors.Is(err, team.ErrUncertain) || f.pushes != 0 { |
| + t.Fatalf("want definitive no dispatch, got %v; pushes=%d", err, f.pushes) |
| + } |
| + r, err := f.p.Reconcile(ctx, f.auth.Ticket.Dispatch) |
| + if !errors.Is(err, team.ErrNotDispatched) || r.Receipt != nil { |
| + t.Fatalf("reconcile did not confirm no dispatch: %+v %v", r, err) |
| + } |
| +} |
| + |
| +func TestPublishNoEffect(t *testing.T) { |
| + for _, name := range []string{"authorize", "validate", "revalidate", "credential", "mkdir", "export", "init", "rev-parse", "expired_export", "journal", "query", "final_authority", "final_validate", "final_objects", "description", "cancel_description", "push_marker", "context"} { |
| + t.Run(name, func(t *testing.T) { |
| + f := newFixture(t) |
| + cleanup := func() {} |
| + switch name { |
| + case "authorize": |
| + f.p.cfg.Authorize = func(context.Context, team.Dispatch) (Authorization, error) { return Authorization{}, team.ErrFence } |
| + case "validate": |
| + f.auth.Ticket.Incarnation++ |
| + case "revalidate": |
| + f.p.cfg.Revalidate = func(context.Context, Authorization) error { return team.ErrFence } |
| + case "credential": |
| + f.p.cfg.Credential = func(context.Context, string) (Credential, error) { return Credential{}, team.ErrUncertain } |
| + case "mkdir": |
| + original := f.p.cfg.Credential |
| + f.p.cfg.Credential = func(c context.Context, s string) (Credential, error) { |
| + must(t, os.Rename(f.p.cfg.Root, f.p.cfg.Root+"-saved")) |
| + must(t, os.WriteFile(f.p.cfg.Root, nil, 0600)) |
| + return original(c, s) |
| + } |
| + cleanup = func() { must(t, os.Remove(f.p.cfg.Root)); must(t, os.Rename(f.p.cfg.Root+"-saved", f.p.cfg.Root)) } |
| + case "export": |
| + f.p.cfg.Export = func(context.Context, team.GitCandidate, string) error { return team.ErrUncertain } |
| + case "init", "rev-parse": |
| + wrapper := filepath.Join(f.root, "git-fail") |
| + must(t, os.WriteFile(wrapper, []byte(fmt.Sprintf("#!/bin/sh\nfor arg do\n if [ \"$arg\" = %s ]; then exit 79; fi\ndone\nexec /usr/bin/git \"$@\"\n", name)), 0700)) |
| + f.p.cfg.GitPath = wrapper |
| + case "expired_export": |
| + original := f.p.cfg.Export |
| + f.p.cfg.Export = func(c context.Context, g team.GitCandidate, s string) error { |
| + e := original(c, g, s) |
| + f.p.cfg.Clock = func() time.Time { return f.auth.Ticket.ExpiresAt } |
| + return e |
| + } |
| + case "journal": |
| + original := f.p.cfg.Export |
| + f.p.cfg.Export = func(c context.Context, g team.GitCandidate, s string) error { |
| + e := original(c, g, s) |
| + must(t, os.Mkdir(f.p.path(f.auth.Ticket.Dispatch), 0700)) |
| + return e |
| + } |
| + cleanup = func() { must(t, os.Remove(f.p.path(f.auth.Ticket.Dispatch))) } |
| + case "query": |
| + must(t, os.Rename(f.remote, f.remote+"-hidden")) |
| + case "final_authority": |
| + calls := 0 |
| + f.p.cfg.Revalidate = func(context.Context, Authorization) error { |
| + calls++ |
| + if calls > 1 { |
| + return team.ErrFence |
| + } |
| + return nil |
| + } |
| + case "final_validate": |
| + original := f.p.localRemote |
| + f.p.localRemote = func(s string) string { |
| + f.p.cfg.Clock = func() time.Time { return f.auth.Ticket.ExpiresAt } |
| + return original(s) |
| + } |
| + case "final_objects": |
| + original := f.p.localRemote |
| + f.p.localRemote = func(s string) string { |
| + dirs, e := filepath.Glob(filepath.Join(f.p.cfg.Root, "objects-*", "git", "objects")) |
| + must(t, e) |
| + for _, dir := range dirs { |
| + must(t, os.RemoveAll(dir)) |
| + } |
| + return original(s) |
| + } |
| + case "description": |
| + f.desc.fail = true |
| + case "cancel_description": |
| + f.desc.before = func() { f.cancelled = true } |
| + case "push_marker": |
| + f.desc.before = func() { |
| + path := f.p.path(f.auth.Ticket.Dispatch) |
| + must(t, os.Rename(path, path+"-saved")) |
| + must(t, os.Mkdir(path, 0700)) |
| + } |
| + cleanup = func() { |
| + path := f.p.path(f.auth.Ticket.Dispatch) |
| + must(t, os.Remove(path)) |
| + must(t, os.Rename(path+"-saved", path)) |
| + } |
| + } |
| + callCtx := ctx |
| + if name == "context" { |
| + var cancel context.CancelFunc |
| + callCtx, cancel = context.WithCancel(ctx) |
| + cancel() |
| + } |
| + _, err := f.p.Execute(callCtx, f.auth.Ticket.Dispatch) |
| + cleanup() |
| + assertNoEffect(t, f, err) |
| + if name == "expired_export" { |
| + if _, e := os.Stat(f.p.path(f.auth.Ticket.Dispatch)); !os.IsNotExist(e) { |
| + t.Fatal("expired export wrote a journal") |
| + } |
| + } |
| + if name == "final_authority" || name == "final_validate" || name == "final_objects" { |
| + if f.desc.calls != 0 { |
| + t.Fatal("description changed before final authority and object checks") |
| + } |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestPublishMissingJournal(t *testing.T) { |
| + f := newFixture(t) |
| + r, err := f.p.Reconcile(ctx, f.auth.Ticket.Dispatch) |
| + if !errors.Is(err, team.ErrNotDispatched) || r.Receipt != nil { |
| + t.Fatalf("missing journal is no dispatch: %+v %v", r, err) |
| + } |
| +} |
| + |
| +func TestPublishIndependentActionLocks(t *testing.T) { |
| + a := newFixture(t) |
| + _, err := a.p.Execute(ctx, a.auth.Ticket.Dispatch) |
| + must(t, err) |
| + entered, release, done := make(chan struct{}), make(chan struct{}), make(chan error, 1) |
| + credential := a.p.cfg.Credential |
| + a.p.cfg.Credential = func(c context.Context, s string) (Credential, error) { |
| + close(entered) |
| + <-release |
| + return credential(c, s) |
| + } |
| + go func() { _, e := a.p.Reconcile(ctx, a.auth.Ticket.Dispatch); done <- e }() |
| + <-entered |
| + b := newFixture(t) |
| + b.p.cfg.Root = a.p.cfg.Root |
| + b.auth.Ticket.Dispatch.Action++ |
| + b.auth.Ticket.Scope.Job++ |
| + _, err = b.p.Execute(ctx, b.auth.Ticket.Dispatch) |
| + close(release) |
| + must(t, <-done) |
| + must(t, err) |
| + if b.pushes != 1 { |
| + t.Fatal("independent action did not push") |
| + } |
| +} |
| + |
| +func TestPublishSameActionLockStaysUncertain(t *testing.T) { |
| + f := newFixture(t) |
| + entered, release, done := make(chan struct{}), make(chan struct{}), make(chan error, 1) |
| + original := f.p.cfg.Export |
| + f.p.cfg.Export = func(c context.Context, g team.GitCandidate, s string) error { |
| + close(entered) |
| + <-release |
| + return original(c, g, s) |
| + } |
| + go func() { _, err := f.p.Execute(ctx, f.auth.Ticket.Dispatch); done <- err }() |
| + <-entered |
| + _, err := f.p.Reconcile(ctx, f.auth.Ticket.Dispatch) |
| + close(release) |
| + must(t, <-done) |
| + if !errors.Is(err, team.ErrUncertain) { |
| + t.Fatal("live action was reported absent", err) |
| + } |
| +} |
| + |
| +func TestPublishDefaultChangeAndManualMerge(t *testing.T) { |
| + for _, name := range []string{"default_change", "manual_merge"} { |
| + t.Run(name, func(t *testing.T) { |
| + f := newFixture(t) |
| + gitTest(t, f.root, "--git-dir="+f.remote, "fetch", f.source, f.auth.Candidate.Commit) |
| + gitTest(t, f.root, "--git-dir="+f.remote, "update-ref", "refs/heads/main", f.auth.Candidate.Commit) |
| + if name == "default_change" { |
| + gitTest(t, f.root, "--git-dir="+f.remote, "symbolic-ref", "HEAD", "refs/heads/new-default") |
| + } |
| + f.auth.Publication.Ref = "main" |
| + f.auth.Ticket.Dispatch.Payload, f.auth.Ticket.Dispatch.Hash, _ = Canonical(marshalPublication(t, f.auth.Publication)) |
| + _, err := f.p.Execute(ctx, f.auth.Ticket.Dispatch) |
| + assertNoEffect(t, f, err) |
| + if f.desc.calls != 0 { |
| + t.Fatal("external branch state granted description authority") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestPublishPushMarkerDurable(t *testing.T) { |
| + f := newFixture(t) |
| + f.p.beforePush = func() { |
| + f.pushes++ |
| + r, err := f.p.load(f.auth.Ticket.Dispatch) |
| + must(t, err) |
| + if r.Phase != "push_started" { |
| + t.Fatal("push began without durable marker", r.Phase) |
| + } |
| + } |
| + _, err := f.p.Execute(ctx, f.auth.Ticket.Dispatch) |
| + must(t, err) |
| +} |
| + |
| +func TestPublishJournalRecoveryClasses(t *testing.T) { |
| + for _, name := range []string{"legacy", "unknown_phase", "corrupt", "prepared_with_remote", "already_identical"} { |
| + t.Run(name, func(t *testing.T) { |
| + f := newFixture(t) |
| + d := f.auth.Ticket.Dispatch |
| + if name == "already_identical" { |
| + gitTest(t, f.root, "--git-dir="+f.remote, "fetch", f.source, f.auth.Candidate.Commit) |
| + gitTest(t, f.root, "--git-dir="+f.remote, "update-ref", "refs/heads/heads/main", f.auth.Candidate.Commit) |
| + _, err := f.p.Execute(ctx, d) |
| + must(t, err) |
| + r, err := f.p.Reconcile(ctx, d) |
| + must(t, err) |
| + if r.Receipt == nil || f.pushes != 0 || f.desc.calls != 1 { |
| + t.Fatal("identical head did not reconcile", r) |
| + } |
| + return |
| + } |
| + _, err := f.p.Execute(ctx, d) |
| + must(t, err) |
| + r, err := f.p.load(d) |
| + must(t, err) |
| + switch name { |
| + case "legacy": |
| + r.Phase = "" |
| + case "unknown_phase": |
| + r.Phase = "unrecognized" |
| + case "prepared_with_remote": |
| + r.Phase = "prepared" |
| + } |
| + must(t, runnerproto.JournalCredentials(f.p.path(d), r)) |
| + if name == "corrupt" { |
| + must(t, os.WriteFile(f.p.path(d), []byte("{"), 0600)) |
| + } |
| + result, err := f.p.Reconcile(ctx, d) |
| + switch name { |
| + case "legacy": |
| + must(t, err) |
| + if result.Receipt == nil { |
| + t.Fatal("legacy lost receipt") |
| + } |
| + case "prepared_with_remote": |
| + if !errors.Is(err, team.ErrNotDispatched) { |
| + t.Fatal("prepared journal inferred dispatch from remote", err) |
| + } |
| + default: |
| + if !errors.Is(err, team.ErrUncertain) { |
| + t.Fatal("unreadable history became no effect", err) |
| + } |
| + } |
| + }) |
| + } |
| +} |
diff --git a/internal/runner/forge/publisher.go b/internal/runner/forge/publisher.go| index f8ef548f..344ac669 100644 |
| --- a/internal/runner/forge/publisher.go |
| +++ b/internal/runner/forge/publisher.go |
| @@ -3,10 +3,8 @@ package forge |
| import ( |
| "bytes" |
| "context" |
| - "crypto/sha256" |
| - "encoding/hex" |
| "encoding/json" |
| - "io" |
| + "errors" |
| "net/url" |
| "os" |
| "path/filepath" |
| @@ -54,7 +52,6 @@ type Publisher struct { |
| 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) { |
| @@ -83,25 +80,9 @@ func (*Publisher) Classify(op team.Operation) (team.ReplayClass, error) { |
| } |
| 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 Digest(b []byte) string { return team.ContentDigest(b) } |
| +func Canonical(raw []byte) ([]byte, string, error) { return team.CanonicalJSON(raw) } |
| +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 |
| @@ -155,7 +136,7 @@ func (p *Publisher) credential(ctx context.Context, repository string) (Credenti |
| 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 { |
| + if e != nil || !team.ValidPublicationAgent(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 |
| @@ -165,13 +146,15 @@ type record struct { |
| Authorization Authorization |
| Description Description |
| Remote string |
| + // An empty phase is a legacy journal and cannot prove no dispatch. |
| + Phase 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) |
| +func (p *Publisher) lock(d team.Dispatch) (func(), error) { |
| + f, e := os.OpenFile(p.path(d)+".lock", os.O_CREATE|os.O_RDWR|syscall.O_NOFOLLOW, 0600) |
| if e != nil { |
| return nil, team.ErrUncertain |
| } |
| @@ -192,11 +175,11 @@ func (p *Publisher) load(d team.Dispatch) (record, error) { |
| } |
| return r, nil |
| } |
| -func (p *Publisher) Execute(ctx context.Context, d team.Dispatch) (team.Receipt, error) { |
| +func (p *Publisher) Execute(ctx context.Context, d team.Dispatch) (receipt team.Receipt, resultErr error) { |
| if validateDispatch(d) != nil { |
| return team.Receipt{}, team.ErrInvalid |
| } |
| - unlock, e := p.lock() |
| + unlock, e := p.lock(d) |
| if e != nil { |
| return team.Receipt{}, e |
| } |
| @@ -206,6 +189,13 @@ func (p *Publisher) Execute(ctx context.Context, d team.Dispatch) (team.Receipt, |
| } else if !os.IsNotExist(err) { |
| return team.Receipt{}, err |
| } |
| + // Only a fresh action under its lock can prove a preparation failure. |
| + mayPublish := false |
| + defer func() { |
| + if resultErr != nil && !mayPublish && !errors.Is(resultErr, team.ErrConflict) { |
| + resultErr = team.ErrNotDispatched |
| + } |
| + }() |
| a, e := p.cfg.Authorize(ctx, d) |
| if e != nil { |
| return team.Receipt{}, e |
| @@ -229,8 +219,11 @@ func (p *Publisher) Execute(ctx context.Context, d team.Dispatch) (team.Receipt, |
| if e != nil { |
| return team.Receipt{}, e |
| } |
| + if e = p.validate(a, d); 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} |
| + r := record{Authorization: a, Description: desc, Remote: cred.Remote, Phase: "prepared"} |
| if e = runnerproto.JournalCredentials(p.path(d), r); e != nil { |
| return team.Receipt{}, team.ErrUncertain |
| } |
| @@ -238,10 +231,30 @@ func (p *Publisher) Execute(ctx context.Context, d team.Dispatch) (team.Receipt, |
| if err != nil { |
| return team.Receipt{}, err |
| } |
| - if head != "" { |
| - if head != a.Candidate.Commit { |
| - return team.Receipt{}, team.ErrConflict |
| + if head != "" && head != a.Candidate.Commit { |
| + return team.Receipt{}, team.ErrConflict |
| + } |
| + ready := func() error { |
| + if err := ctx.Err(); err != nil { |
| + return err |
| + } |
| + if err := p.verifyObjects(ctx, repo, a.Candidate); err != nil { |
| + return err |
| + } |
| + if err := p.validate(a, d); err != nil { |
| + return err |
| } |
| + return p.cfg.Revalidate(ctx, a) |
| + } |
| + if e = ready(); e != nil { |
| + return team.Receipt{}, e |
| + } |
| + if head == a.Candidate.Commit { |
| + r.Phase = "observed" |
| + if e = runnerproto.JournalCredentials(p.path(d), r); e != nil { |
| + return team.Receipt{}, e |
| + } |
| + mayPublish = true |
| return p.reconcile(ctx, r) |
| } |
| if p.cfg.Description.BeforePush() { |
| @@ -249,15 +262,14 @@ func (p *Publisher) Execute(ctx context.Context, d team.Dispatch) (team.Receipt, |
| 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 { |
| + if e = ready(); e != nil { |
| return team.Receipt{}, e |
| } |
| - if e = p.cfg.Revalidate(ctx, a); e != nil { |
| + r.Phase = "push_started" |
| + if e = runnerproto.JournalCredentials(p.path(d), r); e != nil { |
| return team.Receipt{}, e |
| } |
| + mayPublish = true |
| if p.beforePush != nil { |
| p.beforePush() |
| } |
| @@ -288,6 +300,12 @@ func (p *Publisher) confirmDescription(ctx context.Context, cred Credential, des |
| return nil |
| } |
| func (p *Publisher) reconcile(ctx context.Context, r record) (team.Receipt, error) { |
| + if r.Phase == "prepared" { |
| + return team.Receipt{}, team.ErrNotDispatched |
| + } |
| + if r.Phase != "" && r.Phase != "push_started" && r.Phase != "observed" { |
| + return team.Receipt{}, team.ErrUncertain |
| + } |
| v := r.Authorization.Publication |
| cred, e := p.credential(ctx, v.Repository) |
| if e != nil { |
| @@ -317,12 +335,15 @@ func (p *Publisher) Reconcile(ctx context.Context, d team.Dispatch) (team.Reconc |
| if validateDispatch(d) != nil { |
| return team.ReconcileResult{}, team.ErrInvalid |
| } |
| - unlock, e := p.lock() |
| + unlock, e := p.lock(d) |
| if e != nil { |
| return team.ReconcileResult{}, e |
| } |
| defer unlock() |
| r, e := p.load(d) |
| + if os.IsNotExist(e) { |
| + return team.ReconcileResult{}, team.ErrNotDispatched |
| + } |
| if e != nil { |
| return team.ReconcileResult{}, team.ErrUncertain |
| } |
diff --git a/internal/runner/forge/publisher_test.go b/internal/runner/forge/publisher_test.go| index 864068f6..f9303400 100644 |
| --- a/internal/runner/forge/publisher_test.go |
| +++ b/internal/runner/forge/publisher_test.go |
| @@ -3,6 +3,7 @@ package forge |
| import ( |
| "context" |
| "encoding/json" |
| + "errors" |
| "fmt" |
| "os" |
| "os/exec" |
| @@ -143,7 +144,7 @@ func TestPublishQualifiedRef(t *testing.T) { |
| if f.desc.calls != 1 { |
| t.Fatal("description missing") |
| } |
| - for _, name := range []string{"default", "repo", "ref", "tags", "candidate", "ticket", "runner", "evidence"} { |
| + for _, name := range []string{"default", "repo", "ref", "tags", "candidate", "ticket", "runner", "evidence", "tuple_identity"} { |
| t.Run(name, func(t *testing.T) { |
| f := newFixture(t) |
| d := f.auth.Ticket.Dispatch |
| @@ -156,6 +157,9 @@ func TestPublishQualifiedRef(t *testing.T) { |
| f.auth.Target.Ref = "other" |
| case "tuple_identity": |
| f.auth.Publication.Isolation.ObservedTuples[0].ProviderVersion = "" |
| + raw, _ := json.Marshal(f.auth.Publication) |
| + f.auth.Ticket.Dispatch.Payload, f.auth.Ticket.Dispatch.Hash, _ = Canonical(raw) |
| + d = f.auth.Ticket.Dispatch |
| case "tags": |
| f.auth.Target.Ref = "refs/tags/x" |
| case "candidate": |
| @@ -227,29 +231,21 @@ func TestPublishLostReceipt(t *testing.T) { |
| 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") |
| + if _, err = f.p.Reconcile(ctx, f.auth.Ticket.Dispatch); !errors.Is(err, team.ErrConflict) { |
| + t.Fatal("remote mismatch class", err) |
| } |
| must(t, os.Rename(f.remote, f.remote+"-hidden")) |
| r, err = f.p.Reconcile(ctx, f.auth.Ticket.Dispatch) |
| - if err == nil || r.Definitive { |
| + if !errors.Is(err, team.ErrUncertain) || 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)) |
| + check := hostileGitEnvironment(t, f) |
| _, 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") |
| - } |
| + check() |
| must(t, filepath.WalkDir(f.p.cfg.Root, func(path string, d os.DirEntry, e error) error { |
| if e != nil { |
| return e |
| @@ -323,14 +319,14 @@ 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 _, e := f.p.Execute(ctx, f.auth.Ticket.Dispatch); !errors.Is(e, team.ErrConflict) { |
| + t.Fatal("occupied ref class", e) |
| } |
| 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") |
| + if _, e := f.p.Reconcile(ctx, f.auth.Ticket.Dispatch); !errors.Is(e, team.ErrNotDispatched) { |
| + t.Fatal("unstarted occupied ref class", e) |
| } |
| } |
| @@ -537,3 +533,10 @@ os.execve('/usr/bin/git',['/usr/bin/git']+args,dict(os.environ)) |
| t.Fatal("HTTPS command path not exercised", pushes, remoteCalls) |
| } |
| } |
| + |
| +func marshalPublication(t *testing.T, p team.Publication) []byte { |
| + t.Helper() |
| + b, err := json.Marshal(p) |
| + must(t, err) |
| + return b |
| +} |