did-hosting-common 0.10.1

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

//! ## Operational proofs
//!
//! [`TransportBoundVerifier::verify_operational`] is the stricter check the
//! sender-bound gate uses for a service's own messages (control ↔ edge ops,
//! DID-management requests, session-signed UI envelopes). Per the VTI key-roles
//! rules these are *operational*, not attestations, so the proof must carry
//! `proofPurpose: authentication` and its `verificationMethod` must be listed
//! under the signer's `authentication` relationship. `assertionMethod` is
//! reserved for attestation artefacts (credentials) and is refused here.
//!
//! ## Approver decisions
//!
//! [`TransportBoundVerifier::verify_approval`] is the counterpart for a human
//! approver's decision (a consent decision, a step-up approval): the one
//! document that is an attestation, so it must carry `proofPurpose:
//! assertionMethod` with the key listed under the signer's `assertionMethod`.
//!
//! ## Deactivated signers
//!
//! A `did:webvh` signer whose DID is deactivated is refused on the operational
//! and approval paths, whatever its last document lists (see
//! `DeactivationCache`). The verdict is remembered for the DID cache TTL, in a
//! bounded map, and is re-read whenever the DID cache re-resolves the document.
//!
//! ## Unreachable signers
//!
//! A signer whose DID cannot be resolved (its log is unreachable, or its status
//! cannot be read) is refused with an error that says so
//! ([`is_unreachable`]); callers report it as retryable, since the same
//! document may verify once the DID is reachable again.
//!
//! ## Key rotation and the DID cache
//!
//! Keys are resolved through the DID cache, whose TTL is bounded
//! ([`crate::server::identity::DID_CACHE_TTL_SECS`]). A peer that has just
//! rotated signs with a key its cached document does not list yet, so a proof
//! that fails against a cached document is retried **once** against a freshly
//! resolved one before it is refused. The forced refresh is rate-limited per
//! DID ([`FORCED_REFRESH_INTERVAL`]) so a stream of bad proofs cannot turn into
//! a stream of outbound resolutions.

use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};

use affinidi_data_integrity::{DataIntegrityError, ResolvedKey, SignatureFailure, VerifyOptions};
use affinidi_did_resolver_cache_sdk::DIDCacheClient;
use async_trait::async_trait;
use didwebvh_rs::host_policy::HostPolicy;
use didwebvh_rs::resolve::ResolveOptions;
use serde::Serialize;
use trust_tasks_proof::affinidi::{
    CachedDidResolver, ProofPurpose, ProofPurposeResolver, PurposeBound,
};
use trust_tasks_rs::{ProofVerifier, TrustTask, VerificationError};

/// The only `proofPurpose` an operational (sender-bound) proof may carry.
pub const OPERATIONAL_PROOF_PURPOSE: &str = "authentication";

/// The only `proofPurpose` a human approver's decision may carry.
pub const APPROVAL_PROOF_PURPOSE: &str = "assertionMethod";

/// Marks a verification failure caused by a signer's DID being unreachable
/// (not by anything wrong with the proof). See [`is_unreachable`].
const UNREACHABLE: &str = "signer DID unreachable";

/// Marks a refusal because the signer deactivated its DID. Final: a
/// `did:webvh` deactivation cannot be undone, so no fresh resolution is tried.
const DEACTIVATED: &str = "is deactivated; its keys are no longer valid";

/// Most DIDs whose deactivation verdict is remembered at once.
const DEACTIVATION_CACHE_CAPACITY: usize = 4096;

/// Whether a verification failure was caused by the signer's DID being
/// unreachable — a condition that may clear, unlike a bad proof.
pub fn is_unreachable(err: &VerificationError) -> bool {
    matches!(err, VerificationError::Other(m) if m.contains(UNREACHABLE))
}

/// Minimum spacing between forced re-resolutions of one DID.
pub const FORCED_REFRESH_INTERVAL: Duration = Duration::from_secs(30);

/// One bearer session's signing delegate: the only key, and the only
/// principal, a delegated proof may name.
#[derive(Clone, Debug)]
struct SessionDelegate {
    principal: String,
    verification_method: String,
}

/// Forces the next lookup of a DID to resolve it fresh. Returns whether it did,
/// i.e. whether a retry could see a different document.
#[async_trait]
trait StaleKeyRefresh: Send + Sync {
    async fn refresh(&self, did: &str) -> bool;
}

/// Allows one forced refresh per DID per [`FORCED_REFRESH_INTERVAL`].
#[derive(Default)]
struct RefreshLimiter {
    last: Mutex<HashMap<String, Instant>>,
}

impl RefreshLimiter {
    fn allow(&self, did: &str, now: Instant) -> bool {
        let mut last = self.last.lock().unwrap_or_else(|p| p.into_inner());
        if last
            .get(did)
            .is_some_and(|t| now.duration_since(*t) < FORCED_REFRESH_INTERVAL)
        {
            return false;
        }
        last.retain(|_, t| now.duration_since(*t) < FORCED_REFRESH_INTERVAL);
        last.insert(did.to_string(), now);
        true
    }
}

/// Evicts a DID from the shared DID cache (and its deactivation verdict),
/// rate-limited per DID.
struct CacheRefresher {
    client: DIDCacheClient,
    limiter: RefreshLimiter,
    deactivation: Arc<DeactivationCache>,
}

#[async_trait]
impl StaleKeyRefresh for CacheRefresher {
    async fn refresh(&self, did: &str) -> bool {
        if !self.limiter.allow(did, Instant::now()) {
            return false;
        }
        self.client.remove(did).await;
        self.deactivation.forget(did);
        true
    }
}

/// Whether a `did:webvh` signer has deactivated its DID, remembered for the
/// DID cache TTL.
///
/// The DID cache keeps only the document and drops resolution metadata. Before
/// `affinidi-did-resolver-cache-sdk` 0.8.39 a deactivated webvh DID still
/// resolved to its last document — keys included — and a document cached
/// before the deactivation still does. So deactivation is read from the DID's
/// own log (`didwebvh-rs` resolution metadata), both after a resolution and
/// when one fails: 0.8.39 refuses to resolve a deactivated did:webvh at all,
/// and that refusal must read as final, not as an unreachable signer. A DID whose deactivation cannot be established is refused: an
/// unreadable log proves nothing about the key.
///
/// The verdict follows the DID cache: it is reused while the cache serves the
/// same document and younger than the cache TTL, and re-read when the cache
/// resolved the document afresh (or the verdict aged out). The map is bounded
/// ([`DEACTIVATION_CACHE_CAPACITY`]); expired verdicts are dropped first.
///
/// The log is fetched under `host_policy`, which must be the policy the DID
/// cache resolves with: a signer whose document the cache may fetch has to
/// have a log this check may fetch too, or every proof from it is refused as
/// unreachable.
#[derive(Default)]
struct DeactivationCache {
    verdicts: Mutex<HashMap<String, (Instant, bool)>>,
    host_policy: HostPolicy,
}

impl DeactivationCache {
    fn ttl() -> Duration {
        Duration::from_secs(u64::from(crate::server::identity::DID_CACHE_TTL_SECS))
    }

    fn forget(&self, did: &str) {
        self.verdicts
            .lock()
            .unwrap_or_else(|p| p.into_inner())
            .remove(did);
    }

    /// The remembered verdict, when one is fresh and the DID cache served the
    /// document it was read alongside.
    fn cached(&self, did: &str, document_cached: bool) -> Option<bool> {
        if !document_cached {
            return None;
        }
        self.verdicts
            .lock()
            .unwrap_or_else(|p| p.into_inner())
            .get(did)
            .filter(|(at, _)| at.elapsed() < Self::ttl())
            .map(|(_, v)| *v)
    }

    fn remember(&self, did: &str, deactivated: bool) {
        let mut verdicts = self.verdicts.lock().unwrap_or_else(|p| p.into_inner());
        if verdicts.len() >= DEACTIVATION_CACHE_CAPACITY && !verdicts.contains_key(did) {
            let ttl = Self::ttl();
            verdicts.retain(|_, (at, _)| at.elapsed() < ttl);
            if verdicts.len() >= DEACTIVATION_CACHE_CAPACITY
                && let Some(oldest) = verdicts
                    .iter()
                    .min_by_key(|(_, (at, _))| *at)
                    .map(|(k, _)| k.clone())
            {
                verdicts.remove(&oldest);
            }
        }
        verdicts.insert(did.to_string(), (Instant::now(), deactivated));
    }

    async fn is_deactivated(
        &self,
        did: &str,
        document_cached: bool,
    ) -> Result<bool, DataIntegrityError> {
        if let Some(verdict) = self.cached(did, document_cached) {
            return Ok(verdict);
        }
        let mut state = didwebvh_rs::DIDWebVHState::default();
        let options = ResolveOptions::default().with_host_policy(self.host_policy);
        let deactivated = state
            .resolve(did, options)
            .await
            .map(|(_, meta)| meta.deactivated)
            .map_err(|e| {
                DataIntegrityError::Resolver(format!(
                    "{UNREACHABLE}: cannot read the DID log of {did} to establish whether it is \
                     deactivated ({e})"
                ))
            })?;
        self.remember(did, deactivated);
        Ok(deactivated)
    }
}

/// Resolves a verification method for a proof purpose through the library's
/// relationship check ([`CachedDidResolver`]: the key must be listed under the
/// relationship the purpose names, and controlled by the DID naming it), after
/// telling an unreachable signer apart from a bad proof, and refusing a
/// deactivated `did:webvh` signer.
struct SignerKeyResolver {
    client: DIDCacheClient,
    decode: CachedDidResolver,
    /// `None` only in tests that resolve from documents placed in the cache.
    deactivation: Option<Arc<DeactivationCache>>,
}

#[async_trait]
impl ProofPurposeResolver for SignerKeyResolver {
    async fn resolve_vm_for_purpose(
        &self,
        vm: &str,
        purpose: ProofPurpose,
    ) -> Result<ResolvedKey, DataIntegrityError> {
        let did = controller_did(vm);
        let resolved = match self.client.resolve(did).await {
            Ok(resolved) => resolved,
            Err(e) => {
                // The cache SDK (0.8.39+) refuses to resolve a deactivated
                // did:webvh. That is final, not an unreachable signer: ask the
                // DID's own log, so it is not retried as if it might come back.
                if did.starts_with("did:webvh:")
                    && let Some(deactivation) = &self.deactivation
                    && let Ok(true) = deactivation.is_deactivated(did, false).await
                {
                    return Err(DataIntegrityError::Resolver(format!("{did} {DEACTIVATED}")));
                }
                return Err(DataIntegrityError::Resolver(format!(
                    "{UNREACHABLE}: cannot resolve {did} (is its DID document reachable from \
                     this service?): {e}"
                )));
            }
        };
        // The relationship check (and key decoding) is the library's.
        let key = self.decode.resolve_vm_for_purpose(vm, purpose).await?;
        // A deactivated DID's keys sign nothing.
        if did.starts_with("did:webvh:")
            && let Some(deactivation) = &self.deactivation
            && deactivation.is_deactivated(did, resolved.cache_hit).await?
        {
            return Err(DataIntegrityError::Resolver(format!("{did} {DEACTIVATED}")));
        }
        Ok(key)
    }
}

/// A [`ProofVerifier`] that requires an in-band `issuer` and binds the proof's
/// `verificationMethod` to it. See the module docs for the security rationale.
#[derive(Clone)]
pub struct TransportBoundVerifier {
    /// Resolves keys for [`ProofVerifier::verify`].
    resolver: Arc<dyn ProofPurposeResolver>,
    /// Resolves keys for the operational and approval checks, which also
    /// refuse a deactivated signer.
    signer_resolver: Arc<dyn ProofPurposeResolver>,
    refresher: Option<Arc<dyn StaleKeyRefresh>>,
    options: VerifyOptions,
    delegate: Option<SessionDelegate>,
    /// The deactivation verdicts `signer_resolver` consults; `None` for a
    /// caller-supplied resolver. Reachable only through the `test-support`
    /// seam [`Self::record_deactivation_verdict`].
    #[cfg_attr(not(any(test, feature = "test-support")), allow(dead_code))]
    deactivation: Option<Arc<DeactivationCache>>,
}

/// Build the proof verifier a service checks inbound Trust Task documents with,
/// over its configured DID cache: [`TransportBoundVerifier::with_did_cache`],
/// so a deactivated `did:webvh` signer is refused, an unreachable signer is
/// reported as retryable ([`is_unreachable`]), and a proof failing against a
/// cached document is retried once against a fresh one (at most one forced
/// re-resolution per DID per [`FORCED_REFRESH_INTERVAL`]).
///
/// Every service (control plane, server, and each half of the daemon) builds
/// its verifier here, so they cannot drift apart. Build it once, at startup,
/// and keep it: the verifier remembers DID-status verdicts for the DID cache
/// TTL and rate-limits forced re-resolutions, and a verifier built per message
/// would remember nothing and limit nothing. `None` when no resolver is
/// configured, in which case no signed document can be accepted.
pub fn build_verifier(
    did_resolver: Option<&DIDCacheClient>,
) -> Option<Arc<TransportBoundVerifier>> {
    did_resolver
        .cloned()
        .map(|client| Arc::new(TransportBoundVerifier::with_did_cache(client)))
}

impl TransportBoundVerifier {
    /// Construct a verifier over a caller-supplied `resolver`, used for both
    /// general and operational checks. For resolvers whose documents cannot
    /// separate relationships (the local `did:key` resolver, where the one key
    /// is by construction an authentication key). Production code uses
    /// [`Self::with_did_cache`].
    pub fn with_resolver(resolver: Arc<dyn ProofPurposeResolver>) -> Self {
        Self {
            signer_resolver: resolver.clone(),
            resolver,
            refresher: None,
            options: VerifyOptions::default(),
            delegate: None,
            deactivation: None,
        }
    }

    /// Construct a verifier over a configured DID cache client: operational
    /// proofs must use an `authentication` key, and a proof failing against a
    /// cached document is retried once against a fresh one.
    ///
    /// A `did:webvh` signer's log is read under [`HostPolicy::PublicOnly`], the
    /// DID cache's own default; a client built with another policy needs
    /// [`Self::with_did_cache_and_host_policy`].
    pub fn with_did_cache(client: DIDCacheClient) -> Self {
        Self::with_did_cache_and_host_policy(client, HostPolicy::PublicOnly)
    }

    /// [`Self::with_did_cache`] for a client built with `host_policy` — pass
    /// the same policy given to its `DIDCacheConfigBuilder::with_host_policy`.
    pub fn with_did_cache_and_host_policy(client: DIDCacheClient, host_policy: HostPolicy) -> Self {
        let decode = CachedDidResolver::new(Arc::new(client.clone()));
        let deactivation = Arc::new(DeactivationCache {
            host_policy,
            ..DeactivationCache::default()
        });
        Self {
            resolver: Arc::new(decode.clone()),
            signer_resolver: Arc::new(SignerKeyResolver {
                client: client.clone(),
                decode,
                deactivation: Some(deactivation.clone()),
            }),
            refresher: Some(Arc::new(CacheRefresher {
                client,
                limiter: RefreshLimiter::default(),
                deactivation: deactivation.clone(),
            })),
            options: VerifyOptions::default(),
            delegate: None,
            deactivation: Some(deactivation),
        }
    }

    /// Record whether `did` is deactivated, as if its DID log had just been
    /// read, so a test can exercise the deactivation refusal of a
    /// [`Self::with_did_cache`] verifier without serving a `did:webvh` log.
    /// The verdict is used only while the DID cache serves its document from
    /// cache, exactly like one read from the log. A no-op on a verifier over a
    /// caller-supplied resolver.
    #[cfg(any(test, feature = "test-support"))]
    pub fn record_deactivation_verdict(&self, did: &str, deactivated: bool) {
        if let Some(deactivation) = &self.deactivation {
            deactivation.remember(did, deactivated);
        }
    }

    /// Override the [`VerifyOptions`] (expected proof purpose, domain /
    /// challenge, …). Defaults match `VerifyOptions::default()`.
    pub fn with_options(mut self, options: VerifyOptions) -> Self {
        self.options = options;
        self
    }

    /// Additionally accept documents whose `issuer` is `principal` and whose
    /// proof is signed by exactly `verification_method` — a bearer session's
    /// JWT-bound signing key acting for the JWT subject.
    ///
    /// Build this per request, from an already-verified bearer token, and never
    /// on a verifier shared across callers.
    pub fn with_session_delegate(
        mut self,
        principal: impl Into<String>,
        verification_method: impl Into<String>,
    ) -> Self {
        self.delegate = Some(SessionDelegate {
            principal: principal.into(),
            verification_method: verification_method.into(),
        });
        self
    }

    /// Verify an operational proof: everything [`ProofVerifier::verify`]
    /// checks, plus `proofPurpose: authentication` and a `verificationMethod`
    /// listed under the signer's `authentication` relationship.
    pub async fn verify_operational<P>(&self, doc: &TrustTask<P>) -> Result<(), VerificationError>
    where
        P: Serialize + Send + Sync,
    {
        if let Some(proof) = &doc.proof
            && proof.proof_purpose != OPERATIONAL_PROOF_PURPOSE
        {
            return Err(VerificationError::MalformedProof(format!(
                "proofPurpose must be `{OPERATIONAL_PROOF_PURPOSE}` for this message, not `{}`",
                proof.proof_purpose
            )));
        }
        self.verify_with(
            doc,
            &*self.signer_resolver,
            ProofPurpose::Authentication,
            Delegation::Allowed,
        )
        .await
    }

    /// Verify a human approver's decision (consent decision, step-up
    /// approval): everything [`ProofVerifier::verify`] checks, plus
    /// `proofPurpose: assertionMethod`, a `verificationMethod` listed under the
    /// signer's `assertionMethod` relationship, and — for `did:webvh` — a signer
    /// that has not deactivated its DID.
    ///
    /// **Never by a session delegate.** A session key stands in for its
    /// subject on ordinary requests only (`auth/authenticate/0.2` Conformance
    /// item 11). An approval must be signed by a key under the approver's *own*
    /// `assertionMethod` relationship. A `did:key` document lists its one key
    /// under every relationship, so without this refusal a session key could
    /// approve its own session's step-up.
    pub async fn verify_approval<P>(&self, doc: &TrustTask<P>) -> Result<(), VerificationError>
    where
        P: Serialize + Send + Sync,
    {
        if let Some(proof) = &doc.proof
            && proof.proof_purpose != APPROVAL_PROOF_PURPOSE
        {
            return Err(VerificationError::MalformedProof(format!(
                "proofPurpose must be `{APPROVAL_PROOF_PURPOSE}` for an approver's decision, not `{}`",
                proof.proof_purpose
            )));
        }
        self.verify_with(
            doc,
            &*self.signer_resolver,
            ProofPurpose::AssertionMethod,
            Delegation::Refused,
        )
        .await
    }

    /// Verify `doc` with its key resolved for `purpose`: the key must be listed
    /// under the relationship `purpose` names in the signer's DID document.
    async fn verify_with<P>(
        &self,
        doc: &TrustTask<P>,
        resolver: &dyn ProofPurposeResolver,
        purpose: ProofPurpose,
        delegation: Delegation,
    ) -> Result<(), VerificationError>
    where
        P: Serialize + Send + Sync,
    {
        let (parsed_proof, doc_value) = self.prepare(doc, delegation)?;
        let resolver = PurposeBound::new(resolver, purpose);
        let attempt = parsed_proof
            .verify(&doc_value, &resolver, self.options.clone())
            .await;
        let err = match attempt {
            Ok(_) => return Ok(()),
            Err(e) => e,
        };
        // Only a failure that a different document could cure is worth a fresh
        // resolution: the key was not found, or the key found did not match.
        // A deactivated signer is final — deactivation cannot be undone.
        let retryable = match &err {
            DataIntegrityError::Resolver(m) => !m.contains(DEACTIVATED),
            DataIntegrityError::InvalidSignature { .. } => true,
            _ => false,
        };
        let vm = doc
            .proof
            .as_ref()
            .map(|p| p.verification_method.clone())
            .unwrap_or_default();
        if retryable
            && let Some(refresher) = &self.refresher
            && refresher.refresh(controller_did(&vm)).await
        {
            tracing::debug!(vm, error = %err, "proof failed against cached DID document; retrying fresh");
            return parsed_proof
                .verify(&doc_value, &resolver, self.options.clone())
                .await
                .map(|_| ())
                .map_err(map_error);
        }
        Err(map_error(err))
    }

    /// Steps shared by every verification: parse the proof, strip it from the
    /// document, and enforce the issuer binding.
    fn prepare<P>(
        &self,
        doc: &TrustTask<P>,
        delegation: Delegation,
    ) -> Result<
        (
            affinidi_data_integrity::DataIntegrityProof,
            serde_json::Value,
        ),
        VerificationError,
    >
    where
        P: Serialize + Send + Sync,
    {
        // ─── 1. Extract the proof.
        let Some(proof) = &doc.proof else {
            return Err(VerificationError::MalformedProof(
                "document carries no proof member".to_string(),
            ));
        };

        // ─── 2. Parse our typed Proof into the Affinidi DataIntegrityProof
        //        via the crate's public helper (members-equivalent, just
        //        different serde casing).
        let proof_value = serde_json::to_value(proof)
            .map_err(|e| VerificationError::MalformedProof(format!("serialise proof: {e}")))?;
        let parsed_proof = trust_tasks_proof::affinidi::parse_data_integrity_proof(&proof_value)?;

        // ─── 3. Serialise the document minus the proof member (W3C Data
        //        Integrity canonicalises over the doc + proof config, not
        //        the embedded proof object).
        let mut doc_value = serde_json::to_value(doc).map_err(|e| {
            VerificationError::Other(format!("serialise TrustTask for verification: {e}"))
        })?;
        if let Some(obj) = doc_value.as_object_mut() {
            obj.remove("proof");
        }

        // ─── 3b. issuer↔verificationMethod binding — unconditional.
        let Some(issuer) = doc_value.get("issuer").and_then(|v| v.as_str()) else {
            return Err(VerificationError::IssuerMismatch(
                "document carries a proof but no in-band issuer to bind it to".to_string(),
            ));
        };
        let vm = proof.verification_method.as_str();
        let self_signed = controller_did(vm) == issuer;
        let delegated = delegation == Delegation::Allowed
            && self
                .delegate
                .as_ref()
                .is_some_and(|d| d.verification_method == vm && d.principal == issuer);
        if !self_signed && !delegated {
            return Err(VerificationError::IssuerMismatch(format!(
                "verificationMethod is controlled by {}, not the document issuer {issuer}",
                controller_did(vm)
            )));
        }
        Ok((parsed_proof, doc_value))
    }
}

/// The DID that controls a verification method URL (the part before `#`).
pub fn controller_did(verification_method: &str) -> &str {
    verification_method
        .split('#')
        .next()
        .unwrap_or(verification_method)
}

#[async_trait]
impl ProofVerifier for TransportBoundVerifier {
    async fn verify<P>(&self, doc: &TrustTask<P>) -> Result<(), VerificationError>
    where
        P: Serialize + Send + Sync,
    {
        // The key must be authorised for the purpose the proof declares.
        let purpose = doc
            .proof
            .as_ref()
            .map(|p| ProofPurpose::parse(&p.proof_purpose))
            .transpose()
            .map_err(map_error)?
            .unwrap_or(ProofPurpose::Authentication);
        // An `assertionMethod` proof is an attestation, and a session delegate
        // never makes one. See `verify_approval`.
        let delegation = if matches!(purpose, ProofPurpose::AssertionMethod) {
            Delegation::Refused
        } else {
            Delegation::Allowed
        };
        self.verify_with(doc, &*self.resolver, purpose, delegation)
            .await
    }
}

/// Whether a check may accept the per-request session delegate
/// ([`TransportBoundVerifier::with_session_delegate`]).
#[derive(Clone, Copy, PartialEq, Eq)]
enum Delegation {
    /// An ordinary request: the delegate may stand in for its principal.
    Allowed,
    /// An attestation: only the signer's own key counts.
    Refused,
}

/// Map [`DataIntegrityError`] into the framework's [`VerificationError`]
/// taxonomy. Mirrors `trust_tasks_proof::affinidi`'s private `map_error`
/// (kept in sync with the pinned crate version) so wire `proof_invalid`
/// diagnostics match the stock verifier's.
fn map_error(err: DataIntegrityError) -> VerificationError {
    match err {
        DataIntegrityError::UnsupportedCryptoSuite { name } => {
            VerificationError::UnsupportedCryptosuite(name)
        }
        DataIntegrityError::KeyTypeMismatch {
            expected,
            actual,
            suite,
        } => VerificationError::IssuerMismatch(format!(
            "key type {actual:?} does not match cryptosuite {suite:?} (expected {expected:?})"
        )),
        DataIntegrityError::InvalidSignature { reason, .. } => match reason {
            SignatureFailure::Malformed | SignatureFailure::Invalid => {
                VerificationError::SignatureInvalid
            }
            _ => VerificationError::SignatureInvalid,
        },
        DataIntegrityError::InvalidPublicKey { reason, .. } => {
            VerificationError::MalformedProof(format!("public key: {reason}"))
        }
        DataIntegrityError::Canonicalization(reason) => {
            VerificationError::Other(format!("canonicalisation: {reason}"))
        }
        DataIntegrityError::MalformedProof(reason) => VerificationError::MalformedProof(reason),
        other => VerificationError::Other(other.to_string()),
    }
}

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

    use affinidi_data_integrity::{
        DataIntegrityProof, DidKeyResolver, SignOptions, VerificationMethodResolver,
    };
    use affinidi_secrets_resolver::secrets::Secret;
    use serde_json::{Value, json};
    use trust_tasks_rs::TrustTask;

    /// A verifier over the local `did:key` resolver (no I/O).
    fn verifier() -> TransportBoundVerifier {
        TransportBoundVerifier::with_resolver(Arc::new(DidKeyResolver))
    }

    /// The base envelope body (no `issuer`, no `proof`). Callers add an
    /// `issuer` when exercising the bind-when-present path.
    fn base_body() -> Value {
        json!({
            "id": "urn:uuid:24f1b27f-36d9-49af-9a20-751def9000aa",
            "type": "https://trusttasks.org/spec/acl/grant/0.1",
            "recipient": "did:web:server.example",
            "issuedAt": "2026-06-09T08:51:03Z",
            "payload": { "entry": { "subject": "did:web:alice.example", "role": "owner" } },
        })
    }

    /// Sign `body` (an object with no `proof` member) with a fresh ed25519
    /// `did:key`, returning the proof-bearing `TrustTask<Value>` plus the
    /// signer's bare `did:key` (no fragment). The signing input is the
    /// document's canonical `TrustTask` serialisation minus `proof` —
    /// exactly what [`TransportBoundVerifier::verify`] reconstructs.
    async fn sign(body: Value) -> (TrustTask<Value>, String) {
        sign_with(body, SignOptions::new()).await
    }

    /// [`sign`] with explicit options (for a proof purpose).
    async fn sign_with(body: Value, options: SignOptions) -> (TrustTask<Value>, String) {
        // Deterministic seed → reproducible key; any 32 bytes work.
        let secret = Secret::generate_ed25519(None, Some(&[7u8; 32]));
        let pk_mb = secret.get_public_keymultibase().expect("multibase pubkey");
        let did_key = format!("did:key:{pk_mb}");
        let mut signer = secret.clone();
        signer.id = format!("{did_key}#{pk_mb}");

        // Canonical no-proof form (skip_serializing_if drops absent fields).
        let doc_noproof: TrustTask<Value> =
            serde_json::from_value(body).expect("body parses as TrustTask");
        let signing_value = serde_json::to_value(&doc_noproof).expect("serialise doc");

        let di_proof = DataIntegrityProof::sign(&signing_value, &signer, options)
            .await
            .expect("sign");

        let mut full = signing_value;
        full.as_object_mut().unwrap().insert(
            "proof".to_string(),
            serde_json::to_value(&di_proof).unwrap(),
        );
        let doc: TrustTask<Value> = serde_json::from_value(full).expect("proofed doc parses");
        (doc, did_key)
    }

    /// GUARD: `issuer` absent → rejected, even though the signature itself is
    /// valid. A proof that names no issuer must never verify as a bare
    /// possession check.
    #[tokio::test]
    async fn issuer_absent_rejected() {
        let (doc, _did) = sign(base_body()).await;
        assert!(doc.issuer.is_none(), "test fixture must omit issuer");
        let err = verifier().verify(&doc).await.expect_err("must reject");
        assert!(
            matches!(err, VerificationError::IssuerMismatch(_)),
            "expected IssuerMismatch, got {err:?}"
        );
    }

    /// Passkey session delegate: `issuer` is the principal, the proof is signed
    /// by the delegate key → accepted.
    #[tokio::test]
    async fn session_delegate_accepts_its_key_for_its_principal() {
        let mut body = base_body();
        body.as_object_mut()
            .unwrap()
            .insert("issuer".to_string(), json!("did:web:alice.example"));
        // A session key signs ordinary requests, so `authentication`.
        let (doc, signer_did) = sign_with(
            body,
            SignOptions::new().with_proof_purpose(OPERATIONAL_PROOF_PURPOSE),
        )
        .await;
        let vm = doc.proof.as_ref().unwrap().verification_method.clone();
        assert!(vm.starts_with(&signer_did));
        verifier()
            .with_session_delegate("did:web:alice.example", vm)
            .verify(&doc)
            .await
            .expect("delegated proof verifies");
    }

    /// GUARD: a delegate is scoped to one principal — the same key acting for a
    /// different issuer is refused.
    #[tokio::test]
    async fn session_delegate_rejects_other_principal() {
        let mut body = base_body();
        body.as_object_mut()
            .unwrap()
            .insert("issuer".to_string(), json!("did:web:admin.example"));
        let (doc, _) = sign(body).await;
        let vm = doc.proof.as_ref().unwrap().verification_method.clone();
        let err = verifier()
            .with_session_delegate("did:web:alice.example", vm)
            .verify(&doc)
            .await
            .expect_err("must reject");
        assert!(matches!(err, VerificationError::IssuerMismatch(_)));
    }

    /// GUARD (`auth/authenticate/0.2` Conformance item 11): a session key never
    /// signs an approval, even for its own principal.
    ///
    /// The first assertion shows why the refusal has to be explicit. A
    /// `did:key` document lists its key under `assertionMethod`, so the same
    /// key signing as *itself* is a valid approval. Only the delegation is
    /// refused: acting for the principal, it is not the principal's own
    /// `assertionMethod` key.
    #[tokio::test]
    async fn session_delegate_never_signs_an_approval() {
        let approval = SignOptions::new().with_proof_purpose(APPROVAL_PROOF_PURPOSE);

        let (as_itself, signer_did) = sign_with(base_body(), approval.clone()).await;
        let mut as_itself_body = serde_json::to_value(&as_itself).unwrap();
        as_itself_body["issuer"] = json!(signer_did);
        as_itself_body.as_object_mut().unwrap().remove("proof");
        let (as_itself, _) = sign_with(as_itself_body, approval.clone()).await;
        verifier()
            .verify_approval(&as_itself)
            .await
            .expect("a did:key's own assertionMethod proof verifies");

        let mut body = base_body();
        body["issuer"] = json!("did:web:alice.example");
        let (doc, _) = sign_with(body, approval).await;
        let vm = doc.proof.as_ref().unwrap().verification_method.clone();
        let delegated = verifier().with_session_delegate("did:web:alice.example", vm);

        let err = delegated
            .verify_approval(&doc)
            .await
            .expect_err("a delegate must not approve");
        assert!(
            matches!(err, VerificationError::IssuerMismatch(_)),
            "{err:?}"
        );
        let err = delegated
            .verify(&doc)
            .await
            .expect_err("nor pass an assertionMethod proof through the generic check");
        assert!(
            matches!(err, VerificationError::IssuerMismatch(_)),
            "{err:?}"
        );
    }

    /// GUARD: a delegate is scoped to one key — a different key acting for the
    /// principal is refused.
    #[tokio::test]
    async fn session_delegate_rejects_other_key() {
        let mut body = base_body();
        body.as_object_mut()
            .unwrap()
            .insert("issuer".to_string(), json!("did:web:alice.example"));
        let (doc, _) = sign(body).await;
        let err = verifier()
            .with_session_delegate("did:web:alice.example", "did:key:z6MkOther#z6MkOther")
            .verify(&doc)
            .await
            .expect_err("must reject");
        assert!(matches!(err, VerificationError::IssuerMismatch(_)));
    }

    /// Wallet path: `issuer` present and equal to the signer's DID → the
    /// binding is enforced and passes.
    #[tokio::test]
    async fn issuer_present_matching_verifies() {
        // We can't know the did:key before generating it, so sign first,
        // then re-sign with the matching issuer in-band.
        let secret = Secret::generate_ed25519(None, Some(&[7u8; 32]));
        let pk_mb = secret.get_public_keymultibase().unwrap();
        let did_key = format!("did:key:{pk_mb}");
        let mut body = base_body();
        body.as_object_mut()
            .unwrap()
            .insert("issuer".to_string(), json!(did_key));
        let (doc, signer_did) = sign(body).await;
        assert_eq!(doc.issuer.as_deref(), Some(signer_did.as_str()));
        verifier()
            .verify(&doc)
            .await
            .expect("issuer-matched proof verifies");
    }

    /// GUARD: `issuer` present but NOT the signer's DID → rejected with
    /// `IssuerMismatch`, *before* the signature is even checked. This is the
    /// anti-spoofing invariant that must never regress into an
    /// unconditional skip.
    #[tokio::test]
    async fn issuer_present_mismatch_rejected() {
        let mut body = base_body();
        body.as_object_mut()
            .unwrap()
            .insert("issuer".to_string(), json!("did:web:evil.example"));
        let (doc, signer_did) = sign(body).await;
        assert_ne!(signer_did, "did:web:evil.example");
        let err = verifier().verify(&doc).await.expect_err("must reject");
        assert!(
            matches!(err, VerificationError::IssuerMismatch(_)),
            "expected IssuerMismatch, got {err:?}"
        );
    }

    /// The signature is actually verified: a tampered payload (after signing)
    /// is rejected, not waved through.
    #[tokio::test]
    async fn tampered_payload_rejected() {
        let secret = Secret::generate_ed25519(None, Some(&[7u8; 32]));
        let pk_mb = secret.get_public_keymultibase().unwrap();
        let mut body = base_body();
        body.as_object_mut()
            .unwrap()
            .insert("issuer".to_string(), json!(format!("did:key:{pk_mb}")));
        let (mut doc, _did) = sign(body).await;
        // Mutate a signed field; the proof no longer covers the document.
        doc.payload = json!({ "entry": { "subject": "did:web:mallory.example", "role": "admin" } });
        let err = verifier()
            .verify(&doc)
            .await
            .expect_err("must reject tampered doc");
        assert!(
            matches!(err, VerificationError::SignatureInvalid),
            "expected SignatureInvalid, got {err:?}"
        );
    }

    /// A document with no `proof` member is malformed for a verifier.
    #[tokio::test]
    async fn missing_proof_rejected() {
        let doc: TrustTask<Value> = serde_json::from_value(base_body()).expect("body parses");
        let err = verifier().verify(&doc).await.expect_err("must reject");
        assert!(
            matches!(err, VerificationError::MalformedProof(_)),
            "expected MalformedProof, got {err:?}"
        );
    }

    // ─── Stale cached DID document ───

    /// A resolver that reports the key missing until the refresher has
    /// "re-resolved" — a peer that rotated keys since its document was cached.
    struct RotatedResolver {
        refreshed: Arc<std::sync::atomic::AtomicBool>,
    }

    #[async_trait]
    impl ProofPurposeResolver for RotatedResolver {
        async fn resolve_vm_for_purpose(
            &self,
            vm: &str,
            purpose: ProofPurpose,
        ) -> Result<ResolvedKey, DataIntegrityError> {
            if self.refreshed.load(std::sync::atomic::Ordering::SeqCst) {
                DidKeyResolver.resolve_vm_for_purpose(vm, purpose).await
            } else {
                Err(DataIntegrityError::Resolver(format!(
                    "{vm} not in cached document"
                )))
            }
        }
    }

    struct FlagRefresher {
        refreshed: Arc<std::sync::atomic::AtomicBool>,
        calls: std::sync::atomic::AtomicUsize,
        allow: bool,
    }

    #[async_trait]
    impl StaleKeyRefresh for FlagRefresher {
        async fn refresh(&self, _did: &str) -> bool {
            self.calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
            if self.allow {
                self.refreshed
                    .store(true, std::sync::atomic::Ordering::SeqCst);
            }
            self.allow
        }
    }

    fn rotated_verifier(allow: bool) -> (TransportBoundVerifier, Arc<FlagRefresher>) {
        let refreshed = Arc::new(std::sync::atomic::AtomicBool::new(false));
        let refresher = Arc::new(FlagRefresher {
            refreshed: refreshed.clone(),
            calls: Default::default(),
            allow,
        });
        let mut v = TransportBoundVerifier::with_resolver(Arc::new(RotatedResolver { refreshed }));
        v.refresher = Some(refresher.clone());
        (v, refresher)
    }

    async fn self_issued_doc() -> TrustTask<Value> {
        let secret = Secret::generate_ed25519(None, Some(&[7u8; 32]));
        let pk_mb = secret.get_public_keymultibase().unwrap();
        let mut body = base_body();
        body.as_object_mut()
            .unwrap()
            .insert("issuer".to_string(), json!(format!("did:key:{pk_mb}")));
        sign(body).await.0
    }

    /// A proof that fails against the cached document verifies after one fresh
    /// resolution — a rotation does not open a rejection window.
    #[tokio::test]
    async fn a_stale_cached_document_is_re_resolved_once_before_refusing() {
        let (v, refresher) = rotated_verifier(true);
        v.verify(&self_issued_doc().await)
            .await
            .expect("verifies after refresh");
        assert_eq!(refresher.calls.load(std::sync::atomic::Ordering::SeqCst), 1);
    }

    /// When a refresh is not allowed (rate limit), the failure stands.
    #[tokio::test]
    async fn without_a_refresh_the_stale_failure_stands() {
        let (v, refresher) = rotated_verifier(false);
        assert!(v.verify(&self_issued_doc().await).await.is_err());
        assert_eq!(refresher.calls.load(std::sync::atomic::Ordering::SeqCst), 1);
    }

    /// A failure a fresh document cannot cure (issuer binding) triggers no
    /// resolution at all.
    #[tokio::test]
    async fn a_binding_failure_does_not_trigger_a_refresh() {
        let (v, refresher) = rotated_verifier(true);
        let mut body = base_body();
        body.as_object_mut()
            .unwrap()
            .insert("issuer".to_string(), json!("did:web:evil.example"));
        let (doc, _) = sign(body).await;
        assert!(matches!(
            v.verify(&doc).await,
            Err(VerificationError::IssuerMismatch(_))
        ));
        assert_eq!(refresher.calls.load(std::sync::atomic::Ordering::SeqCst), 0);
    }

    #[test]
    fn forced_refreshes_are_rate_limited_per_did() {
        let limiter = RefreshLimiter::default();
        let t0 = Instant::now();
        assert!(limiter.allow("did:example:a", t0));
        assert!(!limiter.allow("did:example:a", t0 + Duration::from_secs(1)));
        assert!(limiter.allow("did:example:b", t0 + Duration::from_secs(1)));
        assert!(limiter.allow("did:example:a", t0 + FORCED_REFRESH_INTERVAL));
    }

    /// Operational proofs must be `authentication`-purpose.
    #[tokio::test]
    async fn operational_verification_requires_authentication_purpose() {
        let doc = self_issued_doc().await;
        assert_eq!(doc.proof.as_ref().unwrap().proof_purpose, "assertionMethod");
        let err = verifier().verify_operational(&doc).await.unwrap_err();
        assert!(
            matches!(err, VerificationError::MalformedProof(_)),
            "{err:?}"
        );
    }

    /// Against a real DID document, an operational key must be listed under
    /// `authentication`; one listed only under `assertionMethod` is refused.
    #[tokio::test]
    async fn operational_keys_must_be_authentication_keys() {
        use affinidi_did_resolver_cache_sdk::config::DIDCacheConfigBuilder;

        let secret = Secret::generate_ed25519(None, Some(&[5u8; 32]));
        let pk = secret.get_public_keymultibase().unwrap();
        let mut client = DIDCacheClient::new(DIDCacheConfigBuilder::default().build())
            .await
            .unwrap();
        for (did, rel) in [
            ("did:web:auth.example", "authentication"),
            ("did:web:assert.example", "assertionMethod"),
        ] {
            let doc: affinidi_tdk::did_common::Document = serde_json::from_value(json!({
                "id": did,
                "verificationMethod": [{
                    "id": format!("{did}#key-1"),
                    "type": "Multikey",
                    "controller": did,
                    "publicKeyMultibase": pk,
                }],
                rel: [format!("{did}#key-1")],
            }))
            .unwrap();
            client.add_did_document(did, doc).await;
        }
        let signers = SignerKeyResolver {
            client: client.clone(),
            decode: CachedDidResolver::new(Arc::new(client)),
            deactivation: None,
        };
        let resolver = PurposeBound::new(&signers, ProofPurpose::Authentication);
        resolver
            .resolve_vm("did:web:auth.example#key-1")
            .await
            .expect("authentication key resolves");
        let err = resolver
            .resolve_vm("did:web:assert.example#key-1")
            .await
            .unwrap_err();
        assert!(
            err.to_string().contains("not listed under authentication"),
            "{err}"
        );

        // An approver's decision is the mirror image: its key must be listed
        // under `assertionMethod`, and an authentication-only key is refused.
        let approvals = PurposeBound::new(&signers, ProofPurpose::AssertionMethod);
        approvals
            .resolve_vm("did:web:assert.example#key-1")
            .await
            .expect("assertionMethod key resolves for an approval");
        let err = approvals
            .resolve_vm("did:web:auth.example#key-1")
            .await
            .unwrap_err();
        assert!(
            err.to_string().contains("not listed under assertionMethod"),
            "{err}"
        );
    }

    /// An approver's decision must carry `proofPurpose: assertionMethod`; an
    /// operational (`authentication`) proof is not a decision.
    #[tokio::test]
    async fn approval_verification_requires_assertion_method_purpose() {
        let doc = self_issued_doc().await;
        verifier()
            .verify_approval(&doc)
            .await
            .expect("an assertionMethod-purpose decision verifies");

        let secret = Secret::generate_ed25519(None, Some(&[7u8; 32]));
        let pk_mb = secret.get_public_keymultibase().unwrap();
        let did = format!("did:key:{pk_mb}");
        let mut signer = secret;
        signer.id = format!("{did}#{pk_mb}");
        let mut body = base_body();
        body.as_object_mut()
            .unwrap()
            .insert("issuer".to_string(), json!(did));
        let unsigned: TrustTask<Value> = serde_json::from_value(body).unwrap();
        let signed = super::super::bound::sign_document(&unsigned, &signer)
            .await
            .unwrap();
        assert_eq!(
            signed.proof.as_ref().unwrap().proof_purpose,
            "authentication"
        );
        let err = verifier().verify_approval(&signed).await.unwrap_err();
        assert!(
            matches!(err, VerificationError::MalformedProof(ref m) if m.contains("assertionMethod")),
            "{err:?}"
        );
    }

    /// A resolution failure is reported as the signer being unreachable — the
    /// retryable case — and nothing else is.
    #[test]
    fn unreachable_signers_are_distinguished_from_bad_proofs() {
        let unreachable = map_error(DataIntegrityError::Resolver(format!(
            "{UNREACHABLE}: cannot resolve did:webvh:QmX:gone.example"
        )));
        assert!(is_unreachable(&unreachable), "{unreachable:?}");
        assert!(unreachable.to_string().contains("gone.example"));
        let not_listed = map_error(DataIntegrityError::Resolver(
            "verificationMethod is not listed under authentication in its DID document".into(),
        ));
        assert!(!is_unreachable(&not_listed));
        assert!(!is_unreachable(&VerificationError::SignatureInvalid));
    }

    /// The deactivation verdict follows the DID cache: reused while the cache
    /// serves the same document, re-read when the cache resolved afresh.
    #[test]
    fn a_deactivation_verdict_is_reused_only_for_a_cached_document() {
        let cache = DeactivationCache::default();
        cache.remember("did:webvh:QmA:a.example", false);
        assert_eq!(cache.cached("did:webvh:QmA:a.example", true), Some(false));
        assert_eq!(cache.cached("did:webvh:QmA:a.example", false), None);
        assert_eq!(cache.cached("did:webvh:QmB:b.example", true), None);
    }

    /// The verdict map is bounded.
    #[test]
    fn the_deactivation_cache_is_bounded() {
        let cache = DeactivationCache::default();
        for i in 0..DEACTIVATION_CACHE_CAPACITY + 10 {
            cache.remember(&format!("did:webvh:Qm{i}:x.example"), false);
        }
        let len = cache.verdicts.lock().unwrap().len();
        assert!(len <= DEACTIVATION_CACHE_CAPACITY, "{len}");
        // The newest verdict survives eviction.
        let newest = format!("did:webvh:Qm{}:x.example", DEACTIVATION_CACHE_CAPACITY + 9);
        assert_eq!(cache.cached(&newest, true), Some(false));
    }

    /// A deactivated `did:webvh` signer is refused even though its last
    /// document still lists the key.
    #[tokio::test]
    async fn a_deactivated_webvh_signer_is_refused() {
        use affinidi_did_resolver_cache_sdk::config::DIDCacheConfigBuilder;

        let secret = Secret::generate_ed25519(None, Some(&[6u8; 32]));
        let pk = secret.get_public_keymultibase().unwrap();
        let mut client = DIDCacheClient::new(DIDCacheConfigBuilder::default().build())
            .await
            .unwrap();
        let live = "did:webvh:QmLive:live.example";
        let dead = "did:webvh:QmDead:dead.example";
        for did in [live, dead] {
            let doc: affinidi_tdk::did_common::Document = serde_json::from_value(json!({
                "id": did,
                "verificationMethod": [{
                    "id": format!("{did}#key-1"),
                    "type": "Multikey",
                    "controller": did,
                    "publicKeyMultibase": pk,
                }],
                "authentication": [format!("{did}#key-1")],
            }))
            .unwrap();
            client.add_did_document(did, doc).await;
        }
        let deactivation = Arc::new(DeactivationCache::default());
        {
            let mut v = deactivation.verdicts.lock().unwrap();
            v.insert(live.into(), (Instant::now(), false));
            v.insert(dead.into(), (Instant::now(), true));
        }
        let signers = SignerKeyResolver {
            client: client.clone(),
            decode: CachedDidResolver::new(Arc::new(client)),
            deactivation: Some(deactivation),
        };
        let resolver = PurposeBound::new(&signers, ProofPurpose::Authentication);
        resolver
            .resolve_vm(&format!("{live}#key-1"))
            .await
            .expect("a live signer resolves");
        let err = resolver
            .resolve_vm(&format!("{dead}#key-1"))
            .await
            .unwrap_err();
        assert!(err.to_string().contains("deactivated"), "{err}");
    }

    /// A signed did:webvh log for `localhost:{port}` with `secret` as its
    /// `authentication` key, ending in a deactivation when `deactivate`:
    /// the DID and its `did.jsonl`.
    async fn webvh_log(port: u16, secret: &Secret, deactivate: bool) -> (String, String) {
        use didwebvh_rs::{
            DIDWebVHState, Multibase, log_entry::LogEntryMethods, parameters::Parameters,
        };

        let mut update_key = Secret::generate_ed25519(None, None);
        let update_pk = update_key.get_public_keymultibase().unwrap();
        update_key.id = format!("did:key:{update_pk}#{update_pk}");
        let pk = secret.get_public_keymultibase().unwrap();
        let template = format!("did:webvh:{{SCID}}:localhost%3A{port}");
        let doc = json!({
            "id": template,
            "@context": ["https://www.w3.org/ns/did/v1"],
            "verificationMethod": [{
                "id": format!("{template}#key-1"),
                "type": "Multikey",
                "controller": template,
                "publicKeyMultibase": pk,
            }],
            "authentication": [format!("{template}#key-1")],
        });
        let params = Parameters {
            update_keys: Some(Arc::new(vec![Multibase::new(update_pk)])),
            portable: Some(false),
            ..Default::default()
        };
        // Backdated so a deactivation entry's versionTime is strictly later.
        let genesis = (chrono::Utc::now() - chrono::Duration::seconds(100)).fixed_offset();
        let mut state = DIDWebVHState::default();
        state
            .create_log_entry(Some(genesis), &doc, &params, &update_key)
            .await
            .unwrap();
        if deactivate {
            state.deactivate(&update_key).await.unwrap();
        }
        let did = state
            .log_entries()
            .last()
            .unwrap()
            .log_entry
            .get_did_document()
            .unwrap()["id"]
            .as_str()
            .unwrap()
            .to_string();
        let jsonl = state
            .log_entries()
            .iter()
            .map(|e| serde_json::to_string(&e.log_entry).unwrap())
            .collect::<Vec<_>>()
            .join("\n");
        (did, jsonl)
    }

    /// Serve `body` to every request on `listener`.
    fn serve(listener: tokio::net::TcpListener, body: String) {
        use tokio::io::{AsyncReadExt, AsyncWriteExt};
        tokio::spawn(async move {
            while let Ok((mut socket, _)) = listener.accept().await {
                let body = body.clone();
                tokio::spawn(async move {
                    let mut request = [0u8; 4096];
                    let _ = socket.read(&mut request).await;
                    let reply = format!(
                        "HTTP/1.1 200 OK\r\ncontent-type: text/jsonl\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
                        body.len()
                    );
                    let _ = socket.write_all(reply.as_bytes()).await;
                });
            }
        });
    }

    /// A deactivated `did:webvh` signer the DID cache has never seen is refused
    /// as **deactivated** — final — and not as unreachable. Since
    /// `affinidi-did-resolver-cache-sdk` 0.8.39 the cache refuses to resolve a
    /// deactivated did:webvh at all; that refusal used to be reported as an
    /// unreachable signer, so the proof was retried (a cache eviction and a
    /// re-resolution each time) and the caller told to try again. A live DID
    /// served beside it shows the harness serves logs that resolve.
    #[tokio::test]
    async fn an_uncached_deactivated_webvh_signer_is_refused_as_final() {
        use affinidi_did_resolver_cache_sdk::config::DIDCacheConfigBuilder;
        use affinidi_did_resolver_cache_sdk::network_resolvers::HostPolicy as CacheHostPolicy;

        let secret = Secret::generate_ed25519(None, Some(&[7u8; 32]));
        let live_listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let dead_listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let (live, live_log) =
            webvh_log(live_listener.local_addr().unwrap().port(), &secret, false).await;
        let (dead, dead_log) =
            webvh_log(dead_listener.local_addr().unwrap().port(), &secret, true).await;
        serve(live_listener, live_log);
        serve(dead_listener, dead_log);

        let client = DIDCacheClient::new(
            DIDCacheConfigBuilder::default()
                .with_host_policy(CacheHostPolicy::AllowPrivate)
                .build(),
        )
        .await
        .unwrap();
        let signers = SignerKeyResolver {
            client: client.clone(),
            decode: CachedDidResolver::new(Arc::new(client)),
            deactivation: Some(Arc::new(DeactivationCache {
                host_policy: HostPolicy::AllowPrivate,
                ..DeactivationCache::default()
            })),
        };
        let resolver = PurposeBound::new(&signers, ProofPurpose::Authentication);

        resolver
            .resolve_vm(&format!("{live}#key-1"))
            .await
            .expect("a live signer resolves");
        let err = resolver
            .resolve_vm(&format!("{dead}#key-1"))
            .await
            .unwrap_err()
            .to_string();
        assert!(err.contains(DEACTIVATED), "{err}");
        assert!(
            !err.contains(UNREACHABLE),
            "a deactivated signer is final: {err}"
        );
        assert!(
            !is_unreachable(&map_error(DataIntegrityError::Resolver(err.clone()))),
            "{err}"
        );
    }

    // ─── Cross-language interop with the JS wallet ───
    //
    // `stepup-approval-fixture.json` is generated by the browser plugin's
    // actual signer (`@openvtc/pnm-core` `buildStepUpApproval`, eddsa-jcs-2022)
    // — see the PR that converged step-up to holder-self-signs. These tests are
    // the load-bearing guarantee that the JS wallet and this Rust verifier
    // canonicalize + hash byte-identically: if they ever diverge,
    // holder-self-signed step-up silently stops verifying. Regenerate the
    // fixture from the plugin if the wire shape changes.
    const STEP_UP_FIXTURE: &str = include_str!("testdata/stepup-approval-fixture.json");

    /// A wallet-signed `auth/step-up/approve-response/0.2` (both the approved
    /// and denied variants) verifies against `TransportBoundVerifier` — the
    /// same verifier the `/auth/step-up/vta/finish` handler uses.
    #[tokio::test]
    async fn wallet_signed_step_up_approval_verifies() {
        let fixture: Value = serde_json::from_str(STEP_UP_FIXTURE).expect("fixture parses");

        let approved: TrustTask<Value> =
            serde_json::from_value(fixture["approved"].clone()).expect("approved doc parses");
        verifier()
            .verify(&approved)
            .await
            .expect("wallet-signed approved response verifies");
        // …and passes the approval check `/auth/step-up/vta/finish` applies
        // (`assertionMethod` purpose and relationship).
        verifier()
            .verify_approval(&approved)
            .await
            .expect("wallet-signed approval passes the approval check");

        let denied: TrustTask<Value> =
            serde_json::from_value(fixture["denied"].clone()).expect("denied doc parses");
        verifier()
            .verify(&denied)
            .await
            .expect("wallet-signed denied response verifies");
    }

    /// Flipping the wallet-signed `decision` after signing breaks the proof —
    /// the fixture proves the signature actually covers the payload, not just
    /// that the shapes line up.
    #[tokio::test]
    async fn wallet_signed_step_up_tampered_decision_rejected() {
        let fixture: Value = serde_json::from_str(STEP_UP_FIXTURE).expect("fixture parses");
        let mut doc: TrustTask<Value> =
            serde_json::from_value(fixture["approved"].clone()).expect("approved doc parses");
        doc.payload
            .as_object_mut()
            .expect("payload is an object")
            .insert("decision".to_string(), json!("denied"));

        let err = verifier()
            .verify(&doc)
            .await
            .expect_err("tampered decision must be rejected");
        // The issuer is untouched, so this is a signature failure, not an
        // issuer-binding rejection.
        assert!(
            !matches!(err, VerificationError::IssuerMismatch(_)),
            "expected a signature failure, got {err:?}"
        );
    }
}