tightbeam-rs 0.9.0

A secure, high-performance messaging protocol library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
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
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
//! Certificate trust store
//!
//! This module provides a trait-based abstraction for certificate trust
//! verification, allowing custom implementations for different environments.

use core::fmt::Debug;

#[cfg(not(feature = "std"))]
use alloc::vec::Vec;

use crate::crypto::x509::error::CertificateValidationError;
use crate::crypto::x509::policy::CertificateValidation;
use crate::crypto::x509::Certificate;

#[cfg(feature = "std")]
use crate::crypto::x509::utils::validate_certificate_expiry;
#[cfg(feature = "std")]
use crate::der::Encode;

#[cfg(feature = "std")]
mod std_imports {
	pub use std::collections::{HashMap, HashSet};
	pub use std::sync::Arc;

	pub use crate::cms::signed_data::SignerIdentifier;
	pub use crate::crypto::hash::Digest;
	pub use crate::crypto::hash::Sha3_256;
	pub use crate::crypto::policy::VerificationPolicy;
	pub use crate::crypto::x509::ext::pkix::{BasicConstraints, KeyUsage, KeyUsages};
	pub use crate::crypto::x509::name::Name;
	pub use crate::crypto::x509::utils::{certificate_extension, ensure_signature_algorithm_consistency};
	pub use crate::der::oid::AssociatedOid;
}

#[cfg(feature = "std")]
use std_imports::*;

/// Fingerprint type: SHA3-256 hash (32 bytes)
pub type Fingerprint = [u8; 32];

/// Revocation status check for certificates within a certification path.
///
/// Consulted once per certificate during path validation, satisfying the
/// revocation step of RFC 5280 ยง6.1.3(a)(3). Shipped implementations are
/// [`NoRevocation`] and [`StaticRevocationList`].
///
/// Implementations MUST fail closed: return
/// [`CertificateValidationError::CertificateRevoked`] for a revoked
/// certificate and [`CertificateValidationError::RevocationStatusUnknown`]
/// when status cannot be established.
pub trait RevocationChecker: Debug + Send + Sync {
	/// Check the revocation status of `cert`, issued by `issuer`.
	///
	/// Trust anchors are checked with themselves as issuer.
	fn check(&self, issuer: &Certificate, cert: &Certificate) -> Result<(), CertificateValidationError>;
}

/// [`RevocationChecker`] that treats every certificate as not revoked.
///
/// Default for [`CertificateTrustStore`]. Sound only for a closed PKI with
/// short-lived certificates: a compromised key stays trusted until the
/// certificate expires or the operator re-pins the trust store.
#[derive(Debug, Clone, Copy, Default)]
pub struct NoRevocation;

impl RevocationChecker for NoRevocation {
	fn check(&self, _issuer: &Certificate, _cert: &Certificate) -> Result<(), CertificateValidationError> {
		Ok(())
	}
}

/// Operator-pushed static revocation denylist.
///
/// Revokes by certificate fingerprint (exact) or by issuer-scoped serial number.
#[cfg(feature = "std")]
#[derive(Debug, Default)]
pub struct StaticRevocationList {
	fingerprints: HashSet<Fingerprint>,
	/// Revoked serial numbers keyed by issuer DN DER: RFC 5280 ยง4.1.2.2
	/// guarantees serial uniqueness only within one CA, so an unscoped
	/// serial would falsely revoke unrelated certificates.
	serials: HashMap<Vec<u8>, HashSet<Vec<u8>>>,
}

#[cfg(feature = "std")]
impl StaticRevocationList {
	/// Revoke a certificate by its SHA3-256 DER fingerprint.
	pub fn with_fingerprint(mut self, fingerprint: Fingerprint) -> Self {
		self.fingerprints.insert(fingerprint);
		self
	}

	/// Revoke a certificate directly (computes its fingerprint).
	pub fn with_certificate(self, cert: &Certificate) -> Result<Self, CertificateValidationError> {
		let fingerprint = CertificateTrustStore::to_fingerprint(cert)?;
		Ok(self.with_fingerprint(fingerprint))
	}

	/// Revoke by issuer and raw serial-number bytes (CRL entry scope).
	pub fn with_serial(mut self, issuer: &Name, serial: impl AsRef<[u8]>) -> Result<Self, CertificateValidationError> {
		self.serials
			.entry(issuer.to_der()?)
			.or_default()
			.insert(serial.as_ref().to_vec());
		Ok(self)
	}
}

#[cfg(feature = "std")]
impl RevocationChecker for StaticRevocationList {
	fn check(&self, _issuer: &Certificate, cert: &Certificate) -> Result<(), CertificateValidationError> {
		let fingerprint = CertificateTrustStore::to_fingerprint(cert)?;
		if self.fingerprints.contains(&fingerprint) {
			return Err(CertificateValidationError::CertificateRevoked);
		}
		if self.serials.is_empty() {
			return Ok(());
		}

		let issuer_der = cert.tbs_certificate.issuer.to_der()?;
		let revoked = self
			.serials
			.get(issuer_der.as_slice())
			.is_some_and(|serials| serials.contains(cert.tbs_certificate.serial_number.as_bytes()));
		if revoked {
			return Err(CertificateValidationError::CertificateRevoked);
		}

		Ok(())
	}
}

/// Trait for certificate trust verification.
///
/// Extends `CertificateValidation` with trust-based operations.
/// Implementations can use fingerprints, PKI chains, or custom logic.
#[cfg(feature = "std")]
pub trait CertificateTrust: CertificateValidation + Debug + Send + Sync {
	/// Check if a certificate is trusted.
	fn is_trusted(&self, cert: &Certificate) -> bool;

	/// Verify a certificate chain (partial RFC 5280 ยง6.1 path validation).
	///
	/// Performs:
	/// 1. Root trust anchor check (RFC 5280 ยง6.1.1)
	/// 2. Expiry validation for all certificates (RFC 5280 ยง6.1.3(a)(2))
	/// 3. Rejection of unprocessed critical extensions (RFC 5280 ยง4.2, ยง6.1.3(f))
	/// 4. Issuer/subject DN chaining (RFC 5280 ยง6.1.3(a)(4))
	/// 5. Cryptographic signature verification (RFC 5280 ยง6.1.3(a)(1))
	/// 6. Issuer `basicConstraints.cA` / `keyUsage.keyCertSign` and
	///    `pathLenConstraint` (RFC 5280 ยง6.1.4(k),(l),(m),(n))
	///
	/// Not enforced: name constraints/policies (ยง6.1.3-ยง6.1.5) and
	/// CRL/OCSP fetching (revocation runs through the configured
	/// [`RevocationChecker`]). See
	/// <https://datatracker.ietf.org/doc/html/rfc5280#section-6.1>.
	///
	/// # Arguments
	/// * `chain` - Certificate chain ordered root -> intermediate -> leaf
	///
	/// # Returns
	/// - `Ok(())` if the chain is valid and terminates at a trusted root
	/// - `Err(_)` if validation fails
	fn verify_chain(&self, chain: &[Certificate]) -> Result<(), CertificateValidationError>;

	/// Find a certificate by SignerInfo.
	///
	/// Used for frame signature verification - looks up the signer's certificate
	/// using the SignerInfo's identifier and digest algorithm.
	///
	/// # Arguments
	/// * `signer_info` - SignerInfo from the frame's nonrepudiation field
	///
	/// # Returns
	/// - `Some(&Certificate)` if a matching certificate is found
	/// - `None` if no certificate matches
	fn find_by_signer_info(&self, signer_info: &crate::SignerInfo) -> Option<&Certificate>;

	/// Get the verification policy for signature operations.
	fn to_policy_ref(&self) -> &dyn VerificationPolicy;
}

/// Trait for certificate trust verification (no_std version without SignerIdentifier).
///
/// This crate ships no no_std implementation of this trait
/// ([`CertificateTrustStore`] is `std`-only); it exists so downstream no_std
/// consumers can supply their own store. Implementations decide how much of
/// RFC 5280 ยง6.1 path validation `verify_chain` performs.
#[cfg(not(feature = "std"))]
pub trait CertificateTrust: CertificateValidation + Debug + Send + Sync {
	/// Check if a certificate is trusted.
	fn is_trusted(&self, cert: &Certificate) -> bool;

	/// Verify a certificate chain.
	fn verify_chain(&self, chain: &[Certificate]) -> Result<(), CertificateValidationError>;
}

/// Builder trait for constructing trust stores.
///
/// Validates structural correctness (expiry, issuer/subject chaining) on add.
/// The built store handles cryptographic verification at runtime.
pub trait TrustBuilder: Sized {
	/// The trust store type this builder produces
	type Store: CertificateTrust;

	/// Add a certificate chain with structural validation.
	///
	/// Validates expiry and issuer/subject chaining. All certificates
	/// in the chain are added to the trust store.
	fn with_chain(self, chain: Vec<Certificate>) -> Result<Self, CertificateValidationError>;

	/// Add a single trusted certificate (leaf certificate).
	fn with_certificate(self, cert: Certificate) -> Result<Self, CertificateValidationError>;

	/// Build the sealed trust store.
	fn build(self) -> Self::Store;
}

/// Reject certificates bearing critical extensions this validator does not
/// process.
///
/// RFC 5280 ยง4.2: a certificate-using system MUST reject a certificate when
/// it encounters a critical extension it cannot process.
/// ยง6.1.3(f) applies the same rule during path validation:
/// <https://datatracker.ietf.org/doc/html/rfc5280#section-4.2>.
///
/// Processed by this validator: `basicConstraints` (ยง4.2.1.9) and `keyUsage`
/// (ยง4.2.1.3). Any other critical extension -- including `nameConstraints`
/// and `policyConstraints`, which are not implemented -- fails closed.
#[cfg(feature = "std")]
fn ensure_critical_extensions_processed(cert: &Certificate) -> Result<(), CertificateValidationError> {
	let Some(extensions) = cert.tbs_certificate.extensions.as_ref() else {
		return Ok(());
	};

	for extension in extensions {
		let processed = extension.extn_id == BasicConstraints::OID || extension.extn_id == KeyUsage::OID;
		if extension.critical && !processed {
			return Err(CertificateValidationError::UnprocessedCriticalExtension(extension.extn_id));
		}
	}

	Ok(())
}

/// Reject a presented identity certificate that asserts the CA bit.
///
/// Not an RFC 5280 requirement. The terminal certificate of a multi-certificate
/// path is the identity being authenticated, and an identity carrying
/// `basicConstraints.cA` (ยง4.2.1.9) is misissued for that role.
#[cfg(feature = "std")]
fn ensure_terminal_is_end_entity(path: &[&Certificate]) -> Result<(), CertificateValidationError> {
	let [_, .., terminal] = path else {
		return Ok(());
	};

	match certificate_extension::<BasicConstraints>(terminal)? {
		Some(basic_constraints) if basic_constraints.ca => Err(CertificateValidationError::EndEntityIsCa),
		_ => Ok(()),
	}
}

/// Enforce that an issuer certificate is permitted to sign certificates.
///
/// RFC 5280 ยง6.1.4(k): the issuer's `basicConstraints` extension MUST be
/// present with `cA` asserted. ยง6.1.4(n): when a `keyUsage` extension is
/// present it MUST assert `keyCertSign`.
/// <https://datatracker.ietf.org/doc/html/rfc5280#section-6.1.4>.
///
/// Stricter than the RFC: (k) is version-conditional there (v1/v2 CAs may be
/// verified out-of-band); this enforces it unconditionally, so v1/v2 CA
/// certificates are rejected (see [`CertificateTrustStore::validate_path`]).
#[cfg(feature = "std")]
fn ensure_issuer_is_ca(issuer: &Certificate) -> Result<(), CertificateValidationError> {
	match certificate_extension::<BasicConstraints>(issuer)? {
		Some(basic_constraints) if basic_constraints.ca => {}
		_ => return Err(CertificateValidationError::IssuerNotCa),
	}

	if let Some(key_usage) = certificate_extension::<KeyUsage>(issuer)? {
		if !key_usage.0.contains(KeyUsages::KeyCertSign) {
			return Err(CertificateValidationError::MissingKeyCertSign);
		}
	}

	Ok(())
}

/// Enforce `pathLenConstraint` over an ordered chain (root -> leaf).
///
/// RFC 5280 ยง6.1.4(l),(m): a CA certificate's `pathLenConstraint` bounds the
/// number of intermediate certificates that may follow it in the path before
/// the end-entity. `None` imposes no limit.
/// <https://datatracker.ietf.org/doc/html/rfc5280#section-6.1.4>.
///
/// Stricter than the RFC: self-issued intermediates count toward the bound
/// ((l) exempts them; see [`CertificateTrustStore::validate_path`]).
#[cfg(feature = "std")]
fn ensure_path_len(chain: &[&Certificate]) -> Result<(), CertificateValidationError> {
	for (index, cert) in chain.iter().enumerate() {
		let Some(basic_constraints) = certificate_extension::<BasicConstraints>(cert)? else {
			continue;
		};
		let Some(max_intermediates) = basic_constraints.path_len_constraint else {
			continue;
		};

		// Certificates strictly between this CA and the end-entity leaf.
		let intermediates_below = chain.len().saturating_sub(index + 2);
		if intermediates_below as u64 > u64::from(max_intermediates) {
			return Err(CertificateValidationError::PathLenExceeded);
		}
	}

	Ok(())
}

// ============================================================================
// CertificateTrustStore Implementation
// ============================================================================

/// SKID type: first 20 bytes of hash (RFC 5280)
pub type Skid = [u8; 20];

/// Built-in trust store with cryptographic signature verification.
///
/// Uses a `VerificationPolicy` for runtime signature verification of
/// certificate chains. Stores trusted certificate fingerprints in a
/// `HashSet` for O(1) lookup.
#[cfg(feature = "std")]
pub struct CertificateTrustStore {
	/// Trusted certificate fingerprints
	fingerprints: HashSet<Fingerprint>,
	/// Full certificates indexed by fingerprint
	certificates: HashMap<Fingerprint, Certificate>,
	/// Pre-computed SKID
	skid_index: HashMap<Skid, Fingerprint>,
	/// Verification policy for signature verification
	policy: Arc<dyn VerificationPolicy>,
	/// Revocation checker consulted during path validation
	revocation: Arc<dyn RevocationChecker>,
}

#[cfg(feature = "std")]
impl CertificateTrustStore {
	/// Compute the SHA3-256 fingerprint of a certificate's DER encoding.
	pub fn to_fingerprint(cert: &Certificate) -> Result<Fingerprint, CertificateValidationError> {
		let der_bytes = cert.to_der()?;
		let hash = Sha3_256::digest(&der_bytes);
		let mut fp = [0u8; 32];
		fp.copy_from_slice(hash.as_ref());

		Ok(fp)
	}

	/// Get a certificate by its fingerprint.
	pub fn to_certificate_ref(&self, fingerprint: &Fingerprint) -> Option<&Certificate> {
		self.certificates.get(fingerprint)
	}

	/// Get the number of trusted certificates.
	pub fn len(&self) -> usize {
		self.fingerprints.len()
	}

	/// Check if the trust store is empty.
	pub fn is_empty(&self) -> bool {
		self.fingerprints.is_empty()
	}

	/// Validate an ordered certification path (issuer-first: anchor -> leaf).
	///
	/// [RFC 5280 ยง6.1](https://datatracker.ietf.org/doc/html/rfc5280#section-6.1)
	/// checks shared by both public entry points
	/// ([`CertificateValidation::evaluate`] and
	/// [`CertificateTrust::verify_chain`]) so the two cannot diverge on
	/// validation strength (e.g. `pathLenConstraint`).
	///
	/// Performs, over the whole path:
	/// 1. Validity period ([RFC 5280 ยง6.1.3(a)(2)](https://datatracker.ietf.org/doc/html/rfc5280#section-6.1.3))
	/// 2. Rejection of unprocessed critical extensions ([RFC 5280 ยง4.2, ยง6.1.3(f)](https://datatracker.ietf.org/doc/html/rfc5280#section-4.2))
	/// 3. Algorithm-identifier consistency ([RFC 5280 ยง4.1.1.2](https://datatracker.ietf.org/doc/html/rfc5280#section-4.1.1.2))
	/// 4. Issuer/subject name chaining ([RFC 5280 ยง6.1.3(a)(4)](https://datatracker.ietf.org/doc/html/rfc5280#section-6.1.3))
	/// 5. Issuer `basicConstraints.cA` / `keyUsage.keyCertSign` ([RFC 5280 ยง6.1.4(k),(n)](https://datatracker.ietf.org/doc/html/rfc5280#section-6.1.4))
	/// 6. Cryptographic signature verification ([RFC 5280 ยง6.1.3(a)(1)](https://datatracker.ietf.org/doc/html/rfc5280#section-6.1.3))
	/// 7. Revocation via the configured [`RevocationChecker`]
	///    ([RFC 5280 ยง6.1.3(a)(3)](https://datatracker.ietf.org/doc/html/rfc5280#section-6.1.3))
	/// 8. `pathLenConstraint` ([RFC 5280 ยง6.1.4(l),(m)](https://datatracker.ietf.org/doc/html/rfc5280#section-6.1.4))
	///
	/// Deliberately stricter than RFC 5280 in five fail-closed ways. TightBeam
	/// runs a closed, self-managed PKI, so the interop these rules exist for
	/// (legacy web roots, cross-signing, cross-vendor DN encoding slop) never
	/// applies, and rejecting it removes attack surface:
	/// - ยง6.1.4(k) is enforced on every issuer, not just v3 -- v1/v2 CA
	///   certificates are rejected outright (the RFC permits rejecting).
	/// - Self-issued intermediates count against `pathLenConstraint`
	///   (ยง6.1.4(l) exempts them) -- key rollover here re-issues the trust
	///   store rather than cross-signing.
	/// - The trust anchor itself is subject to checks 1, 2, 3, 5, 7, and 8
	///   (ยง6.1.1(d) treats it as exempt input) -- an expired, revoked, or
	///   non-CA pinned root fails loudly.
	/// - Name chaining is DER byte equality, not ยง7.1 case-insensitive
	///   matching -- both encoders are in-house, and binary comparison
	///   forecloses canonicalization ambiguity.
	/// - The terminal certificate of a multi-certificate path must not assert
	///   `basicConstraints.cA` -- an authenticated identity misissued with CA
	///   power is rejected ([`ensure_terminal_is_end_entity`]).
	///
	/// Trust anchoring is the caller's responsibility. This routine validates
	/// path structure and cryptography only.
	fn validate_path(&self, path: &[&Certificate]) -> Result<(), CertificateValidationError> {
		// RFC 5280 ยง6.1.3(a)(2): every certificate must be within its validity period.
		path.iter().try_for_each(|cert| validate_certificate_expiry(cert))?;

		// RFC 5280 ยง4.2 / ยง6.1.3(f): fail closed on unprocessed critical extensions.
		path.iter().try_for_each(|cert| ensure_critical_extensions_processed(cert))?;

		// Defense-in-depth: the authenticated identity must not assert the CA bit.
		ensure_terminal_is_end_entity(path)?;

		// RFC 5280 ยง4.1.1.2: signatureAlgorithm must match tbsCertificate.signature.
		path.iter().try_for_each(|cert| ensure_signature_algorithm_consistency(cert))?;

		// Verify issuer/subject chaining and signatures via sliding window
		path.windows(2).try_for_each(|pair| {
			let (issuer, cert) = (pair[0], pair[1]);

			// RFC 5280 ยง6.1.3(a)(4): name chaining - issuer DN must equal the
			// preceding certificate's subject DN.
			if cert.tbs_certificate.issuer != issuer.tbs_certificate.subject {
				return Err(CertificateValidationError::InvalidChain);
			}

			// RFC 5280 ยง6.1.4(k),(n): the issuer must be a CA permitted to sign certs.
			ensure_issuer_is_ca(issuer)?;

			// RFC 5280 ยง6.1.3(a)(1): verify the signature using the issuer's key.
			let algorithm_oid = cert.signature_algorithm.oid;
			let public_key_der = issuer.tbs_certificate.subject_public_key_info.to_der()?;
			let message = cert.tbs_certificate.to_der()?;
			let signature_bytes = cert.signature.raw_bytes();

			self.policy
				.verify_signature(&algorithm_oid, &public_key_der, &message, signature_bytes)
		})?;

		// RFC 5280 ยง6.1.3(a)(3): revocation via the configured checker. The
		// anchor is checked against itself as issuer -- stricter than
		// ยง6.1.1(d), consistent with the anchor checks above.
		if let Some(anchor) = path.first() {
			self.revocation.check(anchor, anchor)?;
		}
		path.windows(2).try_for_each(|pair| self.revocation.check(pair[0], pair[1]))?;

		// RFC 5280 ยง6.1.4(m): enforce pathLenConstraint across the ordered path.
		ensure_path_len(path)
	}
}

#[cfg(feature = "std")]
impl Debug for CertificateTrustStore {
	fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
		f.debug_struct("CertificateTrustStore")
			.field("fingerprints", &self.fingerprints.len())
			.field("certificates", &self.certificates.len())
			.finish_non_exhaustive()
	}
}

#[cfg(feature = "std")]
impl CertificateValidation for CertificateTrustStore {
	fn evaluate(&self, cert: &Certificate) -> Result<(), CertificateValidationError> {
		// Walk the issuer hierarchy as far as the store material allows, then
		// validate the accumulated path with the shared routine.
		//
		// Issuer selection assumes at most one stored certificate per subject
		// DN: `find` commits to the first DN match and fails closed if that
		// candidate cannot verify. Full RFC 4158 path building (backtracking
		// across same-DN candidates) is intentionally not implemented.
		let mut path: Vec<&Certificate> = Vec::new();
		let mut visited: HashSet<Fingerprint> = HashSet::new();

		visited.insert(Self::to_fingerprint(cert)?);
		path.push(cert);

		let mut current = cert;
		loop {
			// RFC 5280 ยง6.1.3(a)(4): name chaining - locate an issuer whose
			// subject DN matches the current certificate's issuer DN.
			let Some(issuer) = self
				.certificates
				.values()
				.find(|c| c.tbs_certificate.subject == current.tbs_certificate.issuer)
			else {
				break;
			};

			// Self-issued terminal (root) or RFC 4158 ยง2.4.2 loop detection:
			// revisiting a certificate ends the walk.
			if !visited.insert(Self::to_fingerprint(issuer)?) {
				break;
			}

			path.push(issuer);
			current = issuer;
		}

		// RFC 5280 ยง6.1.1: the walk must reach a configured trust anchor.
		if !self.is_trusted(current) {
			return Err(CertificateValidationError::CertificateNotTrusted);
		}

		// Validate anchor-first (issuer before subject), same as `verify_chain`.
		path.reverse();
		self.validate_path(&path)
	}
}

#[cfg(feature = "std")]
impl CertificateTrust for CertificateTrustStore {
	fn is_trusted(&self, cert: &Certificate) -> bool {
		match Self::to_fingerprint(cert) {
			Ok(fp) => self.fingerprints.contains(&fp),
			Err(_) => false,
		}
	}

	fn verify_chain(&self, chain: &[Certificate]) -> Result<(), CertificateValidationError> {
		// RFC 5280 ยง6.1.1: the chain must terminate at a configured trust anchor.
		let root = chain.first().ok_or(CertificateValidationError::EmptyChain)?;
		if !self.is_trusted(root) {
			return Err(CertificateValidationError::CertificateNotTrusted);
		}

		// Delegate to the shared path-validation routine: single source of
		// truth with `evaluate`, so the two entry points cannot diverge.
		let path: Vec<&Certificate> = chain.iter().collect();
		self.validate_path(&path)
	}

	fn find_by_signer_info(&self, signer_info: &crate::SignerInfo) -> Option<&Certificate> {
		match &signer_info.sid {
			SignerIdentifier::IssuerAndSerialNumber(ias) => {
				// Find by issuer DN + serial number
				self.certificates.values().find(|cert| {
					cert.tbs_certificate.issuer == ias.issuer && cert.tbs_certificate.serial_number == ias.serial_number
				})
			}
			SignerIdentifier::SubjectKeyIdentifier(skid) => {
				// O(1) lookup via pre-indexed SKID
				let skid_bytes = skid.0.as_bytes();
				(skid_bytes.len() == 20)
					.then(|| {
						let mut key = [0u8; 20];
						key.copy_from_slice(skid_bytes);
						key
					})
					.and_then(|key| self.skid_index.get(&key))
					.and_then(|fp| self.certificates.get(fp))
			}
		}
	}

	fn to_policy_ref(&self) -> &dyn VerificationPolicy {
		&*self.policy
	}
}

// ============================================================================
// CertificateTrustBuilder Implementation
// ============================================================================

/// Builder for constructing `CertificateTrustStore`.
///
/// Generic over digest algorithm `D` which is used for SKID computation.
/// Validates structural correctness (expiry, issuer/subject chaining) on add.
/// The resulting store handles cryptographic verification at runtime.
#[cfg(feature = "std")]
pub struct CertificateTrustBuilder<D: Digest> {
	fingerprints: HashSet<Fingerprint>,
	certificates: HashMap<Fingerprint, Certificate>,
	skid_index: HashMap<Skid, Fingerprint>,
	policy: Arc<dyn VerificationPolicy>,
	revocation: Arc<dyn RevocationChecker>,
	_digest: core::marker::PhantomData<D>,
}

#[cfg(feature = "std")]
impl<D: Digest, P: VerificationPolicy + 'static> From<P> for CertificateTrustBuilder<D> {
	fn from(policy: P) -> Self {
		Self {
			fingerprints: HashSet::new(),
			certificates: HashMap::new(),
			skid_index: HashMap::new(),
			policy: Arc::new(policy),
			revocation: Arc::new(NoRevocation),
			_digest: core::marker::PhantomData,
		}
	}
}

#[cfg(feature = "std")]
impl<D: Digest> CertificateTrustBuilder<D> {
	/// Set the revocation checker consulted during path validation.
	///
	/// Defaults to [`NoRevocation`] (documented closed-PKI waiver).
	pub fn with_revocation_checker(mut self, checker: impl RevocationChecker + 'static) -> Self {
		self.revocation = Arc::new(checker);
		self
	}

	/// Add a single certificate (internal helper).
	fn add_certificate(&mut self, cert: Certificate) -> Result<(), CertificateValidationError> {
		let fp = CertificateTrustStore::to_fingerprint(&cert)?;

		// Compute SKID from public key
		let spki_der = cert.tbs_certificate.subject_public_key_info.to_der()?;
		let hash = D::digest(&spki_der);

		let mut skid = [0u8; 20];
		skid.copy_from_slice(crate::crypto::x509::utils::skid_window(hash.as_ref())?);

		// Collision detection: same SKID but different fingerprint
		if let Some(existing_fp) = self.skid_index.get(&skid) {
			if *existing_fp != fp {
				return Err(CertificateValidationError::SkidCollision);
			}
		}

		self.fingerprints.insert(fp);
		self.skid_index.insert(skid, fp);
		self.certificates.insert(fp, cert);

		Ok(())
	}
}

#[cfg(feature = "std")]
impl<D: Digest> TrustBuilder for CertificateTrustBuilder<D> {
	type Store = CertificateTrustStore;

	fn with_chain(mut self, chain: Vec<Certificate>) -> Result<Self, CertificateValidationError> {
		if chain.is_empty() {
			return Err(CertificateValidationError::EmptyChain);
		}

		// Validate expiry for all certificates
		chain.iter().try_for_each(validate_certificate_expiry)?;

		// Validate issuer/subject chaining (structural only, no crypto)
		chain.windows(2).try_for_each(|pair| {
			let (issuer, cert) = (&pair[0], &pair[1]);
			(cert.tbs_certificate.issuer == issuer.tbs_certificate.subject)
				.then_some(())
				.ok_or(CertificateValidationError::InvalidChain)
		})?;

		// Transfer ownership and add all certificates
		chain.into_iter().try_for_each(|cert| self.add_certificate(cert))?;

		Ok(self)
	}

	fn with_certificate(mut self, cert: Certificate) -> Result<Self, CertificateValidationError> {
		validate_certificate_expiry(&cert)?;
		self.add_certificate(cert)?;
		Ok(self)
	}

	fn build(self) -> Self::Store {
		CertificateTrustStore {
			fingerprints: self.fingerprints,
			certificates: self.certificates,
			skid_index: self.skid_index,
			policy: self.policy,
			revocation: self.revocation,
		}
	}
}

#[cfg(feature = "std")]
impl<D: Digest> Debug for CertificateTrustBuilder<D> {
	fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
		f.debug_struct("CertificateTrustBuilder")
			.field("fingerprints", &self.fingerprints.len())
			.field("certificates", &self.certificates.len())
			.field("skid_index", &self.skid_index.len())
			.finish_non_exhaustive()
	}
}

#[cfg(test)]
mod tests {
	use super::*;
	use crate::crypto::policy::Secp256k1Policy;
	use crate::crypto::sign::ecdsa::SigningKey;
	use crate::crypto::sign::Signatory;
	use crate::testing::create_test_signing_key;
	use crate::testing::utils::{
		ca_extensions, create_test_certificate, create_test_certificate_chain, TestCertificateChain,
	};

	type TestResult = Result<(), Box<dyn std::error::Error>>;

	/// Type alias for the builder with SHA3-256 digest (matches secp256k1 signer)
	type TestBuilder = CertificateTrustBuilder<Sha3_256>;

	// ========================================================================
	// Test Helpers
	// ========================================================================

	/// Which certificates to add to the trust store
	#[derive(Debug, Clone, Copy)]
	enum StoreCerts {
		None,
		Root,
		RootAndIntermediate,
	}

	/// Which certificate to evaluate
	#[derive(Debug, Clone, Copy)]
	enum EvalTarget {
		Root,
		Intermediate,
		Leaf,
	}

	/// Build a trust store with the specified certificates from a chain
	fn build_store(
		chain: &TestCertificateChain,
		certs: StoreCerts,
	) -> Result<CertificateTrustStore, CertificateValidationError> {
		let builder: TestBuilder = Secp256k1Policy.into();
		let builder = match certs {
			StoreCerts::None => builder,
			StoreCerts::Root => {
				let certificate = chain.root.clone();
				builder.with_certificate(certificate)?
			}
			StoreCerts::RootAndIntermediate => {
				let root = chain.root.clone();
				let intermediate = chain.intermediate.clone();
				builder.with_certificate(root)?.with_certificate(intermediate)?
			}
		};

		Ok(builder.build())
	}

	/// Get the target certificate from a chain
	fn target_cert(chain: &TestCertificateChain, target: EvalTarget) -> &Certificate {
		match target {
			EvalTarget::Root => &chain.root,
			EvalTarget::Intermediate => &chain.intermediate,
			EvalTarget::Leaf => &chain.leaf,
		}
	}

	// ========================================================================
	// Basic Operations
	// ========================================================================

	#[test]
	fn fingerprint_is_32_bytes() -> TestResult {
		let cert = create_test_certificate(&create_test_signing_key());
		assert_eq!(CertificateTrustStore::to_fingerprint(&cert)?.len(), 32);
		Ok(())
	}

	#[test]
	fn is_trusted_matches_fingerprint() -> TestResult {
		let cert = create_test_certificate(&create_test_signing_key());
		let certificate = cert.clone();
		let store = TestBuilder::from(Secp256k1Policy).with_certificate(certificate)?.build();
		assert!(store.is_trusted(&cert));
		assert!(!store.is_trusted(&create_test_certificate(&SigningKey::from_bytes(&[2u8; 32].into())?)));
		Ok(())
	}

	#[test]
	fn builder_validates_chain_structure() -> TestResult {
		let chain = create_test_certificate_chain()?;
		let chain = vec![chain.root, chain.intermediate, chain.leaf];
		assert!(TestBuilder::from(Secp256k1Policy).with_chain(chain).is_ok());

		Ok(())
	}

	/// Test cases for evaluate() with chain walking
	const EVALUATE_CASES: &[(StoreCerts, EvalTarget, bool)] = &[
		// Direct trust
		(StoreCerts::Root, EvalTarget::Root, true),
		// Fails: presented identity asserts the CA bit (EndEntityIsCa)
		(StoreCerts::Root, EvalTarget::Intermediate, false),
		// Chain walking: root+intermediate trusts leaf
		(StoreCerts::RootAndIntermediate, EvalTarget::Leaf, true),
		// Fails: root alone cannot verify leaf (missing intermediate)
		(StoreCerts::Root, EvalTarget::Leaf, false),
		// Fails: empty store trusts nothing
		(StoreCerts::None, EvalTarget::Leaf, false),
	];

	#[test]
	fn evaluate_chain_walking() -> TestResult {
		let chain = create_test_certificate_chain()?;
		for (store_certs, eval_target, should_succeed) in EVALUATE_CASES {
			let store = build_store(&chain, *store_certs)?;
			let cert = target_cert(&chain, *eval_target);

			let result = store.evaluate(cert);
			assert_eq!(
				result.is_ok(),
				*should_succeed,
				"store={store_certs:?} target={eval_target:?}: expected {should_succeed}, got {result:?}"
			);
		}

		Ok(())
	}

	#[test]
	fn evaluate_rejects_cross_chain_cert() -> TestResult {
		// Store has one chain's root, evaluate leaf from different chain
		let store = TestBuilder::from(Secp256k1Policy)
			.with_certificate(create_test_certificate(&create_test_signing_key()))?
			.build();

		let other_chain = create_test_certificate_chain()?;
		assert!(store.evaluate(&other_chain.leaf).is_err());
		Ok(())
	}

	// ========================================================================
	// Chain Verification
	// ========================================================================

	#[test]
	fn verify_chain_cases() -> TestResult {
		let chain = create_test_certificate_chain()?;
		let cases: &[(StoreCerts, &[&Certificate], bool)] = &[
			// Empty chain fails
			(StoreCerts::Root, &[], false),
			// Untrusted root fails
			(StoreCerts::None, &[&chain.root], false),
			// Trusted root alone succeeds
			(StoreCerts::Root, &[&chain.root], true),
			// Full chain with trusted root succeeds
			(StoreCerts::Root, &[&chain.root, &chain.intermediate, &chain.leaf], true),
		];

		for (store_certs, chain_slice, should_succeed) in cases {
			let store = build_store(&chain, *store_certs)?;
			let chain_vec: Vec<_> = chain_slice.iter().map(|c| (*c).clone()).collect();

			let result: Result<(), CertificateValidationError> = store.verify_chain(&chain_vec);
			assert_eq!(
				result.is_ok(),
				*should_succeed,
				"verify_chain: store={store_certs:?} chain_len={}: expected {should_succeed}, got {result:?}",
				chain_slice.len()
			);
		}

		Ok(())
	}

	// ========================================================================
	// RFC 5280 ยง6.1.4 Path Constraints
	// ========================================================================

	/// Each case replaces the root's extensions, then expects `verify_chain` to
	/// reject the otherwise-valid chain with the mapped error.
	const ISSUER_CONSTRAINT_CASES: &[(bool, bool, Option<u8>, CertificateValidationError)] = &[
		(false, true, None, CertificateValidationError::IssuerNotCa),
		(true, false, None, CertificateValidationError::MissingKeyCertSign),
		(true, true, Some(0), CertificateValidationError::PathLenExceeded),
	];

	#[test]
	fn verify_chain_enforces_issuer_constraints() -> TestResult {
		for (ca, key_cert_sign, path_len, expected) in ISSUER_CONSTRAINT_CASES {
			let chain = create_test_certificate_chain()?;

			let mut root = chain.root.clone();
			root.tbs_certificate.extensions = Some(ca_extensions(*ca, *key_cert_sign, *path_len));

			let certificate = root.clone();
			let store = TestBuilder::from(Secp256k1Policy).with_certificate(certificate)?.build();
			let result = store.verify_chain(&[root, chain.intermediate, chain.leaf]);
			assert!(matches!(result, Err(ref e) if core::mem::discriminant(e) == core::mem::discriminant(expected)));
		}

		Ok(())
	}

	#[test]
	fn evaluate_enforces_path_len_constraint() -> TestResult {
		let chain = create_test_certificate_chain()?;

		let mut root = chain.root.clone();
		root.tbs_certificate.extensions = Some(ca_extensions(true, true, Some(0)));

		let store = TestBuilder::from(Secp256k1Policy)
			.with_certificate(root)?
			.with_certificate(chain.intermediate)?
			.build();
		assert!(matches!(
			store.evaluate(&chain.leaf),
			Err(CertificateValidationError::PathLenExceeded)
		));
		Ok(())
	}

	// ========================================================================
	// RFC 5280 ยง4.2 Critical Extensions
	// ========================================================================

	/// Wrap an empty payload in an extension with the given OID and criticality.
	fn opaque_extension(oid: &str, critical: bool) -> crate::x509::ext::Extension {
		crate::x509::ext::Extension {
			extn_id: crate::der::oid::ObjectIdentifier::new_unwrap(oid),
			critical,
			extn_value: crate::der::asn1::OctetString::new(Vec::new()).unwrap(),
		}
	}

	#[test]
	fn rejects_unknown_critical_extension() {
		// nameConstraints (2.5.29.30) is not processed by this validator.
		let mut cert = create_test_certificate(&create_test_signing_key());
		cert.tbs_certificate.extensions = Some(vec![opaque_extension("2.5.29.30", true)]);

		assert!(matches!(
			ensure_critical_extensions_processed(&cert),
			Err(CertificateValidationError::UnprocessedCriticalExtension(_))
		));
	}

	#[test]
	fn accepts_unknown_noncritical_extension() {
		let mut cert = create_test_certificate(&create_test_signing_key());
		cert.tbs_certificate.extensions = Some(vec![opaque_extension("2.5.29.30", false)]);

		assert!(ensure_critical_extensions_processed(&cert).is_ok());
	}

	#[test]
	fn accepts_processed_critical_extensions() {
		let mut cert = create_test_certificate(&create_test_signing_key());
		cert.tbs_certificate.extensions = Some(ca_extensions(true, true, None));

		assert!(ensure_critical_extensions_processed(&cert).is_ok());
	}

	#[test]
	fn verify_chain_rejects_unknown_critical_extension() -> TestResult {
		let chain = create_test_certificate_chain()?;

		let mut leaf = chain.leaf.clone();
		leaf.tbs_certificate.extensions = Some(vec![opaque_extension("2.5.29.30", true)]);

		let store = build_store(&chain, StoreCerts::Root)?;
		let result = store.verify_chain(&[chain.root, chain.intermediate, leaf]);
		assert!(matches!(
			result,
			Err(CertificateValidationError::UnprocessedCriticalExtension(_))
		));
		Ok(())
	}

	// ========================================================================
	// End-Entity CA Bit (defense-in-depth)
	// ========================================================================

	#[test]
	fn terminal_with_ca_bit_rejected() -> TestResult {
		let chain = create_test_certificate_chain()?;

		// Intermediate carries basicConstraints.cA=true as terminal of [root, intermediate].
		let path = [&chain.root, &chain.intermediate];
		assert!(matches!(
			ensure_terminal_is_end_entity(&path),
			Err(CertificateValidationError::EndEntityIsCa)
		));
		Ok(())
	}

	#[test]
	fn terminal_without_ca_bit_accepted() -> TestResult {
		let chain = create_test_certificate_chain()?;

		let path = [&chain.root, &chain.intermediate, &chain.leaf];
		assert!(ensure_terminal_is_end_entity(&path).is_ok());
		Ok(())
	}

	#[test]
	fn single_certificate_path_exempt_from_ca_bit_check() -> TestResult {
		let chain = create_test_certificate_chain()?;

		// A pinned CA root validating itself is the direct-trust model.
		let path = [&chain.root];
		assert!(ensure_terminal_is_end_entity(&path).is_ok());
		Ok(())
	}

	// ========================================================================
	// RFC 5280 ยง6.1.3(a)(3) Revocation
	// ========================================================================

	/// Build a store trusting the chain root with the given revocation list.
	fn build_store_with_revocation(
		chain: &TestCertificateChain,
		revocation: StaticRevocationList,
	) -> Result<CertificateTrustStore, CertificateValidationError> {
		let root = chain.root.clone();
		Ok(TestBuilder::from(Secp256k1Policy)
			.with_revocation_checker(revocation)
			.with_certificate(root)?
			.build())
	}

	#[test]
	fn static_revocation_list_passes_unlisted_certificate() -> TestResult {
		let chain = create_test_certificate_chain()?;
		let revocation = StaticRevocationList::default().with_certificate(&chain.intermediate)?;

		assert!(revocation.check(&chain.intermediate, &chain.leaf).is_ok());
		Ok(())
	}

	#[test]
	fn verify_chain_rejects_leaf_revoked_by_fingerprint() -> TestResult {
		let chain = create_test_certificate_chain()?;
		let revocation = StaticRevocationList::default().with_certificate(&chain.leaf)?;

		let store = build_store_with_revocation(&chain, revocation)?;
		let result = store.verify_chain(&[chain.root, chain.intermediate, chain.leaf]);
		assert!(matches!(result, Err(CertificateValidationError::CertificateRevoked)));
		Ok(())
	}

	#[test]
	fn verify_chain_rejects_leaf_revoked_by_serial() -> TestResult {
		let chain = create_test_certificate_chain()?;
		let issuer = chain.leaf.tbs_certificate.issuer.clone();
		let serial = chain.leaf.tbs_certificate.serial_number.as_bytes().to_vec();
		let revocation = StaticRevocationList::default().with_serial(&issuer, serial)?;

		let store = build_store_with_revocation(&chain, revocation)?;
		let result = store.verify_chain(&[chain.root, chain.intermediate, chain.leaf]);
		assert!(matches!(result, Err(CertificateValidationError::CertificateRevoked)));
		Ok(())
	}

	#[test]
	fn serial_revocation_is_scoped_to_issuer() -> TestResult {
		let chain = create_test_certificate_chain()?;
		let other_issuer = chain.leaf.tbs_certificate.subject.clone();
		let serial = chain.leaf.tbs_certificate.serial_number.as_bytes().to_vec();
		let revocation = StaticRevocationList::default().with_serial(&other_issuer, serial)?;

		let store = build_store_with_revocation(&chain, revocation)?;
		let result = store.verify_chain(&[chain.root, chain.intermediate, chain.leaf]);
		assert!(result.is_ok());
		Ok(())
	}

	#[test]
	fn verify_chain_rejects_revoked_anchor() -> TestResult {
		let chain = create_test_certificate_chain()?;
		let revocation = StaticRevocationList::default().with_certificate(&chain.root)?;

		let store = build_store_with_revocation(&chain, revocation)?;
		let result = store.verify_chain(&[chain.root]);
		assert!(matches!(result, Err(CertificateValidationError::CertificateRevoked)));
		Ok(())
	}

	// ========================================================================
	// RFC 5280 ยง4.1.1.2 Algorithm Identifier Consistency
	// ========================================================================

	#[test]
	fn rejects_algorithm_identifier_mismatch() -> TestResult {
		let chain = create_test_certificate_chain()?;

		let mut leaf = chain.leaf.clone();
		leaf.signature_algorithm.oid = crate::oids::SIGNER_ECDSA_WITH_SHA256;

		// Both the recursive `evaluate` walk and `verify_chain` must reject it.
		let walk_store = build_store(&chain, StoreCerts::RootAndIntermediate)?;
		assert!(matches!(
			walk_store.evaluate(&leaf),
			Err(CertificateValidationError::AlgorithmMismatch)
		));

		let chain_store = build_store(&chain, StoreCerts::Root)?;
		let result = chain_store.verify_chain(&[chain.root, chain.intermediate, leaf]);
		assert!(matches!(result, Err(CertificateValidationError::AlgorithmMismatch)));
		Ok(())
	}

	// ========================================================================
	// Signer Lookup
	// ========================================================================

	#[test]
	fn find_by_signer_info_skid() -> TestResult {
		let key = create_test_signing_key();
		let cert = create_test_certificate(&key);
		let certificate = cert.clone();
		let store = TestBuilder::from(Secp256k1Policy).with_certificate(certificate)?.build();

		// Create signer info via Signatory trait (uses SHA3-256 for SKID)
		let signer_info = key.to_signer_info(b"test")?;
		// Should find the certificate
		let Some(found) = store.find_by_signer_info(&signer_info) else {
			return Err(crate::testing::error::TestingError::InvariantViolated.into());
		};
		assert_eq!(
			CertificateTrustStore::to_fingerprint(found)?,
			CertificateTrustStore::to_fingerprint(&cert)?
		);

		Ok(())
	}

	#[test]
	fn find_by_signer_info_not_found() -> TestResult {
		let store = TestBuilder::from(Secp256k1Policy)
			.with_certificate(create_test_certificate(&create_test_signing_key()))?
			.build();

		// Different key
		let other_key = SigningKey::from_bytes(&[99u8; 32].into())?;
		let signer_info = other_key.to_signer_info(b"test")?;
		assert!(store.find_by_signer_info(&signer_info).is_none());

		Ok(())
	}
}