1use std::{ops::Deref, time::SystemTime};
4
5use super::{DsigError, SignatureAlgorithm, VerifyingKey};
6use crate::policy::{KeyTrustPolicy, PolicyViolation, VerificationPolicy};
7
8#[derive(Debug, Clone, PartialEq, Eq)]
10#[expect(
12 clippy::large_enum_variant,
13 reason = "bounded inline path evidence avoids heap allocation"
14)]
15pub enum KeyTrustEvidence {
16 NotEvaluated,
18 NotEstablished,
20 CallerTrusted,
22 ValidatedX509(X509TrustEvidence),
24}
25
26#[derive(Debug, Clone, PartialEq, Eq)]
29pub struct X509TrustEvidence {
30 fingerprints: [[u8; 32]; crate::hard_limits::X509_CHAIN_DEPTH_CEILING],
31 path_len: usize,
32 verification_time: SystemTime,
33 revocation_checked: bool,
34}
35
36impl X509TrustEvidence {
37 pub(crate) fn new(
38 certificates: impl ExactSizeIterator<Item = impl AsRef<[u8]>>,
39 verification_time: SystemTime,
40 revocation_checked: bool,
41 ) -> Result<Self, DsigError> {
42 use sha2::{Digest, Sha256};
43 let path_len = certificates.len();
44 if path_len == 0 || path_len > crate::hard_limits::X509_CHAIN_DEPTH_CEILING {
45 return Err(PolicyViolation::KeyTrust {
46 reason: "invalid validated certificate path",
47 }
48 .into());
49 }
50 let mut fingerprints = [[0; 32]; crate::hard_limits::X509_CHAIN_DEPTH_CEILING];
53 for (fingerprint, certificate) in fingerprints.iter_mut().zip(certificates) {
54 *fingerprint = Sha256::digest(certificate.as_ref()).into();
55 }
56 Ok(Self {
57 fingerprints,
58 path_len,
59 verification_time,
60 revocation_checked,
61 })
62 }
63
64 pub fn certificate_fingerprints(&self) -> &[[u8; 32]] {
66 &self.fingerprints[..self.path_len]
67 }
68
69 pub fn anchor_fingerprint(&self) -> &[u8; 32] {
71 &self.fingerprints[self.path_len - 1]
72 }
73
74 pub fn verification_time(&self) -> SystemTime {
76 self.verification_time
77 }
78
79 pub fn revocation_checked(&self) -> bool {
81 self.revocation_checked
82 }
83}
84
85pub struct TrustedPublicKey {
88 key: Box<dyn VerifyingKey>,
89 trust: KeyTrustPolicy,
90 evidence: X509TrustEvidence,
91}
92
93impl TrustedPublicKey {
94 pub(crate) fn new(
95 key: Box<dyn VerifyingKey>,
96 mut trust: KeyTrustPolicy,
97 evidence: X509TrustEvidence,
98 ) -> Self {
99 trust.verification_time = Some(evidence.verification_time);
103 Self {
104 key,
105 trust,
106 evidence,
107 }
108 }
109
110 pub fn evidence(&self) -> &X509TrustEvidence {
112 &self.evidence
113 }
114}
115
116impl VerifyingKey for TrustedPublicKey {
117 fn verification_spki(&self, algorithm: SignatureAlgorithm) -> Result<Option<&[u8]>, DsigError> {
118 self.key.verification_spki(algorithm)
119 }
120
121 fn ecdsa_encoding(&self) -> crate::policy::EcdsaSignatureValueEncoding {
122 self.key.ecdsa_encoding()
123 }
124
125 fn verify_candidate_keys(
126 &self,
127 verify: &mut dyn FnMut(&dyn VerifyingKey) -> Result<bool, DsigError>,
128 ) -> Result<Option<bool>, DsigError> {
129 self.key.verify_candidate_keys(verify)
130 }
131 fn verify_with_context(
132 &self,
133 algorithm: SignatureAlgorithm,
134 context: &super::SignatureContext,
135 data: &[u8],
136 signature: &[u8],
137 ) -> Result<bool, DsigError> {
138 self.key
139 .verify_with_context(algorithm, context, data, signature)
140 }
141 fn validate_policy(&self, policy: &VerificationPolicy) -> Result<(), DsigError> {
142 if self.trust != policy.key_trust {
143 return Err(PolicyViolation::KeyTrust {
144 reason: "validated key belongs to a different trust policy",
145 }
146 .into());
147 }
148 self.key.validate_policy(policy)
149 }
150
151 fn validate_signature_value(
152 &self,
153 algorithm: SignatureAlgorithm,
154 signature: &[u8],
155 ) -> Result<bool, DsigError> {
156 self.key.validate_signature_value(algorithm, signature)
157 }
158
159 fn validate_signature_value_with_policy(
160 &self,
161 policy: &VerificationPolicy,
162 algorithm: SignatureAlgorithm,
163 signature: &[u8],
164 ) -> Result<bool, DsigError> {
165 self.validate_policy(policy)?;
166 self.key
167 .validate_signature_value_with_policy(policy, algorithm, signature)
168 }
169
170 fn verify(
171 &self,
172 algorithm: SignatureAlgorithm,
173 data: &[u8],
174 signature: &[u8],
175 ) -> Result<bool, DsigError> {
176 self.key.verify(algorithm, data, signature)
177 }
178
179 fn verify_with_policy(
180 &self,
181 policy: &VerificationPolicy,
182 algorithm: SignatureAlgorithm,
183 data: &[u8],
184 signature: &[u8],
185 ) -> Result<bool, DsigError> {
186 self.validate_policy(policy)?;
187 self.key
188 .verify_with_policy(policy, algorithm, data, signature)
189 }
190}
191
192#[expect(
194 clippy::large_enum_variant,
195 reason = "one bounded resolver result per operation needs no extra box"
196)]
197pub enum ResolvedVerificationKey<'a> {
198 Candidate(Box<dyn VerifyingKey + 'a>),
200 CallerTrusted(Box<dyn VerifyingKey + 'a>),
202 Validated(TrustedPublicKey),
204}
205
206impl<'a> ResolvedVerificationKey<'a> {
207 pub fn into_key(self) -> Box<dyn VerifyingKey + 'a> {
209 match self {
210 Self::Candidate(key) | Self::CallerTrusted(key) => key,
211 Self::Validated(key) => Box::new(key),
212 }
213 }
214
215 pub(crate) fn authorize(
216 &self,
217 policy: &VerificationPolicy,
218 ) -> Result<KeyTrustEvidence, DsigError> {
219 use crate::policy::VerificationTrustMode;
220 if policy.key_trust.mode == VerificationTrustMode::CryptographicOnly {
224 return Ok(KeyTrustEvidence::NotEstablished);
225 }
226 match self {
227 Self::Candidate(_) => Err(PolicyViolation::KeyTrust {
228 reason: "verification requires an authorized key",
229 }
230 .into()),
231 Self::CallerTrusted(_) => Ok(KeyTrustEvidence::CallerTrusted),
232 Self::Validated(key) => {
233 key.validate_policy(policy)?;
234 Ok(KeyTrustEvidence::ValidatedX509(key.evidence.clone()))
235 }
236 }
237 }
238}
239
240impl<'a> AsRef<dyn VerifyingKey + 'a> for ResolvedVerificationKey<'a> {
241 fn as_ref(&self) -> &(dyn VerifyingKey + 'a) {
242 match self {
243 Self::Candidate(key) | Self::CallerTrusted(key) => key.as_ref(),
244 Self::Validated(key) => key,
245 }
246 }
247}
248
249impl<'a> Deref for ResolvedVerificationKey<'a> {
250 type Target = dyn VerifyingKey + 'a;
251 fn deref(&self) -> &Self::Target {
252 self.as_ref()
253 }
254}
255
256#[cfg(test)]
257mod tests {
258 use super::*;
259
260 struct NeverExecuted;
261 impl VerifyingKey for NeverExecuted {
262 fn verify(&self, _: SignatureAlgorithm, _: &[u8], _: &[u8]) -> Result<bool, DsigError> {
263 panic!("stale authorization must fail before mathematical work");
264 }
265 }
266
267 #[test]
268 fn validated_key_is_bound_to_time_purpose_and_policy() {
269 let time = SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(1_800_000_000);
272 let evidence =
273 X509TrustEvidence::new([b"bounded certificate identity"].into_iter(), time, false)
274 .expect("a one-certificate proof fits the hard path bound");
275 let mut policy = VerificationPolicy::default();
276 policy.key_trust.verify_x509_chains = true;
277 let key =
278 TrustedPublicKey::new(Box::new(NeverExecuted), policy.key_trust.clone(), evidence);
279 assert!(key.validate_policy(&policy).is_err());
280 policy.key_trust.verification_time = Some(time);
281 key.validate_policy(&policy)
282 .expect("the exact captured snapshot must match");
283 let mut changed = policy.clone();
284 changed.key_trust.verification_time = Some(time + std::time::Duration::from_secs(1));
285 assert!(
286 key.verify_with_policy(
287 &changed,
288 SignatureAlgorithm::RsaSha256,
289 b"data",
290 b"signature"
291 )
292 .is_err()
293 );
294 changed = policy.clone();
295 changed
296 .key_trust
297 .allowed_extended_key_usages
298 .insert(crate::policy::ExtendedKeyPurpose::CodeSigning);
299 assert!(key.validate_policy(&changed).is_err());
300 changed = policy;
301 changed.key_trust.check_crls = true;
302 assert!(key.validate_policy(&changed).is_err());
303 }
304}