polyc-crypto 2026.8.1

Provenance signatures (commonware-cryptography ed25519) for polychrome tool calls.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
//! Remembered-approval **grant** canonicals and their verification path.
//!
//! A grant is the highest-privilege artifact in the system: it clears an egress
//! gate on an unattended run with no human present. ADR 0001 makes it
//! unforgeable by the platform — the only signature that mints one comes from
//! the principal's passkey (a `WebAuthn` assertion whose challenge binds the grant
//! canonical), verified here against the public key registered at enrollment.
//! **There is no code path that mints a signed grant from a platform ed25519
//! key.** [`signed_grant_payload`] assembles the passkey-proof payload;
//! [`verify_grant`] is the only acceptance path.
//!
//! Three canonicals live here, each with a distinct `kind` tag so the audit
//! trail can never confuse them:
//!
//! * **grant** ([`grant_canonical`]) — key `(principal, routine, tool)` plus the
//!   coverage record; passkey-signed.
//! * **revocation** ([`revocation_canonical`]) — the principal's own withdrawal;
//!   a fresh passkey assertion binding the grant's [`grant_ref`].
//! * **suspension** ([`suspension_canonical`]) — the platform's act; ed25519,
//!   the existing [`Signer`], binding the same [`grant_ref`], never requiring
//!   the passkey (a lost passkey cannot strand a live grant).
//!
//! [`live_grant`] is the single fold that treats a grant with a matching
//! verified revocation or suspension as absent — the one place "revoked or
//! suspended ⇒ absent" lives.
//!
//! The canonical style mirrors [`crate::approval`] and [`crate::mandate`]
//! (canonical JSON, a literal `kind` tag first). A revocation/suspension
//! references the exact grant by [`grant_ref`] — the sha256 of the grant's full
//! signed payload — the same chain-link pattern as [`crate::mandate::mandate_hash`].

use serde::Serialize;
use serde_json::Value;
use sha2::{Digest, Sha256};

use base64::Engine as _;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;

use crate::signed::{Envelope, canonical_bytes};
use crate::{Signer, verify};
use polyc_passkey::derive::verify_derived_signature;
use polyc_passkey::{Assertion, WebAuthnProof, challenge_b64, verify_assertion};

/// Signed `kind` tag for a routine-grant canonical.
pub const GRANT_KIND: &str = "grant.routine.v1";
/// Signed `kind` tag for a revocation-tombstone canonical.
pub const REVOCATION_KIND: &str = "grant.revocation.v1";
/// Signed `kind` tag for a suspension canonical.
pub const SUSPENSION_KIND: &str = "grant.suspension.v1";
/// Signed `kind` tag for a routine-grant canonical signed by a persona's
/// recorded signing credential rather than a per-enrollment `WebAuthn` passkey.
///
/// Deliberately distinct from [`GRANT_KIND`] — same kind-per-artifact
/// discipline the module doc describes — so a persona-signed grant can never
/// verify as, or be confused with, a `WebAuthn`-signed one in the audit
/// trail (#1197).
pub const GRANT_PERSONA_KIND: &str = "grant.routine.persona.v1";
/// Signed `kind` tag for a persona-signed revocation tombstone.
///
/// Mirrors [`GRANT_PERSONA_KIND`]'s distinction for [`REVOCATION_KIND`] (#1197).
pub const REVOCATION_PERSONA_KIND: &str = "grant.revocation.persona.v1";

/// A persona-derived-key signature over a grant-family canonical (#1197): the
/// signing key's public bytes plus its plain ed25519 signature.
///
/// The persona-signing sibling of [`WebAuthnProof`] — bundled the same way,
/// so [`signed_grant_payload_persona`]/[`signed_revocation_payload_persona`]
/// stay at the same argument count their `WebAuthn` siblings are.
#[derive(Debug, Clone, Copy)]
pub struct PersonaProof<'a> {
    /// The persona's currently recorded `PersonaCredential.signing_public_key`.
    pub signing_public_key: &'a [u8],
    /// That key's plain ed25519 signature over the canonical directly (no
    /// `WebAuthn` challenge/assertion wrapping).
    pub signature: &'a [u8],
}

/// The coverage record a grant binds: the pinned destination, the slot-schema
/// hash, and the covered capabilities.
///
/// Borrowed so a caller can build it from decoded fields without copying.
/// `slot_schema_hash` is #618's template-coverage hash; `covered_capabilities`
/// are stable kebab-case `polyc_capability` names (the consumer resolves them
/// with `CapabilitySet::from_names`, which is fail-closed on unknown names).
/// Changing the destination or the slot-schema hash changes the canonical, so a
/// coverage drift voids the grant — a new approval ceremony is required.
#[derive(Debug, Clone, Copy)]
pub struct GrantCoverage<'a> {
    /// The pinned egress destination the grant covers.
    ///
    /// **Canonicalization contract:** the compact JSON of the template's
    /// destination map serialized from a `BTreeMap` (key-sorted, no
    /// whitespace). Coverage equality is byte equality of this string, so the
    /// mint side (the enrollment ceremony) and every verify side (the dispatch
    /// resolver recomputing current coverage) MUST produce it the same way —
    /// always `serde_json::to_string` of the `BTreeMap` destination, never a
    /// hand-built string. A formatting-only difference reads as coverage drift
    /// and voids the grant.
    pub destination: &'a str,
    /// The content-template slot-schema hash the grant covers (#618).
    pub slot_schema_hash: &'a str,
    /// The stable kebab-case capability names the grant covers.
    pub covered_capabilities: &'a [String],
}

/// The canonical bytes the passkey challenge binds for a routine grant.
///
/// Key `(principal, routine, tool)` plus the coverage record, the
/// `enrollment_id`, and `created_at_ms`. A byte-level change to any field
/// changes these bytes, hence the [`challenge_b64`] the assertion must carry,
/// so verification fails — this is the single source the ceremony (#621) and
/// the gate (#594) both reproduce.
#[must_use]
pub fn grant_canonical(
    principal: &str,
    routine: &str,
    tool: &str,
    coverage: &GrantCoverage<'_>,
    enrollment_id: &str,
    created_at_ms: u64,
) -> Vec<u8> {
    canonical_bytes(&GrantCanonical {
        kind: GRANT_KIND,
        principal,
        routine,
        tool,
        destination: coverage.destination,
        slot_schema_hash: coverage.slot_schema_hash,
        covered_capabilities: coverage.covered_capabilities,
        enrollment_id,
        created_at_ms,
    })
}

/// The signed grant field set, in its frozen order.
///
/// Shared by [`grant_canonical`] and [`grant_canonical_persona`] — the two
/// differ only in the `kind` tag, so one declaration governs both orders and
/// they cannot drift apart. Declaration order IS the signed contract: it
/// determines the [`grant_challenge`] a passkey assertion binds, so reordering
/// a field voids every grant ever minted. See ADR 0009.
#[derive(Serialize)]
struct GrantCanonical<'a> {
    kind: &'static str,
    principal: &'a str,
    routine: &'a str,
    tool: &'a str,
    destination: &'a str,
    slot_schema_hash: &'a str,
    covered_capabilities: &'a [String],
    enrollment_id: &'a str,
    created_at_ms: u64,
}

/// The signed revocation-tombstone field set, in its frozen order.
///
/// Shared by [`revocation_canonical`] and [`revocation_canonical_persona`],
/// which differ only in the `kind` tag. See ADR 0009.
#[derive(Serialize)]
struct RevocationCanonical<'a> {
    kind: &'static str,
    grant_ref: &'a str,
    revoked_at_ms: u64,
}

/// The signed suspension field set, in its frozen order.
///
/// The body [`suspension_payload`] seals into an [`Envelope`] — so the
/// canonical the signature covers and the persisted payload share one
/// declaration of the field list rather than the two hand-maintained copies
/// this replaced (`#1845`). See ADR 0009.
#[derive(Serialize)]
struct SuspensionCanonical<'a> {
    kind: &'static str,
    grant_ref: &'a str,
    reason: &'a str,
    suspended_at_ms: u64,
}

/// The `WebAuthn` challenge a grant-family canonical binds:
/// `base64url(sha256(canonical))` (url-safe, no pad).
///
/// The value the ceremony page passes to `navigator.credentials.get`, and what
/// every verifier recomputes. A thin alias over [`challenge_b64`] named for the
/// grant family — grants and revocations both derive their challenge here, so
/// the derivation cannot drift between the two ceremonies.
#[must_use]
pub fn grant_challenge(canonical: &[u8]) -> String {
    challenge_b64(canonical)
}

/// The sha256-hex of a grant's **full signed payload** — the reference a
/// revocation or suspension binds.
///
/// Hashing the full payload (canonical fields *and* the assertion) commits to
/// one exact, already-minted artifact, exactly as
/// [`crate::mandate::mandate_hash`] does: a grant re-minted with a different
/// assertion produces a different `grant_ref`, so a stale tombstone cannot void
/// it. Callers (#594/#623) compute this over the stored payload bytes to match
/// a tombstone/suspension to its grant.
#[must_use]
pub fn grant_ref(signed_grant_payload: &[u8]) -> String {
    crate::hex::lower(&Sha256::digest(signed_grant_payload))
}

/// Assemble the full signed grant payload from the canonical fields and a
/// verified-shape `WebAuthn` proof.
///
/// This is the **only** constructor of a signed grant (ADR 0001): the proof is
/// a passkey assertion, never a platform signature. The ceremony (#621) calls
/// this after [`verify_grant`] accepts the freshly minted assertion, then
/// persists the returned bytes as the `routine_grant` event payload. The
/// assertion fields are carried as url-safe base64.
#[must_use]
pub fn signed_grant_payload(
    principal: &str,
    routine: &str,
    tool: &str,
    coverage: &GrantCoverage<'_>,
    enrollment_id: &str,
    created_at_ms: u64,
    proof: &WebAuthnProof<'_>,
) -> Vec<u8> {
    let canonical = grant_canonical(
        principal,
        routine,
        tool,
        coverage,
        enrollment_id,
        created_at_ms,
    );
    attach_proof(&canonical, proof)
}

/// Append a `WebAuthn` proof's four fields to a grant-family canonical,
/// producing the full signed payload.
///
/// Parses `canonical` back into a JSON object and inserts
/// `credential_id`/`authenticator_data`/`client_data_json`/`signature` (each
/// url-safe base64, no padding), then reserializes. Both
/// [`signed_grant_payload`] and [`signed_revocation_payload`] build their
/// canonical fields once (via [`grant_canonical`] / [`revocation_canonical`])
/// and delegate the proof-attachment step here, so a payload can never carry
/// fields that diverge from its own canonical.
///
/// Byte-for-byte compatible with the previous single hand-written `json!`
/// construction regardless of whether `serde_json`'s `preserve_order` feature
/// is active for this build (this crate does not request it, but cargo
/// feature unification can switch it on when another workspace member does):
/// a `BTreeMap`-backed object always resorts keys alphabetically no matter
/// the insertion order, and an order-preserving map always appends genuinely
/// new keys at the end — so parse-then-insert reproduces exactly what
/// building all fields in one macro call would have, under either
/// configuration.
///
/// **That equivalence is per-configuration, not across configurations.** This
/// function round-trips its input through a [`serde_json::Map`], so the bytes
/// it returns still track whichever map type the build resolved: sorted keys
/// under a lean selection, canonical-then-appended under `preserve_order`.
/// `#1845` made the *canonical* build-graph-independent — which is what
/// [`grant_challenge`] hashes, so passkey and persona verification are now
/// independent of the build graph — but the assembled payload is not, and
/// [`grant_ref`] is the sha256 of that payload. Nothing signs or verifies
/// against the payload's own bytes, and no deployment has ever minted a grant
/// (this module is unwired), so nothing is broken today. Because `grant_ref` is
/// always taken over *stored* bytes, a minted grant keeps a stable ref forever;
/// the only divergence is two binaries minting the same logical grant, which
/// cannot happen for a once-minted artifact.
///
/// Sealing the proof fields through a declared struct the way
/// [`suspension_payload`] does closes it, and `#1959` tracks that as a blocker
/// on the grant ceremony rather than a follow-up to it: today there are zero
/// durable bytes to preserve, so the fix is free, and the first mint makes it
/// impossible forever.
fn attach_proof(canonical: &[u8], proof: &WebAuthnProof<'_>) -> Vec<u8> {
    // canonical-allow: a grant payload's key order tracks the build's map type,
    // which is the residual `#1959` tracks. It is annotated rather than fixed
    // here because nothing has ever minted a grant, so no bytes are at risk;
    // see the doc comment above for why the fix must precede the first mint.
    let mut map: serde_json::Map<String, Value> =
        serde_json::from_slice(canonical).expect("a grant-family canonical is a JSON object");
    map.insert(
        "credential_id".to_owned(),
        Value::String(b64(proof.credential_id)),
    );
    map.insert(
        "authenticator_data".to_owned(),
        Value::String(b64(proof.authenticator_data)),
    );
    map.insert(
        "client_data_json".to_owned(),
        Value::String(b64(proof.client_data_json)),
    );
    map.insert("signature".to_owned(), Value::String(b64(proof.signature)));
    Value::Object(map).to_string().into_bytes() // canonical-allow: see `#1959` above
}

/// Verify the passkey proof carried in a grant-family payload against the
/// canonical it claims to bind.
///
/// The shared verification skeleton of [`verify_grant`] and
/// [`verify_revocation`]: base64-decode the three assertion fields off the
/// payload object, derive the expected challenge from `canonical`, and run
/// [`verify_assertion`]. Each public verifier keeps only its own kind check,
/// field extraction, and canonical rebuild. Fail-closed: `None` on any
/// missing field, bad base64, or assertion failure. [`verify_assertion`]'s
/// `sign_count` is discarded here — this crate enforces no counter policy
/// today; a future consumer that wants it reads [`verify_assertion`] directly.
fn verify_passkey_proof(
    v: &Value,
    canonical: &[u8],
    registered_pubkey_sec1: &[u8],
    rp_id: &str,
    origin: &str,
) -> Option<()> {
    let authenticator_data = b64_decode(v.get("authenticator_data")?.as_str()?)?;
    let client_data_json = b64_decode(v.get("client_data_json")?.as_str()?)?;
    let signature = b64_decode(v.get("signature")?.as_str()?)?;
    let assertion = Assertion {
        authenticator_data: &authenticator_data,
        client_data_json: &client_data_json,
        signature: &signature,
    };
    verify_assertion(
        registered_pubkey_sec1,
        &assertion,
        &grant_challenge(canonical),
        rp_id,
        origin,
    )
    .ok()
    .map(|_checks| ())
}

/// Append a [`PersonaProof`]'s two fields to a grant-family canonical,
/// producing the full signed payload.
///
/// The persona-signing sibling of [`attach_proof`]: a persona-derived key
/// signs the canonical directly (a plain ed25519 signature, no `WebAuthn`
/// assertion wrapping — the `WebAuthn` ceremony already ran once, at
/// `PersonaCredential` enrollment, to bind this key), so there is no
/// `authenticator_data`/`client_data_json` to carry, only the raw signature
/// and the signing key it claims to be from (#1197). Shares
/// [`attach_proof`]'s per-configuration byte-equivalence caveat.
fn attach_persona_proof(canonical: &[u8], proof: &PersonaProof<'_>) -> Vec<u8> {
    // canonical-allow: the same residual as `attach_proof`, tracked by `#1959`.
    let mut map: serde_json::Map<String, Value> =
        serde_json::from_slice(canonical).expect("a grant-family canonical is a JSON object");
    map.insert(
        "signing_public_key".to_owned(),
        Value::String(b64(proof.signing_public_key)),
    );
    map.insert("signature".to_owned(), Value::String(b64(proof.signature)));
    Value::Object(map).to_string().into_bytes() // canonical-allow: see `#1959` above
}

/// Verify the persona-signed proof carried in a grant-family payload against
/// the canonical it claims to bind.
///
/// The persona-signing sibling of [`verify_passkey_proof`]: decodes
/// `signing_public_key`/`signature`, checks the payload's claimed signing key
/// equals `expected_persona_pubkey` (the SAME pinning discipline
/// [`verify_suspension`]'s `expected_platform_key` uses — a payload's
/// self-claimed key is never trusted on its own, only a caller-supplied
/// expected one), then verifies the signature via
/// [`verify_derived_signature`] — a plain ed25519 check, matching exactly
/// what a browser's PRF-derived key actually signs with (see
/// [`verify_derived_signature`]'s own docs on why this must NOT be
/// `commonware_cryptography`'s namespaced verify). Fail-closed: `None` on any
/// missing field, bad base64, key mismatch, or signature mismatch.
fn verify_persona_proof(v: &Value, canonical: &[u8], expected_persona_pubkey: &[u8]) -> Option<()> {
    let signing_public_key = b64_decode(v.get("signing_public_key")?.as_str()?)?;
    let signature = b64_decode(v.get("signature")?.as_str()?)?;
    if signing_public_key != expected_persona_pubkey {
        return None;
    }
    if verify_derived_signature(&signing_public_key, canonical, &signature) {
        Some(())
    } else {
        None
    }
}

/// The canonical bytes a persona-signed grant's signature binds.
///
/// The persona-signing sibling of [`grant_canonical`], identical fields,
/// distinguished only by [`GRANT_PERSONA_KIND`] so the two can never verify
/// as each other (#1197).
#[must_use]
pub fn grant_canonical_persona(
    principal: &str,
    routine: &str,
    tool: &str,
    coverage: &GrantCoverage<'_>,
    enrollment_id: &str,
    created_at_ms: u64,
) -> Vec<u8> {
    canonical_bytes(&GrantCanonical {
        kind: GRANT_PERSONA_KIND,
        principal,
        routine,
        tool,
        destination: coverage.destination,
        slot_schema_hash: coverage.slot_schema_hash,
        covered_capabilities: coverage.covered_capabilities,
        enrollment_id,
        created_at_ms,
    })
}

/// Assemble the full signed grant payload from the canonical fields and a
/// [`PersonaProof`].
///
/// The persona-signing sibling of [`signed_grant_payload`] (#1197):
/// `proof.signing_public_key` is the persona's currently recorded
/// `PersonaCredential.signing_public_key`; `proof.signature` is that key's
/// plain ed25519 signature over [`grant_canonical_persona`]'s bytes directly
/// (no `WebAuthn` challenge/assertion wrapping).
#[must_use]
pub fn signed_grant_payload_persona(
    principal: &str,
    routine: &str,
    tool: &str,
    coverage: &GrantCoverage<'_>,
    enrollment_id: &str,
    created_at_ms: u64,
    proof: &PersonaProof<'_>,
) -> Vec<u8> {
    let canonical = grant_canonical_persona(
        principal,
        routine,
        tool,
        coverage,
        enrollment_id,
        created_at_ms,
    );
    attach_persona_proof(&canonical, proof)
}

/// Verify a persisted persona-signed `routine_grant` payload.
///
/// The persona-signing sibling of [`verify_grant`] (#1197). Recomputes
/// [`grant_canonical_persona`] from the payload's own fields and verifies the
/// persona proof against `expected_persona_pubkey` — the
/// persona's CURRENTLY recorded `PersonaCredential.signing_public_key`,
/// looked up live by the caller (never trusted from the payload itself, and
/// never snapshotted at grant-mint time) so a later credential revocation is
/// reflected on every subsequent verification of every grant that credential
/// ever signed — the cascading-revocation property #1197 intentionally
/// chose over per-grant-independent revocation. Returns `None` fail-closed
/// on any malformed field, bad base64, key mismatch, or signature failure.
#[must_use]
pub fn verify_persona_signed_grant(
    payload: &[u8],
    expected_persona_pubkey: &[u8],
) -> Option<VerifiedGrant> {
    let v: Value = serde_json::from_slice(payload).ok()?;
    if v.get("kind")?.as_str()? != GRANT_PERSONA_KIND {
        return None;
    }
    let principal = v.get("principal")?.as_str()?.to_owned();
    let routine = v.get("routine")?.as_str()?.to_owned();
    let tool = v.get("tool")?.as_str()?.to_owned();
    let destination = v.get("destination")?.as_str()?.to_owned();
    let slot_schema_hash = v.get("slot_schema_hash")?.as_str()?.to_owned();
    let covered_capabilities: Vec<String> = v
        .get("covered_capabilities")?
        .as_array()?
        .iter()
        .map(|c| c.as_str().map(str::to_owned))
        .collect::<Option<Vec<_>>>()?;
    let enrollment_id = v.get("enrollment_id")?.as_str()?.to_owned();
    let created_at_ms = v.get("created_at_ms")?.as_u64()?;

    let coverage = GrantCoverage {
        destination: &destination,
        slot_schema_hash: &slot_schema_hash,
        covered_capabilities: &covered_capabilities,
    };
    let canonical = grant_canonical_persona(
        &principal,
        &routine,
        &tool,
        &coverage,
        &enrollment_id,
        created_at_ms,
    );
    verify_persona_proof(&v, &canonical, expected_persona_pubkey)?;

    Some(VerifiedGrant {
        principal,
        routine,
        tool,
        destination,
        slot_schema_hash,
        covered_capabilities,
        enrollment_id,
        created_at_ms,
        grant_ref: grant_ref(payload),
        registered_public_key: expected_persona_pubkey.to_vec(),
    })
}

/// A grant whose passkey assertion verified against the registered key.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct VerifiedGrant {
    /// The principal the grant is scoped to (a persona id — matched against the
    /// turn's caller for isolation, the same rule as
    /// [`crate::approval::is_session_grant_for`]).
    pub principal: String,
    /// The routine the grant belongs to.
    pub routine: String,
    /// The tool the grant covers.
    pub tool: String,
    /// The pinned egress destination the grant covers.
    pub destination: String,
    /// The content-template slot-schema hash the grant covers.
    pub slot_schema_hash: String,
    /// The stable kebab-case capability names the grant covers.
    pub covered_capabilities: Vec<String>,
    /// The enrollment this grant was minted in.
    pub enrollment_id: String,
    /// Milliseconds since the Unix epoch the grant was created.
    pub created_at_ms: u64,
    /// The sha256-hex of the full signed payload — the [`grant_ref`] a
    /// revocation or suspension binds.
    pub grant_ref: String,
    /// The SEC1 registered public key the assertion verified against.
    pub registered_public_key: Vec<u8>,
}

/// Verify a persisted `routine_grant` payload against a registered passkey.
///
/// Recomputes the grant canonical from the payload's own fields, derives the
/// expected [`grant_challenge`], and runs [`verify_assertion`] against
/// `registered_pubkey_sec1` for `rp_id` / `origin`. A byte-level change to ANY
/// canonical-bound field changes the challenge and fails the assertion; a grant
/// signed by a different passkey, or verified against a different registered
/// key, fails. Returns `None` fail-closed on any malformed field, bad base64,
/// or verification failure.
#[must_use]
pub fn verify_grant(
    payload: &[u8],
    registered_pubkey_sec1: &[u8],
    rp_id: &str,
    origin: &str,
) -> Option<VerifiedGrant> {
    let v: Value = serde_json::from_slice(payload).ok()?;
    if v.get("kind")?.as_str()? != GRANT_KIND {
        return None;
    }
    let principal = v.get("principal")?.as_str()?.to_owned();
    let routine = v.get("routine")?.as_str()?.to_owned();
    let tool = v.get("tool")?.as_str()?.to_owned();
    let destination = v.get("destination")?.as_str()?.to_owned();
    let slot_schema_hash = v.get("slot_schema_hash")?.as_str()?.to_owned();
    let covered_capabilities: Vec<String> = v
        .get("covered_capabilities")?
        .as_array()?
        .iter()
        .map(|c| c.as_str().map(str::to_owned))
        .collect::<Option<Vec<_>>>()?;
    let enrollment_id = v.get("enrollment_id")?.as_str()?.to_owned();
    let created_at_ms = v.get("created_at_ms")?.as_u64()?;

    let coverage = GrantCoverage {
        destination: &destination,
        slot_schema_hash: &slot_schema_hash,
        covered_capabilities: &covered_capabilities,
    };
    let canonical = grant_canonical(
        &principal,
        &routine,
        &tool,
        &coverage,
        &enrollment_id,
        created_at_ms,
    );
    verify_passkey_proof(&v, &canonical, registered_pubkey_sec1, rp_id, origin)?;

    Some(VerifiedGrant {
        principal,
        routine,
        tool,
        destination,
        slot_schema_hash,
        covered_capabilities,
        enrollment_id,
        created_at_ms,
        grant_ref: grant_ref(payload),
        registered_public_key: registered_pubkey_sec1.to_vec(),
    })
}

/// The canonical bytes a revocation tombstone's passkey challenge binds.
///
/// Binds the [`grant_ref`] of the grant being withdrawn and the revocation
/// time. A distinct `kind` tag ([`REVOCATION_KIND`]) keeps it separable from a
/// grant in the audit trail.
#[must_use]
pub fn revocation_canonical(grant_ref: &str, revoked_at_ms: u64) -> Vec<u8> {
    canonical_bytes(&RevocationCanonical {
        kind: REVOCATION_KIND,
        grant_ref,
        revoked_at_ms,
    })
}

/// Assemble the full signed revocation payload from a `WebAuthn` proof.
///
/// The principal's own act (ADR 0001 / CONTEXT.md): a fresh passkey assertion
/// over the revocation's own [`grant_challenge`]. Symmetric with
/// [`signed_grant_payload`].
#[must_use]
pub fn signed_revocation_payload(
    grant_ref: &str,
    revoked_at_ms: u64,
    proof: &WebAuthnProof<'_>,
) -> Vec<u8> {
    let canonical = revocation_canonical(grant_ref, revoked_at_ms);
    attach_proof(&canonical, proof)
}

/// A revocation tombstone whose passkey assertion verified.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct VerifiedRevocation {
    /// The [`grant_ref`] this tombstone voids.
    pub grant_ref: String,
    /// Milliseconds since the Unix epoch the grant was revoked.
    pub revoked_at_ms: u64,
    /// The SEC1 registered public key the assertion verified against.
    pub registered_public_key: Vec<u8>,
}

/// Verify a persisted `grant_revocation` payload against a registered passkey.
///
/// Recomputes the revocation canonical, derives the expected challenge, and
/// runs [`verify_assertion`]. Returns `None` fail-closed on any malformed
/// field, bad base64, or verification failure — including a tombstone signed by
/// a passkey other than the one that minted the grant (verified against the
/// caller-supplied registered key).
#[must_use]
pub fn verify_revocation(
    payload: &[u8],
    registered_pubkey_sec1: &[u8],
    rp_id: &str,
    origin: &str,
) -> Option<VerifiedRevocation> {
    let v: Value = serde_json::from_slice(payload).ok()?;
    if v.get("kind")?.as_str()? != REVOCATION_KIND {
        return None;
    }
    let grant_ref = v.get("grant_ref")?.as_str()?.to_owned();
    let revoked_at_ms = v.get("revoked_at_ms")?.as_u64()?;

    let canonical = revocation_canonical(&grant_ref, revoked_at_ms);
    verify_passkey_proof(&v, &canonical, registered_pubkey_sec1, rp_id, origin)?;

    Some(VerifiedRevocation {
        grant_ref,
        revoked_at_ms,
        registered_public_key: registered_pubkey_sec1.to_vec(),
    })
}

/// The canonical bytes a persona-signed revocation tombstone's signature binds.
///
/// The persona-signing sibling of [`revocation_canonical`], identical
/// fields, distinguished only by [`REVOCATION_PERSONA_KIND`] (#1197).
#[must_use]
pub fn revocation_canonical_persona(grant_ref: &str, revoked_at_ms: u64) -> Vec<u8> {
    canonical_bytes(&RevocationCanonical {
        kind: REVOCATION_PERSONA_KIND,
        grant_ref,
        revoked_at_ms,
    })
}

/// Assemble the full signed revocation payload from a [`PersonaProof`].
///
/// The persona-signing sibling of [`signed_revocation_payload`] (#1197).
/// Symmetric with [`signed_grant_payload_persona`].
#[must_use]
pub fn signed_revocation_payload_persona(
    grant_ref: &str,
    revoked_at_ms: u64,
    proof: &PersonaProof<'_>,
) -> Vec<u8> {
    let canonical = revocation_canonical_persona(grant_ref, revoked_at_ms);
    attach_persona_proof(&canonical, proof)
}

/// Verify a persisted persona-signed `grant_revocation` payload.
///
/// The persona-signing sibling of [`verify_revocation`] (#1197).
/// `expected_persona_pubkey` is the persona's CURRENTLY recorded signing
/// key, looked up live by the caller — same cascading-revocation rationale
/// as [`verify_persona_signed_grant`]'s docs.
#[must_use]
pub fn verify_persona_signed_revocation(
    payload: &[u8],
    expected_persona_pubkey: &[u8],
) -> Option<VerifiedRevocation> {
    let v: Value = serde_json::from_slice(payload).ok()?;
    if v.get("kind")?.as_str()? != REVOCATION_PERSONA_KIND {
        return None;
    }
    let grant_ref = v.get("grant_ref")?.as_str()?.to_owned();
    let revoked_at_ms = v.get("revoked_at_ms")?.as_u64()?;

    let canonical = revocation_canonical_persona(&grant_ref, revoked_at_ms);
    verify_persona_proof(&v, &canonical, expected_persona_pubkey)?;

    Some(VerifiedRevocation {
        grant_ref,
        revoked_at_ms,
        registered_public_key: expected_persona_pubkey.to_vec(),
    })
}

/// The canonical (signature-covered) bytes of a suspension.
///
/// Binds the [`grant_ref`], the `reason`, and the suspension time under a
/// distinct `kind` tag ([`SUSPENSION_KIND`]) — so a suspension and a revocation
/// can never be confused in the audit trail even though both bind a `grant_ref`.
#[must_use]
pub fn suspension_canonical(grant_ref: &str, reason: &str, suspended_at_ms: u64) -> Vec<u8> {
    canonical_bytes(&suspension_fields(grant_ref, reason, suspended_at_ms))
}

/// The suspension body both [`suspension_canonical`] and
/// [`suspension_payload`] build, so the signed field list exists once.
const fn suspension_fields<'a>(
    grant_ref: &'a str,
    reason: &'a str,
    suspended_at_ms: u64,
) -> SuspensionCanonical<'a> {
    SuspensionCanonical {
        kind: SUSPENSION_KIND,
        grant_ref,
        reason,
        suspended_at_ms,
    }
}

/// Build a platform-signed (ed25519) suspension payload.
///
/// The platform's act, never the principal's (CONTEXT.md): it reuses the
/// existing [`Signer`] and NEVER requires the passkey, so a lost passkey cannot
/// strand a live grant. `signed_by` / `signature_hex` are appended after
/// signing and are not covered. Returns
/// `(full_payload_bytes, signature_bytes, public_key_bytes)`.
#[must_use]
pub fn suspension_payload(
    grant_ref: &str,
    reason: &str,
    suspended_at_ms: u64,
    signer: &Signer,
) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
    Envelope::seal(
        suspension_fields(grant_ref, reason, suspended_at_ms),
        signer,
    )
}

/// A suspension whose ed25519 signature verified.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct VerifiedSuspension {
    /// The [`grant_ref`] this suspension voids.
    pub grant_ref: String,
    /// The platform's audit reason for the suspension.
    pub reason: String,
    /// Milliseconds since the Unix epoch the grant was suspended.
    pub suspended_at_ms: u64,
    /// The verified platform signer's public key (encoded).
    pub signer_public_key: Vec<u8>,
}

/// Verify a persisted `grant_suspension` payload against the deployment's
/// pinned platform verification key.
///
/// **Trust model:** the caller supplies `expected_platform_key` — the
/// deployment's platform verification key, the one the operator's [`Signer`]
/// corresponds to (never taken from the payload). After decoding, this
/// requires the payload's own `signed_by` key bytes to equal
/// `expected_platform_key` exactly (byte equality; not constant-time, since a
/// public key carries no secret worth guarding against a timing side channel)
/// **before** running the ed25519 verify. A suspension signed by any other
/// key — including a well-formed, self-consistent one from a disposable
/// keypair an attacker controls — is dropped fail-closed: without the pin, a
/// suspension payload carries both its own pubkey and signature, so anyone who
/// can get a suspension-shaped payload accepted could forge one that verifies
/// against itself. Pinning is what makes the audit trail's "the platform did
/// this" claim actually true.
///
/// Rebuilds the suspension canonical and checks the embedded signature via the
/// existing [`verify`]. Returns `None` fail-closed on any malformed field, bad
/// hex, key mismatch, or signature mismatch. The `kind` tag is checked first so
/// a revocation or grant payload can never verify as a suspension.
#[must_use]
pub fn verify_suspension(
    payload: &[u8],
    expected_platform_key: &[u8],
) -> Option<VerifiedSuspension> {
    let v: Value = serde_json::from_slice(payload).ok()?;
    if v.get("kind")?.as_str()? != SUSPENSION_KIND {
        return None;
    }
    let grant_ref = v.get("grant_ref")?.as_str()?.to_owned();
    let reason = v.get("reason")?.as_str()?.to_owned();
    let suspended_at_ms = v.get("suspended_at_ms")?.as_u64()?;
    let pk = crate::hex::decode(v.get("signed_by")?.as_str()?)?;
    let sig = crate::hex::decode(v.get("signature_hex")?.as_str()?)?;
    if pk != expected_platform_key {
        return None;
    }
    let canonical = suspension_canonical(&grant_ref, &reason, suspended_at_ms);
    if verify(&pk, &canonical, &sig) {
        Some(VerifiedSuspension {
            grant_ref,
            reason,
            suspended_at_ms,
            signer_public_key: pk,
        })
    } else {
        None
    }
}

/// The single fold that decides which grant is live.
///
/// Returns the first grant with no matching verified revocation or suspension
/// (matched by [`grant_ref`]); a grant with either is absent. This is the ONE
/// place "revoked or suspended ⇒ absent" lives — #594 (the gate) and #623
/// (re-gating) call it, never reimplement it — so the two paths cannot drift on
/// what counts as live.
#[must_use]
pub fn live_grant<'a>(
    grants: &'a [VerifiedGrant],
    revocations: &[VerifiedRevocation],
    suspensions: &[VerifiedSuspension],
) -> Option<&'a VerifiedGrant> {
    grants.iter().find(|g| {
        !revocations.iter().any(|r| r.grant_ref == g.grant_ref)
            && !suspensions.iter().any(|s| s.grant_ref == g.grant_ref)
    })
}

fn b64(bytes: &[u8]) -> String {
    URL_SAFE_NO_PAD.encode(bytes)
}

fn b64_decode(s: &str) -> Option<Vec<u8>> {
    URL_SAFE_NO_PAD.decode(s).ok()
}

#[cfg(test)]
mod tests {
    #![allow(clippy::pedantic, clippy::nursery, missing_docs)]

    use super::*;
    use polyc_passkey::softkey::SoftPasskey;

    const RP_ID: &str = "enroll.polychrome.test";
    const ORIGIN: &str = "https://enroll.polychrome.test";

    fn caps() -> Vec<String> {
        vec![
            "arbitrary-egress".to_owned(),
            "fixed-connector-read".to_owned(),
        ]
    }

    // Mint a full signed grant with a SoftPasskey over its own challenge — the
    // exact assemble-then-persist flow the ceremony (#621) runs.
    fn mint_grant(key: &SoftPasskey) -> Vec<u8> {
        let covered = caps();
        let coverage = GrantCoverage {
            destination: "slack:T1:C42",
            slot_schema_hash: "sha256:template-abc",
            covered_capabilities: &covered,
        };
        let canonical = grant_canonical(
            "persona-9",
            "standup",
            "post_summary",
            &coverage,
            "enr-1",
            1_700_000_000_000,
        );
        let challenge = grant_challenge(&canonical);
        let signed = key.sign_assertion(&challenge, RP_ID, ORIGIN);
        let proof = WebAuthnProof {
            credential_id: &signed.credential_id,
            authenticator_data: &signed.authenticator_data,
            client_data_json: &signed.client_data_json,
            signature: &signed.signature,
        };
        signed_grant_payload(
            "persona-9",
            "standup",
            "post_summary",
            &coverage,
            "enr-1",
            1_700_000_000_000,
            &proof,
        )
    }

    #[test]
    fn grant_round_trips_and_carries_coverage() {
        let key = SoftPasskey::from_seed(1);
        let payload = mint_grant(&key);
        let g = verify_grant(&payload, &key.public_key_sec1(), RP_ID, ORIGIN).expect("verifies");
        assert_eq!(g.principal, "persona-9");
        assert_eq!(g.routine, "standup");
        assert_eq!(g.tool, "post_summary");
        assert_eq!(g.destination, "slack:T1:C42");
        assert_eq!(g.slot_schema_hash, "sha256:template-abc");
        assert_eq!(g.covered_capabilities, caps());
        assert_eq!(g.enrollment_id, "enr-1");
        assert_eq!(g.grant_ref, grant_ref(&payload));
    }

    #[test]
    fn grant_signed_by_a_different_passkey_is_dropped() {
        let signer = SoftPasskey::from_seed(1);
        let attacker = SoftPasskey::from_seed(2);
        let payload = mint_grant(&signer);
        // Verified against the attacker's registered key ⇒ fail-closed.
        assert!(verify_grant(&payload, &attacker.public_key_sec1(), RP_ID, ORIGIN).is_none());
        // And the genuine key still verifies (control).
        assert!(verify_grant(&payload, &signer.public_key_sec1(), RP_ID, ORIGIN).is_some());
    }

    #[test]
    fn every_canonical_field_including_kind_is_tamper_evident() {
        let key = SoftPasskey::from_seed(3);
        let payload = mint_grant(&key);
        let pk = key.public_key_sec1();
        // Tampering any canonical-bound field changes the challenge the
        // assertion must carry, so verification fails. The proof fields are
        // covered indirectly (a swapped assertion won't match the challenge).
        // `kind` is the one exception: it fails its own explicit equality
        // check in verify_grant before the challenge is ever recomputed, so a
        // grant payload relabeled as a revocation (or any other kind) is
        // rejected on that check instead — still covered by this table so the
        // tamper coverage reads as "every canonical field", not "every field
        // except kind".
        for (field, val) in [
            ("kind", serde_json::json!(REVOCATION_KIND)),
            ("principal", serde_json::json!("persona-EVIL")),
            ("routine", serde_json::json!("other-routine")),
            ("tool", serde_json::json!("exfiltrate")),
            ("destination", serde_json::json!("slack:T1:CEVIL")),
            ("slot_schema_hash", serde_json::json!("sha256:tampered")),
            (
                "covered_capabilities",
                serde_json::json!(["arbitrary-egress", "mutate-external"]),
            ),
            ("enrollment_id", serde_json::json!("enr-2")),
            ("created_at_ms", serde_json::json!(1_700_000_000_001u64)),
        ] {
            let mut v: Value = serde_json::from_slice(&payload).unwrap();
            v[field] = val;
            assert!(
                verify_grant(v.to_string().as_bytes(), &pk, RP_ID, ORIGIN).is_none(),
                "tampered {field} must fail verification"
            );
        }
        // Untampered still verifies.
        assert!(verify_grant(&payload, &pk, RP_ID, ORIGIN).is_some());
    }

    #[test]
    fn grant_ref_is_sensitive_to_the_full_payload() {
        let key = SoftPasskey::from_seed(4);
        let a = mint_grant(&key);
        assert_eq!(grant_ref(&a), grant_ref(&a));
        // A different key mints a different assertion ⇒ a different grant_ref,
        // since it hashes the full signed artifact.
        let b = mint_grant(&SoftPasskey::from_seed(5));
        assert_ne!(grant_ref(&a), grant_ref(&b));
    }

    fn mint_revocation(key: &SoftPasskey, grant_ref_hex: &str, revoked_at_ms: u64) -> Vec<u8> {
        let canonical = revocation_canonical(grant_ref_hex, revoked_at_ms);
        let challenge = grant_challenge(&canonical);
        let signed = key.sign_assertion(&challenge, RP_ID, ORIGIN);
        let proof = WebAuthnProof {
            credential_id: &signed.credential_id,
            authenticator_data: &signed.authenticator_data,
            client_data_json: &signed.client_data_json,
            signature: &signed.signature,
        };
        signed_revocation_payload(grant_ref_hex, revoked_at_ms, &proof)
    }

    #[test]
    fn revocation_round_trips_and_binds_the_grant_ref() {
        let key = SoftPasskey::from_seed(6);
        let payload = mint_grant(&key);
        let gref = grant_ref(&payload);
        let rev = mint_revocation(&key, &gref, 1_700_000_100_000);
        let v = verify_revocation(&rev, &key.public_key_sec1(), RP_ID, ORIGIN).expect("verifies");
        assert_eq!(v.grant_ref, gref);
        assert_eq!(v.revoked_at_ms, 1_700_000_100_000);
        // A tombstone signed by a different passkey is rejected.
        assert!(
            verify_revocation(
                &rev,
                &SoftPasskey::from_seed(7).public_key_sec1(),
                RP_ID,
                ORIGIN
            )
            .is_none()
        );
    }

    #[test]
    fn revocation_tampered_grant_ref_fails() {
        let key = SoftPasskey::from_seed(6);
        let rev = mint_revocation(&key, &"0".repeat(64), 1);
        let mut v: Value = serde_json::from_slice(&rev).unwrap();
        v["grant_ref"] = serde_json::json!("f".repeat(64));
        assert!(
            verify_revocation(
                v.to_string().as_bytes(),
                &key.public_key_sec1(),
                RP_ID,
                ORIGIN
            )
            .is_none()
        );
    }

    #[test]
    fn suspension_round_trips_and_is_tamper_evident() {
        let signer = Signer::from_seed(1);
        let platform_key = signer.public_key_bytes();
        let (payload, _sig, _pk) = suspension_payload(
            "deadbeef",
            "misbehaving routine",
            1_700_000_200_000,
            &signer,
        );
        let v = verify_suspension(&payload, &platform_key).expect("verifies");
        assert_eq!(v.grant_ref, "deadbeef");
        assert_eq!(v.reason, "misbehaving routine");
        assert_eq!(v.suspended_at_ms, 1_700_000_200_000);
        for (field, val) in [
            ("grant_ref", serde_json::json!("cafe")),
            ("reason", serde_json::json!("something else")),
            ("suspended_at_ms", serde_json::json!(0u64)),
        ] {
            let mut t: Value = serde_json::from_slice(&payload).unwrap();
            t[field] = val;
            assert!(
                verify_suspension(t.to_string().as_bytes(), &platform_key).is_none(),
                "tampered {field} must fail"
            );
        }
    }

    #[test]
    fn suspension_signed_by_a_key_other_than_the_expected_platform_key_is_dropped() {
        // A suspension shaped payload carries BOTH its signer's pubkey and
        // signature; without pinning, that pubkey+signature are always
        // self-consistent no matter which key minted them. Anyone who can get
        // a grant_suspension-shaped payload accepted could forge one with a
        // disposable keypair. Pinning `expected_platform_key` closes that:
        // a suspension signed by any key other than the deployment's platform
        // key must be dropped fail-closed, even though it verifies fine
        // against its own embedded key.
        let forger = Signer::from_seed(99);
        let real_platform = Signer::from_seed(1);
        let (payload, _sig, _pk) =
            suspension_payload("deadbeef", "misbehaving routine", 1, &forger);
        assert!(verify_suspension(&payload, &real_platform.public_key_bytes()).is_none());
    }

    #[test]
    fn suspension_signed_by_the_expected_platform_key_round_trips() {
        let platform = Signer::from_seed(1);
        let (payload, _sig, _pk) =
            suspension_payload("deadbeef", "misbehaving routine", 1, &platform);
        assert!(verify_suspension(&payload, &platform.public_key_bytes()).is_some());
    }

    #[test]
    fn live_grant_ignores_a_wrong_key_suspension_and_leaves_the_grant_live() {
        // Fail-closed cuts the OTHER way here than for grants/revocations: a
        // forged suspension (real canonical fields, wrong signer) must be
        // IGNORED, not honored, so the grant stays live. Honoring it would let
        // an attacker holding a disposable keypair suspend (DoS) any grant it
        // can guess a grant_ref for. The pinned check's job isn't to protect
        // availability of the grant — it's to keep the audit trail's "the
        // platform acted" claim true: a suspension record must only ever
        // originate from the platform's actual key, or it doesn't count.
        let key = SoftPasskey::from_seed(20);
        let payload = mint_grant(&key);
        let pk = key.public_key_sec1();
        let grant = verify_grant(&payload, &pk, RP_ID, ORIGIN).unwrap();
        let grants = vec![grant.clone()];

        let forger = Signer::from_seed(99);
        let real_platform = Signer::from_seed(1);
        let (susp_payload, _s, _p) =
            suspension_payload(&grant.grant_ref, "kill switch", 1, &forger);
        // The forged suspension does not verify against the real platform key.
        assert!(verify_suspension(&susp_payload, &real_platform.public_key_bytes()).is_none());
        // So no verified suspension exists to fold in, and the grant is live.
        assert_eq!(live_grant(&grants, &[], &[]), Some(&grants[0]));
    }

    #[test]
    fn revocation_and_suspension_cannot_be_confused() {
        // Distinct kinds: a suspension never verifies as a revocation, and a
        // grant never verifies as a suspension.
        let signer = Signer::from_seed(1);
        let (susp, _s, _p) = suspension_payload("deadbeef", "x", 1, &signer);
        assert!(
            verify_revocation(
                &susp,
                &SoftPasskey::from_seed(1).public_key_sec1(),
                RP_ID,
                ORIGIN
            )
            .is_none()
        );
        let grant = mint_grant(&SoftPasskey::from_seed(1));
        assert!(verify_suspension(&grant, &signer.public_key_bytes()).is_none());
    }

    #[test]
    fn live_grant_folds_revocations_and_suspensions() {
        let key = SoftPasskey::from_seed(8);
        let payload = mint_grant(&key);
        let pk = key.public_key_sec1();
        let grant = verify_grant(&payload, &pk, RP_ID, ORIGIN).unwrap();
        let grants = vec![grant.clone()];

        // No tombstone/suspension ⇒ live.
        assert_eq!(live_grant(&grants, &[], &[]), Some(&grants[0]));

        // Matching revocation ⇒ absent.
        let rev = verify_revocation(
            &mint_revocation(&key, &grant.grant_ref, 1),
            &pk,
            RP_ID,
            ORIGIN,
        )
        .unwrap();
        assert!(live_grant(&grants, std::slice::from_ref(&rev), &[]).is_none());

        // Matching suspension ⇒ absent.
        let platform = Signer::from_seed(1);
        let (susp_payload, _s, _p) =
            suspension_payload(&grant.grant_ref, "kill switch", 1, &platform);
        let susp = verify_suspension(&susp_payload, &platform.public_key_bytes()).unwrap();
        assert!(live_grant(&grants, &[], std::slice::from_ref(&susp)).is_none());

        // A revocation for a DIFFERENT grant_ref leaves this grant live.
        let other = verify_revocation(
            &mint_revocation(&key, &"0".repeat(64), 1),
            &pk,
            RP_ID,
            ORIGIN,
        )
        .unwrap();
        assert_eq!(
            live_grant(&grants, std::slice::from_ref(&other), &[]),
            Some(&grants[0])
        );
    }

    #[test]
    fn garbage_payloads_return_none_not_panic() {
        let pk = SoftPasskey::from_seed(1).public_key_sec1();
        assert!(verify_grant(b"not json", &pk, RP_ID, ORIGIN).is_none());
        assert!(verify_revocation(b"{}", &pk, RP_ID, ORIGIN).is_none());
        assert!(verify_suspension(b"[]", &Signer::from_seed(1).public_key_bytes()).is_none());
    }

    // ── #1197: persona-signed grants (grant-signing credential reuse) ────────

    fn persona_keypair(seed: &[u8]) -> polyc_passkey::derive::SigningKeypair {
        polyc_passkey::derive::derive_signing_keypair(seed)
    }

    // Mint a full persona-signed grant — the exact assemble-then-persist flow
    // the enrollment ceremony runs when the persona already has a recorded
    // signing credential, instead of minting a new per-enrollment passkey.
    fn mint_persona_grant(keypair: &polyc_passkey::derive::SigningKeypair) -> Vec<u8> {
        let covered = caps();
        let coverage = GrantCoverage {
            destination: "slack:T1:C42",
            slot_schema_hash: "sha256:template-abc",
            covered_capabilities: &covered,
        };
        let canonical = grant_canonical_persona(
            "persona-9",
            "standup",
            "post_summary",
            &coverage,
            "enr-1",
            1_700_000_000_000,
        );
        let signature = keypair.sign(&canonical);
        let public_key = keypair.public_key();
        signed_grant_payload_persona(
            "persona-9",
            "standup",
            "post_summary",
            &coverage,
            "enr-1",
            1_700_000_000_000,
            &PersonaProof {
                signing_public_key: &public_key,
                signature: &signature,
            },
        )
    }

    #[test]
    fn persona_grant_round_trips_and_carries_coverage() {
        let keypair = persona_keypair(b"persona-seed-1-------------------");
        let payload = mint_persona_grant(&keypair);
        let g = verify_persona_signed_grant(&payload, &keypair.public_key()).expect("verifies");
        assert_eq!(g.principal, "persona-9");
        assert_eq!(g.routine, "standup");
        assert_eq!(g.tool, "post_summary");
        assert_eq!(g.destination, "slack:T1:C42");
        assert_eq!(g.slot_schema_hash, "sha256:template-abc");
        assert_eq!(g.covered_capabilities, caps());
        assert_eq!(g.enrollment_id, "enr-1");
        assert_eq!(g.grant_ref, grant_ref(&payload));
        assert_eq!(g.registered_public_key, keypair.public_key());
    }

    #[test]
    fn persona_grant_signed_by_a_different_key_is_dropped() {
        let signer = persona_keypair(b"persona-seed-2-------------------");
        let attacker = persona_keypair(b"persona-seed-3-------------------");
        let payload = mint_persona_grant(&signer);
        // Verified against the attacker's key ⇒ fail-closed.
        assert!(verify_persona_signed_grant(&payload, &attacker.public_key()).is_none());
        // The genuine key still verifies (control).
        assert!(verify_persona_signed_grant(&payload, &signer.public_key()).is_some());
    }

    #[test]
    fn persona_grant_every_canonical_field_is_tamper_evident() {
        let keypair = persona_keypair(b"persona-seed-4-------------------");
        let payload = mint_persona_grant(&keypair);
        let pk = keypair.public_key();
        for (field, val) in [
            ("kind", serde_json::json!(REVOCATION_PERSONA_KIND)),
            ("principal", serde_json::json!("persona-EVIL")),
            ("routine", serde_json::json!("other-routine")),
            ("tool", serde_json::json!("exfiltrate")),
            ("destination", serde_json::json!("slack:T1:CEVIL")),
            ("slot_schema_hash", serde_json::json!("sha256:tampered")),
            (
                "covered_capabilities",
                serde_json::json!(["arbitrary-egress", "mutate-external"]),
            ),
            ("enrollment_id", serde_json::json!("enr-2")),
            ("created_at_ms", serde_json::json!(1_700_000_000_001u64)),
        ] {
            let mut v: Value = serde_json::from_slice(&payload).unwrap();
            v[field] = val;
            assert!(
                verify_persona_signed_grant(v.to_string().as_bytes(), &pk).is_none(),
                "tampered {field} must fail verification"
            );
        }
        assert!(verify_persona_signed_grant(&payload, &pk).is_some());
    }

    #[test]
    fn persona_grant_and_webauthn_grant_never_verify_as_each_other() {
        // A persona-signed grant carries GRANT_PERSONA_KIND, not GRANT_KIND —
        // verify_grant (the WebAuthn path) must refuse it outright, and
        // verify_persona_signed_grant must refuse a real WebAuthn-signed
        // grant right back. Distinct kind tags, never confusable, exactly
        // the discipline this module already holds for grant/revocation/
        // suspension.
        let keypair = persona_keypair(b"persona-seed-5-------------------");
        let persona_payload = mint_persona_grant(&keypair);
        assert!(
            verify_grant(
                &persona_payload,
                &SoftPasskey::from_seed(1).public_key_sec1(),
                RP_ID,
                ORIGIN
            )
            .is_none()
        );

        let webauthn_payload = mint_grant(&SoftPasskey::from_seed(1));
        assert!(verify_persona_signed_grant(&webauthn_payload, &keypair.public_key()).is_none());
    }

    #[test]
    fn persona_revocation_round_trips_and_binds_the_grant_ref() {
        let keypair = persona_keypair(b"persona-seed-6-------------------");
        let payload = mint_persona_grant(&keypair);
        let gref = grant_ref(&payload);
        let canonical = revocation_canonical_persona(&gref, 1_700_000_100_000);
        let signature = keypair.sign(&canonical);
        let public_key = keypair.public_key();
        let rev = signed_revocation_payload_persona(
            &gref,
            1_700_000_100_000,
            &PersonaProof {
                signing_public_key: &public_key,
                signature: &signature,
            },
        );
        let v = verify_persona_signed_revocation(&rev, &keypair.public_key()).expect("verifies");
        assert_eq!(v.grant_ref, gref);
        assert_eq!(v.revoked_at_ms, 1_700_000_100_000);
        // A tombstone signed by a different key is rejected.
        let other = persona_keypair(b"persona-seed-7-------------------");
        assert!(verify_persona_signed_revocation(&rev, &other.public_key()).is_none());
    }

    #[test]
    fn persona_grant_and_revocation_can_fold_through_live_grant() {
        // The generic live_grant fold doesn't care which signing method
        // produced a VerifiedGrant/VerifiedRevocation — a persona-signed
        // grant with a persona-signed revocation folds exactly like the
        // WebAuthn-signed pair does.
        let keypair = persona_keypair(b"persona-seed-8-------------------");
        let payload = mint_persona_grant(&keypair);
        let grant = verify_persona_signed_grant(&payload, &keypair.public_key()).unwrap();
        let grants = vec![grant.clone()];
        assert_eq!(live_grant(&grants, &[], &[]), Some(&grants[0]));

        let canonical = revocation_canonical_persona(&grant.grant_ref, 1);
        let signature = keypair.sign(&canonical);
        let public_key = keypair.public_key();
        let rev_payload = signed_revocation_payload_persona(
            &grant.grant_ref,
            1,
            &PersonaProof {
                signing_public_key: &public_key,
                signature: &signature,
            },
        );
        let rev = verify_persona_signed_revocation(&rev_payload, &keypair.public_key()).unwrap();
        assert!(live_grant(&grants, std::slice::from_ref(&rev), &[]).is_none());
    }

    #[test]
    fn persona_grant_garbage_payloads_return_none_not_panic() {
        let pk = persona_keypair(b"persona-seed-9-------------------").public_key();
        assert!(verify_persona_signed_grant(b"not json", &pk).is_none());
        assert!(verify_persona_signed_revocation(b"{}", &pk).is_none());
    }
}

#[cfg(test)]
mod canonical_freeze {
    //! Every signed canonical in this module, frozen as literal bytes (`#1845`).
    //!
    //! These are the bytes a deployment has already signed and has sitting in
    //! its log. They are checked in, never regenerated: regenerating one is the
    //! defect this module exists to catch, because a canonical whose bytes move
    //! invalidates every signature ever minted over the old ones.
    //!
    //! The reason they can be single literals at all is the conversion `#1845`
    //! made, following `#1842`. Before it, each canonical was a
    //! [`serde_json::Value`], whose object is a `BTreeMap` (keys sorted) by
    //! default and an `IndexMap` (insertion order) whenever anything in the
    //! build graph enables `serde_json/preserve_order` — so the same payload
    //! signed by two binaries with different dependency sets produced different
    //! bytes and different signatures. Every literal below is the
    //! insertion-order form, which is what a control-plane binary (where
    //! `preserve_order` is unified in) has always signed. Run this module under
    //! either selection and every literal holds:
    //!
    //! ```text
    //! cargo nextest run -p polyc-crypto                    # no preserve_order
    //! cargo nextest run -p polyc-crypto -p polyc-payments  # preserve_order on
    //! ```
    //!
    //! See ADR 0009 for the decision these literals enforce.
    #![allow(clippy::pedantic, clippy::nursery, missing_docs)]

    use super::*;

    /// Assert a canonical's bytes are exactly the frozen literal.
    fn frozen(label: &str, got: &[u8], want: &str) {
        assert_eq!(
            String::from_utf8(got.to_vec()).unwrap(),
            want,
            "{label}: canonical bytes moved — every signature over the old bytes is now unverifiable"
        );
    }

    const DESTINATION: &str = r#"{"channel":"C1","workspace":"T1"}"#;
    const GRANT_REF: &str = "cafe0123";
    const CREATED_AT_MS: u64 = 1_700_000_000_000;
    const REVOKED_AT_MS: u64 = 1_700_000_100_000;
    const SUSPENDED_AT_MS: u64 = 1_700_000_200_000;
    const REASON: &str = "policy change";

    fn caps() -> Vec<String> {
        vec!["arbitrary-egress".to_owned(), "mutate-external".to_owned()]
    }

    #[test]
    fn grant_canonicals_are_frozen() {
        let caps = caps();
        let coverage = GrantCoverage {
            destination: DESTINATION,
            slot_schema_hash: "sha256:abc",
            covered_capabilities: &caps,
        };
        frozen(
            "grant_canonical",
            &grant_canonical(
                "persona-1",
                "routine-1",
                "paid_fetch",
                &coverage,
                "enr-1",
                CREATED_AT_MS,
            ),
            GRANT_CANONICAL,
        );
        frozen(
            "grant_canonical_persona",
            &grant_canonical_persona(
                "persona-1",
                "routine-1",
                "paid_fetch",
                &coverage,
                "enr-1",
                CREATED_AT_MS,
            ),
            GRANT_PERSONA_CANONICAL,
        );
    }

    #[test]
    fn revocation_canonicals_are_frozen() {
        frozen(
            "revocation_canonical",
            &revocation_canonical(GRANT_REF, REVOKED_AT_MS),
            REVOCATION_CANONICAL,
        );
        frozen(
            "revocation_canonical_persona",
            &revocation_canonical_persona(GRANT_REF, REVOKED_AT_MS),
            REVOCATION_PERSONA_CANONICAL,
        );
    }

    #[test]
    fn suspension_canonical_and_payload_are_frozen() {
        frozen(
            "suspension_canonical",
            &suspension_canonical(GRANT_REF, REASON, SUSPENDED_AT_MS),
            SUSPENSION_CANONICAL,
        );
        let (full, sig, _) =
            suspension_payload(GRANT_REF, REASON, SUSPENDED_AT_MS, &Signer::from_seed(99));
        frozen("suspension_payload", &full, SUSPENSION_PAYLOAD);
        assert_eq!(crate::hex::lower(&sig), SUSPENSION_SIG);
    }

    const GRANT_CANONICAL: &str = r#"{"kind":"grant.routine.v1","principal":"persona-1","routine":"routine-1","tool":"paid_fetch","destination":"{\"channel\":\"C1\",\"workspace\":\"T1\"}","slot_schema_hash":"sha256:abc","covered_capabilities":["arbitrary-egress","mutate-external"],"enrollment_id":"enr-1","created_at_ms":1700000000000}"#;
    const GRANT_PERSONA_CANONICAL: &str = r#"{"kind":"grant.routine.persona.v1","principal":"persona-1","routine":"routine-1","tool":"paid_fetch","destination":"{\"channel\":\"C1\",\"workspace\":\"T1\"}","slot_schema_hash":"sha256:abc","covered_capabilities":["arbitrary-egress","mutate-external"],"enrollment_id":"enr-1","created_at_ms":1700000000000}"#;
    const REVOCATION_CANONICAL: &str =
        r#"{"kind":"grant.revocation.v1","grant_ref":"cafe0123","revoked_at_ms":1700000100000}"#;
    const REVOCATION_PERSONA_CANONICAL: &str = r#"{"kind":"grant.revocation.persona.v1","grant_ref":"cafe0123","revoked_at_ms":1700000100000}"#;
    const SUSPENSION_CANONICAL: &str = r#"{"kind":"grant.suspension.v1","grant_ref":"cafe0123","reason":"policy change","suspended_at_ms":1700000200000}"#;
    const SUSPENSION_PAYLOAD: &str = r#"{"kind":"grant.suspension.v1","grant_ref":"cafe0123","reason":"policy change","suspended_at_ms":1700000200000,"signed_by":"35ccaf567ce385fe73a3d0ef44c04c8e4f13cf02ec853ac430a8bfd40cefe008","signature_hex":"dd7c046496ba66d2fc531bbbdbdc926a3f400a45a399a2c7668a2a59253d067eecfd6447de4b2842d21331db5aa8fc6154776094cc694399b507c0684459ea01"}"#;
    const SUSPENSION_SIG: &str = "dd7c046496ba66d2fc531bbbdbdc926a3f400a45a399a2c7668a2a59253d067eecfd6447de4b2842d21331db5aa8fc6154776094cc694399b507c0684459ea01";
}