diff --git a/.github/workflows/pr-checks.yml b/.github/workflows/pr-checks.yml index f07393fe..203ef8f2 100644 --- a/.github/workflows/pr-checks.yml +++ b/.github/workflows/pr-checks.yml @@ -238,3 +238,43 @@ 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 + + # 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 client behavior (tls-rustls, Windows) + shell: pwsh + # 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 diff --git a/Cargo.lock b/Cargo.lock index d4992a7f..2c64664c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -678,6 +678,7 @@ dependencies = [ "ring", "rsa", "rustls", + "rustls-native-certs", "rustls-webpki", "serde", "serde_json", @@ -690,6 +691,7 @@ dependencies = [ "tracing", "tracing-subscriber", "webpki-roots", + "windows-sys 0.61.2", "wiremock", "wkb", "wkt", diff --git a/Cargo.toml b/Cargo.toml index ee46e1b7..ba91b6b9 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -145,6 +145,14 @@ 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 +# 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_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"] } wiremock = "0.6" @@ -212,6 +220,7 @@ tls-rustls = [ "dep:rustls", "dep:rustls-webpki", "dep:webpki-roots", + "dep:rustls-native-certs", ] [lib] diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index 2ebce050..68b38965 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -11,6 +11,19 @@ changes go in their respective binding's NEXT_CHANGELOG. ### Added +- 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`. CRL and OCSP fetches + use Windows' networking and proxy settings, and Windows caches their results. + 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 ### Updated diff --git a/adbc/Cargo.lock b/adbc/Cargo.lock index dcaa4b65..b903c723 100644 --- a/adbc/Cargo.lock +++ b/adbc/Cargo.lock @@ -683,6 +683,7 @@ dependencies = [ "tokio-util", "tracing", "tracing-subscriber", + "windows-sys 0.61.2", "wkb", "wkt", "zeroize", diff --git a/docs/designs/tls-config-design.md b/docs/designs/tls-config-design.md index 1fc856f4..a0e26c9f 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, 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,7 +253,20 @@ 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 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. +- **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. +- **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. +- **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. - **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 e167f181..841d98c9 100644 --- a/include/databricks_kernel.h +++ b/include/databricks_kernel.h @@ -468,6 +468,32 @@ 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). + * + * 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. + * + * CRL and OCSP retrieval uses Windows networking and proxy settings, not the + * 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, 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 + * 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); + /* 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/napi/Cargo.lock b/napi/Cargo.lock index b3b4c36e..49f9eb15 100644 --- a/napi/Cargo.lock +++ b/napi/Cargo.lock @@ -634,6 +634,7 @@ dependencies = [ "rand 0.10.2", "reqwest", "rustls", + "rustls-native-certs", "rustls-webpki", "serde", "serde_json", @@ -644,6 +645,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 fa59876f..a3ac4bf9 100644 --- a/pyo3/Cargo.lock +++ b/pyo3/Cargo.lock @@ -630,6 +630,7 @@ dependencies = [ "rand 0.10.2", "reqwest", "rustls", + "rustls-native-certs", "rustls-webpki", "serde", "serde_json", @@ -640,6 +641,7 @@ dependencies = [ "tracing", "tracing-subscriber", "webpki-roots", + "windows-sys 0.61.2", "wkb", "wkt", "zeroize", diff --git a/src/c_abi/session.rs b/src/c_abi/session.rs index b3365f49..21ae8f53 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,30 @@ 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 (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. +#[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 +1775,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("TLS certificate revocation checking"), + "{message}" + ); + } + } +} + +/// 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}; + + /// 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}; + + 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(); + // rustls renders the error as "invalid peer certificate: Revoked". + assert!( + message.to_ascii_lowercase().contains("revoked"), + "{message}" + ); + } + } +} diff --git a/src/client/http.rs b/src/client/http.rs index cac2243b..04571de7 100644 --- a/src/client/http.rs +++ b/src/client/http.rs @@ -199,6 +199,40 @@ pub struct TlsConfig { pub client_key_pem: Option>, } +/// 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)) +} + +/// 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`. `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(()); + } + match revocation_unsupported_message(cfg!(windows), cfg!(feature = "tls-rustls")) { + Some(message) => Err(Error::invalid_argument().message(message)), + None => Ok(()), + } +} + impl std::fmt::Debug for TlsConfig { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { // Mirrors the redacting Debug on the public @@ -386,6 +420,7 @@ pub struct DatabricksHttpClient { config: HttpClientConfig, auth_provider: OnceLock>, retry_configs: HashMap, + revocation: Option, } impl DatabricksHttpClient { @@ -395,8 +430,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 @@ -478,8 +524,13 @@ 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())?; + 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 @@ -502,6 +553,7 @@ impl DatabricksHttpClient { config, auth_provider: OnceLock::new(), retry_configs, + revocation, }) } @@ -514,7 +566,9 @@ impl DatabricksHttpClient { fn build_reqwest_client( config: &HttpClientConfig, redirect: reqwest::redirect::Policy, + revocation: Option, ) -> Result { + 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 @@ -700,6 +754,18 @@ 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. `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, + accept_undetermined, + )?); + } + builder.build().map_err(|e| { Error::invalid_argument().message(format!("Failed to create HTTP client: {e}")) }) @@ -731,6 +797,12 @@ impl DatabricksHttpClient { &self.config } + /// 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 @@ -805,7 +877,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}")) })?; @@ -1083,6 +1159,43 @@ impl DatabricksHttpClient { #[path = "http_tls_tests.rs"] mod tls_tests; +#[cfg(test)] +mod revocation_support_tests { + 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() { + 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::*; @@ -1093,6 +1206,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(); @@ -1648,6 +1797,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/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 af553abf..0edc69d2 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(all(windows, 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..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)); diff --git a/src/client/tls_revocation.rs b/src/client/tls_revocation.rs new file mode 100644 index 00000000..bb29bd33 --- /dev/null +++ b/src/client/tls_revocation.rs @@ -0,0 +1,672 @@ +// 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. + +//! Certificate revocation for the `tls-rustls` backend on Windows, through CryptoAPI. +//! +//! 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. +//! +//! 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. + +use std::ptr::{null, null_mut}; +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier}; +use rustls::client::WebPkiServerVerifier; +use rustls::pki_types::{pem::PemObject, CertificateDer, ServerName, UnixTime}; +use rustls::{ + CertificateError, ClientConfig, DigitallySignedStruct, RootCertStore, SignatureScheme, +}; +use windows_sys::Win32::Security::Cryptography::{ + CertAddCertificateContextToStore, CertCloseStore, CertCreateCertificateChainEngine, + CertCreateCertificateContext, CertFreeCertificateChain, CertFreeCertificateChainEngine, + 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_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, + CRYPT_INTEGER_BLOB, HCERTCHAINENGINE, HCERTSTORE, PKCS_7_ASN_ENCODING, 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_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 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 = + 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, +} + +/// An in-memory certificate store. Closed on drop. +struct Store(HCERTSTORE); + +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)) + } + + /// Adds a copy of `der`. The store keeps its own reference, so the temporary context is + /// 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; + }; + // SAFETY: both handles are live, and no output context is requested. + unsafe { + CertAddCertificateContextToStore(self.0, context.0, CERT_STORE_ADD_ALWAYS, null_mut()) + != 0 + } + } +} + +impl Drop for Store { + fn drop(&mut self) { + // SAFETY: the handle came from `CertOpenStore` and is closed once. + unsafe { CertCloseStore(self.0, 0) }; + } +} + +/// A certificate context, freed on drop. +struct Context(*mut CERT_CONTEXT); + +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) + }; + (!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 { + 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 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`, 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 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); + let mut elements: Vec<(&[u8], u32)> = Vec::with_capacity(simple.cElement as usize); + for j in 0..simple.cElement as usize { + 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) + } + } +} + +/// 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. + 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. + unsafe { CertFreeCertificateChain(self.0) }; + } +} + +/// 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]], + 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; + }; + // 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) { + store.add(der); + } + 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", + &leaf, + &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. + // 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; + }; + 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, + 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. `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; + let para = CERT_CHAIN_PARA { + cbSize: std::mem::size_of::() 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(); + // SAFETY: the engine, leaf and store are live for the call, and `para` outlives it. Null + // time is now. + let built = unsafe { + CertGetCertificateChain( + engine, + leaf.0, + null(), + store.0, + ¶, + CHAIN_FLAGS, + null(), + &mut chain, + ) + }; + 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 [{label}]: CertGetCertificateChain failed, GetLastError={}", + unsafe { GetLastError() } + ); + return Status::Undetermined; + } + let chain = ChainContext(chain); + #[cfg(test)] + eprintln!("revocation diagnostics [{label}]: {}", chain.describe()); + chain.status(custom_cas) +} + +/// 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, + // 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(); + // 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. +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(), + } +} + +fn tls_error(e: impl std::fmt::Display) -> Error { + Error::invalid_argument().message(format!("invalid TLS configuration: {e}")) +} + +/// 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 { + /// Webpki over the kernel's roots, without CRLs. + signatures: Arc, + /// 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. + 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 { + // 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, + server_name, + ocsp_response, + now, + ))?; + 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, ocsp_response)) { + 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, + )), + } + } + + 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() + } +} + +/// 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, 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()); + } + let mut custom_cas = Vec::new(); + for pem in pems { + for cert in CertificateDer::pem_slice_iter(&pem) { + let cert = cert.map_err(tls_error)?; + roots.add(cert.clone()).map_err(tls_error)?; + custom_cas.push(cert); + } + } + + let signatures = + WebPkiServerVerifier::builder_with_provider(Arc::new(roots), Arc::clone(&provider)) + .build() + .map_err(tls_error)?; + let verifier = RevocationVerifier { + signatures, + custom_cas, + 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 = rustls::pki_types::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()]; + // 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) +} + +#[cfg(test)] +#[path = "tls_revocation_tests.rs"] +pub(crate) mod tests; diff --git a/src/client/tls_revocation_tests.rs b/src/client/tls_revocation_tests.rs new file mode 100644 index 00000000..a9da9a07 --- /dev/null +++ b/src/client/tls_revocation_tests.rs @@ -0,0 +1,828 @@ +// 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. + +//! 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::{DatabricksHttpClient, HttpClientConfig}; +use crate::client::retry::{build_retry_configs, RetryConfig}; +use rcgen::{ + date_time_ymd, BasicConstraints, CertificateParams, CertificateRevocationListParams, + 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::{SocketAddr, TcpListener, TcpStream}; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex}; +use std::thread; + +/// 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 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)] +pub(crate) enum Served { + /// A current CRL that lists nothing. + Good, + /// A current CRL that lists the covered certificate as revoked. + Revoked, + /// The distribution point is a closed port, so the fetch fails. + Refused, +} + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum Outcome { + Pass, + Revoked, + Undetermined, +} + +/// 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, + 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, 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 }, +]; + +pub(crate) struct Pki { + root_der: CertificateDer<'static>, + pub(crate) 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 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(); + 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_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)); + 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) + .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!("{}{}", client_cert.pem(), intermediate_cert.pem()), + client_key_pem: client_key.serialize_pem(), + } +} + +/// 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(CURRENT.0, CURRENT.1, CURRENT.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, 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"), + }; + Route { status: 200, body } +} + +/// A PKI, its CRL origin server, and the TLS leaf server. +pub(crate) struct Fixture { + crl: CrlServer, + 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); + +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"); + let intermediate_path = format!("/{id}/intermediate.crl"); + let dead = TcpListener::bind("127.0.0.1:0") + .unwrap() + .local_addr() + .unwrap(); + let url = |served: Served, path: &str| match served { + Served::Refused => format!("http://{dead}{path}"), + _ => crl.url(path), + }; + 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_path, + route(served, &pki.intermediate_issuer, LEAF_SERIAL), + ); + } + if let served @ (Served::Good | Served::Revoked) = intermediate { + crl.set( + &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. +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 key = PrivatePkcs8KeyDer::from(key_der).into(); + let config = if let Some(root) = mtls_root { + let mut roots = rustls::RootCertStore::empty(); + roots.add(root).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 +} + +/// 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(); + 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()) +} + +struct Route { + status: u16, + body: Vec, +} + +/// 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>>, + 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); + } + + /// The number of requests received so far, for any path. + fn hits(&self) -> usize { + 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; + }; + let path = head + .lines() + .next() + .and_then(|line| line.split_whitespace().nth(1)) + .unwrap_or("/") + .to_owned(); + 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 {status} X\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", + body.len() + ) + .into_bytes(); + response.extend_from_slice(&body); + let _ = stream.write_all(&response); + } +} + +/// 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()); + // 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 { + DatabricksHttpClient::with_revocation( + config, + build_retry_configs(&RetryConfig::default(), &HashMap::new()), + revocation, + ) + .unwrap() +} + +/// One GET to `addr`. `revocation` is `None` (off), `Some(false)` (strict) or +/// `Some(true)` (accept undetermined). +async fn get( + config: HttpClientConfig, + revocation: Option, + addr: SocketAddr, +) -> std::result::Result<(), String> { + let client = client(config, revocation); + 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 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 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}"), + (Outcome::Undetermined, Err(err)) => assert!(err.contains(UNDETERMINED), "{label}: {err}"), + _ => panic!("{label}: expected {want:?}, got {result:?}"), + } +} + +/// 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}"); +} + +#[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 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 + // 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 + // 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 { + check(scenario, false, scenario.strict).await; + check(scenario, true, scenario.accept).await; + } +} + +#[tokio::test] +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"); +} + +#[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), 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, Some(false), fx.addr) + .await + .expect("allow_hostname_mismatch passes a good chain with revocation still checked"); +} + +#[tokio::test] +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(), 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, Some(false), mtls_addr) + .await + .expect_err("the mTLS server rejects a client without an identity"); +} + +#[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), Some(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 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_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 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"); + 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("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}" + ); + } +} diff --git a/src/config.rs b/src/config.rs index 9c1eb0a9..33f3ab95 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1041,6 +1041,47 @@ pub struct TlsConfig { /// [`Self::client_cert_pem`] for pairing rules and the /// backend-specific validation timing. pub client_key_pem: Option>, + + /// Check the revocation status of the server certificate chain with Windows + /// CryptoAPI. Default off. Revoked certificates are always rejected. + /// + /// 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`]. + /// + /// 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, 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 + /// 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 + /// 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, 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, + + /// 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, } impl std::fmt::Debug for TlsConfig { @@ -1071,6 +1112,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() } } @@ -2210,4 +2259,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}" + ); + } } diff --git a/src/session.rs b/src/session.rs index ac2f462f..6477bb46 100644 --- a/src/session.rs +++ b/src/session.rs @@ -366,11 +366,19 @@ 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. + let revocation = crate::client::http::revocation_mode( + 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 @@ -451,6 +459,7 @@ impl Session { &telemetry_config, &config.connection, &config.auth, + &config.tls, config.driver_system_configuration.clone(), http_client, session_info.session_id.clone(), @@ -3988,3 +3997,46 @@ mod is_open_tests { } } } + +/// 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_unsupported_platform_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("revocation must be refused on this platform or backend"); + assert_eq!(error.code, crate::kernel_error::ErrorCode::InvalidArgument); + assert!( + error + .message + .contains("TLS certificate revocation checking"), + "{}", + error.message + ); + } +} diff --git a/src/telemetry/circuit_breaker.rs b/src/telemetry/circuit_breaker.rs index c9ea8c47..48e12df2 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 @@ -274,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 { @@ -283,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, )) } @@ -297,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), } } } @@ -547,6 +563,64 @@ 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)); + } + + #[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/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..1c22fdb2 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,12 +64,13 @@ 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()); 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, @@ -325,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,7 +338,7 @@ fn exporter_for_config( // 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), + maybe_wrap_exporter(&connection.host, &breaker_key, config, exporter), true, ); } @@ -342,6 +347,7 @@ fn exporter_for_config( ( maybe_wrap_exporter( &connection.host, + &breaker_key, config, Arc::new(DatabricksTelemetryExporter::new( &connection.host, @@ -353,6 +359,22 @@ 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", + Some(false) => "strict", + Some(true) => "accept_undetermined", + }; + format!("{host}|revocation={mode}") +} + fn build_system_configuration( override_config: Option, ) -> DriverSystemConfiguration { @@ -400,11 +422,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 { @@ -472,6 +499,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 { 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/v0_tls_revocation_e2e.rs b/tests/v0_tls_revocation_e2e.rs new file mode 100644 index 00000000..d9f2bc41 --- /dev/null +++ b/tests/v0_tls_revocation_e2e.rs @@ -0,0 +1,78 @@ +// 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 v0_tls_revocation_e2e -- --ignored --nocapture +//! ``` +//! +//! `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; + +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"); +}