synta-certificate 0.2.2

X.509 certificate structures for synta ASN.1 library
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
//! X.509 Distinguished Name formatting and building.
//!
//! Provides [`format_dn`], a fast RFC 4514-style formatter that walks the DER
//! bytes of a Name SEQUENCE directly — without building a `SequenceOf<Element>`
//! tree or going through Rust's generic `Debug` formatting machinery.
//!
//! Also provides [`NameBuilder`], a fluent builder for constructing DER-encoded
//! X.509 Names programmatically from OID + string attribute pairs.
//!
//! OID-to-label mapping is driven by the [`crate::oids::attr`] constants, which
//! are generated from the ASN.1 schema and cover the standard X.500 attribute
//! types plus PKCS #9 emailAddress and the LDAP uid/domainComponent OIDs.

use synta::der::decoder::Decoder;
use synta::types::oid::ObjectIdentifier;
use synta::{Decode, Encoding};

/// Walk a DER-encoded X.509 Name SEQUENCE and return `(dotted_oid, value_str)` pairs.
///
/// Input: the **complete TLV** bytes of the Name SEQUENCE (tag + length + value),
/// as returned by `RawDer::as_bytes()`.
///
/// Output: `vec![("2.5.4.3", "example.com"), ("2.5.4.6", "US"), ...]`
///
/// String values are decoded using the same per-tag rules as [`format_dn`]:
/// direct UTF-8 for most types, Latin-1 for TeletexString, and UCS-2/UCS-4
/// for BMPString/UniversalString.  Values with unknown tag numbers are returned
/// as hex strings prefixed with `#`.  Returns an empty `Vec` on parse error.
///
/// # Example
///
/// ```
/// use synta_certificate::parse_name_attrs;
///
/// // DER for: Name { SET { SEQUENCE { OID 2.5.4.3 (CN), UTF8String "A" } } }
/// let der: &[u8] = &[
///     0x30, 0x0C,                         // SEQUENCE (Name)
///       0x31, 0x0A,                       // SET (RDN)
///         0x30, 0x08,                     // SEQUENCE (ATV)
///           0x06, 0x03, 0x55, 0x04, 0x03, // OID 2.5.4.3 (commonName)
///           0x0C, 0x01, 0x41,             // UTF8String "A"
/// ];
/// let attrs = parse_name_attrs(der);
/// assert_eq!(attrs.len(), 1);
/// assert_eq!(attrs[0].0, "2.5.4.3");
/// assert_eq!(attrs[0].1, "A");
/// ```
pub fn parse_name_attrs(raw: &[u8]) -> Vec<(String, String)> {
    parse_name_attrs_inner(raw).unwrap_or_default()
}

fn parse_name_attrs_inner(raw: &[u8]) -> Option<Vec<(String, String)>> {
    let mut dec = Decoder::new(raw, Encoding::Der);

    // Consume the outer SEQUENCE tag + length to get the Name content bytes.
    dec.read_tag().ok()?;
    let len = dec.read_length().ok()?.definite().ok()?;
    let content = dec.read_bytes(len).ok()?;

    let mut result = Vec::new();
    let mut rdn_dec = Decoder::new(content, Encoding::Der);

    while !rdn_dec.is_empty() {
        // Each element is a SET (RelativeDistinguishedName).
        rdn_dec.read_tag().ok()?;
        let set_len = rdn_dec.read_length().ok()?.definite().ok()?;
        let set_content = rdn_dec.read_bytes(set_len).ok()?;

        // Walk the AttributeTypeAndValue SEQUENCEs inside the SET.
        let mut atv_dec = Decoder::new(set_content, Encoding::Der);
        while !atv_dec.is_empty() {
            // Each element is a SEQUENCE (AttributeTypeAndValue).
            atv_dec.read_tag().ok()?;
            let seq_len = atv_dec.read_length().ok()?.definite().ok()?;
            let seq_content = atv_dec.read_bytes(seq_len).ok()?;

            let mut field_dec = Decoder::new(seq_content, Encoding::Der);

            // Decode the attribute type OID.
            let oid = ObjectIdentifier::decode(&mut field_dec).ok()?;
            let oid_str = oid.to_string();

            // Read the attribute value: tag + length + raw bytes.
            let val_tag = field_dec.read_tag().ok()?;
            let val_len = field_dec.read_length().ok()?.definite().ok()?;
            let val_bytes = field_dec.read_bytes(val_len).ok()?;

            let mut value = String::new();
            append_string_value(&mut value, val_tag.number(), val_bytes);

            result.push((oid_str, value));
        }
    }

    Some(result)
}

/// Format a DER-encoded X.509 Name as a compact comma-separated string.
///
/// Input: the **complete TLV** bytes of the Name SEQUENCE (tag + length + value),
/// as returned by `RawDer::as_bytes()`.
///
/// Output: `"CN=example.com, O=Example, C=US"` or similar.
///
/// # Performance
///
/// This is significantly faster than
/// `format!("{:?}", SequenceOf::<Element>::decode(...))` because it:
/// - Walks the DER bytes in a single pass
/// - Never builds a `SequenceOf` or `Element` tree
/// - Writes directly into a `String` without the generic Debug formatter
///
/// # Example
///
/// ```ignore
/// let dn_string = format_dn(cert.tbs_certificate.issuer.as_bytes());
/// assert!(dn_string.contains("CN="));
/// ```
pub fn format_dn(raw: &[u8]) -> String {
    format_dn_inner(raw, false).unwrap_or_else(|| "<invalid>".to_string())
}

/// Like [`format_dn`] but uses the openssl slash-prefix style used for
/// DirName values inside AKI/SAN: `/C=BM/O=Example Corp/CN=Root CA`.
pub fn format_dn_slash(raw: &[u8]) -> String {
    format_dn_inner(raw, true).unwrap_or_else(|| "<invalid>".to_string())
}

fn format_dn_inner(raw: &[u8], slash: bool) -> Option<String> {
    let mut dec = Decoder::new(raw, Encoding::Der);

    // Consume the outer SEQUENCE tag + length to get the Name content bytes.
    dec.read_tag().ok()?;
    let len = dec.read_length().ok()?.definite().ok()?;
    let content = dec.read_bytes(len).ok()?;

    let mut out = String::with_capacity(64);
    let mut rdn_dec = Decoder::new(content, Encoding::Der);

    while !rdn_dec.is_empty() {
        // Each element is a SET (RelativeDistinguishedName).
        rdn_dec.read_tag().ok()?;
        let set_len = rdn_dec.read_length().ok()?.definite().ok()?;
        let set_content = rdn_dec.read_bytes(set_len).ok()?;

        // Walk the AttributeTypeAndValue SEQUENCEs inside the SET.
        let mut atv_dec = Decoder::new(set_content, Encoding::Der);
        while !atv_dec.is_empty() {
            // Each element is a SEQUENCE (AttributeTypeAndValue).
            atv_dec.read_tag().ok()?;
            let seq_len = atv_dec.read_length().ok()?.definite().ok()?;
            let seq_content = atv_dec.read_bytes(seq_len).ok()?;

            let mut field_dec = Decoder::new(seq_content, Encoding::Der);

            // Decode the attribute type OID.
            let oid = ObjectIdentifier::decode(&mut field_dec).ok()?;

            // Read the attribute value: tag + length + raw bytes.
            let val_tag = field_dec.read_tag().ok()?;
            let val_len = field_dec.read_length().ok()?.definite().ok()?;
            let val_bytes = field_dec.read_bytes(val_len).ok()?;

            // Append "ATTR=value" to the output buffer.
            if slash {
                out.push('/');
            } else if !out.is_empty() {
                out.push_str(", ");
            }
            append_attr_name(&mut out, oid.components());
            out.push('=');
            append_string_value(&mut out, val_tag.number(), val_bytes);
        }
    }

    Some(out)
}

/// Append the RFC 4514 short name for well-known attribute OIDs,
/// or fall back to the dotted OID notation for unknown ones.
///
/// # Performance note
///
/// `&[u32]` constants used directly as match arms (e.g. `attr::COMMON_NAME`)
/// require runtime slice equality (length check + element comparison) for every
/// arm.  Instead, this function:
///
/// 1. Checks the common `[2, 5, 4]` X.500 prefix once via an explicit
///    4-element slice destructure.
/// 2. Dispatches on the sub-attribute arc as a plain `u32` integer, which the
///    compiler can lower to a jump table.
///
/// All numeric values are derived from the generated `oids::attr` constants via
/// const-indexing, so they stay in sync with the ASN.1 schema automatically.
#[inline]
fn append_attr_name(out: &mut String, comps: &[u32]) {
    use crate::oids::attr;

    // Common X.500 arc prefix [2, 5, 4], sourced from a generated constant.
    const ARC0: u32 = attr::COMMON_NAME[0];
    const ARC1: u32 = attr::COMMON_NAME[1];
    const ARC2: u32 = attr::COMMON_NAME[2];

    // Sub-attribute discriminants derived from generated constants.
    // These are u32 values, so the inner match compiles to a jump table.
    const CN: u32 = attr::COMMON_NAME[3];
    const SN: u32 = attr::SURNAME[3];
    const SERNO: u32 = attr::SERIAL_NUMBER[3];
    const CTRY: u32 = attr::COUNTRY[3];
    const LCL: u32 = attr::LOCALITY[3];
    const ST: u32 = attr::STATE[3];
    const STR: u32 = attr::STREET[3];
    const ORG: u32 = attr::ORGANIZATION[3];
    const OU: u32 = attr::ORG_UNIT[3];
    const TITL: u32 = attr::TITLE[3];
    const GN: u32 = attr::GIVEN_NAME[3];
    const INIT: u32 = attr::INITIALS[3];
    const OI: u32 = attr::ORG_IDENTIFIER[3];

    // Destructure into exactly 4 elements by value; this handles the X.500
    // family (length check + prefix check + sub-attribute dispatch).
    let name = if let &[a0, a1, a2, sub] = comps {
        if a0 == ARC0 && a1 == ARC1 && a2 == ARC2 {
            match sub {
                CN => "CN",
                SN => "SN",
                SERNO => "SERIALNUMBER",
                CTRY => "C",
                LCL => "L",
                ST => "ST",
                STR => "STREET",
                ORG => "O",
                OU => "OU",
                TITL => "T",
                GN => "GN",
                INIT => "I",
                OI => "OI",
                _ => "",
            }
        } else {
            ""
        }
    } else if comps == attr::EMAIL_ADDRESS {
        // PKCS#9 emailAddress (1.2.840.113549.1.9.1) — 7 arcs, rare in DNs.
        "emailAddress"
    } else if comps == attr::USER_ID {
        // LDAP uid/userId (0.9.2342.19200300.100.1.1)
        "UID"
    } else if comps == attr::DOMAIN_COMPONENT {
        // domainComponent (0.9.2342.19200300.100.1.25)
        "DC"
    } else {
        ""
    };

    if !name.is_empty() {
        out.push_str(name);
    } else {
        // Fallback: write OID in dotted decimal notation directly into `out`.
        use core::fmt::Write;
        for (i, c) in comps.iter().enumerate() {
            if i > 0 {
                out.push('.');
            }
            let _ = write!(out, "{}", c);
        }
    }
}

/// Decode raw ASN.1 string value bytes for a given universal tag number into a `String`.
///
/// This is the Rust counterpart to `Decoder.decode_any_str()` in the Python binding.
/// It accepts the **value bytes only** (the content after the tag and length have been
/// stripped) together with the tag number, and applies the appropriate per-type encoding:
///
/// | Tag | Type | Encoding |
/// |-----|------|----------|
/// | 12 | UTF8String | UTF-8 (lossy) |
/// | 18 | NumericString | UTF-8 (lossy) |
/// | 19 | PrintableString | UTF-8 (lossy) |
/// | 20 | TeletexString / T61String | Latin-1 (each byte → U+00xx) |
/// | 22 | IA5String | UTF-8 (lossy) |
/// | 26 | VisibleString | UTF-8 (lossy) |
/// | 27 | GeneralString | UTF-8 (lossy) |
/// | 28 | UniversalString | UCS-4 big-endian |
/// | 30 | BMPString | UCS-2 big-endian |
///
/// Any other tag number produces a hex-encoded string prefixed with `#`
/// (consistent with the [`format_dn`] fallback for unknown attribute value types).
///
/// # Example
///
/// ```
/// use synta_certificate::decode_string_value;
///
/// // UTF8String (tag 12) — bytes are valid UTF-8
/// assert_eq!(decode_string_value(12, b"Hello"), "Hello");
///
/// // TeletexString (tag 20) — each byte is a Latin-1 code point
/// assert_eq!(decode_string_value(20, &[0xE9]), "\u{00E9}"); // é
///
/// // Unknown tag — hex fallback with '#' prefix
/// assert_eq!(decode_string_value(99, &[0xAB, 0xCD]), "#abcd");
/// ```
pub fn decode_string_value(tag_number: u32, bytes: &[u8]) -> String {
    let mut out = String::new();
    append_string_value(&mut out, tag_number, bytes);
    out
}

/// Append the string content of an ASN.1 value to `out`.
///
/// Single-byte-per-character encodings (UTF-8, PrintableString, IA5String,
/// etc.) are appended directly. Multi-byte encodings (BMPString, UniversalString)
/// are decoded to Unicode codepoints first.
#[inline]
fn append_string_value(out: &mut String, tag_number: u32, bytes: &[u8]) {
    use synta::tag::*;

    match tag_number {
        // Direct UTF-8 compatible encodings — no conversion needed.
        TAG_UTF8_STRING | TAG_PRINTABLE_STRING | TAG_IA5_STRING | TAG_VISIBLE_STRING
        | TAG_NUMERIC_STRING | TAG_GENERAL_STRING => {
            out.push_str(&String::from_utf8_lossy(bytes));
        }

        // TeletexString / T61String: treat each byte as Latin-1 codepoint.
        TAG_TELETEX_STRING => {
            out.extend(bytes.iter().map(|&b| b as char));
        }

        // BMPString: UCS-2 big-endian (Basic Multilingual Plane only).
        TAG_BMP_STRING => {
            out.extend(
                bytes.chunks_exact(2).filter_map(|pair| {
                    char::from_u32(u16::from_be_bytes([pair[0], pair[1]]) as u32)
                }),
            );
        }

        // UniversalString: UCS-4 big-endian.
        TAG_UNIVERSAL_STRING => {
            out.extend(bytes.chunks_exact(4).filter_map(|quad| {
                char::from_u32(u32::from_be_bytes([quad[0], quad[1], quad[2], quad[3]]))
            }));
        }

        // Unknown or binary tag — show as hex.
        _ => {
            use core::fmt::Write;
            out.push('#');
            for b in bytes {
                let _ = write!(out, "{:02x}", b);
            }
        }
    }
}

// ── NameBuilder ───────────────────────────────────────────────────────────────

/// Fluent builder for DER-encoded X.509 `Name` SEQUENCE structures.
///
/// Constructs a `Name` by accumulating `RelativeDistinguishedName` (RDN) entries,
/// each containing one `AttributeTypeAndValue` (ATV) with a UTF8String value.
/// Call [`build`](NameBuilder::build) at the end to obtain the complete DER bytes.
///
/// The output is a complete DER Name TLV (`SEQUENCE { SET { SEQUENCE { OID, UTF8String } } … }`)
/// suitable for use with [`CertificateBuilder::issuer_name`] and
/// [`CertificateBuilder::subject_name`].
///
/// # Example
///
/// ```
/// use synta_certificate::{NameBuilder, oids};
///
/// // Build: CN=My Root CA
/// let name_der = NameBuilder::new()
///     .common_name("My Root CA")
///     .build()
///     .unwrap();
/// assert!(!name_der.is_empty());
///
/// // Build: C=US, O=Example Corp, CN=example.com
/// let name_der2 = NameBuilder::new()
///     .country("US")
///     .organization("Example Corp")
///     .common_name("example.com")
///     .build()
///     .unwrap();
/// assert!(!name_der2.is_empty());
///
/// // Use a custom OID via `add_attr`:
/// let name_der3 = NameBuilder::new()
///     .add_attr(oids::attr::COMMON_NAME, "custom.example")
///     .build()
///     .unwrap();
/// assert!(!name_der3.is_empty());
/// ```
///
/// [`CertificateBuilder::issuer_name`]: crate::CertificateBuilder::issuer_name
/// [`CertificateBuilder::subject_name`]: crate::CertificateBuilder::subject_name
pub struct NameBuilder {
    /// Accumulated RDN entries: (OID component slice, UTF-8 value string).
    attrs: Vec<(Vec<u32>, String)>,
}

impl Default for NameBuilder {
    fn default() -> Self {
        Self::new()
    }
}

impl NameBuilder {
    /// Create a new, empty `NameBuilder`.
    pub fn new() -> Self {
        Self { attrs: Vec::new() }
    }

    /// Add an attribute with the given OID component slice and UTF-8 string value.
    ///
    /// Use the constants in [`crate::oids::attr`] for well-known DN attribute types:
    ///
    /// ```
    /// use synta_certificate::{NameBuilder, oids};
    ///
    /// let name_der = NameBuilder::new()
    ///     .add_attr(oids::attr::ORGANIZATION, "Example Corp")
    ///     .add_attr(oids::attr::COMMON_NAME, "example.com")
    ///     .build()
    ///     .unwrap();
    /// assert!(!name_der.is_empty());
    /// ```
    pub fn add_attr(mut self, oid_comps: &[u32], value: &str) -> Self {
        self.attrs.push((oid_comps.to_vec(), value.to_string()));
        self
    }

    /// Add a `commonName` (2.5.4.3) attribute.
    pub fn common_name(self, value: &str) -> Self {
        self.add_attr(crate::oids::attr::COMMON_NAME, value)
    }

    /// Add an `organizationName` (2.5.4.10) attribute.
    pub fn organization(self, value: &str) -> Self {
        self.add_attr(crate::oids::attr::ORGANIZATION, value)
    }

    /// Add an `organizationalUnitName` (2.5.4.11) attribute.
    pub fn organizational_unit(self, value: &str) -> Self {
        self.add_attr(crate::oids::attr::ORG_UNIT, value)
    }

    /// Add a `countryName` (2.5.4.6) attribute.
    pub fn country(self, value: &str) -> Self {
        self.add_attr(crate::oids::attr::COUNTRY, value)
    }

    /// Add a `stateOrProvinceName` (2.5.4.8) attribute.
    pub fn state(self, value: &str) -> Self {
        self.add_attr(crate::oids::attr::STATE, value)
    }

    /// Add a `localityName` (2.5.4.7) attribute.
    pub fn locality(self, value: &str) -> Self {
        self.add_attr(crate::oids::attr::LOCALITY, value)
    }

    /// Add a `streetAddress` (2.5.4.9) attribute.
    pub fn street(self, value: &str) -> Self {
        self.add_attr(crate::oids::attr::STREET, value)
    }

    /// Add an `emailAddress` (1.2.840.113549.1.9.1) attribute.
    pub fn email_address(self, value: &str) -> Self {
        self.add_attr(crate::oids::attr::EMAIL_ADDRESS, value)
    }

    /// Build the DER-encoded X.509 `Name` SEQUENCE.
    ///
    /// Returns the complete TLV bytes including the outer `SEQUENCE` tag and
    /// length.  Returns a DER-encoded empty `SEQUENCE` (`30 00`) if no
    /// attributes have been added.
    ///
    /// Returns `Err` if an OID arc is invalid or if DER encoding fails (which
    /// cannot happen for well-formed OID arcs and non-empty UTF-8 strings in
    /// practice, but the `Result` allows callers to propagate errors cleanly).
    pub fn build(&self) -> Result<Vec<u8>, String> {
        use synta::types::oid::ObjectIdentifier;
        use synta::types::string::Utf8StringRef;
        use synta::{Encoder, Encoding};

        // Encode a DER TLV from a tag byte and content slice.
        // Supports short-form (≤ 127 bytes), 1-byte long-form (128–255 bytes),
        // and 2-byte long-form (256–65535 bytes).  Returns Err for larger content.
        fn encode_tlv(tag: u8, content: &[u8]) -> Result<Vec<u8>, String> {
            let len = content.len();
            if len > 0xFFFF {
                return Err(format!("TLV content too large: {len} bytes (max 65535)"));
            }
            let mut buf = Vec::with_capacity(content.len() + 4);
            buf.push(tag);
            if len <= 0x7F {
                buf.push(len as u8);
            } else if len <= 0xFF {
                buf.push(0x81);
                buf.push(len as u8);
            } else {
                // Long-form 2-byte: 0x82 <high> <low>  (handles 256–65535)
                buf.push(0x82);
                buf.push((len >> 8) as u8);
                buf.push((len & 0xFF) as u8);
            }
            buf.extend_from_slice(content);
            Ok(buf)
        }

        let mut name_content: Vec<u8> = Vec::new();

        for (oid_comps, value) in &self.attrs {
            // Encode the attribute type OID.
            let oid = ObjectIdentifier::new(oid_comps)
                .map_err(|e| format!("NameBuilder: invalid OID component slice: {e:?}"))?;
            let mut oid_enc = Encoder::new(Encoding::Der);
            oid_enc
                .encode(&oid)
                .map_err(|e| format!("NameBuilder: failed to encode OID: {e:?}"))?;
            let oid_bytes = oid_enc
                .finish()
                .map_err(|e| format!("NameBuilder: failed to finish OID encoder: {e:?}"))?;

            // Encode the value as UTF8String.
            let val = Utf8StringRef::new(value);
            let mut val_enc = Encoder::new(Encoding::Der);
            val_enc
                .encode(&val)
                .map_err(|e| format!("NameBuilder: failed to encode value: {e:?}"))?;
            let val_bytes = val_enc
                .finish()
                .map_err(|e| format!("NameBuilder: failed to finish value encoder: {e:?}"))?;

            // ATV SEQUENCE { OID, UTF8String }
            let mut atv_content: Vec<u8> = Vec::with_capacity(oid_bytes.len() + val_bytes.len());
            atv_content.extend_from_slice(&oid_bytes);
            atv_content.extend_from_slice(&val_bytes);
            let atv_buf = encode_tlv(0x30, &atv_content)?;

            // RDN SET { ATV }
            let rdn_buf = encode_tlv(0x31, &atv_buf)?;

            name_content.extend_from_slice(&rdn_buf);
        }

        // Wrap all RDNs in the outer Name SEQUENCE.
        encode_tlv(0x30, &name_content)
    }
}

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

    /// Build the raw DER bytes for a Name SEQUENCE containing one RDN with
    /// the given OID and UTF-8 value.  Used to construct minimal test vectors
    /// without depending on external certificate files.
    fn build_name_der(oid_comps: &[u32], value: &str) -> Vec<u8> {
        use synta::types::oid::ObjectIdentifier;
        use synta::types::string::Utf8StringRef;
        use synta::{Encoder, Encoding};

        // Encode OID
        let oid = ObjectIdentifier::new(oid_comps).unwrap();
        let mut oid_enc = Encoder::new(Encoding::Der);
        oid_enc.encode(&oid).unwrap();
        let oid_bytes = oid_enc.finish().unwrap();

        // Encode value as UTF-8 string
        let val = Utf8StringRef::new(value);
        let mut val_enc = Encoder::new(Encoding::Der);
        val_enc.encode(&val).unwrap();
        let val_bytes = val_enc.finish().unwrap();

        // ATV SEQUENCE = OID + value
        let atv_content: Vec<u8> = [oid_bytes.as_slice(), val_bytes.as_slice()].concat();
        assert!(
            atv_content.len() <= 127,
            "test helper: ATV content too long for short-form DER length"
        );
        let mut atv_buf = vec![0x30u8, atv_content.len() as u8];
        atv_buf.extend_from_slice(&atv_content);

        // RDN SET = ATV
        assert!(
            atv_buf.len() <= 127,
            "test helper: RDN content too long for short-form DER length"
        );
        let mut rdn_buf = vec![0x31u8, atv_buf.len() as u8];
        rdn_buf.extend_from_slice(&atv_buf);

        // Name SEQUENCE = RDN
        assert!(
            rdn_buf.len() <= 127,
            "test helper: Name content too long for short-form DER length"
        );
        let mut name_buf = vec![0x30u8, rdn_buf.len() as u8];
        name_buf.extend_from_slice(&rdn_buf);

        name_buf
    }

    #[test]
    fn test_format_dn_cn() {
        let der = build_name_der(&[2, 5, 4, 3], "example.com");
        let result = format_dn(&der);
        assert_eq!(result, "CN=example.com");
    }

    #[test]
    fn test_format_dn_country() {
        let der = build_name_der(&[2, 5, 4, 6], "US");
        let result = format_dn(&der);
        assert_eq!(result, "C=US");
    }

    #[test]
    fn test_format_dn_invalid() {
        let result = format_dn(&[0x00, 0x01, 0x02]);
        assert_eq!(result, "<invalid>");
    }

    #[test]
    fn test_format_dn_empty_sequence() {
        // SEQUENCE with zero content
        let der = vec![0x30u8, 0x00];
        let result = format_dn(&der);
        assert_eq!(result, "");
    }
}