Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions NEXT_CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,9 @@ changes go in their respective binding's NEXT_CHANGELOG.

### Fixed

- Reject non-HTTPS endpoints before connecting when an mTLS client
certificate and private key are configured.

---
*Note: When making changes, please add your change under the appropriate
section with a brief description. At release time, move the entries here
Expand Down
45 changes: 35 additions & 10 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -87,9 +87,10 @@ impl ConnectionConfig {
/// bare warehouse id (no `/sql/1.0/...` prefix).
///
/// `host` is normalised: `https://` is prepended if no scheme is
/// present, and any trailing `/` is stripped. So `"my-workspace.databricks.com"`,
/// `"my-workspace.databricks.com/"`, and
/// `"https://my-workspace.databricks.com"` all produce the same
/// present, an explicitly supplied HTTP(S) scheme is canonicalised
/// case-insensitively, and any trailing `/` is stripped. So
/// `"my-workspace.databricks.com"`, `"my-workspace.databricks.com/"`,
/// and `"HTTPS://my-workspace.databricks.com"` all produce the same
/// canonical `host`.
pub fn new(host: impl Into<String>, warehouse_id: impl Into<String>) -> Self {
Self {
Expand Down Expand Up @@ -131,14 +132,20 @@ impl ConnectionConfig {
}

/// Normalise a workspace host: prepend `https://` if no scheme is
/// present, and strip any trailing `/`. Done eagerly at config
/// construction so the rest of the kernel never has to second-guess
/// the input shape.
/// present, canonicalise an explicit HTTP(S) scheme case-insensitively,
/// and strip any trailing `/`. Other explicit schemes are preserved so
/// later configuration validation can reject them rather than disguising
/// them as part of an HTTPS host.
fn normalise_host(host: String) -> String {
let with_scheme = if host.starts_with("http://") || host.starts_with("https://") {
host
} else {
format!("https://{host}")
let with_scheme = match host.split_once("://") {
Some((scheme, rest)) if scheme.eq_ignore_ascii_case("http") => {
format!("http://{rest}")
}
Some((scheme, rest)) if scheme.eq_ignore_ascii_case("https") => {
format!("https://{rest}")
}
Some(_) => host,
None => format!("https://{host}"),
};
with_scheme.trim_end_matches('/').to_string()
}
Expand Down Expand Up @@ -1004,6 +1011,9 @@ pub struct TlsConfig {
/// together; setting only one is rejected at
/// [`Session::open`](crate::Session::open) with
/// `ErrorCode::InvalidArgument`.
/// When both are set, the connection endpoint must use HTTPS;
/// an explicitly non-HTTPS scheme is rejected before any request
/// is sent.
///
/// **Validation timing differs by backend.** Under `tls-native`,
/// `from_pkcs8_pem` validates the cert/key pair at `Session::open`,
Expand Down Expand Up @@ -2038,6 +2048,21 @@ mod tests {
assert_eq!(c.host, "http://127.0.0.1:8080");
}

#[test]
fn new_normalises_explicit_http_scheme_case() {
let http = ConnectionConfig::new("HTTP://127.0.0.1:8080", "abc");
assert_eq!(http.host, "http://127.0.0.1:8080");

let https = ConnectionConfig::new("HTTPS://workspace.databricks.com", "abc");
assert_eq!(https.host, "https://workspace.databricks.com");
}

#[test]
fn new_preserves_other_explicit_schemes_for_later_validation() {
let c = ConnectionConfig::new("ftp://workspace.databricks.com", "abc");
assert_eq!(c.host, "ftp://workspace.databricks.com");
}

#[test]
fn new_strips_trailing_slash() {
let c = ConnectionConfig::new("https://workspace.databricks.com/", "abc");
Expand Down
112 changes: 112 additions & 0 deletions src/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -263,6 +263,13 @@ impl Session {
))
})?;

// A client certificate has no meaning on a plaintext transport.
// Reject the contradictory configuration before constructing an
// auth provider or issuing the CreateSession request; otherwise
// reqwest silently ignores the identity for `http://` and sends the
// bearer credential in cleartext.
validate_mtls_endpoint_scheme(&config)?;

// Install the tracing subscriber from the caller's LoggingConfig —
// but ONLY when they explicitly configured a filter or a
// destination. This is the direct-Rust counterpart to the C ABI's
Expand Down Expand Up @@ -955,6 +962,33 @@ impl SessionBuilder {

// ─── Internal config translation ─────────────────────────────────────

/// Reject a fully configured mTLS identity on anything except HTTPS.
///
/// Incomplete identities are intentionally left to the HTTP-client
/// validator, which reports which half is missing. Ordinary explicit HTTP
/// endpoints remain supported for non-mTLS test servers.
fn validate_mtls_endpoint_scheme(config: &SessionConfig) -> Result<()> {
if config.tls.client_cert_pem.is_none() || config.tls.client_key_pem.is_none() {
return Ok(());
}

let scheme = config
.connection
.host
.split_once("://")
.map(|(scheme, _)| scheme);
if scheme.is_some_and(|scheme| scheme.eq_ignore_ascii_case("https")) {
return Ok(());
}

let scheme = scheme
.filter(|scheme| !scheme.is_empty())
.unwrap_or("<missing>");
Err(Error::invalid_argument().message(format!(
"mTLS client identity requires an HTTPS endpoint; got scheme '{scheme}'"
)))
}

/// Translate the public [`HttpConfig`] (+ proxy / TLS / org_id) into
/// the internal [`HttpClientConfig`] the HTTP client expects.
///
Expand Down Expand Up @@ -1437,6 +1471,84 @@ async fn build_base_auth_provider(
}
}

#[cfg(test)]
mod mtls_endpoint_tests {
use super::*;

fn config(host: &str, cert: bool, key: bool) -> SessionConfig {
let tls = TlsConfig {
client_cert_pem: cert.then(|| b"test-cert".to_vec()),
client_key_pem: key.then(|| b"test-key".to_vec()),
..TlsConfig::default()
};

SessionConfig {
connection: ConnectionConfig::new(host, "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(),
http: HttpConfig::default(),
proxy: None,
tls,
result: ResultConfig::default(),
logging: LoggingConfig::default(),
telemetry: TelemetryConfig::default(),
transport: None,
}
}

#[test]
fn complete_mtls_identity_accepts_only_https() {
for host in [
"https://workspace.databricks.com",
"HTTPS://workspace.databricks.com",
"workspace.databricks.com",
] {
validate_mtls_endpoint_scheme(&config(host, true, true))
.unwrap_or_else(|error| panic!("{host} should be accepted: {error}"));
}

for host in [
"http://127.0.0.1:8080",
"HTTP://127.0.0.1:8080",
"ftp://workspace.databricks.com",
] {
let error = validate_mtls_endpoint_scheme(&config(host, true, true))
.expect_err("non-HTTPS mTLS endpoint must be rejected");
assert_eq!(error.code, crate::kernel_error::ErrorCode::InvalidArgument);
assert!(error.message.contains("HTTPS"), "{}", error.message);
}
}

#[test]
fn explicit_http_remains_available_without_a_complete_mtls_identity() {
for (cert, key) in [(false, false), (true, false), (false, true)] {
validate_mtls_endpoint_scheme(&config("http://127.0.0.1:8080", cert, key))
.expect("scheme validation must not replace ordinary HTTP or missing-half checks");
}
}

#[tokio::test]
async fn session_open_rejects_http_mtls_before_client_construction() {
for host in ["http://127.0.0.1:1", "HTTP://127.0.0.1:1"] {
let error = Session::open(config(host, true, true))
.await
.expect_err("HTTP mTLS session must fail before dialing");
assert_eq!(error.code, crate::kernel_error::ErrorCode::InvalidArgument);
assert!(error.message.contains("HTTPS"), "{}", error.message);
assert!(
!error.message.contains("Failed to construct HTTP client"),
"scheme validation must run before HTTP client construction: {}",
error.message
);
}
}
}

#[cfg(test)]
mod u2m_default_tests {
use super::*;
Expand Down
Loading