package forge import ( "context" "encoding/base64" "encoding/json" "errors" "fmt" "net/http" "os" "os/exec" "path/filepath" "strings" "sync" "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", GitPassword: "git-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", "tuple_identity"} { 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 = "" 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": 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); !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 !errors.Is(err, team.ErrUncertain) || r.Definitive { t.Fatal("query failure became absence") } } func TestPublishCredentialIsolation(t *testing.T) { f := newFixture(t) check := hostileGitEnvironment(t, f) _, err := f.p.Execute(ctx, f.auth.Ticket.Dispatch) must(t, err) check() 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") || strings.Contains(string(b), "git-canary") || strings.Contains(string(b), base64.StdEncoding.EncodeToString([]byte("x:git-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); !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); !errors.Is(e, team.ErrNotDispatched) { t.Fatal("unstarted occupied ref class", e) } } 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("GET failed to confirm lost description reply", e) } 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", "git_header", "git_missing"} { 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" case "git_header": c.GitPassword = "git-canary\r\nHeader: value" case "git_missing": c.GitPassword = "" } 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", GitPassword: "git-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") || strings.Contains(args, "git-canary") || strings.Contains(args, base64.StdEncoding.EncodeToString([]byte("x:git-canary"))) || strings.Contains(fmt.Sprint(row.Env), "agent-canary") || row.Env["PERSON_SECRET"] != "" { t.Fatal("credential escaped allowed environment") } if row.Env["GIT_CONFIG_KEY_7"] != "maintenance.auto" || row.Env["GIT_CONFIG_VALUE_7"] != "false" || row.Env["GIT_CONFIG_KEY_8"] != "gc.autoDetach" || row.Env["GIT_CONFIG_VALUE_8"] != "false" { t.Fatal("publication lost detached helper guards") } remote := strings.Contains(args, "https://amadan.net/example/repo") if remote { remoteCalls++ if row.Env["GIT_CONFIG_COUNT"] != "10" || row.Env["GIT_CONFIG_KEY_9"] != "http.extraHeader" || row.Env["GIT_CONFIG_VALUE_9"] != "Authorization: Basic "+base64.StdEncoding.EncodeToString([]byte("x:git-canary")) { t.Fatal("runner credential missing") } } else if strings.Contains(fmt.Sprint(row.Env), "git-canary") || strings.Contains(fmt.Sprint(row.Env), base64.StdEncoding.EncodeToString([]byte("x:git-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) } } func marshalPublication(t *testing.T, p team.Publication) []byte { t.Helper() b, err := json.Marshal(p) must(t, err) return b } func TestTrialPublisherRequiresBothLabels(t *testing.T) { f := newFixture(t) f.auth.Publication.Isolation.Status = "unconfined" f.auth.Publication.Isolation.Trial = &team.TrialSnapshot{Label: "supervised trial", AcknowledgementIDs: []string{"trial"}, UnverifiedChecks: team.TrialChecks(), ProviderVersionSource: "observed_locally"} for _, label := range []string{"unconfined", "supervised trial", "supervised trial unconfined"} { f.auth.Publication.Description = label f.auth.Publication.DescriptionHash = Digest([]byte(label)) raw, _ := json.Marshal(f.auth.Publication) raw, hash, _ := Canonical(raw) f.auth.Ticket.Dispatch.Payload, f.auth.Ticket.Dispatch.Hash = raw, hash err := f.p.validate(f.auth, f.auth.Ticket.Dispatch) if (err == nil) != (label == "supervised trial unconfined") { t.Fatalf("%s: %v", label, err) } } } // The fake writer only writes the in-memory response served by loopback GET. type descriptionWriterFunc func(context.Context, Credential, Description) error func (f descriptionWriterFunc) Set(ctx context.Context, c Credential, d Description) error { return f(ctx, c, d) } func TestPublishDescriptionRecovery(t *testing.T) { for _, mode := range []string{"not_dispatched", "lost_reply", "delayed_readback", "empty", "trimmed", "wrong_digest", "wrong_ref", "wrong_repo", "wrong_body", "wrong_agent"} { t.Run(mode, func(t *testing.T) { f := newFixture(t) f.auth.Publication.Description = " unconfined; approved beyond profile\n" f.auth.Publication.DescriptionHash = Digest([]byte(f.auth.Publication.Description)) raw, _ := json.Marshal(f.auth.Publication) f.auth.Ticket.Dispatch.Payload, f.auth.Ticket.Dispatch.Hash, _ = Canonical(raw) var mu sync.Mutex body := "" writes, reads, calls := 0, 0, 0 f.p.beforePush = func() { saved, err := f.p.load(f.auth.Ticket.Dispatch) must(t, err) if saved.Description.Body != f.auth.Publication.Description || saved.DescriptionAttempted { t.Fatal("missing pending description before push") } f.pushes++ } visible := mode != "delayed_readback" client := descriptionServer(t, func(w http.ResponseWriter, r *http.Request) { mu.Lock() defer mu.Unlock() reads++ if r.URL.EscapedPath() != "/api/v1/repos/example/repo/branches/heads%2Fmain/description" { t.Error("ref qualified twice or not escaped") } if body == "" || !visible || mode == "empty" { _ = json.NewEncoder(w).Encode(map[string]any{"empty": true}) return } _ = json.NewEncoder(w).Encode(descriptionResponse(body, "equipo~operator@example.test")) }) transport := NewDescriptionTransport(client, descriptionWriterFunc(func(_ context.Context, c Credential, d Description) error { mu.Lock() defer mu.Unlock() calls++ if f.pushes != 1 || gitTest(t, f.root, "--git-dir="+f.remote, "rev-parse", "refs/heads/heads/main") != f.auth.Candidate.Commit { t.Fatal("describe before exact ref exists") } saved, err := f.p.load(f.auth.Ticket.Dispatch) must(t, err) if saved.Description.Body != d.Body || !saved.DescriptionAttempted { t.Fatal("description intent not durable before write") } if mode == "not_dispatched" && calls == 1 { return fmt.Errorf("local setup: %w", team.ErrNotDispatched) } writes++ body = d.Body if mode == "trimmed" { body = strings.TrimSpace(body) } return team.ErrUncertain // Server stored it, command reply was lost. })) if transport.BeforePush() { t.Fatal("production transport describes before push") } f.p.cfg.Description = transport if strings.HasPrefix(mode, "wrong_") { f.p.cfg.Description = changedDescription{DescriptionTransport: transport, field: mode} } receipt, err := f.p.Execute(ctx, f.auth.Ticket.Dispatch) if mode == "lost_reply" { must(t, err) if receipt.Outcome != team.OutcomeSuccess { t.Fatal("readback did not confirm lost reply") } } else if err == nil { t.Fatal("unconfirmed description delivered success") } if mode == "not_dispatched" { saved, e := f.p.load(f.auth.Ticket.Dispatch) must(t, e) if saved.DescriptionAttempted { t.Fatal("never-sent description latched as attempted") } } mu.Lock() visible = true mu.Unlock() // Reconstruct the publisher to exercise the durable journal after a restart. restarted, err := newPublisher(f.p.cfg, f.p.localRemote) must(t, err) restarted.beforePush = f.p.beforePush result, err := restarted.Reconcile(ctx, f.auth.Ticket.Dispatch) if mode == "lost_reply" || mode == "delayed_readback" || mode == "not_dispatched" { must(t, err) if result.Receipt == nil || result.Receipt.Fields["description_hash"] != f.auth.Publication.DescriptionHash { t.Fatal("lost body digest") } } else if err == nil || result.Receipt != nil { t.Fatal("unconfirmed description reconciled success") } _, _ = restarted.Execute(ctx, f.auth.Ticket.Dispatch) if mode == "not_dispatched" && calls != 2 { t.Fatal("never-sent description not retried exactly once", calls) } if writes != 1 || f.pushes != 1 || reads < 3 { t.Fatal("duplicate write/push or skipped GET", writes, f.pushes, reads) } }) } } type changedDescription struct { DescriptionTransport field string } func (c changedDescription) Read(ctx context.Context, cred Credential, repo, ref string) (Description, error) { d, err := c.DescriptionTransport.Read(ctx, cred, repo, ref) switch c.field { case "wrong_digest": d.Digest = strings.Repeat("0", 64) case "wrong_ref": d.Ref = "another/ref" case "wrong_repo": d.Repository = "amadan.net/other/repo" case "wrong_body": d.Body = strings.TrimSpace(d.Body) case "wrong_agent": d.Agent = "another~operator@example.test" } return d, err } func TestPublishDescriptionReadFailureDoesNotWrite(t *testing.T) { f := newFixture(t) writes := 0 client := descriptionServer(t, func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusUnauthorized) }) f.p.cfg.Description = NewDescriptionTransport(client, descriptionWriterFunc(func(context.Context, Credential, Description) error { writes++; return team.ErrUncertain })) _, err := f.p.Execute(ctx, f.auth.Ticket.Dispatch) if err == nil || f.pushes != 1 || writes != 0 { t.Fatal("read failure caused a write or success", err, writes) } }