oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1package forge
2
3import (
4 "context"
5 "encoding/base64"
6 "encoding/json"
7 "errors"
8 "fmt"
9 "net/http"
10 "os"
11 "os/exec"
12 "path/filepath"
13 "strings"
14 "sync"
15 "testing"
16 "time"
17
18 "amadan.net/oficina/equipo/internal/equipo/team"
19)
20
21var ctx = context.Background()
22
23func must(t *testing.T, err error) {
24 t.Helper()
25 if err != nil {
26 t.Fatal(err)
27 }
28}
29func gitTest(t *testing.T, dir string, args ...string) string {
30 t.Helper()
31 c := exec.Command("git", args...)
32 c.Dir = dir
33 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")
34 b, e := c.CombinedOutput()
35 if e != nil {
36 t.Fatalf("git %v: %v %s", args, e, b)
37 }
38 return strings.TrimSpace(string(b))
39}
40
41type fakeDescription struct {
42 value Description
43 fail, requiresRef bool
44 lostSet, wrongRead bool
45 calls int
46 before func()
47}
48
49func (f *fakeDescription) BeforePush() bool { return !f.requiresRef }
50func (f *fakeDescription) Set(_ context.Context, credential Credential, d Description) error {
51 if credential.Agent != d.Agent || credential.Bearer != "agent-canary" {
52 return team.ErrScope
53 }
54 f.calls++
55 if f.before != nil {
56 f.before()
57 }
58 if f.fail {
59 return team.ErrUncertain
60 }
61 f.value = d
62 if f.lostSet {
63 return team.ErrUncertain
64 }
65 return nil
66}
67func (f *fakeDescription) Read(context.Context, Credential, string, string) (Description, error) {
68 if f.fail {
69 return Description{}, team.ErrUncertain
70 }
71 if f.wrongRead {
72 got := f.value
73 got.Agent = "person@example.test"
74 return got, nil
75 }
76 return f.value, nil
77}
78
79type fixture struct {
80 p *Publisher
81 auth Authorization
82 desc *fakeDescription
83 remote, source, root string
84 cancelled bool
85 pushes int
86}
87
88func newFixture(t *testing.T) *fixture {
89 t.Helper()
90 root := t.TempDir()
91 source := filepath.Join(root, "source")
92 remote := filepath.Join(root, "remote.git")
93 must(t, os.Mkdir(source, 0700))
94 gitTest(t, source, "init", "--template=")
95 must(t, os.WriteFile(filepath.Join(source, "file"), []byte("base"), 0600))
96 gitTest(t, source, "add", "file")
97 gitTest(t, source, "commit", "-m", "base")
98 base := gitTest(t, source, "rev-parse", "HEAD")
99 must(t, os.WriteFile(filepath.Join(source, "file"), []byte("fixed"), 0600))
100 gitTest(t, source, "commit", "-am", "candidate")
101 head := gitTest(t, source, "rev-parse", "HEAD")
102 tree := gitTest(t, source, "rev-parse", "HEAD^{tree}")
103 gitTest(t, root, "init", "--bare", "--template=", remote)
104 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)}}}
105 c := team.GitCandidate{Repository: "amadan.net/example/repo", BaseCommit: base, Commit: head, Tree: tree}
106 pub := team.Publication{Repository: c.Repository, Ref: "heads/main", Head: head, CandidateHash: CanonicalHash(c), Isolation: iso, Description: `{"status":"unconfined","executor":"checks","connection":"confined"}`}
107 pub.DescriptionHash = Digest([]byte(pub.Description))
108 raw, _ := json.Marshal(pub)
109 raw, hash, _ := Canonical(raw)
110 d := team.Dispatch{Action: 1, Key: "publish", Operation: team.OpForgePublish, Payload: raw, Hash: hash}
111 f := &fixture{source: source, remote: remote, root: root, desc: &fakeDescription{}}
112 now := time.Now().UTC()
113 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}
114 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) {
115 if f.cancelled {
116 return Authorization{}, team.ErrFence
117 }
118 return f.auth, nil
119 }, Revalidate: func(context.Context, Authorization) error {
120 if f.cancelled {
121 return team.ErrFence
122 }
123 return nil
124 }, Export: func(_ context.Context, c team.GitCandidate, dir string) error {
125 gitTest(t, root, "clone", "--no-local", "--template=", source, dir)
126 return nil
127 }, Credential: func(context.Context, string) (Credential, error) {
128 return Credential{Remote: "https://amadan.net/example/repo", Agent: "equipo~operator@example.test", Bearer: "agent-canary", GitPassword: "git-canary"}, nil
129 }, Description: f.desc}
130 var err error
131 f.p, err = newPublisher(cfg, func(_ string) string { return remote })
132 must(t, err)
133 f.p.beforePush = func() { f.pushes++ }
134 return f
135}
136func TestPublishQualifiedRef(t *testing.T) {
137 f := newFixture(t)
138 r, err := f.p.Execute(ctx, f.auth.Ticket.Dispatch)
139 must(t, err)
140 if r.Outcome != team.OutcomeSuccess || r.Fields["agent"] != "equipo~operator@example.test" {
141 t.Fatal("missing disclosed receipt", r)
142 }
143 got := gitTest(t, f.root, "--git-dir="+f.remote, "rev-parse", "refs/heads/heads/main")
144 if got != f.auth.Candidate.Commit {
145 t.Fatal("wrong qualified commit")
146 }
147 if f.desc.calls != 1 {
148 t.Fatal("description missing")
149 }
150 for _, name := range []string{"default", "repo", "ref", "tags", "candidate", "ticket", "runner", "evidence", "tuple_identity"} {
151 t.Run(name, func(t *testing.T) {
152 f := newFixture(t)
153 d := f.auth.Ticket.Dispatch
154 switch name {
155 case "default":
156 f.auth.Target.DefaultRef = f.auth.Target.Ref
157 case "repo":
158 f.auth.Target.Repository = "forged/repo"
159 case "ref":
160 f.auth.Target.Ref = "other"
161 case "tuple_identity":
162 f.auth.Publication.Isolation.ObservedTuples[0].ProviderVersion = ""
163 raw, _ := json.Marshal(f.auth.Publication)
164 f.auth.Ticket.Dispatch.Payload, f.auth.Ticket.Dispatch.Hash, _ = Canonical(raw)
165 d = f.auth.Ticket.Dispatch
166 case "tags":
167 f.auth.Target.Ref = "refs/tags/x"
168 case "candidate":
169 f.auth.Candidate.Commit = strings.Repeat("b", 40)
170 case "ticket":
171 f.auth.Ticket.Incarnation++
172 case "runner":
173 f.auth.Ticket.Handle.Runner = "other"
174 case "evidence":
175 f.auth.Publication.Description = ""
176 }
177 if _, err := f.p.Execute(ctx, d); err == nil {
178 t.Fatal("invalid publication accepted")
179 }
180 if f.pushes != 0 {
181 t.Fatal("invalid publication reached Git push")
182 }
183 })
184 }
185}
186func TestPublishExactEvidence(t *testing.T) {
187 f := newFixture(t)
188 f.desc.before = func() {
189 if f.pushes != 0 {
190 t.Fatal("description must precede push")
191 }
192 }
193 _, err := f.p.Execute(ctx, f.auth.Ticket.Dispatch)
194 must(t, err)
195 if !strings.Contains(f.desc.value.Body, "unconfined") || f.desc.value.Digest != f.auth.Publication.DescriptionHash {
196 t.Fatal("lost immutable label")
197 }
198 t.Run("remote_first", func(t *testing.T) {
199 f := newFixture(t)
200 f.desc.requiresRef = true
201 f.desc.fail = true
202 if _, e := f.p.Execute(ctx, f.auth.Ticket.Dispatch); e == nil {
203 t.Fatal("pushed ref without description delivered success")
204 }
205 if f.pushes != 1 {
206 t.Fatal("no push window exercised")
207 }
208 r, e := f.p.Reconcile(ctx, f.auth.Ticket.Dispatch)
209 if e == nil && r.Receipt != nil {
210 t.Fatal("unconfirmed description reconciled success")
211 }
212 f.desc.fail = false
213 r, e = f.p.Reconcile(ctx, f.auth.Ticket.Dispatch)
214 must(t, e)
215 if r.Receipt == nil || f.pushes != 1 {
216 t.Fatal("description recovery duplicated push")
217 }
218 })
219}
220func TestPublishLostReceipt(t *testing.T) {
221 f := newFixture(t)
222 _, err := f.p.Execute(ctx, f.auth.Ticket.Dispatch)
223 must(t, err)
224 for i := 0; i < 2; i++ {
225 _, err = f.p.Execute(ctx, f.auth.Ticket.Dispatch)
226 must(t, err)
227 }
228 if f.pushes != 1 {
229 t.Fatal("duplicate dispatch")
230 }
231 r, err := f.p.Reconcile(ctx, f.auth.Ticket.Dispatch)
232 must(t, err)
233 if r.Receipt == nil {
234 t.Fatal("receipt lost")
235 }
236 gitTest(t, f.root, "--git-dir="+f.remote, "update-ref", "refs/heads/heads/main", f.auth.Candidate.BaseCommit)
237 if _, err = f.p.Reconcile(ctx, f.auth.Ticket.Dispatch); !errors.Is(err, team.ErrConflict) {
238 t.Fatal("remote mismatch class", err)
239 }
240 must(t, os.Rename(f.remote, f.remote+"-hidden"))
241 r, err = f.p.Reconcile(ctx, f.auth.Ticket.Dispatch)
242 if !errors.Is(err, team.ErrUncertain) || r.Definitive {
243 t.Fatal("query failure became absence")
244 }
245}
246func TestPublishCredentialIsolation(t *testing.T) {
247 f := newFixture(t)
248 check := hostileGitEnvironment(t, f)
249 _, err := f.p.Execute(ctx, f.auth.Ticket.Dispatch)
250 must(t, err)
251 check()
252 must(t, filepath.WalkDir(f.p.cfg.Root, func(path string, d os.DirEntry, e error) error {
253 if e != nil {
254 return e
255 }
256 if !d.IsDir() {
257 b, e := os.ReadFile(path)
258 if e != nil {
259 return e
260 }
261 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"))) {
262 t.Fatal("credential persisted", path)
263 }
264 }
265 return nil
266 }))
267}
268func TestPublishCancelRace(t *testing.T) {
269 f := newFixture(t)
270 f.cancelled = true
271 if _, e := f.p.Execute(ctx, f.auth.Ticket.Dispatch); e == nil || f.pushes != 0 {
272 t.Fatal("cancelled dispatch pushed")
273 }
274 f.cancelled = false
275 f.desc.requiresRef = true
276 f.desc.before = func() { f.cancelled = true }
277 _, e := f.p.Execute(ctx, f.auth.Ticket.Dispatch)
278 must(t, e)
279 r, e := f.p.Reconcile(ctx, f.auth.Ticket.Dispatch)
280 must(t, e)
281 if r.Receipt == nil || f.pushes != 1 {
282 t.Fatal("in-flight cancellation lost publication")
283 }
284 if gitTest(t, f.root, "--git-dir="+f.remote, "rev-parse", "refs/heads/heads/main") != f.auth.Candidate.Commit {
285 t.Fatal("cancel deleted branch")
286 }
287}
288
289func TestPublishLostPushReply(t *testing.T) {
290 f := newFixture(t)
291 seen := filepath.Join(f.root, "seen")
292 receiver := filepath.Join(f.root, "receive")
293 must(t, os.WriteFile(receiver, []byte("#!/bin/sh\nexec /usr/bin/env -i PATH=/usr/bin:/bin /usr/bin/git receive-pack \"$@\"\n"), 0700))
294 f.p.localReceivePack = receiver
295 hook := filepath.Join(f.remote, "hooks", "pre-receive")
296 must(t, os.MkdirAll(filepath.Dir(hook), 0700))
297 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))
298 wrapper := filepath.Join(f.root, "git-lost")
299 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))
300 f.p.cfg.GitPath = wrapper
301 if _, e := f.p.Execute(ctx, f.auth.Ticket.Dispatch); e == nil {
302 t.Fatal("lost push reply became success")
303 }
304 observed, err := os.ReadFile(seen)
305 must(t, err)
306 if strings.TrimSpace(string(observed)) != f.auth.Candidate.Commit+" refs/heads/heads/main" {
307 t.Fatal("receive hook missed exact commit", string(observed))
308 }
309 restarted, e := newPublisher(f.p.cfg, f.p.localRemote)
310 must(t, e)
311 restarted.beforePush = func() { t.Fatal("restart pushed twice") }
312 r, e := restarted.Reconcile(ctx, f.auth.Ticket.Dispatch)
313 must(t, e)
314 if r.Receipt == nil || r.Receipt.Fields["head"] != f.auth.Candidate.Commit {
315 t.Fatal("lost exact commit receipt")
316 }
317 _, e = restarted.Execute(ctx, f.auth.Ticket.Dispatch)
318 must(t, e)
319}
320
321func TestPublishOccupiedRef(t *testing.T) {
322 f := newFixture(t)
323 gitTest(t, f.root, "--git-dir="+f.remote, "fetch", f.source, f.auth.Candidate.BaseCommit)
324 gitTest(t, f.root, "--git-dir="+f.remote, "update-ref", "refs/heads/heads/main", f.auth.Candidate.BaseCommit)
325 if _, e := f.p.Execute(ctx, f.auth.Ticket.Dispatch); !errors.Is(e, team.ErrConflict) {
326 t.Fatal("occupied ref class", e)
327 }
328 if got := gitTest(t, f.root, "--git-dir="+f.remote, "rev-parse", "refs/heads/heads/main"); got != f.auth.Candidate.BaseCommit {
329 t.Fatal("absence lease did not protect existing branch")
330 }
331 if _, e := f.p.Reconcile(ctx, f.auth.Ticket.Dispatch); !errors.Is(e, team.ErrNotDispatched) {
332 t.Fatal("unstarted occupied ref class", e)
333 }
334}
335
336func TestPublishDeadlineAndPrePushAuthority(t *testing.T) {
337 for _, name := range []string{"expired", "cancel_during_description", "expired_during_export", "changed_local_objects"} {
338 t.Run(name, func(t *testing.T) {
339 f := newFixture(t)
340 switch name {
341 case "expired":
342 f.p.cfg.Clock = func() time.Time { return f.auth.Ticket.ExpiresAt }
343 case "cancel_during_description":
344 f.desc.before = func() { f.cancelled = true }
345 case "expired_during_export":
346 original := f.p.cfg.Export
347 f.p.cfg.Export = func(ctx context.Context, c team.GitCandidate, dir string) error {
348 e := original(ctx, c, dir)
349 f.p.cfg.Clock = func() time.Time { return f.auth.Ticket.ExpiresAt }
350 return e
351 }
352 case "changed_local_objects":
353 f.auth.Candidate.Tree = strings.Repeat("c", 40)
354 f.auth.Publication.CandidateHash = CanonicalHash(f.auth.Candidate)
355 raw, _ := json.Marshal(f.auth.Publication)
356 f.auth.Ticket.Dispatch.Payload, f.auth.Ticket.Dispatch.Hash, _ = Canonical(raw)
357 }
358 if _, e := f.p.Execute(ctx, f.auth.Ticket.Dispatch); e == nil || f.pushes != 0 {
359 t.Fatal("stale authority or objects reached push")
360 }
361 })
362 }
363}
364
365func TestPublishOccupiedRefKeepsDescription(t *testing.T) {
366 f := newFixture(t)
367 gitTest(t, f.root, "--git-dir="+f.remote, "fetch", f.source, f.auth.Candidate.BaseCommit)
368 gitTest(t, f.root, "--git-dir="+f.remote, "update-ref", "refs/heads/heads/main", f.auth.Candidate.BaseCommit)
369 if _, e := f.p.Execute(ctx, f.auth.Ticket.Dispatch); e == nil {
370 t.Fatal("existing branch accepted")
371 }
372 if f.desc.calls != 0 {
373 t.Fatal("other commit description overwritten")
374 }
375}
376
377func TestPublishAbsentLeaseRace(t *testing.T) {
378 f := newFixture(t)
379 f.p.beforePush = func() {
380 gitTest(t, f.root, "--git-dir="+f.remote, "fetch", f.source, f.auth.Candidate.BaseCommit)
381 gitTest(t, f.root, "--git-dir="+f.remote, "update-ref", "refs/heads/heads/main", f.auth.Candidate.BaseCommit)
382 }
383 if _, e := f.p.Execute(ctx, f.auth.Ticket.Dispatch); e == nil {
384 t.Fatal("racing branch replaced")
385 }
386 if got := gitTest(t, f.root, "--git-dir="+f.remote, "rev-parse", "refs/heads/heads/main"); got != f.auth.Candidate.BaseCommit {
387 t.Fatal("absence lease failed during race")
388 }
389}
390
391func TestPublishDescriptionIdentity(t *testing.T) {
392 t.Run("readback", func(t *testing.T) {
393 f := newFixture(t)
394 f.desc.wrongRead = true
395 if _, e := f.p.Execute(ctx, f.auth.Ticket.Dispatch); e == nil || f.pushes != 0 {
396 t.Fatal("wrong description attribution confirmed")
397 }
398 })
399 t.Run("lost_description_reply", func(t *testing.T) {
400 f := newFixture(t)
401 f.desc.requiresRef = true
402 f.desc.lostSet = true
403 if _, e := f.p.Execute(ctx, f.auth.Ticket.Dispatch); e != nil {
404 t.Fatal("GET failed to confirm lost description reply", e)
405 }
406 r, e := f.p.Reconcile(ctx, f.auth.Ticket.Dispatch)
407 must(t, e)
408 if r.Receipt == nil || f.pushes != 1 || f.desc.calls != 1 {
409 t.Fatal("lost label or duplicated effect")
410 }
411 })
412}
413
414func TestPublishLostReceiptNoRedispatch(t *testing.T) {
415 f := newFixture(t)
416 _, err := f.p.Execute(ctx, f.auth.Ticket.Dispatch)
417 must(t, err)
418 gitTest(t, f.root, "--git-dir="+f.remote, "update-ref", "-d", "refs/heads/heads/main")
419 if _, err = f.p.Execute(ctx, f.auth.Ticket.Dispatch); err == nil || f.pushes != 1 {
420 t.Fatal("missing visibility caused redispatch")
421 }
422}
423
424func TestPublishEvidenceAndCredentialGuards(t *testing.T) {
425 for _, name := range []string{"description", "digest", "taint", "acknowledgement", "tuple", "tuple_identity", "tags", "person", "http", "foreign_remote", "header", "git_header", "git_missing"} {
426 t.Run(name, func(t *testing.T) {
427 f := newFixture(t)
428 switch name {
429 case "description":
430 f.auth.Publication.Description = ""
431 f.auth.Publication.DescriptionHash = Digest(nil)
432 case "digest":
433 f.auth.Publication.DescriptionHash = strings.Repeat("a", 64)
434 case "taint":
435 f.auth.Publication.Description = `{"label":"confined"}`
436 f.auth.Publication.DescriptionHash = Digest([]byte(f.auth.Publication.Description))
437 case "acknowledgement":
438 f.auth.Publication.Isolation.AcknowledgementIDs = nil
439 case "tuple":
440 f.auth.Publication.Isolation.ObservedTuples = nil
441 case "tuple_identity":
442 f.auth.Publication.Isolation.ObservedTuples[0].ProviderVersion = ""
443 case "tags":
444 f.auth.Target.Ref = "refs/tags/tag"
445 f.auth.Publication.Ref = f.auth.Target.Ref
446 default:
447 original := f.p.cfg.Credential
448 f.p.cfg.Credential = func(ctx context.Context, r string) (Credential, error) {
449 c, e := original(ctx, r)
450 switch name {
451 case "person":
452 c.Agent = "person@example.test"
453 case "http":
454 c.Remote = "http://amadan.net/example/repo.git"
455 case "foreign_remote":
456 c.Remote = "https://amadan.net/foreign/repo.git"
457 case "header":
458 c.Bearer = "token\r\nHeader: value"
459 case "git_header":
460 c.GitPassword = "git-canary\r\nHeader: value"
461 case "git_missing":
462 c.GitPassword = ""
463 }
464 return c, e
465 }
466 }
467 raw, _ := json.Marshal(f.auth.Publication)
468 f.auth.Ticket.Dispatch.Payload, f.auth.Ticket.Dispatch.Hash, _ = Canonical(raw)
469 if _, e := f.p.Execute(ctx, f.auth.Ticket.Dispatch); e == nil || f.pushes != 0 {
470 t.Fatal("invalid evidence or credential reached push")
471 }
472 })
473 }
474}
475
476func TestPublishCanonicalRepository(t *testing.T) {
477 f := newFixture(t)
478 f.auth.Target.Repository = "amadan.net/example/repo"
479 f.auth.Candidate.Repository = f.auth.Target.Repository
480 f.auth.Publication.Repository = f.auth.Target.Repository
481 f.auth.Publication.CandidateHash = CanonicalHash(f.auth.Candidate)
482 raw, _ := json.Marshal(f.auth.Publication)
483 f.auth.Ticket.Dispatch.Payload, f.auth.Ticket.Dispatch.Hash, _ = Canonical(raw)
484 f.p.cfg.Credential = func(context.Context, string) (Credential, error) {
485 return Credential{Remote: "https://amadan.net/example/repo", Agent: "equipo~operator@example.test", Bearer: "agent-canary", GitPassword: "git-canary"}, nil
486 }
487 if _, err := f.p.Execute(ctx, f.auth.Ticket.Dispatch); err != nil {
488 t.Fatal("saved canonical project repository rejected", err)
489 }
490}
491
492func TestPublishCredentialIsolationHTTPS(t *testing.T) {
493 f := newFixture(t)
494 t.Setenv("PERSON_SECRET", "person-canary")
495 spy := filepath.Join(f.root, "git-spy")
496 log := filepath.Join(f.root, "git-observations")
497 script := fmt.Sprintf(`#!/usr/bin/python3
498import os,sys,json
499args=sys.argv[1:]
500with open(%q,'a') as out:
501 out.write(json.dumps({'args':args,'env':dict(os.environ)})+'\n')
502if 'https://amadan.net/example/repo' in args:
503 args[args.index('https://amadan.net/example/repo')]=%q
504 args=['-c','protocol.file.allow=always']+args
505os.execve('/usr/bin/git',['/usr/bin/git']+args,dict(os.environ))
506`, log, f.remote)
507 must(t, os.WriteFile(spy, []byte(script), 0700))
508 f.p.localRemote = nil
509 f.p.cfg.GitPath = spy
510 _, err := f.p.Execute(ctx, f.auth.Ticket.Dispatch)
511 must(t, err)
512 raw, err := os.ReadFile(log)
513 must(t, err)
514 pushes := 0
515 remoteCalls := 0
516 for _, line := range strings.Split(strings.TrimSpace(string(raw)), "\n") {
517 var row struct {
518 Args []string
519 Env map[string]string
520 }
521 must(t, json.Unmarshal([]byte(line), &row))
522 args := strings.Join(row.Args, " ")
523 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"] != "" {
524 t.Fatal("credential escaped allowed environment")
525 }
526 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" {
527 t.Fatal("publication lost detached helper guards")
528 }
529 remote := strings.Contains(args, "https://amadan.net/example/repo")
530 if remote {
531 remoteCalls++
532 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")) {
533 t.Fatal("runner credential missing")
534 }
535 } else if strings.Contains(fmt.Sprint(row.Env), "git-canary") || strings.Contains(fmt.Sprint(row.Env), base64.StdEncoding.EncodeToString([]byte("x:git-canary"))) {
536 t.Fatal("credential exposed to local Git")
537 }
538 if strings.Contains(args, " push ") {
539 pushes++
540 }
541 }
542 if pushes != 1 || remoteCalls < 3 {
543 t.Fatal("HTTPS command path not exercised", pushes, remoteCalls)
544 }
545}
546
547func marshalPublication(t *testing.T, p team.Publication) []byte {
548 t.Helper()
549 b, err := json.Marshal(p)
550 must(t, err)
551 return b
552}
553
554func TestTrialPublisherRequiresBothLabels(t *testing.T) {
555 f := newFixture(t)
556 f.auth.Publication.Isolation.Status = "unconfined"
557 f.auth.Publication.Isolation.Trial = &team.TrialSnapshot{Label: "supervised trial", AcknowledgementIDs: []string{"trial"}, UnverifiedChecks: team.TrialChecks(), ProviderVersionSource: "observed_locally"}
558 for _, label := range []string{"unconfined", "supervised trial", "supervised trial unconfined"} {
559 f.auth.Publication.Description = label
560 f.auth.Publication.DescriptionHash = Digest([]byte(label))
561 raw, _ := json.Marshal(f.auth.Publication)
562 raw, hash, _ := Canonical(raw)
563 f.auth.Ticket.Dispatch.Payload, f.auth.Ticket.Dispatch.Hash = raw, hash
564 err := f.p.validate(f.auth, f.auth.Ticket.Dispatch)
565 if (err == nil) != (label == "supervised trial unconfined") {
566 t.Fatalf("%s: %v", label, err)
567 }
568 }
569}
570
571// The fake writer only writes the in-memory response served by loopback GET.
572type descriptionWriterFunc func(context.Context, Credential, Description) error
573
574func (f descriptionWriterFunc) Set(ctx context.Context, c Credential, d Description) error {
575 return f(ctx, c, d)
576}
577
578func TestPublishDescriptionRecovery(t *testing.T) {
579 for _, mode := range []string{"not_dispatched", "lost_reply", "delayed_readback", "empty", "trimmed", "wrong_digest", "wrong_ref", "wrong_repo", "wrong_body", "wrong_agent"} {
580 t.Run(mode, func(t *testing.T) {
581 f := newFixture(t)
582 f.auth.Publication.Description = " unconfined; approved beyond profile\n"
583 f.auth.Publication.DescriptionHash = Digest([]byte(f.auth.Publication.Description))
584 raw, _ := json.Marshal(f.auth.Publication)
585 f.auth.Ticket.Dispatch.Payload, f.auth.Ticket.Dispatch.Hash, _ = Canonical(raw)
586 var mu sync.Mutex
587 body := ""
588 writes, reads, calls := 0, 0, 0
589 f.p.beforePush = func() {
590 saved, err := f.p.load(f.auth.Ticket.Dispatch)
591 must(t, err)
592 if saved.Description.Body != f.auth.Publication.Description || saved.DescriptionAttempted {
593 t.Fatal("missing pending description before push")
594 }
595 f.pushes++
596 }
597 visible := mode != "delayed_readback"
598 client := descriptionServer(t, func(w http.ResponseWriter, r *http.Request) {
599 mu.Lock()
600 defer mu.Unlock()
601 reads++
602 if r.URL.EscapedPath() != "/api/v1/repos/example/repo/branches/heads%2Fmain/description" {
603 t.Error("ref qualified twice or not escaped")
604 }
605 if body == "" || !visible || mode == "empty" {
606 _ = json.NewEncoder(w).Encode(map[string]any{"empty": true})
607 return
608 }
609 _ = json.NewEncoder(w).Encode(descriptionResponse(body, "equipo~operator@example.test"))
610 })
611 transport := NewDescriptionTransport(client, descriptionWriterFunc(func(_ context.Context, c Credential, d Description) error {
612 mu.Lock()
613 defer mu.Unlock()
614 calls++
615 if f.pushes != 1 || gitTest(t, f.root, "--git-dir="+f.remote, "rev-parse", "refs/heads/heads/main") != f.auth.Candidate.Commit {
616 t.Fatal("describe before exact ref exists")
617 }
618 saved, err := f.p.load(f.auth.Ticket.Dispatch)
619 must(t, err)
620 if saved.Description.Body != d.Body || !saved.DescriptionAttempted {
621 t.Fatal("description intent not durable before write")
622 }
623 if mode == "not_dispatched" && calls == 1 {
624 return fmt.Errorf("local setup: %w", team.ErrNotDispatched)
625 }
626 writes++
627 body = d.Body
628 if mode == "trimmed" {
629 body = strings.TrimSpace(body)
630 }
631 return team.ErrUncertain // Server stored it, command reply was lost.
632 }))
633 if transport.BeforePush() {
634 t.Fatal("production transport describes before push")
635 }
636 f.p.cfg.Description = transport
637 if strings.HasPrefix(mode, "wrong_") {
638 f.p.cfg.Description = changedDescription{DescriptionTransport: transport, field: mode}
639 }
640 receipt, err := f.p.Execute(ctx, f.auth.Ticket.Dispatch)
641 if mode == "lost_reply" {
642 must(t, err)
643 if receipt.Outcome != team.OutcomeSuccess {
644 t.Fatal("readback did not confirm lost reply")
645 }
646 } else if err == nil {
647 t.Fatal("unconfirmed description delivered success")
648 }
649 if mode == "not_dispatched" {
650 saved, e := f.p.load(f.auth.Ticket.Dispatch)
651 must(t, e)
652 if saved.DescriptionAttempted {
653 t.Fatal("never-sent description latched as attempted")
654 }
655 }
656 mu.Lock()
657 visible = true
658 mu.Unlock()
659 // Reconstruct the publisher to exercise the durable journal after a restart.
660 restarted, err := newPublisher(f.p.cfg, f.p.localRemote)
661 must(t, err)
662 restarted.beforePush = f.p.beforePush
663 result, err := restarted.Reconcile(ctx, f.auth.Ticket.Dispatch)
664 if mode == "lost_reply" || mode == "delayed_readback" || mode == "not_dispatched" {
665 must(t, err)
666 if result.Receipt == nil || result.Receipt.Fields["description_hash"] != f.auth.Publication.DescriptionHash {
667 t.Fatal("lost body digest")
668 }
669 } else if err == nil || result.Receipt != nil {
670 t.Fatal("unconfirmed description reconciled success")
671 }
672 _, _ = restarted.Execute(ctx, f.auth.Ticket.Dispatch)
673 if mode == "not_dispatched" && calls != 2 {
674 t.Fatal("never-sent description not retried exactly once", calls)
675 }
676 if writes != 1 || f.pushes != 1 || reads < 3 {
677 t.Fatal("duplicate write/push or skipped GET", writes, f.pushes, reads)
678 }
679 })
680 }
681}
682
683type changedDescription struct {
684 DescriptionTransport
685 field string
686}
687
688func (c changedDescription) Read(ctx context.Context, cred Credential, repo, ref string) (Description, error) {
689 d, err := c.DescriptionTransport.Read(ctx, cred, repo, ref)
690 switch c.field {
691 case "wrong_digest":
692 d.Digest = strings.Repeat("0", 64)
693 case "wrong_ref":
694 d.Ref = "another/ref"
695 case "wrong_repo":
696 d.Repository = "amadan.net/other/repo"
697 case "wrong_body":
698 d.Body = strings.TrimSpace(d.Body)
699 case "wrong_agent":
700 d.Agent = "another~operator@example.test"
701 }
702 return d, err
703}
704
705func TestPublishDescriptionReadFailureDoesNotWrite(t *testing.T) {
706 f := newFixture(t)
707 writes := 0
708 client := descriptionServer(t, func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusUnauthorized) })
709 f.p.cfg.Description = NewDescriptionTransport(client, descriptionWriterFunc(func(context.Context, Credential, Description) error { writes++; return team.ErrUncertain }))
710 _, err := f.p.Execute(ctx, f.auth.Ticket.Dispatch)
711 if err == nil || f.pushes != 1 || writes != 0 {
712 t.Fatal("read failure caused a write or success", err, writes)
713 }
714}
715