diff --git a/CONNECTION_PARAMETERS.md b/CONNECTION_PARAMETERS.md index 2a11227d..6e29dc0c 100644 --- a/CONNECTION_PARAMETERS.md +++ b/CONNECTION_PARAMETERS.md @@ -32,6 +32,46 @@ warehouse id and org id out of a `/sql/1.0/warehouses/{id}` path). | `warehouse_id` | Warehouse id, e.g. `abc123`. Accepts `/sql/1.0/warehouses/{id}` and legacy `/sql/1.0/endpoints/{id}` forms via `from_http_path`. | **(required)** | | `org_id` | Workspace organization id for multi-tenant routing; sent as the `x-databricks-org-id` header. Auto-populated from the `?o=` query parameter of the HTTP path. | `None` | +### Connection port + +A connection port is an input, not a field: the kernel folds it into `host` +as `scheme://host:port`, and the transport connects there. Set it with +`ConnectionConfig::with_port(port)` in Rust, the pyo3 `port=` keyword, the +napi `port` option, or `kernel_session_config_set_port` in the C ABI. Bindings +no longer build the port into the host string themselves. + +| Port | Effect | +|------|--------| +| `0` (or omitted) | Unset. The host is unchanged. | +| The scheme default (`443` for `https`, `80` for `http`) | Unchanged, with no validation. | +| Any other port | Appended to the host, which otherwise stays as written. | + +The host is parsed with the same URL parser the transport uses. A non-default +port is rejected with `InvalidArgument` when: + +- the host has credentials (`user:pw@host`); +- the host has a path, query or fragment; +- the parser rejects the host: an empty host, a bad embedded port, or an IPv6 + address without brackets (write `[2001:db8::1]`, not `2001:db8::1`). + +Error text never repeats the host, so credentials or tokens in it stay out of +errors and logs. + +A non-default port already in the host (`host:N` or `[v6]:N`) is kept and +wins over the requested port, and the kernel logs a `WARN` when they differ. A +default port written in the host (`host:443`) counts as no port, so the +requested port is used. A requested port equal to the scheme default is +treated as unset, so it never warns. Only `http` and `https` hosts are +accepted. The applied port is reported as `host_info.port` in connection +telemetry. + +The C ABI validates eagerly. A bad host/port combination returns +`InvalidArgument` from whichever of `kernel_session_config_set_port`, +`kernel_session_config_set_warehouse` or `kernel_session_config_set_http_path` +is called second, and the config is unchanged. The port number itself is +checked once, in the kernel (`config::port_from_value`), for every binding, +before any network I/O. + ## `AuthConfig` — authentication (required) An enum; pick one variant. Use the validating constructors diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index 2ebce050..23fe84ce 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -11,6 +11,11 @@ changes go in their respective binding's NEXT_CHANGELOG. ### Added +- A connection port option: `ConnectionConfig::with_port` and the C ABI + `kernel_session_config_set_port` connect to `host:port`, so bindings no longer + build it into the host. A non-default port is rejected with `InvalidArgument` + if the host has credentials, a path, query or fragment. + ### Changed ### Updated diff --git a/include/databricks_kernel.h b/include/databricks_kernel.h index e167f181..32d74033 100644 --- a/include/databricks_kernel.h +++ b/include/databricks_kernel.h @@ -245,6 +245,24 @@ KernelStatusCode kernel_session_config_set_http_path(KernelSessionConfig* config const char* host, const char* http_path); +/* Connection port — optional, may be set before or after the host; last call + * wins. `port` is a signed 64-bit integer so callers pass their own integer + * type as is; a value outside 0..65535 returns KernelStatusCode_InvalidArgument. + * `0` (the default) means unset. The scheme default (443 for https, 80 for + * http) is accepted and changes nothing. Any other port is folded into the + * host at kernel_session_open, so the kernel connects to host:port. + * + * The host must not carry userinfo (`user:pw@host`), a path, a query or a + * fragment, and must be a valid host (an IPv6 address needs brackets). A + * non-default port already in the host (`host:N` or `[v6]:N`) is kept and wins + * over this one, and the kernel logs a warning when they differ; a default + * port written in the host (`host:443`) counts as none. Validation is eager: a + * bad combination returns KernelStatusCode_InvalidArgument from whichever of + * this call or the host setter came second, and leaves the config unchanged. + * Error text never repeats the host. */ +KernelStatusCode kernel_session_config_set_port(KernelSessionConfig* config, + int64_t port); + /* Authentication — call exactly one; the last one wins. */ KernelStatusCode kernel_session_config_set_auth_pat(KernelSessionConfig* config, const char* token); diff --git a/napi/NEXT_CHANGELOG.md b/napi/NEXT_CHANGELOG.md index 8597f31e..ac77df4a 100644 --- a/napi/NEXT_CHANGELOG.md +++ b/napi/NEXT_CHANGELOG.md @@ -14,6 +14,10 @@ layout, or npm publishing. Pure-kernel changes go in the root ### Added +- `ConnectionOptions.port`: an optional connection port. A value outside + `0..=65535`, or a host the kernel can't combine with the port, gives + `InvalidArgument`. + ### Changed ### Updated diff --git a/napi/index.d.ts b/napi/index.d.ts index 064f856d..13729932 100644 --- a/napi/index.d.ts +++ b/napi/index.d.ts @@ -202,6 +202,16 @@ export interface ConnectionOptions { * kernel parses out the warehouse id. */ httpPath: string + /** + * Connection port. Omitted, `0`, or the scheme default (443 for + * `https`, 80 for `http`) changes nothing. Any other port is folded + * into the host by the kernel, so the connection goes to `host:port`. + * The host must not carry credentials, a path, a query or a fragment, + * an IPv6 address needs brackets, and a non-default port already in the + * host wins over this one. A value that is not an integer in + * `0..=65535` is an `InvalidArgument` error. + */ + port?: number /** * Authentication mode. Omitted ⇒ [`AuthMode::Pat`] (back-compat: * existing PAT callers pass only `token`). diff --git a/napi/src/database.rs b/napi/src/database.rs index 4a8fbe3f..02ce1754 100644 --- a/napi/src/database.rs +++ b/napi/src/database.rs @@ -33,8 +33,9 @@ use napi::bindgen_prelude::Buffer; #[cfg(test)] type Buffer = Vec; +use databricks_sql_kernel::config::{port_from_value, PortValue}; use databricks_sql_kernel::{ - AuthConfig, DefaultOpts, DriverSystemConfiguration, Error as KernelError, + AuthConfig, ConnectionConfig, DefaultOpts, DriverSystemConfiguration, Error as KernelError, GeospatialResultRepresentation, HttpConfig, ProxyConfig, ResultConfig, Session, TelemetryConfig, TlsConfig, TokenCacheConfig, }; @@ -154,6 +155,14 @@ pub struct ConnectionOptions { /// JDBC-style HTTP path, e.g. `/sql/1.0/warehouses/abc123`. The /// kernel parses out the warehouse id. pub http_path: String, + /// Connection port. Omitted, `0`, or the scheme default (443 for + /// `https`, 80 for `http`) changes nothing. Any other port is folded + /// into the host by the kernel, so the connection goes to `host:port`. + /// The host must not carry credentials, a path, a query or a fragment, + /// an IPv6 address needs brackets, and a non-default port already in the + /// host wins over this one. A value that is not an integer in + /// `0..=65535` is an `InvalidArgument` error. + pub port: Option, /// Authentication mode. Omitted ⇒ [`AuthMode::Pat`] (back-compat: /// existing PAT callers pass only `token`). pub auth_mode: Option, @@ -465,6 +474,21 @@ pub struct ConnectionOptions { pub socket_timeout_ms: Option, } +/// Build the kernel [`ConnectionConfig`] from `hostName`, `httpPath` and +/// the optional `port`. A JS number is passed to the kernel as a float +/// ([`PortValue::Float`]), so the kernel's [`port_from_value`] rejects a +/// fraction, `NaN` or an infinity instead of truncating it; the kernel then +/// folds the port into the host ([`ConnectionConfig::with_port`]). Pure +/// (borrows `options`) so it can be tested without opening a session. +fn build_connection(options: &ConnectionOptions) -> napi::Result { + port_from_value(options.port.map(PortValue::Float)) + .and_then(|port| { + ConnectionConfig::from_http_path(options.host_name.clone(), &options.http_path)? + .with_port(port) + }) + .map_err(napi_err_from_kernel) +} + /// Map the JS `ConnectionOptions` auth fields onto the kernel /// [`AuthConfig`]. Per-mode required-field validation lives in the /// kernel's validating constructors ([`AuthConfig::pat`] / @@ -814,6 +838,9 @@ pub async fn open_session(mut options: ConnectionOptions) -> napi::Result napi::Result>) -> PyResult { + let value = port.filter(|obj| !obj.is_none()).map(|obj| { + if obj.is_instance_of::() || !obj.is_instance_of::() { + PortValue::Unsupported + } else { + obj.extract::() + .map_or(PortValue::Unsupported, PortValue::Integer) + } + }); + port_from_value(value).map_err(|err| pyo3::exceptions::PyValueError::new_err(err.message)) +} + +/// Build the kernel connection from `host`, `http_path` and the validated +/// port. Port `0` leaves the host unchanged; a bad host/port combination is +/// the kernel's `InvalidArgument`. +fn connection_config( + host: String, + http_path: &str, + port: u16, +) -> Result { + ConnectionConfig::from_http_path(host, http_path)?.with_port(port) +} + fn geospatial_result_representation(enabled: bool) -> GeospatialResultRepresentation { if enabled { GeospatialResultRepresentation::Binary @@ -280,6 +312,16 @@ impl Session { /// fully-qualified (`https://...`). `http_path` is the SQL /// endpoint path. /// + /// `port` is an optional connection port (`int`, `0..=65535`, default + /// `None`). A non-default port is folded into the host by the kernel, + /// so the connection goes to `host:port`. Port `0` and the scheme + /// default (443 for `https`, 80 for `http`) change nothing. The host + /// must not carry credentials, a path, a query, or a fragment, and an + /// IPv6 address needs brackets. A non-default port already in `host` + /// wins over `port`, and the kernel logs a warning when they differ. A + /// bad host/port combination raises `KernelError` (`InvalidArgument`). A + /// value outside `0..=65535`, or a non-int, raises `ValueError`. + /// /// Auth: pass `auth_type` plus the matching credentials. /// /// - `"pat"` (or omit `auth_type` and pass `access_token`): @@ -351,6 +393,7 @@ impl Session { host, http_path, *, + port=None, auth_type=None, access_token=None, client_id=None, @@ -416,6 +459,7 @@ impl Session { py: Python<'_>, host: String, http_path: String, + port: Option>, auth_type: Option, access_token: Option, client_id: Option, @@ -478,6 +522,9 @@ impl Session { telemetry_circuit_breaker_threshold: Option, telemetry_circuit_breaker_timeout_ms: Option, ) -> PyResult { + // Range/type check first: a bad port is a plain argument error and + // never reaches the kernel. + let port = parse_port(port)?; // Resolve auth_type. Explicit `auth_type` always wins. When // omitted, default to "pat" if `access_token` was passed // (back-compat for existing PAT callers). A bare @@ -628,7 +675,7 @@ impl Session { let rt = runtime.clone(); let session = run_kernel!(py, rt, async { let mut builder = KSession::builder() - .http_path(host, http_path) + .connection(connection_config(host, &http_path, port)?) .auth(auth_config); if let Some(tls) = tls_config { builder = builder.tls(tls); diff --git a/pyo3/tests/test_port.py b/pyo3/tests/test_port.py new file mode 100644 index 00000000..ef7c2d62 --- /dev/null +++ b/pyo3/tests/test_port.py @@ -0,0 +1,48 @@ +# 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. + +"""Connection `port` kwarg: argument validation. + +Every case here is rejected before any network I/O, so no workspace is +needed. A valid port is folded into the host by the kernel and exercised +by the live/e2e suites. +""" + +from __future__ import annotations + +import pytest + +import databricks_sql_kernel as k + + +def _open(port, host="x.databricks.com"): + return k.Session( + host=host, + http_path="/sql/1.0/warehouses/abc", + access_token="dapi-test", + port=port, + ) + + +@pytest.mark.parametrize("bad", [-1, 65536, 10**12, True, False, 8443.0, "8443"]) +def test_port_out_of_range_or_non_int_raises_value_error(bad): + with pytest.raises(ValueError, match="port must be an integer between 0 and 65535"): + _open(bad) + + +def test_port_with_credentials_is_rejected_without_leaking_them(): + with pytest.raises(k.KernelError) as excinfo: + _open(8443, host="https://user:s3cret@x.databricks.com") + assert excinfo.value.code == "InvalidArgument", excinfo.value.code + assert "s3cret" not in str(excinfo.value) diff --git a/src/auth/oauth/azure.rs b/src/auth/oauth/azure.rs index 1a111ffa..19874af7 100644 --- a/src/auth/oauth/azure.rs +++ b/src/auth/oauth/azure.rs @@ -52,33 +52,26 @@ const AZURE_APP_IDS_BY_SUFFIX: &[(&str, &str)] = &[ ), ]; -/// Reduce a workspace URL/host to its lowercase host authority (scheme and any +/// Reduce a workspace URL/host to its lowercase host name (scheme, port and any /// path/query/fragment dropped, trailing dot trimmed), so a suffix test can't /// be fooled by the pattern appearing in the scheme or path (e.g. -/// `adb-1.dev.azuredatabricks.net.example.com`). -fn host_authority(host: &str) -> String { - let host = host.to_ascii_lowercase(); - let authority = host - .split_once("://") - .map(|(_, rest)| rest) - .unwrap_or(&host); - authority - .split(['/', '?', '#']) - .next() - .unwrap_or(authority) - .trim_end_matches('.') - .to_string() +/// `adb-1.dev.azuredatabricks.net.example.com`) and still matches a host with +/// a port. +fn host_name(host: &str) -> String { + super::federation::host_of(host) + .map(|name| name.trim_end_matches('.').to_owned()) + .unwrap_or_default() } /// The effective Azure Databricks resource app id for `host` (the resource in /// the M2M `.default` scope). Falls back to [`AZURE_DATABRICKS_APP_ID`] (prod) /// for commercial prod and sovereign hosts. pub(crate) fn effective_app_id(host: &str) -> &'static str { - let authority = host_authority(host); + let name = host_name(host); for (suffix, app_id) in AZURE_APP_IDS_BY_SUFFIX { // Match the host suffix, not a substring: a host that merely embeds the // pattern (e.g. `adb-1.dev.azuredatabricks.net.example.com`) is not dev/staging. - if authority.ends_with(suffix) { + if name.ends_with(suffix) { return app_id; } } @@ -404,6 +397,11 @@ mod tests { effective_app_id("https://adb-1.staging.azuredatabricks.net"), "4a67d088-db5c-48f1-9ff2-0aace800ae68" ); + // A port (e.g. from a custom connection port) does not hide the suffix. + assert_eq!( + effective_app_id("https://adb-1.dev.azuredatabricks.net:8443"), + "62a912ac-b58e-4c1d-89ea-b2dbfc7358fc" + ); // Sovereign / unknown → prod app id fallback. assert_eq!( effective_app_id("https://adb-1.databricks.azure.us"), diff --git a/src/auth/oauth/federation.rs b/src/auth/oauth/federation.rs index a7eed7ba..1aefd07b 100644 --- a/src/auth/oauth/federation.rs +++ b/src/auth/oauth/federation.rs @@ -456,7 +456,7 @@ impl AuthProvider for FederationProvider { /// Extracts the hostname from a URL-ish string, lowercased and without its /// port. Accepts values with or without a scheme and returns `None` if no host /// can be found. -fn host_of(url: &str) -> Option { +pub(super) fn host_of(url: &str) -> Option { let normalized; let url = if url.contains("://") { url diff --git a/src/c_abi/session.rs b/src/c_abi/session.rs index b3365f49..44e1cbb8 100644 --- a/src/c_abi/session.rs +++ b/src/c_abi/session.rs @@ -136,6 +136,11 @@ enum AuthSpec { /// exists nor is needed. pub struct KernelSessionConfig { connection: Option, + /// Connection port set by `kernel_session_config_set_port` (`0` = unset). + /// Folded into the host at open via `ConnectionConfig::with_port`, and + /// checked against the host whenever either side changes, so a bad + /// combination is reported at config time. + port: u16, auth: Option, session_conf: HashMap, /// Optional client-facing representation for GEOMETRY / GEOGRAPHY results. @@ -281,6 +286,7 @@ pub unsafe extern "C" fn kernel_session_config_new( } let config = Box::new(KernelSessionConfig { connection: None, + port: 0, auth: None, session_conf: HashMap::new(), geospatial_result_representation: None, @@ -334,8 +340,10 @@ pub unsafe extern "C" fn kernel_session_config_set_warehouse( warehouse_id: *const c_char, ) -> KernelStatusCode { set_on_config(config, |c| { + let host = required_str(host, "host")?; + check_port_fits_host(&host, c.port)?; c.connection = Some(ConnectionSpec::HostWarehouse { - host: required_str(host, "host")?, + host, warehouse_id: required_str(warehouse_id, "warehouse_id")?, }); Ok(()) @@ -346,7 +354,8 @@ pub unsafe extern "C" fn kernel_session_config_set_warehouse( /// (`/sql/1.0/warehouses/{id}` with an optional `?o={org_id}`). /// Mutually exclusive with [`kernel_session_config_set_warehouse`] — the /// last one called wins. The path is parsed at [`kernel_session_open`] -/// so a malformed path surfaces there as `InvalidArgument`. +/// so a malformed path surfaces there as `InvalidArgument`. A port set with +/// [`kernel_session_config_set_port`] is checked against this host here. /// /// # Safety /// `config` must be a live config handle; `host` / `http_path` must be @@ -358,14 +367,84 @@ pub unsafe extern "C" fn kernel_session_config_set_http_path( http_path: *const c_char, ) -> KernelStatusCode { set_on_config(config, |c| { + let host = required_str(host, "host")?; + check_port_fits_host(&host, c.port)?; c.connection = Some(ConnectionSpec::HttpPath { - host: required_str(host, "host")?, + host, http_path: required_str(http_path, "http_path")?, }); Ok(()) }) } +/// Set the connection port, folded into the workspace host at +/// [`kernel_session_open`]. The rules are those of +/// `ConnectionConfig::with_port`: +/// +/// - `port` is a signed 64-bit integer so a caller can pass its own integer +/// type as is; the kernel rejects a value outside `0..=65535` with +/// `InvalidArgument` (`config::port_from_value`). +/// - `0` means unset (the default). The scheme default (`443` for `https`, +/// `80` for `http`) is accepted and changes nothing. +/// - Any other port is written into the host, so the kernel connects to it. +/// The host must have no credentials and no path, query or fragment. If it +/// already carries a non-default port, that port wins, and the kernel logs +/// a warning when the two differ. +/// +/// Validation is eager. The port is checked against the host set so far, and +/// each later [`kernel_session_config_set_warehouse`] or +/// [`kernel_session_config_set_http_path`] call checks it against its own +/// host. A bad value or combination returns `InvalidArgument` at that call, +/// and the config is left unchanged. The `port` may be set before or after +/// the host. Last call wins, and setting `0` clears a port. +/// +/// # Safety +/// `config` must be a live config handle. +#[no_mangle] +pub unsafe extern "C" fn kernel_session_config_set_port( + config: *mut KernelSessionConfig, + port: i64, +) -> KernelStatusCode { + set_on_config(config, |c| { + let port = crate::config::port_from_value(Some(crate::config::PortValue::Integer(port)))?; + if let Some(spec) = &c.connection { + check_port_fits_host(spec_host(spec), port)?; + } + c.port = port; + Ok(()) + }) +} + +/// Build the kernel [`ConnectionConfig`] from the C-side spec, then fold the +/// connection port into its host (a no-op for port `0`). Runs at +/// `kernel_session_open`, so the transport dials the folded host. +fn connection_config(spec: ConnectionSpec, port: u16) -> Result { + let connection = match spec { + ConnectionSpec::HostWarehouse { host, warehouse_id } => { + ConnectionConfig::new(host, warehouse_id) + } + ConnectionSpec::HttpPath { host, http_path } => { + ConnectionConfig::from_http_path(host, &http_path)? + } + }; + connection.with_port(port) +} + +/// The host a connection spec carries, before normalisation. +fn spec_host(spec: &ConnectionSpec) -> &str { + match spec { + ConnectionSpec::HostWarehouse { host, .. } | ConnectionSpec::HttpPath { host, .. } => host, + } +} + +/// Check that `port` can be folded into `host`, using the kernel's own +/// normalisation and folding rules, without logging. The config-time checks +/// run this; the open-time fold runs the full rules and logs. +fn check_port_fits_host(host: &str, port: u16) -> Result<(), Error> { + let normalised = crate::config::normalise_host(host.to_owned()); + crate::config::fold_host_port(&normalised, port).map(|_| ()) +} + /// Set PAT (personal access token) authentication. Mutually exclusive /// with [`kernel_session_config_set_auth_m2m`] — the last one called /// wins. @@ -1644,6 +1723,7 @@ fn auth_spec_to_config( fn build_session(config: KernelSessionConfig) -> Result { let KernelSessionConfig { connection, + port, auth, session_conf, geospatial_result_representation, @@ -1679,14 +1759,7 @@ fn build_session(config: KernelSessionConfig) -> Result { - ConnectionConfig::new(host, warehouse_id) - } - ConnectionSpec::HttpPath { host, http_path } => { - ConnectionConfig::from_http_path(host, &http_path)? - } - }; + let connection = connection_config(connection, port)?; let auth = auth_spec_to_config( auth, @@ -2140,6 +2213,106 @@ mod tests { } } + #[test] + fn port_is_checked_against_the_host_in_either_order() { + unsafe { + let mut config: *mut KernelSessionConfig = std::ptr::null_mut(); + assert_eq!( + kernel_session_config_new(&mut config), + KernelStatusCode::Success + ); + let wh = CString::new("wh123").unwrap(); + + // Port first: a host with credentials is rejected at set_warehouse, + // the spec is not stored, and the error does not echo the password. + assert_eq!( + kernel_session_config_set_port(config, 8443), + KernelStatusCode::Success + ); + let creds = CString::new("https://user:s3cret@h").unwrap(); + assert_eq!( + kernel_session_config_set_warehouse(config, creds.as_ptr(), wh.as_ptr()), + KernelStatusCode::InvalidArgument + ); + assert!(config.as_ref().unwrap().connection.is_none()); + 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 = std::ffi::CStr::from_ptr(error.message).to_str().unwrap(); + assert!(!message.contains("s3cret"), "password leaked: {message}"); + assert!(message.contains("credentials"), "{message}"); + + // Port set, then a host with a path: rejected at set_http_path. + let path_host = CString::new("https://h/path").unwrap(); + let http_path = CString::new("/sql/1.0/warehouses/abc").unwrap(); + assert_eq!( + kernel_session_config_set_http_path(config, path_host.as_ptr(), http_path.as_ptr()), + KernelStatusCode::InvalidArgument + ); + assert!(config.as_ref().unwrap().connection.is_none()); + assert_eq!(config.as_ref().unwrap().port, 8443); + + // Port cleared: the same host is now accepted, since 0 is a no-op. + assert_eq!( + kernel_session_config_set_port(config, 0), + KernelStatusCode::Success + ); + assert_eq!( + kernel_session_config_set_http_path(config, path_host.as_ptr(), http_path.as_ptr()), + KernelStatusCode::Success + ); + // Setting a port that the stored host cannot take is rejected at + // set_port, and the previous port (0) is kept. + assert_eq!( + kernel_session_config_set_port(config, 8443), + KernelStatusCode::InvalidArgument + ); + assert_eq!(config.as_ref().unwrap().port, 0); + + // The scheme default changes nothing, so it is accepted even for a + // host with credentials. + assert_eq!( + kernel_session_config_set_port(config, 443), + KernelStatusCode::Success + ); + assert_eq!( + kernel_session_config_set_warehouse(config, creds.as_ptr(), wh.as_ptr()), + KernelStatusCode::Success + ); + kernel_session_config_free(config); + } + } + + #[test] + fn connection_config_folds_the_port_for_both_connection_forms() { + let http_path = ConnectionSpec::HttpPath { + host: "workspace.databricks.com".to_string(), + http_path: "/sql/1.0/warehouses/abc".to_string(), + }; + assert_eq!( + connection_config(http_path, 8443).unwrap().host, + "https://workspace.databricks.com:8443" + ); + + let warehouse = ConnectionSpec::HostWarehouse { + host: "https://[2001:db8::1]".to_string(), + warehouse_id: "abc".to_string(), + }; + assert_eq!( + connection_config(warehouse, 8443).unwrap().host, + "https://[2001:db8::1]:8443" + ); + + // Port 0 leaves the host exactly as the spec gave it. + let unset = ConnectionSpec::HostWarehouse { + host: "https://h".to_string(), + warehouse_id: "abc".to_string(), + }; + let c = connection_config(unset, 0).unwrap(); + assert_eq!(c.host, "https://h"); + assert_eq!(c.applied_port, None); + } + #[test] fn m2m_carries_scopes_and_token_endpoint_override() { // The additive setters must reach the built AuthConfig so an Azure SP diff --git a/src/config.rs b/src/config.rs index 9c1eb0a9..f9af2e3f 100644 --- a/src/config.rs +++ b/src/config.rs @@ -80,6 +80,12 @@ pub struct ConnectionConfig { /// parameter when constructing via /// [`ConnectionConfig::from_http_path`]. pub org_id: Option, + + /// The effective port applied by [`ConnectionConfig::with_port`]: the + /// requested port, or the port already embedded in the host when that + /// one wins. `None` when no port was applied. Crate-internal; connection + /// telemetry reports it as `host_info.port`. + pub(crate) applied_port: Option, } impl ConnectionConfig { @@ -97,6 +103,7 @@ impl ConnectionConfig { host: normalise_host(host.into()), warehouse_id: warehouse_id.into(), org_id: None, + applied_port: None, } } @@ -127,8 +134,187 @@ impl ConnectionConfig { host: normalise_host(host.into()), warehouse_id, org_id: parse_org_id(http_path), + applied_port: None, }) } + + /// Fold a connection `port` into [`Self::host`], so the transport + /// connects to it. + /// + /// `port` `0` means unset and is a no-op. A `port` equal to the + /// scheme's default (443 for `https`, 80 for `http`) leaves the host + /// unchanged and validates nothing. Any other port is written into the + /// host as `scheme://host:port`. A host that already carries a + /// non-default port keeps it, and that port is what the connection uses. + /// `Err(ErrorCode::InvalidArgument)` covers credentials, a path, query or + /// fragment, and a host the URL parser rejects (an empty host, a bad + /// port, an unbracketed IPv6 address). Error text never repeats the host. + pub fn with_port(mut self, port: u16) -> crate::kernel_error::Result { + let host = host_with_port(&self.host, port)?; + // Port 0 changes nothing, so it keeps a port an earlier call already applied to the host. + if port != 0 { + self.applied_port = Some(effective_port(&host)); + } + self.host = host; + Ok(self) + } +} + +/// A connection port as a binding received it, before validation. A binding only maps its +/// language's value onto this; [`port_from_value`] holds the rules, so every binding accepts the +/// same ports and reports a bad one with the same message. +#[derive(Debug, Clone, Copy, PartialEq)] +#[non_exhaustive] +pub enum PortValue { + /// An integer, such as a Python `int`. + Integer(i64), + /// A floating-point number, such as a JavaScript `number`. + Float(f64), + /// Any other type, such as a Python `bool` or `str`, or an integer too large for `i64`. + Unsupported, +} + +/// Validate a connection port given to a binding, for [`ConnectionConfig::with_port`]. +/// +/// `None` means unset and gives `0`. An integer must be in `0..=65535`. A float must also be +/// finite and whole, so `8443.5`, `NaN` and infinities are rejected rather than truncated or +/// wrapped. Any other type is rejected. The error is `InvalidArgument`. +pub fn port_from_value(value: Option) -> crate::kernel_error::Result { + let port = match value { + None => return Ok(0), + Some(PortValue::Integer(n)) => u16::try_from(n).ok(), + Some(PortValue::Float(f)) + if f.is_finite() && f.fract() == 0.0 && (0.0..=65535.0).contains(&f) => + { + Some(f as u16) + } + Some(_) => None, + }; + port.ok_or_else(|| { + crate::kernel_error::Error::invalid_argument() + .message("port must be an integer between 0 and 65535") + }) +} + +/// Fold `port` into a normalised `host` (`http` or `https` scheme, as +/// [`normalise_host`] produces), parsing it with the URL parser the transport +/// uses ([`reqwest::Url`]). Rules, in order: +/// +/// - `port == 0`, or `port` equal to the scheme's default (443 for `https`, +/// 80 for `http`): `host` is returned unchanged, with no validation. +/// - Otherwise `host` must be an `http` or `https` URL with no credentials and +/// no path, query or fragment. An IPv6 address must be bracketed (`[::1]`). +/// - A non-default port already in the host wins: the host is kept, and a +/// warning names both ports when they differ. A default port written in the +/// host (`h:443`) counts as no port, as the URL parser drops it. +/// - Otherwise the result is `scheme://host:port`, with the host as written +/// (its case is kept). +/// +/// Every error is `InvalidArgument`. Neither the errors nor the warning repeat +/// the host, so a credential or token in it never reaches error or log text. +/// +/// This is the logging wrapper over [`fold_host_port`], which holds the +/// rules; the config-time check in the C ABI calls `fold_host_port` directly +/// so that it does not log a warning the open-time fold would log again. +pub(crate) fn host_with_port(host: &str, port: u16) -> crate::kernel_error::Result { + let (folded, conflicting_port) = fold_host_port(host, port)?; + if let Some(embedded_port) = conflicting_port { + crate::klog::warn!( + "connection port {port} ignored: the host already sets port {embedded_port}, \ + and the host's port is used" + ); + } + Ok(folded) +} + +/// The rules of [`host_with_port`], without logging. Returns the folded host, +/// and the host's own port when it differs from `port` (the caller warns). +pub(crate) fn fold_host_port( + host: &str, + port: u16, +) -> crate::kernel_error::Result<(String, Option)> { + if port == 0 { + return Ok((host.to_owned(), None)); + } + let (default_port, rest) = match host.split_once("://") { + Some((scheme, rest)) if scheme.eq_ignore_ascii_case("https") => (443, rest), + Some((scheme, rest)) if scheme.eq_ignore_ascii_case("http") => (80, rest), + _ => { + return Err(invalid_port( + port, + "the host must use an http or https scheme", + )) + } + }; + if port == default_port { + return Ok((host.to_owned(), None)); + } + // The parser ignores trailing spaces and control characters, so drop them here too: the + // result is built from the host text and must not carry them. + let host = host.trim_end_matches(|c: char| c <= ' '); + let rest = rest.trim_end_matches(|c: char| c <= ' '); + // Checked before parsing: a password may contain `/`, `?` or `#`, which the + // parser would read as the end of the authority rather than as credentials. + if host.contains('@') { + return Err(invalid_port( + port, + "credentials (userinfo) cannot be combined with a port", + )); + } + // Checked on the raw text: the parser would normalise a path such as `/a/..` away, and it + // reads `\` as a path separator too. A trailing `/` is already stripped by normalise_host. + if rest.contains(['/', '?', '#', '\\']) { + return Err(invalid_port( + port, + "a port cannot be combined with a host that has a path, query or fragment", + )); + } + let url = reqwest::Url::parse(host).map_err(|_| { + invalid_port( + port, + "the host is not a valid host name or IP address (an IPv6 address needs brackets)", + ) + })?; + match url.port() { + Some(0) => Err(invalid_port( + port, + "the port in the host must be 1 to 65535", + )), + Some(embedded) => Ok((host.to_owned(), (embedded != port).then_some(embedded))), + // The port is appended to the host as written; the parser's own output would also + // lowercase and normalise the host. An empty or default port the parser dropped + // (`h:`, `h:443`) is removed first. + None => { + let scheme = &host[..host.len() - rest.len()]; + let authority = match rest.rfind(':') { + Some(i) if !rest[i..].contains(']') => &rest[..i], + _ => rest, + }; + Ok((format!("{scheme}{authority}:{port}"), None)) + } + } +} + +/// Effective port of a host that [`host_with_port`] has accepted: its explicit +/// port, or the scheme's default. +fn effective_port(host: &str) -> u16 { + if let Some(port) = reqwest::Url::parse(host) + .ok() + .and_then(|url| url.port_or_known_default()) + { + return port; + } + match host.split_once("://") { + Some((scheme, _)) if scheme.eq_ignore_ascii_case("http") => 80, + _ => 443, + } +} + +/// The `InvalidArgument` error for a rejected port. The host is not repeated, +/// so credentials or tokens in it never reach the message. +fn invalid_port(port: u16, reason: &str) -> crate::kernel_error::Error { + crate::kernel_error::Error::invalid_argument() + .message(format!("cannot apply connection port {port}: {reason}")) } /// Normalise a workspace host: prepend `https://` if no scheme is @@ -136,7 +322,7 @@ impl ConnectionConfig { /// 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 { +pub(crate) fn normalise_host(host: String) -> String { let with_scheme = match host.split_once("://") { Some((scheme, rest)) if scheme.eq_ignore_ascii_case("http") => { format!("http://{rest}") @@ -2118,6 +2304,204 @@ mod tests { assert_eq!(c.host, "https://workspace.databricks.com"); } + // ─── Connection port folding ─────────────────────────────────── + + use crate::kernel_error::ErrorCode; + + #[test] + fn host_with_port_accepts_and_folds() { + let cases: &[(&str, u16, &str)] = &[ + // Port 0 and the scheme default change nothing and validate nothing. + ("https://h", 0, "https://h"), + ("https://user:pw@h/path?q", 443, "https://user:pw@h/path?q"), + ("http://h", 80, "http://h"), + // A custom port folds in; over http, 443 is not the default. + ("https://h", 8443, "https://h:8443"), + ("http://h", 443, "http://h:443"), + ("https://10.0.0.1", 8443, "https://10.0.0.1:8443"), + ("https://[2001:db8::1]", 8443, "https://[2001:db8::1]:8443"), + // The host is kept as written, case included. + ( + "https://MyWS.Example.com", + 8443, + "https://MyWS.Example.com:8443", + ), + // A non-default port in the host wins; an empty or default one counts as no port. + ("https://H:9000", 8443, "https://H:9000"), + ("https://h:443", 8443, "https://h:8443"), + ("https://h:", 8443, "https://h:8443"), + ( + "https://[2001:db8::1]:443", + 8443, + "https://[2001:db8::1]:8443", + ), + // Trailing whitespace, which the parser ignores, is not carried into the result. + ("https://h ", 8443, "https://h:8443"), + ("https://h:443\t\n", 8443, "https://h:8443"), + ("https://H:9000 ", 8443, "https://H:9000"), + ]; + for &(host, port, want) in cases { + assert_eq!( + host_with_port(host, port).unwrap(), + want, + "host={host} port={port}" + ); + } + } + + #[test] + fn host_with_port_rejects_bad_combinations() { + for host in [ + "https://", + "https://h/path", + "https://h/private/..", + "https://h?x=1", + "https://h#frag", + "https://h\\path", + "https://user:pw@h", + "https://h:0", + "https://h:99999", + "https://::1", + "https://[::1", + "ftp://h", + "h", + ] { + let err = host_with_port(host, 8443).unwrap_err(); + assert_eq!(err.code, ErrorCode::InvalidArgument, "host={host}"); + } + } + + #[test] + fn host_with_port_errors_never_repeat_the_host() { + for host in [ + "https://user:s3cret@h", + "https://user:s3cret?pw@h", + "https://h?access_token=s3cret", + "https://h#s3cret", + "h?token=s3cret&next=https://x", + ] { + let err = host_with_port(host, 8443).unwrap_err(); + assert!(!err.message.contains("s3cret"), "leaked: {}", err.message); + assert!( + err.message + .starts_with("cannot apply connection port 8443: "), + "{}", + err.message + ); + } + } + + #[test] + fn port_from_value_accepts_unset_and_whole_numbers_in_range() { + assert_eq!(port_from_value(None).unwrap(), 0); + for (value, port) in [ + (PortValue::Integer(65535), 65535), + (PortValue::Float(8443.0), 8443), + ] { + assert_eq!(port_from_value(Some(value)).unwrap(), port, "{value:?}"); + } + } + + #[test] + fn port_from_value_rejects_out_of_range_fractions_and_other_types() { + for value in [ + PortValue::Integer(-1), + PortValue::Integer(65536), + PortValue::Float(8443.5), + PortValue::Float(f64::NAN), + PortValue::Float(f64::INFINITY), + PortValue::Unsupported, + ] { + let err = port_from_value(Some(value)).unwrap_err(); + assert_eq!(err.code, ErrorCode::InvalidArgument, "{value:?}"); + assert_eq!(err.message, "port must be an integer between 0 and 65535"); + } + } + + #[derive(Clone, Default)] + struct CapturedLogs(std::sync::Arc>>); + + impl std::io::Write for CapturedLogs { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + self.0.lock().unwrap().extend_from_slice(buf); + Ok(buf.len()) + } + + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } + } + + /// Run `f` under a thread-local WARN-level subscriber and return its + /// result with everything logged meanwhile. + fn capture_warnings(f: impl FnOnce() -> T) -> (T, String) { + let sink = CapturedLogs::default(); + let writer = sink.clone(); + let subscriber = tracing_subscriber::fmt() + .with_writer(move || writer.clone()) + .with_ansi(false) + .with_max_level(tracing::Level::WARN) + .finish(); + let out = tracing::subscriber::with_default(subscriber, f); + let logged = String::from_utf8(sink.0.lock().unwrap().clone()).unwrap(); + (out, logged) + } + + #[test] + fn host_with_port_warns_only_when_the_host_port_overrides_another() { + let (result, logged) = capture_warnings(|| host_with_port("https://h:9000", 8443)); + assert_eq!(result.unwrap(), "https://h:9000"); + assert_eq!( + logged.matches("connection port 8443 ignored").count(), + 1, + "{logged}" + ); + assert!( + logged.contains("9000") && !logged.contains("https://h"), + "{logged}" + ); + // The same port, or the scheme default, is silent. + for port in [9000, 443] { + let (_, logged) = capture_warnings(|| host_with_port("https://h:9000", port)); + assert!(logged.is_empty(), "port={port}: {logged}"); + } + } + + #[test] + fn with_port_records_the_port_the_connection_uses() { + let folded = ConnectionConfig::new("workspace.databricks.com", "abc") + .with_port(8443) + .unwrap(); + assert_eq!(folded.host, "https://workspace.databricks.com:8443"); + assert_eq!(folded.applied_port, Some(8443)); + // A non-default port in the host wins. + let kept = ConnectionConfig::new("https://[2001:db8::1]:9000", "abc") + .with_port(8443) + .unwrap(); + assert_eq!(kept.applied_port, Some(9000)); + // A default port validates nothing; the host's own port is reported past userinfo. + let default = ConnectionConfig::new("https://u:pw@h:9000", "abc") + .with_port(443) + .unwrap(); + assert_eq!(default.host, "https://u:pw@h:9000"); + assert_eq!(default.applied_port, Some(9000)); + // Port 0 keeps a port an earlier call applied. + let again = folded.with_port(0).unwrap(); + assert_eq!(again.host, "https://workspace.databricks.com:8443"); + assert_eq!(again.applied_port, Some(8443)); + } + + #[test] + fn with_port_applies_after_from_http_path() { + let c = ConnectionConfig::from_http_path("h", "/sql/1.0/warehouses/abc123?o=42") + .expect("parse") + .with_port(8443) + .expect("fold"); + assert_eq!(c.host, "https://h:8443"); + assert_eq!(c.warehouse_id, "abc123"); + assert_eq!(c.org_id, Some("42".to_string())); + } + // ─── AuthConfig Debug redaction ──────────────────────────────── #[test] diff --git a/src/telemetry/runtime.rs b/src/telemetry/runtime.rs index 1b8f751b..f20677fa 100644 --- a/src/telemetry/runtime.rs +++ b/src/telemetry/runtime.rs @@ -409,7 +409,8 @@ fn build_connection_params( mode: Some(DriverMode::Sea), host_info: Some(HostDetails { host_url: Some(connection.host.clone()), - port: None, + // Only a port the caller applied explicitly via `with_port` (it may equal the default). + port: connection.applied_port.map(i32::from), proxy_auth_type: None, }), auth_mech: Some(auth_mech(auth)), @@ -509,6 +510,34 @@ mod tests { ); } + #[test] + fn connection_params_report_only_an_applied_port() { + let pat = AuthConfig::Pat { + token: "dapi-token".to_string(), + identity_federation_client_id: None, + }; + + // No port applied: host_info.port stays absent, as before. + let unset = ConnectionConfig::new("https://h", "abc") + .with_port(0) + .expect("noop"); + assert_eq!( + build_connection_params(&unset, &pat) + .host_info + .unwrap() + .port, + None + ); + + // A port applied via with_port is reported as the effective port. + let folded = ConnectionConfig::new("https://h", "abc") + .with_port(8443) + .expect("fold"); + let info = build_connection_params(&folded, &pat).host_info.unwrap(); + assert_eq!(info.port, Some(8443)); + assert_eq!(info.host_url.as_deref(), Some("https://h:8443")); + } + #[test] fn telemetry_config_requires_non_zero_flush_interval() { let default_config = TelemetryConfig::default(); diff --git a/tests/c/session_smoke.c b/tests/c/session_smoke.c index f6b78c2c..e12d724c 100644 --- a/tests/c/session_smoke.c +++ b/tests/c/session_smoke.c @@ -154,6 +154,44 @@ static void test_http_path_and_m2m_setters(void) { kernel_session_config_free(config); } +/* Connection port: set before the host, a host that cannot take a port is + * rejected at set_warehouse (eager), the error never echoes the password, and + * clearing the port (0) makes the same host acceptable again. */ +static void test_port_setter(void) { + KernelSessionConfig* config = NULL; + (void)kernel_session_config_new(&config); + + KernelStatusCode rc = kernel_session_config_set_port(config, 8443); + CHECK(rc == KernelStatusCode_Success, "set_port before host succeeds"); + + rc = kernel_session_config_set_warehouse( + config, "https://user:s3cret@example.databricks.com", "wh123"); + CHECK(rc == KernelStatusCode_InvalidArgument, + "set_warehouse with credentials + port → InvalidArgument"); + + KernelError err; + memset(&err, 0, sizeof(err)); + CHECK(kernel_get_last_error(&err) && err.message != NULL, + "port rejection populates last error"); + CHECK(err.message != NULL && strstr(err.message, "s3cret") == NULL, + "port rejection message does not echo the password"); + + rc = kernel_session_config_set_port(config, 0); + CHECK(rc == KernelStatusCode_Success, "set_port(0) clears the port"); + rc = kernel_session_config_set_warehouse( + config, "https://user:s3cret@example.databricks.com", "wh123"); + CHECK(rc == KernelStatusCode_Success, "set_warehouse with no port succeeds"); + + rc = kernel_session_config_set_port(NULL, 8443); + CHECK(rc == KernelStatusCode_InvalidArgument, "set_port(NULL cfg) → InvalidArgument"); + rc = kernel_session_config_set_port(config, 70000); + CHECK(rc == KernelStatusCode_InvalidArgument, "set_port(70000) → InvalidArgument"); + rc = kernel_session_config_set_port(config, -1); + CHECK(rc == KernelStatusCode_InvalidArgument, "set_port(-1) → InvalidArgument"); + + kernel_session_config_free(config); +} + /* A null required string argument to a setter → InvalidArgument. */ static void test_setter_null_arg_rejected(void) { KernelSessionConfig* config = NULL; @@ -386,6 +424,7 @@ int main(void) { test_open_requires_connection_and_auth(); test_open_unreachable_host_errors(); test_http_path_and_m2m_setters(); + test_port_setter(); test_setter_null_arg_rejected(); test_proxy_and_tls_setters(); test_u2m_and_header_setters();