tenuo 0.1.0-beta.18

Agent Capability Flow Control - Rust core library
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
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
//! Approval types for human-in-the-loop and multi-sig workflows.
//!
//! Tenuo treats Identity Providers as "Notaries" - they map enterprise
//! identities (AWS IAM ARNs, Okta users, YubiKey certificates) to Ed25519
//! public keys. Tenuo only cares about the cryptographic signature.
//!
//! ## Trust Hierarchy
//!
//! The Control Plane is the root of trust. It certifies orchestrators, which
//! in turn certify their child agents. Notaries are scoped to deployments.
//!
//! ```text
//! Control Plane (Root of Trust)
//!//!     ├── Certifies Orchestrator A (deployment)
//!     │       │
//!     │       ├── Bound Notary (scoped to this deployment)
//!     │       │       └── Maps enterprise identities → keys
//!     │       │
//!     │       ├── Worker Agent 1 (delegated warrant from Orchestrator A)
//!     │       └── Worker Agent 2 (delegated warrant from Orchestrator A)
//!//!     └── Certifies Orchestrator B (different deployment)
//!             └── ...
//! ```
//!
//! **Verification flow:**
//! 1. Control Plane → Orchestrator: Root warrant with deployment binding
//! 2. Orchestrator → Worker: Attenuated warrant with holder binding
//! 3. Chain verification proves: Control Plane → Orchestrator → Worker
//!
//! ## Key Generation Principle
//!
//! **Every agent generates its own keys locally.** This applies to:
//! - Orchestrators registering with the Control Plane
//! - Workers registering with their orchestrators
//! - Notaries bound to specific deployments
//!
//! Only the public key is ever shared. The private key never leaves the agent.
//!
//! ```text
//! Root Agent → Control Plane:
//! ┌──────────────────┐                    ┌──────────────────┐
//! │   ROOT AGENT     │   Send pubkey      │  CONTROL PLANE   │
//! │  [PrivateKey]    │  ───────────────►  │  Register + Issue│
//! │  (NEVER LEAVES)  │  ◄─── Warrant ───  │     warrant      │
//! └──────────────────┘                    └──────────────────┘
//!
//! Sub-Agent → Orchestrator (same principle):
//! ┌──────────────────┐                    ┌──────────────────┐
//! │   SUB-AGENT      │   Send pubkey      │  ORCHESTRATOR    │
//! │  [PrivateKey]    │  ───────────────►  │  Attenuate with  │
//! │  (NEVER LEAVES)  │  ◄─── Warrant ───  │  holder=pubkey   │
//! └──────────────────┘                    └──────────────────┘
//! ```
//!
//! ## Philosophy
//!
//! ```text
//! ┌─────────────────────────────────────────────────────────────────┐
//! │  IDENTITY PROVIDER (Notary)          TENUO CORE (The Math)     │
//! │  ─────────────────────────           ──────────────────────    │
//! │                                                                 │
//! │  "arn:aws:iam::123:user/admin"  →    PublicKey [32 bytes]      │
//! │  "okta:user:alice@corp.com"     →    PublicKey [32 bytes]      │
//! │  "yubikey:serial:12345678"      →    PublicKey [32 bytes]      │
//! │                                                                 │
//! │  Provider handles:                   Tenuo verifies:           │
//! │  • Identity verification             • Signature math          │
//! │  • Key derivation/storage            • Multi-sig counting      │
//! │  • Key rotation                      • Offline verification    │
//! └─────────────────────────────────────────────────────────────────┘
//! ```
//!
//! ## Notary Registry
//!
//! The `NotaryRegistry` manages the lifecycle of identity-to-key bindings:
//!
//! ```rust,ignore
//! let mut registry = NotaryRegistry::new();
//!
//! // Register an AWS IAM user's key
//! registry.register_key(KeyBinding {
//!     external_id: "arn:aws:iam::123:user/admin".into(),
//!     provider: "aws-iam".into(),
//!     public_key: admin_keypair.public_key(),
//!     registered_by: "bootstrap".into(),
//!     // ...
//! })?;
//!
//! // All operations emit audit events
//! for event in registry.drain_events() {
//!     audit_log.record(event);
//! }
//! ```
//!
//! ## Authorization Model
//!
//! Different operations require different authorization:
//!
//! | Operation | Authorization |
//! |-----------|---------------|
//! | `register_key` | PoP (new key signs) + Notary approval |
//! | `rotate_key` | Self-rotation (old key signs) |
//! | `revoke_key` | Notary signs (for compromised keys) |
//!
//! ## Stateless Design & Replay Protection
//!
//! Tenuo is designed for **stateless verification** - a warrant and signature
//! can be verified anywhere, offline, without database lookups. This is a core
//! design principle that enables edge deployment and air-gapped environments.
//!
//! Approvals include a 128-bit random **nonce** for cryptographic uniqueness,
//! but Tenuo does NOT track used nonces server-side. This is intentional:
//!
//! ```text
//! ┌─────────────────────────────────────────────────────────────────────┐
//! │  REPLAY PROTECTION LAYERS                                          │
//! ├─────────────────────────────────────────────────────────────────────┤
//! │  1. Domain Separation    "tenuo-approval-v1" context prefix        │
//! │  2. Nonce                128-bit random, makes each approval unique│
//! │  3. TTL                  Short expiration window (default 5 min)   │
//! │  4. Request Binding      H(warrant_id || tool || args || holder)   │
//! │  5. Holder Binding       Approval bound to specific agent's key    │
//! │  6. PoP Required         Attacker also needs holder's private key  │
//! └─────────────────────────────────────────────────────────────────────┘
//! ```
//!
//! **Why no server-side nonce tracking?**
//!
//! For replay to succeed, an attacker needs BOTH:
//! - The intercepted approval
//! - The holder's private key (to sign the Proof-of-Possession)
//!
//! If they have the holder's key, they don't need the approval at all.
//! The attack window is extremely narrow (requires tricking the legitimate
//! holder into signing a PoP for a replayed approval within TTL).
//!
//! **Application-layer opt-in:**
//!
//! Applications requiring stricter guarantees can implement nonce tracking
//! at their layer. The nonce field enables this without forcing statefulness
//! on all deployments.
//!
//! ## Implementation Status
//!
//! - [x] Approval struct (data model with nonce + domain separation)
//! - [x] NotaryRegistry (key lifecycle management)
//! - [x] RegistrationProof (PoP for registration)
//! - [x] Notary struct (registry administrator)
//! - [x] KeyBinding (identity → key mapping)
//! - [x] AuditEvent (key lifecycle auditing)
//! - [x] Multi-sig verification in Authorizer
//! - [ ] Python SDK: ApprovalProvider ABC
//! - [ ] Provider implementations (AWS IAM, Okta, YubiKey)

use crate::crypto::{PublicKey, Signature};
use crate::error::{Error, Result};
use base64::Engine;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};

/// A cryptographically signed approval from a human or external system.
///
/// The approval is bound to a specific request (via `request_hash`) and
/// signed by an approver's keypair. The approver's identity is tracked
/// via `external_id` for audit purposes.
///
/// Each approval includes a random nonce to ensure uniqueness and prevent
/// replay attacks even for identical requests within the TTL window.
/// Inner approval payload (what gets signed).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ApprovalPayload {
    /// Payload version (currently 1)
    pub version: u8,

    /// Hash of what was approved: H(warrant_id || tool || sorted(args) || holder)
    pub request_hash: [u8; 32],

    /// Random nonce for replay protection (128 bits)
    pub nonce: [u8; 16],

    /// External identity reference (e.g., "arn:aws:iam::123:user/admin")
    pub external_id: String,

    /// When approved (Unix seconds)
    pub approved_at: u64,

    /// When this approval expires (Unix seconds)
    pub expires_at: u64,

    /// Optional: application-specific signed metadata
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub extensions: Option<std::collections::HashMap<String, Vec<u8>>>,
}

/// Outer envelope containing payload and signature.
///
/// Uses the envelope pattern for "verify before deserialize" security:
/// 1. Extract approver_key from envelope
/// 2. Verify signature over raw payload bytes
/// 3. Only then deserialize the payload
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SignedApproval {
    /// Envelope version (currently 1)
    pub approval_version: u8,

    /// Raw CBOR bytes of ApprovalPayload (what gets signed)
    #[serde(with = "serde_bytes")]
    pub payload: Vec<u8>,

    /// The approver's public key (extracted for convenience; not signed)
    pub approver_key: PublicKey,

    /// Signature over domain-separated preimage:
    /// b"tenuo-approval-v1" || approval_version || payload_bytes
    pub signature: Signature,
}

/// Metadata about an approval (not part of the signed payload).
///
/// This information is stored alongside the SignedApproval but is not
/// cryptographically protected. Used for audit, display, and routing.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ApprovalMetadata {
    /// Provider name (e.g., "okta", "aws-iam", "manual")
    pub provider: String,

    /// Human-readable reason/justification
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reason: Option<String>,
}

impl SignedApproval {
    /// Create a new signed approval.
    ///
    /// # Arguments
    ///
    /// * `payload` - The approval payload to sign
    /// * `keypair` - The approver's signing key
    ///
    /// # Returns
    ///
    /// A SignedApproval with the payload and signature
    pub fn create(payload: ApprovalPayload, keypair: &crate::crypto::SigningKey) -> Self {
        // Serialize payload to CBOR
        let mut payload_bytes = Vec::new();
        ciborium::into_writer(&payload, &mut payload_bytes)
            .expect("Failed to serialize approval payload");

        // Build domain-separated preimage
        let preimage = Self::build_preimage(1, &payload_bytes);

        // Sign
        let signature = keypair.sign(&preimage);

        Self {
            approval_version: 1,
            payload: payload_bytes,
            approver_key: keypair.public_key(),
            signature,
        }
    }

    /// Verify the approval signature and deserialize the payload.
    ///
    /// This follows the "verify before deserialize" pattern:
    /// 1. Check envelope version
    /// 2. Verify signature over raw payload bytes
    /// 3. Deserialize payload (now safe)
    /// 4. Check payload version
    /// 5. Check expiration
    ///
    /// # Returns
    ///
    /// The verified and deserialized ApprovalPayload
    pub fn verify(&self) -> Result<ApprovalPayload> {
        // 1. Check envelope version
        if self.approval_version != 1 {
            return Err(Error::UnsupportedVersion(self.approval_version));
        }

        // 2. Verify signature over raw payload bytes (before deserializing)
        let preimage = Self::build_preimage(self.approval_version, &self.payload);
        self.approver_key.verify(&preimage, &self.signature)?;

        // 3. Now safe to deserialize (signature is valid)
        let payload: ApprovalPayload = ciborium::from_reader(&self.payload[..])
            .map_err(|e| Error::InvalidApproval(format!("Failed to deserialize payload: {}", e)))?;

        // 4. Check payload version
        if payload.version != 1 {
            return Err(Error::UnsupportedVersion(payload.version));
        }

        // 5. Temporal Sanity Checks
        let now = Utc::now().timestamp() as u64;

        // Check A: Approved in future (Clock Skew)
        // Prevent "time travel" attacks where an attacker creates an approval valid in the future
        // to bypass current valid-time checks or replay protections.
        use crate::warrant::CLOCK_SKEW_TOLERANCE_SECS;
        if payload.approved_at > now.saturating_add(CLOCK_SKEW_TOLERANCE_SECS) {
            return Err(Error::InvalidApproval(format!(
                "approval timestamp is in the future (skew > {}s)",
                CLOCK_SKEW_TOLERANCE_SECS
            )));
        }

        // Check B: Expiration sanity
        if payload.expires_at <= payload.approved_at {
            return Err(Error::InvalidApproval(
                "approval expires_at must be strictly greater than approved_at".to_string(),
            ));
        }

        // Note: Actual expiration checking (is now > expires_at) is done by the caller
        // (e.g., authorizer) because an expired approval is cryptographically valid
        // but semantically stale.
        // verify() checks inherent structure and cryptographic integrity.

        Ok(payload)
    }

    /// CBOR-serialize this envelope as standard base64.
    ///
    /// Control planes and audit pipelines can decode with [`ciborium`] and call
    /// [`SignedApproval::verify`] to confirm the approver signature independently
    /// of the authorizer.
    pub fn to_cbor_b64(&self) -> Result<String> {
        let mut buf = Vec::new();
        ciborium::into_writer(self, &mut buf).map_err(|e| {
            Error::InvalidApproval(format!("SignedApproval CBOR encode failed: {e}"))
        })?;
        Ok(base64::engine::general_purpose::STANDARD.encode(&buf))
    }

    /// Check if this approval matches a given request.
    ///
    /// Note: This verifies the signature first, so it's safe to use.
    pub fn matches_request(&self, request_hash: &[u8; 32]) -> Result<bool> {
        let payload = self.verify()?;
        Ok(&payload.request_hash == request_hash)
    }

    /// Build the domain-separated signing preimage.
    ///
    /// Format: b"tenuo-approval-v1" || approval_version || payload_bytes
    fn build_preimage(approval_version: u8, payload_bytes: &[u8]) -> Vec<u8> {
        use crate::domain::APPROVAL_CONTEXT;

        let mut preimage = Vec::with_capacity(APPROVAL_CONTEXT.len() + 1 + payload_bytes.len());
        preimage.extend_from_slice(APPROVAL_CONTEXT);
        preimage.push(approval_version);
        preimage.extend_from_slice(payload_bytes);
        preimage
    }
}

impl ApprovalPayload {
    /// Create a new approval payload.
    pub fn new(
        request_hash: [u8; 32],
        nonce: [u8; 16],
        external_id: String,
        approved_at: DateTime<Utc>,
        expires_at: DateTime<Utc>,
    ) -> Self {
        Self {
            version: 1,
            request_hash,
            nonce,
            external_id,
            approved_at: approved_at.timestamp() as u64,
            expires_at: expires_at.timestamp() as u64,
            extensions: None,
        }
    }

    /// Check if this approval matches a given request hash.
    pub fn matches_request(&self, request_hash: &[u8; 32]) -> bool {
        &self.request_hash == request_hash
    }

    /// Check if the approval is expired.
    pub fn is_expired(&self) -> bool {
        let now = Utc::now().timestamp() as u64;
        now > self.expires_at
    }
}

/// CBOR-encode tool arguments in the same canonical form used by [`compute_request_hash`].
pub fn canonical_tool_args_cbor(
    args: &std::collections::HashMap<String, crate::constraints::ConstraintValue>,
) -> Option<Vec<u8>> {
    use std::collections::BTreeMap;

    let sorted: BTreeMap<_, _> = args.iter().collect();
    let mut cbor_buf = Vec::new();
    if ciborium::into_writer(&sorted, &mut cbor_buf).is_ok() {
        Some(cbor_buf)
    } else {
        None
    }
}

/// Compute a request hash for approval binding.
///
/// This ensures an approval is bound to a specific (warrant, tool, args, holder) tuple.
/// Including the holder prevents approval theft: even if an attacker intercepts an
/// approval, they can't use it because the hash won't match their holder key.
pub fn compute_request_hash(
    warrant_id: &str,
    tool: &str,
    args: &std::collections::HashMap<String, crate::constraints::ConstraintValue>,
    authorized_holder: Option<&crate::crypto::PublicKey>,
) -> [u8; 32] {
    use sha2::{Digest, Sha256};

    let mut hasher = Sha256::new();
    hasher.update(warrant_id.as_bytes());
    hasher.update(b"|");
    hasher.update(tool.as_bytes());
    hasher.update(b"|");

    if let Some(buf) = canonical_tool_args_cbor(args) {
        hasher.update(&buf);
    }

    // Bind to authorized holder (prevents approval theft)
    hasher.update(b"|");
    if let Some(holder) = authorized_holder {
        hasher.update(holder.to_bytes());
    }

    hasher.finalize().into()
}

/// Build the signed preimage for an approval-context attestation (version 1).
///
/// Layout: `WARRANT_CONTEXT` || `APPROVAL_CONTEXT_ATTESTATION` || `0x01` ||
/// `u32_be(len) || warrant_id` || `u32_be(len) || tool` ||
/// `u32_be(len) || request_hash` (32) || `u32_be(len) || holder_pk` (32) ||
/// `u32_be(len) || args_cbor`.
pub fn build_approval_context_preimage(
    warrant_id: &str,
    tool: &str,
    request_hash: &[u8; 32],
    holder: &crate::crypto::PublicKey,
    args_cbor: &[u8],
) -> Vec<u8> {
    use crate::domain::{APPROVAL_CONTEXT_ATTESTATION, WARRANT_CONTEXT};

    fn push_lp(out: &mut Vec<u8>, data: &[u8]) {
        out.extend_from_slice(&(data.len() as u32).to_be_bytes());
        out.extend_from_slice(data);
    }

    let mut out = Vec::new();
    out.extend_from_slice(WARRANT_CONTEXT);
    out.extend_from_slice(APPROVAL_CONTEXT_ATTESTATION);
    out.push(1u8);
    push_lp(&mut out, warrant_id.as_bytes());
    push_lp(&mut out, tool.as_bytes());
    push_lp(&mut out, request_hash);
    push_lp(&mut out, &holder.to_bytes());
    push_lp(&mut out, args_cbor);
    out
}

/// Sign an approval-context attestation; returns `(args_cbor_b64, metadata)`.
///
/// `metadata` is suitable for JSON sidecars / audit; it is not trusted without
/// verifying `signature` over the preimage from [`build_approval_context_preimage`].
pub fn build_approval_context_attestation(
    signing_key: &crate::crypto::SigningKey,
    warrant_id: &str,
    tool: &str,
    args: &std::collections::HashMap<String, crate::constraints::ConstraintValue>,
    holder: &crate::crypto::PublicKey,
) -> Result<(String, ApprovalContextAttestationMeta)> {
    let args_cbor = canonical_tool_args_cbor(args).ok_or_else(|| {
        crate::error::Error::InvalidApproval("canonical CBOR encode of tool args failed".into())
    })?;
    let request_hash = compute_request_hash(warrant_id, tool, args, Some(holder));
    let preimage =
        build_approval_context_preimage(warrant_id, tool, &request_hash, holder, &args_cbor);
    let signature = signing_key.sign_raw(&preimage);
    let signer_pk = signing_key.public_key();

    use base64::Engine;
    let args_b64 = base64::engine::general_purpose::STANDARD.encode(&args_cbor);
    let sig_b64 = base64::engine::general_purpose::STANDARD.encode(signature.to_bytes());

    let meta = ApprovalContextAttestationMeta {
        version: 1,
        canonicalization: "cbor-canonical-v1".to_string(),
        warrant_id: warrant_id.to_string(),
        tool: tool.to_string(),
        request_hash: hex::encode(request_hash),
        holder_key_hex: hex::encode(holder.to_bytes()),
        args_canonical_cbor_b64: args_b64.clone(),
        signer_key_hex: hex::encode(signer_pk.to_bytes()),
        signature_b64: sig_b64,
    };
    Ok((args_b64, meta))
}

/// Verify an approval-context attestation from the same logical inputs as
/// [`build_approval_context_attestation`].
///
/// Recomputes canonical args CBOR, the request hash, and the signed preimage, then
/// checks `signature` with [`crate::crypto::PublicKey::verify_raw`]. Control plane
/// and other verifiers should use this (or the language bindings) instead of
/// reimplementing the preimage layout.
pub fn verify_approval_context_attestation(
    approver: &crate::crypto::PublicKey,
    warrant_id: &str,
    tool: &str,
    args: &std::collections::HashMap<String, crate::constraints::ConstraintValue>,
    holder: &crate::crypto::PublicKey,
    signature: &crate::crypto::Signature,
) -> Result<()> {
    let args_cbor = canonical_tool_args_cbor(args).ok_or_else(|| {
        crate::error::Error::InvalidApproval("canonical CBOR encode of tool args failed".into())
    })?;
    let request_hash = compute_request_hash(warrant_id, tool, args, Some(holder));
    let preimage =
        build_approval_context_preimage(warrant_id, tool, &request_hash, holder, &args_cbor);
    approver.verify_raw(&preimage, signature)
}

/// Metadata for an approval-context attestation (not independently authenticated).
#[derive(Debug, Clone)]
pub struct ApprovalContextAttestationMeta {
    pub version: u8,
    pub canonicalization: String,
    pub warrant_id: String,
    pub tool: String,
    pub request_hash: String,
    pub holder_key_hex: String,
    pub args_canonical_cbor_b64: String,
    pub signer_key_hex: String,
    pub signature_b64: String,
}

// ============================================================================
// Approval Request (emitted when an approval gate fires)
// ============================================================================

/// A request for human approval, emitted by the authorizer when an approval gate fires
/// and no valid approval is present.
///
/// This is a **convenience structure**, not a signed artifact. It provides the
/// approval engine with everything needed to present the decision to a human
/// and construct a valid `SignedApproval` in response.
///
/// The `request_hash` is precomputed so the engine can verify it independently
/// (defense against confused-deputy attacks).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ApprovalRequest {
    /// Unique request identifier (UUIDv7 bytes).
    #[serde(with = "serde_bytes")]
    pub request_id: [u8; 16],

    /// Warrant ID this request is for.
    pub warrant_id: String,

    /// Tool the agent is attempting to invoke.
    pub tool: String,

    /// Arguments the agent is passing (CBOR-compatible values).
    pub args: std::collections::BTreeMap<String, crate::constraints::ConstraintValue>,

    /// Precomputed request_hash the approval must match.
    /// `H(warrant_id || tool || sorted(args) || holder)`
    pub request_hash: [u8; 32],

    /// Keys authorized to approve (from `warrant.required_approvers`).
    pub required_approvers: Vec<PublicKey>,

    /// Approval threshold (from `warrant.min_approvals` or `len(required_approvers)`).
    pub min_approvals: u32,

    /// Warrant expiration (Unix seconds). The approval SHOULD NOT outlive the warrant.
    pub warrant_expires_at: u64,

    /// When this request was created (Unix seconds).
    pub created_at: u64,
}

impl ApprovalRequest {
    /// Create a new approval request from authorization context.
    pub fn new(
        warrant_id: &str,
        tool: &str,
        args: &std::collections::HashMap<String, crate::constraints::ConstraintValue>,
        request_hash: [u8; 32],
        required_approvers: Vec<PublicKey>,
        min_approvals: u32,
        warrant_expires_at: u64,
    ) -> Self {
        let request_id = uuid::Uuid::now_v7();
        let now = Utc::now().timestamp() as u64;

        Self {
            request_id: *request_id.as_bytes(),
            warrant_id: warrant_id.to_string(),
            tool: tool.to_string(),
            args: args.iter().map(|(k, v)| (k.clone(), v.clone())).collect(),
            request_hash,
            required_approvers,
            min_approvals,
            warrant_expires_at,
            created_at: now,
        }
    }
}

// ============================================================================
// Notary Proofs (PoP for Registration and Rotation)
// ============================================================================

use crate::domain::{REGISTRATION_PROOF_CONTEXT, ROTATION_PROOF_CONTEXT};

/// Proof of Possession for key registration.
///
/// When registering a new key, the holder must prove they control the private
/// key by signing a payload containing their identity information.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RegistrationProof {
    /// Signature by the NEW key over the registration payload.
    pub signature: Signature,
    /// Timestamp for replay protection (Unix timestamp).
    pub timestamp: i64,
}

impl RegistrationProof {
    /// Create a registration proof.
    ///
    /// The signed payload is: context || provider || external_id || public_key || timestamp
    pub fn create(
        keypair: &crate::crypto::SigningKey,
        provider: &str,
        external_id: &str,
        timestamp: i64,
    ) -> Self {
        let payload = Self::build_payload(provider, external_id, &keypair.public_key(), timestamp);
        let signature = keypair.sign(&payload);
        Self {
            signature,
            timestamp,
        }
    }

    /// Verify the registration proof against a public key.
    pub fn verify(&self, public_key: &PublicKey, provider: &str, external_id: &str) -> Result<()> {
        let payload = Self::build_payload(provider, external_id, public_key, self.timestamp);
        public_key
            .verify(&payload, &self.signature)
            .map_err(|e| Error::InvalidApproval(format!("Invalid registration proof: {}", e)))
    }

    fn build_payload(
        provider: &str,
        external_id: &str,
        public_key: &PublicKey,
        timestamp: i64,
    ) -> Vec<u8> {
        let mut payload = Vec::new();
        payload.extend_from_slice(REGISTRATION_PROOF_CONTEXT);
        payload.extend_from_slice(b"|");
        payload.extend_from_slice(provider.as_bytes());
        payload.extend_from_slice(b"|");
        payload.extend_from_slice(external_id.as_bytes());
        payload.extend_from_slice(b"|");
        payload.extend_from_slice(&public_key.to_bytes());
        payload.extend_from_slice(b"|");
        payload.extend_from_slice(&timestamp.to_le_bytes());
        payload
    }
}

/// Proof of authorization for key rotation.
///
/// The OLD key holder signs a payload authorizing rotation to a new key.
/// This proves the current key holder approves the rotation.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RotationProof {
    /// Signature by the OLD key over the rotation payload.
    pub signature: Signature,
    /// Timestamp for replay protection (Unix timestamp).
    pub timestamp: i64,
}

impl RotationProof {
    /// Create a rotation proof.
    ///
    /// The signed payload is: context || provider || external_id || new_key || timestamp
    pub fn create(
        old_keypair: &crate::crypto::SigningKey,
        provider: &str,
        external_id: &str,
        new_key: &PublicKey,
        timestamp: i64,
    ) -> Self {
        let payload = Self::build_payload(provider, external_id, new_key, timestamp);
        let signature = old_keypair.sign(&payload);
        Self {
            signature,
            timestamp,
        }
    }

    /// Verify the rotation proof against the old public key.
    pub fn verify(
        &self,
        old_key: &PublicKey,
        provider: &str,
        external_id: &str,
        new_key: &PublicKey,
    ) -> Result<()> {
        let payload = Self::build_payload(provider, external_id, new_key, self.timestamp);
        old_key
            .verify(&payload, &self.signature)
            .map_err(|e| Error::InvalidApproval(format!("Invalid rotation proof: {}", e)))
    }

    fn build_payload(
        provider: &str,
        external_id: &str,
        new_key: &PublicKey,
        timestamp: i64,
    ) -> Vec<u8> {
        let mut payload = Vec::new();
        payload.extend_from_slice(ROTATION_PROOF_CONTEXT);
        payload.extend_from_slice(b"|");
        payload.extend_from_slice(provider.as_bytes());
        payload.extend_from_slice(b"|");
        payload.extend_from_slice(external_id.as_bytes());
        payload.extend_from_slice(b"|");
        payload.extend_from_slice(&new_key.to_bytes());
        payload.extend_from_slice(b"|");
        payload.extend_from_slice(&timestamp.to_le_bytes());
        payload
    }
}

// ============================================================================
// Notary (Registry Administrator)
// ============================================================================

/// A Notary is an entity with administrative authority over the registry.
///
/// Notaries are required for operations that cannot be self-authorized:
/// - **Key registration**: Approving new identity-to-key bindings
/// - **Key revocation**: Deactivating compromised or expired keys
///
/// Unlike rotation (which is self-authorized by the old key), revocation requires
/// a trusted third party because the key holder's key may be compromised.
///
/// ## Deployment Binding
///
/// Notaries can be scoped to a specific deployment. The Control Plane verifies
/// that a notary is authorized for the deployment before accepting registrations.
///
/// ## Properties
///
/// - **Type safety**: Can't accidentally pass arbitrary strings
/// - **Key association**: Each notary is tied to a cryptographic identity
/// - **Deployment scoping**: Notary can be bound to a specific orchestrator
/// - **Signature verification**: Operations require notary signatures
///
/// ## Example
///
/// ```rust,ignore
/// let admin_keypair = SigningKey::generate();
/// let admin = Notary::new("admin-1", admin_keypair.public_key())
///     .with_deployment("orchestrator-prod-us-east-1");
///
/// // Register a key (notary approves)
/// registry.register_key(binding, &proof, &admin)?;
///
/// // Revoke a key (notary signs revocation)
/// let sig = admin_keypair.sign(&revocation_message);
/// registry.revoke_key(provider, external_id, reason, &sig, &admin)?;
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Notary {
    /// Unique identifier for this notary
    pub id: String,
    /// Human-readable name
    pub name: Option<String>,
    /// The notary's public key
    pub public_key: PublicKey,
    /// Deployment this notary is bound to (for scoping)
    /// If None, the notary is global (not recommended for production)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub deployment_id: Option<String>,
}

impl Notary {
    /// Create a new notary with an ID and public key.
    pub fn new(id: impl Into<String>, public_key: PublicKey) -> Self {
        Self {
            id: id.into(),
            name: None,
            public_key,
            deployment_id: None,
        }
    }

    /// Bind this notary to a specific deployment.
    ///
    /// In production, notaries should be scoped to prevent cross-deployment
    /// authorization attacks.
    pub fn with_deployment(mut self, deployment_id: impl Into<String>) -> Self {
        self.deployment_id = Some(deployment_id.into());
        self
    }

    /// Create a notary with a display name.
    pub fn with_name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }

    /// Get the notary's ID.
    pub fn id(&self) -> &str {
        &self.id
    }

    /// Get the deployment this notary is bound to.
    pub fn deployment_id(&self) -> Option<&str> {
        self.deployment_id.as_deref()
    }

    /// Get the display name, falling back to ID.
    pub fn display_name(&self) -> &str {
        self.name.as_deref().unwrap_or(&self.id)
    }
}

// ============================================================================
// Key Binding (Identity → Key Mapping)
// ============================================================================

/// A binding between an external identity and a Tenuo public key.
///
/// This is the core data structure for the Notary Registry, mapping
/// enterprise identities (IAM ARNs, Okta users, etc.) to Ed25519 keys.
///
/// ## Deployment Scoping
///
/// Bindings can be scoped to a specific deployment using `deployment_id`.
/// This ensures that an identity registered for one orchestrator cannot
/// be used to authorize actions in a different deployment.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct KeyBinding {
    /// Unique ID for this binding (e.g., `kb_<uuid>`)
    pub id: String,

    /// External identity (e.g., "arn:aws:iam::123:user/admin")
    pub external_id: String,

    /// Provider name (e.g., "aws-iam", "okta", "yubikey")
    pub provider: String,

    /// The bound public key
    pub public_key: PublicKey,

    /// Deployment this binding is scoped to (optional)
    ///
    /// If set, this binding only authorizes actions within the specified
    /// deployment. Cross-deployment use is rejected.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub deployment_id: Option<String>,

    /// Human-readable display name
    #[serde(skip_serializing_if = "Option::is_none")]
    pub display_name: Option<String>,

    /// Who registered this binding
    pub registered_by: String,

    /// When this binding was created
    pub registered_at: DateTime<Utc>,

    /// When this binding expires (None = never)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub expires_at: Option<DateTime<Utc>>,

    /// Whether this binding is currently active
    pub active: bool,

    /// Optional metadata (tags, permissions, etc.)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<std::collections::BTreeMap<String, String>>,
}

impl KeyBinding {
    /// Check if this binding is valid (active and not expired)
    pub fn is_valid(&self) -> bool {
        if !self.active {
            return false;
        }
        if let Some(expires) = self.expires_at {
            if Utc::now() > expires {
                return false;
            }
        }
        true
    }
}

// ============================================================================
// Audit Events
// ============================================================================

/// Types of key lifecycle events.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum AuditEventType {
    /// A new key binding was registered
    KeyRegistered,
    /// A key binding was rotated (new key, same identity)
    KeyRotated,
    /// A key binding was revoked/deactivated
    KeyRevoked,
    /// A key binding expired
    KeyExpired,
    /// An approval was granted using this key
    ApprovalGranted,
    /// An approval verification succeeded
    ApprovalVerified,
    /// An approval verification failed
    ApprovalFailed,
    /// Provider was registered
    ProviderRegistered,
    /// Provider was removed
    ProviderRemoved,

    // -- Enrollment Events --
    /// An orchestrator successfully enrolled
    EnrollmentSuccess,
    /// An enrollment attempt failed
    EnrollmentFailure,

    // -- Warrant Events --
    /// A warrant was issued
    WarrantIssued,
    /// A warrant was revoked
    WarrantRevoked,

    // -- Authorization Events --
    /// An action was authorized
    AuthorizationSuccess,
    /// An action was denied
    AuthorizationFailure,

    // -- Verification Events --
    /// Chain verification failed (invalid signature, expiration, untrusted root, etc.)
    VerificationFailed,
}

/// An audit event for key lifecycle operations.
///
/// These events should be persisted to an audit log for compliance
/// and forensic analysis.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuditEvent {
    /// Unique event ID
    pub id: String,

    /// Event type
    pub event_type: AuditEventType,

    /// When this event occurred
    pub timestamp: DateTime<Utc>,

    /// Which provider this relates to
    pub provider: String,

    /// External identity involved (if applicable)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub external_id: Option<String>,

    /// Public key involved (hex-encoded for readability)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub public_key_hex: Option<String>,

    /// Who/what triggered this event
    pub actor: String,

    /// Additional context
    #[serde(skip_serializing_if = "Option::is_none")]
    pub details: Option<String>,

    /// Related IDs (warrant_id, approval_id, etc.)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub related_ids: Option<Vec<String>>,
}

impl AuditEvent {
    /// Create a new audit event
    pub fn new(
        event_type: AuditEventType,
        provider: impl Into<String>,
        actor: impl Into<String>,
    ) -> Self {
        Self {
            id: format!("evt_{}", uuid::Uuid::now_v7().simple()),
            event_type,
            timestamp: Utc::now(),
            provider: provider.into(),
            external_id: None,
            public_key_hex: None,
            actor: actor.into(),
            details: None,
            related_ids: None,
        }
    }

    /// Add external identity context
    pub fn with_identity(mut self, external_id: impl Into<String>) -> Self {
        self.external_id = Some(external_id.into());
        self
    }

    /// Add public key context
    pub fn with_key(mut self, key: &PublicKey) -> Self {
        self.public_key_hex = Some(hex::encode(key.to_bytes()));
        self
    }

    /// Add details
    pub fn with_details(mut self, details: impl Into<String>) -> Self {
        self.details = Some(details.into());
        self
    }

    /// Add related IDs
    pub fn with_related(mut self, ids: Vec<String>) -> Self {
        self.related_ids = Some(ids);
        self
    }
}

// ============================================================================
// Warrant Tracking
// ============================================================================

/// Trait for components that track warrant issuance (e.g., NotaryRegistry).
///
/// This allows the Control Plane to enforce tracking when issuing warrants,
/// ensuring that cascading revocation works correctly.
pub trait WarrantTracker {
    /// Track a warrant for a specific key (issuer or holder).
    fn track_warrant(&mut self, key: &PublicKey, warrant_id: &str);
}

// ============================================================================
// Notary Registry
// ============================================================================

/// Registry for managing Notaries (identity providers and their key bindings).
///
/// The registry handles:
/// - Provider registration
/// - Key binding lifecycle (register, rotate, revoke)
/// - Audit event generation
///
/// ## Example
///
/// ```rust,ignore
/// let mut registry = NotaryRegistry::new();
///
/// // Register a provider
/// registry.register_provider("aws-iam", "AWS IAM Identity Provider")?;
///
/// // Register a key binding
/// let binding = KeyBinding {
///     id: "kb_123".into(),
///     external_id: "arn:aws:iam::123:user/admin".into(),
///     provider: "aws-iam".into(),
///     public_key: admin_key,
///     // ...
/// };
/// registry.register_key(binding, "system")?;
///
/// // Resolve identity to key
/// let key = registry.resolve("aws-iam", "arn:aws:iam::123:user/admin")?;
///
/// // Drain audit events for logging
/// for event in registry.drain_events() {
///     log::info!("Audit: {:?}", event);
/// }
/// ```
#[derive(Debug, Default)]
pub struct NotaryRegistry {
    /// Registered providers: name → description
    providers: std::collections::HashMap<String, String>,

    /// Key bindings: (provider, external_id) → KeyBinding
    bindings: std::collections::HashMap<(String, String), KeyBinding>,

    /// Warrant index: PublicKey → Set of warrant IDs
    /// Used for cascading revocation when a key is compromised.
    warrant_index: std::collections::HashMap<[u8; 32], std::collections::HashSet<String>>,

    /// Pending audit events (drain these periodically)
    pending_events: Vec<AuditEvent>,
}

impl NotaryRegistry {
    /// Create a new empty registry.
    pub fn new() -> Self {
        Self::default()
    }

    /// Register a new provider.
    pub fn register_provider(
        &mut self,
        name: impl Into<String>,
        description: impl Into<String>,
        actor: impl Into<String>,
    ) {
        let name = name.into();
        let actor = actor.into();

        self.providers.insert(name.clone(), description.into());

        self.pending_events.push(
            AuditEvent::new(AuditEventType::ProviderRegistered, &name, actor)
                .with_details(format!("Provider '{}' registered", name)),
        );
    }

    /// Remove a provider (also removes all its bindings).
    pub fn remove_provider(&mut self, name: &str, actor: impl Into<String>) {
        let actor = actor.into();

        // Remove all bindings for this provider
        let to_remove: Vec<_> = self
            .bindings
            .keys()
            .filter(|(p, _)| p == name)
            .cloned()
            .collect();

        for key in to_remove {
            self.bindings.remove(&key);
        }

        self.providers.remove(name);

        self.pending_events.push(
            AuditEvent::new(AuditEventType::ProviderRemoved, name, actor)
                .with_details(format!("Provider '{}' removed", name)),
        );
    }

    /// Check if a provider is registered.
    pub fn has_provider(&self, name: &str) -> bool {
        self.providers.contains_key(name)
    }

    /// List all registered providers.
    pub fn list_providers(&self) -> Vec<(&str, &str)> {
        self.providers
            .iter()
            .map(|(k, v)| (k.as_str(), v.as_str()))
            .collect()
    }

    /// Register a new key binding with Proof of Possession.
    ///
    /// # Security
    ///
    /// This operation requires two forms of authorization:
    /// 1. **Proof of Possession (PoP)**: The new key holder must sign a registration
    ///    proof to prove they control the private key being registered.
    /// 2. **Notary authorization**: A trusted notary must approve the registration.
    ///
    /// # Arguments
    ///
    /// * `binding` - The key binding to register
    /// * `proof` - RegistrationProof signed by the private key being registered
    /// * `notary` - The notary authorizing this registration
    pub fn register_key(
        &mut self,
        binding: KeyBinding,
        proof: &RegistrationProof,
        notary: &Notary,
    ) -> Result<()> {
        if !self.has_provider(&binding.provider) {
            return Err(Error::UnknownProvider(binding.provider.clone()));
        }

        // Verify Deployment Scoping
        // If the notary is bound to a deployment, they can ONLY register keys for that deployment.
        if let Some(notary_deployment) = &notary.deployment_id {
            match &binding.deployment_id {
                Some(binding_deployment) if binding_deployment != notary_deployment => {
                    return Err(Error::Unauthorized(format!(
                        "Notary scoped to '{}' cannot register key for '{}'",
                        notary_deployment, binding_deployment
                    )));
                }
                None => {
                    return Err(Error::Unauthorized(format!(
                        "Notary scoped to '{}' cannot register global key",
                        notary_deployment
                    )));
                }
                _ => {} // Matches
            }
        }

        // Verify Proof of Possession
        proof.verify(&binding.public_key, &binding.provider, &binding.external_id)?;

        let key = (binding.provider.clone(), binding.external_id.clone());

        self.pending_events.push(
            AuditEvent::new(
                AuditEventType::KeyRegistered,
                &binding.provider,
                notary.id(),
            )
            .with_identity(&binding.external_id)
            .with_key(&binding.public_key)
            .with_details(format!(
                "Key registered for '{}' by {} (PoP verified)",
                binding
                    .display_name
                    .as_deref()
                    .unwrap_or(&binding.external_id),
                notary.display_name()
            )),
        );

        self.bindings.insert(key, binding);
        Ok(())
    }

    /// Rotate a key (update the public key for an existing binding).
    ///
    /// # Security
    ///
    /// This operation requires a signature from the **current (old) key** to prove
    /// the key holder authorizes the rotation. This is a self-rotation model.
    ///
    /// The signed message is: `provider || external_id || new_key_bytes`
    ///
    /// For compromised keys where self-rotation isn't possible, use `revoke_key()`
    /// followed by a new registration through the external provider's auth flow.
    ///
    /// # Arguments
    ///
    /// * `provider` - The identity provider name
    /// * `external_id` - The external identity being rotated
    /// * `new_key` - The new public key
    /// * `signature` - Signature by the OLD key over the rotation message
    /// * `actor` - Identifier for audit logging
    pub fn rotate_key(
        &mut self,
        provider: &str,
        external_id: &str,
        new_key: PublicKey,
        signature: &Signature,
        actor: impl Into<String>,
    ) -> Result<()> {
        let actor = actor.into();
        let key = (provider.to_string(), external_id.to_string());

        let binding = self
            .bindings
            .get_mut(&key)
            .ok_or_else(|| Error::UnknownProvider(format!("{}:{}", provider, external_id)))?;

        // 1. Verify authorization: Old key must sign the rotation request
        let mut message = Vec::new();
        message.extend_from_slice(provider.as_bytes());
        message.extend_from_slice(external_id.as_bytes());
        message.extend_from_slice(&new_key.to_bytes());

        binding
            .public_key
            .verify(&message, signature)
            .map_err(|_| Error::SignatureInvalid("Invalid rotation signature".into()))?;

        let old_key_hex = hex::encode(binding.public_key.to_bytes());

        // 2. Perform rotation
        binding.public_key = new_key.clone();

        self.pending_events.push(
            AuditEvent::new(AuditEventType::KeyRotated, provider, actor)
                .with_identity(external_id)
                .with_key(&new_key)
                .with_details(format!("Key rotated from {}", &old_key_hex[..16])),
        );

        Ok(())
    }

    /// Revoke a key binding (deactivate it).
    ///
    /// Unlike rotation (which is self-authorized), revocation requires authorization
    /// from a **Notary** (registry administrator). This handles the case where the
    /// key holder's key is compromised or unavailable.
    ///
    /// # Security
    ///
    /// The notary must sign the revocation request to prove authorization.
    /// The signed message is: `provider || external_id || reason`
    ///
    /// # Arguments
    ///
    /// * `provider` - The identity provider name
    /// * `external_id` - The external identity being revoked
    /// * `reason` - Human-readable reason for revocation (for audit)
    /// * `signature` - Signature by the notary over the revocation message
    /// * `notary` - The notary authorizing this revocation
    ///
    /// # Returns
    /// A list of warrant IDs that should be added to the Signed Revocation List.
    /// These are warrants issued by or held by the revoked key.
    pub fn revoke_key(
        &mut self,
        provider: &str,
        external_id: &str,
        reason: impl Into<String>,
        signature: &Signature,
        notary: &Notary,
    ) -> Result<Vec<String>> {
        let reason = reason.into();
        let key = (provider.to_string(), external_id.to_string());

        // First, get the binding immutably to check deployment and get the public key
        let binding = self
            .bindings
            .get(&key)
            .ok_or_else(|| Error::UnknownProvider(format!("{}:{}", provider, external_id)))?;

        // Verify Deployment Scoping
        if let Some(notary_deployment) = &notary.deployment_id {
            match &binding.deployment_id {
                Some(binding_deployment) if binding_deployment != notary_deployment => {
                    return Err(Error::Unauthorized(format!(
                        "Notary scoped to '{}' cannot revoke key for '{}'",
                        notary_deployment, binding_deployment
                    )));
                }
                None => {
                    return Err(Error::Unauthorized(format!(
                        "Notary scoped to '{}' cannot revoke global key",
                        notary_deployment
                    )));
                }
                _ => {} // Deployment matches
            }
        }

        // Verify authorization: Notary must sign the revocation request
        let mut message = Vec::new();
        message.extend_from_slice(provider.as_bytes());
        message.extend_from_slice(external_id.as_bytes());
        message.extend_from_slice(reason.as_bytes());

        notary
            .public_key
            .verify(&message, signature)
            .map_err(|_| Error::SignatureInvalid("Invalid revocation signature".into()))?;

        // Get affected warrants and public key before mutable borrow
        let public_key = binding.public_key.clone();
        let affected_warrants = self.get_warrants_for_key(&public_key);

        // Now get mutable reference to deactivate
        let binding = self.bindings.get_mut(&key).unwrap();
        binding.active = false;

        self.pending_events.push(
            AuditEvent::new(AuditEventType::KeyRevoked, provider, notary.id())
                .with_identity(external_id)
                .with_key(&public_key)
                .with_details(format!(
                    "Revoked by {}: {}. Affected warrants: {}",
                    notary.display_name(),
                    reason,
                    affected_warrants.len()
                )),
        );

        Ok(affected_warrants)
    }

    /// Track a warrant issued by or held by a key.
    ///
    /// Call this when warrants are created so that cascading revocation works.
    /// The warrant should be tracked for both its issuer and holder (if any).
    ///
    /// # Example
    /// ```rust,ignore
    /// // Track warrant for both issuer and holder
    /// registry.track_warrant(warrant.issuer(), warrant.id());
    /// if let Some(holder) = warrant.authorized_holder() {
    ///     registry.track_warrant(holder, warrant.id());
    /// }
    /// ```
    pub fn track_warrant(&mut self, key: &PublicKey, warrant_id: impl Into<String>) {
        let key_bytes = key.to_bytes();
        self.warrant_index
            .entry(key_bytes)
            .or_default()
            .insert(warrant_id.into());
    }

    /// Remove a warrant from tracking (e.g., when it expires).
    pub fn untrack_warrant(&mut self, key: &PublicKey, warrant_id: &str) {
        let key_bytes = key.to_bytes();
        if let Some(warrants) = self.warrant_index.get_mut(&key_bytes) {
            warrants.remove(warrant_id);
            if warrants.is_empty() {
                self.warrant_index.remove(&key_bytes);
            }
        }
    }

    /// Get all warrant IDs associated with a key.
    ///
    /// Returns warrants where this key is either the issuer or the authorized holder.
    pub fn get_warrants_for_key(&self, key: &PublicKey) -> Vec<String> {
        let key_bytes = key.to_bytes();
        self.warrant_index
            .get(&key_bytes)
            .map(|set| set.iter().cloned().collect())
            .unwrap_or_default()
    }

    /// Resolve an external identity to a public key.
    pub fn resolve(&self, provider: &str, external_id: &str) -> Result<&PublicKey> {
        let key = (provider.to_string(), external_id.to_string());

        let binding = self
            .bindings
            .get(&key)
            .ok_or_else(|| Error::UnknownProvider(format!("{}:{}", provider, external_id)))?;

        if !binding.is_valid() {
            return Err(Error::ApprovalExpired {
                approved_at: binding.registered_at,
                expired_at: binding.expires_at.unwrap_or(Utc::now()),
            });
        }

        Ok(&binding.public_key)
    }

    /// Get a key binding by identity.
    pub fn get_binding(&self, provider: &str, external_id: &str) -> Option<&KeyBinding> {
        let key = (provider.to_string(), external_id.to_string());
        self.bindings.get(&key)
    }

    /// List all bindings for a provider.
    pub fn list_bindings(&self, provider: &str) -> Vec<&KeyBinding> {
        self.bindings
            .iter()
            .filter(|((p, _), _)| p == provider)
            .map(|(_, b)| b)
            .collect()
    }

    /// Drain pending audit events.
    ///
    /// Call this periodically to persist events to your audit log.
    pub fn drain_events(&mut self) -> Vec<AuditEvent> {
        std::mem::take(&mut self.pending_events)
    }

    /// Get pending event count (for monitoring).
    pub fn pending_event_count(&self) -> usize {
        self.pending_events.len()
    }
}

impl WarrantTracker for NotaryRegistry {
    fn track_warrant(&mut self, key: &PublicKey, warrant_id: &str) {
        self.track_warrant(key, warrant_id);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::crypto::SigningKey;
    use std::collections::HashMap;

    #[test]
    fn test_request_hash_deterministic() {
        let mut args1 = HashMap::new();
        args1.insert(
            "z".to_string(),
            crate::constraints::ConstraintValue::String("last".to_string()),
        );
        args1.insert(
            "a".to_string(),
            crate::constraints::ConstraintValue::String("first".to_string()),
        );

        let mut args2 = HashMap::new();
        args2.insert(
            "a".to_string(),
            crate::constraints::ConstraintValue::String("first".to_string()),
        );
        args2.insert(
            "z".to_string(),
            crate::constraints::ConstraintValue::String("last".to_string()),
        );

        let hash1 = compute_request_hash("wrt_123", "delete", &args1, None);
        let hash2 = compute_request_hash("wrt_123", "delete", &args2, None);

        assert_eq!(
            hash1, hash2,
            "Hash should be deterministic regardless of insertion order"
        );

        // Test that holder affects the hash
        let holder = crate::crypto::SigningKey::generate();
        let hash_with_holder =
            compute_request_hash("wrt_123", "delete", &args1, Some(&holder.public_key()));
        assert_ne!(
            hash1, hash_with_holder,
            "Hash should differ when holder is included"
        );
    }

    #[test]
    fn approval_context_attestation_round_trip() {
        let signer = SigningKey::generate();
        let holder = SigningKey::generate();
        let mut args = HashMap::new();
        args.insert(
            "path".to_string(),
            crate::constraints::ConstraintValue::String("/tmp/x".to_string()),
        );
        let (args_b64, meta) = build_approval_context_attestation(
            &signer,
            "wrt_test",
            "read_file",
            &args,
            &holder.public_key(),
        )
        .expect("attestation");

        assert_eq!(meta.warrant_id, "wrt_test");
        assert_eq!(meta.tool, "read_file");
        assert_eq!(meta.args_canonical_cbor_b64, args_b64);

        let rh = compute_request_hash("wrt_test", "read_file", &args, Some(&holder.public_key()));
        assert_eq!(meta.request_hash, hex::encode(rh));

        use base64::Engine;
        let sig_bytes = base64::engine::general_purpose::STANDARD
            .decode(meta.signature_b64.as_bytes())
            .expect("sig b64");
        let sig_arr: [u8; 64] = sig_bytes.as_slice().try_into().unwrap();
        let sig = crate::crypto::Signature::from_bytes(&sig_arr).expect("sig");
        verify_approval_context_attestation(
            &signer.public_key(),
            "wrt_test",
            "read_file",
            &args,
            &holder.public_key(),
            &sig,
        )
        .expect("verify_approval_context_attestation");
    }

    #[test]
    fn approval_context_attestation_verify_rejects_wrong_args() {
        let signer = SigningKey::generate();
        let holder = SigningKey::generate();
        let mut args = HashMap::new();
        args.insert(
            "path".to_string(),
            crate::constraints::ConstraintValue::String("/tmp/x".to_string()),
        );
        let (_args_b64, _meta) = build_approval_context_attestation(
            &signer,
            "wrt_test",
            "read_file",
            &args,
            &holder.public_key(),
        )
        .expect("attestation");

        let mut wrong_args = HashMap::new();
        wrong_args.insert(
            "path".to_string(),
            crate::constraints::ConstraintValue::String("/other".to_string()),
        );
        let args_cbor_wrong = canonical_tool_args_cbor(&wrong_args).expect("cbor");
        let rh_wrong = compute_request_hash(
            "wrt_test",
            "read_file",
            &wrong_args,
            Some(&holder.public_key()),
        );
        let preimage_wrong = build_approval_context_preimage(
            "wrt_test",
            "read_file",
            &rh_wrong,
            &holder.public_key(),
            &args_cbor_wrong,
        );
        let sig_wrong = signer.sign_raw(&preimage_wrong);

        assert!(
            verify_approval_context_attestation(
                &signer.public_key(),
                "wrt_test",
                "read_file",
                &args,
                &holder.public_key(),
                &sig_wrong,
            )
            .is_err(),
            "signature over different preimage must not verify for original args"
        );
    }

    #[test]
    fn test_request_hash_cbor_determinism() {
        // Test that CBOR serialization produces deterministic hashes
        // for semantically equivalent values

        // Test with floats (CBOR canonical encoding)
        let mut args1 = HashMap::new();
        args1.insert(
            "amount".to_string(),
            crate::constraints::ConstraintValue::Float(100.0),
        );

        let mut args2 = HashMap::new();
        args2.insert(
            "amount".to_string(),
            crate::constraints::ConstraintValue::Float(100.0), // Same float
        );

        let hash1 = compute_request_hash("wrt_123", "transfer", &args1, None);
        let hash2 = compute_request_hash("wrt_123", "transfer", &args2, None);

        assert_eq!(
            hash1, hash2,
            "CBOR should produce same hash for same float values"
        );

        // Test with integers
        let mut args_int1 = HashMap::new();
        args_int1.insert(
            "count".to_string(),
            crate::constraints::ConstraintValue::Integer(42),
        );

        let mut args_int2 = HashMap::new();
        args_int2.insert(
            "count".to_string(),
            crate::constraints::ConstraintValue::Integer(42),
        );

        let hash_int1 = compute_request_hash("wrt_456", "process", &args_int1, None);
        let hash_int2 = compute_request_hash("wrt_456", "process", &args_int2, None);

        assert_eq!(
            hash_int1, hash_int2,
            "CBOR should produce same hash for same integer values"
        );

        // Test that different types produce different hashes
        let mut args_float = HashMap::new();
        args_float.insert(
            "value".to_string(),
            crate::constraints::ConstraintValue::Float(100.0),
        );

        let mut args_int = HashMap::new();
        args_int.insert(
            "value".to_string(),
            crate::constraints::ConstraintValue::Integer(100),
        );

        let hash_float = compute_request_hash("wrt_789", "calc", &args_float, None);
        let hash_int = compute_request_hash("wrt_789", "calc", &args_int, None);

        assert_ne!(
            hash_float, hash_int,
            "CBOR should produce different hashes for float vs integer"
        );
    }

    #[test]
    fn test_notary_registry_lifecycle() {
        let mut registry = NotaryRegistry::new();

        // Create a notary (admin)
        let admin_keypair = SigningKey::generate();
        let admin = Notary::new("admin-1", admin_keypair.public_key()).with_name("Test Admin");

        // Register a provider
        registry.register_provider("aws-iam", "AWS IAM Provider", "admin-1");
        assert!(registry.has_provider("aws-iam"));

        // Create a key binding
        let keypair = SigningKey::generate();
        let binding = KeyBinding {
            id: "kb_test_123".to_string(),
            external_id: "arn:aws:iam::123:user/admin".to_string(),
            provider: "aws-iam".to_string(),
            public_key: keypair.public_key(),
            deployment_id: None,
            display_name: Some("Admin User".to_string()),
            registered_by: admin.id().to_string(),
            registered_at: Utc::now(),
            expires_at: None,
            active: true,
            metadata: None,
        };

        // Create registration proof (PoP)
        let proof = RegistrationProof::create(
            &keypair,
            "aws-iam",
            "arn:aws:iam::123:user/admin",
            Utc::now().timestamp(),
        );

        // Register the key with proof
        registry.register_key(binding, &proof, &admin).unwrap();

        // Resolve the identity
        let resolved = registry
            .resolve("aws-iam", "arn:aws:iam::123:user/admin")
            .unwrap();
        assert_eq!(resolved.to_bytes(), keypair.public_key().to_bytes());

        // Check audit events
        let events = registry.drain_events();
        assert_eq!(events.len(), 2); // provider registered + key registered
        assert_eq!(events[0].event_type, AuditEventType::ProviderRegistered);
        assert_eq!(events[1].event_type, AuditEventType::KeyRegistered);
    }

    #[test]
    fn test_key_rotation() {
        let mut registry = NotaryRegistry::new();

        // Create notary for provider registration
        let system_keypair = SigningKey::generate();
        let system = Notary::new("system", system_keypair.public_key());

        registry.register_provider("test", "Test Provider", "system");

        let old_keypair = SigningKey::generate();
        let new_keypair = SigningKey::generate();

        let binding = KeyBinding {
            id: "kb_rotate".to_string(),
            external_id: "user@example.com".to_string(),
            provider: "test".to_string(),
            public_key: old_keypair.public_key(),
            deployment_id: None,
            display_name: None,
            registered_by: system.id().to_string(),
            registered_at: Utc::now(),
            expires_at: None,
            active: true,
            metadata: None,
        };

        // Create registration proof
        let reg_proof = RegistrationProof::create(
            &old_keypair,
            "test",
            "user@example.com",
            Utc::now().timestamp(),
        );
        registry.register_key(binding, &reg_proof, &system).unwrap();

        // Create rotation signature (signed by OLD key)
        // Message format: provider || external_id || new_key_bytes
        let mut message = Vec::new();
        message.extend_from_slice(b"test");
        message.extend_from_slice(b"user@example.com");
        message.extend_from_slice(&new_keypair.public_key().to_bytes());
        let rotation_sig = old_keypair.sign(&message);

        // Rotate the key with signature
        registry
            .rotate_key(
                "test",
                "user@example.com",
                new_keypair.public_key(),
                &rotation_sig,
                "admin",
            )
            .unwrap();

        // Verify the new key is returned
        let resolved = registry.resolve("test", "user@example.com").unwrap();
        assert_eq!(resolved.to_bytes(), new_keypair.public_key().to_bytes());

        // Check audit events
        let events = registry.drain_events();
        assert!(events
            .iter()
            .any(|e| e.event_type == AuditEventType::KeyRotated));
    }

    #[test]
    fn test_key_revocation() {
        let mut registry = NotaryRegistry::new();

        let system_keypair = SigningKey::generate();
        let system = Notary::new("system", system_keypair.public_key());
        let security_keypair = SigningKey::generate();
        let security = Notary::new("security-team", security_keypair.public_key());

        registry.register_provider("test", "Test Provider", "system");

        let keypair = SigningKey::generate();
        let binding = KeyBinding {
            id: "kb_revoke".to_string(),
            external_id: "user@example.com".to_string(),
            provider: "test".to_string(),
            public_key: keypair.public_key(),
            deployment_id: None,
            display_name: None,
            registered_by: system.id().to_string(),
            registered_at: Utc::now(),
            expires_at: None,
            active: true,
            metadata: None,
        };

        let proof =
            RegistrationProof::create(&keypair, "test", "user@example.com", Utc::now().timestamp());
        registry.register_key(binding, &proof, &system).unwrap();

        // Create revocation signature (signed by security notary)
        // Message format: provider || external_id || reason
        let reason = "Compromised";
        let mut message = Vec::new();
        message.extend_from_slice(b"test");
        message.extend_from_slice(b"user@example.com");
        message.extend_from_slice(reason.as_bytes());
        let revoke_sig = security_keypair.sign(&message);

        // Revoke the key
        registry
            .revoke_key("test", "user@example.com", reason, &revoke_sig, &security)
            .unwrap();

        // Verify resolution fails
        let result = registry.resolve("test", "user@example.com");
        assert!(result.is_err());

        // Check the binding is marked inactive
        let binding = registry.get_binding("test", "user@example.com").unwrap();
        assert!(!binding.active);
    }

    #[test]
    fn test_unknown_provider_fails() {
        let mut registry = NotaryRegistry::new();

        let notary_keypair = SigningKey::generate();
        let notary = Notary::new("test-notary", notary_keypair.public_key());

        let keypair = SigningKey::generate();
        let binding = KeyBinding {
            id: "kb_fail".to_string(),
            external_id: "user@example.com".to_string(),
            provider: "unknown-provider".to_string(),
            public_key: keypair.public_key(),
            deployment_id: None,
            display_name: None,
            registered_by: notary.id().to_string(),
            registered_at: Utc::now(),
            expires_at: None,
            active: true,
            metadata: None,
        };

        let proof = RegistrationProof::create(
            &keypair,
            "unknown-provider",
            "user@example.com",
            Utc::now().timestamp(),
        );

        let result = registry.register_key(binding, &proof, &notary);
        assert!(result.is_err());
    }

    #[test]
    fn test_signed_approval_create_verify_roundtrip() {
        let approver = SigningKey::generate();
        let nonce: [u8; 16] = rand::random();
        let now = Utc::now();

        let payload = ApprovalPayload::new(
            [0xAA; 32],
            nonce,
            "arn:aws:iam::123:user/admin".to_string(),
            now,
            now + chrono::Duration::seconds(300),
        );

        let signed = SignedApproval::create(payload, &approver);
        let verified = signed.verify().expect("verify should succeed");

        assert_eq!(verified.external_id, "arn:aws:iam::123:user/admin");
        assert_eq!(verified.request_hash, [0xAA; 32]);
        assert_eq!(verified.nonce, nonce);
    }

    #[test]
    fn test_signed_approval_rejects_tampered_payload() {
        let approver = SigningKey::generate();
        let now = Utc::now();

        let payload = ApprovalPayload::new(
            [0xBB; 32],
            rand::random(),
            "user@corp.com".to_string(),
            now,
            now + chrono::Duration::seconds(300),
        );

        let mut signed = SignedApproval::create(payload, &approver);

        // Tamper with the CBOR payload after signing
        if let Some(byte) = signed.payload.last_mut() {
            *byte ^= 0xFF;
        }

        assert!(
            signed.verify().is_err(),
            "tampered payload must fail verification"
        );
    }

    #[test]
    fn test_signed_approval_rejects_wrong_key() {
        let real_approver = SigningKey::generate();
        let impersonator = SigningKey::generate();
        let now = Utc::now();

        let payload = ApprovalPayload::new(
            [0xCC; 32],
            rand::random(),
            "victim@corp.com".to_string(),
            now,
            now + chrono::Duration::seconds(300),
        );

        let signed = SignedApproval::create(payload, &real_approver);

        // Replace the public key with the impersonator's key
        let forged = SignedApproval {
            approver_key: impersonator.public_key(),
            ..signed
        };

        assert!(
            forged.verify().is_err(),
            "approval with wrong public key must fail verification"
        );
    }

    #[test]
    fn test_signed_approval_matches_request() {
        let approver = SigningKey::generate();
        let now = Utc::now();
        let hash = [0xDD; 32];

        let payload = ApprovalPayload::new(
            hash,
            rand::random(),
            "approver@test.com".to_string(),
            now,
            now + chrono::Duration::seconds(300),
        );

        let signed = SignedApproval::create(payload, &approver);

        assert!(signed.matches_request(&hash).unwrap());
        assert!(!signed.matches_request(&[0xEE; 32]).unwrap());
    }

    #[test]
    fn test_signed_approval_rejects_future_timestamp() {
        let approver = SigningKey::generate();
        let far_future = Utc::now() + chrono::Duration::hours(24);

        let payload = ApprovalPayload::new(
            [0x11; 32],
            rand::random(),
            "time-traveler@test.com".to_string(),
            far_future,
            far_future + chrono::Duration::seconds(300),
        );

        let signed = SignedApproval::create(payload, &approver);
        let result = signed.verify();

        assert!(
            result.is_err(),
            "approval with far-future approved_at must be rejected"
        );
    }

    #[test]
    fn test_signed_approval_rejects_bad_expiry_order() {
        let approver = SigningKey::generate();
        let now = Utc::now();

        let payload = ApprovalPayload {
            version: 1,
            request_hash: [0x22; 32],
            nonce: rand::random(),
            external_id: "bad-expiry@test.com".to_string(),
            approved_at: now.timestamp() as u64,
            expires_at: now.timestamp() as u64, // equal, not strictly greater
            extensions: None,
        };

        let signed = SignedApproval::create(payload, &approver);
        let result = signed.verify();

        assert!(
            result.is_err(),
            "approval with expires_at <= approved_at must be rejected"
        );
    }

    #[test]
    fn test_domain_separation_prevents_cross_context_replay() {
        let keypair = SigningKey::generate();
        let now = Utc::now();

        let payload = ApprovalPayload::new(
            [0x33; 32],
            rand::random(),
            "user@test.com".to_string(),
            now,
            now + chrono::Duration::seconds(300),
        );

        let signed = SignedApproval::create(payload, &keypair);

        // The preimage format is "tenuo-approval-v1" || version || payload_bytes.
        // Verify that the raw payload bytes alone (without domain prefix) cannot
        // pass verification, proving domain separation works.
        let raw_sig = keypair.sign(&signed.payload);
        let forged = SignedApproval {
            approval_version: 1,
            payload: signed.payload.clone(),
            approver_key: keypair.public_key(),
            signature: raw_sig,
        };

        assert!(
            forged.verify().is_err(),
            "signature over raw payload (without domain prefix) must fail"
        );
    }

    #[test]
    fn test_registration_proof_roundtrip() {
        let keypair = SigningKey::generate();
        let ts = Utc::now().timestamp();

        let proof =
            RegistrationProof::create(&keypair, "aws-iam", "arn:aws:iam::123:user/admin", ts);

        assert!(proof
            .verify(
                &keypair.public_key(),
                "aws-iam",
                "arn:aws:iam::123:user/admin"
            )
            .is_ok());

        // Wrong provider must fail
        assert!(proof
            .verify(&keypair.public_key(), "okta", "arn:aws:iam::123:user/admin")
            .is_err());

        // Wrong identity must fail
        assert!(proof
            .verify(
                &keypair.public_key(),
                "aws-iam",
                "arn:aws:iam::999:user/evil"
            )
            .is_err());

        // Wrong key must fail
        let other = SigningKey::generate();
        assert!(proof
            .verify(
                &other.public_key(),
                "aws-iam",
                "arn:aws:iam::123:user/admin"
            )
            .is_err());
    }

    #[test]
    fn test_rotation_proof_roundtrip() {
        let old_keypair = SigningKey::generate();
        let new_keypair = SigningKey::generate();
        let ts = Utc::now().timestamp();

        let proof = RotationProof::create(
            &old_keypair,
            "test",
            "user@test.com",
            &new_keypair.public_key(),
            ts,
        );

        assert!(proof
            .verify(
                &old_keypair.public_key(),
                "test",
                "user@test.com",
                &new_keypair.public_key()
            )
            .is_ok());

        // Wrong old key must fail
        let imposter = SigningKey::generate();
        assert!(proof
            .verify(
                &imposter.public_key(),
                "test",
                "user@test.com",
                &new_keypair.public_key()
            )
            .is_err());

        // Different new key must fail
        let other_new = SigningKey::generate();
        assert!(proof
            .verify(
                &old_keypair.public_key(),
                "test",
                "user@test.com",
                &other_new.public_key()
            )
            .is_err());
    }
}