vouch-core 4.2.0

Vouch Protocol canonical core: JCS canonicalization, Ed25519 + ML-DSA proofs, did:key/multikey, Data Integrity (eddsa-jcs-2022), credentials, delegation, revocation. One byte-exact implementation shared by every language SDK via WASM and UniFFI/C-FFI.
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
//! Root of Trust for Machine Identity (Vouch Protocol).
//!
//! Byte-exact port of the Python reference `vouch/root_of_trust.py`. Lets Vouch
//! Protocol act as the trust anchor for AI agent and robot identity. A verifier
//! pins ONE Vouch root, then verifies any agent offline by walking:
//!
//! ```text
//! agent identity credential  ->  recognized-issuer credential  ->  Vouch root
//! ```
//!
//! Three credential types compose this chain, all secured with the same
//! `eddsa-jcs-2022` Data Integrity proof used elsewhere in the core:
//!
//!   1. Root of Trust credential: self-issued by the root (issuer == subject).
//!   2. Recognized-issuer credential: issued by the root, naming an issuer that may attest agent or robot identity.
//!   3. Agent identity credential: issued by a recognized issuer, binding an agent key to real attributes (issuer != subject).
//!
//! The core is deterministic and clock-free: the caller supplies `valid_from`,
//! `created`, and the current instant used for verification. That keeps the
//! proofs reproducible and interoperable with the Python and TypeScript SDKs
//! (see `test-vectors/root-of-trust/vector.json`).

#[allow(unused_imports)]
use crate::prelude::*;

use serde_json::{json, Map, Value};

use crate::credentials::{PROTOCOL_VERSION, VC_CONTEXT_V2, VC_TYPE, VOUCH_CONTEXT_V1};
use crate::data_integrity::{self, BuildProofOptions};
use crate::error::{CoreError, Result};
use crate::keys::{did_key_to_ed25519, ed25519_to_did_key, Ed25519KeyPair};
use crate::time::{iso_to_epoch_seconds, parse_protocol_time_ns, seconds_to_ns};

/// Credential type identifiers (the second entry in each `type` array).
pub const ROOT_OF_TRUST_TYPE: &str = "VouchRootOfTrust";
pub const RECOGNIZED_ISSUER_TYPE: &str = "RecognizedIssuerCredential";
pub const AGENT_IDENTITY_TYPE: &str = "AgentIdentityCredential";

/// Actions an issuer can be recognized to perform.
pub const ACTION_ISSUE_AGENT_IDENTITY: &str = "issueAgentIdentity";
pub const ACTION_ISSUE_ROBOT_IDENTITY: &str = "issueRobotIdentity";

/// The three trust-layer credential types. A single credential must carry exactly
/// one of these, otherwise one signed object could be replayed into a different
/// slot of the chain (type confusion).
const TRUST_TYPES: [&str; 3] = [
    ROOT_OF_TRUST_TYPE,
    RECOGNIZED_ISSUER_TYPE,
    AGENT_IDENTITY_TYPE,
];

/// Default validity windows. Roots are long lived; issuer and identity
/// credentials rotate more often. All are overridable per call.
pub const ROOT_VALID_SECONDS: i64 = 10 * 365 * 24 * 3600;
pub const ISSUER_VALID_SECONDS: i64 = 365 * 24 * 3600;
pub const IDENTITY_VALID_SECONDS: i64 = 365 * 24 * 3600;

/// The proof verification method is always `{did}#key-1` for a did:key signer.
fn verification_method_of(did: &str) -> String {
    format!("{did}#key-1")
}

/// Outcome of [`verify_identity_chain`].
///
/// `ok` is true only if every link verified and anchored to the pinned root.
/// On failure `reason` carries a structured code matching the Python reference.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IdentityChainResult {
    pub ok: bool,
    pub reason: Option<String>,
    pub agent_did: Option<String>,
    pub issuer_did: Option<String>,
    pub root_did: Option<String>,
    pub attributes: Option<Value>,
}

impl IdentityChainResult {
    fn fail(reason: impl Into<String>) -> Self {
        Self {
            ok: false,
            reason: Some(reason.into()),
            agent_did: None,
            issuer_did: None,
            root_did: None,
            attributes: None,
        }
    }
}

// ---------------------------------------------------------------------------
// Credential builders
// ---------------------------------------------------------------------------

/// Self-issue the Vouch Root of Trust credential.
///
/// Issuer and subject are both the root's own DID (derived from `root_seed`).
/// `scope` defaults to `["ai-agent", "robot"]` when None. `valid_from` and
/// `created` are ISO-8601 instants ("YYYY-MM-DDTHH:MM:SSZ"); the core does not
/// read a clock.
#[allow(clippy::too_many_arguments)]
pub fn build_root_of_trust(
    root_seed: &[u8],
    name: &str,
    scope: Option<&[&str]>,
    valid_seconds: i64,
    valid_from: &str,
    created: &str,
    credential_id: &str,
) -> Result<Value> {
    let root_did = did_of_seed(root_seed)?;
    let scope_val: Vec<Value> = match scope {
        Some(s) => s.iter().map(|x| json!(x)).collect(),
        None => vec![json!("ai-agent"), json!("robot")],
    };
    let mut subject = Map::new();
    subject.insert("id".into(), json!(root_did));
    subject.insert("vouchVersion".into(), json!(PROTOCOL_VERSION));
    subject.insert(
        "rootOfTrust".into(),
        json!({ "name": name, "scope": scope_val }),
    );

    let credential = envelope(
        credential_id,
        &[VC_TYPE, ROOT_OF_TRUST_TYPE],
        &root_did,
        Value::Object(subject),
        valid_from,
        valid_seconds,
        None,
    )?;
    sign(&credential, root_seed, &root_did, created)
}

/// Issue a recognized-issuer credential from the root.
///
/// The root attests that `issuer_did` may perform `recognized_actions`
/// (default `["issueAgentIdentity"]`). `recognizedIn` chains back to the root
/// DID so a verifier can trace the recognition to the anchor it pinned.
#[allow(clippy::too_many_arguments)]
pub fn build_recognized_issuer(
    root_seed: &[u8],
    issuer_did: &str,
    recognized_actions: Option<&[&str]>,
    valid_seconds: i64,
    valid_from: &str,
    created: &str,
    credential_status: Option<Value>,
    credential_id: &str,
) -> Result<Value> {
    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); drop credential_status);
    if issuer_did.is_empty() {
        return Err(CoreError::Json("issuer_did is required".into()));
    }
    let root_did = did_of_seed(root_seed)?;
    let actions: Vec<Value> = match recognized_actions {
        Some(a) => a.iter().map(|x| json!(x)).collect(),
        None => vec![json!(ACTION_ISSUE_AGENT_IDENTITY)],
    };
    let mut subject = Map::new();
    subject.insert("id".into(), json!(issuer_did));
    subject.insert("recognizedActions".into(), Value::Array(actions));
    subject.insert("recognizedIn".into(), json!(root_did));

    let credential = envelope(
        credential_id,
        &[VC_TYPE, RECOGNIZED_ISSUER_TYPE],
        &root_did,
        Value::Object(subject),
        valid_from,
        valid_seconds,
        credential_status,
    )?;
    sign(&credential, root_seed, &root_did, created)
}

/// Issue an authority-issued identity credential for an agent.
///
/// Here the issuer (derived from `issuer_seed`) differs from the subject: a
/// recognized issuer binds `subject_did` to real `attributes` (owner, model,
/// capability class, and so on). `attributes` MUST be a non-empty JSON object.
#[allow(clippy::too_many_arguments)]
pub fn build_agent_identity(
    issuer_seed: &[u8],
    subject_did: &str,
    attributes: &Value,
    valid_seconds: i64,
    valid_from: &str,
    created: &str,
    credential_status: Option<Value>,
    credential_id: &str,
) -> Result<Value> {
    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); attributes; drop credential_status);
    if subject_did.is_empty() {
        return Err(CoreError::Json("subject_did is required".into()));
    }
    match attributes.as_object() {
        Some(o) if !o.is_empty() => {}
        _ => {
            return Err(CoreError::Json(
                "attributes must be a non-empty object".into(),
            ))
        }
    }
    let issuer_did = did_of_seed(issuer_seed)?;
    let mut subject = Map::new();
    subject.insert("id".into(), json!(subject_did));
    subject.insert("identity".into(), attributes.clone());

    let credential = envelope(
        credential_id,
        &[VC_TYPE, AGENT_IDENTITY_TYPE],
        &issuer_did,
        Value::Object(subject),
        valid_from,
        valid_seconds,
        credential_status,
    )?;
    sign(&credential, issuer_seed, &issuer_did, created)
}

// ---------------------------------------------------------------------------
// Verification
// ---------------------------------------------------------------------------

/// What a host is asked for while a chain is walked (see [`walk_identity_chain`]).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ChainAsk {
    /// The Ed25519 public key of `did` for the proof's verification method.
    Key { did: String, vm: String },
    /// Whether the recognized-issuer ("recognized") or the identity
    /// ("identity") credential is revoked.
    Revoked(&'static str),
    /// The action credential's verdict: does it verify (the host's verifier,
    /// which runs the core decision), and who issued it.
    Action,
}

/// A host's answers. Each method answers None when it has not been asked
/// before: the walk then stops with that [`ChainAsk`], the host finds the
/// answer, and the walk runs again from the start with it.
pub trait ChainHost {
    /// The issuer's key: Some(Some(key)), Some(None) when it cannot be
    /// resolved, None when not yet asked.
    fn key(&mut self, did: &str, vm: &str) -> Option<Option<Vec<u8>>>;
    /// Whether a credential is revoked; a host with no revocation check
    /// answers Some(false).
    fn revoked(&mut self, which: &'static str) -> Option<bool>;
    /// The action credential's (verifies, issuer).
    fn action(&mut self) -> Option<(bool, Option<String>)>;
    /// Whether the credential in a slot ("recognized", "identity", "root")
    /// has no JSON form the host could hand over (a NaN, an infinity, a lone
    /// surrogate, a number out of range, nesting too deep): the host sends a
    /// copy with those values as null, and its proof is malformed. The slot
    /// "requiredAction" names a required action with no JSON form, which no
    /// issuer holds.
    fn unreadable(&mut self, _slot: &'static str) -> bool {
        false
    }
}

/// Where a walk stopped.
#[derive(Debug, Clone, PartialEq)]
pub enum ChainWalk {
    Done(IdentityChainResult),
    Ask(ChainAsk),
}

/// Why a trust credential check stopped: a reason code, or a question.
enum Stop {
    Reason(&'static str),
    Ask(ChainAsk),
}

/// Walk an agent identity to a pinned Vouch root, the reference's checks in
/// the reference's order:
///
/// 1. the recognized-issuer credential is a valid trust credential, issued
///    by `trusted_root`, with a subject that is recognized for
///    `required_action`, and not revoked;
/// 2. the identity credential is a valid trust credential issued by that
///    recognized issuer, not revoked, with a subject;
/// 3. when given, the root credential is a valid trust credential issued by
///    `trusted_root` about itself;
/// 4. when `has_action`, the action credential verifies and its issuer is the
///    agent the identity names.
///
/// Keys, revocation and the action verdict come from the host, one question
/// at a time, so it is asked only what the reference would ask, in the
/// reference's order. A replay check of the action credential stays with the
/// host (its store), after a result that is ok.
#[allow(clippy::too_many_arguments)]
pub fn walk_identity_chain(
    identity_credential: &Value,
    recognized_issuer_credential: &Value,
    trusted_root: &str,
    root_credential: Option<&Value>,
    has_action: bool,
    required_action: &Value,
    now_iso: &str,
    clock_skew_seconds: i64,
    host: &mut dyn ChainHost,
) -> ChainWalk {
    crate::nesting::deep_guard!(ChainWalk::Done(IdentityChainResult::fail(crate::nesting::TOO_DEEP)); identity_credential, recognized_issuer_credential, root_credential, required_action);
    let fail = |r: &str| ChainWalk::Done(IdentityChainResult::fail(r));
    // A skew outside 0..120 is a caller error: the chain is refused.
    if crate::time::check_clock_skew(clock_skew_seconds).is_err() {
        return fail("invalid_clock_skew");
    }
    if trusted_root.is_empty() {
        return fail("no_trusted_root");
    }
    macro_rules! check {
        ($cred:expr, $ty:expr, $slot:expr, $prefix:expr) => {
            match verify_trust_credential($cred, $ty, $slot, now_iso, clock_skew_seconds, host) {
                Ok(()) => {}
                Err(Stop::Ask(ask)) => return ChainWalk::Ask(ask),
                Err(Stop::Reason(r)) => return fail(&format!("{}{r}", $prefix)),
            }
        };
    }

    // 1. The recognition must be signed by the pinned root.
    check!(
        recognized_issuer_credential,
        RECOGNIZED_ISSUER_TYPE,
        "recognized",
        "recognized_issuer_"
    );
    if issuer_of(recognized_issuer_credential).as_deref() != Some(trusted_root) {
        return fail("recognized_issuer_not_from_root");
    }
    let rec_subject = match recognized_issuer_credential.get("credentialSubject") {
        Some(Value::Object(o)) => o,
        _ => return fail("recognized_issuer_bad_subject"),
    };
    let recognized_did = match rec_subject.get("id").and_then(|v| v.as_str()) {
        Some(s) if !s.is_empty() => s.to_string(),
        _ => return fail("recognized_issuer_no_subject"),
    };
    let actions_ok = rec_subject
        .get("recognizedActions")
        .and_then(|v| v.as_array())
        // Any JSON value the caller names, compared as the reference's `in`
        // compares it: a value that is not one of the actions matches none.
        .map(|a| a.iter().any(|x| x == required_action))
        .unwrap_or(false)
        // An action the host could not hand over (no JSON form) is one no
        // issuer holds.
        && !host.unreadable("requiredAction");
    if !actions_ok {
        return fail("issuer_not_recognized_for_action");
    }
    match host.revoked("recognized") {
        None => return ChainWalk::Ask(ChainAsk::Revoked("recognized")),
        Some(true) => return fail("recognized_issuer_revoked"),
        Some(false) => {}
    }

    // 2. The identity must be signed by the recognized issuer.
    check!(
        identity_credential,
        AGENT_IDENTITY_TYPE,
        "identity",
        "identity_"
    );
    if issuer_of(identity_credential).as_deref() != Some(recognized_did.as_str()) {
        return fail("identity_not_from_recognized_issuer");
    }
    match host.revoked("identity") {
        None => return ChainWalk::Ask(ChainAsk::Revoked("identity")),
        Some(true) => return fail("identity_revoked"),
        Some(false) => {}
    }
    let id_subject = match identity_credential.get("credentialSubject") {
        Some(Value::Object(o)) => o,
        _ => return fail("identity_bad_subject"),
    };
    let agent_did = match id_subject.get("id").and_then(|v| v.as_str()) {
        Some(s) if !s.is_empty() => s.to_string(),
        _ => return fail("identity_no_subject"),
    };
    let attributes = id_subject.get("identity").cloned();

    // 3. Optional: confirm the root credential is genuinely self-issued.
    if let Some(root_cred) = root_credential {
        check!(root_cred, ROOT_OF_TRUST_TYPE, "root", "root_");
        let root_sub = match root_cred.get("credentialSubject") {
            Some(Value::Object(o)) => o,
            _ => return fail("root_bad_subject"),
        };
        if issuer_of(root_cred).as_deref() != Some(trusted_root)
            || root_sub.get("id").and_then(|v| v.as_str()) != Some(trusted_root)
        {
            return fail("root_not_self_issued");
        }
    }

    // 4. Optional: bind the agent's own action to this identity.
    if has_action {
        match host.action() {
            None => return ChainWalk::Ask(ChainAsk::Action),
            Some((false, _)) => return fail("action_proof_invalid"),
            Some((true, issuer)) => {
                if issuer.as_deref() != Some(agent_did.as_str()) {
                    return fail("action_not_from_agent");
                }
            }
        }
    }

    ChainWalk::Done(IdentityChainResult {
        ok: true,
        reason: None,
        agent_did: Some(agent_did),
        issuer_did: Some(recognized_did),
        root_did: Some(trusted_root.to_string()),
        attributes,
    })
}

/// The offline host: did:key issuers only, no revocation check.
struct DidKeyHost;

impl ChainHost for DidKeyHost {
    fn key(&mut self, did: &str, _vm: &str) -> Option<Option<Vec<u8>>> {
        Some(resolve_key(did))
    }
    fn revoked(&mut self, _which: &'static str) -> Option<bool> {
        Some(false)
    }
    fn action(&mut self) -> Option<(bool, Option<String>)> {
        None
    }
}

/// Verify an agent identity against a pinned Vouch root, fully offline for
/// did:key issuers (see [`walk_identity_chain`] for a host that resolves
/// other DIDs, checks revocation, and verifies the action credential with its
/// verifier). `action_credential`, when given, must verify under its did:key
/// issuer inside its window and be issued by the agent.
#[allow(clippy::too_many_arguments)]
pub fn verify_identity_chain(
    identity_credential: &Value,
    recognized_issuer_credential: &Value,
    trusted_root: &str,
    root_credential: Option<&Value>,
    action_credential: Option<&Value>,
    required_action: &str,
    now_iso: &str,
    clock_skew_seconds: i64,
) -> IdentityChainResult {
    crate::nesting::deep_guard!(IdentityChainResult::fail(crate::nesting::TOO_DEEP); identity_credential, recognized_issuer_credential, root_credential, action_credential);
    let walked = walk_identity_chain(
        identity_credential,
        recognized_issuer_credential,
        trusted_root,
        root_credential,
        false,
        &Value::String(required_action.to_string()),
        now_iso,
        clock_skew_seconds,
        &mut DidKeyHost,
    );
    let result = match walked {
        ChainWalk::Done(r) => r,
        // The offline host answers every question.
        ChainWalk::Ask(_) => return IdentityChainResult::fail("unresolved_key"),
    };
    let Some(action_cred) = action_credential.filter(|_| result.ok) else {
        return result;
    };
    let action_issuer = match issuer_of(action_cred) {
        Some(i) => i,
        None => return IdentityChainResult::fail("action_proof_invalid"),
    };
    match resolve_key(&action_issuer) {
        Some(pk) => match data_integrity::verify_proof(action_cred, &pk) {
            Ok(true) => {}
            _ => return IdentityChainResult::fail("action_proof_invalid"),
        },
        None => return IdentityChainResult::fail("action_proof_invalid"),
    }
    if !within_window(action_cred, now_iso, clock_skew_seconds) {
        return IdentityChainResult::fail("action_proof_invalid");
    }
    if Some(action_issuer.as_str()) != result.agent_did.as_deref() {
        return IdentityChainResult::fail("action_not_from_agent");
    }
    result
}

// ---------------------------------------------------------------------------
// Module-private helpers
// ---------------------------------------------------------------------------

/// Build the unsigned VC envelope shared by all three credential types.
#[allow(clippy::too_many_arguments)]
fn envelope(
    credential_id: &str,
    types: &[&str],
    issuer: &str,
    subject: Value,
    valid_from: &str,
    valid_seconds: i64,
    credential_status: Option<Value>,
) -> Result<Value> {
    let from = iso_to_epoch_seconds(valid_from)?;
    // The last instant a protocol time can name.
    const LAST_SECOND: i64 = 253_402_300_799; // 9999-12-31T23:59:59Z
    let until = from
        .checked_add(valid_seconds)
        .filter(|u| *u <= LAST_SECOND)
        .ok_or_else(|| {
            CoreError::Json("valid_seconds puts validUntil past 9999-12-31T23:59:59Z".into())
        })?;
    let valid_until = epoch_to_iso(until);
    let types_val: Vec<Value> = types.iter().map(|t| json!(t)).collect();

    let mut vc = Map::new();
    vc.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
    vc.insert("id".into(), json!(credential_id));
    vc.insert("type".into(), Value::Array(types_val));
    vc.insert("issuer".into(), json!(issuer));
    vc.insert("validFrom".into(), json!(valid_from));
    vc.insert("validUntil".into(), json!(valid_until));
    vc.insert("credentialSubject".into(), subject);
    if let Some(status) = credential_status {
        vc.insert("credentialStatus".into(), status);
    }
    Ok(Value::Object(vc))
}

/// Attach an eddsa-jcs-2022 Data Integrity proof to `credential`.
fn sign(credential: &Value, seed: &[u8], issuer_did: &str, created: &str) -> Result<Value> {
    let opts = BuildProofOptions::new(verification_method_of(issuer_did), created);
    data_integrity::sign(credential, seed, &opts)
}

/// did:key DID for a raw 32-byte Ed25519 seed.
fn did_of_seed(seed: &[u8]) -> Result<String> {
    let kp = Ed25519KeyPair::from_seed_slice(seed)?;
    ed25519_to_did_key(&kp.public_key())
}

/// Verify a trust-layer credential (root, recognized-issuer, or identity).
///
/// Checks the type (exactly one trust type), the issuer, the proof purpose,
/// that the verification method belongs to the issuer, the issuer's key
/// (from the host), the proof, and the validity window. Returns the Python
/// reason code on failure.
fn verify_trust_credential(
    credential: &Value,
    expected_type: &str,
    slot: &'static str,
    now_iso: &str,
    clock_skew_seconds: i64,
    host: &mut dyn ChainHost,
) -> core::result::Result<(), Stop> {
    let reason = |r: &'static str| Err(Stop::Reason(r));
    let Some(obj) = credential.as_object() else {
        return reason("not_a_credential");
    };
    let types = match obj.get("type").and_then(|v| v.as_array()) {
        Some(t) if t.iter().any(|t| t.as_str() == Some(expected_type)) => t,
        _ => return reason("wrong_type"),
    };
    // Exactly one trust-layer type, so the credential cannot double as another
    // link in the chain.
    let trust_count = TRUST_TYPES
        .iter()
        .filter(|tt| types.iter().any(|t| t.as_str() == Some(**tt)))
        .count();
    // A list or object inside `type` cannot be compared with the trust types
    // (the reference stops there): never one clear type.
    let nested = types.iter().any(|t| t.is_array() || t.is_object());
    if trust_count != 1 || nested {
        return reason("ambiguous_type");
    }
    let issuer = match issuer_of(credential) {
        Some(i) if !i.is_empty() => i,
        _ => return reason("no_issuer"),
    };
    let Some(proof) = obj.get("proof").and_then(|p| p.as_object()) else {
        return reason("no_proof");
    };
    if proof.get("proofPurpose").and_then(|v| v.as_str()) != Some("assertionMethod") {
        return reason("bad_proof_purpose");
    }
    let vm = match proof.get("verificationMethod").and_then(|v| v.as_str()) {
        Some(vm) if !vm.is_empty() && vm.split('#').next() == Some(issuer.as_str()) => vm,
        _ => return reason("vm_mismatch"),
    };
    let public_key = match host.key(&issuer, vm) {
        None => {
            return Err(Stop::Ask(ChainAsk::Key {
                did: issuer,
                vm: vm.to_string(),
            }))
        }
        Some(None) => return reason("unresolved_key"),
        Some(Some(k)) => k,
    };
    // A credential with no JSON form has no signing input: its proof is
    // malformed, as the reference finds when it cannot canonicalize it.
    if host.unreadable(slot) {
        return reason("proof_malformed");
    }
    match crate::proof_json::verify_eddsa(credential, &public_key) {
        Ok(true) => {}
        Ok(false) => return reason("proof_invalid"),
        Err(_) => return reason("proof_malformed"),
    }

    // Temporal window.
    let time = |name: &str| {
        obj.get(name)
            .and_then(|v| v.as_str())
            .and_then(|t| parse_protocol_time_ns(t).ok())
    };
    let (Some(valid_from), Some(valid_until)) = (time("validFrom"), time("validUntil")) else {
        return reason("no_validity_window");
    };
    let Ok(now) = parse_protocol_time_ns(now_iso) else {
        return reason("no_validity_window");
    };
    let skew = seconds_to_ns(clock_skew_seconds);
    if now - valid_until > skew {
        return reason("expired");
    }
    if valid_from - now > skew {
        return reason("not_yet_valid");
    }
    Ok(())
}

/// Whether `now_iso` falls inside the credential's validity window (used for the
/// optional action credential check).
fn within_window(credential: &Value, now_iso: &str, clock_skew_seconds: i64) -> bool {
    let obj = match credential.as_object() {
        Some(o) => o,
        None => return false,
    };
    let vf = obj.get("validFrom").and_then(|v| v.as_str());
    let vu = obj.get("validUntil").and_then(|v| v.as_str());
    let (vf, vu) = match (vf, vu) {
        (Some(a), Some(b)) => (a, b),
        _ => return false,
    };
    let now = match parse_protocol_time_ns(now_iso) {
        Ok(n) => n,
        Err(_) => return false,
    };
    let from = match parse_protocol_time_ns(vf) {
        Ok(t) => t,
        Err(_) => return false,
    };
    let until = match parse_protocol_time_ns(vu) {
        Ok(t) => t,
        Err(_) => return false,
    };
    let skew = seconds_to_ns(clock_skew_seconds);
    from <= until && now >= from - skew && now <= until + skew
}

/// Resolve an issuer's Ed25519 public key. Offline for did:key issuers, which is
/// all the vector and the current core support.
fn resolve_key(did: &str) -> Option<Vec<u8>> {
    if did.starts_with("did:key:") {
        did_key_to_ed25519(did).ok()
    } else {
        None
    }
}

/// Return the issuer DID, tolerating the list form used by multi-issuer VCs.
fn issuer_of(credential: &Value) -> Option<String> {
    match credential.get("issuer") {
        Some(Value::String(s)) => Some(s.clone()),
        Some(Value::Array(a)) => a.first().and_then(|v| v.as_str()).map(|s| s.to_string()),
        _ => None,
    }
}

/// Format Unix epoch seconds as "YYYY-MM-DDTHH:MM:SSZ" (inverse of
/// [`iso_to_epoch_seconds`] for whole-second UTC instants).
fn epoch_to_iso(epoch: i64) -> String {
    let days = epoch.div_euclid(86400);
    let secs = epoch.rem_euclid(86400);
    let (y, m, d) = civil_from_days(days);
    let hh = secs / 3600;
    let mm = (secs % 3600) / 60;
    let ss = secs % 60;
    format!("{y:04}-{m:02}-{d:02}T{hh:02}:{mm:02}:{ss:02}Z")
}

/// Civil date (year, month, day) from days since the Unix epoch. Howard
/// Hinnant's algorithm; the inverse of `time::days_from_civil`.
fn civil_from_days(z: i64) -> (i64, i64, i64) {
    let z = z + 719468;
    let era = (if z >= 0 { z } else { z - 146096 }) / 146097;
    let doe = z - era * 146097;
    let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
    let y = yoe + era * 400;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    let mp = (5 * doy + 2) / 153;
    let d = doy - (153 * mp + 2) / 5 + 1;
    let m = if mp < 10 { mp + 3 } else { mp - 9 };
    (if m <= 2 { y + 1 } else { y }, m, d)
}

// ---------------------------------------------------------------------------
// JSON entry (for the language SDKs)
// ---------------------------------------------------------------------------

/// The answers a host has given so far, read from a JSON request.
struct JsonHost<'a> {
    unreadable: &'a [Value],
    keys: &'a [Value],
    check_revoked: bool,
    revoked: Option<&'a Map<String, Value>>,
    action: Option<&'a Value>,
}

impl ChainHost for JsonHost<'_> {
    fn key(&mut self, did: &str, vm: &str) -> Option<Option<Vec<u8>>> {
        use base64::{engine::general_purpose::STANDARD, Engine};
        let entry = self.keys.iter().find(|k| {
            k.get("did").and_then(Value::as_str) == Some(did)
                && k.get("vm").and_then(Value::as_str) == Some(vm)
        })?;
        Some(
            entry
                .get("publicKey")
                .and_then(Value::as_str)
                .and_then(|k| STANDARD.decode(k).ok()),
        )
    }
    fn revoked(&mut self, which: &'static str) -> Option<bool> {
        if !self.check_revoked {
            return Some(false);
        }
        self.revoked?.get(which).and_then(Value::as_bool)
    }
    fn unreadable(&mut self, slot: &'static str) -> bool {
        self.unreadable.iter().any(|v| v.as_str() == Some(slot))
    }
    fn action(&mut self) -> Option<(bool, Option<String>)> {
        let a = self.action.filter(|a| a.is_object())?;
        Some((
            a.get("valid").and_then(Value::as_bool) == Some(true),
            a.get("issuer").and_then(Value::as_str).map(String::from),
        ))
    }
}

fn ask_json(ask: &ChainAsk) -> Value {
    match ask {
        ChainAsk::Key { did, vm } => json!({"kind": "key", "did": did, "vm": vm}),
        ChainAsk::Revoked(which) => json!({"kind": "revoked", "which": which}),
        ChainAsk::Action => json!({"kind": "action"}),
    }
}

fn chain_json(r: &IdentityChainResult) -> Value {
    json!({
        "ok": r.ok, "reason": r.reason, "agentDid": r.agent_did,
        "issuerDid": r.issuer_did, "rootDid": r.root_did, "attributes": r.attributes,
    })
}

/// The pinned root as the reference reads it: a root that is not given (or
/// false, zero, empty) pins nothing; a value that is not text pins a root no
/// issuer can be.
fn trusted_root_of(request: &Value) -> String {
    match request.get("trustedRoot") {
        Some(Value::String(s)) => s.clone(),
        None | Some(Value::Null) | Some(Value::Bool(false)) => String::new(),
        Some(Value::Number(n)) if n.as_f64() == Some(0.0) => String::new(),
        Some(Value::Array(a)) if a.is_empty() => String::new(),
        Some(Value::Object(o)) if o.is_empty() => String::new(),
        // NUL never appears in a DID.
        Some(_) => "\u{0}not a DID".to_string(),
    }
}

/// A true-or-false member: absent or null is false; anything else that is
/// not a boolean is a malformed request.
fn optional_bool(request: &Value, name: &str) -> Result<bool> {
    match request.get(name) {
        None | Some(Value::Null) => Ok(false),
        Some(Value::Bool(b)) => Ok(*b),
        Some(_) => Err(CoreError::Json(format!("{name} must be true or false"))),
    }
}

fn optional_array<'a>(request: &'a Value, name: &str) -> Result<Option<&'a Vec<Value>>> {
    match request.get(name) {
        None | Some(Value::Null) => Ok(None),
        Some(Value::Array(a)) => Ok(Some(a)),
        Some(_) => Err(CoreError::Json(format!("{name} must be a list"))),
    }
}

fn required_text<'a>(request: &'a Value, name: &str) -> Result<&'a str> {
    request
        .get(name)
        .and_then(Value::as_str)
        .ok_or_else(|| CoreError::Json(format!("{name} must be text")))
}

fn optional_object<'a>(request: &'a Value, name: &str) -> Option<&'a Value> {
    request.get(name).filter(|v| !v.is_null())
}

/// The valid_seconds rule every builder applies, with the reference's text.
fn valid_seconds_of(request: &Value, default: i64) -> Result<i64> {
    let refused = || {
        CoreError::Json("valid_seconds must be a whole number of seconds greater than zero".into())
    };
    match request.get("validSeconds") {
        None => Ok(default),
        Some(v) => v
            .as_i64()
            .filter(|n| *n > 0 && !v.is_f64())
            .ok_or_else(refused),
    }
}

fn walk_json(
    request: &Value,
    identity: &Value,
    recognized: &Value,
    required_action: &Value,
    has_action: bool,
) -> Result<core::result::Result<IdentityChainResult, Value>> {
    let skew = match request.get("clockSkewSeconds") {
        None | Some(Value::Null) => 30,
        Some(v) => crate::time_json::check_skew(v)?,
    };
    let empty = Vec::new();
    let unreadable = optional_array(request, "unreadable")?.unwrap_or(&empty);
    // A root credential the host could not hand over is still a root
    // credential given: it is checked (and is not a credential when its
    // copy is not an object), never skipped as absent.
    let root = if unreadable.iter().any(|v| v.as_str() == Some("root")) {
        Some(request.get("root").unwrap_or(&Value::Null))
    } else {
        optional_object(request, "root")
    };
    let mut host = JsonHost {
        unreadable,
        keys: request
            .get("keys")
            .and_then(Value::as_array)
            .unwrap_or(&empty),
        check_revoked: optional_bool(request, "checkRevoked")?,
        revoked: request.get("revoked").and_then(Value::as_object),
        action: optional_object(request, "action"),
    };
    let walked = walk_identity_chain(
        identity,
        recognized,
        &trusted_root_of(request),
        root,
        has_action,
        required_action,
        required_text(request, "now")?,
        skew,
        &mut host,
    );
    Ok(match walked {
        ChainWalk::Done(r) => Ok(r),
        ChainWalk::Ask(ask) => Err(json!({ "ask": ask_json(&ask) })),
    })
}

/// The root of trust rules, `{"op": ...}` in:
///
/// * `verifyChain` `{identity, recognized, trustedRoot, root?, hasAction?,
///   requiredAction? (issueAgentIdentity), now, clockSkewSeconds? (30),
///   keys?: [{did, vm, publicKey (standard base64) or null}],
///   checkRevoked?, revoked?: {recognized?, identity?}, action?: {valid,
///   issuer}}` -> `{"ask": {kind: "key" (did, vm) | "revoked" (which) |
///   "action"}}` or `{"result": {ok, reason, agentDid, issuerDid, rootDid,
///   attributes}}`. `requiredAction`, when given, is compared as given (a
///   value that is not one of the issuer's actions matches none);
///   `checkRevoked` and `hasAction` must be true or false. `unreadable`
///   names the slots ("recognized", "identity", "root", and for a robot
///   chain "hardwareCredential") whose credential had no JSON form: the host
///   sends them with those values as null and their proof is malformed. An
///   unreadable "requiredAction" is one no issuer holds. The host answers the ask (adds the key, null when it
///   cannot resolve one; the revocation answer; the action verdict from its
///   verifier) and calls again with the same request plus the answer. A
///   replay check of the action stays with the host, after an ok result.
/// * `verifyRobotChain` `{authorityIdentity, recognized, hardwareCredential,
///   robotPublicKey (standard base64 raw Ed25519), trustedRoot, root?, now,
///   clockSkewSeconds?, keys?, checkRevoked?, revoked?}` -> an ask, or
///   `{"result": {ok, reason, robotDid, issuerDid, rootDid, attributes,
///   hardwareRooted}}`: the chain for `issueRobotIdentity`, then the robot's
///   own credential, its subject, its key and the hardware root.
/// * `build` `{kind: "root" | "recognizedIssuer" | "agentIdentity" |
///   "robotIdentity", issuerDid, credentialId, validFrom, validSeconds?,
///   credentialStatus?, ...}` -> `{credential}`: the unsigned credential, for
///   the host to sign with the issuer's key (proof rules `prepare` and
///   `attach`). `root`: `name`, `scope?`; `recognizedIssuer`:
///   `subjectDid`, `recognizedActions?`; `agentIdentity`: `subjectDid`,
///   `attributes`; `robotIdentity`: `robotDid`, `hardwareKeyMultibase`,
///   `attributes`, `hardwareRootKeyMultibase?`.
pub fn rules_json(request: &Value) -> Result<Value> {
    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); request);
    let op = required_text(request, "op")?;
    let field = |name: &str| request.get(name).unwrap_or(&Value::Null);
    match op {
        "verifyChain" => {
            // Absent: the default action. Present: compared as given, so a
            // value that is not an action the issuer holds matches none.
            let default_action = Value::String(ACTION_ISSUE_AGENT_IDENTITY.into());
            let required = request.get("requiredAction").unwrap_or(&default_action);
            let has_action = optional_bool(request, "hasAction")?;
            Ok(
                match walk_json(
                    request,
                    field("identity"),
                    field("recognized"),
                    required,
                    has_action,
                )? {
                    Ok(r) => json!({ "result": chain_json(&r) }),
                    Err(ask) => ask,
                },
            )
        }
        "verifyRobotChain" => {
            use base64::{engine::general_purpose::STANDARD, Engine};
            let root = request
                .get("trustedRoot")
                .and_then(Value::as_str)
                .unwrap_or("");
            let robot_action = Value::String(ACTION_ISSUE_ROBOT_IDENTITY.into());
            let chain = match walk_json(
                request,
                field("authorityIdentity"),
                field("recognized"),
                &robot_action,
                false,
            )? {
                Ok(r) => r,
                Err(ask) => return Ok(ask),
            };
            let key = request
                .get("robotPublicKey")
                .and_then(Value::as_str)
                .and_then(|k| STANDARD.decode(k).ok())
                .unwrap_or_default();
            let r = crate::robotics::robot_identity_chain_tail(
                chain,
                // A robot credential with no JSON form cannot verify.
                if optional_array(request, "unreadable")?
                    .is_some_and(|u| u.iter().any(|v| v.as_str() == Some("hardwareCredential")))
                {
                    &Value::Null
                } else {
                    field("hardwareCredential")
                },
                root,
                &key,
                required_text(request, "now")?,
            );
            Ok(json!({"result": {
                "ok": r.ok, "reason": r.reason, "robotDid": r.robot_did,
                "issuerDid": r.issuer_did, "rootDid": r.root_did,
                "attributes": r.attributes, "hardwareRooted": r.hardware_rooted,
            }}))
        }
        "build" => {
            let issuer = required_text(request, "issuerDid")?;
            let status = optional_object(request, "credentialStatus").cloned();
            // The reference checks the lifetime first, except for a robot
            // identity, whose own checks come before it.
            if request.get("kind").and_then(Value::as_str) != Some("robotIdentity") {
                valid_seconds_of(request, 1)?;
            }
            let (types, subject, default_seconds, status) = match required_text(request, "kind")? {
                "root" => {
                    let scope = match list_or_default(request, "scope", "scope")? {
                        Some(a) => Value::Array(a.clone()),
                        None => json!(["ai-agent", "robot"]),
                    };
                    let mut subject = Map::new();
                    subject.insert("id".into(), json!(issuer));
                    subject.insert("vouchVersion".into(), json!(PROTOCOL_VERSION));
                    subject.insert(
                        "rootOfTrust".into(),
                        json!({"name": field("name"), "scope": scope}),
                    );
                    (ROOT_OF_TRUST_TYPE, subject, ROOT_VALID_SECONDS, None)
                }
                "recognizedIssuer" => {
                    let subject_did = request
                        .get("subjectDid")
                        .and_then(Value::as_str)
                        .filter(|d| !d.is_empty())
                        .ok_or_else(|| CoreError::Json("issuer_did is required".into()))?;
                    let actions = match list_or_default(
                        request,
                        "recognizedActions",
                        "recognized_actions",
                    )? {
                        Some(a) => Value::Array(a.clone()),
                        None => json!([ACTION_ISSUE_AGENT_IDENTITY]),
                    };
                    let mut subject = Map::new();
                    subject.insert("id".into(), json!(subject_did));
                    subject.insert("recognizedActions".into(), actions);
                    subject.insert("recognizedIn".into(), json!(issuer));
                    (
                        RECOGNIZED_ISSUER_TYPE,
                        subject,
                        ISSUER_VALID_SECONDS,
                        status,
                    )
                }
                kind @ ("agentIdentity" | "robotIdentity") => {
                    let robot = kind == "robotIdentity";
                    let name = if robot { "robotDid" } else { "subjectDid" };
                    let subject_did = request
                        .get(name)
                        .and_then(Value::as_str)
                        .filter(|d| !d.is_empty())
                        .ok_or_else(|| {
                            CoreError::Json(if robot {
                                "robot_did is required".into()
                            } else {
                                "subject_did is required".into()
                            })
                        })?;
                    let attributes = if robot {
                        let hw = request
                            .get("hardwareKeyMultibase")
                            .and_then(Value::as_str)
                            .filter(|k| !k.is_empty())
                            .ok_or_else(|| {
                                CoreError::Json("hardware_key_multibase is required".into())
                            })?;
                        let mut attributes = attribute_map(field("attributes"))?;
                        attributes.insert("kind".into(), json!("robot"));
                        attributes.insert("hardwareKey".into(), json!(hw));
                        match optional_object(request, "hardwareRootKeyMultibase") {
                            None => {}
                            Some(Value::String(k)) if !k.is_empty() => {
                                attributes.insert("hardwareRootKey".into(), json!(k));
                            }
                            Some(_) => {
                                return Err(CoreError::Json(
                                    "hardware_root_key_multibase must be a multikey string".into(),
                                ))
                            }
                        }
                        attributes
                    } else {
                        attribute_map(field("attributes"))?
                    };
                    let mut subject = Map::new();
                    subject.insert("id".into(), json!(subject_did));
                    subject.insert("identity".into(), Value::Object(attributes));
                    (AGENT_IDENTITY_TYPE, subject, IDENTITY_VALID_SECONDS, status)
                }
                other => {
                    return Err(CoreError::Json(format!(
                        "no root of trust credential of kind {other:?}"
                    )))
                }
            };
            let valid_seconds = valid_seconds_of(request, default_seconds)?;
            let credential = envelope(
                required_text(request, "credentialId")?,
                &[VC_TYPE, types],
                issuer,
                Value::Object(subject),
                required_text(request, "validFrom")?,
                valid_seconds,
                status,
            )?;
            Ok(json!({ "credential": credential }))
        }
        other => Err(CoreError::Json(format!(
            "unknown root of trust op {other:?}"
        ))),
    }
}

/// [`rules_json`] on request text, read with the nesting the reference's
/// canonical form allows (see [`crate::jcs::parse_deep`]), so a credential
/// nested 130 levels is judged by its proof, not refused unread.
pub fn rules_json_text(text: &str) -> Result<Value> {
    rules_json(&crate::jcs::parse_deep(text)?)
}

/// A list member that falls back to its default when absent, null or empty
/// (as the reference's `x or default`); any other type is refused.
fn list_or_default<'a>(
    request: &'a Value,
    name: &str,
    text: &str,
) -> Result<Option<&'a Vec<Value>>> {
    match request.get(name) {
        None | Some(Value::Null) => Ok(None),
        Some(Value::Array(a)) if a.is_empty() => Ok(None),
        Some(Value::Array(a)) => Ok(Some(a)),
        Some(_) => Err(CoreError::Json(format!("{text} must be a list"))),
    }
}

fn attribute_map(v: &Value) -> Result<Map<String, Value>> {
    match v.as_object() {
        Some(o) if !o.is_empty() => Ok(o.clone()),
        _ => Err(CoreError::Json(
            "attributes must be a non-empty dict".into(),
        )),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::path::PathBuf;

    const ROOT_SEED: [u8; 32] = [0x01; 32];
    const ISSUER_SEED: [u8; 32] = [0x02; 32];
    const AGENT_SEED: [u8; 32] = [0x03; 32];

    const VALID_FROM: &str = "2026-01-01T00:00:00Z";
    const CREATED: &str = "2026-01-01T00:00:00Z";
    const VALID_SECONDS: i64 = 100 * 365 * 24 * 3600;
    const NOW: &str = "2026-07-01T00:00:00Z";

    const ROOT_ID: &str = "urn:uuid:11111111-1111-1111-1111-111111111111";
    const RECOGNITION_ID: &str = "urn:uuid:22222222-2222-2222-2222-222222222222";
    const IDENTITY_ID: &str = "urn:uuid:33333333-3333-3333-3333-333333333333";

    fn load_vector() -> Value {
        let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
            .join("../../test-vectors/root-of-trust/vector.json");
        let text = std::fs::read_to_string(&path)
            .unwrap_or_else(|e| panic!("read vector {}: {e}", path.display()));
        serde_json::from_str(&text).expect("vector is valid JSON")
    }

    fn agent_attributes() -> Value {
        json!({ "owner": "Acme", "model": "gpt-x", "capabilityClass": "shopping" })
    }

    fn build_all() -> (Value, Value, Value) {
        let issuer_did = did_of_seed(&ISSUER_SEED).unwrap();
        let agent_did = did_of_seed(&AGENT_SEED).unwrap();

        let root = build_root_of_trust(
            &ROOT_SEED,
            "Vouch Machine Identity Root",
            None,
            VALID_SECONDS,
            VALID_FROM,
            CREATED,
            ROOT_ID,
        )
        .unwrap();

        let recognition = build_recognized_issuer(
            &ROOT_SEED,
            &issuer_did,
            Some(&[ACTION_ISSUE_AGENT_IDENTITY]),
            VALID_SECONDS,
            VALID_FROM,
            CREATED,
            None,
            RECOGNITION_ID,
        )
        .unwrap();

        let identity = build_agent_identity(
            &ISSUER_SEED,
            &agent_did,
            &agent_attributes(),
            VALID_SECONDS,
            VALID_FROM,
            CREATED,
            None,
            IDENTITY_ID,
        )
        .unwrap();

        (root, recognition, identity)
    }

    // (a) Verify Python-signed credentials from the committed interop vector.
    #[test]
    fn verifies_python_signed_vector() {
        let vector = load_vector();
        let trusted_root = vector["trustedRoot"].as_str().unwrap();
        let result = verify_identity_chain(
            &vector["agentIdentity"],
            &vector["recognizedIssuer"],
            trusted_root,
            Some(&vector["rootOfTrust"]),
            None,
            ACTION_ISSUE_AGENT_IDENTITY,
            NOW,
            30,
        );
        assert!(result.ok, "chain must verify: {:?}", result.reason);
        assert_eq!(
            result.agent_did.as_deref(),
            vector["expected"]["agentDid"].as_str()
        );
        assert_eq!(
            result.issuer_did.as_deref(),
            vector["expected"]["issuerDid"].as_str()
        );
        assert_eq!(result.root_did.as_deref(), Some(trusted_root));
    }

    // (b) Reproduce every proofValue byte-for-byte from the same fixed inputs.
    #[test]
    fn reproduces_vector_byte_for_byte() {
        let vector = load_vector();
        let (root, recognition, identity) = build_all();

        assert_eq!(
            root["proof"]["proofValue"], vector["rootOfTrust"]["proof"]["proofValue"],
            "root of trust proofValue diverges from Python"
        );
        assert_eq!(
            recognition["proof"]["proofValue"], vector["recognizedIssuer"]["proof"]["proofValue"],
            "recognized issuer proofValue diverges from Python"
        );
        assert_eq!(
            identity["proof"]["proofValue"], vector["agentIdentity"]["proof"]["proofValue"],
            "agent identity proofValue diverges from Python"
        );

        // The derived DIDs and validity window must also match the vector.
        assert_eq!(root["issuer"], vector["trustedRoot"]);
        assert_eq!(root["validUntil"], vector["rootOfTrust"]["validUntil"]);
        assert_eq!(identity["issuer"], vector["agentIdentity"]["issuer"]);
    }

    // Round-trip: credentials we build verify through our own chain walker.
    #[test]
    fn self_built_chain_verifies() {
        let (root, recognition, identity) = build_all();
        let root_did = did_of_seed(&ROOT_SEED).unwrap();
        let agent_did = did_of_seed(&AGENT_SEED).unwrap();
        let issuer_did = did_of_seed(&ISSUER_SEED).unwrap();

        let result = verify_identity_chain(
            &identity,
            &recognition,
            &root_did,
            Some(&root),
            None,
            ACTION_ISSUE_AGENT_IDENTITY,
            NOW,
            30,
        );
        assert!(
            result.ok,
            "self-built chain must verify: {:?}",
            result.reason
        );
        assert_eq!(result.agent_did.as_deref(), Some(agent_did.as_str()));
        assert_eq!(result.issuer_did.as_deref(), Some(issuer_did.as_str()));
        assert_eq!(result.attributes, Some(agent_attributes()));
    }

    #[test]
    fn skew_outside_zero_to_120_is_refused() {
        let (root, recognition, identity) = build_all();
        let root_did = did_of_seed(&ROOT_SEED).unwrap();
        for skew in [-1, 121, 300, 1_000_000_000] {
            let result = verify_identity_chain(
                &identity,
                &recognition,
                &root_did,
                Some(&root),
                None,
                ACTION_ISSUE_AGENT_IDENTITY,
                NOW,
                skew,
            );
            assert!(!result.ok, "skew {skew} must be refused");
            assert_eq!(result.reason.as_deref(), Some("invalid_clock_skew"));
        }
    }

    // (c) Adversarial: a tampered identity proof must break the chain.
    #[test]
    fn tampered_identity_proof_is_rejected() {
        let vector = load_vector();
        let mut identity = vector["agentIdentity"].clone();
        // Edit a signed attribute: the proof no longer matches. (A changed
        // proofValue whose S is no longer below the group order is a
        // malformed proof instead, as in the reference.)
        identity["credentialSubject"]["identity"]["capabilityClass"] = json!("admin");
        let result = verify_identity_chain(
            &identity,
            &vector["recognizedIssuer"],
            vector["trustedRoot"].as_str().unwrap(),
            Some(&vector["rootOfTrust"]),
            None,
            ACTION_ISSUE_AGENT_IDENTITY,
            NOW,
            30,
        );
        assert!(!result.ok, "tampered proof must be rejected");
        assert_eq!(
            result.reason.as_deref(),
            Some("identity_proof_invalid"),
            "unexpected reason for tampered proof"
        );
    }

    // A recognition that does not grant the required action is rejected.
    #[test]
    fn wrong_action_is_rejected() {
        let (root, _recognition, identity) = build_all();
        let root_did = did_of_seed(&ROOT_SEED).unwrap();
        let issuer_did = did_of_seed(&ISSUER_SEED).unwrap();
        let recognition = build_recognized_issuer(
            &ROOT_SEED,
            &issuer_did,
            Some(&[ACTION_ISSUE_ROBOT_IDENTITY]),
            VALID_SECONDS,
            VALID_FROM,
            CREATED,
            None,
            RECOGNITION_ID,
        )
        .unwrap();
        let result = verify_identity_chain(
            &identity,
            &recognition,
            &root_did,
            Some(&root),
            None,
            ACTION_ISSUE_AGENT_IDENTITY,
            NOW,
            30,
        );
        assert!(!result.ok);
        assert_eq!(
            result.reason.as_deref(),
            Some("issuer_not_recognized_for_action")
        );
    }

    // A credential carrying two trust types is ambiguous and rejected.
    #[test]
    fn ambiguous_type_is_rejected() {
        let (_root, recognition, mut identity) = build_all();
        identity["type"] = json!([VC_TYPE, AGENT_IDENTITY_TYPE, RECOGNIZED_ISSUER_TYPE]);
        let root_did = did_of_seed(&ROOT_SEED).unwrap();
        let result = verify_identity_chain(
            &identity,
            &recognition,
            &root_did,
            None,
            None,
            ACTION_ISSUE_AGENT_IDENTITY,
            NOW,
            30,
        );
        assert!(!result.ok);
        assert_eq!(result.reason.as_deref(), Some("identity_ambiguous_type"));
    }

    #[test]
    fn epoch_iso_roundtrip() {
        assert_eq!(epoch_to_iso(0), "1970-01-01T00:00:00Z");
        let from = iso_to_epoch_seconds(VALID_FROM).unwrap();
        assert_eq!(epoch_to_iso(from + VALID_SECONDS), "2125-12-08T00:00:00Z");
    }

    fn walk_request(extra: Value) -> Value {
        let (root, recognition, identity) = build_all();
        let mut req = json!({
            "op": "verifyChain",
            "identity": identity,
            "recognized": recognition,
            "trustedRoot": did_of_seed(&ROOT_SEED).unwrap(),
            "root": root,
            "now": NOW,
        });
        for (k, v) in extra.as_object().unwrap() {
            req[k] = v.clone();
        }
        req
    }

    /// Walk with the offline keys: answer every key ask from the did:key.
    fn walk(mut req: Value) -> Value {
        use base64::{engine::general_purpose::STANDARD, Engine};
        for _ in 0..8 {
            let out = rules_json(&req).unwrap();
            let Some(ask) = out.get("ask") else {
                return out["result"].clone();
            };
            assert_eq!(ask["kind"], "key", "{out}");
            let did = ask["did"].as_str().unwrap();
            let key = did_key_to_ed25519(did).unwrap();
            let keys = req
                .as_object_mut()
                .unwrap()
                .entry("keys")
                .or_insert(json!([]));
            keys.as_array_mut()
                .unwrap()
                .push(json!({"did": did, "vm": ask["vm"], "publicKey": STANDARD.encode(key)}));
        }
        panic!("the walk did not finish");
    }

    #[test]
    fn a_required_action_is_compared_as_given() {
        assert_eq!(walk(walk_request(json!({})))["ok"], json!(true));
        for odd in [
            json!(null),
            json!(5),
            json!(["issueAgentIdentity"]),
            json!(""),
        ] {
            let got = walk(walk_request(json!({ "requiredAction": odd })));
            assert_eq!(
                got["reason"],
                json!("issuer_not_recognized_for_action"),
                "{odd}"
            );
        }
    }

    #[test]
    fn flags_that_are_not_true_or_false_are_refused() {
        for (name, value) in [("checkRevoked", json!(1)), ("hasAction", json!("true"))] {
            let err = rules_json(&walk_request(json!({ name: value }))).unwrap_err();
            assert_eq!(
                err,
                CoreError::Json(format!("{name} must be true or false"))
            );
        }
    }

    #[test]
    fn an_unreadable_credential_has_a_malformed_proof() {
        let got = walk(walk_request(json!({"unreadable": ["identity"]})));
        assert_eq!(got["reason"], json!("identity_proof_malformed"));
        let got = walk(walk_request(json!({"unreadable": ["recognized"]})));
        assert_eq!(got["reason"], json!("recognized_issuer_proof_malformed"));
    }

    #[test]
    fn an_unreadable_required_action_matches_no_action() {
        let got = walk(walk_request(json!({
            "requiredAction": null, "unreadable": ["requiredAction"]
        })));
        assert_eq!(got["reason"], json!("issuer_not_recognized_for_action"));
        let got = walk(walk_request(json!({
            "requiredAction": "issueAgentIdentity", "unreadable": ["requiredAction"]
        })));
        assert_eq!(got["reason"], json!("issuer_not_recognized_for_action"));
    }

    #[test]
    fn an_unreadable_root_that_is_not_an_object_is_not_a_credential() {
        // The host's copy of a root with no JSON form (a NaN, a lone
        // surrogate) is null: the root was still given, so it is checked.
        let got = walk(walk_request(json!({"root": null, "unreadable": ["root"]})));
        assert_eq!(got["reason"], json!("root_not_a_credential"));
        let got = walk(walk_request(json!({"root": null})));
        assert_eq!(got["ok"], json!(true));
    }

    #[test]
    fn a_trust_type_list_with_a_nested_list_is_ambiguous() {
        let (_, mut recognition, identity) = build_all();
        recognition["type"]
            .as_array_mut()
            .unwrap()
            .push(json!(["VouchRootOfTrust"]));
        let got = walk(walk_request(
            json!({"recognized": recognition, "identity": identity}),
        ));
        assert_eq!(got["reason"], json!("recognized_issuer_ambiguous_type"));
    }

    #[test]
    fn a_trusted_root_that_is_not_text_pins_nothing_an_issuer_can_be() {
        let got = walk(walk_request(json!({"trustedRoot": 5})));
        assert_eq!(got["reason"], json!("recognized_issuer_not_from_root"));
        let got = walk(walk_request(json!({"trustedRoot": ""})));
        assert_eq!(got["reason"], json!("no_trusted_root"));
    }

    #[test]
    #[cfg_attr(not(feature = "std"), ignore = "the std build's 512-level allowance")]
    fn a_deep_credential_is_read_and_judged_by_its_proof() {
        let (_, recognition, mut identity) = build_all();
        let deep =
            crate::jcs::parse_deep(&format!("{}{}", "[".repeat(130), "]".repeat(130))).unwrap();
        identity["x"] = deep;
        let mut req = walk_request(json!({"recognized": recognition}));
        req["identity"] = identity;
        let text = req.to_string();
        assert!(
            serde_json::from_str::<Value>(&text).is_err(),
            "deeper than the default reader"
        );
        let out = rules_json_text(&text).unwrap();
        assert!(out.get("ask").is_some() || out.get("result").is_some());
    }

    #[test]
    #[cfg_attr(feature = "std", ignore = "checks the no_std build")]
    fn no_std_text_entry_refuses_past_the_cap_before_parsing() {
        let (_, recognition, _) = build_all();
        let req = walk_request(json!({"recognized": recognition})).to_string();
        for n in [32, 129, 600] {
            let deep = format!("{}{}", "[".repeat(n), "]".repeat(n));
            let text = format!("{{\"x\":{deep},{}", &req[1..]);
            assert_eq!(
                rules_json_text(&text).unwrap_err(),
                crate::nesting::too_deep(),
                "{n} levels"
            );
        }
    }

    #[test]
    fn build_refuses_wrong_types_and_a_window_past_year_9999() {
        let base = json!({"op": "build", "issuerDid": "did:web:a.example", "credentialId": "urn:x",
                          "validFrom": "2026-01-01T00:00:00Z"});
        let with = |k: &str, v: Value, kind: &str| {
            let mut r = base.clone();
            r["kind"] = json!(kind);
            r["name"] = json!("n");
            r["subjectDid"] = json!("did:web:b.example");
            r[k] = v;
            rules_json(&r)
        };
        assert_eq!(
            with("scope", json!("robot"), "root").unwrap_err(),
            CoreError::Json("scope must be a list".into())
        );
        assert_eq!(
            with("recognizedActions", json!({"a": 1}), "recognizedIssuer").unwrap_err(),
            CoreError::Json("recognized_actions must be a list".into())
        );
        assert!(with("validSeconds", json!(null), "root").is_err());
        let err = with("validSeconds", json!(i64::MAX), "root").unwrap_err();
        assert_eq!(
            err,
            CoreError::Json("valid_seconds puts validUntil past 9999-12-31T23:59:59Z".into())
        );
        let mut r = base.clone();
        r["kind"] = json!("root");
        r["validFrom"] = json!("9999-12-31T23:59:58Z");
        r["validSeconds"] = json!(1);
        assert_eq!(
            rules_json(&r).unwrap()["credential"]["validUntil"],
            json!("9999-12-31T23:59:59Z")
        );
    }
}