vta-vault 0.6.2

VTA holder credential vault — storage, query, receive/verify, present, and status refresh for credentials a holder stores on a VTA
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
//! Receive a credential into the VTA vault (task 1.2,
//! `docs/05-design-notes/vti-credential-architecture.md` §5 "Receive").
//!
//! This is the **write path** of the credential vault: it takes an incoming
//! SD-JWT-VC, verifies it **minimally** (issuer signature + temporal
//! validity), maps the verified claims into a [`StoredCredential`] envelope,
//! and stores + indexes it via the storage layer ([`super::storage`]).
//!
//! ## Scope (deliberately minimal — spec §5 "verify minimally")
//!
//! Receive verifies exactly two things, and **rejects-without-storing** on
//! either failure:
//! 1. **Issuer signature.** The SD-JWT's issuer JWS is verified against the
//!    Ed25519 key resolved from the credential's own `iss` DID (`did:key`).
//!    A tampered signature never produces verified claims, so a forged
//!    credential cannot reach the store.
//! 2. **Temporal validity.** `affinidi_sd_jwt_vc::verify_temporal` over the
//!    *verified* claims — `iat` not in the future, `exp` not in the past,
//!    `nbf` not in the future. An expired credential is rejected.
//!
//! Everything else the broader architecture eventually checks — schema
//! validation (§8), issuer-trust policy (§14.6), status-list revocation
//! (§14.5), holder binding (§14.4, a *presentation*-time concern) — is **out
//! of scope for receive** and lands in later tasks. `status` is therefore set
//! to [`CredentialStatus::Valid`] only in the narrow "passed signature +
//! temporal" sense; task 1.6 resolves real revocation state.
//!
//! ## Security invariants upheld here (spec §14)
//! - **Reject-before-store.** The verification result is the *only* path to a
//!   [`StoredCredential`]: claims are read from the verified result, never
//!   from the unverified payload. A tampered or expired credential returns an
//!   `Err` and **nothing is written** — there is no partial-store window
//!   (`storage::put` is the single, final side effect, reached only after
//!   both checks pass).
//! - **No enumeration.** This module only *writes*; it adds no list/scan
//!   surface (spec §14.1). Discovery stays the targeted index scan from task
//!   1.1.
//! - **Input validation.** The compact serialization is parsed and the issuer
//!   DID is resolved before any trust is placed in the bytes; a malformed
//!   credential, an `iss` that is not a resolvable `did:key`, or a missing
//!   `iss` all fail closed.
//!
//! ## What this module does NOT do
//! It pulls in **no BBS** (`affinidi-bbs` is audit-gated; BBS receive is a
//! later task) and adds **no route / DIDComm handler** — the credential vault
//! exposes no wire surface yet, so receive is a library operation only.

use affinidi_data_integrity::{DataIntegrityProof, VerifyOptions, crypto_suites::CryptoSuite};
use affinidi_sd_jwt::SdJwt;
use affinidi_sd_jwt::hasher::Sha256Hasher;
use affinidi_sd_jwt::signer::JwtVerifier;
use affinidi_sd_jwt::verifier::{VerificationOptions, verify};
use base64::Engine;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use chrono::{DateTime, Utc};
use ed25519_dalek::{Signature, Verifier, VerifyingKey};
use serde_json::Value;
use vti_common::error::AppError;
use vti_common::store::KeyspaceHandle;

use super::model::{CredentialFormat, CredentialPurpose, CredentialStatus, StoredCredential};
use super::storage;

/// An EdDSA (Ed25519) `JwtVerifier` bound to a single issuer key.
///
/// The key is resolved from the credential's own `iss` DID before this
/// verifier is built, so verification proves the JWS was signed by the key
/// the credential names as its issuer. It validates the `alg` header is
/// `EdDSA` *before* touching the signature and checks the Ed25519 signature
/// over the compact signing input (`header_b64.payload_b64`). A wrong `alg`,
/// a malformed JWS, or a bad signature all return an error — which means
/// `verify` returns `Err` and no claims are produced.
struct IssuerEddsaVerifier {
    key: VerifyingKey,
}

impl JwtVerifier for IssuerEddsaVerifier {
    fn verify_jwt(&self, jws: &str) -> Result<Value, affinidi_sd_jwt::error::SdJwtError> {
        use affinidi_sd_jwt::error::SdJwtError;

        let parts: Vec<&str> = jws.split('.').collect();
        if parts.len() != 3 {
            return Err(SdJwtError::Verification("malformed compact JWS".into()));
        }
        let (header_b64, payload_b64, sig_b64) = (parts[0], parts[1], parts[2]);

        // Validate the algorithm header before doing any signature work.
        let header_bytes = URL_SAFE_NO_PAD
            .decode(header_b64)
            .map_err(|e| SdJwtError::Verification(e.to_string()))?;
        let header: Value = serde_json::from_slice(&header_bytes)
            .map_err(|e| SdJwtError::Verification(e.to_string()))?;
        if header.get("alg").and_then(Value::as_str) != Some("EdDSA") {
            return Err(SdJwtError::Verification(
                "unexpected alg (want EdDSA)".into(),
            ));
        }

        // Verify the Ed25519 signature over `header_b64.payload_b64`.
        let signing_input = format!("{header_b64}.{payload_b64}");
        let sig_bytes = URL_SAFE_NO_PAD
            .decode(sig_b64)
            .map_err(|e| SdJwtError::Verification(e.to_string()))?;
        let sig = Signature::from_slice(&sig_bytes)
            .map_err(|e| SdJwtError::Verification(e.to_string()))?;
        self.key
            .verify(signing_input.as_bytes(), &sig)
            .map_err(|_| SdJwtError::Verification("Ed25519 signature invalid".into()))?;

        // Signature good — decode and return the payload.
        let payload_bytes = URL_SAFE_NO_PAD
            .decode(payload_b64)
            .map_err(|e| SdJwtError::Verification(e.to_string()))?;
        serde_json::from_slice(&payload_bytes).map_err(|e| SdJwtError::Verification(e.to_string()))
    }
}

/// Provenance hint recorded on the stored envelope's `source` field.
///
/// Free-form; carried through verbatim. Callers pass the exchange thread id /
/// delivering DID so an operator can later trace where a credential came
/// from. `None` leaves `source` unset.
pub type Provenance = Option<String>;

/// Receive an incoming SD-JWT-VC into the vault: verify minimally, map, and
/// store.
///
/// `compact` is the SD-JWT-VC compact serialization (the JWS plus tilde-
/// separated disclosures). `id` is the holder-agent-assigned local handle
/// (the vault primary key — a ULID is recommended). `source` is optional
/// provenance. `now_unix` is the current time in Unix seconds, injected for
/// testability (production callers pass `chrono::Utc::now().timestamp()`).
///
/// On success the credential is stored under `id` and indexed by
/// `{type, community_did, issuer_did, purpose, status}` so it is findable via
/// [`super::find_by_index`]. Returns the [`StoredCredential`] that was
/// persisted.
///
/// ## Failure modes (all reject **without** storing)
/// - `id` is empty → [`AppError::Validation`].
/// - `compact` does not parse as an SD-JWT → [`AppError::Validation`].
/// - the payload has no `iss`, or `iss` is not a resolvable `did:key`
///   → [`AppError::Validation`].
/// - the issuer signature does not verify → [`AppError::Validation`].
/// - the credential is expired / not-yet-valid / has no `iat`
///   → [`AppError::Validation`].
///
/// No write to the store happens on any of these paths.
pub async fn receive_sd_jwt_vc(
    vault: &KeyspaceHandle,
    id: &str,
    compact: &str,
    source: Provenance,
    now_unix: u64,
) -> Result<StoredCredential, AppError> {
    if id.trim().is_empty() {
        return Err(AppError::Validation(
            "credential id must be non-empty".to_string(),
        ));
    }

    let hasher = Sha256Hasher;

    // Parse the compact serialization. Malformed input fails closed here,
    // before any trust is placed in the bytes.
    let sd_jwt = SdJwt::parse(compact, &hasher)
        .map_err(|e| AppError::Validation(format!("malformed SD-JWT-VC: {e}")))?;

    // Read the *unverified* payload only to learn which issuer DID to resolve.
    // No claim is trusted from this view — every value mapped onto the stored
    // envelope below comes from the *verified* result.
    let unverified_payload = sd_jwt
        .payload()
        .map_err(|e| AppError::Validation(format!("unreadable SD-JWT-VC payload: {e}")))?;

    let issuer_did = unverified_payload
        .get("iss")
        .and_then(Value::as_str)
        .filter(|s| !s.is_empty())
        .ok_or_else(|| AppError::Validation("SD-JWT-VC is missing the `iss` claim".to_string()))?;

    // Resolve the issuer DID to its Ed25519 public key. The credential names
    // its own issuer; resolution failing (not a did:key, bad multicodec)
    // rejects the credential rather than trusting an unresolvable issuer.
    let issuer_pub = affinidi_crypto::did_key::did_key_to_ed25519_pub(issuer_did).map_err(|e| {
        AppError::Validation(format!(
            "issuer `iss` ({issuer_did}) is not a resolvable did:key: {e}"
        ))
    })?;
    let verifying_key = VerifyingKey::from_bytes(&issuer_pub)
        .map_err(|e| AppError::Validation(format!("issuer key is not a valid Ed25519 key: {e}")))?;
    let verifier = IssuerEddsaVerifier { key: verifying_key };

    // Verify the issuer signature. A tampered JWS produces `Err` here, so
    // forged credentials never reach the store. We pass no holder-binding
    // verifier: holder binding is a *presentation*-time concern (spec §14.4),
    // not a receive-time one. The returned `claims` are the only trusted view.
    let opts = VerificationOptions::default();
    let result = verify(&sd_jwt, &verifier, &hasher, &opts, None)
        .map_err(|e| AppError::Validation(format!("issuer signature verification failed: {e}")))?;
    if !result.is_verified() {
        return Err(AppError::Validation(
            "SD-JWT-VC verification did not succeed".to_string(),
        ));
    }
    let claims = &result.claims;

    // Temporal validity over the *verified* claims. Expired / not-yet-valid /
    // missing-iat all reject without storing.
    affinidi_sd_jwt_vc::verify_temporal(claims, now_unix)
        .map_err(|e| AppError::Validation(format!("temporal validity check failed: {e}")))?;

    // --- map verified claims → StoredCredential envelope (spec §5) ---

    let types = extract_types(claims);
    let subject_did = claims
        .get("sub")
        .and_then(Value::as_str)
        .map(str::to_string);
    let purpose = infer_purpose(&types);
    let valid_from =
        unix_claim_to_rfc3339(claims, "nbf").or_else(|| unix_claim_to_rfc3339(claims, "iat"));
    let valid_until = unix_claim_to_rfc3339(claims, "exp");

    let cred = StoredCredential {
        id: id.to_string(),
        format: CredentialFormat::SdJwtVc,
        types,
        // schema_id resolution against the VTC schema store is task 1.2's
        // sibling-phase work (§8); not derived here.
        schema_id: None,
        // The credential's community/context binding is a higher-layer
        // concept (a claim convention); not part of the minimal SD-JWT-VC
        // profile, so left unset at receive time.
        community_did: None,
        context_id: None,
        subject_did,
        issuer_did: Some(issuer_did.to_string()),
        purpose,
        // "Valid" here means *passed signature + temporal* only. Real
        // revocation state is resolved by the status task (1.6).
        status: CredentialStatus::Valid,
        valid_from,
        valid_until,
        received_at: chrono::Utc::now().to_rfc3339(),
        source,
        tags: std::collections::BTreeMap::new(),
        // Store the credential verbatim as the holder received it, so a later
        // present/refresh re-parses the exact bytes. Opaque to the store.
        body: compact.as_bytes().to_vec(),
        lifecycle: vti_common::vault::VaultStatus::Active,
        archived_at: None,
        deleted_at: None,
        grace_until: None,
    };

    // Single, final side effect. Reached only after both checks passed, so
    // there is no path that stores an unverified or expired credential.
    storage::put(vault, &cred).await?;

    Ok(cred)
}

/// The claims a stored credential carries, as one JSON document — what a
/// `claimPath` (RFC 6901) is read against.
///
/// - **SD-JWT-VC**: re-verified against its issuer and reconstructed with
///   every disclosure the holder holds, exactly as [`receive_sd_jwt_vc`] reads
///   it on arrival. The stored body is what was verified then; re-verifying is
///   what makes this the only way the claims are read.
/// - **Data-Integrity VC**: the document itself, verified on arrival.
/// - **mdoc**: not readable by path here, and refused rather than guessed.
///
/// Fails closed: a body that does not parse, or a signature that no longer
/// verifies, is an error, never an empty document.
pub fn stored_claims(cred: &StoredCredential) -> Result<Value, AppError> {
    match &cred.format {
        CredentialFormat::SdJwtVc => {
            let hasher = Sha256Hasher;
            let compact = std::str::from_utf8(&cred.body)
                .map_err(|e| AppError::Validation(format!("SD-JWT-VC body is not UTF-8: {e}")))?;
            let sd_jwt = SdJwt::parse(compact, &hasher)
                .map_err(|e| AppError::Validation(format!("malformed SD-JWT-VC: {e}")))?;
            let issuer_did = sd_jwt
                .payload()
                .ok()
                .and_then(|p| p.get("iss").and_then(Value::as_str).map(str::to_string))
                .ok_or_else(|| {
                    AppError::Validation("SD-JWT-VC is missing the `iss` claim".to_string())
                })?;
            let issuer_pub = affinidi_crypto::did_key::did_key_to_ed25519_pub(&issuer_did)
                .map_err(|e| {
                    AppError::Validation(format!("issuer {issuer_did} is not a did:key: {e}"))
                })?;
            let key = VerifyingKey::from_bytes(&issuer_pub)
                .map_err(|e| AppError::Validation(format!("issuer key is not Ed25519: {e}")))?;
            let result = verify(
                &sd_jwt,
                &IssuerEddsaVerifier { key },
                &hasher,
                &VerificationOptions::default(),
                None,
            )
            .map_err(|e| {
                AppError::Validation(format!("issuer signature no longer verifies: {e}"))
            })?;
            if !result.is_verified() {
                return Err(AppError::Validation(
                    "SD-JWT-VC verification did not succeed".to_string(),
                ));
            }
            Ok(result.claims)
        }
        CredentialFormat::EddsaJcs2022 | CredentialFormat::Bbs2023 => {
            serde_json::from_slice(&cred.body).map_err(|e| {
                AppError::Validation(format!("Data-Integrity VC body is not JSON: {e}"))
            })
        }
        other => Err(AppError::Validation(format!(
            "claims of a {other:?} credential cannot be read by path"
        ))),
    }
}

/// Receive a **W3C Data-Integrity VC** (`eddsa-jcs-2022`) into the vault: verify
/// the issuer proof + temporal validity, map, and store (spec D4 — the
/// format-agnostic bridge; the W3C-DI sibling of [`receive_sd_jwt_vc`]).
///
/// `vc_json` is the credential as the holder received it (a W3C VC 2.0 JSON
/// document with a `proof`). `issuer_pub` is the issuer's Ed25519 public key —
/// **the caller resolves the issuer DID** (the vault stays network-free,
/// mirroring the injected-signer pattern in [`super::present`]; the wire layer
/// resolves a `did:webvh` / `did:web` issuer, a test passes the known key).
/// `now` anchors the temporal check.
///
/// ## Failure modes (all reject **without** storing)
/// - `id` empty, or `vc_json` not a JSON object → [`AppError::Validation`];
/// - no `proof`, or a non-`eddsa-jcs-2022` cryptosuite (BBS+ is audit-gated and
///   routed elsewhere) → [`AppError::Validation`];
/// - the issuer proof does not verify against `issuer_pub` → [`AppError::Validation`];
/// - `now` is outside `validFrom`/`validUntil` → [`AppError::Validation`].
pub async fn receive_di_vc(
    vault: &KeyspaceHandle,
    id: &str,
    vc_json: &[u8],
    issuer_pub: &[u8],
    source: Provenance,
    now: DateTime<Utc>,
) -> Result<StoredCredential, AppError> {
    if id.trim().is_empty() {
        return Err(AppError::Validation(
            "credential id must be non-empty".to_string(),
        ));
    }

    let vc: Value = serde_json::from_slice(vc_json)
        .map_err(|e| AppError::Validation(format!("malformed Data-Integrity VC JSON: {e}")))?;

    // Pull the proof and require eddsa-jcs-2022 (BBS+ is audit-gated, routed by
    // [`receive`] to an explicit error).
    let proof_val = vc
        .get("proof")
        .cloned()
        .ok_or_else(|| AppError::Validation("Data-Integrity VC has no `proof`".to_string()))?;
    let proof: DataIntegrityProof = serde_json::from_value(proof_val)
        .map_err(|e| AppError::Validation(format!("unparseable Data-Integrity proof: {e}")))?;
    if !matches!(proof.cryptosuite, CryptoSuite::EddsaJcs2022) {
        return Err(AppError::Validation(format!(
            "unsupported cryptosuite {:?} (expected eddsa-jcs-2022; BBS+ is audit-gated)",
            proof.cryptosuite
        )));
    }

    // Verify over the document with `proof` removed — JCS is presence-sensitive,
    // so sign-time and verify-time both strip it. A tampered credential fails
    // here, before any trust is placed in the bytes.
    let mut signing_doc = vc.clone();
    signing_doc
        .as_object_mut()
        .ok_or_else(|| AppError::Validation("Data-Integrity VC is not a JSON object".to_string()))?
        .remove("proof");
    proof
        .verify_with_public_key(&signing_doc, issuer_pub, VerifyOptions::new())
        .map_err(|e| {
            AppError::Validation(format!(
                "issuer Data-Integrity proof verification failed: {e}"
            ))
        })?;

    // Temporal validity over W3C VC 2.0 `validFrom` / `validUntil`.
    di_temporal_valid(&vc, now)?;

    // --- map verified VC → StoredCredential envelope ---
    let types = extract_types(&vc);
    let subject_did = vc
        .get("credentialSubject")
        .and_then(|s| s.get("id"))
        .and_then(Value::as_str)
        .map(str::to_string);
    let issuer_did = vc.get("issuer").and_then(|i| {
        i.as_str()
            .map(str::to_string)
            .or_else(|| i.get("id").and_then(Value::as_str).map(str::to_string))
    });
    let purpose = infer_purpose(&types);
    let valid_from = vc
        .get("validFrom")
        .and_then(Value::as_str)
        .map(str::to_string);
    let valid_until = vc
        .get("validUntil")
        .and_then(Value::as_str)
        .map(str::to_string);

    let cred = StoredCredential {
        id: id.to_string(),
        format: CredentialFormat::EddsaJcs2022,
        types,
        schema_id: None,
        community_did: None,
        context_id: None,
        subject_did,
        issuer_did,
        purpose,
        status: CredentialStatus::Valid,
        valid_from,
        valid_until,
        received_at: now.to_rfc3339(),
        source,
        tags: std::collections::BTreeMap::new(),
        body: vc_json.to_vec(),
        lifecycle: vti_common::vault::VaultStatus::Active,
        archived_at: None,
        deleted_at: None,
        grace_until: None,
    };

    storage::put(vault, &cred).await?;
    Ok(cred)
}

/// Receive an ISO/IEC 18013-5 **mdoc** into the vault: verify, map, and store.
///
/// `body` is the CBOR `IssuerSigned` wire form. `issuer_pub` is the **caller-
/// resolved** Document Signer public key (SEC1, P-256) — deliberately the same
/// shape as [`receive_di_vc`]'s issuer key, and for the same reason: resolving
/// *which* key to trust is a policy decision that belongs to the wire layer,
/// not to the verifier.
///
/// That seam matters more here than for DI. **mdoc anchors issuer trust in an
/// X.509 chain** (`x5chain`, COSE header label 33, rooted in an IACA), while
/// this stack is DID-rooted end to end. Taking a resolved key here keeps that
/// unresolved question — configured trust-anchor set, trust-registry mapping,
/// or `did:x509` — out of the storage layer instead of quietly settling it.
///
/// Verifies three things, rejecting-without-storing on any failure, per
/// ISO 18013-5 §9.3.1:
/// 1. **`issuerAuth`** — the COSE_Sign1 over the MSO, against `issuer_pub`.
/// 2. **Digests** — every disclosed item against the MSO's `valueDigests`. A
///    valid signature over an MSO whose digests do not match the items is a
///    tampered credential.
/// 3. **`validityInfo`** — `now` inside `[validFrom, validUntil]`.
///
/// `device_key_id` names the VTA key whose public half is the MSO's
/// `deviceKey` — the caller resolves it, because matching a COSE_Key against
/// the VTA's own keyspace is above this layer. It is recorded on the stored
/// envelope so presentation can find the key that must sign `DeviceAuth`.
/// Refusing an mdoc whose device key the VTA does not hold is the point: such a
/// credential could be stored but never presented with holder binding, and the
/// failure would otherwise surface much later, at presentation, with nothing
/// pointing at the cause.
///
/// ES256 only. ISO 18013-5 and the EUDI profiles mandate it, and it is what the
/// VTA already has via [`vta_sdk::keys::KeyType::P256`], so no new curve enters
/// the graph. A credential signed with any other algorithm is refused by name
/// rather than silently mis-verified.
pub async fn receive_mdoc(
    vault: &KeyspaceHandle,
    id: &str,
    body: &[u8],
    issuer_pub: &[u8],
    device_key_id: &str,
    source: Provenance,
    now: DateTime<Utc>,
) -> Result<StoredCredential, AppError> {
    if id.trim().is_empty() {
        return Err(AppError::Validation(
            "credential id must be non-empty".to_string(),
        ));
    }

    // Parse. This is structure only — nothing is trusted yet.
    let issued = affinidi_mdoc::IssuerSigned::from_cbor_bytes(body)
        .map_err(|e| AppError::Validation(format!("mdoc body is not a valid IssuerSigned: {e}")))?;

    // Refuse an unexpected algorithm before touching the signature, mirroring
    // the SD-JWT path's `alg` check.
    let alg = issued.issuer_auth.protected.header.alg.clone();
    let expected = coset::RegisteredLabelWithPrivate::Assigned(coset::iana::Algorithm::ES256);
    if alg.as_ref() != Some(&expected) {
        return Err(AppError::Validation(format!(
            "mdoc issuerAuth must be ES256 (ISO 18013-5 / EUDI); got {alg:?}"
        )));
    }

    // 1. issuerAuth signature, against the caller-resolved Document Signer key.
    let verifier = affinidi_mdoc::es256_cose::Es256CoseVerifier::from_bytes(issuer_pub)
        .map_err(|e| AppError::Validation(format!("invalid mdoc issuer key: {e}")))?;
    let mso = issued
        .verify_issuer_auth(&verifier)
        .map_err(|e| AppError::Validation(format!("mdoc issuerAuth did not verify: {e}")))?;

    // 2. Digests. A good signature over an MSO whose digests do not match the
    //    items means the items were swapped after signing.
    if !issued
        .verify_digests()
        .map_err(|e| AppError::Validation(format!("mdoc digest check failed: {e}")))?
    {
        return Err(AppError::Validation(
            "mdoc item digests do not match the signed MSO".to_string(),
        ));
    }

    // 3. Temporal validity.
    let now_odt = time::OffsetDateTime::from_unix_timestamp(now.timestamp())
        .map_err(|e| AppError::Internal(format!("clock conversion: {e}")))?;
    mso.validity_info
        .check(now_odt)
        .map_err(|e| AppError::Validation(format!("mdoc is not currently valid: {e}")))?;

    // Map. `docType` is the credential's type — taken from the *signed* MSO,
    // never from the outer map (the codec guarantees this).
    let cred = StoredCredential {
        id: id.to_string(),
        format: CredentialFormat::MsoMdoc,
        types: vec![mso.doc_type.clone()],
        schema_id: None,
        community_did: None,
        context_id: None,
        // An mdoc binds to the holder through the MSO's `deviceKey`, not a
        // subject DID, and carries no issuer DID — its issuer identity is the
        // X.509 chain. Leaving both `None` is truthful; inventing a DID here
        // would put an unverifiable identifier into a secondary index.
        subject_did: None,
        issuer_did: None,
        purpose: Some(CredentialPurpose::Other(mso.doc_type.clone())),
        status: CredentialStatus::Valid,
        valid_from: Some(mso.validity_info.valid_from.clone()),
        valid_until: Some(mso.validity_info.valid_until.clone()),
        received_at: now.to_rfc3339(),
        source,
        // The holder-binding key, recorded now because nothing else in the
        // stored envelope says which VTA key can speak for this credential.
        tags: std::collections::BTreeMap::from([(
            super::model::MDOC_DEVICE_KEY_TAG.to_string(),
            device_key_id.to_string(),
        )]),
        body: body.to_vec(),
        lifecycle: vti_common::vault::VaultStatus::Active,
        archived_at: None,
        deleted_at: None,
        grace_until: None,
    };

    storage::put(vault, &cred).await?;
    Ok(cred)
}

/// Format-dispatching receive — the vault's single entry point for storing an
/// incoming credential of any format (spec D4).
///
/// `SdJwtVc` resolves its issuer `did:key` internally; the Data-Integrity
/// formats take a caller-resolved `issuer_pub` (the wire layer resolves the
/// issuer DID). `Bbs2023` is audit-gated and `Zkp` is Phase-0-gated; `Other`
/// is rejected.
pub async fn receive(
    vault: &KeyspaceHandle,
    id: &str,
    format: &CredentialFormat,
    body: &[u8],
    issuer_pub: Option<&[u8]>,
    source: Provenance,
    now: DateTime<Utc>,
) -> Result<StoredCredential, AppError> {
    match format {
        CredentialFormat::SdJwtVc => {
            let compact = std::str::from_utf8(body).map_err(|e| {
                AppError::Validation(format!("SD-JWT-VC body is not valid UTF-8: {e}"))
            })?;
            receive_sd_jwt_vc(vault, id, compact, source, now.timestamp().max(0) as u64).await
        }
        CredentialFormat::EddsaJcs2022 => {
            let pubkey = issuer_pub.ok_or_else(|| {
                AppError::Validation(
                    "a Data-Integrity credential needs a caller-resolved issuer key".to_string(),
                )
            })?;
            receive_di_vc(vault, id, body, pubkey, source, now).await
        }
        CredentialFormat::Bbs2023 => {
            #[cfg(feature = "bbs")]
            {
                let pubkey = issuer_pub.ok_or_else(|| {
                    AppError::Validation(
                        "a BBS (bbs-2023) credential needs a caller-resolved 96-byte G2 issuer key"
                            .to_string(),
                    )
                })?;
                super::bbs::receive_bbs(vault, id, body, pubkey, source, now).await
            }
            #[cfg(not(feature = "bbs"))]
            Err(AppError::Validation(
                "BBS+ receive requires the `bbs` feature (audit-gated, Phase 0b)".to_string(),
            ))
        }
        CredentialFormat::Zkp => Err(AppError::Validation(
            "ZKP receive is Phase-0-gated and not yet supported (commitment primitives \
             + Circom/Groth16 verifier not yet wired)"
                .to_string(),
        )),
        // Not reachable through this entry point: an mdoc needs a
        // caller-resolved Document Signer key *and* the VTA key id holding its
        // MSO deviceKey. This signature can carry the first but not the second,
        // and guessing the binding is exactly what must not happen.
        CredentialFormat::MsoMdoc => Err(AppError::Validation(
            "receive an mdoc through `receive_mdoc`, which takes the device-key binding \
             this format-agnostic entry point cannot supply"
                .to_string(),
        )),
        CredentialFormat::Other(tag) => Err(AppError::Validation(format!(
            "unsupported credential format `{tag}`"
        ))),
    }
}

/// True iff `now` lies within a W3C VC 2.0 `validFrom`/`validUntil` window.
/// Either bound may be absent; a malformed RFC-3339 bound is a hard error
/// (default-deny — never store a credential whose window can't be evaluated).
pub(super) fn di_temporal_valid(vc: &Value, now: DateTime<Utc>) -> Result<(), AppError> {
    if let Some(from) = vc.get("validFrom").and_then(Value::as_str) {
        let from = from.parse::<DateTime<Utc>>().map_err(|e| {
            AppError::Validation(format!("`validFrom` ({from}) is not RFC-3339: {e}"))
        })?;
        if now < from {
            return Err(AppError::Validation(
                "credential is not yet valid (`validFrom` is in the future)".to_string(),
            ));
        }
    }
    if let Some(until) = vc.get("validUntil").and_then(Value::as_str) {
        let until = until.parse::<DateTime<Utc>>().map_err(|e| {
            AppError::Validation(format!("`validUntil` ({until}) is not RFC-3339: {e}"))
        })?;
        if now >= until {
            return Err(AppError::Validation(
                "credential has expired (`validUntil` is in the past)".to_string(),
            ));
        }
    }
    Ok(())
}

/// Extract VC `type` tags from the verified claims.
///
/// SD-JWT-VC's primary type identifier is the `vct` claim (always present in
/// the protected payload). We index that, and additionally fold in any
/// JSON-LD-style `type` / `vc.type` arrays a richer credential carries, so a
/// match on either the SD-JWT-VC `vct` or a classic VC `type` tag finds the
/// credential. Duplicates are de-duplicated; order is preserved.
pub(super) fn extract_types(claims: &Value) -> Vec<String> {
    let mut types: Vec<String> = Vec::new();
    let mut push_unique = |s: String| {
        if !s.is_empty() && !types.contains(&s) {
            types.push(s);
        }
    };

    if let Some(vct) = claims.get("vct").and_then(Value::as_str) {
        push_unique(vct.to_string());
    }
    collect_type_field(claims.get("type"), &mut push_unique);
    if let Some(vc) = claims.get("vc") {
        collect_type_field(vc.get("type"), &mut push_unique);
    }

    types
}

/// Fold a `type` field — which may be a string or an array of strings — into
/// the type set via `push`.
fn collect_type_field(field: Option<&Value>, push: &mut impl FnMut(String)) {
    match field {
        Some(Value::String(s)) => push(s.clone()),
        Some(Value::Array(arr)) => {
            for v in arr {
                if let Some(s) = v.as_str() {
                    push(s.to_string());
                }
            }
        }
        _ => {}
    }
}

/// Infer the credential [`CredentialPurpose`] from its type tags.
///
/// A best-effort mapping from the catalog type names (spec §3) onto the
/// indexed purpose taxonomy, so a received credential is findable by purpose
/// without the caller having to classify it. Matching is case-insensitive and
/// substring-based against the known catalog families; an unrecognised type
/// leaves `purpose` unset (rather than guessing wrong).
pub(super) fn infer_purpose(types: &[String]) -> Option<CredentialPurpose> {
    for t in types {
        let lower = t.to_ascii_lowercase();
        if lower.contains("invitation") || lower.contains("invite") {
            return Some(CredentialPurpose::Invite);
        }
        if lower.contains("membership") {
            return Some(CredentialPurpose::Membership);
        }
        if lower.contains("role") {
            return Some(CredentialPurpose::Role);
        }
        if lower.contains("endorsement") {
            return Some(CredentialPurpose::Endorsement);
        }
        if lower.contains("personhood") {
            return Some(CredentialPurpose::Personhood);
        }
    }
    None
}

/// Convert a Unix-seconds numeric claim into an RFC-3339 timestamp string for
/// the envelope's `valid_from` / `valid_until` fields. Returns `None` if the
/// claim is absent or not a representable timestamp.
fn unix_claim_to_rfc3339(claims: &Value, key: &str) -> Option<String> {
    let secs = claims.get(key).and_then(Value::as_i64)?;
    chrono::DateTime::<chrono::Utc>::from_timestamp(secs, 0).map(|dt| dt.to_rfc3339())
}

#[cfg(test)]
mod tests {
    use super::*;
    use affinidi_sd_jwt::hasher::Sha256Hasher;
    use affinidi_sd_jwt::signer::JwtSigner;
    use ed25519_dalek::{Signer, SigningKey};
    use serde_json::json;
    use vti_common::config::StoreConfig;
    use vti_common::store::Store;

    /// A production-shape EdDSA (Ed25519) JWT signer for the tests. Mirrors
    /// the SDK smoke test's issuer: signs the compact signing input and emits
    /// the full compact JWS.
    struct EddsaSigner {
        key: SigningKey,
        kid: String,
    }

    impl JwtSigner for EddsaSigner {
        fn algorithm(&self) -> &str {
            "EdDSA"
        }
        fn key_id(&self) -> Option<&str> {
            Some(&self.kid)
        }
        fn sign_jwt(
            &self,
            header: &Value,
            payload: &Value,
        ) -> Result<String, affinidi_sd_jwt::error::SdJwtError> {
            use affinidi_sd_jwt::error::SdJwtError;
            let header_b64 = URL_SAFE_NO_PAD.encode(
                serde_json::to_string(header)
                    .map_err(|e| SdJwtError::Verification(e.to_string()))?
                    .as_bytes(),
            );
            let payload_b64 = URL_SAFE_NO_PAD.encode(
                serde_json::to_string(payload)
                    .map_err(|e| SdJwtError::Verification(e.to_string()))?
                    .as_bytes(),
            );
            let signing_input = format!("{header_b64}.{payload_b64}");
            let sig: Signature = self.key.sign(signing_input.as_bytes());
            let sig_b64 = URL_SAFE_NO_PAD.encode(sig.to_bytes());
            Ok(format!("{signing_input}.{sig_b64}"))
        }
    }

    /// A fresh tempdir-backed `vault` keyspace handle.
    fn fresh_vault() -> (tempfile::TempDir, Store, KeyspaceHandle) {
        let dir = tempfile::tempdir().expect("tempdir");
        let store = Store::open(&StoreConfig {
            data_dir: dir.path().to_path_buf(),
        })
        .expect("open store");
        let ks = store
            .keyspace(vta_keyspaces::VAULT)
            .expect("vault keyspace");
        (dir, store, ks)
    }

    /// An issuer whose DID is the *real* `did:key` for its Ed25519 key, so the
    /// receive path's `iss` → key resolution resolves to the verifying key.
    fn issuer() -> (EddsaSigner, String) {
        let secret = [9u8; 32];
        let signing = SigningKey::from_bytes(&secret);
        let did =
            affinidi_crypto::did_key::ed25519_pub_to_did_key(signing.verifying_key().as_bytes());
        let kid = format!("{did}#key-0");
        (EddsaSigner { key: signing, kid }, did)
    }

    /// Issue a membership-shaped SD-JWT-VC from `issuer_did` whose `iat`/`exp`
    /// bracket `iat..exp`. Returns the compact serialization.
    fn issue_membership(
        signer: &EddsaSigner,
        issuer_did: &str,
        iat: u64,
        exp: Option<u64>,
    ) -> String {
        let hasher = Sha256Hasher;
        let claims = json!({
            "community": "did:web:community.example",
            "tier": "founding",
        });
        let frame = json!({ "_sd": ["community", "tier"] });
        let vc = affinidi_sd_jwt_vc::issue(
            "https://openvtc.org/credentials/MembershipCredential",
            issuer_did,
            Some("did:example:alice"),
            &claims,
            &frame,
            signer,
            &hasher,
            None,
            iat,
            exp,
        )
        .expect("issue SD-JWT-VC");
        vc.serialize()
    }

    #[tokio::test]
    async fn valid_sd_jwt_vc_is_stored_and_indexed() {
        let (_dir, _store, vault) = fresh_vault();
        let (signer, did) = issuer();
        // valid_from = 1_700_000_000, valid_until = 1_900_000_000.
        let compact = issue_membership(&signer, &did, 1_700_000_000, Some(1_900_000_000));

        let stored = receive_sd_jwt_vc(
            &vault,
            "cred-1",
            &compact,
            Some("exchange:thread-7".into()),
            1_800_000_000,
        )
        .await
        .expect("valid credential is received");

        // Envelope mapping.
        assert_eq!(stored.id, "cred-1");
        assert_eq!(stored.format, CredentialFormat::SdJwtVc);
        assert!(
            stored
                .types
                .contains(&"https://openvtc.org/credentials/MembershipCredential".to_string())
        );
        assert_eq!(stored.issuer_did.as_deref(), Some(did.as_str()));
        assert_eq!(stored.subject_did.as_deref(), Some("did:example:alice"));
        assert_eq!(stored.purpose, Some(CredentialPurpose::Membership));
        assert_eq!(stored.status, CredentialStatus::Valid);
        assert_eq!(stored.source.as_deref(), Some("exchange:thread-7"));
        assert!(stored.valid_until.is_some());
        // Body is the verbatim compact serialization.
        assert_eq!(stored.body, compact.as_bytes());

        // Findable by type via the 1.1 index.
        let by_type = storage::find_by_index(
            &vault,
            crate::IndexField::Type,
            "https://openvtc.org/credentials/MembershipCredential",
        )
        .await
        .unwrap();
        assert_eq!(by_type.len(), 1);
        assert_eq!(by_type[0].id, "cred-1");

        // Findable by issuer via the 1.1 index.
        let by_issuer = storage::find_by_index(&vault, crate::IndexField::IssuerDid, &did)
            .await
            .unwrap();
        assert_eq!(by_issuer.len(), 1);
        assert_eq!(by_issuer[0].id, "cred-1");
    }

    #[tokio::test]
    async fn tampered_signature_is_rejected_and_not_stored() {
        let (_dir, _store, vault) = fresh_vault();
        let (signer, did) = issuer();
        let compact = issue_membership(&signer, &did, 1_700_000_000, Some(1_900_000_000));

        // Flip a byte inside the issuer JWS signature segment. The compact
        // form is `<jws>~<disclosure>~...`; mutate a char in the first
        // (JWS) segment's signature so the Ed25519 check fails.
        let mut chars: Vec<char> = compact.chars().collect();
        // Find the end of the JWS (first '~') and a position just before it.
        let tilde = compact.find('~').expect("has disclosures");
        let pos = tilde - 1;
        chars[pos] = if chars[pos] == 'A' { 'B' } else { 'A' };
        let tampered: String = chars.into_iter().collect();

        let err = receive_sd_jwt_vc(&vault, "cred-bad", &tampered, None, 1_800_000_000)
            .await
            .expect_err("tampered credential must be rejected");
        assert!(matches!(err, AppError::Validation(_)));

        // Nothing was stored.
        assert!(storage::get(&vault, "cred-bad").await.unwrap().is_none());
    }

    #[tokio::test]
    async fn expired_credential_is_rejected_and_not_stored() {
        let (_dir, _store, vault) = fresh_vault();
        let (signer, did) = issuer();
        // exp is in the past relative to the `now` we pass below.
        let compact = issue_membership(&signer, &did, 1_700_000_000, Some(1_701_000_000));

        let err = receive_sd_jwt_vc(&vault, "cred-exp", &compact, None, 1_900_000_000)
            .await
            .expect_err("expired credential must be rejected");
        assert!(matches!(err, AppError::Validation(_)));

        // Nothing was stored, and no stray index row points at it.
        assert!(storage::get(&vault, "cred-exp").await.unwrap().is_none());
        assert!(
            storage::find_by_index(&vault, crate::IndexField::IssuerDid, &did)
                .await
                .unwrap()
                .is_empty()
        );
    }

    #[tokio::test]
    async fn credential_signed_by_a_different_key_than_iss_is_rejected() {
        // An attacker signs with their own key but sets `iss` to a victim's
        // did:key. Resolution picks the victim's key, the signature fails to
        // verify, and the credential is rejected — proving the signature is
        // checked against the *named* issuer, not whoever actually signed.
        let (_dir, _store, vault) = fresh_vault();
        let attacker_secret = [1u8; 32];
        let attacker = SigningKey::from_bytes(&attacker_secret);
        let attacker_signer = EddsaSigner {
            key: attacker,
            kid: "did:key:attacker#key-0".to_string(),
        };
        // The victim's did:key (a different key than the attacker's).
        let victim_secret = [2u8; 32];
        let victim_did = affinidi_crypto::did_key::ed25519_pub_to_did_key(
            SigningKey::from_bytes(&victim_secret)
                .verifying_key()
                .as_bytes(),
        );

        let compact = issue_membership(
            &attacker_signer,
            &victim_did,
            1_700_000_000,
            Some(1_900_000_000),
        );

        let err = receive_sd_jwt_vc(&vault, "cred-forged", &compact, None, 1_800_000_000)
            .await
            .expect_err("issuer-impersonation must be rejected");
        assert!(matches!(err, AppError::Validation(_)));
        assert!(storage::get(&vault, "cred-forged").await.unwrap().is_none());
    }

    #[tokio::test]
    async fn missing_iss_is_rejected() {
        // An SD-JWT (not VC-profiled) with no `iss` must fail closed: the
        // receive path can't resolve an issuer key, so it can't verify.
        let (_dir, _store, vault) = fresh_vault();
        let hasher = Sha256Hasher;
        let signing = SigningKey::from_bytes(&[3u8; 32]);
        let signer = EddsaSigner {
            key: signing,
            kid: "k".into(),
        };
        // Issue a raw SD-JWT with no `iss` claim.
        let claims = json!({ "iat": 1_700_000_000, "foo": "bar" });
        let frame = json!({ "_sd": ["foo"] });
        let sd_jwt =
            affinidi_sd_jwt::issuer::issue(&claims, &frame, &signer, &hasher, None).unwrap();
        let compact = sd_jwt.serialize();

        let err = receive_sd_jwt_vc(&vault, "cred-noiss", &compact, None, 1_800_000_000)
            .await
            .expect_err("missing iss must be rejected");
        assert!(matches!(err, AppError::Validation(_)));
        assert!(storage::get(&vault, "cred-noiss").await.unwrap().is_none());
    }

    #[tokio::test]
    async fn empty_id_is_rejected() {
        let (_dir, _store, vault) = fresh_vault();
        let (signer, did) = issuer();
        let compact = issue_membership(&signer, &did, 1_700_000_000, Some(1_900_000_000));
        let err = receive_sd_jwt_vc(&vault, "  ", &compact, None, 1_800_000_000)
            .await
            .expect_err("empty id must be rejected");
        assert!(matches!(err, AppError::Validation(_)));
    }

    #[test]
    fn infer_purpose_maps_catalog_types() {
        assert_eq!(
            infer_purpose(&["InvitationCredential".into()]),
            Some(CredentialPurpose::Invite)
        );
        assert_eq!(
            infer_purpose(&["https://x/MembershipCredential".into()]),
            Some(CredentialPurpose::Membership)
        );
        assert_eq!(
            infer_purpose(&["RoleCredential".into()]),
            Some(CredentialPurpose::Role)
        );
        assert_eq!(infer_purpose(&["UnknownThing".into()]), None);
    }

    #[test]
    fn extract_types_folds_vct_and_type_arrays() {
        let claims = json!({
            "vct": "https://x/MembershipCredential",
            "type": ["VerifiableCredential", "MembershipCredential"],
        });
        let types = extract_types(&claims);
        assert!(types.contains(&"https://x/MembershipCredential".to_string()));
        assert!(types.contains(&"VerifiableCredential".to_string()));
        assert!(types.contains(&"MembershipCredential".to_string()));
        // No duplicates.
        let mut sorted = types.clone();
        sorted.sort();
        sorted.dedup();
        assert_eq!(sorted.len(), types.len());
    }

    // ---- Data-Integrity (eddsa-jcs-2022) receive ------------------------

    use affinidi_data_integrity::{
        DataIntegrityProof as DiProof, SignOptions, crypto_suites::CryptoSuite as Suite,
    };
    use affinidi_secrets_resolver::secrets::Secret;

    /// Build + sign a W3C-DI VC (eddsa-jcs-2022); returns `(vc_bytes,
    /// issuer_public_key_bytes)`.
    async fn signed_di_vc(seed: u8, valid_until: Option<&str>) -> (Vec<u8>, Vec<u8>) {
        let secret =
            Secret::generate_ed25519(Some("did:web:issuer.example#key-0"), Some(&[seed; 32]));
        let mut vc = json!({
            "@context": ["https://www.w3.org/ns/credentials/v2"],
            "type": ["VerifiableCredential", "MembershipCredential"],
            "issuer": "did:web:issuer.example",
            "validFrom": "2020-01-01T00:00:00Z",
            "credentialSubject": { "id": "did:key:zMember", "givenName": "Alice" }
        });
        if let Some(u) = valid_until {
            vc["validUntil"] = json!(u);
        }
        let proof = DiProof::sign(
            &vc,
            &secret,
            SignOptions::new()
                .with_proof_purpose("assertionMethod")
                .with_cryptosuite(Suite::EddsaJcs2022),
        )
        .await
        .expect("sign DI VC");
        vc["proof"] = serde_json::to_value(&proof).unwrap();
        (
            serde_json::to_vec(&vc).unwrap(),
            secret.get_public_bytes().to_vec(),
        )
    }

    #[tokio::test]
    async fn di_vc_verifies_and_stores() {
        let (_dir, _store, vault) = fresh_vault();
        let (vc, issuer_pub) = signed_di_vc(9, Some("2100-01-01T00:00:00Z")).await;
        let cred = receive_di_vc(&vault, "c1", &vc, &issuer_pub, None, Utc::now())
            .await
            .expect("receive DI VC");
        assert_eq!(cred.format, CredentialFormat::EddsaJcs2022);
        assert_eq!(cred.subject_did.as_deref(), Some("did:key:zMember"));
        assert_eq!(cred.issuer_did.as_deref(), Some("did:web:issuer.example"));
        assert!(cred.types.contains(&"MembershipCredential".to_string()));
        assert!(crate::storage::get(&vault, "c1").await.unwrap().is_some());
    }

    #[tokio::test]
    async fn di_vc_tampered_is_rejected_and_not_stored() {
        let (_dir, _store, vault) = fresh_vault();
        let (vc, issuer_pub) = signed_di_vc(9, None).await;
        let mut v: Value = serde_json::from_slice(&vc).unwrap();
        v["credentialSubject"]["givenName"] = json!("Mallory"); // tamper after signing
        let tampered = serde_json::to_vec(&v).unwrap();
        let err = receive_di_vc(&vault, "c1", &tampered, &issuer_pub, None, Utc::now())
            .await
            .unwrap_err();
        assert!(matches!(err, AppError::Validation(_)), "{err:?}");
        assert!(crate::storage::get(&vault, "c1").await.unwrap().is_none());
    }

    #[tokio::test]
    async fn di_vc_expired_is_rejected() {
        let (_dir, _store, vault) = fresh_vault();
        let (vc, issuer_pub) = signed_di_vc(9, Some("2001-01-01T00:00:00Z")).await;
        let err = receive_di_vc(&vault, "c1", &vc, &issuer_pub, None, Utc::now())
            .await
            .unwrap_err();
        assert!(matches!(err, AppError::Validation(_)), "{err:?}");
    }

    #[tokio::test]
    async fn dispatch_routes_di_requires_key_and_gates_bbs() {
        let (_dir, _store, vault) = fresh_vault();
        let (vc, issuer_pub) = signed_di_vc(9, None).await;
        // DI without a resolved issuer key → rejected.
        assert!(
            receive(
                &vault,
                "c1",
                &CredentialFormat::EddsaJcs2022,
                &vc,
                None,
                None,
                Utc::now()
            )
            .await
            .is_err()
        );
        // With the key → routed to receive_di_vc + stored.
        let cred = receive(
            &vault,
            "c1",
            &CredentialFormat::EddsaJcs2022,
            &vc,
            Some(&issuer_pub),
            None,
            Utc::now(),
        )
        .await
        .expect("dispatch DI");
        assert_eq!(cred.format, CredentialFormat::EddsaJcs2022);
        // BBS+ is audit-gated.
        assert!(
            receive(
                &vault,
                "c2",
                &CredentialFormat::Bbs2023,
                &vc,
                Some(&issuer_pub),
                None,
                Utc::now()
            )
            .await
            .is_err()
        );
        // ZKP is Phase-0-gated.
        let zkp_err = receive(
            &vault,
            "c3",
            &CredentialFormat::Zkp,
            &vc,
            Some(&issuer_pub),
            None,
            Utc::now(),
        )
        .await
        .unwrap_err();
        assert!(
            matches!(&zkp_err, AppError::Validation(m) if m.contains("ZKP")),
            "{zkp_err:?}"
        );
        // mdoc is deliberately unreachable through the format-dispatching entry
        // point: it needs the device-key binding, which this signature cannot
        // carry. Guessing that binding is exactly what must not happen.
        let mdoc_err = receive(
            &vault,
            "c4",
            &CredentialFormat::MsoMdoc,
            &vc,
            None,
            None,
            Utc::now(),
        )
        .await
        .unwrap_err();
        assert!(
            matches!(&mdoc_err, AppError::Validation(m) if m.contains("receive_mdoc")),
            "error should point at the right entry point, got {mdoc_err:?}"
        );
    }

    #[test]
    fn zkp_format_tag_round_trips_as_kebab_case() {
        // The additive variant must serialise to a stable wire tag so stored
        // credentials and DCQL `format` selectors agree on it.
        let json = serde_json::to_string(&CredentialFormat::Zkp).unwrap();
        assert_eq!(json, "\"zkp\"");
        let back: CredentialFormat = serde_json::from_str(&json).unwrap();
        assert_eq!(back, CredentialFormat::Zkp);
    }

    /// The mdoc tag is `mso_mdoc` — underscore, matching OpenID4VP's
    /// `CredentialQuery.format` — and NOT the `rename_all` kebab-case
    /// `mso-mdoc` the enum would otherwise produce. Storage and protocol must
    /// spell it identically or a DCQL selector silently matches nothing, so
    /// pin the exact bytes rather than only the round-trip.
    #[test]
    fn mso_mdoc_format_tag_is_the_openid4vp_spelling() {
        let json = serde_json::to_string(&CredentialFormat::MsoMdoc).unwrap();
        assert_eq!(json, "\"mso_mdoc\"", "must match the OID4VP format token");
        let back: CredentialFormat = serde_json::from_str(&json).unwrap();
        assert_eq!(back, CredentialFormat::MsoMdoc);
    }

    /// Before this variant existed an mdoc deserialised into the
    /// `Other("mso_mdoc")` escape hatch. It must now land on the real variant,
    /// or every downstream `match` treats a known format as unknown.
    #[test]
    fn mso_mdoc_no_longer_falls_into_the_other_escape_hatch() {
        let parsed: CredentialFormat = serde_json::from_str("\"mso_mdoc\"").unwrap();
        assert_eq!(parsed, CredentialFormat::MsoMdoc);
        assert_ne!(parsed, CredentialFormat::Other("mso_mdoc".to_string()));
    }
    // ── mdoc receive ──────────────────────────────────────────────────

    /// Build a signed mdoc plus its Document Signer public key. The MSO carries
    /// a generated P-256 device key, returned so a test can assert the binding.
    fn test_mdoc() -> (Vec<u8>, Vec<u8>) {
        use affinidi_mdoc::es256_cose::Es256CoseSigner;
        use affinidi_mdoc::mso::ValidityInfo;

        let signer = Es256CoseSigner::generate();
        let issued = affinidi_mdoc::MdocBuilder::new("eu.europa.ec.eudi.pid.1")
            .validity(ValidityInfo {
                signed: "2026-01-01T00:00:00Z".into(),
                valid_from: "2026-01-01T00:00:00Z".into(),
                valid_until: "2036-01-01T00:00:00Z".into(),
            })
            .add_json_attribute(
                affinidi_mdoc::EIDAS_PID_NAMESPACE,
                "family_name",
                &serde_json::json!("Gore"),
            )
            .build(&signer)
            .unwrap();
        (issued.to_cbor_bytes().unwrap(), signer.public_key_bytes())
    }

    #[tokio::test]
    async fn mdoc_receive_verifies_and_stores() {
        let (_tmp, _store, vault) = fresh_vault();
        let (body, issuer_pub) = test_mdoc();

        let cred = receive_mdoc(
            &vault,
            "m1",
            &body,
            &issuer_pub,
            "key-device-1",
            None,
            Utc::now(),
        )
        .await
        .expect("a well-formed mdoc should store");

        assert_eq!(cred.format, CredentialFormat::MsoMdoc);
        // docType comes from the signed MSO, and becomes the credential type.
        assert_eq!(cred.types, vec!["eu.europa.ec.eudi.pid.1"]);
        // No subject/issuer DID: an mdoc binds via the MSO deviceKey and its
        // issuer identity is an X.509 chain. Inventing either would put an
        // unverifiable identifier into a secondary index.
        assert!(cred.subject_did.is_none());
        assert!(cred.issuer_did.is_none());
        assert_eq!(cred.body, body, "the body is stored verbatim");
    }

    #[tokio::test]
    async fn mdoc_receive_rejects_a_wrong_issuer_key() {
        use affinidi_mdoc::es256_cose::Es256CoseSigner;
        let (_tmp, _store, vault) = fresh_vault();
        let (body, _) = test_mdoc();
        let attacker = Es256CoseSigner::generate().public_key_bytes();

        let err = receive_mdoc(
            &vault,
            "m2",
            &body,
            &attacker,
            "key-device-1",
            None,
            Utc::now(),
        )
        .await
        .unwrap_err();
        assert!(
            matches!(&err, AppError::Validation(m) if m.contains("issuerAuth")),
            "{err:?}"
        );
    }

    /// Reject-before-store: a failed verification must leave nothing behind.
    #[tokio::test]
    async fn mdoc_receive_stores_nothing_when_verification_fails() {
        use affinidi_mdoc::es256_cose::Es256CoseSigner;
        let (_tmp, _store, vault) = fresh_vault();
        let (body, _) = test_mdoc();
        let attacker = Es256CoseSigner::generate().public_key_bytes();

        let _ = receive_mdoc(
            &vault,
            "m3",
            &body,
            &attacker,
            "key-device-1",
            None,
            Utc::now(),
        )
        .await;

        assert!(
            storage::get(&vault, "m3").await.unwrap().is_none(),
            "a rejected mdoc must not be stored"
        );
    }

    /// An expired credential is refused even though its signature is perfectly
    /// good — ISO 18013-5 §9.3.1 requires the validityInfo check separately.
    #[tokio::test]
    async fn mdoc_receive_rejects_an_expired_credential() {
        let (_tmp, _store, vault) = fresh_vault();
        let (body, issuer_pub) = test_mdoc();
        let long_after = "2040-01-01T00:00:00Z".parse::<DateTime<Utc>>().unwrap();

        let err = receive_mdoc(
            &vault,
            "m4",
            &body,
            &issuer_pub,
            "key-device",
            None,
            long_after,
        )
        .await
        .unwrap_err();
        assert!(
            matches!(&err, AppError::Validation(m) if m.contains("not currently valid")),
            "{err:?}"
        );
    }

    /// The device-key binding is recorded on the stored envelope. Without it
    /// nothing downstream could know which VTA key may sign `DeviceAuth`, and
    /// the credential would be unpresentable with no trace of why.
    #[tokio::test]
    async fn mdoc_receive_records_the_device_key_binding() {
        let (_tmp, _store, vault) = fresh_vault();
        let (body, issuer_pub) = test_mdoc();

        let cred = receive_mdoc(
            &vault,
            "m5",
            &body,
            &issuer_pub,
            "key-device-42",
            None,
            Utc::now(),
        )
        .await
        .expect("stores");

        assert_eq!(
            cred.tags.get(super::super::model::MDOC_DEVICE_KEY_TAG),
            Some(&"key-device-42".to_string()),
            "the binding must survive onto the stored envelope"
        );
    }

    #[tokio::test]
    async fn mdoc_receive_rejects_a_body_that_is_not_an_mdoc() {
        let (_tmp, _store, vault) = fresh_vault();
        let err = receive_mdoc(
            &vault,
            "m6",
            b"not cbor at all",
            &[0u8; 65],
            "key-device-1",
            None,
            Utc::now(),
        )
        .await
        .unwrap_err();
        assert!(
            matches!(&err, AppError::Validation(m) if m.contains("IssuerSigned")),
            "{err:?}"
        );
    }
}