gunk-dev/the-valley

main_test.go

source5ed515359461main's published tip history
17.4 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 identityVariables {
132 t.Setenv(name, "")
133 os.Unsetenv(name)
134 }
135}
136
137// restacked reads origin into the restacker's scratch repository, rebases
138// the change's family there, and pushes its branch. It returns the
139// family and the prepared head of its bottom layer.
140func restacked(t *testing.T, g rebase.Git) (*rebase.Family, string) {
141 t.Helper()
142 ctx := context.Background()
143 s, err := rebase.ReadSnapshot(ctx, g, rebase.Verifier{})
144 if err != nil {
145 t.Fatal(err)
146 }
147 fam, err := rebase.Capture(s, rebase.Selection{ID: idA})
148 if err != nil {
149 t.Fatal(err)
150 }
151 p, err := rebase.Prepare(ctx, g, fam)
152 if err != nil {
153 t.Fatalf("prepare: %v", err)
154 }
155 defer p.Release(ctx, g)
156 pub, err := rebase.Publish(ctx, g, p)
157 if err != nil || pub.Push != rebase.Pushed {
158 t.Fatalf("publish: %v %v %+v", err, pub.Push, pub.Refused)
159 }
160 return fam, p.Heads[fam.Bottom()]
161}
162
163func logged(t *testing.T, g rebase.Git, format, commit string) string {
164 t.Helper()
165 out, err := gitOut(context.Background(), g, "log", "-1", "--format="+format, commit)
166 if err != nil {
167 t.Fatal(err)
168 }
169 return strings.TrimSpace(out)
170}
171
172// With no identity variable in its environment, the restacker commits
173// under the identity its flags give: it is the committer of each commit
174// it rebases, whose author stays the change's, and the author and the
175// committer of each record commit. An identity in the environment is not
176// inherited.
177func TestScratchCommitsAsTheController(t *testing.T) {
178 withoutIdentity(t)
179 f := newFixture(t, "")
180 f.readied("author", "a", "A title")
181 f.moveMain()
182 c := config{repo: f.origin, state: t.TempDir(), principal: "restacker",
183 commitName: "The Restacker", commitEmail: "restacker@example.invalid"}
184 ctx := context.Background()
185 g, err := scratchRepo(ctx, c)
186 if err != nil {
187 t.Fatal(err)
188 }
189
190 fam, head := restacked(t, g)
191 const restacker = "The Restacker <restacker@example.invalid>"
192 if got := logged(t, g, "%an <%ae>|%cn <%ce>", head); got != "A. Author <author@example.invalid>|"+restacker {
193 t.Errorf("the rebased commit is authored and committed as %q", got)
194 }
195 p, err := rebase.BuildRestack(ctx, g, rebase.RestackAppend{ID: idA, Head: head, IfActive: fam.Bottom().Head, Principal: "restacker"})
196 if err != nil {
197 t.Fatal(err)
198 }
199 if got := logged(t, g, "%an <%ae>|%cn <%ce>", p.Commit); got != restacker+"|"+restacker {
200 t.Errorf("the record commit is authored and committed as %q", got)
201 }
202
203 t.Setenv("GIT_AUTHOR_NAME", "Inherited")
204 t.Setenv("GIT_COMMITTER_EMAIL", "inherited@example.invalid")
205 t.Setenv("EMAIL", "inherited@example.invalid")
206 g, err = scratchRepo(ctx, c)
207 if err != nil {
208 t.Fatal(err)
209 }
210 tree, err := gitOut(ctx, g, "mktree")
211 if err != nil {
212 t.Fatal(err)
213 }
214 commit, err := gitOut(ctx, g, "commit-tree", strings.TrimSpace(tree), "-m", "inherited")
215 if err != nil {
216 t.Fatal(err)
217 }
218 if got := logged(t, g, "%an <%ae>|%cn <%ce>", strings.TrimSpace(commit)); got != restacker+"|"+restacker {
219 t.Errorf("with an identity in the environment, a commit is authored and committed as %q", got)
220 }
221}
222
223// Configuration the environment injects reaches no git the restacker
224// runs. An author and a committer given in GIT_CONFIG_COUNT entries and in
225// GIT_CONFIG_PARAMETERS would beat the scratch repository's user.name and
226// user.email. They are not inherited: the restacker is the committer of
227// each commit it rebases, whose author stays the change's, and the author
228// and the committer of each record commit.
229func TestInheritedConfigurationDoesNotCommit(t *testing.T) {
230 withoutIdentity(t)
231 f := newFixture(t, "")
232 f.readied("author", "a", "A title")
233 f.moveMain()
234 for name, value := range map[string]string{
235 "GIT_CONFIG_COUNT": "2",
236 "GIT_CONFIG_KEY_0": "author.name", "GIT_CONFIG_VALUE_0": "Inherited",
237 "GIT_CONFIG_KEY_1": "author.email", "GIT_CONFIG_VALUE_1": "inherited@example.invalid",
238 "GIT_CONFIG_PARAMETERS": "'committer.name'='Inherited' 'committer.email'='inherited@example.invalid'",
239 } {
240 t.Setenv(name, value)
241 }
242 c := config{repo: f.origin, state: t.TempDir(), principal: "restacker",
243 commitName: "The Restacker", commitEmail: "restacker@example.invalid"}
244 ctx := context.Background()
245 g, err := scratchRepo(ctx, c)
246 if err != nil {
247 t.Fatal(err)
248 }
249
250 fam, head := restacked(t, g)
251 const restacker = "The Restacker <restacker@example.invalid>"
252 if got := logged(t, g, "%an <%ae>|%cn <%ce>", head); got != "A. Author <author@example.invalid>|"+restacker {
253 t.Errorf("the rebased commit is authored and committed as %q", got)
254 }
255 p, err := rebase.BuildRestack(ctx, g, rebase.RestackAppend{ID: idA, Head: head, IfActive: fam.Bottom().Head, Principal: "restacker"})
256 if err != nil {
257 t.Fatal(err)
258 }
259 if got := logged(t, g, "%an <%ae>|%cn <%ce>", p.Commit); got != restacker+"|"+restacker {
260 t.Errorf("the record commit is authored and committed as %q", got)
261 }
262}
263
264// A pass locks its state directory. A second lock fails at once, saying
265// another pass holds it, and succeeds once the first is let go.
266func TestAPassLocksItsState(t *testing.T) {
267 dir := filepath.Join(t.TempDir(), "state")
268 release, err := lockState(dir)
269 if err != nil {
270 t.Fatal(err)
271 }
272 if _, err := lockState(dir); err == nil || !strings.Contains(err.Error(), "another pass is using the state directory") {
273 t.Fatalf("a second lock while one is held: %v", err)
274 }
275 release()
276 again, err := lockState(dir)
277 if err != nil {
278 t.Fatalf("a lock once the first is let go: %v", err)
279 }
280 again()
281}
282
283// A state directory belongs to the repository, target and principal the
284// first pass used it for, and a pass for any other is refused.
285func TestStateBelongsToOneRepositoryTargetAndPrincipal(t *testing.T) {
286 dir := t.TempDir()
287 first := binding{Repository: "ssh://valley/project.git", Target: "main", Principal: "restacker"}
288 if err := bindState(dir, first); err != nil {
289 t.Fatal(err)
290 }
291 if err := bindState(dir, first); err != nil {
292 t.Fatalf("the same binding again: %v", err)
293 }
294 for _, other := range []binding{
295 {Repository: "ssh://valley/other.git", Target: "main", Principal: "restacker"},
296 {Repository: "ssh://valley/project.git", Target: "main", Principal: "requester"},
297 {Repository: "ssh://valley/project.git", Target: "next", Principal: "restacker"},
298 } {
299 if err := bindState(dir, other); err == nil || !strings.Contains(err.Error(), "give each its own --state") {
300 t.Errorf("a pass for %+v: %v", other, err)
301 }
302 }
303}
304
305// blocker is a script that stands for a program that does not return.
306// The first time it runs, it says it has started, then keeps its output
307// open for a minute and beats while it does: it adds a line to a file
308// every tenth of a second.
309type blocker struct {
310 script, started, beats string
311}
312
313func newBlocker(t *testing.T, script string) *blocker {
314 t.Helper()
315 dir := t.TempDir()
316 b := &blocker{script: script, started: filepath.Join(dir, "started"), beats: filepath.Join(dir, "beats")}
317 body := fmt.Sprintf("#!/bin/sh\n[ -e '%s' ] && exit 0\n: > '%s'\n"+
318 "i=0\nwhile [ $i -lt 600 ]; do echo >> '%s'; sleep 0.1; i=$((i+1)); done\n",
319 b.started, b.started, b.beats)
320 if err := os.WriteFile(script, []byte(body), 0o755); err != nil {
321 t.Fatal(err)
322 }
323 return b
324}
325
326func (b *blocker) wait(t *testing.T) {
327 t.Helper()
328 for deadline := time.Now().Add(30 * time.Second); time.Now().Before(deadline); time.Sleep(20 * time.Millisecond) {
329 if _, err := os.Stat(b.started); err == nil {
330 return
331 }
332 }
333 t.Fatal("the blocker never started")
334}
335
336func (b *blocker) beating() bool {
337 size := func() int64 {
338 fi, err := os.Stat(b.beats)
339 if err != nil {
340 return 0
341 }
342 return fi.Size()
343 }
344 time.Sleep(200 * time.Millisecond)
345 before := size()
346 time.Sleep(time.Second)
347 return size() != before
348}
349
350// bounded runs read under a context with a two-second deadline, and holds
351// that it fails, returns soon after the deadline, and leaves nothing of
352// the blocker it ran into running.
353func bounded(t *testing.T, b *blocker, read func(ctx context.Context) error) {
354 t.Helper()
355 ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
356 defer cancel()
357 start := time.Now()
358 if err := read(ctx); err == nil {
359 t.Fatal("a read that never returned succeeded")
360 }
361 if took := time.Since(start); took > 15*time.Second {
362 t.Errorf("the read took %v, with a deadline of 2s", took)
363 }
364 b.wait(t)
365 if b.beating() {
366 t.Error("what the read started outlived the deadline")
367 }
368}
369
370// Composing the policy ends at the pass's deadline, with the cue that
371// never returned killed.
372func TestPolicyCompositionEndsAtTheDeadline(t *testing.T) {
373 f := newFixture(t, "")
374 floor := t.TempDir()
375 if err := os.WriteFile(filepath.Join(floor, "floor.cue"), []byte("package verification\n"), 0o644); err != nil {
376 t.Fatal(err)
377 }
378 b := newBlocker(t, filepath.Join(t.TempDir(), "cue"))
379 c := config{cue: b.script, schema: filepath.Join(floor, "floor.cue"), floor: composed.Floor{Path: floor}, projectPolicy: "policy/project"}
380 g := rebase.Git{Dir: f.work, Env: f.env}
381 tip := f.git("rev-parse", "HEAD")
382 bounded(t, b, func(ctx context.Context) error {
383 _, err := policyCap(ctx, g, c, tip)
384 return err
385 })
386}
387
388// Reading the floor from the instance repository ends at the pass's
389// deadline, with the ssh that never answered killed: the scratch
390// repository's git reaches origin unattended.
391func TestInstanceReadEndsAtTheDeadline(t *testing.T) {
392 b := newBlocker(t, filepath.Join(t.TempDir(), "ssh"))
393 t.Setenv("GIT_SSH_COMMAND", b.script)
394 c := config{repo: "ssh://valley/project.git", state: t.TempDir(), principal: "restacker",
395 commitName: "The Restacker", commitEmail: "restacker@example.invalid",
396 instanceRepo: "ssh://valley/instance.git", floor: composed.Floor{Ref: "refs/heads/main", Dir: "policy/instance"}}
397 g, err := scratchRepo(context.Background(), c)
398 if err != nil {
399 t.Fatal(err)
400 }
401 bounded(t, b, func(ctx context.Context) error {
402 _, err := policyCap(ctx, g, c, strings.Repeat("0", 40))
403 return err
404 })
405}
406
407// Through the host's rendered hook, the restacker principal, which holds
408// the restack grant and not the request grant, adds a restack version to
409// a change another principal owns: the version keeps the active title
410// though its head's subject differs. The hook refuses a version it adds
411// under any other title. It also takes a restack report from the
412// restacker, built and then pushed, and refuses one from the owner, who
413// holds no restack grant.
414func TestRenderedHookTakesTheRestackAppend(t *testing.T) {
415 hook := os.Getenv(hookEnv)
416 if hook == "" {
417 t.Skip(hookEnv + " names no rendered hook; restack-unit supplies one")
418 }
419 withoutIdentity(t)
420 f := newFixture(t, hook)
421 was := f.readied("alice", "a", "A title unlike its commit's subject")
422 f.moveMain()
423 t.Setenv("VALLEY_PRINCIPAL", "restacker")
424 c := config{repo: f.origin, state: t.TempDir(), principal: "restacker",
425 commitName: "The Restacker", commitEmail: "restacker@example.invalid"}
426 ctx := context.Background()
427 g, err := scratchRepo(ctx, c)
428 if err != nil {
429 t.Fatal(err)
430 }
431 var stderr bytes.Buffer
432 g.Stderr = &stderr
433 _, head := restacked(t, g)
434 ref := change.Ref(rebase.Target, idA)
435 old := f.at(ref)
436
437 before, err := rebase.ReadRecord(ctx, g, old)
438 if err != nil {
439 t.Fatal(err)
440 }
441 forged, err := rebase.NextRecord("kkkk", before, change.Version{
442 Head: change.HeadPrefix + head, Title: "A forged title", Branch: "a", Uploader: "restacker",
443 })
444 if err != nil {
445 t.Fatal(err)
446 }
447 commit, err := rebase.WriteRecord(ctx, g, forged, "forged", old, head)
448 if err != nil {
449 t.Fatal(err)
450 }
451 if w := rebase.PushRecord(ctx, g, idA, old, commit); w.Push != rebase.Refused || f.at(ref) != old {
452 t.Fatalf("a restack version under a forged title: %+v", w)
453 }
454 if !strings.Contains(stderr.String(), "under the title of the active one") {
455 t.Errorf("the hook's refusal does not name the title:\n%s", stderr.String())
456 }
457
458 p, err := rebase.BuildRestack(ctx, g, rebase.RestackAppend{ID: idA, Head: head, IfActive: was, Principal: "restacker"})
459 if err != nil {
460 t.Fatal(err)
461 }
462 if ap := p.Push(ctx, g); ap.Err != nil || ap.Version != 2 || f.at(ref) != p.Commit {
463 t.Fatalf("the restack append: %+v\n%s", ap, stderr.String())
464 }
465 if err := rebase.Fetch(ctx, g, f.at(ref)); err != nil {
466 t.Fatal(err)
467 }
468 r, err := rebase.ReadRecord(ctx, g, f.at(ref))
469 if err != nil {
470 t.Fatal(err)
471 }
472 if v := r.ActiveVersion(); v.Title != "A title unlike its commit's subject" || v.Uploader != "restacker" || v.Branch != "a" || r.Owner != "alice" {
473 t.Errorf("the record on origin is %+v", r)
474 }
475
476 read, tip, record := change.HeadPrefix+was, change.HeadPrefix+head, change.HeadPrefix+p.Commit
477 report := &change.RestackReport{
478 Schema: change.RestackSchema, ChangeID: idA, Target: rebase.Target,
479 TargetTip: change.HeadPrefix + f.at("refs/heads/main"), Operation: "test-1", Result: change.RestackComplete,
480 Layers: []change.RestackLayer{{
481 ChangeID: idA, Record: change.HeadPrefix + old, Version: 1, Head: change.HeadPrefix + was,
482 Branch: "a", BranchTip: &read, Published: &change.RestackPublished{Head: tip, Version: &p.Version, Record: &record},
483 }},
484 }
485 alice := f.as("alice")
486 alice.Stderr = &stderr
487 byAlice, err := rebase.WriteReport(ctx, alice, report, rebase.ReportMessage("kkkk", report), "")
488 if err != nil {
489 t.Fatal(err)
490 }
491 if w := rebase.PushReport(ctx, alice, idA, "", byAlice); w.Push != rebase.Refused {
492 t.Errorf("a report from a principal with no restack grant: %+v", w)
493 }
494 byRestacker, err := rebase.WriteReport(ctx, g, report, rebase.ReportMessage("kkkk", report), "")
495 if err != nil {
496 t.Fatal(err)
497 }
498 if w := rebase.PushReport(ctx, g, idA, "", byRestacker); w.Push != rebase.Pushed || f.at(rebase.RestackPrefix+idA) != byRestacker {
499 t.Errorf("a report from the restacker: %+v\n%s", w, stderr.String())
500 }
501}