tightbeam-rs 0.8.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
//! Certificate validation policies and strategies.
//!
//! This module provides various certificate validation policies that can be
//! used to validate X.509 certificates according to different trust models.

use core::marker::PhantomData;
use core::time::Duration;

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

use crate::asn1::GeneralizedTime;
use crate::crypto::hash::Digest;
use crate::crypto::policy::VerificationPolicy;
use crate::crypto::x509::error::CertificateValidationError;
use crate::crypto::x509::utils::{ensure_signature_algorithm_consistency, validate_certificate_expiry};
use crate::crypto::x509::Certificate;
use crate::der::Encode;

/// Trait for certificate validation strategies.
///
/// This trait allows pluggable certificate validation with different
/// policies and trust models. Implementors can validate certificates
/// against specific requirements.
///
/// For simple validation (pinning, denylists, expiry checks), implement
/// only this trait. For full PKI validation with signature verification,
/// also implement `SignatureVerification`.
pub trait CertificateValidation: Send + Sync {
	/// Perform certificate validation.
	///
	/// This method should perform all validation checks that don't require
	/// cryptographic signature verification (expiry, pinning, denylists, etc.).
	///
	/// # Arguments
	/// * `cert` - The certificate to validate
	///
	/// # Returns
	/// * `Ok(())` if validation succeeds
	/// * `Err(_)` with specific error details
	fn evaluate(&self, cert: &Certificate) -> Result<(), CertificateValidationError>;
}

/// Trait for certificate validation with cryptographic signature verification.
///
/// This trait extends `CertificateValidation` with the ability to verify
/// certificate signatures using a pluggable verification policy.
pub trait SignatureVerification: CertificateValidation {
	/// Perform full certificate validation with cryptographic verification.
	///
	/// This method verifies the certificate signature using the provided
	/// verification policy and issuer's public key.
	///
	/// # Arguments
	/// * `cert` - The certificate to validate
	/// * `curr_time` - Current UNIX timestamp (seconds since epoch)
	/// * `issuer_pub_key` - DER-encoded public key of the issuer
	/// * `policy` - Verification policy to use for signature validation
	///
	/// # Returns
	/// * `Ok(())` if validation succeeds
	/// * `Err(_)` with specific error details
	fn verify_with_policy(
		&self,
		cert: &Certificate,
		curr_time: u64,
		issuer_pub_key: &[u8],
		policy: &dyn VerificationPolicy,
	) -> Result<(), CertificateValidationError>;
}

// ============================================================================
// Built-in Validators
//
// The pinning and denylist validators below implement direct-trust models
// (trust-on-first-use / key pinning, cf. RFC 7469), not RFC 5280 §6.1
// certification-path validation.
// ============================================================================

/// Validate only certificate expiry.
///
/// This validator checks if the certificate is within its validity period
/// but does not verify signatures or perform other cryptographic checks.
#[derive(Debug, Clone, Copy, Default)]
pub struct ExpiryValidator;

impl CertificateValidation for ExpiryValidator {
	fn evaluate(&self, cert: &Certificate) -> Result<(), CertificateValidationError> {
		// RFC 5280 §6.1.3(a)(2): validity-period check only.
		validate_certificate_expiry(cert)
	}
}

/// Public key pinning validator with const-generic array
///
/// The const generic parameter `N` specifies the number of pinned keys.
#[derive(Debug, Clone, Copy)]
pub struct PublicKeyPinning<const N: usize> {
	allowed_keys: [&'static [u8]; N],
}

impl<const N: usize> PublicKeyPinning<N> {
	/// Create a new public key pinning validator with the given allowed keys.
	///
	/// This is a const function, allowing creation in const contexts.
	pub const fn new(keys: [&'static [u8]; N]) -> Self {
		Self { allowed_keys: keys }
	}
}

impl<const N: usize> CertificateValidation for PublicKeyPinning<N> {
	fn evaluate(&self, cert: &Certificate) -> Result<(), CertificateValidationError> {
		let pub_key_bytes = cert.tbs_certificate.subject_public_key_info.subject_public_key.raw_bytes();
		self.allowed_keys
			.contains(&pub_key_bytes)
			.then_some(())
			.ok_or(CertificateValidationError::PublicKeyNotPinned)
	}
}

/// Certificate fingerprint pinning validator with const-generic array.
///
/// This validator is const-constructible, making it suitable for use in static
/// configurations.
///
/// Generic over the digest algorithm and the number of pinned fingerprints.
#[derive(Debug, Clone, Copy)]
pub struct FingerprintPinning<D, const N: usize> {
	allowed_fingerprints: [&'static [u8]; N],
	_digest: PhantomData<D>,
}

impl<D, const N: usize> FingerprintPinning<D, N>
where
	D: Digest,
{
	/// Create a new fingerprint pinning validator with the given allowed fingerprints.
	///
	/// This is a const function, allowing creation in const contexts.
	pub const fn new(fingerprints: [&'static [u8]; N]) -> Self {
		Self { allowed_fingerprints: fingerprints, _digest: PhantomData }
	}
}

impl<D, const N: usize> CertificateValidation for FingerprintPinning<D, N>
where
	D: Digest + Send + Sync,
{
	fn evaluate(&self, cert: &Certificate) -> Result<(), CertificateValidationError> {
		let cert_der = cert.to_der()?;
		let fingerprint = D::digest(&cert_der);
		self.allowed_fingerprints
			.iter()
			.any(|fp| *fp == fingerprint.as_ref())
			.then_some(())
			.ok_or(CertificateValidationError::CertificateNotPinned)
	}
}

/// Certificate fingerprint denylist validator with const-generic array.
///
/// This validator is const-constructible, making it suitable for use in
/// static configurations.
#[derive(Debug, Clone, Copy)]
pub struct FingerprintDenylist<D, const N: usize> {
	denied_fingerprints: [&'static [u8]; N],
	_digest: PhantomData<D>,
}

impl<D, const N: usize> FingerprintDenylist<D, N>
where
	D: Digest,
{
	/// Create a new fingerprint denylist validator with the given fingerprints.
	pub const fn new(fingerprints: [&'static [u8]; N]) -> Self {
		Self { denied_fingerprints: fingerprints, _digest: PhantomData }
	}
}

impl<D, const N: usize> CertificateValidation for FingerprintDenylist<D, N>
where
	D: Digest + Send + Sync,
{
	fn evaluate(&self, cert: &Certificate) -> Result<(), CertificateValidationError> {
		let cert_der = cert.to_der()?;
		let fingerprint = D::digest(&cert_der);

		let is_denied = self.denied_fingerprints.iter().any(|fp| *fp == fingerprint.as_ref());
		if is_denied {
			Err(CertificateValidationError::CertificateDenied)
		} else {
			Ok(())
		}
	}
}

/// Runtime certificate pinning validator.
///
/// Pins to a specific set of certificates using fingerprint comparison.
/// Unlike `FingerprintPinning<D, N>`, this validator can be created at runtime
/// with dynamic certificate lists, making it suitable for use in builders.
#[cfg(feature = "std")]
#[derive(Clone)]
pub struct RuntimeCertificatePinning<D> {
	fingerprints: Vec<Vec<u8>>,
	_digest: PhantomData<D>,
}

#[cfg(feature = "std")]
impl<D> RuntimeCertificatePinning<D>
where
	D: Digest,
{
	/// Create a new runtime certificate pinning validator from certificates.
	///
	/// Computes fingerprints for each certificate and stores them for validation.
	pub fn from_certificates(certs: impl IntoIterator<Item = Certificate>) -> Result<Self, CertificateValidationError> {
		let fingerprints = certs
			.into_iter()
			.map(|cert| cert.to_der().map(|der| D::digest(&der).to_vec()))
			.collect::<Result<Vec<_>, _>>()?;

		Ok(Self { fingerprints, _digest: PhantomData })
	}

	/// Create validator directly from pre-computed fingerprints.
	///
	/// This method allows creating a validator without cloning certificates,
	/// as fingerprints can be computed once and passed directly.
	pub fn from_fingerprints(fingerprints: impl IntoIterator<Item = Vec<u8>>) -> Self {
		Self { fingerprints: fingerprints.into_iter().collect(), _digest: PhantomData }
	}
}

#[cfg(feature = "std")]
impl<D> CertificateValidation for RuntimeCertificatePinning<D>
where
	D: Digest + Send + Sync,
{
	fn evaluate(&self, cert: &Certificate) -> Result<(), CertificateValidationError> {
		let cert_der = cert.to_der()?;
		let fingerprint = D::digest(&cert_der);
		self.fingerprints
			.iter()
			.any(|fp| fp.as_slice() == fingerprint.as_ref())
			.then_some(())
			.ok_or(CertificateValidationError::CertificateNotPinned)
	}
}

/// Direct-trust certificate validator.
///
/// This is **not** a full RFC 5280 §6.1 certification-path validator: it does
/// not build paths, walk name chains, or check `basicConstraints`/`keyUsage`.
///
/// - [`CertificateValidation::evaluate`]: validity period
///   (RFC 5280 §6.1.3(a)(2)) plus direct-trust anchoring - the presented
///   certificate must itself be a configured trust anchor (RFC 5280 §6.1.1).
/// - [`SignatureVerification::verify_with_policy`]: single-certificate validity,
///   algorithm-identifier consistency (RFC 5280 §4.1.1.2), and signature
///   verification against a caller-supplied issuer key (RFC 5280 §6.1.3(a)(1)).
///
/// See <https://datatracker.ietf.org/doc/html/rfc5280#section-6.1>.
#[derive(Default, Clone)]
pub struct DirectTrustValidator {
	trust_chain: Vec<Certificate>,
}

impl DirectTrustValidator {
	/// Add a trust chain to the validator.
	///
	/// # Arguments
	/// * `trust_chain` - Vector of certificates representing the trust chain
	pub fn with_trust_chain(mut self, trust_chain: Vec<Certificate>) -> Self {
		self.trust_chain = trust_chain;
		self
	}
}

impl CertificateValidation for DirectTrustValidator {
	fn evaluate(&self, cert: &Certificate) -> Result<(), CertificateValidationError> {
		// RFC 5280 §6.1.3(a)(2): the certificate must be within its validity period.
		validate_certificate_expiry(cert)?;

		// Without a configured anchor there is nothing to chain to; expiry-only.
		if self.trust_chain.is_empty() {
			return Ok(());
		}

		// RFC 5280 §6.1.1: direct trust - the presented certificate must itself
		// be a configured trust anchor (no path building is performed here).
		let cert_der = cert.to_der()?;
		for anchor in &self.trust_chain {
			if anchor.to_der()? == cert_der {
				return Ok(());
			}
		}

		Err(CertificateValidationError::CertificateNotTrusted)
	}
}

impl SignatureVerification for DirectTrustValidator {
	fn verify_with_policy(
		&self,
		cert: &Certificate,
		curr_time: u64,
		public_key_der: &[u8],
		policy: &dyn VerificationPolicy,
	) -> Result<(), CertificateValidationError> {
		// RFC 5280 §6.1.3(a)(2): notBefore <= current time <= notAfter.
		let not_before = cert.tbs_certificate.validity.not_before.to_unix_duration();
		let not_after = cert.tbs_certificate.validity.not_after.to_unix_duration();
		let now_duration = GeneralizedTime::from_unix_duration(Duration::from_secs(curr_time))
			.map_err(|_| CertificateValidationError::InvalidTimestamp)?
			.to_unix_duration();

		if now_duration < not_before {
			return Err(CertificateValidationError::NotYetValid);
		}
		if now_duration > not_after {
			return Err(CertificateValidationError::Expired);
		}

		// RFC 5280 §4.1.2.7: the subjectPublicKeyInfo must carry a key.
		let subject_public_key = cert.tbs_certificate.subject_public_key_info.subject_public_key.raw_bytes();
		if subject_public_key.is_empty() {
			return Err(CertificateValidationError::EmptyPublicKey);
		}

		// RFC 5280 §4.1.1.3: the signatureValue must be present.
		let signature_bytes = cert.signature.raw_bytes();
		if signature_bytes.is_empty() {
			return Err(CertificateValidationError::EmptySignature);
		}

		// RFC 5280 §4.1.1.2: signatureAlgorithm must match tbsCertificate.signature.
		ensure_signature_algorithm_consistency(cert)?;

		// RFC 5280 §6.1.3(a)(1): verify the signature using the issuer's key.
		let message = cert.tbs_certificate.to_der()?;
		policy.verify_signature(&cert.signature_algorithm.oid, public_key_der, &message, signature_bytes)
	}
}

/// Chain multiple validators together.
///
/// All validators must succeed for the certificate to be accepted.
/// Validators are evaluated in order. This validator only chains
/// simple `evaluate()` calls and does not support signature verification.
#[cfg(feature = "std")]
#[derive(Default)]
pub struct ChainValidator {
	validators: Vec<Box<dyn CertificateValidation>>,
}

#[cfg(feature = "std")]
impl ChainValidator {
	/// Add a validator to the chain.
	#[allow(clippy::should_implement_trait)]
	pub fn add(mut self, validator: Box<dyn CertificateValidation>) -> Self {
		self.validators.push(validator);
		self
	}
}

#[cfg(feature = "std")]
impl CertificateValidation for ChainValidator {
	fn evaluate(&self, cert: &Certificate) -> Result<(), CertificateValidationError> {
		self.validators.iter().try_for_each(|v| v.evaluate(cert))
	}
}

#[cfg(test)]
mod tests {
	use crate::crypto::x509::error::CertificateValidationError;
	use crate::crypto::x509::policy::{CertificateValidation, ExpiryValidator};
	use crate::testing::create_expired_test_certificate;

	#[test]
	fn test_expiry_validator_rejects_expired_cert() {
		let expired_cert = create_expired_test_certificate();
		let validator = ExpiryValidator;

		// This certificate expired on August 17, 2019, so it should be rejected
		let result = validator.evaluate(&expired_cert);
		assert!(result.is_err(), "Expired certificate should be rejected");

		// Verify it's specifically an expiry error
		match result {
			Err(CertificateValidationError::Expired) => {
				// Expected error
			}
			other => panic!("Expected Expired error, got: {other:?}"),
		}
	}

	#[cfg(all(feature = "secp256k1", feature = "signature", feature = "x509", feature = "std"))]
	mod direct_trust {
		use k256::ecdsa::SigningKey;

		use crate::crypto::policy::Secp256k1Policy;
		use crate::crypto::x509::error::CertificateValidationError;
		use crate::crypto::x509::policy::{CertificateValidation, DirectTrustValidator, SignatureVerification};
		use crate::crypto::x509::Certificate;
		use crate::oids::SIGNER_ECDSA_WITH_SHA256;
		use crate::spki::EncodePublicKey;
		use crate::testing::utils::{create_test_certificate, create_test_signing_key};

		fn test_cert() -> Certificate {
			create_test_certificate(&create_test_signing_key())
		}

		/// Run the out-of-the-box policy over `cert`, supplying the issuer key
		/// that matches `signing_key`.
		fn verify(signing_key: &SigningKey, cert: &Certificate) -> Result<(), CertificateValidationError> {
			let issuer_pub = signing_key.verifying_key().to_public_key_der()?;
			DirectTrustValidator::default().verify_with_policy(cert, 1_000, issuer_pub.as_bytes(), &Secp256k1Policy)
		}

		#[test]
		fn accepts_configured_anchor() {
			let cert = test_cert();
			let validator = DirectTrustValidator::default().with_trust_chain(vec![cert.clone()]);
			assert!(validator.evaluate(&cert).is_ok());
		}

		#[test]
		fn rejects_non_anchor() -> Result<(), Box<dyn core::error::Error>> {
			let validator = DirectTrustValidator::default().with_trust_chain(vec![test_cert()]);
			let other = create_test_certificate(&SigningKey::from_bytes(&[7u8; 32].into())?);
			assert!(matches!(
				validator.evaluate(&other),
				Err(CertificateValidationError::CertificateNotTrusted)
			));
			Ok(())
		}

		#[test]
		fn without_anchor_is_expiry_only() {
			assert!(DirectTrustValidator::default().evaluate(&test_cert()).is_ok());
		}

		#[test]
		fn rejects_algorithm_mismatch() {
			let key = create_test_signing_key();
			let mut cert = create_test_certificate(&key);
			// signatureAlgorithm disagrees with tbsCertificate.signature (RFC 5280 §4.1.1.2).
			cert.signature_algorithm.oid = SIGNER_ECDSA_WITH_SHA256;
			assert!(matches!(
				verify(&key, &cert),
				Err(CertificateValidationError::AlgorithmMismatch)
			));
		}

		#[test]
		fn rejects_foreign_algorithm() {
			let key = create_test_signing_key();
			let mut cert = create_test_certificate(&key);
			// Consistent identifiers, but an algorithm the out-of-the-box policy refuses.
			cert.signature_algorithm.oid = SIGNER_ECDSA_WITH_SHA256;
			cert.tbs_certificate.signature.oid = SIGNER_ECDSA_WITH_SHA256;
			assert!(matches!(
				verify(&key, &cert),
				Err(CertificateValidationError::UnsupportedAlgorithm(_))
			));
		}
	}
}