gunk-dev/the-valley

main_test.go

sourcebc331c79617cmain's published tip history
18.8 KiB
1package main
2
3import (
4 "bytes"
5 "context"
6 "fmt"
7 "os"
8 "os/exec"
9 "path/filepath"
10 "strings"
11 "testing"
12 "time"
13
14 "the-valley/change"
15 "the-valley/composed"
16 "the-valley/rebase"
17)
18
19// hookEnv names the rendered pre-receive hook restack-unit wires origin
20// with (nix/checks/restack.nix). Without it, the tests that need the hook
21// are skipped.
22const hookEnv = "VALLEY_RESTACK_TEST_HOOK"
23
24var idA = strings.Repeat("k", 32)
25
26// fixture is a bare origin and a clone of it to work in. The clone's git
27// commits as an author of its own, named in its environment, whatever the
28// test's process inherits.
29type fixture struct {
30 t *testing.T
31 origin, work string
32 env []string
33}
34
35func newFixture(t *testing.T, hook string) *fixture {
36 t.Helper()
37 dir := t.TempDir()
38 f := &fixture{t: t, origin: filepath.Join(dir, "origin.git"), work: filepath.Join(dir, "work")}
39 f.env = append(os.Environ(), "HOME="+dir, "GIT_CONFIG_NOSYSTEM=1", "GIT_CONFIG_GLOBAL=/dev/null",
40 "GIT_AUTHOR_NAME=A. Author", "GIT_AUTHOR_EMAIL=author@example.invalid",
41 "GIT_COMMITTER_NAME=A. Author", "GIT_COMMITTER_EMAIL=author@example.invalid")
42 f.run(dir, "init", "--quiet", "--bare", "--initial-branch=main", f.origin)
43 if hook != "" {
44 data, err := os.ReadFile(hook)
45 if err != nil {
46 t.Fatal(err)
47 }
48 if err := os.WriteFile(filepath.Join(f.origin, "hooks", "pre-receive"), data, 0o755); err != nil {
49 t.Fatal(err)
50 }
51 }
52 f.run(dir, "clone", "--quiet", f.origin, f.work)
53 f.git("checkout", "--quiet", "-b", "main")
54 f.commit("base", "base.txt")
55 f.git("push", "--quiet", "origin", "main")
56 return f
57}
58
59func (f *fixture) run(dir string, args ...string) string {
60 f.t.Helper()
61 cmd := exec.Command("git", args...)
62 cmd.Dir, cmd.Env = dir, f.env
63 out, err := cmd.CombinedOutput()
64 if err != nil {
65 f.t.Fatalf("git %s: %v\n%s", strings.Join(args, " "), err, out)
66 }
67 return strings.TrimSpace(string(out))
68}
69
70func (f *fixture) git(args ...string) string { f.t.Helper(); return f.run(f.work, args...) }
71
72func (f *fixture) commit(subject, file string) string {
73 f.t.Helper()
74 if err := os.WriteFile(filepath.Join(f.work, file), []byte(subject+"\n"), 0o644); err != nil {
75 f.t.Fatal(err)
76 }
77 f.git("add", file)
78 f.git("commit", "--quiet", "-m", subject)
79 return f.git("rev-parse", "HEAD")
80}
81
82// as is the clone's git pushing as a principal.
83func (f *fixture) as(principal string) rebase.Git {
84 return rebase.Git{Dir: f.work, Env: append(append([]string(nil), f.env...), "VALLEY_PRINCIPAL="+principal)}
85}
86
87// readied pushes a branch off main with one commit, and readies it as a
88// change owned by owner, under a title unlike the commit's subject.
89// It returns the head.
90func (f *fixture) readied(owner, branch, title string) string {
91 f.t.Helper()
92 f.git("checkout", "--quiet", "-b", branch, "main")
93 head := f.commit("layer "+branch, branch+".txt")
94 f.git("push", "--quiet", "origin", branch)
95 r := &change.Record{
96 Schema: change.Schema, ChangeID: idA, Target: rebase.Target, Owner: owner, State: change.Ready, Seq: 1, Active: 1,
97 Versions: []change.Version{{N: 1, Head: change.HeadPrefix + head, Title: title, Branch: branch, Uploader: owner}},
98 }
99 ctx := context.Background()
100 g := f.as(owner)
101 commit, err := rebase.WriteRecord(ctx, g, r, "test record", head)
102 if err != nil {
103 f.t.Fatal(err)
104 }
105 if w := rebase.PushRecord(ctx, g, idA, "", commit); w.Push != rebase.Pushed {
106 f.t.Fatalf("the record of %s was not pushed: %+v", idA, w)
107 }
108 return head
109}
110
111// moveMain moves origin's main on by a commit of its own.
112func (f *fixture) moveMain() {
113 f.t.Helper()
114 f.git("checkout", "--quiet", "main")
115 f.commit("main moves on", "main.txt")
116 f.git("push", "--quiet", "origin", "main")
117}
118
119// at is a ref on origin, or "" for none.
120func (f *fixture) at(ref string) string {
121 cmd := exec.Command("git", "rev-parse", "--verify", "--quiet", ref)
122 cmd.Dir, cmd.Env = f.origin, f.env
123 out, _ := cmd.Output()
124 return strings.TrimSpace(string(out))
125}
126
127// withoutIdentity leaves the test's process with no identity variable,
128// as a service may run.
129func withoutIdentity(t *testing.T) {
130 t.Helper()
131 for _, name := range []string{"GIT_AUTHOR_NAME", "GIT_AUTHOR_EMAIL", "GIT_AUTHOR_DATE",
132 "GIT_COMMITTER_NAME", "GIT_COMMITTER_EMAIL", "GIT_COMMITTER_DATE", "EMAIL"} {
133 t.Setenv(name, "")
134 os.Unsetenv(name)
135 }
136}
137
138// restacked reads origin into the restacker's scratch repository, rebases
139// the change's family there, and pushes its branch. It returns the
140// family and the prepared head of its bottom layer.
141func restacked(t *testing.T, g rebase.Git) (*rebase.Family, string) {
142 t.Helper()
143 ctx := context.Background()
144 s, err := rebase.ReadSnapshot(ctx, g, rebase.Verifier{})
145 if err != nil {
146 t.Fatal(err)
147 }
148 fam, err := rebase.Capture(s, rebase.Selection{ID: idA})
149 if err != nil {
150 t.Fatal(err)
151 }
152 p, err := rebase.Prepare(ctx, g, fam)
153 if err != nil {
154 t.Fatalf("prepare: %v", err)
155 }
156 defer p.Release(ctx, g)
157 pub, err := rebase.Publish(ctx, g, p)
158 if err != nil || pub.Push != rebase.Pushed {
159 t.Fatalf("publish: %v %v %+v", err, pub.Push, pub.Refused)
160 }
161 return fam, p.Heads[fam.Bottom()]
162}
163
164func logged(t *testing.T, g rebase.Git, format, commit string) string {
165 t.Helper()
166 out, err := gitOut(context.Background(), g, "log", "-1", "--format="+format, commit)
167 if err != nil {
168 t.Fatal(err)
169 }
170 return strings.TrimSpace(out)
171}
172
173// With no identity variable in its environment, the restacker commits
174// under the identity its flags give: it is the committer of each commit
175// it rebases, whose author stays the change's, and the author and the
176// committer of each record commit. An identity in the environment is not
177// inherited.
178func TestScratchCommitsAsTheController(t *testing.T) {
179 withoutIdentity(t)
180 f := newFixture(t, "")
181 f.readied("author", "a", "A title")
182 f.moveMain()
183 c := config{repo: f.origin, state: t.TempDir(), principal: "restacker",
184 commitName: "The Restacker", commitEmail: "restacker@example.invalid"}
185 ctx := context.Background()
186 g, err := scratchRepo(ctx, c)
187 if err != nil {
188 t.Fatal(err)
189 }
190
191 fam, head := restacked(t, g)
192 const restacker = "The Restacker <restacker@example.invalid>"
193 if got := logged(t, g, "%an <%ae>|%cn <%ce>", head); got != "A. Author <author@example.invalid>|"+restacker {
194 t.Errorf("the rebased commit is authored and committed as %q", got)
195 }
196 p, err := rebase.BuildRestack(ctx, g, rebase.RestackAppend{ID: idA, Head: head, IfActive: fam.Bottom().Head, Principal: "restacker"})
197 if err != nil {
198 t.Fatal(err)
199 }
200 if got := logged(t, g, "%an <%ae>|%cn <%ce>", p.Commit); got != restacker+"|"+restacker {
201 t.Errorf("the record commit is authored and committed as %q", got)
202 }
203
204 t.Setenv("GIT_AUTHOR_NAME", "Inherited")
205 t.Setenv("GIT_COMMITTER_EMAIL", "inherited@example.invalid")
206 t.Setenv("EMAIL", "inherited@example.invalid")
207 g, err = scratchRepo(ctx, c)
208 if err != nil {
209 t.Fatal(err)
210 }
211 tree, err := gitOut(ctx, g, "mktree")
212 if err != nil {
213 t.Fatal(err)
214 }
215 commit, err := gitOut(ctx, g, "commit-tree", strings.TrimSpace(tree), "-m", "inherited")
216 if err != nil {
217 t.Fatal(err)
218 }
219 if got := logged(t, g, "%an <%ae>|%cn <%ce>", strings.TrimSpace(commit)); got != restacker+"|"+restacker {
220 t.Errorf("with an identity in the environment, a commit is authored and committed as %q", got)
221 }
222}
223
224// Configuration the environment injects reaches no git the restacker
225// runs. An author and a committer given in GIT_CONFIG_COUNT entries and in
226// GIT_CONFIG_PARAMETERS would beat the scratch repository's user.name and
227// user.email. They are not inherited: the restacker is the committer of
228// each commit it rebases, whose author stays the change's, and the author
229// and the committer of each record commit.
230func TestInheritedConfigurationDoesNotCommit(t *testing.T) {
231 withoutIdentity(t)
232 f := newFixture(t, "")
233 f.readied("author", "a", "A title")
234 f.moveMain()
235 for name, value := range map[string]string{
236 "GIT_CONFIG_COUNT": "2",
237 "GIT_CONFIG_KEY_0": "author.name", "GIT_CONFIG_VALUE_0": "Inherited",
238 "GIT_CONFIG_KEY_1": "author.email", "GIT_CONFIG_VALUE_1": "inherited@example.invalid",
239 "GIT_CONFIG_PARAMETERS": "'committer.name'='Inherited' 'committer.email'='inherited@example.invalid'",
240 } {
241 t.Setenv(name, value)
242 }
243 c := config{repo: f.origin, state: t.TempDir(), principal: "restacker",
244 commitName: "The Restacker", commitEmail: "restacker@example.invalid"}
245 ctx := context.Background()
246 g, err := scratchRepo(ctx, c)
247 if err != nil {
248 t.Fatal(err)
249 }
250
251 fam, head := restacked(t, g)
252 const restacker = "The Restacker <restacker@example.invalid>"
253 if got := logged(t, g, "%an <%ae>|%cn <%ce>", head); got != "A. Author <author@example.invalid>|"+restacker {
254 t.Errorf("the rebased commit is authored and committed as %q", got)
255 }
256 p, err := rebase.BuildRestack(ctx, g, rebase.RestackAppend{ID: idA, Head: head, IfActive: fam.Bottom().Head, Principal: "restacker"})
257 if err != nil {
258 t.Fatal(err)
259 }
260 if got := logged(t, g, "%an <%ae>|%cn <%ce>", p.Commit); got != restacker+"|"+restacker {
261 t.Errorf("the record commit is authored and committed as %q", got)
262 }
263}
264
265// A pass locks its state directory. A second lock fails at once, saying
266// another pass holds it, and succeeds once the first is let go.
267func TestAPassLocksItsState(t *testing.T) {
268 dir := filepath.Join(t.TempDir(), "state")
269 release, err := lockState(dir)
270 if err != nil {
271 t.Fatal(err)
272 }
273 if _, err := lockState(dir); err == nil || !strings.Contains(err.Error(), "another pass is using the state directory") {
274 t.Fatalf("a second lock while one is held: %v", err)
275 }
276 release()
277 again, err := lockState(dir)
278 if err != nil {
279 t.Fatalf("a lock once the first is let go: %v", err)
280 }
281 again()
282}
283
284// A state directory belongs to the repository, target and principal the
285// first pass used it for, and a pass for any other is refused.
286func TestStateBelongsToOneRepositoryTargetAndPrincipal(t *testing.T) {
287 dir := t.TempDir()
288 first := binding{Repository: "ssh://valley/project.git", Target: "main", Principal: "restacker"}
289 if err := bindState(dir, first); err != nil {
290 t.Fatal(err)
291 }
292 if err := bindState(dir, first); err != nil {
293 t.Fatalf("the same binding again: %v", err)
294 }
295 for _, other := range []binding{
296 {Repository: "ssh://valley/other.git", Target: "main", Principal: "restacker"},
297 {Repository: "ssh://valley/project.git", Target: "main", Principal: "requester"},
298 {Repository: "ssh://valley/project.git", Target: "next", Principal: "restacker"},
299 } {
300 if err := bindState(dir, other); err == nil || !strings.Contains(err.Error(), "give each its own --state") {
301 t.Errorf("a pass for %+v: %v", other, err)
302 }
303 }
304}
305
306// blocker is a script that stands for a program that does not return.
307// The first time it runs, it says it has started, then keeps its output
308// open for a minute and beats while it does: it adds a line to a file
309// every tenth of a second.
310type blocker struct {
311 script, started, beats string
312}
313
314func newBlocker(t *testing.T, script string) *blocker {
315 t.Helper()
316 dir := t.TempDir()
317 b := &blocker{script: script, started: filepath.Join(dir, "started"), beats: filepath.Join(dir, "beats")}
318 body := fmt.Sprintf("#!/bin/sh\n[ -e '%s' ] && exit 0\n: > '%s'\n"+
319 "i=0\nwhile [ $i -lt 600 ]; do echo >> '%s'; sleep 0.1; i=$((i+1)); done\n",
320 b.started, b.started, b.beats)
321 if err := os.WriteFile(script, []byte(body), 0o755); err != nil {
322 t.Fatal(err)
323 }
324 return b
325}
326
327func (b *blocker) wait(t *testing.T) {
328 t.Helper()
329 for deadline := time.Now().Add(30 * time.Second); time.Now().Before(deadline); time.Sleep(20 * time.Millisecond) {
330 if _, err := os.Stat(b.started); err == nil {
331 return
332 }
333 }
334 t.Fatal("the blocker never started")
335}
336
337func (b *blocker) beating() bool {
338 size := func() int64 {
339 fi, err := os.Stat(b.beats)
340 if err != nil {
341 return 0
342 }
343 return fi.Size()
344 }
345 time.Sleep(200 * time.Millisecond)
346 before := size()
347 time.Sleep(time.Second)
348 return size() != before
349}
350
351// bounded runs read under a context with a two-second deadline, and holds
352// that it fails, returns soon after the deadline, and leaves nothing of
353// the blocker it ran into running.
354func bounded(t *testing.T, b *blocker, read func(ctx context.Context) error) {
355 t.Helper()
356 ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
357 defer cancel()
358 start := time.Now()
359 if err := read(ctx); err == nil {
360 t.Fatal("a read that never returned succeeded")
361 }
362 if took := time.Since(start); took > 15*time.Second {
363 t.Errorf("the read took %v, with a deadline of 2s", took)
364 }
365 b.wait(t)
366 if b.beating() {
367 t.Error("what the read started outlived the deadline")
368 }
369}
370
371// Composing the policy ends at the pass's deadline, with the cue that
372// never returned killed.
373func TestPolicyCompositionEndsAtTheDeadline(t *testing.T) {
374 f := newFixture(t, "")
375 floor := t.TempDir()
376 if err := os.WriteFile(filepath.Join(floor, "floor.cue"), []byte("package verification\n"), 0o644); err != nil {
377 t.Fatal(err)
378 }
379 b := newBlocker(t, filepath.Join(t.TempDir(), "cue"))
380 c := config{cue: b.script, schema: filepath.Join(floor, "floor.cue"), floor: composed.Floor{Path: floor}, projectPolicy: "policy/project"}
381 g := rebase.Git{Dir: f.work, Env: f.env}
382 tip := f.git("rev-parse", "HEAD")
383 bounded(t, b, func(ctx context.Context) error {
384 _, err := policyCap(ctx, g, c, tip)
385 return err
386 })
387}
388
389// Reading the floor from the instance repository ends at the pass's
390// deadline, with the ssh that never answered killed: the scratch
391// repository's git reaches origin unattended.
392func TestInstanceReadEndsAtTheDeadline(t *testing.T) {
393 b := newBlocker(t, filepath.Join(t.TempDir(), "ssh"))
394 t.Setenv("GIT_SSH_COMMAND", b.script)
395 c := config{repo: "ssh://valley/project.git", state: t.TempDir(), principal: "restacker",
396 commitName: "The Restacker", commitEmail: "restacker@example.invalid",
397 instanceRepo: "ssh://valley/instance.git", floor: composed.Floor{Ref: "refs/heads/main", Dir: "policy/instance"}}
398 g, err := scratchRepo(context.Background(), c)
399 if err != nil {
400 t.Fatal(err)
401 }
402 bounded(t, b, func(ctx context.Context) error {
403 _, err := policyCap(ctx, g, c, strings.Repeat("0", 40))
404 return err
405 })
406}
407
408// The floor is read at --instance-ref by that exact name. ls-remote
409// matches its pattern against the tail of each name, so for an instance
410// repository with no refs/heads/main it lists
411// refs/heads/refs/heads/main, a branch a pusher can make. That branch is
412// no floor, and the pass finds none.
413func TestTheFloorIsReadAtItsRefByItsExactName(t *testing.T) {
414 f := newFixture(t, "")
415 tip := f.git("rev-parse", "HEAD")
416 if err := os.MkdirAll(filepath.Join(f.work, "policy", "instance"), 0o755); err != nil {
417 t.Fatal(err)
418 }
419 f.commit("package verification", filepath.Join("policy", "instance", "floor.cue"))
420 instance := filepath.Join(t.TempDir(), "instance.git")
421 f.run(f.work, "init", "--quiet", "--bare", instance)
422 f.git("push", "--quiet", instance, "HEAD:refs/heads/refs/heads/main")
423 c := config{repo: f.origin, state: t.TempDir(), principal: "restacker",
424 commitName: "The Restacker", commitEmail: "restacker@example.invalid",
425 instanceRepo: instance, floor: composed.Floor{Ref: "refs/heads/main", Dir: "policy/instance"}}
426 g, err := scratchRepo(context.Background(), c)
427 if err != nil {
428 t.Fatal(err)
429 }
430 _, err = policyCap(context.Background(), g, c, tip)
431 if err == nil || !strings.Contains(err.Error(), "has no refs/heads/main: "+composed.Floorless) {
432 t.Fatalf("with no refs/heads/main, the floor read returned %v", err)
433 }
434}
435
436// Through the host's rendered hook, the restacker principal, which holds
437// the restack grant and not the request grant, adds a restack version to
438// a change another principal owns: the version keeps the active title
439// though its head's subject differs. The hook refuses a version it adds
440// under any other title. It also takes a restack report from the
441// restacker, built and then pushed, and refuses one from the owner, who
442// holds no restack grant.
443func TestRenderedHookTakesTheRestackAppend(t *testing.T) {
444 hook := os.Getenv(hookEnv)
445 if hook == "" {
446 t.Skip(hookEnv + " names no rendered hook; restack-unit supplies one")
447 }
448 withoutIdentity(t)
449 f := newFixture(t, hook)
450 was := f.readied("alice", "a", "A title unlike its commit's subject")
451 f.moveMain()
452 t.Setenv("VALLEY_PRINCIPAL", "restacker")
453 c := config{repo: f.origin, state: t.TempDir(), principal: "restacker",
454 commitName: "The Restacker", commitEmail: "restacker@example.invalid"}
455 ctx := context.Background()
456 g, err := scratchRepo(ctx, c)
457 if err != nil {
458 t.Fatal(err)
459 }
460 var stderr bytes.Buffer
461 g.Stderr = &stderr
462 _, head := restacked(t, g)
463 ref := change.Ref(rebase.Target, idA)
464 old := f.at(ref)
465
466 before, err := rebase.ReadRecord(ctx, g, old)
467 if err != nil {
468 t.Fatal(err)
469 }
470 forged, err := rebase.NextRecord("kkkk", before, change.Version{
471 Head: change.HeadPrefix + head, Title: "A forged title", Branch: "a", Uploader: "restacker",
472 })
473 if err != nil {
474 t.Fatal(err)
475 }
476 commit, err := rebase.WriteRecord(ctx, g, forged, "forged", old, head)
477 if err != nil {
478 t.Fatal(err)
479 }
480 if w := rebase.PushRecord(ctx, g, idA, old, commit); w.Push != rebase.Refused || f.at(ref) != old {
481 t.Fatalf("a restack version under a forged title: %+v", w)
482 }
483 if !strings.Contains(stderr.String(), "under the title of the active one") {
484 t.Errorf("the hook's refusal does not name the title:\n%s", stderr.String())
485 }
486
487 p, err := rebase.BuildRestack(ctx, g, rebase.RestackAppend{ID: idA, Head: head, IfActive: was, Principal: "restacker"})
488 if err != nil {
489 t.Fatal(err)
490 }
491 if ap := p.Push(ctx, g); ap.Err != nil || ap.Version != 2 || f.at(ref) != p.Commit {
492 t.Fatalf("the restack append: %+v\n%s", ap, stderr.String())
493 }
494 if err := rebase.Fetch(ctx, g, f.at(ref)); err != nil {
495 t.Fatal(err)
496 }
497 r, err := rebase.ReadRecord(ctx, g, f.at(ref))
498 if err != nil {
499 t.Fatal(err)
500 }
501 if v := r.ActiveVersion(); v.Title != "A title unlike its commit's subject" || v.Uploader != "restacker" || v.Branch != "a" || r.Owner != "alice" {
502 t.Errorf("the record on origin is %+v", r)
503 }
504
505 read, tip, record := change.HeadPrefix+was, change.HeadPrefix+head, change.HeadPrefix+p.Commit
506 report := &change.RestackReport{
507 Schema: change.RestackSchema, ChangeID: idA, Target: rebase.Target,
508 TargetTip: change.HeadPrefix + f.at("refs/heads/main"), Operation: "test-1", Result: change.RestackComplete,
509 Layers: []change.RestackLayer{{
510 ChangeID: idA, Record: change.HeadPrefix + old, Version: 1, Head: change.HeadPrefix + was,
511 Branch: "a", BranchTip: &read, Published: &change.RestackPublished{Head: tip, Version: &p.Version, Record: &record},
512 }},
513 }
514 alice := f.as("alice")
515 alice.Stderr = &stderr
516 byAlice, err := rebase.WriteReport(ctx, alice, report, rebase.ReportMessage("kkkk", report), "")
517 if err != nil {
518 t.Fatal(err)
519 }
520 if w := rebase.PushReport(ctx, alice, idA, "", byAlice); w.Push != rebase.Refused {
521 t.Errorf("a report from a principal with no restack grant: %+v", w)
522 }
523 byRestacker, err := rebase.WriteReport(ctx, g, report, rebase.ReportMessage("kkkk", report), "")
524 if err != nil {
525 t.Fatal(err)
526 }
527 if w := rebase.PushReport(ctx, g, idA, "", byRestacker); w.Push != rebase.Pushed || f.at(rebase.RestackPrefix+idA) != byRestacker {
528 t.Errorf("a report from the restacker: %+v\n%s", w, stderr.String())
529 }
530}