gunk-dev/the-valley

attestation_test.go

sourceb115ae7362ffmain's published tip history
33.1 KiB
1package main
2
3import (
4 "bytes"
5 "crypto/ecdsa"
6 "crypto/ed25519"
7 "crypto/elliptic"
8 "crypto/rand"
9 "crypto/sha256"
10 "crypto/x509"
11 "crypto/x509/pkix"
12 "encoding/asn1"
13 "encoding/base64"
14 "encoding/binary"
15 "encoding/hex"
16 "encoding/pem"
17 "math/big"
18 "os"
19 "slices"
20 "strings"
21 "testing"
22 "time"
23
24 "the-valley/approval"
25 "the-valley/note"
26)
27
28// The device fixtures are the-valley operator's own approval key, from a
29// YubiKey 5C (firmware 5.7.4): an Ed25519 key generated in PIV slot 9c
30// with PIN policy always and touch policy always, the slot certificate the
31// YubiKey wrote for it, its f9 certificate, and a 2075-byte text the key
32// signed with a touch (`yubico-piv-tool -a verify-pin --sign -A ED25519 -s
33// 9c`). They are test vectors and stay in testdata/ (testdata/README.md):
34// only a real device's chain verifies to Yubico's root.
35
36func testdata(t *testing.T, name string) string {
37 t.Helper()
38 b, err := os.ReadFile("testdata/" + name)
39 if err != nil {
40 t.Fatal(err)
41 }
42 return string(b)
43}
44
45// deviceKey is the device key's registry line.
46func deviceKey(t *testing.T) string {
47 return strings.TrimSpace(testdata(t, "valley-approve.pub"))
48}
49
50// deviceReport is what the compiler reports for the device's attestation.
51func deviceReport(t *testing.T) string {
52 return strings.TrimSpace(testdata(t, "valley-approve.report"))
53}
54
55func deviceAttestation(t *testing.T) attestation {
56 return attestation{Slot: testdata(t, "valley-approve.attest.pem"), F9: testdata(t, "yubico-f9.pem")}
57}
58
59func devicePublic(t *testing.T) ed25519.PublicKey {
60 t.Helper()
61 pub, err := sshEd25519Public(deviceKey(t))
62 if err != nil {
63 t.Fatal(err)
64 }
65 return pub
66}
67
68// The registry's ssh-ed25519 line and the PEM public key the YubiKey
69// exported are one key.
70func TestTheDeviceKeyIsTheExportedKey(t *testing.T) {
71 block, _ := pem.Decode([]byte(testdata(t, "valley-approve.pub.pem")))
72 exported, err := x509.ParsePKIXPublicKey(block.Bytes)
73 if err != nil {
74 t.Fatal(err)
75 }
76 if !devicePublic(t).Equal(exported) {
77 t.Fatalf("%s is not the exported key", deviceKey(t))
78 }
79}
80
81// The pinned root is the one Yubico publishes, by the fingerprint Yubico
82// publishes for it, and each pinned intermediate is a PIV one beneath it.
83func TestThePinnedCertificatesAreYubicosPIVChain(t *testing.T) {
84 const fingerprint = "62:76:0C:6A:6E:F9:16:79:F4:54:C8:90:2B:80:FD:00:98:25:B3:F2:5D:A9:0F:1F:BA:CE:2E:C6:58:6C:D5:A8"
85 block, _ := pem.Decode(yubicoRootPEM)
86 sum := sha256.Sum256(block.Bytes)
87 got := strings.ToUpper(hex.EncodeToString(sum[:]))
88 if got != strings.ReplaceAll(fingerprint, ":", "") {
89 t.Errorf("the pinned root's SHA-256 is %s, not Yubico Attestation Root 1's", got)
90 }
91 root, err := x509.ParseCertificate(block.Bytes)
92 if err != nil {
93 t.Fatal(err)
94 }
95 if root.Subject.CommonName != "Yubico Attestation Root 1" {
96 t.Errorf("the pinned root is %q", root.Subject.CommonName)
97 }
98
99 var names []string
100 for rest := yubicoIntermediatesPEM; ; {
101 var block *pem.Block
102 if block, rest = pem.Decode(rest); block == nil {
103 break
104 }
105 cert, err := x509.ParseCertificate(block.Bytes)
106 if err != nil {
107 t.Fatal(err)
108 }
109 names = append(names, cert.Subject.CommonName)
110 if _, err := cert.Verify(x509.VerifyOptions{
111 Roots: yubico.roots, Intermediates: yubico.intermediates,
112 KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageAny},
113 }); err != nil {
114 t.Errorf("the pinned %s does not verify to the root: %v", cert.Subject.CommonName, err)
115 }
116 }
117 want := []string{
118 "Yubico Attestation Intermediate A 1",
119 "Yubico Attestation Intermediate B 1",
120 "Yubico PIV Attestation A 1",
121 "Yubico PIV Attestation B 1",
122 "Yubico PIV Attestation B2 1",
123 }
124 if !slices.Equal(names, want) {
125 t.Errorf("the pinned intermediates are %q, want %q", names, want)
126 }
127}
128
129// The real device's attestation verifies with Go's crypto/x509, through
130// its f9 certificate, Yubico PIV Attestation B 1 and Yubico Attestation
131// Intermediate B 1, to the pinned root, and says what the device spike
132// observed.
133func TestTheDeviceAttestationVerifies(t *testing.T) {
134 got, err := verifyAttestation(deviceAttestation(t), devicePublic(t), day(t, "2026-10-22"), yubico)
135 if err != nil {
136 t.Fatal(err)
137 }
138 if !got.hardware() {
139 t.Error("the device's touch-always key is not a hardware key")
140 }
141 if want := deviceReport(t); got.String() != want {
142 t.Errorf("reported %q, want %q", got, want)
143 }
144}
145
146// The example registry's attestation (examples/identity/attested/) is a
147// synthetic chain under a test-only root, "the-valley example attestation
148// root, not Yubico". The compiler refuses it under the pinned Yubico
149// roots, so an entry copied from the example compiles only with a real
150// device's certificates. Under the test-only root it verifies, so the root
151// is the one thing wrong with it. The identity-e2e check holds the example
152// to these same certificates and has the compiler refuse it.
153func TestTheExampleAttestationVerifiesOnlyUnderItsTestRoot(t *testing.T) {
154 const exampleKey = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAID/3+vgQhY5cdQ4AqspQ1A2yW60nn4j1FOyx04WfuQjc"
155 pub, err := sshEd25519Public(exampleKey)
156 if err != nil {
157 t.Fatal(err)
158 }
159 if !testPrivateKey("the-valley example approval key").Public().(ed25519.PublicKey).Equal(pub) {
160 t.Fatal("the example key is not the one derived from its published seed")
161 }
162 example := attestation{Slot: testdata(t, "example-slot.pem"), F9: testdata(t, "example-f9.pem")}
163 on := day(t, "2026-10-23")
164
165 _, err = verifyAttestation(example, pub, on, yubico)
166 if err == nil || !strings.Contains(err.Error(), "does not verify to Yubico Attestation Root 1: x509: certificate signed by unknown authority") {
167 t.Errorf("under the pinned Yubico roots: error = %v", err)
168 }
169
170 root, err := x509.ParseCertificate(pemBytes(t, testdata(t, "example-root.pem")))
171 if err != nil {
172 t.Fatal(err)
173 }
174 if root.Subject.CommonName != "the-valley example attestation root, not Yubico" {
175 t.Fatalf("the test-only root is %q", root.Subject.CommonName)
176 }
177 testOnly := trust{roots: x509.NewCertPool(), intermediates: x509.NewCertPool()}
178 testOnly.roots.AddCert(root)
179 got, err := verifyAttestation(example, pub, on, testOnly)
180 if err != nil {
181 t.Fatalf("under the test-only root: %v", err)
182 }
183 if want := "YubiKey serial 12345678, firmware 5.7.4, PIN policy always, touch policy always"; got.String() != want || !got.hardware() {
184 t.Errorf("under the test-only root: reported %q, hardware %v", got, got.hardware())
185 }
186}
187
188// Each way the device's own attestation can be wrong is refused. None of
189// them leaves a key that is merely not hardware: each is an error.
190func TestAttestationsThatDoNotVerifyAreRefused(t *testing.T) {
191 good := deviceAttestation(t)
192 pub := devicePublic(t)
193 on := day(t, "2026-10-22")
194 other := newTestPKI(t)
195
196 slotDER := pemBytes(t, good.Slot)
197 f9DER := pemBytes(t, good.F9)
198
199 // The touch policy is inside what Yubico's signature covers: the
200 // policy extension's value, 03 02, edited to 03 03 (cached).
201 policy := []byte{0x06, 0x0a, 0x2b, 0x06, 0x01, 0x04, 0x01, 0x82, 0xc4, 0x0a, 0x03, 0x08, 0x04, 0x02, 0x03, 0x02}
202 if bytes.Count(slotDER, policy) != 1 {
203 t.Fatal("the slot certificate's policy extension is not where this test looks")
204 }
205 cached := bytes.Replace(slotDER, policy, append(policy[:len(policy)-1:len(policy)-1], 0x03), 1)
206
207 for name, c := range map[string]struct {
208 a attestation
209 pub ed25519.PublicKey
210 on time.Time
211 trust trust
212 want string
213 }{
214 "another root": {good, pub, on, other.trust, "does not verify"},
215 "no intermediates": {good, pub, on,
216 trust{roots: yubico.roots, intermediates: x509.NewCertPool()}, "does not verify"},
217 "a slot certificate with its policy edited": {
218 attestation{Slot: pemText(cached), F9: good.F9}, pub, on, yubico, "does not verify"},
219 "a slot certificate with its signature altered": {
220 attestation{Slot: pemText(flipLast(slotDER)), F9: good.F9}, pub, on, yubico, "does not verify"},
221 "an f9 certificate with its signature altered": {
222 attestation{Slot: good.Slot, F9: pemText(flipLast(f9DER))}, pub, on, yubico, "does not verify"},
223 "the slot certificate given as f9": {
224 attestation{Slot: good.Slot, F9: good.Slot}, pub, on, yubico, "does not verify"},
225 "another key": {good, ed25519.PublicKey(make([]byte, ed25519.PublicKeySize)), on, yubico, "a different key"},
226 "a day before the certificates": {good, pub, day(t, "2024-11-30"), yubico, "does not verify"},
227 "a slot that is not PEM": {
228 attestation{Slot: "MIICJzCCAQ+gAwIBAgIQ", F9: good.F9}, pub, on, yubico, "not PEM"},
229 "text beside the PEM": {
230 attestation{Slot: good.Slot + "trailing words\n", F9: good.F9}, pub, on, yubico, "beside its one PEM block"},
231 "text before the PEM": {
232 attestation{Slot: "leading words\n" + good.Slot, F9: good.F9}, pub, on, yubico, "beside its one PEM block"},
233 "two certificates as f9": {
234 attestation{Slot: good.Slot, F9: good.F9 + good.F9}, pub, on, yubico, "beside its one PEM block"},
235 "a public key as the slot": {
236 attestation{Slot: testdata(t, "valley-approve.pub.pem"), F9: good.F9}, pub, on, yubico, "not a plain certificate"},
237 } {
238 _, err := verifyAttestation(c.a, c.pub, c.on, c.trust)
239 if err == nil || !strings.Contains(err.Error(), c.want) {
240 t.Errorf("%s: error = %v, want one saying %q", name, err, c.want)
241 }
242 }
243}
244
245// The touch policy decides: only always makes a hardware key. The device
246// fixture is touch-always, so the other policies are attested here under
247// a stand-in for Yubico's PKI.
248func TestOnlyTouchAlwaysIsHardware(t *testing.T) {
249 pki := newTestPKI(t)
250 pub, _ := testKey("approver")
251 for touch, want := range map[byte]bool{1: false, 2: true, 3: false} {
252 got, err := verifyAttestation(pki.attest(t, pub, policyExtension(3, touch)), pub, day(t, "2026-10-22"), pki.trust)
253 if err != nil {
254 t.Fatalf("touch policy %d: %v", touch, err)
255 }
256 if got.hardware() != want {
257 t.Errorf("touch policy %d: hardware = %v, want %v", touch, got.hardware(), want)
258 }
259 }
260}
261
262// Every signed fault fails the compilation, one fault at a time. Each case
263// is a stand-in attestation of the same key that a key holder could
264// present, correct in every respect but the one its name gives, and
265// signed by the keys its certificates name. The control case, with no
266// fault, compiles the key into the hardware file, so each failure is the
267// fault's alone.
268func TestEachSignedFaultFailsTheCompilation(t *testing.T) {
269 pki := newTestPKI(t)
270 trustBoth(t, pki)
271 pub, line := testKey("approver")
272
273 // device is an f9 certificate the stand-in intermediate signs, with
274 // its template edited first.
275 device := func(edit func(*x509.Certificate)) (*x509.Certificate, ed25519.PrivateKey) {
276 f9Pub, f9Key, _ := ed25519.GenerateKey(rand.Reader)
277 template := f9Template()
278 edit(template)
279 return pki.issue(t, pki.intermediate, pki.intermediateKey, template, f9Pub), f9Key
280 }
281 // slot is f9's attestation of the key, touch policy always, with its
282 // template edited first. It is not parsed here, so it may be one Go
283 // refuses to read.
284 slot := func(f9 *x509.Certificate, f9Key ed25519.PrivateKey, edit func(*x509.Certificate)) attestation {
285 template := leafTemplate(policyExtension(3, 2))
286 edit(template)
287 return attestation{Slot: pemText(sign(t, template, f9, f9Key, pub)), F9: pemText(f9.Raw)}
288 }
289 under := func(edit func(*x509.Certificate)) attestation {
290 f9, f9Key := device(edit)
291 return slot(f9, f9Key, none)
292 }
293 stated := func(edit func(*x509.Certificate)) attestation {
294 return slot(pki.f9, pki.f9Key, edit)
295 }
296 // policy replaces the policy extension's value.
297 policy := func(value ...byte) func(*x509.Certificate) {
298 return func(c *x509.Certificate) { c.ExtraExtensions[2].Value = value }
299 }
300 expired := func(c *x509.Certificate) { c.NotAfter = time.Date(2026, 10, 21, 0, 0, 0, 0, time.UTC) }
301
302 // A slot certificate signed by f9's key under another issuer name.
303 renamed := *pki.f9
304 renamed.RawSubject = nil
305 renamed.Subject = pkix.Name{CommonName: "YubiKey PIV Attestation, another"}
306
307 // An f9 certificate the key holder made: self-signed, or signed by
308 // the holder's own key under the stand-in intermediate's name.
309 ownPub, ownKey, _ := ed25519.GenerateKey(rand.Reader)
310 ownF9 := pki.issue(t, nil, ownKey, f9Template(), ownPub)
311 forger := *pki.intermediate
312 forger.PublicKey = ownPub
313 forgedPub, forgedKey, _ := ed25519.GenerateKey(rand.Reader)
314 forgedF9 := pki.issue(t, &forger, ownKey, f9Template(), forgedPub)
315 // A slot certificate the attested key signed for itself.
316 selfSigned := pki.issue(t, nil, testPrivateKey("approver"), leafTemplate(policyExtension(3, 2)), pub)
317
318 ec, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
319 if err != nil {
320 t.Fatal(err)
321 }
322 ecSlot := pki.issue(t, pki.f9, pki.f9Key, leafTemplate(policyExtension(3, 2)), &ec.PublicKey)
323 direct := pki.issue(t, pki.intermediate, pki.intermediateKey, leafTemplate(policyExtension(3, 2)), pub)
324
325 compile := func(a attestation) (artifacts, error) {
326 r := governedRegistry()
327 r.Boundaries["approve"] = boundary{Kind: boundaryApprove}
328 founder := r.Principals["founder"]
329 founder.Grants["approve"] = grant{Boundary: "approve"}
330 founder.Keys = append(founder.Keys, key{Class: sshEd25519, Bound: "hardware", Public: line, Attestation: &a})
331 r.Principals["founder"] = founder
332 return render(r, day(t, "2026-10-22"), nil)
333 }
334
335 // Three faults keep a signature f9's key made and only break the
336 // chain around it: f9 is no CA, f9 states no basic constraints, or the
337 // slot certificate names another issuer. Each slot certificate is
338 // checked here to verify under its f9 key, so the refusal below is the
339 // fault's and not a bad signature's.
340 nonCA := under(func(c *x509.Certificate) { c.IsCA, c.MaxPathLen, c.MaxPathLenZero = false, 0, false })
341 noConstraints := under(func(c *x509.Certificate) { c.BasicConstraintsValid = false })
342 misnamed := slot(&renamed, pki.f9Key, none)
343 for _, a := range []attestation{nonCA, noConstraints, misnamed} {
344 slotCert, err := x509.ParseCertificate(pemBytes(t, a.Slot))
345 if err != nil {
346 t.Fatal(err)
347 }
348 f9Cert, err := x509.ParseCertificate(pemBytes(t, a.F9))
349 if err != nil {
350 t.Fatal(err)
351 }
352 if err := f9Cert.CheckSignature(slotCert.SignatureAlgorithm, slotCert.RawTBSCertificate, slotCert.Signature); err != nil {
353 t.Fatalf("a slot certificate meant to be signed by its f9 key is not: %v", err)
354 }
355 }
356
357 control, err := compile(stated(none))
358 if err != nil {
359 t.Fatalf("the attestation with no fault: %v", err)
360 }
361 if !strings.Contains(string(control.approvalHardware), note.NewVerifierKey("founder", pub).String()) {
362 t.Fatalf("the attestation with no fault left the key out of the hardware file:\n%s", control.approvalHardware)
363 }
364
365 for _, c := range []struct {
366 name string
367 a attestation
368 want string
369 }{
370 // The chain.
371 {"an expired slot certificate", stated(expired), "has expired"},
372 {"an expired f9 certificate", under(expired), "has expired"},
373 {"an f9 certificate that is not a CA", nonCA, "parent certificate cannot sign"},
374 {"an f9 certificate without basic constraints", noConstraints, "parent certificate cannot sign"},
375 {"an issuer name that is not f9's", misnamed, "signed by unknown authority"},
376 {"a slot certificate the intermediate signed", attestation{Slot: pemText(direct.Raw), F9: pemText(pki.f9.Raw)}, "without its f9 certificate"},
377 // Anchors the key holder supplies.
378 {"a self-signed f9 certificate", slot(ownF9, ownKey, none), "signed by unknown authority"},
379 {"an f9 certificate the holder signed under the intermediate's name", slot(forgedF9, forgedKey, none), "Ed25519 verification failure"},
380 {"a self-signed slot certificate", attestation{Slot: pemText(selfSigned.Raw), F9: pemText(pki.f9.Raw)}, "signed by unknown authority"},
381 // The key.
382 {"an ECDSA key", attestation{Slot: pemText(ecSlot.Raw), F9: pemText(pki.f9.Raw)}, "attests a key of type ECDSA, not Ed25519"},
383 // The policy extension.
384 {"no policy extension", stated(func(c *x509.Certificate) { c.ExtraExtensions = c.ExtraExtensions[:2] }), "states no PIN and touch policy"},
385 {"a critical policy extension", stated(func(c *x509.Certificate) { c.ExtraExtensions[2].Critical = true }), "unhandled critical extension"},
386 {"two policy extensions", stated(func(c *x509.Certificate) {
387 c.ExtraExtensions = append(c.ExtraExtensions, policyExtension(3, 3))
388 }), "duplicate extension"},
389 {"a policy of no bytes", stated(policy()), "PIN and touch policy"},
390 {"a policy of one byte", stated(policy(3)), "is 1 byte(s), not 2"},
391 {"a policy of three bytes", stated(policy(3, 2, 2)), "is 3 byte(s), not 2"},
392 {"PIN policy 0x00", stated(policy(0, 2)), "PIN policy 0x00, which Yubico does not specify"},
393 {"PIN policy 0x04", stated(policy(4, 2)), "PIN policy 0x04, which Yubico does not specify"},
394 {"PIN policy 0xff", stated(policy(0xff, 2)), "PIN policy 0xff, which Yubico does not specify"},
395 {"touch policy 0x00", stated(policy(3, 0)), "touch policy 0x00, which Yubico does not specify"},
396 {"touch policy 0x04", stated(policy(3, 4)), "touch policy 0x04, which Yubico does not specify"},
397 {"touch policy 0xff", stated(policy(3, 0xff)), "touch policy 0xff, which Yubico does not specify"},
398 } {
399 a, err := compile(c.a)
400 if err == nil {
401 t.Errorf("%s: compiled, with hardware file\n%s", c.name, a.approvalHardware)
402 continue
403 }
404 if want := "founder: key 1: "; !strings.Contains(err.Error(), want) || !strings.Contains(err.Error(), c.want) {
405 t.Errorf("%s: error = %v, want one naming founder's key 1 and saying %q", c.name, err, c.want)
406 }
407 }
408}
409
410// none edits nothing.
411func none(*x509.Certificate) {}
412
413// approvalRegistry exercises every reason a key is or is not in the
414// approval files. founder governs and approves with three keys: an
415// ordinary one, the device's touch-always key, and a stand-in key whose
416// touch is cached. second approves under the grant's first name with a
417// stand-in touch-always key. departed has expired, pusher holds no
418// approve grant, and robot is not a human, so none of their keys appear.
419func approvalRegistry(t *testing.T, pki testPKI) registry {
420 t.Helper()
421 r := governedRegistry()
422 r.Boundaries["approve"] = boundary{Kind: boundaryApprove}
423 r.Boundaries["request"] = boundary{Kind: boundaryRequest}
424 approve := grant{Boundary: "approve"}
425 attestedKey := func(seed string, touch byte) key {
426 pub, line := testKey(seed)
427 a := pki.attest(t, pub, policyExtension(3, touch))
428 return key{Class: sshEd25519, Bound: "hardware", Public: line, Attestation: &a}
429 }
430 plainKey := func(seed string) key {
431 _, line := testKey(seed)
432 return key{Class: sshEd25519, Bound: "host", Public: line}
433 }
434
435 founder := r.Principals["founder"]
436 device := deviceAttestation(t)
437 founder.Keys = append(founder.Keys,
438 key{Class: sshEd25519, Bound: "hardware", Public: deviceKey(t), Attestation: &device},
439 attestedKey("cached", 3),
440 )
441 founder.Grants["approve"] = approve
442 r.Principals["founder"] = founder
443
444 r.Principals["second"] = principal{
445 Kind: kindHuman,
446 Keys: []key{attestedKey("second", 2)},
447 Grants: map[string]grant{"request": {Boundary: "request"}},
448 }
449 r.Principals["departed"] = principal{
450 Kind: kindHuman,
451 Keys: []key{attestedKey("departed", 2)},
452 Grants: map[string]grant{"approve": approve},
453 Expires: "2026-09-01",
454 }
455 r.Principals["pusher"] = principal{
456 Kind: kindHuman,
457 Keys: []key{plainKey("pusher")},
458 Grants: map[string]grant{"push": {Boundary: "push"}},
459 }
460 r.Principals["robot"] = principal{
461 Kind: "machine",
462 Keys: []key{attestedKey("robot", 2)},
463 Grants: map[string]grant{"approve": approve},
464 Expires: "2027-01-01",
465 }
466 return r
467}
468
469// The whole of both files, byte for byte, with the lines written by the
470// note package rather than by the compiler.
471func TestApprovalFilesListHumanApproversAndTheirHardwareKeys(t *testing.T) {
472 pki := newTestPKI(t)
473 trustBoth(t, pki)
474 r := approvalRegistry(t, pki)
475 a, err := render(r, day(t, "2026-10-22"), nil)
476 if err != nil {
477 t.Fatal(err)
478 }
479
480 line := func(name, public string) string {
481 pub, err := sshEd25519Public(public)
482 if err != nil {
483 t.Fatal(err)
484 }
485 return note.NewVerifierKey(name, pub).String()
486 }
487 _, cached := testKey("cached")
488 _, second := testKey("second")
489 founderPlain := r.Principals["founder"].Keys[0].Public
490 all := []string{line("founder", founderPlain), line("founder", deviceKey(t)), line("founder", cached), line("second", second)}
491 hardware := []string{line("founder", deviceKey(t)), line("second", second)}
492 for _, c := range []struct {
493 name string
494 got []byte
495 count int
496 head string
497 want []string
498 }{
499 {"approval-signers", a.approvalSigners, a.approvers, approvalSignersHeader, all},
500 {"approval-signers-hardware", a.approvalHardware, a.hardware, approvalHardwareHeader, hardware},
501 } {
502 slices.Sort(c.want)
503 want := c.head + strings.Join(c.want, "\n") + "\n"
504 if string(c.got) != want {
505 t.Errorf("%s =\n%s\nwant\n%s", c.name, c.got, want)
506 }
507 if c.count != len(c.want) {
508 t.Errorf("%s: count %d, want %d", c.name, c.count, len(c.want))
509 }
510 }
511
512 // Each attested key of a principal still in force is reported for
513 // review, and the expired one is not.
514 for _, want := range []string{
515 "founder: key 1 is on " + deviceReport(t) + "; it approves as a hardware key",
516 "founder: key 2 is on YubiKey serial 12345678, firmware 5.7.4, PIN policy always, touch policy cached; it approves, but not as a hardware key, because its touch policy is not always",
517 "robot: key 0 is on YubiKey serial 12345678, firmware 5.7.4, PIN policy always, touch policy always; its principal approves nothing",
518 } {
519 if !slices.Contains(a.notes, want) {
520 t.Errorf("no report %q among %q", want, a.notes)
521 }
522 }
523 for _, n := range a.notes {
524 if strings.HasPrefix(n, "departed: key") {
525 t.Errorf("an expired entry's key was reported: %q", n)
526 }
527 }
528}
529
530// A registry without approvers compiles both files holding only their
531// headers, and the note reader reads each as no keys.
532func TestARegistryWithoutApproversCompilesEmptyFiles(t *testing.T) {
533 a, err := render(governedRegistry(), day(t, "2026-10-22"), nil)
534 if err != nil {
535 t.Fatal(err)
536 }
537 for _, f := range [][]byte{a.approvalSigners, a.approvalHardware} {
538 keys, err := note.ParseVerifierKeys(f)
539 if err != nil || len(keys) != 0 {
540 t.Errorf("%q: %d keys, %v", f, len(keys), err)
541 }
542 }
543 if string(a.approvalSigners) != approvalSignersHeader || string(a.approvalHardware) != approvalHardwareHeader {
544 t.Errorf("the empty files are %q and %q", a.approvalSigners, a.approvalHardware)
545 }
546}
547
548// Rendering is reproducible: the order of principals and keys in the
549// registry does not reach the files.
550func TestApprovalFilesRenderTheSameWhateverTheOrder(t *testing.T) {
551 pki := newTestPKI(t)
552 trustBoth(t, pki)
553 r := approvalRegistry(t, pki)
554 first, err := render(r, day(t, "2026-10-22"), nil)
555 if err != nil {
556 t.Fatal(err)
557 }
558 founder := r.Principals["founder"]
559 slices.Reverse(founder.Keys)
560 r.Principals["founder"] = founder
561 second, err := render(r, day(t, "2026-10-22"), nil)
562 if err != nil {
563 t.Fatal(err)
564 }
565 if !bytes.Equal(first.approvalSigners, second.approvalSigners) || !bytes.Equal(first.approvalHardware, second.approvalHardware) {
566 t.Error("reordering founder's keys changed the approval files")
567 }
568}
569
570// Each approval signers file is written opening with the stamp of the
571// commit the registry was read from and the day it was judged on, --now's
572// included, and then the render byte for byte. The same render and source
573// write the same bytes, and a source the stamp cannot name writes nothing.
574func TestApprovalFilesNameTheCommitAndDayTheyRender(t *testing.T) {
575 pki := newTestPKI(t)
576 trustBoth(t, pki)
577 on := day(t, "2026-10-22")
578 a, err := render(approvalRegistry(t, pki), on, nil)
579 if err != nil {
580 t.Fatal(err)
581 }
582 commit := strings.Repeat("5e", 20)
583 source := approval.Authority{Ref: "refs/heads/main", Commit: commit, Day: on}
584 approvers, hardware, err := stampApproval(a, source)
585 if err != nil {
586 t.Fatal(err)
587 }
588 stamp := "# valley-approval-authority-v1 ref=refs/heads/main commit=" + commit + " day=2026-10-22\n"
589 for _, c := range []struct {
590 name string
591 got, rendered []byte
592 }{
593 {"approval-signers", approvers, a.approvalSigners},
594 {"approval-signers-hardware", hardware, a.approvalHardware},
595 } {
596 if string(c.got) != stamp+string(c.rendered) {
597 t.Errorf("%s is written as\n%s\nnot the stamp and the render", c.name, c.got)
598 }
599 if got, err := approval.ReadAuthority(bytes.NewReader(c.got)); err != nil || got != source {
600 t.Errorf("%s's stamp reads as %+v, %v", c.name, got, err)
601 }
602 }
603 again, _, err := stampApproval(a, source)
604 if err != nil || !bytes.Equal(again, approvers) {
605 t.Errorf("stamping one render twice wrote different files (%v)", err)
606 }
607 if _, _, err := stampApproval(a, approval.Authority{Ref: "main", Commit: commit, Day: on}); err == nil {
608 t.Error("a short ref name was stamped")
609 }
610}
611
612// A key that approves belongs to one principal, so the render fails when
613// another principal lists it too, whatever that principal holds.
614func TestAKeyThatApprovesBelongsToOnePrincipal(t *testing.T) {
615 pki := newTestPKI(t)
616 trustBoth(t, pki)
617 for name, holder := range map[string]principal{
618 "another approver": {Kind: kindHuman, Grants: map[string]grant{"approve": {Boundary: "approve"}}},
619 "a principal holding nothing": {Kind: kindHuman, Grants: map[string]grant{}},
620 "a machine": {Kind: "machine", Grants: map[string]grant{}, Expires: "2027-01-01"},
621 } {
622 r := approvalRegistry(t, pki)
623 device := deviceAttestation(t)
624 holder.Keys = []key{{Class: sshEd25519, Bound: "hardware", Public: deviceKey(t), Attestation: &device}}
625 r.Principals["impostor"] = holder
626 _, err := render(r, day(t, "2026-10-22"), nil)
627 if err == nil || !strings.Contains(err.Error(), "founder: key 1 is also impostor's, and a key that approves belongs to one principal") {
628 t.Errorf("%s holding founder's approval key: error = %v", name, err)
629 }
630 }
631}
632
633// An attestation that is offered and does not verify fails the whole
634// render. It is never read as no attestation, which would compile the key
635// into approval-signers as an ordinary key.
636func TestAnAttestationThatDoesNotVerifyFailsTheRender(t *testing.T) {
637 r := governedRegistry()
638 r.Boundaries["approve"] = boundary{Kind: boundaryApprove}
639 founder := r.Principals["founder"]
640 founder.Grants["approve"] = grant{Boundary: "approve"}
641 // The device's attestation, offered for another key.
642 device := deviceAttestation(t)
643 founder.Keys[0].Attestation = &device
644 r.Principals["founder"] = founder
645 _, err := render(r, day(t, "2026-10-22"), nil)
646 if err == nil || !strings.Contains(err.Error(), "founder: key 0: the slot certificate attests a different key") {
647 t.Errorf("render error = %v", err)
648 }
649}
650
651// The device's own signature, made with a touch, opens against both files
652// the device's registry entry compiles to. The same key without its
653// attestation is in approval-signers alone, and the signature does not
654// open against the hardware file.
655func TestTheDeviceSignatureOpensAgainstTheCompiledFiles(t *testing.T) {
656 text := []byte(testdata(t, "spike.txt"))
657 sig, err := base64.StdEncoding.DecodeString(strings.TrimSpace(testdata(t, "spike.sig.b64")))
658 if err != nil {
659 t.Fatal(err)
660 }
661 signed := func(name string) []byte {
662 blob := binary.BigEndian.AppendUint32(nil, note.KeyHash(name, devicePublic(t)))
663 return append(append(append([]byte{}, text...), '\n'),
664 note.Mark+name+" "+base64.StdEncoding.EncodeToString(append(blob, sig...))+"\n"...)
665 }
666 compiled := func(attested bool) artifacts {
667 r := governedRegistry()
668 r.Boundaries["approve"] = boundary{Kind: boundaryApprove}
669 founder := r.Principals["founder"]
670 founder.Grants["approve"] = grant{Boundary: "approve"}
671 k := key{Class: sshEd25519, Bound: "hardware", Public: deviceKey(t)}
672 if attested {
673 device := deviceAttestation(t)
674 k.Attestation = &device
675 }
676 founder.Keys = append(founder.Keys, k)
677 r.Principals["founder"] = founder
678 a, err := render(r, day(t, "2026-10-22"), nil)
679 if err != nil {
680 t.Fatal(err)
681 }
682 return a
683 }
684 opens := func(file []byte) bool {
685 keys, err := note.ParseVerifierKeys(file)
686 if err != nil {
687 t.Fatal(err)
688 }
689 _, _, err = note.Open(signed("founder"), keys)
690 return err == nil
691 }
692
693 a := compiled(true)
694 if !opens(a.approvalSigners) || !opens(a.approvalHardware) {
695 t.Error("the device's signature does not open against the files its attested key compiles to")
696 }
697 a = compiled(false)
698 if !opens(a.approvalSigners) {
699 t.Error("the device's signature does not open against approval-signers without the attestation")
700 }
701 if opens(a.approvalHardware) {
702 t.Error("the device's key is in the hardware file without its attestation")
703 }
704}
705
706// ----------------------------------------------------------------------
707// A stand-in for Yubico's PKI: a root, one intermediate beneath it, and
708// one device whose f9 certificate the intermediate signed. It attests
709// whatever key and policy a test asks for, which a real YubiKey only does
710// for the keys it holds.
711
712type testPKI struct {
713 trust trust
714 root *x509.Certificate
715 intermediate *x509.Certificate
716 intermediateKey ed25519.PrivateKey
717 f9 *x509.Certificate
718 f9Key ed25519.PrivateKey
719}
720
721func newTestPKI(t *testing.T) testPKI {
722 t.Helper()
723 var p testPKI
724 rootPub, rootKey, _ := ed25519.GenerateKey(rand.Reader)
725 p.root = p.issue(t, nil, rootKey, caTemplate("Test Attestation Root", 2), rootPub)
726 interPub, interKey, _ := ed25519.GenerateKey(rand.Reader)
727 p.intermediate = p.issue(t, p.root, rootKey, caTemplate("Test PIV Attestation", 1), interPub)
728 p.intermediateKey = interKey
729 f9Pub, f9Key, _ := ed25519.GenerateKey(rand.Reader)
730 p.f9 = p.issue(t, p.intermediate, interKey, f9Template(), f9Pub)
731 p.f9Key = f9Key
732 p.trust = trust{roots: x509.NewCertPool(), intermediates: x509.NewCertPool()}
733 p.trust.roots.AddCert(p.root)
734 p.trust.intermediates.AddCert(p.intermediate)
735 return p
736}
737
738// attest is the stand-in device's attestation of a key in a slot.
739func (p testPKI) attest(t *testing.T, pub any, extensions ...pkix.Extension) attestation {
740 t.Helper()
741 slot := p.issue(t, p.f9, p.f9Key, leafTemplate(extensions...), pub)
742 return attestation{Slot: pemText(slot.Raw), F9: pemText(p.f9.Raw)}
743}
744
745func (testPKI) issue(t *testing.T, parent *x509.Certificate, parentKey ed25519.PrivateKey, template *x509.Certificate, pub any) *x509.Certificate {
746 t.Helper()
747 cert, err := x509.ParseCertificate(sign(t, template, parent, parentKey, pub))
748 if err != nil {
749 t.Fatal(err)
750 }
751 return cert
752}
753
754// sign makes a certificate and returns its DER unparsed. A nil parent
755// makes it self-signed.
756func sign(t *testing.T, template, parent *x509.Certificate, parentKey ed25519.PrivateKey, pub any) []byte {
757 t.Helper()
758 if parent == nil {
759 parent = template
760 }
761 der, err := x509.CreateCertificate(rand.Reader, template, parent, pub, parentKey)
762 if err != nil {
763 t.Fatal(err)
764 }
765 return der
766}
767
768func caTemplate(name string, pathLen int) *x509.Certificate {
769 return &x509.Certificate{
770 SerialNumber: big.NewInt(1),
771 Subject: pkix.Name{CommonName: name},
772 NotBefore: time.Date(2024, 12, 1, 0, 0, 0, 0, time.UTC),
773 NotAfter: time.Date(9999, 12, 31, 23, 59, 59, 0, time.UTC),
774 IsCA: true,
775 BasicConstraintsValid: true,
776 MaxPathLen: pathLen,
777 KeyUsage: x509.KeyUsageCertSign,
778 }
779}
780
781// f9Template is a device's f9 certificate: a CA that signs slot
782// certificates and nothing beneath them.
783func f9Template() *x509.Certificate {
784 f9 := caTemplate("YubiKey PIV Attestation", 0)
785 f9.MaxPathLenZero = true
786 return f9
787}
788
789// leafTemplate is a slot certificate as a YubiKey writes one: firmware
790// 5.7.4, serial 12345678, and the extensions given.
791func leafTemplate(extensions ...pkix.Extension) *x509.Certificate {
792 serial, _ := asn1.Marshal(big.NewInt(12345678))
793 return &x509.Certificate{
794 SerialNumber: big.NewInt(2),
795 Subject: pkix.Name{CommonName: "YubiKey PIV Attestation 9c"},
796 NotBefore: time.Date(2024, 12, 1, 0, 0, 0, 0, time.UTC),
797 NotAfter: time.Date(9999, 12, 31, 23, 59, 59, 0, time.UTC),
798 ExtraExtensions: append([]pkix.Extension{
799 {Id: extFirmware, Value: []byte{5, 7, 4}},
800 {Id: extSerial, Value: serial},
801 }, extensions...),
802 }
803}
804
805func policyExtension(pin, touch byte) pkix.Extension {
806 return pkix.Extension{Id: extPolicy, Value: []byte{pin, touch}}
807}
808
809// trustBoth has the render trust the stand-in PKI beside Yubico's, so one
810// registry can hold the device's real attestation and stand-in ones.
811func trustBoth(t *testing.T, p testPKI) {
812 t.Helper()
813 pinned := yubico
814 t.Cleanup(func() { yubico = pinned })
815 yubico = trust{roots: pinned.roots.Clone(), intermediates: pinned.intermediates.Clone()}
816 yubico.roots.AddCert(p.root)
817 yubico.intermediates.AddCert(p.intermediate)
818}
819
820// testKey is an Ed25519 public key made from a seed, and its registry
821// line.
822func testKey(seed string) (ed25519.PublicKey, string) {
823 pub := testPrivateKey(seed).Public().(ed25519.PublicKey)
824 var blob []byte
825 for _, f := range [][]byte{[]byte(sshEd25519), pub} {
826 blob = binary.BigEndian.AppendUint32(blob, uint32(len(f)))
827 blob = append(blob, f...)
828 }
829 return pub, sshEd25519 + " " + base64.StdEncoding.EncodeToString(blob)
830}
831
832// testPrivateKey is the private half of testKey's key.
833func testPrivateKey(seed string) ed25519.PrivateKey {
834 s := sha256.Sum256([]byte(seed))
835 return ed25519.NewKeyFromSeed(s[:])
836}
837
838func pemText(der []byte) string {
839 return string(pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}))
840}
841
842func pemBytes(t *testing.T, text string) []byte {
843 t.Helper()
844 block, _ := pem.Decode([]byte(text))
845 if block == nil {
846 t.Fatal("not PEM")
847 }
848 return block.Bytes
849}
850
851// flipLast changes the last byte of a certificate: a bit of its signature.
852func flipLast(der []byte) []byte {
853 out := slices.Clone(der)
854 out[len(out)-1] ^= 1
855 return out
856}