vouch-core 4.1.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
//! Vouch Credential build and verify.
//!
//! Byte-exact port of the TypeScript `buildVouchCredential` (vc.ts): same JSON
//! shape and field ordering. The core is deterministic and clock-free, so the
//! caller supplies the credential id and the validity window (the SDK/wrapper
//! computes them); verification takes the current instant as a parameter.

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

use crate::data_integrity::{self, BuildProofOptions};
use crate::error::{CoreError, Result};
use crate::time::{check_clock_skew, parse_protocol_time_ns, window_state_ns, WindowState};

pub const VC_CONTEXT_V2: &str = "https://www.w3.org/ns/credentials/v2";
pub const VOUCH_CONTEXT_V1: &str = "https://vouch-protocol.com/contexts/v1";
pub const VC_TYPE: &str = "VerifiableCredential";
pub const VOUCH_CREDENTIAL_TYPE: &str = "VouchCredential";
pub const PROTOCOL_VERSION: &str = "1.0";

/// Inputs to build an unsigned Vouch Credential.
#[derive(Debug, Clone)]
pub struct BuildCredentialOptions {
    pub issuer_did: String,
    pub credential_id: String,
    pub intent: Value,
    pub valid_from: String,
    pub valid_until: String,
    pub reputation_score: Option<i64>,
    pub delegation_chain: Option<Value>,
    pub credential_status: Option<Value>,
}

/// Validate that `intent` carries the REQUIRED non-empty action/target/resource
/// (Specification 5.4.1).
pub fn validate_intent(intent: &Value) -> Result<()> {
    let obj = intent
        .as_object()
        .ok_or_else(|| CoreError::Json("intent must be an object".into()))?;
    for req in ["action", "target", "resource"] {
        match obj.get(req).and_then(|v| v.as_str()) {
            Some(s) if !s.is_empty() => {}
            _ => {
                return Err(CoreError::Json(format!(
                    "intent.{req} is REQUIRED and must be a non-empty string"
                )))
            }
        }
    }
    Ok(())
}

/// Construct an unsigned Vouch Credential matching `buildVouchCredential`.
pub fn build_vouch_credential(opts: &BuildCredentialOptions) -> Result<Value> {
    build_credential(opts, None)
}

/// Construct an unsigned sub-grant: a Vouch Credential that names the grant it
/// is made under by digest, in `credentialSubject.parentGrantDigest`
/// ([`crate::grant_chain::grant_digest`] of the direct parent grant). A
/// sub-grant carries no `delegationChain`; its delegatee is handed the whole
/// grant chain instead ([`crate::grant_chain::grant_chain`]). Matches the
/// reference builder's `parent_grant_digest` (vc.build_vouch_credential).
///
/// Errors: the intent is missing a required field, the digest is empty, or
/// `opts.delegation_chain` is a non-empty list (a grant names its parent one
/// way, never both).
pub fn build_sub_grant(opts: &BuildCredentialOptions, parent_grant_digest: &str) -> Result<Value> {
    build_credential(opts, Some(parent_grant_digest))
}

/// Build and sign a sub-grant in one step (eddsa-jcs-2022); see
/// [`build_sub_grant`].
pub fn sign_sub_grant(
    opts: &BuildCredentialOptions,
    parent_grant_digest: &str,
    raw_private_seed: &[u8],
    proof_opts: &BuildProofOptions,
) -> Result<Value> {
    let cred = build_sub_grant(opts, parent_grant_digest)?;
    data_integrity::sign(&cred, raw_private_seed, proof_opts)
}

fn build_credential(opts: &BuildCredentialOptions, parent_digest: Option<&str>) -> Result<Value> {
    validate_intent(&opts.intent)?;
    let has_chain = opts
        .delegation_chain
        .as_ref()
        .and_then(|c| c.as_array())
        .is_some_and(|a| !a.is_empty());
    if let Some(digest) = parent_digest {
        if digest.is_empty() {
            return Err(CoreError::Json(
                "parent_grant_digest must be a grant digest string".into(),
            ));
        }
        if has_chain {
            return Err(CoreError::Json(
                "a credential carries parentGrantDigest or a delegationChain, never both".into(),
            ));
        }
    }

    let mut subject = Map::new();
    subject.insert("id".into(), json!(opts.issuer_did));
    subject.insert("vouchVersion".into(), json!(PROTOCOL_VERSION));
    subject.insert("intent".into(), opts.intent.clone());
    if let Some(r) = opts.reputation_score {
        subject.insert("reputationScore".into(), json!(r.clamp(0, 100)));
    }
    if let Some(digest) = parent_digest {
        subject.insert(
            crate::grant_chain::PARENT_GRANT_DIGEST.into(),
            json!(digest),
        );
    }
    if let Some(chain) = &opts.delegation_chain {
        if chain.as_array().map(|a| !a.is_empty()).unwrap_or(false) {
            subject.insert("delegationChain".into(), chain.clone());
        }
    }

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

/// Build and sign a Vouch Credential in one step (eddsa-jcs-2022).
pub fn sign_vouch_credential(
    opts: &BuildCredentialOptions,
    raw_private_seed: &[u8],
    proof_opts: &BuildProofOptions,
) -> Result<Value> {
    let cred = build_vouch_credential(opts)?;
    data_integrity::sign(&cred, raw_private_seed, proof_opts)
}

/// Every `vouchVersion` this codebase has ever issued. A credential with a
/// missing or different version is refused.
pub const SUPPORTED_VOUCH_VERSIONS: &[&str] = &[PROTOCOL_VERSION];

/// The outcome of verifying a credential: the proof, the temporal window, and
/// the embedded delegation chain are reported separately so a caller can
/// distinguish "bad signature" from "expired" from "chain refused".
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct VerifyResult {
    /// The signature verifies with the key given, the key is the issuer's (for
    /// a `did:key` issuer, the key the DID encodes), and the proof is bound to
    /// the issuer: proofPurpose "assertionMethod" and a verificationMethod of
    /// the issuer's DID.
    pub proof_valid: bool,
    /// `now` is inside [validFrom, validUntil] (with the skew), the window is
    /// not inverted, and no proof has passed its `expires`.
    pub time_valid: bool,
    /// True when the credential has no delegation chain, or its chain verifies
    /// from one of the caller's trusted roots
    /// (`delegation::verify_delegation_chain_with`).
    pub chain_valid: bool,
}

impl VerifyResult {
    pub fn is_valid(&self) -> bool {
        self.proof_valid && self.time_valid && self.chain_valid
    }
}

/// The issuer DID of a credential: the `issuer` string, or the `id` of an
/// issuer object.
pub fn issuer_did(credential: &Value) -> Option<&str> {
    match credential.get("issuer") {
        Some(Value::String(s)) if !s.is_empty() => Some(s.as_str()),
        Some(Value::Object(o)) => o
            .get("id")
            .and_then(|v| v.as_str())
            .filter(|s| !s.is_empty()),
        _ => None,
    }
}

/// True when one proof is bound to `issuer`: its proofPurpose is
/// "assertionMethod" and its verificationMethod names a key of the issuer's
/// DID (the part before '#' equals the issuer DID). Applies to every member of
/// a proof set.
pub fn proof_bound_to_issuer(proof: &Value, issuer: &str) -> bool {
    let Some(p) = proof.as_object() else {
        return false;
    };
    if p.get("proofPurpose").and_then(|v| v.as_str()) != Some("assertionMethod") {
        return false;
    }
    match p.get("verificationMethod").and_then(|v| v.as_str()) {
        Some(vm) if !vm.is_empty() => vm.split('#').next() == Some(issuer),
        _ => false,
    }
}

/// Refuse a credential whose `credentialSubject.vouchVersion` is missing or
/// not one of [`SUPPORTED_VOUCH_VERSIONS`].
pub fn check_vouch_version(credential: &Value) -> Result<()> {
    let version = credential
        .get("credentialSubject")
        .and_then(|s| s.get("vouchVersion"));
    match version.and_then(|v| v.as_str()) {
        Some(v) if SUPPORTED_VOUCH_VERSIONS.contains(&v) => Ok(()),
        Some(v) => Err(CoreError::Json(format!(
            "unsupported vouchVersion {:?}",
            v.chars().take(32).collect::<String>()
        ))),
        None => Err(CoreError::Json(
            "credentialSubject.vouchVersion is required".into(),
        )),
    }
}

/// Refuse a credential whose `credentialSubject.intent.resource` is missing,
/// not a string, or empty. The resource is a non-empty string naming what the
/// credential is for (Specification 5.4.1); relative names such as
/// "reports/q3.txt" are valid, so no URI syntax is required.
pub fn check_intent_resource(credential: &Value) -> Result<()> {
    let resource = credential
        .get("credentialSubject")
        .and_then(|s| s.get("intent"))
        .and_then(|i| i.get("resource"));
    match resource.and_then(|r| r.as_str()) {
        Some(r) if !r.is_empty() => Ok(()),
        _ => Err(CoreError::Json(
            "intent.resource is REQUIRED and must be a non-empty string".into(),
        )),
    }
}

/// Refuse a credential whose envelope is not a Vouch Credential: `@context` is
/// an array starting with the VC 2.0 context, `type` is an array holding
/// "VerifiableCredential" and "VouchCredential", and `credentialSubject` and
/// its `intent` are objects.
pub fn check_envelope(credential: &Value) -> Result<()> {
    let ctx_ok = credential
        .get("@context")
        .and_then(|c| c.as_array())
        .and_then(|c| c.first())
        .and_then(|c| c.as_str())
        == Some(VC_CONTEXT_V2);
    if !ctx_ok {
        return Err(CoreError::Json(
            "the credential's @context must start with the VC 2.0 context".into(),
        ));
    }
    let types_ok = credential
        .get("type")
        .and_then(|t| t.as_array())
        .map(|t| {
            [VC_TYPE, VOUCH_CREDENTIAL_TYPE]
                .iter()
                .all(|want| t.iter().any(|x| x.as_str() == Some(want)))
        })
        .unwrap_or(false);
    if !types_ok {
        return Err(CoreError::Json(
            "the credential's type must include VerifiableCredential and VouchCredential".into(),
        ));
    }
    let subject_ok = credential
        .get("credentialSubject")
        .map(|s| s.is_object() && s.get("intent").map(|i| i.is_object()).unwrap_or(false))
        .unwrap_or(false);
    if !subject_ok {
        return Err(CoreError::Json(
            "credentialSubject and its intent must be objects".into(),
        ));
    }
    Ok(())
}

/// A proof's own fields, checked before any signature: type
/// "DataIntegrityProof", a known cryptosuite, proofPurpose "assertionMethod",
/// a verificationMethod of the issuer's DID, a non-empty proofValue, and a
/// `created` (when present) in the time grammar. `Ok(false)` refuses the proof;
/// `Err` is a malformed time.
fn proof_fields_ok(proof: &Value, issuer: &str) -> Result<bool> {
    let Some(p) = proof.as_object() else {
        return Ok(false);
    };
    if p.get("type").and_then(|v| v.as_str()) != Some(data_integrity::PROOF_TYPE) {
        return Ok(false);
    }
    // The earlier composite proof (hybrid-eddsa-mldsa44-jcs-2026) is refused:
    // the post-quantum profile is a proof set of separate proofs only.
    let known = crate::hybrid::Suite::of_proof(proof).is_some();
    if !known || !proof_bound_to_issuer(proof, issuer) {
        return Ok(false);
    }
    let has_value = p
        .get("proofValue")
        .and_then(|v| v.as_str())
        .is_some_and(|v| !v.is_empty());
    if !has_value {
        return Ok(false);
    }
    if let Some(created) = p.get("created") {
        match created.as_str() {
            Some(c) => {
                parse_protocol_time_ns(c)?;
            }
            None => {
                return Err(CoreError::Json(
                    "proof.created must be a time string".into(),
                ))
            }
        }
    }
    Ok(true)
}

/// The replay key for a credential, the same in every language:
/// lowercase hex of `SHA-256(issuer UTF-8 || 0x00 || SHA-256(proofValue
/// UTF-8))`, where `proof_value` is the `proofValue` of the proof the verifier
/// checked (for a proof set, the Ed25519 proof). A DID never contains a NUL, so
/// the two parts cannot run together. The core is stateless: the caller keeps
/// the replay store and marks this key after a credential verifies.
pub fn replay_key(issuer: &str, proof_value: &str) -> Result<String> {
    use sha2::{Digest, Sha256};
    if issuer.is_empty() || proof_value.is_empty() {
        return Err(CoreError::Json(
            "issuer and proofValue must be non-empty strings".into(),
        ));
    }
    let inner = Sha256::digest(proof_value.as_bytes());
    let mut h = Sha256::new();
    h.update(issuer.as_bytes());
    h.update([0u8]);
    h.update(inner);
    Ok(h.finalize().iter().map(|b| format!("{b:02x}")).collect())
}

/// One proof member under the top-level rules ([`proof_fields_ok`]) plus its
/// `expires`, which must be a time string (null is not "absent") that has not
/// passed at `now` (with the skew). Used for grants and status lists.
pub(crate) fn proof_member_ok(proof: &Value, issuer: &str, now: i128, skew: i128) -> bool {
    if !matches!(proof_fields_ok(proof, issuer), Ok(true)) {
        return false;
    }
    match proof.get("expires") {
        None => true,
        Some(Value::String(e)) => match parse_protocol_time_ns(e) {
            Ok(t) => window_state_ns(now, None, Some(t), skew) == WindowState::Ok,
            Err(_) => false,
        },
        Some(_) => false,
    }
}

/// True when the key the caller supplied is the issuer's own key as far as
/// the core can tell offline: for a `did:key` issuer it must be exactly the key
/// the DID encodes. For other DID methods the caller resolved the key and the
/// proof's verificationMethod binding is checked instead.
fn key_matches_issuer(issuer: &str, raw_public_key: &[u8]) -> bool {
    if issuer.starts_with("did:key:") {
        return match crate::keys::did_key_to_ed25519(issuer) {
            Ok(k) => k.as_slice() == raw_public_key,
            Err(_) => false,
        };
    }
    true
}

/// Verify the Data Integrity proof, the validity window against `now_iso`, and
/// the embedded delegation chain (Specification 9.3).
///
/// A credential that carries a delegation chain is refused here
/// (`chain_valid` false) because no trusted starting point is named: use
/// [`verify_with_roots`] for those. A credential without a chain needs no
/// roots. Refused with an `Err`: a skew outside 0..120 seconds, a malformed
/// time, a missing or unsupported `vouchVersion`, or an `intent.resource` that
/// is missing or not a non-empty string.
///
/// `credentialStatus` is not checked here: call
/// [`crate::status_list::check_credential_status`] for that. The core keeps no
/// state, so replay protection is the caller's: keep a replay store keyed by
/// [`replay_key`].
pub fn verify(
    credential: &Value,
    raw_public_key: &[u8],
    now_iso: &str,
    clock_skew_seconds: i64,
) -> Result<VerifyResult> {
    let opts = crate::delegation::ChainOptions::default();
    Ok(verify_explained(
        credential,
        raw_public_key,
        now_iso,
        clock_skew_seconds,
        &opts,
    )?
    .0)
}

/// [`verify`] with the trusted starting points for a delegation chain: the
/// chain's first grant must be issued by one of `trusted_roots`. With an empty
/// list a credential carrying a chain is refused.
pub fn verify_with_roots(
    credential: &Value,
    raw_public_key: &[u8],
    now_iso: &str,
    clock_skew_seconds: i64,
    trusted_roots: &[String],
) -> Result<VerifyResult> {
    let opts = crate::delegation::ChainOptions {
        trusted_roots: Some(trusted_roots),
        ..Default::default()
    };
    Ok(verify_explained(
        credential,
        raw_public_key,
        now_iso,
        clock_skew_seconds,
        &opts,
    )?
    .0)
}

/// The full verifier: returns the [`VerifyResult`] and, when the chain is
/// refused, its reason. `opts` carries the trusted roots, grant keys for
/// non-`did:key` issuers, the post-quantum requirement and any explicit budget
/// (see [`crate::delegation::ChainOptions`]). The credential's own proof must
/// be a single `eddsa-jcs-2022` proof here; [`verify_with_keys`] also takes an
/// ML-DSA-44 key for a proof set.
pub fn verify_explained(
    credential: &Value,
    raw_public_key: &[u8],
    now_iso: &str,
    clock_skew_seconds: i64,
    opts: &crate::delegation::ChainOptions,
) -> Result<(VerifyResult, Option<String>)> {
    verify_with_keys(
        credential,
        raw_public_key,
        None,
        now_iso,
        clock_skew_seconds,
        opts,
    )
}

/// The top-level verifier for every proof shape a Vouch Credential carries:
///
/// * one `eddsa-jcs-2022` proof, verified with `ed25519_key` (refused when
///   post-quantum is required: a single classical proof does not meet it);
/// * a proof set of exactly one `eddsa-jcs-2022` proof and one proof of each
///   post-quantum suite it carries (ML-DSA-44 and/or SLH-DSA-SHA2-128s), all
///   verified ([`crate::hybrid::verify_set`]; needs `mldsa44_key` for an
///   ML-DSA-44 member and `opts.slhdsa128_key` for an SLH-DSA member).
///
/// The earlier composite `hybrid-eddsa-mldsa44-jcs-2026` proof is refused
/// (proofValid false), as is every single proof object that is not
/// `eddsa-jcs-2022`.
///
/// Before any signature: the envelope ([`check_envelope`]), the version
/// ([`check_vouch_version`]), the resource ([`check_intent_resource`]), an
/// issuer that is a DID, and every proof's own fields (type, a known
/// cryptosuite, proofPurpose "assertionMethod", a verificationMethod of the
/// issuer's DID). For a `did:key` issuer the Ed25519 key must be the one the DID
/// encodes. Then the window ([`verify_temporal`]) and the delegation chain
/// (which needs trusted roots, see [`verify_with_roots`]). The chain step
/// starts with the credential's own binding fields
/// ([`crate::grant_chain::binding_fields_problem`]): a `parentGrantDigest`
/// that is not a string, a `delegationChain` that is not a list, or a digest
/// together with a non-empty `delegationChain` gives `chain_valid` false with
/// the reason "malformed_delegation", whatever roots are named. A sub-grant (a
/// string digest and no chain) verifies on its own; whether it was made under
/// a trusted chain is checked with its grant chain.
///
/// Supplying `mldsa44_key` means the ML-DSA-44 proof is required for this
/// credential: it must be 1312 bytes (else an `Err`), and a single classical
/// proof, or a set without that proof, is refused. `opts.slhdsa128_key` (32
/// bytes, else an `Err`) does the same for the SLH-DSA proof. The keys apply
/// to this credential only; grants follow `opts` (their own post-quantum
/// keys, and `opts.require_pq`). Every trusted root
/// must be a DID or a domain name (else an `Err`). `credentialStatus` and replay
/// are the caller's to check, as for [`verify`].
pub fn verify_with_keys(
    credential: &Value,
    ed25519_key: &[u8],
    mldsa44_key: Option<&[u8]>,
    now_iso: &str,
    clock_skew_seconds: i64,
    opts: &crate::delegation::ChainOptions,
) -> Result<(VerifyResult, Option<String>)> {
    check_clock_skew(clock_skew_seconds)?;
    if let Some(ml) = mldsa44_key {
        if ml.len() != crate::pq::MLDSA44_PUBLIC_LEN {
            return Err(CoreError::InvalidKeyLength {
                expected: crate::pq::MLDSA44_PUBLIC_LEN,
                got: ml.len(),
            });
        }
    }
    if let Some(slh) = opts.slhdsa128_key {
        if slh.len() != crate::slh::SLHDSA128_PUBLIC_LEN {
            return Err(CoreError::InvalidKeyLength {
                expected: crate::slh::SLHDSA128_PUBLIC_LEN,
                got: slh.len(),
            });
        }
    }
    // A supplied post-quantum key means that suite's proof is required.
    verify_with_selected_keys(
        credential,
        Some(ed25519_key),
        mldsa44_key,
        opts.slhdsa128_key,
        crate::hybrid::Required {
            post_quantum: false,
            mldsa44: mldsa44_key.is_some(),
            slhdsa128: opts.slhdsa128_key.is_some(),
        },
        now_iso,
        clock_skew_seconds,
        opts,
    )
}

/// The verifier behind [`verify_with_keys`] and
/// [`verify_with_did_webvh_log`], once the issuer's keys are chosen: with no
/// Ed25519 key the proof is not valid, and `issuer_requires` refuses a proof
/// that lacks a suite the issuer's keys require.
#[allow(clippy::too_many_arguments)]
fn verify_with_selected_keys(
    credential: &Value,
    ed25519_key: Option<&[u8]>,
    mldsa44_key: Option<&[u8]>,
    slhdsa128_key: Option<&[u8]>,
    issuer_requires: crate::hybrid::Required,
    now_iso: &str,
    clock_skew_seconds: i64,
    opts: &crate::delegation::ChainOptions,
) -> Result<(VerifyResult, Option<String>)> {
    check_clock_skew(clock_skew_seconds)?;
    if let Some(roots) = opts.trusted_roots {
        for r in roots {
            crate::did_web::normalize_root(r)?;
        }
    }
    if !credential.is_object() {
        return Err(CoreError::Json("credential must be an object".into()));
    }
    check_envelope(credential)?;
    check_vouch_version(credential)?;
    check_intent_resource(credential)?;

    let issuer = issuer_did(credential).filter(|i| i.starts_with("did:") && i.len() > 4);
    let proof_valid = match (issuer, credential.get("proof")) {
        (Some(issuer), Some(proof)) => {
            let members: Vec<&Value> = match proof {
                Value::Array(items) => items.iter().collect(),
                other => vec![other],
            };
            let mut fields_ok = !members.is_empty();
            for m in &members {
                fields_ok = fields_ok && proof_fields_ok(m, issuer)?;
            }
            match ed25519_key {
                Some(ed) => {
                    fields_ok
                        && key_matches_issuer(issuer, ed)
                        && proof_shape_verifies(
                            credential,
                            proof,
                            ed,
                            mldsa44_key,
                            slhdsa128_key,
                            issuer_requires,
                            opts,
                        )?
                }
                // No key for the issuer: nothing to check the signature with.
                None => false,
            }
        }
        // No issuer DID to bind the proof to, or no proof.
        _ => false,
    };
    let time_valid = verify_temporal(credential, now_iso, clock_skew_seconds)?;
    let chain_reason = crate::delegation::verify_delegation_chain_with(
        credential,
        now_iso,
        clock_skew_seconds,
        opts,
    );
    Ok((
        VerifyResult {
            proof_valid,
            time_valid,
            chain_valid: chain_reason.is_none(),
        },
        chain_reason,
    ))
}

/// The outcome of [`verify_with_did_webvh_log`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DidWebvhVerifyOutcome {
    /// The verdict, as [`verify_with_keys`] gives it.
    pub result: VerifyResult,
    /// Why the delegation chain was refused, when it was.
    pub chain_reason: Option<String>,
    /// The issuer's log: its latest versionId (remember it as the version
    /// seen for this DID), or why it was refused (then the proof is not
    /// valid).
    pub log: std::result::Result<String, crate::did_webvh::DidWebvhError>,
    /// The logs of the grant issuers the delegation chain needed, by DID, as
    /// [`crate::did_webvh::LogSet::outcomes`] reports them (the issuer's own
    /// log is in `log`).
    pub grant_logs: std::collections::BTreeMap<
        String,
        std::result::Result<String, crate::did_webvh::DidWebvhError>,
    >,
}

/// The verificationMethods a credential's (or a grant's) proof names, by
/// suite (only the Ed25519 one for a single classical proof).
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub(crate) struct ProofMethods {
    pub ed25519: Option<String>,
    pub mldsa44: Option<String>,
    pub slhdsa128: Option<String>,
}

pub(crate) fn proof_methods(credential: &Value) -> ProofMethods {
    use crate::hybrid::Suite;
    let vm = |p: &Value| {
        p.get("verificationMethod")
            .and_then(Value::as_str)
            .map(str::to_string)
    };
    match credential.get("proof") {
        Some(p @ Value::Object(_)) if Suite::of_proof(p) == Some(Suite::Eddsa) => ProofMethods {
            ed25519: vm(p),
            ..Default::default()
        },
        Some(Value::Array(items)) => {
            let first = |suite: Suite| {
                items
                    .iter()
                    .find(|p| Suite::of_proof(p) == Some(suite))
                    .and_then(vm)
            };
            ProofMethods {
                ed25519: first(Suite::Eddsa),
                mldsa44: first(Suite::Mldsa44),
                slhdsa128: first(Suite::Slhdsa128),
            }
        }
        _ => ProofMethods::default(),
    }
}

/// Verify a credential whose issuer is a did:webvh DID, with the did:webvh
/// logs the caller fetched: the core keeps no state and never fetches, so the
/// caller fetches each log from [`crate::did_webvh::log_url`], puts it in
/// `logs` with the latest versionId it saw before for that DID, and
/// remembers the versions the outcome reports.
///
/// The issuer's log must be in `logs` (else an `Err`). It is verified in full
/// ([`crate::did_webvh::verify_log`], always the latest entry) against the
/// set's clock, which is the system clock unless the caller fixed it
/// ([`crate::did_webvh::LogClock`]): the credential's `now_iso` decides its
/// own validity window, never whether a log entry is dated in the future.
/// The issuer's keys come from the latest state with the rules of
/// [`crate::did_document::assertion_key`]: the state's id is exactly the
/// issuer, and the key the proof names is the issuer's own, listed in
/// assertionMethod. When the state lists an ML-DSA-44 key for assertions,
/// the post-quantum proof is required, so it cannot be dropped from a
/// credential. The same holds for an SLH-DSA-SHA2-128s assertion key and the
/// SLH-DSA proof. A refused or deactivated log gives no key, so the proof is
/// not valid.
///
/// The delegation chain's did:webvh grant issuers resolve the same way from
/// `logs` (see [`crate::delegation::ChainOptions::grant_logs`]; the set given
/// here is used in place of `opts.grant_logs`). Everything else is as
/// [`verify_with_keys`].
///
/// Errors (as for [`verify_with_keys`]) on a malformed request, when the
/// credential's issuer is not a did:webvh DID, and when `logs` holds no log
/// for it.
pub fn verify_with_did_webvh_log(
    credential: &Value,
    logs: &crate::did_webvh::LogSet,
    now_iso: &str,
    clock_skew_seconds: i64,
    opts: &crate::delegation::ChainOptions,
) -> Result<DidWebvhVerifyOutcome> {
    check_clock_skew(clock_skew_seconds)?;
    parse_protocol_time_ns(now_iso)?;
    let issuer = issuer_did(credential)
        .filter(|i| crate::did_webvh::is_did_webvh(i))
        .ok_or_else(|| {
            CoreError::InvalidDid("the credential's issuer is not a did:webvh DID".into())
        })?
        .to_string();
    let resolved = logs
        .resolve(&issuer)
        .ok_or_else(|| CoreError::Json("there is no log for the credential's issuer".into()))?;
    let keys = match &resolved {
        Ok(resolution) => {
            let methods = proof_methods(credential);
            crate::did_document::proof_keys_for(
                &resolution.document,
                &issuer,
                crate::did_document::ProofMethodRefs {
                    ed25519: methods.ed25519.as_deref(),
                    mldsa44: methods.mldsa44.as_deref(),
                    slhdsa128: methods.slhdsa128.as_deref(),
                },
            )
        }
        Err(_) => crate::did_document::ProofKeys::default(),
    };
    let chain = crate::delegation::ChainOptions {
        grant_logs: Some(logs),
        ..*opts
    };
    let (result, chain_reason) = verify_with_selected_keys(
        credential,
        keys.ed25519.as_deref(),
        keys.mldsa44.as_deref(),
        keys.slhdsa128.as_deref(),
        keys.required(),
        now_iso,
        clock_skew_seconds,
        &chain,
    )?;
    let mut grant_logs = logs.outcomes();
    grant_logs.remove(&issuer);
    Ok(DidWebvhVerifyOutcome {
        result,
        chain_reason,
        log: resolved.map(|r| r.latest_version_id),
        grant_logs,
    })
}

/// [`verify_request_json_with_clock`], with did:webvh logs checked against
/// the system clock.
pub fn verify_request_json(request: &Value) -> Result<Value> {
    verify_request_json_with_clock(request, crate::did_webvh::LogClock::System)
}

/// [`verify_with_keys`] as one JSON request, for a credential whose issuer's
/// keys the caller already holds, with the delegation chain's grant keys kept
/// apart from its trusted roots and the did:webvh logs of grant issuers.
///
/// The request is `{"credential", "publicKey", "mldsa44PublicKey",
/// "slhdsa128PublicKey"}` plus the chain and log members every verify request
/// shares (`now`, `clockSkewSeconds`, `trustedRoots`, `requirePostQuantum`,
/// `grantKeys`, `grantMldsa44Keys`, `grantSlhdsa128Keys`, `grantLogs`, `grantLogsB64`, `grantSeenVersionIds`,
/// `limits`, `logNow`; see [`crate::did_webvh::verify_credential_json`]):
///
/// - `credential`: the credential, a JSON object;
/// - `publicKey`: the issuer's Ed25519 key (base64, 32 bytes);
/// - `mldsa44PublicKey` (optional): the issuer's ML-DSA-44 key (base64,
///   1312 bytes). Giving it requires the ML-DSA-44 proof on this
///   credential, as for [`verify_with_keys`];
/// - `slhdsa128PublicKey` (optional): the issuer's SLH-DSA-SHA2-128s key
///   (base64, 32 bytes). Giving it requires the SLH-DSA proof on this
///   credential.
///
/// A key in `grantKeys` resolves a grant's signature only: unlike the root
/// keys of the fleet entry points, it never makes its DID a trusted root. A
/// did:webvh grant issuer with no key there takes its keys from its log in
/// `grantLogs` (see [`crate::delegation::ChainOptions::grant_logs`]), checked
/// against `logNow` when the request gives one, else against `clock`.
///
/// Returns `{"proofValid", "timeValid", "chainValid", "valid",
/// "chainReason", "grantVersionIds", "grantLogErrors"}`: the last two give,
/// by DID, the latest versionId of each grant issuer's log the chain needed
/// (remember it as the version seen) or why it was refused. Errors on a
/// malformed request.
pub fn verify_request_json_with_clock(
    request: &Value,
    clock: crate::did_webvh::LogClock,
) -> Result<Value> {
    use crate::did_webvh::{base64_decode, grant_log_json, read_chain_request, request_object};

    let mut allowed = vec![
        "credential",
        "publicKey",
        "mldsa44PublicKey",
        "slhdsa128PublicKey",
    ];
    allowed.extend(crate::did_webvh::CHAIN_REQUEST_MEMBERS);
    let obj = request_object(request, &allowed)?;
    let credential = obj
        .get("credential")
        .filter(|c| c.is_object())
        .ok_or_else(|| CoreError::Json("credential must be a JSON object".into()))?;
    let public_key = obj
        .get("publicKey")
        .and_then(Value::as_str)
        .ok_or_else(|| CoreError::Json("publicKey must be a base64 Ed25519 key".into()))?;
    let public_key = base64_decode(public_key, "publicKey")?;
    let mldsa44_key = match obj.get("mldsa44PublicKey") {
        None | Some(Value::Null) => None,
        Some(Value::String(b64)) => Some(base64_decode(b64, "mldsa44PublicKey")?),
        Some(_) => {
            return Err(CoreError::Json(
                "mldsa44PublicKey must be a base64 ML-DSA-44 key".into(),
            ))
        }
    };
    let slhdsa128_key = match obj.get("slhdsa128PublicKey") {
        None | Some(Value::Null) => None,
        Some(Value::String(b64)) => Some(base64_decode(b64, "slhdsa128PublicKey")?),
        Some(_) => {
            return Err(CoreError::Json(
                "slhdsa128PublicKey must be a base64 SLH-DSA-SHA2-128s key".into(),
            ))
        }
    };
    let request = read_chain_request(obj, clock)?;
    let chain = crate::delegation::ChainOptions {
        trusted_roots: request.roots.as_deref(),
        grant_keys: request.grant_keys.as_ref(),
        mldsa_keys: request.grant_mldsa_keys.as_ref(),
        slhdsa_keys: request.grant_slhdsa_keys.as_ref(),
        slhdsa128_key: slhdsa128_key.as_deref(),
        require_pq: request.require_pq,
        grant_logs: Some(&request.logs),
        ..Default::default()
    };
    let (r, chain_reason) = verify_with_keys(
        credential,
        &public_key,
        mldsa44_key.as_deref(),
        &request.now,
        request.skew,
        &chain,
    )?;
    let (grant_versions, grant_errors) = grant_log_json(&request.logs.outcomes());
    Ok(serde_json::json!({
        "proofValid": r.proof_valid,
        "timeValid": r.time_valid,
        "chainValid": r.chain_valid,
        "valid": r.is_valid(),
        "chainReason": chain_reason,
        "grantVersionIds": grant_versions,
        "grantLogErrors": grant_errors,
    }))
}

/// Verify the credential's proof by its shape (see [`verify_with_keys`]).
fn proof_shape_verifies(
    credential: &Value,
    proof: &Value,
    ed25519_key: &[u8],
    mldsa44_key: Option<&[u8]>,
    slhdsa128_key: Option<&[u8]>,
    issuer_requires: crate::hybrid::Required,
    opts: &crate::delegation::ChainOptions,
) -> Result<bool> {
    use crate::hybrid::Suite;
    let required = crate::hybrid::Required {
        post_quantum: issuer_requires.post_quantum || opts.require_pq,
        ..issuer_requires
    };
    match proof {
        // One proof object is an eddsa-jcs-2022 proof or nothing: a
        // post-quantum proof needs its eddsa-jcs-2022 partner in a set, and
        // the earlier composite proof is refused.
        Value::Object(_) => {
            if Suite::of_proof(proof) != Some(Suite::Eddsa) || required.any() {
                return Ok(false);
            }
            data_integrity::verify_proof(credential, ed25519_key)
        }
        Value::Array(items) => {
            let Some(members) = crate::hybrid::set_members(items) else {
                return Ok(false); // not one Ed25519 proof plus post-quantum proofs
            };
            if !required.met_by(&members.suites()) {
                return Ok(false);
            }
            crate::hybrid::verify_set(credential, ed25519_key, mldsa44_key, slhdsa128_key)
        }
        _ => Ok(false),
    }
}

/// Check that `now_iso` falls within [validFrom, validUntil] allowing
/// `clock_skew_seconds` of drift at each edge, at full fraction precision
/// ([`crate::time`]). An inverted window (validFrom after validUntil) is never
/// valid, and neither is a proof past its own `expires`. Errors on a missing
/// or malformed time and on a skew outside 0..120 seconds.
pub fn verify_temporal(credential: &Value, now_iso: &str, clock_skew_seconds: i64) -> Result<bool> {
    let skew = check_clock_skew(clock_skew_seconds)?;
    let obj = credential
        .as_object()
        .ok_or_else(|| CoreError::Json("credential must be an object".into()))?;
    let vf = obj
        .get("validFrom")
        .and_then(|v| v.as_str())
        .ok_or_else(|| CoreError::Json("credential missing validFrom".into()))?;
    let vu = obj
        .get("validUntil")
        .and_then(|v| v.as_str())
        .ok_or_else(|| CoreError::Json("credential missing validUntil".into()))?;
    let now = parse_protocol_time_ns(now_iso)?;
    let from = parse_protocol_time_ns(vf)?;
    let until = parse_protocol_time_ns(vu)?;
    if window_state_ns(now, Some(from), Some(until), skew) != WindowState::Ok {
        return Ok(false);
    }
    // A proof may carry its own `expires`: past it, the proof no longer
    // speaks for the credential.
    let proofs: Vec<&Value> = match obj.get("proof") {
        Some(Value::Array(items)) => items.iter().collect(),
        Some(p) => vec![p],
        None => Vec::new(),
    };
    for p in proofs {
        match p.get("expires") {
            None => {}
            Some(Value::String(e)) => {
                let expires = parse_protocol_time_ns(e)?;
                if window_state_ns(now, None, Some(expires), skew) != WindowState::Ok {
                    return Ok(false);
                }
            }
            Some(_) => {
                return Err(CoreError::Json(
                    "proof.expires must be a time string".into(),
                ))
            }
        }
    }
    Ok(true)
}

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

    fn opts() -> BuildCredentialOptions {
        BuildCredentialOptions {
            issuer_did: "did:web:agent.example.com".into(),
            credential_id: "urn:uuid:00000000-0000-4000-8000-000000000000".into(),
            intent: json!({
                "action": "read_database",
                "target": "users_table",
                "resource": "https://api.example.com/v1/users"
            }),
            valid_from: "2026-04-26T10:00:00Z".into(),
            valid_until: "2026-04-26T10:05:00Z".into(),
            reputation_score: Some(150),
            delegation_chain: None,
            credential_status: None,
        }
    }

    #[test]
    fn builds_expected_shape() {
        let vc = build_vouch_credential(&opts()).unwrap();
        assert_eq!(
            vc["type"],
            json!(["VerifiableCredential", "VouchCredential"])
        );
        assert_eq!(vc["credentialSubject"]["vouchVersion"], json!("1.0"));
        // reputationScore clamps to 100.
        assert_eq!(vc["credentialSubject"]["reputationScore"], json!(100));
    }

    #[test]
    fn rejects_missing_intent_fields() {
        let mut o = opts();
        o.intent = json!({ "action": "read", "target": "t" }); // no resource
        assert!(build_vouch_credential(&o).is_err());
    }

    #[test]
    fn sub_grant_names_its_parent_one_way_only() {
        let digest = "uEiCJcGBDXiN3XLgg5yQXBbX0UV019vMoX1n9_Ttuka1VAQ";
        let sub = build_sub_grant(&opts(), digest).unwrap();
        assert_eq!(sub["credentialSubject"]["parentGrantDigest"], json!(digest));
        assert!(sub["credentialSubject"].get("delegationChain").is_none());
        // Written after reputationScore, as the reference builder does.
        let keys: Vec<&str> = sub["credentialSubject"]
            .as_object()
            .unwrap()
            .keys()
            .map(|k| k.as_str())
            .collect();
        assert_eq!(
            keys,
            [
                "id",
                "vouchVersion",
                "intent",
                "reputationScore",
                "parentGrantDigest"
            ]
        );
        assert!(build_vouch_credential(&opts())
            .unwrap()
            .pointer("/credentialSubject/parentGrantDigest")
            .is_none());
        assert_eq!(
            build_sub_grant(&opts(), "").unwrap_err().to_string(),
            "json error: parent_grant_digest must be a grant digest string"
        );
        let mut both = opts();
        both.delegation_chain = Some(json!([{"issuer": "did:web:a"}]));
        assert_eq!(
            build_sub_grant(&both, digest).unwrap_err().to_string(),
            "json error: a credential carries parentGrantDigest or a delegationChain, never both"
        );
        // An empty chain is no chain.
        both.delegation_chain = Some(json!([]));
        assert!(build_sub_grant(&both, digest).is_ok());
        // The intent is still checked first.
        let mut bad = opts();
        bad.intent = json!({ "action": "read" });
        assert!(build_sub_grant(&bad, "")
            .unwrap_err()
            .to_string()
            .contains("intent."));
        let seed = [5u8; 32];
        let signed = sign_sub_grant(
            &opts(),
            digest,
            &seed,
            &BuildProofOptions::new("did:web:agent.example.com#key-1", "2026-04-26T10:00:00Z"),
        )
        .unwrap();
        let pk = crate::keys::Ed25519KeyPair::from_seed(&seed).public_key();
        assert!(verify(&signed, &pk, "2026-04-26T10:02:00Z", 30)
            .unwrap()
            .is_valid());
    }

    #[test]
    fn own_binding_fields_are_checked_on_every_verify_path() {
        let seed = [5u8; 32];
        let po = BuildProofOptions::new("did:web:agent.example.com#key-1", "2026-04-26T10:00:00Z");
        let with = |fields: Value| {
            let mut c = build_vouch_credential(&opts()).unwrap();
            for (k, v) in fields.as_object().unwrap() {
                c["credentialSubject"][k] = v.clone();
            }
            data_integrity::sign(&c, &seed, &po).unwrap()
        };
        let roots = ["did:web:root.example".to_string()];
        let with_roots = crate::delegation::ChainOptions {
            trusted_roots: Some(&roots),
            ..Default::default()
        };
        let none = crate::delegation::ChainOptions::default();
        // (chain_valid, reason) from each verify path.
        let every_path = |c: &Value| {
            let mut out = Vec::new();
            for r in [
                verify(c, &pk(), NOW, 30).unwrap(),
                verify_with_roots(c, &pk(), NOW, 30, &roots).unwrap(),
            ] {
                assert!(r.proof_valid && r.time_valid);
                out.push((r.chain_valid, None));
            }
            for o in [&none, &with_roots] {
                let (r, reason) = verify_explained(c, &pk(), NOW, 30, o).unwrap();
                assert!(r.proof_valid && r.time_valid);
                out.push((r.chain_valid, reason.clone()));
                let (r, reason2) = verify_with_keys(c, &pk(), None, NOW, 30, o).unwrap();
                assert_eq!(reason2, reason);
                out.push((r.chain_valid, reason2));
                out.push((
                    reason.is_none(),
                    crate::delegation::verify_delegation_chain_with(c, NOW, 30, o),
                ));
            }
            out
        };
        let malformed = Some("malformed_delegation".to_string());
        let digest = "uEiCJcGBDXiN3XLgg5yQXBbX0UV019vMoX1n9_Ttuka1VAQ";
        for fields in [
            json!({"parentGrantDigest": null}),
            json!({"parentGrantDigest": 5}),
            json!({"parentGrantDigest": ["u"]}),
            json!({"parentGrantDigest": {}}),
            json!({"delegationChain": null}),
            json!({"delegationChain": {}}),
            json!({"parentGrantDigest": digest, "delegationChain": [{"issuer": "did:web:a"}]}),
            json!({"parentGrantDigest": null, "delegationChain": [{"issuer": "did:web:a"}]}),
        ] {
            for (i, (chain_valid, reason)) in
                every_path(&with(fields.clone())).into_iter().enumerate()
            {
                assert!(!chain_valid, "{fields} path {i}");
                if i >= 2 {
                    assert_eq!(reason, malformed, "{fields} path {i}");
                }
            }
        }
        // A sub-grant on its own (a string digest, no chain) verifies, with or
        // without roots; so does one with an empty chain.
        for fields in [
            json!({ "parentGrantDigest": digest }),
            json!({"parentGrantDigest": digest, "delegationChain": []}),
        ] {
            for (i, (chain_valid, reason)) in
                every_path(&with(fields.clone())).into_iter().enumerate()
            {
                assert!(chain_valid, "{fields} path {i}");
                assert_eq!(reason, None, "{fields} path {i}");
            }
        }
    }

    #[test]
    fn sign_and_verify_within_window() {
        let seed = [5u8; 32];
        let proof_opts =
            BuildProofOptions::new("did:web:agent.example.com#key-1", "2026-04-26T10:00:00Z");
        let signed = sign_vouch_credential(&opts(), &seed, &proof_opts).unwrap();
        let pk = crate::keys::Ed25519KeyPair::from_seed(&seed).public_key();
        let r = verify(&signed, &pk, "2026-04-26T10:02:00Z", 30).unwrap();
        assert!(r.is_valid());
        // Expired.
        let r2 = verify(&signed, &pk, "2026-04-26T11:00:00Z", 30).unwrap();
        assert!(r2.proof_valid && !r2.time_valid);
    }

    fn signed_with(purpose: &str, vm: &str) -> Value {
        let seed = [5u8; 32];
        let mut proof_opts = BuildProofOptions::new(vm, "2026-04-26T10:00:00Z");
        proof_opts.proof_purpose = purpose.into();
        sign_vouch_credential(&opts(), &seed, &proof_opts).unwrap()
    }

    fn pk() -> [u8; 32] {
        crate::keys::Ed25519KeyPair::from_seed(&[5u8; 32]).public_key()
    }

    const NOW: &str = "2026-04-26T10:02:00Z";

    #[test]
    fn proof_must_be_an_assertion_by_the_issuer() {
        let ok = signed_with("assertionMethod", "did:web:agent.example.com#key-1");
        assert!(verify(&ok, &pk(), NOW, 30).unwrap().is_valid());
        let auth = signed_with("authentication", "did:web:agent.example.com#key-1");
        assert!(!verify(&auth, &pk(), NOW, 30).unwrap().proof_valid);
        let other = signed_with("assertionMethod", "did:web:other.example.com#key-1");
        assert!(!verify(&other, &pk(), NOW, 30).unwrap().proof_valid);
        let prefix = signed_with("assertionMethod", "did:web:agent.example.com.evil#key-1");
        assert!(!verify(&prefix, &pk(), NOW, 30).unwrap().proof_valid);
    }

    #[test]
    fn did_key_issuer_must_be_the_signing_key() {
        let seed = [6u8; 32];
        let kp = crate::keys::Ed25519KeyPair::from_seed(&seed);
        let did = kp.did_key();
        let mut o = opts();
        o.issuer_did = did.clone();
        let vm = format!("{did}#{}", did.trim_start_matches("did:key:"));
        let signed = sign_vouch_credential(
            &o,
            &seed,
            &BuildProofOptions::new(vm, "2026-04-26T10:00:00Z"),
        )
        .unwrap();
        assert!(verify(&signed, &kp.public_key(), NOW, 30)
            .unwrap()
            .is_valid());
        // The same credential re-signed by another key that claims the DID.
        let other = [7u8; 32];
        let vm = format!("{did}#{}", did.trim_start_matches("did:key:"));
        let impostor = sign_vouch_credential(
            &o,
            &other,
            &BuildProofOptions::new(vm, "2026-04-26T10:00:00Z"),
        )
        .unwrap();
        let other_pk = crate::keys::Ed25519KeyPair::from_seed(&other).public_key();
        assert!(!verify(&impostor, &other_pk, NOW, 30).unwrap().proof_valid);
    }

    #[test]
    fn vouch_version_and_resource_are_required() {
        let ok = signed_with("assertionMethod", "did:web:agent.example.com#key-1");
        for (path, value) in [
            ("vouchVersion", Value::Null),
            ("vouchVersion", json!("2.0")),
            ("vouchVersion", json!(1.0)),
        ] {
            let mut c = ok.clone();
            if value.is_null() {
                c["credentialSubject"].as_object_mut().unwrap().remove(path);
            } else {
                c["credentialSubject"][path] = value;
            }
            assert!(verify(&c, &pk(), NOW, 30).is_err(), "{path}");
        }
        for bad in [json!(""), json!(42), Value::Null, json!(["https://x"])] {
            let mut c = ok.clone();
            c["credentialSubject"]["intent"]["resource"] = bad.clone();
            assert!(verify(&c, &pk(), NOW, 30).is_err(), "{bad}");
        }
        // A relative name is a valid resource (it is signed, so re-sign it).
        let mut o = opts();
        o.intent["resource"] = json!("reports/q3.txt");
        let signed = sign_vouch_credential(
            &o,
            &[5u8; 32],
            &BuildProofOptions::new("did:web:agent.example.com#key-1", "2026-04-26T10:00:00Z"),
        )
        .unwrap();
        assert!(verify(&signed, &pk(), NOW, 30).unwrap().is_valid());
    }

    #[test]
    fn window_rules() {
        let ok = signed_with("assertionMethod", "did:web:agent.example.com#key-1");
        // A skew outside 0..120 seconds is refused, never wrapped.
        for skew in [-1, 121, i64::MAX, i64::MIN] {
            assert!(verify(&ok, &pk(), NOW, skew).is_err(), "{skew}");
            assert!(verify_temporal(&ok, NOW, skew).is_err(), "{skew}");
        }
        // A naive or loose `now` is refused.
        for now in [
            "2026-04-26T10:02:00",
            "2026-04-26 10:02:00Z",
            "2026-04-26t10:02:00z",
        ] {
            assert!(verify_temporal(&ok, now, 30).is_err(), "{now}");
        }
        // Fractions count: one nanosecond past validUntil is expired at skew 0.
        assert!(verify_temporal(&ok, "2026-04-26T10:05:00Z", 0).unwrap());
        assert!(!verify_temporal(&ok, "2026-04-26T10:05:00.000000001Z", 0).unwrap());
        // An inverted window is never valid.
        let inverted =
            json!({"validFrom": "2026-04-26T10:05:00Z", "validUntil": "2026-04-26T10:00:00Z"});
        assert!(!verify_temporal(&inverted, "2026-04-26T10:02:00Z", 120).unwrap());
        // A proof past its own `expires` no longer speaks for the credential.
        let mut c = json!({"validFrom": "2026-04-26T10:00:00Z", "validUntil": "2026-04-26T10:05:00Z",
                           "proof": {"expires": "2026-04-26T10:01:00Z"}});
        assert!(!verify_temporal(&c, NOW, 30).unwrap());
        c["proof"]["expires"] = json!("2026-04-26T10:03:00Z");
        assert!(verify_temporal(&c, NOW, 30).unwrap());
        c["proof"]["expires"] = json!(5);
        assert!(verify_temporal(&c, NOW, 30).is_err());
    }

    #[test]
    fn proof_context_must_match_the_document() {
        let mut c = signed_with("assertionMethod", "did:web:agent.example.com#key-1");
        c["proof"]["@context"] = json!(["https://example.com/other"]);
        assert!(!verify(&c, &pk(), NOW, 30).unwrap().proof_valid);
    }

    #[test]
    fn issuer_object_is_bound_by_its_id() {
        let mut o = opts();
        o.issuer_did = "did:web:agent.example.com".into();
        let mut cred = build_vouch_credential(&o).unwrap();
        cred["issuer"] = json!({"id": "did:web:agent.example.com", "name": "Agent"});
        let signed = data_integrity::sign(
            &cred,
            &[5u8; 32],
            &BuildProofOptions::new("did:web:agent.example.com#key-1", "2026-04-26T10:00:00Z"),
        )
        .unwrap();
        assert!(verify(&signed, &pk(), NOW, 30).unwrap().is_valid());
        let mut bad = cred.clone();
        bad["issuer"] = json!(["did:web:agent.example.com"]);
        let signed = data_integrity::sign(
            &bad,
            &[5u8; 32],
            &BuildProofOptions::new("did:web:agent.example.com#key-1", "2026-04-26T10:00:00Z"),
        )
        .unwrap();
        assert!(!verify(&signed, &pk(), NOW, 30).unwrap().proof_valid);
    }

    #[test]
    fn envelope_must_be_a_vouch_credential() {
        let ok = signed_with("assertionMethod", "did:web:agent.example.com#key-1");
        for (key, value) in [
            ("@context", Value::Null),
            ("@context", json!("https://www.w3.org/ns/credentials/v2")),
            ("@context", json!(["https://example.com/other"])),
            ("type", json!(["VerifiableCredential"])),
            ("type", json!("VouchCredential")),
        ] {
            let mut c = ok.clone();
            if value.is_null() {
                c.as_object_mut().unwrap().remove(key);
            } else {
                c[key] = value.clone();
            }
            assert!(verify(&c, &pk(), NOW, 30).is_err(), "{key} = {value}");
        }
        // An issuer that is not a DID is never bound.
        let mut o = opts();
        o.issuer_did = "agent.example.com".into();
        let signed = sign_vouch_credential(
            &o,
            &[5u8; 32],
            &BuildProofOptions::new("agent.example.com#key-1", "2026-04-26T10:00:00Z"),
        )
        .unwrap();
        assert!(!verify(&signed, &pk(), NOW, 30).unwrap().proof_valid);
        // A malformed proof.created is refused.
        let mut c = ok.clone();
        c["proof"]["created"] = json!("yesterday");
        assert!(verify(&c, &pk(), NOW, 30).is_err());
    }

    #[test]
    fn every_proof_shape_through_one_verifier() {
        use crate::delegation::ChainOptions;
        let seed = [5u8; 32];
        let ml = crate::pq::MlDsa44KeyPair::generate().unwrap();
        let unsigned = build_vouch_credential(&opts()).unwrap();
        let dual = crate::hybrid::sign_dual(
            &unsigned,
            &seed,
            &ml,
            "did:web:agent.example.com#key-1",
            "did:web:agent.example.com#key-2",
            "2026-04-26T10:00:00Z",
        )
        .unwrap();
        let none = ChainOptions::default();
        let pq = ChainOptions {
            require_pq: true,
            ..Default::default()
        };
        let mlk = ml.public_key();
        let run = |c: &Value, ml: Option<&[u8]>, o: &ChainOptions| {
            verify_with_keys(c, &pk(), ml, NOW, 30, o).unwrap().0
        };
        assert!(run(&dual, Some(&mlk), &none).is_valid());
        assert!(run(&dual, Some(&mlk), &pq).is_valid());
        // A proof set without the ML-DSA key, or through the Ed25519-only form.
        assert!(!run(&dual, None, &none).proof_valid);
        assert!(!verify(&dual, &pk(), NOW, 30).unwrap().proof_valid);
        // A single classical proof does not meet the post-quantum profile, and
        // supplying an ML-DSA-44 key means post-quantum is required.
        let single = signed_with("assertionMethod", "did:web:agent.example.com#key-1");
        assert!(run(&single, None, &none).is_valid());
        assert!(!run(&single, None, &pq).proof_valid);
        assert!(!run(&single, Some(&mlk), &none).proof_valid);
        // The ML-DSA-44 key must be 1312 bytes.
        assert!(verify_with_keys(&dual, &pk(), Some(&mlk[..1311]), NOW, 30, &none).is_err());
        // Every trusted root must be a DID or a domain name.
        let bad_roots = vec!["127.0.0.1".to_string()];
        let with_bad = ChainOptions {
            trusted_roots: Some(&bad_roots),
            ..Default::default()
        };
        assert!(verify_with_keys(&single, &pk(), None, NOW, 30, &with_bad).is_err());
        // The ML-DSA member alone, or the set with an extra member.
        let mut lone = dual.clone();
        lone["proof"] = dual["proof"][1].clone();
        assert!(!run(&lone, Some(&mlk), &none).proof_valid);
        let mut extra = dual.clone();
        extra["proof"]
            .as_array_mut()
            .unwrap()
            .push(dual["proof"][0].clone());
        assert!(!run(&extra, Some(&mlk), &none).proof_valid);
        // An unknown cryptosuite in the set is refused at the top level.
        let mut unknown = dual.clone();
        let mut odd = dual["proof"][0].clone();
        odd["cryptosuite"] = json!("some-unregistered-suite-2030");
        unknown["proof"].as_array_mut().unwrap().push(odd);
        assert!(!run(&unknown, Some(&mlk), &none).proof_valid);
    }

    #[test]
    fn replay_key_is_issuer_nul_and_proof_digest() {
        use sha2::{Digest, Sha256};
        let k = replay_key("did:web:a.example", "z3abc").unwrap();
        let mut h = Sha256::new();
        h.update(b"did:web:a.example\x00");
        h.update(Sha256::digest(b"z3abc"));
        let want: String = h.finalize().iter().map(|b| format!("{b:02x}")).collect();
        assert_eq!(k, want);
        assert_eq!(k.len(), 64);
        assert!(replay_key("", "z3abc").is_err());
        assert!(replay_key("did:web:a.example", "").is_err());
        // The NUL keeps the two parts apart.
        assert_ne!(
            replay_key("did:web:a", "bc").unwrap(),
            replay_key("did:web:ab", "c").unwrap()
        );
    }
}