| 1 | package approval |
| 2 | |
| 3 | import ( |
| 4 | "bufio" |
| 5 | "bytes" |
| 6 | "crypto/ed25519" |
| 7 | "crypto/rand" |
| 8 | "crypto/sha256" |
| 9 | "crypto/x509" |
| 10 | "crypto/x509/pkix" |
| 11 | "errors" |
| 12 | "flag" |
| 13 | "fmt" |
| 14 | "io" |
| 15 | "math/big" |
| 16 | "os" |
| 17 | "strings" |
| 18 | "testing" |
| 19 | "time" |
| 20 | |
| 21 | "the-valley/note" |
| 22 | ) |
| 23 | |
| 24 | var update = flag.Bool("update", false, "rewrite the vectors under testdata/") |
| 25 | |
| 26 | func key(label string) Key { |
| 27 | seed := sha256.Sum256([]byte("approval test key " + label)) |
| 28 | return NewKey(ed25519.NewKeyFromSeed(seed[:])) |
| 29 | } |
| 30 | |
| 31 | func example() Statement { |
| 32 | return Statement{ |
| 33 | Instance: strings.Repeat("5f", 32), |
| 34 | Project: "app", |
| 35 | Target: "main", |
| 36 | Change: "nxvpwlkmqtsrzyoukklnpmqrstuvwxyz", |
| 37 | Version: 2, |
| 38 | Head: "git-sha1:" + strings.Repeat("2", 40), |
| 39 | Record: "git-sha1:" + strings.Repeat("3", 40), |
| 40 | Principal: "operator", |
| 41 | Issued: time.Date(2026, 11, 6, 0, 43, 26, 0, time.UTC), |
| 42 | } |
| 43 | } |
| 44 | |
| 45 | func authority(principal string, keys ...Key) []note.VerifierKey { |
| 46 | var out []note.VerifierKey |
| 47 | for _, k := range keys { |
| 48 | out = append(out, note.NewVerifierKey(principal, k.Public())) |
| 49 | } |
| 50 | return out |
| 51 | } |
| 52 | |
| 53 | // pinned holds got to the vector in testdata/name, or rewrites it. |
| 54 | func pinned(t *testing.T, name string, got []byte) { |
| 55 | t.Helper() |
| 56 | path := "testdata/" + name |
| 57 | if *update { |
| 58 | if err := os.WriteFile(path, got, 0o644); err != nil { |
| 59 | t.Fatal(err) |
| 60 | } |
| 61 | } |
| 62 | want, err := os.ReadFile(path) |
| 63 | if err != nil { |
| 64 | t.Fatal(err) |
| 65 | } |
| 66 | if !bytes.Equal(got, want) { |
| 67 | t.Fatalf("%s:\ngot\n%s\nwant\n%s", path, got, want) |
| 68 | } |
| 69 | } |
| 70 | |
| 71 | func TestVectors(t *testing.T) { |
| 72 | text, err := example().Encode() |
| 73 | if err != nil { |
| 74 | t.Fatal(err) |
| 75 | } |
| 76 | pinned(t, "approval.statement", text) |
| 77 | n, err := Sign(example(), key("operator")) |
| 78 | if err != nil { |
| 79 | t.Fatal(err) |
| 80 | } |
| 81 | pinned(t, "approval.note", n) |
| 82 | s, err := Verify(n, authority("operator", key("operator"))) |
| 83 | if err != nil { |
| 84 | t.Fatal(err) |
| 85 | } |
| 86 | if s != example() { |
| 87 | t.Fatalf("verified %+v, want %+v", s, example()) |
| 88 | } |
| 89 | id, err := InstanceID("sha1", []string{strings.Repeat("b", 40), strings.Repeat("a", 40)}) |
| 90 | if err != nil { |
| 91 | t.Fatal(err) |
| 92 | } |
| 93 | pinned(t, "instance-id", []byte(id+"\n")) |
| 94 | } |
| 95 | |
| 96 | // The largest statement the form allows is the bound itself, and the |
| 97 | // hardware acceptance signs it. |
| 98 | func TestBound(t *testing.T) { |
| 99 | s := example() |
| 100 | s.Target = strings.Repeat("t", MaxStatement-len(mustEncode(t, s))+len(s.Target)) |
| 101 | text := mustEncode(t, s) |
| 102 | if len(text) != MaxStatement { |
| 103 | t.Fatalf("the largest statement is %d bytes", len(text)) |
| 104 | } |
| 105 | pinned(t, "largest.statement", text) |
| 106 | if _, err := Parse(text); err != nil { |
| 107 | t.Fatal(err) |
| 108 | } |
| 109 | s.Target += "t" |
| 110 | if _, err := s.Encode(); err == nil || !strings.Contains(err.Error(), "1024") { |
| 111 | t.Fatalf("a statement over the bound encoded, or did not name the bound: %v", err) |
| 112 | } |
| 113 | if _, err := Sign(s, failing{}); err == nil || !strings.Contains(err.Error(), "1024") { |
| 114 | t.Fatalf("a statement over the bound reached the signer: %v", err) |
| 115 | } |
| 116 | if _, err := Parse(append(text, 'x')); err == nil { |
| 117 | t.Fatal("text over the bound parsed") |
| 118 | } |
| 119 | } |
| 120 | |
| 121 | func mustEncode(t *testing.T, s Statement) []byte { |
| 122 | t.Helper() |
| 123 | text, err := s.Encode() |
| 124 | if err != nil { |
| 125 | t.Fatal(err) |
| 126 | } |
| 127 | return text |
| 128 | } |
| 129 | |
| 130 | func TestParseRefuses(t *testing.T) { |
| 131 | good := string(mustEncode(t, example())) |
| 132 | swap := func(old, new string) string { return strings.Replace(good, old, new, 1) } |
| 133 | for name, text := range map[string]string{ |
| 134 | "attestation type": swap(Type, note.StatementType), |
| 135 | "line missing": swap("record git-sha1:"+strings.Repeat("3", 40)+"\n", ""), |
| 136 | "line added": good + "expires 2026-11-07T00:43:26Z\n", |
| 137 | "lines swapped": swap("project app\ntarget main", "target main\nproject app"), |
| 138 | "unknown key": swap("project app", "projects app"), |
| 139 | "repeated line": swap("target main\n", "target main\ntarget main\n"), |
| 140 | "two spaces": swap("project app", "project app"), |
| 141 | "trailing space": swap("project app", "project app "), |
| 142 | "empty value": swap("project app", "project "), |
| 143 | "leading zero": swap("version 2", "version 02"), |
| 144 | "version zero": swap("version 2", "version 0"), |
| 145 | "version too large": swap("version 2", "version 1001"), |
| 146 | "upper hex": swap("instance 5f5f", "instance 5F5f"), |
| 147 | "short instance": swap("instance 5f5f", "instance 5f"), |
| 148 | "untyped head": swap("head git-sha1:", "head "), |
| 149 | "sha256 head": swap("head git-sha1:", "head git-sha256:"), |
| 150 | "bad change id": swap("change nx", "change ax"), |
| 151 | "bad target": swap("target main", "target ma..in"), |
| 152 | "bad principal": swap("principal operator", "principal -operator"), |
| 153 | "local time": swap("00:43:26Z", "00:43:26+01:00"), |
| 154 | "fractional second": swap("00:43:26Z", "00:43:26.5Z"), |
| 155 | "no closing newline": strings.TrimSuffix(good, "\n"), |
| 156 | "carriage return": swap("project app\n", "project app\r\n"), |
| 157 | "empty": "", |
| 158 | } { |
| 159 | if _, err := Parse([]byte(text)); err == nil { |
| 160 | t.Errorf("%s: parsed", name) |
| 161 | } |
| 162 | } |
| 163 | } |
| 164 | |
| 165 | // Every field is under the signature: a note whose statement is altered |
| 166 | // in any one value does not verify. |
| 167 | func TestFieldMutations(t *testing.T) { |
| 168 | n, err := Sign(example(), key("operator")) |
| 169 | if err != nil { |
| 170 | t.Fatal(err) |
| 171 | } |
| 172 | keys := authority("operator", key("operator")) |
| 173 | lines := strings.Split(string(n), "\n") |
| 174 | for i := 1; i <= 9; i++ { |
| 175 | mutated := slicesClone(lines) |
| 176 | l := mutated[i] |
| 177 | last := l[len(l)-1] |
| 178 | repl := byte('1') |
| 179 | if last == '1' { |
| 180 | repl = '2' |
| 181 | } |
| 182 | mutated[i] = l[:len(l)-1] + string(repl) |
| 183 | if _, err := Verify([]byte(strings.Join(mutated, "\n")), keys); err == nil { |
| 184 | t.Errorf("altering %q verified", l) |
| 185 | } |
| 186 | } |
| 187 | } |
| 188 | |
| 189 | func slicesClone(s []string) []string { return append([]string(nil), s...) } |
| 190 | |
| 191 | func TestVerifyRefuses(t *testing.T) { |
| 192 | operator := key("operator") |
| 193 | keys := authority("operator", operator) |
| 194 | good, err := Sign(example(), operator) |
| 195 | if err != nil { |
| 196 | t.Fatal(err) |
| 197 | } |
| 198 | attestation := []byte(note.StatementType + "\nsubject.primary valley-tree-v1\n") |
| 199 | wrongType, _ := note.Sign(attestation, "operator", operator.priv) |
| 200 | unknown, _ := Sign(example(), key("stranger")) |
| 201 | other := example() |
| 202 | other.Principal = "alice" |
| 203 | otherText := mustEncode(t, other) |
| 204 | mismatch, _ := note.Sign(otherText, "operator", operator.priv) |
| 205 | twice, _ := note.AddSignature(good, "operator", key("spare").priv) |
| 206 | noncanonical, _ := note.Sign(bytes.Replace(mustEncode(t, example()), []byte("version 2"), []byte("version 02"), 1), "operator", operator.priv) |
| 207 | for name, n := range map[string][]byte{ |
| 208 | "wrong namespace": wrongType, |
| 209 | "unknown key": unknown, |
| 210 | "principal mismatch": mismatch, |
| 211 | "two signatures": twice, |
| 212 | "noncanonical text": noncanonical, |
| 213 | "no signature block": mustEncode(t, example()), |
| 214 | "garbage signature": append(mustEncode(t, example()), "\n— operator AAAA\n"...), |
| 215 | "truncated": good[:len(good)-10], |
| 216 | "oversized": append(bytes.Repeat([]byte("x"), MaxNote), good...), |
| 217 | } { |
| 218 | if _, err := Verify(n, keys); err == nil { |
| 219 | t.Errorf("%s: verified", name) |
| 220 | } |
| 221 | } |
| 222 | } |
| 223 | |
| 224 | // Which keys a reader holds is which approvals count. A software key's |
| 225 | // approval verifies under approval-signers, which lists it, and is refused |
| 226 | // under approval-signers-hardware, which lists only hardware keys. |
| 227 | func TestAuthoritySelection(t *testing.T) { |
| 228 | software, hardware := key("software"), key("hardware") |
| 229 | all := []byte("# approval-signers\n" + note.NewVerifierKey("operator", software.Public()).String() + "\n" + |
| 230 | note.NewVerifierKey("operator", hardware.Public()).String() + "\n") |
| 231 | hw := []byte("# approval-signers-hardware\n" + note.NewVerifierKey("operator", hardware.Public()).String() + "\n") |
| 232 | read := func(b []byte) []note.VerifierKey { |
| 233 | keys, err := note.ParseVerifierKeys(b) |
| 234 | if err != nil { |
| 235 | t.Fatal(err) |
| 236 | } |
| 237 | return keys |
| 238 | } |
| 239 | n, err := Sign(example(), software) |
| 240 | if err != nil { |
| 241 | t.Fatal(err) |
| 242 | } |
| 243 | if _, err := Verify(n, read(all)); err != nil { |
| 244 | t.Fatalf("a software key under ordinary authority: %v", err) |
| 245 | } |
| 246 | if _, err := Verify(n, read(hw)); err == nil { |
| 247 | t.Fatal("a software key verified under hardware-only authority") |
| 248 | } |
| 249 | if n, err = Sign(example(), hardware); err != nil { |
| 250 | t.Fatal(err) |
| 251 | } |
| 252 | if _, err := Verify(n, read(hw)); err != nil { |
| 253 | t.Fatalf("a hardware key under hardware-only authority: %v", err) |
| 254 | } |
| 255 | } |
| 256 | |
| 257 | type failing struct{} |
| 258 | |
| 259 | func (failing) Public() ed25519.PublicKey { return key("operator").Public() } |
| 260 | func (failing) Sign([]byte) ([]byte, error) { return nil, errors.New("the device went away") } |
| 261 | |
| 262 | // otherText signs something other than the statement it is given. |
| 263 | type otherText struct{ Key } |
| 264 | |
| 265 | func (o otherText) Sign(text []byte) ([]byte, error) { return o.Key.Sign(append(text, 'x')) } |
| 266 | |
| 267 | func TestSigningFailure(t *testing.T) { |
| 268 | if n, err := Sign(example(), failing{}); err == nil || n != nil { |
| 269 | t.Fatalf("a failing signer gave a note: %q, %v", n, err) |
| 270 | } |
| 271 | if n, err := Sign(example(), otherText{key("operator")}); err == nil || n != nil { |
| 272 | t.Fatalf("a signature over other text was sealed: %q, %v", n, err) |
| 273 | } |
| 274 | } |
| 275 | |
| 276 | func TestInstanceIDRefuses(t *testing.T) { |
| 277 | a := strings.Repeat("a", 40) |
| 278 | for name, c := range map[string]struct { |
| 279 | format string |
| 280 | roots []string |
| 281 | }{ |
| 282 | "unknown format": {"md5", []string{a}}, |
| 283 | "no roots": {"sha1", nil}, |
| 284 | "twice": {"sha1", []string{a, a}}, |
| 285 | "wrong length": {"sha256", []string{a}}, |
| 286 | "upper hex": {"sha1", []string{strings.ToUpper(a)}}, |
| 287 | } { |
| 288 | if _, err := InstanceID(c.format, c.roots); err == nil { |
| 289 | t.Errorf("%s: derived an identity", name) |
| 290 | } |
| 291 | } |
| 292 | } |
| 293 | |
| 294 | func TestParseKey(t *testing.T) { |
| 295 | raw, err := os.ReadFile("testdata/software.key") |
| 296 | if err != nil { |
| 297 | t.Fatal(err) |
| 298 | } |
| 299 | k, err := ParseKey(raw) |
| 300 | if err != nil { |
| 301 | t.Fatal(err) |
| 302 | } |
| 303 | if _, err := Sign(example(), k); err != nil { |
| 304 | t.Fatal(err) |
| 305 | } |
| 306 | if _, err := ParseKey(raw[:len(raw)/2]); err == nil { |
| 307 | t.Fatal("a truncated key parsed") |
| 308 | } |
| 309 | } |
| 310 | |
| 311 | // The PIV session, against a stand-in for valley-piv-signer: this test |
| 312 | // binary, run with APPROVAL_FAKE_PIV naming what the device does. |
| 313 | func TestMain(m *testing.M) { |
| 314 | if scenario := os.Getenv("APPROVAL_FAKE_PIV"); scenario != "" { |
| 315 | os.Exit(fakePIV(scenario)) |
| 316 | } |
| 317 | os.Exit(m.Run()) |
| 318 | } |
| 319 | |
| 320 | func device() ed25519.PrivateKey { return key("device").priv } |
| 321 | |
| 322 | func fakePIV(scenario string) int { |
| 323 | if scenario == "absent" { |
| 324 | fmt.Println("error device no YubiKey could be reached: PCSC error") |
| 325 | return 1 |
| 326 | } |
| 327 | pinPolicy := map[string]byte{"pin-always": 3, "pin-never": 1}[scenario] |
| 328 | if pinPolicy == 0 { |
| 329 | pinPolicy = 2 |
| 330 | } |
| 331 | tmpl := &x509.Certificate{ |
| 332 | SerialNumber: big.NewInt(1), |
| 333 | Subject: pkix.Name{CommonName: "YubiKey PIV Attestation 9c"}, |
| 334 | NotBefore: time.Unix(0, 0), |
| 335 | NotAfter: time.Unix(1<<33, 0), |
| 336 | ExtraExtensions: []pkix.Extension{{Id: policyOID, Value: []byte{pinPolicy, 2}}}, |
| 337 | } |
| 338 | der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, device().Public(), device()) |
| 339 | if err != nil { |
| 340 | fmt.Println("error device", err) |
| 341 | return 1 |
| 342 | } |
| 343 | fmt.Printf("key 12345678 %x\n", der) |
| 344 | in := bufio.NewReader(os.Stdin) |
| 345 | for { |
| 346 | line, err := in.ReadString('\n') |
| 347 | if err != nil { |
| 348 | return 0 |
| 349 | } |
| 350 | var n int |
| 351 | var mode string |
| 352 | fmt.Sscanf(line, "sign %d %s", &n, &mode) |
| 353 | text := make([]byte, n) |
| 354 | io.ReadFull(in, text) |
| 355 | if want := map[byte]string{1: "none", 2: "session", 3: "each"}[pinPolicy]; mode != want { |
| 356 | fmt.Println("error request the mode is", mode, "not", want) |
| 357 | return 1 |
| 358 | } |
| 359 | switch scenario { |
| 360 | case "pin": |
| 361 | fmt.Println("error pin 2") |
| 362 | return 1 |
| 363 | case "cancelled": |
| 364 | fmt.Println("error cancelled") |
| 365 | return 1 |
| 366 | case "touch": |
| 367 | fmt.Println("touch\nerror touch") |
| 368 | return 1 |
| 369 | case "other-text": |
| 370 | text = append(text, 'x') |
| 371 | } |
| 372 | fmt.Printf("touch\nsignature %x\n", ed25519.Sign(device(), text)) |
| 373 | } |
| 374 | } |
| 375 | |
| 376 | func openFake(t *testing.T, scenario string) (*PIVSession, *bytes.Buffer, error) { |
| 377 | t.Setenv("APPROVAL_FAKE_PIV", scenario) |
| 378 | var prompt bytes.Buffer |
| 379 | p, err := OpenPIV(os.Args[0], "", "", &prompt) |
| 380 | if p != nil { |
| 381 | t.Cleanup(func() { p.Close() }) |
| 382 | } |
| 383 | return p, &prompt, err |
| 384 | } |
| 385 | |
| 386 | func TestPIVSession(t *testing.T) { |
| 387 | for _, scenario := range []string{"session", "pin-always", "pin-never"} { |
| 388 | p, prompt, err := openFake(t, scenario) |
| 389 | if err != nil { |
| 390 | t.Fatalf("%s: %v", scenario, err) |
| 391 | } |
| 392 | keys := authority("operator", NewKey(device())) |
| 393 | for v := 1; v <= 3; v++ { |
| 394 | s := example() |
| 395 | s.Version = v |
| 396 | n, err := Sign(s, p) |
| 397 | if err != nil { |
| 398 | t.Fatalf("%s: signature %d: %v", scenario, v, err) |
| 399 | } |
| 400 | if _, err := Verify(n, keys); err != nil { |
| 401 | t.Fatalf("%s: signature %d: %v", scenario, v, err) |
| 402 | } |
| 403 | } |
| 404 | if got := strings.Count(prompt.String(), "touch the YubiKey (serial 12345678)"); got != 3 { |
| 405 | t.Fatalf("%s: %d touch prompts for 3 signatures:\n%s", scenario, got, prompt) |
| 406 | } |
| 407 | } |
| 408 | } |
| 409 | |
| 410 | func TestPIVRefusals(t *testing.T) { |
| 411 | if _, _, err := openFake(t, "absent"); !isKind(err, "device") { |
| 412 | t.Fatalf("no device: %v", err) |
| 413 | } |
| 414 | for scenario, kind := range map[string]string{"pin": "pin", "cancelled": "cancelled", "touch": "touch"} { |
| 415 | p, _, err := openFake(t, scenario) |
| 416 | if err != nil { |
| 417 | t.Fatal(err) |
| 418 | } |
| 419 | if n, err := Sign(example(), p); n != nil || !isKind(err, kind) { |
| 420 | t.Fatalf("%s: %q, %v", scenario, n, err) |
| 421 | } |
| 422 | // The session is over: nothing more is sent. |
| 423 | if _, err := Sign(example(), p); !isKind(err, kind) { |
| 424 | t.Fatalf("%s: a second signature after the refusal: %v", scenario, err) |
| 425 | } |
| 426 | } |
| 427 | p, _, err := openFake(t, "other-text") |
| 428 | if err != nil { |
| 429 | t.Fatal(err) |
| 430 | } |
| 431 | if n, err := Sign(example(), p); n != nil || err == nil { |
| 432 | t.Fatalf("a device signature over other text was sealed: %q", n) |
| 433 | } |
| 434 | p, _, err = openFake(t, "session") |
| 435 | if err != nil { |
| 436 | t.Fatal(err) |
| 437 | } |
| 438 | if _, err := p.Sign(make([]byte, MaxStatement+1)); err == nil || !strings.Contains(err.Error(), "1024") { |
| 439 | t.Fatalf("text over the bound was sent: %v", err) |
| 440 | } |
| 441 | } |
| 442 | |
| 443 | func isKind(err error, kind string) bool { |
| 444 | var e *PIVError |
| 445 | return errors.As(err, &e) && e.Kind == kind |
| 446 | } |
| 447 | |
| 448 | // The packaged helper, with no smart card service to reach: it refuses |
| 449 | // in the form the session reads. PCSCLITE_CSOCK_NAME points pcsc-lite at |
| 450 | // a socket that does not exist, so no device is ever reached. |
| 451 | func TestPIVHelperWithoutDevice(t *testing.T) { |
| 452 | helper := os.Getenv("VALLEY_PIV_SIGNER") |
| 453 | if helper == "" { |
| 454 | t.Skip("VALLEY_PIV_SIGNER names no helper; approval-unit sets it") |
| 455 | } |
| 456 | t.Setenv("PCSCLITE_CSOCK_NAME", t.TempDir()+"/no-pcscd") |
| 457 | if _, err := OpenPIV(helper, "9c", "", io.Discard); !isKind(err, "device") { |
| 458 | t.Fatalf("the helper without a device: %v", err) |
| 459 | } |
| 460 | if _, err := OpenPIV(helper, "77", "", io.Discard); !isKind(err, "request") { |
| 461 | t.Fatalf("the helper given no PIV slot: %v", err) |
| 462 | } |
| 463 | } |