From f6869900085c9eebafb146d4928c70ee9678c947 Mon Sep 17 00:00:00 2001 From: cat23123 <58714163+cat23123@users.noreply.github.com> Date: Wed, 25 Nov 2026 20:22:53 +0000 Subject: [PATCH 01/11] feat(config): accept a connection port and fold it into the host Bindings each folded a port into the host string themselves, with different rules. The kernel now does it once. ConnectionConfig::with_port applies a port (0 and the scheme default are no-ops and are not validated). Anything else is written as scheme://host:port. It is rejected with InvalidArgument for userinfo, an empty host, a path, query or fragment, or an embedded port outside 1-65535. An embedded port already in the host wins, with a warning when it differs. Error and log text redact credentials. The C ABI gains kernel_session_config_set_port. It validates eagerly against the host set so far, and the host setters re-check it, so a bad combination fails at config time. pyo3 Session gains an optional port kwarg, and napi ConnectionOptions gains an optional port field. Both validate the value type and range before any network I/O. Connection telemetry reports the applied port as host_info.port. Signed-off-by: cat23123 <58714163+cat23123@users.noreply.github.com> Co-authored-by: Isaac --- CONNECTION_PARAMETERS.md | 32 +++ NEXT_CHANGELOG.md | 12 ++ include/databricks_kernel.h | 15 ++ napi/NEXT_CHANGELOG.md | 8 + napi/index.d.ts | 9 + napi/src/database.rs | 98 ++++++++- pyo3/NEXT_CHANGELOG.md | 8 + pyo3/src/session.rs | 89 +++++++- pyo3/tests/test_port.py | 47 ++++ src/c_abi/session.rs | 191 ++++++++++++++++- src/config.rs | 415 +++++++++++++++++++++++++++++++++++- src/telemetry/runtime.rs | 31 ++- tests/c/session_smoke.c | 35 +++ 13 files changed, 968 insertions(+), 22 deletions(-) create mode 100644 pyo3/tests/test_port.py diff --git a/CONNECTION_PARAMETERS.md b/CONNECTION_PARAMETERS.md index 2a11227d..23db547f 100644 --- a/CONNECTION_PARAMETERS.md +++ b/CONNECTION_PARAMETERS.md @@ -32,6 +32,38 @@ 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 the two differ. 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..1dc23532 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 it + differs. 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..0e9af665 100644 --- a/include/databricks_kernel.h +++ b/include/databricks_kernel.h @@ -245,6 +245,21 @@ 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 the two differ. 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..880dffa7 --- /dev/null +++ b/pyo3/tests/test_port.py @@ -0,0 +1,47 @@ +# 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(Exception) as excinfo: + _open(8443, host="https://user:s3cret@x.databricks.com") + 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..2790e912 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,195 @@ 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`. +/// - 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", + )); + } + 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); + 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 +331,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 +2313,224 @@ 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), + // 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_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_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..89ee2188 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 via `with_port` (never a 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(); From b5aac45d54bb4842b7e04dd7fbf2368216b6de4e Mon Sep 17 00:00:00 2001 From: cat23123 <58714163+cat23123@users.noreply.github.com> Date: Wed, 25 Nov 2026 20:35:58 +0000 Subject: [PATCH 02/11] fix(config): treat a backslash as a path and read the port past userinfo URL parsers treat `\` as a path separator for http(s), so `https://h\path` with a port was folded to `https://h\path:8443` and connected to the default port. `\` now ends the authority like `/`, so such a host is rejected with a port. With the default port, a host with userinfo is left unvalidated, and a `:` in the userinfo made the reported telemetry port fall back to 443. The effective port is now read after the last `@`. Also reword the telemetry port comment (an explicitly applied default port is reported), and have the pyo3 credential test require a KernelError with code InvalidArgument instead of any exception. Signed-off-by: cat23123 <58714163+cat23123@users.noreply.github.com> Co-authored-by: Isaac --- pyo3/tests/test_port.py | 3 ++- src/config.rs | 23 +++++++++++++++++++++-- src/telemetry/runtime.rs | 2 +- 3 files changed, 24 insertions(+), 4 deletions(-) diff --git a/pyo3/tests/test_port.py b/pyo3/tests/test_port.py index 880dffa7..e4af1a9e 100644 --- a/pyo3/tests/test_port.py +++ b/pyo3/tests/test_port.py @@ -42,6 +42,7 @@ def test_port_out_of_range_or_non_int_raises_value_error(bad): def test_port_with_credentials_is_rejected_without_leaking_them(): - with pytest.raises(Exception) as excinfo: + 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/config.rs b/src/config.rs index 2790e912..a330312a 100644 --- a/src/config.rs +++ b/src/config.rs @@ -224,7 +224,9 @@ pub(crate) fn fold_host_port( "credentials (userinfo) cannot be combined with a port", )); } - let authority_end = rest.find(['/', '?', '#']).unwrap_or(rest.len()); + // `\` 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")); @@ -297,7 +299,10 @@ fn parse_embedded_port(text: &str) -> Option { /// 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); + 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 @@ -2378,6 +2383,9 @@ mod tests { ("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), @@ -2502,6 +2510,17 @@ mod tests { 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") diff --git a/src/telemetry/runtime.rs b/src/telemetry/runtime.rs index 89ee2188..f20677fa 100644 --- a/src/telemetry/runtime.rs +++ b/src/telemetry/runtime.rs @@ -409,7 +409,7 @@ fn build_connection_params( mode: Some(DriverMode::Sea), host_info: Some(HostDetails { host_url: Some(connection.host.clone()), - // Only a port the caller applied via `with_port` (never a default). + // 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, }), From 22ae6ec250837b38d0e3dc720310d4dcfb81fa98 Mon Sep 17 00:00:00 2001 From: cat23123 <58714163+cat23123@users.noreply.github.com> Date: Wed, 25 Nov 2026 20:46:41 +0000 Subject: [PATCH 03/11] docs(config): say a default connection port never warns A requested port equal to the scheme default is treated as unset, so a port already in the host is used without a warning; the drivers rely on this, since they often pass the default as a plain value. The docs said a warning is logged whenever the two differ. They now say it is logged only for a non-default requested port, and a test pins the silent default case. Signed-off-by: cat23123 <58714163+cat23123@users.noreply.github.com> Co-authored-by: Isaac --- CONNECTION_PARAMETERS.md | 4 +++- NEXT_CHANGELOG.md | 4 ++-- include/databricks_kernel.h | 3 ++- src/config.rs | 11 ++++++++++- 4 files changed, 17 insertions(+), 5 deletions(-) diff --git a/CONNECTION_PARAMETERS.md b/CONNECTION_PARAMETERS.md index 23db547f..a8b288df 100644 --- a/CONNECTION_PARAMETERS.md +++ b/CONNECTION_PARAMETERS.md @@ -53,7 +53,9 @@ A non-default port is rejected with `InvalidArgument` when: - 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 the two differ. A bare +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. diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index 1dc23532..e763ad1e 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -17,8 +17,8 @@ changes go in their respective binding's NEXT_CHANGELOG. `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 it - differs. Bare IPv6 literals are bracketed. + 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. diff --git a/include/databricks_kernel.h b/include/databricks_kernel.h index 0e9af665..a9d9bd00 100644 --- a/include/databricks_kernel.h +++ b/include/databricks_kernel.h @@ -253,7 +253,8 @@ KernelStatusCode kernel_session_config_set_http_path(KernelSessionConfig* config * 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 the two differ. Validation is eager: a bad combination returns + * 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. */ diff --git a/src/config.rs b/src/config.rs index a330312a..761d32a2 100644 --- a/src/config.rs +++ b/src/config.rs @@ -169,7 +169,8 @@ impl ConnectionConfig { /// 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`. +/// `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`. /// @@ -2476,6 +2477,14 @@ mod tests { ); } + #[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)); From 3781473d6d00363afd01c30783a87f1617d62480 Mon Sep 17 00:00:00 2001 From: cat23123 <58714163+cat23123@users.noreply.github.com> Date: Mon, 30 Nov 2026 18:32:20 +0000 Subject: [PATCH 04/11] docs(changelog): shorten the connection port entries Keep what each API adds and how it fails; the folding rules stay in CONNECTION_PARAMETERS.md and the PR description. Signed-off-by: cat23123 <58714163+cat23123@users.noreply.github.com> Co-authored-by: Isaac --- NEXT_CHANGELOG.md | 15 ++++----------- napi/NEXT_CHANGELOG.md | 8 ++------ pyo3/NEXT_CHANGELOG.md | 10 +++------- 3 files changed, 9 insertions(+), 24 deletions(-) diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index e763ad1e..23fe84ce 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -11,17 +11,10 @@ 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. +- 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 diff --git a/napi/NEXT_CHANGELOG.md b/napi/NEXT_CHANGELOG.md index a999f806..ac77df4a 100644 --- a/napi/NEXT_CHANGELOG.md +++ b/napi/NEXT_CHANGELOG.md @@ -14,12 +14,8 @@ 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 +- `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 diff --git a/pyo3/NEXT_CHANGELOG.md b/pyo3/NEXT_CHANGELOG.md index c4004df0..bb50d48b 100644 --- a/pyo3/NEXT_CHANGELOG.md +++ b/pyo3/NEXT_CHANGELOG.md @@ -13,13 +13,9 @@ changes go in the root `NEXT_CHANGELOG.md`. ### Added -- `Session(host, http_path, port=...)`: an optional connection `port` - (`int`, default `None`). 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 outside `0..=65535`, or a non-int, - raises `ValueError`. A bad host/port combination raises the usual - `KernelError` (`InvalidArgument`). +- `Session(..., port=None)`: an optional connection port. A value outside + `0..=65535` raises `ValueError`; a host the kernel can't combine with the port + raises `KernelError` (`InvalidArgument`). ### Changed From aa6a89f0f893ca9f00a7762c7721f8cfefe16191 Mon Sep 17 00:00:00 2001 From: cat23123 <58714163+cat23123@users.noreply.github.com> Date: Mon, 30 Nov 2026 18:47:09 +0000 Subject: [PATCH 05/11] fix(config): redact a host's path, query and fragment in port errors redact_host only replaced userinfo, so a rejected host such as `https://h?access_token=...` put the token in the InvalidArgument text and the port warning. It now shows only the scheme and authority; the rest becomes ``. Also keep applied_port when with_port(0) follows a port that was already applied, so telemetry matches the host the kernel connects to. Signed-off-by: cat23123 <58714163+cat23123@users.noreply.github.com> Co-authored-by: Isaac --- src/config.rs | 67 +++++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 59 insertions(+), 8 deletions(-) diff --git a/src/config.rs b/src/config.rs index 761d32a2..b9ef1009 100644 --- a/src/config.rs +++ b/src/config.rs @@ -152,7 +152,10 @@ impl ConnectionConfig { /// 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)); + // 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) } @@ -312,14 +315,24 @@ fn effective_port(host: &str) -> u16 { }) } -/// 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 `#`. +/// Redact a host for error and log text, showing only its scheme and +/// authority. 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 `#`. A path, query or fragment can carry a token too +/// (`h?access_token=...`), so everything from the first `/`, `?`, `#` or `\` +/// after the authority also becomes ``. fn redact_host(host: &str) -> String { - match host.rfind('@') { - Some(at) => format!("{}", &host[at..]), - None => host.to_owned(), + let (head, tail) = match host.rfind('@') { + Some(at) => ("@".to_owned(), &host[at + 1..]), + None => match host.split_once("://") { + Some((scheme, rest)) => (format!("{scheme}://"), rest), + None => (String::new(), host), + }, + }; + match tail.find(['/', '?', '#', '\\']) { + Some(end) => format!("{head}{}", &tail[..end]), + None => format!("{head}{tail}"), } } @@ -2437,6 +2450,44 @@ mod tests { } } + #[test] + fn host_with_port_error_text_never_has_a_path_query_or_fragment() { + for host in [ + "https://h?access_token=s3cret", + "https://h/sql/x?token=s3cret", + "https://h#s3cret", + "https://h\\s3cret", + "https://u@h/p?s3cret", + ] { + 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("h"), "{}", err.message); + } + } + + #[test] + fn redact_host_keeps_only_scheme_and_authority() { + assert_eq!(redact_host("https://h:8443"), "https://h:8443"); + assert_eq!(redact_host("https://h/x?t=1"), "https://h"); + assert_eq!( + redact_host("https://u:p/w@h:1/x"), + "@h:1" + ); + assert_eq!(redact_host("h?t=1"), "h"); + } + + #[test] + fn with_port_zero_keeps_an_applied_port() { + let c = ConnectionConfig::new("https://h", "abc") + .with_port(8443) + .expect("applied") + .with_port(0) + .expect("noop"); + assert_eq!(c.host, "https://h:8443"); + assert_eq!(c.applied_port, Some(8443)); + } + #[derive(Clone, Default)] struct CapturedLogs(std::sync::Arc>>); From 1be9c1ff39c5ff420b3bcaf026407c24909208ca Mon Sep 17 00:00:00 2001 From: cat23123 <58714163+cat23123@users.noreply.github.com> Date: Mon, 30 Nov 2026 19:31:15 +0000 Subject: [PATCH 06/11] refactor(config): validate binding port values in the kernel pyo3 and napi each range-checked their own port value with their own message. The kernel now owns the rule: a binding maps its language's value onto `config::PortValue` (an integer, a float, or unsupported) and `config::port_from_value` decides, so `8443.5`, `NaN`, out-of-range values and non-numbers are rejected the same way everywhere. pyo3 still raises ValueError like its other argument checks, and napi still gives InvalidArgument; both now carry the kernel's message. The C ABI already takes a `uint16_t`, so it is unchanged. Signed-off-by: cat23123 <58714163+cat23123@users.noreply.github.com> Co-authored-by: Isaac --- napi/src/database.rs | 60 ++++++++++----------------------- pyo3/src/session.rs | 47 +++++++++----------------- pyo3/tests/test_port.py | 2 +- src/config.rs | 75 +++++++++++++++++++++++++++++++++++++++++ 4 files changed, 108 insertions(+), 76 deletions(-) diff --git a/napi/src/database.rs b/napi/src/database.rs index 362b6479..a4d61588 100644 --- a/napi/src/database.rs +++ b/napi/src/database.rs @@ -33,6 +33,7 @@ use napi::bindgen_prelude::Buffer; #[cfg(test)] type Buffer = Vec; +use databricks_sql_kernel::config::{port_from_value, PortValue}; use databricks_sql_kernel::{ AuthConfig, ConnectionConfig, DefaultOpts, DriverSystemConfiguration, Error as KernelError, GeospatialResultRepresentation, HttpConfig, ProxyConfig, ResultConfig, Session, @@ -473,32 +474,20 @@ pub struct ConnectionOptions { } /// 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 +/// 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 { - 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)) + 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) } -/// 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`] / @@ -1410,28 +1399,13 @@ mod tests { } #[test] - fn port_from_js_accepts_unset_and_integers_in_range() { - assert_eq!(port_from_js(None).unwrap(), 0); - assert_eq!(port_from_js(Some(0.0)).unwrap(), 0); - assert_eq!(port_from_js(Some(8443.0)).unwrap(), 8443); - assert_eq!(port_from_js(Some(65535.0)).unwrap(), 65535); - } - - #[test] - fn port_from_js_rejects_non_integers_and_out_of_range() { - // A fraction would truncate and a negative would wrap under a u32 - // read; both, plus NaN and infinities, must be InvalidArgument. - for bad in [ - -1.0, - 65536.0, - 1e10, - 0.5, - 8443.25, - f64::NAN, - f64::INFINITY, - f64::NEG_INFINITY, - ] { - let err = port_from_js(Some(bad)).unwrap_err(); + fn build_connection_rejects_a_bad_port_number_as_invalid_arg() { + // The rules live in the kernel's `port_from_value`; this checks the JS + // number reaches it as a float and the error maps to InvalidArg. + for bad in [-1.0, 65536.0, 8443.5, f64::NAN, f64::INFINITY] { + let mut o = base(); + o.port = Some(bad); + let err = build_connection(&o).unwrap_err(); assert_eq!(err.status, napi::Status::InvalidArg, "port={bad}"); } } diff --git a/pyo3/src/session.rs b/pyo3/src/session.rs index 7fc70a07..c26bdb04 100644 --- a/pyo3/src/session.rs +++ b/pyo3/src/session.rs @@ -25,6 +25,7 @@ use crate::executed_async::ExecutedAsyncStatement; use crate::metadata::Metadata; use crate::runtime::KernelRuntime; use crate::statement::Statement; +use databricks_sql_kernel::config::{port_from_value, PortValue}; use databricks_sql_kernel::{ ConnectionConfig, GeospatialResultRepresentation, Session as KSession, }; @@ -146,29 +147,21 @@ fn build_telemetry_config( Ok(telemetry) } -/// Validate the optional `port` argument. `None` (or Python `None`) means -/// unset, which is `0`. Anything else must be an `int` in `0..=65535`: a -/// non-int (`bool` included) or an out-of-range value raises `ValueError`. +/// Validate the optional `port` argument with the kernel's [`port_from_value`], +/// which holds the rules. Only Python's types are mapped here: `None` is unset, +/// an `int` is an integer, and anything else (including `bool`, an `int` +/// subclass) is unsupported. A bad port raises `ValueError`, like this +/// binding's other argument checks, with the kernel's message. fn parse_port(port: Option>) -> 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() + 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 @@ -816,16 +809,6 @@ 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( diff --git a/pyo3/tests/test_port.py b/pyo3/tests/test_port.py index e4af1a9e..ef7c2d62 100644 --- a/pyo3/tests/test_port.py +++ b/pyo3/tests/test_port.py @@ -37,7 +37,7 @@ def _open(port, host="x.databricks.com"): @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"): + with pytest.raises(ValueError, match="port must be an integer between 0 and 65535"): _open(bad) diff --git a/src/config.rs b/src/config.rs index b9ef1009..30398e17 100644 --- a/src/config.rs +++ b/src/config.rs @@ -161,6 +161,41 @@ impl ConnectionConfig { } } +/// 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)] +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). Rules, in order: /// @@ -2477,6 +2512,46 @@ mod tests { assert_eq!(redact_host("h?t=1"), "h"); } + #[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(0), 0), + (PortValue::Integer(8443), 8443), + (PortValue::Integer(65535), 65535), + (PortValue::Float(0.0), 0), + (PortValue::Float(8443.0), 8443), + (PortValue::Float(65535.0), 65535), + ] { + assert_eq!(port_from_value(Some(value)).unwrap(), port, "{value:?}"); + } + } + + #[test] + fn port_from_value_rejects_out_of_range_fractions_and_other_types() { + // A fraction would truncate and a negative would wrap under a plain cast; all of these, + // plus NaN, infinities and non-numbers, are InvalidArgument with one message. + for value in [ + PortValue::Integer(-1), + PortValue::Integer(65536), + PortValue::Integer(i64::MAX), + PortValue::Integer(i64::MIN), + PortValue::Float(-1.0), + PortValue::Float(65536.0), + PortValue::Float(1e10), + PortValue::Float(0.5), + PortValue::Float(8443.25), + PortValue::Float(f64::NAN), + PortValue::Float(f64::INFINITY), + PortValue::Float(f64::NEG_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"); + } + } + #[test] fn with_port_zero_keeps_an_applied_port() { let c = ConnectionConfig::new("https://h", "abc") From 403ef247a71c3e49297d7cb7fc97211db942d200 Mon Sep 17 00:00:00 2001 From: cat23123 <58714163+cat23123@users.noreply.github.com> Date: Mon, 30 Nov 2026 19:55:26 +0000 Subject: [PATCH 07/11] refactor(config): fold the port with reqwest::Url and take an int64 C ABI port Replace the hand-written authority parsing (split_authority, parse_embedded_port, IPv6 bracketing, redact_host) with the URL parser the transport already uses. Behavior changes for a non-default port: an IPv6 address must be bracketed, and a default port written in the host (`h:443`) counts as no port, so the requested port is used. Errors and the conflicting-port warning no longer repeat the host, so a credential or token in it never reaches error or log text; the warning now goes through klog like other kernel warnings. kernel_session_config_set_port takes an int64_t, so C callers pass their own integer as is and the kernel range-checks it with port_from_value. Docs updated, and redundant unit tests removed. Signed-off-by: cat23123 <58714163+cat23123@users.noreply.github.com> Co-authored-by: Isaac --- CONNECTION_PARAMETERS.md | 32 +-- include/databricks_kernel.h | 22 +- napi/index.d.ts | 5 +- napi/src/database.rs | 15 +- pyo3/src/session.rs | 27 +-- src/c_abi/session.rs | 20 +- src/config.rs | 447 ++++++++++-------------------------- tests/c/session_smoke.c | 4 + 8 files changed, 174 insertions(+), 398 deletions(-) diff --git a/CONNECTION_PARAMETERS.md b/CONNECTION_PARAMETERS.md index a8b288df..546c8b02 100644 --- a/CONNECTION_PARAMETERS.md +++ b/CONNECTION_PARAMETERS.md @@ -46,25 +46,31 @@ no longer build the port into the host string themselves. | 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 is parsed with the same URL parser the transport uses. 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`. +- 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`). -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. +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 bindings validate the port -value at construction or open, before any network I/O. +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) diff --git a/include/databricks_kernel.h b/include/databricks_kernel.h index a9d9bd00..32d74033 100644 --- a/include/databricks_kernel.h +++ b/include/databricks_kernel.h @@ -246,20 +246,22 @@ KernelStatusCode kernel_session_config_set_http_path(KernelSessionConfig* config 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 + * 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 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. */ + * 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, - uint16_t port); + int64_t port); /* Authentication — call exactly one; the last one wins. */ KernelStatusCode kernel_session_config_set_auth_pat(KernelSessionConfig* config, diff --git a/napi/index.d.ts b/napi/index.d.ts index 822a2be5..13729932 100644 --- a/napi/index.d.ts +++ b/napi/index.d.ts @@ -207,8 +207,9 @@ export interface ConnectionOptions { * `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. + * 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 /** diff --git a/napi/src/database.rs b/napi/src/database.rs index a4d61588..02ce1754 100644 --- a/napi/src/database.rs +++ b/napi/src/database.rs @@ -159,8 +159,9 @@ pub struct ConnectionOptions { /// `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. + /// 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`). @@ -1422,16 +1423,6 @@ mod tests { assert_eq!(c.warehouse_id, "abc"); } - #[test] - fn build_connection_rejects_credentials_with_a_port_without_leaking_them() { - let mut o = base(); - o.host_name = "https://u:s3cret@adb-1.azuredatabricks.net".to_owned(); - o.port = Some(8443.0); - let err = build_connection(&o).unwrap_err(); - assert_eq!(err.status, napi::Status::InvalidArg); - assert!(!err.reason.contains("s3cret"), "leaked: {}", err.reason); - } - #[test] fn tls_hostname_check_can_be_disabled_independently() { // Chain validation stays ON; only the hostname check is skipped. diff --git a/pyo3/src/session.rs b/pyo3/src/session.rs index c26bdb04..8996d446 100644 --- a/pyo3/src/session.rs +++ b/pyo3/src/session.rs @@ -316,9 +316,9 @@ impl Session { /// `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` + /// 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`. /// @@ -809,27 +809,6 @@ mod send_sync_tests { assert_send_sync::(); } - #[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/src/c_abi/session.rs b/src/c_abi/session.rs index 07c68233..44e1cbb8 100644 --- a/src/c_abi/session.rs +++ b/src/c_abi/session.rs @@ -381,28 +381,32 @@ pub unsafe extern "C" fn kernel_session_config_set_http_path( /// [`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 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. +/// 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 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. +/// 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: u16, + 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)?; } @@ -2236,7 +2240,7 @@ mod tests { 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}"); + 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(); diff --git a/src/config.rs b/src/config.rs index 30398e17..3e38f825 100644 --- a/src/config.rs +++ b/src/config.rs @@ -51,7 +51,6 @@ #![allow(dead_code)] use std::collections::HashMap; -use std::net::Ipv6Addr; use std::path::PathBuf; use std::time::Duration; @@ -145,11 +144,11 @@ impl ConnectionConfig { /// `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. + /// 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. @@ -197,23 +196,20 @@ pub fn port_from_value(value: Option) -> crate::kernel_error::Result< } /// Fold `port` into a normalised `host` (`http` or `https` scheme, as -/// [`normalise_host`] produces). Rules, in order: +/// [`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 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`. +/// - 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`. /// -/// Every error is `InvalidArgument`. Its text, and the warning, show the -/// host through [`redact_host`], so credentials never appear in them. +/// 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 @@ -221,10 +217,9 @@ pub fn port_from_value(value: Option) -> crate::kernel_error::Result< 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) + crate::klog::warn!( + "connection port {port} ignored: the host already sets port {embedded_port}, \ + and the host's port is used" ); } Ok(folded) @@ -239,145 +234,76 @@ pub(crate) fn fold_host_port( 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), + let default_port = match host.split_once("://") { + Some((scheme, _)) if scheme.eq_ignore_ascii_case("https") => 443, + Some((scheme, _)) if scheme.eq_ignore_ascii_case("http") => 80, _ => { 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. + // 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( - 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() { + let mut 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)", + ) + })?; + if url.path() != "/" || url.query().is_some() || url.fragment().is_some() { 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)) + let conflicting = match url.port() { + Some(0) => { + return Err(invalid_port( + port, + "the port in the host must be 1 to 65535", + )) } - 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; + Some(embedded) => (embedded != port).then_some(embedded), + None => { + url.set_port(Some(port)) + .map_err(|()| invalid_port(port, "the host cannot take a port"))?; + 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) + }; + Ok((url.origin().ascii_serialization(), conflicting)) } -/// 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. +/// 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 { - 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 a host for error and log text, showing only its scheme and -/// authority. 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 `#`. A path, query or fragment can carry a token too -/// (`h?access_token=...`), so everything from the first `/`, `?`, `#` or `\` -/// after the authority also becomes ``. -fn redact_host(host: &str) -> String { - let (head, tail) = match host.rfind('@') { - Some(at) => ("@".to_owned(), &host[at + 1..]), - None => match host.split_once("://") { - Some((scheme, rest)) => (format!("{scheme}://"), rest), - None => (String::new(), host), - }, - }; - match tail.find(['/', '?', '#', '\\']) { - Some(end) => format!("{head}{}", &tail[..end]), - None => format!("{head}{tail}"), + 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, } } -/// 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) - )) +/// 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 @@ -2374,42 +2300,18 @@ mod tests { #[test] fn host_with_port_accepts_and_folds() { let cases: &[(&str, u16, &str)] = &[ - // No port, or port 0: unchanged. + // Port 0 and the scheme default change nothing and validate nothing. ("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"), + ("https://user:pw@h/path?q", 443, "https://user:pw@h/path?q"), ("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. + // A custom port folds in; over http, 443 is not the default. ("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). + // A non-default port in the host wins; a default one counts as no port. ("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", - ), + ("https://h:443", 8443, "https://h:8443"), ]; for &(host, port, want) in cases { assert_eq!( @@ -2422,106 +2324,51 @@ mod tests { #[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", + "https://", + "https://h/path", + "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}"); - assert!(!err.message.contains("s3cret"), "leaked: {}", err.message); - assert!(!err.message.contains("pw"), "leaked: {}", err.message); - assert!( - err.message.contains("@"), - "not redacted: {}", - err.message - ); } } #[test] - fn host_with_port_error_text_never_has_a_path_query_or_fragment() { + 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/sql/x?token=s3cret", "https://h#s3cret", - "https://h\\s3cret", - "https://u@h/p?s3cret", + "h?token=s3cret&next=https://x", ] { 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("h"), "{}", err.message); + assert!( + err.message + .starts_with("cannot apply connection port 8443: "), + "{}", + err.message + ); } } - #[test] - fn redact_host_keeps_only_scheme_and_authority() { - assert_eq!(redact_host("https://h:8443"), "https://h:8443"); - assert_eq!(redact_host("https://h/x?t=1"), "https://h"); - assert_eq!( - redact_host("https://u:p/w@h:1/x"), - "@h:1" - ); - assert_eq!(redact_host("h?t=1"), "h"); - } - #[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(0), 0), - (PortValue::Integer(8443), 8443), (PortValue::Integer(65535), 65535), - (PortValue::Float(0.0), 0), (PortValue::Float(8443.0), 8443), - (PortValue::Float(65535.0), 65535), ] { assert_eq!(port_from_value(Some(value)).unwrap(), port, "{value:?}"); } @@ -2529,21 +2376,12 @@ mod tests { #[test] fn port_from_value_rejects_out_of_range_fractions_and_other_types() { - // A fraction would truncate and a negative would wrap under a plain cast; all of these, - // plus NaN, infinities and non-numbers, are InvalidArgument with one message. for value in [ PortValue::Integer(-1), PortValue::Integer(65536), - PortValue::Integer(i64::MAX), - PortValue::Integer(i64::MIN), - PortValue::Float(-1.0), - PortValue::Float(65536.0), - PortValue::Float(1e10), - PortValue::Float(0.5), - PortValue::Float(8443.25), + PortValue::Float(8443.5), PortValue::Float(f64::NAN), PortValue::Float(f64::INFINITY), - PortValue::Float(f64::NEG_INFINITY), PortValue::Unsupported, ] { let err = port_from_value(Some(value)).unwrap_err(); @@ -2552,17 +2390,6 @@ mod tests { } } - #[test] - fn with_port_zero_keeps_an_applied_port() { - let c = ConnectionConfig::new("https://h", "abc") - .with_port(8443) - .expect("applied") - .with_port(0) - .expect("noop"); - assert_eq!(c.host, "https://h:8443"); - assert_eq!(c.applied_port, Some(8443)); - } - #[derive(Clone, Default)] struct CapturedLogs(std::sync::Arc>>); @@ -2593,85 +2420,47 @@ mod tests { } #[test] - fn host_with_port_warns_once_when_embedded_port_differs() { + 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").count(), 1, "{logged}"); + assert_eq!( + logged.matches("connection port 8443 ignored").count(), + 1, + "{logged}" + ); assert!( - logged.contains("8443") && logged.contains("9000"), + 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 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") + fn with_port_records_the_port_the_connection_uses() { + let folded = ConnectionConfig::new("workspace.databricks.com", "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") + .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_err(); - assert_eq!(err.code, ErrorCode::InvalidArgument); - assert!(!err.message.contains("s3cret"), "leaked: {}", err.message); + .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] diff --git a/tests/c/session_smoke.c b/tests/c/session_smoke.c index 92af69b0..e12d724c 100644 --- a/tests/c/session_smoke.c +++ b/tests/c/session_smoke.c @@ -184,6 +184,10 @@ static void test_port_setter(void) { 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); } From 7e76a603fd4e3ce74e90e6c578e86bc75ac025eb Mon Sep 17 00:00:00 2001 From: cat23123 <58714163+cat23123@users.noreply.github.com> Date: Mon, 30 Nov 2026 20:07:55 +0000 Subject: [PATCH 08/11] fix(config): reject any path in a host given a port, before URL normalisation The path check ran on the parsed URL, which normalises dot segments, so `https://h/private/..` passed with a custom port and lost its path. The check now runs on the raw text after `scheme://`: any `/`, `?`, `#` or `\` is a path, query or fragment. Also mark `PortValue` `#[non_exhaustive]` and re-wrap the pyo3 `Session` docstring. Signed-off-by: cat23123 <58714163+cat23123@users.noreply.github.com> Co-authored-by: Isaac --- pyo3/src/session.rs | 6 +++--- src/config.rs | 22 +++++++++++++--------- 2 files changed, 16 insertions(+), 12 deletions(-) diff --git a/pyo3/src/session.rs b/pyo3/src/session.rs index 8996d446..a999eb23 100644 --- a/pyo3/src/session.rs +++ b/pyo3/src/session.rs @@ -318,9 +318,9 @@ impl Session { /// 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`. + /// 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. /// diff --git a/src/config.rs b/src/config.rs index 3e38f825..fc323a23 100644 --- a/src/config.rs +++ b/src/config.rs @@ -164,6 +164,7 @@ impl ConnectionConfig { /// 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), @@ -234,9 +235,9 @@ pub(crate) fn fold_host_port( if port == 0 { return Ok((host.to_owned(), None)); } - let default_port = match host.split_once("://") { - Some((scheme, _)) if scheme.eq_ignore_ascii_case("https") => 443, - Some((scheme, _)) if scheme.eq_ignore_ascii_case("http") => 80, + 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, @@ -255,18 +256,20 @@ pub(crate) fn fold_host_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 mut 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)", ) })?; - if url.path() != "/" || url.query().is_some() || url.fragment().is_some() { - return Err(invalid_port( - port, - "a port cannot be combined with a host that has a path, query or fragment", - )); - } let conflicting = match url.port() { Some(0) => { return Err(invalid_port( @@ -2327,6 +2330,7 @@ mod tests { for host in [ "https://", "https://h/path", + "https://h/private/..", "https://h?x=1", "https://h#frag", "https://h\\path", From da0d57c95651eb7907cd2b9a5ab304f2b7ae5842 Mon Sep 17 00:00:00 2001 From: cat23123 <58714163+cat23123@users.noreply.github.com> Date: Mon, 30 Nov 2026 21:35:39 +0000 Subject: [PATCH 09/11] fix(config): keep the host as written when folding a port; match Azure dev hosts with a port Folding a port no longer lowercases or normalises the host: the port is appended to the host as written, and a host with its own non-default port is returned unchanged. This keeps the U2M token cache key the same as the drivers' own folding produced. The Azure dev/staging app id lookup now strips the port before the suffix match, so `https://adb-1.dev.azuredatabricks.net:8443` gets the dev scope. Signed-off-by: cat23123 <58714163+cat23123@users.noreply.github.com> Co-authored-by: Isaac --- CONNECTION_PARAMETERS.md | 2 +- src/auth/oauth/azure.rs | 30 ++++++++++------------ src/auth/oauth/federation.rs | 2 +- src/config.rs | 50 ++++++++++++++++++++++++------------ 4 files changed, 49 insertions(+), 35 deletions(-) diff --git a/CONNECTION_PARAMETERS.md b/CONNECTION_PARAMETERS.md index 546c8b02..6e29dc0c 100644 --- a/CONNECTION_PARAMETERS.md +++ b/CONNECTION_PARAMETERS.md @@ -44,7 +44,7 @@ no longer build the port into the host string themselves. |------|--------| | `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. | +| 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: 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/config.rs b/src/config.rs index fc323a23..cd60b196 100644 --- a/src/config.rs +++ b/src/config.rs @@ -207,7 +207,8 @@ pub fn port_from_value(value: Option) -> crate::kernel_error::Result< /// - 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`. +/// - 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. @@ -264,27 +265,30 @@ pub(crate) fn fold_host_port( "a port cannot be combined with a host that has a path, query or fragment", )); } - let mut url = reqwest::Url::parse(host).map_err(|_| { + 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)", ) })?; - let conflicting = match url.port() { - Some(0) => { - return Err(invalid_port( - port, - "the port in the host must be 1 to 65535", - )) - } - Some(embedded) => (embedded != port).then_some(embedded), + 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 => { - url.set_port(Some(port)) - .map_err(|()| invalid_port(port, "the host cannot take a port"))?; - None + let authority = match rest.rfind(':') { + Some(i) if !rest[i..].contains(']') => &rest[..i], + _ => rest, + }; + let scheme = &host[..host.len() - rest.len()]; + Ok((format!("{scheme}{authority}:{port}"), None)) } - }; - Ok((url.origin().ascii_serialization(), conflicting)) + } } /// Effective port of a host that [`host_with_port`] has accepted: its explicit @@ -2312,9 +2316,21 @@ mod tests { ("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"), - // A non-default port in the host wins; a default one counts as no port. - ("https://h:9000", 8443, "https://h:9000"), + // 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", + ), ]; for &(host, port, want) in cases { assert_eq!( From d8a4a613b9cce0ad02e32f5c206245b190fc5349 Mon Sep 17 00:00:00 2001 From: cat23123 <58714163+cat23123@users.noreply.github.com> Date: Mon, 30 Nov 2026 21:53:33 +0000 Subject: [PATCH 10/11] fix(config): drop trailing whitespace before appending a port to the host The URL parser ignores trailing spaces and control characters, so a host such as `https://h ` passed validation and then became `https://h :8443`. Trim them before appending the port. Signed-off-by: cat23123 <58714163+cat23123@users.noreply.github.com> Co-authored-by: Isaac --- src/config.rs | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/src/config.rs b/src/config.rs index cd60b196..8b829277 100644 --- a/src/config.rs +++ b/src/config.rs @@ -278,14 +278,16 @@ pub(crate) fn fold_host_port( )), 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. + // lowercase and normalise the host. Trailing spaces and control characters, which the + // parser ignores, are trimmed first, then an empty or default port it dropped (`h:`, + // `h:443`). None => { + let scheme = &host[..host.len() - rest.len()]; + let rest = rest.trim_end_matches(|c: char| c <= ' '); let authority = match rest.rfind(':') { Some(i) if !rest[i..].contains(']') => &rest[..i], _ => rest, }; - let scheme = &host[..host.len() - rest.len()]; Ok((format!("{scheme}{authority}:{port}"), None)) } } @@ -2331,6 +2333,9 @@ mod tests { 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"), ]; for &(host, port, want) in cases { assert_eq!( From dbfd616ac6ddcd0e4311130f1fa8b4875103f4c9 Mon Sep 17 00:00:00 2001 From: cat23123 <58714163+cat23123@users.noreply.github.com> Date: Mon, 30 Nov 2026 22:03:12 +0000 Subject: [PATCH 11/11] fix(config): trim trailing whitespace when the host keeps its own port A host with its own non-default port was returned untrimmed, so `https://h:9000 ` kept the space. Trim once before validation so both branches use the trimmed host. Signed-off-by: cat23123 <58714163+cat23123@users.noreply.github.com> Co-authored-by: Isaac --- src/config.rs | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/src/config.rs b/src/config.rs index 8b829277..f9af2e3f 100644 --- a/src/config.rs +++ b/src/config.rs @@ -249,6 +249,10 @@ pub(crate) fn fold_host_port( 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('@') { @@ -278,12 +282,10 @@ pub(crate) fn fold_host_port( )), 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. Trailing spaces and control characters, which the - // parser ignores, are trimmed first, then an empty or default port it dropped (`h:`, - // `h:443`). + // 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 rest = rest.trim_end_matches(|c: char| c <= ' '); let authority = match rest.rfind(':') { Some(i) if !rest[i..].contains(']') => &rest[..i], _ => rest, @@ -2336,6 +2338,7 @@ mod tests { // 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!(