gunk-dev/the-valley

main_test.go

source5f0229dc1066main's published tip history
15.6 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// A pass locks its state directory. A second lock fails at once, saying
224// another pass holds it, and succeeds once the first is let go.
225func TestAPassLocksItsState(t *testing.T) {
226 dir := filepath.Join(t.TempDir(), "state")
227 release, err := lockState(dir)
228 if err != nil {
229 t.Fatal(err)
230 }
231 if _, err := lockState(dir); err == nil || !strings.Contains(err.Error(), "another pass is using the state directory") {
232 t.Fatalf("a second lock while one is held: %v", err)
233 }
234 release()
235 again, err := lockState(dir)
236 if err != nil {
237 t.Fatalf("a lock once the first is let go: %v", err)
238 }
239 again()
240}
241
242// A state directory belongs to the repository, target and principal the
243// first pass used it for, and a pass for any other is refused.
244func TestStateBelongsToOneRepositoryTargetAndPrincipal(t *testing.T) {
245 dir := t.TempDir()
246 first := binding{Repository: "ssh://valley/project.git", Target: "main", Principal: "restacker"}
247 if err := bindState(dir, first); err != nil {
248 t.Fatal(err)
249 }
250 if err := bindState(dir, first); err != nil {
251 t.Fatalf("the same binding again: %v", err)
252 }
253 for _, other := range []binding{
254 {Repository: "ssh://valley/other.git", Target: "main", Principal: "restacker"},
255 {Repository: "ssh://valley/project.git", Target: "main", Principal: "requester"},
256 {Repository: "ssh://valley/project.git", Target: "next", Principal: "restacker"},
257 } {
258 if err := bindState(dir, other); err == nil || !strings.Contains(err.Error(), "give each its own --state") {
259 t.Errorf("a pass for %+v: %v", other, err)
260 }
261 }
262}
263
264// blocker is a script that stands for a program that does not return.
265// The first time it runs, it says it has started, then keeps its output
266// open for a minute and beats while it does: it adds a line to a file
267// every tenth of a second.
268type blocker struct {
269 script, started, beats string
270}
271
272func newBlocker(t *testing.T, script string) *blocker {
273 t.Helper()
274 dir := t.TempDir()
275 b := &blocker{script: script, started: filepath.Join(dir, "started"), beats: filepath.Join(dir, "beats")}
276 body := fmt.Sprintf("#!/bin/sh\n[ -e '%s' ] && exit 0\n: > '%s'\n"+
277 "i=0\nwhile [ $i -lt 600 ]; do echo >> '%s'; sleep 0.1; i=$((i+1)); done\n",
278 b.started, b.started, b.beats)
279 if err := os.WriteFile(script, []byte(body), 0o755); err != nil {
280 t.Fatal(err)
281 }
282 return b
283}
284
285func (b *blocker) wait(t *testing.T) {
286 t.Helper()
287 for deadline := time.Now().Add(30 * time.Second); time.Now().Before(deadline); time.Sleep(20 * time.Millisecond) {
288 if _, err := os.Stat(b.started); err == nil {
289 return
290 }
291 }
292 t.Fatal("the blocker never started")
293}
294
295func (b *blocker) beating() bool {
296 size := func() int64 {
297 fi, err := os.Stat(b.beats)
298 if err != nil {
299 return 0
300 }
301 return fi.Size()
302 }
303 time.Sleep(200 * time.Millisecond)
304 before := size()
305 time.Sleep(time.Second)
306 return size() != before
307}
308
309// bounded runs read under a context with a two-second deadline, and holds
310// that it fails, returns soon after the deadline, and leaves nothing of
311// the blocker it ran into running.
312func bounded(t *testing.T, b *blocker, read func(ctx context.Context) error) {
313 t.Helper()
314 ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
315 defer cancel()
316 start := time.Now()
317 if err := read(ctx); err == nil {
318 t.Fatal("a read that never returned succeeded")
319 }
320 if took := time.Since(start); took > 15*time.Second {
321 t.Errorf("the read took %v, with a deadline of 2s", took)
322 }
323 b.wait(t)
324 if b.beating() {
325 t.Error("what the read started outlived the deadline")
326 }
327}
328
329// Composing the policy ends at the pass's deadline, with the cue that
330// never returned killed.
331func TestPolicyCompositionEndsAtTheDeadline(t *testing.T) {
332 f := newFixture(t, "")
333 floor := t.TempDir()
334 if err := os.WriteFile(filepath.Join(floor, "floor.cue"), []byte("package verification\n"), 0o644); err != nil {
335 t.Fatal(err)
336 }
337 b := newBlocker(t, filepath.Join(t.TempDir(), "cue"))
338 c := config{cue: b.script, schema: filepath.Join(floor, "floor.cue"), floor: composed.Floor{Path: floor}, projectPolicy: "policy/project"}
339 g := rebase.Git{Dir: f.work, Env: f.env}
340 tip := f.git("rev-parse", "HEAD")
341 bounded(t, b, func(ctx context.Context) error {
342 _, err := policyCap(ctx, g, c, tip)
343 return err
344 })
345}
346
347// Reading the floor from the instance repository ends at the pass's
348// deadline, with the ssh that never answered killed: the scratch
349// repository's git reaches origin unattended.
350func TestInstanceReadEndsAtTheDeadline(t *testing.T) {
351 b := newBlocker(t, filepath.Join(t.TempDir(), "ssh"))
352 t.Setenv("GIT_SSH_COMMAND", b.script)
353 c := config{repo: "ssh://valley/project.git", state: t.TempDir(), principal: "restacker",
354 commitName: "The Restacker", commitEmail: "restacker@example.invalid",
355 instanceRepo: "ssh://valley/instance.git", floor: composed.Floor{Ref: "refs/heads/main", Dir: "policy/instance"}}
356 g, err := scratchRepo(context.Background(), c)
357 if err != nil {
358 t.Fatal(err)
359 }
360 bounded(t, b, func(ctx context.Context) error {
361 _, err := policyCap(ctx, g, c, strings.Repeat("0", 40))
362 return err
363 })
364}
365
366// Through the host's rendered hook, the restacker principal, which holds
367// the restack grant and not the request grant, adds a restack version to
368// a change another principal owns: the version keeps the active title
369// though its head's subject differs. The hook refuses a version it adds
370// under any other title. It also takes a restack report from the
371// restacker, built and then pushed, and refuses one from the owner, who
372// holds no restack grant.
373func TestRenderedHookTakesTheRestackAppend(t *testing.T) {
374 hook := os.Getenv(hookEnv)
375 if hook == "" {
376 t.Skip(hookEnv + " names no rendered hook; restack-unit supplies one")
377 }
378 withoutIdentity(t)
379 f := newFixture(t, hook)
380 was := f.readied("alice", "a", "A title unlike its commit's subject")
381 f.moveMain()
382 t.Setenv("VALLEY_PRINCIPAL", "restacker")
383 c := config{repo: f.origin, state: t.TempDir(), principal: "restacker",
384 commitName: "The Restacker", commitEmail: "restacker@example.invalid"}
385 ctx := context.Background()
386 g, err := scratchRepo(ctx, c)
387 if err != nil {
388 t.Fatal(err)
389 }
390 var stderr bytes.Buffer
391 g.Stderr = &stderr
392 _, head := restacked(t, g)
393 ref := change.Ref(rebase.Target, idA)
394 old := f.at(ref)
395
396 before, err := rebase.ReadRecord(ctx, g, old)
397 if err != nil {
398 t.Fatal(err)
399 }
400 forged, err := rebase.NextRecord("kkkk", before, change.Version{
401 Head: change.HeadPrefix + head, Title: "A forged title", Branch: "a", Uploader: "restacker",
402 })
403 if err != nil {
404 t.Fatal(err)
405 }
406 commit, err := rebase.WriteRecord(ctx, g, forged, "forged", old, head)
407 if err != nil {
408 t.Fatal(err)
409 }
410 if w := rebase.PushRecord(ctx, g, idA, old, commit); w.Push != rebase.Refused || f.at(ref) != old {
411 t.Fatalf("a restack version under a forged title: %+v", w)
412 }
413 if !strings.Contains(stderr.String(), "under the title of the active one") {
414 t.Errorf("the hook's refusal does not name the title:\n%s", stderr.String())
415 }
416
417 p, err := rebase.BuildRestack(ctx, g, rebase.RestackAppend{ID: idA, Head: head, IfActive: was, Principal: "restacker"})
418 if err != nil {
419 t.Fatal(err)
420 }
421 if ap := p.Push(ctx, g); ap.Err != nil || ap.Version != 2 || f.at(ref) != p.Commit {
422 t.Fatalf("the restack append: %+v\n%s", ap, stderr.String())
423 }
424 if err := rebase.Fetch(ctx, g, f.at(ref)); err != nil {
425 t.Fatal(err)
426 }
427 r, err := rebase.ReadRecord(ctx, g, f.at(ref))
428 if err != nil {
429 t.Fatal(err)
430 }
431 if v := r.ActiveVersion(); v.Title != "A title unlike its commit's subject" || v.Uploader != "restacker" || v.Branch != "a" || r.Owner != "alice" {
432 t.Errorf("the record on origin is %+v", r)
433 }
434
435 read, tip, record := change.HeadPrefix+was, change.HeadPrefix+head, change.HeadPrefix+p.Commit
436 report := &change.RestackReport{
437 Schema: change.RestackSchema, ChangeID: idA, Target: rebase.Target,
438 TargetTip: change.HeadPrefix + f.at("refs/heads/main"), Operation: "test-1", Result: change.RestackComplete,
439 Layers: []change.RestackLayer{{
440 ChangeID: idA, Record: change.HeadPrefix + old, Version: 1, Head: change.HeadPrefix + was,
441 Branch: "a", BranchTip: &read, Published: &change.RestackPublished{Head: tip, Version: &p.Version, Record: &record},
442 }},
443 }
444 alice := f.as("alice")
445 alice.Stderr = &stderr
446 byAlice, err := rebase.WriteReport(ctx, alice, report, rebase.ReportMessage("kkkk", report), "")
447 if err != nil {
448 t.Fatal(err)
449 }
450 if w := rebase.PushReport(ctx, alice, idA, "", byAlice); w.Push != rebase.Refused {
451 t.Errorf("a report from a principal with no restack grant: %+v", w)
452 }
453 byRestacker, err := rebase.WriteReport(ctx, g, report, rebase.ReportMessage("kkkk", report), "")
454 if err != nil {
455 t.Fatal(err)
456 }
457 if w := rebase.PushReport(ctx, g, idA, "", byRestacker); w.Push != rebase.Pushed || f.at(rebase.RestackPrefix+idA) != byRestacker {
458 t.Errorf("a report from the restacker: %+v\n%s", w, stderr.String())
459 }
460}