synta-certificate 0.2.6

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
//! Fluent builder for DER-encoded `ResponseData` / `OCSPResponse` (RFC 6960).
//!
//! [`OCSPResponseBuilder`] assembles a `ResponseData` DER blob that can be
//! handed to an external signer.  The outer `BasicOCSPResponse`
//! (ResponseData + AlgorithmIdentifier + BIT STRING) and the wrapping
//! `OCSPResponse` are assembled by [`OCSPResponseBuilder::assemble`].
//!
//! # Example
//!
//! ```rust,ignore
//! use synta_certificate::{OCSPResponseBuilder, SingleResponseSpec};
//!
//! let tbs_der = OCSPResponseBuilder::new()
//!     .responder_key_hash(&key_hash_bytes)
//!     .produced_at("20240101120000Z")
//!     .add_response(SingleResponseSpec {
//!         hash_algorithm_der: &alg_id_der,
//!         issuer_name_hash: &issuer_name_hash,
//!         issuer_key_hash: &issuer_key_hash,
//!         serial: &serial_bytes,
//!         status: 0,  // good
//!         this_update: "20240101120000Z",
//!         next_update: Some("20240201120000Z"),
//!     })
//!     .build_tbs()
//!     .unwrap();
//! let response_der = OCSPResponseBuilder::assemble(&tbs_der, &sig_alg_der, &signature).unwrap();
//! ```

use synta::{
    BitStringRef, Decoder, Encoding, GeneralizedTime, Integer, Null, ObjectIdentifier,
    OctetStringRef,
};

use crate::ocsp::{
    BasicOCSPResponse, CertID, CertStatus, OCSPResponse, OCSPResponseStatus, ResponseBytes,
    ResponseData, RevokedInfo, SingleResponse, ID_PKIX_OCSP_BASIC,
};
use crate::time_utils::parse_generalized_time;
use crate::{AlgorithmIdentifier, Name};

// ── Single response input / storage ───────────────────────────────────────────

/// Input parameters for one `SingleResponse` entry in an OCSP response.
///
/// Used with [`OCSPResponseBuilder::add_response`].
pub struct SingleResponseSpec<'a> {
    /// Pre-encoded `AlgorithmIdentifier` DER TLV (e.g. SHA-1).
    pub hash_algorithm_der: &'a [u8],
    /// Raw hash bytes of the issuer name (OCTET STRING value, no TLV wrapper).
    pub issuer_name_hash: &'a [u8],
    /// Raw hash bytes of the issuer public key (OCTET STRING value, no TLV).
    pub issuer_key_hash: &'a [u8],
    /// Big-endian DER INTEGER value bytes of the certificate serial number.
    pub serial: &'a [u8],
    /// Certificate status: `0` = good, `1` = revoked, `2` = unknown.
    pub status: u8,
    /// `thisUpdate` time string (`YYYYMMDDHHmmssZ` or `YYMMDDHHmmssZ`).
    pub this_update: &'a str,
    /// `nextUpdate` time string (same format), or `None` to omit.
    pub next_update: Option<&'a str>,
}

/// All data needed to build one `SingleResponse` entry, stored as owned bytes
/// until `build_tbs` is called.
struct PendingSingleResponse {
    /// DER-encoded `AlgorithmIdentifier` TLV for the hash algorithm.
    hash_algorithm_der: Vec<u8>,
    /// Raw hash bytes for `issuerNameHash` (OCTET STRING value, no TLV).
    issuer_name_hash: Vec<u8>,
    /// Raw hash bytes for `issuerKeyHash` (OCTET STRING value, no TLV).
    issuer_key_hash: Vec<u8>,
    /// Big-endian DER INTEGER value bytes for the serial number.
    serial: Vec<u8>,
    /// 0 = good, 1 = revoked, 2 = unknown.
    status: u8,
    this_update: GeneralizedTime,
    next_update: Option<GeneralizedTime>,
}

/// Owned byte storage that keeps borrowed `SingleResponse<'_>` data alive
/// during DER encoding in `build_tbs`.
struct ResponseByteStorage {
    hash_algorithm_der: Vec<u8>,
    issuer_name_hash: Vec<u8>,
    issuer_key_hash: Vec<u8>,
    serial: Vec<u8>,
}

// ── OCSPResponseBuilder ────────────────────────────────────────────────────────

/// Fluent builder for a DER-encoded `ResponseData` (RFC 6960 §4.2.1).
///
/// Produces the unsigned TBS DER blob.  After signing externally, assemble
/// the complete `OCSPResponse` with [`OCSPResponseBuilder::assemble`].
///
/// # Responder identity
///
/// Set exactly one of:
/// - [`responder_name`](Self::responder_name) — `byName` from pre-encoded Name DER
/// - [`responder_key_hash`](Self::responder_key_hash) — `byKey` from raw key-hash bytes
///
/// # Example
///
/// ```rust,ignore
/// use synta_certificate::OCSPResponseBuilder;
///
/// let tbs = OCSPResponseBuilder::new()
///     .responder_key_hash(&key_hash)
///     .produced_at("20240101120000Z")
///     .add_response(synta_certificate::SingleResponseSpec {
///         hash_algorithm_der: &alg_der, issuer_name_hash: &name_hash,
///         issuer_key_hash: &key_hash, serial: &serial, status: 0,
///         this_update: "20240101120000Z", next_update: Some("20240201120000Z"),
///     })
///     .build_tbs()
///     .unwrap();
/// let ocsp_der = OCSPResponseBuilder::assemble(&tbs, &sig_alg_der, &sig_bytes).unwrap();
/// ```
pub struct OCSPResponseBuilder {
    /// Pre-encoded DER Name SEQUENCE TLV for `byName` responder, or `None`.
    responder_name_der: Option<Vec<u8>>,
    /// Raw key-hash bytes for `byKey` responder, or `None`.
    responder_key_hash: Option<Vec<u8>>,
    /// `producedAt` GeneralizedTime.
    produced_at: Option<GeneralizedTime>,
    /// Accumulated `SingleResponse` entries.
    responses: Vec<PendingSingleResponse>,
    /// First error encountered; subsequent builder calls are no-ops.
    error: Option<String>,
}

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

impl OCSPResponseBuilder {
    /// Create a new, empty `OCSPResponseBuilder`.
    pub fn new() -> Self {
        Self {
            responder_name_der: None,
            responder_key_hash: None,
            produced_at: None,
            responses: Vec::new(),
            error: None,
        }
    }

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

    /// Set `responderID byName` from a pre-encoded DER Name SEQUENCE TLV.
    ///
    /// Pass the bytes from `Certificate::subject_raw_der()` or equivalent.
    /// The bytes are validated by attempting to decode them as `Name`.
    pub fn responder_name(mut self, name_der: &[u8]) -> Self {
        if self.error.is_some() {
            return self;
        }
        // Validate the bytes decode as Name.
        match Decoder::new(name_der, Encoding::Der).decode::<Name<'_>>() {
            Ok(_) => self.responder_name_der = Some(name_der.to_vec()),
            Err(e) => self.error = Some(format!("invalid responder Name DER: {e}")),
        }
        self
    }

    /// Set `responderID byKey` from the raw key-hash bytes (OCTET STRING value).
    ///
    /// `key_hash` is the raw hash bytes without any TLV wrapper — typically
    /// the SHA-1 hash of the issuer's `subjectPublicKey` BIT STRING value.
    pub fn responder_key_hash(mut self, key_hash: &[u8]) -> Self {
        if self.error.is_none() {
            self.responder_key_hash = Some(key_hash.to_vec());
        }
        self
    }

    /// Set `producedAt` GeneralizedTime.
    ///
    /// Accepts `"YYYYMMDDHHmmssZ"` (GeneralizedTime) or `"YYMMDDHHmmssZ"`
    /// (UTCTime short form, automatically promoted to a 4-digit-year
    /// `GeneralizedTime` as required by RFC 6960).
    pub fn produced_at(mut self, time: &str) -> Self {
        if self.error.is_none() {
            match parse_generalized_time(time) {
                Ok(t) => self.produced_at = Some(t),
                Err(e) => self.error = Some(e),
            }
        }
        self
    }

    /// Add a `SingleResponse` entry.
    ///
    /// All parameters are supplied via [`SingleResponseSpec`].
    pub fn add_response(mut self, spec: SingleResponseSpec<'_>) -> Self {
        if self.error.is_some() {
            return self;
        }
        // Validate the AlgorithmIdentifier DER.
        if let Err(e) =
            Decoder::new(spec.hash_algorithm_der, Encoding::Der).decode::<AlgorithmIdentifier<'_>>()
        {
            self.error = Some(format!("invalid hash_algorithm_der: {e}"));
            return self;
        }
        let this = match parse_generalized_time(spec.this_update) {
            Ok(t) => t,
            Err(e) => {
                self.error = Some(e);
                return self;
            }
        };
        let next = if let Some(s) = spec.next_update {
            match parse_generalized_time(s) {
                Ok(t) => Some(t),
                Err(e) => {
                    self.error = Some(e);
                    return self;
                }
            }
        } else {
            None
        };
        if spec.status > 2 {
            self.error = Some(format!(
                "invalid status {}: must be 0, 1, or 2",
                spec.status
            ));
            return self;
        }
        self.responses.push(PendingSingleResponse {
            hash_algorithm_der: spec.hash_algorithm_der.to_vec(),
            issuer_name_hash: spec.issuer_name_hash.to_vec(),
            issuer_key_hash: spec.issuer_key_hash.to_vec(),
            serial: spec.serial.to_vec(),
            status: spec.status,
            this_update: this,
            next_update: next,
        });
        self
    }

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

    /// Build the DER-encoded `ResponseData` SEQUENCE.
    ///
    /// Required: at least one of `responder_name` or `responder_key_hash` must
    /// be set, and `produced_at` must be set.
    ///
    /// Returns `Err` if any required field is absent, if a time string was
    /// malformed, or if DER encoding fails.
    pub fn build_tbs(self) -> Result<Vec<u8>, String> {
        if let Some(e) = self.error {
            return Err(e);
        }
        let produced_at = self.produced_at.ok_or("produced_at not set")?;

        // Build owned SingleResponse values for encoding.
        // Keep byte Vecs alive so the borrowed slices inside the structs remain valid.
        let mut response_storage: Vec<ResponseByteStorage> =
            Vec::with_capacity(self.responses.len());
        for r in &self.responses {
            response_storage.push(ResponseByteStorage {
                hash_algorithm_der: r.hash_algorithm_der.clone(),
                issuer_name_hash: r.issuer_name_hash.clone(),
                issuer_key_hash: r.issuer_key_hash.clone(),
                serial: r.serial.clone(),
            });
        }
        let mut single_responses: Vec<SingleResponse<'_>> =
            Vec::with_capacity(self.responses.len());
        for (r, storage) in self.responses.iter().zip(response_storage.iter()) {
            let hash_algorithm: AlgorithmIdentifier<'_> =
                Decoder::new(&storage.hash_algorithm_der, Encoding::Der)
                    .decode()
                    .map_err(|e| format!("re-decode hash_algorithm_der failed: {e}"))?;
            let cert_id = CertID {
                hash_algorithm,
                issuer_name_hash: OctetStringRef::new(&storage.issuer_name_hash),
                issuer_key_hash: OctetStringRef::new(&storage.issuer_key_hash),
                serial_number: Integer::from_unsigned_bytes(&storage.serial),
            };
            let cert_status = match r.status {
                0 => CertStatus::Good(Null),
                2 => CertStatus::Unknown(Null),
                _ => {
                    // status == 1: revoked; use thisUpdate as revocationTime.
                    CertStatus::Revoked(RevokedInfo {
                        revocation_time: r.this_update.clone(),
                        revocation_reason: None,
                    })
                }
            };
            single_responses.push(SingleResponse {
                cert_id,
                cert_status,
                this_update: r.this_update.clone(),
                next_update: r.next_update.clone(),
                single_extensions: None,
            });
        }

        // Build ResponderID.
        let responder_id = if let Some(name_der) = &self.responder_name_der {
            let name: Name<'_> = Decoder::new(name_der, Encoding::Der)
                .decode()
                .map_err(|e| format!("re-decode responder Name failed: {e}"))?;
            crate::ocsp::ResponderID::ByName(name)
        } else if let Some(key_hash) = &self.responder_key_hash {
            crate::ocsp::ResponderID::ByKey(OctetStringRef::new(key_hash))
        } else {
            return Err("responder not set: call responder_name() or responder_key_hash()".into());
        };

        let response_data = ResponseData {
            version: None,
            responder_id,
            produced_at,
            responses: single_responses,
            response_extensions: None,
        };

        response_data
            .to_der()
            .map_err(|e| format!("ResponseData encode error: {e}"))
    }

    /// Assemble a DER-encoded `OCSPResponse` from its signed components.
    ///
    /// # Structure produced
    ///
    /// ```text
    /// OCSPResponse ::= SEQUENCE {
    ///   responseStatus ENUMERATED { successful(0) },
    ///   responseBytes [0] EXPLICIT ResponseBytes {
    ///     responseType OID id-pkix-ocsp-basic,
    ///     response OCTET STRING { BasicOCSPResponse {
    ///       tbsResponseData  <tbs_der>,
    ///       signatureAlgorithm <sig_alg_der>,
    ///       signature BIT STRING <signature>
    ///     }}
    ///   }
    /// }
    /// ```
    ///
    /// # Parameters
    ///
    /// - `tbs_der` — DER-encoded `ResponseData` from [`build_tbs`](Self::build_tbs)
    /// - `sig_alg_der` — DER-encoded `AlgorithmIdentifier` for the signature
    /// - `signature` — raw signature bytes (BIT STRING value; unused-bits = 0 is added)
    ///
    /// Returns the complete DER-encoded `OCSPResponse`.
    pub fn assemble(
        tbs_der: &[u8],
        sig_alg_der: &[u8],
        signature: &[u8],
    ) -> Result<Vec<u8>, String> {
        // ── Step 1: build BasicOCSPResponse ─────────────────────────────────────
        //
        // Re-decode tbs_der and sig_alg_der to get borrowing types.
        let tbs: ResponseData<'_> = Decoder::new(tbs_der, Encoding::Der)
            .decode()
            .map_err(|e| format!("assemble: tbs_der decode error: {e}"))?;
        let sig_algorithm: AlgorithmIdentifier<'_> = Decoder::new(sig_alg_der, Encoding::Der)
            .decode()
            .map_err(|e| format!("assemble: sig_alg_der decode error: {e}"))?;
        let sig_bstr = BitStringRef::new(signature, 0)
            .map_err(|e| format!("assemble: signature BIT STRING error: {e}"))?;

        let basic = BasicOCSPResponse {
            tbs_response_data: tbs,
            signature_algorithm: sig_algorithm,
            signature: sig_bstr,
            certs: None,
        };

        let basic_der = basic
            .to_der()
            .map_err(|e| format!("BasicOCSPResponse encode error: {e}"))?;

        // ── Step 2: build ResponseBytes = OID + OCTET STRING(BasicOCSPResponse) ─
        let response_type = ObjectIdentifier::new(ID_PKIX_OCSP_BASIC)
            .map_err(|e| format!("id-pkix-ocsp-basic OID error: {e}"))?;
        let response_octet = OctetStringRef::new(&basic_der);
        let response_bytes = ResponseBytes {
            response_type,
            response: response_octet,
        };

        // ── Step 3: build OCSPResponse = ENUMERATED(0) + [0] EXPLICIT ResponseBytes
        let ocsp_response = OCSPResponse {
            response_status: OCSPResponseStatus::Successful,
            response_bytes: Some(response_bytes),
        };

        ocsp_response
            .to_der()
            .map_err(|e| format!("OCSPResponse encode error: {e}"))
    }
}

// ── Tests ──────────────────────────────────────────────────────────────────────

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

    // SHA-1 AlgorithmIdentifier: SEQUENCE { OID 1.3.14.3.2.26, NULL }
    // 30 09 06 05 2b 0e 03 02 1a 05 00
    fn sha1_alg_der() -> &'static [u8] {
        &[
            0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03, 0x02, 0x1a, 0x05, 0x00,
        ]
    }

    // SHA-256withRSA AlgorithmIdentifier for outer signature.
    // 30 0d 06 09 2a 86 48 86 f7 0d 01 01 0b 05 00
    fn sha256_rsa_alg_der() -> &'static [u8] {
        &[
            0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x0b, 0x05,
            0x00,
        ]
    }

    // Minimal issuer Name: SEQUENCE { SET { SEQUENCE { OID CN, UTF8String "Test" } } }
    fn test_name_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"
        ]
    }

    /// Round-trip: build a minimal ResponseData with byKey responder and one
    /// "good" entry, assemble the full OCSPResponse, then decode back and
    /// verify the structure.
    #[test]
    fn build_and_assemble_minimal() {
        let key_hash = [0x01u8; 20]; // 20-byte dummy SHA-1 hash
        let name_hash = [0x02u8; 20];
        let serial = [0x01u8];
        let fake_sig = [0xdeu8; 32]; // dummy signature bytes

        let tbs = OCSPResponseBuilder::new()
            .responder_key_hash(&key_hash)
            .produced_at("20240101120000Z")
            .add_response(SingleResponseSpec {
                hash_algorithm_der: sha1_alg_der(),
                issuer_name_hash: &name_hash,
                issuer_key_hash: &key_hash,
                serial: &serial,
                status: 0, // good
                this_update: "20240101120000Z",
                next_update: Some("20240201120000Z"),
            })
            .build_tbs()
            .expect("build_tbs should succeed");

        assert!(!tbs.is_empty(), "TBS DER must not be empty");

        let ocsp_der = OCSPResponseBuilder::assemble(&tbs, sha256_rsa_alg_der(), &fake_sig)
            .expect("assemble should succeed");

        // Decode back and check the outer structure.
        let mut dec = Decoder::new(&ocsp_der, Encoding::Der);
        let resp: OCSPResponse<'_> = dec.decode().expect("OCSPResponse round-trip decode failed");

        assert_eq!(resp.response_status, OCSPResponseStatus::Successful);
        let rb = resp.response_bytes.expect("responseBytes must be present");
        assert_eq!(rb.response_type.components(), ID_PKIX_OCSP_BASIC);

        // The response OCTET STRING contains a BasicOCSPResponse.
        let basic_der = rb.response.as_bytes();
        let mut basic_dec = Decoder::new(basic_der, Encoding::Der);
        let basic: BasicOCSPResponse<'_> =
            basic_dec.decode().expect("BasicOCSPResponse decode failed");

        let rd = &basic.tbs_response_data;
        assert_eq!(rd.responses.len(), 1);
        assert!(
            matches!(rd.responses[0].cert_status, CertStatus::Good(_)),
            "status must be Good"
        );
    }

    /// Build a TBS with a byName responder and verify that it decodes correctly.
    #[test]
    fn build_tbs_responder_name() {
        let name_hash = [0xaau8; 20];
        let key_hash = [0xbbu8; 20];
        let serial = [0x02u8];

        let tbs = OCSPResponseBuilder::new()
            .responder_name(test_name_der())
            .produced_at("20240601000000Z")
            .add_response(SingleResponseSpec {
                hash_algorithm_der: sha1_alg_der(),
                issuer_name_hash: &name_hash,
                issuer_key_hash: &key_hash,
                serial: &serial,
                status: 0,
                this_update: "20240601000000Z",
                next_update: None,
            })
            .build_tbs()
            .expect("build_tbs with byName should succeed");

        let mut dec = Decoder::new(&tbs, Encoding::Der);
        let rd: ResponseData<'_> = dec.decode().expect("ResponseData decode failed");
        assert!(
            matches!(rd.responder_id, crate::ocsp::ResponderID::ByName(_)),
            "expected byName responder"
        );
        assert_eq!(rd.responses.len(), 1);
    }

    /// Calling `build_tbs()` without setting a responder must return `Err`
    /// containing the word "responder".
    #[test]
    fn missing_responder_returns_error() {
        let result = OCSPResponseBuilder::new()
            .produced_at("20240101120000Z")
            .build_tbs();

        assert!(result.is_err(), "expected error for missing responder");
        let msg = result.unwrap_err();
        assert!(
            msg.contains("responder"),
            "error message must mention 'responder', got: {msg}"
        );
    }

    /// An invalid time string must record an error and propagate through `build_tbs`.
    #[test]
    fn invalid_time_format_propagates() {
        let result = OCSPResponseBuilder::new()
            .responder_key_hash(&[0x01u8; 20])
            .produced_at("not-a-time")
            .build_tbs();
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("not-a-time"));
    }
}