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

Filter by extension

Filter by extension

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

### Connection port

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

| Port | Effect |
|------|--------|
| `0` (or omitted) | Unset. The host is unchanged. |
| The scheme default (`443` for `https`, `80` for `http`) | Unchanged, with no validation. |
| Any other port | Appended to the host, which otherwise stays as written. |

The host is parsed with the same URL parser the transport uses. A non-default
port is rejected with `InvalidArgument` when:

- the host has credentials (`user:pw@host`);
- the host has a path, query or fragment;
- the parser rejects the host: an empty host, a bad embedded port, or an IPv6
address without brackets (write `[2001:db8::1]`, not `2001:db8::1`).

Error text never repeats the host, so credentials or tokens in it stay out of
errors and logs.

A non-default port already in the host (`host:N` or `[v6]:N`) is kept and
wins over the requested port, and the kernel logs a `WARN` when they differ. A
default port written in the host (`host:443`) counts as no port, so the
requested port is used. A requested port equal to the scheme default is
treated as unset, so it never warns. Only `http` and `https` hosts are
accepted. The applied port is reported as `host_info.port` in connection
telemetry.

The C ABI validates eagerly. A bad host/port combination returns
`InvalidArgument` from whichever of `kernel_session_config_set_port`,
`kernel_session_config_set_warehouse` or `kernel_session_config_set_http_path`
is called second, and the config is unchanged. The port number itself is
checked once, in the kernel (`config::port_from_value`), for every binding,
before any network I/O.

## `AuthConfig` — authentication (required)

An enum; pick one variant. Use the validating constructors
Expand Down
5 changes: 5 additions & 0 deletions NEXT_CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,11 @@ changes go in their respective binding's NEXT_CHANGELOG.

### Added

- A connection port option: `ConnectionConfig::with_port` and the C ABI
`kernel_session_config_set_port` connect to `host:port`, so bindings no longer
build it into the host. A non-default port is rejected with `InvalidArgument`
if the host has credentials, a path, query or fragment.

### Changed

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

/* Connection port — optional, may be set before or after the host; last call
* wins. `port` is a signed 64-bit integer so callers pass their own integer
* type as is; a value outside 0..65535 returns KernelStatusCode_InvalidArgument.
* `0` (the default) means unset. The scheme default (443 for https, 80 for
* http) is accepted and changes nothing. Any other port is folded into the
* host at kernel_session_open, so the kernel connects to host:port.
*
* The host must not carry userinfo (`user:pw@host`), a path, a query or a
* fragment, and must be a valid host (an IPv6 address needs brackets). A
* non-default port already in the host (`host:N` or `[v6]:N`) is kept and wins
* over this one, and the kernel logs a warning when they differ; a default
* port written in the host (`host:443`) counts as none. Validation is eager: a
* bad combination returns KernelStatusCode_InvalidArgument from whichever of
* this call or the host setter came second, and leaves the config unchanged.
* Error text never repeats the host. */
KernelStatusCode kernel_session_config_set_port(KernelSessionConfig* config,
int64_t port);

/* Authentication — call exactly one; the last one wins. */
KernelStatusCode kernel_session_config_set_auth_pat(KernelSessionConfig* config,
const char* token);
Expand Down
4 changes: 4 additions & 0 deletions napi/NEXT_CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,10 @@ layout, or npm publishing. Pure-kernel changes go in the root

### Added

- `ConnectionOptions.port`: an optional connection port. A value outside
`0..=65535`, or a host the kernel can't combine with the port, gives
`InvalidArgument`.

### Changed

### Updated
Expand Down
10 changes: 10 additions & 0 deletions napi/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,16 @@ export interface ConnectionOptions {
* kernel parses out the warehouse id.
*/
httpPath: string
/**
* Connection port. Omitted, `0`, or the scheme default (443 for
* `https`, 80 for `http`) changes nothing. Any other port is folded
* into the host by the kernel, so the connection goes to `host:port`.
* The host must not carry credentials, a path, a query or a fragment,
* an IPv6 address needs brackets, and a non-default port already in the
* host wins over this one. A value that is not an integer in
* `0..=65535` is an `InvalidArgument` error.
*/
port?: number
/**
* Authentication mode. Omitted ⇒ [`AuthMode::Pat`] (back-compat:
* existing PAT callers pass only `token`).
Expand Down
63 changes: 56 additions & 7 deletions napi/src/database.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,9 @@ use napi::bindgen_prelude::Buffer;
#[cfg(test)]
type Buffer = Vec<u8>;

use databricks_sql_kernel::config::{port_from_value, PortValue};
use databricks_sql_kernel::{
AuthConfig, DefaultOpts, DriverSystemConfiguration, Error as KernelError,
AuthConfig, ConnectionConfig, DefaultOpts, DriverSystemConfiguration, Error as KernelError,
GeospatialResultRepresentation, HttpConfig, ProxyConfig, ResultConfig, Session,
TelemetryConfig, TlsConfig, TokenCacheConfig,
};
Expand Down Expand Up @@ -154,6 +155,14 @@ pub struct ConnectionOptions {
/// JDBC-style HTTP path, e.g. `/sql/1.0/warehouses/abc123`. The
/// kernel parses out the warehouse id.
pub http_path: String,
/// Connection port. Omitted, `0`, or the scheme default (443 for
/// `https`, 80 for `http`) changes nothing. Any other port is folded
/// into the host by the kernel, so the connection goes to `host:port`.
/// The host must not carry credentials, a path, a query or a fragment,
/// an IPv6 address needs brackets, and a non-default port already in the
/// host wins over this one. A value that is not an integer in
/// `0..=65535` is an `InvalidArgument` error.
pub port: Option<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 +474,21 @@ pub struct ConnectionOptions {
pub socket_timeout_ms: Option<u32>,
}

/// Build the kernel [`ConnectionConfig`] from `hostName`, `httpPath` and
/// the optional `port`. A JS number is passed to the kernel as a float
/// ([`PortValue::Float`]), so the kernel's [`port_from_value`] rejects a
/// fraction, `NaN` or an infinity instead of truncating it; the kernel then
/// folds the port into the host ([`ConnectionConfig::with_port`]). Pure
/// (borrows `options`) so it can be tested without opening a session.
fn build_connection(options: &ConnectionOptions) -> napi::Result<ConnectionConfig> {
port_from_value(options.port.map(PortValue::Float))
.and_then(|port| {
ConnectionConfig::from_http_path(options.host_name.clone(), &options.http_path)?
.with_port(port)
})
.map_err(napi_err_from_kernel)
}

/// Map the JS `ConnectionOptions` auth fields onto the kernel
/// [`AuthConfig`]. Per-mode required-field validation lives in the
/// kernel's validating constructors ([`AuthConfig::pat`] /
Expand Down Expand Up @@ -814,6 +838,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 +857,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 +935,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 +1399,30 @@ mod tests {
assert!(tls.skip_hostname_verification);
}

#[test]
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}");
}
}

#[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 tls_hostname_check_can_be_disabled_independently() {
// Chain validation stays ON; only the hostname check is skipped.
Expand Down
4 changes: 4 additions & 0 deletions pyo3/NEXT_CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@ changes go in the root `NEXT_CHANGELOG.md`.

### Added

- `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

### Updated
Expand Down
51 changes: 49 additions & 2 deletions pyo3/src/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,12 @@ use crate::executed_async::ExecutedAsyncStatement;
use crate::metadata::Metadata;
use crate::runtime::KernelRuntime;
use crate::statement::Statement;
use databricks_sql_kernel::{GeospatialResultRepresentation, Session as KSession};
use databricks_sql_kernel::config::{port_from_value, PortValue};
use databricks_sql_kernel::{
ConnectionConfig, GeospatialResultRepresentation, Session as KSession,
};
use pyo3::prelude::*;
use pyo3::types::{PyBool, PyInt};
use std::collections::HashMap;
use std::sync::Arc;
use tokio::runtime::Builder;
Expand Down Expand Up @@ -143,6 +147,34 @@ fn build_telemetry_config(
Ok(telemetry)
}

/// 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<Bound<'_, PyAny>>) -> PyResult<u16> {
let value = port.filter(|obj| !obj.is_none()).map(|obj| {
if obj.is_instance_of::<PyBool>() || !obj.is_instance_of::<PyInt>() {
PortValue::Unsupported
} else {
obj.extract::<i64>()
.map_or(PortValue::Unsupported, PortValue::Integer)
}
});
port_from_value(value).map_err(|err| pyo3::exceptions::PyValueError::new_err(err.message))
}

/// Build the kernel connection from `host`, `http_path` and the validated
/// port. Port `0` leaves the host unchanged; a bad host/port combination is
/// the kernel's `InvalidArgument`.
fn connection_config(
host: String,
http_path: &str,
port: u16,
) -> Result<ConnectionConfig, databricks_sql_kernel::Error> {
ConnectionConfig::from_http_path(host, http_path)?.with_port(port)
}

fn geospatial_result_representation(enabled: bool) -> GeospatialResultRepresentation {
if enabled {
GeospatialResultRepresentation::Binary
Expand Down Expand Up @@ -280,6 +312,16 @@ impl Session {
/// fully-qualified (`https://...`). `http_path` is the SQL
/// endpoint path.
///
/// `port` is an optional connection port (`int`, `0..=65535`, default
/// `None`). A non-default port is folded into the host by the kernel,
/// so the connection goes to `host:port`. Port `0` and the scheme
/// default (443 for `https`, 80 for `http`) change nothing. The host
/// must not carry credentials, a path, a query, or a fragment, and an
/// IPv6 address needs brackets. A non-default port already in `host`
/// wins over `port`, and the kernel logs a warning when they differ. A
/// bad host/port combination raises `KernelError` (`InvalidArgument`). A
/// value outside `0..=65535`, or a non-int, raises `ValueError`.
///
/// Auth: pass `auth_type` plus the matching credentials.
///
/// - `"pat"` (or omit `auth_type` and pass `access_token`):
Expand Down Expand Up @@ -351,6 +393,7 @@ impl Session {
host,
http_path,
*,
port=None,
auth_type=None,
access_token=None,
client_id=None,
Expand Down Expand Up @@ -416,6 +459,7 @@ impl Session {
py: Python<'_>,
host: String,
http_path: String,
port: Option<Bound<'_, PyAny>>,
auth_type: Option<String>,
access_token: Option<String>,
client_id: Option<String>,
Expand Down Expand Up @@ -478,6 +522,9 @@ impl Session {
telemetry_circuit_breaker_threshold: Option<u32>,
telemetry_circuit_breaker_timeout_ms: Option<u64>,
) -> PyResult<Self> {
// 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
Expand Down Expand Up @@ -628,7 +675,7 @@ impl Session {
let rt = runtime.clone();
let session = run_kernel!(py, rt, async {
let mut builder = KSession::builder()
.http_path(host, http_path)
.connection(connection_config(host, &http_path, port)?)
.auth(auth_config);
if let Some(tls) = tls_config {
builder = builder.tls(tls);
Expand Down
48 changes: 48 additions & 0 deletions pyo3/tests/test_port.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
# Copyright (c) 2026 Databricks, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Connection `port` kwarg: argument validation.

Every case here is rejected before any network I/O, so no workspace is
needed. A valid port is folded into the host by the kernel and exercised
by the live/e2e suites.
"""

from __future__ import annotations

import pytest

import databricks_sql_kernel as k


def _open(port, host="x.databricks.com"):
return k.Session(
host=host,
http_path="/sql/1.0/warehouses/abc",
access_token="dapi-test",
port=port,
)


@pytest.mark.parametrize("bad", [-1, 65536, 10**12, True, False, 8443.0, "8443"])
def test_port_out_of_range_or_non_int_raises_value_error(bad):
with pytest.raises(ValueError, match="port must be an integer between 0 and 65535"):
_open(bad)


def test_port_with_credentials_is_rejected_without_leaking_them():
with pytest.raises(k.KernelError) as excinfo:
_open(8443, host="https://user:s3cret@x.databricks.com")
assert excinfo.value.code == "InvalidArgument", excinfo.value.code
assert "s3cret" not in str(excinfo.value)
Loading
Loading