tsp-ltv 0.2.0

Shared timestamping (RFC 3161) and long-term validation (OCSP, CRL, trust stores) infrastructure for AdES signatures
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
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
//! [`TrustStore`] — a collection of trusted CA certificates (trust anchors).

use crate::error::TrustError;
use der::{Decode, Encode};
use std::path::Path;
use x509_cert::Certificate;

/// Read `(is_ca, pathLenConstraint)` from a certificate's `BasicConstraints`
/// extension. Available in all build configurations (independent of the `ltv`
/// feature) so `verify_chain` can enforce `pathLenConstraint` on the TSP-only
/// token-verification path as well as under `ltv`. A certificate without the
/// extension yields `(false, None)`.
fn basic_constraints(cert: &Certificate) -> Result<(bool, Option<u64>), TrustError> {
    let bc_oid = const_oid::ObjectIdentifier::new_unwrap("2.5.29.19");
    let Some(extensions) = &cert.tbs_certificate.extensions else {
        return Ok((false, None));
    };
    for ext in extensions.iter() {
        if ext.extn_id == bc_oid {
            return crate::der_utils::parse_basic_constraints(ext.extn_value.as_bytes())
                .map_err(TrustError::CertificateParse);
        }
    }
    Ok((false, None))
}

fn is_self_issued(cert: &Certificate) -> bool {
    cert.tbs_certificate.subject == cert.tbs_certificate.issuer
}

/// Read the `keyCertSign` bit (bit 5) from a certificate's `keyUsage`
/// extension (2.5.29.15). Returns `Ok(None)` when the extension is absent and
/// `Ok(Some(bool))` otherwise. Available in all build configurations so
/// `verify_chain` can enforce CA key-usage even without the `ltv` feature
/// (finding L-3).
fn key_cert_sign(cert: &Certificate) -> Result<Option<bool>, TrustError> {
    let ku_oid = const_oid::ObjectIdentifier::new_unwrap("2.5.29.15");
    let Some(extensions) = &cert.tbs_certificate.extensions else {
        return Ok(None);
    };
    let Some(ext) = extensions.iter().find(|e| e.extn_id == ku_oid) else {
        return Ok(None);
    };
    parse_key_cert_sign_bit(ext.extn_value.as_bytes()).map(Some)
}

/// Parse a `keyUsage` extension value (a DER BIT STRING) and return whether the
/// `keyCertSign` bit (bit 5) is set.
///
/// The parse is strict — a malformed encoding is a hard error, kept distinct
/// from the semantic "keyCertSign not set" (`Ok(false)`): the value must be a
/// single BIT STRING with no trailing bytes, a valid unused-bits count (0..=7),
/// all unused bits in the final octet set to 0 (DER, X.690 §11.2.1), and at
/// least one content octet (RFC 5280 §4.2.1.3 requires keyUsage to assert at
/// least one bit, so a content-less BIT STRING is rejected).
fn parse_key_cert_sign_bit(extn_value: &[u8]) -> Result<bool, TrustError> {
    // keyUsage is a BIT STRING: first content byte is the unused-bit count,
    // followed by the bit bytes (MSB-first). keyCertSign is bit 5.
    let (tag, body, rest) = crate::der_utils::parse_tlv_with_rest(extn_value)
        .map_err(|e| TrustError::CertificateParse(format!("keyUsage: {e}")))?;
    if !rest.is_empty() {
        return Err(TrustError::CertificateParse(
            "keyUsage: trailing data after BIT STRING".into(),
        ));
    }
    if tag != 0x03 {
        return Err(TrustError::CertificateParse(format!(
            "keyUsage: expected BIT STRING (0x03), got 0x{tag:02x}"
        )));
    }
    if body.is_empty() {
        return Err(TrustError::CertificateParse(
            "keyUsage: BIT STRING missing the unused-bits octet".into(),
        ));
    }
    let unused_bits = body[0];
    if unused_bits > 7 {
        return Err(TrustError::CertificateParse(format!(
            "keyUsage: invalid unused-bits count {unused_bits} (must be 0..=7)"
        )));
    }
    let bit_bytes = &body[1..];
    if bit_bytes.is_empty() {
        return Err(TrustError::CertificateParse(
            "keyUsage: BIT STRING has no content octets (no key-usage bits set)".into(),
        ));
    }
    // DER (X.690 §11.2.1): every unused bit in the final octet MUST be 0.
    // A non-zero pad is a malformed encoding and is rejected rather than
    // silently masked, keeping encoding errors distinct from the semantic
    // "keyCertSign not set" case.
    if unused_bits > 0 {
        let last = bit_bytes[bit_bytes.len() - 1];
        let pad_mask = (1u8 << unused_bits) - 1;
        if last & pad_mask != 0 {
            return Err(TrustError::CertificateParse(format!(
                "keyUsage: BIT STRING has {unused_bits} non-zero unused bit(s) (not valid DER)"
            )));
        }
    }
    // bit 5 → byte 0, mask 0b0000_0100 (7 - 5 = 2).
    Ok((bit_bytes[0] >> 2) & 1 == 1)
}

/// Validate that an intermediate (issuer) certificate is permitted to sign
/// certificates: it must assert `basicConstraints` `cA:TRUE`, and — *if* it
/// carries a `keyUsage` extension — that extension must assert `keyCertSign`.
///
/// Per RFC 5280 §4.2.1.3 the `keyUsage` extension is **optional**: when absent
/// there is no key-usage restriction and `cA:TRUE` alone authorizes certificate
/// signing, so a missing `keyUsage` is accepted. Only a `keyUsage` that is
/// present *without* `keyCertSign` is rejected (the key must not then be used to
/// verify certificate signatures).
///
/// This is enforced in **every** build configuration (finding L-3): the
/// previous CA-extension check lived in the `ltv`-gated extension module, so a
/// `tsp`-only build skipped intermediate CA validation entirely. `verify_chain`
/// is reached by the RFC 3161 token path even without `ltv`, so the check must
/// not be feature-gated.
fn validate_intermediate_ca_extensions(cert: &Certificate, label: &str) -> Result<(), TrustError> {
    let (is_ca, _) = basic_constraints(cert)?;
    if !is_ca {
        return Err(TrustError::SignatureVerification(format!(
            "{label} is not a CA (basicConstraints cA is not TRUE)"
        )));
    }
    match key_cert_sign(cert)? {
        // keyUsage present and asserts keyCertSign, or keyUsage absent (no
        // restriction — RFC 5280 permits a CA certificate without keyUsage).
        Some(true) | None => Ok(()),
        // keyUsage present but does NOT assert keyCertSign — the key must not be
        // used to verify certificate signatures.
        Some(false) => Err(TrustError::SignatureVerification(format!(
            "{label} keyUsage is present but does not assert keyCertSign"
        ))),
    }
}

/// Enforce `issuer`'s `pathLenConstraint` against the CA certificates in
/// `below` (the certificates subordinate to it in the chain). `label`
/// identifies the issuer in error messages. A parse failure of any
/// `BasicConstraints` on the path is a hard error, not a silent skip.
fn enforce_path_len(
    issuer: &Certificate,
    below: &[Certificate],
    label: &str,
) -> Result<(), TrustError> {
    let (_is_ca, path_len) = basic_constraints(issuer).map_err(|e| {
        TrustError::SignatureVerification(format!(
            "failed to parse basicConstraints for {label}: {e}"
        ))
    })?;
    let Some(max_depth) = path_len else {
        return Ok(());
    };
    // RFC 5280 counts only non-self-issued CA certificates below the
    // constrained issuer. A CA leaf is counted when it is not self-issued (the
    // chain is generic leaf-to-anchor, so `below[0]` is not assumed to be an
    // end-entity); a self-issued rollover CA does not consume the budget.
    let mut subordinate_ca_count = 0u64;
    for cert in below {
        let (is_ca, _) = basic_constraints(cert).map_err(|e| {
            TrustError::SignatureVerification(format!(
                "failed to parse basicConstraints below {label}: {e}"
            ))
        })?;
        if is_ca && !is_self_issued(cert) {
            subordinate_ca_count += 1;
        }
    }
    if subordinate_ca_count > max_depth {
        return Err(TrustError::SignatureVerification(format!(
            "pathLenConstraint ({max_depth}) exceeded for {label}: {subordinate_ca_count} non-self-issued subordinate CA certs below"
        )));
    }
    Ok(())
}

/// A trust anchor: a parsed certificate paired with its DER encoding.
#[derive(Clone)]
struct TrustAnchor {
    cert: Certificate,
    der: Vec<u8>,
}

/// A collection of trusted CA certificates.
///
/// Used to validate that a certificate chain terminates at one of the
/// configured trust anchors.
#[derive(Clone)]
pub struct TrustStore {
    anchors: Vec<TrustAnchor>,
    /// Human-readable label for diagnostics (e.g., "sig", "tsa", "svt").
    label: Option<String>,
    /// Signature-algorithm policy applied during chain verification. Defaults
    /// to strict (weak digests MD5/SHA-1/SHA-224 rejected); opt into legacy via
    /// [`TrustStore::allow_legacy_signatures`].
    signature_policy: crate::crypto::verify::SignaturePolicy,
}

impl TrustStore {
    /// Create an empty trust store.
    pub fn new() -> Self {
        Self {
            anchors: Vec::new(),
            label: None,
            signature_policy: crate::crypto::verify::SignaturePolicy::default(),
        }
    }

    /// Set a diagnostic label for this store.
    pub fn with_label(mut self, label: impl Into<String>) -> Self {
        self.label = Some(label.into());
        self
    }

    /// Set the signature-algorithm policy used by
    /// [`verify_chain`](Self::verify_chain).
    pub fn with_signature_policy(mut self, policy: crate::crypto::verify::SignaturePolicy) -> Self {
        self.signature_policy = policy;
        self
    }

    /// Accept certificates signed with weak/legacy digests (MD5/SHA-1/SHA-224)
    /// during chain verification.
    ///
    /// Off by default — weak digests are rejected. Enable this only to validate
    /// historical material (e.g. legacy XML-DSig interop certificates) whose
    /// risk you have accepted; never for fresh trust decisions.
    pub fn allow_legacy_signatures(mut self) -> Self {
        self.signature_policy = crate::crypto::verify::SignaturePolicy::allow_legacy();
        self
    }

    /// The signature-algorithm policy this store applies during verification.
    pub fn signature_policy(&self) -> crate::crypto::verify::SignaturePolicy {
        self.signature_policy
    }

    /// The diagnostic label, if set.
    pub fn label(&self) -> Option<&str> {
        self.label.as_deref()
    }

    /// Number of trust anchors in this store.
    pub fn len(&self) -> usize {
        self.anchors.len()
    }

    /// Whether the store is empty.
    pub fn is_empty(&self) -> bool {
        self.anchors.is_empty()
    }

    // ── Loading methods ──────────────────────────────────────────────

    /// Load trust anchors from a PEM file (may contain multiple certificates).
    pub fn from_pem_file(path: impl AsRef<Path>) -> Result<Self, TrustError> {
        let data = std::fs::read(path.as_ref()).map_err(TrustError::Io)?;
        let mut store = Self::new();
        store.add_pem_data(&data)?;
        Ok(store)
    }

    /// Load trust anchors from all PEM files (*.pem, *.crt, *.cer) in a directory.
    ///
    /// Non-PEM files and files that fail to parse are silently skipped.
    pub fn from_pem_directory(dir: impl AsRef<Path>) -> Result<Self, TrustError> {
        let dir = dir.as_ref();
        if !dir.is_dir() {
            return Err(TrustError::NotADirectory(dir.display().to_string()));
        }

        let mut store = Self::new();
        let mut entries: Vec<_> = std::fs::read_dir(dir)
            .map_err(TrustError::Io)?
            .filter_map(|e| e.ok())
            .collect();
        entries.sort_by_key(|e| e.file_name());

        for entry in entries {
            let path = entry.path();
            if let Some(ext) = path.extension() {
                let ext = ext.to_string_lossy().to_lowercase();
                if ext == "pem" || ext == "crt" || ext == "cer" {
                    if let Ok(data) = std::fs::read(&path) {
                        // Best effort — skip files that aren't valid PEM
                        let _ = store.add_pem_data(&data);
                    }
                }
            }
        }

        Ok(store)
    }

    /// Add a single trust anchor from DER-encoded bytes.
    pub fn add_der_certificate(&mut self, der: &[u8]) -> Result<(), TrustError> {
        let cert = Certificate::from_der(der)
            .map_err(|e| TrustError::CertificateParse(format!("DER decode failed: {e}")))?;
        self.anchors.push(TrustAnchor {
            cert,
            der: der.to_vec(),
        });
        Ok(())
    }

    /// Add a trust anchor from an already-parsed `Certificate`.
    pub fn add_certificate(&mut self, cert: Certificate) -> Result<(), TrustError> {
        let der = cert
            .to_der()
            .map_err(|e| TrustError::CertificateParse(format!("DER encode failed: {e}")))?;
        self.anchors.push(TrustAnchor { cert, der });
        Ok(())
    }

    /// Add trust anchors from PEM-encoded data (may contain multiple certs).
    pub fn add_pem_data(&mut self, pem_data: &[u8]) -> Result<(), TrustError> {
        let pem_str = std::str::from_utf8(pem_data)
            .map_err(|e| TrustError::CertificateParse(format!("invalid UTF-8 in PEM: {e}")))?;

        let mut found_any = false;

        // Parse PEM by looking for BEGIN/END CERTIFICATE markers
        let mut remaining = pem_str;
        while let Some(begin_pos) = remaining.find("-----BEGIN CERTIFICATE-----") {
            let block_start = &remaining[begin_pos..];
            if let Some(end_pos) = block_start.find("-----END CERTIFICATE-----") {
                let end = end_pos + "-----END CERTIFICATE-----".len();
                let pem_block = &block_start[..end];

                // Decode the base64 between the markers
                let b64: String = pem_block
                    .lines()
                    .filter(|line| !line.starts_with("-----"))
                    .collect();

                use base64::Engine;
                let der_bytes = base64::engine::general_purpose::STANDARD
                    .decode(&b64)
                    .map_err(|e| {
                        TrustError::CertificateParse(format!("base64 decode error: {e}"))
                    })?;

                self.add_der_certificate(&der_bytes)?;
                found_any = true;

                remaining = &block_start[end..];
            } else {
                break;
            }
        }

        if !found_any {
            return Err(TrustError::CertificateParse(
                "no CERTIFICATE blocks found in PEM data".into(),
            ));
        }

        Ok(())
    }

    // ── Query methods ────────────────────────────────────────────────

    /// Check whether a given certificate (DER) is directly one of our anchors.
    ///
    /// Comparison is by raw DER bytes (exact match).
    pub fn contains_der(&self, cert_der: &[u8]) -> bool {
        self.anchors.iter().any(|a| a.der == cert_der)
    }

    /// Find the trust anchor that issued the given certificate, if any.
    ///
    /// Matching is done by comparing the certificate's issuer name with
    /// each anchor's subject name. Returns the **first** name-match.
    /// This does NOT verify the signature —
    /// use [`verify_chain`](Self::verify_chain) for full validation.
    pub fn find_issuer(&self, cert: &Certificate) -> Option<&Certificate> {
        let issuer = &cert.tbs_certificate.issuer;
        self.anchors.iter().find_map(|anchor| {
            if &anchor.cert.tbs_certificate.subject == issuer {
                Some(&anchor.cert)
            } else {
                None
            }
        })
    }

    /// Find **all** trust anchors whose subject matches the given certificate's issuer.
    ///
    /// This is used by [`verify_chain`](Self::verify_chain) so that when multiple
    /// anchors share the same subject name (but have different keys), each can be
    /// tried until one successfully verifies the certificate's signature.
    fn find_all_issuers(&self, cert: &Certificate) -> Vec<&Certificate> {
        let issuer = &cert.tbs_certificate.issuer;
        self.anchors
            .iter()
            .filter_map(|anchor| {
                if &anchor.cert.tbs_certificate.subject == issuer {
                    Some(&anchor.cert)
                } else {
                    None
                }
            })
            .collect()
    }

    /// Find the trust anchor that issued the given DER-encoded certificate.
    pub fn find_issuer_for_der(&self, cert_der: &[u8]) -> Option<&Certificate> {
        let cert = Certificate::from_der(cert_der).ok()?;
        self.find_issuer(&cert)
    }

    /// Get an iterator over all trust anchor certificates.
    pub fn certificates(&self) -> impl Iterator<Item = &Certificate> {
        self.anchors.iter().map(|a| &a.cert)
    }

    /// Get an iterator over all trust anchor DER encodings.
    pub fn certificates_der(&self) -> impl Iterator<Item = &[u8]> {
        self.anchors.iter().map(|a| a.der.as_slice())
    }

    /// Verify a certificate chain from leaf to a trust anchor.
    ///
    /// The chain should be ordered: `[leaf, intermediate_0, ..., intermediate_n]`.
    /// This method checks:
    /// 1. Each certificate's issuer matches the next certificate's subject
    /// 2. The final certificate's issuer matches a trust anchor's subject
    /// 3. Each certificate's signature is verified against its issuer's public key
    /// 4. Time validity (not before / not after) if `validation_time` is provided
    ///
    /// Returns the matching trust anchor on success.
    ///
    /// Signature verification honours this store's
    /// [`signature_policy`](Self::signature_policy): by default a chain
    /// containing a certificate signed with MD5/SHA-1/SHA-224 is rejected.
    /// Build the store with [`allow_legacy_signatures`](Self::allow_legacy_signatures)
    /// to validate such historical chains.
    pub fn verify_chain(
        &self,
        chain: &[Certificate],
        validation_time: Option<der::DateTime>,
    ) -> Result<&Certificate, TrustError> {
        let policy = &self.signature_policy;
        if chain.is_empty() {
            return Err(TrustError::EmptyChain);
        }

        // Check time validity of all certificates in the chain
        if let Some(time) = validation_time {
            for (i, cert) in chain.iter().enumerate() {
                let validity = &cert.tbs_certificate.validity;
                if time < validity.not_before.to_date_time() {
                    return Err(TrustError::NotYetValid {
                        index: i,
                        not_before: validity.not_before.to_date_time(),
                    });
                }
                if time > validity.not_after.to_date_time() {
                    return Err(TrustError::Expired {
                        index: i,
                        not_after: validity.not_after.to_date_time(),
                    });
                }
            }
        }

        // Walk the chain: each cert's issuer must match next cert's subject
        // Track path length for pathLenConstraint enforcement (M-5).
        // CA depth starts at 0 (the leaf at chain[0]) and increments for each
        // intermediate. The anchor (last element) is a root that established
        // the trust; pathLen constraints on it apply to the chain beneath it.
        for i in 0..chain.len().saturating_sub(1) {
            let cert = &chain[i];
            let issuer_cert = &chain[i + 1];

            // Issuer name must match the next certificate's subject name
            if cert.tbs_certificate.issuer != issuer_cert.tbs_certificate.subject {
                return Err(TrustError::ChainBroken {
                    index: i,
                    expected_issuer: format!("{}", cert.tbs_certificate.issuer),
                    found_subject: format!("{}", issuer_cert.tbs_certificate.subject),
                });
            }

            // Verify signature of cert against issuer's public key
            crate::crypto::verify::verify_certificate_signature_with_policy(
                cert,
                issuer_cert,
                policy,
            )?;

            // Validate extensions: intermediates must have CA:TRUE + keyCertSign.
            // Enforced in every build configuration (L-3) — the RFC 3161 token
            // path reaches verify_chain even without the `ltv` feature, so this
            // must not be gated behind it.
            validate_intermediate_ca_extensions(
                issuer_cert,
                &format!("issuer at index {}", i + 1),
            )?;

            // Enforce pathLenConstraint (M-5), in every build configuration —
            // TSP-only token verification reaches `verify_chain` too, so this
            // must not be gated behind `ltv`. Per RFC 5280 §4.2.1.9 the
            // constraint bounds the number of CA certificates that may *follow*
            // this CA toward the leaf in a valid path. The certs below this
            // issuer are `chain[0..=i]`.
            enforce_path_len(
                issuer_cert,
                &chain[0..=i],
                &format!("intermediate index {}", i + 1),
            )?;
        }

        // The last cert in the chain must be issued by a trust anchor
        let last = chain.last().unwrap();

        // Check if the last cert is self-signed and directly in the store
        // (i.e., the chain includes the root itself)
        if last.tbs_certificate.issuer == last.tbs_certificate.subject {
            let last_der = last.to_der().map_err(|e| {
                TrustError::CertificateParse(format!(
                    "failed to encode certificate for anchor lookup: {e}"
                ))
            })?;
            if let Some(anchor) = self.anchors.iter().find(|a| a.der == last_der) {
                // Self-signed cert is directly trusted — verify its self-signature
                crate::crypto::verify::verify_certificate_signature_with_policy(
                    last, last, policy,
                )?;
                return Ok(&anchor.cert);
            }
        }

        let candidates = self.find_all_issuers(last);
        if candidates.is_empty() {
            return Err(TrustError::UntrustedRoot {
                issuer: format!("{}", last.tbs_certificate.issuer),
            });
        }

        // Try each candidate anchor — different anchors may share the same
        // subject name but have different keys (e.g., re-issued roots).
        let mut last_err = None;
        for anchor in &candidates {
            match crate::crypto::verify::verify_certificate_signature_with_policy(
                last, anchor, policy,
            ) {
                Ok(()) => {
                    // Enforce the anchor's own pathLenConstraint. The chain
                    // builder stops before appending the anchor, so this anchor
                    // is not in `chain` and its constraint would otherwise never
                    // be checked. Every certificate in `chain` is subordinate to
                    // it.
                    enforce_path_len(anchor, chain, "trust anchor")?;

                    // Signature verified — now check anchor time validity
                    if let Some(time) = validation_time {
                        let validity = &anchor.tbs_certificate.validity;
                        if time < validity.not_before.to_date_time() {
                            return Err(TrustError::NotYetValid {
                                index: chain.len(),
                                not_before: validity.not_before.to_date_time(),
                            });
                        }
                        if time > validity.not_after.to_date_time() {
                            return Err(TrustError::Expired {
                                index: chain.len(),
                                not_after: validity.not_after.to_date_time(),
                            });
                        }
                    }
                    return Ok(anchor);
                }
                Err(e) => {
                    last_err = Some(e);
                    // Try next candidate
                }
            }
        }

        // All candidates failed signature verification
        Err(last_err.unwrap())
    }
}

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

impl std::fmt::Debug for TrustStore {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("TrustStore")
            .field("label", &self.label)
            .field("anchors", &self.anchors.len())
            .finish()
    }
}

// Signature verification is now in crate::crypto::verify

#[cfg(test)]
mod tests {
    use super::*;
    use crate::crypto::verify::SignaturePolicy;

    /// Build a self-signed root certificate signed with SHA-1 + RSA
    /// (`sha1WithRSAEncryption`) at runtime, so we can exercise the weak-digest
    /// policy without committing a legacy fixture.
    ///
    /// `rsa`'s builder signer only emits SHA-2/3 signature OIDs, so we build a
    /// well-formed TBS with SHA-256, then re-sign that TBS with SHA-1 and
    /// relabel the outer `signatureAlgorithm` — yielding a certificate whose
    /// outer signature is a genuine, valid `sha1WithRSAEncryption` signature.
    fn sha1_self_signed_root() -> Certificate {
        use der::asn1::BitString;
        use der::{Any, Encode};
        use rsa::pkcs1v15::SigningKey;
        use rsa::signature::Keypair;
        use rsa::{Pkcs1v15Sign, RsaPrivateKey};
        use sha1::{Digest, Sha1};
        use sha2::Sha256;
        use spki::AlgorithmIdentifierOwned;
        use x509_cert::builder::{Builder, CertificateBuilder, Profile};
        use x509_cert::name::Name;
        use x509_cert::serial_number::SerialNumber;
        use x509_cert::spki::SubjectPublicKeyInfoOwned;
        use x509_cert::time::Validity;

        let mut rng = rand::thread_rng();
        let key = RsaPrivateKey::new(&mut rng, 2048).expect("RSA keygen");
        let signer = SigningKey::<Sha256>::new(key.clone());
        let spki =
            SubjectPublicKeyInfoOwned::from_key(signer.verifying_key()).expect("SPKI from key");

        let serial = SerialNumber::new(&[0x01]).unwrap();
        let validity =
            Validity::from_now(std::time::Duration::from_secs(3650 * 24 * 3600)).unwrap();
        let subject: Name = "CN=Legacy SHA-1 Root,O=tsp-ltv tests".parse().unwrap();
        let base = CertificateBuilder::new(Profile::Root, serial, validity, subject, spki, &signer)
            .expect("cert builder")
            .build()
            .expect("build base root");

        // Set the inner tbsCertificate.signature to SHA-1 too, then re-sign that
        // TBS with SHA-1. The result is well-formed (outer == inner per RFC 5280
        // §4.1.1.2) and genuinely SHA-1-signed, so it exercises the weak-digest
        // gate rather than the signatureAlgorithm-mismatch check (L-5).
        let sha1_algid = AlgorithmIdentifierOwned {
            oid: crate::crypto::algorithm::OID_SHA1_WITH_RSA,
            // sha1WithRSAEncryption carries an explicit NULL parameter.
            parameters: Some(Any::from_der(&[0x05, 0x00]).unwrap()),
        };
        let mut tbs = base.tbs_certificate.clone();
        tbs.signature = sha1_algid.clone();
        let tbs_der = tbs.to_der().unwrap();
        let hash = Sha1::digest(&tbs_der);
        let sig = key
            .sign(Pkcs1v15Sign::new::<Sha1>(), &hash)
            .expect("SHA-1 RSA sign");
        Certificate {
            tbs_certificate: tbs,
            signature_algorithm: sha1_algid,
            signature: BitString::from_bytes(&sig).unwrap(),
        }
    }

    #[test]
    fn test_verify_chain_rejects_sha1_by_default_and_accepts_with_legacy() {
        let root = sha1_self_signed_root();
        // Sanity: it really is a weak (SHA-1) signature algorithm.
        assert!(crate::crypto::verify::is_weak_signature_oid(
            &root.signature_algorithm.oid
        ));

        let mut store = TrustStore::new();
        store.add_certificate(root.clone()).unwrap();
        let chain = [root];

        // Strict default: the SHA-1 self-signature is refused.
        let err = store.verify_chain(&chain, None).unwrap_err();
        assert!(
            matches!(err, TrustError::WeakAlgorithm(_)),
            "strict store must reject a SHA-1-signed chain, got {err:?}"
        );

        // Legacy opt-in via the builder: the same chain now verifies. This is
        // the reachable path a consumer (e.g. bergshamra's XML-DSig interop
        // fixtures) uses.
        let legacy_store = TrustStore::new()
            .allow_legacy_signatures()
            .with_label("legacy");
        let mut legacy_store = legacy_store;
        legacy_store.add_certificate(chain[0].clone()).unwrap();
        legacy_store
            .verify_chain(&chain, None)
            .expect("legacy store must accept a SHA-1-signed chain");

        assert_eq!(
            legacy_store.signature_policy(),
            SignaturePolicy::allow_legacy()
        );
        assert_eq!(store.signature_policy(), SignaturePolicy::strict());
    }

    /// Issue a certificate with the given builder `profile`, subject key, and
    /// issuer signer (the parent CA's key; for a root, pass its own key). Built
    /// at runtime so no fixtures are committed.
    fn issue_cert(
        profile: x509_cert::builder::Profile,
        subject: &str,
        subject_key: &rsa::RsaPrivateKey,
        issuer_signer: &rsa::pkcs1v15::SigningKey<sha2::Sha256>,
    ) -> Certificate {
        use rsa::pkcs1v15::SigningKey;
        use rsa::signature::Keypair;
        use sha2::Sha256;
        use x509_cert::builder::{Builder, CertificateBuilder};
        use x509_cert::name::Name;
        use x509_cert::serial_number::SerialNumber;
        use x509_cert::spki::SubjectPublicKeyInfoOwned;
        use x509_cert::time::Validity;

        let subject_signer = SigningKey::<Sha256>::new(subject_key.clone());
        let spki = SubjectPublicKeyInfoOwned::from_key(subject_signer.verifying_key())
            .expect("SPKI from key");
        let serial = SerialNumber::new(&[0x01]).unwrap();
        let validity =
            Validity::from_now(std::time::Duration::from_secs(3650 * 24 * 3600)).unwrap();
        let subject: Name = subject.parse().unwrap();
        CertificateBuilder::new(profile, serial, validity, subject, spki, issuer_signer)
            .expect("cert builder")
            .build()
            .expect("build cert")
    }

    /// Build a `[leaf_subca, mid_subca, root]` chain where `mid_subca` carries
    /// `pathLenConstraint = path_len`. `chain[0]` is itself a CA — the case the
    /// old `subordinate_ca_count = i` shortcut undercounted (it never counted
    /// the leaf). Returns `(store_with_root_anchor, chain)`.
    fn ca_leaf_chain(path_len: Option<u8>) -> (TrustStore, Vec<Certificate>) {
        use rsa::pkcs1v15::SigningKey;
        use rsa::RsaPrivateKey;
        use sha2::Sha256;
        use x509_cert::builder::Profile;
        use x509_cert::name::Name;

        let mut rng = rand::thread_rng();
        let root_key = RsaPrivateKey::new(&mut rng, 2048).expect("root key");
        let mid_key = RsaPrivateKey::new(&mut rng, 2048).expect("mid key");
        let leaf_key = RsaPrivateKey::new(&mut rng, 2048).expect("leaf key");

        let root_signer = SigningKey::<Sha256>::new(root_key.clone());
        let mid_signer = SigningKey::<Sha256>::new(mid_key.clone());

        let root_name = "CN=PathLen Root,O=tsp-ltv tests";
        let mid_name = "CN=PathLen Mid,O=tsp-ltv tests";
        let leaf_name = "CN=PathLen Leaf CA,O=tsp-ltv tests";
        let root_issuer: Name = root_name.parse().unwrap();
        let mid_issuer: Name = mid_name.parse().unwrap();

        let root = issue_cert(Profile::Root, root_name, &root_key, &root_signer);
        let mid = issue_cert(
            Profile::SubCA {
                issuer: root_issuer,
                path_len_constraint: path_len,
            },
            mid_name,
            &mid_key,
            &root_signer,
        );
        // leaf is itself a CA (SubCA), so chain[0] is a CA certificate.
        let leaf = issue_cert(
            Profile::SubCA {
                issuer: mid_issuer,
                path_len_constraint: None,
            },
            leaf_name,
            &leaf_key,
            &mid_signer,
        );

        let mut store = TrustStore::new();
        store.add_certificate(root.clone()).unwrap();
        (store, vec![leaf, mid, root])
    }

    #[test]
    fn test_verify_chain_pathlen_rejects_ca_leaf_below_zero_constraint() {
        // mid_subca has pathLenConstraint = 0, but a CA (leaf_subca) sits below
        // it. The leaf must be counted, so the chain is rejected.
        let (store, chain) = ca_leaf_chain(Some(0));
        let err = store
            .verify_chain(&chain, None)
            .expect_err("pathLen=0 with a CA leaf below must be rejected");
        assert!(
            matches!(err, TrustError::SignatureVerification(ref m) if m.contains("pathLenConstraint")),
            "expected pathLenConstraint rejection, got: {err:?}"
        );
    }

    #[test]
    fn test_verify_chain_pathlen_allows_ca_leaf_within_constraint() {
        // Same chain but pathLenConstraint = 1 permits exactly one CA below the
        // mid CA — the chain verifies (guards against over-rejection).
        let (store, chain) = ca_leaf_chain(Some(1));
        store
            .verify_chain(&chain, None)
            .expect("pathLen=1 with one CA leaf below must be accepted");
    }

    /// Build a chain `[leaf_subca, mid_subca]` that does NOT include the root,
    /// with the self-signed root anchor carrying `pathLenConstraint = root_plen`.
    /// The anchor lives only in the store, so its constraint is reached via the
    /// `find_all_issuers` path rather than the in-chain walk.
    fn anchor_only_chain(root_plen: Option<u8>) -> (TrustStore, Vec<Certificate>) {
        use rsa::pkcs1v15::SigningKey;
        use rsa::RsaPrivateKey;
        use sha2::Sha256;
        use x509_cert::builder::Profile;
        use x509_cert::name::Name;

        let mut rng = rand::thread_rng();
        let root_key = RsaPrivateKey::new(&mut rng, 2048).expect("root key");
        let mid_key = RsaPrivateKey::new(&mut rng, 2048).expect("mid key");
        let leaf_key = RsaPrivateKey::new(&mut rng, 2048).expect("leaf key");

        let root_signer = SigningKey::<Sha256>::new(root_key.clone());
        let mid_signer = SigningKey::<Sha256>::new(mid_key.clone());

        let root_name = "CN=Anchor Root,O=tsp-ltv tests";
        let mid_name = "CN=Anchor Mid,O=tsp-ltv tests";
        let leaf_name = "CN=Anchor Leaf CA,O=tsp-ltv tests";
        let root_issuer: Name = root_name.parse().unwrap();
        let mid_issuer: Name = mid_name.parse().unwrap();

        // Self-signed root WITH a pathLenConstraint: Profile::Root forces None,
        // so build it as a SubCA whose issuer is its own name.
        let root = issue_cert(
            Profile::SubCA {
                issuer: root_issuer.clone(),
                path_len_constraint: root_plen,
            },
            root_name,
            &root_key,
            &root_signer,
        );
        let mid = issue_cert(
            Profile::SubCA {
                issuer: root_issuer,
                path_len_constraint: None,
            },
            mid_name,
            &mid_key,
            &root_signer,
        );
        let leaf = issue_cert(
            Profile::SubCA {
                issuer: mid_issuer,
                path_len_constraint: None,
            },
            leaf_name,
            &leaf_key,
            &mid_signer,
        );

        let mut store = TrustStore::new();
        store.add_certificate(root).unwrap();
        // Chain stops below the anchor — the root is only in the store.
        (store, vec![leaf, mid])
    }

    #[test]
    fn test_verify_chain_anchor_pathlen_enforced() {
        // The root anchor (not in the chain) is constrained to pathLen=0 but two
        // subordinate CAs sit below it. The anchor's constraint must be checked.
        let (store, chain) = anchor_only_chain(Some(0));
        let err = store
            .verify_chain(&chain, None)
            .expect_err("anchor pathLen=0 with CAs below must be rejected");
        assert!(
            matches!(err, TrustError::SignatureVerification(ref m) if m.contains("pathLenConstraint") && m.contains("trust anchor")),
            "expected trust-anchor pathLenConstraint rejection, got: {err:?}"
        );
    }

    #[test]
    fn test_verify_chain_anchor_pathlen_within_constraint() {
        // pathLen=2 permits the two subordinate CAs — chain verifies.
        let (store, chain) = anchor_only_chain(Some(2));
        store
            .verify_chain(&chain, None)
            .expect("anchor pathLen=2 with two CAs below must be accepted");
    }

    /// Build a chain containing a self-issued CA certificate below a root
    /// anchor. Self-issued rollover CAs do not consume pathLenConstraint.
    fn self_issued_ca_below_anchor(root_plen: Option<u8>) -> (TrustStore, Vec<Certificate>) {
        use rsa::pkcs1v15::SigningKey;
        use rsa::RsaPrivateKey;
        use sha2::Sha256;
        use x509_cert::builder::Profile;
        use x509_cert::name::Name;

        let mut rng = rand::thread_rng();
        let root_key = RsaPrivateKey::new(&mut rng, 2048).expect("root key");
        let rollover_key = RsaPrivateKey::new(&mut rng, 2048).expect("rollover key");

        let root_signer = SigningKey::<Sha256>::new(root_key.clone());

        let root_name = "CN=Rollover Root,O=tsp-ltv tests";
        let root_issuer: Name = root_name.parse().unwrap();

        let root = issue_cert(
            Profile::SubCA {
                issuer: root_issuer.clone(),
                path_len_constraint: root_plen,
            },
            root_name,
            &root_key,
            &root_signer,
        );
        let rollover = issue_cert(
            Profile::SubCA {
                issuer: root_issuer,
                path_len_constraint: None,
            },
            root_name,
            &rollover_key,
            &root_signer,
        );

        let mut store = TrustStore::new();
        store.add_certificate(root).unwrap();
        (store, vec![rollover])
    }

    #[test]
    fn test_verify_chain_pathlen_ignores_self_issued_ca_below_anchor() {
        // A self-issued rollover CA below the anchor does not consume the
        // anchor's pathLen budget, so pathLen=0 remains valid.
        let (store, chain) = self_issued_ca_below_anchor(Some(0));
        store
            .verify_chain(&chain, None)
            .expect("self-issued CA below anchor must not consume pathLenConstraint");
    }

    #[test]
    fn test_parse_key_cert_sign_bit() {
        use crate::der_utils::encode_tlv;

        // BIT STRING { unused=1, 0x04 } -> keyCertSign (bit 5) set.
        assert!(parse_key_cert_sign_bit(&encode_tlv(0x03, &[0x01, 0x04])).unwrap());
        // BIT STRING { unused=7, 0x80 } -> digitalSignature only; keyCertSign not set.
        assert!(!parse_key_cert_sign_bit(&encode_tlv(0x03, &[0x07, 0x80])).unwrap());

        // Not a BIT STRING.
        assert!(parse_key_cert_sign_bit(&encode_tlv(0x04, &[0x01, 0x04])).is_err());
        // Trailing data after the BIT STRING is rejected (parse_tlv would ignore it).
        let mut trailing = encode_tlv(0x03, &[0x01, 0x04]);
        trailing.extend_from_slice(&[0x05, 0x00]); // a stray NULL
        assert!(parse_key_cert_sign_bit(&trailing).is_err());
        // Empty value (no unused-bits octet) is rejected.
        assert!(parse_key_cert_sign_bit(&encode_tlv(0x03, &[])).is_err());
        // Only the unused-bits octet, no content octets -> rejected (not Some(false)).
        assert!(parse_key_cert_sign_bit(&encode_tlv(0x03, &[0x00])).is_err());
        // Invalid unused-bits count (>7) is rejected.
        assert!(parse_key_cert_sign_bit(&encode_tlv(0x03, &[0x08, 0x04])).is_err());
        // Non-zero unused bits in the final octet are invalid DER (X.690
        // §11.2.1) and rejected: unused=1 but the low bit of 0x05 is set.
        assert!(parse_key_cert_sign_bit(&encode_tlv(0x03, &[0x01, 0x05])).is_err());
        // keyCertSign bit set *and* a clean (zero) unused-bit pad still parses.
        assert!(parse_key_cert_sign_bit(&encode_tlv(0x03, &[0x01, 0x06])).unwrap());
    }

    #[test]
    fn test_verify_chain_rejects_non_ca_intermediate() {
        // L-3: an intermediate that is not a CA (basicConstraints CA:FALSE) must
        // be rejected by verify_chain in every build configuration, even when its
        // signature over the leaf is valid. This check used to be gated behind
        // the `ltv` feature.
        use rsa::pkcs1v15::SigningKey;
        use rsa::RsaPrivateKey;
        use sha2::Sha256;
        use x509_cert::builder::Profile;
        use x509_cert::name::Name;

        let mut rng = rand::thread_rng();
        let root_key = RsaPrivateKey::new(&mut rng, 2048).expect("root key");
        let mid_key = RsaPrivateKey::new(&mut rng, 2048).expect("mid key");
        let leaf_key = RsaPrivateKey::new(&mut rng, 2048).expect("leaf key");

        let root_signer = SigningKey::<Sha256>::new(root_key.clone());
        let mid_signer = SigningKey::<Sha256>::new(mid_key.clone());

        let root_name = "CN=NonCA Root,O=tsp-ltv tests";
        let mid_name = "CN=NonCA Mid,O=tsp-ltv tests";
        let leaf_name = "CN=NonCA Leaf,O=tsp-ltv tests";
        let root_issuer: Name = root_name.parse().unwrap();
        let mid_issuer: Name = mid_name.parse().unwrap();

        let root = issue_cert(Profile::Root, root_name, &root_key, &root_signer);
        // mid is an end-entity profile (CA:FALSE) but is (mis)used as an issuer.
        let mid = issue_cert(
            Profile::Leaf {
                issuer: root_issuer,
                enable_key_agreement: false,
                enable_key_encipherment: false,
            },
            mid_name,
            &mid_key,
            &root_signer,
        );
        let leaf = issue_cert(
            Profile::Leaf {
                issuer: mid_issuer,
                enable_key_agreement: false,
                enable_key_encipherment: false,
            },
            leaf_name,
            &leaf_key,
            &mid_signer,
        );

        let mut store = TrustStore::new();
        store.add_certificate(root.clone()).unwrap();
        let chain = vec![leaf, mid, root];

        let err = store
            .verify_chain(&chain, None)
            .expect_err("a non-CA intermediate must be rejected");
        assert!(
            matches!(err, TrustError::SignatureVerification(ref m) if m.contains("not a CA")),
            "expected non-CA intermediate rejection, got: {err:?}"
        );
    }
}