diff --git a/.github/workflows/pr-checks.yml b/.github/workflows/pr-checks.yml index cbfb6d61..f07393fe 100644 --- a/.github/workflows/pr-checks.yml +++ b/.github/workflows/pr-checks.yml @@ -235,3 +235,6 @@ jobs: # under tls-native don't disappear under tls-rustls and vice # versa. run: cargo clippy -p databricks-sql-kernel --no-default-features --features tls-rustls --all-targets -- -D warnings + + - name: Test client behavior (tls-rustls) + run: "cargo test -p databricks-sql-kernel --no-default-features --features tls-rustls --lib client::" diff --git a/Cargo.lock b/Cargo.lock index b22dfe75..b47213ce 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -667,6 +667,7 @@ dependencies = [ "log", "lz4_flex", "moka", + "native-tls", "oauth2", "open", "pbkdf2 0.13.0", diff --git a/Cargo.toml b/Cargo.toml index 92e43869..f428c382 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -60,6 +60,8 @@ arrow-ipc = "59" # module load time and segfaults the process before any Rust code runs. # `rustls` is pure Rust + ring and avoids the conflict entirely. reqwest = { version = "0.12", default-features = false, features = ["json", "gzip", "stream"] } +native-tls = { version = "0.2", optional = true } +rustls = { version = "0.23.41", optional = true, default-features = false, features = ["ring", "std", "tls12"] } # Enforce TLS dependency minimums for consumers with their own lockfiles. rustls-webpki = { version = "0.103.16", optional = true, default-features = false } webpki-roots = { version = "1.0.11", optional = true, default-features = false } @@ -193,7 +195,7 @@ tokio-rustls = { version = "0.26.4", default-features = false, features = ["ring # guarantee — items 1 and 2 above are. [features] default = ["tls-native"] -tls-native = ["reqwest/native-tls"] +tls-native = ["reqwest/native-tls", "dep:native-tls"] # `rustls-tls` alone is `reqwest/rustls-tls-webpki-roots` — the bundled Mozilla # root set only, which does NOT read the OS system trust store. `tls-native` # (native-tls → OpenSSL) DOES read `/etc/ssl/...`, so a `tls-rustls` build behind @@ -207,6 +209,7 @@ tls-native = ["reqwest/native-tls"] tls-rustls = [ "reqwest/rustls-tls", "reqwest/rustls-tls-native-roots", + "dep:rustls", "dep:rustls-webpki", "dep:webpki-roots", ] diff --git a/adbc/Cargo.lock b/adbc/Cargo.lock index 442e7c96..37956eeb 100644 --- a/adbc/Cargo.lock +++ b/adbc/Cargo.lock @@ -668,6 +668,7 @@ dependencies = [ "jsonwebtoken", "lz4_flex", "moka", + "native-tls", "oauth2", "open", "pbkdf2 0.13.0", diff --git a/napi/Cargo.lock b/napi/Cargo.lock index 951fe3c9..303fb234 100644 --- a/napi/Cargo.lock +++ b/napi/Cargo.lock @@ -633,6 +633,7 @@ dependencies = [ "pkcs8", "rand 0.10.2", "reqwest", + "rustls", "rustls-webpki", "serde", "serde_json", diff --git a/pyo3/Cargo.lock b/pyo3/Cargo.lock index 2843e0d0..30946d3c 100644 --- a/pyo3/Cargo.lock +++ b/pyo3/Cargo.lock @@ -629,6 +629,7 @@ dependencies = [ "pkcs8", "rand 0.10.2", "reqwest", + "rustls", "rustls-webpki", "serde", "serde_json", diff --git a/src/client/http.rs b/src/client/http.rs index 30590bb0..e5f9ad0b 100644 --- a/src/client/http.rs +++ b/src/client/http.rs @@ -24,7 +24,8 @@ use crate::auth::AuthProvider; use crate::client::retry::{ - calculate_backoff, RequestCategory, RequestType, RetryConfig, RetryStrategy, + calculate_backoff, is_certificate_verification_failure, RequestCategory, RequestType, + RetryConfig, RetryStrategy, }; use crate::kernel_error::{Error, Result}; use crate::klog::{debug, warn}; @@ -828,7 +829,6 @@ impl DatabricksHttpClient { let start_time = Instant::now(); let mut attempts: u32 = 0; - let mut last_error: Option = None; // Clone the request parts we need for retries let method = request.method().clone(); @@ -988,7 +988,6 @@ impl DatabricksHttpClient { )); } - last_error = Some(format!("HTTP {}", status.as_u16())); warn!( "{:?}: HTTP {} (attempt {}/{}), waiting {:.1}s before retry", request_type, @@ -1017,6 +1016,11 @@ impl DatabricksHttpClient { )); } Err(e) => { + let mut causes = super::error_chain(&e) + .map(ToString::to_string) + .collect::>(); + causes.dedup(); + let error_message = causes.join(": "); if strategy.is_retryable_error(&e) && attempts < max_attempts { let elapsed = start_time.elapsed(); let wait = calculate_backoff(config, attempts, None); @@ -1032,17 +1036,16 @@ impl DatabricksHttpClient { "HTTP request failed — retry timeout exceeded after {} attempts ({:.1}s): {}", attempts, elapsed.as_secs_f64(), - last_error.unwrap_or_else(|| e.to_string()) + error_message ))); } - last_error = Some(e.to_string()); warn!( "{:?}: error (attempt {}/{}): {}, waiting {:.1}s before retry", request_type, attempts, max_attempts, - e, + error_message, wait.as_secs_f64() ); sleep(wait).await; @@ -1054,19 +1057,24 @@ impl DatabricksHttpClient { request_type, attempts, start_time.elapsed().as_secs_f64(), - e + error_message ); - return Err(Error::network_error().message(format!( - "HTTP request failed after {} attempts: {}", - attempts, - last_error.unwrap_or_else(|| e.to_string()) - ))); + return Err(Error::network_error() + .with_retryable(!is_certificate_verification_failure(&e)) + .message(format!( + "HTTP request failed after {} attempts: {}", + attempts, error_message + ))); } } } } } +#[cfg(test)] +#[path = "http_tls_tests.rs"] +mod tls_tests; + #[cfg(test)] mod tests { use super::*; @@ -1970,6 +1978,70 @@ lGrv15pBcePj server.await.unwrap(); } + #[tokio::test] + async fn test_non_idempotent_read_timeout_preserves_retryable_flag() { + let server = MockServer::start().await; + Mock::given(method("POST")) + .and(path("/test")) + .respond_with(ResponseTemplate::new(200).set_delay(Duration::from_millis(300))) + .mount(&server) + .await; + let client = test_client_with_http_config( + fast_retry_config(2), + HttpClientConfig { + read_timeout: Duration::from_millis(75), + ..HttpClientConfig::default() + }, + ); + let request = client + .inner() + .post(format!("{}/test", server.uri())) + .build() + .unwrap(); + let error = client + .execute(request, RequestType::ExecuteStatement) + .await + .expect_err("response must time out after the request is sent"); + + assert_eq!(server.received_requests().await.unwrap().len(), 1); + assert!(error.message.contains("after 1 attempts"), "{error}"); + assert!(error.message.contains("timed out"), "{error}"); + assert!( + error.retryable, + "preserve the existing network-error flag: {error}" + ); + } + + #[tokio::test] + async fn test_redirect_failure_preserves_retryable_flag() { + let server = MockServer::start().await; + Mock::given(method("GET")) + .and(path("/test")) + .respond_with( + ResponseTemplate::new(302) + .insert_header("Location", format!("{}/test", server.uri())), + ) + .mount(&server) + .await; + let client = test_client(&server, fast_retry_config(2)); + let request = client + .inner() + .get(format!("{}/test", server.uri())) + .build() + .unwrap(); + let error = client + .execute(request, RequestType::GetStatementStatus) + .await + .expect_err("redirect loop must fail"); + + assert!(error.message.contains("after 1 attempts"), "{error}"); + assert!(error.message.contains("redirect"), "{error}"); + assert!( + error.retryable, + "preserve the existing network-error flag: {error}" + ); + } + #[tokio::test] async fn test_idempotent_request_succeeds_on_retry_after_503() { let mock_server = MockServer::start().await; diff --git a/src/client/http_tls_tests.rs b/src/client/http_tls_tests.rs new file mode 100644 index 00000000..b4b2d8c3 --- /dev/null +++ b/src/client/http_tls_tests.rs @@ -0,0 +1,489 @@ +// 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. + +use super::*; +use rcgen::{BasicConstraints, CertificateParams, IsCa, Issuer, KeyPair}; +use rustls::pki_types::PrivatePkcs8KeyDer; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use tokio::net::TcpListener; +use tokio::sync::oneshot; +use tokio_rustls::TlsAcceptor; + +#[derive(Clone, Copy)] +enum CertificateFailure { + UnknownCa, + SelfSigned, + HostnameMismatch, + DnsHostnameMismatch, + Expired, +} + +fn test_client(config: HttpClientConfig, overall_timeout: Duration) -> DatabricksHttpClient { + let retry = RetryConfig { + max_retries: 2, + min_wait: Duration::from_millis(1), + max_wait: Duration::from_millis(1), + overall_timeout, + ..Default::default() + }; + DatabricksHttpClient::new( + config, + HashMap::from([ + (RequestCategory::Sea, retry.clone()), + (RequestCategory::CloudFetch, retry), + ]), + ) + .unwrap() +} + +async fn download_cloudfetch_chunk( + client: DatabricksHttpClient, + url: String, +) -> Result> { + use crate::client::ChunkLinkFetchResult; + use crate::reader::cloudfetch::{ + ChunkDownloader, ChunkLinkFetcher, StreamingCloudFetchProvider, + }; + use crate::types::cloudfetch::{CloudFetchConfig, CloudFetchLink}; + use crate::types::sea::CompressionCodec; + + #[derive(Debug)] + struct SingleLink(CloudFetchLink); + + #[async_trait::async_trait] + impl ChunkLinkFetcher for SingleLink { + async fn fetch_links(&self, _: i64, _: i64) -> Result { + Ok(ChunkLinkFetchResult { + links: vec![self.0.clone()], + ..ChunkLinkFetchResult::end_of_stream() + }) + } + + async fn refetch_link(&self, _: i64, _: i64) -> Result { + panic!("unexpired signed URL must not be refreshed") + } + + async fn refetch_links_from(&self, _: i64, _: i64) -> Result> { + panic!("unexpired signed URL must not be refreshed") + } + } + + let fetcher = Arc::new(SingleLink(CloudFetchLink { + url, + chunk_index: 0, + row_offset: 0, + row_count: 1, + byte_count: 0, + expiration: chrono::Utc::now() + chrono::Duration::hours(1), + http_headers: HashMap::new(), + next_chunk_index: None, + })); + let downloader = Arc::new(ChunkDownloader::new( + Arc::new(client), + CompressionCodec::None, + 0.1, + )); + let provider = StreamingCloudFetchProvider::new( + CloudFetchConfig { + retry_delay: Duration::from_millis(1), + ..CloudFetchConfig::default() + }, + fetcher, + downloader, + Some(1), + tokio::runtime::Handle::current(), + ); + provider.next_batch().await +} + +async fn assert_certificate_failure(failure: CertificateFailure) { + for request_type in [ + RequestType::CreateSession, + RequestType::ExecuteStatement, + RequestType::CloudFetchDownload, + ] { + 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, "Retry 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 name = match failure { + CertificateFailure::HostnameMismatch | CertificateFailure::DnsHostnameMismatch => { + "wrong-host.invalid" + } + _ => "127.0.0.1", + }; + let mut server_params = CertificateParams::new(vec![name.to_string()]).unwrap(); + if matches!(failure, CertificateFailure::Expired) { + server_params.not_before = rcgen::date_time_ymd(2000, 1, 1); + server_params.not_after = rcgen::date_time_ymd(2001, 1, 1); + } + let server_key = KeyPair::generate().unwrap(); + let server_cert = match failure { + CertificateFailure::SelfSigned => server_params.self_signed(&server_key).unwrap(), + _ => server_params.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 (shutdown, mut stopped) = oneshot::channel(); + let server = tokio::spawn(async move { + let mut attempts = 0; + let mut requests = 0; + loop { + let socket = tokio::select! { + _ = &mut stopped => return (attempts, requests), + accepted = listener.accept() => accepted.unwrap().0, + }; + attempts += 1; + if let Ok(mut stream) = acceptor.accept(socket).await { + let mut buffer = [0; 1024]; + if stream.read(&mut buffer).await.unwrap_or(0) > 0 { + requests += 1; + let _ = stream + .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n") + .await; + } + } + } + }); + + let mut config = HttpClientConfig::default(); + if matches!( + failure, + CertificateFailure::HostnameMismatch + | CertificateFailure::DnsHostnameMismatch + | CertificateFailure::Expired + ) { + config.tls.trusted_certificate_pem = Some(ca_cert.pem().into_bytes()); + } + let mut client = test_client(config, Duration::from_secs(10)); + let host = if matches!(failure, CertificateFailure::DnsHostnameMismatch) { + // Preserve the DNS name in the URL and SNI while dialing loopback. + client.client = reqwest::Client::builder() + .no_proxy() + .add_root_certificate( + reqwest::Certificate::from_pem(ca_cert.pem().as_bytes()).unwrap(), + ) + .resolve("expected-host.invalid", address) + .build() + .unwrap(); + format!("https://expected-host.invalid:{}", address.port()) + } else { + format!("https://{address}") + }; + let result = if matches!(request_type, RequestType::CloudFetchDownload) { + download_cloudfetch_chunk(client, format!("{host}/chunk.arrow")) + .await + .map(|_| ()) + } else { + let request = client + .inner() + .post(format!("{host}/api/2.0/sql/sessions")) + .build() + .unwrap(); + client + .execute_without_auth(request, request_type) + .await + .map(|_| ()) + }; + shutdown.send(()).unwrap(); + let (attempts, requests) = server.await.unwrap(); + let error = result.expect_err("invalid server certificate must be rejected"); + assert_eq!(attempts, 1, "certificate failure must not retry: {error}"); + assert_eq!(requests, 0, "HTTP request must not reach the TLS server"); + assert!(error.message.contains("after 1 attempts"), "{error}"); + assert!( + !error.retryable, + "permanent certificate error must not be retryable: {error}" + ); + + let expected_causes: &[&str] = match failure { + CertificateFailure::UnknownCa => &[ + "unknownissuer", + "unable to get local issuer", + "not trusted", + "untrusted", + "unknown root", + "invalid certificate chain", + ], + CertificateFailure::SelfSigned => &[ + "unknownissuer", + "self-signed", + "self signed", + "not trusted", + "untrusted", + "unknown root", + "invalid certificate chain", + ], + CertificateFailure::HostnameMismatch | CertificateFailure::DnsHostnameMismatch => &[ + "notvalidforname", + "not valid for name", + "ip address mismatch", + "hostname mismatch", + "host name mismatch", + "name does not match", + "name mismatch", + "target principal name is incorrect", + "name in the certificate is invalid", + ], + CertificateFailure::Expired => &["expired"], + }; + let message = error.message.to_ascii_lowercase(); + assert!( + expected_causes.iter().any(|cause| message.contains(cause)), + "expected certificate cause in error message: {error}" + ); + } +} + +#[tokio::test] +async fn unknown_ca_fails_once_with_certificate_cause() { + assert_certificate_failure(CertificateFailure::UnknownCa).await; +} + +#[tokio::test] +async fn self_signed_fails_once_with_certificate_cause() { + assert_certificate_failure(CertificateFailure::SelfSigned).await; +} + +#[tokio::test] +async fn hostname_mismatch_fails_once_with_certificate_cause() { + assert_certificate_failure(CertificateFailure::HostnameMismatch).await; +} + +#[tokio::test] +async fn dns_hostname_mismatch_fails_once_with_certificate_cause() { + assert_certificate_failure(CertificateFailure::DnsHostnameMismatch).await; +} + +#[tokio::test] +async fn expired_certificate_fails_once_with_certificate_cause() { + assert_certificate_failure(CertificateFailure::Expired).await; +} + +#[tokio::test] +async fn tls_handshake_timeout_still_retries() { + for request_type in [RequestType::CreateSession, RequestType::ExecuteStatement] { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let (shutdown, mut stopped) = oneshot::channel(); + let server = tokio::spawn(async move { + let mut sockets = Vec::new(); + loop { + tokio::select! { + _ = &mut stopped => return sockets.len(), + accepted = listener.accept() => sockets.push(accepted.unwrap().0), + } + } + }); + let config = HttpClientConfig { + connect_timeout: Duration::from_millis(100), + ..Default::default() + }; + let client = test_client(config, Duration::from_secs(10)); + let request = client + .inner() + .get(format!("https://{address}/")) + .build() + .unwrap(); + let error = client + .execute_without_auth(request, request_type) + .await + .unwrap_err(); + assert!( + error.retryable, + "handshake timeouts remain retryable: {error}" + ); + shutdown.send(()).unwrap(); + assert_eq!(server.await.unwrap(), 3, "{error}"); + assert!(error.message.contains("after 3 attempts"), "{error}"); + assert!( + error.message.contains("timed out"), + "timeout cause missing: {error}" + ); + } +} + +#[tokio::test] +async fn retry_timeout_preserves_connect_cause() { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + drop(listener); + let client = test_client(HttpClientConfig::default(), Duration::ZERO); + let request = client + .inner() + .get(format!("http://{address}/")) + .build() + .unwrap(); + let error = client + .execute_without_auth(request, RequestType::CreateSession) + .await + .unwrap_err(); + assert!( + error.retryable, + "connection refusal remains retryable: {error}" + ); + assert!( + error + .message + .contains("retry timeout exceeded after 1 attempts"), + "{error}" + ); + assert!( + error.message.to_ascii_lowercase().contains("refused"), + "connect cause missing: {error}" + ); +} + +#[tokio::test] +async fn dns_failure_preserves_retryable_flag_without_http_retry() { + use reqwest::dns::{Name, Resolve, Resolving}; + use std::sync::atomic::{AtomicUsize, Ordering}; + + #[derive(Debug)] + struct DnsFailure { + calls: AtomicUsize, + message: &'static str, + } + + impl Resolve for DnsFailure { + fn resolve(&self, _: Name) -> Resolving { + self.calls.fetch_add(1, Ordering::SeqCst); + let message = self.message; + Box::pin(async move { + Err(Box::new(std::io::Error::other(message)) + as Box) + }) + } + } + + for message in ["nodename nor servname provided, or not known", "NXDOMAIN"] { + for request_type in [RequestType::CreateSession, RequestType::ExecuteStatement] { + let resolver = Arc::new(DnsFailure { + calls: AtomicUsize::new(0), + message, + }); + let mut client = test_client(HttpClientConfig::default(), Duration::from_secs(10)); + client.client = reqwest::Client::builder() + .no_proxy() + .dns_resolver(resolver.clone()) + .build() + .unwrap(); + let request = client + .inner() + .get("http://missing.invalid/") + .build() + .unwrap(); + let error = client + .execute_without_auth(request, request_type) + .await + .unwrap_err(); + assert_eq!(resolver.calls.load(Ordering::SeqCst), 1, "{error}"); + assert!(error.retryable, "preserve the existing DNS flag: {error}"); + assert!(error.message.contains(message), "{error}"); + } + } +} + +#[tokio::test] +async fn cloudfetch_recovers_after_dns_failure() { + use arrow_array::{ArrayRef, Int32Array, RecordBatch}; + use arrow_ipc::writer::StreamWriter; + use reqwest::dns::{Addrs, Name, Resolve, Resolving}; + use std::net::SocketAddr; + use std::sync::atomic::{AtomicUsize, Ordering}; + use wiremock::matchers::{method, path}; + use wiremock::{Mock, MockServer, ResponseTemplate}; + + #[derive(Debug)] + struct FailOnceResolver { + calls: AtomicUsize, + message: &'static str, + address: SocketAddr, + } + + impl Resolve for FailOnceResolver { + fn resolve(&self, _: Name) -> Resolving { + let fail = self.calls.fetch_add(1, Ordering::SeqCst) == 0; + let message = self.message; + let address = self.address; + Box::pin(async move { + if fail { + Err(Box::new(std::io::Error::other(message)) + as Box) + } else { + Ok(Box::new(std::iter::once(address)) as Addrs) + } + }) + } + } + + let expected = + RecordBatch::try_from_iter([("id", Arc::new(Int32Array::from(vec![42])) as ArrayRef)]) + .unwrap(); + let mut ipc = Vec::new(); + { + let mut writer = StreamWriter::try_new(&mut ipc, &expected.schema()).unwrap(); + writer.write(&expected).unwrap(); + writer.finish().unwrap(); + } + + for message in ["nodename nor servname provided, or not known", "NXDOMAIN"] { + let server = MockServer::start().await; + Mock::given(method("GET")) + .and(path("/chunk.arrow")) + .respond_with(ResponseTemplate::new(200).set_body_bytes(ipc.clone())) + .mount(&server) + .await; + let resolver = Arc::new(FailOnceResolver { + calls: AtomicUsize::new(0), + message, + address: *server.address(), + }); + let mut client = test_client(HttpClientConfig::default(), Duration::from_secs(10)); + client.client = reqwest::Client::builder() + .no_proxy() + .dns_resolver(resolver.clone()) + .build() + .unwrap(); + let url = format!( + "http://storage.invalid:{}/chunk.arrow", + server.address().port() + ); + let batch = download_cloudfetch_chunk(client, url) + .await + .expect("CloudFetch must retry after a DNS failure") + .expect("downloaded chunk must yield a batch"); + + assert_eq!(batch, expected, "{message}"); + assert_eq!(resolver.calls.load(Ordering::SeqCst), 2, "{message}"); + assert_eq!(server.received_requests().await.unwrap().len(), 1); + } +} diff --git a/src/client/mod.rs b/src/client/mod.rs index e2f59a71..af553abf 100644 --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -36,6 +36,19 @@ pub mod retry; pub mod sea; pub(crate) mod transport; +fn error_chain<'a>( + error: &'a (dyn std::error::Error + 'static), +) -> impl Iterator { + std::iter::successors(Some(error), |error| { + // io::Error::source() skips its inner error, which can be a rustls error. + error + .downcast_ref::() + .and_then(std::io::Error::get_ref) + .map(|inner| inner as &(dyn std::error::Error + 'static)) + .or_else(|| error.source()) + }) +} + // Public surface — kept stable for advanced wrappers that tune HTTP. pub use http::{DatabricksHttpClient, HttpClientConfig, ProxyConfig}; pub use retry::{ diff --git a/src/client/retry.rs b/src/client/retry.rs index 7b66237b..cdd1c31b 100644 --- a/src/client/retry.rs +++ b/src/client/retry.rs @@ -247,10 +247,10 @@ impl RetryStrategy { /// Whether the given network/client error is retryable. pub fn is_retryable_error(&self, error: &reqwest::Error) -> bool { - // A permanent DNS lookup failure (for example NXDOMAIN) cannot recover - // through retry. Temporary resolver failures remain ordinary connect - // errors and follow the request's idempotency policy below. - if is_permanent_dns_resolution_failure(error) { + // Certificate verification and permanent DNS failures cannot recover + // through retry, even though reqwest reports them as connect errors. + if is_certificate_verification_failure(error) || is_permanent_dns_resolution_failure(error) + { return false; } match self.idempotency { @@ -264,6 +264,129 @@ impl RetryStrategy { } } +pub(crate) fn is_certificate_verification_failure( + error: &(dyn std::error::Error + 'static), +) -> bool { + super::error_chain(error).any(|error| { + #[cfg(feature = "tls-rustls")] + if matches!( + error.downcast_ref::(), + Some(rustls::Error::InvalidCertificate(_) | rustls::Error::NoCertificatesPresented) + ) { + return true; + } + + #[cfg(feature = "tls-native")] + if let Some(error) = error.downcast_ref::() { + #[cfg(target_vendor = "apple")] + if let Some(permanent) = apple_certificate_verification_failure(&format!("{error:?}")) { + return permanent; + } + // Restrict platform-message matching to TLS errors so ordinary + // connect/timeout errors still retry. + return is_native_certificate_verification_failure(&error.to_string()); + } + false + }) +} + +#[cfg(all(feature = "tls-native", any(target_vendor = "apple", test)))] +fn apple_certificate_verification_failure(debug: &str) -> Option { + // native-tls forwards security-framework's Debug, which retains OSStatus + // even when Display contains only a localized message. + let code = debug + .strip_prefix("Error { code: ")? + .split_once([',', '}'])? + .0 + .trim() + .parse::() + .ok()?; + Some(matches!( + code, + -9807 // errSSLXCertChainInvalid + | -9808 // errSSLBadCert + | -9812 // errSSLUnknownRootCert + | -9813 // errSSLNoRootCert + | -9814 // errSSLCertExpired + | -9815 // errSSLCertNotYetValid + | -9843 // errSSLHostNameMismatch + | -25318 // errSecCreateChainFailed + | -67602 // errSecHostNameMismatch + | -67609 // errSecInvalidExtendedKeyUsage + | -67654 // errSecTrustSettingDeny + | -67808 // errSecVerifyFailed + | -67818 // errSecCertificateExpired + | -67819 // errSecCertificateNotValidYet + | -67820 // errSecCertificateRevoked + | -67843 // errSecNotTrusted + )) +} + +#[cfg(feature = "tls-native")] +fn is_native_certificate_verification_failure(message: &str) -> bool { + // native-tls hides SChannel's io::Error, but Display retains the OS code + // even when Windows localizes the message. + if let Some(code) = message + .rsplit_once(" (os error ") + .and_then(|(_, code)| code.strip_suffix(')')) + .and_then(|code| code.parse::().ok()) + { + // Revocation-check availability errors remain retryable. + return matches!( + code as u32, + 0x80090322 // SEC_E_WRONG_PRINCIPAL + | 0x80090325 // SEC_E_UNTRUSTED_ROOT + | 0x80090328 // SEC_E_CERT_EXPIRED + | 0x80092010 // CRYPT_E_REVOKED + | 0x80096004 // TRUST_E_CERT_SIGNATURE + | 0x80096019 // TRUST_E_BASIC_CONSTRAINTS + | 0x800B0101 // CERT_E_EXPIRED + | 0x800B0102 // CERT_E_VALIDITYPERIODNESTING + | 0x800B0103 // CERT_E_ROLE + | 0x800B0104 // CERT_E_PATHLENCONST + | 0x800B0105 // CERT_E_CRITICAL + | 0x800B0106 // CERT_E_PURPOSE + | 0x800B0107 // CERT_E_ISSUERCHAINING + | 0x800B0108 // CERT_E_MALFORMED + | 0x800B0109 // CERT_E_UNTRUSTEDROOT + | 0x800B010A // CERT_E_CHAINING + | 0x800B010C // CERT_E_REVOKED + | 0x800B010D // CERT_E_UNTRUSTEDTESTROOT + | 0x800B010F // CERT_E_CN_NO_MATCH + | 0x800B0110 // CERT_E_WRONG_USAGE + | 0x800B0111 // TRUST_E_EXPLICIT_DISTRUST + | 0x800B0112 // CERT_E_UNTRUSTEDCA + | 0x800B0113 // CERT_E_INVALID_POLICY + | 0x800B0114 // CERT_E_INVALID_NAME + ); + } + + // OpenSSL's X509VerifyResult is hidden; this fallback depends on English + // messages if no platform status code is available. + // Match local verification failures, not peer-sent certificate alerts. + let message = message.to_ascii_lowercase(); + [ + "certificate verify failed", + "hostname mismatch", + "host name mismatch", + "ip address mismatch", + "invalid certificate chain", + "certificate for this server is invalid", + "unknown root certificate", + "root certificate is not trusted", + "certificate was not trusted", + "certificate has expired", + "certificate is not yet valid", + "certificate chain was issued by an authority that is not trusted", + "root certificate which is not trusted", + "untrusted root", + "target principal name is incorrect", + "certificate's cn name does not match", + ] + .iter() + .any(|marker| message.contains(marker)) +} + /// Heuristic: is this network error a permanent DNS lookup failure (the host /// name does not exist), as opposed to a temporary resolver/connect error? /// @@ -367,6 +490,224 @@ fn parse_retry_after(value: &str) -> Option { mod tests { use super::*; + #[cfg(feature = "tls-rustls")] + #[test] + fn certificate_errors_are_detected_inside_io_errors() { + for error in [ + rustls::Error::InvalidCertificate(rustls::CertificateError::UnknownIssuer), + rustls::Error::InvalidCertificate(rustls::CertificateError::NotValidForName), + rustls::Error::InvalidCertificate(rustls::CertificateError::Expired), + rustls::Error::NoCertificatesPresented, + ] { + let error = std::io::Error::other(std::io::Error::other(error)); + assert!(is_certificate_verification_failure(&error)); + } + } + + #[cfg(feature = "tls-rustls")] + #[test] + fn peer_certificate_alerts_are_not_local_verification_failures() { + use rustls::AlertDescription::*; + for alert in [ + BadCertificate, + UnsupportedCertificate, + CertificateRevoked, + CertificateExpired, + CertificateUnknown, + UnknownCA, + CertificateUnobtainable, + BadCertificateStatusResponse, + BadCertificateHashValue, + CertificateRequired, + ] { + let error = std::io::Error::other(rustls::Error::AlertReceived(alert)); + assert!(!is_certificate_verification_failure(&error), "{alert:?}"); + } + } + + #[cfg(feature = "tls-native")] + #[test] + fn apple_certificate_status_codes_are_permanent() { + for debug in [ + "Error { code: -67602, message: \"A host name mismatch has occurred.\" }", + "Error { code: -67602, message: \"Der Hostname stimmt nicht überein.\" }", + "Error { code: -67843, message: \"Certificat non approuvé.\" }", + "Error { code: -67818, message: \"Zertifikat abgelaufen.\" }", + "Error { code: -67819 }", + "Error { code: -67820 }", + "Error { code: -67609 }", + "Error { code: -67654 }", + "Error { code: -67808 }", + "Error { code: -25318 }", + "Error { code: -9807 }", + "Error { code: -9808 }", + "Error { code: -9812 }", + "Error { code: -9813 }", + "Error { code: -9814 }", + "Error { code: -9815 }", + "Error { code: -9843 }", + ] { + assert_eq!( + apple_certificate_verification_failure(debug), + Some(true), + "{debug}" + ); + } + } + + #[cfg(feature = "tls-native")] + #[test] + fn apple_peer_alerts_and_other_errors_are_not_local_verification_failures() { + for debug in [ + "Error { code: -9825, message: \"Peer bad certificate\" }", + "Error { code: -9827 }", // errSSLPeerCertRevoked + "Error { code: -9828 }", // errSSLPeerCertExpired + "Error { code: -9829 }", // errSSLPeerCertUnknown + "Error { code: -9831 }", // errSSLPeerUnknownCA + "Error { code: -9803 }", // errSSLWouldBlock + "Error { code: -9844 }", // errSSLConnectionRefused + "Error { code: -36 }", // errSecIO + "Error { code: -50, message: \"bad parameter\" }", + ] { + assert_eq!( + apple_certificate_verification_failure(debug), + Some(false), + "{debug}" + ); + } + for debug in [ + "A host name mismatch has occurred.", + "Error { message: \"code: -67602\" }", + "Error { code: invalid }", + "Error { code: -67602", + "Os { code: -67602, kind: Other }", + ] { + assert_eq!( + apple_certificate_verification_failure(debug), + None, + "{debug}" + ); + } + } + + #[cfg(feature = "tls-native")] + #[test] + fn native_certificate_verification_messages_are_permanent() { + for message in [ + // OpenSSL. + "error:0A000086:SSL routines:tls_post_process_server_certificate:certificate verify failed (unable to get local issuer certificate)", + "certificate verify failed (self-signed certificate)", + "certificate verify failed (hostname mismatch)", + "certificate verify failed (IP address mismatch)", + // Secure Transport. + "Invalid certificate chain", + "The certificate for this server is invalid.", + "Unknown root certificate", + "The root certificate is not trusted.", + "The certificate was not trusted.", + "The certificate has expired.", + "The certificate is not yet valid.", + "A host name mismatch has occurred.", + // SChannel. + "The certificate chain was issued by an authority that is not trusted. (os error -2146893019)", + "A certificate chain processed, but terminated in a root certificate which is not trusted by the trust provider. (os error -2146762487)", + "Untrusted root certificate", + "The target principal name is incorrect. (os error -2146893022)", + "The certificate's CN name does not match the passed value. (os error -2146762481)", + "CERTIFICATE VERIFY FAILED", + ] { + assert!(is_native_certificate_verification_failure(message), "{message}"); + } + } + + #[cfg(feature = "tls-native")] + #[test] + fn native_peer_alerts_and_other_tls_failures_are_not_local_verification_failures() { + for message in [ + "sslv3 alert bad certificate", + "sslv3 alert unsupported certificate", + "sslv3 alert certificate revoked", + "sslv3 alert certificate expired", + "sslv3 alert certificate unknown", + "tlsv1 alert unknown ca", + "tlsv1 alert certificate unobtainable", + "tlsv1 alert bad certificate status response", + "tlsv1 alert bad certificate hash value", + "tlsv13 alert certificate required", + "unexpected eof while reading", + "wrong version number", + "SSL routines:tls_process_server_certificate:unexpected eof while reading", + "Connection reset by peer", + "TLS-Fehler (os error -2146893018)", // SEC_E_ILLEGAL_MESSAGE + "TLS-Fehler (os error -2146893048)", // SEC_E_INVALID_TOKEN + "Verbindung abgelehnt (os error 10061)", + "Zeitüberschreitung (os error 10060)", + "The revocation function was unable to check revocation for the certificate. (os error -2146762482)", + "The revocation function was unable to check revocation because the revocation server was offline. (os error -2146885613)", + "The certificate's revocation status could not be determined. (os error -2146892973)", + ] { + assert!( + !is_native_certificate_verification_failure(message), + "{message}" + ); + } + } + + #[cfg(feature = "tls-native")] + #[test] + fn schannel_certificate_policy_failures_are_permanent() { + for message in [ + "The certificate is not valid for the requested usage. (os error -2146762480)", + "A certificate was explicitly revoked by its issuer. (os error -2146762484)", + "The signature of the certificate cannot be verified. (os error -2146869244)", + "The certificate is revoked. (os error -2146885616)", + "The basic constraints of the certificate are invalid or missing. (os error -2146869223)", + "Das Zertifikat wurde ausdrücklich als nicht vertrauenswürdig markiert. (os error -2146762479)", + "Une extension critique du certificat est inconnue. (os error -2146762491)", + "The validity periods of the certification chain do not nest correctly. (os error -2146762494)", + "A certificate that can only be used as an end-entity is being used as a CA or vice versa. (os error -2146762493)", + "A path length constraint in the certification chain has been violated. (os error -2146762492)", + "A certificate is being used for a purpose other than the ones specified by its CA. (os error -2146762490)", + "A parent of a given certificate did not issue that child certificate. (os error -2146762489)", + "A certificate is missing or has an empty value for an important field. (os error -2146762488)", + "The certification path terminates with the test root which is not trusted. (os error -2146762483)", + "The certificate has invalid policy. (os error -2146762477)", + "The certificate has an invalid name. (os error -2146762476)", + ] { + assert!(is_native_certificate_verification_failure(message), "{message}"); + } + } + + #[cfg(feature = "tls-native")] + #[test] + fn localized_schannel_certificate_failures_are_permanent() { + for message in [ + "Die Zertifikatskette wurde von einer nicht vertrauenswürdigen Zertifizierungsstelle ausgestellt. (os error -2146893019)", + "Zertifikatsfehler (os error -2146762487)", + "Der Zielprinzipalname ist falsch. (os error -2146893022)", + "Le nom CN du certificat ne correspond pas à la valeur passée. (os error -2146762481)", + "Zertifikat abgelaufen (os error -2146893016)", + "Certificat expiré (os error -2146762495)", + "Zertifikatskette unvollständig (os error -2146762486)", + "Autorité de certification non approuvée (os error -2146762478)", + ] { + assert!(is_native_certificate_verification_failure(message), "{message}"); + } + } + + #[test] + fn ordinary_io_errors_are_not_certificate_failures() { + for error in [ + std::io::Error::from(std::io::ErrorKind::ConnectionRefused), + std::io::Error::from(std::io::ErrorKind::TimedOut), + std::io::Error::from(std::io::ErrorKind::UnexpectedEof), + std::io::Error::other("certificate verify failed"), + std::io::Error::from_raw_os_error(-2146893019), + ] { + assert!(!is_certificate_verification_failure(&error)); + } + } + // --- DNS-resolution detection tests --- #[test] diff --git a/src/kernel_error.rs b/src/kernel_error.rs index 6d08a56e..ecfb7fb2 100644 --- a/src/kernel_error.rs +++ b/src/kernel_error.rs @@ -122,7 +122,8 @@ pub enum ErrorCode { /// Transport-layer failure — DNS resolution, TCP handshake, TLS /// negotiation. Distinct from `Unavailable` (which is server- - /// reported transient). Retryable with backoff. + /// reported transient). Retryable with backoff except for certificate + /// verification failures. NetworkError, /// Server-reported SQL execution error. `sql_state` and @@ -359,7 +360,8 @@ impl Error { Self::empty(ErrorCode::InvalidStatementHandle) } - /// `ErrorCode::NetworkError`. Default `retryable=true`. + /// `ErrorCode::NetworkError`. Defaults to retryable; override with + /// [`Self::with_retryable`] for permanent transport failures. pub fn network_error() -> Self { Self::empty(ErrorCode::NetworkError).with_retryable(true) } diff --git a/src/reader/cloudfetch/streaming_provider.rs b/src/reader/cloudfetch/streaming_provider.rs index 04822874..5fbab8d7 100644 --- a/src/reader/cloudfetch/streaming_provider.rs +++ b/src/reader/cloudfetch/streaming_provider.rs @@ -20,7 +20,7 @@ //! - Memory management via chunk limits //! - Consumer API via RecordBatchReader trait -use crate::kernel_error::{Error, Result}; +use crate::kernel_error::{Error, ErrorCode, Result}; use crate::klog::{debug, error, info, warn}; use crate::reader::cloudfetch::chunk_downloader::ChunkDownloader; use crate::reader::cloudfetch::link_fetcher::ChunkLinkFetcher; @@ -1114,6 +1114,10 @@ impl StreamingCloudFetchProvider { return Ok(batches); } Err(e) => { + // Refreshing a signed URL cannot repair certificate verification failures. + if e.code == ErrorCode::NetworkError && !e.retryable { + return Err(e); + } // Every completed download failure consumes the hard attempt // budget, even when its link became stale while in flight. attempts += 1; @@ -1834,6 +1838,12 @@ mod tests { #[tokio::test] async fn persistent_download_failure_is_bounded_when_links_expire_in_flight() { + for status in [403, 500] { + assert_persistent_download_failure_is_bounded(status).await; + } + } + + async fn assert_persistent_download_failure_is_bounded(status: u16) { use crate::client::retry::{build_retry_configs, RetryConfig}; use crate::client::{DatabricksHttpClient, HttpClientConfig}; use crate::types::cloudfetch::LINK_EXPIRY_BUFFER_SECS; @@ -1848,7 +1858,7 @@ mod tests { let server = MockServer::start().await; Mock::given(method("GET")) .and(path("/chunk-0.arrow")) - .respond_with(ResponseTemplate::new(500).set_delay(RESPONSE_DELAY)) + .respond_with(ResponseTemplate::new(status).set_delay(RESPONSE_DELAY)) .mount(&server) .await; @@ -1933,9 +1943,9 @@ mod tests { .await .expect("persistent failures must exhaust the download attempt budget"); - let error = result.expect_err("persistent HTTP 500 must be terminal"); + let error = result.expect_err("persistent HTTP failure must be terminal"); assert!( - error.message.contains("HTTP 500"), + error.message.contains(&format!("HTTP {status}")), "unexpected error: {error}" ); assert_eq!(