bhx5chain 0.3.2

TBTL's library for handling X.509 certificate chains.
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
// Copyright (C) 2020-2025  The Blockhouse Technology Limited (TBTL).
//
// This program is free software: you can redistribute it and/or modify it
// under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or (at your
// option) any later version.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public
// License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

use bherror::traits::{ErrorContext as _, ForeignError as _};
use openssl::{
    base64,
    error::ErrorStack,
    pkey::{PKey, Public},
    stack::Stack,
    x509::{
        store::{X509Store, X509StoreBuilder},
        verify::X509VerifyFlags,
        X509StoreContext, X509,
    },
};

use crate::{Error, JwtX5Chain, Result};

/// The `x5chain` as defined in [RFC 9360][1].
///
/// The certificates are ordered starting with the certificate containing the end-entity key
/// followed by the certificate that signed it, and so on, as stated in [RFC 9360][1].
///
/// All methods of this type that return an [`Error`] do so in case the `x5chain` is invalid.
///
/// [1]: <https://www.rfc-editor.org/rfc/rfc9360.html#section-2-5.4.1>
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct X5Chain {
    leaf: X509,
    intermediates: Vec<X509>,
}

impl X5Chain {
    /// Create a new [`X5Chain`].
    ///
    /// The chain **MUST BE** ordered in such a way that the leaf certificate is at first place,
    /// then goes its parent, and so on.
    ///
    /// # Warning
    ///
    /// The chain is at this point **NOT VALIDATED** against any trusted root certificate. In order
    /// to validate the chain against a trusted root certificate, use the
    /// [`X5Chain::verify_against_trusted_roots`] method.
    pub fn new(chain: Vec<X509>) -> Result<Self> {
        // validate the order of certificates
        validate_chain_order(&chain)?;

        let mut chain = chain.into_iter();
        // `expect` is fine as the length is checked within the `validate_chain_order`
        let leaf = chain.next().expect("chain is empty");
        let intermediates = chain.collect();

        Ok(Self {
            leaf,
            intermediates,
        })
    }

    /// Constructs a [`X5Chain`] from raw bytes.
    ///
    /// Each certificate **MUST BE** represented as a [`Vec`] of bytes of the respective certificate
    /// in the _DER_ format.
    ///
    /// The chain **MUST BE** ordered in such a way that the leaf certificate is at first place,
    /// then goes its parent, and so on.
    ///
    /// # Warning
    ///
    /// The chain is at this point **NOT VALIDATED** against any trusted root certificate. In order
    /// to validate the chain against a trusted root certificate, use the
    /// [`X5Chain::verify_against_trusted_roots`] method.
    pub fn from_raw_bytes(bytes: &[Vec<u8>]) -> Result<Self> {
        let certs = bytes
            .iter()
            .enumerate()
            .map(|(i, der)| X509::from_der(der).foreign_err(|| Error::X5Chain).ctx(|| i))
            .collect::<Result<_>>()
            .ctx(|| "invalid X509 certificate")?;

        Self::new(certs)
    }

    /// Constructs a [`X5Chain`] from a sequence of PEM-encoded strings.
    ///
    /// The chain **MUST BE** ordered in such a way that the leaf certificate is at first place,
    /// then goes its parent, and so on.
    ///
    /// # Warning
    ///
    /// The chain is at this point **NOT VALIDATED** against any trusted root certificate. In order
    /// to validate the chain against a trusted root certificate, use the
    /// [`X5Chain::verify_against_trusted_roots`] method.
    pub fn from_pem<S: AsRef<str>>(pem: &[S]) -> Result<Self> {
        let certs = pem
            .iter()
            .enumerate()
            .map(|(i, pem)| {
                X509::from_pem(pem.as_ref().as_bytes())
                    .foreign_err(|| Error::X5Chain)
                    .ctx(|| i)
            })
            .collect::<Result<_>>()
            .ctx(|| "invalid X509 certificate")?;

        Self::new(certs)
    }

    /// Serializes the chain into a sequence of PEM-encoded X509 structure.
    ///
    /// The chain will be ordered in a way that leaf certificate is at first place, then goes its
    /// parent, and so on.
    pub fn to_pem(&self) -> Result<Vec<String>> {
        std::iter::once(&self.leaf)
            .chain(&self.intermediates)
            .map(x509_to_pem)
            .collect()
    }

    /// Constructs a [`X5Chain`] from a string of **concatenated** PEM-encoded strings.
    ///
    /// The chain **MUST BE** ordered in such a way that the leaf certificate is at first place,
    /// then goes its parent, and so on.
    ///
    /// # Warning
    ///
    /// The chain is at this point **NOT VALIDATED** against any trusted root certificate. In order
    /// to validate the chain against a trusted root certificate, use the
    /// [`X5Chain::verify_against_trusted_roots`] method.
    pub fn from_pem_concat(pem: &str) -> Result<Self> {
        Self::new(X509::stack_from_pem(pem.as_bytes()).foreign_err(|| Error::X5Chain)?)
    }

    /// Serializes the chain into a string of **concatenated** PEM-encoded strings.
    ///
    /// The chain will be ordered in such a way that the leaf certificate is at first place,
    /// then goes its parent, and so on.
    pub fn to_pem_concat(&self) -> Result<String> {
        Ok(self.to_pem()?.concat())
    }

    /// Verify the [`X5Chain`] against trusted root certificates.
    ///
    /// The root certificate may be in chain, but it **MUST BE** found in `trust` as well.
    pub fn verify_against_trusted_roots(&self, trust: &X509Trust) -> Result<()> {
        // It is "ugly" that we need to clone here, but if intermediates are kept as a Stack instead
        // of Vec, it messes up a lot of other things, such as Debug, Clone, PartialEq. It is hard
        // to work with it in general.
        let intermediates = chain_to_stack(self.intermediates.clone())?;

        // It is "ugly" that we need to clone here, but if trust is kept as X509Store, instead of
        // Vec, it messes up a lot of other things, such as Debug, Clone. It is hard to work with it
        // as well.
        let trust = certs_to_store(trust.0.clone())?;

        // The `X509StoreContext` doesn't bother if chain has leaf certificate in chain or not. It
        // uses chain as list of untrusted certificates that should help verify target certificate.
        // For more details check https://docs.openssl.org/master/man3/X509_STORE_CTX_new/

        let mut context = X509StoreContext::new().foreign_err(|| Error::X5Chain)?;
        let is_valid = context
            .init(&trust, &self.leaf, &intermediates, |ctx| {
                clean_up_after_openssl(|| ctx.verify_cert())
            })
            .foreign_err(|| Error::X5Chain)?;

        if !is_valid {
            return Err(bherror::Error::root(Error::X5Chain)
                .ctx("Chain validation against trusted root certificates failed")
                .ctx(format!(
                    "OpenSSL error on depth {}: {}",
                    context.error_depth(),
                    context.error()
                )));
        };

        Ok(())
    }

    /// Convert the chain into a list of DER encoded certificates.
    pub fn as_bytes(&self) -> Result<Vec<Vec<u8>>> {
        let mut bytes = Vec::new();

        bytes.push(self.leaf.to_der().foreign_err(|| Error::X5Chain)?);

        for intermediate in &self.intermediates {
            bytes.push(intermediate.to_der().foreign_err(|| Error::X5Chain)?);
        }

        Ok(bytes)
    }

    /// Returns the public key from the leaf certificate.
    pub fn leaf_certificate_key(&self) -> Result<PKey<Public>> {
        self.leaf_certificate()
            .public_key()
            .foreign_err(|| Error::X5Chain)
            .ctx(|| "Failed to access X509 public key")
    }

    /// Returns the leaf certificate.
    pub fn leaf_certificate(&self) -> &X509 {
        &self.leaf
    }

    /// Constructor of test `X5Chain` instance.
    ///
    /// Do NOT use this method for production code, but only tests.
    #[cfg(any(feature = "test-utils", test))]
    pub fn dummy() -> Self {
        let cert = "-----BEGIN CERTIFICATE-----
MIICtzCCAl2gAwIBAgIUXT1Yn4YbUTz3wnpQC8RwexqCuDcwCgYIKoZIzj0EAwIw
ZTELMAkGA1UEBhMCSFIxFDASBgNVBAgMC0dyYWQgWmFncmViMQ8wDQYDVQQHDAZa
YWdyZWIxDTALBgNVBAoMBFRCVEwxETAPBgNVBAsMCFRlYW0gQmVlMQ0wCwYDVQQD
DARyb290MCAXDTI1MTIxMDEzMzMxN1oYDzIxMjUxMTE2MTMzMzE3WjBlMQswCQYD
VQQGEwJIUjEUMBIGA1UECAwLR3JhZCBaYWdyZWIxDzANBgNVBAcMBlphZ3JlYjEN
MAsGA1UECgwEVEJUTDERMA8GA1UECwwIVGVhbSBCZWUxDTALBgNVBAMMBHJvb3Qw
WTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAARkIF0Dd+xzZrIofEhY/Um7TlMLDfpE
og+Moq7unhBn9NT1W/iIVuxiZJR9FTPLctUKjkPiV9rvDvULosK/aRD6o4HoMIHl
MA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFHUFpeGAC0ZFRAQha7ykyHFmqekt
MIGiBgNVHSMEgZowgZeAFHUFpeGAC0ZFRAQha7ykyHFmqektoWmkZzBlMQswCQYD
VQQGEwJIUjEUMBIGA1UECAwLR3JhZCBaYWdyZWIxDzANBgNVBAcMBlphZ3JlYjEN
MAsGA1UECgwEVEJUTDERMA8GA1UECwwIVGVhbSBCZWUxDTALBgNVBAMMBHJvb3SC
FF09WJ+GG1E898J6UAvEcHsagrg3MA4GA1UdDwEB/wQEAwIBBjAKBggqhkjOPQQD
AgNIADBFAiBT9FLacHRRyUmLa8PdGEHbiJaE9p5rg9rzQSptcgfZKgIhAMVDZkEh
m0u5S+/UL3BnCba7Efw3lkBfTBkdKWgrdzEw
-----END CERTIFICATE-----";

        let cert = X509::from_pem(cert.as_bytes()).unwrap();

        let trust = X509Trust::new(vec![cert.clone()]);

        let chain = X5Chain::new(vec![cert]).unwrap();
        chain.verify_against_trusted_roots(&trust).unwrap();

        chain
    }
}

/// A collection of [`X509`] trusted root certificates.
///
/// This is used to verify the authenticity of the [`X5Chain`].
#[derive(Debug, Clone)]
pub struct X509Trust(Vec<X509>);

impl X509Trust {
    /// Create a new [`X509Trust`].
    pub fn new(trust: Vec<X509>) -> Self {
        Self(trust)
    }
}

fn x509_to_pem(x509: &X509) -> Result<String> {
    let bytes = x509
        .to_pem()
        .foreign_err(|| Error::X5Chain)
        .ctx(|| "Failed to convert x509 to pem")?;
    String::from_utf8(bytes)
        .foreign_err(|| Error::X5Chain)
        .ctx(|| "Failed to convert pem bytes to utf-8 string")
}

/// Helper method for converting certificates to `Stack<x509>`.
fn chain_to_stack(chain: impl IntoIterator<Item = X509>) -> Result<Stack<X509>> {
    let mut intermediates = Stack::new().foreign_err(|| Error::X5Chain)?;

    for cert in chain {
        intermediates.push(cert).foreign_err(|| Error::X5Chain)?;
    }

    Ok(intermediates)
}

/// Helper method for converting certificates to `X509Store`.
fn certs_to_store(certificates: impl IntoIterator<Item = X509>) -> Result<X509Store> {
    let mut builder = X509StoreBuilder::new().foreign_err(|| Error::X5Chain)?;
    builder
        .set_flags(X509VerifyFlags::X509_STRICT | X509VerifyFlags::CHECK_SS_SIGNATURE)
        .foreign_err(|| Error::X5Chain)?;

    for cert in certificates {
        builder.add_cert(cert).foreign_err(|| Error::X5Chain)?;
    }

    Ok(builder.build())
}

/// Validates that the certificates in a chain are in order.
///
/// The chain must be ordered in such a way that the leaf certificate is at the
/// first place, then goes its parent, and so on.
///
/// # Note
///
/// This check is not provided through [`X509StoreContext`]. Without this check,
/// chains in reversed order would seem valid, even though they are not.
fn validate_chain_order(chain: &[X509]) -> Result<()> {
    if chain.is_empty() {
        return Err(bherror::Error::root(Error::X5Chain).ctx("chain is empty"));
    }

    let is_ordered = chain
        .windows(2)
        .try_fold(true, |acc, cert_pair| {
            // this is safe since we use the 2-sized sliding window
            let child = &cert_pair[0];
            let parent = &cert_pair[1];

            let is_child = clean_up_after_openssl(|| child.verify(parent.public_key()?.as_ref()))?;

            Ok::<_, openssl::error::ErrorStack>(acc && is_child)
        })
        .foreign_err(|| Error::X5Chain)?;

    if !is_ordered {
        return Err(bherror::Error::root(Error::X5Chain).ctx("invalid chain order"));
    }

    Ok(())
}

impl TryFrom<JwtX5Chain> for X5Chain {
    type Error = bherror::Error<Error>;

    fn try_from(jwt_x5chain: JwtX5Chain) -> Result<Self> {
        let der_certs: Vec<Vec<u8>> = jwt_x5chain
            .into_base64_ders()
            .iter()
            .enumerate()
            .map(|(i, base64_der)| {
                base64::decode_block(base64_der)
                    .foreign_err(|| Error::X5Chain)
                    .ctx(|| i)
            })
            .collect::<Result<_>>()
            .ctx(|| "invalid base64 string")?;

        X5Chain::from_raw_bytes(&der_certs)
    }
}

/// Wrap a closure calling OpenSSL with low-level cleanup to make it safer in an async context.
///
/// Usage: wrap an `openssl` call in a closure and call this function with it.
/// Try to make the closure as small as possible.
fn clean_up_after_openssl<T>(
    f: impl FnOnce() -> std::result::Result<T, ErrorStack>,
) -> std::result::Result<T, ErrorStack> {
    // Early return on error. Hopefully the error stack will be popped here if everything is correct.
    let return_value = f()?;

    // We did not return early, so we should expect that the call "succeeded".
    // In that case, we expect the error stack to be clean, so clear it if it isn't already.
    drop(ErrorStack::get());

    Ok(return_value)
}

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

    // Certificates are generated using following script:
    // ```bash
    //
    // # generate root
    // openssl ecparam -genkey -name secp256r1 -out tbtl_root.key
    // openssl req -new -key tbtl_root.key -out tbtl_root.csr -sha256 \
    //     --subj "/C=HR/ST=Grad Zagreb/L=Zagreb/O=TBTL/OU=Team Bee/CN=root"
    // openssl x509 -req -days 36500 -in tbtl_root.csr -signkey tbtl_root.key \
    //     -out tbtl_root.crt -extensions v3_ca -extfile root.config

    // # generate intermediary
    // openssl ecparam -genkey -name secp256r1 -out tbtl_intermediary.key
    // openssl req -new -key tbtl_intermediary.key -out tbtl_intermediary.csr -sha256 \
    //     --subj "/C=HR/ST=Grad Zagreb/L=Zagreb/O=TBTL/OU=Team Bee/CN=intermediary"
    // openssl x509 -req -in tbtl_intermediary.csr -CA tbtl_root.crt -CAkey tbtl_root.key \
    //     -out tbtl_intermediary.crt -days 36500 -sha256 -extensions v3_intermediate_ca \
    //     -extfile mid.config

    // # generate leaf
    // openssl ecparam -genkey -name secp256r1 -out tbtl_leaf.key
    // openssl req -new -key tbtl_leaf.key -out tbtl_leaf.csr -sha256 \
    //     --subj "/C=HR/ST=Grad Zagreb/L=Zagreb/O=TBTL/OU=Team Bee/CN=leaf"
    // openssl x509 -req -in tbtl_leaf.csr -CA tbtl_intermediary.crt -CAkey tbtl_intermediary.key \
    //     -out tbtl_leaf.crt -days 36500 -sha256 \

    // cat tbtl_leaf.crt tbtl_intermediary.crt tbtl_root.crt
    // ```
    //
    // The `mid.config`:
    // ```
    // [ v3_intermediate_ca ]
    // subjectKeyIdentifier = hash
    // authorityKeyIdentifier = keyid:always,issuer
    // basicConstraints = critical, CA:true, pathlen:0
    // keyUsage = critical, digitalSignature, cRLSign, keyCertSign
    // ```
    //
    // The `root.config`:
    //```
    // [ v3_ca ]
    // basicConstraints        = critical, CA:TRUE
    // subjectKeyIdentifier    = hash
    // authorityKeyIdentifier  = keyid:always, issuer:always
    // keyUsage                = critical, cRLSign, keyCertSign
    //```
    //
    // Certificates are in order: leaf, intermediary, root
    const CERTS: &str = "-----BEGIN CERTIFICATE-----
MIIB0DCCAXUCFA66hLaomVZPSG6NONR/+TborprgMAoGCCqGSM49BAMCMG0xCzAJ
BgNVBAYTAkhSMRQwEgYDVQQIDAtHcmFkIFphZ3JlYjEPMA0GA1UEBwwGWmFncmVi
MQ0wCwYDVQQKDARUQlRMMREwDwYDVQQLDAhUZWFtIEJlZTEVMBMGA1UEAwwMaW50
ZXJtZWRpYXJ5MCAXDTI1MTIxMDEzMzM1MFoYDzIxMjUxMTE2MTMzMzUwWjBlMQsw
CQYDVQQGEwJIUjEUMBIGA1UECAwLR3JhZCBaYWdyZWIxDzANBgNVBAcMBlphZ3Jl
YjENMAsGA1UECgwEVEJUTDERMA8GA1UECwwIVGVhbSBCZWUxDTALBgNVBAMMBGxl
YWYwWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAASbC272RjmKpednBkEvlk2CrEJe
iSgaviOkZ7yaRY83HpgIgG6QqJMyMYiaS8W6IS3jaf/ODTq2/np2a7Zna0u+MAoG
CCqGSM49BAMCA0kAMEYCIQClk1uafXqibcHx6kqbw0xiFcejZMQ1UMU03Xq51ftN
UwIhAJ1NXHQzD3LUehcb9eewIcv7R1SBKsb0R00gVYZ186ps
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
MIICPDCCAeKgAwIBAgIUbxX7OZkOub1NGzC1D88yA6BDK4EwCgYIKoZIzj0EAwIw
ZTELMAkGA1UEBhMCSFIxFDASBgNVBAgMC0dyYWQgWmFncmViMQ8wDQYDVQQHDAZa
YWdyZWIxDTALBgNVBAoMBFRCVEwxETAPBgNVBAsMCFRlYW0gQmVlMQ0wCwYDVQQD
DARyb290MCAXDTI1MTIxMDEzMzMzMloYDzIxMjUxMTE2MTMzMzMyWjBtMQswCQYD
VQQGEwJIUjEUMBIGA1UECAwLR3JhZCBaYWdyZWIxDzANBgNVBAcMBlphZ3JlYjEN
MAsGA1UECgwEVEJUTDERMA8GA1UECwwIVGVhbSBCZWUxFTATBgNVBAMMDGludGVy
bWVkaWFyeTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABEiANYWwYfYs8fnV2Jwk
UrKOoN3NqXk2DoJ86S7VzyIMkDtv2WEL+UX7zzVJzEI8SMfyMnfxQfw6qh0hzePP
qxajZjBkMB0GA1UdDgQWBBQnLZcuND2wi4LLgqEkCG/BTzl0TjAfBgNVHSMEGDAW
gBR1BaXhgAtGRUQEIWu8pMhxZqnpLTASBgNVHRMBAf8ECDAGAQH/AgEAMA4GA1Ud
DwEB/wQEAwIBhjAKBggqhkjOPQQDAgNIADBFAiEA20t9kGAyOgDv/m4/GO09OVV2
EOpMWMcM9L4uOaPcoZgCIAeoA48SV5eN5TukS8UF8Q5Iu6y1zla1/SLb5isn3WYr
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
MIICtzCCAl2gAwIBAgIUXT1Yn4YbUTz3wnpQC8RwexqCuDcwCgYIKoZIzj0EAwIw
ZTELMAkGA1UEBhMCSFIxFDASBgNVBAgMC0dyYWQgWmFncmViMQ8wDQYDVQQHDAZa
YWdyZWIxDTALBgNVBAoMBFRCVEwxETAPBgNVBAsMCFRlYW0gQmVlMQ0wCwYDVQQD
DARyb290MCAXDTI1MTIxMDEzMzMxN1oYDzIxMjUxMTE2MTMzMzE3WjBlMQswCQYD
VQQGEwJIUjEUMBIGA1UECAwLR3JhZCBaYWdyZWIxDzANBgNVBAcMBlphZ3JlYjEN
MAsGA1UECgwEVEJUTDERMA8GA1UECwwIVGVhbSBCZWUxDTALBgNVBAMMBHJvb3Qw
WTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAARkIF0Dd+xzZrIofEhY/Um7TlMLDfpE
og+Moq7unhBn9NT1W/iIVuxiZJR9FTPLctUKjkPiV9rvDvULosK/aRD6o4HoMIHl
MA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFHUFpeGAC0ZFRAQha7ykyHFmqekt
MIGiBgNVHSMEgZowgZeAFHUFpeGAC0ZFRAQha7ykyHFmqektoWmkZzBlMQswCQYD
VQQGEwJIUjEUMBIGA1UECAwLR3JhZCBaYWdyZWIxDzANBgNVBAcMBlphZ3JlYjEN
MAsGA1UECgwEVEJUTDERMA8GA1UECwwIVGVhbSBCZWUxDTALBgNVBAMMBHJvb3SC
FF09WJ+GG1E898J6UAvEcHsagrg3MA4GA1UdDwEB/wQEAwIBBjAKBggqhkjOPQQD
AgNIADBFAiBT9FLacHRRyUmLa8PdGEHbiJaE9p5rg9rzQSptcgfZKgIhAMVDZkEh
m0u5S+/UL3BnCba7Efw3lkBfTBkdKWgrdzEw
-----END CERTIFICATE-----
";

    fn get_certs() -> [X509; 3] {
        X509::stack_from_pem(CERTS.as_bytes())
            .unwrap()
            .try_into()
            .unwrap()
    }

    #[test]
    fn test_validate_chain_order() {
        let [leaf, intermediary, root] = get_certs();

        // valid order
        validate_chain_order(&[leaf.clone(), intermediary.clone(), root.clone()]).unwrap();

        // reversed order is invalid
        let err = validate_chain_order(&[intermediary, leaf]).unwrap_err();
        assert!(matches!(err.error, Error::X5Chain));
        assert_empty_error_stack();

        // empty is invalid
        let err = validate_chain_order(&[]).unwrap_err();
        assert!(matches!(err.error, Error::X5Chain));
        assert_empty_error_stack();

        // single certificate is valid
        validate_chain_order(&[root]).unwrap();
    }

    #[test]
    fn test_from_raw_bytes() {
        let [leaf, intermediary, root] = get_certs();
        let leaf = leaf.to_der().unwrap();
        let intermediary = intermediary.to_der().unwrap();
        let root = root.to_der().unwrap();

        // valid chain
        X5Chain::from_raw_bytes(&[leaf, intermediary, root]).unwrap();

        // empty chain is invalid
        let err = X5Chain::from_raw_bytes(&[]).unwrap_err();
        assert!(matches!(err.error, Error::X5Chain));
        assert_empty_error_stack();

        // invalid bytes
        let err = X5Chain::from_raw_bytes(&[vec![0u8, 1u8], vec![2u8]]).unwrap_err();
        assert!(matches!(err.error, Error::X5Chain));
        assert_empty_error_stack();
    }

    #[test]
    fn test_from_pem() {
        let mut certs = CERTS.split_inclusive("-----END CERTIFICATE-----\n");
        let leaf = certs.next().unwrap();
        let intermediary = certs.next().unwrap();
        let root = certs.next().unwrap();

        // valid chain
        X5Chain::from_pem(&[leaf, intermediary, root]).unwrap();

        // empty chain is invalid
        let err = X5Chain::from_pem::<&str>(&[]).unwrap_err();
        assert!(matches!(err.error, Error::X5Chain));
        assert_empty_error_stack();

        // invalid PEM
        let err = X5Chain::from_pem(&["babadeda", "bla"]).unwrap_err();
        assert!(matches!(err.error, Error::X5Chain));
        assert_empty_error_stack();
    }

    #[test]
    fn test_to_pem() {
        let mut certs = CERTS.split_inclusive("-----END CERTIFICATE-----\n");
        let leaf = certs.next().unwrap();
        let intermediary = certs.next().unwrap();
        let root = certs.next().unwrap();

        let x5chain = X5Chain::from_pem(&[leaf, intermediary, root]).unwrap();

        let pem = x5chain.to_pem().unwrap();

        assert_eq!(pem.concat(), CERTS);

        let x5chain_round_trip = X5Chain::from_pem(&pem).unwrap();

        assert_eq!(x5chain, x5chain_round_trip);
    }

    #[test]
    fn test_from_pem_concat() {
        let mut certs = CERTS.split_inclusive("-----END CERTIFICATE-----\n");
        let leaf = certs.next().unwrap();
        let intermediary = certs.next().unwrap();
        let root = certs.next().unwrap();

        let x5chain_from_pem = X5Chain::from_pem(&[leaf, intermediary, root]).unwrap();

        // valid chain
        let x5chain_from_pem_concat = X5Chain::from_pem_concat(CERTS).unwrap();

        assert_eq!(x5chain_from_pem, x5chain_from_pem_concat);

        // empty chain is invalid
        let err = X5Chain::from_pem_concat("").unwrap_err();
        assert!(matches!(err.error, Error::X5Chain));
        assert_empty_error_stack();

        // invalid PEM
        let err = X5Chain::from_pem_concat("babadedabla").unwrap_err();
        assert!(matches!(err.error, Error::X5Chain));
        assert_empty_error_stack();
    }

    #[test]
    fn test_to_pem_concat() {
        let x5chain = X5Chain::from_pem_concat(CERTS).unwrap();

        assert_eq!(x5chain.to_pem_concat().unwrap(), CERTS);
    }

    #[test]
    fn check_x5chain_relationship() {
        let [leaf, intermediary, root] = get_certs();

        // Chain is valid when chain is in right order
        X5Chain::new(vec![leaf.clone()]).unwrap();
        X5Chain::new(vec![leaf.clone(), intermediary.clone()]).unwrap();
        X5Chain::new(vec![leaf.clone(), intermediary.clone(), root]).unwrap();

        // Chain is not valid if chain is not in right order
        X5Chain::new(vec![intermediary, leaf]).unwrap_err();
        assert_empty_error_stack();

        // Chain cannot be empty
        X5Chain::new(Vec::new()).unwrap_err();
        assert_empty_error_stack();
    }

    #[test]
    fn test_verify_against_trusted_roots() {
        let [leaf, intermediary, root] = get_certs();

        let chain = X5Chain::new(vec![leaf.clone()]).unwrap();

        // Chain is valid when both intermediary and root CA are trusted
        let trusted = X509Trust::new(vec![intermediary.clone(), root.clone()]);
        chain.verify_against_trusted_roots(&trusted).unwrap();

        // Chain is not valid when there are no trusted root CAs (this would
        // pass if `X509VerifyFlags::PARTIAL_CHAIN` was used)
        let trusted = X509Trust::new(vec![intermediary.clone()]);
        chain.verify_against_trusted_roots(&trusted).unwrap_err();
        assert_empty_error_stack();

        // Chain is not valid if leaf cannot be traced to root
        let trusted = X509Trust::new(vec![root.clone()]);
        chain.verify_against_trusted_roots(&trusted).unwrap_err();
        assert_empty_error_stack();

        // Chain is not valid when leaf cannot be traced to any trusted root
        let chain = X5Chain::new(vec![leaf, intermediary, root]).unwrap();
        let trusted = X509Trust::new(Vec::new());
        chain.verify_against_trusted_roots(&trusted).unwrap_err();
        assert_empty_error_stack();
    }

    // Kindly taken from bhcrypto
    fn assert_empty_error_stack() {
        let errors = openssl::error::ErrorStack::get();
        assert!(
            errors.errors().is_empty(),
            "Error stack was non-empty: {:?}",
            errors
        );
    }

    #[test]
    fn test_from_jwtx5chain_to_x5chain() {
        let received: X5Chain = JwtX5Chain::dummy().try_into().unwrap();
        let expected = X5Chain::dummy();

        assert_eq!(received, expected);
    }
}