diff --git a/CONNECTION_PARAMETERS.md b/CONNECTION_PARAMETERS.md index 2a11227d..a8b288df 100644 --- a/CONNECTION_PARAMETERS.md +++ b/CONNECTION_PARAMETERS.md @@ -32,6 +32,40 @@ 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 | Folded into the host. | + +A non-default port is rejected with `InvalidArgument` when: + +- the host has userinfo (`user:pw@host`); error text shows `@host`; +- the host is empty, or has a path, query or fragment; +- the host already has an embedded port that is not `1` to `65535`. + +A port already embedded in the host (`host:N` or `[v6]:N`) is kept and wins +over the requested port. The kernel logs a `WARN` when a non-default requested +port differs from it; a requested port equal to the scheme default is treated +as unset, so it never warns. A bare +IPv6 literal is bracketed, so `2001:db8::1` becomes `[2001:db8::1]:port`. 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 bindings validate the port +value at construction or open, 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..e763ad1e 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -11,6 +11,18 @@ changes go in their respective binding's NEXT_CHANGELOG. ### Added +- `ConnectionConfig::with_port(port)` takes a connection port and folds it + into `host` (as `scheme://host:port`), so bindings no longer build the port + into the host string themselves. Port `0` and the scheme default (443 for + `https`, 80 for `http`) change nothing and are not validated. Rejected with + `InvalidArgument`: userinfo in the host (shown as `@host`), an + empty host, a path/query/fragment, and an embedded port outside `1`–`65535`. + An embedded port that is already in the host wins, with a warning if a + non-default requested port differs from it. Bare IPv6 literals are bracketed. +- C ABI `kernel_session_config_set_port(config, port)`. It validates eagerly + against the host set so far, and each later host setter re-checks it. + `host_info.port` in connection telemetry reports the applied port. + ### Changed ### Updated diff --git a/include/databricks_kernel.h b/include/databricks_kernel.h index e167f181..a9d9bd00 100644 --- a/include/databricks_kernel.h +++ b/include/databricks_kernel.h @@ -245,6 +245,22 @@ 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. `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 not be empty. A port already embedded in the host + * (`host:N` or `[v6]:N`) is kept and wins over this one; the kernel logs a + * warning when a non-default port differs from it (the scheme default never + * warns). 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 + * includes credentials. */ +KernelStatusCode kernel_session_config_set_port(KernelSessionConfig* config, + uint16_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..a999f806 100644 --- a/napi/NEXT_CHANGELOG.md +++ b/napi/NEXT_CHANGELOG.md @@ -14,6 +14,14 @@ layout, or npm publishing. Pure-kernel changes go in the root ### Added +- `ConnectionOptions.port` (`port?: number`): an optional connection port. + A non-default port is folded into the host by the kernel. `0` and the scheme + default (443 for `https`, 80 for `http`) change nothing. The host must not + have credentials, a path, a query or a fragment. A port already in the host + wins. A value that is not an integer in `0..=65535` gives the + `InvalidArgument` error. A bad host/port combination also gives + `InvalidArgument`. + ### Changed ### Updated diff --git a/napi/index.d.ts b/napi/index.d.ts index 064f856d..822a2be5 100644 --- a/napi/index.d.ts +++ b/napi/index.d.ts @@ -202,6 +202,15 @@ 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, + * and a 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..362b6479 100644 --- a/napi/src/database.rs +++ b/napi/src/database.rs @@ -34,7 +34,7 @@ use napi::bindgen_prelude::Buffer; type Buffer = Vec; 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 +154,13 @@ 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, + /// and a 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 +472,33 @@ pub struct ConnectionOptions { pub socket_timeout_ms: Option, } +/// Build the kernel [`ConnectionConfig`] from `hostName`, `httpPath` and +/// the optional `port`. The port is validated as a JS number, then folded +/// into the host by the kernel ([`ConnectionConfig::with_port`]). Pure +/// (borrows `options`) so it can be tested without opening a session. +fn build_connection(options: &ConnectionOptions) -> napi::Result { + let port = port_from_js(options.port)?; + ConnectionConfig::from_http_path(options.host_name.clone(), &options.http_path) + .and_then(|connection| connection.with_port(port)) + .map_err(napi_err_from_kernel) +} + +/// Validate the JS `port` option. `undefined` / `null` means unset (`0`). +/// Otherwise the value must be an integer in `0..=65535`. A JS number is +/// read as `f64` so that a fraction, `NaN`, or an infinity is rejected +/// rather than truncated or wrapped (as `u32` would do). +fn port_from_js(port: Option) -> napi::Result { + let Some(value) = port else { + return Ok(0); + }; + if !value.is_finite() || value.fract() != 0.0 || !(0.0..=65535.0).contains(&value) { + return Err(napi_err_from_kernel( + KernelError::invalid_argument().message("port must be an integer between 0 and 65535"), + )); + } + Ok(value as u16) +} + /// 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 +848,9 @@ pub async fn open_session(mut options: ConnectionOptions) -> napi::Result napi::Result>) -> PyResult { + const INVALID: &str = "port must be an int between 0 and 65535"; + let Some(obj) = port else { + return Ok(0); + }; + if obj.is_none() { + return Ok(0); + } + if obj.is_instance_of::() || !obj.is_instance_of::() { + return Err(pyo3::exceptions::PyValueError::new_err(INVALID)); + } + let value: i64 = obj + .extract() + .map_err(|_| pyo3::exceptions::PyValueError::new_err(INVALID))?; + port_from_int(value).ok_or_else(|| pyo3::exceptions::PyValueError::new_err(INVALID)) +} + +/// Range-check an already-extracted Python int into a port (`0..=65535`). +fn port_from_int(value: i64) -> Option { + u16::try_from(value).ok() +} + +/// 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 +319,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. A 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 +400,7 @@ impl Session { host, http_path, *, + port=None, auth_type=None, access_token=None, client_id=None, @@ -416,6 +466,7 @@ impl Session { py: Python<'_>, host: String, http_path: String, + port: Option>, auth_type: Option, access_token: Option, client_id: Option, @@ -478,6 +529,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 +682,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); @@ -762,6 +816,37 @@ mod send_sync_tests { assert_send_sync::(); } + #[test] + fn port_range_check_accepts_0_to_65535_only() { + assert_eq!(port_from_int(0), Some(0)); + assert_eq!(port_from_int(8443), Some(8443)); + assert_eq!(port_from_int(65535), Some(65535)); + for bad in [-1, 65536, i64::MAX, i64::MIN] { + assert_eq!(port_from_int(bad), None, "{bad}"); + } + } + + #[test] + fn connection_config_folds_port_and_keeps_credentials_out_of_errors() { + let folded = connection_config( + "workspace.databricks.com".into(), + "/sql/1.0/warehouses/abc", + 8443, + ) + .expect("fold"); + assert_eq!(folded.host, "https://workspace.databricks.com:8443"); + + // Port 0 is the unset case: the host is exactly what the caller passed. + let unset = + connection_config("https://h".into(), "/sql/1.0/warehouses/abc", 0).expect("unset"); + assert_eq!(unset.host, "https://h"); + + match connection_config("https://u:s3cret@h".into(), "/sql/1.0/warehouses/abc", 8443) { + Ok(_) => panic!("credentials with a port must be rejected"), + Err(err) => assert!(!err.message.contains("s3cret"), "{}", err.message), + } + } + #[test] fn enable_geospatial_support_maps_to_kernel_representation() { assert_eq!( diff --git a/pyo3/tests/test_port.py b/pyo3/tests/test_port.py new file mode 100644 index 00000000..e4af1a9e --- /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 int 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/c_abi/session.rs b/src/c_abi/session.rs index b3365f49..07c68233 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,80 @@ 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`: +/// +/// - `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 userinfo, no path, query or fragment, and no +/// other port. If it already carries a 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 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: u16, +) -> KernelStatusCode { + set_on_config(config, |c| { + 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 +1719,7 @@ fn auth_spec_to_config( fn build_session(config: KernelSessionConfig) -> Result { let KernelSessionConfig { connection, + port, auth, session_conf, geospatial_result_representation, @@ -1679,14 +1755,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 +2209,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("@"), "not redacted: {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..761d32a2 100644 --- a/src/config.rs +++ b/src/config.rs @@ -51,6 +51,7 @@ #![allow(dead_code)] use std::collections::HashMap; +use std::net::Ipv6Addr; use std::path::PathBuf; use std::time::Duration; @@ -80,6 +81,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 +104,7 @@ impl ConnectionConfig { host: normalise_host(host.into()), warehouse_id: warehouse_id.into(), org_id: None, + applied_port: None, } } @@ -127,8 +135,201 @@ 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://authority:port`. A host that already carries a + /// port keeps it, and that port is what the connection uses. The + /// `Err(ErrorCode::InvalidArgument)` cases cover userinfo, an empty + /// host, a path, query or fragment, and an out-of-range embedded port. + /// Error text never includes credentials. + pub fn with_port(mut self, port: u16) -> crate::kernel_error::Result { + let host = host_with_port(&self.host, port)?; + self.applied_port = (port != 0).then(|| effective_port(&host)); + self.host = host; + Ok(self) + } +} + +/// Fold `port` into a normalised `host` (`http` or `https` scheme, as +/// [`normalise_host`] produces). 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 the scheme must be `http` or `https`, and no `@` (userinfo) +/// may appear anywhere in `host`. The authority is the text after +/// `scheme://`, up to the first `/`, `?` or `#`. It must be non-empty, +/// and nothing (no path, query or fragment) may follow it. +/// - An authority that already carries a port (`h:N` or `[v6]:N`) keeps it. +/// `N` must be `1..=65535`. The host is returned unchanged, and a +/// `tracing::warn!` names both ports when `N != port`. A `port` equal to the +/// scheme default returned unchanged under the first rule, so it never warns. +/// - Otherwise a bare IPv6 literal is bracketed and the result is +/// `scheme://authority:port`. +/// +/// Every error is `InvalidArgument`. Its text, and the warning, show the +/// host through [`redact_host`], so credentials never appear in them. +/// +/// 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 { + tracing::warn!( + "connection port {port} ignored: host {} already sets port {embedded_port}, \ + and the host's port is used", + redact_host(host) + ); + } + 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 (scheme, rest) = match host.split_once("://") { + Some((s, rest)) if s.eq_ignore_ascii_case("https") => ("https", rest), + Some((s, rest)) if s.eq_ignore_ascii_case("http") => ("http", rest), + _ => { + return Err(invalid_port( + host, + port, + "the host must use an http or https scheme", + )) + } + }; + let default_port = if scheme == "https" { 443 } else { 80 }; + if port == default_port { + return Ok((host.to_owned(), None)); + } + // Checked before the authority split: a password may contain `/`, `?` + // or `#`, which would otherwise be read as the end of the authority. + if host.contains('@') { + return Err(invalid_port( + host, + port, + "credentials (userinfo) cannot be combined with a port", + )); + } + // `\` ends the authority too: URL parsers treat it as a path separator for http(s), so + // `https://h\path` would otherwise take the port after the path and connect to the default. + let authority_end = rest.find(['/', '?', '#', '\\']).unwrap_or(rest.len()); + let (authority, tail) = rest.split_at(authority_end); + if authority.is_empty() { + return Err(invalid_port(host, port, "a port needs a host")); + } + if !tail.is_empty() { + return Err(invalid_port( + host, + port, + "a port cannot be combined with a host that has a path, query or fragment", + )); + } + let Some((bare_host, embedded)) = split_authority(authority) else { + return Err(invalid_port( + host, + port, + "the host has a malformed port or IPv6 literal", + )); + }; + if bare_host.is_empty() { + return Err(invalid_port(host, port, "a port needs a host")); + } + match embedded { + Some(text) => { + let embedded_port = parse_embedded_port(text).ok_or_else(|| { + invalid_port(host, port, "the port in the host must be 1 to 65535") + })?; + let conflicting = (embedded_port != port).then_some(embedded_port); + Ok((format!("{scheme}://{authority}"), conflicting)) + } + None => Ok((format!("{scheme}://{bare_host}:{port}"), None)), + } +} + +/// Split an authority into its host part and any embedded port text. +/// A bare IPv6 literal (which parses as [`Ipv6Addr`]) is returned bracketed +/// and carries no port. `None` means malformed: an unclosed or empty +/// bracket, junk after `]`, or several colons that are not an IPv6 literal. +fn split_authority(authority: &str) -> Option<(String, Option<&str>)> { + if let Some(after_open) = authority.strip_prefix('[') { + let (inner, after) = after_open.split_once(']')?; + if inner.is_empty() { + return None; + } + let bracketed = format!("[{inner}]"); + return match after { + "" => Some((bracketed, None)), + _ => Some((bracketed, Some(after.strip_prefix(':')?))), + }; + } + if authority.parse::().is_ok() { + return Some((format!("[{authority}]"), None)); + } + match authority.rsplit_once(':') { + Some((h, p)) if !h.contains(':') => Some((h.to_owned(), Some(p))), + Some(_) => None, + None => Some((authority.to_owned(), None)), + } +} + +/// Parse an embedded port written as decimal digits only (no sign, no +/// whitespace). Returns `None` unless the value is `1..=65535`. +fn parse_embedded_port(text: &str) -> Option { + if text.is_empty() || !text.bytes().all(|b| b.is_ascii_digit()) { + return None; + } + text.parse::().ok().filter(|&p| p != 0) +} + +/// Effective port of a host that [`host_with_port`] has accepted: the port +/// in its authority, or the scheme's default when there is none. +fn effective_port(host: &str) -> u16 { + let (scheme, rest) = host.split_once("://").unwrap_or(("https", host)); + let authority = rest.split(['/', '?', '#', '\\']).next().unwrap_or(rest); + // A default port leaves a host with userinfo unvalidated, and the userinfo may contain a `:`, + // so drop everything up to the last `@` before reading the port. + let authority = authority.rsplit_once('@').map_or(authority, |(_, h)| h); + let embedded = split_authority(authority).and_then(|(_, p)| p.and_then(parse_embedded_port)); + embedded.unwrap_or(if scheme.eq_ignore_ascii_case("http") { + 80 + } else { + 443 + }) +} + +/// Redact credentials for error and log text: everything up to the last +/// `@` becomes ``, so `user:p/w@h` shows as `@h`. +/// Splitting at the last `@` (not parsing an authority) is deliberate, +/// because a password may contain `/`, `?` or `#`. +fn redact_host(host: &str) -> String { + match host.rfind('@') { + Some(at) => format!("{}", &host[at..]), + None => host.to_owned(), + } +} + +/// Build the `InvalidArgument` error for a rejected port, with the host +/// redacted. +fn invalid_port(host: &str, port: u16, reason: &str) -> crate::kernel_error::Error { + crate::kernel_error::Error::invalid_argument().message(format!( + "cannot apply connection port {port} to host {}: {reason}", + redact_host(host) + )) } /// Normalise a workspace host: prepend `https://` if no scheme is @@ -136,7 +337,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 +2319,246 @@ 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)] = &[ + // No port, or port 0: unchanged. + ("https://h", 0, "https://h"), + ("http://h:8080", 0, "http://h:8080"), + // The scheme default is unchanged, with no validation at all. + ("https://h", 443, "https://h"), + ("http://h", 80, "http://h"), + ("https://user:pw@h", 443, "https://user:pw@h"), + ("https://h/path?q#f", 443, "https://h/path?q#f"), + // A custom port folds in. + ("https://h", 8443, "https://h:8443"), + ( + "https://workspace.databricks.com", + 8443, + "https://workspace.databricks.com:8443", + ), + // Over http, 443 is not the default, so it folds; 80 is a no-op. + ("http://h", 443, "http://h:443"), + ("http://h", 8080, "http://h:8080"), + ("https://h", 80, "https://h:80"), + // IPv4. + ("https://10.0.0.1", 8443, "https://10.0.0.1:8443"), + ("http://127.0.0.1", 8080, "http://127.0.0.1:8080"), + // Bare IPv6 is bracketed; bracketed IPv6 is kept. + ("https://2001:db8::1", 8443, "https://[2001:db8::1]:8443"), + ("https://::1", 8443, "https://[::1]:8443"), + ("https://[2001:db8::1]", 8443, "https://[2001:db8::1]:8443"), + // Embedded port equal to the requested one: unchanged. + ("https://h:8443", 8443, "https://h:8443"), + // Embedded port differs: the host's port wins (and a warning is logged). + ("https://h:9000", 8443, "https://h:9000"), + ("https://h:443", 8443, "https://h:443"), + ( + "https://[2001:db8::1]:9000", + 8443, + "https://[2001:db8::1]: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() { + let cases: &[(&str, u16)] = &[ + // Empty host. + ("https://", 8443), + ("http://", 8080), + ("https://:8443", 8443), + // Path, query or fragment after the authority. + ("https://h/path", 8443), + ("https://h/", 8443), + ("https://h?x=1", 8443), + ("https://h#frag", 8443), + // `\` is a path separator for http(s) URL parsers. + ("https://h\\path", 8443), + ("http://h\\", 8080), + // Userinfo anywhere in the host. + ("https://user@h", 8443), + ("https://user:pw@h", 8443), + ("https://user:s3cret/pw@h", 8443), + ("https://user:s3cret?pw@h", 8443), + ("https://user:s3cret#pw@h", 8443), + // Embedded port out of range, or not digits. + ("https://h:0", 8443), + ("https://h:65536", 8443), + ("https://h:99999", 8443), + ("https://h:abc", 8443), + ("https://h:", 8443), + ("https://h:+80", 8443), + ("https://[2001:db8::1]:0", 8443), + // Malformed bracket or IPv6 forms. + ("https://[::1", 8443), + ("https://[]:8443", 8443), + ("https://[::1]x", 8443), + ("https://a:b:c", 8443), + // Scheme other than http(s), or no scheme. + ("ftp://h", 8443), + ("h", 8443), + ]; + for &(host, port) in cases { + let err = host_with_port(host, port).unwrap_err(); + assert_eq!(err.code, ErrorCode::InvalidArgument, "host={host}"); + } + } + + #[test] + fn host_with_port_error_text_never_has_credentials() { + for host in [ + "https://user:s3cret@h", + "https://user:s3cret/pw@h", + "https://user:s3cret?pw@h", + "https://user:s3cret#pw@h", + "https://s3cret@h:99999", + ] { + let err = host_with_port(host, 8443).unwrap_err(); + assert_eq!(err.code, ErrorCode::InvalidArgument, "host={host}"); + assert!(!err.message.contains("s3cret"), "leaked: {}", err.message); + assert!(!err.message.contains("pw"), "leaked: {}", err.message); + assert!( + err.message.contains("@"), + "not redacted: {}", + err.message + ); + } + } + + #[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_once_when_embedded_port_differs() { + 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").count(), 1, "{logged}"); + assert!( + logged.contains("8443") && logged.contains("9000"), + "{logged}" + ); + } + + #[test] + fn host_with_port_default_port_never_warns_about_an_embedded_port() { + // The scheme default is treated as unset, so the host's own port is used silently. + let (result, logged) = capture_warnings(|| host_with_port("https://h:9000", 443)); + assert_eq!(result.unwrap(), "https://h:9000"); + assert!(logged.is_empty(), "unexpected log: {logged}"); + } + + #[test] + fn host_with_port_is_silent_when_embedded_port_matches() { + let (result, logged) = capture_warnings(|| host_with_port("https://h:8443", 8443)); + assert_eq!(result.unwrap(), "https://h:8443"); + assert!(logged.is_empty(), "unexpected log: {logged}"); + } + + #[test] + fn with_port_folds_and_records_effective_port() { + let c = ConnectionConfig::new("workspace.databricks.com", "abc") + .with_port(8443) + .expect("fold"); + assert_eq!(c.host, "https://workspace.databricks.com:8443"); + assert_eq!(c.applied_port, Some(8443)); + } + + #[test] + fn with_port_zero_is_a_noop() { + let c = ConnectionConfig::new("https://h", "abc") + .with_port(0) + .expect("noop"); + assert_eq!(c.host, "https://h"); + assert_eq!(c.applied_port, None); + } + + #[test] + fn with_port_default_port_records_it_without_folding() { + let c = ConnectionConfig::new("https://h", "abc") + .with_port(443) + .expect("noop"); + assert_eq!(c.host, "https://h"); + assert_eq!(c.applied_port, Some(443)); + } + + #[test] + fn with_port_default_port_reads_the_host_port_past_userinfo() { + // A default port does not validate the host, so userinfo with a ":" stays; the reported + // port is still the host's own. + let c = ConnectionConfig::new("https://u:pw@h:9000", "abc") + .with_port(443) + .expect("noop"); + assert_eq!(c.host, "https://u:pw@h:9000"); + assert_eq!(c.applied_port, Some(9000)); + } + + #[test] + fn with_port_records_the_embedded_port_that_wins() { + let c = ConnectionConfig::new("https://[2001:db8::1]:9000", "abc") + .with_port(8443) + .expect("keep host port"); + assert_eq!(c.host, "https://[2001:db8::1]:9000"); + assert_eq!(c.applied_port, Some(9000)); + } + + #[test] + fn with_port_rejects_credentials_without_leaking_them() { + let err = ConnectionConfig::new("https://user:s3cret@h", "abc") + .with_port(8443) + .unwrap_err(); + assert_eq!(err.code, ErrorCode::InvalidArgument); + assert!(!err.message.contains("s3cret"), "leaked: {}", err.message); + } + + #[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..92af69b0 100644 --- a/tests/c/session_smoke.c +++ b/tests/c/session_smoke.c @@ -154,6 +154,40 @@ 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"); + + 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 +420,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();