pkix-path 0.4.9

RFC 5280 X.509 certificate path validation — pure Rust, no_std
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
//! Helper functions for serde-serializing DER-encodable types in a
//! format-adaptive wire form.
//!
//! # Wire form
//!
//! Human-readable serializers (JSON, TOML, YAML) receive a **base64**
//! string of the type's DER encoding. Binary serializers (postcard,
//! bincode, MessagePack, CBOR-without-readability-hint) receive the **raw
//! DER bytes**. The selection is driven by
//! [`serde::Serializer::is_human_readable`] /
//! [`serde::Deserializer::is_human_readable`].
//!
//! # Round-trip
//!
//! DER is a canonical encoding for the types this helper is used on
//! (`x509_cert::name::Name`, `x509_cert::serial_number::SerialNumber`,
//! `spki::SubjectPublicKeyInfoOwned`,
//! `x509_cert::ext::pkix::certpolicy::PolicyQualifierInfo`,
//! `der::asn1::ObjectIdentifier`, …). Serialize-then-deserialize produces
//! a value whose DER re-encoding is byte-identical to the original.
//!
//! # Usage
//!
//! ```ignore
//! #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
//! struct Anchor {
//!     #[cfg_attr(
//!         feature = "serde",
//!         serde(with = "crate::serde_der")
//!     )]
//!     subject: x509_cert::name::Name,
//! }
//! ```
//!
//! For `Option<T>` fields, use [`crate::serde_der::option`]. For
//! `Vec<T>` fields, use [`crate::serde_der::vec`].
//!
//! # Why not `serde_with`?
//!
//! [`serde_with`](https://docs.rs/serde_with) would express these helpers more concisely via
//! `#[serde_as(as = "DerBase64")]`. We avoid the dependency because the
//! workspace MSRV is 1.87 and the latest `serde_with` 3.x releases
//! (3.18+) require rustc 1.88. Pinning to 3.12 was a viable alternative,
//! but a small hand-written helper module is simpler and keeps the
//! dependency footprint smaller.

#[cfg(not(feature = "std"))]
use alloc::{string::String, vec::Vec};

use base64ct::{Base64, Encoding};
use der::{Decode, Encode};
use serde::{Deserialize, Deserializer, Serialize, Serializer};

/// Serialize a single DER-encodable value.
///
/// Emits a base64 string in human-readable serializers and raw bytes in
/// binary serializers.
///
/// # Errors
///
/// Returns the serializer's error if the underlying serializer fails or
/// if DER encoding of `value` fails.
pub fn serialize<S, T>(value: &T, serializer: S) -> Result<S::Ok, S::Error>
where
    S: Serializer,
    T: Encode,
{
    let der_bytes = value.to_der().map_err(serde::ser::Error::custom)?;
    if serializer.is_human_readable() {
        let encoded = Base64::encode_string(&der_bytes);
        serializer.serialize_str(&encoded)
    } else {
        serializer.serialize_bytes(&der_bytes)
    }
}

/// Deserialize a single DER-encodable value.
///
/// Accepts a base64 string from human-readable deserializers and raw
/// bytes from binary deserializers.
///
/// # Errors
///
/// Returns the deserializer's error if the underlying deserializer
/// fails, if base64 decoding fails (human-readable mode), or if DER
/// decoding of the recovered bytes fails.
pub fn deserialize<'de, D, T>(deserializer: D) -> Result<T, D::Error>
where
    D: Deserializer<'de>,
    T: for<'a> Decode<'a>,
{
    let der_bytes = if deserializer.is_human_readable() {
        let s = String::deserialize(deserializer)?;
        Base64::decode_vec(&s).map_err(serde::de::Error::custom)?
    } else {
        Vec::<u8>::deserialize(deserializer)?
    };
    T::from_der(&der_bytes).map_err(serde::de::Error::custom)
}

/// Serde helper for `Option<T>` fields where `T` is DER-encodable.
///
/// Use as `#[serde(with = "crate::serde_der::option")]` on the field.
pub mod option {
    use super::{Base64, Decode, Deserialize, Deserializer, Encode, Encoding, Serializer};
    #[cfg(not(feature = "std"))]
    use alloc::{string::String, vec::Vec};

    /// Serialize an optional DER-encodable value.
    ///
    /// `None` serializes as `null` / unit; `Some(value)` serializes as
    /// `value` per the top-level format rule.
    ///
    /// # Errors
    ///
    /// Returns the serializer's error if the underlying serializer fails
    /// or if DER encoding fails.
    pub fn serialize<S, T>(value: &Option<T>, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
        T: Encode,
    {
        match value {
            Some(v) => {
                let der_bytes = v.to_der().map_err(serde::ser::Error::custom)?;
                if serializer.is_human_readable() {
                    let encoded = Base64::encode_string(&der_bytes);
                    serializer.serialize_some(&encoded)
                } else {
                    serializer.serialize_some(&der_bytes)
                }
            }
            None => serializer.serialize_none(),
        }
    }

    /// Deserialize an optional DER-encodable value.
    ///
    /// # Errors
    ///
    /// Returns the deserializer's error if the underlying deserializer
    /// fails, if base64 decoding fails, or if DER decoding fails.
    pub fn deserialize<'de, D, T>(deserializer: D) -> Result<Option<T>, D::Error>
    where
        D: Deserializer<'de>,
        T: for<'a> Decode<'a>,
    {
        if deserializer.is_human_readable() {
            let opt = Option::<String>::deserialize(deserializer)?;
            match opt {
                Some(s) => {
                    let der_bytes = Base64::decode_vec(&s).map_err(serde::de::Error::custom)?;
                    let v = T::from_der(&der_bytes).map_err(serde::de::Error::custom)?;
                    Ok(Some(v))
                }
                None => Ok(None),
            }
        } else {
            let opt = Option::<Vec<u8>>::deserialize(deserializer)?;
            match opt {
                Some(bytes) => {
                    let v = T::from_der(&bytes).map_err(serde::de::Error::custom)?;
                    Ok(Some(v))
                }
                None => Ok(None),
            }
        }
    }
}

/// Serde helper for `Vec<T>` fields where `T` is DER-encodable.
///
/// Use as `#[serde(with = "crate::serde_der::vec")]` on the field. Each
/// element is encoded independently per the top-level format rule.
pub mod vec {
    use super::{Base64, Decode, Deserialize, Deserializer, Encode, Encoding, Serializer};
    #[cfg(not(feature = "std"))]
    use alloc::{string::String, vec::Vec};
    use serde::ser::SerializeSeq;

    /// Serialize a `Vec` of DER-encodable values as a sequence.
    ///
    /// # Errors
    ///
    /// Returns the serializer's error if the underlying serializer fails
    /// or if DER encoding of any element fails.
    pub fn serialize<S, T>(values: &[T], serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
        T: Encode,
    {
        let is_hr = serializer.is_human_readable();
        let mut seq = serializer.serialize_seq(Some(values.len()))?;
        for v in values {
            let der_bytes = v.to_der().map_err(serde::ser::Error::custom)?;
            if is_hr {
                let encoded = Base64::encode_string(&der_bytes);
                seq.serialize_element(&encoded)?;
            } else {
                seq.serialize_element(der_bytes.as_slice())?;
            }
        }
        seq.end()
    }

    /// Deserialize a `Vec` of DER-encodable values from a sequence.
    ///
    /// # Errors
    ///
    /// Returns the deserializer's error if the underlying deserializer
    /// fails, if base64 decoding fails, or if DER decoding of any
    /// element fails.
    pub fn deserialize<'de, D, T>(deserializer: D) -> Result<Vec<T>, D::Error>
    where
        D: Deserializer<'de>,
        T: for<'a> Decode<'a>,
    {
        if deserializer.is_human_readable() {
            let strs = Vec::<String>::deserialize(deserializer)?;
            let mut out = Vec::with_capacity(strs.len());
            for s in strs {
                let der_bytes = Base64::decode_vec(&s).map_err(serde::de::Error::custom)?;
                let v = T::from_der(&der_bytes).map_err(serde::de::Error::custom)?;
                out.push(v);
            }
            Ok(out)
        } else {
            let byte_vecs = Vec::<Vec<u8>>::deserialize(deserializer)?;
            let mut out = Vec::with_capacity(byte_vecs.len());
            for bytes in byte_vecs {
                let v = T::from_der(&bytes).map_err(serde::de::Error::custom)?;
                out.push(v);
            }
            Ok(out)
        }
    }
}

/// Serde helper for `Option<Vec<T>>` fields where `T` is DER-encodable.
///
/// Use as `#[serde(with = "crate::serde_der::option_vec")]` on the
/// field. `None` serializes as `null` / unit; `Some(vec)` serializes as
/// a sequence per [`mod@crate::serde_der::vec`].
pub mod option_vec {
    use super::{
        Base64, Decode, Deserialize, Deserializer, Encode, Encoding, Serialize, Serializer,
    };
    #[cfg(not(feature = "std"))]
    use alloc::{string::String, vec::Vec};
    use serde::ser::SerializeSeq;

    /// Serialize an optional `Vec` of DER-encodable values.
    ///
    /// # Errors
    ///
    /// Returns the serializer's error if the underlying serializer fails
    /// or if DER encoding fails.
    pub fn serialize<S, T>(value: &Option<Vec<T>>, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
        T: Encode,
    {
        match value {
            Some(values) => {
                if serializer.is_human_readable() {
                    let mut str_buf: Vec<String> = Vec::with_capacity(values.len());
                    for v in values {
                        let der_bytes = v.to_der().map_err(serde::ser::Error::custom)?;
                        str_buf.push(Base64::encode_string(&der_bytes));
                    }
                    serializer.serialize_some(&str_buf)
                } else {
                    let mut bytes_buf: Vec<Vec<u8>> = Vec::with_capacity(values.len());
                    for v in values {
                        let der_bytes = v.to_der().map_err(serde::ser::Error::custom)?;
                        bytes_buf.push(der_bytes);
                    }
                    // Serialize the outer Some(Vec<Vec<u8>>) via a custom
                    // wrapper so each element is emitted as a byte string
                    // rather than a generic sequence-of-u8.
                    struct Bytes<'a>(&'a [Vec<u8>]);
                    impl<'a> Serialize for Bytes<'a> {
                        fn serialize<S2: Serializer>(&self, s: S2) -> Result<S2::Ok, S2::Error> {
                            let mut seq = s.serialize_seq(Some(self.0.len()))?;
                            for b in self.0 {
                                seq.serialize_element(b.as_slice())?;
                            }
                            seq.end()
                        }
                    }
                    serializer.serialize_some(&Bytes(&bytes_buf))
                }
            }
            None => serializer.serialize_none(),
        }
    }

    /// Deserialize an optional `Vec` of DER-encodable values.
    ///
    /// # Errors
    ///
    /// Returns the deserializer's error if the underlying deserializer
    /// fails, if base64 decoding fails, or if DER decoding fails.
    pub fn deserialize<'de, D, T>(deserializer: D) -> Result<Option<Vec<T>>, D::Error>
    where
        D: Deserializer<'de>,
        T: for<'a> Decode<'a>,
    {
        if deserializer.is_human_readable() {
            let opt = Option::<Vec<String>>::deserialize(deserializer)?;
            match opt {
                Some(strs) => {
                    let mut out = Vec::with_capacity(strs.len());
                    for s in strs {
                        let der_bytes = Base64::decode_vec(&s).map_err(serde::de::Error::custom)?;
                        let v = T::from_der(&der_bytes).map_err(serde::de::Error::custom)?;
                        out.push(v);
                    }
                    Ok(Some(out))
                }
                None => Ok(None),
            }
        } else {
            let opt = Option::<Vec<Vec<u8>>>::deserialize(deserializer)?;
            match opt {
                Some(byte_vecs) => {
                    let mut out = Vec::with_capacity(byte_vecs.len());
                    for bytes in byte_vecs {
                        let v = T::from_der(&bytes).map_err(serde::de::Error::custom)?;
                        out.push(v);
                    }
                    Ok(Some(out))
                }
                None => Ok(None),
            }
        }
    }
}

#[cfg(test)]
mod tests {
    //! Unit tests for the DER serde helpers.
    //!
    //! These tests use the `der::asn1::ObjectIdentifier` type as the
    //! DER-encodable subject because it is small, has a stable encoding,
    //! and is independent of the path-validation code under test in the
    //! rest of `pkix-path`. The OID `1.2.840.10045.4.3.2`
    //! (`ecdsa-with-SHA256`) encodes to the DER bytes
    //! `06 08 2A 86 48 CE 3D 04 03 02` per the published ASN.1 encoding
    //! rules — this is the *external* oracle: a hand-computed expected
    //! encoding, not anything produced by this helper.

    use super::*;
    use der::asn1::ObjectIdentifier;

    const ECDSA_WITH_SHA256_OID: &str = "1.2.840.10045.4.3.2";
    // Hand-computed DER encoding of ECDSA_WITH_SHA256_OID. Tag 0x06 (OID),
    // length 0x08, then the OID body bytes per X.690 §8.19.
    const ECDSA_WITH_SHA256_DER: &[u8] =
        &[0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x04, 0x03, 0x02];
    // Standard base64 (RFC 4648 §4) of the DER bytes, with required
    // `=` padding for a 10-byte input. Padding is mandatory in the
    // standard alphabet that base64ct's `Base64` type emits and
    // requires on decode.
    const ECDSA_WITH_SHA256_BASE64: &str = "BggqhkjOPQQDAg==";

    // A second OID, so the sequence helpers can be tested with more than
    // one element and with the elements in a known order.
    // 2.16.840.1.101.3.4.2.1 is id-sha256. First two arcs 2 and 16 pack as
    // 2*40+16 = 0x60; then 840 as 0x86 0x48, then 1, 101, 3, 4, 2, 1 as
    // single bytes. Nine body bytes under tag 0x06.
    const SHA256_OID: &str = "2.16.840.1.101.3.4.2.1";
    const SHA256_DER: &[u8] = &[
        0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01,
    ];
    const SHA256_BASE64: &str = "BglghkgBZQMEAgE=";

    /// Serialize a known OID to JSON; assert the emitted JSON matches a
    /// hand-computed base64 string. JSON is the human-readable oracle.
    #[test]
    fn json_serialize_matches_hand_computed_base64() {
        #[derive(Serialize)]
        struct Wrapper {
            #[serde(serialize_with = "super::serialize")]
            oid: ObjectIdentifier,
        }
        let oid: ObjectIdentifier = ECDSA_WITH_SHA256_OID.parse().unwrap();
        let w = Wrapper { oid };
        let json = serde_json::to_string(&w).unwrap();
        let expected = format!(r#"{{"oid":"{}"}}"#, ECDSA_WITH_SHA256_BASE64);
        assert_eq!(json, expected);
    }

    /// Deserialize a hand-written JSON document; assert the recovered OID
    /// equals the known reference value.
    #[test]
    fn json_deserialize_matches_hand_constructed_value() {
        #[derive(Deserialize)]
        struct Wrapper {
            #[serde(deserialize_with = "super::deserialize")]
            oid: ObjectIdentifier,
        }
        let json = format!(r#"{{"oid":"{}"}}"#, ECDSA_WITH_SHA256_BASE64);
        let w: Wrapper = serde_json::from_str(&json).unwrap();
        let expected: ObjectIdentifier = ECDSA_WITH_SHA256_OID.parse().unwrap();
        assert_eq!(w.oid, expected);
    }

    /// Round-trip OID through JSON; the recovered OID must DER-encode to
    /// the same canonical bytes. This is the cache-key requirement from
    /// AGENTS.md non-negotiable #6.
    #[test]
    fn json_round_trip_preserves_der_canonical_form() {
        #[derive(Serialize, Deserialize)]
        struct Wrapper {
            #[serde(with = "super::super::serde_der")]
            oid: ObjectIdentifier,
        }
        let oid: ObjectIdentifier = ECDSA_WITH_SHA256_OID.parse().unwrap();
        let original_der = oid.to_der().unwrap();
        assert_eq!(original_der.as_slice(), ECDSA_WITH_SHA256_DER);

        let w = Wrapper { oid };
        let json = serde_json::to_string(&w).unwrap();
        let back: Wrapper = serde_json::from_str(&json).unwrap();
        let recovered_der = back.oid.to_der().unwrap();
        assert_eq!(recovered_der, original_der);
    }

    /// Serialize via a binary format (postcard-equivalent custom serializer
    /// that reports is_human_readable=false). The helper must emit raw
    /// DER bytes, NOT base64. Verified by asserting the serialized
    /// `Vec<u8>` payload contains the canonical DER bytes verbatim.
    #[test]
    fn binary_serializer_emits_raw_der_bytes_not_base64() {
        use serde::ser::Impossible;

        /// Minimal binary serializer that records the bytes written
        /// without any encoding transformation. Reports
        /// `is_human_readable() = false` so the helper takes the binary
        /// branch. Only implements the serializer surface the helper
        /// uses (`serialize_bytes`); everything else panics, which
        /// suffices for this targeted assertion.
        struct BytesCapture {
            captured: Vec<u8>,
        }
        impl Serializer for &mut BytesCapture {
            type Ok = ();
            type Error = serde::de::value::Error;
            type SerializeSeq = Impossible<(), Self::Error>;
            type SerializeTuple = Impossible<(), Self::Error>;
            type SerializeTupleStruct = Impossible<(), Self::Error>;
            type SerializeTupleVariant = Impossible<(), Self::Error>;
            type SerializeMap = Impossible<(), Self::Error>;
            type SerializeStruct = Impossible<(), Self::Error>;
            type SerializeStructVariant = Impossible<(), Self::Error>;

            fn is_human_readable(&self) -> bool {
                false
            }
            fn serialize_bytes(self, v: &[u8]) -> Result<(), Self::Error> {
                self.captured.extend_from_slice(v);
                Ok(())
            }
            fn serialize_bool(self, _: bool) -> Result<(), Self::Error> {
                unreachable!()
            }
            fn serialize_i8(self, _: i8) -> Result<(), Self::Error> {
                unreachable!()
            }
            fn serialize_i16(self, _: i16) -> Result<(), Self::Error> {
                unreachable!()
            }
            fn serialize_i32(self, _: i32) -> Result<(), Self::Error> {
                unreachable!()
            }
            fn serialize_i64(self, _: i64) -> Result<(), Self::Error> {
                unreachable!()
            }
            fn serialize_u8(self, _: u8) -> Result<(), Self::Error> {
                unreachable!()
            }
            fn serialize_u16(self, _: u16) -> Result<(), Self::Error> {
                unreachable!()
            }
            fn serialize_u32(self, _: u32) -> Result<(), Self::Error> {
                unreachable!()
            }
            fn serialize_u64(self, _: u64) -> Result<(), Self::Error> {
                unreachable!()
            }
            fn serialize_f32(self, _: f32) -> Result<(), Self::Error> {
                unreachable!()
            }
            fn serialize_f64(self, _: f64) -> Result<(), Self::Error> {
                unreachable!()
            }
            fn serialize_char(self, _: char) -> Result<(), Self::Error> {
                unreachable!()
            }
            fn serialize_str(self, _: &str) -> Result<(), Self::Error> {
                unreachable!()
            }
            fn serialize_none(self) -> Result<(), Self::Error> {
                unreachable!()
            }
            fn serialize_some<T: ?Sized + Serialize>(self, _: &T) -> Result<(), Self::Error> {
                unreachable!()
            }
            fn serialize_unit(self) -> Result<(), Self::Error> {
                unreachable!()
            }
            fn serialize_unit_struct(self, _: &'static str) -> Result<(), Self::Error> {
                unreachable!()
            }
            fn serialize_unit_variant(
                self,
                _: &'static str,
                _: u32,
                _: &'static str,
            ) -> Result<(), Self::Error> {
                unreachable!()
            }
            fn serialize_newtype_struct<T: ?Sized + Serialize>(
                self,
                _: &'static str,
                _: &T,
            ) -> Result<(), Self::Error> {
                unreachable!()
            }
            fn serialize_newtype_variant<T: ?Sized + Serialize>(
                self,
                _: &'static str,
                _: u32,
                _: &'static str,
                _: &T,
            ) -> Result<(), Self::Error> {
                unreachable!()
            }
            fn serialize_seq(self, _: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> {
                unreachable!()
            }
            fn serialize_tuple(self, _: usize) -> Result<Self::SerializeTuple, Self::Error> {
                unreachable!()
            }
            fn serialize_tuple_struct(
                self,
                _: &'static str,
                _: usize,
            ) -> Result<Self::SerializeTupleStruct, Self::Error> {
                unreachable!()
            }
            fn serialize_tuple_variant(
                self,
                _: &'static str,
                _: u32,
                _: &'static str,
                _: usize,
            ) -> Result<Self::SerializeTupleVariant, Self::Error> {
                unreachable!()
            }
            fn serialize_map(self, _: Option<usize>) -> Result<Self::SerializeMap, Self::Error> {
                unreachable!()
            }
            fn serialize_struct(
                self,
                _: &'static str,
                _: usize,
            ) -> Result<Self::SerializeStruct, Self::Error> {
                unreachable!()
            }
            fn serialize_struct_variant(
                self,
                _: &'static str,
                _: u32,
                _: &'static str,
                _: usize,
            ) -> Result<Self::SerializeStructVariant, Self::Error> {
                unreachable!()
            }
        }

        let oid: ObjectIdentifier = ECDSA_WITH_SHA256_OID.parse().unwrap();
        let mut cap = BytesCapture {
            captured: Vec::new(),
        };
        super::serialize(&oid, &mut cap).unwrap();
        assert_eq!(cap.captured, ECDSA_WITH_SHA256_DER);
    }

    // -----------------------------------------------------------------
    // option, vec and option_vec
    //
    // The four tests above drive the single-value helpers only. The three
    // submodules -- six more functions -- had nothing: their serializers
    // could have emitted the wrong shape and their deserializers could
    // have returned an empty collection, and no test would have noticed.
    //
    // JSON throughout, because that is the only serde format in this
    // crate's dev-dependencies. The binary branch of each helper is
    // exercised for the single-value form by
    // `binary_serializer_emits_raw_der_bytes_not_base64`; doing the same
    // for the sequence forms needs a hand-rolled Deserializer, which is
    // noted here rather than left as an apparent oversight.
    // -----------------------------------------------------------------

    fn oid1() -> ObjectIdentifier {
        ECDSA_WITH_SHA256_OID
            .parse()
            .expect("hand-written OID parses")
    }

    fn oid2() -> ObjectIdentifier {
        SHA256_OID.parse().expect("hand-written OID parses")
    }

    #[derive(Serialize, Deserialize, PartialEq, Debug)]
    struct OptWrapper {
        #[serde(with = "super::option")]
        oid: Option<ObjectIdentifier>,
    }

    #[derive(Serialize, Deserialize, PartialEq, Debug)]
    struct VecWrapper {
        #[serde(with = "super::vec")]
        oids: Vec<ObjectIdentifier>,
    }

    #[derive(Serialize, Deserialize, PartialEq, Debug)]
    struct OptVecWrapper {
        #[serde(with = "super::option_vec")]
        oids: Option<Vec<ObjectIdentifier>>,
    }

    /// `Some` carries the same base64 the single-value helper emits, and
    /// `None` is JSON null rather than an empty string or a missing field.
    #[test]
    fn option_wire_form_is_base64_or_null() {
        let some = serde_json::to_string(&OptWrapper { oid: Some(oid1()) }).expect("serialize");
        assert_eq!(some, format!(r#"{{"oid":"{ECDSA_WITH_SHA256_BASE64}"}}"#));

        let none = serde_json::to_string(&OptWrapper { oid: None }).expect("serialize");
        assert_eq!(none, r#"{"oid":null}"#);
    }

    #[test]
    fn option_round_trips_both_ways() {
        for value in [Some(oid1()), None] {
            let w = OptWrapper { oid: value };
            let json = serde_json::to_string(&w).expect("serialize");
            let back: OptWrapper = serde_json::from_str(&json).expect("deserialize");
            assert_eq!(w, back, "round trip changed {json}");
        }
    }

    /// A sequence is a JSON array of base64 strings, in order.
    ///
    /// Order is the part worth asserting: a helper that collected into a set
    /// or reversed the sequence would round-trip a one-element vector
    /// perfectly.
    /// The second OID's hand-written DER is the oracle for its base64, so
    /// the two constants check each other rather than both coming from the
    /// helper under test.
    #[test]
    fn the_second_oids_der_and_base64_agree() {
        let oid: ObjectIdentifier = SHA256_OID.parse().expect("hand-written OID parses");
        assert_eq!(
            oid.to_der().expect("an OID encodes").as_slice(),
            SHA256_DER,
            "the arc-by-arc encoding in the fixture table"
        );
        assert_eq!(Base64::encode_string(SHA256_DER), SHA256_BASE64);
    }

    #[test]
    fn vec_wire_form_is_an_ordered_array_of_base64() {
        let w = VecWrapper {
            oids: vec![oid1(), oid2()],
        };
        let json = serde_json::to_string(&w).expect("serialize");
        assert_eq!(
            json,
            format!(r#"{{"oids":["{ECDSA_WITH_SHA256_BASE64}","{SHA256_BASE64}"]}}"#)
        );

        let back: VecWrapper = serde_json::from_str(&json).expect("deserialize");
        assert_eq!(w, back);
        assert_eq!(
            back.oids.first().expect("two elements"),
            &oid1(),
            "the first element must still be first"
        );
    }

    /// An empty sequence is an empty array, not null and not absent.
    ///
    /// This is the case a deserializer returning `Vec::new()` for
    /// everything would also satisfy, so it is asserted alongside the
    /// populated one rather than instead of it.
    #[test]
    fn an_empty_vec_round_trips_as_an_empty_array() {
        let w = VecWrapper { oids: Vec::new() };
        let json = serde_json::to_string(&w).expect("serialize");
        assert_eq!(json, r#"{"oids":[]}"#);
        let back: VecWrapper = serde_json::from_str(&json).expect("deserialize");
        assert_eq!(w, back);
    }

    /// `option_vec` keeps all three states apart: absent, present-and-empty,
    /// present-and-populated.
    ///
    /// Collapsing `Some(vec![])` into `None` is the plausible mistake, and
    /// for a field like `policy_qualifiers` the two mean different things --
    /// no qualifiers were supplied, against a qualifier list that was
    /// supplied empty.
    #[test]
    fn option_vec_keeps_absent_and_empty_apart() {
        let cases = [
            (None, r#"{"oids":null}"#),
            (Some(Vec::new()), r#"{"oids":[]}"#),
            (Some(vec![oid2()]), r#"{"oids":["BglghkgBZQMEAgE="]}"#),
        ];
        for (value, expected) in cases {
            let w = OptVecWrapper { oids: value };
            let json = serde_json::to_string(&w).expect("serialize");
            assert_eq!(json, expected);
            let back: OptVecWrapper = serde_json::from_str(&json).expect("deserialize");
            assert_eq!(w, back, "round trip changed {json}");
        }
    }

    /// Malformed base64 and valid base64 that is not valid DER are both
    /// errors, in every helper.
    ///
    /// Each deserializer decodes then parses, and a helper that swallowed
    /// either failure would hand back a default value -- which for
    /// `Option` is `None` and for `Vec` is empty, both of which read as
    /// "nothing was there" rather than "the input was wrong".
    #[test]
    fn every_helper_refuses_garbage() {
        assert!(serde_json::from_str::<OptWrapper>(r#"{"oid":"not base64!"}"#).is_err());
        assert!(serde_json::from_str::<VecWrapper>(r#"{"oids":["not base64!"]}"#).is_err());
        assert!(serde_json::from_str::<OptVecWrapper>(r#"{"oids":["not base64!"]}"#).is_err());

        // "AAAA" is valid base64 for three zero bytes, which is not a DER
        // OBJECT IDENTIFIER.
        assert!(serde_json::from_str::<OptWrapper>(r#"{"oid":"AAAA"}"#).is_err());
        assert!(serde_json::from_str::<VecWrapper>(r#"{"oids":["AAAA"]}"#).is_err());
        assert!(serde_json::from_str::<OptVecWrapper>(r#"{"oids":["AAAA"]}"#).is_err());
    }
}