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
6 changes: 3 additions & 3 deletions include/databricks_kernel.h
Original file line number Diff line number Diff line change
Expand Up @@ -239,9 +239,9 @@ KernelStatusCode kernel_session_config_set_auth_m2m(KernelSessionConfig* config,
const char* client_id,
const char* client_secret);
/* OAuth U2M (user-to-machine: authorization code + PKCE, browser flow).
* All args optional: `client_id` NULL → public `databricks-cli` client;
* `redirect_port` 0 → kernel default (8020); `scopes` (comma-separated)
* NULL → kernel default (`all-apis`,`offline_access`; `offline_access`
* All args optional: `client_id` NULL → `databricks-sql-connector` client;
* `redirect_port` 0 → kernel default (8030); `scopes` (comma-separated)
* NULL → kernel default (`sql`,`offline_access`; `offline_access`
* yields a cached, auto-refreshed refresh token). INTERACTIVE: opening the
* session starts a localhost listener and opens the user's browser. */
KernelStatusCode kernel_session_config_set_auth_u2m(KernelSessionConfig* config,
Expand Down
6 changes: 3 additions & 3 deletions napi/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,7 @@ export interface ProxyInput {
* - `Pat` — `token` required.
* - `OAuthM2m` — `oauthClientId` + `oauthClientSecret` required.
* - `OAuthU2m` — `oauthClientId` / `oauthRedirectPort` optional
* (defaults to the `databricks-sql-connector` client on port 8020).
* (defaults to the `databricks-sql-connector` client on port 8030).
*
* Catalog / schema / sessionConf are applied once at session creation
* and remain in effect for every statement run on the resulting
Expand Down Expand Up @@ -197,12 +197,12 @@ export interface ConnectionOptions {
oauthClientSecret?: string
/**
* Localhost callback port for the [`AuthMode::OAuthU2m`] browser
* flow. Omitted ⇒ kernel default (8020).
* flow. Omitted ⇒ kernel default (8030).
*/
oauthRedirectPort?: number
/**
* OAuth scopes override (M2M / U2M). Omitted ⇒ kernel defaults
* (`["all-apis"]` for M2M; `["all-apis", "offline_access"]` for U2M).
* (`["all-apis"]` for M2M; `["sql", "offline_access"]` for U2M).
*/
oauthScopes?: Array<string>
/**
Expand Down
66 changes: 19 additions & 47 deletions napi/src/database.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,27 +59,6 @@ use crate::error::napi_err_from_kernel;
use crate::runtime;
use crate::util::guarded;

/// Default U2M OAuth client id for the **Node** binding.
///
/// Matches the standalone Node driver's
/// `DatabricksOAuthManager.defaultClientId` (`databricks-sql-connector`)
/// rather than the kernel's bare-Rust fallback (`databricks-cli`), for
/// two reasons:
///
/// 1. **OAuth app identity** — the napi path registers as the same
/// OAuth app the standalone Node driver does, so admin-side consent
/// screens / SSO policies attribute it consistently.
/// 2. **Per-binding cache-key isolation** — the kernel's U2M token
/// cache is keyed on `{host, client_id, scopes}`; a distinct client
/// id keeps the napi cache from colliding with the pyo3 (Python,
/// `databricks-sql-python`) binding's.
///
/// This does NOT share a token-cache *entry* with databricks-sql-nodejs
/// — the kernel writes to its own `~/.config/databricks-sql-kernel/
/// oauth/` directory. The alignment is of the OAuth app identity, not
/// the on-disk cache.
const NODE_OAUTH_CLIENT_ID: &str = "databricks-sql-connector";

/// Authentication mode selector crossing the napi boundary. The string
/// literals are what napi-rs emits from this `#[napi(string_enum)]` — the
/// NodeJS SEA adapter (`KernelAuth`) matches them verbatim (`'Pat'`,
Expand Down Expand Up @@ -142,7 +121,7 @@ pub struct ProxyInput {
/// - `Pat` — `token` required.
/// - `OAuthM2m` — `oauthClientId` + `oauthClientSecret` required.
/// - `OAuthU2m` — `oauthClientId` / `oauthRedirectPort` optional
/// (defaults to the `databricks-sql-connector` client on port 8020).
/// (defaults to the `databricks-sql-connector` client on port 8030).
///
/// Catalog / schema / sessionConf are applied once at session creation
/// and remain in effect for every statement run on the resulting
Expand Down Expand Up @@ -173,10 +152,10 @@ pub struct ConnectionOptions {
/// OAuth client secret. Required for [`AuthMode::OAuthM2m`].
pub oauth_client_secret: Option<String>,
/// Localhost callback port for the [`AuthMode::OAuthU2m`] browser
/// flow. Omitted ⇒ kernel default (8020).
/// flow. Omitted ⇒ kernel default (8030).
Comment thread
oss-reviewer-bot[bot] marked this conversation as resolved.
Resolved
pub oauth_redirect_port: Option<u16>,
/// OAuth scopes override (M2M / U2M). Omitted ⇒ kernel defaults
/// (`["all-apis"]` for M2M; `["all-apis", "offline_access"]` for U2M).
/// (`["all-apis"]` for M2M; `["sql", "offline_access"]` for U2M).
pub oauth_scopes: Option<Vec<String>>,
/// Default catalog for statements executed on this session.
/// Routed through the kernel's `DefaultOpts` and onto the SEA
Expand Down Expand Up @@ -363,33 +342,24 @@ fn build_auth_config(options: &ConnectionOptions) -> napi::Result<AuthConfig> {
None,
)
.map_err(napi_err_from_kernel),
// All U2M fields are optional. Default the OAuth client_id to
// the Node driver's own registered client
// (`databricks-sql-connector`, matching the standalone
// databricks-sql-nodejs `DatabricksOAuthManager.defaultClientId`)
// rather than the kernel's bare-Rust `databricks-cli` fallback,
// so the napi path presents the same OAuth app identity as the
// standalone Node driver and keeps a cache key distinct from the
// pyo3 (Python) binding. Port 8020 / default scopes are still
// filled by the kernel when omitted.
// napi injects no client_id/scope default: it rides the kernel's
// single U2M default bundle (databricks-sql-connector / sql
// offline_access / port 8030), which already IS the standalone Node
// driver's OAuth app identity. See PECOBLR-4039.
AuthMode::OAuthU2m => {
// Reject an explicit empty client_id (parity with pyo3):
// an empty string would bypass the default and bind an empty
// OAuth client, surfacing as an opaque server error. Omit
// the field to get the `databricks-sql-connector` default.
// An explicit empty client_id is still rejected — it would bind
// an empty OAuth client and surface an opaque server error. Omit
// the field to use the kernel default.
if matches!(options.oauth_client_id.as_deref(), Some("")) {
return Err(napi_err_from_kernel(
KernelError::invalid_argument().message(
"oauthClientId must be non-empty when set; omit it to use the \
default 'databricks-sql-connector'",
kernel default 'databricks-sql-connector'",
),
));
}
Ok(AuthConfig::oauth_u2m(
options
.oauth_client_id
.clone()
.or_else(|| Some(NODE_OAUTH_CLIENT_ID.to_owned())),
options.oauth_client_id.clone(),
options.oauth_redirect_port,
options.oauth_scopes.clone(),
None,
Expand Down Expand Up @@ -711,18 +681,20 @@ mod tests {
fn u2m_fields_are_all_optional() {
let mut o = base();
o.auth_mode = Some(AuthMode::OAuthU2m);
// Bare U2M: the napi binding defaults client_id to
// `databricks-sql-connector` (matching the standalone Node
// driver), NOT the kernel's bare `databricks-cli`. Port 8020 /
// default scopes are still filled by the kernel.
// Bare U2M: napi injects no override, so client_id / scopes /
// redirect_port are all None and the kernel fills its default bundle
// (databricks-sql-connector / sql offline_access / 8030). See
// PECOBLR-4039.
match build_auth_config(&o).unwrap() {
AuthConfig::OAuthU2M {
client_id,
redirect_port,
scopes,
..
} => {
assert_eq!(client_id.as_deref(), Some("databricks-sql-connector"));
assert!(client_id.is_none());
assert!(redirect_port.is_none());
assert!(scopes.is_none());
}
other => panic!("expected OAuthU2M, got {other:?}"),
}
Expand Down
81 changes: 53 additions & 28 deletions pyo3/src/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ pub(crate) struct OAuthParams {
///
/// Matches the standalone Thrift connector's `PYSQL_OAUTH_CLIENT_ID`
/// (`databricks-sql-python`) rather than the kernel's bare-Rust
/// fallback (`databricks-cli`). Two reasons:
/// fallback (`databricks-sql-connector`). Two reasons:
///
/// 1. **OAuth app identity** — the `use_kernel=True` path registers as
/// the same OAuth app the standalone Python connector does, so
Expand All @@ -79,14 +79,14 @@ const PYSQL_OAUTH_CLIENT_ID: &str = "databricks-sql-python";
/// Default U2M scopes for the **Python** binding when the caller relies
/// on the default `PYSQL_OAUTH_CLIENT_ID` above.
///
/// The kernel's intrinsic U2M default is `["all-apis", "offline_access"]`,
/// which is correct for its bare-Rust default client (`databricks-cli`).
/// But the Python binding overrides the default client to
/// `databricks-sql-python` — and *that* client is only registered for
/// `sql` (plus `offline_access`) on the Databricks IdP. Without a
/// matching scope override here, an out-of-the-box
/// `Session(auth_type="oauth-u2m")` from Python fails on the
/// authorization request with
/// The Python binding overrides the U2M client to `databricks-sql-python`
/// (see `PYSQL_OAUTH_CLIENT_ID`), which is registered for `sql` (plus
/// `offline_access`) on the Databricks IdP. These scopes currently match the
/// kernel's own default (`sql offline_access`), but the binding pins them
/// explicitly so the `databricks-sql-python` bundle
/// (`{client_id, scopes, redirect_port}`) stays self-consistent and would not
/// silently break if the kernel default ever changed — a `databricks-sql-python`
/// authorization requesting `all-apis`, say, would fail with
/// `access_denied — Scopes 'all-apis' are not assigned to the client
/// databricks-sql-python`.
///
Expand All @@ -96,10 +96,23 @@ const PYSQL_OAUTH_CLIENT_ID: &str = "databricks-sql-python";
///
/// Only applied when the caller passed neither `client_id` nor `scopes`
/// — a caller supplying their own `client_id` may legitimately want
/// `all-apis` (or anything else), and an explicit `scopes` is always
/// honoured verbatim.
/// different scopes, and an explicit `scopes` is always honoured verbatim.
const PYSQL_OAUTH_SCOPES: &[&str] = &["sql", "offline_access"];

/// Default U2M redirect port for the **Python** binding.
///
/// The kernel's intrinsic default is `8030` — the port registered for its
/// default `databricks-sql-connector` app. But the Python binding overrides
/// the client to `databricks-sql-python`, whose registered redirect port is
/// `8020` (the standalone connector's `PYSQL_OAUTH_REDIRECT_PORT_RANGE` starts
/// at 8020). `client_id`, `scopes`, and `redirect_port` are a coupled bundle —
/// overriding the client without pinning its port would inherit the kernel's
/// `8030` and fail the browser redirect with `redirect_uri_mismatch`.
///
/// Only applied when the caller relies on the default `client_id`; a caller
/// supplying their own `client_id` owns the matching port too.
const PYSQL_OAUTH_REDIRECT_PORT: u16 = 8020;

/// Build a kernel `AuthConfig` from the Python kwargs the `Session`
/// constructor accepts.
///
Expand Down Expand Up @@ -149,8 +162,8 @@ fn build_auth_config_inner(
}
"oauth-u2m" => {
// Browser flow: every field is optional and `None` lets the
// kernel apply its defaults (client_id "databricks-cli",
// redirect_port 8020, scopes ["all-apis", "offline_access"],
// kernel apply its defaults (client_id "databricks-sql-connector",
Comment thread
oss-reviewer-bot[bot] marked this conversation as resolved.
Resolved
// redirect_port 8030, scopes ["sql", "offline_access"],
// callback timeout 120s). But a *present-yet-degenerate*
// value is a footgun the kernel can't distinguish from an
// intentional setting, so reject those here:
Expand Down Expand Up @@ -183,7 +196,7 @@ fn build_auth_config_inner(
}
// Default the U2M OAuth client to the Python connector's
// own registered client (`databricks-sql-python`), NOT the
// kernel's bare-Rust fallback (`databricks-cli`). This
// kernel's bare-Rust fallback (`databricks-sql-connector`). This
// matches the standalone Thrift connector
// (`PYSQL_OAUTH_CLIENT_ID` in databricks-sql-python's
// auth.py) so a user gets the same OAuth app identity whether
Expand All @@ -202,7 +215,7 @@ fn build_auth_config_inner(
// `client_id` and no `scopes`), also default the scopes to
// the Python-binding set so the default client/scopes pair
// is internally consistent. The kernel's intrinsic scope
// default is for its `databricks-cli` client, not for
// default is for its `databricks-sql-connector` client, not for
// `databricks-sql-python` — see `PYSQL_OAUTH_SCOPES` above.
let caller_set_client_id = oauth.client_id.is_some();
let client_id = oauth
Expand All @@ -215,9 +228,17 @@ fn build_auth_config_inner(
}
None => None,
};
// Pin the databricks-sql-python app's own redirect port when
// relying on the default client_id — the kernel default (8030) is
// for the databricks-sql-connector app and would mismatch.
let redirect_port = match oauth.redirect_port {
Some(p) => Some(p),
None if !caller_set_client_id => Some(PYSQL_OAUTH_REDIRECT_PORT),
None => None,
};
Ok(AuthConfig::OAuthU2M {
client_id,
redirect_port: oauth.redirect_port,
redirect_port,
scopes,
token_url_override: oauth.token_url,
callback_timeout: oauth.callback_timeout_secs.map(Duration::from_secs),
Expand Down Expand Up @@ -341,13 +362,11 @@ mod tests {
fn u2m_defaults_client_id_and_scopes_to_python_connector() {
// U2M takes no mandatory fields. The Python binding defaults the
// OAuth client_id to `databricks-sql-python` (NOT the kernel's
// bare `databricks-cli`) so it matches the standalone Thrift
// connector and the napi binding gets a distinct cache key.
// It also defaults the scopes to `["sql", "offline_access"]` to
// match the scopes registered for that client on the Databricks
// IdP — the kernel's intrinsic `all-apis` default is for its
// own `databricks-cli` client, which `databricks-sql-python`
// isn't allowed to request.
// default `databricks-sql-connector`) so it matches the standalone
// Thrift connector and gets a cache key distinct from the napi
// binding. It pins scopes to `["sql", "offline_access"]` for the
// databricks-sql-python app; these match the kernel's default scopes
// but are pinned explicitly so the bundle stays self-consistent.
let cfg = build_auth_config_inner("oauth-u2m", None, OAuthParams::default()).unwrap();
match cfg {
AuthConfig::OAuthU2M {
Expand All @@ -359,7 +378,9 @@ mod tests {
token_cache,
} => {
assert_eq!(client_id.as_deref(), Some("databricks-sql-python"));
assert!(redirect_port.is_none());
// Python bundle pins its own app's registered port (8020),
// NOT the kernel default 8030 (databricks-sql-connector).
assert_eq!(redirect_port, Some(8020));
assert_eq!(
scopes,
Some(vec!["sql".to_string(), "offline_access".to_string()])
Expand Down Expand Up @@ -392,13 +413,17 @@ mod tests {
.unwrap();
match cfg {
AuthConfig::OAuthU2M {
client_id, scopes, ..
client_id,
scopes,
redirect_port,
..
} => {
assert_eq!(client_id.as_deref(), Some("my-custom-app"));
// Custom client_id without scopes: don't override the
// kernel's default scopes — a custom client may
// legitimately request `all-apis` (or anything else).
// Custom client_id without scopes/port: don't pin the Python
// bundle's defaults — a custom app owns its own scopes and
// redirect port, so both defer to the kernel (None).
assert!(scopes.is_none());
assert!(redirect_port.is_none());
}
other => panic!("expected OAuthU2M, got {other:?}"),
}
Expand Down
6 changes: 5 additions & 1 deletion pyo3/src/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -369,7 +369,11 @@ impl Session {
target: crate::logging::PYO3_LOG_TARGET,
"Session.attach_async_statement: re-attaching by id (GIL released)"
);
let exec = run_kernel!(py, runtime, inner.session.attach_async_statement(statement_id))?;
let exec = run_kernel!(
py,
runtime,
inner.session.attach_async_statement(statement_id)
)?;
Ok(ExecutedAsyncStatement::new(exec, runtime))
}

Expand Down
6 changes: 3 additions & 3 deletions src/auth/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -106,9 +106,9 @@ impl AuthConfig {
}
AuthType::OAuthU2m => {
// U2M flow has no required fields - all parameters have defaults:
// - client_id defaults to "databricks-cli"
// - scopes defaults to "all-apis offline_access"
// - redirect_port defaults to 8020
// - client_id defaults to "databricks-sql-connector"
// - scopes defaults to "sql offline_access"
// - redirect_port defaults to 8030
}
}

Expand Down
11 changes: 6 additions & 5 deletions src/auth/oauth/callback.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
//!
//! This module implements a lightweight HTTP server that listens on localhost
//! for OAuth redirect callbacks from the browser. The server:
//! - Binds to a configurable port (default 8020)
//! - Binds to a configurable port (default 8030)
//! - Validates the state parameter for CSRF protection
//! - Extracts the authorization code from query parameters
//! - Returns a simple HTML page to the browser
Expand Down Expand Up @@ -74,8 +74,8 @@ enum CallbackResult {
/// use std::time::Duration;
///
/// # async fn example() -> databricks_sql_kernel::Result<()> {
/// // Start callback server on port 8020
/// let server = CallbackServer::new(8020).await?;
/// // Start callback server on port 8030
/// let server = CallbackServer::new(8030).await?;
/// let redirect_uri = server.redirect_uri();
/// println!("Redirect URI: {}", redirect_uri);
///
Expand Down Expand Up @@ -112,7 +112,7 @@ impl CallbackServer {
///
/// # Arguments
///
/// * `port` - Port number to listen on (typically 8020)
/// * `port` - Port number to listen on (typically 8030)
///
/// # Returns
///
Expand Down Expand Up @@ -158,7 +158,8 @@ impl CallbackServer {
///
/// This URI should be used when constructing the OAuth authorization URL.
/// The format is `http://localhost:{port}` (matching the redirect URI
/// registered for the `databricks-cli` OAuth application).
/// registered for the kernel's default U2M OAuth application,
/// `databricks-sql-connector`, at `http://localhost:8030`).
pub fn redirect_uri(&self) -> String {
format!("http://localhost:{}", self.port)
}
Expand Down
Loading
Loading