asx-rs 0.14.0

AS2 and AS4 B2B messaging library for Rust — signing, encryption, MDN, and ebMS3/AS4 profile support
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
#[cfg(any(test, feature = "async-ocsp"))]
use openssl::hash::MessageDigest;
#[cfg(any(test, feature = "async-ocsp"))]
use openssl::ocsp::{OcspCertId, OcspRequest};
use openssl::x509::X509Ref;
use parking_lot::Mutex;
#[cfg(any(test, feature = "async-ocsp"))]
use sha2::{Digest, Sha256};
use std::sync::{Arc, OnceLock};
#[cfg(any(test, feature = "async-ocsp"))]
use std::time::Duration;
#[cfg(any(test, feature = "async-ocsp"))]
use std::time::{SystemTime, UNIX_EPOCH};

use crate::core::{AsxError, ErrorCode, ErrorContext, Result};

#[cfg(feature = "async-ocsp")]
const DEFAULT_CACHE_TTL_SECS: u64 = 300;
#[cfg(feature = "async-ocsp")]
const DEFAULT_HTTP_TIMEOUT: Duration = Duration::from_secs(3);

/// Maximum number of entries in any OCSP response cache instance.
///
/// When the capacity limit is reached, the LRU entry is evicted automatically.
/// A value of 512 covers typical enterprise deployments (hundreds of distinct
/// partner certificates) with negligible memory footprint (each entry is a few
/// kB of DER-encoded OCSP response data).
pub const DEFAULT_OCSP_CACHE_CAPACITY: usize = 512;

#[derive(Debug, Clone)]
struct CachedResponses {
    expires_at_unix_secs: u64,
    responses_der: Vec<Vec<u8>>,
}

// ---------------------------------------------------------------------------
// OcspResponseCache trait
// ---------------------------------------------------------------------------

pub trait OcspResponseCache: Send + Sync + std::fmt::Debug {
    fn get(&self, cache_key: &str, now_secs: u64) -> Result<Option<Vec<Vec<u8>>>>;
    fn put(
        &self,
        cache_key: &str,
        responses_der: &[Vec<u8>],
        expires_at_unix_secs: u64,
    ) -> Result<()>;
}

// ---------------------------------------------------------------------------
// LruOcspResponseCache — instance-scoped, bounded LRU
// ---------------------------------------------------------------------------

/// Instance-scoped OCSP response cache backed by an LRU eviction policy.
///
/// Unlike [`ProcessLocalOcspResponseCache`] which uses a process-global static,
/// this cache is created per-instance (e.g. per tenant, per `RevocationPolicy`)
/// and provides hard memory bounds via LRU eviction.
///
/// ## Usage
///
/// ```rust,ignore
/// let cache = Arc::new(LruOcspResponseCache::new(512));
/// // Pass to RevocationPolicy or fetch functions:
/// // revocation_policy.with_ocsp_cache(cache)
/// ```
///
/// ## Thread safety
///
/// All methods take `&self` and acquire an internal `parking_lot::Mutex`.
/// The lock is held only for the duration of the get/put operation (no I/O),
/// so contention is negligible in practice.
#[derive(Debug)]
pub struct LruOcspResponseCache {
    inner: Mutex<lru::LruCache<String, CachedResponses>>,
}

impl LruOcspResponseCache {
    /// Create a new LRU cache with the given capacity.
    ///
    /// When `capacity` entries are stored and a new entry is inserted, the
    /// least-recently-used entry is evicted automatically.
    pub fn new(capacity: usize) -> Self {
        let cap = std::num::NonZeroUsize::new(capacity.max(1))
            .expect("capacity is always ≥ 1 after max(1)");
        Self {
            inner: Mutex::new(lru::LruCache::new(cap)),
        }
    }

    /// Create with the default capacity ([`DEFAULT_OCSP_CACHE_CAPACITY`]).
    pub fn with_default_capacity() -> Self {
        Self::new(DEFAULT_OCSP_CACHE_CAPACITY)
    }
}

impl OcspResponseCache for LruOcspResponseCache {
    fn get(&self, cache_key: &str, now_secs: u64) -> Result<Option<Vec<Vec<u8>>>> {
        let mut guard = self.inner.lock();
        // `peek` does not update LRU order; `get` does.  Use `get` so that
        // recently-accessed certificates stay in cache under eviction pressure.
        Ok(guard
            .get(cache_key)
            .filter(|entry| entry.expires_at_unix_secs >= now_secs)
            .map(|entry| entry.responses_der.clone()))
    }

    fn put(
        &self,
        cache_key: &str,
        responses_der: &[Vec<u8>],
        expires_at_unix_secs: u64,
    ) -> Result<()> {
        let mut guard = self.inner.lock();
        // `push` inserts and returns the evicted entry (if any); we discard it.
        // LRU eviction is O(1) — no sweep required.
        guard.push(
            cache_key.to_string(),
            CachedResponses {
                expires_at_unix_secs,
                responses_der: responses_der.to_vec(),
            },
        );
        Ok(())
    }
}

// ---------------------------------------------------------------------------
// ProcessLocalOcspResponseCache — process-global fallback (single-tenant)
// ---------------------------------------------------------------------------

/// Process-global OCSP response cache.
///
/// Backed by a process-global `parking_lot::Mutex<LruCache>` with hard-bound
/// LRU eviction at [`DEFAULT_OCSP_CACHE_CAPACITY`] entries.
///
/// ## ⚠ Multi-tenant warning
///
/// All callers that use `ProcessLocalOcspResponseCache` share a single cache
/// namespace.  In multi-tenant embeddings, use a per-tenant
/// [`LruOcspResponseCache`] instance instead and pass it via
/// `RevocationPolicy::with_ocsp_cache(...)`.
///
/// The `ocsp_cache_namespace` key prefix in `RevocationPolicy` provides logical
/// isolation within the same physical cache but does NOT prevent a cache-miss
/// storm in one tenant from evicting recently-fetched entries for other tenants.
/// Only instance-scoped caches provide hard memory and LRU isolation.
#[derive(Debug, Default, Clone, Copy)]
pub struct ProcessLocalOcspResponseCache;

fn process_local_cache() -> &'static Mutex<lru::LruCache<String, CachedResponses>> {
    static CACHE: OnceLock<Mutex<lru::LruCache<String, CachedResponses>>> = OnceLock::new();
    CACHE.get_or_init(|| {
        let cap = std::num::NonZeroUsize::new(DEFAULT_OCSP_CACHE_CAPACITY)
            .expect("DEFAULT_OCSP_CACHE_CAPACITY > 0");
        Mutex::new(lru::LruCache::new(cap))
    })
}

impl OcspResponseCache for ProcessLocalOcspResponseCache {
    fn get(&self, cache_key: &str, now_secs: u64) -> Result<Option<Vec<Vec<u8>>>> {
        Ok(process_local_cache()
            .lock()
            .get(cache_key)
            .filter(|entry| entry.expires_at_unix_secs >= now_secs)
            .map(|entry| entry.responses_der.clone()))
    }

    fn put(
        &self,
        cache_key: &str,
        responses_der: &[Vec<u8>],
        expires_at_unix_secs: u64,
    ) -> Result<()> {
        // `push` evicts the LRU entry when capacity is exceeded — O(1), no sweep.
        process_local_cache().lock().push(
            cache_key.to_string(),
            CachedResponses {
                expires_at_unix_secs,
                responses_der: responses_der.to_vec(),
            },
        );
        Ok(())
    }
}

/// Context for OCSP response fetching operations.
///
/// Bundles parameters needed for fetching OCSP responses, reducing parameter passing
/// complexity and improving API clarity compared to individual parameters.
#[cfg(any(test, feature = "async-ocsp"))]
pub(crate) struct OcspFetchContext<'a> {
    pub cache_key: &'a str,
    pub urls: &'a [String],
    pub request_der: &'a [u8],
    pub cache_provider: &'a dyn OcspResponseCache,
    pub ttl_secs: u64,
    pub timeout: Duration,
    pub now_secs: u64,
}

/// Sync OCSP HTTP transport interface — used only in unit tests via `FakeTransport`.
#[cfg(test)]
pub(crate) trait OcspHttpTransport {
    fn post_ocsp_request(
        &self,
        url: &str,
        request_der: &[u8],
        timeout: Duration,
    ) -> Result<Vec<u8>>;
}

pub fn fetch_ocsp_responses_with_cache(cert: &X509Ref, issuer: &X509Ref) -> Result<Vec<Vec<u8>>> {
    fetch_ocsp_responses_with_cache_scoped(cert, issuer, "default-global")
}

pub fn fetch_ocsp_responses_with_cache_scoped(
    cert: &X509Ref,
    issuer: &X509Ref,
    cache_namespace: &str,
) -> Result<Vec<Vec<u8>>> {
    fetch_ocsp_responses_with_cache_provider_scoped(
        cert,
        issuer,
        Arc::new(ProcessLocalOcspResponseCache),
        cache_namespace,
    )
}

#[cfg(feature = "async-ocsp")]
pub async fn fetch_ocsp_responses_with_cache_async(
    cert: &X509Ref,
    issuer: &X509Ref,
) -> Result<Vec<Vec<u8>>> {
    fetch_ocsp_responses_with_cache_async_scoped(cert, issuer, "shared").await
}

#[cfg(feature = "async-ocsp")]
pub async fn fetch_ocsp_responses_with_cache_async_scoped(
    cert: &X509Ref,
    issuer: &X509Ref,
    cache_namespace: &str,
) -> Result<Vec<Vec<u8>>> {
    fetch_ocsp_responses_with_cache_provider_async_scoped(
        cert,
        issuer,
        Arc::new(ProcessLocalOcspResponseCache),
        cache_namespace,
    )
    .await
}

#[cfg(feature = "async-ocsp")]
pub async fn fetch_ocsp_responses_with_cache_provider_async(
    cert: &X509Ref,
    issuer: &X509Ref,
    cache_provider: Arc<dyn OcspResponseCache>,
) -> Result<Vec<Vec<u8>>> {
    fetch_ocsp_responses_with_cache_provider_async_scoped(cert, issuer, cache_provider, "shared")
        .await
}

#[cfg(feature = "async-ocsp")]
pub async fn fetch_ocsp_responses_with_cache_provider_async_scoped(
    cert: &X509Ref,
    issuer: &X509Ref,
    cache_provider: Arc<dyn OcspResponseCache>,
    cache_namespace: &str,
) -> Result<Vec<Vec<u8>>> {
    async_transport::fetch_ocsp_responses_with_cache_async_scoped(
        cert,
        issuer,
        cache_provider.as_ref(),
        cache_namespace,
    )
    .await
}

pub fn fetch_ocsp_responses_with_cache_provider(
    cert: &X509Ref,
    issuer: &X509Ref,
    cache_provider: Arc<dyn OcspResponseCache>,
) -> Result<Vec<Vec<u8>>> {
    fetch_ocsp_responses_with_cache_provider_scoped(cert, issuer, cache_provider, "shared")
}

pub fn fetch_ocsp_responses_with_cache_provider_scoped(
    cert: &X509Ref,
    issuer: &X509Ref,
    cache_provider: Arc<dyn OcspResponseCache>,
    cache_namespace: &str,
) -> Result<Vec<Vec<u8>>> {
    #[cfg(feature = "async-ocsp")]
    {
        let handle = tokio::runtime::Handle::try_current().map_err(|_| {
            AsxError::new(
                ErrorCode::PolicyViolation,
                "OCSP fetching with 'async-ocsp' requires an active Tokio runtime; use the async OCSP API or inject a runtime upstream",
                ErrorContext::new("ocsp_client_fetch_async_runtime"),
            )
        })?;

        if matches!(
            handle.runtime_flavor(),
            tokio::runtime::RuntimeFlavor::MultiThread
        ) {
            tokio::task::block_in_place(|| {
                handle.block_on(fetch_ocsp_responses_with_cache_provider_async_scoped(
                    cert,
                    issuer,
                    cache_provider,
                    cache_namespace,
                ))
            })
        } else {
            handle.block_on(fetch_ocsp_responses_with_cache_provider_async_scoped(
                cert,
                issuer,
                cache_provider,
                cache_namespace,
            ))
        }
    }

    #[cfg(not(feature = "async-ocsp"))]
    {
        let _ = (cert, issuer, cache_provider, cache_namespace);
        Err(AsxError::new(
            ErrorCode::PolicyViolation,
            "OCSP responder fetching requires feature 'async-ocsp' (sync fallback removed)",
            ErrorContext::new("ocsp_client_fetch"),
        ))
    }
}

#[cfg(test)]
fn fetch_from_cache_or_responder(
    ctx: &OcspFetchContext<'_>,
    transport: &dyn OcspHttpTransport,
) -> Result<Vec<Vec<u8>>> {
    if let Some(cached) = ctx.cache_provider.get(ctx.cache_key, ctx.now_secs)? {
        return Ok(cached);
    }

    let mut responses = Vec::new();
    for url in ctx.urls {
        let Ok(body) = transport.post_ocsp_request(url, ctx.request_der, ctx.timeout) else {
            continue;
        };
        if !body.is_empty() {
            responses.push(body);
        }
    }

    if !responses.is_empty() {
        ctx.cache_provider.put(
            ctx.cache_key,
            &responses,
            ctx.now_secs.saturating_add(ctx.ttl_secs),
        )?;
    }

    Ok(responses)
}

#[cfg(any(test, feature = "async-ocsp"))]
#[allow(dead_code)]
fn build_ocsp_request_der(cert: &X509Ref, issuer: &X509Ref) -> Result<Vec<u8>> {
    let cert_id = OcspCertId::from_cert(MessageDigest::sha1(), cert, issuer).map_err(|err| {
        AsxError::new(
            ErrorCode::SecurityVerificationFailed,
            format!("failed to build OCSP cert id: {err}"),
            ErrorContext::new("ocsp_client_request"),
        )
    })?;

    let mut request = OcspRequest::new().map_err(|err| {
        AsxError::new(
            ErrorCode::SecurityVerificationFailed,
            format!("failed to initialize OCSP request: {err}"),
            ErrorContext::new("ocsp_client_request"),
        )
    })?;
    request.add_id(cert_id).map_err(|err| {
        AsxError::new(
            ErrorCode::SecurityVerificationFailed,
            format!("failed to add cert id to OCSP request: {err}"),
            ErrorContext::new("ocsp_client_request"),
        )
    })?;

    request.to_der().map_err(|err| {
        AsxError::new(
            ErrorCode::SecurityVerificationFailed,
            format!("failed to serialize OCSP request: {err}"),
            ErrorContext::new("ocsp_client_request"),
        )
    })
}

#[cfg(any(test, feature = "async-ocsp"))]
#[allow(dead_code)]
fn build_cache_key(
    cert: &X509Ref,
    issuer: &X509Ref,
    urls: &[String],
    cache_namespace: &str,
) -> Result<String> {
    let cert_der = cert.to_der().map_err(|err| {
        AsxError::new(
            ErrorCode::SecurityVerificationFailed,
            format!("failed to serialize certificate DER for OCSP cache key: {err}"),
            ErrorContext::new("ocsp_client_cache"),
        )
    })?;
    let issuer_der = issuer.to_der().map_err(|err| {
        AsxError::new(
            ErrorCode::SecurityVerificationFailed,
            format!("failed to serialize issuer DER for OCSP cache key: {err}"),
            ErrorContext::new("ocsp_client_cache"),
        )
    })?;

    let mut hasher = Sha256::new();
    hasher.update(cache_namespace.as_bytes());
    hasher.update([0xffu8]);
    hasher.update(cert_der);
    hasher.update(issuer_der);
    for url in urls {
        hasher.update([0u8]);
        hasher.update(url.as_bytes());
    }

    Ok(hex_lower(&hasher.finalize()))
}

#[cfg(any(test, feature = "async-ocsp"))]
#[allow(dead_code)]
fn current_unix_secs() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0)
}

#[cfg(any(test, feature = "async-ocsp"))]
#[allow(dead_code)]
fn hex_lower(bytes: &[u8]) -> String {
    const HEX: &[u8; 16] = b"0123456789abcdef";
    let mut out = String::with_capacity(bytes.len() * 2);
    for &byte in bytes {
        out.push(HEX[(byte >> 4) as usize] as char);
        out.push(HEX[(byte & 0x0f) as usize] as char);
    }
    out
}

// Async OCSP support (feature-gated behind "async-ocsp")
#[cfg(feature = "async-ocsp")]
pub mod async_transport {
    use super::*;
    use crate::crypto::ocsp_discovery::discover_ocsp_responder_urls;

    /// Async variant of OcspHttpTransport for non-blocking I/O with tokio.
    ///
    /// Returns a boxed future so the trait is dyn-compatible; embedders that
    /// use `ReqwestOcspTransport` directly pay no boxing cost in practice.
    pub trait AsyncOcspHttpTransport: Send + Sync {
        fn post_ocsp_request_async<'a>(
            &'a self,
            url: &'a str,
            request_der: &'a [u8],
            timeout: Duration,
        ) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<Vec<u8>>> + Send + 'a>>;
    }

    /// Reqwest-based OCSP transport for async/await
    #[derive(Debug, Default)]
    pub struct ReqwestOcspTransport {
        client: Option<reqwest::Client>,
    }

    impl ReqwestOcspTransport {
        /// Create a new reqwest-based OCSP transport
        pub fn new() -> Self {
            Self { client: None }
        }

        /// Create with a pre-configured reqwest client.
        ///
        /// # ⚠ This opts out of responder-URL validation
        ///
        /// The default transport validates each responder URL against the
        /// private/loopback/link-local ranges and pins the connection to the
        /// addresses it checked, because the URL comes from an inbound
        /// certificate's AIA extension. Supplying a client asserts that **you**
        /// own that policy — the URL is used as given.
        ///
        /// The legitimate reason to do this is an internal PKI whose responder
        /// really is on a private address, or an egress proxy. If that is not
        /// your situation, use [`new`](Self::new).
        pub fn with_client(client: reqwest::Client) -> Self {
            Self {
                client: Some(client),
            }
        }

        /// Build the client for one responder URL.
        ///
        /// The URL comes from the certificate's AIA extension, so on an inbound
        /// message it is chosen by whoever presented the certificate — and
        /// revocation checking runs *while* trust is being established, i.e.
        /// before that party is trusted at all. It is therefore validated
        /// against the private/loopback/link-local ranges and pinned to the
        /// addresses that were checked, exactly like any other egress. Without
        /// that, a peer could point the responder at `169.254.169.254` or an
        /// internal admin endpoint and have this process POST to it.
        ///
        /// A caller-supplied client (`with_client`) is used as given: that
        /// caller has taken responsibility for its own egress policy.
        async fn client_for(&self, url: &str) -> Result<reqwest::Client> {
            if let Some(client) = self.client.clone() {
                return Ok(client);
            }
            crate::transport::egress::validated_pinned_ocsp_client(
                url,
                &crate::transport::egress::TransportConfig::default(),
                "ocsp_client_fetch_async",
            )
            .await
        }
    }

    impl AsyncOcspHttpTransport for ReqwestOcspTransport {
        fn post_ocsp_request_async<'a>(
            &'a self,
            url: &'a str,
            request_der: &'a [u8],
            timeout: Duration,
        ) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<Vec<u8>>> + Send + 'a>>
        {
            Box::pin(async move {
                let client = self.client_for(url).await?;

                let response = client
                    .post(url)
                    .header("Content-Type", "application/ocsp-request")
                    .header("Accept", "application/ocsp-response")
                    .timeout(timeout)
                    .body(request_der.to_vec())
                    .send()
                    .await
                    .map_err(|err| {
                        AsxError::new(
                            ErrorCode::TransportFailure,
                            format!("failed OCSP responder request (async): {err}"),
                            ErrorContext::new("ocsp_client_fetch_async"),
                        )
                    })?;

                if !response.status().is_success() {
                    return Err(AsxError::new(
                        ErrorCode::TransportFailure,
                        format!("OCSP responder returned HTTP status {}", response.status()),
                        ErrorContext::new("ocsp_client_fetch_async"),
                    ));
                }

                let body = response.bytes().await.map_err(|err| {
                    AsxError::new(
                        ErrorCode::TransportFailure,
                        format!("failed to read OCSP responder body (async): {err}"),
                        ErrorContext::new("ocsp_client_fetch_async"),
                    )
                })?;

                Ok(body.to_vec())
            }) // Box::pin
        }
    }

    /// Fetch OCSP responses asynchronously with caching
    pub async fn fetch_ocsp_responses_with_cache_async(
        cert: &X509Ref,
        issuer: &X509Ref,
        cache_provider: &dyn OcspResponseCache,
    ) -> Result<Vec<Vec<u8>>> {
        fetch_ocsp_responses_with_cache_async_scoped(cert, issuer, cache_provider, "shared").await
    }

    /// Fetch OCSP responses asynchronously with explicit cache namespace.
    pub async fn fetch_ocsp_responses_with_cache_async_scoped(
        cert: &X509Ref,
        issuer: &X509Ref,
        cache_provider: &dyn OcspResponseCache,
        cache_namespace: &str,
    ) -> Result<Vec<Vec<u8>>> {
        fetch_ocsp_responses_with_cache_and_transport_async_scoped(
            AsyncOcspFetchWithTransportRequest {
                cert,
                issuer,
                transport: &ReqwestOcspTransport::new(),
                cache_provider,
                ttl_secs: DEFAULT_CACHE_TTL_SECS,
                timeout: DEFAULT_HTTP_TIMEOUT,
                now_override_unix_secs: None,
                cache_namespace,
            },
        )
        .await
    }

    /// Async fetch with configurable transport
    pub async fn fetch_ocsp_responses_with_cache_and_transport_async(
        cert: &X509Ref,
        issuer: &X509Ref,
        transport: &dyn AsyncOcspHttpTransport,
        cache_provider: &dyn OcspResponseCache,
        ttl_secs: u64,
        timeout: Duration,
        now_override_unix_secs: Option<u64>,
    ) -> Result<Vec<Vec<u8>>> {
        fetch_ocsp_responses_with_cache_and_transport_async_scoped(
            AsyncOcspFetchWithTransportRequest {
                cert,
                issuer,
                transport,
                cache_provider,
                ttl_secs,
                timeout,
                now_override_unix_secs,
                cache_namespace: "shared",
            },
        )
        .await
    }

    pub struct AsyncOcspFetchWithTransportRequest<'a> {
        pub cert: &'a X509Ref,
        pub issuer: &'a X509Ref,
        pub transport: &'a dyn AsyncOcspHttpTransport,
        pub cache_provider: &'a dyn OcspResponseCache,
        pub ttl_secs: u64,
        pub timeout: Duration,
        pub now_override_unix_secs: Option<u64>,
        pub cache_namespace: &'a str,
    }

    impl std::fmt::Debug for AsyncOcspFetchWithTransportRequest<'_> {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            f.debug_struct("AsyncOcspFetchWithTransportRequest")
                .field("ttl_secs", &self.ttl_secs)
                .field("cache_namespace", &self.cache_namespace)
                .finish_non_exhaustive()
        }
    }

    /// Async fetch with configurable transport and explicit cache namespace.
    pub async fn fetch_ocsp_responses_with_cache_and_transport_async_scoped(
        request: AsyncOcspFetchWithTransportRequest<'_>,
    ) -> Result<Vec<Vec<u8>>> {
        let AsyncOcspFetchWithTransportRequest {
            cert,
            issuer,
            transport,
            cache_provider,
            ttl_secs,
            timeout,
            now_override_unix_secs,
            cache_namespace,
        } = request;

        let cert_owned = cert.to_owned();
        let mut urls = discover_ocsp_responder_urls(&cert_owned);
        urls.sort();
        urls.dedup();

        if urls.is_empty() {
            return Ok(Vec::new());
        }

        let request_der = build_ocsp_request_der(cert, issuer)?;
        let cache_key = build_cache_key(cert, issuer, &urls, cache_namespace)?;
        let now_secs = now_override_unix_secs.unwrap_or_else(current_unix_secs);

        let ctx = OcspFetchContext {
            cache_key: &cache_key,
            urls: &urls,
            request_der: &request_der,
            cache_provider,
            ttl_secs,
            timeout,
            now_secs,
        };

        fetch_from_cache_or_responder_async(&ctx, transport).await
    }

    pub(crate) async fn fetch_from_cache_or_responder_async(
        ctx: &OcspFetchContext<'_>,
        transport: &dyn AsyncOcspHttpTransport,
    ) -> Result<Vec<Vec<u8>>> {
        if let Some(cached) = ctx.cache_provider.get(ctx.cache_key, ctx.now_secs)? {
            return Ok(cached);
        }

        let mut responses = Vec::new();
        for url in ctx.urls {
            let Ok(body) = transport
                .post_ocsp_request_async(url, ctx.request_der, ctx.timeout)
                .await
            else {
                continue;
            };
            if !body.is_empty() {
                responses.push(body);
            }
        }

        if !responses.is_empty() {
            ctx.cache_provider.put(
                ctx.cache_key,
                &responses,
                ctx.now_secs.saturating_add(ctx.ttl_secs),
            )?;
        }

        Ok(responses)
    }
}

#[cfg(test)]
fn clear_ocsp_response_cache_for_tests() {
    process_local_cache().lock().clear();
}

/// Serializes all tests that touch the process-global OCSP response cache.
///
/// `cargo test` runs tests in parallel by default. Tests that call
/// `clear_ocsp_response_cache_for_tests()` share a single in-process LRU cache, so
/// without a serialization guard a concurrent `clear()` from another test can evict
/// an entry between the two `fetch_from_cache_or_responder` calls in the same test,
/// producing a spurious second transport call. Each cache-touching test must acquire
/// this guard before touching the cache.
#[cfg(test)]
static CACHE_TEST_MUTEX: std::sync::Mutex<()> = std::sync::Mutex::new(());

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

    #[derive(Debug)]

    struct InMemoryTestCache {
        store: parking_lot::Mutex<std::collections::HashMap<String, CachedResponses>>,
        gets: parking_lot::Mutex<u32>,
        puts: parking_lot::Mutex<u32>,
    }

    impl InMemoryTestCache {
        fn new() -> Self {
            Self {
                store: parking_lot::Mutex::new(std::collections::HashMap::new()),
                gets: parking_lot::Mutex::new(0),
                puts: parking_lot::Mutex::new(0),
            }
        }

        fn get_count(&self) -> u32 {
            *self.gets.lock()
        }

        fn put_count(&self) -> u32 {
            *self.puts.lock()
        }
    }

    impl OcspResponseCache for InMemoryTestCache {
        fn get(&self, cache_key: &str, now_secs: u64) -> Result<Option<Vec<Vec<u8>>>> {
            let mut gets = self.gets.lock();
            *gets += 1;
            drop(gets);

            let store = self.store.lock();
            Ok(store
                .get(cache_key)
                .filter(|entry| entry.expires_at_unix_secs >= now_secs)
                .map(|entry| entry.responses_der.clone()))
        }

        fn put(
            &self,
            cache_key: &str,
            responses_der: &[Vec<u8>],
            expires_at_unix_secs: u64,
        ) -> Result<()> {
            let mut puts = self.puts.lock();
            *puts += 1;
            drop(puts);

            let mut store = self.store.lock();
            store.insert(
                cache_key.to_string(),
                CachedResponses {
                    expires_at_unix_secs,
                    responses_der: responses_der.to_vec(),
                },
            );
            Ok(())
        }
    }

    struct FakeTransport {
        calls: parking_lot::Mutex<u32>,
        payload: Vec<u8>,
    }

    impl FakeTransport {
        fn new(payload: Vec<u8>) -> Self {
            Self {
                calls: parking_lot::Mutex::new(0),
                payload,
            }
        }

        fn call_count(&self) -> u32 {
            *self.calls.lock()
        }
    }

    impl OcspHttpTransport for FakeTransport {
        fn post_ocsp_request(
            &self,
            _url: &str,
            _request_der: &[u8],
            _timeout: Duration,
        ) -> Result<Vec<u8>> {
            let mut calls = self.calls.lock();
            *calls += 1;
            Ok(self.payload.clone())
        }
    }

    #[test]
    fn cache_hit_avoids_second_transport_call() {
        let _guard = CACHE_TEST_MUTEX.lock().unwrap_or_else(|e| e.into_inner());
        clear_ocsp_response_cache_for_tests();
        let transport = FakeTransport::new(vec![1, 2, 3]);
        let cache_provider = ProcessLocalOcspResponseCache;
        let urls = vec!["http://example.test/ocsp".to_string()];
        let request = vec![9, 9, 9];

        let ctx = OcspFetchContext {
            cache_key: "key-1",
            urls: &urls,
            request_der: &request,
            cache_provider: &cache_provider,
            ttl_secs: 60,
            timeout: Duration::from_secs(1),
            now_secs: 100,
        };
        let first = fetch_from_cache_or_responder(&ctx, &transport).unwrap();

        let ctx = OcspFetchContext {
            cache_key: "key-1",
            urls: &urls,
            request_der: &request,
            cache_provider: &cache_provider,
            ttl_secs: 60,
            timeout: Duration::from_secs(1),
            now_secs: 101,
        };
        let second = fetch_from_cache_or_responder(&ctx, &transport).unwrap();

        assert_eq!(first, vec![vec![1, 2, 3]]);
        assert_eq!(second, vec![vec![1, 2, 3]]);
        assert_eq!(transport.call_count(), 1);
    }

    #[test]
    fn expired_cache_refetches_transport() {
        let _guard = CACHE_TEST_MUTEX.lock().unwrap_or_else(|e| e.into_inner());
        clear_ocsp_response_cache_for_tests();
        let transport = FakeTransport::new(vec![4, 5, 6]);
        let cache_provider = ProcessLocalOcspResponseCache;
        let urls = vec!["http://example.test/ocsp".to_string()];
        let request = vec![8, 8, 8];

        let ctx = OcspFetchContext {
            cache_key: "key-2",
            urls: &urls,
            request_der: &request,
            cache_provider: &cache_provider,
            ttl_secs: 1,
            timeout: Duration::from_secs(1),
            now_secs: 100,
        };
        let _ = fetch_from_cache_or_responder(&ctx, &transport).unwrap();

        let ctx = OcspFetchContext {
            cache_key: "key-2",
            urls: &urls,
            request_der: &request,
            cache_provider: &cache_provider,
            ttl_secs: 1,
            timeout: Duration::from_secs(1),
            now_secs: 102,
        };
        let _ = fetch_from_cache_or_responder(&ctx, &transport).unwrap();

        assert_eq!(transport.call_count(), 2);
    }

    #[test]
    fn empty_responder_bodies_are_not_cached() {
        let _guard = CACHE_TEST_MUTEX.lock().unwrap_or_else(|e| e.into_inner());
        clear_ocsp_response_cache_for_tests();
        let transport = FakeTransport::new(Vec::new());
        let cache_provider = ProcessLocalOcspResponseCache;
        let urls = vec!["http://example.test/ocsp".to_string()];
        let request = vec![7, 7, 7];

        let ctx = OcspFetchContext {
            cache_key: "key-3",
            urls: &urls,
            request_der: &request,
            cache_provider: &cache_provider,
            ttl_secs: 60,
            timeout: Duration::from_secs(1),
            now_secs: 100,
        };
        let first = fetch_from_cache_or_responder(&ctx, &transport).unwrap();

        let ctx = OcspFetchContext {
            cache_key: "key-3",
            urls: &urls,
            request_der: &request,
            cache_provider: &cache_provider,
            ttl_secs: 60,
            timeout: Duration::from_secs(1),
            now_secs: 101,
        };
        let second = fetch_from_cache_or_responder(&ctx, &transport).unwrap();

        assert!(first.is_empty());
        assert!(second.is_empty());
        assert_eq!(transport.call_count(), 2);
    }

    #[test]
    fn custom_cache_provider_is_used() {
        let transport = FakeTransport::new(vec![2, 4, 6]);
        let cache_provider = InMemoryTestCache::new();
        let urls = vec!["http://example.test/ocsp".to_string()];
        let request = vec![3, 3, 3];

        let ctx = OcspFetchContext {
            cache_key: "key-custom",
            urls: &urls,
            request_der: &request,
            cache_provider: &cache_provider,
            ttl_secs: 60,
            timeout: Duration::from_secs(1),
            now_secs: 100,
        };
        let first = fetch_from_cache_or_responder(&ctx, &transport).expect("first fetch");

        let ctx = OcspFetchContext {
            cache_key: "key-custom",
            urls: &urls,
            request_der: &request,
            cache_provider: &cache_provider,
            ttl_secs: 60,
            timeout: Duration::from_secs(1),
            now_secs: 101,
        };
        let second = fetch_from_cache_or_responder(&ctx, &transport).expect("second fetch");

        assert_eq!(first, vec![vec![2, 4, 6]]);
        assert_eq!(second, vec![vec![2, 4, 6]]);
        assert_eq!(transport.call_count(), 1);
        assert_eq!(cache_provider.get_count(), 2);
        assert_eq!(cache_provider.put_count(), 1);
    }

    // ── Async transport tests ────────────────────────────────────────────────

    #[cfg(feature = "async-ocsp")]
    mod async_transport_tests {
        use super::super::async_transport::AsyncOcspHttpTransport;
        use super::*;

        struct AsyncFakeTransport {
            calls: parking_lot::Mutex<u32>,
            payload: Vec<u8>,
            fail: bool,
        }

        impl AsyncFakeTransport {
            fn ok(payload: Vec<u8>) -> Self {
                Self {
                    calls: parking_lot::Mutex::new(0),
                    payload,
                    fail: false,
                }
            }

            fn failing() -> Self {
                Self {
                    calls: parking_lot::Mutex::new(0),
                    payload: Vec::new(),
                    fail: true,
                }
            }

            fn call_count(&self) -> u32 {
                *self.calls.lock()
            }
        }

        impl AsyncOcspHttpTransport for AsyncFakeTransport {
            fn post_ocsp_request_async<'a>(
                &'a self,
                _url: &'a str,
                _request_der: &'a [u8],
                _timeout: Duration,
            ) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<Vec<u8>>> + Send + 'a>>
            {
                Box::pin(async move {
                    let mut calls = self.calls.lock();
                    *calls += 1;
                    drop(calls);
                    if self.fail {
                        return Err(AsxError::new(
                            ErrorCode::TransportFailure,
                            "injected async transport failure",
                            ErrorContext::new("async_fake_transport"),
                        ));
                    }
                    Ok(self.payload.clone())
                })
            }
        }

        // ── cache-or-responder (async) ───────────────────────────────────

        #[tokio::test]
        async fn async_cache_hit_avoids_transport_call() {
            let transport = AsyncFakeTransport::ok(vec![10, 20, 30]);
            let cache = InMemoryTestCache::new();
            let urls = vec!["http://example.test/ocsp".to_string()];
            let req_der = vec![1, 2, 3];

            // Prime the cache manually.
            cache
                .put("async-key-1", &[vec![10, 20, 30]], 9999)
                .expect("prime");

            let ctx = OcspFetchContext {
                cache_key: "async-key-1",
                urls: &urls,
                request_der: &req_der,
                cache_provider: &cache,
                ttl_secs: 60,
                timeout: Duration::from_secs(1),
                now_secs: 100,
            };
            let result = super::super::async_transport::fetch_from_cache_or_responder_async(
                &ctx, &transport,
            )
            .await
            .expect("cache hit");

            assert_eq!(result, vec![vec![10, 20, 30]]);
            // Transport must not have been called — cache served the response.
            assert_eq!(transport.call_count(), 0);
        }

        #[tokio::test]
        async fn async_cache_miss_calls_transport_and_stores_result() {
            let transport = AsyncFakeTransport::ok(vec![7, 8, 9]);
            let cache = InMemoryTestCache::new();
            let urls = vec!["http://example.test/ocsp".to_string()];
            let req_der = vec![4, 5, 6];

            let ctx = OcspFetchContext {
                cache_key: "async-key-2",
                urls: &urls,
                request_der: &req_der,
                cache_provider: &cache,
                ttl_secs: 60,
                timeout: Duration::from_secs(1),
                now_secs: 200,
            };
            let first = super::super::async_transport::fetch_from_cache_or_responder_async(
                &ctx, &transport,
            )
            .await
            .expect("first fetch");

            let ctx = OcspFetchContext {
                cache_key: "async-key-2",
                urls: &urls,
                request_der: &req_der,
                cache_provider: &cache,
                ttl_secs: 60,
                timeout: Duration::from_secs(1),
                now_secs: 201,
            };
            let second = super::super::async_transport::fetch_from_cache_or_responder_async(
                &ctx, &transport,
            )
            .await
            .expect("second fetch");

            assert_eq!(first, vec![vec![7, 8, 9]]);
            assert_eq!(second, vec![vec![7, 8, 9]]);
            // Transport called only on first miss; second served from cache.
            assert_eq!(transport.call_count(), 1);
            assert_eq!(cache.put_count(), 1);
        }

        #[tokio::test]
        async fn async_transport_failure_is_gracefully_skipped() {
            let transport = AsyncFakeTransport::failing();
            let cache = InMemoryTestCache::new();
            let urls = vec!["http://example.test/ocsp".to_string()];
            let req_der = vec![0u8; 16];

            let ctx = OcspFetchContext {
                cache_key: "async-key-fail",
                urls: &urls,
                request_der: &req_der,
                cache_provider: &cache,
                ttl_secs: 60,
                timeout: Duration::from_secs(1),
                now_secs: 300,
            };
            let result = super::super::async_transport::fetch_from_cache_or_responder_async(
                &ctx, &transport,
            )
            .await
            .expect("transport failure must not propagate — result is empty");

            // Transport errors are skipped; empty response is returned without panic.
            assert!(result.is_empty());
            // Nothing cached for a failed fetch.
            assert_eq!(cache.put_count(), 0);
        }

        #[tokio::test]
        async fn async_empty_transport_body_is_not_cached() {
            let transport = AsyncFakeTransport::ok(Vec::new()); // empty body
            let cache = InMemoryTestCache::new();
            let urls = vec!["http://example.test/ocsp".to_string()];
            let req_der = vec![0u8; 4];

            for i in 0u64..3 {
                let ctx = OcspFetchContext {
                    cache_key: "async-key-empty",
                    urls: &urls,
                    request_der: &req_der,
                    cache_provider: &cache,
                    ttl_secs: 60,
                    timeout: Duration::from_secs(1),
                    now_secs: 400 + i,
                };
                let res = super::super::async_transport::fetch_from_cache_or_responder_async(
                    &ctx, &transport,
                )
                .await
                .expect("call");
                assert!(res.is_empty());
            }

            // Transport called every time because empty body is not cached.
            assert_eq!(transport.call_count(), 3);
            assert_eq!(cache.put_count(), 0);
        }

        #[tokio::test]
        async fn async_concurrent_transport_calls_all_complete() {
            let transport = Arc::new(AsyncFakeTransport::ok(vec![42]));
            let cache = Arc::new(InMemoryTestCache::new());
            let urls = vec!["http://example.test/ocsp".to_string()];
            let req_der = vec![0u8; 8];

            const CONCURRENCY: usize = 32;
            let mut handles = Vec::with_capacity(CONCURRENCY);

            for i in 0..CONCURRENCY {
                let transport = transport.clone();
                let cache = cache.clone();
                let urls = urls.clone();
                let req_der = req_der.clone();
                let key = format!("async-concurrent-{i}");
                handles.push(tokio::spawn(async move {
                    let ctx = OcspFetchContext {
                        cache_key: &key,
                        urls: &urls,
                        request_der: &req_der,
                        cache_provider: cache.as_ref(),
                        ttl_secs: 60,
                        timeout: Duration::from_secs(1),
                        now_secs: 500,
                    };
                    super::super::async_transport::fetch_from_cache_or_responder_async(
                        &ctx,
                        transport.as_ref(),
                    )
                    .await
                }));
            }

            let mut successes = 0usize;
            for handle in handles {
                if handle.await.is_ok_and(|r| r.is_ok()) {
                    successes += 1;
                }
            }
            assert_eq!(
                successes, CONCURRENCY,
                "all {CONCURRENCY} concurrent async fetches must succeed"
            );
            // Each unique key misses cache → transport called once per key.
            assert_eq!(transport.call_count() as usize, CONCURRENCY);
        }
    }

    // The previous shared-runtime worker path and its metrics tests were removed.
}

#[cfg(all(test, feature = "async-ocsp"))]
mod ocsp_ssrf_tests {
    use super::async_transport::{AsyncOcspHttpTransport, ReqwestOcspTransport};
    use std::time::Duration;

    /// The responder URL comes from an inbound certificate's AIA extension, and
    /// revocation checking runs *before* that certificate is trusted. Without a
    /// private-range check a peer could point it at cloud instance metadata or
    /// an internal admin endpoint and have this process POST to it.
    #[tokio::test]
    async fn a_responder_on_a_private_or_link_local_address_is_refused() {
        let transport = ReqwestOcspTransport::new();
        for url in [
            "http://169.254.169.254/latest/meta-data/", // cloud metadata
            "http://127.0.0.1:8080/ocsp",
            "http://localhost/ocsp",
            "http://10.0.0.5/ocsp",
            "http://192.168.1.1/ocsp",
            "https://[::1]/ocsp",
        ] {
            let err = transport
                .post_ocsp_request_async(url, b"req", Duration::from_secs(1))
                .await
                .expect_err("must refuse a private-range OCSP responder");
            assert_eq!(
                err.code,
                crate::core::ErrorCode::InvalidInput,
                "url {url} produced {err:?}"
            );
        }
    }

    /// A non-HTTP scheme must not reach the transport either.
    #[tokio::test]
    async fn a_non_http_responder_scheme_is_refused() {
        let transport = ReqwestOcspTransport::new();
        for url in ["file:///etc/passwd", "gopher://example.org/", "ftp://x/"] {
            let err = transport
                .post_ocsp_request_async(url, b"req", Duration::from_secs(1))
                .await
                .expect_err("must refuse a non-HTTP scheme");
            assert_eq!(err.code, crate::core::ErrorCode::InvalidInput);
        }
    }

    /// RFC 6960 responders are routinely plain HTTP and their responses are
    /// signed, so requiring HTTPS here would break revocation against most
    /// public PKIs. Plain HTTP must therefore pass *validation* — it fails
    /// later, at connect time, which is a different error.
    #[tokio::test]
    async fn plain_http_to_a_public_host_passes_validation() {
        let transport = ReqwestOcspTransport::new();
        let err = transport
            .post_ocsp_request_async(
                "http://ocsp.invalid-tld-for-tests./x",
                b"req",
                Duration::from_millis(200),
            )
            .await
            .expect_err("the host does not resolve");
        // Whatever it is, it must not be the scheme rejection.
        assert!(
            !err.message.contains("plain HTTP egress is not permitted"),
            "plain HTTP must be allowed for OCSP: {err:?}"
        );
    }
}