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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions CONNECTION_PARAMETERS.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,40 @@ warehouse id and org id out of a `/sql/1.0/warehouses/{id}` path).
| `warehouse_id` | Warehouse id, e.g. `abc123`. Accepts `/sql/1.0/warehouses/{id}` and legacy `/sql/1.0/endpoints/{id}` forms via `from_http_path`. | **(required)** |
| `org_id` | Workspace organization id for multi-tenant routing; sent as the `x-databricks-org-id` header. Auto-populated from the `?o=` query parameter of the HTTP path. | `None` |

### Connection port

A connection port is an input, not a field: the kernel folds it into `host`
as `scheme://host:port`, and the transport connects there. Set it with
`ConnectionConfig::with_port(port)` in Rust, the pyo3 `port=` keyword, the
napi `port` option, or `kernel_session_config_set_port` in the C ABI. Bindings
no longer build the port into the host string themselves.

| Port | Effect |
|------|--------|
| `0` (or omitted) | Unset. The host is unchanged. |
| The scheme default (`443` for `https`, `80` for `http`) | Unchanged, with no validation. |
| Any other port | Folded into the host. |

A non-default port is rejected with `InvalidArgument` when:

- the host has userinfo (`user:pw@host`); error text shows `<redacted>@host`;
- the host is empty, or has a path, query or fragment;
- the host already has an embedded port that is not `1` to `65535`.

A port already embedded in the host (`host:N` or `[v6]:N`) is kept and wins
over the requested port. The kernel logs a `WARN` when a non-default requested
port differs from it; a requested port equal to the scheme default is treated
as unset, so it never warns. A bare
IPv6 literal is bracketed, so `2001:db8::1` becomes `[2001:db8::1]:port`. Only
`http` and `https` hosts are accepted. The applied port is reported as
`host_info.port` in connection telemetry.

The C ABI validates eagerly. A bad host/port combination returns
`InvalidArgument` from whichever of `kernel_session_config_set_port`,
`kernel_session_config_set_warehouse` or `kernel_session_config_set_http_path`
is called second, and the config is unchanged. The bindings validate the port
value at construction or open, before any network I/O.

## `AuthConfig` — authentication (required)

An enum; pick one variant. Use the validating constructors
Expand Down
12 changes: 12 additions & 0 deletions NEXT_CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<redacted>@host`), an
empty host, a path/query/fragment, and an embedded port outside `1`–`65535`.
An embedded port that is already in the host wins, with a warning if a
non-default requested port differs from it. Bare IPv6 literals are bracketed.
- C ABI `kernel_session_config_set_port(config, port)`. It validates eagerly
against the host set so far, and each later host setter re-checks it.
`host_info.port` in connection telemetry reports the applied port.

### Changed

### Updated
Expand Down
16 changes: 16 additions & 0 deletions include/databricks_kernel.h
Original file line number Diff line number Diff line change
Expand Up @@ -245,6 +245,22 @@ KernelStatusCode kernel_session_config_set_http_path(KernelSessionConfig* config
const char* host,
const char* http_path);

/* Connection port — optional, may be set before or after the host; last call
* wins. `0` (the default) means unset. The scheme default (443 for https, 80
* for http) is accepted and changes nothing. Any other port is folded into the
* host at kernel_session_open, so the kernel connects to host:port.
*
* The host must not carry userinfo (`user:pw@host`), a path, a query or a
* fragment, and must not be empty. A port already embedded in the host
* (`host:N` or `[v6]:N`) is kept and wins over this one; the kernel logs a
* warning when a non-default port differs from it (the scheme default never
* warns). Validation is eager: a bad combination returns
* KernelStatusCode_InvalidArgument from whichever of this call or the host
* setter came second, and leaves the config unchanged. Error text never
* includes credentials. */
KernelStatusCode kernel_session_config_set_port(KernelSessionConfig* config,
uint16_t port);

/* Authentication — call exactly one; the last one wins. */
KernelStatusCode kernel_session_config_set_auth_pat(KernelSessionConfig* config,
const char* token);
Expand Down
8 changes: 8 additions & 0 deletions napi/NEXT_CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
9 changes: 9 additions & 0 deletions napi/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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`).
Expand Down
98 changes: 91 additions & 7 deletions napi/src/database.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ use napi::bindgen_prelude::Buffer;
type Buffer = Vec<u8>;

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,
};
Expand Down Expand Up @@ -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<f64>,
/// Authentication mode. Omitted ⇒ [`AuthMode::Pat`] (back-compat:
/// existing PAT callers pass only `token`).
pub auth_mode: Option<AuthMode>,
Expand Down Expand Up @@ -465,6 +472,33 @@ pub struct ConnectionOptions {
pub socket_timeout_ms: Option<u32>,
}

/// 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<ConnectionConfig> {
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<f64>) -> napi::Result<u16> {
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`] /
Expand Down Expand Up @@ -814,6 +848,9 @@ pub async fn open_session(mut options: ConnectionOptions) -> napi::Result<Connec
// Resolve auth before the builder moves `host_name` / `http_path`
// out of `options` (validation can fail fast, before any network).
let auth_config = build_auth_config(&options)?;
// Resolve host + port + http path before the builder moves them out
// of `options`, so a bad port fails fast, before any network I/O.
let connection = build_connection(&options)?;
// Build the TLS config before the builder moves fields out of
// `options`. Always wired (even at defaults) because the
// permissive-by-default stance needs the relaxation flags set —
Expand All @@ -830,12 +867,9 @@ pub async fn open_session(mut options: ConnectionOptions) -> napi::Result<Connec

// SessionConfig is `#[non_exhaustive]` — go through the
// builder, which is the only public path that constructs it.
// `http_path()` is the convenience setter that maps a bare
// hostname + `/sql/1.0/warehouses/{id}` path into the kernel's
// `ConnectionConfig`.
let mut builder = Session::builder()
.http_path(options.host_name, options.http_path)
.auth(auth_config);
// `connection` is the `ConnectionConfig` built (with the port
// folded in) by `build_connection` above.
let mut builder = Session::builder().connection(connection).auth(auth_config);
// Only wire `DefaultOpts` when at least one of catalog / schema
// was provided; otherwise leave the config's `defaults` field
// `None` so the kernel can distinguish "no defaults" from
Expand Down Expand Up @@ -911,6 +945,7 @@ mod tests {
ConnectionOptions {
host_name: "adb-1.azuredatabricks.net".to_owned(),
http_path: "/sql/1.0/warehouses/abc".to_owned(),
port: None,
auth_mode: None,
token: None,
oauth_client_id: None,
Expand Down Expand Up @@ -1374,6 +1409,55 @@ mod tests {
assert!(tls.skip_hostname_verification);
}

#[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();
assert_eq!(err.status, napi::Status::InvalidArg, "port={bad}");
}
}

#[test]
fn build_connection_folds_a_port_and_leaves_the_host_without_one() {
let c = build_connection(&base()).unwrap();
assert_eq!(c.host, "https://adb-1.azuredatabricks.net");

let mut o = base();
o.port = Some(8443.0);
let c = build_connection(&o).unwrap();
assert_eq!(c.host, "https://adb-1.azuredatabricks.net:8443");
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.
Expand Down
8 changes: 8 additions & 0 deletions pyo3/NEXT_CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,14 @@ 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`).

### Changed

### Updated
Expand Down
Loading
Loading