rustls-crl-refresh 0.0.2

Process-wide CRL cache and refreshable rustls verifiers without ServerConfig churn.
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
//! Wrapper certificate verifiers that build a fresh
//! `WebPkiClientVerifier` / `WebPkiServerVerifier` per handshake from
//! the latest CRL snapshot held in [`crate::CrlCache`]. This is the
//! mechanism that satisfies the `Arc<ClientConfig>` /
//! `Arc<ServerConfig>` stability invariant: refreshing CRL bytes does
//! not invalidate cached configs, and the wrapper just sees the new
//! bytes the next time it consults the cache.

use std::sync::Arc;

use arc_swap::ArcSwapOption;
use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier};
use rustls::pki_types::{CertificateDer, CertificateRevocationListDer, ServerName, UnixTime};
use rustls::server::WebPkiClientVerifier;
use rustls::server::danger::{ClientCertVerified, ClientCertVerifier};
use rustls::{DigitallySignedStruct, DistinguishedName, RootCertStore, SignatureScheme};

use crate::cache::{CrlCache, CrlSourceId};

/// Identity fingerprint of a CRL snapshot. We hash by the
/// `Arc::as_ptr` of each `CertificateRevocationListDer` rather than by
/// the bytes themselves: [`CrlCache`] guarantees that the inner Arc
/// changes iff the bytes change, so the pointer-tuple is a cheap and
/// correct "did this snapshot move?" key. Heavy CRLs that arrive every
/// few hours therefore don't pay a per-handshake byte compare.
type CrlFingerprint = Vec<usize>;

fn fingerprint(crls: &[Arc<CertificateRevocationListDer<'static>>]) -> CrlFingerprint {
	crls.iter().map(|arc| Arc::as_ptr(arc) as usize).collect()
}

fn build_owned(
	crls: &[Arc<CertificateRevocationListDer<'static>>],
) -> Vec<CertificateRevocationListDer<'static>> {
	crls.iter().map(|arc| (**arc).clone()).collect()
}

struct CachedClient {
	fingerprint: CrlFingerprint,
	verifier: Arc<dyn ClientCertVerifier>,
}

struct CachedServer {
	fingerprint: CrlFingerprint,
	verifier: Arc<dyn ServerCertVerifier>,
}

/// Listener-side wrapper that defers to a `WebPkiClientVerifier`
/// rebuilt only when the cached CRL snapshot's Arc identity changes,
/// against the latest CRL bytes pulled from the cache.
pub struct RefreshableClientCertVerifier {
	cache: Arc<CrlCache>,
	sources: Vec<CrlSourceId>,
	cas: Arc<RootCertStore>,
	allow_unauthenticated: bool,
	root_hint_subjects: Vec<DistinguishedName>,
	cached: ArcSwapOption<CachedClient>,
}

impl std::fmt::Debug for RefreshableClientCertVerifier {
	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
		f.debug_struct("RefreshableClientCertVerifier")
			.field("sources", &self.sources)
			.field("allow_unauthenticated", &self.allow_unauthenticated)
			.finish_non_exhaustive()
	}
}

impl RefreshableClientCertVerifier {
	#[must_use]
	pub fn new(
		cache: Arc<CrlCache>,
		sources: Vec<CrlSourceId>,
		cas: Arc<RootCertStore>,
		allow_unauthenticated: bool,
	) -> Arc<Self> {
		let root_hint_subjects = cas.subjects();
		Arc::new(Self {
			cache,
			sources,
			cas,
			allow_unauthenticated,
			root_hint_subjects,
			cached: ArcSwapOption::from(None),
		})
	}

	fn build_inner(&self) -> Result<Arc<dyn ClientCertVerifier>, rustls::Error> {
		let crls = self
			.cache
			.snapshot(&self.sources)
			.map_err(|e| rustls::Error::General(format!("crl unavailable: {e}")))?;
		let fp = fingerprint(&crls);
		if let Some(hit) = self.cached.load_full()
			&& hit.fingerprint == fp
		{
			return Ok(Arc::clone(&hit.verifier));
		}
		let mut builder = WebPkiClientVerifier::builder(Arc::clone(&self.cas));
		if !crls.is_empty() {
			builder = builder.with_crls(build_owned(&crls));
		}
		if self.allow_unauthenticated {
			builder = builder.allow_unauthenticated();
		}
		let verifier =
			builder.build().map_err(|e| rustls::Error::General(format!("verifier build: {e}")))?;
		let verifier: Arc<dyn ClientCertVerifier> = verifier;
		self
			.cached
			.store(Some(Arc::new(CachedClient { fingerprint: fp, verifier: Arc::clone(&verifier) })));
		Ok(verifier)
	}
}

impl ClientCertVerifier for RefreshableClientCertVerifier {
	fn offer_client_auth(&self) -> bool {
		true
	}

	fn client_auth_mandatory(&self) -> bool {
		!self.allow_unauthenticated
	}

	fn root_hint_subjects(&self) -> &[DistinguishedName] {
		&self.root_hint_subjects
	}

	fn verify_client_cert(
		&self,
		end_entity: &CertificateDer<'_>,
		intermediates: &[CertificateDer<'_>],
		now: UnixTime,
	) -> Result<ClientCertVerified, rustls::Error> {
		self.build_inner()?.verify_client_cert(end_entity, intermediates, now)
	}

	fn verify_tls12_signature(
		&self,
		message: &[u8],
		cert: &CertificateDer<'_>,
		dss: &DigitallySignedStruct,
	) -> Result<HandshakeSignatureValid, rustls::Error> {
		// Defer to the process-wide rustls crypto provider — must be
		// installed by the host before any handshake runs.
		rustls::crypto::verify_tls12_signature(
			message,
			cert,
			dss,
			&rustls::crypto::CryptoProvider::get_default()
				.expect("rustls crypto provider installed at boot")
				.signature_verification_algorithms,
		)
	}

	fn verify_tls13_signature(
		&self,
		message: &[u8],
		cert: &CertificateDer<'_>,
		dss: &DigitallySignedStruct,
	) -> Result<HandshakeSignatureValid, rustls::Error> {
		rustls::crypto::verify_tls13_signature(
			message,
			cert,
			dss,
			&rustls::crypto::CryptoProvider::get_default()
				.expect("rustls crypto provider installed at boot")
				.signature_verification_algorithms,
		)
	}

	fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
		rustls::crypto::CryptoProvider::get_default()
			.expect("rustls crypto provider installed at boot")
			.signature_verification_algorithms
			.supported_schemes()
	}
}

/// Upstream-side counterpart. Reuses a cached `WebPkiServerVerifier`
/// across handshakes when the CRL snapshot's Arc identity is
/// unchanged; rebuilds only after a refresh swaps the underlying
/// bytes.
pub struct RefreshableServerCertVerifier {
	cache: Arc<CrlCache>,
	sources: Vec<CrlSourceId>,
	cas: Arc<RootCertStore>,
	cached: ArcSwapOption<CachedServer>,
}

impl std::fmt::Debug for RefreshableServerCertVerifier {
	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
		f.debug_struct("RefreshableServerCertVerifier")
			.field("sources", &self.sources)
			.finish_non_exhaustive()
	}
}

impl RefreshableServerCertVerifier {
	#[must_use]
	pub fn new(
		cache: Arc<CrlCache>,
		sources: Vec<CrlSourceId>,
		cas: Arc<RootCertStore>,
	) -> Arc<Self> {
		Arc::new(Self { cache, sources, cas, cached: ArcSwapOption::from(None) })
	}

	fn build_inner(&self) -> Result<Arc<dyn ServerCertVerifier>, rustls::Error> {
		let crls = self
			.cache
			.snapshot(&self.sources)
			.map_err(|e| rustls::Error::General(format!("crl unavailable: {e}")))?;
		let fp = fingerprint(&crls);
		if let Some(hit) = self.cached.load_full()
			&& hit.fingerprint == fp
		{
			return Ok(Arc::clone(&hit.verifier));
		}
		let mut builder = rustls::client::WebPkiServerVerifier::builder(Arc::clone(&self.cas));
		if !crls.is_empty() {
			builder = builder.with_crls(build_owned(&crls));
		}
		let inner =
			builder.build().map_err(|e| rustls::Error::General(format!("verifier build: {e}")))?;
		let verifier: Arc<dyn ServerCertVerifier> = inner;
		self
			.cached
			.store(Some(Arc::new(CachedServer { fingerprint: fp, verifier: Arc::clone(&verifier) })));
		Ok(verifier)
	}
}

impl ServerCertVerifier for RefreshableServerCertVerifier {
	fn verify_server_cert(
		&self,
		end_entity: &CertificateDer<'_>,
		intermediates: &[CertificateDer<'_>],
		server_name: &ServerName<'_>,
		ocsp_response: &[u8],
		now: UnixTime,
	) -> Result<ServerCertVerified, rustls::Error> {
		self.build_inner()?.verify_server_cert(
			end_entity,
			intermediates,
			server_name,
			ocsp_response,
			now,
		)
	}

	fn verify_tls12_signature(
		&self,
		message: &[u8],
		cert: &CertificateDer<'_>,
		dss: &DigitallySignedStruct,
	) -> Result<HandshakeSignatureValid, rustls::Error> {
		rustls::crypto::verify_tls12_signature(
			message,
			cert,
			dss,
			&rustls::crypto::CryptoProvider::get_default()
				.expect("rustls crypto provider installed at boot")
				.signature_verification_algorithms,
		)
	}

	fn verify_tls13_signature(
		&self,
		message: &[u8],
		cert: &CertificateDer<'_>,
		dss: &DigitallySignedStruct,
	) -> Result<HandshakeSignatureValid, rustls::Error> {
		rustls::crypto::verify_tls13_signature(
			message,
			cert,
			dss,
			&rustls::crypto::CryptoProvider::get_default()
				.expect("rustls crypto provider installed at boot")
				.signature_verification_algorithms,
		)
	}

	fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
		rustls::crypto::CryptoProvider::get_default()
			.expect("rustls crypto provider installed at boot")
			.signature_verification_algorithms
			.supported_schemes()
	}
}

#[cfg(test)]
mod tests {
	use std::sync::Arc;
	use std::sync::atomic::{AtomicUsize, Ordering};

	use async_trait::async_trait;
	use rustls::RootCertStore;

	use super::*;
	use crate::cache::{CrlCache, CrlFetchFailure, CrlFetcher, CrlSourceId};

	struct StaticFetcher {
		bytes: Vec<u8>,
		count: AtomicUsize,
	}

	#[async_trait]
	impl CrlFetcher for StaticFetcher {
		async fn fetch(&self, _src: &CrlSourceId) -> Result<Vec<u8>, String> {
			self.count.fetch_add(1, Ordering::SeqCst);
			Ok(self.bytes.clone())
		}
	}

	struct FailingFetcher;

	#[async_trait]
	impl CrlFetcher for FailingFetcher {
		async fn fetch(&self, _src: &CrlSourceId) -> Result<Vec<u8>, String> {
			Err("test failure".into())
		}
	}

	fn install_crypto_once() {
		// Idempotent — `install_default` is best-effort and other tests
		// in this crate also call it. Ignore the result.
		let _ = rustls::crypto::aws_lc_rs::default_provider().install_default();
	}

	fn ca_only_root_store() -> (Arc<RootCertStore>, rcgen::Issuer<'static, rcgen::KeyPair>) {
		use rcgen::{BasicConstraints, CertificateParams, IsCa, Issuer, KeyPair, KeyUsagePurpose};
		let mut params = CertificateParams::new(vec!["test ca".into()]).expect("ca params");
		params.is_ca = IsCa::Ca(BasicConstraints::Unconstrained);
		params.key_usages = vec![
			KeyUsagePurpose::KeyCertSign,
			KeyUsagePurpose::DigitalSignature,
			KeyUsagePurpose::CrlSign,
		];
		let key = KeyPair::generate().expect("ca key");
		let cert = params.clone().self_signed(&key).expect("self-sign ca");
		let cert_der = cert.der().clone();
		let issuer = Issuer::new(params, key);
		let mut store = RootCertStore::empty();
		store.add(cert_der).expect("add ca");
		(Arc::new(store), issuer)
	}

	fn fixture_crl(issuer: &rcgen::Issuer<'_, rcgen::KeyPair>, revoked: &[u64]) -> Vec<u8> {
		use rcgen::{
			CertificateRevocationListParams, KeyIdMethod, RevocationReason, RevokedCertParams,
			SerialNumber,
		};
		let now = time::OffsetDateTime::now_utc();
		let params = CertificateRevocationListParams {
			this_update: now,
			next_update: now + time::Duration::hours(24),
			crl_number: SerialNumber::from(1u64),
			issuing_distribution_point: None,
			revoked_certs: revoked
				.iter()
				.map(|s| RevokedCertParams {
					serial_number: SerialNumber::from(*s),
					revocation_time: now,
					reason_code: Some(RevocationReason::KeyCompromise),
					invalidity_date: None,
				})
				.collect(),
			key_identifier_method: KeyIdMethod::Sha256,
		};
		params.signed_by(issuer).expect("sign crl").der().as_ref().to_vec()
	}

	#[tokio::test(flavor = "multi_thread")]
	async fn client_verifier_builds_with_empty_cache_when_no_sources() {
		install_crypto_once();
		let (cas, _issuer) = ca_only_root_store();
		let fetcher = Arc::new(StaticFetcher { bytes: vec![], count: AtomicUsize::new(0) });
		let cache = CrlCache::new(fetcher);
		let v = RefreshableClientCertVerifier::new(cache, Vec::new(), cas, false);
		assert!(v.build_inner().is_ok());
		assert!(v.client_auth_mandatory());
	}

	#[tokio::test(flavor = "multi_thread")]
	async fn client_verifier_propagates_reject_unavailable() {
		install_crypto_once();
		let (cas, _issuer) = ca_only_root_store();
		let cache = CrlCache::new(Arc::new(FailingFetcher));
		let src = CrlSourceId::Url("https://crl.example/down".into());
		let _ = cache.ensure_loaded(&[(src.clone(), CrlFetchFailure::Reject)]);
		let v = RefreshableClientCertVerifier::new(cache, vec![src], cas, false);
		let err = v.build_inner().expect_err("reject unavailable must fail");
		match err {
			rustls::Error::General(msg) => assert!(msg.contains("crl unavailable"), "{msg}"),
			other => panic!("unexpected: {other:?}"),
		}
	}

	#[tokio::test(flavor = "multi_thread")]
	async fn server_verifier_builds_with_real_crl_bytes() {
		install_crypto_once();
		let (cas, issuer) = ca_only_root_store();
		let bytes = fixture_crl(&issuer, &[42]);
		let fetcher = Arc::new(StaticFetcher { bytes, count: AtomicUsize::new(0) });
		let cache = CrlCache::new(fetcher);
		let src = CrlSourceId::Url("https://crl.example/with-revoke".into());
		cache.ensure_loaded(&[(src.clone(), CrlFetchFailure::Tolerate)]).expect("load");
		let v = RefreshableServerCertVerifier::new(cache, vec![src], cas);
		assert!(v.build_inner().is_ok());
	}

	// Test-only fetcher that serves a different byte string on the
	// second fetch so we can simulate a real CRL rotation without
	// rebuilding the cache from scratch.
	struct SwapFetcher {
		calls: AtomicUsize,
		first: Vec<u8>,
		second: Vec<u8>,
	}

	#[async_trait]
	impl CrlFetcher for SwapFetcher {
		async fn fetch(&self, _src: &CrlSourceId) -> Result<Vec<u8>, String> {
			let n = self.calls.fetch_add(1, Ordering::SeqCst);
			Ok(if n == 0 { self.first.clone() } else { self.second.clone() })
		}
	}

	#[tokio::test(flavor = "multi_thread")]
	async fn client_verifier_reuses_cached_inner_until_crl_arc_changes() {
		install_crypto_once();
		let (cas, issuer) = ca_only_root_store();
		let bytes_v1 = fixture_crl(&issuer, &[1]);
		let bytes_v2 = fixture_crl(&issuer, &[1, 2]);
		let fetcher =
			Arc::new(SwapFetcher { calls: AtomicUsize::new(0), first: bytes_v1, second: bytes_v2 });
		let cache = CrlCache::new(fetcher);
		let src = CrlSourceId::Url("https://crl.example/cached".into());
		cache.ensure_loaded(&[(src.clone(), CrlFetchFailure::Tolerate)]).expect("load v1");
		let v = RefreshableClientCertVerifier::new(cache.clone(), vec![src.clone()], cas, false);
		let a = v.build_inner().expect("build a");
		let b = v.build_inner().expect("build b");
		assert!(Arc::ptr_eq(&a, &b), "cache hit reuses the same inner verifier Arc");

		// Refresh: cache now serves the v2 bytes, so a new build is
		// required.
		cache.ensure_loaded(&[(src, CrlFetchFailure::Tolerate)]).expect("refresh to v2");
		let c = v.build_inner().expect("build c");
		assert!(!Arc::ptr_eq(&b, &c), "post-refresh forces a rebuild");
	}

	#[tokio::test(flavor = "multi_thread")]
	async fn allow_unauthenticated_flips_mandatory_flag() {
		install_crypto_once();
		let (cas, _issuer) = ca_only_root_store();
		let fetcher = Arc::new(StaticFetcher { bytes: vec![], count: AtomicUsize::new(0) });
		let cache = CrlCache::new(fetcher);
		let v_mandatory =
			RefreshableClientCertVerifier::new(Arc::clone(&cache), Vec::new(), Arc::clone(&cas), false);
		let v_request = RefreshableClientCertVerifier::new(cache, Vec::new(), cas, true);
		assert!(v_mandatory.client_auth_mandatory());
		assert!(!v_request.client_auth_mandatory());
	}
}