uselesskey-x509 0.9.1

X.509 self-signed and chain certificate fixtures with negative variants for tests.
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
//! X.509 certificate chain specification.

use super::{KeyUsage, NotBeforeOffset};

/// Specification for generating a three-level X.509 certificate chain
/// (root CA -> intermediate CA -> leaf).
#[derive(Clone, Debug, Eq, PartialEq, Hash)]
pub struct ChainSpec {
    /// Common Name (CN) for the leaf certificate.
    pub leaf_cn: String,
    /// DNS Subject Alternative Names for the leaf certificate.
    pub leaf_sans: Vec<String>,
    /// Common Name (CN) for the root CA.
    pub root_cn: String,
    /// Common Name (CN) for the intermediate CA.
    pub intermediate_cn: String,
    /// RSA key size in bits.
    pub rsa_bits: usize,
    /// Root CA validity period in days.
    pub root_validity_days: u32,
    /// Intermediate CA validity period in days.
    pub intermediate_validity_days: u32,
    /// Leaf certificate validity period in days.
    pub leaf_validity_days: u32,
    /// Override for leaf `not_before` relative to the deterministic base time.
    ///
    /// When `None`, `not_before = base_time - 1 day` (the default).
    pub leaf_not_before: Option<NotBeforeOffset>,
    /// Override for intermediate `not_before` relative to the deterministic base time.
    ///
    /// When `None`, `not_before = base_time - 1 day` (the default).
    pub intermediate_not_before: Option<NotBeforeOffset>,
    /// Optional override for whether the intermediate claims CA status.
    ///
    /// When `None`, the intermediate remains a CA.
    pub intermediate_is_ca: Option<bool>,
    /// Optional override for the intermediate key usage bits.
    ///
    /// When `None`, the intermediate uses standard CA key usage.
    pub intermediate_key_usage: Option<KeyUsage>,
}

impl ChainSpec {
    /// Create a chain spec with sensible defaults for the given leaf CN.
    ///
    /// The leaf CN is automatically added to the SAN list.
    pub fn new(leaf_cn: impl Into<String>) -> Self {
        let leaf_cn = leaf_cn.into();
        let root_cn = format!("{} Root CA", leaf_cn);
        let intermediate_cn = format!("{} Intermediate CA", leaf_cn);
        let leaf_sans = vec![leaf_cn.clone()];
        Self {
            leaf_cn,
            leaf_sans,
            root_cn,
            intermediate_cn,
            rsa_bits: 2048,
            root_validity_days: 3650,
            intermediate_validity_days: 1825,
            leaf_validity_days: 3650,
            leaf_not_before: None,
            intermediate_not_before: None,
            intermediate_is_ca: None,
            intermediate_key_usage: None,
        }
    }

    /// Set the DNS Subject Alternative Names for the leaf certificate.
    ///
    /// The leaf CN is **not** automatically added; include it explicitly if needed.
    pub fn with_sans(mut self, sans: Vec<String>) -> Self {
        self.leaf_sans = sans;
        self
    }

    /// Set the root CA Common Name.
    pub fn with_root_cn(mut self, cn: impl Into<String>) -> Self {
        self.root_cn = cn.into();
        self
    }

    /// Set the intermediate CA Common Name.
    pub fn with_intermediate_cn(mut self, cn: impl Into<String>) -> Self {
        self.intermediate_cn = cn.into();
        self
    }

    /// Set the RSA key size in bits.
    pub fn with_rsa_bits(mut self, bits: usize) -> Self {
        self.rsa_bits = bits;
        self
    }

    /// Set the root CA validity period in days.
    pub fn with_root_validity_days(mut self, days: u32) -> Self {
        self.root_validity_days = days;
        self
    }

    /// Set the intermediate CA validity period in days.
    pub fn with_intermediate_validity_days(mut self, days: u32) -> Self {
        self.intermediate_validity_days = days;
        self
    }

    /// Set the leaf certificate validity period in days.
    pub fn with_leaf_validity_days(mut self, days: u32) -> Self {
        self.leaf_validity_days = days;
        self
    }

    /// Set the leaf `not_before` override.
    pub fn with_leaf_not_before(mut self, offset: NotBeforeOffset) -> Self {
        self.leaf_not_before = Some(offset);
        self
    }

    /// Set the intermediate `not_before` override.
    pub fn with_intermediate_not_before(mut self, offset: NotBeforeOffset) -> Self {
        self.intermediate_not_before = Some(offset);
        self
    }

    /// Override whether the intermediate claims CA status.
    pub fn with_intermediate_is_ca(mut self, is_ca: bool) -> Self {
        self.intermediate_is_ca = Some(is_ca);
        self
    }

    /// Override the intermediate key usage bits.
    pub fn with_intermediate_key_usage(mut self, key_usage: KeyUsage) -> Self {
        self.intermediate_key_usage = Some(key_usage);
        self
    }

    /// Stable byte representation for deterministic derivation.
    ///
    /// SANs are sorted and deduplicated before encoding for stability.
    ///
    /// For backward compatibility, specs that only use the pre-#279 surface
    /// keep the legacy v2 encoding so existing good/expired chain fixtures do
    /// not drift. Richer time offsets and intermediate overrides use v3.
    pub fn stable_bytes(&self) -> Vec<u8> {
        if self.uses_v2_compat_encoding() {
            return self.stable_bytes_v2_compat();
        }

        self.stable_bytes_v3()
    }

    fn uses_v2_compat_encoding(&self) -> bool {
        self.intermediate_is_ca.is_none()
            && self.intermediate_key_usage.is_none()
            && supports_v2_not_before(self.leaf_not_before)
            && supports_v2_not_before(self.intermediate_not_before)
    }

    fn stable_bytes_v2_compat(&self) -> Vec<u8> {
        let mut out = Vec::new();

        // Version prefix (v2: pre-#279 ChainSpec encoding)
        out.push(2);
        encode_common_fields(self, &mut out);
        encode_optional_days_ago_i64(&mut out, self.leaf_not_before);
        encode_optional_days_ago_i64(&mut out, self.intermediate_not_before);
        out
    }

    fn stable_bytes_v3(&self) -> Vec<u8> {
        let mut out = Vec::new();

        // Version prefix (v3: rich not_before offsets + intermediate overrides)
        out.push(3);
        encode_common_fields(self, &mut out);

        // not_before offsets and intermediate overrides
        encode_optional_not_before(&mut out, self.leaf_not_before);
        encode_optional_not_before(&mut out, self.intermediate_not_before);

        match self.intermediate_is_ca {
            None => out.push(0),
            Some(false) => out.push(1),
            Some(true) => out.push(2),
        }

        match self.intermediate_key_usage {
            None => out.push(0),
            Some(key_usage) => {
                out.push(1);
                out.extend_from_slice(&key_usage.stable_bytes());
            }
        }

        out
    }
}

fn encode_common_fields(spec: &ChainSpec, out: &mut Vec<u8>) {
    // leaf_cn
    let leaf_cn_bytes = spec.leaf_cn.as_bytes();
    out.extend_from_slice(&(leaf_cn_bytes.len() as u32).to_be_bytes());
    out.extend_from_slice(leaf_cn_bytes);

    // leaf_sans (sorted and deduplicated for stability)
    let mut sorted_sans = spec.leaf_sans.clone();
    sorted_sans.sort();
    sorted_sans.dedup();
    out.extend_from_slice(&(sorted_sans.len() as u32).to_be_bytes());
    for san in &sorted_sans {
        let san_bytes = san.as_bytes();
        out.extend_from_slice(&(san_bytes.len() as u32).to_be_bytes());
        out.extend_from_slice(san_bytes);
    }

    // root_cn
    let root_cn_bytes = spec.root_cn.as_bytes();
    out.extend_from_slice(&(root_cn_bytes.len() as u32).to_be_bytes());
    out.extend_from_slice(root_cn_bytes);

    // intermediate_cn
    let int_cn_bytes = spec.intermediate_cn.as_bytes();
    out.extend_from_slice(&(int_cn_bytes.len() as u32).to_be_bytes());
    out.extend_from_slice(int_cn_bytes);

    // rsa_bits
    out.extend_from_slice(&(spec.rsa_bits as u32).to_be_bytes());

    // validity periods
    out.extend_from_slice(&spec.root_validity_days.to_be_bytes());
    out.extend_from_slice(&spec.intermediate_validity_days.to_be_bytes());
    out.extend_from_slice(&spec.leaf_validity_days.to_be_bytes());
}

fn supports_v2_not_before(offset: Option<NotBeforeOffset>) -> bool {
    matches!(offset, None | Some(NotBeforeOffset::DaysAgo(_)))
}

fn encode_optional_days_ago_i64(out: &mut Vec<u8>, offset: Option<NotBeforeOffset>) {
    match offset {
        None => out.push(0),
        Some(NotBeforeOffset::DaysAgo(days)) => {
            out.push(1);
            out.extend_from_slice(&i64::from(days).to_be_bytes());
        }
        Some(NotBeforeOffset::DaysFromNow(_)) => {
            unreachable!("DaysFromNow requires v3 encoding")
        }
    }
}

fn encode_optional_not_before(out: &mut Vec<u8>, offset: Option<NotBeforeOffset>) {
    match offset {
        None => out.push(0),
        Some(NotBeforeOffset::DaysAgo(days)) => {
            out.push(1);
            out.extend_from_slice(&days.to_be_bytes());
        }
        Some(NotBeforeOffset::DaysFromNow(days)) => {
            out.push(2);
            out.extend_from_slice(&days.to_be_bytes());
        }
    }
}

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

    #[test]
    fn test_defaults() {
        let spec = ChainSpec::new("test.example.com");
        assert_eq!(spec.leaf_cn, "test.example.com");
        assert_eq!(spec.leaf_sans, vec!["test.example.com"]);
        assert_eq!(spec.root_cn, "test.example.com Root CA");
        assert_eq!(spec.intermediate_cn, "test.example.com Intermediate CA");
        assert_eq!(spec.rsa_bits, 2048);
        assert_eq!(spec.root_validity_days, 3650);
        assert_eq!(spec.intermediate_validity_days, 1825);
        assert_eq!(spec.leaf_validity_days, 3650);
        assert_eq!(spec.leaf_not_before, None);
        assert_eq!(spec.intermediate_not_before, None);
        assert_eq!(spec.intermediate_is_ca, None);
        assert_eq!(spec.intermediate_key_usage, None);
    }

    #[test]
    fn test_builders() {
        let spec = ChainSpec::new("example.com")
            .with_sans(vec![
                "example.com".to_string(),
                "www.example.com".to_string(),
            ])
            .with_root_cn("My Root CA")
            .with_intermediate_cn("My Int CA")
            .with_rsa_bits(4096)
            .with_root_validity_days(7300)
            .with_intermediate_validity_days(3650)
            .with_leaf_validity_days(90)
            .with_leaf_not_before(NotBeforeOffset::DaysFromNow(7))
            .with_intermediate_not_before(NotBeforeOffset::DaysAgo(30))
            .with_intermediate_is_ca(false)
            .with_intermediate_key_usage(KeyUsage::leaf());

        assert_eq!(spec.leaf_sans.len(), 2);
        assert_eq!(spec.root_cn, "My Root CA");
        assert_eq!(spec.intermediate_cn, "My Int CA");
        assert_eq!(spec.rsa_bits, 4096);
        assert_eq!(spec.root_validity_days, 7300);
        assert_eq!(spec.intermediate_validity_days, 3650);
        assert_eq!(spec.leaf_validity_days, 90);
        assert_eq!(spec.leaf_not_before, Some(NotBeforeOffset::DaysFromNow(7)));
        assert_eq!(
            spec.intermediate_not_before,
            Some(NotBeforeOffset::DaysAgo(30))
        );
        assert_eq!(spec.intermediate_is_ca, Some(false));
        assert_eq!(spec.intermediate_key_usage, Some(KeyUsage::leaf()));
    }

    #[test]
    fn test_stable_bytes_determinism() {
        let spec1 = ChainSpec::new("test.example.com");
        let spec2 = ChainSpec::new("test.example.com");
        assert_eq!(spec1.stable_bytes(), spec2.stable_bytes());

        let spec3 = ChainSpec::new("other.example.com");
        assert_ne!(spec1.stable_bytes(), spec3.stable_bytes());
    }

    #[test]
    fn test_stable_bytes_san_order_independent() {
        let spec1 = ChainSpec::new("test.example.com").with_sans(vec![
            "a.example.com".to_string(),
            "b.example.com".to_string(),
        ]);
        let spec2 = ChainSpec::new("test.example.com").with_sans(vec![
            "b.example.com".to_string(),
            "a.example.com".to_string(),
        ]);
        assert_eq!(spec1.stable_bytes(), spec2.stable_bytes());
    }

    #[test]
    fn test_stable_bytes_field_sensitivity() {
        let base = ChainSpec::new("test.example.com");
        let base_bytes = base.stable_bytes();

        // Changing rsa_bits
        let changed = base.clone().with_rsa_bits(4096);
        assert_ne!(
            changed.stable_bytes(),
            base_bytes,
            "rsa_bits must affect stable_bytes"
        );

        // Changing root_validity_days
        let changed = base.clone().with_root_validity_days(999);
        assert_ne!(
            changed.stable_bytes(),
            base_bytes,
            "root_validity_days must affect stable_bytes"
        );

        // Changing intermediate_validity_days
        let changed = base.clone().with_intermediate_validity_days(999);
        assert_ne!(
            changed.stable_bytes(),
            base_bytes,
            "intermediate_validity_days must affect stable_bytes"
        );

        // Changing leaf_validity_days
        let changed = base.clone().with_leaf_validity_days(999);
        assert_ne!(
            changed.stable_bytes(),
            base_bytes,
            "leaf_validity_days must affect stable_bytes"
        );

        // Changing root_cn
        let changed = base.clone().with_root_cn("Other Root CA");
        assert_ne!(
            changed.stable_bytes(),
            base_bytes,
            "root_cn must affect stable_bytes"
        );

        // Changing intermediate_cn
        let changed = base.clone().with_intermediate_cn("Other Int CA");
        assert_ne!(
            changed.stable_bytes(),
            base_bytes,
            "intermediate_cn must affect stable_bytes"
        );

        // Changing leaf_sans
        let changed = base
            .clone()
            .with_sans(vec!["extra.example.com".to_string()]);
        assert_ne!(
            changed.stable_bytes(),
            base_bytes,
            "leaf_sans must affect stable_bytes"
        );
    }

    #[test]
    fn test_stable_bytes_optional_offset_sensitivity() {
        let base = ChainSpec::new("test.example.com");
        let base_bytes = base.stable_bytes();

        // leaf_not_before_offset_days: None vs Some(100)
        let mut with_leaf_offset = base.clone();
        with_leaf_offset.leaf_not_before = Some(NotBeforeOffset::DaysAgo(100));
        assert_ne!(
            with_leaf_offset.stable_bytes(),
            base_bytes,
            "leaf_not_before None vs Some must differ"
        );

        // leaf_not_before: DaysAgo(100) vs DaysFromNow(100)
        let mut with_leaf_offset2 = base.clone();
        with_leaf_offset2.leaf_not_before = Some(NotBeforeOffset::DaysFromNow(100));
        assert_ne!(
            with_leaf_offset.stable_bytes(),
            with_leaf_offset2.stable_bytes(),
            "leaf_not_before days-ago vs days-from-now must differ"
        );

        // intermediate_not_before: None vs Some(100)
        let mut with_int_offset = base.clone();
        with_int_offset.intermediate_not_before = Some(NotBeforeOffset::DaysAgo(100));
        assert_ne!(
            with_int_offset.stable_bytes(),
            base_bytes,
            "intermediate_not_before None vs Some must differ"
        );

        // intermediate_not_before: Some(100) vs Some(200)
        let mut with_int_offset2 = base.clone();
        with_int_offset2.intermediate_not_before = Some(NotBeforeOffset::DaysAgo(200));
        assert_ne!(
            with_int_offset.stable_bytes(),
            with_int_offset2.stable_bytes(),
            "intermediate_not_before Some(100) vs Some(200) must differ"
        );

        let with_int_is_ca = base.clone().with_intermediate_is_ca(false);
        assert_ne!(
            with_int_is_ca.stable_bytes(),
            base_bytes,
            "intermediate_is_ca must affect stable_bytes"
        );

        let with_int_ku = base.clone().with_intermediate_key_usage(KeyUsage::leaf());
        assert_ne!(
            with_int_ku.stable_bytes(),
            base_bytes,
            "intermediate_key_usage must affect stable_bytes"
        );
    }

    #[test]
    fn test_stable_bytes_v3_encodes_not_before_offsets() {
        let base = ChainSpec::new("test.example.com").with_intermediate_is_ca(false);
        let base_bytes = base.stable_bytes();

        let leaf_future = base
            .clone()
            .with_leaf_not_before(NotBeforeOffset::DaysFromNow(7));
        assert_ne!(
            leaf_future.stable_bytes(),
            base_bytes,
            "v3 leaf not_before offset must affect stable_bytes"
        );

        let leaf_past = base
            .clone()
            .with_leaf_not_before(NotBeforeOffset::DaysAgo(7));
        assert_ne!(
            leaf_future.stable_bytes(),
            leaf_past.stable_bytes(),
            "v3 leaf days-from-now and days-ago offsets must differ"
        );

        let intermediate_future =
            base.with_intermediate_not_before(NotBeforeOffset::DaysFromNow(7));
        assert_ne!(
            intermediate_future.stable_bytes(),
            base_bytes,
            "v3 intermediate not_before offset must affect stable_bytes"
        );
    }

    #[test]
    fn test_stable_bytes_default_uses_v2_compat_prefix() {
        let spec = ChainSpec::new("compat.example.com");
        assert_eq!(spec.stable_bytes()[0], 2);
    }

    #[test]
    fn test_stable_bytes_days_ago_only_stays_on_v2_compat() {
        let spec = ChainSpec::new("compat.example.com")
            .with_leaf_not_before(NotBeforeOffset::DaysAgo(7))
            .with_intermediate_not_before(NotBeforeOffset::DaysAgo(30));
        assert_eq!(spec.stable_bytes()[0], 2);
    }

    #[test]
    fn test_stable_bytes_days_from_now_or_intermediate_overrides_use_v3() {
        let future = ChainSpec::new("future.example.com")
            .with_leaf_not_before(NotBeforeOffset::DaysFromNow(7));
        assert_eq!(future.stable_bytes()[0], 3);

        let not_ca = ChainSpec::new("path.example.com").with_intermediate_is_ca(false);
        assert_eq!(not_ca.stable_bytes()[0], 3);

        let wrong_ku =
            ChainSpec::new("path.example.com").with_intermediate_key_usage(KeyUsage::leaf());
        assert_eq!(wrong_ku.stable_bytes()[0], 3);
    }
}