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
//! Fluent builder for DER-encoded TBSCertList (RFC 5280 §5).
//!
//! [`CertificateListBuilder`] assembles a `TBSCertList` DER blob that can be
//! handed to an external signer.  The outer `CertificateList` (TBS +
//! AlgorithmIdentifier + BIT STRING) is not produced here; callers splice those
//! three components together after signing.
//!
//! # Example
//!
//! ```rust,ignore
//! use synta_certificate::CertificateListBuilder;
//!
//! let tbs_der = CertificateListBuilder::new()
//!     .issuer(&name_der)
//!     .this_update("20240101120000Z")
//!     .next_update("20240201120000Z")
//!     .revoke(&serial_bytes, "20240101000000Z", Some(1))
//!     .build()
//!     .unwrap();
//! ```

use synta::tag::TAG_SEQUENCE;
use synta::{Boolean, Enumerated, Integer, ObjectIdentifier, OctetStringRef, RawDer, Tag, ToDer};

use crate::time_utils::parse_time;
use crate::{Extension, Time};

// ── RevokedEntry ──────────────────────────────────────────────────────────────

struct RevokedEntry {
    serial: Integer,
    revocation_date: Time,
    /// Pre-encoded `crlEntryExtensions` SEQUENCE OF for a single `reasonCode`,
    /// or empty if no reason was given.
    extensions_der: Vec<u8>,
}

impl RevokedEntry {
    /// Encode this `RevokedCertificate` SEQUENCE to DER.
    fn encode(&self) -> Result<Vec<u8>, String> {
        let mut enc = synta::Encoder::new(synta::Encoding::Der);
        enc.start_constructed_no_guard(Tag::universal_constructed(TAG_SEQUENCE))
            .map_err(|e| format!("RevokedCertificate encode error: {e}"))?;
        enc.encode(&self.serial)
            .map_err(|e| format!("serial encode error: {e}"))?;
        enc.encode(&self.revocation_date)
            .map_err(|e| format!("revocationDate encode error: {e}"))?;
        if !self.extensions_der.is_empty() {
            enc.write_bytes(&self.extensions_der);
        }
        enc.end_constructed()
            .map_err(|e| format!("RevokedCertificate end error: {e}"))?;
        enc.finish()
            .map_err(|e| format!("RevokedCertificate finish error: {e}"))
    }
}

// ── CertificateListBuilder ────────────────────────────────────────────────────

/// Fluent builder for a DER-encoded `TBSCertList` (RFC 5280 §5.1).
///
/// Produces the unsigned TBS DER blob suitable for external signing.  The
/// caller is responsible for wrapping the TBS with a signature algorithm
/// identifier and BIT STRING signature to form the outer `CertificateList`.
///
/// # RFC 5280 §5.1.2.1 — version
///
/// The builder always emits CRL v2 (`version INTEGER 1`) when CRL extensions
/// are present; otherwise the `version` field is omitted (v1 default).
///
/// # Example
///
/// ```rust,ignore
/// use synta_certificate::CertificateListBuilder;
///
/// let tbs_der = CertificateListBuilder::new()
///     .issuer(&name_der)
///     .this_update("20240101120000Z")
///     .next_update("20240201120000Z")
///     .revoke(&serial_bytes, "20240101000000Z", Some(1))
///     .build()
///     .unwrap();
/// ```
pub struct CertificateListBuilder {
    /// DER bytes of the issuer Name SEQUENCE.
    issuer: Option<Vec<u8>>,
    /// `thisUpdate` Time value.
    this_update: Option<Time>,
    /// `nextUpdate` Time value (optional per RFC 5280).
    next_update: Option<Time>,
    /// Accumulated revoked certificate entries.
    revoked: Vec<RevokedEntry>,
    /// CRL-level extensions: (OID, critical, extension-value DER bytes).
    crl_extensions: Vec<(ObjectIdentifier, bool, Vec<u8>)>,
    /// Pre-encoded signature AlgorithmIdentifier DER (for TBSCertList.signature).
    signature_algorithm_der: Option<Vec<u8>>,
    /// First error encountered; subsequent builder calls are no-ops.
    error: Option<String>,
}

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

impl CertificateListBuilder {
    /// Create a new, empty `CertificateListBuilder`.
    pub fn new() -> Self {
        Self {
            issuer: None,
            this_update: None,
            next_update: None,
            revoked: Vec::new(),
            crl_extensions: Vec::new(),
            signature_algorithm_der: None,
            error: None,
        }
    }

    // ── Fluent setters ─────────────────────────────────────────────────────────

    /// Set the issuer `Name` from a pre-encoded DER SEQUENCE TLV.
    ///
    /// Pass the bytes from `Certificate::subject_raw_der()` or the issuer
    /// field bytes of another `CertificateList` directly — no re-encoding
    /// is performed.
    pub fn issuer(mut self, name_der: &[u8]) -> Self {
        if self.error.is_none() {
            self.issuer = Some(name_der.to_vec());
        }
        self
    }

    /// Set the `thisUpdate` time.
    ///
    /// Accepts a time string in `YYYYMMDDHHmmssZ` (GeneralizedTime) or
    /// `YYMMDDHHmmssZ` (UTCTime) format.  UTC offset `Z` is mandatory.
    pub fn this_update(mut self, time: &str) -> Self {
        if self.error.is_none() {
            match parse_time(time) {
                Ok(t) => self.this_update = Some(t),
                Err(e) => self.error = Some(e),
            }
        }
        self
    }

    /// Set the optional `nextUpdate` time.
    ///
    /// Accepts the same format as [`this_update`](Self::this_update).
    pub fn next_update(mut self, time: &str) -> Self {
        if self.error.is_none() {
            match parse_time(time) {
                Ok(t) => self.next_update = Some(t),
                Err(e) => self.error = Some(e),
            }
        }
        self
    }

    /// Add a revoked certificate entry.
    ///
    /// `serial` is the big-endian two's-complement DER INTEGER value bytes
    /// (i.e. the bytes you would get from `Integer::as_bytes()`).
    ///
    /// `revocation_date` uses the same format as [`this_update`](Self::this_update).
    ///
    /// `reason` is the optional CRL reason code (RFC 5280 §5.3.1):
    ///
    /// | Value | Reason |
    /// |-------|--------|
    /// | 0 | unspecified |
    /// | 1 | keyCompromise |
    /// | 2 | cACompromise |
    /// | 3 | affiliationChanged |
    /// | 4 | superseded |
    /// | 5 | cessationOfOperation |
    /// | 6 | certificateHold |
    /// | 8 | removeFromCRL |
    /// | 9 | privilegeWithdrawn |
    /// | 10 | aACompromise |
    pub fn revoke(mut self, serial: &[u8], revocation_date: &str, reason: Option<u8>) -> Self {
        if self.error.is_some() {
            return self;
        }
        let rev_date = match parse_time(revocation_date) {
            Ok(t) => t,
            Err(e) => {
                self.error = Some(e);
                return self;
            }
        };
        let extensions_der = match reason.map(encode_reason_code_extension) {
            Some(Ok(der)) => der,
            Some(Err(e)) => {
                self.error = Some(e);
                return self;
            }
            None => Vec::new(),
        };
        self.revoked.push(RevokedEntry {
            serial: Integer::from_unsigned_bytes(serial),
            revocation_date: rev_date,
            extensions_der,
        });
        self
    }

    /// Add a CRL-level extension.
    ///
    /// `oid_components` is the OID as a `&[u32]` arc slice (e.g. from
    /// `synta_certificate::oids::CRL_NUMBER`).  `critical` marks the
    /// extension as critical.  `value_der` is the raw DER of the extension
    /// value (the OCTET STRING wrapper is added automatically).
    pub fn add_crl_extension(
        mut self,
        oid_components: &[u32],
        critical: bool,
        value_der: &[u8],
    ) -> Self {
        if self.error.is_some() {
            return self;
        }
        match ObjectIdentifier::new(oid_components) {
            Ok(oid) => self
                .crl_extensions
                .push((oid, critical, value_der.to_vec())),
            Err(e) => self.error = Some(format!("invalid extension OID: {e}")),
        }
        self
    }

    /// Set the signature `AlgorithmIdentifier` DER (for `TBSCertList.signature`).
    ///
    /// The bytes must be a complete `AlgorithmIdentifier` SEQUENCE TLV.
    /// This field is required — `build()` returns an error if it is absent.
    pub fn signature_algorithm(mut self, alg_der: &[u8]) -> Self {
        if self.error.is_none() {
            self.signature_algorithm_der = Some(alg_der.to_vec());
        }
        self
    }

    // ── Build ──────────────────────────────────────────────────────────────────

    /// Build the DER-encoded `TBSCertList` SEQUENCE.
    ///
    /// Required fields: `issuer`, `this_update`, and `signature_algorithm`.
    /// Returns `Err` if any required field is absent, if a time string was
    /// malformed, or if DER encoding fails.
    pub fn build(self) -> Result<Vec<u8>, String> {
        if let Some(e) = self.error {
            return Err(e);
        }
        let issuer = self.issuer.ok_or("issuer not set")?;
        let this_update = self.this_update.ok_or("this_update not set")?;
        let sig_alg_der = self
            .signature_algorithm_der
            .ok_or("signature_algorithm not set")?;

        let has_crl_extensions = !self.crl_extensions.is_empty();

        let mut enc = synta::Encoder::new(synta::Encoding::Der);

        enc.start_constructed_no_guard(Tag::universal_constructed(TAG_SEQUENCE))
            .map_err(|e| format!("TBSCertList start error: {e}"))?;

        // version INTEGER OPTIONAL — emit v2 (value 1) only when CRL extensions
        // are present (RFC 5280 §5.1.2.1).
        if has_crl_extensions {
            enc.encode(&Integer::from_i64(1))
                .map_err(|e| format!("version encode error: {e}"))?;
        }

        // signature AlgorithmIdentifier — verbatim splice.
        enc.write_bytes(&sig_alg_der);

        // issuer Name — verbatim splice.
        enc.encode(&RawDer(&issuer))
            .map_err(|e| format!("issuer encode error: {e}"))?;

        // thisUpdate Time.
        enc.encode(&this_update)
            .map_err(|e| format!("thisUpdate encode error: {e}"))?;

        // nextUpdate Time OPTIONAL.
        if let Some(next) = self.next_update {
            enc.encode(&next)
                .map_err(|e| format!("nextUpdate encode error: {e}"))?;
        }

        // revokedCertificates SEQUENCE OF OPTIONAL.
        if !self.revoked.is_empty() {
            enc.start_constructed_no_guard(Tag::universal_constructed(TAG_SEQUENCE))
                .map_err(|e| format!("revokedCertificates start error: {e}"))?;
            for entry in &self.revoked {
                let entry_der = entry.encode()?;
                enc.write_bytes(&entry_der);
            }
            enc.end_constructed()
                .map_err(|e| format!("revokedCertificates end error: {e}"))?;
        }

        // crlExtensions [0] EXPLICIT SEQUENCE OF Extension OPTIONAL.
        if has_crl_extensions {
            enc.start_constructed_no_guard(Tag::context_specific_constructed(0))
                .map_err(|e| format!("crlExtensions [0] start error: {e}"))?;
            enc.start_constructed_no_guard(Tag::universal_constructed(TAG_SEQUENCE))
                .map_err(|e| format!("crlExtensions SEQUENCE start error: {e}"))?;
            for (oid, critical, value_bytes) in &self.crl_extensions {
                let ext = Extension {
                    extn_id: oid.clone(),
                    critical: if *critical {
                        Some(Boolean::new(true))
                    } else {
                        None
                    },
                    extn_value: OctetStringRef::new(value_bytes),
                };
                enc.encode(&ext)
                    .map_err(|e| format!("crlExtension encode error: {e}"))?;
            }
            enc.end_constructed()
                .map_err(|e| format!("crlExtensions SEQUENCE end error: {e}"))?;
            enc.end_constructed()
                .map_err(|e| format!("crlExtensions [0] end error: {e}"))?;
        }

        enc.end_constructed()
            .map_err(|e| format!("TBSCertList end error: {e}"))?;
        enc.finish()
            .map_err(|e| format!("TBSCertList finish error: {e}"))
    }

    /// Assemble a DER-encoded `CertificateList` SEQUENCE from its three
    /// components.
    ///
    /// `tbs_der` is the DER-encoded `TBSCertList` produced by
    /// [`build`](Self::build).  `sig_alg_der` is the outer
    /// `AlgorithmIdentifier` SEQUENCE TLV (typically the same bytes as
    /// `TBSCertList.signature`).  `signature` is the raw signature bytes
    /// (without a BIT STRING wrapper — this function adds `unused_bits = 0`).
    ///
    /// Returns the complete DER-encoded `CertificateList`.
    pub fn assemble(
        tbs_der: &[u8],
        sig_alg_der: &[u8],
        signature: &[u8],
    ) -> Result<Vec<u8>, String> {
        use synta::BitStringRef;

        let mut enc = synta::Encoder::with_capacity(
            synta::Encoding::Der,
            tbs_der.len() + sig_alg_der.len() + signature.len() + 8,
        );
        enc.start_constructed_no_guard(Tag::universal_constructed(TAG_SEQUENCE))
            .map_err(|e| format!("CertificateList start error: {e}"))?;

        enc.write_bytes(tbs_der);
        enc.write_bytes(sig_alg_der);

        let sig_bstr = BitStringRef::new(signature, 0)
            .map_err(|e| format!("signature BIT STRING error: {e}"))?;
        enc.encode(&sig_bstr)
            .map_err(|e| format!("signature encode error: {e}"))?;

        enc.end_constructed()
            .map_err(|e| format!("CertificateList end error: {e}"))?;
        enc.finish()
            .map_err(|e| format!("CertificateList finish error: {e}"))
    }
}

// ── reasonCode extension DER encoder ─────────────────────────────────────────

/// Encode a `crlEntryExtensions` SEQUENCE OF containing a single `reasonCode`
/// extension (OID 2.5.29.21, ENUMERATED value).
///
/// Uses the code-generated [`Extension`] struct and synta encoder:
/// ```text
/// SEQUENCE OF {                          30 0C
///   Extension SEQUENCE {                 30 0A
///     OID 2.5.29.21                      06 03 55 1D 15
///     OCTET STRING {                     04 03
///       ENUMERATED reason                0A 01 xx
/// ```
fn encode_reason_code_extension(reason: u8) -> Result<Vec<u8>, String> {
    // Encode ENUMERATED { reason } — the raw DER value bytes placed inside the OCTET STRING.
    let enum_der = Enumerated::from_i32(reason as i32)
        .to_der()
        .map_err(|e| format!("reasonCode ENUMERATED encode error: {e}"))?;

    // Build the Extension struct and wrap it in a SEQUENCE OF.
    let oid = ObjectIdentifier::new(crate::oids::CRL_REASON)
        .map_err(|e| format!("CRL_REASON OID error: {e}"))?;
    let ext = Extension {
        extn_id: oid,
        critical: None,
        extn_value: OctetStringRef::new(&enum_der),
    };
    let mut enc = synta::Encoder::new(synta::Encoding::Der);
    enc.start_constructed_no_guard(Tag::universal_constructed(TAG_SEQUENCE))
        .map_err(|e| format!("crlEntryExtensions SEQUENCE start error: {e}"))?;
    enc.encode(&ext)
        .map_err(|e| format!("reasonCode Extension encode error: {e}"))?;
    enc.end_constructed()
        .map_err(|e| format!("crlEntryExtensions SEQUENCE end error: {e}"))?;
    enc.finish()
        .map_err(|e| format!("crlEntryExtensions finish error: {e}"))
}

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

    // Minimal issuer Name for tests: SEQUENCE { SET { SEQUENCE { OID CN, UTF8String "Test" } } }
    fn test_issuer_der() -> &'static [u8] {
        &[
            0x30, 0x0f, // Name SEQUENCE
            0x31, 0x0d, // RDN SET
            0x30, 0x0b, // AttributeTypeAndValue SEQUENCE
            0x06, 0x03, 0x55, 0x04, 0x03, // OID 2.5.4.3 (commonName)
            0x0c, 0x04, b'T', b'e', b's', b't', // UTF8String "Test"
        ]
    }

    // Minimal SHA-256withRSA AlgorithmIdentifier.
    fn test_alg_der() -> &'static [u8] {
        &[
            0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x0b, 0x05,
            0x00,
        ]
    }

    /// Round-trip: build a minimal TBSCertList and verify synta can decode it.
    #[test]
    fn build_and_roundtrip_minimal() {
        let tbs = CertificateListBuilder::new()
            .issuer(test_issuer_der())
            .this_update("20240101120000Z")
            .next_update("20250101120000Z")
            .signature_algorithm(test_alg_der())
            .build()
            .expect("build should succeed");

        let mut dec = synta::Decoder::new(&tbs, synta::Encoding::Der);
        let _: crate::crl::TBSCertList<'_> = dec.decode().expect("round-trip decode failed");
    }

    /// Build a CRL with one revoked entry and a reasonCode extension.
    #[test]
    fn build_with_revoked_entry_and_reason() {
        let serial = &[0x01u8];

        let tbs = CertificateListBuilder::new()
            .issuer(test_issuer_der())
            .this_update("20240101120000Z")
            .signature_algorithm(test_alg_der())
            .revoke(serial, "20231201000000Z", Some(1)) // keyCompromise
            .build()
            .expect("build with revoked entry should succeed");

        let mut dec = synta::Decoder::new(&tbs, synta::Encoding::Der);
        let tbs_list: crate::crl::TBSCertList<'_> = dec.decode().expect("round-trip decode failed");
        let revoked = tbs_list
            .revoked_certificates
            .expect("should have revoked entries");
        assert_eq!(revoked.len(), 1);
    }

    /// Missing required fields must yield a descriptive error.
    #[test]
    fn missing_fields_returns_error() {
        let err = CertificateListBuilder::new().build();
        assert!(err.is_err(), "expected error for missing fields");
        let msg = err.unwrap_err();
        assert!(
            msg.contains("issuer")
                || msg.contains("this_update")
                || msg.contains("signature_algorithm"),
            "unexpected error: {msg}"
        );
    }

    /// An invalid time string must record an error and propagate through `build`.
    #[test]
    fn invalid_time_format_propagates() {
        let result = CertificateListBuilder::new()
            .issuer(test_issuer_der())
            .this_update("not-a-time")
            .signature_algorithm(test_alg_der())
            .build();
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("not-a-time"));
    }
}