gunk-dev/the-valley

approvalsign_test.go

sourcebc00697b19b5main's published tip history
30.6 KiB
1package main
2
3import (
4 "bytes"
5 "crypto/ed25519"
6 "crypto/rand"
7 "crypto/sha256"
8 "crypto/x509"
9 "crypto/x509/pkix"
10 "encoding/binary"
11 "encoding/pem"
12 "errors"
13 "fmt"
14 "io"
15 "math/big"
16 "os"
17 "os/exec"
18 "os/signal"
19 "path/filepath"
20 "runtime"
21 "strconv"
22 "strings"
23 "syscall"
24 "testing"
25 "time"
26
27 approvals "the-valley/approval"
28 "the-valley/change"
29 "the-valley/note"
30)
31
32// signWorld is a project whose main names an instance repository, which
33// publishes approval keys at refs/the-valley/signers, and a ready change
34// in it, topic, recorded as id. Its policy requires no check, so approving
35// runs nothing and needs no attest.
36type signWorld struct {
37 t *testing.T
38 dir, work string
39 origin, valley string
40 id, head string
41 operator ed25519.PrivateKey // listed in approval-signers
42 operatorFile string
43 instanceID string
44 stdout, stderr bytes.Buffer
45 floor string
46 signers, hardware string // the published approval files: the operator's software key and device, and the device
47 omitApprovalFiles bool
48 malformedApprovalFile bool
49}
50
51func seeded(name string) ed25519.PrivateKey {
52 seed := sha256.Sum256([]byte(name))
53 return ed25519.NewKeyFromSeed(seed[:])
54}
55
56// signSchema is the verification schema, found before any test changes
57// directory.
58var signSchema, _ = filepath.Abs("../schema/verification.cue")
59
60func newSignWorld(t *testing.T, configure func(w *signWorld)) *signWorld {
61 schema := signSchema
62 dir := t.TempDir()
63 w := &signWorld{t: t, dir: dir, work: filepath.Join(dir, "project"), origin: filepath.Join(dir, "project.git"),
64 valley: filepath.Join(dir, "valley.git"), id: strings.Repeat("m", 32), operator: seeded("operator"),
65 floor: "floor: classes: everything: {paths: \"**\": true, requires: {}}\n"}
66 w.hardware = note.NewVerifierKey("operator", seeded("device").Public().(ed25519.PublicKey)).String() + "\n"
67 w.signers = note.NewVerifierKey("operator", w.operator.Public().(ed25519.PublicKey)).String() + "\n" + w.hardware
68 if configure != nil {
69 configure(w)
70 }
71 for k, v := range map[string]string{"HOME": dir, "XDG_CONFIG_HOME": filepath.Join(dir, "config"),
72 "XDG_STATE_HOME": filepath.Join(dir, "state"), "GIT_CONFIG_NOSYSTEM": "1", "VALLEY_KNOWN_SIGNERS": "",
73 "VALLEY_INTEGRATOR_SIGNER": "", "VALLEY_APPROVAL_KEY": "", "VALLEY_APPROVAL_PIV": "",
74 "VALLEY_APPROVAL_PIV_READER": "", "VALLEY_VERIFICATION_SCHEMA": schema, "VALLEY_TEST_FAKE_PIV": ""} {
75 t.Setenv(k, v)
76 }
77 w.operatorFile = filepath.Join(dir, "operator.key")
78 if err := os.WriteFile(w.operatorFile, opensshKey(w.operator), 0o600); err != nil {
79 t.Fatal(err)
80 }
81
82 // The instance: its floor on main, and its publication.
83 valleyWork := filepath.Join(dir, "valley-work")
84 w.run("", "git", "init", "--quiet", "--bare", "--initial-branch=main", w.valley)
85 w.run("", "git", "init", "--quiet", "--initial-branch=main", valleyWork)
86 w.write(valleyWork, "policy/instance/floor.cue", "package verification\n\n"+w.floor)
87 w.run(valleyWork, "git", "add", "-A")
88 w.run(valleyWork, "git", "-c", "user.name=t", "-c", "user.email=t@localhost", "commit", "--quiet", "-m", "floor")
89 w.run(valleyWork, "git", "push", "--quiet", w.valley, "main")
90 w.instanceID = strings.Repeat("ab", 32)
91 w.publish(nil)
92
93 // The project, and its change.
94 w.run("", "git", "init", "--quiet", "--bare", "--initial-branch=main", w.origin)
95 w.run("", "git", "clone", "--quiet", w.origin, w.work)
96 for k, v := range map[string]string{"user.name": "sign-test", "user.email": "sign-test@localhost", "valley.principal": "alice"} {
97 w.git("config", k, v)
98 }
99 w.git("checkout", "--quiet", "-b", "main")
100 w.write(w.work, "policy/valley", w.valley+"\n")
101 w.write(w.work, "policy/project/policy.cue", "package verification\n\nproject: {}\n")
102 w.git("add", "-A")
103 w.git("commit", "--quiet", "-m", "base")
104 w.git("push", "--quiet", "origin", "main")
105 t.Chdir(w.work)
106 w.git("checkout", "--quiet", "-b", "topic")
107 w.write(w.work, "readme.md", "a readme\n")
108 w.git("add", "readme.md")
109 w.git("commit", "--quiet", "-m", "a readme")
110 w.git("push", "--quiet", "origin", "topic")
111 w.head = w.git("rev-parse", "HEAD")
112 w.valleyCLI("ready", "--change", w.id, "topic")
113 return w
114}
115
116// publish writes the instance's publication, with extra files beside the
117// ones the world was configured with.
118func (w *signWorld) publish(extra map[string]string) {
119 files := map[string]string{
120 "known-signers": note.NewVerifierKey("integrator", seeded("integrator").Public().(ed25519.PublicKey)).String() + "\n",
121 "integrator-name": "integrator\n",
122 }
123 if !w.omitApprovalFiles {
124 files[signersApprovers], files[signersHardware] = w.signers, w.hardware
125 files[signersInstance] = w.instanceID + "\n"
126 }
127 if w.malformedApprovalFile {
128 files[signersApprovers] = "not a verifier key\n"
129 }
130 for k, v := range extra {
131 files[k] = v
132 }
133 var entries strings.Builder
134 for name, body := range files {
135 blob := w.runInput(w.valley, body, "git", "hash-object", "-w", "--stdin")
136 fmt.Fprintf(&entries, "100644 blob %s\t%s\n", blob, name)
137 }
138 tree := w.runInput(w.valley, entries.String(), "git", "mktree")
139 w.run(w.valley, "git", "update-ref", signersRef, tree)
140}
141
142func (w *signWorld) run(dir string, args ...string) string {
143 return w.runInput(dir, "", args...)
144}
145
146func (w *signWorld) runInput(dir, stdin string, args ...string) string {
147 w.t.Helper()
148 cmd := exec.Command(args[0], args[1:]...)
149 cmd.Dir, cmd.Stdin = dir, strings.NewReader(stdin)
150 out, err := cmd.CombinedOutput()
151 if err != nil {
152 w.t.Fatalf("%s: %v\n%s", strings.Join(args, " "), err, out)
153 }
154 return strings.TrimSpace(string(out))
155}
156
157func (w *signWorld) git(args ...string) string {
158 w.t.Helper()
159 return w.run(w.work, append([]string{"git"}, args...)...)
160}
161
162func (w *signWorld) write(dir, path, body string) {
163 w.t.Helper()
164 path = filepath.Join(dir, path)
165 if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
166 w.t.Fatal(err)
167 }
168 if err := os.WriteFile(path, []byte(body), 0o644); err != nil {
169 w.t.Fatal(err)
170 }
171}
172
173func (w *signWorld) valleyCLI(args ...string) {
174 w.t.Helper()
175 var out bytes.Buffer
176 if code := run(args, &out, &out, func(int) { w.t.Fatal("ended by a signal") }); code != 0 {
177 w.t.Fatalf("valley %s: %s", strings.Join(args, " "), out.String())
178 }
179}
180
181// approve runs valley approve with args, and returns its exit status. The
182// verb holds SIGINT and SIGTERM until the process exits, so a signal
183// another test sends itself later reaches its end path, which leaves the
184// goroutine it was called on, as it would leave the process.
185func (w *signWorld) approve(args ...string) int {
186 w.stdout.Reset()
187 w.stderr.Reset()
188 return run(append([]string{"approve"}, args...), &w.stdout, &w.stderr, func(int) { runtime.Goexit() })
189}
190
191// onOrigin is the object origin's ref names, or "".
192func (w *signWorld) onOrigin(ref string) string {
193 out, _ := exec.Command("git", "-C", w.origin, "rev-parse", "--verify", "--quiet", ref).Output()
194 return strings.TrimSpace(string(out))
195}
196
197func (w *signWorld) request() string {
198 return w.onOrigin("refs/the-valley/integration-requests/main/c-" + w.id)
199}
200func (w *signWorld) approvalRef() string {
201 return w.onOrigin(approvals.Ref(recordTarget, w.id))
202}
203func (w *signWorld) record() string { return w.onOrigin(change.Ref(recordTarget, w.id)) }
204
205// published is the statement origin's approval note carries, verified
206// under keys.
207func (w *signWorld) published(keys string) approvals.Statement {
208 w.t.Helper()
209 n, err := exec.Command("git", "-C", w.origin, "cat-file", "blob", approvals.Ref(recordTarget, w.id)).Output()
210 if err != nil {
211 w.t.Fatalf("origin holds no approval of %s: %v", w.id, err)
212 }
213 authority, err := note.ParseVerifierKeys([]byte(keys))
214 if err != nil {
215 w.t.Fatal(err)
216 }
217 s, err := approvals.Verify(n, authority)
218 if err != nil {
219 w.t.Fatalf("the published approval does not verify: %v\n%s", err, n)
220 }
221 return s
222}
223
224// signedAs checks the published statement: the instance, the project, the
225// change at v1 and its head, the record commit given, and the principal.
226func (w *signWorld) signedAs(keys, record string) {
227 w.t.Helper()
228 s := w.published(keys)
229 if s.Instance != w.instanceID || s.Project != "project" || s.Target != "main" || s.Change != w.id ||
230 s.Version != 1 || s.Head != change.HeadPrefix+w.head || s.Record != change.HeadPrefix+record ||
231 s.Principal != "operator" || time.Since(s.Issued) > time.Hour {
232 w.t.Errorf("the published statement is %+v; want instance %s, project, change %s v1 at %s, record %s, operator",
233 s, w.instanceID, w.id, w.head, record)
234 }
235 if w.request() != w.head {
236 w.t.Errorf("the request stands at %q, not %s", w.request(), w.head)
237 }
238}
239
240// nothingPublished fails unless the last approval refused, with why on
241// stderr, and left neither a request nor an approval on origin.
242func (w *signWorld) nothingPublished(status int, why string) {
243 w.t.Helper()
244 if status != 1 || !strings.Contains(w.stderr.String(), why) {
245 w.t.Errorf("exit %d, stderr %q; want 1 and %q", status, w.stderr.String(), why)
246 }
247 if r, a := w.request(), w.approvalRef(); r != "" || a != "" {
248 w.t.Errorf("a refused approval left request %q and approval %q on origin", r, a)
249 }
250}
251
252const unsignedLine = "no signed approval was written: no approval key is selected\n"
253
254// The approve verb with a software key publishes the note beside the
255// request, in one push: the statement names what approve bound, and
256// verifies under approval-signers.
257func TestSignedApproveVerbPublishesTheNote(t *testing.T) {
258 w := newSignWorld(t, nil)
259 record := w.record()
260 if status := w.approve("-v", "--head", w.head, "--approval-key", w.operatorFile, w.id); status != 0 {
261 t.Fatalf("exit %d\n%s%s", status, w.stdout.String(), w.stderr.String())
262 }
263 w.signedAs(w.signers, record)
264 out := w.stdout.String()
265 if !strings.Contains(out, "signed and approved · no checks required") || strings.Contains(out, unsignedLine) {
266 t.Errorf("the verdict does not say the approval was signed:\n%s", out)
267 }
268 if !strings.Contains(out, " signed operator, key ") || !strings.Contains(out, "not listed as a hardware key") {
269 t.Errorf("-v does not say who signed:\n%s", out)
270 }
271}
272
273// With no approval key selected, approve files as it does unsigned and
274// says no signed approval was written: a recorded change while the
275// publication's approval files do not read, and a plain branch while the
276// publication has none.
277func TestUnsignedApproveIsUnchanged(t *testing.T) {
278 w := newSignWorld(t, func(w *signWorld) { w.malformedApprovalFile = true })
279 if status := w.approve("--head", w.head, w.id); status != 0 {
280 t.Fatalf("exit %d\n%s%s", status, w.stdout.String(), w.stderr.String())
281 }
282 if w.request() != w.head || w.approvalRef() != "" || !strings.HasSuffix(w.stdout.String(), unsignedLine) {
283 t.Errorf("request %q, approval %q, stdout:\n%s", w.request(), w.approvalRef(), w.stdout.String())
284 }
285
286 w = newSignWorld(t, func(w *signWorld) { w.omitApprovalFiles = true })
287 w.git("push", "--quiet", "origin", "topic:plain")
288 if status := w.approve("origin/plain"); status != 0 {
289 t.Fatalf("exit %d\n%s%s", status, w.stdout.String(), w.stderr.String())
290 }
291 if w.onOrigin("refs/the-valley/integration-requests/main/plain") != w.head ||
292 !strings.HasSuffix(w.stdout.String(), unsignedLine) {
293 t.Errorf("the plain branch was not filed unsigned:\n%s%s", w.stdout.String(), w.stderr.String())
294 }
295}
296
297// With a key selected, approve refuses whatever stops the signing, and
298// publishes nothing: no request, no approval.
299func TestSignedApprovalRefusals(t *testing.T) {
300 stranger := seeded("stranger")
301 for _, c := range []struct {
302 name string
303 configure func(w *signWorld)
304 args func(w *signWorld) []string
305 why string
306 }{
307 {name: "plain branch", why: "no recorded version to sign",
308 args: func(w *signWorld) []string {
309 w.git("push", "--quiet", "origin", "topic:plain")
310 return []string{"--approval-key", w.operatorFile, "origin/plain"}
311 }},
312 {name: "unlisted key", why: "approval key is not listed in approval-signers",
313 configure: func(w *signWorld) {
314 w.signers = note.NewVerifierKey("operator", stranger.Public().(ed25519.PublicKey)).String() + "\n"
315 }},
316 {name: "two principals", why: "approval key is listed under several principals",
317 configure: func(w *signWorld) {
318 w.signers += note.NewVerifierKey("alice", w.operator.Public().(ed25519.PublicKey)).String() + "\n"
319 }},
320 {name: "hardware required", why: "policy requires a hardware key, and this key is none",
321 configure: func(w *signWorld) { w.floor += "floor: approval: hardware: true\n" }},
322 {name: "revoked", why: "approval key is not listed in approval-signers",
323 configure: func(w *signWorld) { w.signers = "" }},
324 {name: "no approval files", why: "could not read the published approval keys",
325 configure: func(w *signWorld) { w.omitApprovalFiles = true }},
326 {name: "malformed approval file", why: "could not read the published approval keys",
327 configure: func(w *signWorld) { w.malformedApprovalFile = true }},
328 {name: "hook refuses", why: "origin refused the push",
329 configure: func(w *signWorld) {}, args: func(w *signWorld) []string {
330 w.write(w.origin, "hooks/pre-receive", "#!/bin/sh\n! grep -q refs/the-valley/approvals/\n")
331 if err := os.Chmod(filepath.Join(w.origin, "hooks/pre-receive"), 0o755); err != nil {
332 t.Fatal(err)
333 }
334 return []string{"--head", w.head, "--approval-key", w.operatorFile, w.id}
335 }},
336 } {
337 t.Run(c.name, func(t *testing.T) {
338 w := newSignWorld(t, c.configure)
339 args := []string{"--head", w.head, "--approval-key", w.operatorFile, w.id}
340 if c.args != nil {
341 args = c.args(w)
342 }
343 w.nothingPublished(w.approve(args...), c.why)
344 })
345 }
346
347 // Both kinds selected at one level are refused before anything runs;
348 // a flag beats the environment.
349 w := newSignWorld(t, nil)
350 t.Setenv("VALLEY_APPROVAL_KEY", w.operatorFile)
351 t.Setenv("VALLEY_APPROVAL_PIV", "9c")
352 w.nothingPublished(w.approve("--head", w.head, w.id), "select two approval keys")
353 w.nothingPublished(w.approve("--head", w.head, "--approval-piv", "--approval-key", w.operatorFile, w.id), "select two approval keys")
354 // Where this build has no PIV signer, selecting a PIV slot is refused.
355 t.Setenv("VALLEY_APPROVAL_KEY", "")
356 saved := pivSigner
357 pivSigner = ""
358 w.nothingPublished(w.approve("--head", w.head, "--approval-piv", w.id), "hardware signing is not available on this platform")
359 pivSigner = saved
360 t.Setenv("VALLEY_APPROVAL_KEY", filepath.Join(w.dir, "missing.key"))
361 if status := w.approve("--head", w.head, "--approval-key", w.operatorFile, w.id); status != 0 {
362 t.Fatalf("--approval-key did not beat the environment: exit %d\n%s", status, w.stderr.String())
363 }
364 w.signedAs(w.signers, w.record())
365}
366
367// A YubiKey's PIV slot, through a stand-in for valley-piv-signer: this
368// test binary, with VALLEY_TEST_FAKE_PIV naming what the device does when
369// it is asked to sign. A device that signs publishes the note. One that is
370// absent, or not touched, publishes nothing. The device's touch is where
371// the rest of the world moves: the publication changing, the change
372// withdrawn, or a new version readied, after which the approval still
373// names the version and record it read.
374func TestPIVApproval(t *testing.T) {
375 saved := pivSigner
376 pivSigner = os.Args[0]
377 t.Cleanup(func() { pivSigner = saved })
378 for _, c := range []struct{ scenario, why string }{
379 {"absent", "no YubiKey could be reached"},
380 {"touch", "it was not touched in time"},
381 {"publish", "the published approval keys changed meanwhile"},
382 {"withdraw", "change is withdrawn"},
383 } {
384 t.Run(c.scenario, func(t *testing.T) {
385 w := newSignWorld(t, nil)
386 t.Setenv("VALLEY_TEST_FAKE_PIV", c.scenario)
387 t.Setenv("VALLEY_TEST_FAKE_PIV_VALLEY", w.valley)
388 w.nothingPublished(w.approve("--head", w.head, "--approval-piv", w.id), c.why)
389 })
390 }
391 for _, scenario := range []string{"sign", "new-version"} {
392 t.Run(scenario, func(t *testing.T) {
393 w := newSignWorld(t, func(w *signWorld) { w.floor += "floor: approval: hardware: true\n" })
394 record := w.record()
395 t.Setenv("VALLEY_TEST_FAKE_PIV", scenario)
396 t.Setenv("VALLEY_APPROVAL_PIV", "9c")
397 if status := w.approve("--head", w.head, w.id); status != 0 {
398 t.Fatalf("exit %d\n%s%s", status, w.stdout.String(), w.stderr.String())
399 }
400 w.signedAs(w.hardware, record)
401 if scenario == "new-version" && w.record() == record {
402 t.Error("the stand-in readied no new version while the device signed")
403 }
404 if !strings.Contains(w.stderr.String(), "touch the YubiKey (serial 12345678)") {
405 t.Errorf("no touch was asked for:\n%s", w.stderr.String())
406 }
407 })
408 }
409}
410
411// An approval of head A, where the request already stands at A, pushes
412// the note alone. Another approver replacing the request and its approval
413// between approve's one read of both and its push refuses that push,
414// through the lease on the approval, so origin keeps the other approver's
415// request and approval together. A receive-pack that writes both refs
416// first, once, stands in for the other approver. (The hook refuses a note
417// of A beside a request at B however the lease reads: valleyhook's tests.)
418func TestAnApprovalPublishedMeanwhileRefusesThePush(t *testing.T) {
419 w := newSignWorld(t, nil)
420 if status := w.approve("--head", w.head, w.id); status != 0 || w.request() != w.head {
421 t.Fatalf("filing the request unsigned: exit %d\n%s", status, w.stderr.String())
422 }
423 racer := filepath.Join(w.dir, "racing-receive-pack")
424 if err := os.Symlink(os.Args[0], racer); err != nil {
425 t.Fatal(err)
426 }
427 marker := filepath.Join(w.dir, "race-armed")
428 w.write(w.dir, "race-armed", "")
429 w.git("config", "remote.origin.receivepack", racer)
430 request := "refs/the-valley/integration-requests/main/c-" + w.id
431 t.Setenv("VALLEY_TEST_RACE", marker+"\t"+request+"\t"+approvals.Ref(recordTarget, w.id))
432 status := w.approve("--head", w.head, "--approval-key", w.operatorFile, w.id)
433 if _, err := os.Stat(marker); err == nil {
434 t.Fatal("the racing receive-pack never ran")
435 }
436 if status != 1 || !strings.Contains(w.stderr.String(), "another approval of the change was published meanwhile") {
437 t.Errorf("exit %d, stderr %q", status, w.stderr.String())
438 }
439 other := w.onOrigin("refs/heads/main")
440 if w.request() != other || w.approvalRef() != w.run(w.origin, "git", "hash-object", "/dev/null") {
441 t.Errorf("origin holds the request at %s and the approval at %s, not the other approver's", w.request(), w.approvalRef())
442 }
443}
444
445// A signal to approve while the PIV signer's helper reaches the device,
446// or waits for the PIN, stops the helper and waits for it before the
447// command exits 130, and nothing is published. The stand-in device writes
448// its process ID to a FIFO before it sends its key (init-wait), or once
449// it is asked to sign (pin-wait), and waits for a signal.
450func TestASignalStopsThePIVSigner(t *testing.T) {
451 saved := pivSigner
452 pivSigner = os.Args[0]
453 t.Cleanup(func() { pivSigner = saved })
454 for _, scenario := range []string{"init-wait", "pin-wait"} {
455 t.Run(scenario, func(t *testing.T) {
456 w := newSignWorld(t, nil)
457 ended := make(chan int, 1)
458 pid := w.helperWaiting(scenario, func() {
459 run([]string{"approve", "--head", w.head, "--approval-piv", w.id}, &w.stdout, &w.stderr,
460 func(status int) { ended <- status; runtime.Goexit() })
461 }, ended)
462 if err := syscall.Kill(os.Getpid(), syscall.SIGTERM); err != nil {
463 t.Fatal(err)
464 }
465 select {
466 case status := <-ended:
467 if status != interruptedStatus {
468 t.Errorf("approve ended with %d, not %d", status, interruptedStatus)
469 }
470 case <-time.After(time.Minute):
471 t.Fatal("approve did not end on SIGTERM")
472 }
473 if err := syscall.Kill(pid, 0); !errors.Is(err, syscall.ESRCH) {
474 t.Errorf("the PIV signer's helper %d was not stopped and waited for: %v", pid, err)
475 }
476 if r, a := w.request(), w.approvalRef(); r != "" || a != "" {
477 t.Errorf("an interrupted approval left request %q and approval %q", r, a)
478 }
479 })
480 }
481}
482
483// An interrupt that arrives after the PIV signer's helper has started,
484// and before it is registered as approve's child, waits for the
485// registration, then stops the helper and waits for it. A start function
486// the test controls holds that window open: it starts the stand-in, which
487// waits for a signal before it sends its key, and then blocks until the
488// interrupt has begun.
489func TestAnInterruptDuringTheHelpersStartStopsIt(t *testing.T) {
490 savedSigner, savedStart, savedBegins := pivSigner, startPIV, interruptBegins
491 t.Cleanup(func() { pivSigner, startPIV, interruptBegins = savedSigner, savedStart, savedBegins })
492 pivSigner = os.Args[0]
493 w := newSignWorld(t, nil)
494 fifo := filepath.Join(w.dir, "waiting")
495 if err := syscall.Mkfifo(fifo, 0o600); err != nil {
496 t.Fatal(err)
497 }
498 t.Setenv("VALLEY_TEST_FAKE_PIV", "init-wait")
499 t.Setenv("VALLEY_TEST_FAKE_PIV_FIFO", fifo)
500 go os.ReadFile(fifo)
501
502 started, release, began := make(chan int, 1), make(chan struct{}), make(chan struct{}, 1)
503 startPIV = func(program, slot, reader string, prompt io.Writer) (*approvals.PIVSession, error) {
504 p, err := savedStart(program, slot, reader, prompt)
505 if err == nil {
506 started <- p.Process().Pid
507 <-release
508 }
509 return p, err
510 }
511 // Approvals earlier tests left watching take the signal too; only
512 // this one writes to this world's stdout.
513 interruptBegins = func(a *approval) {
514 if a.stdout == io.Writer(&w.stdout) {
515 select {
516 case began <- struct{}{}:
517 default:
518 }
519 }
520 }
521 ended := make(chan int, 1)
522 go run([]string{"approve", "--head", w.head, "--approval-piv", w.id}, &w.stdout, &w.stderr,
523 func(status int) { ended <- status; runtime.Goexit() })
524
525 var pid int
526 select {
527 case pid = <-started:
528 case status := <-ended:
529 t.Fatalf("approve ended with %d before the helper started\n%s", status, w.stderr.String())
530 case <-time.After(time.Minute):
531 t.Fatal("the helper never started")
532 }
533 if err := syscall.Kill(os.Getpid(), syscall.SIGTERM); err != nil {
534 t.Fatal(err)
535 }
536 select {
537 case <-began:
538 case <-time.After(time.Minute):
539 t.Fatal("the interrupt never began")
540 }
541 close(release)
542 select {
543 case status := <-ended:
544 if status != interruptedStatus {
545 t.Errorf("approve ended with %d, not %d", status, interruptedStatus)
546 }
547 case <-time.After(time.Minute):
548 t.Fatal("approve did not end on SIGTERM")
549 }
550 if err := syscall.Kill(pid, 0); !errors.Is(err, syscall.ESRCH) {
551 t.Errorf("the PIV signer's helper %d, started as the interrupt came, was not stopped and waited for: %v", pid, err)
552 }
553 if r, a := w.request(), w.approvalRef(); r != "" || a != "" {
554 t.Errorf("an interrupted approval left request %q and approval %q", r, a)
555 }
556}
557
558// helperWaiting runs approve, which ends by sending its status to ended,
559// with the stand-in device of scenario, and returns the device's process
560// ID once it says, through a FIFO, that it is waiting.
561func (w *signWorld) helperWaiting(scenario string, approve func(), ended chan int) int {
562 w.t.Helper()
563 fifo := filepath.Join(w.dir, "waiting")
564 if err := syscall.Mkfifo(fifo, 0o600); err != nil {
565 w.t.Fatal(err)
566 }
567 w.t.Setenv("VALLEY_TEST_FAKE_PIV", scenario)
568 w.t.Setenv("VALLEY_TEST_FAKE_PIV_FIFO", fifo)
569 waiting := make(chan string, 1)
570 go approve()
571 go func() {
572 pid, _ := os.ReadFile(fifo)
573 waiting <- strings.TrimSpace(string(pid))
574 }()
575 select {
576 case p := <-waiting:
577 pid, _ := strconv.Atoi(p)
578 return pid
579 case status := <-ended:
580 w.t.Fatalf("approve ended with %d before the device was waiting\n%s", status, w.stderr.String())
581 case <-time.After(time.Minute):
582 w.t.Fatal("the device never said it was waiting")
583 }
584 return 0
585}
586
587// waitingFor writes this process's ID to the FIFO the test names, after
588// stop is set up to catch the signals that end the stand-in.
589func waitingFor(stop chan os.Signal) bool {
590 signal.Notify(stop, os.Interrupt, syscall.SIGTERM)
591 f, err := os.OpenFile(os.Getenv("VALLEY_TEST_FAKE_PIV_FIFO"), os.O_WRONLY, 0)
592 if err != nil {
593 return false
594 }
595 fmt.Fprintf(f, "%d\n", os.Getpid())
596 return f.Close() == nil
597}
598
599// extraFakePIV are stand-in scenarios a platform's tests add, run once
600// the stand-in is asked to sign, as the helper asks for the PIN.
601var extraFakePIV = map[string]func() int{}
602
603// What a publication or a key file says reaches the terminal as one line
604// of printable text: an escape byte in an approval-signers entry, or in a
605// key file's key type, is written escaped.
606func TestApprovalDiagnosticsAreEscaped(t *testing.T) {
607 w := newSignWorld(t, func(w *signWorld) { w.signers = "operator\x1b[2J+00000000+AAAA\n" })
608 w.nothingPublished(w.approve("--head", w.head, "--approval-key", w.operatorFile, w.id), "could not read the published approval keys")
609 bad := filepath.Join(w.dir, "bad.key")
610 if err := os.WriteFile(bad, opensshKeyOfKind(w.operator, "ssh-\x1b]0;title\x07"), 0o600); err != nil {
611 t.Fatal(err)
612 }
613 stderr := w.stderr.String()
614 w = newSignWorld(t, nil)
615 w.nothingPublished(w.approve("--head", w.head, "--approval-key", bad, w.id), "could not read the approval key")
616 for _, says := range []string{stderr, w.stderr.String()} {
617 if strings.ContainsAny(says, "\x1b\x07") || !strings.Contains(says, `\x1b`) {
618 t.Errorf("a diagnostic was not escaped: %q", says)
619 }
620 }
621}
622
623// Review's [a]pprove signs as the approve verb does with a key, and says
624// no signed approval was written without one.
625func TestReviewApprovalSigns(t *testing.T) {
626 for _, key := range []bool{true, false} {
627 w := newSignWorld(t, nil)
628 record := w.record()
629 answers := filepath.Join(w.dir, "answers")
630 w.write(w.dir, "answers", "a\n")
631 stdin, err := os.Open(answers)
632 if err != nil {
633 t.Fatal(err)
634 }
635 defer stdin.Close()
636 var selected *approvalKey
637 if key {
638 selected = &approvalKey{file: w.operatorFile, from: "--approval-key"}
639 }
640 g := git{env: gitEnvironment(os.Environ()), stderr: &w.stderr, dir: w.work}
641 o := reviewChange(reviewStep{g: g, key: selected, stdin: stdin, stdout: &w.stdout, stderr: &w.stderr,
642 signers: &signerSource{g: g, stderr: &w.stderr}, interrupts: make(chan os.Signal),
643 end: func(int, stepOutcome) { t.Fatal("the review was ended by a signal") }}, w.id)
644 if o.kind != "approved" {
645 t.Fatalf("the review ended %s\n%s%s", o.kind, w.stdout.String(), w.stderr.String())
646 }
647 if key {
648 w.signedAs(w.signers, record)
649 } else if w.approvalRef() != "" || !strings.Contains(w.stdout.String(), unsignedLine) {
650 t.Errorf("an unsigned review left approval %q, stdout:\n%s", w.approvalRef(), w.stdout.String())
651 }
652 }
653}
654
655// opensshKey is priv as the OpenSSH private key file ssh-keygen writes
656// for an ed25519 key with no passphrase.
657func opensshKey(priv ed25519.PrivateKey) []byte { return opensshKeyOfKind(priv, "ssh-ed25519") }
658
659// opensshKeyOfKind is that file with another key type written in it.
660func opensshKeyOfKind(priv ed25519.PrivateKey, kindName string) []byte {
661 str := func(b []byte) []byte { return append(binary.BigEndian.AppendUint32(nil, uint32(len(b))), b...) }
662 pub := priv.Public().(ed25519.PublicKey)
663 kind := str([]byte(kindName))
664 section := binary.BigEndian.AppendUint32(binary.BigEndian.AppendUint32(nil, 7), 7)
665 section = append(append(append(append(section, kind...), str(pub)...), str(priv)...), str(nil)...)
666 for i := byte(1); len(section)%8 != 0; i++ {
667 section = append(section, i)
668 }
669 body := append([]byte("openssh-key-v1\x00"), str([]byte("none"))...)
670 body = append(append(body, str([]byte("none"))...), str(nil)...)
671 body = binary.BigEndian.AppendUint32(body, 1)
672 body = append(append(body, str(append(kind, str(pub)...))...), str(section)...)
673 return pem.EncodeToMemory(&pem.Block{Type: "OPENSSH PRIVATE KEY", Bytes: body})
674}
675
676// fakePIV speaks valley-piv-signer's protocol (approval/piv.go) for the
677// device seeded "device", which approval-signers-hardware lists. Asked to
678// sign, it does what the scenario says first.
679func fakePIV(scenario string) int {
680 if scenario == "init-wait" {
681 stop := make(chan os.Signal, 1)
682 if waitingFor(stop) {
683 <-stop
684 }
685 return 1
686 }
687 if scenario == "absent" {
688 fmt.Println("error device no YubiKey could be reached: PCSC error")
689 return 1
690 }
691 device := seeded("device")
692 tmpl := &x509.Certificate{SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: "YubiKey PIV Attestation 9c"},
693 NotBefore: time.Unix(0, 0), NotAfter: time.Unix(1<<33, 0)}
694 der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, device.Public(), device)
695 if err != nil {
696 fmt.Println("error device", err)
697 return 1
698 }
699 fmt.Printf("key 12345678 %x\n", der)
700 var line string
701 var n int
702 if _, err := fmt.Scanf("sign %d %s\n", &n, &line); err != nil {
703 return 0
704 }
705 text := make([]byte, n)
706 if _, err := io.ReadFull(os.Stdin, text); err != nil {
707 return 1
708 }
709 id := strings.Repeat("m", 32)
710 quiet := func(args ...string) {
711 if code := cli(args, io.Discard, os.Stderr, os.Exit); code != 0 {
712 os.Exit(code)
713 }
714 }
715 switch scenario {
716 case "pin-wait", "echo-off":
717 if f := extraFakePIV[scenario]; f != nil {
718 return f()
719 }
720 stop := make(chan os.Signal, 1)
721 if waitingFor(stop) {
722 <-stop
723 }
724 fmt.Println("error cancelled")
725 return 1
726 case "touch":
727 fmt.Println("touch\nerror touch")
728 return 1
729 case "publish":
730 repo := os.Getenv("VALLEY_TEST_FAKE_PIV_VALLEY")
731 blob, err := exec.Command("git", "-C", repo, "hash-object", "-w", "/dev/null").Output()
732 if err != nil {
733 return 1
734 }
735 out, err := exec.Command("git", "-C", repo, "ls-tree", signersRef).Output()
736 if err != nil {
737 return 1
738 }
739 mktree := exec.Command("git", "-C", repo, "mktree")
740 mktree.Stdin = strings.NewReader(string(out) + "100644 blob " + strings.TrimSpace(string(blob)) + "\tchanged\n")
741 tree, err := mktree.Output()
742 if err != nil || exec.Command("git", "-C", repo, "update-ref", signersRef, strings.TrimSpace(string(tree))).Run() != nil {
743 return 1
744 }
745 case "withdraw":
746 quiet("withdraw", id)
747 case "new-version":
748 os.WriteFile("readme.md", []byte("a better readme\n"), 0o644)
749 if exec.Command("git", "commit", "--quiet", "-am", "a better readme").Run() != nil ||
750 exec.Command("git", "push", "--quiet", "origin", "HEAD:topic").Run() != nil {
751 return 1
752 }
753 quiet("ready", "--change", id, "topic")
754 }
755 fmt.Printf("touch\nsignature %x\n", ed25519.Sign(device, text))
756 io.Copy(io.Discard, os.Stdin)
757 return 0
758}
759
760// racingReceivePack writes the refs VALLEY_TEST_RACE names in the
761// repository it receives into, once, while the marker file it names is
762// there, and then receives the push: an integration request at main, and
763// any other ref at the empty blob.
764func racingReceivePack(args []string) int {
765 race := strings.Split(os.Getenv("VALLEY_TEST_RACE"), "\t")
766 repo := args[len(args)-1]
767 if os.Remove(race[0]) == nil {
768 blob, err := exec.Command("git", "-C", repo, "hash-object", "-w", "/dev/null").Output()
769 main, merr := exec.Command("git", "-C", repo, "rev-parse", "refs/heads/main").Output()
770 if err != nil || merr != nil {
771 return 1
772 }
773 for _, ref := range race[1:] {
774 value := blob
775 if strings.HasPrefix(ref, "refs/the-valley/integration-requests/") {
776 value = main
777 }
778 if exec.Command("git", "-C", repo, "update-ref", ref, strings.TrimSpace(string(value))).Run() != nil {
779 return 1
780 }
781 }
782 }
783 cmd := exec.Command("git", append([]string{"receive-pack"}, args...)...)
784 cmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr
785 if err := cmd.Run(); err != nil {
786 return 1
787 }
788 return 0
789}