1use std::collections::{HashMap, HashSet, VecDeque};
41#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
42use std::io::Read;
43use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
44#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
45use std::net::{SocketAddr, ToSocketAddrs};
46use std::sync::{Arc, LazyLock};
47use std::time::{Duration, Instant};
48
49use regex::Regex;
50#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
51use reqwest::header::{ACCEPT, CONTENT_ENCODING, CONTENT_LENGTH, CONTENT_TYPE};
52#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
53use reqwest::redirect::Policy;
54#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
55use reqwest::StatusCode;
56use serde::Deserialize;
57use serde_json::Value;
58use url::Url;
59
60use crate::error::{VcpError, VcpResult};
61
62static STRICT_RFC3339: LazyLock<Regex> = LazyLock::new(|| {
63 Regex::new(
64 r"^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(?:\.[0-9]+)?(?:Z|[+-][0-9]{2}:[0-9]{2})$",
65 )
66 .expect("strict RFC 3339 regex is valid")
67});
68
69fn parse_strict_rfc3339(
70 value: &str,
71 field: &str,
72) -> VcpResult<chrono::DateTime<chrono::FixedOffset>> {
73 if !STRICT_RFC3339.is_match(value) {
74 return Err(VcpError::RevocationError(format!(
75 "invalid CRL {field}: expected strict RFC 3339"
76 )));
77 }
78 chrono::DateTime::parse_from_rfc3339(value)
79 .map_err(|error| VcpError::RevocationError(format!("invalid CRL {field}: {error}")))
80}
81
82#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
86pub enum RevocationDecision {
87 #[default]
89 NotRevoked,
90 Revoked,
92 Unavailable,
94}
95
96#[derive(Debug, Clone, Default)]
98pub struct RevocationStatus {
99 pub decision: RevocationDecision,
101 pub revoked: bool,
103 pub reason: Option<String>,
105 pub revoked_at: Option<String>,
107}
108
109impl RevocationStatus {
110 pub fn not_revoked() -> Self {
112 Self::default()
113 }
114
115 pub fn revoked(reason: impl Into<String>, revoked_at: impl Into<String>) -> Self {
117 Self {
118 decision: RevocationDecision::Revoked,
119 revoked: true,
120 reason: Some(reason.into()),
121 revoked_at: Some(revoked_at.into()),
122 }
123 }
124
125 pub fn unavailable() -> Self {
127 Self {
128 decision: RevocationDecision::Unavailable,
129 revoked: false,
130 reason: Some("revocation_status_unavailable".to_string()),
131 revoked_at: None,
132 }
133 }
134
135 pub fn should_reject(&self) -> bool {
137 self.decision != RevocationDecision::NotRevoked
138 }
139}
140
141pub fn is_private_ip(ip: IpAddr) -> bool {
149 match ip {
150 IpAddr::V4(v4) => is_private_ipv4(v4),
151 IpAddr::V6(v6) => is_private_ipv6(v6),
152 }
153}
154
155fn is_private_ipv4(ip: Ipv4Addr) -> bool {
157 let octets = ip.octets();
158 matches!(
159 octets,
160 [0 | 10 | 127 | 224..=239 | 240..=255, ..]
161 | [100, 64..=127, ..]
162 | [169, 254, ..]
163 | [172, 16..=31, ..]
164 | [192, 0, 0 | 2, ..]
165 | [192, 88, 99, ..]
166 | [192, 168, ..]
167 | [198, 18..=19, ..]
168 | [198, 51, 100, ..]
169 | [203, 0, 113, ..]
170 )
171}
172
173fn is_private_ipv6(ip: Ipv6Addr) -> bool {
175 if let Some(mapped) = ip.to_ipv4_mapped() {
176 return is_private_ipv4(mapped);
177 }
178 if ip == Ipv6Addr::LOCALHOST {
180 return true;
181 }
182 let segments = ip.segments();
183 if segments[0] & 0xffc0 == 0xfe80 || segments[0] & 0xffc0 == 0xfec0 {
185 return true;
186 }
187 if segments[0] & 0xfe00 == 0xfc00 {
189 return true;
190 }
191 if ip == Ipv6Addr::UNSPECIFIED {
193 return true;
194 }
195 if segments[0] & 0xff00 == 0xff00 {
197 return true;
198 }
199 if segments[0] == 0x0064 && segments[1] == 0xff9b && segments[2] == 0x0001 {
201 return true;
202 }
203 if segments[..6] == [0x0064, 0xff9b, 0, 0, 0, 0] {
206 return true;
207 }
208 if segments[..6] == [0, 0, 0, 0, 0, 0] {
211 return true;
212 }
213 if segments[0] == 0x0100 && segments[1..4] == [0, 0, 0] {
215 return true;
216 }
217 if segments[0] == 0x2001 && segments[1] <= 0x01ff {
219 return true;
220 }
221 if segments[0] == 0x2001 && segments[1] == 0x0db8 {
223 return true;
224 }
225 if segments[0] == 0x2002 {
227 return true;
228 }
229 if segments[0] == 0x3fff && segments[1] & 0xf000 == 0 {
231 return true;
232 }
233 if segments[0] == 0x5f00 {
235 return true;
236 }
237 false
238}
239
240pub fn validate_uri(uri: &str) -> VcpResult<()> {
250 let (scheme, rest) = uri
252 .split_once("://")
253 .ok_or_else(|| VcpError::RevocationError(format!("invalid URI (no scheme): {uri}")))?;
254
255 let scheme_lower = scheme.to_ascii_lowercase();
256 if scheme_lower != "https" {
257 return Err(VcpError::RevocationError(format!(
258 "unsupported URI scheme '{scheme}': only https is allowed"
259 )));
260 }
261
262 if uri.contains('#') {
263 return Err(VcpError::RevocationError(format!(
264 "fragments are not allowed in URI: {uri}"
265 )));
266 }
267
268 let authority = rest.split(['/', '?', '#']).next().unwrap_or(rest);
270 if authority.contains('@') {
271 return Err(VcpError::RevocationError(format!(
272 "credentials are not allowed in URI: {uri}"
273 )));
274 }
275 let (host, port) = if let Some(bracketed) = authority.strip_prefix('[') {
276 let (address, suffix) = bracketed.split_once(']').ok_or_else(|| {
277 VcpError::RevocationError(format!("invalid bracketed IPv6 host in URI: {uri}"))
278 })?;
279 let parsed_port =
280 if suffix.is_empty() {
281 None
282 } else if let Some(raw_port) = suffix.strip_prefix(':') {
283 Some(raw_port.parse::<u16>().map_err(|_| {
284 VcpError::RevocationError(format!("invalid port in URI: {uri}"))
285 })?)
286 } else {
287 return Err(VcpError::RevocationError(format!(
288 "invalid authority in URI: {uri}"
289 )));
290 };
291 (address, parsed_port)
292 } else if let Some((h, p)) = authority.rsplit_once(':') {
293 if h.contains(':') {
294 return Err(VcpError::RevocationError(format!(
295 "IPv6 hosts must be bracketed in URI: {uri}"
296 )));
297 }
298 let parsed_port = p
299 .parse::<u16>()
300 .map_err(|_| VcpError::RevocationError(format!("invalid port in URI: {uri}")))?;
301 (h, Some(parsed_port))
302 } else {
303 (authority, None)
304 };
305
306 if port.is_some_and(|port| port != 443) {
307 return Err(VcpError::RevocationError(format!(
308 "non-standard HTTPS port in URI: {uri}"
309 )));
310 }
311
312 let clean_host = host.trim_end_matches('.').to_ascii_lowercase();
315 if clean_host.is_empty()
316 || clean_host.chars().any(char::is_whitespace)
317 || clean_host.contains('%')
318 {
319 return Err(VcpError::RevocationError(format!(
320 "invalid host in URI: {uri}"
321 )));
322 }
323 if let Ok(ip) = clean_host.parse::<IpAddr>() {
324 if is_private_ip(ip) {
325 return Err(VcpError::RevocationError(format!(
326 "private/reserved IP address in URI: {uri}"
327 )));
328 }
329 }
330
331 if clean_host == "localhost" || clean_host.ends_with(".localhost") {
334 return Err(VcpError::RevocationError(format!(
335 "localhost is not allowed in URI: {uri}"
336 )));
337 }
338
339 Ok(())
340}
341
342pub const MAX_RESPONSE_BYTES: usize = 327_680;
344pub const MAX_RESPONSE_HEADERS: usize = 64;
346pub const MAX_RESPONSE_HEADER_BYTES: usize = 32_768;
348
349pub trait RevocationTransport: Send + Sync {
354 fn get_json(&self, uri: &str, timeout: Duration) -> VcpResult<Value>;
361}
362
363#[derive(Debug, Clone, Copy, Default)]
369pub struct ReqwestRevocationTransport;
370
371#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
372impl RevocationTransport for ReqwestRevocationTransport {
373 fn get_json(&self, uri: &str, timeout: Duration) -> VcpResult<Value> {
374 validate_uri(uri)?;
375 if timeout.is_zero() {
376 return Err(VcpError::RevocationError(
377 "revocation timeout must be positive".to_string(),
378 ));
379 }
380
381 let url = Url::parse(uri).map_err(|error| {
382 VcpError::RevocationError(format!("invalid revocation URI: {error}"))
383 })?;
384 let host = url.host_str().ok_or_else(|| {
385 VcpError::RevocationError("revocation URI requires a hostname".to_string())
386 })?;
387 let port = url.port_or_known_default().ok_or_else(|| {
388 VcpError::RevocationError("revocation URI requires a known HTTPS port".to_string())
389 })?;
390 let addresses = resolve_public_addresses(host, port)?;
391
392 let client = build_revocation_client(host, &addresses, timeout)?;
393 let response = client
394 .get(url)
395 .header(ACCEPT, "application/json")
396 .header("Accept-Encoding", "identity")
397 .send()
398 .map_err(|error| {
399 VcpError::RevocationError(format!("revocation request failed: {error}"))
400 })?;
401
402 parse_json_response(response)
403 }
404}
405
406#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
407impl RevocationTransport for ReqwestRevocationTransport {
408 fn get_json(&self, uri: &str, timeout: Duration) -> VcpResult<Value> {
409 validate_uri(uri)?;
410 if timeout.is_zero() {
411 return Err(VcpError::RevocationError(
412 "revocation timeout must be positive".to_string(),
413 ));
414 }
415 Err(VcpError::RevocationError(
416 "live revocation transport is unavailable on wasm32-unknown-unknown; inject a host transport or preload a CRL"
417 .to_string(),
418 ))
419 }
420}
421
422#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
423fn build_revocation_client(
424 host: &str,
425 addresses: &[SocketAddr],
426 timeout: Duration,
427) -> VcpResult<reqwest::blocking::Client> {
428 let connect_timeout = std::cmp::min(timeout, Duration::from_secs(5));
429 reqwest::blocking::Client::builder()
430 .tls_backend_rustls()
431 .https_only(true)
432 .no_proxy()
433 .redirect(Policy::none())
434 .retry(reqwest::retry::never())
435 .referer(false)
436 .timeout(timeout)
437 .connect_timeout(connect_timeout)
438 .pool_max_idle_per_host(0)
439 .http1_only()
440 .http1_allow_obsolete_multiline_headers_in_responses(false)
441 .http1_ignore_invalid_headers_in_responses(false)
442 .http1_allow_spaces_after_header_name_in_responses(false)
443 .no_gzip()
444 .no_brotli()
445 .no_deflate()
446 .no_zstd()
447 .no_hickory_dns()
448 .tls_sni(true)
449 .resolve_to_addrs(host, addresses)
450 .build()
451 .map_err(|error| {
452 VcpError::RevocationError(format!("failed to build revocation client: {error}"))
453 })
454}
455
456#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
457fn parse_json_response(mut response: reqwest::blocking::Response) -> VcpResult<Value> {
458 if response.status() != StatusCode::OK {
459 return Err(VcpError::RevocationError(format!(
460 "revocation endpoint returned HTTP {}",
461 response.status()
462 )));
463 }
464
465 validate_response_headers(response.headers())?;
466 if response
467 .headers()
468 .get(CONTENT_ENCODING)
469 .is_some_and(|value| !value.as_bytes().eq_ignore_ascii_case(b"identity"))
470 {
471 return Err(VcpError::RevocationError(
472 "compressed revocation responses are not accepted".to_string(),
473 ));
474 }
475 let content_type = response
476 .headers()
477 .get(CONTENT_TYPE)
478 .and_then(|value| value.to_str().ok())
479 .and_then(|value| value.split(';').next())
480 .map(str::trim)
481 .unwrap_or_default()
482 .to_ascii_lowercase();
483 if content_type != "application/json" && !content_type.ends_with("+json") {
484 return Err(VcpError::RevocationError(
485 "revocation response requires a JSON content type".to_string(),
486 ));
487 }
488 if let Some(length) = response
489 .headers()
490 .get(CONTENT_LENGTH)
491 .and_then(|value| value.to_str().ok())
492 .and_then(|value| value.parse::<u64>().ok())
493 {
494 if length > MAX_RESPONSE_BYTES as u64 {
495 return Err(VcpError::RevocationError(format!(
496 "revocation response exceeds {MAX_RESPONSE_BYTES} bytes"
497 )));
498 }
499 }
500
501 let mut body = Vec::with_capacity(4096);
502 response
503 .by_ref()
504 .take((MAX_RESPONSE_BYTES + 1) as u64)
505 .read_to_end(&mut body)
506 .map_err(|error| {
507 VcpError::RevocationError(format!("failed to read revocation response: {error}"))
508 })?;
509 if body.len() > MAX_RESPONSE_BYTES {
510 return Err(VcpError::RevocationError(format!(
511 "revocation response exceeds {MAX_RESPONSE_BYTES} bytes"
512 )));
513 }
514 let value = crate::strict_json::from_slice(&body)
515 .map_err(|error| VcpError::RevocationError(format!("invalid revocation JSON: {error}")))?;
516 if !value.is_object() {
517 return Err(VcpError::RevocationError(
518 "revocation response must be a JSON object".to_string(),
519 ));
520 }
521 Ok(value)
522}
523
524#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
525fn validate_response_headers(headers: &reqwest::header::HeaderMap) -> VcpResult<()> {
526 if headers.len() > MAX_RESPONSE_HEADERS {
527 return Err(VcpError::RevocationError(format!(
528 "revocation response exceeds {MAX_RESPONSE_HEADERS} headers"
529 )));
530 }
531 let total = headers
532 .iter()
533 .try_fold(0usize, |sum, (name, value)| {
534 sum.checked_add(name.as_str().len())
535 .and_then(|value_sum| value_sum.checked_add(value.as_bytes().len()))
536 })
537 .ok_or_else(|| {
538 VcpError::RevocationError("revocation response header size overflow".to_string())
539 })?;
540 if total > MAX_RESPONSE_HEADER_BYTES {
541 return Err(VcpError::RevocationError(format!(
542 "revocation response headers exceed {MAX_RESPONSE_HEADER_BYTES} bytes"
543 )));
544 }
545 Ok(())
546}
547
548#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
549fn resolve_public_addresses(host: &str, port: u16) -> VcpResult<Vec<SocketAddr>> {
550 let addresses = (host, port).to_socket_addrs().map_err(|error| {
551 VcpError::RevocationError(format!("failed to resolve revocation host: {error}"))
552 })?;
553 validate_resolved_addresses(addresses)
554}
555
556#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
557fn validate_resolved_addresses(
558 addresses: impl IntoIterator<Item = SocketAddr>,
559) -> VcpResult<Vec<SocketAddr>> {
560 let mut addresses: Vec<_> = addresses.into_iter().collect();
561 addresses.sort_unstable();
562 addresses.dedup();
563 if addresses.is_empty() {
564 return Err(VcpError::RevocationError(
565 "revocation hostname resolved to no addresses".to_string(),
566 ));
567 }
568 if addresses.iter().any(|address| is_private_ip(address.ip())) {
569 return Err(VcpError::RevocationError(
570 "revocation hostname resolved to a private or reserved address".to_string(),
571 ));
572 }
573 Ok(addresses)
574}
575
576#[derive(Debug, Clone, Deserialize)]
580pub struct CrlEntry {
581 pub jti: String,
583 pub revoked_at: String,
585 pub reason: String,
587}
588
589#[derive(Debug, Clone, Deserialize)]
591pub struct Crl {
592 pub issuer: String,
594 pub updated_at: String,
596 pub next_update: String,
598 pub revoked: Vec<CrlEntry>,
600}
601
602impl Crl {
603 pub fn find(&self, jti: &str) -> Option<&CrlEntry> {
607 self.revoked.iter().find(|entry| entry.jti == jti)
608 }
609
610 fn validate(
611 &self,
612 expected_issuer: Option<&str>,
613 ) -> VcpResult<chrono::DateTime<chrono::FixedOffset>> {
614 if self.issuer.trim().is_empty() {
615 return Err(VcpError::RevocationError(
616 "CRL issuer must not be empty".to_string(),
617 ));
618 }
619 if let Some(expected) = expected_issuer {
620 if expected.trim().is_empty() || self.issuer != expected {
621 return Err(VcpError::RevocationError(
622 "CRL issuer does not match expected issuer".to_string(),
623 ));
624 }
625 }
626 let updated_at = parse_strict_rfc3339(&self.updated_at, "updated_at")?;
627 let next_update = parse_strict_rfc3339(&self.next_update, "next_update")?;
628 if updated_at > next_update {
629 return Err(VcpError::RevocationError(
630 "CRL updated_at must not be after next_update".to_string(),
631 ));
632 }
633 let mut seen = HashSet::new();
634 for entry in &self.revoked {
635 if entry.jti.trim().is_empty() {
636 return Err(VcpError::RevocationError(
637 "CRL entry jti must not be empty".to_string(),
638 ));
639 }
640 parse_strict_rfc3339(&entry.revoked_at, "revoked[].revoked_at")?;
641 if entry.reason.trim().is_empty() {
642 return Err(VcpError::RevocationError(
643 "CRL entry reason must not be empty".to_string(),
644 ));
645 }
646 if !seen.insert(entry.jti.as_str()) {
647 return Err(VcpError::RevocationError(format!(
648 "CRL contains duplicate jti {:?}",
649 entry.jti
650 )));
651 }
652 }
653 Ok(next_update)
654 }
655
656 pub fn from_json(json_str: &str) -> VcpResult<Self> {
663 if json_str.len() > MAX_RESPONSE_BYTES {
664 return Err(VcpError::RevocationError(format!(
665 "CRL exceeds {MAX_RESPONSE_BYTES} bytes"
666 )));
667 }
668 let value = crate::strict_json::from_str(json_str)
669 .map_err(|e| VcpError::RevocationError(format!("failed to parse CRL: {e}")))?;
670 let crl: Self = serde_json::from_value(value)
671 .map_err(|e| VcpError::RevocationError(format!("failed to parse CRL: {e}")))?;
672 crl.validate(None)?;
673 Ok(crl)
674 }
675}
676
677#[derive(Debug, Deserialize)]
678struct OnlineRevocationResponse {
679 revoked: bool,
680 jti: String,
681 issuer: String,
682 #[serde(default)]
683 reason: Option<String>,
684 #[serde(default)]
685 revoked_at: Option<String>,
686}
687
688impl OnlineRevocationResponse {
689 fn into_status(self, expected_jti: &str, expected_issuer: &str) -> VcpResult<RevocationStatus> {
690 if self.jti != expected_jti {
691 return Err(VcpError::RevocationError(
692 "online revocation response JTI does not match the request".to_string(),
693 ));
694 }
695 if self.issuer != expected_issuer {
696 return Err(VcpError::RevocationError(
697 "online revocation response issuer does not match the request".to_string(),
698 ));
699 }
700 if self.revoked {
701 let reason = self
702 .reason
703 .filter(|value| !value.trim().is_empty())
704 .ok_or_else(|| {
705 VcpError::RevocationError(
706 "confirmed revocation requires a non-empty reason".to_string(),
707 )
708 })?;
709 let revoked_at = self.revoked_at.ok_or_else(|| {
710 VcpError::RevocationError("confirmed revocation requires revoked_at".to_string())
711 })?;
712 parse_strict_rfc3339(&revoked_at, "online.revoked_at")?;
713 Ok(RevocationStatus::revoked(reason, revoked_at))
714 } else {
715 if self.reason.is_some() || self.revoked_at.is_some() {
716 return Err(VcpError::RevocationError(
717 "non-revoked response must not include revocation details".to_string(),
718 ));
719 }
720 Ok(RevocationStatus::not_revoked())
721 }
722 }
723}
724
725pub struct RevocationChecker {
737 cache_ttl: Duration,
739 timeout: Duration,
741 cache: HashMap<(String, String, String), CachedDecision>,
743 cache_order: VecDeque<(String, String, String)>,
744 crl_cache: HashMap<String, (Crl, Instant)>,
746 crl_order: VecDeque<String>,
747 max_cache_entries: usize,
748 max_crl_cache_entries: usize,
749 transport: Arc<dyn RevocationTransport>,
750}
751
752const DEFAULT_MAX_CACHE_ENTRIES: usize = 4096;
753const DEFAULT_MAX_CRL_CACHE_ENTRIES: usize = 256;
754
755struct CachedDecision {
756 status: RevocationStatus,
757 expires_at: Instant,
758}
759
760impl std::fmt::Debug for RevocationChecker {
761 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
762 f.debug_struct("RevocationChecker")
763 .field("cache_ttl", &self.cache_ttl)
764 .field("timeout", &self.timeout)
765 .field("cache_entries", &self.cache.len())
766 .field("cache_order", &self.cache_order.len())
767 .field("crl_entries", &self.crl_cache.len())
768 .field("crl_order", &self.crl_order.len())
769 .field("max_cache_entries", &self.max_cache_entries)
770 .field("max_crl_cache_entries", &self.max_crl_cache_entries)
771 .field("transport", &"dyn RevocationTransport")
772 .finish()
773 }
774}
775
776impl RevocationChecker {
777 pub fn new(cache_ttl: Duration, timeout: Duration) -> Self {
784 Self::with_limits(
785 cache_ttl,
786 timeout,
787 DEFAULT_MAX_CACHE_ENTRIES,
788 DEFAULT_MAX_CRL_CACHE_ENTRIES,
789 )
790 }
791
792 pub fn with_limits(
798 cache_ttl: Duration,
799 timeout: Duration,
800 max_cache_entries: usize,
801 max_crl_cache_entries: usize,
802 ) -> Self {
803 Self::with_limits_and_transport(
804 cache_ttl,
805 timeout,
806 max_cache_entries,
807 max_crl_cache_entries,
808 Arc::new(ReqwestRevocationTransport),
809 )
810 }
811
812 pub fn with_transport<T>(cache_ttl: Duration, timeout: Duration, transport: T) -> Self
814 where
815 T: RevocationTransport + 'static,
816 {
817 Self::with_limits_and_transport(
818 cache_ttl,
819 timeout,
820 DEFAULT_MAX_CACHE_ENTRIES,
821 DEFAULT_MAX_CRL_CACHE_ENTRIES,
822 Arc::new(transport),
823 )
824 }
825
826 fn with_limits_and_transport(
827 cache_ttl: Duration,
828 timeout: Duration,
829 max_cache_entries: usize,
830 max_crl_cache_entries: usize,
831 transport: Arc<dyn RevocationTransport>,
832 ) -> Self {
833 assert!(
834 max_cache_entries > 0,
835 "decision cache limit must be positive"
836 );
837 assert!(
838 max_crl_cache_entries > 0,
839 "CRL cache limit must be positive"
840 );
841 Self {
842 cache_ttl,
843 timeout,
844 cache: HashMap::new(),
845 cache_order: VecDeque::new(),
846 crl_cache: HashMap::new(),
847 crl_order: VecDeque::new(),
848 max_cache_entries,
849 max_crl_cache_entries,
850 transport,
851 }
852 }
853
854 fn cache_key(uri: &str, expected_issuer: Option<&str>, jti: &str) -> (String, String, String) {
855 (
856 uri.to_string(),
857 expected_issuer.unwrap_or_default().to_string(),
858 jti.to_string(),
859 )
860 }
861
862 fn cached(&mut self, key: &(String, String, String)) -> Option<RevocationStatus> {
863 match self.cache.get(key) {
864 Some(entry) if entry.expires_at > Instant::now() => {
865 return Some(entry.status.clone());
866 }
867 Some(_) => {}
868 None => return None,
869 }
870 self.cache.remove(key);
871 self.cache_order.retain(|candidate| candidate != key);
872 None
873 }
874
875 fn insert_decision(
876 &mut self,
877 key: (String, String, String),
878 status: RevocationStatus,
879 ttl: Duration,
880 ) {
881 let now = Instant::now();
882 let Some(expires_at) = now.checked_add(ttl) else {
883 return;
886 };
887 self.cache.retain(|_, entry| entry.expires_at > now);
888 self.cache_order
889 .retain(|candidate| candidate != &key && self.cache.contains_key(candidate));
890 while self.cache.len() >= self.max_cache_entries {
891 let Some(oldest) = self.cache_order.pop_front() else {
892 break;
893 };
894 self.cache.remove(&oldest);
895 }
896 self.cache_order.push_back(key.clone());
897 self.cache
898 .insert(key, CachedDecision { status, expires_at });
899 }
900
901 pub fn check(
912 &mut self,
913 jti: &str,
914 check_uri: Option<&str>,
915 crl_uri: Option<&str>,
916 ) -> RevocationStatus {
917 self.check_with_issuer(jti, check_uri, crl_uri, None)
918 }
919
920 pub fn check_with_issuer(
922 &mut self,
923 jti: &str,
924 check_uri: Option<&str>,
925 crl_uri: Option<&str>,
926 expected_issuer: Option<&str>,
927 ) -> RevocationStatus {
928 if jti.trim().is_empty()
929 || expected_issuer.is_some_and(|issuer| issuer.trim().is_empty())
930 || ((check_uri.is_some() || crl_uri.is_some()) && expected_issuer.is_none())
931 {
932 return RevocationStatus::unavailable();
933 }
934
935 let mut attempted = false;
936
937 if let Some(uri) = check_uri {
939 attempted = true;
940 let key = Self::cache_key(uri, expected_issuer, jti);
941 if let Some(status) = self.cached(&key) {
942 return status;
943 }
944 let Some(issuer) = expected_issuer else {
945 return RevocationStatus::unavailable();
946 };
947 if let Ok(status) = self.check_online(uri, jti, issuer) {
948 self.insert_decision(key, status.clone(), self.cache_ttl);
949 return status;
950 }
951 }
952
953 if let Some(uri) = crl_uri {
955 attempted = true;
956 let key = Self::cache_key(uri, expected_issuer, jti);
957 if let Some(status) = self.cached(&key) {
958 return status;
959 }
960 if let Ok((status, freshness)) = self.check_crl(uri, jti, expected_issuer) {
961 self.insert_decision(
962 key,
963 status.clone(),
964 std::cmp::min(self.cache_ttl, freshness),
965 );
966 return status;
967 }
968 }
969
970 if attempted {
971 RevocationStatus::unavailable()
972 } else {
973 RevocationStatus::not_revoked()
974 }
975 }
976
977 fn check_online(
981 &self,
982 uri: &str,
983 jti: &str,
984 expected_issuer: &str,
985 ) -> VcpResult<RevocationStatus> {
986 validate_uri(uri)?;
987 let mut url = Url::parse(uri).map_err(|error| {
988 VcpError::RevocationError(format!("invalid revocation URI: {error}"))
989 })?;
990 let retained: Vec<(String, String)> = url
991 .query_pairs()
992 .filter(|(key, _)| key != "jti" && key != "issuer")
993 .map(|(key, value)| (key.into_owned(), value.into_owned()))
994 .collect();
995 url.set_query(None);
996 {
997 let mut query = url.query_pairs_mut();
998 for (key, value) in retained {
999 query.append_pair(&key, &value);
1000 }
1001 query.append_pair("jti", jti);
1002 query.append_pair("issuer", expected_issuer);
1003 }
1004 let value = self.transport.get_json(url.as_str(), self.timeout)?;
1005 let response: OnlineRevocationResponse =
1006 serde_json::from_value(value).map_err(|error| {
1007 VcpError::RevocationError(format!("invalid online revocation response: {error}"))
1008 })?;
1009 response.into_status(jti, expected_issuer)
1010 }
1011
1012 fn check_crl(
1017 &mut self,
1018 uri: &str,
1019 jti: &str,
1020 expected_issuer: Option<&str>,
1021 ) -> VcpResult<(RevocationStatus, Duration)> {
1022 if let Some((crl, cached_at)) = self.crl_cache.get(uri) {
1024 if cached_at.elapsed() < self.cache_ttl {
1025 return crl_lookup_status(crl, jti, expected_issuer);
1026 }
1027 }
1028
1029 validate_uri(uri)?;
1030 let value = self.transport.get_json(uri, self.timeout)?;
1031 let crl: Crl = serde_json::from_value(value)
1032 .map_err(|error| VcpError::RevocationError(format!("failed to parse CRL: {error}")))?;
1033 let (status, freshness) = crl_lookup_status(&crl, jti, expected_issuer)?;
1034 self.insert_crl(uri, crl);
1035 Ok((status, freshness))
1036 }
1037
1038 pub fn insert_crl(&mut self, uri: &str, crl: Crl) {
1041 let uri = uri.to_string();
1042 self.crl_order.retain(|candidate| candidate != &uri);
1043 while self.crl_cache.len() >= self.max_crl_cache_entries {
1044 let Some(oldest) = self.crl_order.pop_front() else {
1045 break;
1046 };
1047 self.crl_cache.remove(&oldest);
1048 }
1049 self.crl_order.push_back(uri.clone());
1050 self.crl_cache.insert(uri, (crl, Instant::now()));
1051 }
1052
1053 pub fn clear_cache(&mut self) {
1055 self.cache.clear();
1056 self.cache_order.clear();
1057 self.crl_cache.clear();
1058 self.crl_order.clear();
1059 }
1060}
1061
1062fn crl_lookup_status(
1064 crl: &Crl,
1065 jti: &str,
1066 expected_issuer: Option<&str>,
1067) -> VcpResult<(RevocationStatus, Duration)> {
1068 let next_update = crl.validate(expected_issuer)?;
1069 if next_update <= chrono::Utc::now() {
1070 return Err(VcpError::RevocationError("CRL is expired".to_string()));
1071 }
1072 let freshness = (next_update.with_timezone(&chrono::Utc) - chrono::Utc::now())
1073 .to_std()
1074 .map_err(|_| VcpError::RevocationError("CRL is expired".to_string()))?;
1075 let status = match crl.find(jti) {
1076 Some(entry) => RevocationStatus::revoked(&entry.reason, &entry.revoked_at),
1077 None => RevocationStatus::not_revoked(),
1078 };
1079 Ok((status, freshness))
1080}
1081
1082#[cfg(test)]
1085mod tests {
1086 use super::*;
1087 use std::sync::Mutex;
1088
1089 #[derive(Clone)]
1090 struct FakeTransport {
1091 responses: Arc<Mutex<VecDeque<Result<Value, String>>>>,
1092 requests: Arc<Mutex<Vec<String>>>,
1093 }
1094
1095 impl FakeTransport {
1096 fn new(responses: impl IntoIterator<Item = Result<Value, String>>) -> Self {
1097 Self {
1098 responses: Arc::new(Mutex::new(responses.into_iter().collect())),
1099 requests: Arc::new(Mutex::new(Vec::new())),
1100 }
1101 }
1102 }
1103
1104 impl RevocationTransport for FakeTransport {
1105 fn get_json(&self, uri: &str, _timeout: Duration) -> VcpResult<Value> {
1106 self.requests.lock().unwrap().push(uri.to_string());
1107 self.responses
1108 .lock()
1109 .unwrap()
1110 .pop_front()
1111 .expect("fake response available")
1112 .map_err(VcpError::RevocationError)
1113 }
1114 }
1115
1116 #[derive(Debug)]
1117 struct RejectZeroTimeoutTransport;
1118
1119 impl RevocationTransport for RejectZeroTimeoutTransport {
1120 fn get_json(&self, _uri: &str, timeout: Duration) -> VcpResult<Value> {
1121 if timeout.is_zero() {
1122 return Err(VcpError::RevocationError(
1123 "revocation timeout must be positive".to_string(),
1124 ));
1125 }
1126 Ok(serde_json::json!({
1127 "revoked": false,
1128 "jti": "jti",
1129 "issuer": "issuer"
1130 }))
1131 }
1132 }
1133
1134 #[test]
1137 fn private_ip_loopback_v4() {
1138 let ip: IpAddr = "127.0.0.1".parse().unwrap();
1139 assert!(is_private_ip(ip));
1140 }
1141
1142 #[test]
1143 fn private_ip_loopback_v4_other() {
1144 let ip: IpAddr = "127.255.255.255".parse().unwrap();
1145 assert!(is_private_ip(ip));
1146 }
1147
1148 #[test]
1149 fn private_ip_10_range() {
1150 let ip: IpAddr = "10.0.0.1".parse().unwrap();
1151 assert!(is_private_ip(ip));
1152 }
1153
1154 #[test]
1155 fn private_ip_10_range_high() {
1156 let ip: IpAddr = "10.255.255.255".parse().unwrap();
1157 assert!(is_private_ip(ip));
1158 }
1159
1160 #[test]
1161 fn private_ip_172_16_range() {
1162 let ip: IpAddr = "172.16.0.1".parse().unwrap();
1163 assert!(is_private_ip(ip));
1164 }
1165
1166 #[test]
1167 fn private_ip_172_31_range() {
1168 let ip: IpAddr = "172.31.255.255".parse().unwrap();
1169 assert!(is_private_ip(ip));
1170 }
1171
1172 #[test]
1173 fn not_private_172_15() {
1174 let ip: IpAddr = "172.15.0.1".parse().unwrap();
1175 assert!(!is_private_ip(ip));
1176 }
1177
1178 #[test]
1179 fn not_private_172_32() {
1180 let ip: IpAddr = "172.32.0.1".parse().unwrap();
1181 assert!(!is_private_ip(ip));
1182 }
1183
1184 #[test]
1185 fn private_ip_192_168_range() {
1186 let ip: IpAddr = "192.168.1.1".parse().unwrap();
1187 assert!(is_private_ip(ip));
1188 }
1189
1190 #[test]
1191 fn private_ip_192_168_0() {
1192 let ip: IpAddr = "192.168.0.0".parse().unwrap();
1193 assert!(is_private_ip(ip));
1194 }
1195
1196 #[test]
1197 fn private_ip_link_local() {
1198 let ip: IpAddr = "169.254.1.1".parse().unwrap();
1199 assert!(is_private_ip(ip));
1200 }
1201
1202 #[test]
1203 fn private_ip_zero_network() {
1204 let ip: IpAddr = "0.0.0.0".parse().unwrap();
1205 assert!(is_private_ip(ip));
1206 }
1207
1208 #[test]
1209 fn private_ip_v6_loopback() {
1210 let ip: IpAddr = "::1".parse().unwrap();
1211 assert!(is_private_ip(ip));
1212 }
1213
1214 #[test]
1215 fn private_ip_v6_link_local() {
1216 let ip: IpAddr = "fe80::1".parse().unwrap();
1217 assert!(is_private_ip(ip));
1218 }
1219
1220 #[test]
1221 fn private_ip_v6_unique_local() {
1222 let ip: IpAddr = "fc00::1".parse().unwrap();
1223 assert!(is_private_ip(ip));
1224 }
1225
1226 #[test]
1227 fn private_ip_v6_unique_local_fd() {
1228 let ip: IpAddr = "fd00::1".parse().unwrap();
1229 assert!(is_private_ip(ip));
1230 }
1231
1232 #[test]
1233 fn private_ip_v6_unspecified() {
1234 let ip: IpAddr = "::".parse().unwrap();
1235 assert!(is_private_ip(ip));
1236 }
1237
1238 #[test]
1239 fn public_ip_v4() {
1240 let ip: IpAddr = "8.8.8.8".parse().unwrap();
1241 assert!(!is_private_ip(ip));
1242 }
1243
1244 #[test]
1245 fn documentation_ip_v4_is_reserved() {
1246 let ip: IpAddr = "203.0.113.1".parse().unwrap();
1247 assert!(is_private_ip(ip));
1248 }
1249
1250 #[test]
1251 fn documentation_ip_v6_is_reserved() {
1252 let ip: IpAddr = "2001:db8::1".parse().unwrap();
1253 assert!(is_private_ip(ip));
1254 }
1255
1256 #[test]
1259 fn validate_uri_rejects_file_scheme() {
1260 let result = validate_uri("file:///etc/passwd");
1261 assert!(result.is_err());
1262 assert!(result.unwrap_err().to_string().contains("scheme"));
1263 }
1264
1265 #[test]
1266 fn validate_uri_rejects_ftp_scheme() {
1267 let result = validate_uri("ftp://example.com/file");
1268 assert!(result.is_err());
1269 }
1270
1271 #[test]
1272 fn validate_uri_accepts_https() {
1273 assert!(validate_uri("https://creed.space/api/v1/revoked").is_ok());
1274 }
1275
1276 #[test]
1277 fn validate_uri_rejects_http() {
1278 assert!(validate_uri("http://creed.space/api/v1/revoked").is_err());
1279 }
1280
1281 #[test]
1282 fn validate_uri_rejects_non_standard_port() {
1283 let result = validate_uri("https://example.com:8080/api");
1284 assert!(result.is_err());
1285 assert!(result.unwrap_err().to_string().contains("port"));
1286 }
1287
1288 #[test]
1289 fn validate_uri_accepts_standard_port_443() {
1290 assert!(validate_uri("https://example.com:443/api").is_ok());
1291 }
1292
1293 #[test]
1294 fn validate_uri_rejects_http_default_port_for_https() {
1295 assert!(validate_uri("https://example.com:80/api").is_err());
1296 }
1297
1298 #[test]
1299 fn validate_uri_rejects_private_ip() {
1300 let result = validate_uri("https://192.168.1.1/api");
1301 assert!(result.is_err());
1302 assert!(result.unwrap_err().to_string().contains("private"));
1303 }
1304
1305 #[test]
1306 fn validate_uri_rejects_loopback() {
1307 let result = validate_uri("https://127.0.0.1/api");
1308 assert!(result.is_err());
1309 }
1310
1311 #[test]
1312 fn validate_uri_rejects_localhost() {
1313 let result = validate_uri("https://localhost/api");
1314 assert!(result.is_err());
1315 assert!(result.unwrap_err().to_string().contains("localhost"));
1316 }
1317
1318 #[test]
1319 fn validate_uri_rejects_no_scheme() {
1320 let result = validate_uri("example.com/api");
1321 assert!(result.is_err());
1322 }
1323
1324 #[test]
1325 fn validate_uri_rejects_credentials() {
1326 assert!(validate_uri("https://user:secret@example.com/revoked").is_err());
1327 }
1328
1329 #[test]
1330 fn validate_uri_rejects_fragments_and_localhost_variants() {
1331 assert!(validate_uri("https://example.com/revoked#ignored").is_err());
1332 assert!(validate_uri("https://localhost./revoked").is_err());
1333 assert!(validate_uri("https://service.localhost/revoked").is_err());
1334 }
1335
1336 #[test]
1337 fn validate_uri_rejects_reserved_literal_addresses() {
1338 assert!(validate_uri("https://100.64.0.1/revoked").is_err());
1339 assert!(validate_uri("https://192.0.2.1/revoked").is_err());
1340 assert!(validate_uri("https://198.18.0.1/revoked").is_err());
1341 assert!(validate_uri("https://[2001:db8::1]/revoked").is_err());
1342 }
1343
1344 #[test]
1347 fn crl_from_json_valid() {
1348 let json = r#"{
1349 "issuer": "creed-space",
1350 "updated_at": "2026-02-01T00:00:00Z",
1351 "next_update": "2026-03-01T00:00:00Z",
1352 "revoked": [
1353 {
1354 "jti": "bundle-abc-123",
1355 "revoked_at": "2026-01-15T12:00:00Z",
1356 "reason": "content policy violation"
1357 },
1358 {
1359 "jti": "bundle-def-456",
1360 "revoked_at": "2026-01-20T08:00:00Z",
1361 "reason": "key compromise"
1362 }
1363 ]
1364 }"#;
1365
1366 let crl = Crl::from_json(json).unwrap();
1367 assert_eq!(crl.issuer, "creed-space");
1368 assert_eq!(crl.revoked.len(), 2);
1369
1370 let entry = crl.find("bundle-abc-123");
1372 assert!(entry.is_some());
1373 assert_eq!(entry.unwrap().reason, "content policy violation");
1374
1375 assert!(crl.find("unknown-jti").is_none());
1377 }
1378
1379 #[test]
1380 fn crl_from_json_empty_revoked_list() {
1381 let json = r#"{
1382 "issuer": "test",
1383 "updated_at": "2026-02-01T00:00:00Z",
1384 "next_update": "2026-03-01T00:00:00Z",
1385 "revoked": []
1386 }"#;
1387
1388 let crl = Crl::from_json(json).unwrap();
1389 assert!(crl.revoked.is_empty());
1390 assert!(crl.find("any-jti").is_none());
1391 }
1392
1393 #[test]
1394 fn crl_from_json_invalid() {
1395 let result = Crl::from_json("not valid json");
1396 assert!(result.is_err());
1397 }
1398
1399 #[test]
1400 fn crl_from_json_rejects_duplicate_keys_and_oversized_input() {
1401 assert!(Crl::from_json(
1402 r#"{"issuer":"a","issuer":"b","updated_at":"2025-01-01T00:00:00Z","next_update":"2030-01-01T00:00:00Z","revoked":[]}"#
1403 )
1404 .is_err());
1405 assert!(Crl::from_json(&" ".repeat(MAX_RESPONSE_BYTES + 1)).is_err());
1406 }
1407
1408 #[test]
1411 fn revocation_status_default_not_revoked() {
1412 let status = RevocationStatus::default();
1413 assert!(!status.revoked);
1414 assert!(status.reason.is_none());
1415 assert!(status.revoked_at.is_none());
1416 }
1417
1418 #[test]
1419 fn revocation_status_revoked() {
1420 let status = RevocationStatus::revoked("policy violation", "2026-01-15T12:00:00Z");
1421 assert!(status.revoked);
1422 assert_eq!(status.decision, RevocationDecision::Revoked);
1423 assert_eq!(status.reason.as_deref(), Some("policy violation"));
1424 assert_eq!(status.revoked_at.as_deref(), Some("2026-01-15T12:00:00Z"));
1425 }
1426
1427 #[test]
1428 fn revocation_status_not_revoked() {
1429 let status = RevocationStatus::not_revoked();
1430 assert!(!status.revoked);
1431 }
1432
1433 #[test]
1434 fn unavailable_is_distinct_from_confirmed_revocation() {
1435 let status = RevocationStatus::unavailable();
1436 assert_eq!(status.decision, RevocationDecision::Unavailable);
1437 assert!(!status.revoked);
1438 assert!(status.should_reject());
1439 }
1440
1441 #[test]
1442 fn resolved_addresses_reject_empty_private_and_mixed_sets() {
1443 assert!(validate_resolved_addresses(Vec::<SocketAddr>::new()).is_err());
1444 assert!(validate_resolved_addresses(["127.0.0.1:443".parse().unwrap()]).is_err());
1445 assert!(validate_resolved_addresses([
1446 "8.8.8.8:443".parse().unwrap(),
1447 "10.0.0.1:443".parse().unwrap(),
1448 ])
1449 .is_err());
1450 assert_eq!(
1451 validate_resolved_addresses([
1452 "8.8.8.8:443".parse().unwrap(),
1453 "8.8.8.8:443".parse().unwrap(),
1454 ])
1455 .unwrap()
1456 .len(),
1457 1
1458 );
1459 }
1460
1461 #[test]
1462 fn rejects_translation_and_compatible_ipv6() {
1463 for ip in ["64:ff9b::7f00:1", "64:ff9b:1::808:808", "::808:808"] {
1464 assert!(is_private_ip(ip.parse().unwrap()), "{ip}");
1465 }
1466 assert!(!is_private_ip("3ff0::1".parse().unwrap()));
1467 }
1468
1469 #[test]
1470 fn online_transport_binds_query_and_response_to_jti_and_issuer() {
1471 let transport = FakeTransport::new([Ok(serde_json::json!({
1472 "revoked": false,
1473 "jti": "real-jti",
1474 "issuer": "issuer.example"
1475 }))]);
1476 let requests = transport.requests.clone();
1477 let mut checker = RevocationChecker::with_transport(
1478 Duration::from_secs(300),
1479 Duration::from_secs(5),
1480 transport,
1481 );
1482
1483 let status = checker.check_with_issuer(
1484 "real-jti",
1485 Some("https://status.example/check?jti=attacker&issuer=attacker&mode=full"),
1486 None,
1487 Some("issuer.example"),
1488 );
1489
1490 assert_eq!(status.decision, RevocationDecision::NotRevoked);
1491 let requested = requests.lock().unwrap().first().unwrap().clone();
1492 let url = Url::parse(&requested).unwrap();
1493 let pairs: Vec<_> = url.query_pairs().collect();
1494 assert_eq!(pairs.iter().filter(|(key, _)| key == "jti").count(), 1);
1495 assert_eq!(pairs.iter().filter(|(key, _)| key == "issuer").count(), 1);
1496 assert!(pairs
1497 .iter()
1498 .any(|(key, value)| key == "jti" && value == "real-jti"));
1499 assert!(pairs
1500 .iter()
1501 .any(|(key, value)| key == "issuer" && value == "issuer.example"));
1502 }
1503
1504 #[test]
1505 fn online_response_binding_mismatch_is_unavailable() {
1506 let transport = FakeTransport::new([Ok(serde_json::json!({
1507 "revoked": false,
1508 "jti": "other-jti",
1509 "issuer": "issuer.example"
1510 }))]);
1511 let mut checker = RevocationChecker::with_transport(
1512 Duration::from_secs(300),
1513 Duration::from_secs(5),
1514 transport,
1515 );
1516 let status = checker.check_with_issuer(
1517 "real-jti",
1518 Some("https://status.example/check"),
1519 None,
1520 Some("issuer.example"),
1521 );
1522 assert_eq!(status.decision, RevocationDecision::Unavailable);
1523 assert!(!status.revoked);
1524 }
1525
1526 #[test]
1527 fn live_crl_fetch_uses_injected_transport_and_caches_result() {
1528 let now = chrono::Utc::now();
1529 let transport = FakeTransport::new([Ok(serde_json::json!({
1530 "issuer": "issuer.example",
1531 "updated_at": now.to_rfc3339(),
1532 "next_update": (now + chrono::Duration::hours(1)).to_rfc3339(),
1533 "revoked": [{
1534 "jti": "revoked-jti",
1535 "revoked_at": now.to_rfc3339(),
1536 "reason": "key compromise"
1537 }]
1538 }))]);
1539 let requests = transport.requests.clone();
1540 let mut checker = RevocationChecker::with_transport(
1541 Duration::from_secs(300),
1542 Duration::from_secs(5),
1543 transport,
1544 );
1545 let uri = "https://status.example/crl.json";
1546
1547 let first =
1548 checker.check_with_issuer("revoked-jti", None, Some(uri), Some("issuer.example"));
1549 let second =
1550 checker.check_with_issuer("revoked-jti", None, Some(uri), Some("issuer.example"));
1551
1552 assert_eq!(first.decision, RevocationDecision::Revoked);
1553 assert_eq!(second.decision, RevocationDecision::Revoked);
1554 assert_eq!(requests.lock().unwrap().len(), 1);
1555 }
1556
1557 #[test]
1558 fn shared_online_response_contract_matches_rust_parser() {
1559 let fixture: Value =
1560 serde_json::from_str(include_str!("../testdata/revocation-responses.json")).unwrap();
1561 for case in fixture["vectors"].as_array().unwrap() {
1562 let actual = match serde_json::from_value::<OnlineRevocationResponse>(
1563 case["response"].clone(),
1564 ) {
1565 Ok(response) => match response.into_status(
1566 case["jti"].as_str().unwrap(),
1567 case["issuer"].as_str().unwrap(),
1568 ) {
1569 Ok(status) => match status.decision {
1570 RevocationDecision::NotRevoked => "not_revoked",
1571 RevocationDecision::Revoked => "revoked",
1572 RevocationDecision::Unavailable => "unavailable",
1573 },
1574 Err(_) => "unavailable",
1575 },
1576 Err(_) => "unavailable",
1577 };
1578 assert_eq!(
1579 actual,
1580 case["expected"].as_str().unwrap(),
1581 "case {}",
1582 case["id"].as_str().unwrap()
1583 );
1584 }
1585 }
1586
1587 #[test]
1588 fn shared_crl_response_contract_matches_rust_parser() {
1589 let fixture: Value =
1590 serde_json::from_str(include_str!("../testdata/revocation-crl-responses.json"))
1591 .unwrap();
1592 for case in fixture["vectors"].as_array().unwrap() {
1593 let actual = match serde_json::from_value::<Crl>(case["response"].clone()) {
1594 Ok(crl) => match crl_lookup_status(
1595 &crl,
1596 case["jti"].as_str().unwrap(),
1597 case["issuer"].as_str(),
1598 ) {
1599 Ok((status, _)) => match status.decision {
1600 RevocationDecision::NotRevoked => "not_revoked",
1601 RevocationDecision::Revoked => "revoked",
1602 RevocationDecision::Unavailable => "unavailable",
1603 },
1604 Err(_) => "unavailable",
1605 },
1606 Err(_) => "unavailable",
1607 };
1608 assert_eq!(
1609 actual,
1610 case["expected"].as_str().unwrap(),
1611 "case {}",
1612 case["id"].as_str().unwrap()
1613 );
1614 }
1615 }
1616
1617 #[test]
1620 fn checker_returns_not_revoked_by_default() {
1621 let mut checker = RevocationChecker::new(Duration::from_secs(300), Duration::from_secs(5));
1622
1623 let status = checker.check("some-jti", None, None);
1624 assert!(!status.revoked);
1625 }
1626
1627 #[test]
1628 fn zero_timeout_configuration_does_not_panic_and_fails_closed() {
1629 let mut checker = RevocationChecker::with_transport(
1630 Duration::from_secs(60),
1631 Duration::ZERO,
1632 RejectZeroTimeoutTransport,
1633 );
1634 let status = checker.check_with_issuer(
1635 "jti",
1636 Some("https://example.com/revocation"),
1637 None,
1638 Some("issuer"),
1639 );
1640 assert_eq!(status.decision, RevocationDecision::Unavailable);
1641 }
1642
1643 #[test]
1644 fn checker_crl_cache_lookup() {
1645 let mut checker = RevocationChecker::new(Duration::from_secs(300), Duration::from_secs(5));
1646
1647 let crl = Crl {
1648 issuer: "test".into(),
1649 updated_at: "2026-02-01T00:00:00Z".into(),
1650 next_update: (chrono::Utc::now() + chrono::Duration::days(1)).to_rfc3339(),
1651 revoked: vec![CrlEntry {
1652 jti: "revoked-bundle".into(),
1653 revoked_at: "2026-01-15T12:00:00Z".into(),
1654 reason: "key compromise".into(),
1655 }],
1656 };
1657
1658 checker.insert_crl("https://creed.space/crl/2026.json", crl);
1659
1660 let status = checker.check_with_issuer(
1662 "revoked-bundle",
1663 None,
1664 Some("https://creed.space/crl/2026.json"),
1665 Some("test"),
1666 );
1667 assert!(status.revoked);
1668 assert_eq!(status.decision, RevocationDecision::Revoked);
1669 assert_eq!(status.reason.as_deref(), Some("key compromise"));
1670
1671 let status = checker.check_with_issuer(
1673 "good-bundle",
1674 None,
1675 Some("https://creed.space/crl/2026.json"),
1676 Some("test"),
1677 );
1678 assert!(!status.revoked);
1679 }
1680
1681 #[test]
1682 fn checker_cache_is_bound_to_uri_issuer_and_jti() {
1683 let mut checker = RevocationChecker::new(Duration::from_secs(300), Duration::from_secs(5));
1684
1685 let revoked_crl = Crl {
1686 issuer: "test".into(),
1687 updated_at: chrono::Utc::now().to_rfc3339(),
1688 next_update: (chrono::Utc::now() + chrono::Duration::days(1)).to_rfc3339(),
1689 revoked: vec![CrlEntry {
1690 jti: "cached-jti".into(),
1691 revoked_at: "2026-01-15T12:00:00Z".into(),
1692 reason: "test".into(),
1693 }],
1694 };
1695 checker.insert_crl("https://example.com/a.json", revoked_crl);
1696 checker.insert_crl(
1697 "https://example.com/b.json",
1698 Crl {
1699 issuer: "test".into(),
1700 updated_at: chrono::Utc::now().to_rfc3339(),
1701 next_update: (chrono::Utc::now() + chrono::Duration::days(1)).to_rfc3339(),
1702 revoked: vec![],
1703 },
1704 );
1705
1706 let status = checker.check_with_issuer(
1707 "cached-jti",
1708 None,
1709 Some("https://example.com/a.json"),
1710 Some("test"),
1711 );
1712 assert!(status.revoked);
1713 assert_eq!(status.decision, RevocationDecision::Revoked);
1714
1715 let status = checker.check("cached-jti", None, None);
1717 assert!(!status.revoked);
1718
1719 let status = checker.check_with_issuer(
1720 "cached-jti",
1721 None,
1722 Some("https://example.com/b.json"),
1723 Some("test"),
1724 );
1725 assert!(!status.revoked);
1726
1727 let status = checker.check_with_issuer(
1728 "cached-jti",
1729 None,
1730 Some("https://example.com/a.json"),
1731 Some("other"),
1732 );
1733 assert!(!status.revoked);
1734 assert_eq!(status.decision, RevocationDecision::Unavailable);
1735 assert_eq!(
1736 status.reason.as_deref(),
1737 Some("revocation_status_unavailable")
1738 );
1739 }
1740
1741 #[test]
1742 fn valid_cached_decision_is_retained_across_repeated_hits() {
1743 let mut checker = RevocationChecker::new(Duration::from_secs(300), Duration::from_secs(5));
1744 let uri = "https://example.com/repeated.json";
1745 checker.insert_crl(
1746 uri,
1747 Crl {
1748 issuer: "test".into(),
1749 updated_at: chrono::Utc::now().to_rfc3339(),
1750 next_update: (chrono::Utc::now() + chrono::Duration::days(1)).to_rfc3339(),
1751 revoked: vec![CrlEntry {
1752 jti: "repeated-jti".into(),
1753 revoked_at: "2026-01-01T00:00:00Z".into(),
1754 reason: "test".into(),
1755 }],
1756 },
1757 );
1758
1759 let first = checker.check_with_issuer("repeated-jti", None, Some(uri), Some("test"));
1760 assert!(first.revoked);
1761 checker.crl_cache.clear();
1762
1763 for _ in 0..2 {
1764 let cached = checker.check_with_issuer("repeated-jti", None, Some(uri), Some("test"));
1765 assert!(cached.revoked);
1766 assert_eq!(checker.cache.len(), 1);
1767 }
1768 }
1769
1770 #[test]
1771 fn crl_uri_without_expected_issuer_fails_closed() {
1772 let mut checker = RevocationChecker::new(Duration::from_secs(300), Duration::from_secs(5));
1773 let uri = "https://example.com/issuer-required.json";
1774 checker.insert_crl(
1775 uri,
1776 Crl {
1777 issuer: "test".into(),
1778 updated_at: chrono::Utc::now().to_rfc3339(),
1779 next_update: (chrono::Utc::now() + chrono::Duration::days(1)).to_rfc3339(),
1780 revoked: vec![],
1781 },
1782 );
1783
1784 let status = checker.check("clean-jti", None, Some(uri));
1785
1786 assert!(!status.revoked);
1787 assert_eq!(status.decision, RevocationDecision::Unavailable);
1788 assert_eq!(
1789 status.reason.as_deref(),
1790 Some("revocation_status_unavailable")
1791 );
1792 }
1793
1794 #[test]
1795 fn crl_validation_rejects_bad_timestamps_and_jtis() {
1796 for json in [
1797 r#"{"issuer":"test","updated_at":"2026-01-01 00:00:00Z","next_update":"2026-02-01T00:00:00Z","revoked":[]}"#,
1798 r#"{"issuer":"test","updated_at":"2026-01-01T00:00:00","next_update":"2026-02-01T00:00:00Z","revoked":[]}"#,
1799 r#"{"issuer":"test","updated_at":"2026-01-01T00:00:00.Z","next_update":"2026-02-01T00:00:00Z","revoked":[]}"#,
1800 r#"{"issuer":"test","updated_at":"2026-01-01T00:00:00+1:00","next_update":"2026-02-01T00:00:00Z","revoked":[]}"#,
1801 r#"{"issuer":"test","updated_at":"2026-03-01T00:00:00Z","next_update":"2026-02-01T00:00:00Z","revoked":[]}"#,
1802 r#"{"issuer":"test","updated_at":"2026-01-01T00:00:00Z","next_update":"2026-02-01T00:00:00Z","revoked":[{"jti":"missing-zone","revoked_at":"2026-01-01T00:00:00","reason":"bad"}]}"#,
1803 r#"{"issuer":"test","updated_at":"2026-01-01T00:00:00Z","next_update":"2026-02-01T00:00:00Z","revoked":[{"jti":"","revoked_at":"2026-01-01T00:00:00Z","reason":"bad"}]}"#,
1804 r#"{"issuer":"test","updated_at":"2026-01-01T00:00:00Z","next_update":"2026-02-01T00:00:00Z","revoked":[{"jti":"same","revoked_at":"2026-01-01T00:00:00Z","reason":"one"},{"jti":"same","revoked_at":"2026-01-02T00:00:00Z","reason":"two"}]}"#,
1805 ] {
1806 assert!(Crl::from_json(json).is_err(), "{json}");
1807 }
1808 }
1809
1810 #[test]
1811 fn crl_decision_cache_is_bounded_by_next_update() {
1812 let mut checker =
1813 RevocationChecker::new(Duration::from_secs(86_400), Duration::from_secs(5));
1814 let now = chrono::Utc::now();
1815 checker.insert_crl(
1816 "https://example.com/short-lived.json",
1817 Crl {
1818 issuer: "test".into(),
1819 updated_at: now.to_rfc3339(),
1820 next_update: (now + chrono::Duration::seconds(10)).to_rfc3339(),
1821 revoked: vec![CrlEntry {
1822 jti: "short-lived".into(),
1823 revoked_at: now.to_rfc3339(),
1824 reason: "test".into(),
1825 }],
1826 },
1827 );
1828
1829 let status = checker.check_with_issuer(
1830 "short-lived",
1831 None,
1832 Some("https://example.com/short-lived.json"),
1833 Some("test"),
1834 );
1835 assert!(status.revoked);
1836 let cached = checker.cache.values().next().expect("decision cached");
1837 assert!(cached.expires_at <= Instant::now() + Duration::from_secs(11));
1838 }
1839
1840 #[test]
1841 fn unrepresentable_cache_ttl_does_not_panic_or_cache() {
1842 let mut checker = RevocationChecker::new(Duration::MAX, Duration::from_secs(5));
1843 checker.insert_decision(
1844 RevocationChecker::cache_key("https://example.com/status", None, "jti"),
1845 RevocationStatus::not_revoked(),
1846 Duration::MAX,
1847 );
1848
1849 assert!(checker.cache.is_empty());
1850 assert!(checker.cache_order.is_empty());
1851 }
1852
1853 #[test]
1854 fn checker_rejects_empty_jti_and_expected_issuer() {
1855 let mut checker = RevocationChecker::new(Duration::from_secs(300), Duration::from_secs(5));
1856 assert_eq!(
1857 checker.check("", None, None).decision,
1858 RevocationDecision::Unavailable
1859 );
1860 assert_eq!(
1861 checker
1862 .check_with_issuer("jti", None, None, Some(" "))
1863 .decision,
1864 RevocationDecision::Unavailable
1865 );
1866 }
1867
1868 #[test]
1869 fn checker_clear_cache() {
1870 let mut checker = RevocationChecker::new(Duration::from_secs(300), Duration::from_secs(5));
1871
1872 let crl = Crl {
1873 issuer: "test".into(),
1874 updated_at: "2026-02-01T00:00:00Z".into(),
1875 next_update: (chrono::Utc::now() + chrono::Duration::days(1)).to_rfc3339(),
1876 revoked: vec![CrlEntry {
1877 jti: "cleared-jti".into(),
1878 revoked_at: "2026-01-15T12:00:00Z".into(),
1879 reason: "test".into(),
1880 }],
1881 };
1882 checker.insert_crl("https://example.com/crl.json", crl);
1883
1884 let status = checker.check_with_issuer(
1886 "cleared-jti",
1887 None,
1888 Some("https://example.com/crl.json"),
1889 Some("test"),
1890 );
1891 assert!(status.revoked);
1892 assert_eq!(status.decision, RevocationDecision::Revoked);
1893
1894 checker.clear_cache();
1896 let status = checker.check("cleared-jti", None, None);
1897 assert!(!status.revoked);
1898 }
1899
1900 #[test]
1901 fn checker_caches_are_bounded_with_deterministic_eviction() {
1902 let mut checker =
1903 RevocationChecker::with_limits(Duration::from_secs(300), Duration::from_secs(5), 2, 1);
1904 checker.insert_decision(
1905 ("one".into(), "issuer".into(), "jti-1".into()),
1906 RevocationStatus::not_revoked(),
1907 Duration::from_secs(60),
1908 );
1909 checker.insert_decision(
1910 ("two".into(), "issuer".into(), "jti-2".into()),
1911 RevocationStatus::not_revoked(),
1912 Duration::from_secs(60),
1913 );
1914 checker.insert_decision(
1915 ("three".into(), "issuer".into(), "jti-3".into()),
1916 RevocationStatus::not_revoked(),
1917 Duration::from_secs(60),
1918 );
1919 assert_eq!(checker.cache.len(), 2);
1920 assert!(!checker
1921 .cache
1922 .contains_key(&("one".into(), "issuer".into(), "jti-1".into())));
1923
1924 let crl = |issuer: &str| Crl {
1925 issuer: issuer.into(),
1926 updated_at: chrono::Utc::now().to_rfc3339(),
1927 next_update: (chrono::Utc::now() + chrono::Duration::days(1)).to_rfc3339(),
1928 revoked: vec![],
1929 };
1930 checker.insert_crl("https://example.com/one.json", crl("one"));
1931 checker.insert_crl("https://example.com/two.json", crl("two"));
1932 assert_eq!(checker.crl_cache.len(), 1);
1933 assert!(checker
1934 .crl_cache
1935 .contains_key("https://example.com/two.json"));
1936 }
1937
1938 #[test]
1939 fn checker_rejects_unsafe_crl_uri() {
1940 let mut checker = RevocationChecker::new(Duration::from_secs(300), Duration::from_secs(5));
1941
1942 let status = checker.check_with_issuer(
1944 "some-jti",
1945 None,
1946 Some("https://192.168.1.1/crl.json"),
1947 Some("test"),
1948 );
1949 assert!(!status.revoked);
1950 assert_eq!(status.decision, RevocationDecision::Unavailable);
1951 assert_eq!(
1952 status.reason.as_deref(),
1953 Some("revocation_status_unavailable")
1954 );
1955 }
1956
1957 #[test]
1958 fn checker_rejects_unsafe_check_uri() {
1959 let mut checker = RevocationChecker::new(Duration::from_secs(300), Duration::from_secs(5));
1960
1961 let status = checker.check_with_issuer(
1963 "some-jti",
1964 Some("https://10.0.0.1/revoked"),
1965 None,
1966 Some("test"),
1967 );
1968 assert!(!status.revoked);
1969 assert_eq!(status.decision, RevocationDecision::Unavailable);
1970 assert_eq!(
1971 status.reason.as_deref(),
1972 Some("revocation_status_unavailable")
1973 );
1974 }
1975
1976 #[test]
1977 fn checker_rejects_expired_cached_crl() {
1978 let mut checker = RevocationChecker::new(Duration::from_secs(300), Duration::from_secs(5));
1979 checker.insert_crl(
1980 "https://example.com/crl.json",
1981 Crl {
1982 issuer: "test".into(),
1983 updated_at: (chrono::Utc::now() - chrono::Duration::days(2)).to_rfc3339(),
1984 next_update: (chrono::Utc::now() - chrono::Duration::days(1)).to_rfc3339(),
1985 revoked: vec![],
1986 },
1987 );
1988
1989 let status = checker.check_with_issuer(
1990 "some-jti",
1991 None,
1992 Some("https://example.com/crl.json"),
1993 Some("test"),
1994 );
1995 assert!(!status.revoked);
1996 assert_eq!(status.decision, RevocationDecision::Unavailable);
1997 assert_eq!(
1998 status.reason.as_deref(),
1999 Some("revocation_status_unavailable")
2000 );
2001 }
2002}