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
89 changes: 74 additions & 15 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, HttpConfig, ResultConfig, Session, TlsConfig,
AuthConfig, DefaultOpts, Error as KernelError, HttpConfig, ResultConfig, Session, TlsConfig,
};

/// NodeJS-driver-appropriate default for `pool_max_idle_per_host`.
Expand All @@ -56,6 +56,27 @@ 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 (`SeaAuth`) matches them verbatim (`'Pat'`,
Expand Down Expand Up @@ -83,8 +104,8 @@ pub enum AuthMode {
/// Authentication is selected by `authMode` (default [`AuthMode::Pat`]):
/// - `Pat` — `token` required.
/// - `OAuthM2m` — `oauthClientId` + `oauthClientSecret` required.
/// - `OAuthU2m` — `oauthClientId` / `oauthRedirectPort` optional (kernel
/// defaults to the `databricks-cli` client on port 8020).
/// - `OAuthU2m` — `oauthClientId` / `oauthRedirectPort` optional
/// (defaults to the `databricks-sql-connector` client on port 8020).
///
/// Catalog / schema / sessionConf are applied once at session creation
/// and remain in effect for every statement run on the resulting
Expand All @@ -110,7 +131,7 @@ pub struct ConnectionOptions {
/// [`AuthMode::Pat`]; ignored otherwise.
pub token: Option<String>,
/// OAuth client id. Required for [`AuthMode::OAuthM2m`]; optional for
/// [`AuthMode::OAuthU2m`] (kernel defaults to `databricks-cli`).
/// [`AuthMode::OAuthU2m`] (defaults to `databricks-sql-connector`).
pub oauth_client_id: Option<String>,
/// OAuth client secret. Required for [`AuthMode::OAuthM2m`].
pub oauth_client_secret: Option<String>,
Expand Down Expand Up @@ -208,15 +229,39 @@ fn build_auth_config(options: &ConnectionOptions) -> napi::Result<AuthConfig> {
None,
)
.map_err(napi_err_from_kernel),
// All U2M fields are optional — the kernel fills `databricks-cli`
// / port 8020 / default scopes when omitted.
AuthMode::OAuthU2m => Ok(AuthConfig::oauth_u2m(
options.oauth_client_id.clone(),
options.oauth_redirect_port,
options.oauth_scopes.clone(),
None,
None,
)),
// 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.
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.
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'",
),
));
}
Ok(AuthConfig::oauth_u2m(
options
.oauth_client_id
.clone()
.or_else(|| Some(NODE_OAUTH_CLIENT_ID.to_owned())),
options.oauth_redirect_port,
options.oauth_scopes.clone(),
None,
None,
))
}
}
}

Expand Down Expand Up @@ -436,14 +481,17 @@ mod tests {
fn u2m_fields_are_all_optional() {
let mut o = base();
o.auth_mode = Some(AuthMode::OAuthU2m);
// Bare U2M: kernel fills databricks-cli / port 8020 / default scopes.
// 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.
match build_auth_config(&o).unwrap() {
AuthConfig::OAuthU2M {
client_id,
redirect_port,
..
} => {
assert!(client_id.is_none());
assert_eq!(client_id.as_deref(), Some("databricks-sql-connector"));
assert!(redirect_port.is_none());
}
other => panic!("expected OAuthU2M, got {other:?}"),
Expand All @@ -464,6 +512,17 @@ mod tests {
}
}

#[test]
fn u2m_rejects_explicit_empty_client_id() {
// Parity with pyo3: an explicit empty oauthClientId is rejected
// (it would bind an empty client and surface an opaque server
// error), rather than silently falling back to the default.
let mut o = base();
o.auth_mode = Some(AuthMode::OAuthU2m);
o.oauth_client_id = Some(String::new());
assert_invalid_arg(build_auth_config(&o).unwrap_err(), "oauthClientId");
}

#[test]
fn tls_defaults_to_secure() {
// No `check_server_certificate` ⇒ secure by default: strict chain +
Expand Down
38 changes: 21 additions & 17 deletions napi/src/statement.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,15 +80,17 @@ enum AnyInner {
}

impl AnyInner {
/// Borrow the underlying result stream regardless of variant. The
/// executed-statement variant delegates to its
/// `ExecutedStatement::result_stream_mut`; the metadata variant
/// returns the bare `ResultStream` directly. Used by
/// `fetch_next_batch` to share one streaming path across both.
fn result_stream_mut(&mut self) -> &mut ResultStream {
/// Pull the next batch, variant-aware so the executed path gets the
/// kernel's **auto-close-on-drain** (fire-and-forget CloseStatement
/// once the stream is exhausted, after all lazy CloudFetch link
/// fetches). The metadata variant uses the bare stream's
/// `next_batch` — it carries its own close-on-drop guard
/// (`ResultStream::from_reader_with_close`), so it must NOT route
/// through the executed auto-close.
async fn next_batch(&mut self) -> databricks_sql_kernel::Result<Option<&ResultBatch>> {
match self {
AnyInner::Executed(s) => s.executed.result_stream_mut(),
AnyInner::Metadata(rs) => rs,
AnyInner::Executed(s) => s.executed.next_batch().await,
AnyInner::Metadata(rs) => rs.next_batch().await,
}
}
}
Expand Down Expand Up @@ -328,15 +330,17 @@ impl Statement {
guarded(async move {
let mut guard = inner.lock().await;
let inner_state = guard.as_mut().ok_or_else(statement_closed_err)?;
// `result_stream_mut` returns `&mut ResultStream` for both
// variants — the executed-path borrows from its
// `ExecutedStatement`, the metadata-path borrows from its
// bare `ResultStream`. The IPC schema header serialised
// into every batch payload comes from the cached
// `self.schema` captured outside the lock (see method
// start), so no need to re-fetch from the stream.
let stream = inner_state.result_stream_mut();
let maybe_batch = stream.next_batch().await.map_err(napi_err_from_kernel)?;
// The IPC schema header serialised into every batch payload
// comes from the cached `self.schema` captured outside the
// lock (see method start), so no need to re-fetch from the
// stream.
// Variant-aware: the executed path auto-closes the server
// statement on drain; the metadata path uses its own
// close-on-drop guard. (See `AnyInner::next_batch`.)
let maybe_batch = inner_state
.next_batch()
.await
.map_err(napi_err_from_kernel)?;
let Some(batch) = maybe_batch else {
// End of stream — record so a defensive cancel after
// natural completion can short-circuit to Ok(()).
Expand Down
67 changes: 62 additions & 5 deletions pyo3/src/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,28 @@ pub(crate) struct OAuthParams {
pub callback_timeout_secs: Option<u64>,
}

/// Default U2M OAuth client id for the **Python** binding.
///
/// 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:
///
/// 1. **OAuth app identity** — the `use_kernel=True` path registers as
/// the same OAuth app the standalone Python connector does, so
/// admin-side consent screens / SSO policies attribute it
/// consistently (not as the generic CLI client).
/// 2. **Per-binding cache-key isolation** — the kernel's U2M token
/// cache is keyed on `{host, client_id, scopes}`. Distinct client
/// ids keep the pyo3 (Python) and napi (Node,
/// `databricks-sql-connector`) caches from colliding.
///
/// Note: this does NOT share a token-cache *entry* with the standalone
/// Thrift connector — the kernel writes to its own
/// `~/.config/databricks-sql-kernel/oauth/` directory, and the Thrift
/// connector caches U2M tokens in-memory only. The alignment is of the
/// OAuth app identity, not the on-disk cache.
const PYSQL_OAUTH_CLIENT_ID: &str = "databricks-sql-python";

/// Build a kernel `AuthConfig` from the Python kwargs the `Session`
/// constructor accepts.
///
Expand Down Expand Up @@ -117,7 +139,7 @@ fn build_auth_config_inner(
if matches!(oauth.client_id.as_deref(), Some("")) {
return Err(
"auth_type='oauth-u2m' client_id must be non-empty when set; \
omit it to use the default 'databricks-cli'"
omit it to use the default 'databricks-sql-python'"
.to_owned(),
);
}
Expand All @@ -136,7 +158,20 @@ fn build_auth_config_inner(
);
}
Ok(AuthConfig::OAuthU2M {
client_id: oauth.client_id,
// 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 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 —
// and the same SSO token cache entry — whether they use
// the Thrift backend or `use_kernel=True`. It also keeps
// the kernel's per-{host,client_id,scopes} token cache
// distinct from the napi (Node) binding's, which defaults
// to its own client.
client_id: oauth
.client_id
.or_else(|| Some(PYSQL_OAUTH_CLIENT_ID.to_owned())),
redirect_port: oauth.redirect_port,
scopes: oauth.scopes,
token_url_override: oauth.token_url,
Expand Down Expand Up @@ -250,8 +285,11 @@ mod tests {
}

#[test]
fn u2m_builds_with_all_defaults_none() {
// U2M takes no mandatory fields; the kernel fills defaults.
fn u2m_defaults_client_id_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.
let cfg = build_auth_config_inner("oauth-u2m", None, OAuthParams::default()).unwrap();
match cfg {
AuthConfig::OAuthU2M {
Expand All @@ -261,7 +299,7 @@ mod tests {
token_url_override,
callback_timeout,
} => {
assert!(client_id.is_none());
assert_eq!(client_id.as_deref(), Some("databricks-sql-python"));
assert!(redirect_port.is_none());
assert!(scopes.is_none());
assert!(token_url_override.is_none());
Expand All @@ -271,6 +309,25 @@ mod tests {
}
}

#[test]
fn u2m_explicit_client_id_overrides_default() {
let cfg = build_auth_config_inner(
"oauth-u2m",
None,
OAuthParams {
client_id: Some("my-custom-app".to_string()),
..Default::default()
},
)
.unwrap();
match cfg {
AuthConfig::OAuthU2M { client_id, .. } => {
assert_eq!(client_id.as_deref(), Some("my-custom-app"));
}
other => panic!("expected OAuthU2M, got {other:?}"),
}
}

#[test]
fn u2m_maps_callback_timeout_secs_to_duration() {
let cfg = build_auth_config_inner(
Expand Down
42 changes: 41 additions & 1 deletion pyo3/src/fetch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
use arrow_array::RecordBatch;
use arrow_pyarrow::ToPyArrow;
use arrow_schema::Schema;
use databricks_sql_kernel::{Error, Result, ResultBatch, ResultStream};
use databricks_sql_kernel::{Error, ExecutedStatement, Result, ResultBatch, ResultStream};
use pyo3::prelude::*;
use std::sync::Arc;
use tokio::runtime::Runtime;
Expand Down Expand Up @@ -65,6 +65,46 @@ pub(crate) fn drain(runtime: &Runtime, stream: &mut ResultStream) -> Result<Vec<
})
}

/// Like [`next_batch`], but drives the `ExecutedStatement` (not a bare
/// `ResultStream`) so the kernel's auto-close-on-drain fires when the
/// stream is exhausted. Used by `ExecutedStatement.fetch_next_batch`.
pub(crate) fn next_batch_exec(
runtime: &Runtime,
exec: &mut ExecutedStatement,
) -> Result<Option<RecordBatch>> {
runtime.block_on(async {
match exec.next_batch().await? {
Some(ResultBatch::Arrow(rb)) => Ok(Some(rb.clone())),
Some(_) => Err(Error::invalid_argument()
.message("kernel returned a non-Arrow ResultBatch variant")),
None => Ok(None),
}
})
}

/// Like [`drain`], but drives the `ExecutedStatement` so auto-close-on-
/// drain fires once the stream is exhausted. Used by
/// `ExecutedStatement.fetch_all_arrow`.
pub(crate) fn drain_exec(
runtime: &Runtime,
exec: &mut ExecutedStatement,
) -> Result<Vec<RecordBatch>> {
runtime.block_on(async {
let mut out = Vec::new();
loop {
match exec.next_batch().await? {
Some(ResultBatch::Arrow(rb)) => out.push(rb.clone()),
Some(_) => {
return Err(Error::invalid_argument()
.message("kernel returned a non-Arrow ResultBatch variant"));
}
None => break,
}
}
Ok(out)
})
}

/// Wrap a Vec of `RecordBatch` into a `pyarrow.Table`. Centralised
/// so both `ExecutedStatement.fetch_all_arrow` and
/// `ResultStream.fetch_all_arrow` produce identical Python objects.
Expand Down
Loading
Loading