From adcfece181a8806bc0db6fa0399e5f9177fa1271 Mon Sep 17 00:00:00 2001 From: cat23123 <58714163+cat23123@users.noreply.github.com> Date: Thu, 19 Nov 2026 17:24:29 +0000 Subject: [PATCH 01/43] feat(tls): opt-in certificate revocation checking Add an opt-in TLS certificate-revocation policy. It is off by default, so existing connections are unchanged. - Public TlsConfig gains check_certificate_revocation and accept_undetermined_certificate_revocation (Option; unset means off). Session open rejects a revocation request on tls-native with InvalidArgument. - tls-rustls: with checking on, the verifier builds the chain with webpki, then fetches the CRLs from each certificate's distribution points (end-entity and intermediates) and checks them with webpki. Revoked is rejected in both modes. An undetermined status is rejected in strict mode and accepted in accept-undetermined mode. A bad CRL signature or wrong issuer is rejected in both modes. A rejected CRL is evicted from the cache. - CRL fetches send no auth or custom headers, go through the connection's proxy, and are bounded by a 10 s timeout, a 32 MiB body and 3 redirects. Each CRL is cached until its nextUpdate. - accept_self_signed turns revocation off. - C ABI: kernel_session_config_set_tls_certificate_revocation, with a smoke check in tests/c/session_smoke.c. - Hermetic tests use an rcgen PKI, a loopback CRL server, a loopback TLS server and a loopback forward-proxy stub. One table covers each outcome in both modes. - tests/tls_revocation_e2e.rs is an #[ignore] live hook driven by DATABRICKS_TEST_REVOCATION=off|strict|accept_undetermined. Signed-off-by: cat23123 <58714163+cat23123@users.noreply.github.com> Co-authored-by: Isaac --- Cargo.lock | 2 + Cargo.toml | 8 + NEXT_CHANGELOG.md | 5 + include/databricks_kernel.h | 17 + src/c_abi/session.rs | 78 +++ src/client/http.rs | 66 ++ src/client/mod.rs | 2 + src/client/retry.rs | 6 +- src/client/tls_revocation.rs | 542 +++++++++++++++++ src/client/tls_revocation_tests.rs | 925 +++++++++++++++++++++++++++++ src/config.rs | 10 + src/session.rs | 44 ++ tests/c/session_smoke.c | 20 + tests/tls_revocation_e2e.rs | 76 +++ 14 files changed, 1800 insertions(+), 1 deletion(-) create mode 100644 src/client/tls_revocation.rs create mode 100644 src/client/tls_revocation_tests.rs create mode 100644 tests/tls_revocation_e2e.rs diff --git a/Cargo.lock b/Cargo.lock index b8867a94..732b6f83 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -658,6 +658,7 @@ dependencies = [ "cbc 0.2.1", "chrono", "dashmap", + "der", "dirs", "futures", "geo-traits", @@ -678,6 +679,7 @@ dependencies = [ "ring", "rsa", "rustls", + "rustls-native-certs", "rustls-webpki", "serde", "serde_json", diff --git a/Cargo.toml b/Cargo.toml index f428c382..e07eb921 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -65,6 +65,12 @@ rustls = { version = "0.23.41", optional = true, default-features = false, featu # Enforce TLS dependency minimums for consumers with their own lockfiles. rustls-webpki = { version = "0.103.16", optional = true, default-features = false } webpki-roots = { version = "1.0.11", optional = true, default-features = false } +# `tls-rustls` only: opt-in certificate revocation checking (see +# `src/client/tls_revocation.rs`). Both crates are already in the runtime graph +# through reqwest / pkcs8; they are declared here so the kernel can build its own +# rustls client config (root store from the OS trust store, and a CRL DER reader). +rustls-native-certs = { version = "0.8", optional = true } +der = { version = "0.7", optional = true } tokio = { version = "1", features = ["full", "sync"] } # Serialization @@ -212,6 +218,8 @@ tls-rustls = [ "dep:rustls", "dep:rustls-webpki", "dep:webpki-roots", + "dep:rustls-native-certs", + "dep:der", ] [lib] diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index 3964deb0..fbc999ba 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -13,6 +13,11 @@ changes go in their respective binding's NEXT_CHANGELOG. - A native Rust ADBC 1.1 driver in `adbc/`, with an optional standard ADBC C ABI for driver-manager loading from other languages. +- Opt-in TLS certificate revocation checking, off by default (`tls-rustls` only; + `tls-native` fails session open with `InvalidArgument`). Set it with + `TlsConfig::check_certificate_revocation` and + `TlsConfig::accept_undetermined_certificate_revocation`, or with + `kernel_session_config_set_tls_certificate_revocation`. ### Changed diff --git a/include/databricks_kernel.h b/include/databricks_kernel.h index e167f181..5f5463b2 100644 --- a/include/databricks_kernel.h +++ b/include/databricks_kernel.h @@ -468,6 +468,23 @@ KernelStatusCode kernel_session_config_set_tls_client_certificate( KernelSessionConfig* config, const uint8_t* cert_pem, size_t cert_len, const uint8_t* key_pem, size_t key_len); +/* Enable or disable TLS certificate-revocation checking (default: off). + * + * With `check_revocation` true, the server certificate chain (end-entity and + * intermediates) is checked against the CRLs named by its CRL distribution + * points. A revoked certificate is always rejected. `accept_undetermined` + * governs a status that cannot be determined (no distribution point, CRL fetch + * failure or timeout, non-200 or oversized response, expired CRL): false + * rejects it (strict), true accepts it. An invalid CRL signature or a CRL for + * the wrong issuer is always rejected. `check_revocation` false disables the + * check whatever `accept_undetermined` says. Revocation is also skipped when + * the self-signed setter is set. + * + * Requires the tls-rustls backend; under tls-native, opening a session with + * `check_revocation` true fails and the error names the backend. */ +KernelStatusCode kernel_session_config_set_tls_certificate_revocation( + KernelSessionConfig* config, bool check_revocation, bool accept_undetermined); + /* Configure the HTTP retry / backoff policy. `min_wait_ms` / `max_wait_ms` * are the backoff-wait bounds between attempts (the wait is exponential * with jitter, clamped to this range); `max_retries` is the number of diff --git a/src/c_abi/session.rs b/src/c_abi/session.rs index b3365f49..90fee838 100644 --- a/src/c_abi/session.rs +++ b/src/c_abi/session.rs @@ -242,6 +242,9 @@ struct TlsSpec { client_cert_pem: Option>, /// PEM-encoded private key for the mTLS client certificate. Never log it. client_key_pem: Option>, + /// Set by `kernel_session_config_set_tls_certificate_revocation`. + check_certificate_revocation: Option, + accept_undetermined_certificate_revocation: Option, } /// Read a required C string argument into an owned `String`, mapping a @@ -1297,6 +1300,29 @@ pub unsafe extern "C" fn kernel_session_config_set_tls_client_certificate( }) } +/// Enable or disable TLS certificate-revocation checking (default: off). +/// +/// `check_revocation` turns checking on. A revoked certificate is always +/// rejected. An undetermined status (no distribution point, CRL fetch failure, +/// expired CRL) is rejected unless `accept_undetermined` is true. Requires the +/// `tls-rustls` backend: under `tls-native`, opening a session with +/// `check_revocation` true fails with `InvalidArgument`. +/// +/// # Safety +/// `config` must be a live config handle. +#[no_mangle] +pub unsafe extern "C" fn kernel_session_config_set_tls_certificate_revocation( + config: *mut KernelSessionConfig, + check_revocation: bool, + accept_undetermined: bool, +) -> KernelStatusCode { + set_on_config(config, |c| { + c.tls.check_certificate_revocation = Some(check_revocation); + c.tls.accept_undetermined_certificate_revocation = Some(accept_undetermined); + Ok(()) + }) +} + /// Set whether transaction control is ignored (no-oped). Pass `true` /// (the default) for `IgnoreTransactions=1` semantics — `SQLEndTran` / /// commit / rollback / autocommit-off become silent no-ops. Pass `false` @@ -1748,6 +1774,7 @@ fn build_session(config: KernelSessionConfig) -> Result Result::uninit(); + assert!(crate::c_abi::error::kernel_get_last_error(out.as_mut_ptr())); + let error = out.assume_init(); + let message = CStr::from_ptr(error.message).to_str().unwrap(); + assert!( + message.contains("certificate revocation checking requires the tls-rustls backend"), + "{message}" + ); + } + } +} diff --git a/src/client/http.rs b/src/client/http.rs index cac2243b..e95d92cf 100644 --- a/src/client/http.rs +++ b/src/client/http.rs @@ -197,6 +197,53 @@ pub struct TlsConfig { /// Populated from [`crate::config::TlsConfig::client_key_pem`]. /// Secret material — redacted in `Debug`. pub client_key_pem: Option>, + /// Check the chain's revocation status against its CRL distribution + /// points (tls-rustls only). `None` / `Some(false)` = off. + pub check_certificate_revocation: Option, + /// With revocation checking on, accept an undetermined status. + pub accept_undetermined_certificate_revocation: Option, + /// Bounds on each CRL fetch. Production defaults. + #[cfg(feature = "tls-rustls")] + pub(crate) crl_fetch_limits: CrlFetchLimits, +} + +/// Bounds applied to each CRL HTTP fetch. +#[cfg(feature = "tls-rustls")] +#[derive(Clone, Copy, Debug)] +pub(crate) struct CrlFetchLimits { + pub(crate) timeout: Duration, + pub(crate) max_bytes: usize, +} + +#[cfg(feature = "tls-rustls")] +impl Default for CrlFetchLimits { + fn default() -> Self { + Self { + timeout: Duration::from_secs(10), + max_bytes: 32 * 1024 * 1024, + } + } +} + +/// Rejects a revocation request the backend cannot honour. Shared by session +/// open (which must report `InvalidArgument` unwrapped) and the HTTP client. +pub(crate) fn check_revocation_support(tls: &TlsConfig) -> Result<()> { + if cfg!(feature = "tls-rustls") || tls.check_certificate_revocation != Some(true) { + return Ok(()); + } + Err(Error::invalid_argument() + .message("certificate revocation checking requires the tls-rustls backend")) +} + +/// The accept-undetermined flag when revocation checking applies. `allow_self_signed` +/// turns it off, as Simba does. +#[cfg(feature = "tls-rustls")] +fn revocation_policy(tls: &TlsConfig) -> Option { + (tls.check_certificate_revocation == Some(true) && !tls.allow_self_signed.unwrap_or(false)) + .then(|| { + tls.accept_undetermined_certificate_revocation + .unwrap_or(false) + }) } impl std::fmt::Debug for TlsConfig { @@ -260,6 +307,11 @@ impl TlsConfig { trusted_certificate_pem: cfg.custom_ca_cert.clone(), client_cert_pem: cfg.client_cert_pem.clone(), client_key_pem: cfg.client_key_pem.clone(), + check_certificate_revocation: cfg.check_certificate_revocation, + accept_undetermined_certificate_revocation: cfg + .accept_undetermined_certificate_revocation, + #[cfg(feature = "tls-rustls")] + crl_fetch_limits: CrlFetchLimits::default(), } } } @@ -515,6 +567,7 @@ impl DatabricksHttpClient { config: &HttpClientConfig, redirect: reqwest::redirect::Policy, ) -> Result { + check_revocation_support(&config.tls)?; let mut builder = Client::builder() .connect_timeout(config.connect_timeout) // `read_timeout` is a historical name; reqwest applies this as @@ -700,6 +753,17 @@ impl DatabricksHttpClient { debug!("HTTP client using default proxy behavior (env vars)"); } + // With revocation on, the verifier replaces reqwest's trust roots and + // identity. Those were already validated above. + #[cfg(feature = "tls-rustls")] + if let Some(accept_undetermined) = revocation_policy(&config.tls) { + builder = builder.use_preconfigured_tls(super::tls_revocation::client_config( + &config.tls, + &config.proxy, + accept_undetermined, + )?); + } + builder.build().map_err(|e| { Error::invalid_argument().message(format!("Failed to create HTTP client: {e}")) }) @@ -1648,6 +1712,8 @@ lGrv15pBcePj skip_hostname_verification: true, client_cert_pem: Some(b"cert-bytes".to_vec()), client_key_pem: Some(b"key-bytes".to_vec()), + check_certificate_revocation: Some(true), + accept_undetermined_certificate_revocation: Some(true), }; let internal = TlsConfig::from_public(&public); assert_eq!(internal.allow_self_signed, Some(true)); diff --git a/src/client/mod.rs b/src/client/mod.rs index af553abf..bd6303c4 100644 --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -34,6 +34,8 @@ pub mod http; pub mod retry; pub mod sea; +#[cfg(feature = "tls-rustls")] +pub(crate) mod tls_revocation; pub(crate) mod transport; fn error_chain<'a>( diff --git a/src/client/retry.rs b/src/client/retry.rs index cdd1c31b..45a4c917 100644 --- a/src/client/retry.rs +++ b/src/client/retry.rs @@ -271,7 +271,11 @@ pub(crate) fn is_certificate_verification_failure( #[cfg(feature = "tls-rustls")] if matches!( error.downcast_ref::(), - Some(rustls::Error::InvalidCertificate(_) | rustls::Error::NoCertificatesPresented) + Some( + rustls::Error::InvalidCertificate(_) + | rustls::Error::InvalidCertRevocationList(_) + | rustls::Error::NoCertificatesPresented + ) ) { return true; } diff --git a/src/client/tls_revocation.rs b/src/client/tls_revocation.rs new file mode 100644 index 00000000..7f1cf9b3 --- /dev/null +++ b/src/client/tls_revocation.rs @@ -0,0 +1,542 @@ +// Copyright (c) 2026 Databricks, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! CRL revocation checking for the `tls-rustls` backend. +//! +//! The server verifier builds the chain with webpki first, so a bad chain never +//! reaches the network. It then fetches the CRLs named by the distribution points +//! of each non-self-issued certificate and hands the current ones to webpki, which +//! checks their signatures and the revocation status. The DER reader here only +//! selects CRLs and reads issuer names and `nextUpdate`. Authenticity is webpki's. + +use std::collections::HashMap; +use std::sync::{Arc, Mutex, PoisonError}; + +use der::asn1::{AnyRef, GeneralizedTime, UtcTime}; +use der::{Decode, Reader, SliceReader, Tagged}; +use reqwest::StatusCode; +use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier}; +use rustls::client::WebPkiServerVerifier; +use rustls::crypto::CryptoProvider; +use rustls::pki_types::{ + pem::PemObject, CertificateDer, CertificateRevocationListDer, PrivateKeyDer, ServerName, + UnixTime, +}; +use rustls::{ + CertRevocationListError, CertificateError, ClientConfig, DigitallySignedStruct, RootCertStore, + SignatureScheme, +}; + +use super::http::{CrlFetchLimits, ProxyConfig, TlsConfig}; +use crate::kernel_error::{Error, Result}; + +const TAG_INTEGER: u8 = 0x02; +const TAG_UTC_TIME: u8 = 0x17; +const TAG_GENERALIZED_TIME: u8 = 0x18; +const TAG_SEQUENCE: u8 = 0x30; +/// Context [0]: explicit version, `distributionPoint`, `fullName`. +const TAG_CONTEXT_0: u8 = 0xA0; +/// Context [2]: `cRLIssuer` (an indirect CRL, which is not supported). +const TAG_CONTEXT_2: u8 = 0xA2; +/// Context [3]: certificate extensions. +const TAG_CONTEXT_3: u8 = 0xA3; +/// Context [6] primitive: a `uniformResourceIdentifier`. +const TAG_URI: u8 = 0x86; +/// OID 2.5.29.31, the CRL distribution points extension (content octets). +const OID_CRL_DISTRIBUTION_POINTS: &[u8] = &[0x55, 0x1D, 0x1F]; +const CRL_MAX_REDIRECTS: usize = 3; + +/// The (tag, content) pairs of the consecutive TLVs in `der`. +fn tlvs(der: &[u8]) -> Option> { + let mut reader = SliceReader::new(der).ok()?; + let mut out = Vec::new(); + while !reader.is_finished() { + let any = AnyRef::decode(&mut reader).ok()?; + out.push((any.tag().into(), any.value())); + } + Some(out) +} + +/// The children of the single SEQUENCE that `der` consists of. +fn sequence(der: &[u8]) -> Option> { + match tlvs(der)?.as_slice() { + [(TAG_SEQUENCE, body)] => tlvs(body), + _ => None, + } +} + +/// The fields of a certificate that the revocation check needs. +struct Cert<'a> { + issuer: &'a [u8], + self_issued: bool, + crl_uris: Vec, +} + +fn parse_cert(der: &[u8]) -> Option> { + let top = sequence(der)?; + let fields = tlvs(top.first()?.1)?; + // Optional explicit version, then serialNumber, signature, issuer, validity, subject. + let base = usize::from(fields.first()?.0 == TAG_CONTEXT_0); + let issuer = fields.get(base + 2)?.1; + let subject = fields.get(base + 4)?.1; + let mut crl_uris = Vec::new(); + if let Some(&(_, extensions)) = fields.iter().find(|f| f.0 == TAG_CONTEXT_3) { + for (_, extension) in sequence(extensions)? { + let parts = tlvs(extension)?; + if parts.first()?.1 == OID_CRL_DISTRIBUTION_POINTS { + crl_uris = distribution_points(parts.last()?.1)?; + } + } + } + Some(Cert { + issuer, + self_issued: issuer == subject, + crl_uris, + }) +} + +/// The http(s) URIs of a CRLDistributionPoints value. Indirect points are skipped. +fn distribution_points(value: &[u8]) -> Option> { + let mut uris = Vec::new(); + for (_, point) in sequence(value)? { + let parts = tlvs(point)?; + if parts.iter().any(|part| part.0 == TAG_CONTEXT_2) { + continue; + } + for (_, name) in parts.iter().filter(|part| part.0 == TAG_CONTEXT_0) { + general_names(name, &mut uris)?; + } + } + Some(uris) +} + +/// Collects http(s) URIs from a DistributionPointName. Nested wrappers are followed. +/// Directory and relative names are ignored. +fn general_names(der: &[u8], out: &mut Vec) -> Option<()> { + for (tag, value) in tlvs(der)? { + match tag { + TAG_URI => { + if let Ok(uri) = std::str::from_utf8(value) { + let lower = uri.to_ascii_lowercase(); + if lower.starts_with("http://") || lower.starts_with("https://") { + out.push(uri.to_owned()); + } + } + } + TAG_CONTEXT_0 | TAG_SEQUENCE => general_names(value, out)?, + _ => {} + } + } + Some(()) +} + +/// The fields of a CRL that the classification needs. +struct Crl<'a> { + issuer: &'a [u8], + next_update: Option, +} + +fn parse_crl(der: &[u8]) -> Option> { + let top = sequence(der)?; + let fields = tlvs(top.first()?.1)?; + // Optional version, then signature, issuer, thisUpdate, nextUpdate. + let base = usize::from(fields.first()?.0 == TAG_INTEGER); + let issuer = fields.get(base + 1)?.1; + let next_update = match fields.get(base + 3) { + Some(&(tag, value)) if tag == TAG_UTC_TIME || tag == TAG_GENERALIZED_TIME => { + Some(to_unix_secs(tag, value)?) + } + _ => None, + }; + Some(Crl { + issuer, + next_update, + }) +} + +/// Unix seconds of a UTCTime or GeneralizedTime, given its tag and contents. +fn to_unix_secs(tag: u8, value: &[u8]) -> Option { + let mut tlv = vec![tag, u8::try_from(value.len()).ok()?]; + tlv.extend_from_slice(value); + let at = if tag == TAG_UTC_TIME { + UtcTime::from_der(&tlv).ok()?.to_unix_duration() + } else { + GeneralizedTime::from_der(&tlv).ok()?.to_unix_duration() + }; + Some(at.as_secs()) +} + +/// The outcome of checking one fetched CRL against the certificate it covers. +enum Verdict { + Current, + Undetermined, + WrongIssuer, +} + +fn classify(der: &[u8], cert_issuer: &[u8], now: u64) -> Verdict { + if webpki::BorrowedCertRevocationList::from_der(der).is_err() { + return Verdict::Undetermined; + } + match parse_crl(der) { + Some(crl) if crl.issuer != cert_issuer => Verdict::WrongIssuer, + Some(Crl { + next_update: Some(next), + .. + }) if now <= next => Verdict::Current, + _ => Verdict::Undetermined, + } +} + +/// A cached CRL and its nextUpdate in Unix seconds. +type CachedCrl = (Arc>, u64); + +/// Fetches CRLs and caches each until its `nextUpdate`. +#[derive(Debug)] +struct CrlFetcher { + proxy: ProxyConfig, + limits: CrlFetchLimits, + /// URL to (CRL bytes, nextUpdate in Unix seconds). + cache: Mutex>, +} + +impl CrlFetcher { + /// The CRL at `url`, from cache while current, otherwise freshly fetched. + /// `None` means the fetch failed. Only a CRL with a future `nextUpdate` is cached. + fn get(&self, url: &str, now: u64) -> Option>> { + let cached = self + .cache + .lock() + .unwrap_or_else(PoisonError::into_inner) + .get(url) + .filter(|(_, next)| now <= *next) + .map(|(der, _)| Arc::clone(der)); + if cached.is_some() { + return cached; + } + self.evict(url); + let der = Arc::new(fetch_blocking( + self.proxy.clone(), + self.limits, + url.to_owned(), + )?); + if let Some(next) = parse_crl(&der) + .and_then(|crl| crl.next_update) + .filter(|next| now <= *next) + { + self.cache + .lock() + .unwrap_or_else(PoisonError::into_inner) + .insert(url.to_owned(), (Arc::clone(&der), next)); + } + Some(der) + } + + fn evict(&self, url: &str) { + self.cache + .lock() + .unwrap_or_else(PoisonError::into_inner) + .remove(url); + } +} + +/// Runs one fetch on its own thread and runtime. The caller's runtime is never +/// re-entered, so a current-thread caller cannot deadlock. +fn fetch_blocking(proxy: ProxyConfig, limits: CrlFetchLimits, url: String) -> Option> { + std::thread::spawn(move || { + tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .ok()? + .block_on(fetch(&proxy, &url, limits)) + }) + .join() + .ok() + .flatten() +} + +/// One CRL download. It carries no auth or custom headers, goes through the +/// connection's proxy, and is bounded by time, size and redirects. +async fn fetch(proxy: &ProxyConfig, url: &str, limits: CrlFetchLimits) -> Option> { + let mut builder = reqwest::Client::builder() + .connect_timeout(limits.timeout) + .timeout(limits.timeout) + .redirect(reqwest::redirect::Policy::limited(CRL_MAX_REDIRECTS)); + if let Some(proxy_url) = &proxy.url { + let mut via = reqwest::Proxy::all(proxy_url).ok()?; + if let Some(username) = &proxy.username { + via = via.basic_auth(username, proxy.password.as_deref().unwrap_or("")); + } + if let Some(bypass) = &proxy.bypass_hosts { + let normalized = bypass + .split(',') + .map(str::trim) + .collect::>() + .join(","); + via = via.no_proxy(reqwest::NoProxy::from_string(&normalized)); + } + builder = builder.proxy(via); + } + let mut response = builder.build().ok()?.get(url).send().await.ok()?; + if response.status() != StatusCode::OK + || response + .content_length() + .is_some_and(|len| len > limits.max_bytes as u64) + { + return None; + } + let mut body = Vec::new(); + while let Some(chunk) = response.chunk().await.ok()? { + if body.len() + chunk.len() > limits.max_bytes { + return None; + } + body.extend_from_slice(&chunk); + } + Some(body) +} + +/// The server verifier: webpki for the chain, signatures and name, with CRLs. +#[derive(Debug)] +struct RevocationVerifier { + roots: Arc, + provider: Arc, + /// Webpki verifier without CRLs. Supplies the handshake signature checks. + signatures: Arc, + fetcher: CrlFetcher, + accept_undetermined: bool, + allow_hostname_mismatch: bool, +} + +impl RevocationVerifier { + /// Forgives a name-only failure under `allow_hostname_mismatch`. webpki checks + /// the name last, so the chain has already verified when this happens. + fn tolerate_name( + &self, + result: std::result::Result, + ) -> std::result::Result { + match result { + Err(rustls::Error::InvalidCertificate( + CertificateError::NotValidForName | CertificateError::NotValidForNameContext { .. }, + )) if self.allow_hostname_mismatch => Ok(ServerCertVerified::assertion()), + other => other, + } + } +} + +impl ServerCertVerifier for RevocationVerifier { + fn verify_server_cert( + &self, + end_entity: &CertificateDer<'_>, + intermediates: &[CertificateDer<'_>], + server_name: &ServerName<'_>, + ocsp_response: &[u8], + now: UnixTime, + ) -> std::result::Result { + self.tolerate_name(self.signatures.verify_server_cert( + end_entity, + intermediates, + server_name, + ocsp_response, + now, + ))?; + + let now_secs = now.as_secs(); + let mut crls = Vec::new(); + let mut used_urls = Vec::new(); + let mut undetermined = false; + for cert in std::iter::once(end_entity).chain(intermediates) { + let Some(parsed) = parse_cert(cert.as_ref()) else { + undetermined = true; + continue; + }; + // Trust anchors are not revocation-checked (webpki does not check them either). + if parsed.self_issued { + continue; + } + let mut covered = false; + for url in &parsed.crl_uris { + let Some(der) = self.fetcher.get(url, now_secs) else { + continue; + }; + match classify(&der, parsed.issuer, now_secs) { + Verdict::Current => { + crls.push(CertificateRevocationListDer::from(der.to_vec())); + used_urls.push(url.clone()); + covered = true; + } + Verdict::Undetermined => self.fetcher.evict(url), + Verdict::WrongIssuer => { + self.fetcher.evict(url); + return Err(rustls::Error::InvalidCertRevocationList( + CertRevocationListError::IssuerInvalidForCrl, + )); + } + } + } + undetermined |= !covered; + } + if undetermined && !self.accept_undetermined { + return Err(rustls::Error::InvalidCertificate( + CertificateError::UnknownRevocationStatus, + )); + } + + let mut builder = WebPkiServerVerifier::builder_with_provider( + Arc::clone(&self.roots), + Arc::clone(&self.provider), + ) + .with_crls(crls); + if self.accept_undetermined { + builder = builder.allow_unknown_revocation_status(); + } + let verifier = builder + .build() + .map_err(|e| rustls::Error::General(format!("revocation verifier setup: {e}")))?; + let result = self.tolerate_name(verifier.verify_server_cert( + end_entity, + intermediates, + server_name, + ocsp_response, + now, + )); + // A CRL that webpki rejects must not stay cached. + if let Err(rustls::Error::InvalidCertRevocationList(_)) = &result { + for url in &used_urls { + self.fetcher.evict(url); + } + } + result + } + + fn verify_tls12_signature( + &self, + message: &[u8], + cert: &CertificateDer<'_>, + dss: &DigitallySignedStruct, + ) -> std::result::Result { + self.signatures.verify_tls12_signature(message, cert, dss) + } + + fn verify_tls13_signature( + &self, + message: &[u8], + cert: &CertificateDer<'_>, + dss: &DigitallySignedStruct, + ) -> std::result::Result { + self.signatures.verify_tls13_signature(message, cert, dss) + } + + fn supported_verify_schemes(&self) -> Vec { + self.signatures.supported_verify_schemes() + } +} + +fn tls_error(e: impl std::fmt::Display) -> Error { + Error::invalid_argument().message(format!("invalid TLS configuration: {e}")) +} + +/// The rustls config for a connection with revocation checking. Trust roots are +/// webpki roots, then the OS store, then custom CAs, as reqwest's rustls assembly +/// uses. ALPN is HTTP/1.1, since the kernel enables no HTTP/2. +/// +/// The caller has already validated the PEM bytes and the mTLS identity pair, so +/// they are parsed here without re-checking. +pub(crate) fn client_config( + tls: &TlsConfig, + proxy: &ProxyConfig, + accept_undetermined: bool, +) -> Result { + let provider = Arc::new(rustls::crypto::ring::default_provider()); + let mut roots = RootCertStore::empty(); + roots.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned()); + // Same assembly and failure rule as reqwest's rustls-tls-native-roots path + // (reqwest-0.12.28 src/async_impl/client.rs:697-732): entries that do not parse + // are skipped, and the build fails only when none parse. + let native = rustls_native_certs::load_native_certs(); + let (mut valid, mut invalid) = (0_usize, 0_usize); + for cert in native.certs { + match roots.add(cert) { + Ok(()) => valid += 1, + Err(_) => invalid += 1, + } + } + if valid == 0 && invalid > 0 { + let detail = if native.errors.is_empty() { + "zero valid certificates found in native root store".to_owned() + } else { + native + .errors + .iter() + .map(ToString::to_string) + .collect::>() + .join("\n") + }; + return Err( + Error::invalid_argument().message(format!("Failed to create HTTP client: {detail}")) + ); + } + let mut pems = Vec::new(); + if let Some(path) = &tls.trusted_certificate_path { + pems.push(std::fs::read(path).map_err(tls_error)?); + } + if let Some(pem) = &tls.trusted_certificate_pem { + pems.push(pem.clone()); + } + for pem in pems { + for cert in CertificateDer::pem_slice_iter(&pem) { + roots.add(cert.map_err(tls_error)?).map_err(tls_error)?; + } + } + + let roots = Arc::new(roots); + let signatures = + WebPkiServerVerifier::builder_with_provider(Arc::clone(&roots), Arc::clone(&provider)) + .build() + .map_err(tls_error)?; + let verifier = RevocationVerifier { + roots, + provider: Arc::clone(&provider), + signatures, + fetcher: CrlFetcher { + proxy: proxy.clone(), + limits: tls.crl_fetch_limits, + cache: Mutex::new(HashMap::new()), + }, + accept_undetermined, + allow_hostname_mismatch: tls.allow_hostname_mismatch.unwrap_or(false), + }; + + let builder = ClientConfig::builder_with_provider(provider) + .with_safe_default_protocol_versions() + .map_err(tls_error)? + .dangerous() + .with_custom_certificate_verifier(Arc::new(verifier)); + let mut config = match (&tls.client_cert_pem, &tls.client_key_pem) { + (Some(cert), Some(key)) => { + let chain = CertificateDer::pem_slice_iter(cert) + .collect::, _>>() + .map_err(tls_error)?; + let key = PrivateKeyDer::from_pem_slice(key).map_err(tls_error)?; + builder + .with_client_auth_cert(chain, key) + .map_err(tls_error)? + } + _ => builder.with_no_client_auth(), + }; + config.alpn_protocols = vec![b"http/1.1".to_vec()]; + Ok(config) +} + +#[cfg(test)] +#[path = "tls_revocation_tests.rs"] +mod tests; diff --git a/src/client/tls_revocation_tests.rs b/src/client/tls_revocation_tests.rs new file mode 100644 index 00000000..3fba6755 --- /dev/null +++ b/src/client/tls_revocation_tests.rs @@ -0,0 +1,925 @@ +// Copyright (c) 2026 Databricks, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Hermetic revocation tests. Each fixture generates a root, an intermediate and a +//! leaf with rcgen, serves the CRLs over HTTP on loopback, and serves the leaf over +//! TLS on loopback. A forward-proxy stub can sit in front of the CRL fetches. + +use super::*; +use crate::client::http::{CrlFetchLimits, DatabricksHttpClient, HttpClientConfig}; +use rcgen::{ + date_time_ymd, BasicConstraints, CertificateParams, CertificateRevocationListParams, + CrlDistributionPoint, CustomExtension, DnType, IsCa, Issuer, KeyIdMethod, KeyPair, + RevokedCertParams, SerialNumber, SigningKey, +}; +use rustls::pki_types::PrivatePkcs8KeyDer; +use std::collections::HashMap; +use std::io::{Read, Write}; +use std::net::{Shutdown, SocketAddr, TcpListener, TcpStream}; +use std::sync::{Arc, Mutex}; +use std::thread; +use std::time::Duration; + +/// Lower-cased fragment of rustls's `UnknownRevocationStatus` error text. +const UNDETERMINED: &str = "unknownrevocationstatus"; +const ROOT_CN: &str = "Revocation Test Root"; +const INTERMEDIATE_CN: &str = "Revocation Test Intermediate"; +const LEAF_SERIAL: u64 = 1000; +const INTERMEDIATE_SERIAL: u64 = 2000; +const CLIENT_SERIAL: u64 = 3000; +/// (year, month, day) for CRL validity bounds. +type Ymd = (i32, u8, u8); +const CURRENT: Ymd = (2099, 1, 1); +const EXPIRED: Ymd = (2021, 1, 1); + +/// What the CRL at one distribution point serves. +#[derive(Clone, Copy)] +enum Served { + Good, + /// Lists the covered certificate as revoked. + Revoked, + /// Signed with a key other than the issuer's (same issuer name). + WrongKey, + /// Signed by the other CA in the chain. + WrongIssuer, + Expired, + Status(u16), + /// Responds after the fetch timeout. + Timeout, + /// Body larger than the fetch size limit. + Oversize, + /// Distribution point is a closed port. + Refused, + /// Distribution point is not http(s), so there is nothing to fetch. + NonHttp, + /// Distribution point is indirect (has a cRLIssuer), so it must be skipped. + Indirect, +} + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum Outcome { + Pass, + Revoked, + Undetermined, + InvalidCrl, +} + +#[derive(Clone, Copy)] +enum Relay { + /// The proxy forwards plain CRL requests to the origin. + Forward, + /// The proxy answers plain CRL requests with 502. The origin must not be reached. + Refuse, +} + +/// One table row. Each row is checked in strict and accept-undetermined modes. +struct Scenario { + name: &'static str, + /// `None` means the leaf has no CRL distribution point. + leaf: Option, + intermediate: Served, + relay: Option, + strict: Outcome, + accept: Outcome, +} + +// One row per line, so the table stays readable. rustfmt would split each row. +#[rustfmt::skip] +const SCENARIOS: &[Scenario] = &[ + Scenario { + name: "good chain", + leaf: Some(Served::Good), + intermediate: Served::Good, + relay: None, + strict: Outcome::Pass, + accept: Outcome::Pass, + }, + Scenario { + name: "revoked leaf", + leaf: Some(Served::Revoked), + intermediate: Served::Good, + relay: None, + strict: Outcome::Revoked, + accept: Outcome::Revoked, + }, + Scenario { + name: "revoked intermediate", + leaf: Some(Served::Good), + intermediate: Served::Revoked, + relay: None, + strict: Outcome::Revoked, + accept: Outcome::Revoked, + }, + Scenario { + name: "leaf without CDP", + leaf: None, + intermediate: Served::Good, + relay: None, + strict: Outcome::Undetermined, + accept: Outcome::Pass, + }, + Scenario { + name: "leaf CRL HTTP 503", + leaf: Some(Served::Status(503)), + intermediate: Served::Good, + relay: None, + strict: Outcome::Undetermined, + accept: Outcome::Pass, + }, + Scenario { + name: "leaf CRL refused", + leaf: Some(Served::Refused), + intermediate: Served::Good, + relay: None, + strict: Outcome::Undetermined, + accept: Outcome::Pass, + }, + Scenario { + name: "leaf CRL timeout", + leaf: Some(Served::Timeout), + intermediate: Served::Good, + relay: None, + strict: Outcome::Undetermined, + accept: Outcome::Pass, + }, + Scenario { + name: "leaf CRL oversize", + leaf: Some(Served::Oversize), + intermediate: Served::Good, + relay: None, + strict: Outcome::Undetermined, + accept: Outcome::Pass, + }, + Scenario { + name: "leaf CRL expired", + leaf: Some(Served::Expired), + intermediate: Served::Good, + relay: None, + strict: Outcome::Undetermined, + accept: Outcome::Pass, + }, + Scenario { + name: "leaf CDP not http(s)", + leaf: Some(Served::NonHttp), + intermediate: Served::Good, + relay: None, + strict: Outcome::Undetermined, + accept: Outcome::Pass, + }, + Scenario { + name: "leaf CDP indirect (cRLIssuer)", + leaf: Some(Served::Indirect), + intermediate: Served::Good, + relay: None, + strict: Outcome::Undetermined, + accept: Outcome::Pass, + }, + Scenario { + name: "intermediate CRL HTTP 503", + leaf: Some(Served::Good), + intermediate: Served::Status(503), + relay: None, + strict: Outcome::Undetermined, + accept: Outcome::Pass, + }, + Scenario { + name: "leaf CRL wrong key", + leaf: Some(Served::WrongKey), + intermediate: Served::Good, + relay: None, + strict: Outcome::InvalidCrl, + accept: Outcome::InvalidCrl, + }, + Scenario { + name: "leaf CRL wrong issuer", + leaf: Some(Served::WrongIssuer), + intermediate: Served::Good, + relay: None, + strict: Outcome::InvalidCrl, + accept: Outcome::InvalidCrl, + }, + Scenario { + name: "good chain via proxy", + leaf: Some(Served::Good), + intermediate: Served::Good, + relay: Some(Relay::Forward), + strict: Outcome::Pass, + accept: Outcome::Pass, + }, + Scenario { + name: "revoked leaf via proxy", + leaf: Some(Served::Revoked), + intermediate: Served::Good, + relay: Some(Relay::Forward), + strict: Outcome::Revoked, + accept: Outcome::Revoked, + }, + Scenario { + name: "refused by proxy, no bypass", + leaf: Some(Served::Good), + intermediate: Served::Good, + relay: Some(Relay::Refuse), + strict: Outcome::Undetermined, + accept: Outcome::Pass, + }, +]; + +struct Pki { + root_der: CertificateDer<'static>, + root_pem: String, + root_issuer: Issuer<'static, KeyPair>, + intermediate_issuer: Issuer<'static, KeyPair>, + intermediate_der: CertificateDer<'static>, + leaf_der: CertificateDer<'static>, + leaf_key_der: Vec, + client_cert_pem: String, + client_key_pem: String, +} + +fn ca_params(common_name: &str, serial: u64) -> CertificateParams { + let mut params = CertificateParams::new(Vec::new()).unwrap(); + params.is_ca = IsCa::Ca(BasicConstraints::Unconstrained); + params + .distinguished_name + .push(DnType::CommonName, common_name); + params.serial_number = Some(SerialNumber::from(serial)); + params +} + +/// The leaf's CRL distribution point. +enum LeafCdp { + None, + Uris(Vec), + /// An indirect point: `uri` as a full name, plus a cRLIssuer. + Indirect(String), +} + +/// A distribution point that is not http(s). Verifiers must ignore it. +const NON_HTTP_CDP: &str = "ldap://127.0.0.1/cn=crl"; + +/// A CRLDistributionPoints extension holding one indirect point. +fn indirect_cdp(uri: &str) -> CustomExtension { + let tlv = |tag: u8, content: &[u8]| { + assert!(content.len() < 128, "short-form DER only"); + let mut out = vec![tag, content.len() as u8]; + out.extend_from_slice(content); + out + }; + let full_name = tlv(0xA0, &tlv(0x86, uri.as_bytes())); + let point_name = tlv(0xA0, &full_name); + let issuer = tlv(0xA2, &tlv(0x86, b"http://crl-issuer.invalid/")); + let point = tlv(0x30, &[point_name, issuer].concat()); + CustomExtension::from_oid_content(&[2, 5, 29, 31], tlv(0x30, &point)) +} + +fn build_pki(leaf_cdp: LeafCdp, intermediate_cdp: String, san: &str) -> Pki { + let root_key = KeyPair::generate().unwrap(); + let root_params = ca_params(ROOT_CN, 1); + let root_cert = root_params.self_signed(&root_key).unwrap(); + let root_pem = root_cert.pem(); + let root_der = root_cert.der().clone(); + let root_issuer = Issuer::new(root_params, root_key); + + let intermediate_key = KeyPair::generate().unwrap(); + let mut intermediate_params = ca_params(INTERMEDIATE_CN, INTERMEDIATE_SERIAL); + intermediate_params.crl_distribution_points = vec![CrlDistributionPoint { + uris: vec![intermediate_cdp], + }]; + let intermediate_cert = intermediate_params + .signed_by(&intermediate_key, &root_issuer) + .unwrap(); + let intermediate_pem = intermediate_cert.pem(); + let intermediate_der = intermediate_cert.der().clone(); + let intermediate_issuer = Issuer::new(intermediate_params, intermediate_key); + + let leaf_key = KeyPair::generate().unwrap(); + let mut leaf_params = CertificateParams::new(vec![san.to_owned()]).unwrap(); + leaf_params.serial_number = Some(SerialNumber::from(LEAF_SERIAL)); + match leaf_cdp { + LeafCdp::None => {} + LeafCdp::Uris(uris) => { + leaf_params.crl_distribution_points = vec![CrlDistributionPoint { uris }]; + } + LeafCdp::Indirect(uri) => leaf_params.custom_extensions = vec![indirect_cdp(&uri)], + } + let leaf_der = leaf_params + .signed_by(&leaf_key, &intermediate_issuer) + .unwrap() + .der() + .clone(); + + let client_key = KeyPair::generate().unwrap(); + let mut client_params = + CertificateParams::new(vec!["revocation-test-client".to_owned()]).unwrap(); + client_params.serial_number = Some(SerialNumber::from(CLIENT_SERIAL)); + let client_cert = client_params + .signed_by(&client_key, &intermediate_issuer) + .unwrap(); + + Pki { + root_der, + root_pem, + root_issuer, + intermediate_issuer, + intermediate_der, + leaf_der, + leaf_key_der: leaf_key.serialize_der(), + // The mTLS identity presents the client leaf, then its intermediate. + client_cert_pem: format!("{}{intermediate_pem}", client_cert.pem()), + client_key_pem: client_key.serialize_pem(), + } +} + +/// A CRL listing `revoked` serials, valid until `next_update`. +fn sign_crl(issuer: &Issuer<'_, K>, revoked: &[u64], next_update: Ymd) -> Vec { + CertificateRevocationListParams { + this_update: date_time_ymd(2020, 1, 1), + next_update: date_time_ymd(next_update.0, next_update.1, next_update.2), + crl_number: SerialNumber::from(1_u64), + issuing_distribution_point: None, + revoked_certs: revoked + .iter() + .map(|serial| RevokedCertParams { + serial_number: SerialNumber::from(*serial), + revocation_time: date_time_ymd(2020, 1, 2), + reason_code: None, + invalidity_date: None, + }) + .collect(), + key_identifier_method: KeyIdMethod::Sha256, + } + .signed_by(issuer) + .unwrap() + .der() + .to_vec() +} + +/// The route for one CRL. `issuer` signs it, `covered` is the serial it revokes, +/// and `other` is the other CA (used for `WrongIssuer`). +fn route( + served: Served, + issuer: &Issuer<'_, KeyPair>, + issuer_cn: &str, + covered: u64, + other: &Issuer<'_, KeyPair>, +) -> Route { + let body = |bytes: Vec| Route { + status: 200, + body: bytes, + delay: Duration::ZERO, + }; + match served { + Served::Good => body(sign_crl(issuer, &[], CURRENT)), + Served::Revoked => body(sign_crl(issuer, &[covered], CURRENT)), + Served::WrongKey => { + let impostor = Issuer::new(ca_params(issuer_cn, 0), KeyPair::generate().unwrap()); + body(sign_crl(&impostor, &[covered], CURRENT)) + } + Served::WrongIssuer => body(sign_crl(other, &[], CURRENT)), + Served::Expired => body(sign_crl(issuer, &[], EXPIRED)), + Served::Status(status) => Route { + status, + body: Vec::new(), + delay: Duration::ZERO, + }, + Served::Timeout => Route { + status: 200, + body: sign_crl(issuer, &[], CURRENT), + delay: Duration::from_secs(3), + }, + Served::Oversize => body(vec![0; 128 * 1024]), + Served::Refused | Served::NonHttp | Served::Indirect => { + unreachable!("this distribution point kind has no route") + } + } +} + +/// A PKI, its CRL origin server, and the TLS leaf server. +struct Fixture { + crl: CrlServer, + pki: Pki, + addr: SocketAddr, +} + +fn fixture(leaf: Option, intermediate: Served, san: &str) -> Fixture { + let crl = CrlServer::start(); + let dead = TcpListener::bind("127.0.0.1:0") + .unwrap() + .local_addr() + .unwrap(); + let cdp = |served: Served, path: &str| match served { + Served::Refused => format!("http://{dead}{path}"), + _ => crl.url(path), + }; + let leaf_cdp = match leaf { + None => LeafCdp::None, + Some(Served::NonHttp) => LeafCdp::Uris(vec![NON_HTTP_CDP.to_owned()]), + Some(Served::Indirect) => LeafCdp::Indirect(crl.url("/leaf.crl")), + Some(served) => LeafCdp::Uris(vec![cdp(served, "/leaf.crl")]), + }; + let pki = build_pki(leaf_cdp, cdp(intermediate, "/intermediate.crl"), san); + // An indirect point names a CRL that is served but must be skipped, so serve a good one. + let routed = match leaf { + Some(Served::Indirect) => Some(Served::Good), + Some(Served::Refused | Served::NonHttp) | None => None, + other => other, + }; + if let Some(served) = routed { + crl.set( + "/leaf.crl", + route( + served, + &pki.intermediate_issuer, + INTERMEDIATE_CN, + LEAF_SERIAL, + &pki.root_issuer, + ), + ); + } + if !matches!(intermediate, Served::Refused) { + crl.set( + "/intermediate.crl", + route( + intermediate, + &pki.root_issuer, + ROOT_CN, + INTERMEDIATE_SERIAL, + &pki.intermediate_issuer, + ), + ); + } + let addr = spawn_tls_server(&pki, false); + Fixture { crl, pki, addr } +} + +/// A TLS server presenting the leaf chain. With `mtls`, it requires a client +/// certificate that chains to the test root. +fn spawn_tls_server(pki: &Pki, mtls: bool) -> SocketAddr { + let provider = Arc::new(rustls::crypto::ring::default_provider()); + let builder = rustls::ServerConfig::builder_with_provider(provider) + .with_safe_default_protocol_versions() + .unwrap(); + let chain = vec![pki.leaf_der.clone(), pki.intermediate_der.clone()]; + let key = PrivatePkcs8KeyDer::from(pki.leaf_key_der.clone()).into(); + let config = if mtls { + let mut roots = rustls::RootCertStore::empty(); + roots.add(pki.root_der.clone()).unwrap(); + let verifier = rustls::server::WebPkiClientVerifier::builder(Arc::new(roots)) + .build() + .unwrap(); + builder + .with_client_cert_verifier(verifier) + .with_single_cert(chain, key) + .unwrap() + } else { + builder + .with_no_client_auth() + .with_single_cert(chain, key) + .unwrap() + }; + let config = Arc::new(config); + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = listener.local_addr().unwrap(); + thread::spawn(move || { + for tcp in listener.incoming().flatten() { + let config = Arc::clone(&config); + thread::spawn(move || { + let Ok(conn) = rustls::ServerConnection::new(config) else { + return; + }; + let mut stream = rustls::StreamOwned::new(conn, tcp); + if read_head(&mut stream).is_some() { + let _ = stream.write_all( + b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok", + ); + let _ = stream.flush(); + } + }); + } + }); + addr +} + +/// Reads one request or response head, up to the blank line. +fn read_head(stream: &mut impl Read) -> Option { + let mut head = Vec::new(); + let mut byte = [0_u8; 1]; + while !head.ends_with(b"\r\n\r\n") && head.len() < 8192 { + match stream.read(&mut byte) { + Ok(1) => head.push(byte[0]), + _ => return None, + } + } + Some(String::from_utf8_lossy(&head).into_owned()) +} + +#[derive(Clone)] +struct Route { + status: u16, + body: Vec, + delay: Duration, +} + +/// Loopback HTTP server for CRLs. It records each request head and answers from a +/// route table that can be filled after the PKI (which holds the URLs) exists. +#[derive(Clone)] +struct CrlServer { + addr: SocketAddr, + routes: Arc>>, + requests: Arc>>, +} + +impl CrlServer { + fn start() -> Self { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let server = Self { + addr: listener.local_addr().unwrap(), + routes: Arc::new(Mutex::new(HashMap::new())), + requests: Arc::new(Mutex::new(Vec::new())), + }; + let accept_side = server.clone(); + thread::spawn(move || { + for stream in listener.incoming().flatten() { + let handler = accept_side.clone(); + thread::spawn(move || handler.handle(stream)); + } + }); + server + } + + fn url(&self, path: &str) -> String { + format!("http://{}{path}", self.addr) + } + + fn set(&self, path: &str, route: Route) { + self.routes.lock().unwrap().insert(path.to_owned(), route); + } + + /// Requests received for `path`. + fn hits(&self, path: &str) -> usize { + self.requests + .lock() + .unwrap() + .iter() + .filter(|(seen, _)| seen == path) + .count() + } + + /// Every request head received, lower-cased. + fn headers(&self) -> String { + self.requests + .lock() + .unwrap() + .iter() + .map(|(_, head)| head.to_ascii_lowercase()) + .collect() + } + + fn handle(&self, mut stream: TcpStream) { + let Some(head) = read_head(&mut stream) else { + return; + }; + let path = head + .lines() + .next() + .and_then(|line| line.split_whitespace().nth(1)) + .unwrap_or("/") + .to_owned(); + self.requests.lock().unwrap().push((path.clone(), head)); + let route = self + .routes + .lock() + .unwrap() + .get(&path) + .cloned() + .unwrap_or(Route { + status: 404, + body: Vec::new(), + delay: Duration::ZERO, + }); + if !route.delay.is_zero() { + thread::sleep(route.delay); + } + let mut response = format!( + "HTTP/1.1 {} X\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", + route.status, + route.body.len() + ) + .into_bytes(); + response.extend_from_slice(&route.body); + // The client may have given up already (timeout case). + let _ = stream.write_all(&response); + } +} + +/// Loopback forward proxy. Plain requests arrive in absolute form and are recorded. +/// CONNECT is tunnelled, so the TLS leaf also connects through the proxy. +struct ForwardProxy { + addr: SocketAddr, + heads: Arc>>, +} + +impl ForwardProxy { + fn start(relay: Relay) -> Self { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = listener.local_addr().unwrap(); + let heads = Arc::new(Mutex::new(Vec::new())); + let shared = Arc::clone(&heads); + thread::spawn(move || { + for client in listener.incoming().flatten() { + let heads = Arc::clone(&shared); + thread::spawn(move || handle_proxy_client(client, &heads, relay)); + } + }); + Self { addr, heads } + } + + /// Plain (non-CONNECT) request heads the proxy received. + fn plain_requests(&self) -> Vec { + self.heads + .lock() + .unwrap() + .iter() + .filter(|head| !head.starts_with("CONNECT ")) + .cloned() + .collect() + } +} + +fn handle_proxy_client(mut client: TcpStream, heads: &Mutex>, relay: Relay) { + let Some(head) = read_head(&mut client) else { + return; + }; + heads.lock().unwrap().push(head.clone()); + let mut request_line = head.lines().next().unwrap_or("").split_whitespace(); + let method = request_line.next().unwrap_or("").to_owned(); + let target = request_line.next().unwrap_or("").to_owned(); + let bad_gateway = b"HTTP/1.1 502 Bad Gateway\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"; + + if method == "CONNECT" { + if let Ok(upstream) = TcpStream::connect(&target) { + if client + .write_all(b"HTTP/1.1 200 Connection established\r\n\r\n") + .is_ok() + { + tunnel(client, upstream); + } + } + return; + } + if matches!(relay, Relay::Refuse) { + let _ = client.write_all(bad_gateway); + return; + } + // Absolute-form target: http://host:port/path. Forward it in origin form, minus + // the proxy-only headers, and relay the origin's response back. + let rest = target.strip_prefix("http://").unwrap_or(&target); + let (authority, path) = rest + .split_once('/') + .map_or((rest, "/".to_owned()), |(authority, path)| { + (authority, format!("/{path}")) + }); + let Ok(mut upstream) = TcpStream::connect(authority) else { + let _ = client.write_all(bad_gateway); + return; + }; + let mut forwarded = format!("{method} {path} HTTP/1.1\r\n"); + for line in head.split("\r\n").skip(1) { + if !line.is_empty() && !line.to_ascii_lowercase().starts_with("proxy-") { + forwarded.push_str(line); + forwarded.push_str("\r\n"); + } + } + forwarded.push_str("\r\n"); + if upstream.write_all(forwarded.as_bytes()).is_ok() { + let mut response = Vec::new(); + let _ = upstream.read_to_end(&mut response); + let _ = client.write_all(&response); + } +} + +/// Copies bytes both ways until either side closes. +fn tunnel(client: TcpStream, upstream: TcpStream) { + let (Ok(mut client_read), Ok(mut upstream_write)) = (client.try_clone(), upstream.try_clone()) + else { + return; + }; + let mut upstream_read = upstream; + let mut client_write = client; + let back = thread::spawn(move || { + let _ = std::io::copy(&mut upstream_read, &mut client_write); + }); + let _ = std::io::copy(&mut client_read, &mut upstream_write); + let _ = upstream_write.shutdown(Shutdown::Write); + let _ = back.join(); +} + +/// Config that trusts the test root, asks for revocation, and fetches with short bounds. +fn revocation_config(root_pem: &str, accept_undetermined: bool) -> HttpClientConfig { + let mut config = HttpClientConfig::default(); + config.tls.trusted_certificate_pem = Some(root_pem.as_bytes().to_vec()); + config.tls.check_certificate_revocation = Some(true); + config.tls.accept_undetermined_certificate_revocation = Some(accept_undetermined); + config.tls.crl_fetch_limits = CrlFetchLimits { + timeout: Duration::from_millis(500), + max_bytes: 64 * 1024, + }; + // No pooling: each request runs a fresh handshake and revocation check. + config.max_connections_per_host = 0; + config +} + +async fn get(config: HttpClientConfig, addr: SocketAddr) -> std::result::Result<(), String> { + let client = DatabricksHttpClient::with_default_retry(config).unwrap(); + client + .inner() + .get(format!("https://{addr}/")) + .send() + .await + .map(|_| ()) + .map_err(|error| error_text(&error)) +} + +fn error_text(error: &dyn std::error::Error) -> String { + let mut text = error.to_string(); + let mut source = error.source(); + while let Some(inner) = source { + text.push_str(": "); + text.push_str(&inner.to_string()); + source = inner.source(); + } + text.to_ascii_lowercase() +} + +/// Runs one table row in one policy mode and checks the outcome, the proxy routing, +/// and that the CRL requests carry no auth or connection headers. +async fn check(scenario: &Scenario, accept: bool, want: Outcome) { + let fx = fixture(scenario.leaf, scenario.intermediate, "127.0.0.1"); + let proxy = scenario.relay.map(ForwardProxy::start); + let mut config = revocation_config(&fx.pki.root_pem, accept); + config.custom_headers = vec![("X-Kernel-Secret".to_owned(), "hunter2".to_owned())]; + config.org_id = Some("1234".to_owned()); + if let Some(proxy) = &proxy { + config.proxy.url = Some(format!("http://{}", proxy.addr)); + } + + let label = format!("{} (accept_undetermined={accept})", scenario.name); + let result = get(config, fx.addr).await; + match (want, &result) { + (Outcome::Pass, Ok(())) => {} + (Outcome::Revoked, Err(err)) => assert!(err.contains("revoked"), "{label}: {err}"), + (Outcome::Undetermined, Err(err)) => assert!(err.contains(UNDETERMINED), "{label}: {err}"), + (Outcome::InvalidCrl, Err(err)) => { + assert!( + err.contains("revocation list") && !err.contains(UNDETERMINED), + "{label}: {err}" + ); + } + _ => panic!("{label}: expected {want:?}, got {result:?}"), + } + + let headers = fx.crl.headers(); + for forbidden in [ + "authorization", + "x-kernel-secret", + "x-databricks-org-id", + "cookie", + ] { + assert!( + !headers.contains(forbidden), + "{label}: CRL request carried {forbidden}: {headers}" + ); + } + match (scenario.relay, proxy) { + (Some(Relay::Forward), Some(proxy)) => { + assert!( + !proxy.plain_requests().is_empty(), + "{label}: CRL fetches must reach the proxy" + ); + } + (Some(Relay::Refuse), Some(proxy)) => { + assert!( + !proxy.plain_requests().is_empty(), + "{label}: CRL fetches must reach the proxy" + ); + assert_eq!( + fx.crl.hits("/leaf.crl") + fx.crl.hits("/intermediate.crl"), + 0, + "{label}: proxy refusal must not bypass to the origin" + ); + } + _ => {} + } +} + +#[tokio::test] +async fn revocation_outcomes_follow_the_policy_table() { + for scenario in SCENARIOS { + check(scenario, false, scenario.strict).await; + check(scenario, true, scenario.accept).await; + } +} + +#[tokio::test] +async fn current_crl_is_fetched_once_and_a_rejected_one_is_refetched() { + let fx = fixture(Some(Served::Good), Served::Good, "127.0.0.1"); + let client = + DatabricksHttpClient::with_default_retry(revocation_config(&fx.pki.root_pem, false)) + .unwrap(); + for _ in 0..2 { + client + .inner() + .get(format!("https://{}/", fx.addr)) + .send() + .await + .expect("good chain"); + } + assert_eq!( + fx.crl.hits("/leaf.crl"), + 1, + "a current CRL is cached until nextUpdate" + ); + assert_eq!(fx.crl.hits("/intermediate.crl"), 1); + + let fx = fixture(Some(Served::WrongKey), Served::Good, "127.0.0.1"); + let client = + DatabricksHttpClient::with_default_retry(revocation_config(&fx.pki.root_pem, false)) + .unwrap(); + for _ in 0..2 { + assert!(client + .inner() + .get(format!("https://{}/", fx.addr)) + .send() + .await + .is_err()); + } + assert_eq!( + fx.crl.hits("/leaf.crl"), + 2, + "a CRL that webpki rejects is not served from cache" + ); +} + +#[tokio::test] +async fn hostname_mismatch_is_rejected_unless_allowed() { + let fx = fixture(Some(Served::Good), Served::Good, "wrong-host.invalid"); + get(revocation_config(&fx.pki.root_pem, false), fx.addr) + .await + .expect_err("a name mismatch is rejected by default"); + let mut config = revocation_config(&fx.pki.root_pem, false); + config.tls.allow_hostname_mismatch = Some(true); + get(config, fx.addr) + .await + .expect("allow_hostname_mismatch passes a good chain with revocation still checked"); +} + +#[tokio::test] +async fn client_identity_and_custom_ca_work_with_revocation() { + let fx = fixture(Some(Served::Good), Served::Good, "127.0.0.1"); + let mtls_addr = spawn_tls_server(&fx.pki, true); + let mut config = revocation_config(&fx.pki.root_pem, false); + config.tls.client_cert_pem = Some(fx.pki.client_cert_pem.clone().into_bytes()); + config.tls.client_key_pem = Some(fx.pki.client_key_pem.clone().into_bytes()); + get(config.clone(), mtls_addr) + .await + .expect("mTLS identity passes with revocation"); + + config.tls.client_cert_pem = None; + config.tls.client_key_pem = None; + get(config, mtls_addr) + .await + .expect_err("the mTLS server rejects a client without an identity"); +} + +#[tokio::test] +async fn policy_off_and_accept_self_signed_skip_revocation() { + let fx = fixture(Some(Served::Revoked), Served::Good, "127.0.0.1"); + let mut off = revocation_config(&fx.pki.root_pem, false); + off.tls.check_certificate_revocation = None; + get(off, fx.addr) + .await + .expect("policy off passes a revoked leaf"); + + let mut self_signed = revocation_config(&fx.pki.root_pem, false); + self_signed.tls.allow_self_signed = Some(true); + get(self_signed, fx.addr) + .await + .expect("accept_self_signed turns revocation off"); + + assert_eq!( + fx.crl.hits("/leaf.crl"), + 0, + "no CRL is fetched when revocation is off" + ); +} diff --git a/src/config.rs b/src/config.rs index 9c1eb0a9..e635eab2 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1041,6 +1041,16 @@ pub struct TlsConfig { /// [`Self::client_cert_pem`] for pairing rules and the /// backend-specific validation timing. pub client_key_pem: Option>, + + /// Check the server chain's revocation status against its CRL distribution + /// points. Default off. Revoked certificates are always rejected. Requires + /// the `tls-rustls` backend; `tls-native` fails session open with + /// `InvalidArgument`. Disabled by [`Self::accept_self_signed`]. + pub check_certificate_revocation: Option, + + /// With [`Self::check_certificate_revocation`] on, accept a chain whose status + /// cannot be determined (no CRL, fetch failure, expired CRL). Default off. + pub accept_undetermined_certificate_revocation: Option, } impl std::fmt::Debug for TlsConfig { diff --git a/src/session.rs b/src/session.rs index b77305af..6aa66b29 100644 --- a/src/session.rs +++ b/src/session.rs @@ -366,6 +366,9 @@ impl Session { // 1. HTTP client — built before auth so OAuth providers can use // it for OIDC discovery / token endpoint calls. let http_client_config = build_http_client_config(&config, org_id); + // Checked before the client-construction wrapping below, so the + // configuration error keeps its InvalidArgument category. + crate::client::http::check_revocation_support(&http_client_config.tls)?; let retry_configs = build_retry_configs_for_session(&config); let http_client = Arc::new( DatabricksHttpClient::new(http_client_config, retry_configs).map_err(|e| { @@ -3947,3 +3950,44 @@ mod is_open_tests { } } } + +#[cfg(all(test, not(feature = "tls-rustls")))] +mod revocation_open_tests { + use super::*; + + #[tokio::test] + async fn revocation_on_tls_native_fails_open_as_invalid_argument() { + let config = SessionConfig { + connection: ConnectionConfig::new("https://workspace.invalid", "test_wh"), + defaults: None, + auth: AuthConfig::Pat { + token: "dapi-test".to_string(), + identity_federation_client_id: None, + }, + driver_system_configuration: None, + session_conf: Default::default(), + geospatial_result_representation: None, + http: HttpConfig::default(), + proxy: None, + tls: TlsConfig { + check_certificate_revocation: Some(true), + ..TlsConfig::default() + }, + result: ResultConfig::default(), + logging: LoggingConfig::default(), + telemetry: TelemetryConfig::default(), + transport: None, + }; + let error = Session::open(config) + .await + .expect_err("tls-native must reject a revocation request"); + assert_eq!(error.code, crate::kernel_error::ErrorCode::InvalidArgument); + assert!( + error + .message + .contains("certificate revocation checking requires the tls-rustls backend"), + "{}", + error.message + ); + } +} diff --git a/tests/c/session_smoke.c b/tests/c/session_smoke.c index f6b78c2c..e44a9052 100644 --- a/tests/c/session_smoke.c +++ b/tests/c/session_smoke.c @@ -310,6 +310,25 @@ static void test_enable_geospatial_support_setter(void) { "set_enable_geospatial_support(NULL cfg) -> InvalidArgument"); } +/* TLS certificate-revocation setter: strict, accept-undetermined and off all + * succeed; a null config is rejected. */ +static void test_tls_certificate_revocation_setter(void) { + KernelSessionConfig* config = NULL; + (void)kernel_session_config_new(&config); + KernelStatusCode rc = kernel_session_config_set_tls_certificate_revocation(config, true, false); + CHECK(rc == KernelStatusCode_Success, "set_tls_certificate_revocation(check, strict) succeeds"); + rc = kernel_session_config_set_tls_certificate_revocation(config, true, true); + CHECK(rc == KernelStatusCode_Success, + "set_tls_certificate_revocation(check, accept undetermined) succeeds"); + rc = kernel_session_config_set_tls_certificate_revocation(config, false, false); + CHECK(rc == KernelStatusCode_Success, "set_tls_certificate_revocation(off) succeeds"); + kernel_session_config_free(config); + + rc = kernel_session_config_set_tls_certificate_revocation(NULL, true, false); + CHECK(rc == KernelStatusCode_InvalidArgument, + "set_tls_certificate_revocation(NULL cfg) -> InvalidArgument"); +} + static void capture_log(const char* level, const char* target, const char* message, void* user_data) { (void)level; @@ -388,6 +407,7 @@ int main(void) { test_http_path_and_m2m_setters(); test_setter_null_arg_rejected(); test_proxy_and_tls_setters(); + test_tls_certificate_revocation_setter(); test_u2m_and_header_setters(); test_identity_federation_client_id_setter(); test_client_conf_setter(); diff --git a/tests/tls_revocation_e2e.rs b/tests/tls_revocation_e2e.rs new file mode 100644 index 00000000..caf31723 --- /dev/null +++ b/tests/tls_revocation_e2e.rs @@ -0,0 +1,76 @@ +// Copyright (c) 2026 Databricks, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Live hook for the revocation policy. Ignored by default. +//! +//! ```sh +//! DATABRICKS_TEST_REVOCATION=strict cargo test --no-default-features \ +//! --features tls-rustls --test tls_revocation_e2e -- --ignored --nocapture +//! ``` +//! +//! `DATABRICKS_TEST_REVOCATION` is `off`, `strict` or `accept_undetermined`. + +mod common; + +use common::env_var; +use databricks_sql_kernel::{AuthConfig, Session, TlsConfig}; + +#[tokio::test] +#[ignore] +async fn select_one_with_revocation_policy_from_env() { + let (check, accept) = match std::env::var("DATABRICKS_TEST_REVOCATION").as_deref() { + Ok("strict") => (Some(true), Some(false)), + Ok("accept_undetermined") => (Some(true), Some(true)), + Ok("off") | Err(_) => (None, None), + Ok(other) => panic!( + "DATABRICKS_TEST_REVOCATION must be off, strict or accept_undetermined; got {other:?}" + ), + }; + // `TlsConfig` is non_exhaustive, so set the fields on a default value. + let mut tls = TlsConfig::default(); + tls.check_certificate_revocation = check; + tls.accept_undetermined_certificate_revocation = accept; + + let session = Session::builder() + .http_path( + env_var("DATABRICKS_HOST").expect("DATABRICKS_HOST required"), + env_var("DATABRICKS_HTTP_PATH").expect("DATABRICKS_HTTP_PATH required"), + ) + .auth(AuthConfig::Pat { + token: env_var("DATABRICKS_TOKEN").expect("DATABRICKS_TOKEN required"), + identity_federation_client_id: None, + }) + .tls(tls) + .open() + .await + .expect("open session with the revocation policy from the environment"); + + let mut statement = session.statement(); + statement.spec().sql("SELECT 1 AS one"); + let mut executed = statement.execute().await.expect("execute SELECT 1"); + let mut rows = 0; + while let Some(batch) = executed + .result_stream_mut() + .next_batch() + .await + .expect("next batch") + { + if let databricks_sql_kernel::ResultBatch::Arrow(batch) = batch { + rows += batch.num_rows(); + } + } + assert_eq!(rows, 1, "SELECT 1 returns one row"); + executed.close().await.expect("close statement"); + session.close().await.expect("close session"); +} From 9063fc6f5163a4239b4d00303f55cb59060a7c94 Mon Sep 17 00:00:00 2001 From: cat23123 <58714163+cat23123@users.noreply.github.com> Date: Thu, 19 Nov 2026 18:51:50 +0000 Subject: [PATCH 02/43] feat(bindings): expose TLS certificate revocation in pyo3 and napi Expose the opt-in revocation policy to the Python and Node bindings. Both default to off, so existing connections are unchanged. - pyo3 Session: tls_check_certificate_revocation and tls_accept_undetermined_revocation (Optional[bool], default None). - napi ConnectionOptions: checkCertificateRevocation and acceptUndeterminedRevocation (boolean, optional). Both map onto TlsConfig.check_certificate_revocation and accept_undetermined_certificate_revocation. The napi index.d.ts is updated. The lockfiles gain the kernel's rustls-native-certs and der edges. Co-authored-by: Isaac Signed-off-by: cat23123 <58714163+cat23123@users.noreply.github.com> --- napi/Cargo.lock | 2 ++ napi/NEXT_CHANGELOG.md | 2 ++ napi/index.d.ts | 14 ++++++++++++++ napi/src/database.rs | 34 ++++++++++++++++++++++++++++++++++ pyo3/Cargo.lock | 2 ++ pyo3/NEXT_CHANGELOG.md | 2 ++ pyo3/src/session.rs | 12 ++++++++++++ pyo3/tests/test_session.py | 13 +++++++++++++ 8 files changed, 81 insertions(+) diff --git a/napi/Cargo.lock b/napi/Cargo.lock index b7eb6a6d..134888ac 100644 --- a/napi/Cargo.lock +++ b/napi/Cargo.lock @@ -619,6 +619,7 @@ dependencies = [ "cbc 0.2.1", "chrono", "dashmap", + "der", "dirs", "futures", "geo-traits", @@ -634,6 +635,7 @@ dependencies = [ "rand 0.10.2", "reqwest", "rustls", + "rustls-native-certs", "rustls-webpki", "serde", "serde_json", diff --git a/napi/NEXT_CHANGELOG.md b/napi/NEXT_CHANGELOG.md index d5ca462e..29b2a7c5 100644 --- a/napi/NEXT_CHANGELOG.md +++ b/napi/NEXT_CHANGELOG.md @@ -14,6 +14,8 @@ layout, or npm publishing. Pure-kernel changes go in the root ### Added +- `ConnectionOptions` accepts `checkCertificateRevocation` and `acceptUndeterminedRevocation` (both default off) to check the server chain's CRLs. Needs the `tls-rustls` kernel build, which this package uses. + ### Changed ### Updated diff --git a/napi/index.d.ts b/napi/index.d.ts index 064f856d..e92eeb90 100644 --- a/napi/index.d.ts +++ b/napi/index.d.ts @@ -490,6 +490,20 @@ export interface ConnectionOptions { * Maps onto the kernel [`TlsConfig::client_key_pem`]. */ clientKeyPem?: Buffer + /** + * Check the server certificate chain's CRLs before connecting. Omitted + * / `false` ⇒ off. Needs a `tls-rustls` kernel build; the kernel rejects + * it at open on `tls-native`. Maps onto + * [`TlsConfig::check_certificate_revocation`]. + */ + checkCertificateRevocation?: boolean + /** + * With `checkCertificateRevocation`, accept a chain whose revocation + * status cannot be determined (no CRL distribution point, unreachable + * CRL). Omitted / `false` ⇒ strict. Maps onto + * [`TlsConfig::accept_undetermined_certificate_revocation`]. + */ + acceptUndeterminedRevocation?: boolean /** * Extra HTTP headers to send on every request — the route for * caller-supplied headers (the NodeJS driver's `customHeaders` and diff --git a/napi/src/database.rs b/napi/src/database.rs index 4a8fbe3f..3b7ecf86 100644 --- a/napi/src/database.rs +++ b/napi/src/database.rs @@ -362,6 +362,16 @@ pub struct ConnectionOptions { /// kernel's TLS backends supply a PKCS#8 key (`BEGIN PRIVATE KEY`). /// Maps onto the kernel [`TlsConfig::client_key_pem`]. pub client_key_pem: Option, + /// Check the server certificate chain's CRLs before connecting. Omitted + /// / `false` ⇒ off. Needs a `tls-rustls` kernel build; the kernel rejects + /// it at open on `tls-native`. Maps onto + /// [`TlsConfig::check_certificate_revocation`]. + pub check_certificate_revocation: Option, + /// With `check_certificate_revocation`, accept a chain whose revocation + /// status cannot be determined (no CRL distribution point, unreachable + /// CRL). Omitted / `false` ⇒ strict. Maps onto + /// [`TlsConfig::accept_undetermined_certificate_revocation`]. + pub accept_undetermined_revocation: Option, /// Extra HTTP headers to send on every request — the route for /// caller-supplied headers (the NodeJS driver's `customHeaders` and /// the composed `User-Agent`). Maps onto the kernel @@ -608,6 +618,9 @@ fn build_tls_config(options: &ConnectionOptions) -> TlsConfig { if let Some(key) = &options.client_key_pem { tls.client_key_pem = Some(key.to_vec()); } + // Revocation is opt-in: unset stays `None` (kernel default off). + tls.check_certificate_revocation = options.check_certificate_revocation; + tls.accept_undetermined_certificate_revocation = options.accept_undetermined_revocation; tls } @@ -929,6 +942,8 @@ mod tests { azure_client_secret: None, azure_tenant_id: None, azure_workspace_resource_id: None, + check_certificate_revocation: None, + accept_undetermined_revocation: None, catalog: None, schema: None, session_conf: None, @@ -1411,6 +1426,25 @@ mod tests { assert_eq!(tls.custom_ca_cert.as_deref(), Some(PEM)); } + #[test] + fn tls_revocation_flags_map_onto_kernel_policy() { + // Unset means off; each flag passes straight through to the kernel. + let cases = [ + (None, None, None, None), + (Some(true), None, Some(true), None), + (Some(true), Some(true), Some(true), Some(true)), + (Some(false), None, Some(false), None), + ]; + for (check, accept, want_check, want_accept) in cases { + let mut o = base(); + o.check_certificate_revocation = check; + o.accept_undetermined_revocation = accept; + let tls = build_tls_config(&o); + assert_eq!(tls.check_certificate_revocation, want_check); + assert_eq!(tls.accept_undetermined_certificate_revocation, want_accept); + } + } + #[test] fn tls_hostname_check_on_by_default_and_when_explicit_true() { for hostname in [None, Some(true)] { diff --git a/pyo3/Cargo.lock b/pyo3/Cargo.lock index c908c554..b8a2c445 100644 --- a/pyo3/Cargo.lock +++ b/pyo3/Cargo.lock @@ -615,6 +615,7 @@ dependencies = [ "cbc 0.2.1", "chrono", "dashmap", + "der", "dirs", "futures", "geo-traits", @@ -630,6 +631,7 @@ dependencies = [ "rand 0.10.2", "reqwest", "rustls", + "rustls-native-certs", "rustls-webpki", "serde", "serde_json", diff --git a/pyo3/NEXT_CHANGELOG.md b/pyo3/NEXT_CHANGELOG.md index e0881e54..33fd2bfb 100644 --- a/pyo3/NEXT_CHANGELOG.md +++ b/pyo3/NEXT_CHANGELOG.md @@ -13,6 +13,8 @@ changes go in the root `NEXT_CHANGELOG.md`. ### Added +- `Session` accepts `tls_check_certificate_revocation` and `tls_accept_undetermined_revocation` (both default off) to check the server chain's CRLs. Needs the `tls-rustls` kernel build, which the wheel uses. + ### Changed ### Updated diff --git a/pyo3/src/session.rs b/pyo3/src/session.rs index c626ee89..a84eb6e5 100644 --- a/pyo3/src/session.rs +++ b/pyo3/src/session.rs @@ -305,6 +305,10 @@ impl Session { /// `tls_skip_hostname_verify` disables the hostname check; /// `tls_client_cert` + `tls_client_key` (both PEM bytes) configure /// mutual TLS. The two mTLS fields must be set together. + /// `tls_check_certificate_revocation=True` checks the chain's CRLs + /// (`tls-rustls` builds only); `tls_accept_undetermined_revocation=True` + /// accepts a chain whose revocation status cannot be determined. + /// Both default to off. /// /// Retry/backoff: all optional, default to the kernel's built-in /// policy (1s/60s backoff, 6 total attempts, 900s budget) when @@ -375,6 +379,8 @@ impl Session { tls_skip_hostname_verify=false, tls_client_cert=None, tls_client_key=None, + tls_check_certificate_revocation=None, + tls_accept_undetermined_revocation=None, sea_response_compression_enabled=false, request_timeout_secs=None, max_connections=None, @@ -442,6 +448,8 @@ impl Session { tls_skip_hostname_verify: bool, tls_client_cert: Option>, tls_client_key: Option>, + tls_check_certificate_revocation: Option, + tls_accept_undetermined_revocation: Option, sea_response_compression_enabled: bool, request_timeout_secs: Option, max_connections: Option, @@ -531,6 +539,8 @@ impl Session { || tls_skip_hostname_verify || tls_client_cert.is_some() || tls_client_key.is_some() + || tls_check_certificate_revocation.is_some() + || tls_accept_undetermined_revocation.is_some() { let mut tls = databricks_sql_kernel::TlsConfig::default(); tls.custom_ca_cert = tls_ca_cert; @@ -538,6 +548,8 @@ impl Session { tls.skip_hostname_verification = tls_skip_hostname_verify; tls.client_cert_pem = tls_client_cert; tls.client_key_pem = tls_client_key; + tls.check_certificate_revocation = tls_check_certificate_revocation; + tls.accept_undetermined_certificate_revocation = tls_accept_undetermined_revocation; Some(tls) } else { None diff --git a/pyo3/tests/test_session.py b/pyo3/tests/test_session.py index 4d27fdee..49045867 100644 --- a/pyo3/tests/test_session.py +++ b/pyo3/tests/test_session.py @@ -17,11 +17,24 @@ from __future__ import annotations +import inspect + import databricks_sql_kernel as k from conftest import live +def test_revocation_kwargs_are_keyword_only_and_default_off(): + # Offline: checks the constructor contract. Unset (None) means off. + params = inspect.signature(k.Session).parameters + for name in ( + "tls_check_certificate_revocation", + "tls_accept_undetermined_revocation", + ): + assert params[name].kind is inspect.Parameter.KEYWORD_ONLY, name + assert params[name].default is None, name + + @live def test_session_id_non_empty(session): assert session.session_id, f"session_id should be populated: {session.session_id!r}" From ba7eec2e9ccbabf71417ea54ab2187d83771a479 Mon Sep 17 00:00:00 2001 From: cat23123 <58714163+cat23123@users.noreply.github.com> Date: Thu, 19 Nov 2026 19:14:51 +0000 Subject: [PATCH 03/43] fix(tls): address review findings in certificate revocation Verifier: - Only certificates on a path webpki verifies are checked. The presented intermediates are tried smallest subset first, so a certificate the server appends that no path needs is never fetched. More than six presented intermediates is rejected. - A certificate is a trust anchor only when its subject and SPKI match a configured root, not when its issuer and subject names match. - One deadline bounds all CRL fetches for a chain, at the per-fetch timeout. - CRL fetches trust the connection's custom CA roots, as the connection does. - Fetch failures are logged at debug level with the URL (userinfo removed) and the reason. Configuration: - The internal TlsConfig is #[non_exhaustive], like the public one, so the pub(crate) CRL limits field no longer affects external struct construction. - On tls-native, a revocation request with accept_self_signed is accepted, since self-signed acceptance turns revocation off. The Debug output includes the revocation fields. Tests: an unrelated appended certificate is never fetched; a same-name certificate with another key is not a trust anchor; one timeout budget bounds all fetches for a chain. Co-authored-by: Isaac Signed-off-by: cat23123 <58714163+cat23123@users.noreply.github.com> --- src/client/http.rs | 15 ++- src/client/tls_revocation.rs | 177 ++++++++++++++++++++++++----- src/client/tls_revocation_tests.rs | 112 +++++++++++++++++- 3 files changed, 272 insertions(+), 32 deletions(-) diff --git a/src/client/http.rs b/src/client/http.rs index e95d92cf..04967f79 100644 --- a/src/client/http.rs +++ b/src/client/http.rs @@ -146,6 +146,7 @@ impl std::fmt::Debug for ProxyConfig { /// Relaxing any of these options should only be done in development/testing /// environments. #[derive(Clone, Default)] +#[non_exhaustive] pub struct TlsConfig { /// Enable TLS for connections. When `false`, allows plain HTTP. /// Default: true (TLS enabled). @@ -227,8 +228,12 @@ impl Default for CrlFetchLimits { /// Rejects a revocation request the backend cannot honour. Shared by session /// open (which must report `InvalidArgument` unwrapped) and the HTTP client. +/// `allow_self_signed` turns revocation off, so it is not an error. pub(crate) fn check_revocation_support(tls: &TlsConfig) -> Result<()> { - if cfg!(feature = "tls-rustls") || tls.check_certificate_revocation != Some(true) { + if cfg!(feature = "tls-rustls") + || tls.check_certificate_revocation != Some(true) + || tls.allow_self_signed == Some(true) + { return Ok(()); } Err(Error::invalid_argument() @@ -279,6 +284,14 @@ impl std::fmt::Debug for TlsConfig { "client_key_pem", &self.client_key_pem.as_ref().map(|_| ""), ) + .field( + "check_certificate_revocation", + &self.check_certificate_revocation, + ) + .field( + "accept_undetermined_certificate_revocation", + &self.accept_undetermined_certificate_revocation, + ) .finish() } } diff --git a/src/client/tls_revocation.rs b/src/client/tls_revocation.rs index 7f1cf9b3..56fe18c9 100644 --- a/src/client/tls_revocation.rs +++ b/src/client/tls_revocation.rs @@ -22,6 +22,7 @@ use std::collections::HashMap; use std::sync::{Arc, Mutex, PoisonError}; +use std::time::{Duration, Instant}; use der::asn1::{AnyRef, GeneralizedTime, UtcTime}; use der::{Decode, Reader, SliceReader, Tagged}; @@ -40,6 +41,7 @@ use rustls::{ use super::http::{CrlFetchLimits, ProxyConfig, TlsConfig}; use crate::kernel_error::{Error, Result}; +use crate::klog::debug; const TAG_INTEGER: u8 = 0x02; const TAG_UTC_TIME: u8 = 0x17; @@ -79,7 +81,8 @@ fn sequence(der: &[u8]) -> Option> { /// The fields of a certificate that the revocation check needs. struct Cert<'a> { issuer: &'a [u8], - self_issued: bool, + subject: &'a [u8], + spki: &'a [u8], crl_uris: Vec, } @@ -90,6 +93,7 @@ fn parse_cert(der: &[u8]) -> Option> { let base = usize::from(fields.first()?.0 == TAG_CONTEXT_0); let issuer = fields.get(base + 2)?.1; let subject = fields.get(base + 4)?.1; + let spki = fields.get(base + 5)?.1; let mut crl_uris = Vec::new(); if let Some(&(_, extensions)) = fields.iter().find(|f| f.0 == TAG_CONTEXT_3) { for (_, extension) in sequence(extensions)? { @@ -101,11 +105,22 @@ fn parse_cert(der: &[u8]) -> Option> { } Some(Cert { issuer, - self_issued: issuer == subject, + subject, + spki, crl_uris, }) } +/// Whether `cert` is one of the configured trust anchors. Matching is by subject +/// and SPKI, as webpki matches anchors, so a same-name certificate with a different +/// key is not an anchor. +fn is_trust_anchor(roots: &RootCertStore, cert: &Cert<'_>) -> bool { + roots.roots.iter().any(|anchor| { + anchor.subject.as_ref() == cert.subject + && anchor.subject_public_key_info.as_ref() == cert.spki + }) +} + /// The http(s) URIs of a CRLDistributionPoints value. Indirect points are skipped. fn distribution_points(value: &[u8]) -> Option> { let mut uris = Vec::new(); @@ -206,6 +221,8 @@ type CachedCrl = (Arc>, u64); struct CrlFetcher { proxy: ProxyConfig, limits: CrlFetchLimits, + /// The connection's custom CA roots, so an HTTPS CRL endpoint behind that CA verifies. + custom_roots: Vec, /// URL to (CRL bytes, nextUpdate in Unix seconds). cache: Mutex>, } @@ -213,7 +230,7 @@ struct CrlFetcher { impl CrlFetcher { /// The CRL at `url`, from cache while current, otherwise freshly fetched. /// `None` means the fetch failed. Only a CRL with a future `nextUpdate` is cached. - fn get(&self, url: &str, now: u64) -> Option>> { + fn get(&self, url: &str, now: u64, budget: Duration) -> Option>> { let cached = self .cache .lock() @@ -225,11 +242,25 @@ impl CrlFetcher { return cached; } self.evict(url); - let der = Arc::new(fetch_blocking( + if budget.is_zero() { + return None; + } + let limits = CrlFetchLimits { + timeout: budget, + ..self.limits + }; + let der = match fetch_blocking( self.proxy.clone(), - self.limits, + limits, + self.custom_roots.clone(), url.to_owned(), - )?); + ) { + Ok(der) => Arc::new(der), + Err(reason) => { + debug!("CRL fetch failed for {}: {reason}", redacted(url)); + return None; + } + }; if let Some(next) = parse_crl(&der) .and_then(|crl| crl.next_update) .filter(|next| now <= *next) @@ -252,28 +283,41 @@ impl CrlFetcher { /// Runs one fetch on its own thread and runtime. The caller's runtime is never /// re-entered, so a current-thread caller cannot deadlock. -fn fetch_blocking(proxy: ProxyConfig, limits: CrlFetchLimits, url: String) -> Option> { +fn fetch_blocking( + proxy: ProxyConfig, + limits: CrlFetchLimits, + roots: Vec, + url: String, +) -> std::result::Result, String> { std::thread::spawn(move || { tokio::runtime::Builder::new_current_thread() .enable_all() .build() - .ok()? - .block_on(fetch(&proxy, &url, limits)) + .map_err(|e| e.to_string())? + .block_on(fetch(&proxy, &url, limits, &roots)) }) .join() - .ok() - .flatten() + .unwrap_or_else(|_| Err("CRL fetch thread panicked".to_owned())) } /// One CRL download. It carries no auth or custom headers, goes through the -/// connection's proxy, and is bounded by time, size and redirects. -async fn fetch(proxy: &ProxyConfig, url: &str, limits: CrlFetchLimits) -> Option> { +/// connection's proxy, trusts the connection's custom CA roots, and is bounded by +/// time, size and redirects. +async fn fetch( + proxy: &ProxyConfig, + url: &str, + limits: CrlFetchLimits, + roots: &[reqwest::Certificate], +) -> std::result::Result, String> { let mut builder = reqwest::Client::builder() .connect_timeout(limits.timeout) .timeout(limits.timeout) .redirect(reqwest::redirect::Policy::limited(CRL_MAX_REDIRECTS)); + for root in roots { + builder = builder.add_root_certificate(root.clone()); + } if let Some(proxy_url) = &proxy.url { - let mut via = reqwest::Proxy::all(proxy_url).ok()?; + let mut via = reqwest::Proxy::all(proxy_url).map_err(|e| e.to_string())?; if let Some(username) = &proxy.username { via = via.basic_auth(username, proxy.password.as_deref().unwrap_or("")); } @@ -287,22 +331,45 @@ async fn fetch(proxy: &ProxyConfig, url: &str, limits: CrlFetchLimits) -> Option } builder = builder.proxy(via); } - let mut response = builder.build().ok()?.get(url).send().await.ok()?; - if response.status() != StatusCode::OK - || response - .content_length() - .is_some_and(|len| len > limits.max_bytes as u64) + let client = builder.build().map_err(|e| e.to_string())?; + let mut response = client + .get(url) + .send() + .await + .map_err(|e| e.without_url().to_string())?; + if response.status() != StatusCode::OK { + return Err(format!("HTTP {}", response.status())); + } + if response + .content_length() + .is_some_and(|len| len > limits.max_bytes as u64) { - return None; + return Err("CRL larger than the size limit".to_owned()); } let mut body = Vec::new(); - while let Some(chunk) = response.chunk().await.ok()? { + while let Some(chunk) = response + .chunk() + .await + .map_err(|e| e.without_url().to_string())? + { if body.len() + chunk.len() > limits.max_bytes { - return None; + return Err("CRL larger than the size limit".to_owned()); } body.extend_from_slice(&chunk); } - Some(body) + Ok(body) +} + +/// The URL with any userinfo removed, for logging. +fn redacted(url: &str) -> String { + match reqwest::Url::parse(url) { + Ok(mut parsed) => { + let _ = parsed.set_username(""); + let _ = parsed.set_password(None); + parsed.to_string() + } + Err(_) => "".to_owned(), + } } /// The server verifier: webpki for the chain, signatures and name, with CRLs. @@ -333,6 +400,54 @@ impl RevocationVerifier { } } +impl RevocationVerifier { + /// The indices of the presented intermediates on a path that webpki verifies. Subsets + /// are tried smallest first, and the first one that verifies is the path. An intermediate + /// the server adds that the path does not need is never returned, so its distribution + /// points are never fetched. More than six presented intermediates is rejected. + fn path_intermediates( + &self, + end_entity: &CertificateDer<'_>, + intermediates: &[CertificateDer<'_>], + server_name: &ServerName<'_>, + ocsp_response: &[u8], + now: UnixTime, + ) -> std::result::Result, rustls::Error> { + const MAX_PRESENTED: usize = 6; + let n = intermediates.len(); + if n > MAX_PRESENTED { + return Err(rustls::Error::InvalidCertificate( + CertificateError::UnknownIssuer, + )); + } + for size in 0..=n { + for mask in 0_usize..(1 << n) { + if mask.count_ones() as usize != size { + continue; + } + let picked: Vec = (0..n).filter(|i| mask & (1 << i) != 0).collect(); + let subset: Vec> = + picked.iter().map(|&i| intermediates[i].clone()).collect(); + if self + .tolerate_name(self.signatures.verify_server_cert( + end_entity, + &subset, + server_name, + ocsp_response, + now, + )) + .is_ok() + { + return Ok(picked); + } + } + } + Err(rustls::Error::InvalidCertificate( + CertificateError::UnknownIssuer, + )) + } +} + impl ServerCertVerifier for RevocationVerifier { fn verify_server_cert( &self, @@ -351,21 +466,27 @@ impl ServerCertVerifier for RevocationVerifier { ))?; let now_secs = now.as_secs(); + let path = + self.path_intermediates(end_entity, intermediates, server_name, ocsp_response, now)?; + // One deadline bounds every fetch for this chain, so the total wait is at + // most one per-fetch timeout however many distribution points there are. + let deadline = Instant::now() + self.fetcher.limits.timeout; let mut crls = Vec::new(); let mut used_urls = Vec::new(); let mut undetermined = false; - for cert in std::iter::once(end_entity).chain(intermediates) { + for cert in std::iter::once(end_entity).chain(path.iter().map(|&i| &intermediates[i])) { let Some(parsed) = parse_cert(cert.as_ref()) else { undetermined = true; continue; }; // Trust anchors are not revocation-checked (webpki does not check them either). - if parsed.self_issued { + if is_trust_anchor(&self.roots, &parsed) { continue; } let mut covered = false; for url in &parsed.crl_uris { - let Some(der) = self.fetcher.get(url, now_secs) else { + let budget = deadline.saturating_duration_since(Instant::now()); + let Some(der) = self.fetcher.get(url, now_secs, budget) else { continue; }; match classify(&der, parsed.issuer, now_secs) { @@ -492,10 +613,13 @@ pub(crate) fn client_config( if let Some(pem) = &tls.trusted_certificate_pem { pems.push(pem.clone()); } + // The same custom CAs, as reqwest certificates, for the CRL client. + let mut custom_roots = Vec::new(); for pem in pems { for cert in CertificateDer::pem_slice_iter(&pem) { roots.add(cert.map_err(tls_error)?).map_err(tls_error)?; } + custom_roots.extend(reqwest::Certificate::from_pem_bundle(&pem).map_err(tls_error)?); } let roots = Arc::new(roots); @@ -510,6 +634,7 @@ pub(crate) fn client_config( fetcher: CrlFetcher { proxy: proxy.clone(), limits: tls.crl_fetch_limits, + custom_roots, cache: Mutex::new(HashMap::new()), }, accept_undetermined, diff --git a/src/client/tls_revocation_tests.rs b/src/client/tls_revocation_tests.rs index 3fba6755..c1ec17fa 100644 --- a/src/client/tls_revocation_tests.rs +++ b/src/client/tls_revocation_tests.rs @@ -29,7 +29,7 @@ use std::io::{Read, Write}; use std::net::{Shutdown, SocketAddr, TcpListener, TcpStream}; use std::sync::{Arc, Mutex}; use std::thread; -use std::time::Duration; +use std::time::{Duration, Instant}; /// Lower-cased fragment of rustls's `UnknownRevocationStatus` error text. const UNDETERMINED: &str = "unknownrevocationstatus"; @@ -466,15 +466,26 @@ fn fixture(leaf: Option, intermediate: Served, san: &str) -> Fixture { /// A TLS server presenting the leaf chain. With `mtls`, it requires a client /// certificate that chains to the test root. fn spawn_tls_server(pki: &Pki, mtls: bool) -> SocketAddr { + let chain = vec![pki.leaf_der.clone(), pki.intermediate_der.clone()]; + let mtls_root = mtls.then(|| pki.root_der.clone()); + spawn_tls_chain(chain, pki.leaf_key_der.clone(), mtls_root) +} + +/// A TLS server presenting `chain`, with the leaf key `key_der`. With `mtls_root`, it +/// requires a client certificate that chains to that root. +fn spawn_tls_chain( + chain: Vec>, + key_der: Vec, + mtls_root: Option>, +) -> SocketAddr { let provider = Arc::new(rustls::crypto::ring::default_provider()); let builder = rustls::ServerConfig::builder_with_provider(provider) .with_safe_default_protocol_versions() .unwrap(); - let chain = vec![pki.leaf_der.clone(), pki.intermediate_der.clone()]; - let key = PrivatePkcs8KeyDer::from(pki.leaf_key_der.clone()).into(); - let config = if mtls { + let key = PrivatePkcs8KeyDer::from(key_der).into(); + let config = if let Some(root) = mtls_root { let mut roots = rustls::RootCertStore::empty(); - roots.add(pki.root_der.clone()).unwrap(); + roots.add(root).unwrap(); let verifier = rustls::server::WebPkiClientVerifier::builder(Arc::new(roots)) .build() .unwrap(); @@ -923,3 +934,94 @@ async fn policy_off_and_accept_self_signed_skip_revocation() { "no CRL is fetched when revocation is off" ); } + +#[tokio::test] +async fn unrelated_appended_certificate_is_never_fetched() { + // The server appends a certificate that no path needs, with its own distribution point. + let fx = fixture(Some(Served::Good), Served::Good, "127.0.0.1"); + let other_issuer = Issuer::new( + ca_params("Unrelated Test CA", 9), + KeyPair::generate().unwrap(), + ); + let other_key = KeyPair::generate().unwrap(); + let mut params = CertificateParams::new(vec!["unrelated.invalid".to_owned()]).unwrap(); + params.crl_distribution_points = vec![CrlDistributionPoint { + uris: vec![fx.crl.url("/unrelated.crl")], + }]; + let unrelated = params + .signed_by(&other_key, &other_issuer) + .unwrap() + .der() + .clone(); + fx.crl.set( + "/unrelated.crl", + route( + Served::Good, + &other_issuer, + "Unrelated Test CA", + 9, + &other_issuer, + ), + ); + let chain = vec![ + fx.pki.leaf_der.clone(), + fx.pki.intermediate_der.clone(), + unrelated, + ]; + let addr = spawn_tls_chain(chain, fx.pki.leaf_key_der.clone(), None); + get(revocation_config(&fx.pki.root_pem, false), addr) + .await + .expect("the good path verifies; the appended certificate is not on it"); + assert_eq!( + fx.crl.hits("/unrelated.crl"), + 0, + "an unneeded certificate's distribution point is never fetched" + ); +} + +#[test] +fn same_name_certificate_with_another_key_is_not_a_trust_anchor() { + // Anchors match by subject and SPKI, as webpki matches them. The root's name with + // another key is not an anchor, so its distribution points are still checked. + let root_key = KeyPair::generate().unwrap(); + let root_der = ca_params(ROOT_CN, 1) + .self_signed(&root_key) + .unwrap() + .der() + .clone(); + let mut roots = RootCertStore::empty(); + roots.add(root_der.clone()).unwrap(); + let other_key = KeyPair::generate().unwrap(); + let same_name_der = ca_params(ROOT_CN, 2) + .self_signed(&other_key) + .unwrap() + .der() + .clone(); + let anchor = parse_cert(root_der.as_ref()).unwrap(); + let same_name = parse_cert(same_name_der.as_ref()).unwrap(); + assert!( + is_trust_anchor(&roots, &anchor), + "the anchor matches itself" + ); + assert!( + !is_trust_anchor(&roots, &same_name), + "a same-name certificate with another key is not an anchor" + ); +} + +#[tokio::test] +async fn one_timeout_budget_bounds_all_fetches_for_a_chain() { + // Both distribution points hang past the per-fetch timeout. The chain shares one + // budget, so the second fetch gets none and the check ends in about one timeout. + let fx = fixture(Some(Served::Timeout), Served::Timeout, "127.0.0.1"); + let started = Instant::now(); + let err = get(revocation_config(&fx.pki.root_pem, false), fx.addr) + .await + .expect_err("undetermined under strict"); + let elapsed = started.elapsed(); + assert!(err.contains(UNDETERMINED), "{err}"); + assert!( + elapsed < Duration::from_millis(900), + "the fetches share one budget, but the check took {elapsed:?}" + ); +} From cfc647914885f3199d92ec7efd58edc50c1d302e Mon Sep 17 00:00:00 2001 From: cat23123 <58714163+cat23123@users.noreply.github.com> Date: Thu, 19 Nov 2026 20:33:59 +0000 Subject: [PATCH 04/43] fix(tls): address second review round for certificate revocation Verifier: - The final webpki verification sees only the checked path, not every presented intermediate, so webpki cannot build a path through a certificate whose CRLs were not checked. Regression test: final_verify_uses_only_the_checked_path. - One CRL client per chain verification. A worker thread with one current-thread runtime and one reqwest client serves that chain's fetches, and it is joined when the verification ends. Previously each fetch built its own client and runtime. - Joins and per-fetch waits run under block_in_place on a multi-thread runtime, so the worker's other tasks move to another thread. On current_thread the wait is unchanged, since block_in_place would panic there. - More than six presented intermediates is a clear error that names the limit. - Logged URLs drop the query and fragment as well as the userinfo. - The timing test bounds the budget between one and two timeouts, with slack on each side. Configuration: - http::TlsConfig is back to its base shape: #[non_exhaustive] is removed, and the pub(crate) CRL-limits field is replaced by a test-only per-thread override. Both changes keep external code that uses ..Default::default() compiling. Python: - The signature test is skipped below Python 3.10, where inspect.signature cannot read a pyo3 class's signature. Docs: - docs/designs/tls-config-design.md describes the opt-in revocation. The ADBC revocation_mode mapping is out of scope. Co-authored-by: Isaac Signed-off-by: cat23123 <58714163+cat23123@users.noreply.github.com> --- docs/designs/tls-config-design.md | 4 +- pyo3/tests/test_session.py | 7 ++ src/client/http.rs | 6 - src/client/tls_revocation.rs | 191 ++++++++++++++++++++++------- src/client/tls_revocation_tests.rs | 103 +++++++++++++++- 5 files changed, 253 insertions(+), 58 deletions(-) diff --git a/docs/designs/tls-config-design.md b/docs/designs/tls-config-design.md index 1fc856f4..8a3dd63a 100644 --- a/docs/designs/tls-config-design.md +++ b/docs/designs/tls-config-design.md @@ -245,7 +245,7 @@ E2E tests use mitmproxy as a TLS-intercepting proxy. The CI workflow (`.github/w | Self-signed certs / skip cert validation | `databricks.http.tls.allow_self_signed` | `adbc.http_options.tls.allow_self_signed` + `adbc.http_options.tls.disable_server_certificate_validation` | | Hostname mismatch | `databricks.http.tls.allow_hostname_mismatch` | `adbc.http_options.tls.allow_hostname_mismatch` | | Custom CA cert | `databricks.http.tls.trusted_certificate_path` | `adbc.http_options.tls.trusted_certificate_path` | -| Cert revocation mode | Not supported | `adbc.http_options.tls.revocation_mode` | +| Cert revocation mode | Opt-in on tls-rustls: `check_certificate_revocation`, `accept_undetermined_certificate_revocation` (default off; InvalidArgument on tls-native) | `adbc.http_options.tls.revocation_mode` (ADBC mapping out of scope) | ### Naming Convention Difference @@ -253,7 +253,7 @@ The Rust driver uses `databricks.http.tls.*` while the C# driver uses `adbc.http ### Scope Exclusions -- **Certificate revocation mode**: reqwest does not expose CRL/OCSP configuration. The C# driver supports this via `adbc.http_options.tls.revocation_mode` because .NET's `HttpClientHandler` natively supports it. Can be revisited if reqwest adds support. +- **Certificate revocation mode**: implemented in the kernel's tls-rustls verifier (CRL checks, opt-in, default off), not through reqwest. The ADBC `adbc.http_options.tls.revocation_mode` mapping is out of scope by the user's decision, so the ADBC driver gets no mapping. - **Client certificates (mTLS)**: Not needed per current requirements. Could be added later via `reqwest::ClientBuilder::identity()`. - **TLS version pinning**: Not needed. reqwest/native-tls negotiate the highest supported version automatically. diff --git a/pyo3/tests/test_session.py b/pyo3/tests/test_session.py index 49045867..f3bdc893 100644 --- a/pyo3/tests/test_session.py +++ b/pyo3/tests/test_session.py @@ -18,12 +18,19 @@ from __future__ import annotations import inspect +import sys + +import pytest import databricks_sql_kernel as k from conftest import live +@pytest.mark.skipif( + sys.version_info < (3, 10), + reason="inspect.signature cannot read a pyo3 class's signature before Python 3.10", +) def test_revocation_kwargs_are_keyword_only_and_default_off(): # Offline: checks the constructor contract. Unset (None) means off. params = inspect.signature(k.Session).parameters diff --git a/src/client/http.rs b/src/client/http.rs index 04967f79..41f953b0 100644 --- a/src/client/http.rs +++ b/src/client/http.rs @@ -146,7 +146,6 @@ impl std::fmt::Debug for ProxyConfig { /// Relaxing any of these options should only be done in development/testing /// environments. #[derive(Clone, Default)] -#[non_exhaustive] pub struct TlsConfig { /// Enable TLS for connections. When `false`, allows plain HTTP. /// Default: true (TLS enabled). @@ -203,9 +202,6 @@ pub struct TlsConfig { pub check_certificate_revocation: Option, /// With revocation checking on, accept an undetermined status. pub accept_undetermined_certificate_revocation: Option, - /// Bounds on each CRL fetch. Production defaults. - #[cfg(feature = "tls-rustls")] - pub(crate) crl_fetch_limits: CrlFetchLimits, } /// Bounds applied to each CRL HTTP fetch. @@ -323,8 +319,6 @@ impl TlsConfig { check_certificate_revocation: cfg.check_certificate_revocation, accept_undetermined_certificate_revocation: cfg .accept_undetermined_certificate_revocation, - #[cfg(feature = "tls-rustls")] - crl_fetch_limits: CrlFetchLimits::default(), } } } diff --git a/src/client/tls_revocation.rs b/src/client/tls_revocation.rs index 56fe18c9..5e0c9d59 100644 --- a/src/client/tls_revocation.rs +++ b/src/client/tls_revocation.rs @@ -59,6 +59,23 @@ const TAG_URI: u8 = 0x86; const OID_CRL_DISTRIBUTION_POINTS: &[u8] = &[0x55, 0x1D, 0x1F]; const CRL_MAX_REDIRECTS: usize = 3; +// Tests set a per-thread fetch bound here. The client is built on the calling thread, so +// the bound in effect at construction is the one the fetcher keeps. +#[cfg(test)] +thread_local! { + pub(crate) static TEST_CRL_LIMITS: std::cell::Cell> = + const { std::cell::Cell::new(None) }; +} + +/// The CRL fetch bounds: production defaults, or a test override on this thread. +fn crl_fetch_limits() -> CrlFetchLimits { + #[cfg(test)] + if let Some(limits) = TEST_CRL_LIMITS.with(std::cell::Cell::get) { + return limits; + } + CrlFetchLimits::default() +} + /// The (tag, content) pairs of the consecutive TLVs in `der`. fn tlvs(der: &[u8]) -> Option> { let mut reader = SliceReader::new(der).ok()?; @@ -230,7 +247,13 @@ struct CrlFetcher { impl CrlFetcher { /// The CRL at `url`, from cache while current, otherwise freshly fetched. /// `None` means the fetch failed. Only a CRL with a future `nextUpdate` is cached. - fn get(&self, url: &str, now: u64, budget: Duration) -> Option>> { + fn get( + &self, + url: &str, + now: u64, + budget: Duration, + worker: &mut Option, + ) -> Option>> { let cached = self .cache .lock() @@ -245,16 +268,10 @@ impl CrlFetcher { if budget.is_zero() { return None; } - let limits = CrlFetchLimits { - timeout: budget, - ..self.limits - }; - let der = match fetch_blocking( - self.proxy.clone(), - limits, - self.custom_roots.clone(), - url.to_owned(), - ) { + let worker = worker.get_or_insert_with(|| { + CrlWorker::start(self.proxy.clone(), self.limits, self.custom_roots.clone()) + }); + let der = match worker.fetch(url, budget) { Ok(der) => Arc::new(der), Err(reason) => { debug!("CRL fetch failed for {}: {reason}", redacted(url)); @@ -281,34 +298,93 @@ impl CrlFetcher { } } -/// Runs one fetch on its own thread and runtime. The caller's runtime is never -/// re-entered, so a current-thread caller cannot deadlock. -fn fetch_blocking( - proxy: ProxyConfig, - limits: CrlFetchLimits, - roots: Vec, - url: String, -) -> std::result::Result, String> { - std::thread::spawn(move || { - tokio::runtime::Builder::new_current_thread() - .enable_all() - .build() - .map_err(|e| e.to_string())? - .block_on(fetch(&proxy, &url, limits, &roots)) - }) - .join() - .unwrap_or_else(|_| Err("CRL fetch thread panicked".to_owned())) +/// A fetch to run: the URL, the time it may take, and where the answer goes. +type CrlRequest = ( + String, + Duration, + std::sync::mpsc::Sender, String>>, +); + +/// The CRL client for one chain verification: one thread, one current-thread runtime and +/// one reqwest client, shared by that chain's fetches. Dropping it ends the thread. +struct CrlWorker { + requests: Option>, + thread: Option>, } -/// One CRL download. It carries no auth or custom headers, goes through the -/// connection's proxy, trusts the connection's custom CA roots, and is bounded by -/// time, size and redirects. -async fn fetch( +impl CrlWorker { + fn start(proxy: ProxyConfig, limits: CrlFetchLimits, roots: Vec) -> Self { + let (requests, inbox) = std::sync::mpsc::channel::(); + let thread = std::thread::spawn(move || { + // The caller's runtime is never re-entered, so a current-thread caller cannot + // deadlock. + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build(); + let client = build_client(&proxy, limits, &roots); + for (url, budget, answer) in inbox { + let result = match (&runtime, &client) { + (Ok(runtime), Ok(client)) => { + runtime.block_on(fetch(client, &url, limits.max_bytes, budget)) + } + (Err(e), _) => Err(e.to_string()), + (_, Err(e)) => Err(e.clone()), + }; + let _ = answer.send(result); + } + }); + Self { + requests: Some(requests), + thread: Some(thread), + } + } + + /// Runs one fetch on the worker and waits for its answer. The wait is bounded by + /// `budget`, because the fetch itself is. + fn fetch(&self, url: &str, budget: Duration) -> std::result::Result, String> { + let (answer, received) = std::sync::mpsc::channel(); + let sent = self + .requests + .as_ref() + .is_some_and(|requests| requests.send((url.to_owned(), budget, answer)).is_ok()); + if !sent { + return Err("CRL worker is not running".to_owned()); + } + in_runtime_blocking(|| received.recv()) + .unwrap_or_else(|_| Err("CRL worker stopped".to_owned())) + } +} + +impl Drop for CrlWorker { + fn drop(&mut self) { + // Closing the request channel ends the worker once its queue is empty. + self.requests.take(); + if let Some(thread) = self.thread.take() { + let _ = in_runtime_blocking(|| thread.join()); + } + } +} + +/// Runs a blocking wait. On a multi-thread runtime, block_in_place moves the worker's +/// other tasks to another thread first. It panics on current_thread, so the wait runs as +/// it is there. +fn in_runtime_blocking(wait: impl FnOnce() -> T) -> T { + match tokio::runtime::Handle::try_current() { + Ok(current) if current.runtime_flavor() == tokio::runtime::RuntimeFlavor::MultiThread => { + tokio::task::block_in_place(wait) + } + _ => wait(), + } +} + +/// The client for a chain's CRL fetches. It carries no auth or custom headers, goes +/// through the connection's proxy, trusts the connection's custom CA roots, and is bounded +/// by time and redirects. +fn build_client( proxy: &ProxyConfig, - url: &str, limits: CrlFetchLimits, roots: &[reqwest::Certificate], -) -> std::result::Result, String> { +) -> std::result::Result { let mut builder = reqwest::Client::builder() .connect_timeout(limits.timeout) .timeout(limits.timeout) @@ -331,7 +407,26 @@ async fn fetch( } builder = builder.proxy(via); } - let client = builder.build().map_err(|e| e.to_string())?; + builder.build().map_err(|e| e.to_string()) +} + +/// One CRL download with `client`, bounded by `budget` and by the size limit. +async fn fetch( + client: &reqwest::Client, + url: &str, + max_bytes: usize, + budget: Duration, +) -> std::result::Result, String> { + tokio::time::timeout(budget, download(client, url, max_bytes)) + .await + .unwrap_or_else(|_| Err("CRL fetch timed out".to_owned())) +} + +async fn download( + client: &reqwest::Client, + url: &str, + max_bytes: usize, +) -> std::result::Result, String> { let mut response = client .get(url) .send() @@ -342,7 +437,7 @@ async fn fetch( } if response .content_length() - .is_some_and(|len| len > limits.max_bytes as u64) + .is_some_and(|len| len > max_bytes as u64) { return Err("CRL larger than the size limit".to_owned()); } @@ -352,7 +447,7 @@ async fn fetch( .await .map_err(|e| e.without_url().to_string())? { - if body.len() + chunk.len() > limits.max_bytes { + if body.len() + chunk.len() > max_bytes { return Err("CRL larger than the size limit".to_owned()); } body.extend_from_slice(&chunk); @@ -360,12 +455,14 @@ async fn fetch( Ok(body) } -/// The URL with any userinfo removed, for logging. +/// The URL without userinfo, query or fragment, for logging. fn redacted(url: &str) -> String { match reqwest::Url::parse(url) { Ok(mut parsed) => { let _ = parsed.set_username(""); let _ = parsed.set_password(None); + parsed.set_query(None); + parsed.set_fragment(None); parsed.to_string() } Err(_) => "".to_owned(), @@ -416,9 +513,9 @@ impl RevocationVerifier { const MAX_PRESENTED: usize = 6; let n = intermediates.len(); if n > MAX_PRESENTED { - return Err(rustls::Error::InvalidCertificate( - CertificateError::UnknownIssuer, - )); + return Err(rustls::Error::General(format!( + "the server presented {n} intermediates; revocation checking supports at most {MAX_PRESENTED}" + ))); } for size in 0..=n { for mask in 0_usize..(1 << n) { @@ -471,6 +568,8 @@ impl ServerCertVerifier for RevocationVerifier { // One deadline bounds every fetch for this chain, so the total wait is at // most one per-fetch timeout however many distribution points there are. let deadline = Instant::now() + self.fetcher.limits.timeout; + // One CRL client for this chain, started on the first fetch that needs it. + let mut worker = None; let mut crls = Vec::new(); let mut used_urls = Vec::new(); let mut undetermined = false; @@ -486,7 +585,7 @@ impl ServerCertVerifier for RevocationVerifier { let mut covered = false; for url in &parsed.crl_uris { let budget = deadline.saturating_duration_since(Instant::now()); - let Some(der) = self.fetcher.get(url, now_secs, budget) else { + let Some(der) = self.fetcher.get(url, now_secs, budget, &mut worker) else { continue; }; match classify(&der, parsed.issuer, now_secs) { @@ -523,9 +622,13 @@ impl ServerCertVerifier for RevocationVerifier { let verifier = builder .build() .map_err(|e| rustls::Error::General(format!("revocation verifier setup: {e}")))?; + // The final verification sees only the checked path. Webpki then cannot build a + // path through a presented intermediate whose CRLs were not checked. + let checked: Vec> = + path.iter().map(|&i| intermediates[i].clone()).collect(); let result = self.tolerate_name(verifier.verify_server_cert( end_entity, - intermediates, + &checked, server_name, ocsp_response, now, @@ -633,7 +736,7 @@ pub(crate) fn client_config( signatures, fetcher: CrlFetcher { proxy: proxy.clone(), - limits: tls.crl_fetch_limits, + limits: crl_fetch_limits(), custom_roots, cache: Mutex::new(HashMap::new()), }, diff --git a/src/client/tls_revocation_tests.rs b/src/client/tls_revocation_tests.rs index c1ec17fa..4d808e08 100644 --- a/src/client/tls_revocation_tests.rs +++ b/src/client/tls_revocation_tests.rs @@ -736,16 +736,21 @@ fn tunnel(client: TcpStream, upstream: TcpStream) { let _ = back.join(); } +/// Sets the CRL fetch bounds for clients built on this test's thread. +fn set_fetch_limits(limits: CrlFetchLimits) { + TEST_CRL_LIMITS.with(|cell| cell.set(Some(limits))); +} + /// Config that trusts the test root, asks for revocation, and fetches with short bounds. fn revocation_config(root_pem: &str, accept_undetermined: bool) -> HttpClientConfig { let mut config = HttpClientConfig::default(); config.tls.trusted_certificate_pem = Some(root_pem.as_bytes().to_vec()); config.tls.check_certificate_revocation = Some(true); config.tls.accept_undetermined_certificate_revocation = Some(accept_undetermined); - config.tls.crl_fetch_limits = CrlFetchLimits { + set_fetch_limits(CrlFetchLimits { timeout: Duration::from_millis(500), max_bytes: 64 * 1024, - }; + }); // No pooling: each request runs a fresh handshake and revocation check. config.max_connections_per_host = 0; config @@ -1011,17 +1016,103 @@ fn same_name_certificate_with_another_key_is_not_a_trust_anchor() { #[tokio::test] async fn one_timeout_budget_bounds_all_fetches_for_a_chain() { - // Both distribution points hang past the per-fetch timeout. The chain shares one - // budget, so the second fetch gets none and the check ends in about one timeout. + // Both distribution points hang past the per-fetch timeout. Without a shared budget + // the two fetches take about two timeouts (about 2 s). With it, the chain takes about + // one (about 1 s). The bound sits between the two, with slack on each side. let fx = fixture(Some(Served::Timeout), Served::Timeout, "127.0.0.1"); + let config = revocation_config(&fx.pki.root_pem, false); + set_fetch_limits(CrlFetchLimits { + timeout: Duration::from_millis(1000), + max_bytes: 64 * 1024, + }); let started = Instant::now(); - let err = get(revocation_config(&fx.pki.root_pem, false), fx.addr) + let err = get(config, fx.addr) .await .expect_err("undetermined under strict"); let elapsed = started.elapsed(); assert!(err.contains(UNDETERMINED), "{err}"); assert!( - elapsed < Duration::from_millis(900), + elapsed < Duration::from_millis(1500), "the fetches share one budget, but the check took {elapsed:?}" ); } + +#[tokio::test] +async fn final_verify_uses_only_the_checked_path() { + // Two intermediates share a name and key. Only the first is needed. The second is + // revoked, and its distribution point must neither be fetched nor used by webpki. + let crl = CrlServer::start(); + let root_key = KeyPair::generate().unwrap(); + let root_params = ca_params(ROOT_CN, 1); + let root_pem = root_params.self_signed(&root_key).unwrap().pem(); + let root_issuer = Issuer::new(root_params, root_key); + + let inter_key = KeyPair::generate().unwrap(); + let inter_pem = inter_key.serialize_pem(); + let good_der = signed_intermediate(&inter_key, 2001, crl.url("/good.crl"), &root_issuer); + let revoked_der = signed_intermediate( + &KeyPair::from_pem(&inter_pem).unwrap(), + 2002, + crl.url("/revoked.crl"), + &root_issuer, + ); + crl.set( + "/good.crl", + route(Served::Good, &root_issuer, ROOT_CN, 2001, &root_issuer), + ); + crl.set( + "/revoked.crl", + route(Served::Revoked, &root_issuer, ROOT_CN, 2002, &root_issuer), + ); + + let inter_issuer = Issuer::new( + ca_params(INTERMEDIATE_CN, 2001), + KeyPair::from_pem(&inter_pem).unwrap(), + ); + let mut leaf_params = CertificateParams::new(vec!["127.0.0.1".to_owned()]).unwrap(); + leaf_params.crl_distribution_points = vec![CrlDistributionPoint { + uris: vec![crl.url("/leaf.crl")], + }]; + let leaf_key = KeyPair::generate().unwrap(); + let leaf_der = leaf_params + .signed_by(&leaf_key, &inter_issuer) + .unwrap() + .der() + .clone(); + crl.set( + "/leaf.crl", + route( + Served::Good, + &inter_issuer, + INTERMEDIATE_CN, + LEAF_SERIAL, + &inter_issuer, + ), + ); + + let addr = spawn_tls_chain( + vec![leaf_der, good_der, revoked_der], + leaf_key.serialize_der(), + None, + ); + get(revocation_config(&root_pem, false), addr) + .await + .expect("the checked path verifies; the unused revoked intermediate is ignored"); + assert_eq!( + crl.hits("/revoked.crl"), + 0, + "an intermediate off the checked path is never fetched" + ); +} + +/// A CA certificate with `serial`, a distribution point at `cdp`, signed by `issuer`. +fn signed_intermediate( + key: &KeyPair, + serial: u64, + cdp: String, + issuer: &Issuer<'_, KeyPair>, +) -> CertificateDer<'static> { + let mut params = ca_params(INTERMEDIATE_CN, serial); + params.crl_distribution_points = vec![CrlDistributionPoint { uris: vec![cdp] }]; + params.signed_by(key, issuer).unwrap().der().clone() +} From d96afd71f4448b88361c6d583885f3d1b254c8b8 Mon Sep 17 00:00:00 2001 From: cat23123 <58714163+cat23123@users.noreply.github.com> Date: Thu, 19 Nov 2026 20:46:48 +0000 Subject: [PATCH 05/43] test(tls): cover redacted() and the intermediate cap - redacted() is tested directly: userinfo, query and fragment are removed, and an unparsable URL becomes "". - The intermediate cap is tested at its boundary: six presented intermediates reach path selection, and seven fail with the "supports at most 6" error. Tests only; no runtime change. Co-authored-by: Isaac Signed-off-by: cat23123 <58714163+cat23123@users.noreply.github.com> --- src/client/tls_revocation_tests.rs | 61 ++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) diff --git a/src/client/tls_revocation_tests.rs b/src/client/tls_revocation_tests.rs index 4d808e08..c8d0f388 100644 --- a/src/client/tls_revocation_tests.rs +++ b/src/client/tls_revocation_tests.rs @@ -1116,3 +1116,64 @@ fn signed_intermediate( params.crl_distribution_points = vec![CrlDistributionPoint { uris: vec![cdp] }]; params.signed_by(key, issuer).unwrap().der().clone() } + +#[test] +fn redacted_removes_userinfo_query_and_fragment() { + assert_eq!( + redacted("https://user:secret@crl.example.com/a.crl?token=abc#frag"), + "https://crl.example.com/a.crl" + ); + assert_eq!( + redacted("http://crl.example.com/ca.crl"), + "http://crl.example.com/ca.crl" + ); + assert_eq!(redacted("not a url"), ""); +} + +#[test] +fn intermediate_cap_allows_six_and_rejects_seven() { + // Six presented intermediates pass the cap and reach path selection, whatever it then + // decides. Seven fail at the cap with a message that names the limit. + let fx = fixture(Some(Served::Good), Served::Good, "127.0.0.1"); + let mut roots = RootCertStore::empty(); + roots.add(fx.pki.root_der.clone()).unwrap(); + let verifier = RevocationVerifier { + roots: Arc::new(roots.clone()), + provider: Arc::new(rustls::crypto::ring::default_provider()), + signatures: WebPkiServerVerifier::builder_with_provider( + Arc::new(roots), + Arc::new(rustls::crypto::ring::default_provider()), + ) + .build() + .unwrap(), + fetcher: CrlFetcher { + proxy: ProxyConfig::default(), + limits: CrlFetchLimits::default(), + custom_roots: Vec::new(), + cache: Mutex::new(HashMap::new()), + }, + accept_undetermined: false, + allow_hostname_mismatch: false, + }; + let end = &fx.pki.leaf_der; + let server_name = ServerName::try_from("127.0.0.1").unwrap(); + let now = UnixTime::now(); + + // Any outcome other than the cap error is fine here: the path search decides it. + let six = vec![fx.pki.intermediate_der.clone(); 6]; + if let Err(six_error) = verifier.path_intermediates(end, &six, &server_name, &[], now) { + assert!( + !six_error.to_string().contains("supports at most"), + "six intermediates must pass the cap: {six_error}" + ); + } + + let seven = vec![fx.pki.intermediate_der.clone(); 7]; + match verifier.path_intermediates(end, &seven, &server_name, &[], now) { + Err(rustls::Error::General(message)) => assert_eq!( + message, + "the server presented 7 intermediates; revocation checking supports at most 6" + ), + other => panic!("seven intermediates must fail at the cap, got {other:?}"), + } +} From 9129076cfd40921b97383a939628f82db9a00dfa Mon Sep 17 00:00:00 2001 From: cat23123 <58714163+cat23123@users.noreply.github.com> Date: Thu, 19 Nov 2026 21:13:36 +0000 Subject: [PATCH 06/43] fix(tls): address round-five review findings for certificate revocation Security: - Revocation-enabled client configs disable TLS session resumption. A resumed session skips verify_server_cert, so a certificate revoked after the first handshake would stay accepted. Test: every_handshake_runs_the_revocation_check. - CRL fetches do not follow redirects. A plaintext CRL response could otherwise send the fetch to an internal endpoint. A 3xx is not a 200, so it is undetermined. Test: a_crl_redirect_is_not_followed_and_is_undetermined. Public shape: - http::TlsConfig keeps its base shape. The revocation policy is carried by a crate-private RevocationPolicy through DatabricksHttpClient::with_revocation, so no field is added to a published struct. - Revocation fields in the public config docs and the design doc state where the verifier blocks: the kernel's own runtimes are multi-thread, so only an external current_thread caller can be stalled. Resource and correctness: - The CRL cache caps entries and bytes and drops expired entries on access. - A failed fetch is remembered for 60 s, so an unreachable endpoint is not waited on again by every handshake. A fetch given only a sliver of the chain budget is not remembered. - One CRL worker, started on first use, serves all chains of a verifier. The worker thread uses the kernel's stack size. Dropping it does not wait for the thread, so the drop cannot run past the chain deadline. - Verifier-raised errors (the intermediate cap and verifier setup) are InvalidCertificate, so they are classified as certificate-verification failures. - A certificate's remaining distribution points are not fetched once one CRL is usable. Tests: timing test widened to a 2 s timeout with a 3 s bound; tests for the cache caps, the negative cache, the early stop, the redirect and the classifier. Co-authored-by: Isaac Signed-off-by: cat23123 <58714163+cat23123@users.noreply.github.com> --- docs/designs/tls-config-design.md | 1 + src/client/http.rs | 88 ++++---- src/client/tls_revocation.rs | 231 +++++++++++++------- src/client/tls_revocation_tests.rs | 333 +++++++++++++++++++++++++---- src/config.rs | 5 + src/session.rs | 13 +- 6 files changed, 513 insertions(+), 158 deletions(-) diff --git a/docs/designs/tls-config-design.md b/docs/designs/tls-config-design.md index 8a3dd63a..dc60cd22 100644 --- a/docs/designs/tls-config-design.md +++ b/docs/designs/tls-config-design.md @@ -254,6 +254,7 @@ The Rust driver uses `databricks.http.tls.*` while the C# driver uses `adbc.http ### Scope Exclusions - **Certificate revocation mode**: implemented in the kernel's tls-rustls verifier (CRL checks, opt-in, default off), not through reqwest. The ADBC `adbc.http_options.tls.revocation_mode` mapping is out of scope by the user's decision, so the ADBC driver gets no mapping. +- **Revocation and runtime flavor**: the rustls verifier is synchronous, so a handshake with revocation on waits, up to one 10 s budget per chain, for the CRLs it needs. The kernel's own runtimes are multi-thread (C ABI, telemetry, pyo3, napi). Only an external caller that drives the kernel on its own `current_thread` runtime can be stalled by that wait. - **Client certificates (mTLS)**: Not needed per current requirements. Could be added later via `reqwest::ClientBuilder::identity()`. - **TLS version pinning**: Not needed. reqwest/native-tls negotiate the highest supported version automatically. diff --git a/src/client/http.rs b/src/client/http.rs index 41f953b0..bbd09734 100644 --- a/src/client/http.rs +++ b/src/client/http.rs @@ -197,11 +197,6 @@ pub struct TlsConfig { /// Populated from [`crate::config::TlsConfig::client_key_pem`]. /// Secret material — redacted in `Debug`. pub client_key_pem: Option>, - /// Check the chain's revocation status against its CRL distribution - /// points (tls-rustls only). `None` / `Some(false)` = off. - pub check_certificate_revocation: Option, - /// With revocation checking on, accept an undetermined status. - pub accept_undetermined_certificate_revocation: Option, } /// Bounds applied to each CRL HTTP fetch. @@ -222,31 +217,41 @@ impl Default for CrlFetchLimits { } } +/// Revocation checking for one client: whether an undetermined status is accepted. +/// It is carried next to [`TlsConfig`], not inside it, so that struct keeps its +/// published shape. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct RevocationPolicy { + pub(crate) accept_undetermined: bool, +} + +impl RevocationPolicy { + /// The policy for the public options, or `None` when checking is off (unset or + /// `false`). + pub(crate) fn from_options( + check: Option, + accept_undetermined: Option, + ) -> Option { + (check == Some(true)).then(|| Self { + accept_undetermined: accept_undetermined == Some(true), + }) + } +} + /// Rejects a revocation request the backend cannot honour. Shared by session /// open (which must report `InvalidArgument` unwrapped) and the HTTP client. /// `allow_self_signed` turns revocation off, so it is not an error. -pub(crate) fn check_revocation_support(tls: &TlsConfig) -> Result<()> { - if cfg!(feature = "tls-rustls") - || tls.check_certificate_revocation != Some(true) - || tls.allow_self_signed == Some(true) - { +pub(crate) fn check_revocation_support( + tls: &TlsConfig, + revocation: Option, +) -> Result<()> { + if cfg!(feature = "tls-rustls") || revocation.is_none() || tls.allow_self_signed == Some(true) { return Ok(()); } Err(Error::invalid_argument() .message("certificate revocation checking requires the tls-rustls backend")) } -/// The accept-undetermined flag when revocation checking applies. `allow_self_signed` -/// turns it off, as Simba does. -#[cfg(feature = "tls-rustls")] -fn revocation_policy(tls: &TlsConfig) -> Option { - (tls.check_certificate_revocation == Some(true) && !tls.allow_self_signed.unwrap_or(false)) - .then(|| { - tls.accept_undetermined_certificate_revocation - .unwrap_or(false) - }) -} - impl std::fmt::Debug for TlsConfig { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { // Mirrors the redacting Debug on the public @@ -280,14 +285,6 @@ impl std::fmt::Debug for TlsConfig { "client_key_pem", &self.client_key_pem.as_ref().map(|_| ""), ) - .field( - "check_certificate_revocation", - &self.check_certificate_revocation, - ) - .field( - "accept_undetermined_certificate_revocation", - &self.accept_undetermined_certificate_revocation, - ) .finish() } } @@ -316,9 +313,6 @@ impl TlsConfig { trusted_certificate_pem: cfg.custom_ca_cert.clone(), client_cert_pem: cfg.client_cert_pem.clone(), client_key_pem: cfg.client_key_pem.clone(), - check_certificate_revocation: cfg.check_certificate_revocation, - accept_undetermined_certificate_revocation: cfg - .accept_undetermined_certificate_revocation, } } } @@ -445,6 +439,7 @@ pub struct DatabricksHttpClient { config: HttpClientConfig, auth_provider: OnceLock>, retry_configs: HashMap, + revocation: Option, } impl DatabricksHttpClient { @@ -454,8 +449,19 @@ impl DatabricksHttpClient { /// calling `execute()`. Use `execute_without_auth()` for requests that /// don't need authentication (e.g., OAuth token endpoint calls). pub fn new( + config: HttpClientConfig, + retry_configs: HashMap, + ) -> Result { + Self::with_revocation(config, retry_configs, None) + } + + /// Like [`Self::new`], with a revocation policy applied to every connection this client + /// makes. The policy is kept outside [`TlsConfig`], so that struct keeps its published + /// shape. + pub(crate) fn with_revocation( mut config: HttpClientConfig, retry_configs: HashMap, + revocation: Option, ) -> Result { // Fold any caller-supplied `User-Agent` custom header into the // effective UA, and remove it from `custom_headers` so it isn't @@ -538,7 +544,8 @@ impl DatabricksHttpClient { } // Follow redirects for normal traffic (reqwest's default policy). - let client = Self::build_reqwest_client(&config, reqwest::redirect::Policy::default())?; + let client = + Self::build_reqwest_client(&config, reqwest::redirect::Policy::default(), revocation)?; // Surface which TLS backend was compiled in so oncall debugging // a handshake / unknown-CA report can tell at a glance whether @@ -561,6 +568,7 @@ impl DatabricksHttpClient { config, auth_provider: OnceLock::new(), retry_configs, + revocation, }) } @@ -573,8 +581,9 @@ impl DatabricksHttpClient { fn build_reqwest_client( config: &HttpClientConfig, redirect: reqwest::redirect::Policy, + revocation: Option, ) -> Result { - check_revocation_support(&config.tls)?; + check_revocation_support(&config.tls, revocation)?; let mut builder = Client::builder() .connect_timeout(config.connect_timeout) // `read_timeout` is a historical name; reqwest applies this as @@ -763,11 +772,12 @@ impl DatabricksHttpClient { // With revocation on, the verifier replaces reqwest's trust roots and // identity. Those were already validated above. #[cfg(feature = "tls-rustls")] - if let Some(accept_undetermined) = revocation_policy(&config.tls) { + // `allow_self_signed` turns revocation off, as Simba does. + if let Some(policy) = revocation.filter(|_| config.tls.allow_self_signed != Some(true)) { builder = builder.use_preconfigured_tls(super::tls_revocation::client_config( &config.tls, &config.proxy, - accept_undetermined, + policy.accept_undetermined, )?); } @@ -876,7 +886,11 @@ impl DatabricksHttpClient { /// `azure_tenant_id` (which skips discovery entirely). A single hop is /// sufficient for discovery, so no retry is attempted here. pub async fn first_redirect_location(&self, url: &str) -> Result> { - let client = Self::build_reqwest_client(&self.config, reqwest::redirect::Policy::none())?; + let client = Self::build_reqwest_client( + &self.config, + reqwest::redirect::Policy::none(), + self.revocation, + )?; let response = client.get(url).send().await.map_err(|e| { Error::network_error().message(format!("Redirect-probe request to {url} failed: {e}")) })?; diff --git a/src/client/tls_revocation.rs b/src/client/tls_revocation.rs index 5e0c9d59..02e4c586 100644 --- a/src/client/tls_revocation.rs +++ b/src/client/tls_revocation.rs @@ -42,6 +42,7 @@ use rustls::{ use super::http::{CrlFetchLimits, ProxyConfig, TlsConfig}; use crate::kernel_error::{Error, Result}; use crate::klog::debug; +use crate::util::runtime::{ambient_rust_min_stack, runtime_thread_stack_size}; const TAG_INTEGER: u8 = 0x02; const TAG_UTC_TIME: u8 = 0x17; @@ -57,7 +58,31 @@ const TAG_CONTEXT_3: u8 = 0xA3; const TAG_URI: u8 = 0x86; /// OID 2.5.29.31, the CRL distribution points extension (content octets). const OID_CRL_DISTRIBUTION_POINTS: &[u8] = &[0x55, 0x1D, 0x1F]; -const CRL_MAX_REDIRECTS: usize = 3; +/// How long a failed fetch is remembered, so an unreachable endpoint is not waited on again +/// by every handshake. +const FAILED_FETCH_TTL: Duration = Duration::from_secs(60); +/// Caps on the cached CRLs, by count and by total bytes. +const MAX_CACHED_CRLS: usize = 64; +const MAX_CACHED_BYTES: usize = 16 * 1024 * 1024; + +/// A verification failure the verifier raises itself. It carries a message for the caller +/// and is classified as a certificate-verification failure. +#[derive(Debug)] +struct VerifierError(String); + +impl std::fmt::Display for VerifierError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.0) + } +} + +impl std::error::Error for VerifierError {} + +fn verifier_error(message: String) -> rustls::Error { + rustls::Error::InvalidCertificate(CertificateError::Other(rustls::OtherError(Arc::new( + VerifierError(message), + )))) +} // Tests set a per-thread fetch bound here. The client is built on the calling thread, so // the bound in effect at construction is the one the fetcher keeps. @@ -233,7 +258,27 @@ fn classify(der: &[u8], cert_issuer: &[u8], now: u64) -> Verdict { /// A cached CRL and its nextUpdate in Unix seconds. type CachedCrl = (Arc>, u64); -/// Fetches CRLs and caches each until its `nextUpdate`. +/// Drops expired CRLs, then the ones that expire soonest until the count and byte caps hold. +fn trim_cache(cache: &mut HashMap, now: u64) { + cache.retain(|_, (_, next)| now <= *next); + while cache.len() > MAX_CACHED_CRLS || cached_bytes(cache) > MAX_CACHED_BYTES { + let Some(soonest) = cache + .iter() + .min_by_key(|(_, (_, next))| *next) + .map(|(url, _)| url.clone()) + else { + break; + }; + cache.remove(&soonest); + } +} + +fn cached_bytes(cache: &HashMap) -> usize { + cache.values().map(|(der, _)| der.len()).sum() +} + +/// Fetches CRLs through one worker. Each CRL is cached until its `nextUpdate`, within the +/// caps, and a failed fetch is remembered for `FAILED_FETCH_TTL`. #[derive(Debug)] struct CrlFetcher { proxy: ProxyConfig, @@ -242,54 +287,75 @@ struct CrlFetcher { custom_roots: Vec, /// URL to (CRL bytes, nextUpdate in Unix seconds). cache: Mutex>, + /// URL to the time its last fetch failed. + failed: Mutex>, + /// Started on the first fetch, then reused for every chain this fetcher verifies. + worker: Mutex>, } impl CrlFetcher { - /// The CRL at `url`, from cache while current, otherwise freshly fetched. - /// `None` means the fetch failed. Only a CRL with a future `nextUpdate` is cached. - fn get( - &self, - url: &str, - now: u64, - budget: Duration, - worker: &mut Option, - ) -> Option>> { - let cached = self - .cache - .lock() - .unwrap_or_else(PoisonError::into_inner) - .get(url) - .filter(|(_, next)| now <= *next) - .map(|(der, _)| Arc::clone(der)); - if cached.is_some() { - return cached; + /// The CRL at `url`, from cache while current, otherwise fetched within `budget`. + /// `None` means the fetch failed, no budget was left, or the URL failed recently. + fn get(&self, url: &str, now: u64, budget: Duration) -> Option>> { + { + let mut cache = self.cache.lock().unwrap_or_else(PoisonError::into_inner); + trim_cache(&mut cache, now); + if let Some((der, _)) = cache.get(url) { + return Some(Arc::clone(der)); + } } - self.evict(url); - if budget.is_zero() { + if budget.is_zero() || self.failed_recently(url) { return None; } - let worker = worker.get_or_insert_with(|| { - CrlWorker::start(self.proxy.clone(), self.limits, self.custom_roots.clone()) - }); - let der = match worker.fetch(url, budget) { + let fetched = { + let mut worker = self.worker.lock().unwrap_or_else(PoisonError::into_inner); + if worker.is_none() { + match CrlWorker::start(self.proxy.clone(), self.limits, self.custom_roots.clone()) { + Ok(started) => *worker = Some(started), + Err(reason) => { + debug!("CRL worker failed to start: {reason}"); + return None; + } + } + } + worker.as_ref()?.fetch(url, budget) + }; + let der = match fetched { Ok(der) => Arc::new(der), Err(reason) => { debug!("CRL fetch failed for {}: {reason}", redacted(url)); + // A fetch given only a sliver of the chain's budget says little about the + // endpoint, so only a fetch with most of its time is remembered. + if budget >= self.limits.timeout / 2 { + self.failed + .lock() + .unwrap_or_else(PoisonError::into_inner) + .insert(url.to_owned(), Instant::now()); + } return None; } }; + self.failed + .lock() + .unwrap_or_else(PoisonError::into_inner) + .remove(url); if let Some(next) = parse_crl(&der) .and_then(|crl| crl.next_update) .filter(|next| now <= *next) { - self.cache - .lock() - .unwrap_or_else(PoisonError::into_inner) - .insert(url.to_owned(), (Arc::clone(&der), next)); + let mut cache = self.cache.lock().unwrap_or_else(PoisonError::into_inner); + cache.insert(url.to_owned(), (Arc::clone(&der), next)); + trim_cache(&mut cache, now); } Some(der) } + fn failed_recently(&self, url: &str) -> bool { + let mut failed = self.failed.lock().unwrap_or_else(PoisonError::into_inner); + failed.retain(|_, at| at.elapsed() < FAILED_FETCH_TTL); + failed.contains_key(url) + } + fn evict(&self, url: &str) { self.cache .lock() @@ -305,49 +371,61 @@ type CrlRequest = ( std::sync::mpsc::Sender, String>>, ); -/// The CRL client for one chain verification: one thread, one current-thread runtime and -/// one reqwest client, shared by that chain's fetches. Dropping it ends the thread. +/// The thread that runs a fetcher's CRL fetches: one current-thread runtime and one reqwest +/// client, shared by all of them. Dropping the worker closes its request channel. The +/// thread then exits once its queue is empty, and the drop does not wait for it, so it +/// cannot run past a chain's deadline. struct CrlWorker { - requests: Option>, - thread: Option>, + requests: std::sync::mpsc::Sender, +} + +impl std::fmt::Debug for CrlWorker { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("CrlWorker") + } } impl CrlWorker { - fn start(proxy: ProxyConfig, limits: CrlFetchLimits, roots: Vec) -> Self { + fn start( + proxy: ProxyConfig, + limits: CrlFetchLimits, + roots: Vec, + ) -> std::io::Result { let (requests, inbox) = std::sync::mpsc::channel::(); - let thread = std::thread::spawn(move || { - // The caller's runtime is never re-entered, so a current-thread caller cannot - // deadlock. - let runtime = tokio::runtime::Builder::new_current_thread() - .enable_all() - .build(); - let client = build_client(&proxy, limits, &roots); - for (url, budget, answer) in inbox { - let result = match (&runtime, &client) { - (Ok(runtime), Ok(client)) => { - runtime.block_on(fetch(client, &url, limits.max_bytes, budget)) - } - (Err(e), _) => Err(e.to_string()), - (_, Err(e)) => Err(e.clone()), - }; - let _ = answer.send(result); - } - }); - Self { - requests: Some(requests), - thread: Some(thread), - } + // The JoinHandle is dropped, which detaches the thread. + std::thread::Builder::new() + .name("databricks-crl".to_owned()) + .stack_size(runtime_thread_stack_size(ambient_rust_min_stack())) + .spawn(move || { + // The caller's runtime is never re-entered, so a current-thread caller + // cannot deadlock. + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build(); + let client = build_client(&proxy, limits, &roots); + for (url, budget, answer) in inbox { + let result = match (&runtime, &client) { + (Ok(runtime), Ok(client)) => { + runtime.block_on(fetch(client, &url, limits.max_bytes, budget)) + } + (Err(e), _) => Err(e.to_string()), + (_, Err(e)) => Err(e.clone()), + }; + let _ = answer.send(result); + } + })?; + Ok(Self { requests }) } /// Runs one fetch on the worker and waits for its answer. The wait is bounded by /// `budget`, because the fetch itself is. fn fetch(&self, url: &str, budget: Duration) -> std::result::Result, String> { let (answer, received) = std::sync::mpsc::channel(); - let sent = self + if self .requests - .as_ref() - .is_some_and(|requests| requests.send((url.to_owned(), budget, answer)).is_ok()); - if !sent { + .send((url.to_owned(), budget, answer)) + .is_err() + { return Err("CRL worker is not running".to_owned()); } in_runtime_blocking(|| received.recv()) @@ -355,16 +433,6 @@ impl CrlWorker { } } -impl Drop for CrlWorker { - fn drop(&mut self) { - // Closing the request channel ends the worker once its queue is empty. - self.requests.take(); - if let Some(thread) = self.thread.take() { - let _ = in_runtime_blocking(|| thread.join()); - } - } -} - /// Runs a blocking wait. On a multi-thread runtime, block_in_place moves the worker's /// other tasks to another thread first. It panics on current_thread, so the wait runs as /// it is there. @@ -388,7 +456,9 @@ fn build_client( let mut builder = reqwest::Client::builder() .connect_timeout(limits.timeout) .timeout(limits.timeout) - .redirect(reqwest::redirect::Policy::limited(CRL_MAX_REDIRECTS)); + // Redirects are not followed. A plaintext CRL response could otherwise send the + // fetch to an internal endpoint. A 3xx is not a 200, so the status is undetermined. + .redirect(reqwest::redirect::Policy::none()); for root in roots { builder = builder.add_root_certificate(root.clone()); } @@ -513,7 +583,7 @@ impl RevocationVerifier { const MAX_PRESENTED: usize = 6; let n = intermediates.len(); if n > MAX_PRESENTED { - return Err(rustls::Error::General(format!( + return Err(verifier_error(format!( "the server presented {n} intermediates; revocation checking supports at most {MAX_PRESENTED}" ))); } @@ -568,8 +638,6 @@ impl ServerCertVerifier for RevocationVerifier { // One deadline bounds every fetch for this chain, so the total wait is at // most one per-fetch timeout however many distribution points there are. let deadline = Instant::now() + self.fetcher.limits.timeout; - // One CRL client for this chain, started on the first fetch that needs it. - let mut worker = None; let mut crls = Vec::new(); let mut used_urls = Vec::new(); let mut undetermined = false; @@ -584,8 +652,12 @@ impl ServerCertVerifier for RevocationVerifier { } let mut covered = false; for url in &parsed.crl_uris { + // One usable CRL covers the certificate, so the other URLs are not fetched. + if covered { + break; + } let budget = deadline.saturating_duration_since(Instant::now()); - let Some(der) = self.fetcher.get(url, now_secs, budget, &mut worker) else { + let Some(der) = self.fetcher.get(url, now_secs, budget) else { continue; }; match classify(&der, parsed.issuer, now_secs) { @@ -621,7 +693,7 @@ impl ServerCertVerifier for RevocationVerifier { } let verifier = builder .build() - .map_err(|e| rustls::Error::General(format!("revocation verifier setup: {e}")))?; + .map_err(|e| verifier_error(format!("revocation verifier setup: {e}")))?; // The final verification sees only the checked path. Webpki then cannot build a // path through a presented intermediate whose CRLs were not checked. let checked: Vec> = @@ -739,6 +811,8 @@ pub(crate) fn client_config( limits: crl_fetch_limits(), custom_roots, cache: Mutex::new(HashMap::new()), + failed: Mutex::new(HashMap::new()), + worker: Mutex::new(None), }, accept_undetermined, allow_hostname_mismatch: tls.allow_hostname_mismatch.unwrap_or(false), @@ -762,6 +836,9 @@ pub(crate) fn client_config( _ => builder.with_no_client_auth(), }; config.alpn_protocols = vec![b"http/1.1".to_vec()]; + // Resumed sessions skip `verify_server_cert`, so a certificate revoked after the first + // handshake would stay accepted. Every handshake therefore runs the check. + config.resumption = rustls::client::Resumption::disabled(); Ok(config) } diff --git a/src/client/tls_revocation_tests.rs b/src/client/tls_revocation_tests.rs index c8d0f388..5277c265 100644 --- a/src/client/tls_revocation_tests.rs +++ b/src/client/tls_revocation_tests.rs @@ -17,13 +17,17 @@ //! TLS on loopback. A forward-proxy stub can sit in front of the CRL fetches. use super::*; -use crate::client::http::{CrlFetchLimits, DatabricksHttpClient, HttpClientConfig}; +use crate::client::http::{ + CrlFetchLimits, DatabricksHttpClient, HttpClientConfig, RevocationPolicy, +}; +use crate::client::retry::{build_retry_configs, RetryConfig}; use rcgen::{ date_time_ymd, BasicConstraints, CertificateParams, CertificateRevocationListParams, CrlDistributionPoint, CustomExtension, DnType, IsCa, Issuer, KeyIdMethod, KeyPair, RevokedCertParams, SerialNumber, SigningKey, }; use rustls::pki_types::PrivatePkcs8KeyDer; +use rustls::HandshakeKind; use std::collections::HashMap; use std::io::{Read, Write}; use std::net::{Shutdown, SocketAddr, TcpListener, TcpStream}; @@ -548,6 +552,8 @@ struct Route { struct CrlServer { addr: SocketAddr, routes: Arc>>, + /// Paths that answer `302 Found` with the given `Location`. + redirects: Arc>>, requests: Arc>>, } @@ -557,6 +563,7 @@ impl CrlServer { let server = Self { addr: listener.local_addr().unwrap(), routes: Arc::new(Mutex::new(HashMap::new())), + redirects: Arc::new(Mutex::new(HashMap::new())), requests: Arc::new(Mutex::new(Vec::new())), }; let accept_side = server.clone(); @@ -577,6 +584,13 @@ impl CrlServer { self.routes.lock().unwrap().insert(path.to_owned(), route); } + fn redirect(&self, path: &str, target: String) { + self.redirects + .lock() + .unwrap() + .insert(path.to_owned(), target); + } + /// Requests received for `path`. fn hits(&self, path: &str) -> usize { self.requests @@ -608,6 +622,15 @@ impl CrlServer { .unwrap_or("/") .to_owned(); self.requests.lock().unwrap().push((path.clone(), head)); + if let Some(target) = self.redirects.lock().unwrap().get(&path).cloned() { + let _ = stream.write_all( + format!( + "HTTP/1.1 302 Found\r\nLocation: {target}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n" + ) + .as_bytes(), + ); + return; + } let route = self .routes .lock() @@ -741,12 +764,19 @@ fn set_fetch_limits(limits: CrlFetchLimits) { TEST_CRL_LIMITS.with(|cell| cell.set(Some(limits))); } -/// Config that trusts the test root, asks for revocation, and fetches with short bounds. -fn revocation_config(root_pem: &str, accept_undetermined: bool) -> HttpClientConfig { +/// The revocation policy for a test client: checking on, and an undetermined status +/// accepted when `accept_undetermined` is set. +fn policy(accept_undetermined: bool) -> Option { + Some(RevocationPolicy { + accept_undetermined, + }) +} + +/// Config that trusts the test root and fetches with short bounds. The revocation policy +/// is passed separately, as [`policy`]. +fn revocation_config(root_pem: &str) -> HttpClientConfig { let mut config = HttpClientConfig::default(); config.tls.trusted_certificate_pem = Some(root_pem.as_bytes().to_vec()); - config.tls.check_certificate_revocation = Some(true); - config.tls.accept_undetermined_certificate_revocation = Some(accept_undetermined); set_fetch_limits(CrlFetchLimits { timeout: Duration::from_millis(500), max_bytes: 64 * 1024, @@ -756,8 +786,22 @@ fn revocation_config(root_pem: &str, accept_undetermined: bool) -> HttpClientCon config } -async fn get(config: HttpClientConfig, addr: SocketAddr) -> std::result::Result<(), String> { - let client = DatabricksHttpClient::with_default_retry(config).unwrap(); +/// A client built from `config` and `revocation`, with default retry configs. +fn client(config: HttpClientConfig, revocation: Option) -> DatabricksHttpClient { + DatabricksHttpClient::with_revocation( + config, + build_retry_configs(&RetryConfig::default(), &HashMap::new()), + revocation, + ) + .unwrap() +} + +async fn get( + config: HttpClientConfig, + revocation: Option, + addr: SocketAddr, +) -> std::result::Result<(), String> { + let client = client(config, revocation); client .inner() .get(format!("https://{addr}/")) @@ -783,7 +827,7 @@ fn error_text(error: &dyn std::error::Error) -> String { async fn check(scenario: &Scenario, accept: bool, want: Outcome) { let fx = fixture(scenario.leaf, scenario.intermediate, "127.0.0.1"); let proxy = scenario.relay.map(ForwardProxy::start); - let mut config = revocation_config(&fx.pki.root_pem, accept); + let mut config = revocation_config(&fx.pki.root_pem); config.custom_headers = vec![("X-Kernel-Secret".to_owned(), "hunter2".to_owned())]; config.org_id = Some("1234".to_owned()); if let Some(proxy) = &proxy { @@ -791,7 +835,7 @@ async fn check(scenario: &Scenario, accept: bool, want: Outcome) { } let label = format!("{} (accept_undetermined={accept})", scenario.name); - let result = get(config, fx.addr).await; + let result = get(config, policy(accept), fx.addr).await; match (want, &result) { (Outcome::Pass, Ok(())) => {} (Outcome::Revoked, Err(err)) => assert!(err.contains("revoked"), "{label}: {err}"), @@ -850,12 +894,9 @@ async fn revocation_outcomes_follow_the_policy_table() { #[tokio::test] async fn current_crl_is_fetched_once_and_a_rejected_one_is_refetched() { let fx = fixture(Some(Served::Good), Served::Good, "127.0.0.1"); - let client = - DatabricksHttpClient::with_default_retry(revocation_config(&fx.pki.root_pem, false)) - .unwrap(); + let http = client(revocation_config(&fx.pki.root_pem), policy(false)); for _ in 0..2 { - client - .inner() + http.inner() .get(format!("https://{}/", fx.addr)) .send() .await @@ -869,11 +910,9 @@ async fn current_crl_is_fetched_once_and_a_rejected_one_is_refetched() { assert_eq!(fx.crl.hits("/intermediate.crl"), 1); let fx = fixture(Some(Served::WrongKey), Served::Good, "127.0.0.1"); - let client = - DatabricksHttpClient::with_default_retry(revocation_config(&fx.pki.root_pem, false)) - .unwrap(); + let http = client(revocation_config(&fx.pki.root_pem), policy(false)); for _ in 0..2 { - assert!(client + assert!(http .inner() .get(format!("https://{}/", fx.addr)) .send() @@ -890,12 +929,12 @@ async fn current_crl_is_fetched_once_and_a_rejected_one_is_refetched() { #[tokio::test] async fn hostname_mismatch_is_rejected_unless_allowed() { let fx = fixture(Some(Served::Good), Served::Good, "wrong-host.invalid"); - get(revocation_config(&fx.pki.root_pem, false), fx.addr) + get(revocation_config(&fx.pki.root_pem), policy(false), fx.addr) .await .expect_err("a name mismatch is rejected by default"); - let mut config = revocation_config(&fx.pki.root_pem, false); + let mut config = revocation_config(&fx.pki.root_pem); config.tls.allow_hostname_mismatch = Some(true); - get(config, fx.addr) + get(config, policy(false), fx.addr) .await .expect("allow_hostname_mismatch passes a good chain with revocation still checked"); } @@ -904,16 +943,16 @@ async fn hostname_mismatch_is_rejected_unless_allowed() { async fn client_identity_and_custom_ca_work_with_revocation() { let fx = fixture(Some(Served::Good), Served::Good, "127.0.0.1"); let mtls_addr = spawn_tls_server(&fx.pki, true); - let mut config = revocation_config(&fx.pki.root_pem, false); + let mut config = revocation_config(&fx.pki.root_pem); config.tls.client_cert_pem = Some(fx.pki.client_cert_pem.clone().into_bytes()); config.tls.client_key_pem = Some(fx.pki.client_key_pem.clone().into_bytes()); - get(config.clone(), mtls_addr) + get(config.clone(), policy(false), mtls_addr) .await .expect("mTLS identity passes with revocation"); config.tls.client_cert_pem = None; config.tls.client_key_pem = None; - get(config, mtls_addr) + get(config, policy(false), mtls_addr) .await .expect_err("the mTLS server rejects a client without an identity"); } @@ -921,15 +960,13 @@ async fn client_identity_and_custom_ca_work_with_revocation() { #[tokio::test] async fn policy_off_and_accept_self_signed_skip_revocation() { let fx = fixture(Some(Served::Revoked), Served::Good, "127.0.0.1"); - let mut off = revocation_config(&fx.pki.root_pem, false); - off.tls.check_certificate_revocation = None; - get(off, fx.addr) + get(revocation_config(&fx.pki.root_pem), None, fx.addr) .await .expect("policy off passes a revoked leaf"); - let mut self_signed = revocation_config(&fx.pki.root_pem, false); + let mut self_signed = revocation_config(&fx.pki.root_pem); self_signed.tls.allow_self_signed = Some(true); - get(self_signed, fx.addr) + get(self_signed, policy(false), fx.addr) .await .expect("accept_self_signed turns revocation off"); @@ -974,7 +1011,7 @@ async fn unrelated_appended_certificate_is_never_fetched() { unrelated, ]; let addr = spawn_tls_chain(chain, fx.pki.leaf_key_der.clone(), None); - get(revocation_config(&fx.pki.root_pem, false), addr) + get(revocation_config(&fx.pki.root_pem), policy(false), addr) .await .expect("the good path verifies; the appended certificate is not on it"); assert_eq!( @@ -1017,22 +1054,23 @@ fn same_name_certificate_with_another_key_is_not_a_trust_anchor() { #[tokio::test] async fn one_timeout_budget_bounds_all_fetches_for_a_chain() { // Both distribution points hang past the per-fetch timeout. Without a shared budget - // the two fetches take about two timeouts (about 2 s). With it, the chain takes about - // one (about 1 s). The bound sits between the two, with slack on each side. + // the two fetches take about two timeouts (about 4 s). With it, the chain takes about + // one (about 2 s). The bound of 3 s sits between the two, with about a second of slack + // on each side. let fx = fixture(Some(Served::Timeout), Served::Timeout, "127.0.0.1"); - let config = revocation_config(&fx.pki.root_pem, false); + let config = revocation_config(&fx.pki.root_pem); set_fetch_limits(CrlFetchLimits { - timeout: Duration::from_millis(1000), + timeout: Duration::from_millis(2000), max_bytes: 64 * 1024, }); let started = Instant::now(); - let err = get(config, fx.addr) + let err = get(config, policy(false), fx.addr) .await .expect_err("undetermined under strict"); let elapsed = started.elapsed(); assert!(err.contains(UNDETERMINED), "{err}"); assert!( - elapsed < Duration::from_millis(1500), + elapsed < Duration::from_millis(3000), "the fetches share one budget, but the check took {elapsed:?}" ); } @@ -1095,7 +1133,7 @@ async fn final_verify_uses_only_the_checked_path() { leaf_key.serialize_der(), None, ); - get(revocation_config(&root_pem, false), addr) + get(revocation_config(&root_pem), policy(false), addr) .await .expect("the checked path verifies; the unused revoked intermediate is ignored"); assert_eq!( @@ -1151,6 +1189,8 @@ fn intermediate_cap_allows_six_and_rejects_seven() { limits: CrlFetchLimits::default(), custom_roots: Vec::new(), cache: Mutex::new(HashMap::new()), + failed: Mutex::new(HashMap::new()), + worker: Mutex::new(None), }, accept_undetermined: false, allow_hostname_mismatch: false, @@ -1170,10 +1210,223 @@ fn intermediate_cap_allows_six_and_rejects_seven() { let seven = vec![fx.pki.intermediate_der.clone(); 7]; match verifier.path_intermediates(end, &seven, &server_name, &[], now) { - Err(rustls::Error::General(message)) => assert_eq!( - message, - "the server presented 7 intermediates; revocation checking supports at most 6" + Err(error @ rustls::Error::InvalidCertificate(_)) => assert!( + error.to_string().contains( + "the server presented 7 intermediates; revocation checking supports at most 6" + ), + "unexpected message: {error}" ), other => panic!("seven intermediates must fail at the cap, got {other:?}"), } } + +/// A TLS server that allows session resumption and records the kind of each handshake. +fn spawn_resuming_server(pki: &Pki) -> (SocketAddr, Arc>>) { + let provider = Arc::new(rustls::crypto::ring::default_provider()); + let mut config = rustls::ServerConfig::builder_with_provider(provider) + .with_safe_default_protocol_versions() + .unwrap() + .with_no_client_auth() + .with_single_cert( + vec![pki.leaf_der.clone(), pki.intermediate_der.clone()], + PrivatePkcs8KeyDer::from(pki.leaf_key_der.clone()).into(), + ) + .unwrap(); + config.session_storage = rustls::server::ServerSessionMemoryCache::new(32); + config.ticketer = rustls::crypto::ring::Ticketer::new().unwrap(); + let config = Arc::new(config); + let kinds = Arc::new(Mutex::new(Vec::new())); + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = listener.local_addr().unwrap(); + let recorded = Arc::clone(&kinds); + thread::spawn(move || { + for tcp in listener.incoming().flatten() { + let config = Arc::clone(&config); + let recorded = Arc::clone(&recorded); + thread::spawn(move || { + let Ok(conn) = rustls::ServerConnection::new(config) else { + return; + }; + let mut stream = rustls::StreamOwned::new(conn, tcp); + if read_head(&mut stream).is_some() { + if let Some(kind) = stream.conn.handshake_kind() { + recorded.lock().unwrap().push(kind); + } + let _ = stream.write_all( + b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok", + ); + let _ = stream.flush(); + } + }); + } + }); + (addr, kinds) +} + +#[tokio::test] +async fn every_handshake_runs_the_revocation_check() { + // A resumed session skips `verify_server_cert`. With resumption disabled on the client, + // both connections are full handshakes, and so both run the check. + let fx = fixture(Some(Served::Good), Served::Good, "127.0.0.1"); + let (addr, kinds) = spawn_resuming_server(&fx.pki); + let http = client(revocation_config(&fx.pki.root_pem), policy(false)); + for _ in 0..2 { + http.inner() + .get(format!("https://{addr}/")) + .send() + .await + .expect("good chain"); + } + assert_eq!( + *kinds.lock().unwrap(), + vec![HandshakeKind::Full, HandshakeKind::Full], + "a resumed handshake would skip the revocation check" + ); +} + +#[tokio::test] +async fn a_crl_redirect_is_not_followed_and_is_undetermined() { + // A redirect from the CRL endpoint could send the fetch to an internal address, so it is + // not followed. The 302 is undetermined: strict rejects, accept passes, and the target + // is never requested. + let fx = fixture(Some(Served::Good), Served::Good, "127.0.0.1"); + fx.crl.redirect("/leaf.crl", fx.crl.url("/target.crl")); + fx.crl.set( + "/target.crl", + route( + Served::Good, + &fx.pki.intermediate_issuer, + INTERMEDIATE_CN, + LEAF_SERIAL, + &fx.pki.root_issuer, + ), + ); + let err = get(revocation_config(&fx.pki.root_pem), policy(false), fx.addr) + .await + .expect_err("a redirected CRL is undetermined under strict"); + assert!(err.contains(UNDETERMINED), "{err}"); + get(revocation_config(&fx.pki.root_pem), policy(true), fx.addr) + .await + .expect("a redirected CRL passes under accept-undetermined"); + assert_eq!( + fx.crl.hits("/target.crl"), + 0, + "the redirect target is never requested" + ); +} + +#[tokio::test] +async fn a_failed_crl_fetch_is_not_retried_within_its_ttl() { + // The leaf's CRL endpoint returns 503. The first handshake waits for it and fails. The + // second, on the same client, does not ask again. + let fx = fixture(Some(Served::Status(503)), Served::Good, "127.0.0.1"); + let http = client(revocation_config(&fx.pki.root_pem), policy(false)); + for _ in 0..2 { + assert!(http + .inner() + .get(format!("https://{}/", fx.addr)) + .send() + .await + .is_err()); + } + assert_eq!( + fx.crl.hits("/leaf.crl"), + 1, + "a failed fetch is remembered for its TTL" + ); +} + +#[tokio::test] +async fn a_usable_crl_stops_the_other_distribution_points() { + // The leaf names two distribution points. The first serves a usable CRL, so the + // second, which would hang, is never requested. + let crl = CrlServer::start(); + let pki = build_pki( + LeafCdp::Uris(vec![crl.url("/good.crl"), crl.url("/slow.crl")]), + crl.url("/intermediate.crl"), + "127.0.0.1", + ); + crl.set( + "/good.crl", + route( + Served::Good, + &pki.intermediate_issuer, + INTERMEDIATE_CN, + LEAF_SERIAL, + &pki.root_issuer, + ), + ); + crl.set( + "/slow.crl", + route( + Served::Timeout, + &pki.intermediate_issuer, + INTERMEDIATE_CN, + LEAF_SERIAL, + &pki.root_issuer, + ), + ); + crl.set( + "/intermediate.crl", + route( + Served::Good, + &pki.root_issuer, + ROOT_CN, + INTERMEDIATE_SERIAL, + &pki.intermediate_issuer, + ), + ); + let addr = spawn_tls_server(&pki, false); + get(revocation_config(&pki.root_pem), policy(false), addr) + .await + .expect("the usable CRL covers the leaf"); + assert_eq!( + crl.hits("/slow.crl"), + 0, + "a second distribution point is not fetched once a CRL is usable" + ); +} + +#[test] +fn crl_cache_drops_expired_entries_and_stays_within_its_caps() { + let mut cache: HashMap = HashMap::new(); + cache.insert("expired".to_owned(), (Arc::new(vec![0_u8; 8]), 5)); + for i in 0..(MAX_CACHED_CRLS + 10) { + cache.insert(format!("crl{i}"), (Arc::new(vec![0_u8; 8]), 100 + i as u64)); + } + trim_cache(&mut cache, 10); + assert!( + !cache.contains_key("expired"), + "expired entries are dropped" + ); + assert_eq!( + cache.len(), + MAX_CACHED_CRLS, + "the count cap keeps the entries that expire last" + ); + assert!(cache.contains_key(&format!("crl{}", MAX_CACHED_CRLS + 9))); + assert!( + !cache.contains_key("crl0"), + "the soonest to expire goes first" + ); + + // The byte cap: three 8 MiB entries exceed 16 MiB, so the soonest-expiring one goes. + let mut big: HashMap = HashMap::new(); + for i in 0..3_u64 { + big.insert( + format!("big{i}"), + (Arc::new(vec![0_u8; 8 * 1024 * 1024]), 100 + i), + ); + } + trim_cache(&mut big, 10); + assert_eq!(big.len(), 2, "the byte cap keeps the cache under 16 MiB"); + assert!(!big.contains_key("big0")); +} + +#[test] +fn verifier_errors_are_certificate_verification_failures() { + let error = verifier_error("the server presented 7 intermediates".to_owned()); + assert!(crate::client::retry::is_certificate_verification_failure( + &error + )); +} diff --git a/src/config.rs b/src/config.rs index e635eab2..dd98f016 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1046,6 +1046,11 @@ pub struct TlsConfig { /// points. Default off. Revoked certificates are always rejected. Requires /// the `tls-rustls` backend; `tls-native` fails session open with /// `InvalidArgument`. Disabled by [`Self::accept_self_signed`]. + /// + /// Each handshake waits, up to a 10 s budget per chain, for the CRLs it needs. The + /// kernel's own runtimes are multi-thread (C ABI, telemetry, pyo3 and napi), where that + /// wait moves the runtime's other tasks off the thread. Only a caller that drives the + /// kernel on its own `current_thread` runtime can be stalled by it. pub check_certificate_revocation: Option, /// With [`Self::check_certificate_revocation`] on, accept a chain whose status diff --git a/src/session.rs b/src/session.rs index 6aa66b29..e478ece1 100644 --- a/src/session.rs +++ b/src/session.rs @@ -368,12 +368,17 @@ impl Session { let http_client_config = build_http_client_config(&config, org_id); // Checked before the client-construction wrapping below, so the // configuration error keeps its InvalidArgument category. - crate::client::http::check_revocation_support(&http_client_config.tls)?; + let revocation = crate::client::http::RevocationPolicy::from_options( + config.tls.check_certificate_revocation, + config.tls.accept_undetermined_certificate_revocation, + ); + crate::client::http::check_revocation_support(&http_client_config.tls, revocation)?; let retry_configs = build_retry_configs_for_session(&config); let http_client = Arc::new( - DatabricksHttpClient::new(http_client_config, retry_configs).map_err(|e| { - Error::network_error().message(format!("Failed to construct HTTP client: {e}")) - })?, + DatabricksHttpClient::with_revocation(http_client_config, retry_configs, revocation) + .map_err(|e| { + Error::network_error().message(format!("Failed to construct HTTP client: {e}")) + })?, ); // 2. Auth provider — async because OAuth flows hit the OIDC From 1c9af8b7ed165ebbee38a511f04cb5895c4da0d0 Mon Sep 17 00:00:00 2001 From: cat23123 <58714163+cat23123@users.noreply.github.com> Date: Thu, 19 Nov 2026 21:45:16 +0000 Subject: [PATCH 07/43] fix(tls): address round-six review findings for certificate revocation - The worker lock covers only starting the worker and queuing a request. The wait for the answer happens after it is released, so concurrent verifications no longer serialize. The worker runs each request as its own task, so the fetches overlap. Test: concurrent_verifications_do_not_serialize_their_fetches. - Dropping the worker closes its request channel and waits, for no longer than the per-fetch timeout, for its thread to finish its in-flight fetches. This replaces the detached thread. Trade-off: a fetch that outlives the wait can run after the drop, so a host that unloads the library then could fault that thread. The wait keeps that window to a fetch already past its timeout. Making the worker hold no module code would need the fetch to run outside the library, which the cross-platform fetcher does not do. - A CRL URL whose host resolves to a loopback, private, link-local, unspecified, multicast or shared (CGNAT) address is not fetched, so that certificate is undetermined. Tests use a test-only allowance, which production never sets. Test: crl_hosts_on_restricted_addresses_are_refused, and restricted_addresses_cover_internal_ranges_only. - A test runs the verifier's block_in_place branch on a multi-thread runtime: a_fetch_inside_a_multi_thread_runtime_completes. Co-authored-by: Isaac Signed-off-by: cat23123 <58714163+cat23123@users.noreply.github.com> --- docs/designs/tls-config-design.md | 1 + src/client/tls_revocation.rs | 192 ++++++++++++++++++++++++----- src/client/tls_revocation_tests.rs | 98 +++++++++++++++ src/config.rs | 4 + 4 files changed, 263 insertions(+), 32 deletions(-) diff --git a/docs/designs/tls-config-design.md b/docs/designs/tls-config-design.md index dc60cd22..2e296fdb 100644 --- a/docs/designs/tls-config-design.md +++ b/docs/designs/tls-config-design.md @@ -254,6 +254,7 @@ The Rust driver uses `databricks.http.tls.*` while the C# driver uses `adbc.http ### Scope Exclusions - **Certificate revocation mode**: implemented in the kernel's tls-rustls verifier (CRL checks, opt-in, default off), not through reqwest. The ADBC `adbc.http_options.tls.revocation_mode` mapping is out of scope by the user's decision, so the ADBC driver gets no mapping. +- **Revocation and restricted addresses**: a CRL URL whose host resolves to a loopback, private, link-local, unspecified, multicast, or shared (CGNAT) address is not fetched, so the certificate is undetermined. CRL endpoints must be on public addresses. Redirects are not followed. - **Revocation and runtime flavor**: the rustls verifier is synchronous, so a handshake with revocation on waits, up to one 10 s budget per chain, for the CRLs it needs. The kernel's own runtimes are multi-thread (C ABI, telemetry, pyo3, napi). Only an external caller that drives the kernel on its own `current_thread` runtime can be stalled by that wait. - **Client certificates (mTLS)**: Not needed per current requirements. Could be added later via `reqwest::ClientBuilder::identity()`. - **TLS version pinning**: Not needed. reqwest/native-tls negotiate the highest supported version automatically. diff --git a/src/client/tls_revocation.rs b/src/client/tls_revocation.rs index 02e4c586..7fe44be7 100644 --- a/src/client/tls_revocation.rs +++ b/src/client/tls_revocation.rs @@ -92,6 +92,25 @@ thread_local! { const { std::cell::Cell::new(None) }; } +// Tests allow CRL hosts on loopback, the address of their CRL server. Production never does. +#[cfg(test)] +thread_local! { + pub(crate) static TEST_ALLOW_PRIVATE_CRL: std::cell::Cell = + const { std::cell::Cell::new(false) }; +} + +/// Whether CRL hosts in restricted address ranges are allowed for clients built here. +fn crl_private_allowed() -> bool { + #[cfg(test)] + { + TEST_ALLOW_PRIVATE_CRL.with(std::cell::Cell::get) + } + #[cfg(not(test))] + { + false + } +} + /// The CRL fetch bounds: production defaults, or a test override on this thread. fn crl_fetch_limits() -> CrlFetchLimits { #[cfg(test)] @@ -291,6 +310,8 @@ struct CrlFetcher { failed: Mutex>, /// Started on the first fetch, then reused for every chain this fetcher verifies. worker: Mutex>, + /// Whether CRL hosts in restricted address ranges are allowed. Only tests set it. + allow_private: bool, } impl CrlFetcher { @@ -307,10 +328,17 @@ impl CrlFetcher { if budget.is_zero() || self.failed_recently(url) { return None; } - let fetched = { + // The lock covers only starting the worker and queuing the request. The wait for the + // answer happens after it is released, so concurrent verifications do not serialize. + let answer = { let mut worker = self.worker.lock().unwrap_or_else(PoisonError::into_inner); if worker.is_none() { - match CrlWorker::start(self.proxy.clone(), self.limits, self.custom_roots.clone()) { + match CrlWorker::start( + self.proxy.clone(), + self.limits, + self.custom_roots.clone(), + self.allow_private, + ) { Ok(started) => *worker = Some(started), Err(reason) => { debug!("CRL worker failed to start: {reason}"); @@ -318,7 +346,15 @@ impl CrlFetcher { } } } - worker.as_ref()?.fetch(url, budget) + match worker.as_ref() { + Some(started) => started.submit(url, budget), + None => Err("CRL worker is not running".to_owned()), + } + }; + let fetched = match answer { + Ok(received) => in_runtime_blocking(|| received.recv()) + .unwrap_or_else(|_| Err("CRL worker stopped".to_owned())), + Err(reason) => Err(reason), }; let der = match fetched { Ok(der) => Arc::new(der), @@ -371,12 +407,19 @@ type CrlRequest = ( std::sync::mpsc::Sender, String>>, ); -/// The thread that runs a fetcher's CRL fetches: one current-thread runtime and one reqwest -/// client, shared by all of them. Dropping the worker closes its request channel. The -/// thread then exits once its queue is empty, and the drop does not wait for it, so it -/// cannot run past a chain's deadline. +/// The thread that runs a fetcher's CRL fetches. It has one current-thread runtime and one +/// reqwest client. Each request runs as its own task, so concurrent fetches overlap. +/// +/// Dropping the worker closes its request channel. The thread then finishes its in-flight +/// fetches, each bounded by the per-fetch timeout, and the drop waits at most that long. +/// Trade-off: if a fetch outlives the wait, the thread can still run after the drop. A +/// host that unloads this library then could fault that thread. The wait keeps that window +/// to a fetch that is already past its timeout. struct CrlWorker { - requests: std::sync::mpsc::Sender, + requests: Option>, + /// Disconnects when the thread has finished. + exited: std::sync::mpsc::Receiver<()>, + timeout: Duration, } impl std::fmt::Debug for CrlWorker { @@ -390,46 +433,130 @@ impl CrlWorker { proxy: ProxyConfig, limits: CrlFetchLimits, roots: Vec, + allow_private: bool, ) -> std::io::Result { - let (requests, inbox) = std::sync::mpsc::channel::(); - // The JoinHandle is dropped, which detaches the thread. + let (requests, mut inbox) = tokio::sync::mpsc::unbounded_channel::(); + let (exit_signal, exited) = std::sync::mpsc::channel::<()>(); std::thread::Builder::new() .name("databricks-crl".to_owned()) .stack_size(runtime_thread_stack_size(ambient_rust_min_stack())) .spawn(move || { + // Dropped when the thread ends, which disconnects `exited`. + let _exit_signal = exit_signal; // The caller's runtime is never re-entered, so a current-thread caller // cannot deadlock. - let runtime = tokio::runtime::Builder::new_current_thread() + let Ok(runtime) = tokio::runtime::Builder::new_current_thread() .enable_all() - .build(); + .build() + else { + return; + }; let client = build_client(&proxy, limits, &roots); - for (url, budget, answer) in inbox { - let result = match (&runtime, &client) { - (Ok(runtime), Ok(client)) => { - runtime.block_on(fetch(client, &url, limits.max_bytes, budget)) - } - (Err(e), _) => Err(e.to_string()), - (_, Err(e)) => Err(e.clone()), - }; - let _ = answer.send(result); - } + runtime.block_on(async move { + while let Some((url, budget, answer)) = inbox.recv().await { + let client = client.clone(); + tokio::spawn(async move { + let result = match client { + Ok(client) => match check_host(&url, allow_private).await { + Ok(()) => fetch(&client, &url, limits.max_bytes, budget).await, + Err(reason) => Err(reason), + }, + Err(reason) => Err(reason), + }; + let _ = answer.send(result); + }); + } + }); })?; - Ok(Self { requests }) + Ok(Self { + requests: Some(requests), + exited, + timeout: limits.timeout, + }) } - /// Runs one fetch on the worker and waits for its answer. The wait is bounded by - /// `budget`, because the fetch itself is. - fn fetch(&self, url: &str, budget: Duration) -> std::result::Result, String> { + /// Queues one fetch. This does not wait for it, so the caller can release any lock + /// before it waits on the returned receiver. + fn submit( + &self, + url: &str, + budget: Duration, + ) -> std::result::Result, String>>, String> + { let (answer, received) = std::sync::mpsc::channel(); - if self + let requests = self .requests + .as_ref() + .ok_or_else(|| "CRL worker is closed".to_owned())?; + requests .send((url.to_owned(), budget, answer)) - .is_err() - { - return Err("CRL worker is not running".to_owned()); + .map_err(|_| "CRL worker is not running".to_owned())?; + Ok(received) + } +} + +impl Drop for CrlWorker { + fn drop(&mut self) { + // Closing the channel ends the worker once its in-flight fetches finish. Wait for + // that, but no longer than the per-fetch timeout. + self.requests.take(); + let _ = in_runtime_blocking(|| self.exited.recv_timeout(self.timeout)); + } +} + +/// Refuses a CRL URL whose host resolves to a loopback, private, link-local, unspecified, +/// broadcast, multicast or shared (CGNAT) address. A certificate chained to a trusted CA +/// otherwise could point the fetch at an internal endpoint. `allow_private` is set only by +/// tests. +async fn check_host(url: &str, allow_private: bool) -> std::result::Result<(), String> { + if allow_private { + return Ok(()); + } + let parsed = reqwest::Url::parse(url).map_err(|e| e.to_string())?; + let host = parsed + .host_str() + .ok_or_else(|| "CRL URL has no host".to_owned())?; + let port = parsed + .port_or_known_default() + .ok_or_else(|| "CRL URL has no port".to_owned())?; + let bare = host.trim_start_matches('[').trim_end_matches(']'); + let addresses = tokio::net::lookup_host((bare, port)) + .await + .map_err(|e| e.to_string())?; + for address in addresses { + if restricted_address(address.ip()) { + return Err(format!( + "CRL host {host} resolves to a restricted address {}", + address.ip() + )); + } + } + Ok(()) +} + +fn restricted_address(ip: std::net::IpAddr) -> bool { + match ip { + std::net::IpAddr::V4(v4) => { + let [a, b, _, _] = v4.octets(); + v4.is_loopback() + || v4.is_private() + || v4.is_link_local() + || v4.is_unspecified() + || v4.is_broadcast() + || v4.is_multicast() + || (a == 100 && (b & 0xC0) == 64) + } + std::net::IpAddr::V6(v6) => { + let first = v6.segments()[0]; + v6.is_loopback() + || v6.is_unspecified() + || v6.is_multicast() + || (first & 0xfe00) == 0xfc00 + || (first & 0xffc0) == 0xfe80 + || v6 + .to_ipv4_mapped() + .is_some_and(|v4| restricted_address(std::net::IpAddr::V4(v4))) } - in_runtime_blocking(|| received.recv()) - .unwrap_or_else(|_| Err("CRL worker stopped".to_owned())) } } @@ -813,6 +940,7 @@ pub(crate) fn client_config( cache: Mutex::new(HashMap::new()), failed: Mutex::new(HashMap::new()), worker: Mutex::new(None), + allow_private: crl_private_allowed(), }, accept_undetermined, allow_hostname_mismatch: tls.allow_hostname_mismatch.unwrap_or(false), diff --git a/src/client/tls_revocation_tests.rs b/src/client/tls_revocation_tests.rs index 5277c265..a527152b 100644 --- a/src/client/tls_revocation_tests.rs +++ b/src/client/tls_revocation_tests.rs @@ -65,6 +65,8 @@ enum Served { Oversize, /// Distribution point is a closed port. Refused, + /// A usable CRL that arrives after half a second. + Slow, /// Distribution point is not http(s), so there is nothing to fetch. NonHttp, /// Distribution point is indirect (has a cRLIssuer), so it must be skipped. @@ -397,6 +399,11 @@ fn route( body: Vec::new(), delay: Duration::ZERO, }, + Served::Slow => Route { + status: 200, + body: sign_crl(issuer, &[], CURRENT), + delay: Duration::from_millis(500), + }, Served::Timeout => Route { status: 200, body: sign_crl(issuer, &[], CURRENT), @@ -777,6 +784,8 @@ fn policy(accept_undetermined: bool) -> Option { fn revocation_config(root_pem: &str) -> HttpClientConfig { let mut config = HttpClientConfig::default(); config.tls.trusted_certificate_pem = Some(root_pem.as_bytes().to_vec()); + // The CRL server listens on loopback. Only the address-restriction test turns this off. + TEST_ALLOW_PRIVATE_CRL.with(|allowed| allowed.set(true)); set_fetch_limits(CrlFetchLimits { timeout: Duration::from_millis(500), max_bytes: 64 * 1024, @@ -1191,6 +1200,7 @@ fn intermediate_cap_allows_six_and_rejects_seven() { cache: Mutex::new(HashMap::new()), failed: Mutex::new(HashMap::new()), worker: Mutex::new(None), + allow_private: true, }, accept_undetermined: false, allow_hostname_mismatch: false, @@ -1423,6 +1433,94 @@ fn crl_cache_drops_expired_entries_and_stays_within_its_caps() { assert!(!big.contains_key("big0")); } +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn concurrent_verifications_do_not_serialize_their_fetches() { + // Two handshakes verify at once, and each needs the same slow CRL. Serialized fetches + // take two half-second waits. Overlapping fetches take about one. + let fx = fixture(Some(Served::Slow), Served::Good, "127.0.0.1"); + let config = revocation_config(&fx.pki.root_pem); + set_fetch_limits(CrlFetchLimits { + timeout: Duration::from_millis(2000), + max_bytes: 64 * 1024, + }); + let http = client(config, policy(false)); + let url = format!("https://{}/", fx.addr); + let started = Instant::now(); + let first = tokio::spawn({ + let inner = http.inner().clone(); + let url = url.clone(); + async move { inner.get(url).send().await.map(|_| ()) } + }); + let second = tokio::spawn({ + let inner = http.inner().clone(); + async move { inner.get(url).send().await.map(|_| ()) } + }); + first.await.unwrap().expect("first verification passes"); + second.await.unwrap().expect("second verification passes"); + let elapsed = started.elapsed(); + assert!( + elapsed < Duration::from_millis(900), + "the two verifications' fetches serialized: {elapsed:?}" + ); +} + +#[tokio::test] +async fn crl_hosts_on_restricted_addresses_are_refused() { + // The CRL server is on loopback, a restricted address. With the test allowance off, the + // fetch is refused, so the leaf is undetermined: strict rejects, and nothing is requested. + let fx = fixture(Some(Served::Good), Served::Good, "127.0.0.1"); + let config = revocation_config(&fx.pki.root_pem); + TEST_ALLOW_PRIVATE_CRL.with(|allowed| allowed.set(false)); + let err = get(config, policy(false), fx.addr) + .await + .expect_err("a loopback CRL host is refused"); + assert!(err.contains(UNDETERMINED), "{err}"); + assert_eq!( + fx.crl.hits("/leaf.crl"), + 0, + "a refused host is never requested" + ); +} + +#[test] +fn restricted_addresses_cover_internal_ranges_only() { + for restricted in [ + "127.0.0.1", + "10.1.2.3", + "172.16.0.9", + "192.168.1.1", + "169.254.169.254", + "0.0.0.0", + "100.64.0.1", + "::1", + "fe80::1", + "fc00::1", + "::ffff:169.254.169.254", + ] { + assert!( + restricted_address(restricted.parse().unwrap()), + "{restricted} is restricted" + ); + } + for public in ["8.8.8.8", "203.0.113.7", "2606:4700:4700::1111"] { + assert!( + !restricted_address(public.parse().unwrap()), + "{public} is public" + ); + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn a_fetch_inside_a_multi_thread_runtime_completes() { + // The verifier waits for its CRL inside `block_in_place` on a multi-thread runtime. No + // other test runs that branch. + let fx = fixture(Some(Served::Good), Served::Good, "127.0.0.1"); + get(revocation_config(&fx.pki.root_pem), policy(false), fx.addr) + .await + .expect("good chain"); + assert_eq!(fx.crl.hits("/leaf.crl"), 1); +} + #[test] fn verifier_errors_are_certificate_verification_failures() { let error = verifier_error("the server presented 7 intermediates".to_owned()); diff --git a/src/config.rs b/src/config.rs index dd98f016..a0a50ad2 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1047,6 +1047,10 @@ pub struct TlsConfig { /// the `tls-rustls` backend; `tls-native` fails session open with /// `InvalidArgument`. Disabled by [`Self::accept_self_signed`]. /// + /// A CRL URL whose host resolves to a loopback, private, link-local or shared address + /// is not fetched, so that certificate is undetermined. Put CRL endpoints on public + /// addresses. + /// /// Each handshake waits, up to a 10 s budget per chain, for the CRLs it needs. The /// kernel's own runtimes are multi-thread (C ABI, telemetry, pyo3 and napi), where that /// wait moves the runtime's other tasks off the thread. Only a caller that drives the From 55dd9d53fd765ca21623ad7a228f4f87d29b36e3 Mon Sep 17 00:00:00 2001 From: cat23123 <58714163+cat23123@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:15:48 +0000 Subject: [PATCH 08/43] fix(tls): remove the CRL host guard and document the remaining limits - Removes the restricted-address check on CRL hosts, its DNS pre-resolution, and its tests. CRL URLs come from certificates that chain to a trusted CA and are fetched without destination filtering, as the C#, JDBC and Simba drivers do. This is documented as a residual limitation. - Keeps redirects disabled: a 3xx is undetermined. - Keeps the worker lock released before the wait, the bounded drop, and the multi-thread test. - Documents that a fetch already past its per-fetch timeout can outlive the bounded wait at drop, and that unloading the host library during that window is unsupported. Co-authored-by: Isaac Signed-off-by: cat23123 <58714163+cat23123@users.noreply.github.com> --- docs/designs/tls-config-design.md | 3 +- src/client/tls_revocation.rs | 95 ++---------------------------- src/client/tls_revocation_tests.rs | 49 --------------- src/config.rs | 5 +- 4 files changed, 10 insertions(+), 142 deletions(-) diff --git a/docs/designs/tls-config-design.md b/docs/designs/tls-config-design.md index 2e296fdb..3991e71d 100644 --- a/docs/designs/tls-config-design.md +++ b/docs/designs/tls-config-design.md @@ -254,7 +254,8 @@ The Rust driver uses `databricks.http.tls.*` while the C# driver uses `adbc.http ### Scope Exclusions - **Certificate revocation mode**: implemented in the kernel's tls-rustls verifier (CRL checks, opt-in, default off), not through reqwest. The ADBC `adbc.http_options.tls.revocation_mode` mapping is out of scope by the user's decision, so the ADBC driver gets no mapping. -- **Revocation and restricted addresses**: a CRL URL whose host resolves to a loopback, private, link-local, unspecified, multicast, or shared (CGNAT) address is not fetched, so the certificate is undetermined. CRL endpoints must be on public addresses. Redirects are not followed. +- **Revocation and CRL destinations**: redirects are not followed, so a 3xx is undetermined. CRL distribution-point URLs come from certificates that chain to a trusted CA, and the kernel fetches them without destination filtering. This is a known residual limitation. +- **Revocation and drop**: dropping the CRL worker waits at most one per-fetch timeout for its thread. A fetch already past that timeout can outlive the wait and keep running after the drop. Unloading the host library during that window is unsupported. - **Revocation and runtime flavor**: the rustls verifier is synchronous, so a handshake with revocation on waits, up to one 10 s budget per chain, for the CRLs it needs. The kernel's own runtimes are multi-thread (C ABI, telemetry, pyo3, napi). Only an external caller that drives the kernel on its own `current_thread` runtime can be stalled by that wait. - **Client certificates (mTLS)**: Not needed per current requirements. Could be added later via `reqwest::ClientBuilder::identity()`. - **TLS version pinning**: Not needed. reqwest/native-tls negotiate the highest supported version automatically. diff --git a/src/client/tls_revocation.rs b/src/client/tls_revocation.rs index 7fe44be7..8deb00f9 100644 --- a/src/client/tls_revocation.rs +++ b/src/client/tls_revocation.rs @@ -92,25 +92,6 @@ thread_local! { const { std::cell::Cell::new(None) }; } -// Tests allow CRL hosts on loopback, the address of their CRL server. Production never does. -#[cfg(test)] -thread_local! { - pub(crate) static TEST_ALLOW_PRIVATE_CRL: std::cell::Cell = - const { std::cell::Cell::new(false) }; -} - -/// Whether CRL hosts in restricted address ranges are allowed for clients built here. -fn crl_private_allowed() -> bool { - #[cfg(test)] - { - TEST_ALLOW_PRIVATE_CRL.with(std::cell::Cell::get) - } - #[cfg(not(test))] - { - false - } -} - /// The CRL fetch bounds: production defaults, or a test override on this thread. fn crl_fetch_limits() -> CrlFetchLimits { #[cfg(test)] @@ -310,8 +291,6 @@ struct CrlFetcher { failed: Mutex>, /// Started on the first fetch, then reused for every chain this fetcher verifies. worker: Mutex>, - /// Whether CRL hosts in restricted address ranges are allowed. Only tests set it. - allow_private: bool, } impl CrlFetcher { @@ -333,12 +312,7 @@ impl CrlFetcher { let answer = { let mut worker = self.worker.lock().unwrap_or_else(PoisonError::into_inner); if worker.is_none() { - match CrlWorker::start( - self.proxy.clone(), - self.limits, - self.custom_roots.clone(), - self.allow_private, - ) { + match CrlWorker::start(self.proxy.clone(), self.limits, self.custom_roots.clone()) { Ok(started) => *worker = Some(started), Err(reason) => { debug!("CRL worker failed to start: {reason}"); @@ -433,7 +407,6 @@ impl CrlWorker { proxy: ProxyConfig, limits: CrlFetchLimits, roots: Vec, - allow_private: bool, ) -> std::io::Result { let (requests, mut inbox) = tokio::sync::mpsc::unbounded_channel::(); let (exit_signal, exited) = std::sync::mpsc::channel::<()>(); @@ -457,10 +430,7 @@ impl CrlWorker { let client = client.clone(); tokio::spawn(async move { let result = match client { - Ok(client) => match check_host(&url, allow_private).await { - Ok(()) => fetch(&client, &url, limits.max_bytes, budget).await, - Err(reason) => Err(reason), - }, + Ok(client) => fetch(&client, &url, limits.max_bytes, budget).await, Err(reason) => Err(reason), }; let _ = answer.send(result); @@ -499,67 +469,15 @@ impl Drop for CrlWorker { fn drop(&mut self) { // Closing the channel ends the worker once its in-flight fetches finish. Wait for // that, but no longer than the per-fetch timeout. + // + // Residual window: a fetch already past its per-fetch timeout can outlive this + // bounded wait. The thread then keeps running after the drop. Unloading the host + // library during that window is unsupported. self.requests.take(); let _ = in_runtime_blocking(|| self.exited.recv_timeout(self.timeout)); } } -/// Refuses a CRL URL whose host resolves to a loopback, private, link-local, unspecified, -/// broadcast, multicast or shared (CGNAT) address. A certificate chained to a trusted CA -/// otherwise could point the fetch at an internal endpoint. `allow_private` is set only by -/// tests. -async fn check_host(url: &str, allow_private: bool) -> std::result::Result<(), String> { - if allow_private { - return Ok(()); - } - let parsed = reqwest::Url::parse(url).map_err(|e| e.to_string())?; - let host = parsed - .host_str() - .ok_or_else(|| "CRL URL has no host".to_owned())?; - let port = parsed - .port_or_known_default() - .ok_or_else(|| "CRL URL has no port".to_owned())?; - let bare = host.trim_start_matches('[').trim_end_matches(']'); - let addresses = tokio::net::lookup_host((bare, port)) - .await - .map_err(|e| e.to_string())?; - for address in addresses { - if restricted_address(address.ip()) { - return Err(format!( - "CRL host {host} resolves to a restricted address {}", - address.ip() - )); - } - } - Ok(()) -} - -fn restricted_address(ip: std::net::IpAddr) -> bool { - match ip { - std::net::IpAddr::V4(v4) => { - let [a, b, _, _] = v4.octets(); - v4.is_loopback() - || v4.is_private() - || v4.is_link_local() - || v4.is_unspecified() - || v4.is_broadcast() - || v4.is_multicast() - || (a == 100 && (b & 0xC0) == 64) - } - std::net::IpAddr::V6(v6) => { - let first = v6.segments()[0]; - v6.is_loopback() - || v6.is_unspecified() - || v6.is_multicast() - || (first & 0xfe00) == 0xfc00 - || (first & 0xffc0) == 0xfe80 - || v6 - .to_ipv4_mapped() - .is_some_and(|v4| restricted_address(std::net::IpAddr::V4(v4))) - } - } -} - /// Runs a blocking wait. On a multi-thread runtime, block_in_place moves the worker's /// other tasks to another thread first. It panics on current_thread, so the wait runs as /// it is there. @@ -940,7 +858,6 @@ pub(crate) fn client_config( cache: Mutex::new(HashMap::new()), failed: Mutex::new(HashMap::new()), worker: Mutex::new(None), - allow_private: crl_private_allowed(), }, accept_undetermined, allow_hostname_mismatch: tls.allow_hostname_mismatch.unwrap_or(false), diff --git a/src/client/tls_revocation_tests.rs b/src/client/tls_revocation_tests.rs index a527152b..2b06b488 100644 --- a/src/client/tls_revocation_tests.rs +++ b/src/client/tls_revocation_tests.rs @@ -784,8 +784,6 @@ fn policy(accept_undetermined: bool) -> Option { fn revocation_config(root_pem: &str) -> HttpClientConfig { let mut config = HttpClientConfig::default(); config.tls.trusted_certificate_pem = Some(root_pem.as_bytes().to_vec()); - // The CRL server listens on loopback. Only the address-restriction test turns this off. - TEST_ALLOW_PRIVATE_CRL.with(|allowed| allowed.set(true)); set_fetch_limits(CrlFetchLimits { timeout: Duration::from_millis(500), max_bytes: 64 * 1024, @@ -1200,7 +1198,6 @@ fn intermediate_cap_allows_six_and_rejects_seven() { cache: Mutex::new(HashMap::new()), failed: Mutex::new(HashMap::new()), worker: Mutex::new(None), - allow_private: true, }, accept_undetermined: false, allow_hostname_mismatch: false, @@ -1464,52 +1461,6 @@ async fn concurrent_verifications_do_not_serialize_their_fetches() { ); } -#[tokio::test] -async fn crl_hosts_on_restricted_addresses_are_refused() { - // The CRL server is on loopback, a restricted address. With the test allowance off, the - // fetch is refused, so the leaf is undetermined: strict rejects, and nothing is requested. - let fx = fixture(Some(Served::Good), Served::Good, "127.0.0.1"); - let config = revocation_config(&fx.pki.root_pem); - TEST_ALLOW_PRIVATE_CRL.with(|allowed| allowed.set(false)); - let err = get(config, policy(false), fx.addr) - .await - .expect_err("a loopback CRL host is refused"); - assert!(err.contains(UNDETERMINED), "{err}"); - assert_eq!( - fx.crl.hits("/leaf.crl"), - 0, - "a refused host is never requested" - ); -} - -#[test] -fn restricted_addresses_cover_internal_ranges_only() { - for restricted in [ - "127.0.0.1", - "10.1.2.3", - "172.16.0.9", - "192.168.1.1", - "169.254.169.254", - "0.0.0.0", - "100.64.0.1", - "::1", - "fe80::1", - "fc00::1", - "::ffff:169.254.169.254", - ] { - assert!( - restricted_address(restricted.parse().unwrap()), - "{restricted} is restricted" - ); - } - for public in ["8.8.8.8", "203.0.113.7", "2606:4700:4700::1111"] { - assert!( - !restricted_address(public.parse().unwrap()), - "{public} is public" - ); - } -} - #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn a_fetch_inside_a_multi_thread_runtime_completes() { // The verifier waits for its CRL inside `block_in_place` on a multi-thread runtime. No diff --git a/src/config.rs b/src/config.rs index a0a50ad2..d60e542b 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1047,9 +1047,8 @@ pub struct TlsConfig { /// the `tls-rustls` backend; `tls-native` fails session open with /// `InvalidArgument`. Disabled by [`Self::accept_self_signed`]. /// - /// A CRL URL whose host resolves to a loopback, private, link-local or shared address - /// is not fetched, so that certificate is undetermined. Put CRL endpoints on public - /// addresses. + /// CRL distribution-point URLs come from certificates that chain to a trusted CA, and the + /// kernel fetches them without destination filtering. /// /// Each handshake waits, up to a 10 s budget per chain, for the CRLs it needs. The /// kernel's own runtimes are multi-thread (C ABI, telemetry, pyo3 and napi), where that From 6bb5dc41eab4456b1a0591f17a67e04ccee0a0f9 Mon Sep 17 00:00:00 2001 From: cat23123 <58714163+cat23123@users.noreply.github.com> Date: Thu, 19 Nov 2026 23:10:50 +0000 Subject: [PATCH 09/43] fix(tls): pin the kernel module while the CRL worker can run The CRL worker thread can keep running for a fetch that outlives the bounded drop wait. A host that unloads the library in that window could fault the thread. Pin the module once, when the first CRL worker starts: - Windows: GetModuleHandleExW with FROM_ADDRESS | PIN on a function in this crate. - Unix: dladdr to find the object, then dlopen with RTLD_NOW | RTLD_NOLOAD | RTLD_NODELETE. The handle is not closed. A failed pin is logged at debug and the connection proceeds as before. Once revocation is first used, the library stays loaded for the rest of the process. The new dependencies are target-specific (windows-sys 0.61 and libc 0.2), and both are already in the lock file. Co-authored-by: Isaac Signed-off-by: cat23123 <58714163+cat23123@users.noreply.github.com> --- Cargo.lock | 2 + Cargo.toml | 9 +++ docs/designs/tls-config-design.md | 2 +- src/client/tls_revocation.rs | 117 ++++++++++++++++++++++++++++-- 4 files changed, 123 insertions(+), 7 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 732b6f83..8246c9cb 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -665,6 +665,7 @@ dependencies = [ "hex", "hmac 0.13.0", "jsonwebtoken", + "libc", "log", "lz4_flex", "moka", @@ -692,6 +693,7 @@ dependencies = [ "tracing", "tracing-subscriber", "webpki-roots", + "windows-sys 0.61.2", "wiremock", "wkb", "wkt", diff --git a/Cargo.toml b/Cargo.toml index e07eb921..c4192589 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -151,6 +151,15 @@ zeroize = "1.9" jsonwebtoken = { version = "9", default-features = false, features = ["use_pem"] } # JWT signing (RS256/384/512, PS256/384/512, ES256/384); use_pem = PEM key loading (adds pem + simple_asn1, no TLS) pkcs8 = { version = "0.10", features = ["encryption", "pem", "std"] } # PKCS#8 PEM parsing + PBES2 passphrase decryption +# Pins the module that holds the kernel while the CRL worker thread may still run its +# code (see `pin_crate_module` in `src/client/tls_revocation.rs`). Both crates are already +# in the graph; these target-specific entries add no new crates. +[target.'cfg(windows)'.dependencies] +windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_System_LibraryLoader"] } + +[target.'cfg(unix)'.dependencies] +libc = "0.2" + [dev-dependencies] tokio = { version = "1", features = ["rt-multi-thread", "macros", "net", "io-util"] } wiremock = "0.6" diff --git a/docs/designs/tls-config-design.md b/docs/designs/tls-config-design.md index 3991e71d..72eae659 100644 --- a/docs/designs/tls-config-design.md +++ b/docs/designs/tls-config-design.md @@ -255,7 +255,7 @@ The Rust driver uses `databricks.http.tls.*` while the C# driver uses `adbc.http - **Certificate revocation mode**: implemented in the kernel's tls-rustls verifier (CRL checks, opt-in, default off), not through reqwest. The ADBC `adbc.http_options.tls.revocation_mode` mapping is out of scope by the user's decision, so the ADBC driver gets no mapping. - **Revocation and CRL destinations**: redirects are not followed, so a 3xx is undetermined. CRL distribution-point URLs come from certificates that chain to a trusted CA, and the kernel fetches them without destination filtering. This is a known residual limitation. -- **Revocation and drop**: dropping the CRL worker waits at most one per-fetch timeout for its thread. A fetch already past that timeout can outlive the wait and keep running after the drop. Unloading the host library during that window is unsupported. +- **Revocation and drop**: dropping the CRL worker waits at most one per-fetch timeout for its thread. A fetch already past that timeout can outlive the wait and keep running after the drop. The kernel pins its own module when the first CRL worker starts, once per process: `GetModuleHandleExW` with `FROM_ADDRESS | PIN` on Windows, and `dladdr` followed by `dlopen(RTLD_NOW | RTLD_NOLOAD | RTLD_NODELETE)` on Unix. A pinned module is never unmapped, so the residual window is closed while the library is pinned. Trade-off: once revocation is first used, the library stays loaded for the rest of the process, even after the host unloads it. If the pin fails, the failure is logged at debug and the connection proceeds as before, so the window remains in that case. - **Revocation and runtime flavor**: the rustls verifier is synchronous, so a handshake with revocation on waits, up to one 10 s budget per chain, for the CRLs it needs. The kernel's own runtimes are multi-thread (C ABI, telemetry, pyo3, napi). Only an external caller that drives the kernel on its own `current_thread` runtime can be stalled by that wait. - **Client certificates (mTLS)**: Not needed per current requirements. Could be added later via `reqwest::ClientBuilder::identity()`. - **TLS version pinning**: Not needed. reqwest/native-tls negotiate the highest supported version automatically. diff --git a/src/client/tls_revocation.rs b/src/client/tls_revocation.rs index 8deb00f9..8234498b 100644 --- a/src/client/tls_revocation.rs +++ b/src/client/tls_revocation.rs @@ -386,9 +386,9 @@ type CrlRequest = ( /// /// Dropping the worker closes its request channel. The thread then finishes its in-flight /// fetches, each bounded by the per-fetch timeout, and the drop waits at most that long. -/// Trade-off: if a fetch outlives the wait, the thread can still run after the drop. A -/// host that unloads this library then could fault that thread. The wait keeps that window -/// to a fetch that is already past its timeout. +/// The module is pinned before the thread starts (see [`pin_crate_module_once`]), so a host +/// that unloads this library cannot unmap the thread's code, even when a fetch outlives +/// that wait. struct CrlWorker { requests: Option>, /// Disconnects when the thread has finished. @@ -408,6 +408,8 @@ impl CrlWorker { limits: CrlFetchLimits, roots: Vec, ) -> std::io::Result { + // Pin before the thread exists, so the host cannot unmap this code once it runs. + pin_crate_module_once(); let (requests, mut inbox) = tokio::sync::mpsc::unbounded_channel::(); let (exit_signal, exited) = std::sync::mpsc::channel::<()>(); std::thread::Builder::new() @@ -470,14 +472,117 @@ impl Drop for CrlWorker { // Closing the channel ends the worker once its in-flight fetches finish. Wait for // that, but no longer than the per-fetch timeout. // - // Residual window: a fetch already past its per-fetch timeout can outlive this - // bounded wait. The thread then keeps running after the drop. Unloading the host - // library during that window is unsupported. + // A fetch already past its per-fetch timeout can outlive this bounded wait, and the + // thread then keeps running after the drop. The library was pinned when the worker + // started, so the host cannot unmap that code while the thread runs. Once revocation + // is first used, the library therefore stays loaded for the rest of the process. self.requests.take(); let _ = in_runtime_blocking(|| self.exited.recv_timeout(self.timeout)); } } +/// Pins the module that holds this crate, at most once per process, when the first CRL +/// worker starts. A pinned module is never unmapped, so a host that unloads the library +/// (an ODBC driver manager, or a napi addon's worker) cannot fault a CRL thread that is +/// still running. A failed pin is logged at debug and changes nothing else: the connection +/// proceeds as it did before pinning existed. +fn pin_crate_module_once() { + static PINNED: std::sync::Once = std::sync::Once::new(); + PINNED.call_once(|| { + if let Err(reason) = pin_crate_module() { + debug!("could not pin the kernel module for the CRL worker: {reason}"); + } + }); +} + +/// Windows: `GetModuleHandleExW` with `FROM_ADDRESS | PIN` on the address of a function in +/// this crate. The pinned handle is deliberately never released. +#[cfg(windows)] +fn pin_crate_module() -> std::result::Result<(), String> { + use windows_sys::Win32::Foundation::HMODULE; + use windows_sys::Win32::System::LibraryLoader::{ + GetModuleHandleExW, GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, GET_MODULE_HANDLE_EX_FLAG_PIN, + }; + let mut module: HMODULE = std::ptr::null_mut(); + // SAFETY: with FROM_ADDRESS, the name argument is a code address rather than a string. + // It is the address of `pin_crate_module`, which lives in this crate, and `module` is a + // valid out-pointer. + let found = unsafe { + GetModuleHandleExW( + GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_PIN, + pin_crate_module as *const () as usize as *const u16, + &mut module, + ) + }; + if found == 0 { + return Err(format!( + "GetModuleHandleExW failed: {}", + std::io::Error::last_os_error() + )); + } + Ok(()) +} + +/// Unix: `dladdr` finds the object that holds a function in this crate, then `dlopen` with +/// `RTLD_NOLOAD` reopens that object without loading it again. `RTLD_NODELETE` makes a later +/// `dlclose` a no-op, so the object is never unmapped. The handle is deliberately not closed. +#[cfg(unix)] +fn pin_crate_module() -> std::result::Result<(), String> { + use std::os::unix::ffi::OsStrExt; + + // SAFETY: `Dl_info` is plain data, and dladdr writes it only on success. + let mut info: libc::Dl_info = unsafe { std::mem::zeroed() }; + let address = pin_crate_module as *const () as *const libc::c_void; + // SAFETY: `address` is a code address in this process, and `info` is valid for writes. + if unsafe { libc::dladdr(address, &mut info) } == 0 || info.dli_fname.is_null() { + return Err("dladdr found no object for the kernel's code".to_owned()); + } + // SAFETY: `dli_fname` is a NUL-terminated path from dladdr, valid for this call. + let path = unsafe { std::ffi::CStr::from_ptr(info.dli_fname) }; + let path = std::path::Path::new(std::ffi::OsStr::from_bytes(path.to_bytes())); + // A program that holds the kernel is the main executable, which the host cannot unload. + // dladdr names it by argv[0], and RTLD_NOLOAD cannot reopen it by that name. + if let (Ok(object), Ok(exe)) = ( + std::fs::canonicalize(path), + std::env::current_exe().and_then(std::fs::canonicalize), + ) { + if object == exe { + return Ok(()); + } + } + // The flags request the already-loaded object only, and RTLD_NODELETE pins it. + let handle = unsafe { + libc::dlopen( + info.dli_fname, + libc::RTLD_NOW | libc::RTLD_NOLOAD | libc::RTLD_NODELETE, + ) + }; + if handle.is_null() { + // SAFETY: dlerror returns a NUL-terminated message, or null when there is none. + let detail = unsafe { libc::dlerror() }; + let detail = if detail.is_null() { + "no detail".to_owned() + } else { + // SAFETY: checked non-null above; the message is read before any other dl call. + unsafe { std::ffi::CStr::from_ptr(detail) } + .to_string_lossy() + .into_owned() + }; + return Err(format!("dlopen failed: {detail}")); + } + Ok(()) +} + +#[cfg(all(test, target_os = "linux"))] +mod pin_tests { + use super::*; + + #[test] + fn crate_module_pin_succeeds_on_linux() { + assert_eq!(pin_crate_module(), Ok(())); + } +} + /// Runs a blocking wait. On a multi-thread runtime, block_in_place moves the worker's /// other tasks to another thread first. It panics on current_thread, so the wait runs as /// it is there. From 212dfe999b47493cac4481fad79835af90356156 Mon Sep 17 00:00:00 2001 From: cat23123 <58714163+cat23123@users.noreply.github.com> Date: Thu, 19 Nov 2026 23:24:49 +0000 Subject: [PATCH 10/43] chore(deps): refresh napi, pyo3 and adbc lockfiles for the module pin The module-pin commit added libc (unix) and windows-sys (windows) as target-specific kernel dependencies. Both crates were already in the dependency graph, but the standalone napi, pyo3 and adbc lockfiles didn't list the new edges, so `cargo metadata --locked` failed in those workspaces. This adds only the two dependency edges to each lockfile. There are no new packages and no version changes, and all three pass with `--locked`. Co-authored-by: Isaac Signed-off-by: cat23123 <58714163+cat23123@users.noreply.github.com> --- adbc/Cargo.lock | 2 ++ napi/Cargo.lock | 2 ++ pyo3/Cargo.lock | 2 ++ 3 files changed, 6 insertions(+) diff --git a/adbc/Cargo.lock b/adbc/Cargo.lock index 37956eeb..12b07152 100644 --- a/adbc/Cargo.lock +++ b/adbc/Cargo.lock @@ -666,6 +666,7 @@ dependencies = [ "hex", "hmac 0.13.0", "jsonwebtoken", + "libc", "lz4_flex", "moka", "native-tls", @@ -683,6 +684,7 @@ dependencies = [ "tokio-util", "tracing", "tracing-subscriber", + "windows-sys 0.61.2", "wkb", "wkt", "zeroize", diff --git a/napi/Cargo.lock b/napi/Cargo.lock index 134888ac..4693a172 100644 --- a/napi/Cargo.lock +++ b/napi/Cargo.lock @@ -626,6 +626,7 @@ dependencies = [ "hex", "hmac 0.13.0", "jsonwebtoken", + "libc", "lz4_flex", "moka", "oauth2", @@ -646,6 +647,7 @@ dependencies = [ "tracing", "tracing-subscriber", "webpki-roots", + "windows-sys 0.61.2", "wkb", "wkt", "zeroize", diff --git a/pyo3/Cargo.lock b/pyo3/Cargo.lock index b8a2c445..cea0c648 100644 --- a/pyo3/Cargo.lock +++ b/pyo3/Cargo.lock @@ -622,6 +622,7 @@ dependencies = [ "hex", "hmac 0.13.0", "jsonwebtoken", + "libc", "lz4_flex", "moka", "oauth2", @@ -642,6 +643,7 @@ dependencies = [ "tracing", "tracing-subscriber", "webpki-roots", + "windows-sys 0.61.2", "wkb", "wkt", "zeroize", From 46574b5fb1fdfb171dc3d58d860a0b67cb891e06 Mon Sep 17 00:00:00 2001 From: cat23123 <58714163+cat23123@users.noreply.github.com> Date: Fri, 20 Nov 2026 01:12:51 +0000 Subject: [PATCH 11/43] refactor(bindings): remove TLS revocation from pyo3 and napi Revert the pyo3 and napi revocation bindings and their changelog lines. The Rust config fields and the C ABI setter stay. The revocation design is being replaced by a Windows-only CryptoAPI check, and the bindings will not expose a setting that is not available on every platform. Co-authored-by: Isaac Signed-off-by: cat23123 <58714163+cat23123@users.noreply.github.com> --- napi/NEXT_CHANGELOG.md | 2 -- napi/index.d.ts | 14 -------------- napi/src/database.rs | 34 ---------------------------------- pyo3/NEXT_CHANGELOG.md | 2 -- pyo3/src/session.rs | 12 ------------ pyo3/tests/test_session.py | 20 -------------------- 6 files changed, 84 deletions(-) diff --git a/napi/NEXT_CHANGELOG.md b/napi/NEXT_CHANGELOG.md index 29b2a7c5..d5ca462e 100644 --- a/napi/NEXT_CHANGELOG.md +++ b/napi/NEXT_CHANGELOG.md @@ -14,8 +14,6 @@ layout, or npm publishing. Pure-kernel changes go in the root ### Added -- `ConnectionOptions` accepts `checkCertificateRevocation` and `acceptUndeterminedRevocation` (both default off) to check the server chain's CRLs. Needs the `tls-rustls` kernel build, which this package uses. - ### Changed ### Updated diff --git a/napi/index.d.ts b/napi/index.d.ts index e92eeb90..064f856d 100644 --- a/napi/index.d.ts +++ b/napi/index.d.ts @@ -490,20 +490,6 @@ export interface ConnectionOptions { * Maps onto the kernel [`TlsConfig::client_key_pem`]. */ clientKeyPem?: Buffer - /** - * Check the server certificate chain's CRLs before connecting. Omitted - * / `false` ⇒ off. Needs a `tls-rustls` kernel build; the kernel rejects - * it at open on `tls-native`. Maps onto - * [`TlsConfig::check_certificate_revocation`]. - */ - checkCertificateRevocation?: boolean - /** - * With `checkCertificateRevocation`, accept a chain whose revocation - * status cannot be determined (no CRL distribution point, unreachable - * CRL). Omitted / `false` ⇒ strict. Maps onto - * [`TlsConfig::accept_undetermined_certificate_revocation`]. - */ - acceptUndeterminedRevocation?: boolean /** * Extra HTTP headers to send on every request — the route for * caller-supplied headers (the NodeJS driver's `customHeaders` and diff --git a/napi/src/database.rs b/napi/src/database.rs index 3b7ecf86..4a8fbe3f 100644 --- a/napi/src/database.rs +++ b/napi/src/database.rs @@ -362,16 +362,6 @@ pub struct ConnectionOptions { /// kernel's TLS backends supply a PKCS#8 key (`BEGIN PRIVATE KEY`). /// Maps onto the kernel [`TlsConfig::client_key_pem`]. pub client_key_pem: Option, - /// Check the server certificate chain's CRLs before connecting. Omitted - /// / `false` ⇒ off. Needs a `tls-rustls` kernel build; the kernel rejects - /// it at open on `tls-native`. Maps onto - /// [`TlsConfig::check_certificate_revocation`]. - pub check_certificate_revocation: Option, - /// With `check_certificate_revocation`, accept a chain whose revocation - /// status cannot be determined (no CRL distribution point, unreachable - /// CRL). Omitted / `false` ⇒ strict. Maps onto - /// [`TlsConfig::accept_undetermined_certificate_revocation`]. - pub accept_undetermined_revocation: Option, /// Extra HTTP headers to send on every request — the route for /// caller-supplied headers (the NodeJS driver's `customHeaders` and /// the composed `User-Agent`). Maps onto the kernel @@ -618,9 +608,6 @@ fn build_tls_config(options: &ConnectionOptions) -> TlsConfig { if let Some(key) = &options.client_key_pem { tls.client_key_pem = Some(key.to_vec()); } - // Revocation is opt-in: unset stays `None` (kernel default off). - tls.check_certificate_revocation = options.check_certificate_revocation; - tls.accept_undetermined_certificate_revocation = options.accept_undetermined_revocation; tls } @@ -942,8 +929,6 @@ mod tests { azure_client_secret: None, azure_tenant_id: None, azure_workspace_resource_id: None, - check_certificate_revocation: None, - accept_undetermined_revocation: None, catalog: None, schema: None, session_conf: None, @@ -1426,25 +1411,6 @@ mod tests { assert_eq!(tls.custom_ca_cert.as_deref(), Some(PEM)); } - #[test] - fn tls_revocation_flags_map_onto_kernel_policy() { - // Unset means off; each flag passes straight through to the kernel. - let cases = [ - (None, None, None, None), - (Some(true), None, Some(true), None), - (Some(true), Some(true), Some(true), Some(true)), - (Some(false), None, Some(false), None), - ]; - for (check, accept, want_check, want_accept) in cases { - let mut o = base(); - o.check_certificate_revocation = check; - o.accept_undetermined_revocation = accept; - let tls = build_tls_config(&o); - assert_eq!(tls.check_certificate_revocation, want_check); - assert_eq!(tls.accept_undetermined_certificate_revocation, want_accept); - } - } - #[test] fn tls_hostname_check_on_by_default_and_when_explicit_true() { for hostname in [None, Some(true)] { diff --git a/pyo3/NEXT_CHANGELOG.md b/pyo3/NEXT_CHANGELOG.md index 33fd2bfb..e0881e54 100644 --- a/pyo3/NEXT_CHANGELOG.md +++ b/pyo3/NEXT_CHANGELOG.md @@ -13,8 +13,6 @@ changes go in the root `NEXT_CHANGELOG.md`. ### Added -- `Session` accepts `tls_check_certificate_revocation` and `tls_accept_undetermined_revocation` (both default off) to check the server chain's CRLs. Needs the `tls-rustls` kernel build, which the wheel uses. - ### Changed ### Updated diff --git a/pyo3/src/session.rs b/pyo3/src/session.rs index a84eb6e5..c626ee89 100644 --- a/pyo3/src/session.rs +++ b/pyo3/src/session.rs @@ -305,10 +305,6 @@ impl Session { /// `tls_skip_hostname_verify` disables the hostname check; /// `tls_client_cert` + `tls_client_key` (both PEM bytes) configure /// mutual TLS. The two mTLS fields must be set together. - /// `tls_check_certificate_revocation=True` checks the chain's CRLs - /// (`tls-rustls` builds only); `tls_accept_undetermined_revocation=True` - /// accepts a chain whose revocation status cannot be determined. - /// Both default to off. /// /// Retry/backoff: all optional, default to the kernel's built-in /// policy (1s/60s backoff, 6 total attempts, 900s budget) when @@ -379,8 +375,6 @@ impl Session { tls_skip_hostname_verify=false, tls_client_cert=None, tls_client_key=None, - tls_check_certificate_revocation=None, - tls_accept_undetermined_revocation=None, sea_response_compression_enabled=false, request_timeout_secs=None, max_connections=None, @@ -448,8 +442,6 @@ impl Session { tls_skip_hostname_verify: bool, tls_client_cert: Option>, tls_client_key: Option>, - tls_check_certificate_revocation: Option, - tls_accept_undetermined_revocation: Option, sea_response_compression_enabled: bool, request_timeout_secs: Option, max_connections: Option, @@ -539,8 +531,6 @@ impl Session { || tls_skip_hostname_verify || tls_client_cert.is_some() || tls_client_key.is_some() - || tls_check_certificate_revocation.is_some() - || tls_accept_undetermined_revocation.is_some() { let mut tls = databricks_sql_kernel::TlsConfig::default(); tls.custom_ca_cert = tls_ca_cert; @@ -548,8 +538,6 @@ impl Session { tls.skip_hostname_verification = tls_skip_hostname_verify; tls.client_cert_pem = tls_client_cert; tls.client_key_pem = tls_client_key; - tls.check_certificate_revocation = tls_check_certificate_revocation; - tls.accept_undetermined_certificate_revocation = tls_accept_undetermined_revocation; Some(tls) } else { None diff --git a/pyo3/tests/test_session.py b/pyo3/tests/test_session.py index f3bdc893..4d27fdee 100644 --- a/pyo3/tests/test_session.py +++ b/pyo3/tests/test_session.py @@ -17,31 +17,11 @@ from __future__ import annotations -import inspect -import sys - -import pytest - import databricks_sql_kernel as k from conftest import live -@pytest.mark.skipif( - sys.version_info < (3, 10), - reason="inspect.signature cannot read a pyo3 class's signature before Python 3.10", -) -def test_revocation_kwargs_are_keyword_only_and_default_off(): - # Offline: checks the constructor contract. Unset (None) means off. - params = inspect.signature(k.Session).parameters - for name in ( - "tls_check_certificate_revocation", - "tls_accept_undetermined_revocation", - ): - assert params[name].kind is inspect.Parameter.KEYWORD_ONLY, name - assert params[name].default is None, name - - @live def test_session_id_non_empty(session): assert session.session_id, f"session_id should be populated: {session.session_id!r}" From 115ac588e6c7fc671f162118e5fdecd5c1bc7832 Mon Sep 17 00:00:00 2001 From: cat23123 <58714163+cat23123@users.noreply.github.com> Date: Fri, 20 Nov 2026 02:10:50 +0000 Subject: [PATCH 12/43] refactor(tls): check revocation with Windows CryptoAPI instead of a CRL fetcher Replace the kernel's own CRL fetcher with a Windows-only revocation check. Trust stays with webpki: the connection's WebPkiServerVerifier, over the kernel's roots (webpki roots, the OS store and custom CAs), verifies the chain, the name and the signatures exactly as with revocation off. Only after that succeeds is revocation asked of CryptoAPI (CertGetCertificateChain). CryptoAPI builds the chain from the leaf, the presented intermediates and the custom CAs (in an in-memory additional store), and checks every certificate except the root. The decision reads the chain-level revocation bits only: - CERT_TRUST_IS_REVOKED is rejected in both modes. - Unknown or offline revocation status, and a partial chain, are undetermined: rejected in strict mode, accepted with accept_undetermined. Revocation is supported only on Windows with tls-rustls. Elsewhere, and on tls-native (including Windows), requesting it fails session open with InvalidArgument. Session resumption is disabled while revocation is on, because resumed handshakes skip the verifier. This removes the CRL worker thread and runtime, the CRL caches, the DER reader, the redirect and body-size policies, CrlFetchLimits, the module pin and the der and libc dependencies. The public TlsConfig shape is unchanged from the base commit. Co-authored-by: Isaac Signed-off-by: cat23123 <58714163+cat23123@users.noreply.github.com> --- Cargo.lock | 2 - Cargo.toml | 18 +- src/c_abi/session.rs | 10 +- src/client/http.rs | 122 +-- src/client/http_tls_tests.rs | 56 ++ src/client/mod.rs | 2 +- src/client/retry.rs | 6 +- src/client/tls_revocation.rs | 953 ++++------------------ src/client/tls_revocation_tests.rs | 1221 ++++------------------------ src/session.rs | 12 +- 10 files changed, 481 insertions(+), 1921 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 8246c9cb..5dc627f6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -658,14 +658,12 @@ dependencies = [ "cbc 0.2.1", "chrono", "dashmap", - "der", "dirs", "futures", "geo-traits", "hex", "hmac 0.13.0", "jsonwebtoken", - "libc", "log", "lz4_flex", "moka", diff --git a/Cargo.toml b/Cargo.toml index c4192589..489e761e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -65,12 +65,9 @@ rustls = { version = "0.23.41", optional = true, default-features = false, featu # Enforce TLS dependency minimums for consumers with their own lockfiles. rustls-webpki = { version = "0.103.16", optional = true, default-features = false } webpki-roots = { version = "1.0.11", optional = true, default-features = false } -# `tls-rustls` only: opt-in certificate revocation checking (see -# `src/client/tls_revocation.rs`). Both crates are already in the runtime graph -# through reqwest / pkcs8; they are declared here so the kernel can build its own -# rustls client config (root store from the OS trust store, and a CRL DER reader). +# `tls-rustls` only. Loads the OS trust store for the revocation verifier on Windows (see +# `src/client/tls_revocation.rs`), the same store reqwest's `rustls-tls-native-roots` loads. rustls-native-certs = { version = "0.8", optional = true } -der = { version = "0.7", optional = true } tokio = { version = "1", features = ["full", "sync"] } # Serialization @@ -151,14 +148,10 @@ zeroize = "1.9" jsonwebtoken = { version = "9", default-features = false, features = ["use_pem"] } # JWT signing (RS256/384/512, PS256/384/512, ES256/384); use_pem = PEM key loading (adds pem + simple_asn1, no TLS) pkcs8 = { version = "0.10", features = ["encryption", "pem", "std"] } # PKCS#8 PEM parsing + PBES2 passphrase decryption -# Pins the module that holds the kernel while the CRL worker thread may still run its -# code (see `pin_crate_module` in `src/client/tls_revocation.rs`). Both crates are already -# in the graph; these target-specific entries add no new crates. +# Windows CryptoAPI for TLS certificate revocation (`src/client/tls_revocation.rs`). +# `windows-sys` is already in the lock file; no new packages. [target.'cfg(windows)'.dependencies] -windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_System_LibraryLoader"] } - -[target.'cfg(unix)'.dependencies] -libc = "0.2" +windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_Security_Cryptography"] } [dev-dependencies] tokio = { version = "1", features = ["rt-multi-thread", "macros", "net", "io-util"] } @@ -228,7 +221,6 @@ tls-rustls = [ "dep:rustls-webpki", "dep:webpki-roots", "dep:rustls-native-certs", - "dep:der", ] [lib] diff --git a/src/c_abi/session.rs b/src/c_abi/session.rs index 90fee838..9ab80a81 100644 --- a/src/c_abi/session.rs +++ b/src/c_abi/session.rs @@ -3463,15 +3463,15 @@ mod tests { } } -#[cfg(all(test, not(feature = "tls-rustls")))] +#[cfg(all(test, not(all(windows, feature = "tls-rustls"))))] mod revocation_open_tests { use super::*; use std::ffi::{CStr, CString}; - /// Revocation on tls-native: session open returns InvalidArgument with the - /// backend message. It is rejected before network I/O, so the host is not dialed. + /// Revocation on a platform or backend without it (anything but Windows with + /// tls-rustls): session open returns InvalidArgument. It is rejected before network I/O, so the host is not dialed. #[test] - fn tls_revocation_on_tls_native_open_returns_invalid_argument() { + fn tls_revocation_on_unsupported_platform_open_returns_invalid_argument() { unsafe { let mut config: *mut KernelSessionConfig = std::ptr::null_mut(); assert_eq!( @@ -3504,7 +3504,7 @@ mod revocation_open_tests { let error = out.assume_init(); let message = CStr::from_ptr(error.message).to_str().unwrap(); assert!( - message.contains("certificate revocation checking requires the tls-rustls backend"), + message.contains("TLS certificate revocation checking"), "{message}" ); } diff --git a/src/client/http.rs b/src/client/http.rs index bbd09734..d391e76a 100644 --- a/src/client/http.rs +++ b/src/client/http.rs @@ -199,57 +199,31 @@ pub struct TlsConfig { pub client_key_pem: Option>, } -/// Bounds applied to each CRL HTTP fetch. -#[cfg(feature = "tls-rustls")] -#[derive(Clone, Copy, Debug)] -pub(crate) struct CrlFetchLimits { - pub(crate) timeout: Duration, - pub(crate) max_bytes: usize, -} - -#[cfg(feature = "tls-rustls")] -impl Default for CrlFetchLimits { - fn default() -> Self { - Self { - timeout: Duration::from_secs(10), - max_bytes: 32 * 1024 * 1024, - } - } +/// The revocation mode for a client, from the public options: `None` when checking is +/// off, otherwise `Some(accept_undetermined)`. +pub(crate) fn revocation_mode( + check: Option, + accept_undetermined: Option, +) -> Option { + (check == Some(true)).then(|| accept_undetermined == Some(true)) } -/// Revocation checking for one client: whether an undetermined status is accepted. -/// It is carried next to [`TlsConfig`], not inside it, so that struct keeps its -/// published shape. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) struct RevocationPolicy { - pub(crate) accept_undetermined: bool, -} - -impl RevocationPolicy { - /// The policy for the public options, or `None` when checking is off (unset or - /// `false`). - pub(crate) fn from_options( - check: Option, - accept_undetermined: Option, - ) -> Option { - (check == Some(true)).then(|| Self { - accept_undetermined: accept_undetermined == Some(true), - }) - } -} - -/// Rejects a revocation request the backend cannot honour. Shared by session -/// open (which must report `InvalidArgument` unwrapped) and the HTTP client. +/// Rejects a revocation request that this platform or backend cannot honour, with +/// `InvalidArgument`. Revocation is implemented only on Windows with `tls-rustls`. /// `allow_self_signed` turns revocation off, so it is not an error. -pub(crate) fn check_revocation_support( - tls: &TlsConfig, - revocation: Option, -) -> Result<()> { - if cfg!(feature = "tls-rustls") || revocation.is_none() || tls.allow_self_signed == Some(true) { +pub(crate) fn check_revocation_support(tls: &TlsConfig, revocation: Option) -> Result<()> { + if revocation.is_none() || tls.allow_self_signed == Some(true) { return Ok(()); } - Err(Error::invalid_argument() - .message("certificate revocation checking requires the tls-rustls backend")) + if cfg!(all(windows, feature = "tls-rustls")) { + return Ok(()); + } + let message = if cfg!(windows) { + "TLS certificate revocation checking requires the tls-rustls backend" + } else { + "TLS certificate revocation checking is supported only on Windows" + }; + Err(Error::invalid_argument().message(message)) } impl std::fmt::Debug for TlsConfig { @@ -439,7 +413,7 @@ pub struct DatabricksHttpClient { config: HttpClientConfig, auth_provider: OnceLock>, retry_configs: HashMap, - revocation: Option, + revocation: Option, } impl DatabricksHttpClient { @@ -461,7 +435,7 @@ impl DatabricksHttpClient { pub(crate) fn with_revocation( mut config: HttpClientConfig, retry_configs: HashMap, - revocation: Option, + revocation: Option, ) -> Result { // Fold any caller-supplied `User-Agent` custom header into the // effective UA, and remove it from `custom_headers` so it isn't @@ -581,7 +555,7 @@ impl DatabricksHttpClient { fn build_reqwest_client( config: &HttpClientConfig, redirect: reqwest::redirect::Policy, - revocation: Option, + revocation: Option, ) -> Result { check_revocation_support(&config.tls, revocation)?; let mut builder = Client::builder() @@ -769,15 +743,15 @@ impl DatabricksHttpClient { debug!("HTTP client using default proxy behavior (env vars)"); } - // With revocation on, the verifier replaces reqwest's trust roots and - // identity. Those were already validated above. - #[cfg(feature = "tls-rustls")] - // `allow_self_signed` turns revocation off, as Simba does. - if let Some(policy) = revocation.filter(|_| config.tls.allow_self_signed != Some(true)) { + // With revocation on, the verifier replaces reqwest's trust roots and identity. + // Those were already validated above. `allow_self_signed` turns revocation off. + #[cfg(all(windows, feature = "tls-rustls"))] + if let Some(accept_undetermined) = + revocation.filter(|_| config.tls.allow_self_signed != Some(true)) + { builder = builder.use_preconfigured_tls(super::tls_revocation::client_config( &config.tls, - &config.proxy, - policy.accept_undetermined, + accept_undetermined, )?); } @@ -1178,6 +1152,42 @@ mod tests { build_retry_configs(&RetryConfig::default(), &HashMap::new()) } + #[test] + fn revocation_mode_maps_the_public_options() { + assert_eq!(revocation_mode(None, None), None); + assert_eq!(revocation_mode(Some(false), Some(true)), None); + assert_eq!(revocation_mode(Some(true), None), Some(false)); + assert_eq!(revocation_mode(Some(true), Some(false)), Some(false)); + assert_eq!(revocation_mode(Some(true), Some(true)), Some(true)); + } + + #[test] + fn revocation_request_is_refused_where_it_is_not_implemented() { + let tls = HttpClientConfig::default().tls; + check_revocation_support(&tls, None).expect("no request"); + let mut self_signed = tls.clone(); + self_signed.allow_self_signed = Some(true); + check_revocation_support(&self_signed, Some(false)) + .expect("allow_self_signed turns revocation off"); + if cfg!(all(windows, feature = "tls-rustls")) { + check_revocation_support(&tls, Some(false)).expect("implemented on this platform"); + } else { + let error = check_revocation_support(&tls, Some(false)) + .expect_err("revocation is refused off Windows with tls-rustls"); + assert_eq!( + error.code, + crate::kernel_error::ErrorCode::InvalidArgument, + "{error}" + ); + assert!( + error + .message + .contains("TLS certificate revocation checking"), + "{error}" + ); + } + } + #[test] fn test_http_client_config_default() { let config = HttpClientConfig::default(); diff --git a/src/client/http_tls_tests.rs b/src/client/http_tls_tests.rs index b4b2d8c3..977814e0 100644 --- a/src/client/http_tls_tests.rs +++ b/src/client/http_tls_tests.rs @@ -273,6 +273,62 @@ async fn self_signed_fails_once_with_certificate_cause() { assert_certificate_failure(CertificateFailure::SelfSigned).await; } +#[tokio::test] +async fn trusted_chain_completes_with_revocation_off() { + // Revocation off: a chain the client trusts completes on the default path, on every + // backend, and no revocation check is involved. + let mut ca_params = CertificateParams::new(Vec::new()).unwrap(); + ca_params.is_ca = IsCa::Ca(BasicConstraints::Unconstrained); + ca_params + .distinguished_name + .push(rcgen::DnType::CommonName, "Off test CA"); + let ca_key = KeyPair::generate().unwrap(); + let ca_cert = ca_params.self_signed(&ca_key).unwrap(); + let issuer = Issuer::new(ca_params, ca_key); + let server_key = KeyPair::generate().unwrap(); + let server_cert = CertificateParams::new(vec!["127.0.0.1".to_string()]) + .unwrap() + .signed_by(&server_key, &issuer) + .unwrap(); + let tls = rustls::ServerConfig::builder_with_provider(Arc::new( + rustls::crypto::ring::default_provider(), + )) + .with_safe_default_protocol_versions() + .unwrap() + .with_no_client_auth() + .with_single_cert( + vec![server_cert.der().clone()], + PrivatePkcs8KeyDer::from(server_key.serialize_der()).into(), + ) + .unwrap(); + let acceptor = TlsAcceptor::from(Arc::new(tls)); + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let server = tokio::spawn(async move { + let socket = listener.accept().await.unwrap().0; + let mut stream = acceptor.accept(socket).await.unwrap(); + let mut buffer = [0; 1024]; + let _ = stream.read(&mut buffer).await; + stream + .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\nConnection: close\r\n\r\n") + .await + .unwrap(); + let _ = stream.shutdown().await; + }); + + let mut config = HttpClientConfig::default(); + config.tls.trusted_certificate_pem = Some(ca_cert.pem().into_bytes()); + let client = test_client(config, Duration::from_secs(10)); + let response = client + .inner() + .get(format!("https://{address}/")) + .send() + .await + .expect("a trusted chain completes with revocation off"); + assert_eq!(response.status(), reqwest::StatusCode::OK); + server.await.unwrap(); +} + #[tokio::test] async fn hostname_mismatch_fails_once_with_certificate_cause() { assert_certificate_failure(CertificateFailure::HostnameMismatch).await; diff --git a/src/client/mod.rs b/src/client/mod.rs index bd6303c4..0edc69d2 100644 --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -34,7 +34,7 @@ pub mod http; pub mod retry; pub mod sea; -#[cfg(feature = "tls-rustls")] +#[cfg(all(windows, feature = "tls-rustls"))] pub(crate) mod tls_revocation; pub(crate) mod transport; diff --git a/src/client/retry.rs b/src/client/retry.rs index 45a4c917..cdd1c31b 100644 --- a/src/client/retry.rs +++ b/src/client/retry.rs @@ -271,11 +271,7 @@ pub(crate) fn is_certificate_verification_failure( #[cfg(feature = "tls-rustls")] if matches!( error.downcast_ref::(), - Some( - rustls::Error::InvalidCertificate(_) - | rustls::Error::InvalidCertRevocationList(_) - | rustls::Error::NoCertificatesPresented - ) + Some(rustls::Error::InvalidCertificate(_) | rustls::Error::NoCertificatesPresented) ) { return true; } diff --git a/src/client/tls_revocation.rs b/src/client/tls_revocation.rs index 8234498b..41bde098 100644 --- a/src/client/tls_revocation.rs +++ b/src/client/tls_revocation.rs @@ -12,575 +12,184 @@ // See the License for the specific language governing permissions and // limitations under the License. -//! CRL revocation checking for the `tls-rustls` backend. +//! Certificate revocation for the `tls-rustls` backend on Windows, through CryptoAPI. //! -//! The server verifier builds the chain with webpki first, so a bad chain never -//! reaches the network. It then fetches the CRLs named by the distribution points -//! of each non-self-issued certificate and hands the current ones to webpki, which -//! checks their signatures and the revocation status. The DER reader here only -//! selects CRLs and reads issuer names and `nextUpdate`. Authenticity is webpki's. +//! Trust stays with webpki. The connection's `WebPkiServerVerifier`, over the kernel's +//! roots, verifies the chain, the name and the signatures, as it does with revocation off. +//! Only after that succeeds is revocation asked of CryptoAPI (`CertGetCertificateChain`). +//! CryptoAPI builds the chain from the leaf, the presented intermediates and the custom CAs, +//! and checks the revocation of every certificate except the root. Its CRL and OCSP fetches +//! use the Windows networking stack and proxy settings, and Windows caches their results. +//! +//! The decision reads the chain-level revocation bits only. The trust bits, including the +//! root's, are ignored. +//! +//! This module is compiled only on Windows with `tls-rustls`. Elsewhere, revocation is +//! rejected at session open. -use std::collections::HashMap; -use std::sync::{Arc, Mutex, PoisonError}; -use std::time::{Duration, Instant}; +use std::ptr::{null, null_mut}; +use std::sync::Arc; +use std::time::Duration; -use der::asn1::{AnyRef, GeneralizedTime, UtcTime}; -use der::{Decode, Reader, SliceReader, Tagged}; -use reqwest::StatusCode; use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier}; use rustls::client::WebPkiServerVerifier; -use rustls::crypto::CryptoProvider; -use rustls::pki_types::{ - pem::PemObject, CertificateDer, CertificateRevocationListDer, PrivateKeyDer, ServerName, - UnixTime, -}; +use rustls::pki_types::{pem::PemObject, CertificateDer, ServerName, UnixTime}; use rustls::{ - CertRevocationListError, CertificateError, ClientConfig, DigitallySignedStruct, RootCertStore, - SignatureScheme, + CertificateError, ClientConfig, DigitallySignedStruct, RootCertStore, SignatureScheme, +}; +use windows_sys::Win32::Security::Cryptography::{ + CertAddCertificateContextToStore, CertCloseStore, CertCreateCertificateContext, + CertFreeCertificateChain, CertFreeCertificateContext, CertGetCertificateChain, CertOpenStore, + CERT_CHAIN_CONTEXT, CERT_CHAIN_PARA, CERT_CHAIN_REVOCATION_ACCUMULATIVE_TIMEOUT, + CERT_CHAIN_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT, CERT_CONTEXT, CERT_STORE_ADD_ALWAYS, + CERT_STORE_PROV_MEMORY, CERT_TRUST_IS_OFFLINE_REVOCATION, CERT_TRUST_IS_PARTIAL_CHAIN, + CERT_TRUST_IS_REVOKED, CERT_TRUST_REVOCATION_STATUS_UNKNOWN, HCERTSTORE, PKCS_7_ASN_ENCODING, + X509_ASN_ENCODING, }; -use super::http::{CrlFetchLimits, ProxyConfig, TlsConfig}; +use super::http::TlsConfig; use crate::kernel_error::{Error, Result}; -use crate::klog::debug; -use crate::util::runtime::{ambient_rust_min_stack, runtime_thread_stack_size}; - -const TAG_INTEGER: u8 = 0x02; -const TAG_UTC_TIME: u8 = 0x17; -const TAG_GENERALIZED_TIME: u8 = 0x18; -const TAG_SEQUENCE: u8 = 0x30; -/// Context [0]: explicit version, `distributionPoint`, `fullName`. -const TAG_CONTEXT_0: u8 = 0xA0; -/// Context [2]: `cRLIssuer` (an indirect CRL, which is not supported). -const TAG_CONTEXT_2: u8 = 0xA2; -/// Context [3]: certificate extensions. -const TAG_CONTEXT_3: u8 = 0xA3; -/// Context [6] primitive: a `uniformResourceIdentifier`. -const TAG_URI: u8 = 0x86; -/// OID 2.5.29.31, the CRL distribution points extension (content octets). -const OID_CRL_DISTRIBUTION_POINTS: &[u8] = &[0x55, 0x1D, 0x1F]; -/// How long a failed fetch is remembered, so an unreachable endpoint is not waited on again -/// by every handshake. -const FAILED_FETCH_TTL: Duration = Duration::from_secs(60); -/// Caps on the cached CRLs, by count and by total bytes. -const MAX_CACHED_CRLS: usize = 64; -const MAX_CACHED_BYTES: usize = 16 * 1024 * 1024; - -/// A verification failure the verifier raises itself. It carries a message for the caller -/// and is classified as a certificate-verification failure. -#[derive(Debug)] -struct VerifierError(String); - -impl std::fmt::Display for VerifierError { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.write_str(&self.0) - } -} - -impl std::error::Error for VerifierError {} - -fn verifier_error(message: String) -> rustls::Error { - rustls::Error::InvalidCertificate(CertificateError::Other(rustls::OtherError(Arc::new( - VerifierError(message), - )))) -} - -// Tests set a per-thread fetch bound here. The client is built on the calling thread, so -// the bound in effect at construction is the one the fetcher keeps. -#[cfg(test)] -thread_local! { - pub(crate) static TEST_CRL_LIMITS: std::cell::Cell> = - const { std::cell::Cell::new(None) }; -} - -/// The CRL fetch bounds: production defaults, or a test override on this thread. -fn crl_fetch_limits() -> CrlFetchLimits { - #[cfg(test)] - if let Some(limits) = TEST_CRL_LIMITS.with(std::cell::Cell::get) { - return limits; - } - CrlFetchLimits::default() -} - -/// The (tag, content) pairs of the consecutive TLVs in `der`. -fn tlvs(der: &[u8]) -> Option> { - let mut reader = SliceReader::new(der).ok()?; - let mut out = Vec::new(); - while !reader.is_finished() { - let any = AnyRef::decode(&mut reader).ok()?; - out.push((any.tag().into(), any.value())); - } - Some(out) -} - -/// The children of the single SEQUENCE that `der` consists of. -fn sequence(der: &[u8]) -> Option> { - match tlvs(der)?.as_slice() { - [(TAG_SEQUENCE, body)] => tlvs(body), - _ => None, - } -} - -/// The fields of a certificate that the revocation check needs. -struct Cert<'a> { - issuer: &'a [u8], - subject: &'a [u8], - spki: &'a [u8], - crl_uris: Vec, -} -fn parse_cert(der: &[u8]) -> Option> { - let top = sequence(der)?; - let fields = tlvs(top.first()?.1)?; - // Optional explicit version, then serialNumber, signature, issuer, validity, subject. - let base = usize::from(fields.first()?.0 == TAG_CONTEXT_0); - let issuer = fields.get(base + 2)?.1; - let subject = fields.get(base + 4)?.1; - let spki = fields.get(base + 5)?.1; - let mut crl_uris = Vec::new(); - if let Some(&(_, extensions)) = fields.iter().find(|f| f.0 == TAG_CONTEXT_3) { - for (_, extension) in sequence(extensions)? { - let parts = tlvs(extension)?; - if parts.first()?.1 == OID_CRL_DISTRIBUTION_POINTS { - crl_uris = distribution_points(parts.last()?.1)?; - } - } - } - Some(Cert { - issuer, - subject, - spki, - crl_uris, - }) +/// The budget for CRL and OCSP retrieval for one chain. CryptoAPI applies it to all of the +/// chain's fetches together (`CERT_CHAIN_REVOCATION_ACCUMULATIVE_TIMEOUT`). +const REVOCATION_TIMEOUT: Duration = Duration::from_secs(10); +/// The chain flags: check every certificate except the root. +const CHAIN_FLAGS: u32 = + CERT_CHAIN_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT | CERT_CHAIN_REVOCATION_ACCUMULATIVE_TIMEOUT; + +/// The revocation status of a chain, as CryptoAPI reports it. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Status { + Good, + /// CryptoAPI could not determine the status: a fetch failed or the server is offline, the + /// chain is partial, or no chain could be built at all. + Undetermined, + Revoked, } -/// Whether `cert` is one of the configured trust anchors. Matching is by subject -/// and SPKI, as webpki matches anchors, so a same-name certificate with a different -/// key is not an anchor. -fn is_trust_anchor(roots: &RootCertStore, cert: &Cert<'_>) -> bool { - roots.roots.iter().any(|anchor| { - anchor.subject.as_ref() == cert.subject - && anchor.subject_public_key_info.as_ref() == cert.spki - }) -} +/// An in-memory certificate store. Closed on drop. +struct Store(HCERTSTORE); -/// The http(s) URIs of a CRLDistributionPoints value. Indirect points are skipped. -fn distribution_points(value: &[u8]) -> Option> { - let mut uris = Vec::new(); - for (_, point) in sequence(value)? { - let parts = tlvs(point)?; - if parts.iter().any(|part| part.0 == TAG_CONTEXT_2) { - continue; - } - for (_, name) in parts.iter().filter(|part| part.0 == TAG_CONTEXT_0) { - general_names(name, &mut uris)?; - } +impl Store { + fn memory() -> Option { + // SAFETY: the memory provider takes no parameters. + let handle = unsafe { CertOpenStore(CERT_STORE_PROV_MEMORY, 0, 0, 0, null()) }; + (!handle.is_null()).then_some(Self(handle)) } - Some(uris) -} -/// Collects http(s) URIs from a DistributionPointName. Nested wrappers are followed. -/// Directory and relative names are ignored. -fn general_names(der: &[u8], out: &mut Vec) -> Option<()> { - for (tag, value) in tlvs(der)? { - match tag { - TAG_URI => { - if let Ok(uri) = std::str::from_utf8(value) { - let lower = uri.to_ascii_lowercase(); - if lower.starts_with("http://") || lower.starts_with("https://") { - out.push(uri.to_owned()); - } - } - } - TAG_CONTEXT_0 | TAG_SEQUENCE => general_names(value, out)?, - _ => {} + /// Adds a copy of `der`. The store keeps its own reference, so the temporary context is + /// freed when it drops. + fn add(&self, der: &[u8]) -> bool { + let Some(context) = Context::new(der) else { + return false; + }; + // SAFETY: both handles are live, and no output context is requested. + unsafe { + CertAddCertificateContextToStore(self.0, context.0, CERT_STORE_ADD_ALWAYS, null_mut()) + != 0 } } - Some(()) -} - -/// The fields of a CRL that the classification needs. -struct Crl<'a> { - issuer: &'a [u8], - next_update: Option, -} - -fn parse_crl(der: &[u8]) -> Option> { - let top = sequence(der)?; - let fields = tlvs(top.first()?.1)?; - // Optional version, then signature, issuer, thisUpdate, nextUpdate. - let base = usize::from(fields.first()?.0 == TAG_INTEGER); - let issuer = fields.get(base + 1)?.1; - let next_update = match fields.get(base + 3) { - Some(&(tag, value)) if tag == TAG_UTC_TIME || tag == TAG_GENERALIZED_TIME => { - Some(to_unix_secs(tag, value)?) - } - _ => None, - }; - Some(Crl { - issuer, - next_update, - }) -} - -/// Unix seconds of a UTCTime or GeneralizedTime, given its tag and contents. -fn to_unix_secs(tag: u8, value: &[u8]) -> Option { - let mut tlv = vec![tag, u8::try_from(value.len()).ok()?]; - tlv.extend_from_slice(value); - let at = if tag == TAG_UTC_TIME { - UtcTime::from_der(&tlv).ok()?.to_unix_duration() - } else { - GeneralizedTime::from_der(&tlv).ok()?.to_unix_duration() - }; - Some(at.as_secs()) -} - -/// The outcome of checking one fetched CRL against the certificate it covers. -enum Verdict { - Current, - Undetermined, - WrongIssuer, } -fn classify(der: &[u8], cert_issuer: &[u8], now: u64) -> Verdict { - if webpki::BorrowedCertRevocationList::from_der(der).is_err() { - return Verdict::Undetermined; - } - match parse_crl(der) { - Some(crl) if crl.issuer != cert_issuer => Verdict::WrongIssuer, - Some(Crl { - next_update: Some(next), - .. - }) if now <= next => Verdict::Current, - _ => Verdict::Undetermined, +impl Drop for Store { + fn drop(&mut self) { + // SAFETY: the handle came from `CertOpenStore` and is closed once. + unsafe { CertCloseStore(self.0, 0) }; } } -/// A cached CRL and its nextUpdate in Unix seconds. -type CachedCrl = (Arc>, u64); +/// A certificate context, freed on drop. +struct Context(*mut CERT_CONTEXT); -/// Drops expired CRLs, then the ones that expire soonest until the count and byte caps hold. -fn trim_cache(cache: &mut HashMap, now: u64) { - cache.retain(|_, (_, next)| now <= *next); - while cache.len() > MAX_CACHED_CRLS || cached_bytes(cache) > MAX_CACHED_BYTES { - let Some(soonest) = cache - .iter() - .min_by_key(|(_, (_, next))| *next) - .map(|(url, _)| url.clone()) - else { - break; +impl Context { + fn new(der: &[u8]) -> Option { + let len = u32::try_from(der.len()).ok()?; + // SAFETY: `der` is valid for `len` bytes for the duration of the call. + let context = unsafe { + CertCreateCertificateContext(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, der.as_ptr(), len) }; - cache.remove(&soonest); + (!context.is_null()).then_some(Self(context)) } } -fn cached_bytes(cache: &HashMap) -> usize { - cache.values().map(|(der, _)| der.len()).sum() -} - -/// Fetches CRLs through one worker. Each CRL is cached until its `nextUpdate`, within the -/// caps, and a failed fetch is remembered for `FAILED_FETCH_TTL`. -#[derive(Debug)] -struct CrlFetcher { - proxy: ProxyConfig, - limits: CrlFetchLimits, - /// The connection's custom CA roots, so an HTTPS CRL endpoint behind that CA verifies. - custom_roots: Vec, - /// URL to (CRL bytes, nextUpdate in Unix seconds). - cache: Mutex>, - /// URL to the time its last fetch failed. - failed: Mutex>, - /// Started on the first fetch, then reused for every chain this fetcher verifies. - worker: Mutex>, -} - -impl CrlFetcher { - /// The CRL at `url`, from cache while current, otherwise fetched within `budget`. - /// `None` means the fetch failed, no budget was left, or the URL failed recently. - fn get(&self, url: &str, now: u64, budget: Duration) -> Option>> { - { - let mut cache = self.cache.lock().unwrap_or_else(PoisonError::into_inner); - trim_cache(&mut cache, now); - if let Some((der, _)) = cache.get(url) { - return Some(Arc::clone(der)); - } - } - if budget.is_zero() || self.failed_recently(url) { - return None; - } - // The lock covers only starting the worker and queuing the request. The wait for the - // answer happens after it is released, so concurrent verifications do not serialize. - let answer = { - let mut worker = self.worker.lock().unwrap_or_else(PoisonError::into_inner); - if worker.is_none() { - match CrlWorker::start(self.proxy.clone(), self.limits, self.custom_roots.clone()) { - Ok(started) => *worker = Some(started), - Err(reason) => { - debug!("CRL worker failed to start: {reason}"); - return None; - } - } - } - match worker.as_ref() { - Some(started) => started.submit(url, budget), - None => Err("CRL worker is not running".to_owned()), - } - }; - let fetched = match answer { - Ok(received) => in_runtime_blocking(|| received.recv()) - .unwrap_or_else(|_| Err("CRL worker stopped".to_owned())), - Err(reason) => Err(reason), - }; - let der = match fetched { - Ok(der) => Arc::new(der), - Err(reason) => { - debug!("CRL fetch failed for {}: {reason}", redacted(url)); - // A fetch given only a sliver of the chain's budget says little about the - // endpoint, so only a fetch with most of its time is remembered. - if budget >= self.limits.timeout / 2 { - self.failed - .lock() - .unwrap_or_else(PoisonError::into_inner) - .insert(url.to_owned(), Instant::now()); - } - return None; - } - }; - self.failed - .lock() - .unwrap_or_else(PoisonError::into_inner) - .remove(url); - if let Some(next) = parse_crl(&der) - .and_then(|crl| crl.next_update) - .filter(|next| now <= *next) +impl Drop for Context { + fn drop(&mut self) { + // SAFETY: the handle came from `CertCreateCertificateContext` and is freed once. + unsafe { CertFreeCertificateContext(self.0) }; + } +} + +/// A chain built by CryptoAPI. Freed on drop. +struct ChainContext(*mut CERT_CHAIN_CONTEXT); + +impl ChainContext { + /// The chain-level revocation status. CryptoAPI combines the status of every element + /// (the root is not checked, so its bits do not appear). The trust bits are not read. + fn status(&self) -> Status { + // SAFETY: the chain is live until this guard drops, and the read does not write. + let bits = unsafe { (*self.0).TrustStatus.dwErrorStatus }; + if bits & CERT_TRUST_IS_REVOKED != 0 { + Status::Revoked + } else if bits + & (CERT_TRUST_REVOCATION_STATUS_UNKNOWN + | CERT_TRUST_IS_OFFLINE_REVOCATION + | CERT_TRUST_IS_PARTIAL_CHAIN) + != 0 { - let mut cache = self.cache.lock().unwrap_or_else(PoisonError::into_inner); - cache.insert(url.to_owned(), (Arc::clone(&der), next)); - trim_cache(&mut cache, now); + Status::Undetermined + } else { + Status::Good } - Some(der) - } - - fn failed_recently(&self, url: &str) -> bool { - let mut failed = self.failed.lock().unwrap_or_else(PoisonError::into_inner); - failed.retain(|_, at| at.elapsed() < FAILED_FETCH_TTL); - failed.contains_key(url) - } - - fn evict(&self, url: &str) { - self.cache - .lock() - .unwrap_or_else(PoisonError::into_inner) - .remove(url); - } -} - -/// A fetch to run: the URL, the time it may take, and where the answer goes. -type CrlRequest = ( - String, - Duration, - std::sync::mpsc::Sender, String>>, -); - -/// The thread that runs a fetcher's CRL fetches. It has one current-thread runtime and one -/// reqwest client. Each request runs as its own task, so concurrent fetches overlap. -/// -/// Dropping the worker closes its request channel. The thread then finishes its in-flight -/// fetches, each bounded by the per-fetch timeout, and the drop waits at most that long. -/// The module is pinned before the thread starts (see [`pin_crate_module_once`]), so a host -/// that unloads this library cannot unmap the thread's code, even when a fetch outlives -/// that wait. -struct CrlWorker { - requests: Option>, - /// Disconnects when the thread has finished. - exited: std::sync::mpsc::Receiver<()>, - timeout: Duration, -} - -impl std::fmt::Debug for CrlWorker { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.write_str("CrlWorker") } } -impl CrlWorker { - fn start( - proxy: ProxyConfig, - limits: CrlFetchLimits, - roots: Vec, - ) -> std::io::Result { - // Pin before the thread exists, so the host cannot unmap this code once it runs. - pin_crate_module_once(); - let (requests, mut inbox) = tokio::sync::mpsc::unbounded_channel::(); - let (exit_signal, exited) = std::sync::mpsc::channel::<()>(); - std::thread::Builder::new() - .name("databricks-crl".to_owned()) - .stack_size(runtime_thread_stack_size(ambient_rust_min_stack())) - .spawn(move || { - // Dropped when the thread ends, which disconnects `exited`. - let _exit_signal = exit_signal; - // The caller's runtime is never re-entered, so a current-thread caller - // cannot deadlock. - let Ok(runtime) = tokio::runtime::Builder::new_current_thread() - .enable_all() - .build() - else { - return; - }; - let client = build_client(&proxy, limits, &roots); - runtime.block_on(async move { - while let Some((url, budget, answer)) = inbox.recv().await { - let client = client.clone(); - tokio::spawn(async move { - let result = match client { - Ok(client) => fetch(&client, &url, limits.max_bytes, budget).await, - Err(reason) => Err(reason), - }; - let _ = answer.send(result); - }); - } - }); - })?; - Ok(Self { - requests: Some(requests), - exited, - timeout: limits.timeout, - }) - } - - /// Queues one fetch. This does not wait for it, so the caller can release any lock - /// before it waits on the returned receiver. - fn submit( - &self, - url: &str, - budget: Duration, - ) -> std::result::Result, String>>, String> - { - let (answer, received) = std::sync::mpsc::channel(); - let requests = self - .requests - .as_ref() - .ok_or_else(|| "CRL worker is closed".to_owned())?; - requests - .send((url.to_owned(), budget, answer)) - .map_err(|_| "CRL worker is not running".to_owned())?; - Ok(received) - } -} - -impl Drop for CrlWorker { +impl Drop for ChainContext { fn drop(&mut self) { - // Closing the channel ends the worker once its in-flight fetches finish. Wait for - // that, but no longer than the per-fetch timeout. - // - // A fetch already past its per-fetch timeout can outlive this bounded wait, and the - // thread then keeps running after the drop. The library was pinned when the worker - // started, so the host cannot unmap that code while the thread runs. Once revocation - // is first used, the library therefore stays loaded for the rest of the process. - self.requests.take(); - let _ = in_runtime_blocking(|| self.exited.recv_timeout(self.timeout)); + // SAFETY: the chain came from `CertGetCertificateChain` and is freed once. + unsafe { CertFreeCertificateChain(self.0) }; } } -/// Pins the module that holds this crate, at most once per process, when the first CRL -/// worker starts. A pinned module is never unmapped, so a host that unloads the library -/// (an ODBC driver manager, or a napi addon's worker) cannot fault a CRL thread that is -/// still running. A failed pin is logged at debug and changes nothing else: the connection -/// proceeds as it did before pinning existed. -fn pin_crate_module_once() { - static PINNED: std::sync::Once = std::sync::Once::new(); - PINNED.call_once(|| { - if let Err(reason) = pin_crate_module() { - debug!("could not pin the kernel module for the CRL worker: {reason}"); - } - }); -} - -/// Windows: `GetModuleHandleExW` with `FROM_ADDRESS | PIN` on the address of a function in -/// this crate. The pinned handle is deliberately never released. -#[cfg(windows)] -fn pin_crate_module() -> std::result::Result<(), String> { - use windows_sys::Win32::Foundation::HMODULE; - use windows_sys::Win32::System::LibraryLoader::{ - GetModuleHandleExW, GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, GET_MODULE_HANDLE_EX_FLAG_PIN, - }; - let mut module: HMODULE = std::ptr::null_mut(); - // SAFETY: with FROM_ADDRESS, the name argument is a code address rather than a string. - // It is the address of `pin_crate_module`, which lives in this crate, and `module` is a - // valid out-pointer. - let found = unsafe { - GetModuleHandleExW( - GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_PIN, - pin_crate_module as *const () as usize as *const u16, - &mut module, - ) +/// CryptoAPI's revocation status for the chain that `leaf` builds. The presented +/// intermediates and the custom CAs are in the chain's additional store, so CryptoAPI can +/// reach the issuers that Windows does not trust. Trust is not decided here. +fn cryptoapi_status(leaf: &[u8], intermediates: &[&[u8]], custom_cas: &[&[u8]]) -> Status { + // Each handle has a guard, so every early return frees what was opened. + let Some(store) = Store::memory() else { + return Status::Undetermined; }; - if found == 0 { - return Err(format!( - "GetModuleHandleExW failed: {}", - std::io::Error::last_os_error() - )); - } - Ok(()) -} - -/// Unix: `dladdr` finds the object that holds a function in this crate, then `dlopen` with -/// `RTLD_NOLOAD` reopens that object without loading it again. `RTLD_NODELETE` makes a later -/// `dlclose` a no-op, so the object is never unmapped. The handle is deliberately not closed. -#[cfg(unix)] -fn pin_crate_module() -> std::result::Result<(), String> { - use std::os::unix::ffi::OsStrExt; - - // SAFETY: `Dl_info` is plain data, and dladdr writes it only on success. - let mut info: libc::Dl_info = unsafe { std::mem::zeroed() }; - let address = pin_crate_module as *const () as *const libc::c_void; - // SAFETY: `address` is a code address in this process, and `info` is valid for writes. - if unsafe { libc::dladdr(address, &mut info) } == 0 || info.dli_fname.is_null() { - return Err("dladdr found no object for the kernel's code".to_owned()); - } - // SAFETY: `dli_fname` is a NUL-terminated path from dladdr, valid for this call. - let path = unsafe { std::ffi::CStr::from_ptr(info.dli_fname) }; - let path = std::path::Path::new(std::ffi::OsStr::from_bytes(path.to_bytes())); - // A program that holds the kernel is the main executable, which the host cannot unload. - // dladdr names it by argv[0], and RTLD_NOLOAD cannot reopen it by that name. - if let (Ok(object), Ok(exe)) = ( - std::fs::canonicalize(path), - std::env::current_exe().and_then(std::fs::canonicalize), - ) { - if object == exe { - return Ok(()); + for der in intermediates.iter().chain(custom_cas) { + if !store.add(der) { + return Status::Undetermined; } } - // The flags request the already-loaded object only, and RTLD_NODELETE pins it. - let handle = unsafe { - libc::dlopen( - info.dli_fname, - libc::RTLD_NOW | libc::RTLD_NOLOAD | libc::RTLD_NODELETE, + let Some(leaf) = Context::new(leaf) else { + return Status::Undetermined; + }; + let para = CERT_CHAIN_PARA { + cbSize: std::mem::size_of::() as u32, + dwUrlRetrievalTimeout: REVOCATION_TIMEOUT.as_millis() as u32, + ..Default::default() + }; + let mut chain: *mut CERT_CHAIN_CONTEXT = null_mut(); + // SAFETY: the leaf and store are live, and `para` outlives the call. The null chain + // engine is the default, and null time is now. + let built = unsafe { + CertGetCertificateChain( + null_mut(), + leaf.0, + null(), + store.0, + ¶, + CHAIN_FLAGS, + null(), + &mut chain, ) }; - if handle.is_null() { - // SAFETY: dlerror returns a NUL-terminated message, or null when there is none. - let detail = unsafe { libc::dlerror() }; - let detail = if detail.is_null() { - "no detail".to_owned() - } else { - // SAFETY: checked non-null above; the message is read before any other dl call. - unsafe { std::ffi::CStr::from_ptr(detail) } - .to_string_lossy() - .into_owned() - }; - return Err(format!("dlopen failed: {detail}")); - } - Ok(()) -} - -#[cfg(all(test, target_os = "linux"))] -mod pin_tests { - use super::*; - - #[test] - fn crate_module_pin_succeeds_on_linux() { - assert_eq!(pin_crate_module(), Ok(())); + if built == 0 || chain.is_null() { + return Status::Undetermined; } + ChainContext(chain).status() } /// Runs a blocking wait. On a multi-thread runtime, block_in_place moves the worker's @@ -595,115 +204,25 @@ fn in_runtime_blocking(wait: impl FnOnce() -> T) -> T { } } -/// The client for a chain's CRL fetches. It carries no auth or custom headers, goes -/// through the connection's proxy, trusts the connection's custom CA roots, and is bounded -/// by time and redirects. -fn build_client( - proxy: &ProxyConfig, - limits: CrlFetchLimits, - roots: &[reqwest::Certificate], -) -> std::result::Result { - let mut builder = reqwest::Client::builder() - .connect_timeout(limits.timeout) - .timeout(limits.timeout) - // Redirects are not followed. A plaintext CRL response could otherwise send the - // fetch to an internal endpoint. A 3xx is not a 200, so the status is undetermined. - .redirect(reqwest::redirect::Policy::none()); - for root in roots { - builder = builder.add_root_certificate(root.clone()); - } - if let Some(proxy_url) = &proxy.url { - let mut via = reqwest::Proxy::all(proxy_url).map_err(|e| e.to_string())?; - if let Some(username) = &proxy.username { - via = via.basic_auth(username, proxy.password.as_deref().unwrap_or("")); - } - if let Some(bypass) = &proxy.bypass_hosts { - let normalized = bypass - .split(',') - .map(str::trim) - .collect::>() - .join(","); - via = via.no_proxy(reqwest::NoProxy::from_string(&normalized)); - } - builder = builder.proxy(via); - } - builder.build().map_err(|e| e.to_string()) -} - -/// One CRL download with `client`, bounded by `budget` and by the size limit. -async fn fetch( - client: &reqwest::Client, - url: &str, - max_bytes: usize, - budget: Duration, -) -> std::result::Result, String> { - tokio::time::timeout(budget, download(client, url, max_bytes)) - .await - .unwrap_or_else(|_| Err("CRL fetch timed out".to_owned())) -} - -async fn download( - client: &reqwest::Client, - url: &str, - max_bytes: usize, -) -> std::result::Result, String> { - let mut response = client - .get(url) - .send() - .await - .map_err(|e| e.without_url().to_string())?; - if response.status() != StatusCode::OK { - return Err(format!("HTTP {}", response.status())); - } - if response - .content_length() - .is_some_and(|len| len > max_bytes as u64) - { - return Err("CRL larger than the size limit".to_owned()); - } - let mut body = Vec::new(); - while let Some(chunk) = response - .chunk() - .await - .map_err(|e| e.without_url().to_string())? - { - if body.len() + chunk.len() > max_bytes { - return Err("CRL larger than the size limit".to_owned()); - } - body.extend_from_slice(&chunk); - } - Ok(body) -} - -/// The URL without userinfo, query or fragment, for logging. -fn redacted(url: &str) -> String { - match reqwest::Url::parse(url) { - Ok(mut parsed) => { - let _ = parsed.set_username(""); - let _ = parsed.set_password(None); - parsed.set_query(None); - parsed.set_fragment(None); - parsed.to_string() - } - Err(_) => "".to_owned(), - } +fn tls_error(e: impl std::fmt::Display) -> Error { + Error::invalid_argument().message(format!("invalid TLS configuration: {e}")) } -/// The server verifier: webpki for the chain, signatures and name, with CRLs. +/// The server verifier. Webpki decides the chain, the name and the signatures. CryptoAPI +/// decides the revocation of the chain it builds for the same leaf. #[derive(Debug)] struct RevocationVerifier { - roots: Arc, - provider: Arc, - /// Webpki verifier without CRLs. Supplies the handshake signature checks. + /// Webpki over the kernel's roots, without CRLs. signatures: Arc, - fetcher: CrlFetcher, + /// The custom CAs. CryptoAPI needs them as issuers when Windows does not trust them. + custom_cas: Vec>, accept_undetermined: bool, allow_hostname_mismatch: bool, } impl RevocationVerifier { - /// Forgives a name-only failure under `allow_hostname_mismatch`. webpki checks - /// the name last, so the chain has already verified when this happens. + /// Forgives a name-only failure under `allow_hostname_mismatch`. webpki checks the name + /// last, so the chain has already verified when this happens. fn tolerate_name( &self, result: std::result::Result, @@ -717,54 +236,6 @@ impl RevocationVerifier { } } -impl RevocationVerifier { - /// The indices of the presented intermediates on a path that webpki verifies. Subsets - /// are tried smallest first, and the first one that verifies is the path. An intermediate - /// the server adds that the path does not need is never returned, so its distribution - /// points are never fetched. More than six presented intermediates is rejected. - fn path_intermediates( - &self, - end_entity: &CertificateDer<'_>, - intermediates: &[CertificateDer<'_>], - server_name: &ServerName<'_>, - ocsp_response: &[u8], - now: UnixTime, - ) -> std::result::Result, rustls::Error> { - const MAX_PRESENTED: usize = 6; - let n = intermediates.len(); - if n > MAX_PRESENTED { - return Err(verifier_error(format!( - "the server presented {n} intermediates; revocation checking supports at most {MAX_PRESENTED}" - ))); - } - for size in 0..=n { - for mask in 0_usize..(1 << n) { - if mask.count_ones() as usize != size { - continue; - } - let picked: Vec = (0..n).filter(|i| mask & (1 << i) != 0).collect(); - let subset: Vec> = - picked.iter().map(|&i| intermediates[i].clone()).collect(); - if self - .tolerate_name(self.signatures.verify_server_cert( - end_entity, - &subset, - server_name, - ocsp_response, - now, - )) - .is_ok() - { - return Ok(picked); - } - } - } - Err(rustls::Error::InvalidCertificate( - CertificateError::UnknownIssuer, - )) - } -} - impl ServerCertVerifier for RevocationVerifier { fn verify_server_cert( &self, @@ -774,6 +245,8 @@ impl ServerCertVerifier for RevocationVerifier { ocsp_response: &[u8], now: UnixTime, ) -> std::result::Result { + // Chain, name and validity come first, so a chain webpki rejects never reaches + // CryptoAPI and its errors are the same as with revocation off. self.tolerate_name(self.signatures.verify_server_cert( end_entity, intermediates, @@ -781,87 +254,17 @@ impl ServerCertVerifier for RevocationVerifier { ocsp_response, now, ))?; - - let now_secs = now.as_secs(); - let path = - self.path_intermediates(end_entity, intermediates, server_name, ocsp_response, now)?; - // One deadline bounds every fetch for this chain, so the total wait is at - // most one per-fetch timeout however many distribution points there are. - let deadline = Instant::now() + self.fetcher.limits.timeout; - let mut crls = Vec::new(); - let mut used_urls = Vec::new(); - let mut undetermined = false; - for cert in std::iter::once(end_entity).chain(path.iter().map(|&i| &intermediates[i])) { - let Some(parsed) = parse_cert(cert.as_ref()) else { - undetermined = true; - continue; - }; - // Trust anchors are not revocation-checked (webpki does not check them either). - if is_trust_anchor(&self.roots, &parsed) { - continue; - } - let mut covered = false; - for url in &parsed.crl_uris { - // One usable CRL covers the certificate, so the other URLs are not fetched. - if covered { - break; - } - let budget = deadline.saturating_duration_since(Instant::now()); - let Some(der) = self.fetcher.get(url, now_secs, budget) else { - continue; - }; - match classify(&der, parsed.issuer, now_secs) { - Verdict::Current => { - crls.push(CertificateRevocationListDer::from(der.to_vec())); - used_urls.push(url.clone()); - covered = true; - } - Verdict::Undetermined => self.fetcher.evict(url), - Verdict::WrongIssuer => { - self.fetcher.evict(url); - return Err(rustls::Error::InvalidCertRevocationList( - CertRevocationListError::IssuerInvalidForCrl, - )); - } - } - } - undetermined |= !covered; - } - if undetermined && !self.accept_undetermined { - return Err(rustls::Error::InvalidCertificate( + let presented: Vec<&[u8]> = intermediates.iter().map(AsRef::as_ref).collect(); + let custom: Vec<&[u8]> = self.custom_cas.iter().map(AsRef::as_ref).collect(); + let leaf: &[u8] = end_entity.as_ref(); + match in_runtime_blocking(|| cryptoapi_status(leaf, &presented, &custom)) { + Status::Good => Ok(ServerCertVerified::assertion()), + Status::Revoked => Err(rustls::Error::InvalidCertificate(CertificateError::Revoked)), + Status::Undetermined if self.accept_undetermined => Ok(ServerCertVerified::assertion()), + Status::Undetermined => Err(rustls::Error::InvalidCertificate( CertificateError::UnknownRevocationStatus, - )); - } - - let mut builder = WebPkiServerVerifier::builder_with_provider( - Arc::clone(&self.roots), - Arc::clone(&self.provider), - ) - .with_crls(crls); - if self.accept_undetermined { - builder = builder.allow_unknown_revocation_status(); - } - let verifier = builder - .build() - .map_err(|e| verifier_error(format!("revocation verifier setup: {e}")))?; - // The final verification sees only the checked path. Webpki then cannot build a - // path through a presented intermediate whose CRLs were not checked. - let checked: Vec> = - path.iter().map(|&i| intermediates[i].clone()).collect(); - let result = self.tolerate_name(verifier.verify_server_cert( - end_entity, - &checked, - server_name, - ocsp_response, - now, - )); - // A CRL that webpki rejects must not stay cached. - if let Err(rustls::Error::InvalidCertRevocationList(_)) = &result { - for url in &used_urls { - self.fetcher.evict(url); - } + )), } - result } fn verify_tls12_signature( @@ -887,21 +290,13 @@ impl ServerCertVerifier for RevocationVerifier { } } -fn tls_error(e: impl std::fmt::Display) -> Error { - Error::invalid_argument().message(format!("invalid TLS configuration: {e}")) -} - -/// The rustls config for a connection with revocation checking. Trust roots are -/// webpki roots, then the OS store, then custom CAs, as reqwest's rustls assembly -/// uses. ALPN is HTTP/1.1, since the kernel enables no HTTP/2. +/// The rustls config for a connection with revocation checking. Trust roots are webpki +/// roots, then the OS store, then custom CAs, as reqwest's rustls assembly uses. ALPN is +/// HTTP/1.1, since the kernel enables no HTTP/2. /// -/// The caller has already validated the PEM bytes and the mTLS identity pair, so -/// they are parsed here without re-checking. -pub(crate) fn client_config( - tls: &TlsConfig, - proxy: &ProxyConfig, - accept_undetermined: bool, -) -> Result { +/// The caller has already validated the PEM bytes and the mTLS identity pair, so they are +/// parsed here without re-checking. +pub(crate) fn client_config(tls: &TlsConfig, accept_undetermined: bool) -> Result { let provider = Arc::new(rustls::crypto::ring::default_provider()); let mut roots = RootCertStore::empty(); roots.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned()); @@ -938,32 +333,22 @@ pub(crate) fn client_config( if let Some(pem) = &tls.trusted_certificate_pem { pems.push(pem.clone()); } - // The same custom CAs, as reqwest certificates, for the CRL client. - let mut custom_roots = Vec::new(); + let mut custom_cas = Vec::new(); for pem in pems { for cert in CertificateDer::pem_slice_iter(&pem) { - roots.add(cert.map_err(tls_error)?).map_err(tls_error)?; + let cert = cert.map_err(tls_error)?; + roots.add(cert.clone()).map_err(tls_error)?; + custom_cas.push(cert); } - custom_roots.extend(reqwest::Certificate::from_pem_bundle(&pem).map_err(tls_error)?); } - let roots = Arc::new(roots); let signatures = - WebPkiServerVerifier::builder_with_provider(Arc::clone(&roots), Arc::clone(&provider)) + WebPkiServerVerifier::builder_with_provider(Arc::new(roots), Arc::clone(&provider)) .build() .map_err(tls_error)?; let verifier = RevocationVerifier { - roots, - provider: Arc::clone(&provider), signatures, - fetcher: CrlFetcher { - proxy: proxy.clone(), - limits: crl_fetch_limits(), - custom_roots, - cache: Mutex::new(HashMap::new()), - failed: Mutex::new(HashMap::new()), - worker: Mutex::new(None), - }, + custom_cas, accept_undetermined, allow_hostname_mismatch: tls.allow_hostname_mismatch.unwrap_or(false), }; @@ -978,7 +363,7 @@ pub(crate) fn client_config( let chain = CertificateDer::pem_slice_iter(cert) .collect::, _>>() .map_err(tls_error)?; - let key = PrivateKeyDer::from_pem_slice(key).map_err(tls_error)?; + let key = rustls::pki_types::PrivateKeyDer::from_pem_slice(key).map_err(tls_error)?; builder .with_client_auth_cert(chain, key) .map_err(tls_error)? diff --git a/src/client/tls_revocation_tests.rs b/src/client/tls_revocation_tests.rs index 2b06b488..2e0c8e39 100644 --- a/src/client/tls_revocation_tests.rs +++ b/src/client/tls_revocation_tests.rs @@ -12,28 +12,31 @@ // See the License for the specific language governing permissions and // limitations under the License. -//! Hermetic revocation tests. Each fixture generates a root, an intermediate and a -//! leaf with rcgen, serves the CRLs over HTTP on loopback, and serves the leaf over -//! TLS on loopback. A forward-proxy stub can sit in front of the CRL fetches. +//! Windows revocation tests. Each fixture generates a root, an intermediate and a leaf with +//! rcgen, serves the CRLs over HTTP on loopback, and serves the leaf over TLS on loopback. +//! +//! The roots are not in the Windows store, so each chain also exercises the custom-CA path. +//! Every fixture has its own CRL URL (its own port and path), so CryptoAPI's cache cannot +//! carry a CRL from one test to another. +//! +//! These tests run only on Windows, in the kernel's Windows CI. use super::*; -use crate::client::http::{ - CrlFetchLimits, DatabricksHttpClient, HttpClientConfig, RevocationPolicy, -}; +use crate::client::http::{DatabricksHttpClient, HttpClientConfig}; use crate::client::retry::{build_retry_configs, RetryConfig}; use rcgen::{ date_time_ymd, BasicConstraints, CertificateParams, CertificateRevocationListParams, - CrlDistributionPoint, CustomExtension, DnType, IsCa, Issuer, KeyIdMethod, KeyPair, - RevokedCertParams, SerialNumber, SigningKey, + CrlDistributionPoint, DnType, IsCa, Issuer, KeyIdMethod, KeyPair, RevokedCertParams, + SerialNumber, SigningKey, }; use rustls::pki_types::PrivatePkcs8KeyDer; use rustls::HandshakeKind; use std::collections::HashMap; use std::io::{Read, Write}; -use std::net::{Shutdown, SocketAddr, TcpListener, TcpStream}; +use std::net::{SocketAddr, TcpListener, TcpStream}; +use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::{Arc, Mutex}; use std::thread; -use std::time::{Duration, Instant}; /// Lower-cased fragment of rustls's `UnknownRevocationStatus` error text. const UNDETERMINED: &str = "unknownrevocationstatus"; @@ -42,35 +45,18 @@ const INTERMEDIATE_CN: &str = "Revocation Test Intermediate"; const LEAF_SERIAL: u64 = 1000; const INTERMEDIATE_SERIAL: u64 = 2000; const CLIENT_SERIAL: u64 = 3000; -/// (year, month, day) for CRL validity bounds. -type Ymd = (i32, u8, u8); -const CURRENT: Ymd = (2099, 1, 1); -const EXPIRED: Ymd = (2021, 1, 1); +/// (year, month, day) for the CRL's validity bounds. Valid until 2099. +const CURRENT: (i32, u8, u8) = (2099, 1, 1); /// What the CRL at one distribution point serves. #[derive(Clone, Copy)] enum Served { + /// A current CRL that lists nothing. Good, - /// Lists the covered certificate as revoked. + /// A current CRL that lists the covered certificate as revoked. Revoked, - /// Signed with a key other than the issuer's (same issuer name). - WrongKey, - /// Signed by the other CA in the chain. - WrongIssuer, - Expired, - Status(u16), - /// Responds after the fetch timeout. - Timeout, - /// Body larger than the fetch size limit. - Oversize, - /// Distribution point is a closed port. + /// The distribution point is a closed port, so the fetch fails. Refused, - /// A usable CRL that arrives after half a second. - Slow, - /// Distribution point is not http(s), so there is nothing to fetch. - NonHttp, - /// Distribution point is indirect (has a cRLIssuer), so it must be skipped. - Indirect, } #[derive(Clone, Copy, PartialEq, Eq, Debug)] @@ -78,15 +64,6 @@ enum Outcome { Pass, Revoked, Undetermined, - InvalidCrl, -} - -#[derive(Clone, Copy)] -enum Relay { - /// The proxy forwards plain CRL requests to the origin. - Forward, - /// The proxy answers plain CRL requests with 502. The origin must not be reached. - Refuse, } /// One table row. Each row is checked in strict and accept-undetermined modes. @@ -95,7 +72,6 @@ struct Scenario { /// `None` means the leaf has no CRL distribution point. leaf: Option, intermediate: Served, - relay: Option, strict: Outcome, accept: Outcome, } @@ -103,142 +79,12 @@ struct Scenario { // One row per line, so the table stays readable. rustfmt would split each row. #[rustfmt::skip] const SCENARIOS: &[Scenario] = &[ - Scenario { - name: "good chain", - leaf: Some(Served::Good), - intermediate: Served::Good, - relay: None, - strict: Outcome::Pass, - accept: Outcome::Pass, - }, - Scenario { - name: "revoked leaf", - leaf: Some(Served::Revoked), - intermediate: Served::Good, - relay: None, - strict: Outcome::Revoked, - accept: Outcome::Revoked, - }, - Scenario { - name: "revoked intermediate", - leaf: Some(Served::Good), - intermediate: Served::Revoked, - relay: None, - strict: Outcome::Revoked, - accept: Outcome::Revoked, - }, - Scenario { - name: "leaf without CDP", - leaf: None, - intermediate: Served::Good, - relay: None, - strict: Outcome::Undetermined, - accept: Outcome::Pass, - }, - Scenario { - name: "leaf CRL HTTP 503", - leaf: Some(Served::Status(503)), - intermediate: Served::Good, - relay: None, - strict: Outcome::Undetermined, - accept: Outcome::Pass, - }, - Scenario { - name: "leaf CRL refused", - leaf: Some(Served::Refused), - intermediate: Served::Good, - relay: None, - strict: Outcome::Undetermined, - accept: Outcome::Pass, - }, - Scenario { - name: "leaf CRL timeout", - leaf: Some(Served::Timeout), - intermediate: Served::Good, - relay: None, - strict: Outcome::Undetermined, - accept: Outcome::Pass, - }, - Scenario { - name: "leaf CRL oversize", - leaf: Some(Served::Oversize), - intermediate: Served::Good, - relay: None, - strict: Outcome::Undetermined, - accept: Outcome::Pass, - }, - Scenario { - name: "leaf CRL expired", - leaf: Some(Served::Expired), - intermediate: Served::Good, - relay: None, - strict: Outcome::Undetermined, - accept: Outcome::Pass, - }, - Scenario { - name: "leaf CDP not http(s)", - leaf: Some(Served::NonHttp), - intermediate: Served::Good, - relay: None, - strict: Outcome::Undetermined, - accept: Outcome::Pass, - }, - Scenario { - name: "leaf CDP indirect (cRLIssuer)", - leaf: Some(Served::Indirect), - intermediate: Served::Good, - relay: None, - strict: Outcome::Undetermined, - accept: Outcome::Pass, - }, - Scenario { - name: "intermediate CRL HTTP 503", - leaf: Some(Served::Good), - intermediate: Served::Status(503), - relay: None, - strict: Outcome::Undetermined, - accept: Outcome::Pass, - }, - Scenario { - name: "leaf CRL wrong key", - leaf: Some(Served::WrongKey), - intermediate: Served::Good, - relay: None, - strict: Outcome::InvalidCrl, - accept: Outcome::InvalidCrl, - }, - Scenario { - name: "leaf CRL wrong issuer", - leaf: Some(Served::WrongIssuer), - intermediate: Served::Good, - relay: None, - strict: Outcome::InvalidCrl, - accept: Outcome::InvalidCrl, - }, - Scenario { - name: "good chain via proxy", - leaf: Some(Served::Good), - intermediate: Served::Good, - relay: Some(Relay::Forward), - strict: Outcome::Pass, - accept: Outcome::Pass, - }, - Scenario { - name: "revoked leaf via proxy", - leaf: Some(Served::Revoked), - intermediate: Served::Good, - relay: Some(Relay::Forward), - strict: Outcome::Revoked, - accept: Outcome::Revoked, - }, - Scenario { - name: "refused by proxy, no bypass", - leaf: Some(Served::Good), - intermediate: Served::Good, - relay: Some(Relay::Refuse), - strict: Outcome::Undetermined, - accept: Outcome::Pass, - }, + Scenario { name: "good chain", leaf: Some(Served::Good), intermediate: Served::Good, strict: Outcome::Pass, accept: Outcome::Pass }, + Scenario { name: "revoked leaf", leaf: Some(Served::Revoked), intermediate: Served::Good, strict: Outcome::Revoked, accept: Outcome::Revoked }, + Scenario { name: "revoked intermediate", leaf: Some(Served::Good), intermediate: Served::Revoked, strict: Outcome::Revoked, accept: Outcome::Revoked }, + Scenario { name: "unreachable leaf CRL", leaf: Some(Served::Refused), intermediate: Served::Good, strict: Outcome::Undetermined, accept: Outcome::Pass }, + Scenario { name: "unreachable intermediate CRL", leaf: Some(Served::Good), intermediate: Served::Refused, strict: Outcome::Undetermined, accept: Outcome::Pass }, + Scenario { name: "leaf without a distribution point", leaf: None, intermediate: Served::Good, strict: Outcome::Undetermined, accept: Outcome::Pass }, ]; struct Pki { @@ -263,33 +109,8 @@ fn ca_params(common_name: &str, serial: u64) -> CertificateParams { params } -/// The leaf's CRL distribution point. -enum LeafCdp { - None, - Uris(Vec), - /// An indirect point: `uri` as a full name, plus a cRLIssuer. - Indirect(String), -} - -/// A distribution point that is not http(s). Verifiers must ignore it. -const NON_HTTP_CDP: &str = "ldap://127.0.0.1/cn=crl"; - -/// A CRLDistributionPoints extension holding one indirect point. -fn indirect_cdp(uri: &str) -> CustomExtension { - let tlv = |tag: u8, content: &[u8]| { - assert!(content.len() < 128, "short-form DER only"); - let mut out = vec![tag, content.len() as u8]; - out.extend_from_slice(content); - out - }; - let full_name = tlv(0xA0, &tlv(0x86, uri.as_bytes())); - let point_name = tlv(0xA0, &full_name); - let issuer = tlv(0xA2, &tlv(0x86, b"http://crl-issuer.invalid/")); - let point = tlv(0x30, &[point_name, issuer].concat()); - CustomExtension::from_oid_content(&[2, 5, 29, 31], tlv(0x30, &point)) -} - -fn build_pki(leaf_cdp: LeafCdp, intermediate_cdp: String, san: &str) -> Pki { +/// The CRL distribution points of the leaf and the intermediate. +fn build_pki(leaf_cdp: Option>, intermediate_cdp: String, san: &str) -> Pki { let root_key = KeyPair::generate().unwrap(); let root_params = ca_params(ROOT_CN, 1); let root_cert = root_params.self_signed(&root_key).unwrap(); @@ -305,19 +126,14 @@ fn build_pki(leaf_cdp: LeafCdp, intermediate_cdp: String, san: &str) -> Pki { let intermediate_cert = intermediate_params .signed_by(&intermediate_key, &root_issuer) .unwrap(); - let intermediate_pem = intermediate_cert.pem(); let intermediate_der = intermediate_cert.der().clone(); let intermediate_issuer = Issuer::new(intermediate_params, intermediate_key); let leaf_key = KeyPair::generate().unwrap(); let mut leaf_params = CertificateParams::new(vec![san.to_owned()]).unwrap(); leaf_params.serial_number = Some(SerialNumber::from(LEAF_SERIAL)); - match leaf_cdp { - LeafCdp::None => {} - LeafCdp::Uris(uris) => { - leaf_params.crl_distribution_points = vec![CrlDistributionPoint { uris }]; - } - LeafCdp::Indirect(uri) => leaf_params.custom_extensions = vec![indirect_cdp(&uri)], + if let Some(uris) = leaf_cdp { + leaf_params.crl_distribution_points = vec![CrlDistributionPoint { uris }]; } let leaf_der = leaf_params .signed_by(&leaf_key, &intermediate_issuer) @@ -342,16 +158,16 @@ fn build_pki(leaf_cdp: LeafCdp, intermediate_cdp: String, san: &str) -> Pki { leaf_der, leaf_key_der: leaf_key.serialize_der(), // The mTLS identity presents the client leaf, then its intermediate. - client_cert_pem: format!("{}{intermediate_pem}", client_cert.pem()), + client_cert_pem: format!("{}{}", client_cert.pem(), intermediate_cert.pem()), client_key_pem: client_key.serialize_pem(), } } -/// A CRL listing `revoked` serials, valid until `next_update`. -fn sign_crl(issuer: &Issuer<'_, K>, revoked: &[u64], next_update: Ymd) -> Vec { +/// A CRL listing `revoked` serials, valid until `CURRENT`. +fn sign_crl(issuer: &Issuer<'_, K>, revoked: &[u64]) -> Vec { CertificateRevocationListParams { this_update: date_time_ymd(2020, 1, 1), - next_update: date_time_ymd(next_update.0, next_update.1, next_update.2), + next_update: date_time_ymd(CURRENT.0, CURRENT.1, CURRENT.2), crl_number: SerialNumber::from(1_u64), issuing_distribution_point: None, revoked_certs: revoked @@ -371,49 +187,14 @@ fn sign_crl(issuer: &Issuer<'_, K>, revoked: &[u64], next_update: .to_vec() } -/// The route for one CRL. `issuer` signs it, `covered` is the serial it revokes, -/// and `other` is the other CA (used for `WrongIssuer`). -fn route( - served: Served, - issuer: &Issuer<'_, KeyPair>, - issuer_cn: &str, - covered: u64, - other: &Issuer<'_, KeyPair>, -) -> Route { - let body = |bytes: Vec| Route { - status: 200, - body: bytes, - delay: Duration::ZERO, +/// The route for one CRL. `issuer` signs it, and `covered` is the serial it may revoke. +fn route(served: Served, issuer: &Issuer<'_, KeyPair>, covered: u64) -> Route { + let body = match served { + Served::Good => sign_crl(issuer, &[]), + Served::Revoked => sign_crl(issuer, &[covered]), + Served::Refused => unreachable!("a refused distribution point has no route"), }; - match served { - Served::Good => body(sign_crl(issuer, &[], CURRENT)), - Served::Revoked => body(sign_crl(issuer, &[covered], CURRENT)), - Served::WrongKey => { - let impostor = Issuer::new(ca_params(issuer_cn, 0), KeyPair::generate().unwrap()); - body(sign_crl(&impostor, &[covered], CURRENT)) - } - Served::WrongIssuer => body(sign_crl(other, &[], CURRENT)), - Served::Expired => body(sign_crl(issuer, &[], EXPIRED)), - Served::Status(status) => Route { - status, - body: Vec::new(), - delay: Duration::ZERO, - }, - Served::Slow => Route { - status: 200, - body: sign_crl(issuer, &[], CURRENT), - delay: Duration::from_millis(500), - }, - Served::Timeout => Route { - status: 200, - body: sign_crl(issuer, &[], CURRENT), - delay: Duration::from_secs(3), - }, - Served::Oversize => body(vec![0; 128 * 1024]), - Served::Refused | Served::NonHttp | Served::Indirect => { - unreachable!("this distribution point kind has no route") - } - } + Route { status: 200, body } } /// A PKI, its CRL origin server, and the TLS leaf server. @@ -423,59 +204,42 @@ struct Fixture { addr: SocketAddr, } +/// Each fixture's CRL paths are unique, so no two tests share a CRL URL. +static FIXTURE_ID: AtomicUsize = AtomicUsize::new(0); + fn fixture(leaf: Option, intermediate: Served, san: &str) -> Fixture { let crl = CrlServer::start(); + let id = FIXTURE_ID.fetch_add(1, Ordering::Relaxed); + let leaf_path = format!("/{id}/leaf.crl"); + let intermediate_path = format!("/{id}/intermediate.crl"); let dead = TcpListener::bind("127.0.0.1:0") .unwrap() .local_addr() .unwrap(); - let cdp = |served: Served, path: &str| match served { + let url = |served: Served, path: &str| match served { Served::Refused => format!("http://{dead}{path}"), _ => crl.url(path), }; - let leaf_cdp = match leaf { - None => LeafCdp::None, - Some(Served::NonHttp) => LeafCdp::Uris(vec![NON_HTTP_CDP.to_owned()]), - Some(Served::Indirect) => LeafCdp::Indirect(crl.url("/leaf.crl")), - Some(served) => LeafCdp::Uris(vec![cdp(served, "/leaf.crl")]), - }; - let pki = build_pki(leaf_cdp, cdp(intermediate, "/intermediate.crl"), san); - // An indirect point names a CRL that is served but must be skipped, so serve a good one. - let routed = match leaf { - Some(Served::Indirect) => Some(Served::Good), - Some(Served::Refused | Served::NonHttp) | None => None, - other => other, - }; - if let Some(served) = routed { + let leaf_cdp = leaf.map(|served| vec![url(served, &leaf_path)]); + let pki = build_pki(leaf_cdp, url(intermediate, &intermediate_path), san); + if let Some(served @ (Served::Good | Served::Revoked)) = leaf { crl.set( - "/leaf.crl", - route( - served, - &pki.intermediate_issuer, - INTERMEDIATE_CN, - LEAF_SERIAL, - &pki.root_issuer, - ), + &leaf_path, + route(served, &pki.intermediate_issuer, LEAF_SERIAL), ); } - if !matches!(intermediate, Served::Refused) { + if let served @ (Served::Good | Served::Revoked) = intermediate { crl.set( - "/intermediate.crl", - route( - intermediate, - &pki.root_issuer, - ROOT_CN, - INTERMEDIATE_SERIAL, - &pki.intermediate_issuer, - ), + &intermediate_path, + route(served, &pki.root_issuer, INTERMEDIATE_SERIAL), ); } let addr = spawn_tls_server(&pki, false); Fixture { crl, pki, addr } } -/// A TLS server presenting the leaf chain. With `mtls`, it requires a client -/// certificate that chains to the test root. +/// A TLS server presenting the leaf chain. With `mtls`, it requires a client certificate +/// that chains to the test root. fn spawn_tls_server(pki: &Pki, mtls: bool) -> SocketAddr { let chain = vec![pki.leaf_der.clone(), pki.intermediate_der.clone()]; let mtls_root = mtls.then(|| pki.root_der.clone()); @@ -533,6 +297,49 @@ fn spawn_tls_chain( addr } +/// A TLS server that keeps session state, and records the kind of each handshake it sees. +fn spawn_resuming_server(pki: &Pki) -> (SocketAddr, Arc>>) { + let provider = Arc::new(rustls::crypto::ring::default_provider()); + let mut config = rustls::ServerConfig::builder_with_provider(provider) + .with_safe_default_protocol_versions() + .unwrap() + .with_no_client_auth() + .with_single_cert( + vec![pki.leaf_der.clone(), pki.intermediate_der.clone()], + PrivatePkcs8KeyDer::from(pki.leaf_key_der.clone()).into(), + ) + .unwrap(); + config.session_storage = rustls::server::ServerSessionMemoryCache::new(32); + config.ticketer = rustls::crypto::ring::Ticketer::new().unwrap(); + let config = Arc::new(config); + let kinds = Arc::new(Mutex::new(Vec::new())); + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = listener.local_addr().unwrap(); + let recorded = Arc::clone(&kinds); + thread::spawn(move || { + for tcp in listener.incoming().flatten() { + let config = Arc::clone(&config); + let recorded = Arc::clone(&recorded); + thread::spawn(move || { + let Ok(conn) = rustls::ServerConnection::new(config) else { + return; + }; + let mut stream = rustls::StreamOwned::new(conn, tcp); + if read_head(&mut stream).is_some() { + if let Some(kind) = stream.conn.handshake_kind() { + recorded.lock().unwrap().push(kind); + } + let _ = stream.write_all( + b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok", + ); + let _ = stream.flush(); + } + }); + } + }); + (addr, kinds) +} + /// Reads one request or response head, up to the blank line. fn read_head(stream: &mut impl Read) -> Option { let mut head = Vec::new(); @@ -546,22 +353,18 @@ fn read_head(stream: &mut impl Read) -> Option { Some(String::from_utf8_lossy(&head).into_owned()) } -#[derive(Clone)] struct Route { status: u16, body: Vec, - delay: Duration, } -/// Loopback HTTP server for CRLs. It records each request head and answers from a -/// route table that can be filled after the PKI (which holds the URLs) exists. +/// Loopback HTTP server for CRLs. Its route table is filled after the PKI, which holds the +/// URLs, exists. It records the paths it receives. #[derive(Clone)] struct CrlServer { addr: SocketAddr, routes: Arc>>, - /// Paths that answer `302 Found` with the given `Location`. - redirects: Arc>>, - requests: Arc>>, + requests: Arc>>, } impl CrlServer { @@ -570,7 +373,6 @@ impl CrlServer { let server = Self { addr: listener.local_addr().unwrap(), routes: Arc::new(Mutex::new(HashMap::new())), - redirects: Arc::new(Mutex::new(HashMap::new())), requests: Arc::new(Mutex::new(Vec::new())), }; let accept_side = server.clone(); @@ -591,31 +393,9 @@ impl CrlServer { self.routes.lock().unwrap().insert(path.to_owned(), route); } - fn redirect(&self, path: &str, target: String) { - self.redirects - .lock() - .unwrap() - .insert(path.to_owned(), target); - } - - /// Requests received for `path`. - fn hits(&self, path: &str) -> usize { - self.requests - .lock() - .unwrap() - .iter() - .filter(|(seen, _)| seen == path) - .count() - } - - /// Every request head received, lower-cased. - fn headers(&self) -> String { - self.requests - .lock() - .unwrap() - .iter() - .map(|(_, head)| head.to_ascii_lowercase()) - .collect() + /// The number of requests received so far, for any path. + fn hits(&self) -> usize { + self.requests.lock().unwrap().len() } fn handle(&self, mut stream: TcpStream) { @@ -628,173 +408,32 @@ impl CrlServer { .and_then(|line| line.split_whitespace().nth(1)) .unwrap_or("/") .to_owned(); - self.requests.lock().unwrap().push((path.clone(), head)); - if let Some(target) = self.redirects.lock().unwrap().get(&path).cloned() { - let _ = stream.write_all( - format!( - "HTTP/1.1 302 Found\r\nLocation: {target}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n" - ) - .as_bytes(), - ); - return; - } - let route = self - .routes - .lock() - .unwrap() - .get(&path) - .cloned() - .unwrap_or(Route { - status: 404, - body: Vec::new(), - delay: Duration::ZERO, - }); - if !route.delay.is_zero() { - thread::sleep(route.delay); - } + self.requests.lock().unwrap().push(path.clone()); + let (status, body) = match self.routes.lock().unwrap().get(&path) { + Some(route) => (route.status, route.body.clone()), + None => (404, Vec::new()), + }; let mut response = format!( - "HTTP/1.1 {} X\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", - route.status, - route.body.len() + "HTTP/1.1 {status} X\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", + body.len() ) .into_bytes(); - response.extend_from_slice(&route.body); - // The client may have given up already (timeout case). + response.extend_from_slice(&body); let _ = stream.write_all(&response); } } -/// Loopback forward proxy. Plain requests arrive in absolute form and are recorded. -/// CONNECT is tunnelled, so the TLS leaf also connects through the proxy. -struct ForwardProxy { - addr: SocketAddr, - heads: Arc>>, -} - -impl ForwardProxy { - fn start(relay: Relay) -> Self { - let listener = TcpListener::bind("127.0.0.1:0").unwrap(); - let addr = listener.local_addr().unwrap(); - let heads = Arc::new(Mutex::new(Vec::new())); - let shared = Arc::clone(&heads); - thread::spawn(move || { - for client in listener.incoming().flatten() { - let heads = Arc::clone(&shared); - thread::spawn(move || handle_proxy_client(client, &heads, relay)); - } - }); - Self { addr, heads } - } - - /// Plain (non-CONNECT) request heads the proxy received. - fn plain_requests(&self) -> Vec { - self.heads - .lock() - .unwrap() - .iter() - .filter(|head| !head.starts_with("CONNECT ")) - .cloned() - .collect() - } -} - -fn handle_proxy_client(mut client: TcpStream, heads: &Mutex>, relay: Relay) { - let Some(head) = read_head(&mut client) else { - return; - }; - heads.lock().unwrap().push(head.clone()); - let mut request_line = head.lines().next().unwrap_or("").split_whitespace(); - let method = request_line.next().unwrap_or("").to_owned(); - let target = request_line.next().unwrap_or("").to_owned(); - let bad_gateway = b"HTTP/1.1 502 Bad Gateway\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"; - - if method == "CONNECT" { - if let Ok(upstream) = TcpStream::connect(&target) { - if client - .write_all(b"HTTP/1.1 200 Connection established\r\n\r\n") - .is_ok() - { - tunnel(client, upstream); - } - } - return; - } - if matches!(relay, Relay::Refuse) { - let _ = client.write_all(bad_gateway); - return; - } - // Absolute-form target: http://host:port/path. Forward it in origin form, minus - // the proxy-only headers, and relay the origin's response back. - let rest = target.strip_prefix("http://").unwrap_or(&target); - let (authority, path) = rest - .split_once('/') - .map_or((rest, "/".to_owned()), |(authority, path)| { - (authority, format!("/{path}")) - }); - let Ok(mut upstream) = TcpStream::connect(authority) else { - let _ = client.write_all(bad_gateway); - return; - }; - let mut forwarded = format!("{method} {path} HTTP/1.1\r\n"); - for line in head.split("\r\n").skip(1) { - if !line.is_empty() && !line.to_ascii_lowercase().starts_with("proxy-") { - forwarded.push_str(line); - forwarded.push_str("\r\n"); - } - } - forwarded.push_str("\r\n"); - if upstream.write_all(forwarded.as_bytes()).is_ok() { - let mut response = Vec::new(); - let _ = upstream.read_to_end(&mut response); - let _ = client.write_all(&response); - } -} - -/// Copies bytes both ways until either side closes. -fn tunnel(client: TcpStream, upstream: TcpStream) { - let (Ok(mut client_read), Ok(mut upstream_write)) = (client.try_clone(), upstream.try_clone()) - else { - return; - }; - let mut upstream_read = upstream; - let mut client_write = client; - let back = thread::spawn(move || { - let _ = std::io::copy(&mut upstream_read, &mut client_write); - }); - let _ = std::io::copy(&mut client_read, &mut upstream_write); - let _ = upstream_write.shutdown(Shutdown::Write); - let _ = back.join(); -} - -/// Sets the CRL fetch bounds for clients built on this test's thread. -fn set_fetch_limits(limits: CrlFetchLimits) { - TEST_CRL_LIMITS.with(|cell| cell.set(Some(limits))); -} - -/// The revocation policy for a test client: checking on, and an undetermined status -/// accepted when `accept_undetermined` is set. -fn policy(accept_undetermined: bool) -> Option { - Some(RevocationPolicy { - accept_undetermined, - }) -} - -/// Config that trusts the test root and fetches with short bounds. The revocation policy -/// is passed separately, as [`policy`]. +/// Config that trusts the test root. The revocation mode is passed separately. fn revocation_config(root_pem: &str) -> HttpClientConfig { let mut config = HttpClientConfig::default(); config.tls.trusted_certificate_pem = Some(root_pem.as_bytes().to_vec()); - set_fetch_limits(CrlFetchLimits { - timeout: Duration::from_millis(500), - max_bytes: 64 * 1024, - }); // No pooling: each request runs a fresh handshake and revocation check. config.max_connections_per_host = 0; config } /// A client built from `config` and `revocation`, with default retry configs. -fn client(config: HttpClientConfig, revocation: Option) -> DatabricksHttpClient { +fn client(config: HttpClientConfig, revocation: Option) -> DatabricksHttpClient { DatabricksHttpClient::with_revocation( config, build_retry_configs(&RetryConfig::default(), &HashMap::new()), @@ -803,9 +442,11 @@ fn client(config: HttpClientConfig, revocation: Option) -> Dat .unwrap() } +/// One GET to `addr`. `revocation` is `None` (off), `Some(false)` (strict) or +/// `Some(true)` (accept undetermined). async fn get( config: HttpClientConfig, - revocation: Option, + revocation: Option, addr: SocketAddr, ) -> std::result::Result<(), String> { let client = client(config, revocation); @@ -829,65 +470,17 @@ fn error_text(error: &dyn std::error::Error) -> String { text.to_ascii_lowercase() } -/// Runs one table row in one policy mode and checks the outcome, the proxy routing, -/// and that the CRL requests carry no auth or connection headers. +/// Runs one table row in one mode and checks the outcome. async fn check(scenario: &Scenario, accept: bool, want: Outcome) { let fx = fixture(scenario.leaf, scenario.intermediate, "127.0.0.1"); - let proxy = scenario.relay.map(ForwardProxy::start); - let mut config = revocation_config(&fx.pki.root_pem); - config.custom_headers = vec![("X-Kernel-Secret".to_owned(), "hunter2".to_owned())]; - config.org_id = Some("1234".to_owned()); - if let Some(proxy) = &proxy { - config.proxy.url = Some(format!("http://{}", proxy.addr)); - } - let label = format!("{} (accept_undetermined={accept})", scenario.name); - let result = get(config, policy(accept), fx.addr).await; + let result = get(revocation_config(&fx.pki.root_pem), Some(accept), fx.addr).await; match (want, &result) { (Outcome::Pass, Ok(())) => {} (Outcome::Revoked, Err(err)) => assert!(err.contains("revoked"), "{label}: {err}"), (Outcome::Undetermined, Err(err)) => assert!(err.contains(UNDETERMINED), "{label}: {err}"), - (Outcome::InvalidCrl, Err(err)) => { - assert!( - err.contains("revocation list") && !err.contains(UNDETERMINED), - "{label}: {err}" - ); - } _ => panic!("{label}: expected {want:?}, got {result:?}"), } - - let headers = fx.crl.headers(); - for forbidden in [ - "authorization", - "x-kernel-secret", - "x-databricks-org-id", - "cookie", - ] { - assert!( - !headers.contains(forbidden), - "{label}: CRL request carried {forbidden}: {headers}" - ); - } - match (scenario.relay, proxy) { - (Some(Relay::Forward), Some(proxy)) => { - assert!( - !proxy.plain_requests().is_empty(), - "{label}: CRL fetches must reach the proxy" - ); - } - (Some(Relay::Refuse), Some(proxy)) => { - assert!( - !proxy.plain_requests().is_empty(), - "{label}: CRL fetches must reach the proxy" - ); - assert_eq!( - fx.crl.hits("/leaf.crl") + fx.crl.hits("/intermediate.crl"), - 0, - "{label}: proxy refusal must not bypass to the origin" - ); - } - _ => {} - } } #[tokio::test] @@ -899,384 +492,64 @@ async fn revocation_outcomes_follow_the_policy_table() { } #[tokio::test] -async fn current_crl_is_fetched_once_and_a_rejected_one_is_refetched() { - let fx = fixture(Some(Served::Good), Served::Good, "127.0.0.1"); - let http = client(revocation_config(&fx.pki.root_pem), policy(false)); - for _ in 0..2 { - http.inner() - .get(format!("https://{}/", fx.addr)) - .send() - .await - .expect("good chain"); - } - assert_eq!( - fx.crl.hits("/leaf.crl"), - 1, - "a current CRL is cached until nextUpdate" - ); - assert_eq!(fx.crl.hits("/intermediate.crl"), 1); +async fn off_accepts_a_revoked_chain_and_fetches_nothing() { + // The same chain that the table rejects. With revocation off, it is not checked. + let fx = fixture(Some(Served::Revoked), Served::Good, "127.0.0.1"); + get(revocation_config(&fx.pki.root_pem), None, fx.addr) + .await + .expect("revocation off does not check the chain"); + assert_eq!(fx.crl.hits(), 0, "revocation off must not fetch any CRL"); +} - let fx = fixture(Some(Served::WrongKey), Served::Good, "127.0.0.1"); - let http = client(revocation_config(&fx.pki.root_pem), policy(false)); - for _ in 0..2 { - assert!(http - .inner() - .get(format!("https://{}/", fx.addr)) - .send() - .await - .is_err()); - } - assert_eq!( - fx.crl.hits("/leaf.crl"), - 2, - "a CRL that webpki rejects is not served from cache" - ); +#[tokio::test] +async fn self_signed_mode_turns_revocation_off() { + let fx = fixture(Some(Served::Revoked), Served::Good, "127.0.0.1"); + let mut config = revocation_config(&fx.pki.root_pem); + config.tls.allow_self_signed = Some(true); + get(config, Some(false), fx.addr) + .await + .expect("allow_self_signed turns revocation off"); + assert_eq!(fx.crl.hits(), 0, "allow_self_signed must not fetch any CRL"); } #[tokio::test] async fn hostname_mismatch_is_rejected_unless_allowed() { let fx = fixture(Some(Served::Good), Served::Good, "wrong-host.invalid"); - get(revocation_config(&fx.pki.root_pem), policy(false), fx.addr) + get(revocation_config(&fx.pki.root_pem), Some(false), fx.addr) .await .expect_err("a name mismatch is rejected by default"); let mut config = revocation_config(&fx.pki.root_pem); config.tls.allow_hostname_mismatch = Some(true); - get(config, policy(false), fx.addr) + get(config, Some(false), fx.addr) .await .expect("allow_hostname_mismatch passes a good chain with revocation still checked"); } #[tokio::test] -async fn client_identity_and_custom_ca_work_with_revocation() { +async fn client_identity_works_with_revocation() { let fx = fixture(Some(Served::Good), Served::Good, "127.0.0.1"); let mtls_addr = spawn_tls_server(&fx.pki, true); let mut config = revocation_config(&fx.pki.root_pem); config.tls.client_cert_pem = Some(fx.pki.client_cert_pem.clone().into_bytes()); config.tls.client_key_pem = Some(fx.pki.client_key_pem.clone().into_bytes()); - get(config.clone(), policy(false), mtls_addr) + get(config.clone(), Some(false), mtls_addr) .await .expect("mTLS identity passes with revocation"); config.tls.client_cert_pem = None; config.tls.client_key_pem = None; - get(config, policy(false), mtls_addr) + get(config, Some(false), mtls_addr) .await .expect_err("the mTLS server rejects a client without an identity"); } -#[tokio::test] -async fn policy_off_and_accept_self_signed_skip_revocation() { - let fx = fixture(Some(Served::Revoked), Served::Good, "127.0.0.1"); - get(revocation_config(&fx.pki.root_pem), None, fx.addr) - .await - .expect("policy off passes a revoked leaf"); - - let mut self_signed = revocation_config(&fx.pki.root_pem); - self_signed.tls.allow_self_signed = Some(true); - get(self_signed, policy(false), fx.addr) - .await - .expect("accept_self_signed turns revocation off"); - - assert_eq!( - fx.crl.hits("/leaf.crl"), - 0, - "no CRL is fetched when revocation is off" - ); -} - -#[tokio::test] -async fn unrelated_appended_certificate_is_never_fetched() { - // The server appends a certificate that no path needs, with its own distribution point. - let fx = fixture(Some(Served::Good), Served::Good, "127.0.0.1"); - let other_issuer = Issuer::new( - ca_params("Unrelated Test CA", 9), - KeyPair::generate().unwrap(), - ); - let other_key = KeyPair::generate().unwrap(); - let mut params = CertificateParams::new(vec!["unrelated.invalid".to_owned()]).unwrap(); - params.crl_distribution_points = vec![CrlDistributionPoint { - uris: vec![fx.crl.url("/unrelated.crl")], - }]; - let unrelated = params - .signed_by(&other_key, &other_issuer) - .unwrap() - .der() - .clone(); - fx.crl.set( - "/unrelated.crl", - route( - Served::Good, - &other_issuer, - "Unrelated Test CA", - 9, - &other_issuer, - ), - ); - let chain = vec![ - fx.pki.leaf_der.clone(), - fx.pki.intermediate_der.clone(), - unrelated, - ]; - let addr = spawn_tls_chain(chain, fx.pki.leaf_key_der.clone(), None); - get(revocation_config(&fx.pki.root_pem), policy(false), addr) - .await - .expect("the good path verifies; the appended certificate is not on it"); - assert_eq!( - fx.crl.hits("/unrelated.crl"), - 0, - "an unneeded certificate's distribution point is never fetched" - ); -} - -#[test] -fn same_name_certificate_with_another_key_is_not_a_trust_anchor() { - // Anchors match by subject and SPKI, as webpki matches them. The root's name with - // another key is not an anchor, so its distribution points are still checked. - let root_key = KeyPair::generate().unwrap(); - let root_der = ca_params(ROOT_CN, 1) - .self_signed(&root_key) - .unwrap() - .der() - .clone(); - let mut roots = RootCertStore::empty(); - roots.add(root_der.clone()).unwrap(); - let other_key = KeyPair::generate().unwrap(); - let same_name_der = ca_params(ROOT_CN, 2) - .self_signed(&other_key) - .unwrap() - .der() - .clone(); - let anchor = parse_cert(root_der.as_ref()).unwrap(); - let same_name = parse_cert(same_name_der.as_ref()).unwrap(); - assert!( - is_trust_anchor(&roots, &anchor), - "the anchor matches itself" - ); - assert!( - !is_trust_anchor(&roots, &same_name), - "a same-name certificate with another key is not an anchor" - ); -} - -#[tokio::test] -async fn one_timeout_budget_bounds_all_fetches_for_a_chain() { - // Both distribution points hang past the per-fetch timeout. Without a shared budget - // the two fetches take about two timeouts (about 4 s). With it, the chain takes about - // one (about 2 s). The bound of 3 s sits between the two, with about a second of slack - // on each side. - let fx = fixture(Some(Served::Timeout), Served::Timeout, "127.0.0.1"); - let config = revocation_config(&fx.pki.root_pem); - set_fetch_limits(CrlFetchLimits { - timeout: Duration::from_millis(2000), - max_bytes: 64 * 1024, - }); - let started = Instant::now(); - let err = get(config, policy(false), fx.addr) - .await - .expect_err("undetermined under strict"); - let elapsed = started.elapsed(); - assert!(err.contains(UNDETERMINED), "{err}"); - assert!( - elapsed < Duration::from_millis(3000), - "the fetches share one budget, but the check took {elapsed:?}" - ); -} - -#[tokio::test] -async fn final_verify_uses_only_the_checked_path() { - // Two intermediates share a name and key. Only the first is needed. The second is - // revoked, and its distribution point must neither be fetched nor used by webpki. - let crl = CrlServer::start(); - let root_key = KeyPair::generate().unwrap(); - let root_params = ca_params(ROOT_CN, 1); - let root_pem = root_params.self_signed(&root_key).unwrap().pem(); - let root_issuer = Issuer::new(root_params, root_key); - - let inter_key = KeyPair::generate().unwrap(); - let inter_pem = inter_key.serialize_pem(); - let good_der = signed_intermediate(&inter_key, 2001, crl.url("/good.crl"), &root_issuer); - let revoked_der = signed_intermediate( - &KeyPair::from_pem(&inter_pem).unwrap(), - 2002, - crl.url("/revoked.crl"), - &root_issuer, - ); - crl.set( - "/good.crl", - route(Served::Good, &root_issuer, ROOT_CN, 2001, &root_issuer), - ); - crl.set( - "/revoked.crl", - route(Served::Revoked, &root_issuer, ROOT_CN, 2002, &root_issuer), - ); - - let inter_issuer = Issuer::new( - ca_params(INTERMEDIATE_CN, 2001), - KeyPair::from_pem(&inter_pem).unwrap(), - ); - let mut leaf_params = CertificateParams::new(vec!["127.0.0.1".to_owned()]).unwrap(); - leaf_params.crl_distribution_points = vec![CrlDistributionPoint { - uris: vec![crl.url("/leaf.crl")], - }]; - let leaf_key = KeyPair::generate().unwrap(); - let leaf_der = leaf_params - .signed_by(&leaf_key, &inter_issuer) - .unwrap() - .der() - .clone(); - crl.set( - "/leaf.crl", - route( - Served::Good, - &inter_issuer, - INTERMEDIATE_CN, - LEAF_SERIAL, - &inter_issuer, - ), - ); - - let addr = spawn_tls_chain( - vec![leaf_der, good_der, revoked_der], - leaf_key.serialize_der(), - None, - ); - get(revocation_config(&root_pem), policy(false), addr) - .await - .expect("the checked path verifies; the unused revoked intermediate is ignored"); - assert_eq!( - crl.hits("/revoked.crl"), - 0, - "an intermediate off the checked path is never fetched" - ); -} - -/// A CA certificate with `serial`, a distribution point at `cdp`, signed by `issuer`. -fn signed_intermediate( - key: &KeyPair, - serial: u64, - cdp: String, - issuer: &Issuer<'_, KeyPair>, -) -> CertificateDer<'static> { - let mut params = ca_params(INTERMEDIATE_CN, serial); - params.crl_distribution_points = vec![CrlDistributionPoint { uris: vec![cdp] }]; - params.signed_by(key, issuer).unwrap().der().clone() -} - -#[test] -fn redacted_removes_userinfo_query_and_fragment() { - assert_eq!( - redacted("https://user:secret@crl.example.com/a.crl?token=abc#frag"), - "https://crl.example.com/a.crl" - ); - assert_eq!( - redacted("http://crl.example.com/ca.crl"), - "http://crl.example.com/ca.crl" - ); - assert_eq!(redacted("not a url"), ""); -} - -#[test] -fn intermediate_cap_allows_six_and_rejects_seven() { - // Six presented intermediates pass the cap and reach path selection, whatever it then - // decides. Seven fail at the cap with a message that names the limit. - let fx = fixture(Some(Served::Good), Served::Good, "127.0.0.1"); - let mut roots = RootCertStore::empty(); - roots.add(fx.pki.root_der.clone()).unwrap(); - let verifier = RevocationVerifier { - roots: Arc::new(roots.clone()), - provider: Arc::new(rustls::crypto::ring::default_provider()), - signatures: WebPkiServerVerifier::builder_with_provider( - Arc::new(roots), - Arc::new(rustls::crypto::ring::default_provider()), - ) - .build() - .unwrap(), - fetcher: CrlFetcher { - proxy: ProxyConfig::default(), - limits: CrlFetchLimits::default(), - custom_roots: Vec::new(), - cache: Mutex::new(HashMap::new()), - failed: Mutex::new(HashMap::new()), - worker: Mutex::new(None), - }, - accept_undetermined: false, - allow_hostname_mismatch: false, - }; - let end = &fx.pki.leaf_der; - let server_name = ServerName::try_from("127.0.0.1").unwrap(); - let now = UnixTime::now(); - - // Any outcome other than the cap error is fine here: the path search decides it. - let six = vec![fx.pki.intermediate_der.clone(); 6]; - if let Err(six_error) = verifier.path_intermediates(end, &six, &server_name, &[], now) { - assert!( - !six_error.to_string().contains("supports at most"), - "six intermediates must pass the cap: {six_error}" - ); - } - - let seven = vec![fx.pki.intermediate_der.clone(); 7]; - match verifier.path_intermediates(end, &seven, &server_name, &[], now) { - Err(error @ rustls::Error::InvalidCertificate(_)) => assert!( - error.to_string().contains( - "the server presented 7 intermediates; revocation checking supports at most 6" - ), - "unexpected message: {error}" - ), - other => panic!("seven intermediates must fail at the cap, got {other:?}"), - } -} - -/// A TLS server that allows session resumption and records the kind of each handshake. -fn spawn_resuming_server(pki: &Pki) -> (SocketAddr, Arc>>) { - let provider = Arc::new(rustls::crypto::ring::default_provider()); - let mut config = rustls::ServerConfig::builder_with_provider(provider) - .with_safe_default_protocol_versions() - .unwrap() - .with_no_client_auth() - .with_single_cert( - vec![pki.leaf_der.clone(), pki.intermediate_der.clone()], - PrivatePkcs8KeyDer::from(pki.leaf_key_der.clone()).into(), - ) - .unwrap(); - config.session_storage = rustls::server::ServerSessionMemoryCache::new(32); - config.ticketer = rustls::crypto::ring::Ticketer::new().unwrap(); - let config = Arc::new(config); - let kinds = Arc::new(Mutex::new(Vec::new())); - let listener = TcpListener::bind("127.0.0.1:0").unwrap(); - let addr = listener.local_addr().unwrap(); - let recorded = Arc::clone(&kinds); - thread::spawn(move || { - for tcp in listener.incoming().flatten() { - let config = Arc::clone(&config); - let recorded = Arc::clone(&recorded); - thread::spawn(move || { - let Ok(conn) = rustls::ServerConnection::new(config) else { - return; - }; - let mut stream = rustls::StreamOwned::new(conn, tcp); - if read_head(&mut stream).is_some() { - if let Some(kind) = stream.conn.handshake_kind() { - recorded.lock().unwrap().push(kind); - } - let _ = stream.write_all( - b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok", - ); - let _ = stream.flush(); - } - }); - } - }); - (addr, kinds) -} - #[tokio::test] async fn every_handshake_runs_the_revocation_check() { // A resumed session skips `verify_server_cert`. With resumption disabled on the client, // both connections are full handshakes, and so both run the check. let fx = fixture(Some(Served::Good), Served::Good, "127.0.0.1"); let (addr, kinds) = spawn_resuming_server(&fx.pki); - let http = client(revocation_config(&fx.pki.root_pem), policy(false)); + let http = client(revocation_config(&fx.pki.root_pem), Some(false)); for _ in 0..2 { http.inner() .get(format!("https://{addr}/")) @@ -1292,190 +565,38 @@ async fn every_handshake_runs_the_revocation_check() { } #[tokio::test] -async fn a_crl_redirect_is_not_followed_and_is_undetermined() { - // A redirect from the CRL endpoint could send the fetch to an internal address, so it is - // not followed. The 302 is undetermined: strict rejects, accept passes, and the target - // is never requested. - let fx = fixture(Some(Served::Good), Served::Good, "127.0.0.1"); - fx.crl.redirect("/leaf.crl", fx.crl.url("/target.crl")); - fx.crl.set( - "/target.crl", - route( - Served::Good, - &fx.pki.intermediate_issuer, - INTERMEDIATE_CN, - LEAF_SERIAL, - &fx.pki.root_issuer, - ), - ); - let err = get(revocation_config(&fx.pki.root_pem), policy(false), fx.addr) - .await - .expect_err("a redirected CRL is undetermined under strict"); - assert!(err.contains(UNDETERMINED), "{err}"); - get(revocation_config(&fx.pki.root_pem), policy(true), fx.addr) +async fn custom_ca_outside_the_windows_store_is_revocation_checked() { + // The fixture's root is a custom CA. Windows does not trust it, so the status comes from + // CryptoAPI's chain through the additional store, and a revoked leaf is still rejected. + let fx = fixture(Some(Served::Revoked), Served::Good, "127.0.0.1"); + let err = get(revocation_config(&fx.pki.root_pem), Some(false), fx.addr) .await - .expect("a redirected CRL passes under accept-undetermined"); - assert_eq!( - fx.crl.hits("/target.crl"), - 0, - "the redirect target is never requested" - ); -} - -#[tokio::test] -async fn a_failed_crl_fetch_is_not_retried_within_its_ttl() { - // The leaf's CRL endpoint returns 503. The first handshake waits for it and fails. The - // second, on the same client, does not ask again. - let fx = fixture(Some(Served::Status(503)), Served::Good, "127.0.0.1"); - let http = client(revocation_config(&fx.pki.root_pem), policy(false)); - for _ in 0..2 { - assert!(http - .inner() - .get(format!("https://{}/", fx.addr)) - .send() - .await - .is_err()); - } - assert_eq!( - fx.crl.hits("/leaf.crl"), - 1, - "a failed fetch is remembered for its TTL" - ); + .expect_err("a revoked leaf under a custom CA is rejected"); + assert!(err.contains("revoked"), "{err}"); + assert!(fx.crl.hits() > 0, "the custom CA chain must reach its CRL"); } #[tokio::test] -async fn a_usable_crl_stops_the_other_distribution_points() { - // The leaf names two distribution points. The first serves a usable CRL, so the - // second, which would hang, is never requested. - let crl = CrlServer::start(); - let pki = build_pki( - LeafCdp::Uris(vec![crl.url("/good.crl"), crl.url("/slow.crl")]), - crl.url("/intermediate.crl"), - "127.0.0.1", - ); - crl.set( - "/good.crl", - route( - Served::Good, - &pki.intermediate_issuer, - INTERMEDIATE_CN, - LEAF_SERIAL, - &pki.root_issuer, - ), - ); - crl.set( - "/slow.crl", - route( - Served::Timeout, - &pki.intermediate_issuer, - INTERMEDIATE_CN, - LEAF_SERIAL, - &pki.root_issuer, - ), - ); - crl.set( - "/intermediate.crl", - route( - Served::Good, - &pki.root_issuer, - ROOT_CN, - INTERMEDIATE_SERIAL, - &pki.intermediate_issuer, - ), - ); - let addr = spawn_tls_server(&pki, false); - get(revocation_config(&pki.root_pem), policy(false), addr) - .await - .expect("the usable CRL covers the leaf"); - assert_eq!( - crl.hits("/slow.crl"), - 0, - "a second distribution point is not fetched once a CRL is usable" - ); -} - -#[test] -fn crl_cache_drops_expired_entries_and_stays_within_its_caps() { - let mut cache: HashMap = HashMap::new(); - cache.insert("expired".to_owned(), (Arc::new(vec![0_u8; 8]), 5)); - for i in 0..(MAX_CACHED_CRLS + 10) { - cache.insert(format!("crl{i}"), (Arc::new(vec![0_u8; 8]), 100 + i as u64)); - } - trim_cache(&mut cache, 10); - assert!( - !cache.contains_key("expired"), - "expired entries are dropped" - ); - assert_eq!( - cache.len(), - MAX_CACHED_CRLS, - "the count cap keeps the entries that expire last" - ); - assert!(cache.contains_key(&format!("crl{}", MAX_CACHED_CRLS + 9))); - assert!( - !cache.contains_key("crl0"), - "the soonest to expire goes first" - ); - - // The byte cap: three 8 MiB entries exceed 16 MiB, so the soonest-expiring one goes. - let mut big: HashMap = HashMap::new(); - for i in 0..3_u64 { - big.insert( - format!("big{i}"), - (Arc::new(vec![0_u8; 8 * 1024 * 1024]), 100 + i), - ); - } - trim_cache(&mut big, 10); - assert_eq!(big.len(), 2, "the byte cap keeps the cache under 16 MiB"); - assert!(!big.contains_key("big0")); -} - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn concurrent_verifications_do_not_serialize_their_fetches() { - // Two handshakes verify at once, and each needs the same slow CRL. Serialized fetches - // take two half-second waits. Overlapping fetches take about one. - let fx = fixture(Some(Served::Slow), Served::Good, "127.0.0.1"); - let config = revocation_config(&fx.pki.root_pem); - set_fetch_limits(CrlFetchLimits { - timeout: Duration::from_millis(2000), - max_bytes: 64 * 1024, - }); - let http = client(config, policy(false)); - let url = format!("https://{}/", fx.addr); - let started = Instant::now(); - let first = tokio::spawn({ - let inner = http.inner().clone(); - let url = url.clone(); - async move { inner.get(url).send().await.map(|_| ()) } - }); - let second = tokio::spawn({ - let inner = http.inner().clone(); - async move { inner.get(url).send().await.map(|_| ()) } - }); - first.await.unwrap().expect("first verification passes"); - second.await.unwrap().expect("second verification passes"); - let elapsed = started.elapsed(); - assert!( - elapsed < Duration::from_millis(900), - "the two verifications' fetches serialized: {elapsed:?}" - ); -} - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn a_fetch_inside_a_multi_thread_runtime_completes() { - // The verifier waits for its CRL inside `block_in_place` on a multi-thread runtime. No - // other test runs that branch. +async fn unrelated_presented_certificate_does_not_change_the_result() { + // The server presents an extra certificate that is not on the chain. It has no CRL + // distribution point, and CryptoAPI never reaches it, so the good chain still passes. let fx = fixture(Some(Served::Good), Served::Good, "127.0.0.1"); - get(revocation_config(&fx.pki.root_pem), policy(false), fx.addr) + let unrelated_key = KeyPair::generate().unwrap(); + let unrelated = ca_params("Revocation Test Unrelated", 9) + .self_signed(&unrelated_key) + .unwrap() + .der() + .clone(); + let addr = spawn_tls_chain( + vec![ + fx.pki.leaf_der.clone(), + fx.pki.intermediate_der.clone(), + unrelated, + ], + fx.pki.leaf_key_der.clone(), + None, + ); + get(revocation_config(&fx.pki.root_pem), Some(false), addr) .await - .expect("good chain"); - assert_eq!(fx.crl.hits("/leaf.crl"), 1); -} - -#[test] -fn verifier_errors_are_certificate_verification_failures() { - let error = verifier_error("the server presented 7 intermediates".to_owned()); - assert!(crate::client::retry::is_certificate_verification_failure( - &error - )); + .expect("an unrelated presented certificate does not change the result"); } diff --git a/src/session.rs b/src/session.rs index e478ece1..5ae096d3 100644 --- a/src/session.rs +++ b/src/session.rs @@ -368,7 +368,7 @@ impl Session { let http_client_config = build_http_client_config(&config, org_id); // Checked before the client-construction wrapping below, so the // configuration error keeps its InvalidArgument category. - let revocation = crate::client::http::RevocationPolicy::from_options( + let revocation = crate::client::http::revocation_mode( config.tls.check_certificate_revocation, config.tls.accept_undetermined_certificate_revocation, ); @@ -3956,12 +3956,14 @@ mod is_open_tests { } } -#[cfg(all(test, not(feature = "tls-rustls")))] +/// Revocation is refused at open everywhere except Windows with `tls-rustls`. The +/// Windows success path is covered by the Windows-only verifier tests. +#[cfg(all(test, not(all(windows, feature = "tls-rustls"))))] mod revocation_open_tests { use super::*; #[tokio::test] - async fn revocation_on_tls_native_fails_open_as_invalid_argument() { + async fn revocation_on_unsupported_platform_fails_open_as_invalid_argument() { let config = SessionConfig { connection: ConnectionConfig::new("https://workspace.invalid", "test_wh"), defaults: None, @@ -3985,12 +3987,12 @@ mod revocation_open_tests { }; let error = Session::open(config) .await - .expect_err("tls-native must reject a revocation request"); + .expect_err("revocation must be refused on this platform or backend"); assert_eq!(error.code, crate::kernel_error::ErrorCode::InvalidArgument); assert!( error .message - .contains("certificate revocation checking requires the tls-rustls backend"), + .contains("TLS certificate revocation checking"), "{}", error.message ); From 0ea26cc2c7242f3def517d7ec5282d6753868a09 Mon Sep 17 00:00:00 2001 From: cat23123 <58714163+cat23123@users.noreply.github.com> Date: Fri, 20 Nov 2026 02:20:57 +0000 Subject: [PATCH 13/43] docs(tls): document Windows-only revocation checking Revocation is supported only on Windows with tls-rustls, where Windows CryptoAPI decides the status after webpki has verified the chain. Update the TlsConfig field docs, the C ABI setter's doc comment and header, the TLS design doc and the changelog to say so. They now cover: the check and what it covers (every chain certificate except the root); trust staying with webpki; the strict and accept-undetermined semantics, which match Simba; CRL and OCSP retrieval through Windows networking and proxy settings, with Windows caching the results; the 10 s accumulative fetch budget; session resumption being disabled while checking is on; and InvalidArgument on every other platform and on tls-native. Co-authored-by: Isaac Signed-off-by: cat23123 <58714163+cat23123@users.noreply.github.com> --- NEXT_CHANGELOG.md | 10 +++++++--- docs/designs/tls-config-design.md | 14 +++++++++----- include/databricks_kernel.h | 26 +++++++++++++++----------- src/c_abi/session.rs | 9 +++++---- src/config.rs | 25 ++++++++++++++----------- 5 files changed, 50 insertions(+), 34 deletions(-) diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index fbc999ba..2951156d 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -13,11 +13,15 @@ changes go in their respective binding's NEXT_CHANGELOG. - A native Rust ADBC 1.1 driver in `adbc/`, with an optional standard ADBC C ABI for driver-manager loading from other languages. -- Opt-in TLS certificate revocation checking, off by default (`tls-rustls` only; - `tls-native` fails session open with `InvalidArgument`). Set it with +- Opt-in TLS certificate revocation checking, off by default. It is supported + only on Windows with `tls-rustls`, where Windows CryptoAPI decides the status + after webpki has verified the chain. Requesting it anywhere else (including + `tls-native`) fails session open with `InvalidArgument`. Set it with `TlsConfig::check_certificate_revocation` and `TlsConfig::accept_undetermined_certificate_revocation`, or with - `kernel_session_config_set_tls_certificate_revocation`. + `kernel_session_config_set_tls_certificate_revocation`. CRL and OCSP fetches + use Windows' networking and proxy settings, and Windows caches their results. + Session resumption is disabled while revocation is on. ### Changed diff --git a/docs/designs/tls-config-design.md b/docs/designs/tls-config-design.md index 72eae659..ea6bcef5 100644 --- a/docs/designs/tls-config-design.md +++ b/docs/designs/tls-config-design.md @@ -245,7 +245,7 @@ E2E tests use mitmproxy as a TLS-intercepting proxy. The CI workflow (`.github/w | Self-signed certs / skip cert validation | `databricks.http.tls.allow_self_signed` | `adbc.http_options.tls.allow_self_signed` + `adbc.http_options.tls.disable_server_certificate_validation` | | Hostname mismatch | `databricks.http.tls.allow_hostname_mismatch` | `adbc.http_options.tls.allow_hostname_mismatch` | | Custom CA cert | `databricks.http.tls.trusted_certificate_path` | `adbc.http_options.tls.trusted_certificate_path` | -| Cert revocation mode | Opt-in on tls-rustls: `check_certificate_revocation`, `accept_undetermined_certificate_revocation` (default off; InvalidArgument on tls-native) | `adbc.http_options.tls.revocation_mode` (ADBC mapping out of scope) | +| Cert revocation mode | Opt-in, Windows with tls-rustls only: `check_certificate_revocation`, `accept_undetermined_certificate_revocation` (default off; InvalidArgument elsewhere). Checked by Windows CryptoAPI. | `adbc.http_options.tls.revocation_mode` (ADBC mapping out of scope) | ### Naming Convention Difference @@ -253,10 +253,14 @@ The Rust driver uses `databricks.http.tls.*` while the C# driver uses `adbc.http ### Scope Exclusions -- **Certificate revocation mode**: implemented in the kernel's tls-rustls verifier (CRL checks, opt-in, default off), not through reqwest. The ADBC `adbc.http_options.tls.revocation_mode` mapping is out of scope by the user's decision, so the ADBC driver gets no mapping. -- **Revocation and CRL destinations**: redirects are not followed, so a 3xx is undetermined. CRL distribution-point URLs come from certificates that chain to a trusted CA, and the kernel fetches them without destination filtering. This is a known residual limitation. -- **Revocation and drop**: dropping the CRL worker waits at most one per-fetch timeout for its thread. A fetch already past that timeout can outlive the wait and keep running after the drop. The kernel pins its own module when the first CRL worker starts, once per process: `GetModuleHandleExW` with `FROM_ADDRESS | PIN` on Windows, and `dladdr` followed by `dlopen(RTLD_NOW | RTLD_NOLOAD | RTLD_NODELETE)` on Unix. A pinned module is never unmapped, so the residual window is closed while the library is pinned. Trade-off: once revocation is first used, the library stays loaded for the rest of the process, even after the host unloads it. If the pin fails, the failure is logged at debug and the connection proceeds as before, so the window remains in that case. -- **Revocation and runtime flavor**: the rustls verifier is synchronous, so a handshake with revocation on waits, up to one 10 s budget per chain, for the CRLs it needs. The kernel's own runtimes are multi-thread (C ABI, telemetry, pyo3, napi). Only an external caller that drives the kernel on its own `current_thread` runtime can be stalled by that wait. +- **Certificate revocation is Windows-only**: the check exists only on Windows with `tls-rustls`, and is decided by Windows CryptoAPI (`CertGetCertificateChain`). On every other platform, and on `tls-native` (including Windows), requesting revocation fails session open with `InvalidArgument`, as an unsupported option does. The ODBC driver reads its CheckCertRevocation and AcceptUndeterminedRevocation keys only on Windows; elsewhere it warns and ignores them. The kernel does not port the check to Linux or macOS, and `tls-native` on Windows is not given a CryptoAPI path, because native-tls exposes no verifier hook and this keeps the surface smaller. +- **Trust stays with webpki**: the connection's webpki verifier, over the kernel's roots (webpki roots, the OS store, custom CAs), decides the chain, the name and the signatures, exactly as with revocation off. Only after that succeeds does CryptoAPI decide revocation. CryptoAPI builds its chain from the leaf, the presented intermediates and the custom CAs. It checks every certificate except the root. Only the chain-level revocation bits are read. The trust bits, including the root's, are ignored, so a custom CA that Windows does not trust is still checked, because the custom CAs are in CryptoAPI's additional store. +- **Chain choice**: CryptoAPI may build a different chain from the one webpki verified, for example through a cross-signed issuer. The status then comes from CryptoAPI's chain. The leaf is always checked. A server presenting more intermediates than it needs does not change the result. +- **Strict and accept-undetermined**: a revoked status is rejected in both modes. An undetermined status (a fetch failure, an offline status, a missing revocation URL, or a partial chain) is rejected in strict mode and accepted under accept-undetermined. This matches Simba's semantics. A partial chain is a root that Windows cannot build to and that is not a custom CA, for example a public root that appears only in the webpki bundle. Under strict mode that connection fails. +- **CRL and OCSP fetching**: CryptoAPI retrieves CRLs and OCSP responses through Windows' networking stack (WinHTTP) and its proxy settings, not through the kernel's `ProxyConfig`. Windows caches the results, so a certificate revoked after a CRL was cached may be accepted until the cache refreshes. The kernel adds no CRL cache, worker thread, redirect policy or size limit of its own. +- **Timeout**: CryptoAPI applies one 10 s budget to all the fetches of a chain (`CERT_CHAIN_REVOCATION_ACCUMULATIVE_TIMEOUT`). When the budget runs out, the status is undetermined. The kernel has no public knob for this budget. A handshake with revocation on waits for that budget at most. On a multi-thread runtime the wait runs in `block_in_place`, so the runtime's other tasks move off the thread. A caller that drives the kernel on its own `current_thread` runtime can be stalled by the wait. +- **Session resumption**: resumption is disabled whenever revocation is on, because a resumed handshake skips the server certificate verifier, and a certificate revoked after the first handshake would stay accepted. +- **Documented limits**: the check covers the chain that CryptoAPI builds, not every path that webpki might accept. Windows caches revocation data. The check uses Windows' network stack, so proxy settings and firewall rules that the kernel does not control can make a fetch fail. - **Client certificates (mTLS)**: Not needed per current requirements. Could be added later via `reqwest::ClientBuilder::identity()`. - **TLS version pinning**: Not needed. reqwest/native-tls negotiate the highest supported version automatically. diff --git a/include/databricks_kernel.h b/include/databricks_kernel.h index 5f5463b2..cf6057c0 100644 --- a/include/databricks_kernel.h +++ b/include/databricks_kernel.h @@ -470,18 +470,22 @@ KernelStatusCode kernel_session_config_set_tls_client_certificate( /* Enable or disable TLS certificate-revocation checking (default: off). * - * With `check_revocation` true, the server certificate chain (end-entity and - * intermediates) is checked against the CRLs named by its CRL distribution - * points. A revoked certificate is always rejected. `accept_undetermined` - * governs a status that cannot be determined (no distribution point, CRL fetch - * failure or timeout, non-200 or oversized response, expired CRL): false - * rejects it (strict), true accepts it. An invalid CRL signature or a CRL for - * the wrong issuer is always rejected. `check_revocation` false disables the - * check whatever `accept_undetermined` says. Revocation is also skipped when - * the self-signed setter is set. + * Supported only on Windows with the tls-rustls backend, where Windows CryptoAPI + * checks the revocation of the chain it builds for the server certificate, after + * webpki has verified the chain. A revoked certificate is always rejected. + * `accept_undetermined` governs a status that cannot be determined (a fetch + * failure or timeout, an offline status, a partial chain): false rejects it + * (strict), true accepts it. `check_revocation` false disables the check whatever + * `accept_undetermined` says. Revocation is also skipped when the self-signed + * setter is set. * - * Requires the tls-rustls backend; under tls-native, opening a session with - * `check_revocation` true fails and the error names the backend. */ + * CRL and OCSP retrieval uses Windows networking and proxy settings, not the + * kernel's proxy configuration, and Windows caches the results. Session + * resumption is disabled while checking is on. + * + * Requesting it on any other platform, or on tls-native, makes opening a session + * fail with InvalidArgument, and the error names the unsupported platform or + * backend. */ KernelStatusCode kernel_session_config_set_tls_certificate_revocation( KernelSessionConfig* config, bool check_revocation, bool accept_undetermined); diff --git a/src/c_abi/session.rs b/src/c_abi/session.rs index 9ab80a81..f9b18d3a 100644 --- a/src/c_abi/session.rs +++ b/src/c_abi/session.rs @@ -1303,10 +1303,11 @@ pub unsafe extern "C" fn kernel_session_config_set_tls_client_certificate( /// Enable or disable TLS certificate-revocation checking (default: off). /// /// `check_revocation` turns checking on. A revoked certificate is always -/// rejected. An undetermined status (no distribution point, CRL fetch failure, -/// expired CRL) is rejected unless `accept_undetermined` is true. Requires the -/// `tls-rustls` backend: under `tls-native`, opening a session with -/// `check_revocation` true fails with `InvalidArgument`. +/// rejected. An undetermined status (a fetch failure, an offline status, a +/// partial chain) is rejected unless `accept_undetermined` is true. Supported +/// only on Windows with the `tls-rustls` backend: elsewhere, and under +/// `tls-native`, opening a session with `check_revocation` true fails with +/// `InvalidArgument`. /// /// # Safety /// `config` must be a live config handle. diff --git a/src/config.rs b/src/config.rs index d60e542b..ef176221 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1042,22 +1042,25 @@ pub struct TlsConfig { /// backend-specific validation timing. pub client_key_pem: Option>, - /// Check the server chain's revocation status against its CRL distribution - /// points. Default off. Revoked certificates are always rejected. Requires - /// the `tls-rustls` backend; `tls-native` fails session open with - /// `InvalidArgument`. Disabled by [`Self::accept_self_signed`]. + /// Check the revocation status of the server certificate chain with Windows + /// CryptoAPI. Default off. Revoked certificates are always rejected. /// - /// CRL distribution-point URLs come from certificates that chain to a trusted CA, and the - /// kernel fetches them without destination filtering. + /// Supported only on Windows with the `tls-rustls` backend. Elsewhere, and on + /// `tls-native`, opening a session with this on fails with `InvalidArgument`. + /// Disabled by [`Self::accept_self_signed`]. /// - /// Each handshake waits, up to a 10 s budget per chain, for the CRLs it needs. The - /// kernel's own runtimes are multi-thread (C ABI, telemetry, pyo3 and napi), where that - /// wait moves the runtime's other tasks off the thread. Only a caller that drives the - /// kernel on its own `current_thread` runtime can be stalled by it. + /// Trust, name and signatures are still decided by webpki, as with checking off. + /// CryptoAPI then checks every certificate in the chain it builds except the root. + /// Only the revocation bits are read. The trust bits are ignored. CRL and OCSP + /// retrieval uses Windows networking and proxy settings, not [`ProxyConfig`], and + /// Windows caches the results. Each handshake waits at most 10 s in total for those + /// fetches. A caller on its own `current_thread` runtime can be stalled by that + /// wait. Session resumption is disabled while checking is on. pub check_certificate_revocation: Option, /// With [`Self::check_certificate_revocation`] on, accept a chain whose status - /// cannot be determined (no CRL, fetch failure, expired CRL). Default off. + /// cannot be determined (a fetch failure or timeout, an offline status, a partial + /// chain). Default off. Matches Simba's strict and accept-undetermined modes. pub accept_undetermined_certificate_revocation: Option, } From 8f629a819bd4d77668cb42ab486dbde970b7a362 Mon Sep 17 00:00:00 2001 From: cat23123 <58714163+cat23123@users.noreply.github.com> Date: Fri, 20 Nov 2026 02:21:14 +0000 Subject: [PATCH 14/43] chore(deps): refresh napi, pyo3 and adbc lockfiles for the revocation change The kernel no longer depends on der or libc, so the binding lockfiles drop those two edges. The lockfile check runs with --locked on all three workspaces. Co-authored-by: Isaac Signed-off-by: cat23123 <58714163+cat23123@users.noreply.github.com> --- adbc/Cargo.lock | 1 - napi/Cargo.lock | 2 -- pyo3/Cargo.lock | 2 -- 3 files changed, 5 deletions(-) diff --git a/adbc/Cargo.lock b/adbc/Cargo.lock index 12b07152..1132f626 100644 --- a/adbc/Cargo.lock +++ b/adbc/Cargo.lock @@ -666,7 +666,6 @@ dependencies = [ "hex", "hmac 0.13.0", "jsonwebtoken", - "libc", "lz4_flex", "moka", "native-tls", diff --git a/napi/Cargo.lock b/napi/Cargo.lock index 4693a172..95a3b928 100644 --- a/napi/Cargo.lock +++ b/napi/Cargo.lock @@ -619,14 +619,12 @@ dependencies = [ "cbc 0.2.1", "chrono", "dashmap", - "der", "dirs", "futures", "geo-traits", "hex", "hmac 0.13.0", "jsonwebtoken", - "libc", "lz4_flex", "moka", "oauth2", diff --git a/pyo3/Cargo.lock b/pyo3/Cargo.lock index cea0c648..51c4f47b 100644 --- a/pyo3/Cargo.lock +++ b/pyo3/Cargo.lock @@ -615,14 +615,12 @@ dependencies = [ "cbc 0.2.1", "chrono", "dashmap", - "der", "dirs", "futures", "geo-traits", "hex", "hmac 0.13.0", "jsonwebtoken", - "libc", "lz4_flex", "moka", "oauth2", From 0940953c773ab275ec1bc183d9ad516bf3c36c31 Mon Sep 17 00:00:00 2001 From: cat23123 <58714163+cat23123@users.noreply.github.com> Date: Fri, 20 Nov 2026 03:13:38 +0000 Subject: [PATCH 15/43] fix(config): show the revocation policy in TlsConfig's Debug output The hand-written Debug for the public TlsConfig listed every field except the two revocation options, so a logged config hid whether checking was on. Neither value is secret. Adds tls_config_debug_shows_revocation_policy. Co-authored-by: Isaac Signed-off-by: cat23123 <58714163+cat23123@users.noreply.github.com> --- src/config.rs | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/src/config.rs b/src/config.rs index ef176221..ae4f90d2 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1092,6 +1092,14 @@ impl std::fmt::Debug for TlsConfig { "client_key_pem", &self.client_key_pem.as_ref().map(|_| ""), ) + .field( + "check_certificate_revocation", + &self.check_certificate_revocation, + ) + .field( + "accept_undetermined_certificate_revocation", + &self.accept_undetermined_certificate_revocation, + ) .finish() } } @@ -2231,4 +2239,22 @@ mod tests { "expected cert byte-count summary, got: {s}" ); } + + #[test] + fn tls_config_debug_shows_revocation_policy() { + let tls = TlsConfig { + check_certificate_revocation: Some(true), + accept_undetermined_certificate_revocation: Some(false), + ..TlsConfig::default() + }; + let s = format!("{tls:?}"); + assert!( + s.contains("check_certificate_revocation: Some(true)"), + "revocation check missing from Debug: {s}" + ); + assert!( + s.contains("accept_undetermined_certificate_revocation: Some(false)"), + "accept-undetermined missing from Debug: {s}" + ); + } } From 7495c7ec2d11469842edf28a217c1b77da256e0d Mon Sep 17 00:00:00 2001 From: cat23123 <58714163+cat23123@users.noreply.github.com> Date: Fri, 20 Nov 2026 17:26:29 +0000 Subject: [PATCH 16/43] fix(tls): skip presented certificates CryptoAPI refuses An intermediate that webpki ignores could make CertAddCertificateContextToStore fail. That returned Undetermined before the leaf was checked, so a revoked leaf was accepted in accept-undetermined mode. A refused certificate is now skipped. Store and leaf failures stay undetermined. Adds a Windows test: a revoked leaf with an unusable presented intermediate is rejected in both modes. Co-authored-by: Isaac Signed-off-by: cat23123 <58714163+cat23123@users.noreply.github.com> --- docs/designs/tls-config-design.md | 2 +- src/client/tls_revocation.rs | 9 +++++---- src/client/tls_revocation_tests.rs | 26 ++++++++++++++++++++++++++ 3 files changed, 32 insertions(+), 5 deletions(-) diff --git a/docs/designs/tls-config-design.md b/docs/designs/tls-config-design.md index ea6bcef5..518ff0d0 100644 --- a/docs/designs/tls-config-design.md +++ b/docs/designs/tls-config-design.md @@ -255,7 +255,7 @@ The Rust driver uses `databricks.http.tls.*` while the C# driver uses `adbc.http - **Certificate revocation is Windows-only**: the check exists only on Windows with `tls-rustls`, and is decided by Windows CryptoAPI (`CertGetCertificateChain`). On every other platform, and on `tls-native` (including Windows), requesting revocation fails session open with `InvalidArgument`, as an unsupported option does. The ODBC driver reads its CheckCertRevocation and AcceptUndeterminedRevocation keys only on Windows; elsewhere it warns and ignores them. The kernel does not port the check to Linux or macOS, and `tls-native` on Windows is not given a CryptoAPI path, because native-tls exposes no verifier hook and this keeps the surface smaller. - **Trust stays with webpki**: the connection's webpki verifier, over the kernel's roots (webpki roots, the OS store, custom CAs), decides the chain, the name and the signatures, exactly as with revocation off. Only after that succeeds does CryptoAPI decide revocation. CryptoAPI builds its chain from the leaf, the presented intermediates and the custom CAs. It checks every certificate except the root. Only the chain-level revocation bits are read. The trust bits, including the root's, are ignored, so a custom CA that Windows does not trust is still checked, because the custom CAs are in CryptoAPI's additional store. -- **Chain choice**: CryptoAPI may build a different chain from the one webpki verified, for example through a cross-signed issuer. The status then comes from CryptoAPI's chain. The leaf is always checked. A server presenting more intermediates than it needs does not change the result. +- **Chain choice**: CryptoAPI may build a different chain from the one webpki verified, for example through a cross-signed issuer. The status then comes from CryptoAPI's chain. The leaf is always checked. A server presenting more intermediates than it needs does not change the result. A presented certificate that CryptoAPI refuses to add is skipped, so it cannot hide the leaf's status; a chain that needs it comes out partial and is undetermined. - **Strict and accept-undetermined**: a revoked status is rejected in both modes. An undetermined status (a fetch failure, an offline status, a missing revocation URL, or a partial chain) is rejected in strict mode and accepted under accept-undetermined. This matches Simba's semantics. A partial chain is a root that Windows cannot build to and that is not a custom CA, for example a public root that appears only in the webpki bundle. Under strict mode that connection fails. - **CRL and OCSP fetching**: CryptoAPI retrieves CRLs and OCSP responses through Windows' networking stack (WinHTTP) and its proxy settings, not through the kernel's `ProxyConfig`. Windows caches the results, so a certificate revoked after a CRL was cached may be accepted until the cache refreshes. The kernel adds no CRL cache, worker thread, redirect policy or size limit of its own. - **Timeout**: CryptoAPI applies one 10 s budget to all the fetches of a chain (`CERT_CHAIN_REVOCATION_ACCUMULATIVE_TIMEOUT`). When the budget runs out, the status is undetermined. The kernel has no public knob for this budget. A handshake with revocation on waits for that budget at most. On a multi-thread runtime the wait runs in `block_in_place`, so the runtime's other tasks move off the thread. A caller that drives the kernel on its own `current_thread` runtime can be stalled by the wait. diff --git a/src/client/tls_revocation.rs b/src/client/tls_revocation.rs index 41bde098..fa8c2926 100644 --- a/src/client/tls_revocation.rs +++ b/src/client/tls_revocation.rs @@ -78,7 +78,7 @@ impl Store { } /// Adds a copy of `der`. The store keeps its own reference, so the temporary context is - /// freed when it drops. + /// freed when it drops. Returns false when CryptoAPI refuses the certificate. fn add(&self, der: &[u8]) -> bool { let Some(context) = Context::new(der) else { return false; @@ -158,10 +158,11 @@ fn cryptoapi_status(leaf: &[u8], intermediates: &[&[u8]], custom_cas: &[&[u8]]) let Some(store) = Store::memory() else { return Status::Undetermined; }; + // A certificate that CryptoAPI refuses is skipped, not fatal. Webpki already ignored + // it, and it cannot hide the leaf's status. A chain that needs it comes out partial, + // which is undetermined. for der in intermediates.iter().chain(custom_cas) { - if !store.add(der) { - return Status::Undetermined; - } + store.add(der); } let Some(leaf) = Context::new(leaf) else { return Status::Undetermined; diff --git a/src/client/tls_revocation_tests.rs b/src/client/tls_revocation_tests.rs index 2e0c8e39..44de2a94 100644 --- a/src/client/tls_revocation_tests.rs +++ b/src/client/tls_revocation_tests.rs @@ -600,3 +600,29 @@ async fn unrelated_presented_certificate_does_not_change_the_result() { .await .expect("an unrelated presented certificate does not change the result"); } + +#[tokio::test] +async fn unusable_presented_intermediate_does_not_hide_a_revoked_leaf() { + // Webpki skips the garbage entry and verifies through the real intermediate. CryptoAPI + // refuses the garbage entry too, and that must not stop it from reading the leaf's status. + let fx = fixture(Some(Served::Revoked), Served::Good, "127.0.0.1"); + let garbage = CertificateDer::from(b"not a certificate".to_vec()); + let addr = spawn_tls_chain( + vec![ + fx.pki.leaf_der.clone(), + garbage, + fx.pki.intermediate_der.clone(), + ], + fx.pki.leaf_key_der.clone(), + None, + ); + for accept in [false, true] { + let err = get(revocation_config(&fx.pki.root_pem), Some(accept), addr) + .await + .expect_err("a revoked leaf is rejected in both modes"); + assert!( + err.contains("revoked"), + "accept_undetermined={accept}: {err}" + ); + } +} From 45ce73a645fc47515c29dbf00014e15a54d5766d Mon Sep 17 00:00:00 2001 From: cat23123 <58714163+cat23123@users.noreply.github.com> Date: Fri, 20 Nov 2026 17:26:31 +0000 Subject: [PATCH 17/43] build(tls): make rustls-native-certs a Windows-only dependency Only the Windows revocation module uses rustls-native-certs. The kernel's direct dependency is now a cfg(windows) optional dependency, enabled by the tls-rustls feature, the same as windows-sys. reqwest's rustls-tls-native-roots still pulls the crate on other platforms, so non-Windows tls-rustls builds compile it as before. Co-authored-by: Isaac Signed-off-by: cat23123 <58714163+cat23123@users.noreply.github.com> --- Cargo.toml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 489e761e..df579d51 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -65,9 +65,6 @@ rustls = { version = "0.23.41", optional = true, default-features = false, featu # Enforce TLS dependency minimums for consumers with their own lockfiles. rustls-webpki = { version = "0.103.16", optional = true, default-features = false } webpki-roots = { version = "1.0.11", optional = true, default-features = false } -# `tls-rustls` only. Loads the OS trust store for the revocation verifier on Windows (see -# `src/client/tls_revocation.rs`), the same store reqwest's `rustls-tls-native-roots` loads. -rustls-native-certs = { version = "0.8", optional = true } tokio = { version = "1", features = ["full", "sync"] } # Serialization @@ -152,6 +149,9 @@ pkcs8 = { version = "0.10", features = ["encryption", "pem", "std"] } # `windows-sys` is already in the lock file; no new packages. [target.'cfg(windows)'.dependencies] windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_Security_Cryptography"] } +# `tls-rustls` on Windows only. Loads the OS trust store for the revocation verifier (see +# `src/client/tls_revocation.rs`), the same store reqwest's `rustls-tls-native-roots` loads. +rustls-native-certs = { version = "0.8", optional = true } [dev-dependencies] tokio = { version = "1", features = ["rt-multi-thread", "macros", "net", "io-util"] } From fc83cf516caabf489bdc4cbc1f48862903aa47f7 Mon Sep 17 00:00:00 2001 From: cat23123 <58714163+cat23123@users.noreply.github.com> Date: Fri, 20 Nov 2026 17:26:36 +0000 Subject: [PATCH 18/43] ci(tls): run the Windows revocation module in PR checks The revocation module and its tests compile only on Windows, and no PR job ran on Windows. Adds a windows-revocation job, on the runner label and toolchain setup from release-debuginfo.yml, that runs clippy and the module tests for tls-rustls. Co-authored-by: Isaac Signed-off-by: cat23123 <58714163+cat23123@users.noreply.github.com> --- .github/workflows/pr-checks.yml | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/.github/workflows/pr-checks.yml b/.github/workflows/pr-checks.yml index f07393fe..f4be3a11 100644 --- a/.github/workflows/pr-checks.yml +++ b/.github/workflows/pr-checks.yml @@ -238,3 +238,35 @@ jobs: - name: Test client behavior (tls-rustls) run: "cargo test -p databricks-sql-kernel --no-default-features --features tls-rustls --lib client::" + + windows-revocation: + # The Windows-only revocation module (`client::tls_revocation`) and its tests compile + # only on Windows, so the Linux jobs above never build or run them. Same runner label + # and toolchain setup as the Windows job in `release-debuginfo.yml`. + name: Windows revocation (tls-rustls) + runs-on: + group: databricks-protected-runner-group + labels: [windows-server-latest] + timeout-minutes: 45 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + + - uses: ./.github/actions/setup-jfrog + with: + cargo: "true" + + - uses: actions-rust-lang/setup-rust-toolchain@166cdcfd11aee3cb47222f9ddb555ce30ddb9659 # v1.17.0 + with: + toolchain: stable + components: clippy + + - name: Set up MSVC environment + uses: ilammy/msvc-dev-cmd@0b201ec74fa43914dc39ae48a89fd1d8cb592756 # v1 + with: + arch: x64 + + - name: cargo clippy (tls-rustls, Windows) + run: cargo clippy -p databricks-sql-kernel --no-default-features --features tls-rustls --all-targets -- -D warnings + + - name: Test Windows revocation (tls-rustls) + run: cargo test -p databricks-sql-kernel --no-default-features --features tls-rustls --lib client::tls_revocation From 976bcf12cc5c5e02db45371525c210aa6c1dc7e9 Mon Sep 17 00:00:00 2001 From: cat23123 <58714163+cat23123@users.noreply.github.com> Date: Fri, 20 Nov 2026 17:46:22 +0000 Subject: [PATCH 19/43] ci(tls): run the Windows revocation job's cargo steps in pwsh The first run failed before compiling kernel code: under the runner's default bash (Git Bash), Git's coreutils `link` comes before MSVC's `link.exe` on PATH, so rustc could not link even the proc-macro2 build script. Run both cargo steps with `shell: pwsh`, as the Windows job in release-debuginfo.yml does. Co-authored-by: Isaac Signed-off-by: cat23123 <58714163+cat23123@users.noreply.github.com> --- .github/workflows/pr-checks.yml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.github/workflows/pr-checks.yml b/.github/workflows/pr-checks.yml index f4be3a11..c5f45ebd 100644 --- a/.github/workflows/pr-checks.yml +++ b/.github/workflows/pr-checks.yml @@ -265,8 +265,12 @@ jobs: with: arch: x64 + # pwsh, not the runner's default bash: Git Bash puts Git's coreutils `link` ahead of + # MSVC's `link.exe` on PATH, which breaks linking (as `release-debuginfo.yml` avoids). - name: cargo clippy (tls-rustls, Windows) + shell: pwsh run: cargo clippy -p databricks-sql-kernel --no-default-features --features tls-rustls --all-targets -- -D warnings - name: Test Windows revocation (tls-rustls) + shell: pwsh run: cargo test -p databricks-sql-kernel --no-default-features --features tls-rustls --lib client::tls_revocation From 65a87d8ed53cdc915066da7a12ca9af6b48448da Mon Sep 17 00:00:00 2001 From: cat23123 <58714163+cat23123@users.noreply.github.com> Date: Fri, 20 Nov 2026 18:04:09 +0000 Subject: [PATCH 20/43] refactor(tls): test the revocation support message on every platform The unsupported-platform message is now a pure function of (windows, rustls). Its four combinations are unit-tested on any host, so the Windows-with-tls-native branch is no longer untested. Co-authored-by: Isaac Signed-off-by: cat23123 <58714163+cat23123@users.noreply.github.com> --- src/client/http.rs | 49 +++++++++++++++---- ...cation_e2e.rs => v0_tls_revocation_e2e.rs} | 0 2 files changed, 39 insertions(+), 10 deletions(-) rename tests/{tls_revocation_e2e.rs => v0_tls_revocation_e2e.rs} (100%) diff --git a/src/client/http.rs b/src/client/http.rs index d391e76a..8ebabd75 100644 --- a/src/client/http.rs +++ b/src/client/http.rs @@ -208,22 +208,29 @@ pub(crate) fn revocation_mode( (check == Some(true)).then(|| accept_undetermined == Some(true)) } +/// The reason a revocation request cannot be honoured on this build, or `None` when it can. +/// Revocation is implemented only on Windows with `tls-rustls`. Pure, so every platform and +/// backend combination is testable on any host. +pub(crate) fn revocation_unsupported_message(windows: bool, rustls: bool) -> Option<&'static str> { + match (windows, rustls) { + (true, true) => None, + (true, false) => { + Some("TLS certificate revocation checking requires the tls-rustls backend") + } + (false, _) => Some("TLS certificate revocation checking is supported only on Windows"), + } +} + /// Rejects a revocation request that this platform or backend cannot honour, with -/// `InvalidArgument`. Revocation is implemented only on Windows with `tls-rustls`. -/// `allow_self_signed` turns revocation off, so it is not an error. +/// `InvalidArgument`. `allow_self_signed` turns revocation off, so it is not an error. pub(crate) fn check_revocation_support(tls: &TlsConfig, revocation: Option) -> Result<()> { if revocation.is_none() || tls.allow_self_signed == Some(true) { return Ok(()); } - if cfg!(all(windows, feature = "tls-rustls")) { - return Ok(()); + match revocation_unsupported_message(cfg!(windows), cfg!(feature = "tls-rustls")) { + Some(message) => Err(Error::invalid_argument().message(message)), + None => Ok(()), } - let message = if cfg!(windows) { - "TLS certificate revocation checking requires the tls-rustls backend" - } else { - "TLS certificate revocation checking is supported only on Windows" - }; - Err(Error::invalid_argument().message(message)) } impl std::fmt::Debug for TlsConfig { @@ -1142,6 +1149,28 @@ impl DatabricksHttpClient { #[path = "http_tls_tests.rs"] mod tls_tests; +#[cfg(test)] +mod revocation_support_tests { + use super::revocation_unsupported_message; + + #[test] + fn revocation_message_covers_every_platform_and_backend() { + assert_eq!(revocation_unsupported_message(true, true), None); + assert_eq!( + revocation_unsupported_message(true, false), + Some("TLS certificate revocation checking requires the tls-rustls backend") + ); + assert_eq!( + revocation_unsupported_message(false, true), + Some("TLS certificate revocation checking is supported only on Windows") + ); + assert_eq!( + revocation_unsupported_message(false, false), + Some("TLS certificate revocation checking is supported only on Windows") + ); + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/tests/tls_revocation_e2e.rs b/tests/v0_tls_revocation_e2e.rs similarity index 100% rename from tests/tls_revocation_e2e.rs rename to tests/v0_tls_revocation_e2e.rs From 6a98eecf736ca107b3e45ab7ade612f2d1f3ccc9 Mon Sep 17 00:00:00 2001 From: cat23123 <58714163+cat23123@users.noreply.github.com> Date: Fri, 20 Nov 2026 18:04:15 +0000 Subject: [PATCH 21/43] docs(tls): document the synchronous revocation check and its bounds The check runs inside the TLS handshake and blocks the calling task until CryptoAPI returns. A connect or operation timeout can therefore be exceeded by up to the revocation budget, including on multi-thread runtimes, and the whole runtime waits on current_thread. The 10 s bound covers CRL and OCSP retrieval only; AIA uses a per-URL timeout. Strict mode's undetermined status is a permanent certificate error by design, and AcceptUndeterminedRevocation is the way to tolerate transient outages. Co-authored-by: Isaac Signed-off-by: cat23123 <58714163+cat23123@users.noreply.github.com> --- NEXT_CHANGELOG.md | 5 ++++- docs/designs/tls-config-design.md | 3 ++- include/databricks_kernel.h | 6 +++++- src/config.rs | 17 ++++++++++++++--- 4 files changed, 25 insertions(+), 6 deletions(-) diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index 2951156d..25853cfa 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -21,7 +21,10 @@ changes go in their respective binding's NEXT_CHANGELOG. `TlsConfig::accept_undetermined_certificate_revocation`, or with `kernel_session_config_set_tls_certificate_revocation`. CRL and OCSP fetches use Windows' networking and proxy settings, and Windows caches their results. - Session resumption is disabled while revocation is on. + The check is synchronous and runs inside the TLS handshake, so a connect or + operation timeout can be exceeded by up to the revocation budget (about 10 s + for CRL and OCSP retrieval in total). Session resumption is disabled while + revocation is on. ### Changed diff --git a/docs/designs/tls-config-design.md b/docs/designs/tls-config-design.md index 518ff0d0..0814892a 100644 --- a/docs/designs/tls-config-design.md +++ b/docs/designs/tls-config-design.md @@ -258,7 +258,8 @@ The Rust driver uses `databricks.http.tls.*` while the C# driver uses `adbc.http - **Chain choice**: CryptoAPI may build a different chain from the one webpki verified, for example through a cross-signed issuer. The status then comes from CryptoAPI's chain. The leaf is always checked. A server presenting more intermediates than it needs does not change the result. A presented certificate that CryptoAPI refuses to add is skipped, so it cannot hide the leaf's status; a chain that needs it comes out partial and is undetermined. - **Strict and accept-undetermined**: a revoked status is rejected in both modes. An undetermined status (a fetch failure, an offline status, a missing revocation URL, or a partial chain) is rejected in strict mode and accepted under accept-undetermined. This matches Simba's semantics. A partial chain is a root that Windows cannot build to and that is not a custom CA, for example a public root that appears only in the webpki bundle. Under strict mode that connection fails. - **CRL and OCSP fetching**: CryptoAPI retrieves CRLs and OCSP responses through Windows' networking stack (WinHTTP) and its proxy settings, not through the kernel's `ProxyConfig`. Windows caches the results, so a certificate revoked after a CRL was cached may be accepted until the cache refreshes. The kernel adds no CRL cache, worker thread, redirect policy or size limit of its own. -- **Timeout**: CryptoAPI applies one 10 s budget to all the fetches of a chain (`CERT_CHAIN_REVOCATION_ACCUMULATIVE_TIMEOUT`). When the budget runs out, the status is undetermined. The kernel has no public knob for this budget. A handshake with revocation on waits for that budget at most. On a multi-thread runtime the wait runs in `block_in_place`, so the runtime's other tasks move off the thread. A caller that drives the kernel on its own `current_thread` runtime can be stalled by the wait. +- **Timeout**: CryptoAPI applies one 10 s budget to the CRL and OCSP fetches of a chain (`CERT_CHAIN_REVOCATION_ACCUMULATIVE_TIMEOUT`). When the budget runs out, the status is undetermined. AIA and other chain-building fetches are bounded per URL (`dwUrlRetrievalTimeout`, also 10 s), not in total, so the 10 s total is not guaranteed for a chain that needs them. The kernel has no public knob for either bound. +- **Blocking**: the check is synchronous, because rustls' verifier is. It runs inside the handshake poll and blocks until CryptoAPI returns. On a multi-thread runtime, `block_in_place` moves the worker's other tasks to another thread, but the calling task cannot be cancelled until CryptoAPI returns. A caller's connect or operation timeout can be exceeded by up to the revocation budget, with revocation on only. On a `current_thread` runtime the whole runtime waits. - **Session resumption**: resumption is disabled whenever revocation is on, because a resumed handshake skips the server certificate verifier, and a certificate revoked after the first handshake would stay accepted. - **Documented limits**: the check covers the chain that CryptoAPI builds, not every path that webpki might accept. Windows caches revocation data. The check uses Windows' network stack, so proxy settings and firewall rules that the kernel does not control can make a fetch fail. - **Client certificates (mTLS)**: Not needed per current requirements. Could be added later via `reqwest::ClientBuilder::identity()`. diff --git a/include/databricks_kernel.h b/include/databricks_kernel.h index cf6057c0..45d7db9f 100644 --- a/include/databricks_kernel.h +++ b/include/databricks_kernel.h @@ -480,7 +480,11 @@ KernelStatusCode kernel_session_config_set_tls_client_certificate( * setter is set. * * CRL and OCSP retrieval uses Windows networking and proxy settings, not the - * kernel's proxy configuration, and Windows caches the results. Session + * kernel's proxy configuration, and Windows caches the results. The check is + * synchronous: it blocks the calling thread's TLS handshake until CryptoAPI + * returns, so a connect or operation timeout can be exceeded by up to the + * revocation budget (about 10 s for CRL and OCSP retrieval in total; AIA and + * other chain-building fetches are bounded per URL, not in total). Session * resumption is disabled while checking is on. * * Requesting it on any other platform, or on tls-native, makes opening a session diff --git a/src/config.rs b/src/config.rs index ae4f90d2..9d9e4f95 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1053,14 +1053,25 @@ pub struct TlsConfig { /// CryptoAPI then checks every certificate in the chain it builds except the root. /// Only the revocation bits are read. The trust bits are ignored. CRL and OCSP /// retrieval uses Windows networking and proxy settings, not [`ProxyConfig`], and - /// Windows caches the results. Each handshake waits at most 10 s in total for those - /// fetches. A caller on its own `current_thread` runtime can be stalled by that - /// wait. Session resumption is disabled while checking is on. + /// Windows caches the results. The check is synchronous and runs inside the TLS + /// handshake, so it blocks the calling task until CryptoAPI returns, even on a + /// multi-thread runtime. A connect or operation timeout on that task can be exceeded + /// by up to the revocation budget (about 10 s for CRL and OCSP retrieval in total; + /// AIA and other chain-building fetches are bounded per URL, not in total). On a + /// `current_thread` runtime the whole runtime waits. Session resumption is disabled + /// while checking is on. pub check_certificate_revocation: Option, /// With [`Self::check_certificate_revocation`] on, accept a chain whose status /// cannot be determined (a fetch failure or timeout, an offline status, a partial /// chain). Default off. Matches Simba's strict and accept-undetermined modes. + /// + /// In strict mode (this option unset or false), an undetermined status is a + /// certificate error, and the kernel treats it as permanent: it is not retried. + /// That is by design, so a fetch outage fails the connection at once rather than + /// after retries. To tolerate transient revocation-service outages, set this option + /// (the ODBC driver's `AcceptUndeterminedRevocation=1`). A revoked status is + /// permanent in both modes. pub accept_undetermined_certificate_revocation: Option, } From 1fb2b46c2c0ecc83a7937acb006c19c2a2b93017 Mon Sep 17 00:00:00 2001 From: cat23123 <58714163+cat23123@users.noreply.github.com> Date: Fri, 20 Nov 2026 18:04:24 +0000 Subject: [PATCH 22/43] test(tls): log CryptoAPI chain state and CRL requests on Windows Test builds print the chain's shape and trust bits by name (chain, simple chains and elements), and GetLastError when CertGetCertificateChain fails. Each revocation case prints its result and the CRL paths requested, so a failing Windows run shows whether CryptoAPI fetched the CRLs. The module docs state that the check blocks the handshake, including on current_thread, and that the 10 s budget covers CRL and OCSP only. Co-authored-by: Isaac Signed-off-by: cat23123 <58714163+cat23123@users.noreply.github.com> --- src/client/tls_revocation.rs | 96 +++++++++++++++++++++++++++++- src/client/tls_revocation_tests.rs | 6 ++ 2 files changed, 100 insertions(+), 2 deletions(-) diff --git a/src/client/tls_revocation.rs b/src/client/tls_revocation.rs index fa8c2926..084a37fb 100644 --- a/src/client/tls_revocation.rs +++ b/src/client/tls_revocation.rs @@ -24,6 +24,13 @@ //! The decision reads the chain-level revocation bits only. The trust bits, including the //! root's, are ignored. //! +//! The check is synchronous, because rustls' verifier is. It runs inside the handshake poll +//! and blocks until CryptoAPI returns. On a multi-thread runtime, `block_in_place` lets the +//! worker's other tasks run elsewhere, but the calling task cannot be cancelled until +//! CryptoAPI returns. A caller's connect or operation timeout can therefore be exceeded by +//! up to the revocation budget. This applies only with revocation on. On a `current_thread` +//! runtime the whole runtime waits, because `block_in_place` is not used there. +//! //! This module is compiled only on Windows with `tls-rustls`. Elsewhere, revocation is //! rejected at session open. @@ -47,11 +54,23 @@ use windows_sys::Win32::Security::Cryptography::{ X509_ASN_ENCODING, }; +#[cfg(test)] +use windows_sys::Win32::Foundation::GetLastError; +// The four bits already imported above (OFFLINE_REVOCATION, PARTIAL_CHAIN, REVOKED, +// REVOCATION_STATUS_UNKNOWN) are not repeated here. +#[cfg(test)] +use windows_sys::Win32::Security::Cryptography::{ + CERT_TRUST_IS_CYCLIC, CERT_TRUST_IS_NOT_SIGNATURE_VALID, CERT_TRUST_IS_NOT_TIME_VALID, + CERT_TRUST_IS_NOT_VALID_FOR_USAGE, CERT_TRUST_IS_UNTRUSTED_ROOT, + CERT_TRUST_NO_ISSUANCE_CHAIN_POLICY, +}; + use super::http::TlsConfig; use crate::kernel_error::{Error, Result}; /// The budget for CRL and OCSP retrieval for one chain. CryptoAPI applies it to all of the -/// chain's fetches together (`CERT_CHAIN_REVOCATION_ACCUMULATIVE_TIMEOUT`). +/// chain's revocation fetches together (`CERT_CHAIN_REVOCATION_ACCUMULATIVE_TIMEOUT`). It does +/// not bound AIA or other chain-building fetches, which use the per-URL timeout only. const REVOCATION_TIMEOUT: Duration = Duration::from_secs(10); /// The chain flags: check every certificate except the root. const CHAIN_FLAGS: u32 = @@ -143,6 +162,69 @@ impl ChainContext { } } +#[cfg(test)] +impl ChainContext { + /// Test-only: the chain's shape and trust bits, by name, for diagnosing a failing run. + fn describe(&self) -> String { + // SAFETY: the chain is live for the call. Every read is of a field CryptoAPI sets, and + // each pointer is valid for the count that bounds it (`cChain`, `cElement`). + unsafe { + let chain = &*self.0; + let mut out = format!( + "cChain={} error=[{}] info=0x{:x}", + chain.cChain, + trust_names(chain.TrustStatus.dwErrorStatus), + chain.TrustStatus.dwInfoStatus + ); + for i in 0..chain.cChain as usize { + let simple = &**chain.rgpChain.add(i); + out += &format!( + " | simple[{i}] cElement={} error=[{}]", + simple.cElement, + trust_names(simple.TrustStatus.dwErrorStatus) + ); + for j in 0..simple.cElement as usize { + let element = &**simple.rgpElement.add(j); + out += &format!( + " | element[{j}] error=[{}] info=0x{:x} revocation_info={}", + trust_names(element.TrustStatus.dwErrorStatus), + element.TrustStatus.dwInfoStatus, + !element.pRevocationInfo.is_null() + ); + } + } + out + } + } +} + +/// Test-only: the names of the trust error bits set in `bits`. +#[cfg(test)] +fn trust_names(bits: u32) -> String { + const NAMES: &[(u32, &str)] = &[ + (CERT_TRUST_IS_NOT_TIME_VALID, "NOT_TIME_VALID"), + (CERT_TRUST_IS_REVOKED, "REVOKED"), + (CERT_TRUST_IS_NOT_SIGNATURE_VALID, "NOT_SIGNATURE_VALID"), + (CERT_TRUST_IS_NOT_VALID_FOR_USAGE, "NOT_VALID_FOR_USAGE"), + (CERT_TRUST_IS_UNTRUSTED_ROOT, "UNTRUSTED_ROOT"), + (CERT_TRUST_REVOCATION_STATUS_UNKNOWN, "REVOCATION_STATUS_UNKNOWN"), + (CERT_TRUST_IS_CYCLIC, "CYCLIC"), + (CERT_TRUST_IS_PARTIAL_CHAIN, "PARTIAL_CHAIN"), + (CERT_TRUST_IS_OFFLINE_REVOCATION, "OFFLINE_REVOCATION"), + (CERT_TRUST_NO_ISSUANCE_CHAIN_POLICY, "NO_ISSUANCE_CHAIN_POLICY"), + ]; + let names: Vec<&str> = NAMES + .iter() + .filter(|(bit, _)| bits & bit != 0) + .map(|(_, name)| *name) + .collect(); + if names.is_empty() { + "none".to_owned() + } else { + names.join(",") + } +} + impl Drop for ChainContext { fn drop(&mut self) { // SAFETY: the chain came from `CertGetCertificateChain` and is freed once. @@ -169,6 +251,7 @@ fn cryptoapi_status(leaf: &[u8], intermediates: &[&[u8]], custom_cas: &[&[u8]]) }; let para = CERT_CHAIN_PARA { cbSize: std::mem::size_of::() as u32, + // Per-URL timeout for chain-building fetches (AIA). It is not a total. dwUrlRetrievalTimeout: REVOCATION_TIMEOUT.as_millis() as u32, ..Default::default() }; @@ -188,9 +271,18 @@ fn cryptoapi_status(leaf: &[u8], intermediates: &[&[u8]], custom_cas: &[&[u8]]) ) }; if built == 0 || chain.is_null() { + // SAFETY: GetLastError reads the calling thread's last error and has no other effect. + #[cfg(test)] + eprintln!( + "revocation diagnostics: CertGetCertificateChain failed, GetLastError={}", + unsafe { GetLastError() } + ); return Status::Undetermined; } - ChainContext(chain).status() + let chain = ChainContext(chain); + #[cfg(test)] + eprintln!("revocation diagnostics: {}", chain.describe()); + chain.status() } /// Runs a blocking wait. On a multi-thread runtime, block_in_place moves the worker's diff --git a/src/client/tls_revocation_tests.rs b/src/client/tls_revocation_tests.rs index 44de2a94..fa6de193 100644 --- a/src/client/tls_revocation_tests.rs +++ b/src/client/tls_revocation_tests.rs @@ -398,6 +398,11 @@ impl CrlServer { self.requests.lock().unwrap().len() } + /// The request paths received so far, in order, for diagnosing a failing run. + fn paths(&self) -> Vec { + self.requests.lock().unwrap().clone() + } + fn handle(&self, mut stream: TcpStream) { let Some(head) = read_head(&mut stream) else { return; @@ -475,6 +480,7 @@ async fn check(scenario: &Scenario, accept: bool, want: Outcome) { let fx = fixture(scenario.leaf, scenario.intermediate, "127.0.0.1"); let label = format!("{} (accept_undetermined={accept})", scenario.name); let result = get(revocation_config(&fx.pki.root_pem), Some(accept), fx.addr).await; + eprintln!("{label}: result={result:?} crl_requests={:?}", fx.crl.paths()); match (want, &result) { (Outcome::Pass, Ok(())) => {} (Outcome::Revoked, Err(err)) => assert!(err.contains("revoked"), "{label}: {err}"), From 20c261a188ef3f9416235908ed6ba405addea66f Mon Sep 17 00:00:00 2001 From: cat23123 <58714163+cat23123@users.noreply.github.com> Date: Fri, 20 Nov 2026 18:04:36 +0000 Subject: [PATCH 23/43] test(tls): rename the revocation live test to v0_ naming The e2e test becomes tests/v0_tls_revocation_e2e.rs, matching the other live tests. Its module docs note that strict and accept_undetermined work only on Windows with tls-rustls. Co-authored-by: Isaac Signed-off-by: cat23123 <58714163+cat23123@users.noreply.github.com> --- tests/v0_tls_revocation_e2e.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/tests/v0_tls_revocation_e2e.rs b/tests/v0_tls_revocation_e2e.rs index caf31723..d9f2bc41 100644 --- a/tests/v0_tls_revocation_e2e.rs +++ b/tests/v0_tls_revocation_e2e.rs @@ -16,10 +16,12 @@ //! //! ```sh //! DATABRICKS_TEST_REVOCATION=strict cargo test --no-default-features \ -//! --features tls-rustls --test tls_revocation_e2e -- --ignored --nocapture +//! --features tls-rustls --test v0_tls_revocation_e2e -- --ignored --nocapture //! ``` //! -//! `DATABRICKS_TEST_REVOCATION` is `off`, `strict` or `accept_undetermined`. +//! `DATABRICKS_TEST_REVOCATION` is `off`, `strict` or `accept_undetermined`. `strict` and +//! `accept_undetermined` work only on Windows with `tls-rustls`. Elsewhere, opening the +//! session fails with `InvalidArgument`. mod common; From 84edcd1c016b4347f2b8bb8cdcf5d61da3206363 Mon Sep 17 00:00:00 2001 From: cat23123 <58714163+cat23123@users.noreply.github.com> Date: Fri, 20 Nov 2026 18:04:42 +0000 Subject: [PATCH 24/43] ci(tls): run the whole client suite on Windows The Windows job runs cargo test for client:: rather than only the revocation module, so the http.rs revocation-support test and the revocation-off TLS tests also run on Windows. Co-authored-by: Isaac Signed-off-by: cat23123 <58714163+cat23123@users.noreply.github.com> --- .github/workflows/pr-checks.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/pr-checks.yml b/.github/workflows/pr-checks.yml index c5f45ebd..8031c460 100644 --- a/.github/workflows/pr-checks.yml +++ b/.github/workflows/pr-checks.yml @@ -271,6 +271,6 @@ jobs: shell: pwsh run: cargo clippy -p databricks-sql-kernel --no-default-features --features tls-rustls --all-targets -- -D warnings - - name: Test Windows revocation (tls-rustls) + - name: Test client behavior (tls-rustls, Windows) shell: pwsh - run: cargo test -p databricks-sql-kernel --no-default-features --features tls-rustls --lib client::tls_revocation + run: cargo test -p databricks-sql-kernel --no-default-features --features tls-rustls --lib client:: From ee783ea87026422afae8e65e53ef1f6f789a01a6 Mon Sep 17 00:00:00 2001 From: cat23123 <58714163+cat23123@users.noreply.github.com> Date: Fri, 20 Nov 2026 18:15:34 +0000 Subject: [PATCH 25/43] fix(tls): retry an undetermined chain with a custom-root engine With a custom CA, Windows does not trust its root. The default chain engine can then end the chain at an untrusted root and report no revocation status, so every custom-root check came out undetermined. When the default result is undetermined and custom CAs are configured, the chain is built again with an engine whose exclusive root is the custom CAs, and that result is used. Webpki still decides trust. This is a hypothesis from the Windows CI failures; it is not yet confirmed on Windows, and the diagnostics in the previous commit show the engine that produced each result. The engine is freed on every path. Co-authored-by: Isaac Signed-off-by: cat23123 <58714163+cat23123@users.noreply.github.com> --- src/client/tls_revocation.rs | 83 ++++++++++++++++++++++++++++++------ 1 file changed, 70 insertions(+), 13 deletions(-) diff --git a/src/client/tls_revocation.rs b/src/client/tls_revocation.rs index 084a37fb..9c9a66c0 100644 --- a/src/client/tls_revocation.rs +++ b/src/client/tls_revocation.rs @@ -45,13 +45,14 @@ use rustls::{ CertificateError, ClientConfig, DigitallySignedStruct, RootCertStore, SignatureScheme, }; use windows_sys::Win32::Security::Cryptography::{ - CertAddCertificateContextToStore, CertCloseStore, CertCreateCertificateContext, - CertFreeCertificateChain, CertFreeCertificateContext, CertGetCertificateChain, CertOpenStore, - CERT_CHAIN_CONTEXT, CERT_CHAIN_PARA, CERT_CHAIN_REVOCATION_ACCUMULATIVE_TIMEOUT, + CertAddCertificateContextToStore, CertCloseStore, CertCreateCertificateChainEngine, + CertCreateCertificateContext, CertFreeCertificateChain, CertFreeCertificateChainEngine, + CertFreeCertificateContext, CertGetCertificateChain, CertOpenStore, CERT_CHAIN_CONTEXT, + CERT_CHAIN_ENGINE_CONFIG, CERT_CHAIN_PARA, CERT_CHAIN_REVOCATION_ACCUMULATIVE_TIMEOUT, CERT_CHAIN_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT, CERT_CONTEXT, CERT_STORE_ADD_ALWAYS, CERT_STORE_PROV_MEMORY, CERT_TRUST_IS_OFFLINE_REVOCATION, CERT_TRUST_IS_PARTIAL_CHAIN, - CERT_TRUST_IS_REVOKED, CERT_TRUST_REVOCATION_STATUS_UNKNOWN, HCERTSTORE, PKCS_7_ASN_ENCODING, - X509_ASN_ENCODING, + CERT_TRUST_IS_REVOKED, CERT_TRUST_REVOCATION_STATUS_UNKNOWN, HCERTCHAINENGINE, HCERTSTORE, + PKCS_7_ASN_ENCODING, X509_ASN_ENCODING, }; #[cfg(test)] @@ -207,11 +208,17 @@ fn trust_names(bits: u32) -> String { (CERT_TRUST_IS_NOT_SIGNATURE_VALID, "NOT_SIGNATURE_VALID"), (CERT_TRUST_IS_NOT_VALID_FOR_USAGE, "NOT_VALID_FOR_USAGE"), (CERT_TRUST_IS_UNTRUSTED_ROOT, "UNTRUSTED_ROOT"), - (CERT_TRUST_REVOCATION_STATUS_UNKNOWN, "REVOCATION_STATUS_UNKNOWN"), + ( + CERT_TRUST_REVOCATION_STATUS_UNKNOWN, + "REVOCATION_STATUS_UNKNOWN", + ), (CERT_TRUST_IS_CYCLIC, "CYCLIC"), (CERT_TRUST_IS_PARTIAL_CHAIN, "PARTIAL_CHAIN"), (CERT_TRUST_IS_OFFLINE_REVOCATION, "OFFLINE_REVOCATION"), - (CERT_TRUST_NO_ISSUANCE_CHAIN_POLICY, "NO_ISSUANCE_CHAIN_POLICY"), + ( + CERT_TRUST_NO_ISSUANCE_CHAIN_POLICY, + "NO_ISSUANCE_CHAIN_POLICY", + ), ]; let names: Vec<&str> = NAMES .iter() @@ -249,6 +256,31 @@ fn cryptoapi_status(leaf: &[u8], intermediates: &[&[u8]], custom_cas: &[&[u8]]) let Some(leaf) = Context::new(leaf) else { return Status::Undetermined; }; + let status = chain_status("default engine", &leaf, &store, null_mut()); + // With a custom CA, Windows does not trust its root. The default engine can then end the + // chain at an untrusted root and report no revocation status, so the result is undetermined. + // Build again with an engine whose exclusive root is the custom CAs, which makes the chain + // complete for this check. Webpki still decides trust, and only the revocation bits are read. + if status != Status::Undetermined || custom_cas.is_empty() { + return status; + } + let Some(roots) = Store::memory() else { + return status; + }; + for der in custom_cas { + roots.add(der); + } + let Some(engine) = ChainEngine::exclusive(&roots) else { + return status; + }; + chain_status("exclusive-root engine", &leaf, &store, engine.0) +} + +/// Builds the chain for `leaf` with `engine` (null is the default engine) and reads its +/// revocation status. `label` names the engine in the test-only diagnostics. +fn chain_status(label: &str, leaf: &Context, store: &Store, engine: HCERTCHAINENGINE) -> Status { + // Only the test-only diagnostics below read `label`. + let _ = label; let para = CERT_CHAIN_PARA { cbSize: std::mem::size_of::() as u32, // Per-URL timeout for chain-building fetches (AIA). It is not a total. @@ -256,11 +288,11 @@ fn cryptoapi_status(leaf: &[u8], intermediates: &[&[u8]], custom_cas: &[&[u8]]) ..Default::default() }; let mut chain: *mut CERT_CHAIN_CONTEXT = null_mut(); - // SAFETY: the leaf and store are live, and `para` outlives the call. The null chain - // engine is the default, and null time is now. + // SAFETY: the engine, leaf and store are live for the call, and `para` outlives it. Null + // time is now. let built = unsafe { CertGetCertificateChain( - null_mut(), + engine, leaf.0, null(), store.0, @@ -274,17 +306,42 @@ fn cryptoapi_status(leaf: &[u8], intermediates: &[&[u8]], custom_cas: &[&[u8]]) // SAFETY: GetLastError reads the calling thread's last error and has no other effect. #[cfg(test)] eprintln!( - "revocation diagnostics: CertGetCertificateChain failed, GetLastError={}", + "revocation diagnostics [{label}]: CertGetCertificateChain failed, GetLastError={}", unsafe { GetLastError() } ); return Status::Undetermined; } let chain = ChainContext(chain); #[cfg(test)] - eprintln!("revocation diagnostics: {}", chain.describe()); + eprintln!("revocation diagnostics [{label}]: {}", chain.describe()); chain.status() } +/// A chain engine whose exclusive root is a store of custom CAs. Freed on drop. +struct ChainEngine(HCERTCHAINENGINE); + +impl ChainEngine { + fn exclusive(roots: &Store) -> Option { + let config = CERT_CHAIN_ENGINE_CONFIG { + cbSize: std::mem::size_of::() as u32, + hExclusiveRoot: roots.0, + ..Default::default() + }; + let mut engine: HCERTCHAINENGINE = null_mut(); + // SAFETY: `config` and the root store are live for the call, and `engine` is written + // only on success. + let created = unsafe { CertCreateCertificateChainEngine(&config, &mut engine) }; + (created != 0 && !engine.is_null()).then_some(Self(engine)) + } +} + +impl Drop for ChainEngine { + fn drop(&mut self) { + // SAFETY: the engine came from `CertCreateCertificateChainEngine` and is freed once. + unsafe { CertFreeCertificateChainEngine(self.0) }; + } +} + /// Runs a blocking wait. On a multi-thread runtime, block_in_place moves the worker's /// other tasks to another thread first. It panics on current_thread, so the wait runs as /// it is there. @@ -472,4 +529,4 @@ pub(crate) fn client_config(tls: &TlsConfig, accept_undetermined: bool) -> Resul #[cfg(test)] #[path = "tls_revocation_tests.rs"] -mod tests; +pub(crate) mod tests; From 6efc95b74ecf3dc9e177632c988d262206ba8cbe Mon Sep 17 00:00:00 2001 From: cat23123 <58714163+cat23123@users.noreply.github.com> Date: Fri, 20 Nov 2026 18:15:37 +0000 Subject: [PATCH 26/43] test(tls): cover a strict C ABI open against a revoked leaf on Windows On Windows with tls-rustls, a session opened through the C ABI with strict revocation fails when its leaf is revoked by the fixture's CRL. The failure is in the TLS handshake before any HTTP request, so no SEA server is needed. The revocation fixture is now visible to the C ABI tests. Co-authored-by: Isaac Signed-off-by: cat23123 <58714163+cat23123@users.noreply.github.com> --- src/c_abi/session.rs | 52 ++++++++++++++++++++++++++++++ src/client/tls_revocation_tests.rs | 19 ++++++----- 2 files changed, 63 insertions(+), 8 deletions(-) diff --git a/src/c_abi/session.rs b/src/c_abi/session.rs index f9b18d3a..8532d3cb 100644 --- a/src/c_abi/session.rs +++ b/src/c_abi/session.rs @@ -3510,4 +3510,56 @@ mod revocation_open_tests { ); } } + + /// Strict revocation through the C ABI, on Windows with tls-rustls: a leaf that its CRL + /// revokes fails session open. The TLS endpoint is a local server, and its chain and CRL + /// come from the revocation test fixture. The failure is in the TLS handshake, before any + /// HTTP request, so no SEA server is needed. + #[cfg(all(windows, feature = "tls-rustls"))] + #[test] + fn tls_revocation_strict_open_rejects_a_revoked_leaf() { + use crate::client::tls_revocation::tests::{fixture, Served}; + + let fx = fixture(Some(Served::Revoked), Served::Good, "127.0.0.1"); + let host = CString::new(format!("https://{}", fx.addr)).unwrap(); + let http_path = CString::new("/sql/1.0/warehouses/test_wh").unwrap(); + let token = CString::new("dapi-test-token").unwrap(); + let root = fx.pki.root_pem.as_bytes(); + unsafe { + let mut config: *mut KernelSessionConfig = std::ptr::null_mut(); + assert_eq!( + kernel_session_config_new(&mut config), + KernelStatusCode::Success + ); + assert_eq!( + kernel_session_config_set_http_path(config, host.as_ptr(), http_path.as_ptr()), + KernelStatusCode::Success + ); + assert_eq!( + kernel_session_config_set_auth_pat(config, token.as_ptr()), + KernelStatusCode::Success + ); + assert_eq!( + kernel_session_config_set_tls_trusted_certs(config, root.as_ptr(), root.len()), + KernelStatusCode::Success + ); + // Strict: an undetermined status would also fail, so this asserts the revoked + // message specifically. + assert_eq!( + kernel_session_config_set_tls_certificate_revocation(config, true, false), + KernelStatusCode::Success + ); + + let mut session: *mut kernel_session_t = std::ptr::null_mut(); + let status = kernel_session_open(config, &mut session); + assert_eq!(status, KernelStatusCode::NetworkError); + assert!(session.is_null()); + + let mut out = std::mem::MaybeUninit::::uninit(); + assert!(crate::c_abi::error::kernel_get_last_error(out.as_mut_ptr())); + let error = out.assume_init(); + let message = CStr::from_ptr(error.message).to_str().unwrap(); + assert!(message.contains("revoked"), "{message}"); + } + } } diff --git a/src/client/tls_revocation_tests.rs b/src/client/tls_revocation_tests.rs index fa6de193..bbad9ae0 100644 --- a/src/client/tls_revocation_tests.rs +++ b/src/client/tls_revocation_tests.rs @@ -50,7 +50,7 @@ const CURRENT: (i32, u8, u8) = (2099, 1, 1); /// What the CRL at one distribution point serves. #[derive(Clone, Copy)] -enum Served { +pub(crate) enum Served { /// A current CRL that lists nothing. Good, /// A current CRL that lists the covered certificate as revoked. @@ -87,9 +87,9 @@ const SCENARIOS: &[Scenario] = &[ Scenario { name: "leaf without a distribution point", leaf: None, intermediate: Served::Good, strict: Outcome::Undetermined, accept: Outcome::Pass }, ]; -struct Pki { +pub(crate) struct Pki { root_der: CertificateDer<'static>, - root_pem: String, + pub(crate) root_pem: String, root_issuer: Issuer<'static, KeyPair>, intermediate_issuer: Issuer<'static, KeyPair>, intermediate_der: CertificateDer<'static>, @@ -198,16 +198,16 @@ fn route(served: Served, issuer: &Issuer<'_, KeyPair>, covered: u64) -> Route { } /// A PKI, its CRL origin server, and the TLS leaf server. -struct Fixture { +pub(crate) struct Fixture { crl: CrlServer, - pki: Pki, - addr: SocketAddr, + pub(crate) pki: Pki, + pub(crate) addr: SocketAddr, } /// Each fixture's CRL paths are unique, so no two tests share a CRL URL. static FIXTURE_ID: AtomicUsize = AtomicUsize::new(0); -fn fixture(leaf: Option, intermediate: Served, san: &str) -> Fixture { +pub(crate) fn fixture(leaf: Option, intermediate: Served, san: &str) -> Fixture { let crl = CrlServer::start(); let id = FIXTURE_ID.fetch_add(1, Ordering::Relaxed); let leaf_path = format!("/{id}/leaf.crl"); @@ -480,7 +480,10 @@ async fn check(scenario: &Scenario, accept: bool, want: Outcome) { let fx = fixture(scenario.leaf, scenario.intermediate, "127.0.0.1"); let label = format!("{} (accept_undetermined={accept})", scenario.name); let result = get(revocation_config(&fx.pki.root_pem), Some(accept), fx.addr).await; - eprintln!("{label}: result={result:?} crl_requests={:?}", fx.crl.paths()); + eprintln!( + "{label}: result={result:?} crl_requests={:?}", + fx.crl.paths() + ); match (want, &result) { (Outcome::Pass, Ok(())) => {} (Outcome::Revoked, Err(err)) => assert!(err.contains("revoked"), "{label}: {err}"), From 04c85c4438b7d3e85603ca66a352ba3858175c20 Mon Sep 17 00:00:00 2001 From: cat23123 <58714163+cat23123@users.noreply.github.com> Date: Fri, 20 Nov 2026 18:15:41 +0000 Subject: [PATCH 27/43] fix(telemetry): key the client cache by revocation mode The telemetry client cache was keyed by host alone. A cached client holds the HTTP client of the session that created it, so a session with revocation on could reuse a client with revocation off, and its telemetry skipped the requested TLS policy. The key now includes the revocation mode. Custom CA, mTLS and skip-verify settings are not in the key either; that predates this change and is not changed here. Co-authored-by: Isaac Signed-off-by: cat23123 <58714163+cat23123@users.noreply.github.com> --- src/client/http.rs | 6 ++++++ src/telemetry/manager.rs | 32 ++++++++++++++++++++++++++++++++ src/telemetry/runtime.rs | 15 ++++++++++++++- 3 files changed, 52 insertions(+), 1 deletion(-) diff --git a/src/client/http.rs b/src/client/http.rs index 8ebabd75..583e8922 100644 --- a/src/client/http.rs +++ b/src/client/http.rs @@ -794,6 +794,12 @@ impl DatabricksHttpClient { } /// Returns the underlying reqwest client for building requests. + /// The revocation mode this client was built with: `None` when checking is off, otherwise + /// `Some(accept_undetermined)`. + pub(crate) fn revocation(&self) -> Option { + self.revocation + } + pub fn inner(&self) -> &Client { &self.client } diff --git a/src/telemetry/manager.rs b/src/telemetry/manager.rs index 0b6551e4..0fde6aa8 100644 --- a/src/telemetry/manager.rs +++ b/src/telemetry/manager.rs @@ -251,6 +251,38 @@ mod tests { second.release().await; } + #[tokio::test] + async fn different_revocation_modes_get_different_clients() { + // A client holds the HTTP client of the session that created it. Two sessions to one + // host with different revocation settings must not share a client. + use crate::telemetry::runtime::telemetry_cache_key; + + let manager = Box::leak(Box::new(TelemetryClientManager::default())); + let exporter: Arc = Arc::new(CapturingTelemetryExporter::default()); + let config = TelemetryConfig { + enabled: Some(true), + ..TelemetryConfig::default() + }; + + let off = manager.get_or_create_test( + &telemetry_cache_key("example.com", None), + &config, + exporter.clone(), + false, + ); + let strict = manager.get_or_create_test( + &telemetry_cache_key("example.com", Some(false)), + &config, + exporter, + false, + ); + + assert!(!Arc::ptr_eq(off.client(), strict.client())); + assert_eq!(manager.tracked_client_count(), 2); + off.release().await; + strict.release().await; + } + #[tokio::test] async fn last_lease_drop_removes_host_client() { let manager = Box::leak(Box::new(TelemetryClientManager::default())); diff --git a/src/telemetry/runtime.rs b/src/telemetry/runtime.rs index 1b8f751b..4813b473 100644 --- a/src/telemetry/runtime.rs +++ b/src/telemetry/runtime.rs @@ -66,9 +66,10 @@ impl TelemetryRuntime { connection_params: build_connection_params(connection, auth), auth_type: auth_type(auth), }); + let cache_key = telemetry_cache_key(&connection.host, http_client.revocation()); let (exporter, bypass_cache) = exporter_for_config(config, connection, http_client); let Some(lease) = TelemetryClientManager::global().get_or_create( - &connection.host, + &cache_key, config, exporter, bypass_cache, @@ -353,6 +354,18 @@ fn exporter_for_config( ) } +/// The per-host telemetry client cache key. A cached client holds the HTTP client of the +/// session that created it, so the revocation mode is part of the key: sessions to one host +/// with different revocation settings must not share a client. +pub(super) fn telemetry_cache_key(host: &str, revocation: Option) -> String { + let mode = match revocation { + None => "off", + Some(false) => "strict", + Some(true) => "accept_undetermined", + }; + format!("{host}|revocation={mode}") +} + fn build_system_configuration( override_config: Option, ) -> DriverSystemConfiguration { From 7e9b33e661710a37f480a4b532939aa51622b324 Mon Sep 17 00:00:00 2001 From: cat23123 <58714163+cat23123@users.noreply.github.com> Date: Fri, 20 Nov 2026 18:20:18 +0000 Subject: [PATCH 28/43] ci(tls): quote the Windows test command so the workflow parses The unquoted run value ended in client::, which YAML reads as a mapping value. GitHub rejected pr-checks.yml at 04c85c4, so none of its jobs ran. The command is now quoted, as the Linux step is. Co-authored-by: Isaac Signed-off-by: cat23123 <58714163+cat23123@users.noreply.github.com> --- .github/workflows/pr-checks.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/pr-checks.yml b/.github/workflows/pr-checks.yml index 8031c460..6b0cab2b 100644 --- a/.github/workflows/pr-checks.yml +++ b/.github/workflows/pr-checks.yml @@ -273,4 +273,4 @@ jobs: - name: Test client behavior (tls-rustls, Windows) shell: pwsh - run: cargo test -p databricks-sql-kernel --no-default-features --features tls-rustls --lib client:: + run: "cargo test -p databricks-sql-kernel --no-default-features --features tls-rustls --lib client::" From ae14d918da768e4a36509016f84d0d6f29e2e849 Mon Sep 17 00:00:00 2001 From: cat23123 <58714163+cat23123@users.noreply.github.com> Date: Fri, 20 Nov 2026 18:35:00 +0000 Subject: [PATCH 29/43] fix(tls): key the telemetry cache on the effective revocation mode allow_self_signed turns revocation off. The client now stores that effective mode, not the requested one, so the telemetry cache key matches what the client does. A unit test covers a self-signed session with revocation requested. The revocation() accessor has its own doc, and inner() keeps its original doc. Co-authored-by: Isaac Signed-off-by: cat23123 <58714163+cat23123@users.noreply.github.com> --- src/client/http.rs | 27 +++++++++++++++++++++++---- 1 file changed, 23 insertions(+), 4 deletions(-) diff --git a/src/client/http.rs b/src/client/http.rs index 583e8922..04571de7 100644 --- a/src/client/http.rs +++ b/src/client/http.rs @@ -524,6 +524,10 @@ impl DatabricksHttpClient { })?; } + // `allow_self_signed` turns revocation off, so the effective mode is what this client + // stores and what the telemetry cache keys on. `build_reqwest_client` applies the same rule. + let revocation = revocation.filter(|_| config.tls.allow_self_signed != Some(true)); + // Follow redirects for normal traffic (reqwest's default policy). let client = Self::build_reqwest_client(&config, reqwest::redirect::Policy::default(), revocation)?; @@ -793,13 +797,13 @@ impl DatabricksHttpClient { &self.config } - /// Returns the underlying reqwest client for building requests. - /// The revocation mode this client was built with: `None` when checking is off, otherwise - /// `Some(accept_undetermined)`. + /// The effective revocation mode: `None` when checking is off, including when + /// `allow_self_signed` disables it, otherwise `Some(accept_undetermined)`. pub(crate) fn revocation(&self) -> Option { self.revocation } + /// Returns the underlying reqwest client for building requests. pub fn inner(&self) -> &Client { &self.client } @@ -1157,7 +1161,22 @@ mod tls_tests; #[cfg(test)] mod revocation_support_tests { - use super::revocation_unsupported_message; + use super::{revocation_unsupported_message, DatabricksHttpClient, HttpClientConfig}; + + #[test] + fn allow_self_signed_makes_the_effective_revocation_mode_off() { + // The requested mode is strict, but self-signed turns revocation off, so the stored + // (effective) mode is None. The telemetry cache keys on this value. + let mut config = HttpClientConfig::default(); + config.tls.allow_self_signed = Some(true); + let retry = crate::client::retry::build_retry_configs( + &crate::client::retry::RetryConfig::default(), + &std::collections::HashMap::new(), + ); + let client = DatabricksHttpClient::with_revocation(config, retry, Some(false)) + .expect("self-signed with revocation builds a client"); + assert_eq!(client.revocation(), None); + } #[test] fn revocation_message_covers_every_platform_and_backend() { From d65949b5a8231d0ceeaffeaec1397675c751e99f Mon Sep 17 00:00:00 2001 From: cat23123 <58714163+cat23123@users.noreply.github.com> Date: Fri, 20 Nov 2026 18:35:02 +0000 Subject: [PATCH 30/43] test(tls): compile the Windows C ABI revocation test on Windows The strict open test sat in a module compiled only where Windows and tls-rustls are not both on, so it never ran. It now has its own module gated on Windows with tls-rustls. The Windows spike type-checks it. Co-authored-by: Isaac Signed-off-by: cat23123 <58714163+cat23123@users.noreply.github.com> --- src/c_abi/session.rs | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/src/c_abi/session.rs b/src/c_abi/session.rs index 8532d3cb..2c8088aa 100644 --- a/src/c_abi/session.rs +++ b/src/c_abi/session.rs @@ -3510,12 +3510,18 @@ mod revocation_open_tests { ); } } +} + +/// Strict revocation through the C ABI, on Windows with tls-rustls. Its own module, because the +/// unsupported-platform module above is compiled only where this one is not. +#[cfg(all(test, windows, feature = "tls-rustls"))] +mod revocation_open_windows_tests { + use super::*; + use std::ffi::{CStr, CString}; - /// Strict revocation through the C ABI, on Windows with tls-rustls: a leaf that its CRL - /// revokes fails session open. The TLS endpoint is a local server, and its chain and CRL - /// come from the revocation test fixture. The failure is in the TLS handshake, before any - /// HTTP request, so no SEA server is needed. - #[cfg(all(windows, feature = "tls-rustls"))] + /// A leaf that its CRL revokes fails session open. The TLS endpoint is a local server, and + /// its chain and CRL come from the revocation test fixture. The failure is in the TLS + /// handshake, before any HTTP request, so no SEA server is needed. #[test] fn tls_revocation_strict_open_rejects_a_revoked_leaf() { use crate::client::tls_revocation::tests::{fixture, Served}; From 6a9f2e68affdde42b17dbf96a4d59401e27c764c Mon Sep 17 00:00:00 2001 From: cat23123 <58714163+cat23123@users.noreply.github.com> Date: Fri, 20 Nov 2026 18:35:41 +0000 Subject: [PATCH 31/43] fix(tls): share the revocation budget across a handshake's chain builds With custom CAs, an undetermined default-engine result is built again with the exclusive-root engine. Before, that second build got a fresh 10 s, so one handshake could wait about 20 s. The second build now gets only the time the first left, and is skipped when none is left. The default engine still builds first, so a public chain that verifies costs one build. The docs state the shared budget and the engine order. Co-authored-by: Isaac Signed-off-by: cat23123 <58714163+cat23123@users.noreply.github.com> --- docs/designs/tls-config-design.md | 1 + include/databricks_kernel.h | 5 ++-- src/client/tls_revocation.rs | 45 ++++++++++++++++++++++++------- src/config.rs | 5 ++-- 4 files changed, 42 insertions(+), 14 deletions(-) diff --git a/docs/designs/tls-config-design.md b/docs/designs/tls-config-design.md index 0814892a..d94d1779 100644 --- a/docs/designs/tls-config-design.md +++ b/docs/designs/tls-config-design.md @@ -259,6 +259,7 @@ The Rust driver uses `databricks.http.tls.*` while the C# driver uses `adbc.http - **Strict and accept-undetermined**: a revoked status is rejected in both modes. An undetermined status (a fetch failure, an offline status, a missing revocation URL, or a partial chain) is rejected in strict mode and accepted under accept-undetermined. This matches Simba's semantics. A partial chain is a root that Windows cannot build to and that is not a custom CA, for example a public root that appears only in the webpki bundle. Under strict mode that connection fails. - **CRL and OCSP fetching**: CryptoAPI retrieves CRLs and OCSP responses through Windows' networking stack (WinHTTP) and its proxy settings, not through the kernel's `ProxyConfig`. Windows caches the results, so a certificate revoked after a CRL was cached may be accepted until the cache refreshes. The kernel adds no CRL cache, worker thread, redirect policy or size limit of its own. - **Timeout**: CryptoAPI applies one 10 s budget to the CRL and OCSP fetches of a chain (`CERT_CHAIN_REVOCATION_ACCUMULATIVE_TIMEOUT`). When the budget runs out, the status is undetermined. AIA and other chain-building fetches are bounded per URL (`dwUrlRetrievalTimeout`, also 10 s), not in total, so the 10 s total is not guaranteed for a chain that needs them. The kernel has no public knob for either bound. +- **Engine order and budget**: the default chain engine builds first, so a public chain that verifies costs one build. When custom CAs are configured and that build is undetermined, the chain is built again with an exclusive-root engine whose root store is the custom CAs. The second build gets only the time the first left (`dwUrlRetrievalTimeout` set to the remainder), and is skipped when none is left. One handshake therefore waits at most the 10 s budget for revocation fetches in total. The exclusive-root engine is used only for a second build, so public chains are not affected by its trust set. - **Blocking**: the check is synchronous, because rustls' verifier is. It runs inside the handshake poll and blocks until CryptoAPI returns. On a multi-thread runtime, `block_in_place` moves the worker's other tasks to another thread, but the calling task cannot be cancelled until CryptoAPI returns. A caller's connect or operation timeout can be exceeded by up to the revocation budget, with revocation on only. On a `current_thread` runtime the whole runtime waits. - **Session resumption**: resumption is disabled whenever revocation is on, because a resumed handshake skips the server certificate verifier, and a certificate revoked after the first handshake would stay accepted. - **Documented limits**: the check covers the chain that CryptoAPI builds, not every path that webpki might accept. Windows caches revocation data. The check uses Windows' network stack, so proxy settings and firewall rules that the kernel does not control can make a fetch fail. diff --git a/include/databricks_kernel.h b/include/databricks_kernel.h index 45d7db9f..841d98c9 100644 --- a/include/databricks_kernel.h +++ b/include/databricks_kernel.h @@ -483,8 +483,9 @@ KernelStatusCode kernel_session_config_set_tls_client_certificate( * kernel's proxy configuration, and Windows caches the results. The check is * synchronous: it blocks the calling thread's TLS handshake until CryptoAPI * returns, so a connect or operation timeout can be exceeded by up to the - * revocation budget (about 10 s for CRL and OCSP retrieval in total; AIA and - * other chain-building fetches are bounded per URL, not in total). Session + * revocation budget (about 10 s for CRL and OCSP retrieval in total, shared by a + * handshake's one or two chain builds; AIA and other chain-building fetches are + * bounded per URL, not in total). Session * resumption is disabled while checking is on. * * Requesting it on any other platform, or on tls-native, makes opening a session diff --git a/src/client/tls_revocation.rs b/src/client/tls_revocation.rs index 9c9a66c0..29217787 100644 --- a/src/client/tls_revocation.rs +++ b/src/client/tls_revocation.rs @@ -36,7 +36,7 @@ use std::ptr::{null, null_mut}; use std::sync::Arc; -use std::time::Duration; +use std::time::{Duration, Instant}; use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier}; use rustls::client::WebPkiServerVerifier; @@ -69,9 +69,11 @@ use windows_sys::Win32::Security::Cryptography::{ use super::http::TlsConfig; use crate::kernel_error::{Error, Result}; -/// The budget for CRL and OCSP retrieval for one chain. CryptoAPI applies it to all of the -/// chain's revocation fetches together (`CERT_CHAIN_REVOCATION_ACCUMULATIVE_TIMEOUT`). It does -/// not bound AIA or other chain-building fetches, which use the per-URL timeout only. +/// The budget for CRL and OCSP retrieval for one handshake. CryptoAPI applies it to all of a +/// chain's revocation fetches together (`CERT_CHAIN_REVOCATION_ACCUMULATIVE_TIMEOUT`). One +/// handshake runs at most two chain builds, and the second gets only the time the first left, so +/// the total stays within this budget. It does not bound AIA or other chain-building fetches, +/// which use the per-URL timeout only. const REVOCATION_TIMEOUT: Duration = Duration::from_secs(10); /// The chain flags: check every certificate except the root. const CHAIN_FLAGS: u32 = @@ -256,14 +258,29 @@ fn cryptoapi_status(leaf: &[u8], intermediates: &[&[u8]], custom_cas: &[&[u8]]) let Some(leaf) = Context::new(leaf) else { return Status::Undetermined; }; - let status = chain_status("default engine", &leaf, &store, null_mut()); + let started = Instant::now(); + let status = chain_status( + "default engine", + &leaf, + &store, + null_mut(), + REVOCATION_TIMEOUT, + ); // With a custom CA, Windows does not trust its root. The default engine can then end the // chain at an untrusted root and report no revocation status, so the result is undetermined. // Build again with an engine whose exclusive root is the custom CAs, which makes the chain // complete for this check. Webpki still decides trust, and only the revocation bits are read. + // The second build gets only the budget the first left, so one handshake waits at most + // REVOCATION_TIMEOUT in total. If nothing is left, the first result stands. if status != Status::Undetermined || custom_cas.is_empty() { return status; } + let remaining = REVOCATION_TIMEOUT.saturating_sub(started.elapsed()); + // Under 1 ms counts as none left: dwUrlRetrievalTimeout is in milliseconds, and 0 there + // means CryptoAPI's own default timeout, not "no time". + if remaining.as_millis() == 0 { + return status; + } let Some(roots) = Store::memory() else { return status; }; @@ -273,18 +290,26 @@ fn cryptoapi_status(leaf: &[u8], intermediates: &[&[u8]], custom_cas: &[&[u8]]) let Some(engine) = ChainEngine::exclusive(&roots) else { return status; }; - chain_status("exclusive-root engine", &leaf, &store, engine.0) + chain_status("exclusive-root engine", &leaf, &store, engine.0, remaining) } /// Builds the chain for `leaf` with `engine` (null is the default engine) and reads its -/// revocation status. `label` names the engine in the test-only diagnostics. -fn chain_status(label: &str, leaf: &Context, store: &Store, engine: HCERTCHAINENGINE) -> Status { +/// revocation status. `budget` bounds the revocation fetches of this build. `label` names the +/// engine in the test-only diagnostics. +fn chain_status( + label: &str, + leaf: &Context, + store: &Store, + engine: HCERTCHAINENGINE, + budget: Duration, +) -> Status { // Only the test-only diagnostics below read `label`. let _ = label; let para = CERT_CHAIN_PARA { cbSize: std::mem::size_of::() as u32, - // Per-URL timeout for chain-building fetches (AIA). It is not a total. - dwUrlRetrievalTimeout: REVOCATION_TIMEOUT.as_millis() as u32, + // Per-URL timeout for chain-building fetches (AIA). With the accumulative flag, the + // revocation fetches share this budget in total. + dwUrlRetrievalTimeout: budget.as_millis() as u32, ..Default::default() }; let mut chain: *mut CERT_CHAIN_CONTEXT = null_mut(); diff --git a/src/config.rs b/src/config.rs index 9d9e4f95..03631dd0 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1056,8 +1056,9 @@ pub struct TlsConfig { /// Windows caches the results. The check is synchronous and runs inside the TLS /// handshake, so it blocks the calling task until CryptoAPI returns, even on a /// multi-thread runtime. A connect or operation timeout on that task can be exceeded - /// by up to the revocation budget (about 10 s for CRL and OCSP retrieval in total; - /// AIA and other chain-building fetches are bounded per URL, not in total). On a + /// by up to the revocation budget (about 10 s for CRL and OCSP retrieval in total, shared + /// by the one or two chain builds of a handshake; AIA and other chain-building fetches are + /// bounded per URL, not in total). On a /// `current_thread` runtime the whole runtime waits. Session resumption is disabled /// while checking is on. pub check_certificate_revocation: Option, From e9c4d28e90c966527a0f1e6461d33c9c7b45cc30 Mon Sep 17 00:00:00 2001 From: cat23123 <58714163+cat23123@users.noreply.github.com> Date: Fri, 20 Nov 2026 18:59:10 +0000 Subject: [PATCH 32/43] fix(tls): treat a custom CA anchor as a root in the exclusive engine The exclusive-root engine set no dwExclusiveFlags, so a non-self-signed custom CA, such as a configured intermediate, may not have been treated as a root. The chain then stayed partial and was undetermined. The engine now sets CERT_CHAIN_EXCLUSIVE_ENABLE_CA_FLAG. cbSize is the size of the full struct, so the field is covered. Co-authored-by: Isaac Signed-off-by: cat23123 <58714163+cat23123@users.noreply.github.com> --- src/client/tls_revocation.rs | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/src/client/tls_revocation.rs b/src/client/tls_revocation.rs index 29217787..4a8aceb8 100644 --- a/src/client/tls_revocation.rs +++ b/src/client/tls_revocation.rs @@ -48,11 +48,11 @@ use windows_sys::Win32::Security::Cryptography::{ CertAddCertificateContextToStore, CertCloseStore, CertCreateCertificateChainEngine, CertCreateCertificateContext, CertFreeCertificateChain, CertFreeCertificateChainEngine, CertFreeCertificateContext, CertGetCertificateChain, CertOpenStore, CERT_CHAIN_CONTEXT, - CERT_CHAIN_ENGINE_CONFIG, CERT_CHAIN_PARA, CERT_CHAIN_REVOCATION_ACCUMULATIVE_TIMEOUT, - CERT_CHAIN_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT, CERT_CONTEXT, CERT_STORE_ADD_ALWAYS, - CERT_STORE_PROV_MEMORY, CERT_TRUST_IS_OFFLINE_REVOCATION, CERT_TRUST_IS_PARTIAL_CHAIN, - CERT_TRUST_IS_REVOKED, CERT_TRUST_REVOCATION_STATUS_UNKNOWN, HCERTCHAINENGINE, HCERTSTORE, - PKCS_7_ASN_ENCODING, X509_ASN_ENCODING, + CERT_CHAIN_ENGINE_CONFIG, CERT_CHAIN_EXCLUSIVE_ENABLE_CA_FLAG, CERT_CHAIN_PARA, + CERT_CHAIN_REVOCATION_ACCUMULATIVE_TIMEOUT, CERT_CHAIN_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT, + CERT_CONTEXT, CERT_STORE_ADD_ALWAYS, CERT_STORE_PROV_MEMORY, CERT_TRUST_IS_OFFLINE_REVOCATION, + CERT_TRUST_IS_PARTIAL_CHAIN, CERT_TRUST_IS_REVOKED, CERT_TRUST_REVOCATION_STATUS_UNKNOWN, + HCERTCHAINENGINE, HCERTSTORE, PKCS_7_ASN_ENCODING, X509_ASN_ENCODING, }; #[cfg(test)] @@ -350,6 +350,9 @@ impl ChainEngine { let config = CERT_CHAIN_ENGINE_CONFIG { cbSize: std::mem::size_of::() as u32, hExclusiveRoot: roots.0, + // Without this flag a CA certificate that is not self-signed is not treated as a + // root, so a custom CA configured as an intermediate would leave the chain partial. + dwExclusiveFlags: CERT_CHAIN_EXCLUSIVE_ENABLE_CA_FLAG, ..Default::default() }; let mut engine: HCERTCHAINENGINE = null_mut(); From cd6573ab27fbc1999c5096e8bc4f6b5f538ecdc9 Mon Sep 17 00:00:00 2001 From: cat23123 <58714163+cat23123@users.noreply.github.com> Date: Fri, 20 Nov 2026 18:59:13 +0000 Subject: [PATCH 33/43] test(tls): cover a custom intermediate anchor and the multi-thread runtime A custom CA configured as the intermediate anchors the chain: a good chain passes in strict mode, and a revoked leaf is rejected. A multi-thread runtime test takes the block_in_place branch that the current_thread tests never reach. These tests run on Windows only, where the module is compiled. Co-authored-by: Isaac Signed-off-by: cat23123 <58714163+cat23123@users.noreply.github.com> --- src/client/tls_revocation_tests.rs | 49 ++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) diff --git a/src/client/tls_revocation_tests.rs b/src/client/tls_revocation_tests.rs index bbad9ae0..6e2560d5 100644 --- a/src/client/tls_revocation_tests.rs +++ b/src/client/tls_revocation_tests.rs @@ -492,6 +492,55 @@ async fn check(scenario: &Scenario, accept: bool, want: Outcome) { } } +/// A PEM certificate for `der`, for configuring a custom CA. +fn pem_of(der: &[u8]) -> Vec { + use base64::Engine as _; + let body = base64::engine::general_purpose::STANDARD.encode(der); + let lines: Vec<&str> = body + .as_bytes() + .chunks(64) + .map(|chunk| std::str::from_utf8(chunk).unwrap()) + .collect(); + format!( + "-----BEGIN CERTIFICATE-----\n{}\n-----END CERTIFICATE-----\n", + lines.join("\n") + ) + .into_bytes() +} + +#[tokio::test] +async fn custom_ca_configured_as_the_intermediate_is_an_anchor() { + // The custom CA is the intermediate, not the root. Webpki anchors the chain at it, so the + // check must treat it as the chain's root (it is excluded), and the leaf is still checked. + let good = fixture(Some(Served::Good), Served::Good, "127.0.0.1"); + let mut config = HttpClientConfig::default(); + config.tls.trusted_certificate_pem = Some(pem_of(&good.pki.intermediate_der)); + config.max_connections_per_host = 0; + get(config, Some(false), good.addr) + .await + .expect("a good chain anchored at the intermediate passes in strict mode"); + + let revoked = fixture(Some(Served::Revoked), Served::Good, "127.0.0.1"); + let mut config = HttpClientConfig::default(); + config.tls.trusted_certificate_pem = Some(pem_of(&revoked.pki.intermediate_der)); + config.max_connections_per_host = 0; + let err = get(config, Some(false), revoked.addr) + .await + .expect_err("a revoked leaf anchored at the intermediate is rejected"); + assert!(err.contains("revoked"), "{err}"); +} + +#[tokio::test(flavor = "multi_thread")] +async fn multi_thread_runtime_checks_revocation() { + // The other tests run on current_thread, where `in_runtime_blocking` does not call + // block_in_place. This one takes that branch. + let fx = fixture(Some(Served::Revoked), Served::Good, "127.0.0.1"); + let err = get(revocation_config(&fx.pki.root_pem), Some(false), fx.addr) + .await + .expect_err("a revoked leaf is rejected on a multi-thread runtime"); + assert!(err.contains("revoked"), "{err}"); +} + #[tokio::test] async fn revocation_outcomes_follow_the_policy_table() { for scenario in SCENARIOS { From 8c42d303f45a4ab566acdf22a03250aef4f19ef4 Mon Sep 17 00:00:00 2001 From: cat23123 <58714163+cat23123@users.noreply.github.com> Date: Fri, 20 Nov 2026 18:59:16 +0000 Subject: [PATCH 34/43] docs(tls): state that trust anchors are not revocation-checked A trust anchor is not revocation-checked, including a self-signed server certificate configured as a custom CA. That matches RFC 5280, the JDK PKIX path validator and CryptoAPI's exclude-root flag. The leaf and the other chain certificates are checked. Co-authored-by: Isaac Signed-off-by: cat23123 <58714163+cat23123@users.noreply.github.com> --- docs/designs/tls-config-design.md | 2 +- src/config.rs | 5 ++++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/docs/designs/tls-config-design.md b/docs/designs/tls-config-design.md index d94d1779..22705972 100644 --- a/docs/designs/tls-config-design.md +++ b/docs/designs/tls-config-design.md @@ -254,7 +254,7 @@ The Rust driver uses `databricks.http.tls.*` while the C# driver uses `adbc.http ### Scope Exclusions - **Certificate revocation is Windows-only**: the check exists only on Windows with `tls-rustls`, and is decided by Windows CryptoAPI (`CertGetCertificateChain`). On every other platform, and on `tls-native` (including Windows), requesting revocation fails session open with `InvalidArgument`, as an unsupported option does. The ODBC driver reads its CheckCertRevocation and AcceptUndeterminedRevocation keys only on Windows; elsewhere it warns and ignores them. The kernel does not port the check to Linux or macOS, and `tls-native` on Windows is not given a CryptoAPI path, because native-tls exposes no verifier hook and this keeps the surface smaller. -- **Trust stays with webpki**: the connection's webpki verifier, over the kernel's roots (webpki roots, the OS store, custom CAs), decides the chain, the name and the signatures, exactly as with revocation off. Only after that succeeds does CryptoAPI decide revocation. CryptoAPI builds its chain from the leaf, the presented intermediates and the custom CAs. It checks every certificate except the root. Only the chain-level revocation bits are read. The trust bits, including the root's, are ignored, so a custom CA that Windows does not trust is still checked, because the custom CAs are in CryptoAPI's additional store. +- **Trust stays with webpki**: the connection's webpki verifier, over the kernel's roots (webpki roots, the OS store, custom CAs), decides the chain, the name and the signatures, exactly as with revocation off. Only after that succeeds does CryptoAPI decide revocation. CryptoAPI builds its chain from the leaf, the presented intermediates and the custom CAs. It checks every certificate except the root. Only the chain-level revocation bits are read. The trust bits, including the root's, are ignored, so a custom CA that Windows does not trust is still checked, because the custom CAs are in CryptoAPI's additional store. A trust anchor is not revocation-checked, including a self-signed server certificate configured as a custom CA, as in RFC 5280, the JDK PKIX path validator and CryptoAPI's exclude-root flag. The leaf and the other chain certificates are checked. - **Chain choice**: CryptoAPI may build a different chain from the one webpki verified, for example through a cross-signed issuer. The status then comes from CryptoAPI's chain. The leaf is always checked. A server presenting more intermediates than it needs does not change the result. A presented certificate that CryptoAPI refuses to add is skipped, so it cannot hide the leaf's status; a chain that needs it comes out partial and is undetermined. - **Strict and accept-undetermined**: a revoked status is rejected in both modes. An undetermined status (a fetch failure, an offline status, a missing revocation URL, or a partial chain) is rejected in strict mode and accepted under accept-undetermined. This matches Simba's semantics. A partial chain is a root that Windows cannot build to and that is not a custom CA, for example a public root that appears only in the webpki bundle. Under strict mode that connection fails. - **CRL and OCSP fetching**: CryptoAPI retrieves CRLs and OCSP responses through Windows' networking stack (WinHTTP) and its proxy settings, not through the kernel's `ProxyConfig`. Windows caches the results, so a certificate revoked after a CRL was cached may be accepted until the cache refreshes. The kernel adds no CRL cache, worker thread, redirect policy or size limit of its own. diff --git a/src/config.rs b/src/config.rs index 03631dd0..9d7c610d 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1051,7 +1051,10 @@ pub struct TlsConfig { /// /// Trust, name and signatures are still decided by webpki, as with checking off. /// CryptoAPI then checks every certificate in the chain it builds except the root. - /// Only the revocation bits are read. The trust bits are ignored. CRL and OCSP + /// Only the revocation bits are read. The trust bits are ignored. A trust anchor is not + /// revocation-checked, including a self-signed server certificate configured as a custom CA, + /// as in RFC 5280, the JDK PKIX path validator and CryptoAPI's exclude-root flag. The leaf + /// and the other chain certificates are checked. CRL and OCSP /// retrieval uses Windows networking and proxy settings, not [`ProxyConfig`], and /// Windows caches the results. The check is synchronous and runs inside the TLS /// handshake, so it blocks the calling task until CryptoAPI returns, even on a From 3f4ff95912c4ffd7c2604c960803aa88eec529e9 Mon Sep 17 00:00:00 2001 From: cat23123 <58714163+cat23123@users.noreply.github.com> Date: Fri, 20 Nov 2026 18:59:19 +0000 Subject: [PATCH 35/43] ci(tls): run the C ABI revocation open test on Windows The Windows client:: filter does not match c_abi::session, so the strict C ABI open test never ran in CI. The step now runs client:: and then the revocation open test in a second cargo test invocation. Two invocations avoid relying on libtest's multiple-filter support. Co-authored-by: Isaac Signed-off-by: cat23123 <58714163+cat23123@users.noreply.github.com> --- .github/workflows/pr-checks.yml | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/.github/workflows/pr-checks.yml b/.github/workflows/pr-checks.yml index 6b0cab2b..203ef8f2 100644 --- a/.github/workflows/pr-checks.yml +++ b/.github/workflows/pr-checks.yml @@ -273,4 +273,8 @@ jobs: - name: Test client behavior (tls-rustls, Windows) shell: pwsh - run: "cargo test -p databricks-sql-kernel --no-default-features --features tls-rustls --lib client::" + # Two runs: the client:: suite, then the C ABI revocation open test, which is not under client::. + run: | + cargo test -p databricks-sql-kernel --no-default-features --features tls-rustls --lib client:: + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + cargo test -p databricks-sql-kernel --no-default-features --features tls-rustls --lib c_abi::session::revocation_open_windows_tests From 6b562872dc1998076600285df5eb4789618fffde Mon Sep 17 00:00:00 2001 From: cat23123 <58714163+cat23123@users.noreply.github.com> Date: Fri, 20 Nov 2026 19:23:04 +0000 Subject: [PATCH 36/43] test(tls): match the revoked error case-insensitively in the C ABI test The first Windows run of tls_revocation_strict_open_rejects_a_revoked_leaf showed the revocation working: the exclusive-root engine reported REVOKED, and session open returned NetworkError. The test only failed its last assertion, because rustls renders the error as "invalid peer certificate: Revoked" and the test looked for lowercase "revoked". Compare case-insensitively. Co-authored-by: Isaac Signed-off-by: cat23123 <58714163+cat23123@users.noreply.github.com> --- src/c_abi/session.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/c_abi/session.rs b/src/c_abi/session.rs index 2c8088aa..21ae8f53 100644 --- a/src/c_abi/session.rs +++ b/src/c_abi/session.rs @@ -3565,7 +3565,11 @@ mod revocation_open_windows_tests { assert!(crate::c_abi::error::kernel_get_last_error(out.as_mut_ptr())); let error = out.assume_init(); let message = CStr::from_ptr(error.message).to_str().unwrap(); - assert!(message.contains("revoked"), "{message}"); + // rustls renders the error as "invalid peer certificate: Revoked". + assert!( + message.to_ascii_lowercase().contains("revoked"), + "{message}" + ); } } } From 8a40baa25d1f50aed51b8defeceebd1d90e14823 Mon Sep 17 00:00:00 2001 From: cat23123 <58714163+cat23123@users.noreply.github.com> Date: Fri, 20 Nov 2026 21:28:33 +0000 Subject: [PATCH 37/43] fix(telemetry): report the revocation settings and key breakers by mode Connection parameters now carry the session's configured check and accept-undetermined revocation values, which JDBC also reports. Unit tests cover set and unset values. Circuit breakers are keyed the same way as the client cache, by host and effective revocation mode, so breakers follow the client split. A unit test shows two modes on one host get different breakers. Test-injected exporters use the same key. The cache key's limit is documented: custom CA, self-signed, mTLS and proxy settings are not in the key, as before this change. Co-authored-by: Isaac Signed-off-by: cat23123 <58714163+cat23123@users.noreply.github.com> --- src/session.rs | 1 + src/telemetry/circuit_breaker.rs | 29 ++++++++++++++++++- src/telemetry/runtime.rs | 48 ++++++++++++++++++++++++++++---- 3 files changed, 71 insertions(+), 7 deletions(-) diff --git a/src/session.rs b/src/session.rs index 5ae096d3..a634ae3a 100644 --- a/src/session.rs +++ b/src/session.rs @@ -460,6 +460,7 @@ impl Session { &telemetry_config, &config.connection, &config.auth, + &config.tls, config.driver_system_configuration.clone(), http_client, session_info.session_id.clone(), diff --git a/src/telemetry/circuit_breaker.rs b/src/telemetry/circuit_breaker.rs index c9ea8c47..cb07c470 100644 --- a/src/telemetry/circuit_breaker.rs +++ b/src/telemetry/circuit_breaker.rs @@ -230,7 +230,8 @@ enum CircuitBreakerState { /// Process-global registry of per-host circuit breakers. /// -/// The `breakers` map is keyed by `(host, config)` and holds one entry per +/// The `breakers` map is keyed by `(cache key, config)`, where the cache key is the host and the +/// effective revocation mode from `telemetry_cache_key`, and holds one entry per /// distinct host a process talks to. Entries are never evicted, so the map /// grows monotonically for the process lifetime. This is intentional and /// bounded in practice: a kernel process connects to a small, stable set of @@ -547,6 +548,32 @@ mod tests { assert_eq!(breaker.state_for_test(), CircuitBreakerState::Closed); } + #[test] + fn different_revocation_modes_get_different_breakers() { + // Sessions to one host with different revocation modes share no breaker, as they share + // no telemetry client. + use crate::telemetry::runtime::telemetry_cache_key; + + let host = unique_host("revocation-modes"); + let config = CircuitBreakerConfig::from_telemetry_config(&TelemetryConfig { + enabled: Some(true), + ..TelemetryConfig::default() + }) + .expect("circuit breaker config"); + let off = + CircuitBreakerManager::global().get_or_create(&telemetry_cache_key(host, None), config); + let strict = CircuitBreakerManager::global() + .get_or_create(&telemetry_cache_key(host, Some(false)), config); + let tolerant = CircuitBreakerManager::global() + .get_or_create(&telemetry_cache_key(host, Some(true)), config); + assert!(!Arc::ptr_eq(&off, &strict)); + assert!(!Arc::ptr_eq(&strict, &tolerant)); + // The same key still shares a breaker. + let again = CircuitBreakerManager::global() + .get_or_create(&telemetry_cache_key(host, Some(false)), config); + assert!(Arc::ptr_eq(&strict, &again)); + } + #[tokio::test] async fn different_hosts_have_independent_breakers() { let failing = Arc::new(FailingExporter::default()); diff --git a/src/telemetry/runtime.rs b/src/telemetry/runtime.rs index 4813b473..deb57170 100644 --- a/src/telemetry/runtime.rs +++ b/src/telemetry/runtime.rs @@ -47,6 +47,7 @@ impl TelemetryRuntime { config: &TelemetryConfig, connection: &ConnectionConfig, auth: &AuthConfig, + tls: &crate::config::TlsConfig, system_configuration: Option, http_client: Arc, session_id: String, @@ -63,7 +64,7 @@ impl TelemetryRuntime { .and_then(|org_id| org_id.parse::().ok()) .unwrap_or_default(), system_configuration: build_system_configuration(system_configuration), - connection_params: build_connection_params(connection, auth), + connection_params: build_connection_params(connection, auth, tls), auth_type: auth_type(auth), }); let cache_key = telemetry_cache_key(&connection.host, http_client.revocation()); @@ -326,6 +327,9 @@ fn exporter_for_config( connection: &ConnectionConfig, http_client: Arc, ) -> (Arc, bool) { + // The circuit breaker follows the client cache key, so sessions with different revocation + // modes to one host get separate breakers. + let breaker_key = telemetry_cache_key(&connection.host, http_client.revocation()); #[cfg(test)] { if let Some(exporter) = config.exporter.clone() { @@ -333,16 +337,13 @@ fn exporter_for_config( // parallel tests commonly reuse the same mock host with different // capturing exporters, and cache reuse would route events to the // exporter from whichever test created the host client first. - return ( - maybe_wrap_exporter(&connection.host, config, exporter), - true, - ); + return (maybe_wrap_exporter(&breaker_key, config, exporter), true); } } ( maybe_wrap_exporter( - &connection.host, + &breaker_key, config, Arc::new(DatabricksTelemetryExporter::new( &connection.host, @@ -357,6 +358,10 @@ fn exporter_for_config( /// The per-host telemetry client cache key. A cached client holds the HTTP client of the /// session that created it, so the revocation mode is part of the key: sessions to one host /// with different revocation settings must not share a client. +/// +/// Limit: the key covers the host and the effective revocation mode only. Sessions to one host +/// with different custom CA, self-signed, mTLS or proxy settings still share a telemetry client, +/// as they did before revocation was added. Per-session isolation is a follow-up. pub(super) fn telemetry_cache_key(host: &str, revocation: Option) -> String { let mode = match revocation { None => "off", @@ -413,11 +418,16 @@ fn merge_system_configuration( } } +/// Connection parameters for telemetry. The revocation fields carry the session's configured +/// values, as JDBC reports them, and are unset when the session did not set them. fn build_connection_params( connection: &ConnectionConfig, auth: &AuthConfig, + tls: &crate::config::TlsConfig, ) -> DriverConnectionParameters { DriverConnectionParameters { + check_certificate_revocation: tls.check_certificate_revocation, + accept_undetermined_certificate_revocation: tls.accept_undetermined_certificate_revocation, http_path: Some(format!("/sql/1.0/warehouses/{}", connection.warehouse_id)), mode: Some(DriverMode::Sea), host_info: Some(HostDetails { @@ -485,6 +495,32 @@ fn duration_millis(duration: Duration) -> i64 { mod tests { use super::*; + #[test] + fn connection_params_report_the_configured_revocation_values() { + let connection = ConnectionConfig::new("https://example.cloud.databricks.com", "wh"); + let auth = AuthConfig::Pat { + token: "dapi-test".into(), + identity_federation_client_id: None, + }; + + let set = crate::config::TlsConfig { + check_certificate_revocation: Some(true), + accept_undetermined_certificate_revocation: Some(false), + ..Default::default() + }; + let params = build_connection_params(&connection, &auth, &set); + assert_eq!(params.check_certificate_revocation, Some(true)); + assert_eq!( + params.accept_undetermined_certificate_revocation, + Some(false) + ); + + let unset = crate::config::TlsConfig::default(); + let params = build_connection_params(&connection, &auth, &unset); + assert_eq!(params.check_certificate_revocation, None); + assert_eq!(params.accept_undetermined_certificate_revocation, None); + } + #[test] fn pat_auth_has_no_driver_auth_flow() { let auth = AuthConfig::Pat { From 444125a2778e73584909a77bab1bd44b8b4b3477 Mon Sep 17 00:00:00 2001 From: cat23123 <58714163+cat23123@users.noreply.github.com> Date: Fri, 20 Nov 2026 21:28:37 +0000 Subject: [PATCH 38/43] fix(tls): treat an invalid signature as undetermined and check stapled OCSP The status now reads the trust bits of the chain and of every element. A bad signature on any element is undetermined, so strict mode rejects it and accept-undetermined accepts it. A revoked bit stays revoked. The mapping is a pure function with unit tests on synthetic bits. A non-empty stapled OCSP response is attached to the leaf with CERT_OCSP_RESPONSE_PROP_ID, as SChannel does. An empty response is skipped, and a refused one is ignored. A Windows test shows that an empty or garbage response does not change the good or CRL-revoked outcome. A positive stapled test needs an OCSP responder fixture, which is a follow-up. Co-authored-by: Isaac Signed-off-by: cat23123 <58714163+cat23123@users.noreply.github.com> --- src/client/tls_revocation.rs | 104 ++++++++++++++++++++++------- src/client/tls_revocation_tests.rs | 68 +++++++++++++++++++ 2 files changed, 148 insertions(+), 24 deletions(-) diff --git a/src/client/tls_revocation.rs b/src/client/tls_revocation.rs index 4a8aceb8..4e421bec 100644 --- a/src/client/tls_revocation.rs +++ b/src/client/tls_revocation.rs @@ -47,12 +47,14 @@ use rustls::{ use windows_sys::Win32::Security::Cryptography::{ CertAddCertificateContextToStore, CertCloseStore, CertCreateCertificateChainEngine, CertCreateCertificateContext, CertFreeCertificateChain, CertFreeCertificateChainEngine, - CertFreeCertificateContext, CertGetCertificateChain, CertOpenStore, CERT_CHAIN_CONTEXT, - CERT_CHAIN_ENGINE_CONFIG, CERT_CHAIN_EXCLUSIVE_ENABLE_CA_FLAG, CERT_CHAIN_PARA, + CertFreeCertificateContext, CertGetCertificateChain, CertOpenStore, + CertSetCertificateContextProperty, CERT_CHAIN_CONTEXT, CERT_CHAIN_ENGINE_CONFIG, + CERT_CHAIN_EXCLUSIVE_ENABLE_CA_FLAG, CERT_CHAIN_PARA, CERT_CHAIN_REVOCATION_ACCUMULATIVE_TIMEOUT, CERT_CHAIN_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT, - CERT_CONTEXT, CERT_STORE_ADD_ALWAYS, CERT_STORE_PROV_MEMORY, CERT_TRUST_IS_OFFLINE_REVOCATION, + CERT_CONTEXT, CERT_OCSP_RESPONSE_PROP_ID, CERT_STORE_ADD_ALWAYS, CERT_STORE_PROV_MEMORY, + CERT_TRUST_IS_NOT_SIGNATURE_VALID, CERT_TRUST_IS_OFFLINE_REVOCATION, CERT_TRUST_IS_PARTIAL_CHAIN, CERT_TRUST_IS_REVOKED, CERT_TRUST_REVOCATION_STATUS_UNKNOWN, - HCERTCHAINENGINE, HCERTSTORE, PKCS_7_ASN_ENCODING, X509_ASN_ENCODING, + CRYPT_INTEGER_BLOB, HCERTCHAINENGINE, HCERTSTORE, PKCS_7_ASN_ENCODING, X509_ASN_ENCODING, }; #[cfg(test)] @@ -61,9 +63,8 @@ use windows_sys::Win32::Foundation::GetLastError; // REVOCATION_STATUS_UNKNOWN) are not repeated here. #[cfg(test)] use windows_sys::Win32::Security::Cryptography::{ - CERT_TRUST_IS_CYCLIC, CERT_TRUST_IS_NOT_SIGNATURE_VALID, CERT_TRUST_IS_NOT_TIME_VALID, - CERT_TRUST_IS_NOT_VALID_FOR_USAGE, CERT_TRUST_IS_UNTRUSTED_ROOT, - CERT_TRUST_NO_ISSUANCE_CHAIN_POLICY, + CERT_TRUST_IS_CYCLIC, CERT_TRUST_IS_NOT_TIME_VALID, CERT_TRUST_IS_NOT_VALID_FOR_USAGE, + CERT_TRUST_IS_UNTRUSTED_ROOT, CERT_TRUST_NO_ISSUANCE_CHAIN_POLICY, }; use super::http::TlsConfig; @@ -132,6 +133,31 @@ impl Context { }; (!context.is_null()).then_some(Self(context)) } + + /// Attaches a stapled OCSP response to this certificate, as SChannel does, so CryptoAPI can + /// use it instead of fetching one. CryptoAPI copies the response into the context, so + /// `response` needs to live only for the call. Returns false when CryptoAPI refuses it, and + /// CryptoAPI then fetches as usual. + fn set_ocsp_response(&self, response: &[u8]) -> bool { + let Ok(len) = u32::try_from(response.len()) else { + return false; + }; + let blob = CRYPT_INTEGER_BLOB { + cbData: len, + pbData: response.as_ptr().cast_mut(), + }; + // SAFETY: the context is live. `blob` and `response` are valid for the call, and the + // property is set with no flags. The API takes a pointer to the blob, not the blob's + // contents. + unsafe { + CertSetCertificateContextProperty( + self.0, + CERT_OCSP_RESPONSE_PROP_ID, + 0, + (&blob as *const CRYPT_INTEGER_BLOB).cast(), + ) != 0 + } + } } impl Drop for Context { @@ -145,26 +171,46 @@ impl Drop for Context { struct ChainContext(*mut CERT_CHAIN_CONTEXT); impl ChainContext { - /// The chain-level revocation status. CryptoAPI combines the status of every element - /// (the root is not checked, so its bits do not appear). The trust bits are not read. + /// The revocation status of the chain. CryptoAPI combines the status of the elements into + /// the chain's bits (the root is not checked, so its bits do not appear). The elements are + /// read as well, so no element's bits are missed. The trust bits are not read. fn status(&self) -> Status { - // SAFETY: the chain is live until this guard drops, and the read does not write. - let bits = unsafe { (*self.0).TrustStatus.dwErrorStatus }; - if bits & CERT_TRUST_IS_REVOKED != 0 { - Status::Revoked - } else if bits - & (CERT_TRUST_REVOCATION_STATUS_UNKNOWN - | CERT_TRUST_IS_OFFLINE_REVOCATION - | CERT_TRUST_IS_PARTIAL_CHAIN) - != 0 - { - Status::Undetermined - } else { - Status::Good + // SAFETY: the chain is live until this guard drops, and every read is of a field CryptoAPI + // sets. Each simple chain pointer is valid for `cChain`, and each element pointer for the + // `cElement` of its simple chain. + unsafe { + let chain = &*self.0; + let mut bits = vec![chain.TrustStatus.dwErrorStatus]; + for i in 0..chain.cChain as usize { + let simple = &**chain.rgpChain.add(i); + bits.push(simple.TrustStatus.dwErrorStatus); + for j in 0..simple.cElement as usize { + bits.push((**simple.rgpElement.add(j)).TrustStatus.dwErrorStatus); + } + } + status_from_bits(&bits) } } } +/// Maps the trust error bits of a chain and its elements to a status. Pure, so each case is +/// testable on its own. A revoked bit anywhere makes the chain revoked. A bad signature, unknown +/// or offline revocation, or a partial chain anywhere makes it undetermined: a signature that does +/// not verify is no evidence that the chain is good. Otherwise it is good. +fn status_from_bits(bits: &[u32]) -> Status { + const UNDETERMINED: u32 = CERT_TRUST_IS_NOT_SIGNATURE_VALID + | CERT_TRUST_REVOCATION_STATUS_UNKNOWN + | CERT_TRUST_IS_OFFLINE_REVOCATION + | CERT_TRUST_IS_PARTIAL_CHAIN; + if bits.iter().any(|bit| bit & CERT_TRUST_IS_REVOKED != 0) { + Status::Revoked + } else if bits.iter().any(|bit| bit & UNDETERMINED != 0) { + Status::Undetermined + } else { + Status::Good + } +} + #[cfg(test)] impl ChainContext { /// Test-only: the chain's shape and trust bits, by name, for diagnosing a failing run. @@ -244,7 +290,12 @@ impl Drop for ChainContext { /// CryptoAPI's revocation status for the chain that `leaf` builds. The presented /// intermediates and the custom CAs are in the chain's additional store, so CryptoAPI can /// reach the issuers that Windows does not trust. Trust is not decided here. -fn cryptoapi_status(leaf: &[u8], intermediates: &[&[u8]], custom_cas: &[&[u8]]) -> Status { +fn cryptoapi_status( + leaf: &[u8], + intermediates: &[&[u8]], + custom_cas: &[&[u8]], + ocsp: &[u8], +) -> Status { // Each handle has a guard, so every early return frees what was opened. let Some(store) = Store::memory() else { return Status::Undetermined; @@ -258,6 +309,11 @@ fn cryptoapi_status(leaf: &[u8], intermediates: &[&[u8]], custom_cas: &[&[u8]]) let Some(leaf) = Context::new(leaf) else { return Status::Undetermined; }; + // The stapled response is for the leaf. An empty or refused one is ignored, and CryptoAPI + // fetches as usual. + if !ocsp.is_empty() { + let _attached = leaf.set_ocsp_response(ocsp); + } let started = Instant::now(); let status = chain_status( "default engine", @@ -435,7 +491,7 @@ impl ServerCertVerifier for RevocationVerifier { let presented: Vec<&[u8]> = intermediates.iter().map(AsRef::as_ref).collect(); let custom: Vec<&[u8]> = self.custom_cas.iter().map(AsRef::as_ref).collect(); let leaf: &[u8] = end_entity.as_ref(); - match in_runtime_blocking(|| cryptoapi_status(leaf, &presented, &custom)) { + match in_runtime_blocking(|| cryptoapi_status(leaf, &presented, &custom, ocsp_response)) { Status::Good => Ok(ServerCertVerified::assertion()), Status::Revoked => Err(rustls::Error::InvalidCertificate(CertificateError::Revoked)), Status::Undetermined if self.accept_undetermined => Ok(ServerCertVerified::assertion()), diff --git a/src/client/tls_revocation_tests.rs b/src/client/tls_revocation_tests.rs index 6e2560d5..f96168fc 100644 --- a/src/client/tls_revocation_tests.rs +++ b/src/client/tls_revocation_tests.rs @@ -530,6 +530,74 @@ async fn custom_ca_configured_as_the_intermediate_is_an_anchor() { assert!(err.contains("revoked"), "{err}"); } +#[test] +fn status_from_bits_maps_each_case() { + // The trust bits are not read, so an untrusted root alone is still good. + assert_eq!(status_from_bits(&[]), Status::Good); + assert_eq!(status_from_bits(&[0]), Status::Good); + assert_eq!( + status_from_bits(&[CERT_TRUST_IS_UNTRUSTED_ROOT]), + Status::Good + ); + // A bad signature on the chain or on any element is undetermined, never good. + assert_eq!( + status_from_bits(&[CERT_TRUST_IS_NOT_SIGNATURE_VALID]), + Status::Undetermined + ); + assert_eq!( + status_from_bits(&[0, CERT_TRUST_IS_NOT_SIGNATURE_VALID]), + Status::Undetermined + ); + assert_eq!( + status_from_bits(&[CERT_TRUST_REVOCATION_STATUS_UNKNOWN]), + Status::Undetermined + ); + assert_eq!( + status_from_bits(&[CERT_TRUST_IS_OFFLINE_REVOCATION]), + Status::Undetermined + ); + assert_eq!( + status_from_bits(&[CERT_TRUST_IS_PARTIAL_CHAIN]), + Status::Undetermined + ); + // Revoked wins over an invalid signature. + assert_eq!(status_from_bits(&[CERT_TRUST_IS_REVOKED]), Status::Revoked); + assert_eq!( + status_from_bits(&[CERT_TRUST_IS_NOT_SIGNATURE_VALID, CERT_TRUST_IS_REVOKED]), + Status::Revoked + ); +} + +#[test] +fn stapled_ocsp_empty_or_garbage_does_not_change_the_outcome() { + // An empty response is skipped, and bytes that are not OCSP are attached and then ignored or + // refused by CryptoAPI. Neither may change a good chain or a CRL-revoked leaf. + let good = fixture(Some(Served::Good), Served::Good, "127.0.0.1"); + let revoked = fixture(Some(Served::Revoked), Served::Good, "127.0.0.1"); + for ocsp in [&b""[..], &b"not an ocsp response"[..]] { + assert_eq!( + cryptoapi_status( + good.pki.leaf_der.as_ref(), + &[good.pki.intermediate_der.as_ref()], + &[good.pki.root_der.as_ref()], + ocsp, + ), + Status::Good, + "good chain, ocsp={ocsp:?}" + ); + assert_eq!( + cryptoapi_status( + revoked.pki.leaf_der.as_ref(), + &[revoked.pki.intermediate_der.as_ref()], + &[revoked.pki.root_der.as_ref()], + ocsp, + ), + Status::Revoked, + "revoked leaf, ocsp={ocsp:?}" + ); + } +} + #[tokio::test(flavor = "multi_thread")] async fn multi_thread_runtime_checks_revocation() { // The other tests run on current_thread, where `in_runtime_blocking` does not call From 9a8086a931f8ec827091b307590f1c9876fbd644 Mon Sep 17 00:00:00 2001 From: cat23123 <58714163+cat23123@users.noreply.github.com> Date: Fri, 20 Nov 2026 21:28:40 +0000 Subject: [PATCH 39/43] docs(tls): document stapled OCSP, the signature rule and the telemetry key limit config.rs and the design doc state that a stapled OCSP response is attached to the leaf and that rustls requests OCSP stapling by default. They state the invalid-signature rule and the telemetry cache key limit, and that a positive stapled-OCSP test is a follow-up. Co-authored-by: Isaac Signed-off-by: cat23123 <58714163+cat23123@users.noreply.github.com> --- docs/designs/tls-config-design.md | 6 +++++- src/config.rs | 5 ++++- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/docs/designs/tls-config-design.md b/docs/designs/tls-config-design.md index 22705972..fe13f232 100644 --- a/docs/designs/tls-config-design.md +++ b/docs/designs/tls-config-design.md @@ -254,7 +254,11 @@ The Rust driver uses `databricks.http.tls.*` while the C# driver uses `adbc.http ### Scope Exclusions - **Certificate revocation is Windows-only**: the check exists only on Windows with `tls-rustls`, and is decided by Windows CryptoAPI (`CertGetCertificateChain`). On every other platform, and on `tls-native` (including Windows), requesting revocation fails session open with `InvalidArgument`, as an unsupported option does. The ODBC driver reads its CheckCertRevocation and AcceptUndeterminedRevocation keys only on Windows; elsewhere it warns and ignores them. The kernel does not port the check to Linux or macOS, and `tls-native` on Windows is not given a CryptoAPI path, because native-tls exposes no verifier hook and this keeps the surface smaller. -- **Trust stays with webpki**: the connection's webpki verifier, over the kernel's roots (webpki roots, the OS store, custom CAs), decides the chain, the name and the signatures, exactly as with revocation off. Only after that succeeds does CryptoAPI decide revocation. CryptoAPI builds its chain from the leaf, the presented intermediates and the custom CAs. It checks every certificate except the root. Only the chain-level revocation bits are read. The trust bits, including the root's, are ignored, so a custom CA that Windows does not trust is still checked, because the custom CAs are in CryptoAPI's additional store. A trust anchor is not revocation-checked, including a self-signed server certificate configured as a custom CA, as in RFC 5280, the JDK PKIX path validator and CryptoAPI's exclude-root flag. The leaf and the other chain certificates are checked. +- **Trust stays with webpki**: the connection's webpki verifier, over the kernel's roots (webpki roots, the OS store, custom CAs), decides the chain, the name and the signatures, exactly as with revocation off. Only after that succeeds does CryptoAPI decide revocation. CryptoAPI builds its chain from the leaf, the presented intermediates and the custom CAs. It checks every certificate except the root. Only the chain-level revocation bits are read. The trust bits, including the root's, are ignored, so a custom CA that Windows does not trust is still checked, because the custom CAs are in CryptoAPI's additional store. +- **Telemetry cache limit**: the telemetry client cache key covers the host and the effective revocation mode only. Sessions to one host with different custom CA, self-signed, mTLS or proxy settings share a telemetry client, as before revocation was added. Per-session isolation is a follow-up. +- **Stapled OCSP**: a non-empty stapled OCSP response from the server is attached to the leaf certificate (`CERT_OCSP_RESPONSE_PROP_ID`, as SChannel does), so CryptoAPI can use it and skip a fetch for the leaf. rustls's client sends the `status_request` extension (OCSP) by default, so a server that staples gives the response to the check. An empty or refused response is ignored and CryptoAPI fetches as usual. There is no positive stapled-OCSP test yet: it needs an OCSP responder fixture, which is a follow-up. +- **Trust status**: a chain with an invalid signature on any element is undetermined, never good. Strict mode rejects it and accept-undetermined accepts it. A revoked status stays revoked. +- A trust anchor is not revocation-checked, including a self-signed server certificate configured as a custom CA, as in RFC 5280, the JDK PKIX path validator and CryptoAPI's exclude-root flag. The leaf and the other chain certificates are checked. - **Chain choice**: CryptoAPI may build a different chain from the one webpki verified, for example through a cross-signed issuer. The status then comes from CryptoAPI's chain. The leaf is always checked. A server presenting more intermediates than it needs does not change the result. A presented certificate that CryptoAPI refuses to add is skipped, so it cannot hide the leaf's status; a chain that needs it comes out partial and is undetermined. - **Strict and accept-undetermined**: a revoked status is rejected in both modes. An undetermined status (a fetch failure, an offline status, a missing revocation URL, or a partial chain) is rejected in strict mode and accepted under accept-undetermined. This matches Simba's semantics. A partial chain is a root that Windows cannot build to and that is not a custom CA, for example a public root that appears only in the webpki bundle. Under strict mode that connection fails. - **CRL and OCSP fetching**: CryptoAPI retrieves CRLs and OCSP responses through Windows' networking stack (WinHTTP) and its proxy settings, not through the kernel's `ProxyConfig`. Windows caches the results, so a certificate revoked after a CRL was cached may be accepted until the cache refreshes. The kernel adds no CRL cache, worker thread, redirect policy or size limit of its own. diff --git a/src/config.rs b/src/config.rs index 9d7c610d..bac03b76 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1054,7 +1054,10 @@ pub struct TlsConfig { /// Only the revocation bits are read. The trust bits are ignored. A trust anchor is not /// revocation-checked, including a self-signed server certificate configured as a custom CA, /// as in RFC 5280, the JDK PKIX path validator and CryptoAPI's exclude-root flag. The leaf - /// and the other chain certificates are checked. CRL and OCSP + /// and the other chain certificates are checked. A chain with an invalid signature on any + /// element is undetermined, never good. A non-empty stapled OCSP response from the server is + /// attached to the leaf, so CryptoAPI can use it without a fetch. rustls's client requests + /// OCSP stapling by default, and an empty or refused response is ignored. CRL and OCSP /// retrieval uses Windows networking and proxy settings, not [`ProxyConfig`], and /// Windows caches the results. The check is synchronous and runs inside the TLS /// handshake, so it blocks the calling task until CryptoAPI returns, even on a From 2c5120ea363d99573902acb653a65fd2c04a22f0 Mon Sep 17 00:00:00 2001 From: cat23123 <58714163+cat23123@users.noreply.github.com> Date: Mon, 23 Nov 2026 16:41:11 +0000 Subject: [PATCH 40/43] fix(tls): stop the status at a custom CA anchor When a configured custom CA is a trust anchor, but Windows can build past it to an installed root, the old reading counted the anchor's revocation and the certificates above it. An unreachable CRL for the anchor then rejected strict connections, although anchors are not checked. The status is now read from the leaf up to the first custom CA on the chain, using only the bits below it. The chain-level bits are not used once the chain is cut. A chain without a custom CA is read as before. status_from_chain is a pure function, and its tests cover an anchor in the middle, a custom CA as the root, a leaf that is itself a custom CA, and the no-custom-CA case. CI cannot install a root into the Windows store, so the root-trusted case is covered only by the pure function. Co-authored-by: Isaac Signed-off-by: cat23123 <58714163+cat23123@users.noreply.github.com> --- src/client/tls_revocation.rs | 82 +++++++++++++++++++++++++----- src/client/tls_revocation_tests.rs | 74 +++++++++++++++++++++++++++ 2 files changed, 143 insertions(+), 13 deletions(-) diff --git a/src/client/tls_revocation.rs b/src/client/tls_revocation.rs index 4e421bec..bb29bd33 100644 --- a/src/client/tls_revocation.rs +++ b/src/client/tls_revocation.rs @@ -171,23 +171,69 @@ impl Drop for Context { struct ChainContext(*mut CERT_CHAIN_CONTEXT); impl ChainContext { - /// The revocation status of the chain. CryptoAPI combines the status of the elements into - /// the chain's bits (the root is not checked, so its bits do not appear). The elements are - /// read as well, so no element's bits are missed. The trust bits are not read. - fn status(&self) -> Status { + /// The revocation status of the chain, read from each simple chain from the leaf up (see + /// `status_from_chain`), keeping the worst result. The trust bits are not read. + fn status(&self, custom_cas: &[&[u8]]) -> Status { // SAFETY: the chain is live until this guard drops, and every read is of a field CryptoAPI - // sets. Each simple chain pointer is valid for `cChain`, and each element pointer for the - // `cElement` of its simple chain. + // sets. Each simple chain pointer is valid for `cChain`, each element pointer for the + // `cElement` of its simple chain, and each certificate pointer for its element. The DER + // bytes stay valid while the chain lives, and are used only within this call. unsafe { let chain = &*self.0; - let mut bits = vec![chain.TrustStatus.dwErrorStatus]; + let chain_bits = chain.TrustStatus.dwErrorStatus; + if chain.cChain == 0 { + return status_from_chain(chain_bits, &[], custom_cas); + } + let mut worst = Status::Good; for i in 0..chain.cChain as usize { let simple = &**chain.rgpChain.add(i); - bits.push(simple.TrustStatus.dwErrorStatus); + let mut elements: Vec<(&[u8], u32)> = Vec::with_capacity(simple.cElement as usize); for j in 0..simple.cElement as usize { - bits.push((**simple.rgpElement.add(j)).TrustStatus.dwErrorStatus); + let element = &**simple.rgpElement.add(j); + let cert = &*element.pCertContext; + let der: &[u8] = if cert.pbCertEncoded.is_null() { + &[] + } else { + std::slice::from_raw_parts(cert.pbCertEncoded, cert.cbCertEncoded as usize) + }; + elements.push((der, element.TrustStatus.dwErrorStatus)); } + worst = worse(worst, status_from_chain(chain_bits, &elements, custom_cas)); } + worst + } + } +} + +/// The more severe of two statuses: revoked, then undetermined, then good. +fn worse(a: Status, b: Status) -> Status { + match (a, b) { + (Status::Revoked, _) | (_, Status::Revoked) => Status::Revoked, + (Status::Undetermined, _) | (_, Status::Undetermined) => Status::Undetermined, + _ => Status::Good, + } +} + +/// The status of one simple chain. `elements` are its certificates, from the leaf up, with their +/// trust error bits. `chain_bits` are the chain-level bits, which are used only when no element is +/// a custom CA. +/// +/// A custom CA on the chain is a trust anchor. Anchors are not revocation-checked, and neither are +/// the certificates above one, so the elements below the first anchor are read on their own. The +/// chain-level bits are dropped then, because they combine the anchor and the certificates above +/// it. Without a custom CA on the chain, the chain-level and element bits are read as before. +fn status_from_chain(chain_bits: u32, elements: &[(&[u8], u32)], custom_cas: &[&[u8]]) -> Status { + match elements + .iter() + .position(|(der, _)| custom_cas.contains(der)) + { + Some(anchor) => { + let bits: Vec = elements[..anchor].iter().map(|(_, bits)| *bits).collect(); + status_from_bits(&bits) + } + None => { + let mut bits = vec![chain_bits]; + bits.extend(elements.iter().map(|(_, bits)| *bits)); status_from_bits(&bits) } } @@ -321,6 +367,7 @@ fn cryptoapi_status( &store, null_mut(), REVOCATION_TIMEOUT, + custom_cas, ); // With a custom CA, Windows does not trust its root. The default engine can then end the // chain at an untrusted root and report no revocation status, so the result is undetermined. @@ -346,18 +393,27 @@ fn cryptoapi_status( let Some(engine) = ChainEngine::exclusive(&roots) else { return status; }; - chain_status("exclusive-root engine", &leaf, &store, engine.0, remaining) + chain_status( + "exclusive-root engine", + &leaf, + &store, + engine.0, + remaining, + custom_cas, + ) } /// Builds the chain for `leaf` with `engine` (null is the default engine) and reads its -/// revocation status. `budget` bounds the revocation fetches of this build. `label` names the -/// engine in the test-only diagnostics. +/// revocation status. `budget` bounds the revocation fetches of this build. `custom_cas` are the +/// trust anchors that the status reading stops at. `label` names the engine in the test-only +/// diagnostics. fn chain_status( label: &str, leaf: &Context, store: &Store, engine: HCERTCHAINENGINE, budget: Duration, + custom_cas: &[&[u8]], ) -> Status { // Only the test-only diagnostics below read `label`. let _ = label; @@ -395,7 +451,7 @@ fn chain_status( let chain = ChainContext(chain); #[cfg(test)] eprintln!("revocation diagnostics [{label}]: {}", chain.describe()); - chain.status() + chain.status(custom_cas) } /// A chain engine whose exclusive root is a store of custom CAs. Freed on drop. diff --git a/src/client/tls_revocation_tests.rs b/src/client/tls_revocation_tests.rs index f96168fc..a9da9a07 100644 --- a/src/client/tls_revocation_tests.rs +++ b/src/client/tls_revocation_tests.rs @@ -568,6 +568,80 @@ fn status_from_bits_maps_each_case() { ); } +#[test] +fn status_from_chain_stops_at_a_custom_anchor() { + // Synthetic certificates: only their identity matters for the anchor match. + let leaf: &[u8] = b"leaf"; + let anchor: &[u8] = b"anchor"; + let issuer: &[u8] = b"issuer"; + let other: &[u8] = b"other"; + let cas: [&[u8]; 1] = [anchor]; + let unknown = CERT_TRUST_REVOCATION_STATUS_UNKNOWN; + + // Anchor in the middle: its bits and those of the certificates above it are ignored. + assert_eq!( + status_from_chain( + 0, + &[ + (leaf, 0), + (anchor, unknown), + (issuer, CERT_TRUST_IS_REVOKED) + ], + &cas + ), + Status::Good + ); + // The leaf below an anchor is still checked. + assert_eq!( + status_from_chain(0, &[(leaf, CERT_TRUST_IS_REVOKED), (anchor, 0)], &cas), + Status::Revoked + ); + assert_eq!( + status_from_chain(0, &[(leaf, unknown), (anchor, 0)], &cas), + Status::Undetermined + ); + // The chain-level bits combine the anchor, so they are dropped once the chain is cut. + assert_eq!( + status_from_chain(CERT_TRUST_IS_REVOKED, &[(leaf, 0), (anchor, 0)], &cas), + Status::Good + ); + + // Custom CA is the root: the certificates below it are checked, the root is not. + assert_eq!( + status_from_chain(0, &[(leaf, 0), (other, unknown), (anchor, 0)], &cas), + Status::Undetermined + ); + assert_eq!( + status_from_chain( + 0, + &[(leaf, 0), (other, 0), (anchor, CERT_TRUST_IS_REVOKED)], + &cas + ), + Status::Good + ); + + // No custom CA on the chain: the chain-level and element bits are read as before. + assert_eq!( + status_from_chain(0, &[(leaf, 0), (other, unknown), (issuer, 0)], &cas), + Status::Undetermined + ); + assert_eq!( + status_from_chain(CERT_TRUST_IS_REVOKED, &[(leaf, 0), (other, 0)], &cas), + Status::Revoked + ); + assert_eq!(status_from_chain(0, &[], &cas), Status::Good); + + // A leaf that is itself the custom CA is an anchor, so nothing below it is checked. + assert_eq!( + status_from_chain( + CERT_TRUST_IS_REVOKED, + &[(anchor, CERT_TRUST_IS_REVOKED), (issuer, 0)], + &cas + ), + Status::Good + ); +} + #[test] fn stapled_ocsp_empty_or_garbage_does_not_change_the_outcome() { // An empty response is skipped, and bytes that are not OCSP are attached and then ignored or From c8d6ecda82cd13a1e5f37d1837368755d2732279 Mon Sep 17 00:00:00 2001 From: cat23123 <58714163+cat23123@users.noreply.github.com> Date: Mon, 23 Nov 2026 16:41:14 +0000 Subject: [PATCH 41/43] docs(tls): state that custom anchors and the certificates above them are not checked config.rs and the design doc state that a custom CA on the chain is a trust anchor, including a custom intermediate anchor, and that the certificates above it are not checked. The leaf and the certificates below an anchor are checked. Co-authored-by: Isaac Signed-off-by: cat23123 <58714163+cat23123@users.noreply.github.com> --- docs/designs/tls-config-design.md | 2 +- src/config.rs | 8 +++++--- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/docs/designs/tls-config-design.md b/docs/designs/tls-config-design.md index fe13f232..a0e26c9f 100644 --- a/docs/designs/tls-config-design.md +++ b/docs/designs/tls-config-design.md @@ -258,7 +258,7 @@ The Rust driver uses `databricks.http.tls.*` while the C# driver uses `adbc.http - **Telemetry cache limit**: the telemetry client cache key covers the host and the effective revocation mode only. Sessions to one host with different custom CA, self-signed, mTLS or proxy settings share a telemetry client, as before revocation was added. Per-session isolation is a follow-up. - **Stapled OCSP**: a non-empty stapled OCSP response from the server is attached to the leaf certificate (`CERT_OCSP_RESPONSE_PROP_ID`, as SChannel does), so CryptoAPI can use it and skip a fetch for the leaf. rustls's client sends the `status_request` extension (OCSP) by default, so a server that staples gives the response to the check. An empty or refused response is ignored and CryptoAPI fetches as usual. There is no positive stapled-OCSP test yet: it needs an OCSP responder fixture, which is a follow-up. - **Trust status**: a chain with an invalid signature on any element is undetermined, never good. Strict mode rejects it and accept-undetermined accepts it. A revoked status stays revoked. -- A trust anchor is not revocation-checked, including a self-signed server certificate configured as a custom CA, as in RFC 5280, the JDK PKIX path validator and CryptoAPI's exclude-root flag. The leaf and the other chain certificates are checked. +- **Trust anchors**: a trust anchor is not revocation-checked, and neither are the certificates above it. A custom CA on the chain is an anchor, including a self-signed server certificate configured as a custom CA and a custom intermediate anchor, even when Windows can build past it to an installed root. This follows RFC 5280, the JDK PKIX path validator and CryptoAPI's exclude-root flag. The status is read from the leaf up to the first custom CA on the chain, using only the bits below it, so the chain-level bits (which include the anchor) are not used when the chain is cut. A chain without a custom CA is read as before. The rule is tested through a pure function on synthetic chains, because CI cannot install a root into the Windows store. - **Chain choice**: CryptoAPI may build a different chain from the one webpki verified, for example through a cross-signed issuer. The status then comes from CryptoAPI's chain. The leaf is always checked. A server presenting more intermediates than it needs does not change the result. A presented certificate that CryptoAPI refuses to add is skipped, so it cannot hide the leaf's status; a chain that needs it comes out partial and is undetermined. - **Strict and accept-undetermined**: a revoked status is rejected in both modes. An undetermined status (a fetch failure, an offline status, a missing revocation URL, or a partial chain) is rejected in strict mode and accepted under accept-undetermined. This matches Simba's semantics. A partial chain is a root that Windows cannot build to and that is not a custom CA, for example a public root that appears only in the webpki bundle. Under strict mode that connection fails. - **CRL and OCSP fetching**: CryptoAPI retrieves CRLs and OCSP responses through Windows' networking stack (WinHTTP) and its proxy settings, not through the kernel's `ProxyConfig`. Windows caches the results, so a certificate revoked after a CRL was cached may be accepted until the cache refreshes. The kernel adds no CRL cache, worker thread, redirect policy or size limit of its own. diff --git a/src/config.rs b/src/config.rs index bac03b76..33f3ab95 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1052,9 +1052,11 @@ pub struct TlsConfig { /// Trust, name and signatures are still decided by webpki, as with checking off. /// CryptoAPI then checks every certificate in the chain it builds except the root. /// Only the revocation bits are read. The trust bits are ignored. A trust anchor is not - /// revocation-checked, including a self-signed server certificate configured as a custom CA, - /// as in RFC 5280, the JDK PKIX path validator and CryptoAPI's exclude-root flag. The leaf - /// and the other chain certificates are checked. A chain with an invalid signature on any + /// revocation-checked, and neither are the certificates above it. A custom CA on the chain is + /// an anchor, including a self-signed server certificate configured as a custom CA and a custom + /// intermediate anchor, even when Windows can build past it to an installed root. This follows + /// RFC 5280, the JDK PKIX path validator and CryptoAPI's exclude-root flag. The leaf and the + /// certificates below an anchor are checked. A chain with an invalid signature on any /// element is undetermined, never good. A non-empty stapled OCSP response from the server is /// attached to the leaf, so CryptoAPI can use it without a fetch. rustls's client requests /// OCSP stapling by default, and an empty or refused response is ignored. CRL and OCSP From adb17d96f4baa53cbaf674a43dada526ca1285b5 Mon Sep 17 00:00:00 2001 From: cat23123 <58714163+cat23123@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:46:20 +0000 Subject: [PATCH 42/43] test(retry): pin revocation failures as permanent certificate errors The Windows revocation verifier returns InvalidCertificate(Revoked) for a revoked status and, in strict mode, InvalidCertificate(UnknownRevocationStatus) for an undetermined one. The config docs say both are permanent and never retried. Add both to the classifier test, which runs in the tls-rustls job on Linux and Windows, so a change to the classifier that would retry them fails there. Co-authored-by: Isaac Signed-off-by: cat23123 <58714163+cat23123@users.noreply.github.com> --- src/client/retry.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/client/retry.rs b/src/client/retry.rs index cdd1c31b..1c0d21c5 100644 --- a/src/client/retry.rs +++ b/src/client/retry.rs @@ -497,6 +497,10 @@ mod tests { rustls::Error::InvalidCertificate(rustls::CertificateError::UnknownIssuer), rustls::Error::InvalidCertificate(rustls::CertificateError::NotValidForName), rustls::Error::InvalidCertificate(rustls::CertificateError::Expired), + // What the Windows revocation verifier returns for a revoked or, in strict mode, + // undetermined status: both are permanent and never retried. + rustls::Error::InvalidCertificate(rustls::CertificateError::Revoked), + rustls::Error::InvalidCertificate(rustls::CertificateError::UnknownRevocationStatus), rustls::Error::NoCertificatesPresented, ] { let error = std::io::Error::other(std::io::Error::other(error)); From c2b961dac4b205a9dd701fbb7502616234cc8b67 Mon Sep 17 00:00:00 2001 From: cat23123 <58714163+cat23123@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:57:45 +0000 Subject: [PATCH 43/43] fix(telemetry): log the plain host for the circuit breaker The breaker is shared per host and revocation mode, so its lookup key is `host|revocation=`. That key was also stored as the exporter's host, so breaker debug logs showed it as a hostname. maybe_wrap_exporter now takes the plain host for logging and the composite key for the breaker lookup. Sharing is unchanged; a test checks both. Co-authored-by: Isaac Signed-off-by: cat23123 <58714163+cat23123@users.noreply.github.com> --- src/telemetry/circuit_breaker.rs | 51 ++++++++++++++++++++++++++++++-- src/telemetry/runtime.rs | 6 +++- 2 files changed, 54 insertions(+), 3 deletions(-) diff --git a/src/telemetry/circuit_breaker.rs b/src/telemetry/circuit_breaker.rs index cb07c470..48e12df2 100644 --- a/src/telemetry/circuit_breaker.rs +++ b/src/telemetry/circuit_breaker.rs @@ -275,8 +275,11 @@ impl CircuitBreakerManager { } } +/// Wraps `exporter` in the circuit breaker shared under `breaker_key` (the host plus the +/// revocation mode). `host` is the plain host, used only in log messages. pub(super) fn maybe_wrap_exporter( host: &str, + breaker_key: &str, config: &TelemetryConfig, exporter: Arc, ) -> Arc { @@ -284,9 +287,10 @@ pub(super) fn maybe_wrap_exporter( return exporter; }; - Arc::new(CircuitBreakerTelemetryExporter::new( + Arc::new(CircuitBreakerTelemetryExporter::keyed( exporter, host, + breaker_key, circuit_config, )) } @@ -298,11 +302,22 @@ struct CircuitBreakerTelemetryExporter { } impl CircuitBreakerTelemetryExporter { + #[cfg(test)] fn new(inner: Arc, host: &str, config: CircuitBreakerConfig) -> Self { + Self::keyed(inner, host, host, config) + } + + /// `host` is logged; `breaker_key` selects the shared breaker. + fn keyed( + inner: Arc, + host: &str, + breaker_key: &str, + config: CircuitBreakerConfig, + ) -> Self { Self { inner, host: host.to_string(), - breaker: CircuitBreakerManager::global().get_or_create(host, config), + breaker: CircuitBreakerManager::global().get_or_create(breaker_key, config), } } } @@ -574,6 +589,38 @@ mod tests { assert!(Arc::ptr_eq(&strict, &again)); } + #[test] + fn keyed_exporter_logs_the_plain_host_and_shares_the_keyed_breaker() { + use crate::telemetry::runtime::telemetry_cache_key; + + let host = unique_host("keyed-log-host"); + let key = telemetry_cache_key(host, Some(false)); + let config = CircuitBreakerConfig { + failure_threshold: 1, + open_timeout: Duration::from_secs(60), + }; + let first = CircuitBreakerTelemetryExporter::keyed( + Arc::new(CapturingExporter::default()), + host, + &key, + config, + ); + let second = CircuitBreakerTelemetryExporter::keyed( + Arc::new(CapturingExporter::default()), + host, + &key, + config, + ); + // Logs carry the real host, not the composite key. + assert_eq!(first.host, host); + // The breaker is still shared per key. + assert!(Arc::ptr_eq(&first.breaker, &second.breaker)); + assert!(Arc::ptr_eq( + &first.breaker, + &CircuitBreakerManager::global().get_or_create(&key, config) + )); + } + #[tokio::test] async fn different_hosts_have_independent_breakers() { let failing = Arc::new(FailingExporter::default()); diff --git a/src/telemetry/runtime.rs b/src/telemetry/runtime.rs index deb57170..1c22fdb2 100644 --- a/src/telemetry/runtime.rs +++ b/src/telemetry/runtime.rs @@ -337,12 +337,16 @@ fn exporter_for_config( // parallel tests commonly reuse the same mock host with different // capturing exporters, and cache reuse would route events to the // exporter from whichever test created the host client first. - return (maybe_wrap_exporter(&breaker_key, config, exporter), true); + return ( + maybe_wrap_exporter(&connection.host, &breaker_key, config, exporter), + true, + ); } } ( maybe_wrap_exporter( + &connection.host, &breaker_key, config, Arc::new(DatabricksTelemetryExporter::new(