jmap-base-client 0.1.2

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

use std::sync::Arc;

use base64::engine::general_purpose::STANDARD as BASE64_STANDARD;
use base64::Engine as _;
use reqwest::header::HeaderValue;
use zeroize::Zeroizing;

use crate::error::ClientError;

// ---------------------------------------------------------------------------
// TransportConfig — HTTP client construction (TLS, timeouts, trust roots)
// ---------------------------------------------------------------------------

/// Opaque HTTP client returned by [`TransportConfig::build_client`]
/// (bd:JMAP-6r7c.36).
///
/// The inner third-party type is private; the wrapper exists so the JMAP
/// transport identity does not leak through the public trait signature.
/// A future swap of the underlying HTTP library (e.g. `ureq`, `hyper-util`
/// directly, `curl`) replaces the wrapped type without breaking any
/// downstream extension client or custom `TransportConfig` impl that
/// returns `Result<HttpClient, ClientError>` from `build_client`.
///
/// Custom transports construct via [`HttpClient::new`] — that signature
/// still references [`reqwest::Client`] (the only construction path the
/// kit knows how to make HTTP requests against). The partial-wrap
/// argument mirrors [`ParseError`](crate::error::ParseError) /
/// [`SerializeError`](crate::error::SerializeError): the variant
/// payload / return type is opaque, but the construction signature still
/// names the third-party type so callers have a way in. A future
/// transport swap would deprecate this constructor in favor of an
/// analogous one for the new HTTP client; the wrapper type itself
/// stays stable.
#[non_exhaustive]
pub struct HttpClient(reqwest::Client);

impl HttpClient {
    /// Wrap a [`reqwest::Client`] into an opaque [`HttpClient`].
    ///
    /// Custom [`TransportConfig`] impls use this constructor to wrap a
    /// reqwest client they built with their own TLS / proxy / timeout
    /// configuration:
    ///
    /// ```rust,ignore
    /// impl TransportConfig for MyCustomTransport {
    ///     fn build_client(&self) -> Result<HttpClient, ClientError> {
    ///         let client = reqwest::ClientBuilder::new()
    ///             .proxy(...)
    ///             .build()
    ///             .map_err(ClientError::from_reqwest)?;
    ///         Ok(HttpClient::new(client))
    ///     }
    /// }
    /// ```
    pub fn new(client: reqwest::Client) -> Self {
        Self(client)
    }

    /// Consume the wrapper and return the inner [`reqwest::Client`].
    ///
    /// `pub(crate)` so only this crate's [`JmapClient`](crate::JmapClient)
    /// construction path can unwrap — external code cannot reach inside
    /// the opaque wrapper. A future swap of the HTTP transport would
    /// change the return type here without affecting external callers
    /// (who only see the typed `Result<HttpClient, _>` from
    /// [`TransportConfig::build_client`]).
    pub(crate) fn into_inner(self) -> reqwest::Client {
        self.0
    }
}

impl std::fmt::Debug for HttpClient {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_tuple("HttpClient").finish()
    }
}

/// Controls how the underlying [`HttpClient`] is constructed.
///
/// Implementations configure TLS trust roots, client certificates, and
/// connect timeouts. This is separate from credential injection
/// (see [`AuthProvider`]) so transports and credentials compose freely.
///
/// **Implement this trait** when you need custom TLS logic (e.g. a private CA
/// or a client certificate).  For custom per-request credentials only,
/// implement [`AuthProvider`] instead.  [`DefaultTransport`] covers the common
/// case of publicly-trusted TLS with no custom certificates.
///
/// **Return type contract (bd:JMAP-6r7c.36).** `build_client` returns an
/// opaque [`HttpClient`] wrapper, not a bare [`reqwest::Client`]. Custom
/// impls construct via [`HttpClient::new`] after building their reqwest
/// client; the wrapper insulates the trait's public surface from a
/// future HTTP-transport swap.
///
/// **Maintainer note (bd:JMAP-6lsm.19):** if you add a new method to this
/// trait, update the manual blanket impl for `Box<dyn TransportConfig>` at
/// the bottom of this file. The crate ships a hand-written forwarding impl
/// for the boxed trait object so callers can store heterogeneous transport
/// configurations behind a single type. Adding a method here without
/// mirroring it on the blanket impl silently breaks the
/// `JmapClient::new(Box::<dyn TransportConfig>::new(...))` call shape.
pub trait TransportConfig: Send + Sync {
    /// Build the [`HttpClient`] for this transport configuration.
    fn build_client(&self) -> Result<HttpClient, ClientError>;
}

/// Standard reqwest client with a 10-second connect timeout; no custom TLS.
///
/// Use for servers with publicly-trusted certificates. Pair with any
/// [`AuthProvider`] for credential injection.
#[derive(Debug, Clone)]
pub struct DefaultTransport;

impl TransportConfig for DefaultTransport {
    fn build_client(&self) -> Result<HttpClient, ClientError> {
        default_reqwest_client().map(HttpClient::new)
    }
}

/// Custom CA trust root (DER-encoded). No `Authorization` header is injected.
///
/// Use when the server presents a certificate signed by a private CA.
/// Pair with any [`AuthProvider`] for credential injection — including
/// [`BearerAuth`] or [`BasicAuth`] if the server also requires credentials.
///
/// # Trust scope (bd:JMAP-6r7c.57)
///
/// **The bundled public webpki-roots are DISABLED in the constructed
/// reqwest client.** This type is intended for private-CA pinning —
/// connecting to a JMAP server identified by a private CA the operator
/// controls, *refusing* certificates signed by any public CA. That is
/// the threat model where this transport matters: a corporate internal
/// JMAP server, a service-mesh deployment, an air-gapped network. A
/// compromised or malicious public CA (DigiNotar 2011, Symantec 2017,
/// etc.) issuing a certificate for the target host name would otherwise
/// bypass the private-CA defense entirely; disabling the public roots
/// closes that gap.
///
/// If you want trust against BOTH the bundled public roots AND a custom
/// CA (a "hybrid" deployment), `CustomCaTransport` is the wrong tool —
/// implement [`TransportConfig`] directly with the additive behaviour
/// (`reqwest::ClientBuilder::add_root_certificate` does NOT call
/// `.tls_built_in_root_certs(false)` by default, so a hand-rolled impl
/// has the additive shape automatically).
#[derive(Clone)]
pub struct CustomCaTransport {
    der_cert: Vec<u8>,
}

impl CustomCaTransport {
    /// Construct a `CustomCaTransport` from a DER-encoded CA certificate.
    pub fn new(der_cert: Vec<u8>) -> Self {
        Self { der_cert }
    }

    /// Construct a `CustomCaTransport` from a PEM-encoded CA certificate
    /// (bd:JMAP-6r7c.37).
    ///
    /// Operators typically distribute private-CA certificates as PEM
    /// files (text-format, `-----BEGIN CERTIFICATE-----` framing).
    /// Without this helper, every caller has to convert PEM to DER
    /// themselves before passing to [`CustomCaTransport::new`]:
    ///
    /// ```rust,ignore
    /// // Without from_pem_bytes (the long way):
    /// let pem_bytes = std::fs::read("ca.pem")?;
    /// let der = rustls_pemfile::certs(&mut pem_bytes.as_slice())
    ///     .next()
    ///     .transpose()?
    ///     .ok_or("no certificate in PEM file")?
    ///     .to_vec();
    /// let transport = CustomCaTransport::new(der);
    ///
    /// // With from_pem_bytes (the short way):
    /// let transport = CustomCaTransport::from_pem_bytes(&std::fs::read("ca.pem")?)?;
    /// ```
    ///
    /// The first PEM-framed certificate in `pem_bytes` is used. To use
    /// a different certificate from a multi-cert bundle, split the
    /// bundle yourself and pass the desired one. Multi-cert chains
    /// (root + intermediate) require constructing a custom
    /// [`TransportConfig`] implementation that adds multiple roots —
    /// `CustomCaTransport` is single-root.
    ///
    /// # Errors
    ///
    /// Returns [`ClientError::InvalidArgument`] if `pem_bytes` does not
    /// contain a recognisable PEM-framed certificate or if the PEM
    /// body cannot be base64-decoded.
    ///
    /// **DER validity is NOT checked at this stage.** This matches the
    /// existing [`CustomCaTransport::new`] contract — invalid DER
    /// (PEM body that decodes to non-DER bytes) is detected later when
    /// the `JmapClient` is constructed and the underlying transport
    /// tries to load the root, at which point it surfaces as
    /// [`ClientError::Http`]. The PEM helper deliberately matches the
    /// DER helper's behaviour: cheap validation here, full validation
    /// at client-build time.
    pub fn from_pem_bytes(pem_bytes: &[u8]) -> Result<Self, ClientError> {
        // The PEM-to-DER conversion uses a minimal in-line decoder so
        // this crate does not need to depend on rustls_pemfile. DER
        // semantic validity is the underlying transport's
        // responsibility (it happens at build_client time, where
        // reqwest::Certificate::from_der + ClientBuilder do the
        // actual rustls/native-tls parse).
        let cert_bytes = parse_first_pem_cert(pem_bytes).ok_or_else(|| {
            ClientError::InvalidArgument(
                "CustomCaTransport::from_pem_bytes: no PEM-framed certificate found in input"
                    .into(),
            )
        })?;
        Ok(Self {
            der_cert: cert_bytes,
        })
    }
}

/// Extract the DER bytes of the first PEM-framed certificate in `input`.
///
/// PEM (RFC 7468) format: `-----BEGIN <label>-----` / base64 body /
/// `-----END <label>-----`. We accept any label whose payload is a
/// valid DER certificate (the most common label is `CERTIFICATE`;
/// some toolchains emit `X509 CERTIFICATE` or `TRUSTED CERTIFICATE`).
///
/// Returns `None` if no PEM frame is found or if the base64 body
/// cannot be decoded. The DER validity check is the caller's
/// responsibility (do it via `reqwest::Certificate::from_der`).
fn parse_first_pem_cert(input: &[u8]) -> Option<Vec<u8>> {
    use base64::Engine as _;
    let text = std::str::from_utf8(input).ok()?;
    // Find any BEGIN line. RFC 7468 §3 mandates exactly five hyphens
    // and an ASCII-uppercase label; we accept the common shapes.
    let begin_idx = text.find("-----BEGIN ")?;
    let after_begin = &text[begin_idx + "-----BEGIN ".len()..];
    let begin_eol = after_begin.find('\n')?;
    let label = after_begin[..begin_eol].trim().trim_end_matches('-').trim();
    let end_marker = format!("-----END {label}-----");
    let body_start = begin_idx + "-----BEGIN ".len() + begin_eol + 1;
    let end_offset = text[body_start..].find(end_marker.as_str())?;
    let body = &text[body_start..body_start + end_offset];
    // Strip whitespace from the base64 body. PEM allows line wraps
    // every 64 chars per RFC 7468 §3; the base64 standard engine
    // does not accept embedded whitespace.
    let body_no_ws: String = body.chars().filter(|c| !c.is_whitespace()).collect();
    base64::engine::general_purpose::STANDARD
        .decode(body_no_ws)
        .ok()
}

/// Extract the DER bytes of every PEM-framed certificate in `input`,
/// in input order (bd:JMAP-6r7c.65).
///
/// Iterates `-----BEGIN ... -----` / `-----END ... -----` frames and
/// decodes each base64 body. Skips frames that fail to decode (matches
/// `parse_first_pem_cert`'s lenient posture: DER semantic validity is
/// checked later by the underlying transport at `build_client` time).
/// Returns an empty `Vec` if no PEM frame is found.
fn parse_all_pem_certs(input: &[u8]) -> Vec<Vec<u8>> {
    use base64::Engine as _;
    let Ok(text) = std::str::from_utf8(input) else {
        return Vec::new();
    };
    let mut out = Vec::new();
    let mut rest = text;
    while let Some(begin_idx) = rest.find("-----BEGIN ") {
        let after_begin = &rest[begin_idx + "-----BEGIN ".len()..];
        let Some(begin_eol) = after_begin.find('\n') else {
            break;
        };
        let label = after_begin[..begin_eol].trim().trim_end_matches('-').trim();
        let end_marker = format!("-----END {label}-----");
        let body_start = begin_idx + "-----BEGIN ".len() + begin_eol + 1;
        let Some(end_offset) = rest[body_start..].find(end_marker.as_str()) else {
            break;
        };
        let body = &rest[body_start..body_start + end_offset];
        let body_no_ws: String = body.chars().filter(|c| !c.is_whitespace()).collect();
        if let Ok(der) = base64::engine::general_purpose::STANDARD.decode(body_no_ws) {
            out.push(der);
        }
        let consumed = body_start + end_offset + end_marker.len();
        rest = &rest[consumed..];
    }
    out
}

/// Manual `Debug` impl that redacts the DER-encoded CA bytes
/// (bd:JMAP-6r7c.13).
///
/// The DER bytes are not a credential, but they are deployment-identifying
/// material: a CA certificate uniquely identifies the deployment's PKI
/// (Subject DN, public key, signing algorithm, validity window, X.509
/// extensions). In federated or multi-tenant scenarios, surfacing those
/// bytes in `tracing` output reveals which private-CA-using customer the
/// client is configured to talk to. Print the length only and let the
/// caller obtain the bytes via a constructor-controlled path if they
/// genuinely need them.
///
/// Mirrors the redacting `Debug` impls on `BearerAuth` and `BasicAuth`
/// in this file and on `Session` and `AccountInfo` in `request.rs`.
impl std::fmt::Debug for CustomCaTransport {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("CustomCaTransport")
            .field("der_cert", &format_args!("<{} bytes>", self.der_cert.len()))
            .finish()
    }
}

impl TransportConfig for CustomCaTransport {
    fn build_client(&self) -> Result<HttpClient, ClientError> {
        let cert =
            reqwest::Certificate::from_der(&self.der_cert).map_err(ClientError::from_reqwest)?;
        // Replace (not augment) the trust root set with the configured
        // private CA. tls_built_in_root_certs(false) disables the bundled
        // webpki-roots before add_root_certificate adds the private CA —
        // the order matters because reqwest treats add_root_certificate
        // as additive (bd:JMAP-6r7c.57).
        let client = reqwest::ClientBuilder::new()
            .connect_timeout(std::time::Duration::from_secs(10))
            .tls_built_in_root_certs(false)
            .add_root_certificate(cert)
            .build()
            .map_err(ClientError::from_reqwest)?;
        Ok(HttpClient::new(client))
    }
}

// ---------------------------------------------------------------------------
// CustomTransportBuilder (bd:JMAP-6r7c.65)
// ---------------------------------------------------------------------------

/// Builder for a [`TransportConfig`] with multi-root trust chains and
/// optional mTLS client certificate (bd:JMAP-6r7c.65).
///
/// [`CustomCaTransport`] is single-root and has no mTLS support; the
/// builder is the richer-configuration counterpart. Common cases:
///
/// - **Private PKI with root + intermediate.** Add both via
///   [`add_root_pem`](Self::add_root_pem) (single cert) or
///   [`add_roots_pem_bundle`](Self::add_roots_pem_bundle) (bundle of
///   roots + intermediates).
/// - **Mutual TLS.** Add a client cert + key via
///   [`with_client_cert`](Self::with_client_cert).
/// - **Both.** Compose freely; the builder is chainable.
///
/// Like [`CustomCaTransport`], the resulting transport **replaces**
/// the bundled webpki-roots with the configured trust roots. A
/// "hybrid" deployment that wants both the bundled public roots AND
/// custom roots is not currently supported; implement
/// [`TransportConfig`] directly with the additive behaviour
/// (`reqwest::ClientBuilder::add_root_certificate` is additive by
/// default — a hand-rolled impl that omits
/// `.tls_built_in_root_certs(false)` keeps the bundled roots).
///
/// # Usage
///
/// ```rust,ignore
/// use jmap_base_client::auth::CustomTransportBuilder;
///
/// let transport = CustomTransportBuilder::new()
///     .add_root_pem(&std::fs::read("ca-root.pem")?)?
///     .add_root_pem(&std::fs::read("ca-intermediate.pem")?)?
///     .with_client_cert(
///         std::fs::read("client.pem")?,
///         std::fs::read("client.key.pem")?,
///     )
///     .build();
///
/// let client = JmapClient::new(
///     transport,
///     BearerAuth::new(token)?,
///     "https://internal-jmap.corp",
///     ClientConfig::default(),
/// )?;
/// ```
#[derive(Default)]
pub struct CustomTransportBuilder {
    roots_der: Vec<Vec<u8>>,
    // (cert_pem, key_pem) pair — concatenated into a single PEM bundle
    // for reqwest::Identity::from_pem at build_client time.
    client_identity: Option<(Vec<u8>, Vec<u8>)>,
}

impl CustomTransportBuilder {
    /// Construct an empty builder. A builder with no trust roots and
    /// no client identity will produce a transport that rejects
    /// every TLS connection (no trust roots configured); add at
    /// least one root before [`build`](Self::build).
    pub fn new() -> Self {
        Self::default()
    }

    /// Add a DER-encoded trust-root certificate.
    ///
    /// Validation of the DER bytes is deferred to
    /// [`build`](Self::build) (same posture as
    /// [`CustomCaTransport::new`]). Invalid DER surfaces as
    /// [`ClientError::Http`] at `JmapClient::new` time.
    pub fn add_root_der(mut self, der: Vec<u8>) -> Self {
        self.roots_der.push(der);
        self
    }

    /// Add a PEM-encoded trust-root certificate. The first
    /// PEM-framed certificate in `pem` is consumed; embedded
    /// chains require [`add_roots_pem_bundle`](Self::add_roots_pem_bundle).
    ///
    /// # Errors
    ///
    /// Returns [`ClientError::InvalidArgument`] if `pem` does not
    /// contain a recognisable PEM-framed certificate.
    pub fn add_root_pem(self, pem: &[u8]) -> Result<Self, ClientError> {
        let der = parse_first_pem_cert(pem).ok_or_else(|| {
            ClientError::InvalidArgument(
                "CustomTransportBuilder::add_root_pem: no PEM-framed certificate found in input"
                    .into(),
            )
        })?;
        Ok(self.add_root_der(der))
    }

    /// Add every PEM-framed certificate in a multi-cert bundle.
    ///
    /// A typical private-PKI deployment ships a bundle containing
    /// the root plus one or more intermediates as concatenated PEM
    /// blocks. This method iterates each `-----BEGIN CERTIFICATE-----`
    /// block in input order and adds each to the trust set.
    ///
    /// # Errors
    ///
    /// Returns [`ClientError::InvalidArgument`] if no PEM-framed
    /// certificate is found in the bundle.
    pub fn add_roots_pem_bundle(mut self, pem_bundle: &[u8]) -> Result<Self, ClientError> {
        let ders = parse_all_pem_certs(pem_bundle);
        if ders.is_empty() {
            return Err(ClientError::InvalidArgument(
                "CustomTransportBuilder::add_roots_pem_bundle: no PEM-framed \
                 certificates found in bundle"
                    .into(),
            ));
        }
        self.roots_der.extend(ders);
        Ok(self)
    }

    /// Configure a client certificate + private key for mutual TLS.
    ///
    /// Replaces any previously-configured client identity. The two
    /// PEM byte slices are stored verbatim and concatenated at
    /// [`build`](Self::build) time into a single PEM bundle that
    /// [`reqwest::Identity::from_pem`] consumes.
    ///
    /// `cert_pem` may contain a single client cert or a cert +
    /// intermediates chain. `key_pem` carries the private key
    /// (PKCS#1 or PKCS#8, RSA or ECDSA — whatever reqwest's rustls
    /// build supports).
    pub fn with_client_cert(mut self, cert_pem: Vec<u8>, key_pem: Vec<u8>) -> Self {
        self.client_identity = Some((cert_pem, key_pem));
        self
    }

    /// Consume the builder and return a [`TransportConfig`]
    /// implementation that produces a [`reqwest::Client`] configured
    /// with the accumulated trust roots and optional client identity.
    ///
    /// Behaves identically to [`CustomCaTransport::build_client`] for
    /// single-root use; the additional functionality (multi-root +
    /// mTLS) kicks in when the builder was configured with more than
    /// one root or a client identity.
    pub fn build(self) -> BuilderTransport {
        BuilderTransport {
            roots_der: self.roots_der,
            client_identity: self.client_identity,
        }
    }
}

/// Concrete [`TransportConfig`] produced by [`CustomTransportBuilder::build`].
///
/// Stores the accumulated trust roots and optional client identity by
/// value. Cloneable so consumers that need multiple `JmapClient` instances
/// sharing the same transport configuration can do so without rebuilding.
#[derive(Clone)]
pub struct BuilderTransport {
    roots_der: Vec<Vec<u8>>,
    client_identity: Option<(Vec<u8>, Vec<u8>)>,
}

impl std::fmt::Debug for BuilderTransport {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("BuilderTransport")
            .field(
                "roots_der",
                &format_args!("<{} root cert(s)>", self.roots_der.len()),
            )
            .field(
                "client_identity",
                &format_args!(
                    "<{}>",
                    if self.client_identity.is_some() {
                        "client cert configured"
                    } else {
                        "no client cert"
                    }
                ),
            )
            .finish()
    }
}

impl TransportConfig for BuilderTransport {
    fn build_client(&self) -> Result<HttpClient, ClientError> {
        let mut builder = reqwest::ClientBuilder::new()
            .connect_timeout(std::time::Duration::from_secs(10))
            // Replace (not augment) the trust root set. See
            // CustomCaTransport rationale (bd:JMAP-6r7c.57). Builder
            // users who want hybrid trust (bundled + private) are
            // expected to implement TransportConfig directly.
            .tls_built_in_root_certs(false);

        for der in &self.roots_der {
            let cert = reqwest::Certificate::from_der(der).map_err(ClientError::from_reqwest)?;
            builder = builder.add_root_certificate(cert);
        }

        if let Some((cert_pem, key_pem)) = &self.client_identity {
            // reqwest::Identity::from_pem expects the cert chain and
            // private key concatenated into one PEM bundle. Build
            // that bundle locally without leaking either input across
            // the function boundary.
            let mut bundle = Vec::with_capacity(cert_pem.len() + key_pem.len() + 1);
            bundle.extend_from_slice(cert_pem);
            if !cert_pem.ends_with(b"\n") {
                bundle.push(b'\n');
            }
            bundle.extend_from_slice(key_pem);
            let identity =
                reqwest::Identity::from_pem(&bundle).map_err(ClientError::from_reqwest)?;
            builder = builder.identity(identity);
        }

        let client = builder.build().map_err(ClientError::from_reqwest)?;
        Ok(HttpClient::new(client))
    }
}

// ---------------------------------------------------------------------------
// AuthProvider — per-request credential injection (Authorization header)
// ---------------------------------------------------------------------------

/// Single HTTP `(name, value)` header pair, returned by
/// [`AuthProvider::auth_header`] (bd:JMAP-6r7c.62, bd:JMAP-6r7c.20).
///
/// The wrapper exists for two purposes:
///
/// 1. **Compile-time secret-typing.** [`AuthHeader`]'s `Debug` impl
///    redacts the header value to `"[REDACTED]"`. A future
///    [`AuthProvider`] impl that writes
///    `tracing::trace!(?header, "injecting")` cannot leak the credential
///    through that path because the wrapper's `Debug` output never
///    contains the value bytes. The pre-bd:JMAP-6r7c.62 shape
///    (`Option<(&str, &str)>`) had no such guard — a string tuple
///    formats verbatim via `?`-syntax.
/// 2. **Bounded API surface.** The wrapper packages exactly one
///    `(name, value)` pair. The trait's signature does not admit a
///    list, a sequence, or a per-request-computed value. This is the
///    intentional limitation: `AuthProvider` covers "static,
///    per-connection single-header auth schemes" only (Bearer, Basic,
///    mTLS via [`TransportConfig`]). Schemes that need multiple
///    request-dependent headers (AWS SigV4, OAuth request signing) or
///    async credential refresh require a different abstraction —
///    currently, custom [`TransportConfig`] impls that wire per-request
///    middleware (bd:JMAP-6r7c.20).
///
/// Construct via [`AuthHeader::new`] — both `name` and `value` are
/// caller-supplied borrows; the wrapper stashes them as-is. The
/// constructor does not validate HTTP-header-value syntax; downstream
/// consumers (e.g. [`connect_ws`](crate::ws::connect_ws)) validate at
/// the call site and surface [`ClientError::InvalidArgument`] for
/// invalid bytes.
#[non_exhaustive]
#[derive(Clone, Copy)]
pub struct AuthHeader<'a> {
    name: &'a str,
    value: &'a str,
}

impl<'a> AuthHeader<'a> {
    /// Construct an [`AuthHeader`] from a header name and value borrow.
    pub fn new(name: &'a str, value: &'a str) -> Self {
        Self { name, value }
    }

    /// Borrow the header name. Lowercase-ASCII per RFC 9110 §5.1.
    pub fn name(&self) -> &'a str {
        self.name
    }

    /// Borrow the header value.
    ///
    /// **Do not log this return value.** The value is credential
    /// material; see the type-level rustdoc. The constructor name is
    /// deliberately explicit ([`expose_value`](Self::expose_value)) so a
    /// call site reveals the intent — a `tracing::*` line that
    /// references `header.expose_value()` is visible in code review,
    /// whereas a `?header` formatter is not.
    pub fn expose_value(&self) -> &'a str {
        self.value
    }
}

impl std::fmt::Debug for AuthHeader<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("AuthHeader")
            .field("name", &self.name)
            .field("value", &"[REDACTED]")
            .finish()
    }
}

/// Injects per-request authentication credentials.
///
/// Separate from transport configuration ([`TransportConfig`]) so any
/// credential scheme can be paired with any transport.
///
/// **Implement this trait** when you need a custom `Authorization` header or
/// other per-request credential scheme.  For custom TLS/trust-root logic
/// implement [`TransportConfig`] instead.  [`NoneAuth`], [`BearerAuth`], and
/// [`BasicAuth`] cover the common cases.
///
/// Implementations **must not** log the return value of [`auth_header`];
/// it contains credentials. The [`AuthHeader`] return type provides a
/// compile-time guard against the most common leak path — its `Debug`
/// impl redacts the value bytes — but the explicit
/// [`expose_value`](AuthHeader::expose_value) accessor must not be fed
/// into a `tracing::*` argument either.
///
/// [`auth_header`]: AuthProvider::auth_header
///
/// # Intentional limitation: static single-header per-connection schemes (bd:JMAP-6r7c.20)
///
/// The trait shape commits the kit to "static, per-connection,
/// single-header auth schemes" — bearer-token, HTTP Basic, mTLS via
/// [`TransportConfig`]. Three constraints follow from the
/// [`AuthHeader`] return type:
///
/// 1. **One header per request.** A scheme that needs to attach
///    multiple headers per request (AWS SigV4 carries
///    `Authorization`, `X-Amz-Date`, and `X-Amz-Security-Token`
///    together) cannot be expressed by this trait.
/// 2. **No per-request signature.** [`auth_header`] takes `&self`
///    only — there is no access to the request URL, method, or body.
///    Schemes that compute an HMAC over the request body (SigV4,
///    OAuth request signing) cannot be expressed.
/// 3. **No async refresh.** [`auth_header`] is sync. A scheme that
///    needs to refresh an expired OAuth token before returning
///    cannot await inside this method.
///
/// Workaround for callers who need any of the three: implement a
/// custom [`TransportConfig`] that wires per-request middleware into
/// the [`HttpClient`] it returns from
/// [`build_client`](TransportConfig::build_client). The middleware can
/// observe the full request, compute signatures, and refresh tokens
/// asynchronously. The cost is the awkward layering inversion — TLS
/// config and credential injection conceptually belong to different
/// traits — but it does compose against the existing
/// [`AuthProvider::auth_header`] trait without breakage.
///
/// A future reshape that supports the three constraints (likely a
/// new trait, not a backward-compatible widening of this one) would
/// not deprecate `AuthProvider`. The current trait stays as the
/// "fast path for the common case" alongside any richer abstraction.
///
/// # Credential lifetime
///
/// Implementations that cache header bytes (e.g. [`BearerAuth`],
/// [`BasicAuth`]) SHOULD wrap the cached buffer in [`zeroize::Zeroizing`]
/// or equivalent so the credential is overwritten on drop rather than
/// left in freed heap until the allocator re-uses the slab. Callers that
/// build a credential string before passing it into a constructor (e.g.
/// `BearerAuth::new(token)`) SHOULD likewise store that string in a
/// `Zeroizing<String>` — the zeroization done by the auth-type is bounded
/// by what the type owns and cannot reach back into the caller's buffer
/// (bd:JMAP-6r7c.59).
///
/// **Maintainer note (bd:JMAP-6lsm.19):** if you add a new method to this
/// trait, update BOTH manual blanket impls — `Box<dyn AuthProvider>` and
/// `Arc<dyn AuthProvider>` — at the bottom of this file. The crate
/// supports both Box and Arc trait-object call shapes (e.g. for sharing
/// one credential source across multiple `JmapClient`s), and a missing
/// blanket method silently breaks one of those shapes without breaking
/// the other.
pub trait AuthProvider: Send + Sync {
    /// Return an optional [`AuthHeader`] to attach to every request.
    ///
    /// Returns `None` when no `Authorization` header is required.
    ///
    /// The header name and value both borrow from `self` and must live
    /// at least as long as the `&self` borrow. Implementations that
    /// pre-compute the values at construction time can return
    /// `AuthHeader::new("authorization", &self.field)` directly,
    /// avoiding any per-request allocation.
    ///
    /// # Implementation contract
    ///
    /// The returned strings **must** be valid HTTP field values (RFC 9110 §5):
    /// - Header name: lowercase ASCII token characters only (no spaces, no
    ///   control characters); e.g. `"authorization"`.
    /// - Header value: visible ASCII characters (0x21–0x7E) and horizontal tab
    ///   (0x09) only; no other control characters.
    ///
    /// Implementations that violate this contract will cause
    /// [`ClientError::InvalidArgument`] in `connect_ws` (`ws/mod.rs`), which
    /// parses the value into a typed [`http::HeaderValue`]. On HTTP code paths
    /// reqwest returns the error from `.send()` as a builder error rather than
    /// an `InvalidArgument` — the error type differs between the two paths.
    /// Test all custom `AuthProvider` implementations against both HTTP and
    /// WebSocket call paths.
    fn auth_header(&self) -> Option<AuthHeader<'_>>;
}

/// No authentication: no `Authorization` header.
#[derive(Debug, Clone)]
pub struct NoneAuth;

impl AuthProvider for NoneAuth {
    fn auth_header(&self) -> Option<AuthHeader<'_>> {
        None
    }
}

/// Bearer-token authentication (`Authorization: Bearer <token>`).
///
/// # Drop-path zeroization
///
/// The cached header string is wrapped in [`zeroize::Zeroizing`] so its
/// buffer is overwritten with zeros before being returned to the allocator
/// on drop. This defends against credential recovery from process core
/// dumps, `/proc/PID/mem` inspection, and post-drop heap re-use across
/// tenants in long-running multi-user JMAP clients (bd:JMAP-6r7c.59).
/// Callers that hold the original token string SHOULD also store it in a
/// `Zeroizing<String>` or equivalent — the zeroization here is bounded by
/// what this type owns.
///
/// # Do not move validation from construction to per-request (bd:JMAP-6r7c.18)
///
/// A future contributor may suggest "just store the token field and call
/// `HeaderValue::from_str` in `auth_header` on each request". This is the
/// wrong simplification for both `BearerAuth` and `BasicAuth`. Five
/// reasons:
///
/// 1. **Fail-fast at auth setup.** Validation at construction means
///    invalid credentials surface at `BearerAuth::new()` return value —
///    the caller fails near the bug source (their auth-setup code).
///    Per-request validation pushes failures to the first
///    `JmapClient::call()` or `fetch_session()`, far from the bug and
///    harder to debug.
/// 2. **Hot-path performance.** `auth_header` is called on every HTTP
///    request and every WebSocket connection. `HeaderValue::from_str`
///    walks the string and rejects on the first non-VCHAR/SP/HTAB
///    octet (RFC 7230 §3.2.6) — non-trivial work for a hot path.
///    Pre-validation moves that work out of every request.
/// 3. **Infallible accessor signature.** Pre-validation lets
///    `auth_header` keep the signature
///    `fn auth_header(&self) -> Option<AuthHeader<'_>>` — infallible.
///    Per-request validation would require
///    `Result<Option<(&str, &str)>, ClientError>`, propagating an
///    extra error layer through every call site (HTTP `call`, blob
///    upload/download, WebSocket connect, session fetch).
/// 4. **Borrow simplicity.** Storing as `Zeroizing<String>` lets
///    `auth_header` return borrows directly without ownership tricks
///    (`Cow`, `Box<str>`, etc.). The borrow checker stays simple, the
///    call sites stay readable.
/// 5. **Debug-redaction tripwire compatibility.** The manual `Debug`
///    impls on `BearerAuth` and `BasicAuth` (auth.rs further below)
///    target the stored field. A future contributor adding
///    `#[derive(Debug)]` instead of the manual impl is caught
///    immediately by the existing canary tests
///    `bearer_auth_debug_does_not_leak_token` and
///    `basic_auth_debug_does_not_leak_credentials` (bd:JMAP-sc1b.79).
///    Moving to per-request validation requires the field shape to
///    change in a way that re-derives the canary contract — extra
///    surface area for review without buying anything.
///
/// This is the same pre-validate-at-construction pattern `rustls` and
/// `reqwest` use for their own type designs. It is not over-engineering.
#[derive(Clone)]
pub struct BearerAuth {
    // Pre-validated at construction and stored as String: avoids per-request
    // allocation and ensures invalid credentials fail at construction, not at
    // the first request. Storing as String eliminates the need for a fallible
    // to_str() call in auth_header().
    //
    // Wrapped in Zeroizing<String> so the buffer is overwritten on drop
    // (see type-level doc). Zeroizing<String> Derefs to String, which Derefs
    // to &str, so `&self.header_string` in auth_header() coerces cleanly.
    header_string: Zeroizing<String>,
}

impl BearerAuth {
    /// Construct a `BearerAuth` from a Bearer token string.
    ///
    /// # Errors
    ///
    /// - [`ClientError::InvalidArgument`] if `token` is empty or contains
    ///   whitespace (RFC 6750 §2.1 bearer tokens must not contain whitespace).
    /// - [`ClientError::InvalidHeaderValue`] if `token` contains characters that
    ///   are not valid in an HTTP header value (non-visible-ASCII octets).
    pub fn new(token: &str) -> Result<Self, ClientError> {
        if token.is_empty() || token.chars().any(|c| c.is_ascii_whitespace()) {
            return Err(ClientError::InvalidArgument(
                "BearerAuth token may not be empty or contain whitespace (RFC 6750 §2.1)".into(),
            ));
        }
        let header_string = Zeroizing::new(format!("Bearer {token}"));
        // Validate the header value is legal (no control characters, etc.).
        HeaderValue::from_str(&header_string).map_err(ClientError::from_invalid_header)?;
        Ok(Self { header_string })
    }
}

impl std::fmt::Debug for BearerAuth {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("BearerAuth")
            .field("token", &"[REDACTED]")
            .finish()
    }
}

impl AuthProvider for BearerAuth {
    fn auth_header(&self) -> Option<AuthHeader<'_>> {
        Some(AuthHeader::new("authorization", &self.header_string))
    }
}

/// HTTP Basic authentication (`Authorization: Basic <base64(username:password)>`).
///
/// Credentials are encoded per RFC 7617: `base64(username ":" password)`.
///
/// # Drop-path zeroization
///
/// The cached header string is wrapped in [`zeroize::Zeroizing`] so its
/// buffer is overwritten with zeros before being returned to the allocator
/// on drop. The intermediate `username:password` plaintext built during
/// base64 encoding is ALSO zeroized — that buffer is the most
/// attack-relevant artifact because it carries the raw password rather
/// than the base64-encoded form. See [`BearerAuth`] for the threat model.
/// (bd:JMAP-6r7c.59)
#[derive(Clone)]
pub struct BasicAuth {
    // Pre-validated at construction and stored as String: avoids per-request
    // allocation and ensures invalid credentials fail at construction, not at
    // the first request. Storing as String eliminates the need for a fallible
    // to_str() call in auth_header().
    //
    // Wrapped in Zeroizing<String> so the buffer is overwritten on drop
    // (see type-level doc).
    header_string: Zeroizing<String>,
}

impl BasicAuth {
    /// Construct a `BasicAuth` from a username and password.
    ///
    /// # Errors
    ///
    /// - [`ClientError::InvalidArgument`] if `username` contains a colon (`:`),
    ///   which is forbidden by RFC 7617 §2.
    /// - [`ClientError::InvalidHeaderValue`] if the resulting header value
    ///   contains characters that are not valid in an HTTP header value.
    pub fn new(username: &str, password: &str) -> Result<Self, ClientError> {
        if username.contains(':') {
            return Err(ClientError::InvalidArgument(
                "BasicAuth username may not contain ':'".into(),
            ));
        }
        // The intermediate plaintext buffer is the most sensitive artifact
        // — it carries the raw password, whereas the base64-encoded form is
        // one step further from a credential a replay attacker can use.
        // Wrap it in Zeroizing so the buffer is overwritten when the local
        // goes out of scope at the end of this function.
        let plaintext = Zeroizing::new(format!("{username}:{password}"));
        let encoded = BASE64_STANDARD.encode(plaintext.as_bytes());
        let header_string = Zeroizing::new(format!("Basic {encoded}"));
        // Validate the header value is legal (base64 is always printable ASCII,
        // but keep the check for correctness).
        HeaderValue::from_str(&header_string).map_err(ClientError::from_invalid_header)?;
        Ok(Self { header_string })
    }
}

impl std::fmt::Debug for BasicAuth {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("BasicAuth")
            .field("credentials", &"[REDACTED]")
            .finish()
    }
}

impl AuthProvider for BasicAuth {
    fn auth_header(&self) -> Option<AuthHeader<'_>> {
        Some(AuthHeader::new("authorization", &self.header_string))
    }
}

// ---------------------------------------------------------------------------
// Internal helper
// ---------------------------------------------------------------------------

/// Build a standard reqwest client with a 10-second connect timeout.
fn default_reqwest_client() -> Result<reqwest::Client, ClientError> {
    reqwest::ClientBuilder::new()
        .connect_timeout(std::time::Duration::from_secs(10))
        .build()
        .map_err(ClientError::from_reqwest)
}

// ---------------------------------------------------------------------------
// Blanket impl for Box<dyn TransportConfig>
// ---------------------------------------------------------------------------
//
// Allows `Box<dyn TransportConfig>` to satisfy `impl TransportConfig`, so
// factory functions (e.g. `Config::transport`) can return a boxed
// trait object and pass it directly to `JmapClient::new`.
//
// There is intentionally NO `Arc<dyn TransportConfig>` blanket here.
// TransportConfig is consumed once at `JmapClient::new` to build the
// reqwest::Client. The resulting Client is stored; the TransportConfig itself
// is not kept. Arc would imply shared ownership of something that is not
// shared after construction.
//
// Maintenance cost: every method added to `TransportConfig` must be mirrored here.
impl TransportConfig for Box<dyn TransportConfig> {
    fn build_client(&self) -> Result<HttpClient, ClientError> {
        (**self).build_client()
    }
}

// ---------------------------------------------------------------------------
// Blanket impl for Arc<dyn AuthProvider>
// ---------------------------------------------------------------------------
//
// Allows `Arc<dyn AuthProvider>` to satisfy `impl AuthProvider`, enabling
// `JmapClient` to be `Clone` (Arc is Clone).
//
// Maintenance cost: every method added to `AuthProvider` must be mirrored here.
impl AuthProvider for Arc<dyn AuthProvider> {
    fn auth_header(&self) -> Option<AuthHeader<'_>> {
        (**self).auth_header()
    }
}

// ---------------------------------------------------------------------------
// Blanket impl for Box<dyn AuthProvider>
// ---------------------------------------------------------------------------
//
// Allows `Box<dyn AuthProvider>` to satisfy `impl AuthProvider + 'static`,
// so factory functions (e.g. `Config::auth`) can return a boxed
// trait object and pass it directly to `JmapClient::new`.
//
// Maintenance cost: every method added to `AuthProvider` must be mirrored here.
impl AuthProvider for Box<dyn AuthProvider> {
    fn auth_header(&self) -> Option<AuthHeader<'_>> {
        (**self).auth_header()
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    /// Oracle: NoneAuth has no authentication header — verified by inspection of the spec.
    #[test]
    fn none_auth_no_header() {
        assert!(NoneAuth.auth_header().is_none());
    }

    /// Oracle: BearerAuth constructs successfully with a valid ASCII token.
    #[test]
    fn bearer_auth_valid_constructs() {
        assert!(BearerAuth::new("tok123").is_ok());
    }

    /// Oracle: BearerAuth header value is "Bearer " + the literal token string.
    /// Verified by inspection: the Authorization header MUST be "Bearer tok123".
    #[test]
    fn bearer_auth_header() {
        let auth = BearerAuth::new("tok123").expect("valid ASCII token must construct");
        let header = auth.auth_header().expect("BearerAuth must return a header");
        assert_eq!(header.name(), "authorization");
        assert_eq!(header.expose_value(), "Bearer tok123");
    }

    /// Oracle: BearerAuth constructor rejects tokens containing C0 control characters.
    /// HeaderValue::from_str rejects bytes 0x00-0x08 and 0x0A-0x1F (C0 controls,
    /// excluding HTAB 0x09) and 0x7F (DEL). '\x01' (SOH) is unconditionally invalid
    /// per RFC 7230 §3.2.6 and the http crate's header validation.
    #[test]
    fn bearer_auth_invalid_token_rejected() {
        let result = BearerAuth::new("tok\x01abc");
        assert!(
            result.is_err(),
            "token with C0 control character must be rejected by constructor"
        );
    }

    /// Oracle: BasicAuth constructs successfully with valid username and password.
    #[test]
    fn basic_auth_valid_constructs() {
        assert!(BasicAuth::new("alice", "s3cr3t").is_ok());
    }

    /// Oracle: BasicAuth constructor rejects usernames containing a colon (RFC 7617 §2).
    #[test]
    fn basic_auth_colon_in_username_rejected() {
        let result = BasicAuth::new("ali:ce", "s3cr3t");
        match result {
            Ok(_) => panic!("username with colon must be rejected by constructor"),
            Err(e) => {
                let err_msg = e.to_string();
                assert!(
                    err_msg.contains("username"),
                    "error message should mention 'username', got: {err_msg}"
                );
            }
        }
    }

    /// Oracle: `echo -n "alice:s3cr3t" | base64` → `YWxpY2U6czNjcjN0`  (RFC 7617 §2)
    /// This expected value is computed independently of the code under test.
    #[test]
    fn basic_auth_header() {
        let auth = BasicAuth::new("alice", "s3cr3t").expect("valid credentials must construct");
        let header = auth.auth_header().expect("BasicAuth must return a header");
        assert_eq!(header.name(), "authorization");
        assert_eq!(header.expose_value(), "Basic YWxpY2U6czNjcjN0");
    }

    /// Oracle: CustomCaTransport injects no auth header — it is a transport only.
    #[test]
    fn custom_ca_transport_no_build_with_empty_cert() {
        // Empty DER bytes will fail Certificate::from_der; this test confirms
        // CustomCaTransport is constructible and that auth is separate.
        let transport = CustomCaTransport::new(vec![]);
        assert!(transport.build_client().is_err(), "empty DER must fail");
    }

    // bd:JMAP-6r7c.65 — CustomTransportBuilder tests below.

    /// Oracle: `parse_all_pem_certs` extracts every PEM-framed
    /// certificate in a multi-cert bundle and skips non-certificate
    /// content between frames. Hand-rolled fixture: two valid PEM
    /// frames concatenated with leading and trailing prose.
    #[test]
    fn parse_all_pem_certs_handles_multi_cert_bundle() {
        // Read the single-cert fixture and concatenate it with itself
        // so the bundle has two identical PEM frames. The parser MUST
        // emit two DER blobs even though the content is duplicate.
        let single = std::fs::read("tests/fixtures/tls/test-ca.pem")
            .expect("test-ca.pem fixture must exist");
        let mut bundle = b"# Comment that the parser must ignore\n".to_vec();
        bundle.extend_from_slice(&single);
        bundle.extend_from_slice(b"\n# Another comment between frames\n");
        bundle.extend_from_slice(&single);
        bundle.extend_from_slice(b"\n# Trailing comment\n");

        let ders = parse_all_pem_certs(&bundle);
        assert_eq!(ders.len(), 2, "two-cert bundle must produce two DER blobs");
        assert!(!ders[0].is_empty(), "first DER must be non-empty");
        assert!(!ders[1].is_empty(), "second DER must be non-empty");
        // Deterministic same-input check: both decoded DERs must match
        // because the bundle contains the same cert twice.
        assert_eq!(
            ders[0], ders[1],
            "duplicate-input bundle must produce identical DER blobs"
        );
    }

    /// Oracle: `CustomTransportBuilder::add_root_pem` accepts a
    /// fixture PEM and `build` produces a working `TransportConfig`.
    #[test]
    fn custom_transport_builder_single_pem_root_builds() {
        let pem = std::fs::read("tests/fixtures/tls/test-ca.pem")
            .expect("test-ca.pem fixture must exist");
        let transport = CustomTransportBuilder::new()
            .add_root_pem(&pem)
            .expect("PEM fixture must parse")
            .build();
        transport
            .build_client()
            .expect("single-root build_client must succeed");
    }

    /// Oracle: `add_roots_pem_bundle` accepts a multi-PEM bundle.
    /// Two identical PEM frames concatenated produces a transport
    /// with two trust roots loaded.
    #[test]
    fn custom_transport_builder_multi_root_bundle_builds() {
        let single = std::fs::read("tests/fixtures/tls/test-ca.pem")
            .expect("test-ca.pem fixture must exist");
        let mut bundle = single.clone();
        bundle.extend_from_slice(b"\n");
        bundle.extend_from_slice(&single);

        let transport = CustomTransportBuilder::new()
            .add_roots_pem_bundle(&bundle)
            .expect("two-cert PEM bundle must parse")
            .build();
        transport
            .build_client()
            .expect("multi-root build_client must succeed");
    }

    /// Oracle: `add_root_pem` rejects input that is not a recognisable
    /// PEM-framed certificate. Returns ClientError::InvalidArgument
    /// rather than ClientError::Http — the parse error is at the
    /// PEM-decode boundary, not at reqwest's TLS layer.
    #[test]
    fn custom_transport_builder_add_root_pem_invalid_returns_invalid_argument() {
        let result = CustomTransportBuilder::new().add_root_pem(b"not a pem");
        match result {
            Ok(_) => panic!("garbage input must not produce a valid builder"),
            Err(ClientError::InvalidArgument(msg)) => {
                assert!(
                    msg.contains("CustomTransportBuilder::add_root_pem"),
                    "error must identify the offending method: {msg}"
                );
            }
            Err(other) => panic!("expected InvalidArgument, got {other:?}"),
        }
    }

    /// Oracle: `add_roots_pem_bundle` on input with no PEM frames
    /// returns ClientError::InvalidArgument.
    #[test]
    fn custom_transport_builder_empty_bundle_returns_invalid_argument() {
        let result = CustomTransportBuilder::new().add_roots_pem_bundle(b"plain text");
        match result {
            Ok(_) => panic!("input without PEM frames must not produce a valid builder"),
            Err(ClientError::InvalidArgument(msg)) => {
                assert!(
                    msg.contains("CustomTransportBuilder::add_roots_pem_bundle"),
                    "error must identify the offending method: {msg}"
                );
            }
            Err(other) => panic!("expected InvalidArgument, got {other:?}"),
        }
    }

    /// Oracle: `with_client_cert` configured with bogus PEM bytes
    /// surfaces the reqwest::Identity parse failure as
    /// ClientError::Http at build_client time. The builder itself
    /// does not validate the bytes (matches the DER posture of
    /// add_root_der + add_root_pem — full validation is deferred to
    /// build).
    #[test]
    fn custom_transport_builder_with_client_cert_invalid_fails_at_build() {
        // Valid root, invalid client identity.
        let pem = std::fs::read("tests/fixtures/tls/test-ca.pem")
            .expect("test-ca.pem fixture must exist");
        let transport = CustomTransportBuilder::new()
            .add_root_pem(&pem)
            .expect("PEM fixture must parse")
            .with_client_cert(b"not a cert PEM".to_vec(), b"not a key PEM".to_vec())
            .build();
        let result = transport.build_client();
        assert!(
            matches!(result, Err(ClientError::Http(_))),
            "invalid client identity must surface as ClientError::Http, got {result:?}"
        );
    }

    /// Oracle: `BuilderTransport::Debug` opaquely describes the
    /// trust-root count and identity presence without leaking the
    /// raw cert bytes. Mirror the tripwire pattern from the
    /// CustomCaTransport Debug-redaction test (bd:JMAP-6r7c.13).
    #[test]
    fn builder_transport_debug_does_not_leak_cert_bytes() {
        let canary = vec![0xCA_u8; 32];
        let transport = CustomTransportBuilder::new().add_root_der(canary).build();
        let dbg = format!("{transport:?}");
        assert!(
            !dbg.contains("cacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacaca"),
            "BuilderTransport Debug must not contain lowercase-hex DER bytes; got: {dbg}"
        );
        assert!(
            dbg.contains("1 root cert"),
            "BuilderTransport Debug must surface the root count for diagnostics; got: {dbg}"
        );
    }

    /// Oracle: BearerAuth constructor rejects an empty token string.
    /// An empty token would produce "Bearer " which is a malformed credential.
    #[test]
    fn bearer_auth_empty_token_rejected() {
        let result = BearerAuth::new("");
        match result {
            Ok(_) => panic!("empty token must be rejected by constructor"),
            Err(ClientError::InvalidArgument(msg)) => {
                assert!(
                    msg.contains("empty"),
                    "error message should mention 'empty', got: {msg}"
                );
            }
            Err(e) => panic!("expected InvalidArgument, got: {e}"),
        }
    }

    /// Oracle: BearerAuth constructor rejects a whitespace-only token string.
    /// A whitespace-only token would produce "Bearer   " which is a malformed credential.
    #[test]
    fn bearer_auth_whitespace_only_token_rejected() {
        let result = BearerAuth::new("   ");
        match result {
            Ok(_) => panic!("whitespace-only token must be rejected by constructor"),
            Err(ClientError::InvalidArgument(msg)) => {
                assert!(
                    msg.contains("whitespace"),
                    "error message should mention 'whitespace', got: {msg}"
                );
            }
            Err(e) => panic!("expected InvalidArgument, got: {e}"),
        }
    }

    /// Oracle: DefaultTransport uses the default reqwest::Client which always builds successfully.
    #[tokio::test]
    async fn default_transport_builds_client() {
        DefaultTransport
            .build_client()
            .expect("DefaultTransport::build_client must succeed");
    }

    /// bd:JMAP-6r7c.36 — `TransportConfig::build_client` now returns
    /// `Result<HttpClient, _>`, not `Result<reqwest::Client, _>`. The
    /// wrapper exists so the trait's public signature does not name the
    /// underlying HTTP library, insulating extension clients and custom
    /// transport impls from a future transport swap.
    ///
    /// The compile-time witness below pins the new shape; if a future
    /// refactor accidentally widens the return type back to
    /// `reqwest::Client`, the explicit typed `let` binding here breaks
    /// the build.
    #[tokio::test]
    async fn build_client_returns_opaque_http_client() {
        let result: Result<HttpClient, ClientError> = DefaultTransport.build_client();
        let http = result.expect("DefaultTransport::build_client must succeed");
        // Debug output is opaque — no inner reqwest::Client representation.
        let dbg = format!("{http:?}");
        assert_eq!(
            dbg, "HttpClient",
            "HttpClient Debug must be opaque; the wrapper is the only public surface"
        );
    }

    /// bd:JMAP-6r7c.36 — A custom `TransportConfig` impl constructs the
    /// returned `HttpClient` via `HttpClient::new(reqwest::Client)`. This
    /// pins the public construction path; if the constructor signature
    /// changes, the custom-impl pattern below fails to compile and
    /// downstream consumers will pick up the same migration signal at
    /// build time.
    #[test]
    fn http_client_new_is_callable_from_custom_transport_impl() {
        struct StubTransport;
        impl TransportConfig for StubTransport {
            fn build_client(&self) -> Result<HttpClient, ClientError> {
                let client = reqwest::ClientBuilder::new()
                    .build()
                    .map_err(ClientError::from_reqwest)?;
                Ok(HttpClient::new(client))
            }
        }

        StubTransport
            .build_client()
            .expect("custom transport must build the opaque HttpClient");
    }

    /// bd:JMAP-6r7c.62 — `AuthHeader`'s `Debug` impl MUST redact the value
    /// bytes to "[REDACTED]". This is the compile-time guard against a
    /// future `AuthProvider` impl that writes `tracing::trace!(?header,
    /// ...)`. The pre-bd:JMAP-6r7c.62 shape `Option<(&str, &str)>` would
    /// have rendered the value verbatim via `?`-formatter. The canary
    /// literal is the test's independent oracle, never derived from
    /// `AuthHeader`'s internal state.
    #[test]
    fn auth_header_debug_redacts_value() {
        const CANARY: &str = "CANARY-AUTH-VALUE-DO-NOT-LEAK-456";
        let header = AuthHeader::new("authorization", CANARY);
        let dbg = format!("{header:?}");
        assert!(
            !dbg.contains(CANARY),
            "AuthHeader Debug must not contain the canary value: {dbg}"
        );
        assert!(
            dbg.contains("[REDACTED]"),
            "AuthHeader Debug must render '[REDACTED]' for the value field: {dbg}"
        );
        // The name is non-sensitive and may surface to aid diagnostics.
        assert!(
            dbg.contains("authorization"),
            "AuthHeader Debug should include the header name for diagnostic value: {dbg}"
        );
    }

    /// bd:JMAP-6r7c.62 — `expose_value` is the only path to the credential
    /// bytes, so the call-site name (`expose_value`) is the visible
    /// signal in code review. This test pins the accessor name + return
    /// value, so a future rename of the accessor breaks the test loudly.
    #[test]
    fn auth_header_expose_value_returns_credential_bytes() {
        const VALUE: &str = "Bearer some-token-123";
        let header = AuthHeader::new("authorization", VALUE);
        assert_eq!(header.name(), "authorization");
        assert_eq!(header.expose_value(), VALUE);
    }

    /// Oracle: BearerAuth's Debug impl never reveals the underlying token.
    ///
    /// Tripwire against a future refactor that adds `#[derive(Debug)]` to
    /// BearerAuth (clearing the manual redacting impl), or that prints the
    /// inner `header_string`. The canary literal is the independent
    /// oracle — it is under the test's control, never derived from
    /// BearerAuth's internal state.
    #[test]
    fn bearer_auth_debug_does_not_leak_token() {
        const CANARY: &str = "CANARY-TOKEN-DO-NOT-LEAK-123";
        let auth = BearerAuth::new(CANARY).expect("valid ASCII token must construct");
        let dbg = format!("{auth:?}");
        assert!(
            !dbg.contains(CANARY),
            "BearerAuth Debug must not contain the raw token; got: {dbg}"
        );
    }

    /// Oracle: BasicAuth's Debug impl never reveals the underlying credentials.
    ///
    /// Same tripwire shape as `bearer_auth_debug_does_not_leak_token`.
    /// The canary username and password are independent literals; the
    /// assertion verifies neither, nor the base64 encoding of their
    /// concatenation, appears in the Debug output.
    #[test]
    fn basic_auth_debug_does_not_leak_credentials() {
        const CANARY_USER: &str = "CANARY-USER-DO-NOT-LEAK";
        const CANARY_PASS: &str = "CANARY-PASS-DO-NOT-LEAK";
        let auth =
            BasicAuth::new(CANARY_USER, CANARY_PASS).expect("valid credentials must construct");
        let dbg = format!("{auth:?}");
        assert!(
            !dbg.contains(CANARY_USER),
            "BasicAuth Debug must not contain the raw username; got: {dbg}"
        );
        assert!(
            !dbg.contains(CANARY_PASS),
            "BasicAuth Debug must not contain the raw password; got: {dbg}"
        );
        // Also catch a regression that prints the pre-validated header_string,
        // which would surface the base64-encoded credentials.
        let base64_pair = BASE64_STANDARD.encode(format!("{CANARY_USER}:{CANARY_PASS}"));
        assert!(
            !dbg.contains(&base64_pair),
            "BasicAuth Debug must not contain the base64-encoded credentials; got: {dbg}"
        );
    }

    /// Oracle: `CustomCaTransport`'s Debug impl never prints the raw DER
    /// certificate bytes (bd:JMAP-6r7c.13).
    ///
    /// CA DER bytes are not a credential, but they are deployment-identifying
    /// material — Subject DN, public key, signing algorithm, X.509
    /// extensions. Surfacing them in `tracing` output reveals which private-
    /// CA-using customer the client is configured for. The canary byte
    /// sequence is an unmistakable repeating literal `0xCA` 32 times — the
    /// test asserts neither the lower-hex nor the upper-hex nor the
    /// Rust-debug `[202, 202, ...]` rendering of those bytes appears in the
    /// Debug output. Same tripwire shape as the BearerAuth and BasicAuth
    /// tests above.
    #[test]
    fn custom_ca_transport_debug_does_not_leak_der_bytes() {
        // 32 copies of 0xCA — an unmistakable sentinel byte. No conformant
        // DER encoder produces a run like this, so any leakage path
        // surfaces it intact.
        let canary_der = vec![0xCA_u8; 32];
        let transport = CustomCaTransport::new(canary_der);
        let dbg = format!("{transport:?}");
        // Lowercase hex rendering of the canary.
        assert!(
            !dbg.contains("cacacacacacacacacacacacacacacacacacacacacacacacacacacacacacacaca"),
            "CustomCaTransport Debug must not contain lowercase-hex DER bytes; got: {dbg}"
        );
        // Uppercase hex rendering — in case a future fmt::Debug uses {:X}.
        assert!(
            !dbg.contains("CACACACACACACACACACACACACACACACACACACACACACACACACACACACACACACACA"),
            "CustomCaTransport Debug must not contain uppercase-hex DER bytes; got: {dbg}"
        );
        // Rust `[u8]` default Debug rendering — `[202, 202, ...]`. A
        // derive(Debug) regression on the field would emit this shape.
        assert!(
            !dbg.contains("202, 202, 202"),
            "CustomCaTransport Debug must not contain decimal-byte DER bytes; got: {dbg}"
        );
        // Positive assertion: the redacted form mentions the length, so a
        // reader of `tracing` output still knows the field is non-empty.
        assert!(
            dbg.contains("32 bytes"),
            "CustomCaTransport Debug should record the DER byte length; got: {dbg}"
        );
    }

    // bd:JMAP-6r7c.37 — PEM constructor tests.
    //
    // Oracle: a hand-generated self-signed certificate produced by
    // `openssl req -x509 -newkey rsa:2048 -nodes -days 36500
    // -subj "/CN=JMAP-6r7c.37 test CA"`. The PEM and DER forms of the
    // same certificate are committed under tests/fixtures/tls/. The PEM
    // → DER conversion ran via `openssl x509 -outform DER`. Both files
    // are oracles independent of the code under test: the PEM was not
    // produced by `parse_first_pem_cert` and the DER was not produced
    // by reqwest. The test asserts the round-trip matches OpenSSL's
    // canonical bytes.
    const TEST_CA_PEM: &[u8] = include_bytes!("../tests/fixtures/tls/test-ca.pem");
    const TEST_CA_DER: &[u8] = include_bytes!("../tests/fixtures/tls/test-ca.der");

    #[test]
    fn from_pem_bytes_extracts_der_matching_openssl_oracle() {
        let transport = CustomCaTransport::from_pem_bytes(TEST_CA_PEM)
            .expect("test-ca.pem fixture must parse as a valid CA");
        assert_eq!(
            transport.der_cert.as_slice(),
            TEST_CA_DER,
            "PEM-decoded DER must match the openssl-produced reference DER fixture"
        );
    }

    #[test]
    fn from_pem_bytes_rejects_empty_input() {
        let err = CustomCaTransport::from_pem_bytes(b"").expect_err("empty input must be rejected");
        assert!(
            matches!(err, ClientError::InvalidArgument(_)),
            "empty input must surface as InvalidArgument; got {err:?}"
        );
    }

    #[test]
    fn from_pem_bytes_rejects_input_with_no_pem_framing() {
        let err = CustomCaTransport::from_pem_bytes(b"this is not a PEM file")
            .expect_err("non-PEM input must be rejected");
        assert!(
            matches!(err, ClientError::InvalidArgument(_)),
            "non-PEM input must surface as InvalidArgument; got {err:?}"
        );
    }

    #[test]
    fn from_pem_bytes_rejects_pem_with_invalid_base64() {
        // PEM framing with junk inside — should fail base64 decode.
        let bad =
            b"-----BEGIN CERTIFICATE-----\nNOT VALID BASE64 @#$%\n-----END CERTIFICATE-----\n";
        let err =
            CustomCaTransport::from_pem_bytes(bad).expect_err("invalid base64 must be rejected");
        assert!(
            matches!(err, ClientError::InvalidArgument(_)),
            "invalid-base64 PEM must surface as InvalidArgument; got {err:?}"
        );
    }

    #[test]
    fn from_pem_bytes_accepts_garbage_der_payload_deferring_validation_to_build() {
        use base64::Engine as _;
        // Properly-PEM-framed garbage bytes: PEM framing is correct,
        // base64 decodes OK, but the inner bytes are not a DER
        // certificate. By design (matching CustomCaTransport::new's
        // contract), from_pem_bytes accepts these bytes — DER validity
        // is checked at build_client() time, where it surfaces as
        // ClientError::Http through reqwest. This test documents that
        // contract.
        let garbage_der = [0u8; 16];
        let body = base64::engine::general_purpose::STANDARD.encode(garbage_der);
        let pem = format!("-----BEGIN CERTIFICATE-----\n{body}\n-----END CERTIFICATE-----\n");
        let transport = CustomCaTransport::from_pem_bytes(pem.as_bytes())
            .expect("PEM framing OK + base64 OK = constructor accepts");
        assert_eq!(
            transport.der_cert.as_slice(),
            &garbage_der,
            "PEM helper must extract the exact base64-decoded bytes"
        );
        // build_client() is where rustls/native-tls actually parses the
        // DER and would reject the garbage. Exercising that here would
        // require constructing a real ClientBuilder, which is covered
        // by the broader test suite's integration tests.
    }

    // Note: a dyn-AuthProvider Debug test (bead JMAP-sc1b.79 item #4) is
    // intentionally omitted. The AuthProvider trait does not have
    // `std::fmt::Debug` as a supertrait, so `Box<dyn AuthProvider>` is
    // not `Debug`-formattable. Adding `Debug` to the trait bound would
    // be a foundation-crate public API change far outside the scope of
    // a regression-test bead. The concrete-type tests above already
    // catch the hygiene contract for every shipped AuthProvider
    // implementation; the only way a new AuthProvider leaks credentials
    // via Debug is if its own concrete impl does so, and that is
    // caught by the new-impl reviewer (cookie-cutter rule).
}