diff --git a/.github/workflows/napi-checks.yml b/.github/workflows/napi-checks.yml index 72d07c2f..3ad88d1b 100644 --- a/.github/workflows/napi-checks.yml +++ b/.github/workflows/napi-checks.yml @@ -116,6 +116,15 @@ jobs: # (built below) intentionally omits it and keeps link-time symbols. run: cargo test --locked --features dyn-symbols + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 + with: + node-version: '20' + + - name: Test external authentication from Node + run: | + cargo build --locked + node --test tests/auth-external.test.cjs + # Drift guard for the committed loader (napi/index.js + # napi/index.d.ts). PR #146 review feedback: nothing in CI # detects when a contributor adds a top-level `#[napi]` symbol diff --git a/CONNECTION_PARAMETERS.md b/CONNECTION_PARAMETERS.md index fc6ba26c..97280556 100644 --- a/CONNECTION_PARAMETERS.md +++ b/CONNECTION_PARAMETERS.md @@ -151,9 +151,29 @@ binding additionally exposes `azure-sp-m2m` via `auth_type="azure-sp-m2m"` with the `azure_client_id` / `azure_client_secret` / `azure_tenant_id` (optional) kwargs. -Two further variants are reserved but not usable in v0: +**`External`** — a caller-supplied credentials provider +(`Box`). The kernel calls `TokenProvider::headers` once per +authenticated request, retries included, with no kernel cache; the default +returns `Authorization: Bearer `, and a provider may return extra +headers or omit `Authorization`. Its headers replace configured custom headers +of the same name (case-insensitive). Values with CR, LF or NUL fail the request, +and `User-Agent`, `Content-Type`, `Content-Length`, `Host`, `Transfer-Encoding`, +`Connection`, `Accept-Encoding`, `x-databricks-org-id` and the per-request +`x-databricks-metadata-operation-type`, `x-databricks-sea-can-run-fully-sync`, +and `x-databricks-require-thrift-native-metadata` are ignored. A provider error +fails the request with `Unauthenticated`, without a retry. External authentication +is async-only; the kernel's token-federation exchange does not run for this variant. +Bindings: pyo3 +`auth_type="external"` + `header_provider` (a callable returning a +`dict[str, str]`); napi `authMode: External` + an async `headerProvider` +(second `openSession` argument) returning `HeaderEntry[]`; C ABI +`kernel_session_config_set_auth_external` with a `KernelAuthHeadersCallback`. +The Python and Node bindings reject conflicting token, OAuth, JWT, Azure, +federation and token-cache options with External authentication. + +One further variant is reserved but not usable in v0: `OAuthFederation` (RFC 8693 token exchange — returns `InvalidArgument` -until implemented) and `External` (a caller-supplied `TokenProvider`). +until implemented). ## `DefaultOpts` — session defaults (optional) diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index acd6162e..117940b2 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -22,6 +22,9 @@ changes go in their respective binding's NEXT_CHANGELOG. if the host has credentials, a path, query or fragment. - `ProxyConfig.url`, the Rust ADBC driver's `adbc.databricks.proxy.url`, `HTTPS_PROXY` and `ALL_PROXY` accept SOCKS4 and SOCKS5 proxy URLs. +- Custom credentials providers: `AuthConfig::External` and the C ABI + `kernel_session_config_set_auth_external` call the caller's provider for the + auth headers of every request, so the host can refresh credentials. - Volume `PUT`, `GET` and `REMOVE`: with `StatementSpec::volume` set, executing a statement the server marks as a Volume operation also runs its file transfer. Local paths, with symlinks resolved, must be inside the caller's diff --git a/include/databricks_kernel.h b/include/databricks_kernel.h index 35fc9c4e..79388598 100644 --- a/include/databricks_kernel.h +++ b/include/databricks_kernel.h @@ -243,8 +243,8 @@ typedef struct kernel_result_stream_canceller_t kernel_result_stream_canceller_t * * Build a config, set exactly one connection form and exactly one auth * form, then hand it to `kernel_session_open` (which consumes it). Only - * PAT, OAuth M2M, and OAuth U2M (interactive browser flow) auth are - * exposed over the C ABI. + * PAT, OAuth M2M, OAuth U2M (interactive browser flow) and a host + * credentials callback are exposed over the C ABI. */ KernelStatusCode kernel_session_config_new(KernelSessionConfig** out); void kernel_session_config_free(KernelSessionConfig* config); @@ -325,6 +325,38 @@ KernelStatusCode kernel_session_config_set_auth_azure_sp(KernelSessionConfig* co const char* azure_tenant_id, const char* azure_workspace_resource_id); +/* Host credentials callback. The kernel calls `callback` once per + * authenticated request (retries included, no kernel cache). The callback adds + * headers with kernel_auth_headers_add (usually `Authorization` plus any extra + * headers), which replace custom headers of the same name, and returns 0. Any + * other return fails that request with + * KernelStatusCode_Unauthenticated and no retry; call + * kernel_auth_headers_set_error first to give the reason (no credentials). The + * kernel copies every string before the callback returns. Values with CR, LF or + * NUL fail the request; User-Agent, Content-Type, Content-Length, Host, + * Transfer-Encoding, Connection, Accept-Encoding, x-databricks-org-id and the + * per-request x-databricks-metadata-operation-type, + * x-databricks-sea-can-run-fully-sync and + * x-databricks-require-thrift-native-metadata are ignored. The + * kernel's token-federation exchange does not run for this mode, and + * set_identity_federation_client_id does not apply to it. + * + * The callback runs on kernel threads, possibly concurrently, and must not call + * kernel entry points other than kernel_auth_headers_*. `release` (may be NULL) + * is called exactly once with `user_data` when the kernel no longer needs it: + * after the session is closed and dropped, when the config is freed without + * opening, or when a later set_auth_* call replaces this one. */ +typedef struct KernelAuthHeaders KernelAuthHeaders; +typedef int32_t (*KernelAuthHeadersCallback)(void* user_data, KernelAuthHeaders* headers); +typedef void (*KernelAuthReleaseCallback)(void* user_data); +KernelStatusCode kernel_session_config_set_auth_external(KernelSessionConfig* config, + KernelAuthHeadersCallback callback, + KernelAuthReleaseCallback release, + void* user_data); +KernelStatusCode kernel_auth_headers_add(KernelAuthHeaders* headers, const char* name, + const char* value); +KernelStatusCode kernel_auth_headers_set_error(KernelAuthHeaders* headers, const char* message); + /* Optional SP-wide Workload Identity Federation client id used by mandatory * token exchange. Unset selects BYOT / account-wide WIF. */ KernelStatusCode diff --git a/napi/NEXT_CHANGELOG.md b/napi/NEXT_CHANGELOG.md index f97bd253..cc54059a 100644 --- a/napi/NEXT_CHANGELOG.md +++ b/napi/NEXT_CHANGELOG.md @@ -17,6 +17,9 @@ layout, or npm publishing. Pure-kernel changes go in the root - `ConnectionOptions.port`: an optional connection port. A value outside `0..=65535`, or a host the kernel can't combine with the port, gives `InvalidArgument`. +- `authMode: External` with an async `headerProvider` (the second + `openSession` argument) that returns the request headers, called for every + request. Conflicting token or OAuth options are rejected. - `ExecuteOptions.lz4Compression` overrides Arrow result LZ4 compression per statement. - `ExecuteOptions.volume` (`{ allowedPaths, removeNotFoundIsSuccess? }`): with it, executing a Volume `PUT`, `GET` or `REMOVE` also runs its file transfer. diff --git a/napi/index.d.ts b/napi/index.d.ts index ca7dedfe..7dcc4058 100644 --- a/napi/index.d.ts +++ b/napi/index.d.ts @@ -131,9 +131,8 @@ export interface NamedTypedValueInput { * `'OAuthM2m'`, `'OAuthU2m'`, `'AzureSpM2m'`). * * Mirrors the kernel [`AuthConfig`] variants this binding supports. - * `OAuthFederation` / `External` are intentionally not exposed yet — the - * kernel marks federation as not-yet-implemented and `External` is a - * Rust-trait escape hatch with no JS-callback bridge. + * `OAuthFederation` is intentionally not exposed yet — the kernel marks + * federation as not-yet-implemented. */ export const enum AuthMode { /** Personal access token (`token`). */ @@ -159,7 +158,12 @@ export const enum AuthMode { * `azureWorkspaceResourceId` is set — additionally sends the SP * management token for an RBAC-only service principal. */ - AzureSpM2m = 'AzureSpM2m' + AzureSpM2m = 'AzureSpM2m', + /** + * Caller-supplied credentials: the `headerProvider` passed to + * `openSession`, called once per authenticated request. + */ + External = 'External' } /** * A single extra HTTP header as an explicit `{ name, value }` pair. @@ -241,7 +245,7 @@ export interface ConnectionOptions { authMode?: AuthMode /** * Personal access token. Required (and non-empty) for - * [`AuthMode::Pat`]; ignored otherwise. + * [`AuthMode::Pat`]; rejected for [`AuthMode::External`], ignored otherwise. */ token?: string /** @@ -654,10 +658,17 @@ export interface ConnectionOptions { * `options.auth_mode` (PAT / OAuth M2M / OAuth U2M) — see * [`build_auth_config`]. * + * `headerProvider` is required for, and only allowed with, `authMode` + * `External`. It is an async function returning `HeaderEntry[]` (usually an + * `Authorization` entry plus any extra headers), called once per + * authenticated request with no caching; the kernel's token-federation + * exchange does not run for it. A rejection fails that request. Conflicting + * token, OAuth, JWT, Azure, federation or token-cache options are rejected. + * * The JS-visible name is `openSession` (napi-rs converts snake_case * to camelCase for free functions). */ -export declare function openSession(options: ConnectionOptions): Promise +export declare function openSession(options: ConnectionOptions, headerProvider?: (() => Promise>) | undefined | null): Promise /** * One kernel log event, as handed to JS. `level` is a lower-case string * (`error`/`warn`/`info`/`debug`/`trace`) the Node side maps onto its diff --git a/napi/src/database.rs b/napi/src/database.rs index 634142c9..71c00ada 100644 --- a/napi/src/database.rs +++ b/napi/src/database.rs @@ -33,12 +33,15 @@ use napi::bindgen_prelude::Buffer; #[cfg(test)] type Buffer = Vec; -use databricks_sql_kernel::config::{port_from_value, PortValue}; +use databricks_sql_kernel::config::{port_from_value, HeaderProviderFn, PortValue}; use databricks_sql_kernel::{ AuthConfig, ConnectionConfig, DefaultOpts, DriverSystemConfiguration, Error as KernelError, GeospatialResultRepresentation, HttpConfig, ProxyConfig, ResultConfig, Session, TelemetryConfig, TlsConfig, TokenCacheConfig, }; +use napi::bindgen_prelude::Promise; +use napi::threadsafe_function::ThreadsafeFunction; +use napi::Status; /// NodeJS-driver-appropriate default for `pool_max_idle_per_host`. /// @@ -67,9 +70,8 @@ use crate::util::guarded; /// `'OAuthM2m'`, `'OAuthU2m'`, `'AzureSpM2m'`). /// /// Mirrors the kernel [`AuthConfig`] variants this binding supports. -/// `OAuthFederation` / `External` are intentionally not exposed yet — the -/// kernel marks federation as not-yet-implemented and `External` is a -/// Rust-trait escape hatch with no JS-callback bridge. +/// `OAuthFederation` is intentionally not exposed yet — the kernel marks +/// federation as not-yet-implemented. #[napi(string_enum)] #[derive(Default, Clone, Copy)] pub enum AuthMode { @@ -92,6 +94,97 @@ pub enum AuthMode { /// `azureWorkspaceResourceId` is set — additionally sends the SP /// management token for an RBAC-only service principal. AzureSpM2m, + /// Caller-supplied credentials: the `headerProvider` passed to + /// `openSession`, called once per authenticated request. + External, +} + +/// The JS `headerProvider` callback: an async function, called with no +/// arguments, that resolves to the request headers. Weak (unref'd), like the +/// log sink, so an idle connection does not keep the Node event loop alive; +/// the pending napi call of an in-flight request keeps it alive meanwhile. +pub type HeaderProvider = + ThreadsafeFunction<(), Promise>, (), Status, false, true>; + +/// Map the auth options plus the optional `headerProvider` onto the kernel +/// [`AuthConfig`]. `External` requires a provider; any other mode rejects one. +fn resolve_auth_config( + options: &ConnectionOptions, + header_provider: Option, +) -> napi::Result { + match (options.auth_mode.unwrap_or_default(), header_provider) { + (AuthMode::External, Some(provider)) => { + validate_external_auth_options(options)?; + Ok(external_auth_config(provider)) + } + (_, Some(_)) => Err(napi_err_from_kernel( + KernelError::invalid_argument().message("headerProvider requires authMode External"), + )), + (_, None) => build_auth_config(options), + } +} + +/// Reject credential settings that External would otherwise ignore. +fn validate_external_auth_options(options: &ConnectionOptions) -> napi::Result<()> { + let conflicts = [ + ("token", options.token.is_some()), + ("oauthClientId", options.oauth_client_id.is_some()), + ("oauthClientSecret", options.oauth_client_secret.is_some()), + ("oauthRedirectPort", options.oauth_redirect_port.is_some()), + ("oauthScopes", options.oauth_scopes.is_some()), + ("tokenUrl", options.token_url.is_some()), + ("tokenCacheEnabled", options.token_cache_enabled.is_some()), + ( + "tokenCachePassphrase", + options.token_cache_passphrase.is_some(), + ), + ("jwtKeyFile", options.jwt_key_file.is_some()), + ("jwtKid", options.jwt_kid.is_some()), + ("jwtPassphrase", options.jwt_passphrase.is_some()), + ("jwtAlgorithm", options.jwt_algorithm.is_some()), + ( + "identityFederationClientId", + options.identity_federation_client_id.is_some(), + ), + ("azureClientId", options.azure_client_id.is_some()), + ("azureClientSecret", options.azure_client_secret.is_some()), + ("azureTenantId", options.azure_tenant_id.is_some()), + ( + "azureWorkspaceResourceId", + options.azure_workspace_resource_id.is_some(), + ), + ] + .into_iter() + .filter_map(|(name, present)| present.then_some(name)) + .collect::>(); + if conflicts.is_empty() { + Ok(()) + } else { + Err(napi_err_from_kernel( + KernelError::invalid_argument().message(format!( + "authMode External cannot be combined with {}", + conflicts.join(", ") + )), + )) + } +} + +/// `AuthConfig::External` over the JS callback. The kernel awaits the +/// callback from its runtime thread; the JS thread is never blocked. A +/// rejection fails that request with `Unauthenticated` carrying its message. +/// No caching or federation is added: the Node driver passes its own chain. +fn external_auth_config(provider: HeaderProvider) -> AuthConfig { + let provider = Arc::new(provider); + AuthConfig::External(Box::new(HeaderProviderFn(move || { + let provider = Arc::clone(&provider); + async move { + // The kernel adds the "Custom credentials provider failed" prefix. + let to_kernel = |e: napi::Error| KernelError::unauthenticated().message(e.reason); + let pending = provider.call_async_catch(()).await.map_err(to_kernel)?; + let headers = pending.await.map_err(to_kernel)?; + Ok(headers.into_iter().map(|h| (h.name, h.value)).collect()) + } + }))) } /// A single extra HTTP header as an explicit `{ name, value }` pair. @@ -168,7 +261,7 @@ pub struct ConnectionOptions { /// existing PAT callers pass only `token`). pub auth_mode: Option, /// Personal access token. Required (and non-empty) for - /// [`AuthMode::Pat`]; ignored otherwise. + /// [`AuthMode::Pat`]; rejected for [`AuthMode::External`], ignored otherwise. pub token: Option, /// OAuth client id. Required for [`AuthMode::OAuthM2m`]; optional for /// [`AuthMode::OAuthU2m`] (defaults to `databricks-sql-connector`). @@ -586,6 +679,11 @@ fn build_auth_config(options: &ConnectionOptions) -> napi::Result { options.identity_federation_client_id.clone(), ) .map_err(napi_err_from_kernel), + // The callback arrives as `openSession`'s second argument; see + // `resolve_auth_config`. + AuthMode::External => Err(napi_err_from_kernel( + KernelError::invalid_argument().message("authMode External requires a headerProvider"), + )), } } @@ -822,6 +920,13 @@ fn geospatial_result_representation(enabled: Option) -> GeospatialResultRe /// `options.auth_mode` (PAT / OAuth M2M / OAuth U2M) — see /// [`build_auth_config`]. /// +/// `headerProvider` is required for, and only allowed with, `authMode` +/// `External`. It is an async function returning `HeaderEntry[]` (usually an +/// `Authorization` entry plus any extra headers), called once per +/// authenticated request with no caching; the kernel's token-federation +/// exchange does not run for it. A rejection fails that request. Conflicting +/// token, OAuth, JWT, Azure, federation or token-cache options are rejected. +/// /// The JS-visible name is `openSession` (napi-rs converts snake_case /// to camelCase for free functions). #[allow( @@ -829,7 +934,11 @@ fn geospatial_result_representation(enabled: Option) -> GeospatialResultRe reason = "exported via napi macro codegen; not called from Rust" )] #[napi] -pub async fn open_session(mut options: ConnectionOptions) -> napi::Result { +pub async fn open_session( + mut options: ConnectionOptions, + #[napi(ts_arg_type = "(() => Promise>) | undefined | null")] + header_provider: Option, +) -> napi::Result { guarded(async move { // Cache the napi-rs tokio Handle on the very first async call // so Drop impls (which run on the V8 GC thread, outside any @@ -839,7 +948,7 @@ pub async fn open_session(mut options: ConnectionOptions) -> napi::Result {{ + let mut o = base(); + o.$field = Some($value); + assert_invalid_arg(validate_external_auth_options(&o).unwrap_err(), $name); + }}; + } + conflict!(token, "secret".into(), "token"); + conflict!(oauth_client_id, "id".into(), "oauthClientId"); + conflict!(oauth_client_secret, "secret".into(), "oauthClientSecret"); + conflict!(oauth_redirect_port, 8030, "oauthRedirectPort"); + conflict!(oauth_scopes, vec!["sql".into()], "oauthScopes"); + conflict!(token_url, "url".into(), "tokenUrl"); + conflict!(token_cache_enabled, false, "tokenCacheEnabled"); + conflict!( + token_cache_passphrase, + "secret".into(), + "tokenCachePassphrase" + ); + conflict!(jwt_key_file, "file".into(), "jwtKeyFile"); + conflict!(jwt_kid, "kid".into(), "jwtKid"); + conflict!(jwt_passphrase, "secret".into(), "jwtPassphrase"); + conflict!(jwt_algorithm, "RS256".into(), "jwtAlgorithm"); + conflict!( + identity_federation_client_id, + "id".into(), + "identityFederationClientId" + ); + conflict!(azure_client_id, "id".into(), "azureClientId"); + conflict!(azure_client_secret, "secret".into(), "azureClientSecret"); + conflict!(azure_tenant_id, "tenant".into(), "azureTenantId"); + conflict!( + azure_workspace_resource_id, + "workspace".into(), + "azureWorkspaceResourceId" + ); + } + #[test] fn default_mode_is_pat_and_requires_token() { let mut o = base(); diff --git a/napi/tests/auth-external.test.cjs b/napi/tests/auth-external.test.cjs new file mode 100644 index 00000000..d782175f --- /dev/null +++ b/napi/tests/auth-external.test.cjs @@ -0,0 +1,114 @@ +// Copyright (c) 2026 Databricks, Inc. +// Licensed under the Apache License, Version 2.0. + +// Run after `cargo build --locked`: node --test tests/auth-external.test.cjs. +// NAPI_TEST_BINARY can point to a shared target directory's debug library. +const assert = require('node:assert/strict'); +const { execFile } = require('node:child_process'); +const http = require('node:http'); +const path = require('node:path'); +const { test } = require('node:test'); +const { promisify } = require('node:util'); + +const binary = path.resolve(process.env.NAPI_TEST_BINARY || path.join(__dirname, '../target/debug/libdatabricks_sql_kernel_napi.so')); +const native = { exports: {} }; +process.dlopen(native, binary); +const { openSession } = native.exports; + +async function withServer(run) { + const requests = []; + const server = http.createServer((req, res) => { + requests.push({ method: req.method, url: req.url, headers: req.headers }); + req.resume(); + res.setHeader('Content-Type', 'application/json'); + res.end(JSON.stringify(req.method === 'POST' + ? { session_id: '00000000-0000-0000-0000-000000000001' } + : {})); + }); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + const options = { + hostName: `http://127.0.0.1:${server.address().port}`, + httpPath: '/sql/1.0/warehouses/0000000000000001', + authMode: 'External', + telemetryEnabled: false, + retryMaxAttempts: 1, + socketTimeoutMs: 2000, + customHeaders: [{ name: 'X-Probe', value: 'configured' }], + }; + try { + await run(options, requests); + } finally { + await new Promise((resolve, reject) => server.close((error) => error ? reject(error) : resolve())); + } +} + +test('resolved provider supplies fresh headers and overrides configured headers', async () => { + await withServer(async (options, requests) => { + let calls = 0; + const connection = await openSession(options, async () => [ + { name: 'Authorization', value: `Bearer token-${++calls}` }, + { name: 'X-Probe', value: 'provider' }, + ]); + await connection.close(); + assert.equal(requests.length, 2); + assert.equal(calls, 2); + assert.deepEqual(requests.map((r) => r.headers.authorization), ['Bearer token-1', 'Bearer token-2']); + assert.ok(requests.every((r) => r.headers['x-probe'] === 'provider')); + }); +}); + +test('rejected provider fails unauthenticated before sending a request', async () => { + await withServer(async (options, requests) => { + let calls = 0; + await assert.rejects(openSession(options, async () => { + calls += 1; + throw new Error('provider rejected'); + }), (error) => { + const prefix = '__databricks_error__:'; + assert.ok(error.message.startsWith(prefix), error.message); + const detail = JSON.parse(error.message.slice(prefix.length)); + assert.equal(detail.code, 'Unauthenticated'); + assert.match(detail.message, /provider rejected/); + return true; + }); + assert.equal(calls, 1); + assert.equal(requests.length, 0); + }); +}); + +test('external auth rejects conflicting credentials before calling the provider', async () => { + await withServer(async (options, requests) => { + let calls = 0; + await assert.rejects(openSession({ ...options, token: 'unused' }, async () => { + calls += 1; + return []; + }), (error) => { + const prefix = '__databricks_error__:'; + assert.ok(error.message.startsWith(prefix), error.message); + const detail = JSON.parse(error.message.slice(prefix.length)); + assert.equal(detail.code, 'InvalidArgument'); + assert.match(detail.message, /token/); + return true; + }); + assert.equal(calls, 0); + assert.equal(requests.length, 0); + }); +}); + +test('an idle external-auth connection does not keep Node alive', async () => { + await withServer(async (options, requests) => { + const script = ` + const native = { exports: {} }; + process.dlopen(native, process.argv[1]); + native.exports.openSession(JSON.parse(process.argv[2]), async () => [ + { name: 'Authorization', value: 'Bearer idle' }, + ]).then((connection) => { + global.connection = connection; + console.log('opened'); + }).catch((error) => { console.error(error); process.exitCode = 1; }); + `; + const { stdout } = await promisify(execFile)(process.execPath, ['-e', script, binary, JSON.stringify(options)], { timeout: 10000 }); + assert.match(stdout, /opened/); + assert.ok(requests.some((request) => request.headers.authorization === 'Bearer idle')); + }); +}); diff --git a/pyo3/NEXT_CHANGELOG.md b/pyo3/NEXT_CHANGELOG.md index e86cf6a9..e2067760 100644 --- a/pyo3/NEXT_CHANGELOG.md +++ b/pyo3/NEXT_CHANGELOG.md @@ -16,6 +16,9 @@ changes go in the root `NEXT_CHANGELOG.md`. - `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`). +- `Session(..., auth_type="external", header_provider=...)`: a callable that + returns the request headers, called for every request. Conflicting token or + OAuth options raise `ValueError`. - `Statement.set_lz4_compression` overrides Arrow result LZ4 compression per statement. - `Statement.set_volume_options(allowed_paths, remove_not_found_is_success=False, input_bytes=None)`: with it, executing a Volume `PUT`, `GET` or `REMOVE` also diff --git a/pyo3/src/auth.rs b/pyo3/src/auth.rs index 821871b8..6c9a7aa6 100644 --- a/pyo3/src/auth.rs +++ b/pyo3/src/auth.rs @@ -14,7 +14,7 @@ //! Translate Python auth kwargs into a kernel `AuthConfig`. //! -//! Supports five `auth_type` values: +//! Supports six `auth_type` values: //! //! - `"pat"` — personal access token (`access_token`). //! - `"oauth-m2m"` — OAuth 2.0 client-credentials (service principal): @@ -31,21 +31,27 @@ //! `azure_tenant_id` (auto-discovered from the workspace when omitted) //! / `azure_workspace_resource_id` (opts into the Azure management //! token by setting the management-token resource-id header). +//! - `"external"` — a Python `header_provider` callable, called once per +//! authenticated request (see [`build_external_auth_config`]). //! //! OAuth is **kernel-owned**: the kernel acquires and refreshes tokens //! itself (OIDC discovery against the workspace host, transparent //! refresh for long-running sessions). The Python wrapper only forwards //! the credentials / flow parameters. //! -//! `AuthConfig::OAuthFederation` and `External` remain unwired — the +//! `AuthConfig::OAuthFederation` remains unwired — the //! wrapper rejects unknown `auth_type` values here so the mistake //! surfaces at construction time, not deep inside an HTTP retry loop. +use std::sync::{Arc, Mutex}; use std::time::Duration; -use databricks_sql_kernel::{AuthConfig, TokenCacheConfig}; +use databricks_sql_kernel::config::HeaderProviderFn; +use databricks_sql_kernel::{AuthConfig, Error as KError, TokenCacheConfig}; use pyo3::exceptions::PyValueError; use pyo3::prelude::*; +use pyo3::types::PyDict; +use pyo3::{PyTraverseError, PyVisit}; /// OAuth parameters forwarded from the Python `Session` constructor. /// @@ -362,11 +368,139 @@ fn build_auth_config_inner( } other => Err(format!( "unsupported auth_type {other:?}; expected one of 'pat', 'oauth-m2m', \ - 'oauth-m2m-jwt', 'oauth-u2m', 'azure-sp-m2m'" + 'oauth-m2m-jwt', 'oauth-u2m', 'azure-sp-m2m', 'external'" )), } } +/// Build `AuthConfig::External` for `auth_type="external"` from a Python +/// callable. The kernel calls it once per authenticated request, with the +/// GIL acquired only for the call; it returns the request headers as a +/// `dict[str, str]` (or a list of `(name, value)` pairs). An exception it +/// raises fails that request with `KernelError(code="Unauthenticated")` +/// whose message includes the exception's text. No caching or federation is +/// added: the Python connector passes its own provider chain. +/// +/// The callable is owned by a [`HeaderProviderOwner`]; the returned link is +/// the `Session`'s reference to it, which each child handle clones. +pub(crate) fn build_external_auth_config( + header_provider: Option>, +) -> PyResult<(AuthConfig, ProviderLink)> { + let callable = header_provider + .ok_or_else(|| PyValueError::new_err("auth_type='external' requires header_provider"))?; + if !Python::attach(|py| callable.bind(py).is_callable()) { + return Err(PyValueError::new_err("header_provider must be callable")); + } + let slot: HeaderProviderSlot = Arc::new(Mutex::new(Some(callable))); + let owner = Python::attach(|py| { + let slot = Arc::clone(&slot); + Py::new(py, HeaderProviderOwner { slot }) + })?; + let auth = AuthConfig::External(Box::new(HeaderProviderFn(move || { + let slot = Arc::clone(&slot); + // The GIL wait and the Python call are synchronous: run them on the + // blocking pool so they never hold a runtime worker that other + // in-flight requests need. + async move { + let call = move || Python::attach(|py| call_header_provider(py, &slot)); + match tokio::task::spawn_blocking(call).await { + Ok(headers) => headers, + Err(e) if e.is_panic() => std::panic::resume_unwind(e.into_panic()), + Err(e) => { + Err(KError::io().message(format!("header_provider call did not finish: {e}"))) + } + } + } + }))); + Ok((auth, ProviderLink(Some(owner)))) +} + +/// The `header_provider` callable; `None` once the cycle collector cleared it. +type HeaderProviderSlot = Arc>>>; + +/// The one Python object that reports the `header_provider` callable to the +/// cycle collector. The kernel callback reads the same slot from Rust, which +/// Python cannot see, so the callable's reference is attributed here. +/// +/// Every handle sharing the kernel session (`Session`, `Statement`, +/// `ResultStream`, ...) holds a [`ProviderLink`] to this owner. A reachable +/// handle therefore keeps the callable alive, and a cycle from the provider +/// back to any set of handles is collectable once none is reachable. +#[pyclass(name = "_HeaderProviderOwner")] +pub(crate) struct HeaderProviderOwner { + slot: HeaderProviderSlot, +} + +#[pymethods] +impl HeaderProviderOwner { + fn __traverse__(&self, visit: PyVisit<'_>) -> Result<(), PyTraverseError> { + // A call in flight holds the lock: skipping it only keeps the + // callable alive for this pass. + if let Ok(callable) = self.slot.try_lock() { + visit.call(&*callable)?; + } + Ok(()) + } + + /// Runs only when every handle is unreachable; later provider calls (a + /// best-effort close) fail with `Unauthenticated`. + fn __clear__(&mut self) { + let callable = self.slot.lock().unwrap_or_else(|e| e.into_inner()).take(); + drop(callable); + } +} + +/// A handle's GC-visible reference to its session's [`HeaderProviderOwner`]; +/// empty unless `auth_type="external"`. +#[derive(Default)] +pub(crate) struct ProviderLink(Option>); + +impl ProviderLink { + /// The link for a child handle created from this one. + pub(crate) fn clone_ref(&self, py: Python<'_>) -> Self { + Self(self.0.as_ref().map(|owner| owner.clone_ref(py))) + } + + /// For the holder's `__traverse__`. + pub(crate) fn traverse(&self, visit: &PyVisit<'_>) -> Result<(), PyTraverseError> { + visit.call(&self.0) + } + + /// For the holder's `__clear__`. + pub(crate) fn clear(&mut self) { + self.0 = None; + } +} + +/// Call the Python header provider and convert its result. +fn call_header_provider( + py: Python<'_>, + slot: &Mutex>>, +) -> databricks_sql_kernel::Result> { + // Clone it out so the call runs without the lock held. + let callable = slot + .lock() + .unwrap_or_else(|e| e.into_inner()) + .as_ref() + .map(|callable| callable.clone_ref(py)) + .ok_or_else(|| { + KError::unauthenticated().message("header_provider was released with its Session") + })?; + let to_kernel = |e: PyErr| KError::unauthenticated().message(e.to_string()); + let result = callable.bind(py).call0().map_err(to_kernel)?; + if let Ok(dict) = result.cast::() { + dict.iter() + .map(|(name, value)| Ok((name.extract()?, value.extract()?))) + .collect::>>() + } else { + result.extract::>() + } + .map_err(|_| { + KError::unauthenticated() + .message("header_provider must return a dict of str to str or a list of (str, str)") + }) +} + /// Unwrap an `Option` that must be present and non-empty, /// mapping both the missing and the empty case to the same error /// message. @@ -839,4 +973,65 @@ mod tests { let err = build_auth_config_inner("kerberos", None, OAuthParams::default()).unwrap_err(); assert!(err.contains("unsupported auth_type")); } + + /// A slow Python provider (GIL wait plus call) runs on the blocking pool, + /// so it never holds the runtime's only worker: another task keeps making + /// progress meanwhile. Bounded by the provider's own 10 s wait. + #[test] + fn slow_header_provider_does_not_hold_a_runtime_worker() { + Python::initialize(); + let (callable, entered, release) = Python::attach(|py| -> PyResult<_> { + let globals = PyDict::new(py); + py.run( + c"import threading +entered = threading.Event() +release = threading.Event() +def provider(): + entered.set() + release.wait(10) + return {'Authorization': 'Bearer slow'} +", + Some(&globals), + None, + )?; + let get = |name: &str| -> PyResult> { + Ok(globals.get_item(name)?.expect("defined above").unbind()) + }; + Ok((get("provider")?, get("entered")?, get("release")?)) + }) + .unwrap(); + let (auth, link) = build_external_auth_config(Some(callable)).unwrap(); + let provider = match auth { + AuthConfig::External(provider) => provider, + other => panic!("expected External, got {other:?}"), + }; + let rt = tokio::runtime::Builder::new_multi_thread() + .worker_threads(1) + .enable_all() + .build() + .unwrap(); + let slow_call = rt.spawn(async move { provider.headers().await }); + // `Event.wait` releases the GIL, so the provider can take it. + let started = Python::attach(|py| { + entered + .bind(py) + .call_method1("wait", (10,))? + .extract::() + }) + .unwrap(); + assert!(started, "provider started"); + let (progress_tx, progress) = std::sync::mpsc::channel(); + rt.spawn(async move { + let _ = progress_tx.send(()); + }); + let progressed = progress.recv_timeout(Duration::from_secs(5)).is_ok(); + Python::attach(|py| release.bind(py).call_method0("set").map(drop)).unwrap(); + let headers = rt.block_on(slow_call).unwrap().expect("headers"); + assert!(progressed, "a slow provider held the only runtime worker"); + assert_eq!( + headers, + vec![("Authorization".to_string(), "Bearer slow".to_string())] + ); + Python::attach(|_py| drop((link, entered, release))); + } } diff --git a/pyo3/src/executed_async.rs b/pyo3/src/executed_async.rs index 3f79da65..4845ab1b 100644 --- a/pyo3/src/executed_async.rs +++ b/pyo3/src/executed_async.rs @@ -20,6 +20,7 @@ //! `await_result()` / `fetch_result()`. Mirrors the kernel's //! `executed_async.rs` one-to-one. +use crate::auth::ProviderLink; use crate::errors::to_py_err; use crate::result_stream::ResultStream; use crate::runtime::KernelRuntime; @@ -28,6 +29,7 @@ use databricks_sql_kernel::{ ExecutedAsyncStatement as KExecutedAsyncStatement, ExecutedStatementHandle, StatementStatus, }; use pyo3::prelude::*; +use pyo3::{PyTraverseError, PyVisit}; use std::sync::Arc; #[pyclass(name = "ExecutedAsyncStatement")] @@ -35,6 +37,7 @@ pub(crate) struct ExecutedAsyncStatement { inner: Option, /// Cached statement id so callers can read it after `close()`. statement_id: String, + provider: ProviderLink, } struct ExecutedAsyncInner { @@ -43,17 +46,30 @@ struct ExecutedAsyncInner { } impl ExecutedAsyncStatement { - pub(crate) fn new(exec: KExecutedAsyncStatement, runtime: Arc) -> Self { + pub(crate) fn new( + exec: KExecutedAsyncStatement, + runtime: Arc, + provider: ProviderLink, + ) -> Self { let statement_id = exec.statement_id().to_owned(); Self { statement_id, inner: Some(ExecutedAsyncInner { exec, runtime }), + provider, } } } #[pymethods] impl ExecutedAsyncStatement { + fn __traverse__(&self, visit: PyVisit<'_>) -> Result<(), PyTraverseError> { + self.provider.traverse(&visit) + } + + fn __clear__(&mut self) { + self.provider.clear(); + } + #[getter] fn statement_id(&self) -> &str { &self.statement_id @@ -77,6 +93,7 @@ impl ExecutedAsyncStatement { Ok(AsyncStatementReader { inner: inner.exec.reader().map_err(|error| to_py_err(py, error))?, runtime: Arc::clone(&inner.runtime), + provider: self.provider.clone_ref(py), }) } @@ -113,7 +130,11 @@ impl ExecutedAsyncStatement { let inner = alive!(self, "ExecutedAsyncStatement"); let runtime = inner.runtime.clone(); let stream = run_kernel!(py, runtime, inner.exec.await_result())?; - Ok(ResultStream::new(stream, runtime)) + Ok(ResultStream::new( + stream, + runtime, + self.provider.clone_ref(py), + )) } /// Fetch the result without polling. Raises `KernelError(code= @@ -123,7 +144,11 @@ impl ExecutedAsyncStatement { let inner = alive!(self, "ExecutedAsyncStatement"); let runtime = inner.runtime.clone(); let stream = run_kernel!(py, runtime, inner.exec.fetch_result())?; - Ok(ResultStream::new(stream, runtime)) + Ok(ResultStream::new( + stream, + runtime, + self.provider.clone_ref(py), + )) } /// Cancel the in-flight statement on the server. @@ -164,10 +189,19 @@ impl ExecutedAsyncStatement { pub(crate) struct AsyncStatementReader { inner: KAsyncStatementReader, runtime: Arc, + provider: ProviderLink, } #[pymethods] impl AsyncStatementReader { + fn __traverse__(&self, visit: PyVisit<'_>) -> Result<(), PyTraverseError> { + self.provider.traverse(&visit) + } + + fn __clear__(&mut self) { + self.provider.clear(); + } + #[getter] fn statement_id(&self) -> &str { self.inner.statement_id() @@ -192,14 +226,22 @@ impl AsyncStatementReader { fn await_result(&self, py: Python<'_>) -> PyResult { let runtime = Arc::clone(&self.runtime); let stream = run_kernel!(py, runtime, self.inner.await_result())?; - Ok(ResultStream::new(stream, runtime)) + Ok(ResultStream::new( + stream, + runtime, + self.provider.clone_ref(py), + )) } /// Return a fresh result stream; raises InvalidState if execution is not terminal. fn fetch_result(&self, py: Python<'_>) -> PyResult { let runtime = Arc::clone(&self.runtime); let stream = run_kernel!(py, runtime, self.inner.fetch_result())?; - Ok(ResultStream::new(stream, runtime)) + Ok(ResultStream::new( + stream, + runtime, + self.provider.clone_ref(py), + )) } } diff --git a/pyo3/src/metadata.rs b/pyo3/src/metadata.rs index 8292453e..63824010 100644 --- a/pyo3/src/metadata.rs +++ b/pyo3/src/metadata.rs @@ -41,11 +41,13 @@ //! The outer-scaffolding macro is where the win lives; the inner //! conversions stay explicit and grep-able. +use crate::auth::ProviderLink; use crate::result_stream::ResultStream; use crate::runtime::KernelRuntime; use databricks_sql_kernel::metadata_v0::exact_catalog_and_pattern; use databricks_sql_kernel::{Identifier, LikePattern, Metadata as KMetadata}; use pyo3::prelude::*; +use pyo3::{PyTraverseError, PyVisit}; use std::sync::Arc; /// Python-facing metadata handle. @@ -57,11 +59,24 @@ use std::sync::Arc; pub(crate) struct Metadata { inner: KMetadata, runtime: Arc, + provider: ProviderLink, } impl Metadata { - pub(crate) fn new(inner: KMetadata, runtime: Arc) -> Self { - Self { inner, runtime } + pub(crate) fn new( + inner: KMetadata, + runtime: Arc, + provider: ProviderLink, + ) -> Self { + Self { + inner, + runtime, + provider, + } + } + + fn stream(&self, py: Python<'_>, stream: databricks_sql_kernel::ResultStream) -> ResultStream { + ResultStream::new(stream, self.runtime.clone(), self.provider.clone_ref(py)) } } @@ -70,10 +85,18 @@ impl Metadata { #[pymethods] impl Metadata { + fn __traverse__(&self, visit: PyVisit<'_>) -> Result<(), PyTraverseError> { + self.provider.traverse(&visit) + } + + fn __clear__(&mut self) { + self.provider.clear(); + } + /// All catalogs visible to the session. fn list_catalogs(&self, py: Python<'_>) -> PyResult { let stream = run_kernel_block!(py, self.runtime, { self.inner.list_catalogs().await })?; - Ok(ResultStream::new(stream, self.runtime.clone())) + Ok(self.stream(py, stream)) } /// Schemas filtered by catalog (exact) and schema name pattern. An empty @@ -89,7 +112,7 @@ impl Metadata { let (cat, pat) = exact_catalog_and_pattern(&catalog, &schema_pattern)?; self.inner.list_schemas(cat, pat).await })?; - Ok(ResultStream::new(stream, self.runtime.clone())) + Ok(self.stream(py, stream)) } /// Tables filtered by catalog (**pattern**), schema (pattern), @@ -121,7 +144,7 @@ impl Metadata { let types_slice: Option<&[&str]> = types_owned.as_deref(); self.inner.list_tables(cat, sch, tbl, types_slice).await })?; - Ok(ResultStream::new(stream, self.runtime.clone())) + Ok(self.stream(py, stream)) } /// Columns of tables matching the filter. `catalog = None` emits @@ -143,7 +166,7 @@ impl Metadata { let col = LikePattern::from_opt(&column_pattern)?; self.inner.list_columns(cat, sch, tbl, col).await })?; - Ok(ResultStream::new(stream, self.runtime.clone())) + Ok(self.stream(py, stream)) } /// Primary keys for the given table. All identifiers are exact. @@ -161,7 +184,7 @@ impl Metadata { let tbl = Identifier::new(&table)?; self.inner.primary_keys(cat, sch, tbl).await })?; - Ok(ResultStream::new(stream, self.runtime.clone())) + Ok(self.stream(py, stream)) } /// Foreign-key relationships. The foreign side must be fully @@ -190,7 +213,7 @@ impl Metadata { let ft = Some(Identifier::new(&foreign_table)?); self.inner.foreign_keys(pc, ps, pt, fc, fs, ft).await })?; - Ok(ResultStream::new(stream, self.runtime.clone())) + Ok(self.stream(py, stream)) } /// Functions visible to the session. @@ -208,7 +231,7 @@ impl Metadata { let nam = LikePattern::from_opt(&name_pattern)?; self.inner.functions(cat, sch, nam).await })?; - Ok(ResultStream::new(stream, self.runtime.clone())) + Ok(self.stream(py, stream)) } /// Procedures visible to the session. @@ -226,19 +249,19 @@ impl Metadata { let nam = LikePattern::from_opt(&name_pattern)?; self.inner.procedures(cat, sch, nam).await })?; - Ok(ResultStream::new(stream, self.runtime.clone())) + Ok(self.stream(py, stream)) } /// SQL data types supported by the workspace. No filters; no /// wire call (static in-memory result). fn type_info(&self, py: Python<'_>) -> PyResult { let stream = run_kernel_block!(py, self.runtime, { self.inner.type_info().await })?; - Ok(ResultStream::new(stream, self.runtime.clone())) + Ok(self.stream(py, stream)) } /// All table types. No wire call. fn table_types(&self, py: Python<'_>) -> PyResult { let stream = run_kernel_block!(py, self.runtime, { self.inner.table_types().await })?; - Ok(ResultStream::new(stream, self.runtime.clone())) + Ok(self.stream(py, stream)) } } diff --git a/pyo3/src/result_stream.rs b/pyo3/src/result_stream.rs index 7b2a6334..7057fbf1 100644 --- a/pyo3/src/result_stream.rs +++ b/pyo3/src/result_stream.rs @@ -17,12 +17,14 @@ //! Returned by metadata calls and asynchronous statement reads. Server cleanup //! belongs to the metadata close guard or the asynchronous statement owner. +use crate::auth::ProviderLink; use crate::fetch; use crate::runtime::KernelRuntime; use arrow_pyarrow::ToPyArrow; use arrow_schema::Schema; use databricks_sql_kernel::ResultStream as KResultStream; use pyo3::prelude::*; +use pyo3::{PyTraverseError, PyVisit}; use std::sync::Arc; /// Python-facing borrowed result stream. @@ -32,6 +34,7 @@ pub(crate) struct ResultStream { /// Cached schema — survives `close()` so callers can still read /// the description after exhausting / closing the stream. schema: Arc, + provider: ProviderLink, } struct ResultStreamInner { @@ -41,10 +44,15 @@ struct ResultStreamInner { } impl ResultStream { - pub(crate) fn new(stream: KResultStream, runtime: Arc) -> Self { + pub(crate) fn new( + stream: KResultStream, + runtime: Arc, + provider: ProviderLink, + ) -> Self { let schema = stream.schema(); Self { schema, + provider, inner: Some(ResultStreamInner { stream, runtime, @@ -56,6 +64,14 @@ impl ResultStream { #[pymethods] impl ResultStream { + fn __traverse__(&self, visit: PyVisit<'_>) -> Result<(), PyTraverseError> { + self.provider.traverse(&visit) + } + + fn __clear__(&mut self) { + self.provider.clear(); + } + /// Result schema as a `pyarrow.Schema`. Available even after `close()`. fn arrow_schema<'py>(&self, py: Python<'py>) -> PyResult> { self.schema.as_ref().to_pyarrow(py) diff --git a/pyo3/src/session.rs b/pyo3/src/session.rs index ff74403b..666c1347 100644 --- a/pyo3/src/session.rs +++ b/pyo3/src/session.rs @@ -20,7 +20,7 @@ //! they `block_on` the same pool without keeping the `Session` //! pyclass alive longer than the user keeps a reference. -use crate::auth::{build_auth_config, OAuthParams}; +use crate::auth::{build_auth_config, build_external_auth_config, OAuthParams, ProviderLink}; use crate::executed_async::ExecutedAsyncStatement; use crate::metadata::Metadata; use crate::runtime::KernelRuntime; @@ -31,6 +31,7 @@ use databricks_sql_kernel::{ }; use pyo3::prelude::*; use pyo3::types::{PyBool, PyInt}; +use pyo3::{PyTraverseError, PyVisit}; use std::collections::HashMap; use std::sync::Arc; @@ -48,6 +49,9 @@ pub(crate) struct Session { /// `None` after `close()`. Methods return a clean Python error /// rather than panicking on a closed session. inner: Option, + /// `auth_type="external"` only: the GC-visible link to the + /// `header_provider` callable, cloned into every child handle. + header_provider: ProviderLink, } pub(crate) struct SessionInner { @@ -332,6 +336,11 @@ impl Session { /// (optional `client_id`, `redirect_ports`, `oauth_scopes`, /// `token_url`, `oauth_callback_timeout_secs`). /// + /// - `"external"`: `header_provider`, a callable returning the request + /// headers (`dict[str, str]`, usually `{"Authorization": ...}`). It is + /// called once per authenticated request with no kernel caching, and + /// the kernel's token-federation exchange does not run for it. + /// /// OAuth is kernel-owned: the kernel acquires and transparently /// refreshes tokens itself. /// @@ -395,6 +404,7 @@ impl Session { port=None, auth_type=None, access_token=None, + header_provider=None, client_id=None, client_secret=None, oauth_scopes=None, @@ -461,6 +471,7 @@ impl Session { port: Option>, auth_type: Option, access_token: Option, + header_provider: Option>, client_id: Option, client_secret: Option, oauth_scopes: Option>, @@ -547,6 +558,46 @@ impl Session { )); } }; + if resolved_auth_type == "external" { + let conflicts = [ + ("access_token", access_token.is_some()), + ("client_id", client_id.is_some()), + ("client_secret", client_secret.is_some()), + ("oauth_scopes", oauth_scopes.is_some()), + ("token_url", token_url.is_some()), + ("redirect_ports", redirect_ports.is_some()), + ( + "oauth_callback_timeout_secs", + oauth_callback_timeout_secs.is_some(), + ), + ("jwt_key_file", jwt_key_file.is_some()), + ("jwt_kid", jwt_kid.is_some()), + ("jwt_passphrase", jwt_passphrase.is_some()), + ("jwt_algorithm", jwt_algorithm.is_some()), + ( + "identity_federation_client_id", + identity_federation_client_id.is_some(), + ), + ("azure_client_id", azure_client_id.is_some()), + ("azure_client_secret", azure_client_secret.is_some()), + ("azure_tenant_id", azure_tenant_id.is_some()), + ( + "azure_workspace_resource_id", + azure_workspace_resource_id.is_some(), + ), + ("token_cache_enabled", token_cache_enabled.is_some()), + ("token_cache_passphrase", token_cache_passphrase.is_some()), + ] + .into_iter() + .filter_map(|(name, present)| present.then_some(name)) + .collect::>(); + if !conflicts.is_empty() { + return Err(pyo3::exceptions::PyValueError::new_err(format!( + "auth_type='external' cannot be combined with {}", + conflicts.join(", ") + ))); + } + } let oauth = OAuthParams { client_id, client_secret, @@ -566,7 +617,18 @@ impl Session { token_cache_enabled, token_cache_passphrase, }; - let auth_config = build_auth_config(&resolved_auth_type, access_token, oauth)?; + let (auth_config, header_provider) = match (resolved_auth_type.as_str(), header_provider) { + ("external", provider) => build_external_auth_config(provider)?, + (_, Some(_)) => { + return Err(pyo3::exceptions::PyValueError::new_err( + "header_provider requires auth_type='external'", + )) + } + (_, None) => ( + build_auth_config(&resolved_auth_type, access_token, oauth)?, + ProviderLink::default(), + ), + }; // Build a TLS config only when the caller relaxed or extended // the secure default — otherwise leave the builder on its @@ -701,9 +763,18 @@ impl Session { Ok(Self { inner: Some(SessionInner { session, runtime }), + header_provider, }) } + fn __traverse__(&self, visit: PyVisit<'_>) -> Result<(), PyTraverseError> { + self.header_provider.traverse(&visit) + } + + fn __clear__(&mut self) { + self.header_provider.clear(); + } + /// Server-issued session id. #[getter] fn session_id(&self) -> PyResult { @@ -712,19 +783,21 @@ impl Session { } /// Build a new `Statement` bound to this session. - fn statement(&self) -> PyResult { + fn statement(&self, py: Python<'_>) -> PyResult { let inner = alive!(self, "Session"); let kstmt = inner.session.statement(); - Ok(Statement::new(kstmt, inner.runtime.clone())) + let provider = self.header_provider.clone_ref(py); + Ok(Statement::new(kstmt, inner.runtime.clone(), provider)) } /// Metadata operations bound to this session (flat per-method, /// ODBC-shaped). Returns a fresh `Metadata` handle on every call; /// the handle is cheap to construct and throw away. - fn metadata(&self) -> PyResult { + fn metadata(&self, py: Python<'_>) -> PyResult { let inner = alive!(self, "Session"); let kmeta = inner.session.metadata(); - Ok(Metadata::new(kmeta, inner.runtime.clone())) + let provider = self.header_provider.clone_ref(py); + Ok(Metadata::new(kmeta, inner.runtime.clone(), provider)) } /// Re-attach to an already-submitted server statement by its id, @@ -755,7 +828,8 @@ impl Session { runtime, inner.session.attach_async_statement(statement_id) )?; - Ok(ExecutedAsyncStatement::new(exec, runtime)) + let provider = self.header_provider.clone_ref(py); + Ok(ExecutedAsyncStatement::new(exec, runtime, provider)) } /// Explicitly close the session. Idempotent. Subsequent calls on diff --git a/pyo3/src/statement.rs b/pyo3/src/statement.rs index 3a0904a4..9b2c80d8 100644 --- a/pyo3/src/statement.rs +++ b/pyo3/src/statement.rs @@ -19,6 +19,7 @@ //! (async-consumption). The fetch surface on `ExecutedStatement` //! returns Arrow record batches as pyarrow values. +use crate::auth::ProviderLink; use crate::errors::to_py_err; use crate::executed_async::ExecutedAsyncStatement; use crate::fetch; @@ -32,6 +33,7 @@ use databricks_sql_kernel::{ }; use pyo3::prelude::*; use pyo3::pybacked::PyBackedBytes; +use pyo3::{PyTraverseError, PyVisit}; use std::collections::HashMap; use std::sync::Arc; use tokio_util::bytes::Bytes; @@ -44,6 +46,7 @@ use tokio_util::bytes::Bytes; #[pyclass(name = "Statement")] pub(crate) struct Statement { inner: Option, + provider: ProviderLink, } struct StatementInner { @@ -52,15 +55,28 @@ struct StatementInner { } impl Statement { - pub(crate) fn new(stmt: KStatement, runtime: Arc) -> Self { + pub(crate) fn new( + stmt: KStatement, + runtime: Arc, + provider: ProviderLink, + ) -> Self { Self { inner: Some(StatementInner { stmt, runtime }), + provider, } } } #[pymethods] impl Statement { + fn __traverse__(&self, visit: PyVisit<'_>) -> Result<(), PyTraverseError> { + self.provider.traverse(&visit) + } + + fn __clear__(&mut self) { + self.provider.clear(); + } + /// Set the SQL text to execute. Replaces any previously-set SQL. fn set_sql(&mut self, sql: String) -> PyResult<()> { let inner = alive_mut!(self, "Statement"); @@ -247,11 +263,12 @@ impl Statement { /// Obtain a canceller **before** calling `execute()`; once the /// server issues the statement id mid-execute, `canceller.cancel()` /// reaches it. Cheap; safe to call from another thread. - fn canceller(&self) -> PyResult { + fn canceller(&self, py: Python<'_>) -> PyResult { let inner = alive!(self, "Statement"); Ok(StatementCanceller { inner: inner.stmt.canceller(), runtime: inner.runtime.clone(), + provider: self.provider.clone_ref(py), }) } @@ -264,6 +281,7 @@ impl Statement { /// in-flight future is dropped, firing the kernel's mid-execute /// cancel guard so the server-side statement is cancelled too. fn execute(&mut self, py: Python<'_>) -> PyResult { + let provider = self.provider.clone_ref(py); let inner = alive_mut!(self, "Statement"); let runtime = inner.runtime.clone(); tracing::debug!( @@ -271,7 +289,7 @@ impl Statement { "Statement.execute: running statement synchronously (GIL released, interruptible)" ); let exec = run_kernel_interruptible!(py, &runtime, inner.stmt.execute())?; - Ok(ExecutedStatement::new(exec, runtime)) + Ok(ExecutedStatement::new(exec, runtime, provider)) } /// Submit-and-return. Sends `ExecuteStatement` with @@ -283,6 +301,7 @@ impl Statement { /// Use this path when the caller needs a poll/cancel handle instead of /// waiting synchronously for a terminal state. fn submit(&mut self, py: Python<'_>) -> PyResult { + let provider = self.provider.clone_ref(py); let inner = alive_mut!(self, "Statement"); let runtime = inner.runtime.clone(); tracing::debug!( @@ -290,7 +309,7 @@ impl Statement { "Statement.submit: submitting statement async (GIL released)" ); let exec = run_kernel!(py, runtime, inner.stmt.submit())?; - Ok(ExecutedAsyncStatement::new(exec, runtime)) + Ok(ExecutedAsyncStatement::new(exec, runtime, provider)) } /// Explicit close — cancels and closes any executed handle this @@ -338,6 +357,7 @@ pub(crate) struct ExecutedStatement { /// survives `close()`, like `statement_id` / `schema`. The connector /// surfaces this as `cursor.rowcount`. num_modified_rows: Option, + provider: ProviderLink, } struct ExecutedInner { @@ -347,7 +367,7 @@ struct ExecutedInner { } impl ExecutedStatement { - fn new(exec: KExecutedStatement, runtime: Arc) -> Self { + fn new(exec: KExecutedStatement, runtime: Arc, provider: ProviderLink) -> Self { let statement_id = exec.statement_id().to_owned(); let schema = exec.schema(); let num_modified_rows = exec.num_modified_rows(); @@ -355,6 +375,7 @@ impl ExecutedStatement { statement_id, schema, num_modified_rows, + provider, inner: Some(ExecutedInner { exec, runtime, @@ -366,6 +387,14 @@ impl ExecutedStatement { #[pymethods] impl ExecutedStatement { + fn __traverse__(&self, visit: PyVisit<'_>) -> Result<(), PyTraverseError> { + self.provider.traverse(&visit) + } + + fn __clear__(&mut self) { + self.provider.clear(); + } + #[getter] fn statement_id(&self) -> &str { &self.statement_id @@ -487,10 +516,19 @@ impl ExecutedStatement { pub(crate) struct StatementCanceller { inner: KStatementCanceller, runtime: Arc, + provider: ProviderLink, } #[pymethods] impl StatementCanceller { + fn __traverse__(&self, visit: PyVisit<'_>) -> Result<(), PyTraverseError> { + self.provider.traverse(&visit) + } + + fn __clear__(&mut self) { + self.provider.clear(); + } + /// Server-side cancel of the in-flight statement. /// /// No-op if nothing has executed yet, or the query is still in its diff --git a/pyo3/tests/sql_api.py b/pyo3/tests/sql_api.py index c66ff4bc..9e1801f9 100644 --- a/pyo3/tests/sql_api.py +++ b/pyo3/tests/sql_api.py @@ -23,11 +23,12 @@ @contextmanager -def sql_api(session_type, arrow_bytes=None, statement_response=None): +def sql_api(session_type, arrow_bytes=None, statement_response=None, **auth): state = SimpleNamespace( batches=[[1, 2]] if arrow_bytes else [], mode="buffered", requests=[], + headers=[], statement_bodies=[], chunk_requested=threading.Event(), release_chunk=threading.Event(), @@ -41,6 +42,7 @@ def reply(self): body = self.rfile.read(int(self.headers.get("Content-Length", 0))) path = self.path.split("?")[0] state.requests.append((self.command, path)) + state.headers.append({k.lower(): v for k, v in self.headers.items()}) status, response = 200, {} if self.command == "POST" and path.endswith("/sessions"): response = {"session_id": "00000000-0000-0000-0000-000000000001"} @@ -152,7 +154,7 @@ def log_message(self, *args): state.session = session_type( host=state.host, http_path="/sql/1.0/warehouses/0000000000000001", - access_token="test-token", + **(auth or {"access_token": "test-token"}), telemetry_enabled=False, request_timeout_secs=2, retry_max_attempts=1, diff --git a/pyo3/tests/test_auth.py b/pyo3/tests/test_auth.py index 12bf9138..b21649ec 100644 --- a/pyo3/tests/test_auth.py +++ b/pyo3/tests/test_auth.py @@ -12,18 +12,24 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""Auth surface: input validation. +"""Auth surface: input validation, and the external header provider over a +loopback SQL API. -PAT-only this phase; tests confirm the wrapper rejects unsupported -kwargs at construction time (before any network) rather than -letting the kernel error mid-flight. +Validation tests confirm the wrapper rejects unsupported kwargs at +construction time (before any network) rather than letting the kernel +error mid-flight. """ from __future__ import annotations +import gc +import threading +import weakref + import pytest import databricks_sql_kernel as k +from sql_api import sql_api def test_missing_auth_raises_value_error(): @@ -41,13 +47,61 @@ def test_pat_with_empty_token_raises_value_error(): ) -def test_unsupported_auth_type_raises_value_error(): - with pytest.raises(ValueError, match="unsupported"): +def test_external_auth_type_requires_a_callable_header_provider(): + for kwargs, message in [ + ({}, "requires header_provider"), + ({"header_provider": "not callable"}, "must be callable"), + ]: + with pytest.raises(ValueError, match=message): + k.Session( + host="x.databricks.com", + http_path="/sql/1.0/warehouses/abc", + auth_type="external", + **kwargs, + ) + + +@pytest.mark.parametrize( + "name, value", + [ + ("access_token", "token"), + ("client_id", "client"), + ("client_secret", "secret"), + ("oauth_scopes", ["sql"]), + ("token_url", "https://example.invalid/token"), + ("redirect_ports", [8030]), + ("oauth_callback_timeout_secs", 10), + ("jwt_key_file", "key.pem"), + ("jwt_kid", "kid"), + ("jwt_passphrase", "passphrase"), + ("jwt_algorithm", "RS256"), + ("identity_federation_client_id", "federation"), + ("azure_client_id", "client"), + ("azure_client_secret", "secret"), + ("azure_tenant_id", "tenant"), + ("azure_workspace_resource_id", "workspace"), + ("token_cache_enabled", False), + ("token_cache_passphrase", "passphrase"), + ], +) +def test_external_auth_rejects_other_auth_options(name, value): + with pytest.raises(ValueError, match=name): k.Session( host="x.databricks.com", http_path="/sql/1.0/warehouses/abc", auth_type="external", + header_provider=lambda: {}, + **{name: value}, + ) + + +def test_header_provider_requires_external_auth_type(): + with pytest.raises(ValueError, match="auth_type='external'"): + k.Session( + host="x.databricks.com", + http_path="/sql/1.0/warehouses/abc", access_token="x", + header_provider=lambda: {}, ) @@ -68,3 +122,177 @@ def test_identity_federation_client_id_is_accepted_kwarg(): http_path="/sql/1.0/warehouses/abc", identity_federation_client_id="federation-client", ) + + +def _select(session): + statement = session.statement() + statement.set_sql("SELECT 1") + statement.execute() + statement.close() + + +def test_external_header_provider_runs_per_request(): + calls = [] + + def provider(): + calls.append(threading.get_ident()) + return { + "Authorization": f"Bearer tok-{len(calls)}", + "X-Ddf-Probe": "py", + "User-Agent": "provider-override", + } + + with sql_api(k.Session, auth_type="external", header_provider=provider) as api: + _select(api.session) + _select(api.session) + sent = list(api.headers) + assert len(sent) >= 3 + tokens = [h.get("authorization") for h in sent] + assert all(t and t.startswith("Bearer tok-") for t in tokens), tokens + assert len(set(tokens)) == len(tokens), "a fresh provider call per request" + assert all(h.get("x-ddf-probe") == "py" for h in sent) + assert all(h.get("user-agent") != "provider-override" for h in sent) + assert len(calls) >= len(sent) + + +def test_external_header_provider_without_authorization(): + with sql_api( + k.Session, + auth_type="external", + header_provider=lambda: [("X-Only", "1")], + ) as api: + _select(api.session) + sent = list(api.headers) + assert sent and all("authorization" not in h and h["x-only"] == "1" for h in sent) + + +def test_external_header_provider_exception_fails_without_fallback(): + state = {"fail": False} + + def provider(): + if state["fail"]: + raise RuntimeError("probe provider is down") + return {"Authorization": "Bearer ok"} + + with sql_api(k.Session, auth_type="external", header_provider=provider) as api: + before = len(api.requests) + state["fail"] = True + with pytest.raises(k.KernelError) as err: + _select(api.session) + assert err.value.code == "Unauthenticated" + assert "probe provider is down" in str(err.value) + assert len(api.requests) == before, "nothing sent without a credential" + state["fail"] = False + _select(api.session) + + +@pytest.mark.parametrize( + "result, message", + [ + ({"Authorization": "Bearer a\r\nX-Injected: 1"}, "invalid value"), + ({"Authorization": 1}, "must return a dict"), + ("not headers", "must return a dict"), + ], +) +def test_external_header_provider_bad_result_fails_open(result, message): + with pytest.raises(k.KernelError, match=message) as err: + with sql_api(k.Session, auth_type="external", header_provider=lambda: result): + pass + assert "X-Injected" not in str(err.value) + + +def test_external_header_provider_parallel_statements(): + lock = threading.Lock() + calls = [] + + def provider(): + with lock: + calls.append(1) + return {"Authorization": f"Bearer tok-{len(calls)}"} + + with sql_api(k.Session, auth_type="external", header_provider=provider) as api: + errors = [] + + def run(): + try: + _select(api.session) + except Exception as e: # noqa: BLE001 + errors.append(e) + + threads = [threading.Thread(target=run) for _ in range(4)] + for t in threads: + t.start() + for t in threads: + t.join(timeout=30) + assert not any(t.is_alive() for t in threads), "no deadlock" + assert not errors, errors + posts = [r for r in api.requests if r == ("POST", "/api/2.0/sql/statements")] + assert len(posts) == 4 + + +def test_external_header_provider_session_cycle_is_collected(): + class Provider: + def __call__(self): + return {"Authorization": "Bearer ok"} + + provider = Provider() + with sql_api(k.Session, auth_type="external", header_provider=provider) as api: + _select(api.session) + # provider -> Session -> native callback -> provider + provider.session = api.session + del api.session + alive = weakref.ref(provider) + del provider + gc.collect() + assert alive() is None, "the provider and its Session are collected" + + +def test_external_header_provider_cycle_through_child_handles_is_collected(): + class Provider: + def __call__(self): + return {"Authorization": "Bearer ok"} + + provider = Provider() + with sql_api(k.Session, auth_type="external", header_provider=provider) as api: + _select(api.session) + # provider -> Session, Statement, Metadata, StatementCanceller; each + # handle -> native session -> callback -> provider + provider.session = api.session + provider.statement = api.session.statement() + provider.canceller = provider.statement.canceller() + provider.metadata = api.session.metadata() + provider.statement.set_sql("SELECT 1") + provider.executed = provider.statement.execute() + provider.session.close() + del api.session + alive = weakref.ref(provider) + del provider + gc.collect() + assert alive() is None, "the provider and every handle it retains are collected" + + +def test_external_header_provider_survives_gc_while_a_child_handle_is_reachable(): + calls = [] + + class Provider: + def __call__(self): + calls.append(1) + return {"Authorization": "Bearer ok"} + + provider = Provider() + with sql_api(k.Session, auth_type="external", header_provider=provider) as api: + # The Session is reachable only through the provider cycle, but the + # Statement is still reachable from this frame. + provider.session = api.session + statement = api.session.statement() + del api.session + alive = weakref.ref(provider) + del provider + gc.collect() + assert alive() is not None, "a reachable Statement keeps the provider" + before = len(calls) + statement.set_sql("SELECT 1") + statement.execute() + statement.close() + assert len(calls) > before, "the provider still serves the Statement" + alive().session.close() diff --git a/pyo3/tests/test_volume.py b/pyo3/tests/test_volume.py index 3e15f86a..b14d046a 100644 --- a/pyo3/tests/test_volume.py +++ b/pyo3/tests/test_volume.py @@ -57,6 +57,25 @@ def test_volume_options_and_input_bytes_reach_the_transfer(): assert api.uploaded == b"\x00\xffdata" +def test_external_provider_and_volume_upload(): + with sql_api( + k.Session, + statement_response=instruction("PUT", "__input_stream__"), + auth_type="external", + header_provider=lambda: {"Authorization": "Bearer external"}, + ) as api: + statement = api.session.statement() + statement.set_sql("PUT '__input_stream__' INTO '/Volumes/main/default/files/file'") + statement.set_volume_options([], input_bytes=b"external-data") + assert statement.execute().is_volume_operation + assert api.uploaded == b"external-data" + for (method, path), headers in zip(api.requests, api.headers): + if path.startswith("/api/2.0/sql/"): + assert headers.get("authorization") == "Bearer external" + elif method == "PUT" and path == "/storage/volume": + assert "authorization" not in headers + + def test_local_file_errors_carry_the_os_error_and_path(tmp_path): missing = tmp_path / "missing" with sql_api(k.Session, statement_response=instruction("PUT", str(missing))) as api: diff --git a/src/auth/external.rs b/src/auth/external.rs new file mode 100644 index 00000000..1f23a9bb --- /dev/null +++ b/src/auth/external.rs @@ -0,0 +1,397 @@ +// 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. + +//! [`AuthConfig::External`](crate::AuthConfig::External): a host-supplied +//! credentials provider. +//! +//! The provider runs once per authenticated request, with no kernel cache; the +//! host's own wrapper decides caching and refresh. It is not wrapped by the +//! kernel's token-federation exchange. Its headers are validated before they +//! reach the wire, and an error fails the request without a retry. + +use super::AuthProvider; +use crate::config::TokenProvider; +use crate::kernel_error::{Error, Result}; +use std::sync::Mutex; + +/// Headers the kernel sets itself. A provider cannot override them. +const KERNEL_MANAGED_HEADERS: [&str; 11] = [ + "user-agent", + "content-type", + "content-length", + "host", + "transfer-encoding", + "connection", + "accept-encoding", + "x-databricks-org-id", + "x-databricks-metadata-operation-type", + "x-databricks-sea-can-run-fully-sync", + "x-databricks-require-thrift-native-metadata", +]; + +type Headers = Vec<(String, String)>; + +/// Adapts a [`TokenProvider`] to the kernel's per-request [`AuthProvider`]. +pub(crate) struct ExternalAuthProvider { + provider: Box, + /// Headers from the session-open [`preflight`](AuthProvider::preflight), + /// handed to the next request so it does not call the provider again. + primed: Mutex>, +} + +impl std::fmt::Debug for ExternalAuthProvider { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("ExternalAuthProvider()") + } +} + +impl ExternalAuthProvider { + pub(crate) fn new(provider: Box) -> Self { + Self { + provider, + primed: Mutex::new(None), + } + } + + fn primed(&self) -> std::sync::MutexGuard<'_, Option> { + self.primed.lock().unwrap_or_else(|e| e.into_inner()) + } + + /// Awaits the provider once on the caller's runtime and validates what it + /// returned. Used by every kernel request, so the caller's runtime keeps + /// running other tasks while the provider waits. + async fn call_provider_async(&self) -> Result { + checked(self.provider.headers().await) + } +} + +/// Maps a provider error to `Unauthenticated` and validates the headers. +fn checked(result: Result) -> Result { + let headers = result.map_err(|e| { + Error::unauthenticated() + .message(format!("Custom credentials provider failed: {}", e.message)) + .with_cause(e) + })?; + validate_headers(headers) +} + +/// Rejects names and values that could split or smuggle a header, and drops +/// headers the kernel manages. Never logs values. +fn validate_headers(headers: Vec<(String, String)>) -> Result> { + let mut out = Vec::with_capacity(headers.len()); + for (name, value) in headers { + if reqwest::header::HeaderName::from_bytes(name.as_bytes()).is_err() { + return Err(Error::unauthenticated().message(format!( + "Custom credentials provider returned an invalid header name {name:?}" + ))); + } + if value.contains(['\r', '\n', '\0']) + || reqwest::header::HeaderValue::from_str(&value).is_err() + { + return Err(Error::unauthenticated().message(format!( + "Custom credentials provider returned an invalid value for header {name:?}" + ))); + } + if KERNEL_MANAGED_HEADERS + .iter() + .any(|managed| name.eq_ignore_ascii_case(managed)) + { + crate::klog::debug!( + header = %name, + "ignoring a kernel-managed header from the custom credentials provider" + ); + continue; + } + out.push((name, value)); + } + Ok(out) +} + +#[async_trait::async_trait] +impl AuthProvider for ExternalAuthProvider { + fn get_auth_header(&self) -> Result { + Err(Error::invalid_state().message("External auth is async-only")) + } + + fn extra_headers(&self) -> Result> { + Err(Error::invalid_state().message("External auth is async-only")) + } + + fn request_headers(&self) -> Result { + Err(Error::invalid_state().message("External auth is async-only")) + } + + async fn request_headers_async(&self) -> Result { + let primed = self.primed().take(); + match primed { + Some(headers) => Ok(headers), + None => self.call_provider_async().await, + } + } + + /// One provider call that fails the open on error, as for the other + /// providers. Its headers go to the first request, so the provider runs + /// exactly once per authenticated request. + async fn preflight(&self) -> Result<()> { + let headers = self.call_provider_async().await?; + *self.primed() = Some(headers); + Ok(()) + } +} + +/// Placeholder left in `AuthConfig::External` after the session takes the +/// caller's provider. Never called. +pub(crate) struct ConsumedTokenProvider; + +#[async_trait::async_trait] +impl TokenProvider for ConsumedTokenProvider { + async fn token(&self) -> Result { + Err(Error::invalid_state().message("token provider was moved into the session")) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::atomic::{AtomicUsize, Ordering}; + use std::sync::Arc; + + struct Fixed(Result>, Arc); + + #[async_trait::async_trait] + impl TokenProvider for Fixed { + async fn token(&self) -> Result { + unreachable!("headers() is overridden") + } + async fn headers(&self) -> Result> { + self.1.fetch_add(1, Ordering::SeqCst); + self.0.clone() + } + } + + struct TokenOnly; + + #[async_trait::async_trait] + impl TokenProvider for TokenOnly { + async fn token(&self) -> Result { + Ok("tok-1".to_string()) + } + } + + fn pairs(list: &[(&str, &str)]) -> Headers { + list.iter() + .map(|(n, v)| (n.to_string(), v.to_string())) + .collect() + } + + fn provider(result: Result>) -> (ExternalAuthProvider, Arc) { + let calls = Arc::new(AtomicUsize::new(0)); + let p = ExternalAuthProvider::new(Box::new(Fixed(result, calls.clone()))); + (p, calls) + } + + #[tokio::test(flavor = "multi_thread")] + async fn token_only_provider_defaults_to_bearer_header() { + let p = ExternalAuthProvider::new(Box::new(TokenOnly)); + assert_eq!( + p.request_headers_async().await.unwrap(), + pairs(&[("Authorization", "Bearer tok-1")]) + ); + } + + #[tokio::test(flavor = "multi_thread")] + async fn request_headers_call_the_provider_once() { + let (p, calls) = provider(Ok(pairs(&[ + ("Authorization", "Bearer a"), + ("X-Ddf-Probe", "1"), + ]))); + assert_eq!( + p.request_headers_async().await.unwrap(), + pairs(&[("Authorization", "Bearer a"), ("X-Ddf-Probe", "1")]) + ); + assert_eq!(calls.load(Ordering::SeqCst), 1); + } + + #[tokio::test(flavor = "multi_thread")] + async fn preflight_headers_serve_the_next_request_only() { + let (p, calls) = provider(Ok(pairs(&[("Authorization", "Bearer a")]))); + p.preflight().await.unwrap(); + assert_eq!(calls.load(Ordering::SeqCst), 1); + assert_eq!( + p.request_headers_async().await.unwrap(), + pairs(&[("Authorization", "Bearer a")]) + ); + assert_eq!( + calls.load(Ordering::SeqCst), + 1, + "first request reuses the preflight" + ); + p.request_headers_async().await.unwrap(); + assert_eq!(calls.load(Ordering::SeqCst), 2, "later requests call again"); + } + + #[tokio::test(flavor = "multi_thread")] + async fn failing_preflight_calls_the_provider_once() { + let (p, calls) = provider(Err(Error::io().message("host says no"))); + assert_eq!( + p.preflight().await.unwrap_err().code, + crate::ErrorCode::Unauthenticated + ); + assert_eq!(calls.load(Ordering::SeqCst), 1); + assert!( + p.request_headers_async().await.is_err(), + "nothing primed after a failure" + ); + assert_eq!(calls.load(Ordering::SeqCst), 2); + } + + #[tokio::test(flavor = "current_thread")] + async fn external_sync_methods_reject_without_calling_provider() { + let (p, calls) = provider(Ok(pairs(&[("Authorization", "Bearer a")]))); + assert_eq!( + p.get_auth_header().unwrap_err().code, + crate::ErrorCode::InvalidArgument + ); + assert_eq!( + p.extra_headers().unwrap_err().code, + crate::ErrorCode::InvalidArgument + ); + assert_eq!( + p.request_headers().unwrap_err().code, + crate::ErrorCode::InvalidArgument + ); + assert_eq!(calls.load(Ordering::SeqCst), 0); + } + + /// Answers only through a task spawned on the caller's runtime. + struct ViaCallerTask(tokio::sync::mpsc::Sender>); + + #[async_trait::async_trait] + impl TokenProvider for ViaCallerTask { + async fn token(&self) -> Result { + let (reply, answer) = tokio::sync::oneshot::channel(); + self.0 + .send(reply) + .await + .map_err(|_| Error::io().message("token task gone"))?; + answer + .await + .map_err(|_| Error::io().message("token task dropped the reply")) + } + } + + /// A provider awaiting work scheduled on the caller's own current-thread + /// runtime must finish on the request path (preflight and later + /// requests). Bounded so a regression fails instead of hanging. + #[test] + fn current_thread_request_path_lets_the_caller_runtime_progress() { + let (tx, rx) = std::sync::mpsc::channel(); + std::thread::spawn(move || { + let rt = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .unwrap(); + let got = rt.block_on(async { + let (requests, mut inbox) = + tokio::sync::mpsc::channel::>(1); + tokio::spawn(async move { + let mut n = 0; + while let Some(reply) = inbox.recv().await { + n += 1; + let _ = reply.send(format!("tok-task-{n}")); + } + }); + let p = ExternalAuthProvider::new(Box::new(ViaCallerTask(requests))); + p.preflight().await?; + let first = p.request_headers_async().await?; + let second = p.request_headers_async().await?; + Ok::<_, Error>((first, second)) + }); + let _ = tx.send(got); + }); + let (first, second) = rx + .recv_timeout(std::time::Duration::from_secs(10)) + .expect("provider deadlocked the caller's current-thread runtime") + .unwrap(); + assert_eq!(first, pairs(&[("Authorization", "Bearer tok-task-1")])); + assert_eq!(second, pairs(&[("Authorization", "Bearer tok-task-2")])); + } + + #[tokio::test(flavor = "multi_thread")] + async fn header_validation_cases() { + // (provider headers, expected Ok headers or None for an error) + let cases: Vec<(Headers, Option)> = vec![ + (pairs(&[("X-Only", "1")]), Some(pairs(&[("X-Only", "1")]))), + ( + pairs(&[ + ("Authorization", "Bearer a"), + ("User-Agent", "evil"), + ("content-type", "text/plain"), + ("Host", "evil"), + ("Content-Length", "1"), + ("Transfer-Encoding", "chunked"), + ("Connection", "close"), + ("Accept-Encoding", "br"), + ("X-Databricks-Org-Id", "1"), + ("X-Databricks-Metadata-Operation-Type", "evil"), + ("X-Databricks-Sea-Can-Run-Fully-Sync", "evil"), + ("X-Databricks-Require-Thrift-Native-Metadata", "evil"), + ]), + Some(pairs(&[("Authorization", "Bearer a")])), + ), + ( + pairs(&[("Authorization", "Bearer a\r\nX-Injected: 1")]), + None, + ), + (pairs(&[("Authorization", "Bearer a\n")]), None), + (pairs(&[("Authorization", "Bearer a\0")]), None), + (pairs(&[("Bad Name", "1")]), None), + (pairs(&[("Bad\r\nName", "1")]), None), + ]; + for (input, expected) in cases { + let (p, _) = provider(Ok(input.clone())); + match (p.request_headers_async().await, expected) { + (Ok(got), Some(want)) => assert_eq!(got, want, "{input:?}"), + (Err(e), None) => { + assert_eq!(e.code, crate::ErrorCode::Unauthenticated, "{input:?}"); + assert!( + !e.message.contains("Bearer a"), + "value leaked: {}", + e.message + ); + } + (got, want) => panic!("{input:?}: got {got:?}, want {want:?}"), + } + } + } + + #[tokio::test(flavor = "multi_thread")] + async fn provider_error_carries_the_host_message() { + let (p, calls) = provider(Err(Error::io().message("host says no"))); + let err = p.request_headers_async().await.unwrap_err(); + assert_eq!(err.code, crate::ErrorCode::Unauthenticated); + assert!(err.message.contains("host says no"), "{}", err.message); + assert!(!err.retryable); + assert_eq!(calls.load(Ordering::SeqCst), 1); + } + + #[tokio::test(flavor = "multi_thread")] + async fn external_headers_can_omit_authorization() { + let (p, _) = provider(Ok(pairs(&[("X-Only", "1")]))); + assert_eq!( + p.request_headers_async().await.unwrap(), + pairs(&[("X-Only", "1")]) + ); + } +} diff --git a/src/auth/mod.rs b/src/auth/mod.rs index 7763605e..a57cde10 100644 --- a/src/auth/mod.rs +++ b/src/auth/mod.rs @@ -15,6 +15,7 @@ //! Authentication mechanisms for the Databricks ADBC driver. pub mod config; +pub(crate) mod external; pub mod oauth; pub mod pat; @@ -29,6 +30,7 @@ use crate::kernel_error::Result; use std::fmt::Debug; /// Trait for authentication providers. +#[async_trait::async_trait] pub trait AuthProvider: Send + Sync + Debug { /// Returns the authorization header value for HTTP requests. fn get_auth_header(&self) -> Result; @@ -50,4 +52,98 @@ pub trait AuthProvider: Send + Sync + Debug { fn extra_headers(&self) -> Result> { Ok(Vec::new()) } + + /// All auth headers for one authenticated request, in send order. + /// Defaults to `Authorization` followed by [`extra_headers`](Self::extra_headers). + /// The external provider does not support this synchronous method; its + /// async override calls the host once per request and may omit `Authorization`. + fn request_headers(&self) -> Result> { + let mut headers = vec![("Authorization".to_string(), self.get_auth_header()?)]; + headers.extend(self.extra_headers()?); + Ok(headers) + } + + /// [`request_headers`](Self::request_headers) for the kernel's async + /// request paths. The external provider overrides it to await the host + /// callback on the caller's runtime, so a callback waiting on other tasks + /// of that runtime (even a current-thread one) can finish. + async fn request_headers_async(&self) -> Result> { + self.request_headers() + } + + /// Authenticates once at session open so a failure surfaces before any + /// request. Defaults to fetching (and so caching) the request headers. + /// The external provider keeps its headers for the first request instead. + async fn preflight(&self) -> Result<()> { + self.request_headers_async().await.map(drop) + } +} + +/// Whether `name` is one of a request's auth headers (case-insensitive). +/// Auth headers replace every same-named header the kernel would also send, +/// as on the Thrift connectors, so a refreshed credential never travels next +/// to a stale configured one. +pub(crate) fn replaced_by_auth(auth_headers: &[(String, String)], name: &str) -> bool { + auth_headers + .iter() + .any(|(auth_name, _)| auth_name.eq_ignore_ascii_case(name)) +} + +#[cfg(test)] +pub(crate) mod test_headers { + use super::AuthProvider; + use crate::kernel_error::Result; + + #[derive(Debug)] + pub(crate) struct FixedAuthHeaders(pub Vec<(String, String)>); + + impl AuthProvider for FixedAuthHeaders { + fn get_auth_header(&self) -> Result { + unreachable!("request_headers() is overridden") + } + + fn request_headers(&self) -> Result> { + Ok(self.0.clone()) + } + } + + fn pairs(list: &[(&str, &str)]) -> Vec<(String, String)> { + list.iter() + .map(|(n, v)| (n.to_string(), v.to_string())) + .collect() + } + + type CollisionCase = ( + Vec<(String, String)>, + Vec<(String, String)>, + Vec<(&'static str, Vec<&'static str>)>, + ); + + pub(crate) fn collision_cases() -> Vec { + vec![ + ( + pairs(&[("X-Credential", "old"), ("X-Static", "keep")]), + pairs(&[("Authorization", "Bearer t"), ("x-credential", "fresh")]), + vec![ + ("x-credential", vec!["fresh"]), + ("authorization", vec!["Bearer t"]), + ("x-static", vec!["keep"]), + ], + ), + ( + pairs(&[("x-token", "stale")]), + pairs(&[("X-Token", "new")]), + vec![("x-token", vec!["new"]), ("authorization", vec![])], + ), + ( + pairs(&[("X-Multi", "stale")]), + pairs(&[ + ("Authorization", "Bearer t"), + ("X-Multi", "a"), + ("x-multi", "b"), + ]), + vec![("x-multi", vec!["a", "b"])], + ), + ] + } } diff --git a/src/c_abi/session.rs b/src/c_abi/session.rs index f10dcb96..17623032 100644 --- a/src/c_abi/session.rs +++ b/src/c_abi/session.rs @@ -17,8 +17,9 @@ //! Auth over the C ABI: **PAT, OAuth M2M (shared-secret and JWT //! private-key), OAuth U2M** (interactive browser flow), and **Azure Entra //! service-principal M2M** are all exposed (`set_auth_pat` / `set_auth_m2m` / -//! `set_auth_m2m_jwt` / `set_auth_u2m` / `set_auth_azure_sp`). A host may also -//! drive its own token flow and inject it via PAT. +//! `set_auth_m2m_jwt` / `set_auth_u2m` / `set_auth_azure_sp`). A host that +//! drives its own token flow supplies headers per request with +//! `set_auth_external`. //! //! Transaction control (autocommit / commit / rollback) is exposed via //! `kernel_session_set_autocommit` / `_get_autocommit` / `_commit` / @@ -35,7 +36,7 @@ use crate::logging::{LoggingOutcome, LoggingSink}; use crate::session::Session; use crate::telemetry::DriverSystemConfiguration; use std::collections::HashMap; -use std::ffi::{c_char, CStr}; +use std::ffi::{c_char, c_void, CStr}; use std::time::Duration; /// Opaque session handle. Boxed [`Session`] on the Rust side. @@ -69,8 +70,9 @@ enum ConnectionSpec { } /// Auth choice captured from the C-side setters. The C ABI wires PAT, -/// OAuth M2M (shared-secret and JWT private-key), OAuth U2M, and Azure Entra -/// service-principal M2M; other [`AuthConfig`] variants stay Rust-crate-only. +/// OAuth M2M (shared-secret and JWT private-key), OAuth U2M, Azure Entra +/// service-principal M2M and a host credentials callback; `OAuthFederation` +/// stays Rust-crate-only. /// /// NOTE (secret handling): `token` / `client_secret` / `jwt_passphrase` /// are copied out of the C string into owned `String`s and are not @@ -121,6 +123,129 @@ enum AuthSpec { azure_tenant_id: Option, azure_workspace_resource_id: Option, }, + /// Host credentials callback, called once per authenticated request. + External(ExternalAuthCallback), +} + +/// Kernel-owned header list that a [`KernelAuthHeadersCallback`] fills through +/// [`kernel_auth_headers_add`]. Valid only for the duration of the callback. +pub struct KernelAuthHeaders { + headers: Vec<(String, String)>, + error: Option, +} + +/// Host callback that supplies the auth headers for one request. +/// +/// It fills `headers` with [`kernel_auth_headers_add`] (usually one +/// `Authorization` entry plus any extra headers) and returns `0`. Any other +/// return value fails the request; the callback may first describe the failure +/// with [`kernel_auth_headers_set_error`]. The kernel copies every string before +/// the callback returns. The callback runs on kernel threads, possibly +/// concurrently, and must not call kernel entry points other than +/// `kernel_auth_headers_*`. +pub type KernelAuthHeadersCallback = + unsafe extern "C" fn(user_data: *mut c_void, headers: *mut KernelAuthHeaders) -> i32; + +/// Optional host callback that releases `user_data` once the kernel no longer +/// needs it: when the session is closed and dropped, when the config is freed +/// without opening, or when a later `set_auth_*` call replaces it. +pub type KernelAuthReleaseCallback = unsafe extern "C" fn(user_data: *mut c_void); + +/// The callback registered by [`kernel_session_config_set_auth_external`]. +pub(crate) struct ExternalAuthCallback { + callback: KernelAuthHeadersCallback, + release: Option, + user_data: *mut c_void, +} + +// SAFETY: the setter's contract requires the callback and `user_data` to be +// usable from any thread; the kernel never dereferences `user_data` itself. +unsafe impl Send for ExternalAuthCallback {} +unsafe impl Sync for ExternalAuthCallback {} + +impl Drop for ExternalAuthCallback { + fn drop(&mut self) { + if let Some(release) = self.release { + // SAFETY: called once, after the last use of `user_data`. + unsafe { release(self.user_data) }; + } + } +} + +impl ExternalAuthCallback { + fn call(&self) -> Result, Error> { + let mut out = KernelAuthHeaders { + headers: Vec::new(), + error: None, + }; + // SAFETY: the host's callback contract; `out` outlives the call. + let status = unsafe { (self.callback)(self.user_data, &mut out) }; + if status != 0 { + let detail = out + .error + .unwrap_or_else(|| format!("callback returned status {status}")); + return Err(Error::unauthenticated().message(detail)); + } + Ok(out.headers) + } +} + +/// Add one header to the list a [`KernelAuthHeadersCallback`] is filling. Both +/// strings are copied. +/// +/// # Safety +/// `headers` must be the pointer passed to the running callback; `name` and +/// `value` must be NUL-terminated C strings. +#[no_mangle] +pub unsafe extern "C" fn kernel_auth_headers_add( + headers: *mut KernelAuthHeaders, + name: *const c_char, + value: *const c_char, +) -> KernelStatusCode { + on_auth_headers(headers, |h| { + let name = required_str(name, "name")?; + let value = required_str(value, "value")?; + h.headers.push((name, value)); + Ok(()) + }) +} + +/// Describe why a [`KernelAuthHeadersCallback`] is about to return non-zero. +/// The message becomes the request's error. It is copied; do not include +/// credentials. +/// +/// # Safety +/// `headers` must be the pointer passed to the running callback; `message` must +/// be a NUL-terminated C string. +#[no_mangle] +pub unsafe extern "C" fn kernel_auth_headers_set_error( + headers: *mut KernelAuthHeaders, + message: *const c_char, +) -> KernelStatusCode { + on_auth_headers(headers, |h| { + h.error = Some(required_str(message, "message")?); + Ok(()) + }) +} + +/// Shared body of the `kernel_auth_headers_*` functions. +/// +/// # Safety +/// `headers` must be null or the pointer passed to the running callback. +unsafe fn on_auth_headers( + headers: *mut KernelAuthHeaders, + f: impl FnOnce(&mut KernelAuthHeaders) -> Result<(), Error>, +) -> KernelStatusCode { + super::catch_ffi(|| { + let result = match headers.as_mut() { + Some(h) => f(h), + None => Err(Error::invalid_argument().message("headers must not be null")), + }; + match result { + Ok(()) => KernelStatusCode::Success, + Err(e) => crate::c_abi::error::store_and_code(e), + } + }) } /// C-side session config builder state. @@ -608,6 +733,48 @@ pub unsafe extern "C" fn kernel_session_config_set_auth_azure_sp( }) } +/// Set a host credentials callback. The kernel calls `callback` once per +/// authenticated request (retries included, no kernel cache) and sends the +/// headers it adds, replacing custom headers of the same name; see +/// [`KernelAuthHeadersCallback`]. A non-zero return fails +/// that request with `Unauthenticated` and no retry. Values with CR, LF or NUL +/// fail the request; kernel-managed headers (`User-Agent`, `Content-Type`, +/// `Content-Length`, `Host`, `Transfer-Encoding`, `Connection`, +/// `Accept-Encoding`, `x-databricks-org-id`, `x-databricks-metadata-operation-type`, +/// `x-databricks-sea-can-run-fully-sync`, and +/// `x-databricks-require-thrift-native-metadata`) are ignored. The kernel's +/// token-federation exchange does not run for this mode, and `set_identity_federation_client_id` does not +/// apply to it. Mutually exclusive with the other `set_auth_*` setters — the +/// last one called wins. +/// +/// `release`, if non-null, is called exactly once with `user_data` when the +/// kernel no longer needs it (see [`KernelAuthReleaseCallback`]). If this call +/// fails, `release` is not called and the caller keeps `user_data`. +/// +/// # Safety +/// `config` must be a live config handle. `callback` and `release` must be +/// safe to call from any thread with `user_data` until `release` runs. +#[no_mangle] +pub unsafe extern "C" fn kernel_session_config_set_auth_external( + config: *mut KernelSessionConfig, + callback: Option, + release: Option, + user_data: *mut c_void, +) -> KernelStatusCode { + // Built only after the checks pass, so a rejected call never runs `release` + // and the caller keeps `user_data`. + set_on_config(config, |c| { + let callback = callback + .ok_or_else(|| Error::invalid_argument().message("callback must not be null"))?; + c.auth = Some(AuthSpec::External(ExternalAuthCallback { + callback, + release, + user_data, + })); + Ok(()) + }) +} + /// Set the optional SP-wide Workload Identity Federation client id used by /// mandatory token exchange. Leaving it unset selects BYOT / account-wide WIF. /// @@ -1735,6 +1902,24 @@ fn auth_spec_to_config( azure_workspace_resource_id, identity_federation_client_id, )?, + AuthSpec::External(callback) => { + // Dropping the provider drops the last `Arc`, which runs `release`. + let callback = std::sync::Arc::new(callback); + AuthConfig::External(Box::new(crate::config::HeaderProviderFn(move || { + let callback = std::sync::Arc::clone(&callback); + // The host call is synchronous: run it on the blocking pool so + // a slow callback never holds a runtime worker that other + // in-flight requests need. + async move { + match tokio::task::spawn_blocking(move || callback.call()).await { + Ok(headers) => headers, + Err(e) if e.is_panic() => std::panic::resume_unwind(e.into_panic()), + Err(e) => Err(Error::io() + .message(format!("custom credentials callback did not finish: {e}"))), + } + } + }))) + } }; Ok(auth) } @@ -2120,6 +2305,21 @@ mod tests { use super::*; use std::ffi::CString; + #[test] + fn auth_headers_catches_panics_and_stores_internal_error() { + let mut headers = KernelAuthHeaders { + headers: Vec::new(), + error: None, + }; + let status = unsafe { on_auth_headers(&mut headers, |_| panic!("header panic")) }; + assert_eq!(status, KernelStatusCode::Internal); + let mut out = std::mem::MaybeUninit::::uninit(); + assert!(unsafe { crate::c_abi::error::kernel_get_last_error(out.as_mut_ptr()) }); + let error = unsafe { out.assume_init() }; + let message = unsafe { CStr::from_ptr(error.message) }.to_str().unwrap(); + assert!(message.contains("header panic")); + } + #[test] fn tls_client_certificate_setter_stores_both_values() { unsafe { @@ -2599,6 +2799,80 @@ mod tests { } } + /// A slow host callback runs on the blocking pool, so it never holds the + /// runtime's only worker: another task keeps making progress meanwhile. + /// Bounded, so a regression fails instead of hanging. + #[test] + fn slow_external_callback_does_not_hold_a_runtime_worker() { + use std::sync::{mpsc, Mutex}; + + struct Gate { + entered: Mutex>, + release: Mutex>, + } + + unsafe extern "C" fn slow(user_data: *mut c_void, out: *mut KernelAuthHeaders) -> i32 { + let gate = &*(user_data as *const Gate); + let _ = gate.entered.lock().unwrap().send(()); + let _ = gate + .release + .lock() + .unwrap() + .recv_timeout(Duration::from_secs(10)); + let name = CString::new("Authorization").unwrap(); + let value = CString::new("Bearer slow").unwrap(); + assert_eq!( + kernel_auth_headers_add(out, name.as_ptr(), value.as_ptr()), + KernelStatusCode::Success + ); + 0 + } + + let (entered_tx, entered) = mpsc::channel(); + let (release, release_rx) = mpsc::channel(); + let gate = Box::new(Gate { + entered: Mutex::new(entered_tx), + release: Mutex::new(release_rx), + }); + let auth = auth_spec_to_config( + AuthSpec::External(ExternalAuthCallback { + callback: slow, + release: None, + user_data: &*gate as *const Gate as *mut c_void, + }), + None, + None, + None, + TokenCacheConfig::default(), + ) + .expect("external"); + let provider = match auth { + AuthConfig::External(provider) => provider, + other => panic!("expected External, got {other:?}"), + }; + let rt = tokio::runtime::Builder::new_multi_thread() + .worker_threads(1) + .enable_all() + .build() + .unwrap(); + let slow_call = rt.spawn(async move { provider.headers().await }); + entered + .recv_timeout(Duration::from_secs(10)) + .expect("callback started"); + let (progress_tx, progress) = mpsc::channel(); + rt.spawn(async move { + let _ = progress_tx.send(()); + }); + let progressed = progress.recv_timeout(Duration::from_secs(5)).is_ok(); + let _ = release.send(()); + let headers = rt.block_on(slow_call).unwrap().expect("headers"); + assert!(progressed, "a slow callback held the only runtime worker"); + assert_eq!( + headers, + vec![("Authorization".to_string(), "Bearer slow".to_string())] + ); + } + #[test] fn resolve_log_level_preserves_shared_c_abi_semantics() { let off = CString::new("oFf").unwrap(); diff --git a/src/client/http.rs b/src/client/http.rs index 2a9a9a8c..3841724d 100644 --- a/src/client/http.rs +++ b/src/client/http.rs @@ -890,6 +890,16 @@ impl DatabricksHttpClient { provider.extra_headers() } + /// All auth headers for one authenticated request (`Authorization` plus + /// any extra auth headers), from a single provider call. Errors if the + /// auth provider has not been set. + pub async fn auth_request_headers(&self) -> Result> { + let provider = self.auth_provider.get().ok_or_else(|| { + Error::invalid_state().message("Auth provider not set. Call set_auth_provider() first.") + })?; + provider.request_headers_async().await + } + /// Returns the retry config for the given request category. fn retry_config(&self, category: RequestCategory) -> &RetryConfig { self.retry_configs @@ -990,6 +1000,18 @@ impl DatabricksHttpClient { // Build a fresh request for this attempt let mut req_builder = self.client.request(method.clone(), url.clone()); + // `Authorization` plus extra auth headers (the Azure SP + // management-token pair, or a custom provider's headers), from + // one provider call per attempt. Applied only on authenticated + // requests, never on the token/OIDC calls that use + // `execute_without_auth`. They replace same-named headers below. + let auth_headers = if with_auth { + self.auth_request_headers().await? + } else { + Vec::new() + }; + let replaced = |name: &str| crate::auth::replaced_by_auth(&auth_headers, name); + // Caller-supplied custom headers go on FIRST, so the // kernel's own auth / routing headers (set last, below) take // precedence — matching the Thrift connector, where @@ -1030,23 +1052,24 @@ impl DatabricksHttpClient { ); continue; } + if replaced(name) { + debug!(header = %name, "custom header replaced by an auth header"); + continue; + } req_builder = req_builder.header(name, value); } for (name, value) in headers.iter() { - req_builder = req_builder.header(name, value); + if !replaced(name.as_str()) { + req_builder = req_builder.header(name, value); + } } if with_auth { if !self.config.sea_response_compression_enabled { req_builder = req_builder.header("Accept-Encoding", "identity"); } - let auth_header = self.auth_header()?; - req_builder = req_builder.header("Authorization", auth_header); - // Extra auth headers (Azure SP management-token pair). Empty for - // every other provider. Applied only on authenticated requests, - // never on the token/OIDC calls that use `execute_without_auth`. - for (name, value) in self.auth_extra_headers()? { + for (name, value) in auth_headers { req_builder = req_builder.header(name, value); } } @@ -1424,6 +1447,107 @@ mod tests { // custom header + caller UA present AND auth = real-token. } + use crate::auth::test_headers::{collision_cases, FixedAuthHeaders}; + + /// Every value of `name` on a received request, in order. + fn wire_values(request: &wiremock::Request, name: &str) -> Vec { + request + .headers + .get_all(name) + .iter() + .map(|v| v.to_str().unwrap().to_string()) + .collect() + } + + #[tokio::test] + async fn auth_headers_replace_same_named_custom_headers() { + let server = wiremock::MockServer::start().await; + for (custom, auth, expected) in collision_cases() { + server.reset().await; + wiremock::Mock::given(wiremock::matchers::any()) + .respond_with(wiremock::ResponseTemplate::new(200)) + .mount(&server) + .await; + let config = HttpClientConfig { + custom_headers: custom.clone(), + ..HttpClientConfig::default() + }; + let client = DatabricksHttpClient::new(config, default_retry_configs()).unwrap(); + client.set_auth_provider(Arc::new(FixedAuthHeaders(auth.clone()))); + let req = client + .inner() + .request(reqwest::Method::GET, format!("{}/probe", server.uri())) + .build() + .unwrap(); + client + .execute(req, RequestType::GetStatementStatus) + .await + .expect("request"); + let received = server.received_requests().await.unwrap(); + assert_eq!(received.len(), 1); + for (name, want) in expected { + assert_eq!( + wire_values(&received[0], name), + want, + "{name}: custom {custom:?}, auth {auth:?}" + ); + } + } + } + + #[tokio::test] + async fn external_provider_cannot_override_per_request_routing_headers() { + let server = wiremock::MockServer::start().await; + wiremock::Mock::given(wiremock::matchers::any()) + .respond_with(wiremock::ResponseTemplate::new(200)) + .mount(&server) + .await; + let client = DatabricksHttpClient::with_default_retry(HttpClientConfig::default()).unwrap(); + let provider = crate::config::HeaderProviderFn(|| async { + Ok(vec![ + ("Authorization".into(), "Bearer test".into()), + ( + "X-Databricks-Metadata-Operation-Type".into(), + "wrong".into(), + ), + ("X-Databricks-Sea-Can-Run-Fully-Sync".into(), "wrong".into()), + ( + "X-Databricks-Require-Thrift-Native-Metadata".into(), + "wrong".into(), + ), + ]) + }); + client.set_auth_provider(Arc::new(crate::auth::external::ExternalAuthProvider::new( + Box::new(provider), + ))); + let req = client + .inner() + .get(format!("{}/probe", server.uri())) + .header("x-databricks-metadata-operation-type", "GetCatalogs") + .header("x-databricks-sea-can-run-fully-sync", "true") + .header("x-databricks-require-thrift-native-metadata", "true") + .build() + .unwrap(); + client + .execute(req, RequestType::GetStatementStatus) + .await + .unwrap(); + let requests = server.received_requests().await.unwrap(); + assert_eq!(requests.len(), 1); + assert_eq!( + wire_values(&requests[0], "x-databricks-metadata-operation-type"), + vec!["GetCatalogs"] + ); + assert_eq!( + wire_values(&requests[0], "x-databricks-sea-can-run-fully-sync"), + vec!["true"] + ); + assert_eq!( + wire_values(&requests[0], "x-databricks-require-thrift-native-metadata"), + vec!["true"] + ); + } + #[tokio::test] async fn authenticated_requests_use_identity_encoding_by_default() { use wiremock::matchers::{header, method, path}; diff --git a/src/config.rs b/src/config.rs index f5d2f53a..95f57401 100644 --- a/src/config.rs +++ b/src/config.rs @@ -630,9 +630,11 @@ pub enum AuthConfig { audience: String, }, - /// Caller-supplied token provider for custom auth flows. The - /// kernel calls [`TokenProvider::token`] whenever it needs an - /// Authorization header. + /// Caller-supplied credentials provider for custom auth flows. The + /// kernel calls [`TokenProvider::headers`] (by default `Authorization: + /// Bearer `) on every authenticated request and does not cache + /// the result. The kernel's token-federation exchange does not wrap this + /// variant: a host that federates does so inside its own provider. External(Box), } @@ -824,16 +826,64 @@ impl AuthConfig { /// mechanism (Azure AD MSAL, GCP ADC, AWS STS exchange, …) into the /// kernel without the kernel needing to know the protocol details. /// -/// The kernel calls `token` whenever it needs to populate an -/// `Authorization: Bearer …` header. Implementations should cache -/// the token themselves and respect their own expiry; the kernel -/// does not cache across calls. +/// The kernel calls [`headers`](Self::headers) once per authenticated +/// HTTP request. Implementations should cache the token themselves and +/// respect their own expiry; the kernel does not cache across calls. #[async_trait::async_trait] pub trait TokenProvider: Send + Sync { - /// Return a fresh access token. Called once per HTTP request - /// that needs authentication; implementations are expected to - /// cache and refresh internally. + /// Return a fresh access token. Used by the default + /// [`headers`](Self::headers); implementations are expected to cache + /// and refresh internally. async fn token(&self) -> crate::kernel_error::Result; + + /// Return the headers for one authenticated request: usually + /// `Authorization`, plus any extra headers the provider sends with it. + /// Defaults to `Authorization: Bearer `. + /// + /// Names are case-insensitive, and these headers replace configured + /// custom headers of the same name. Values containing CR, LF or NUL fail the + /// request. Headers the kernel manages (`User-Agent`, `Content-Type`, + /// `Content-Length`, `Host`, `Transfer-Encoding`, `Connection`, + /// `Accept-Encoding`, `x-databricks-org-id`, and the per-request SEA routing + /// headers `x-databricks-metadata-operation-type`, + /// `x-databricks-sea-can-run-fully-sync`, and + /// `x-databricks-require-thrift-native-metadata`) are ignored. An error fails + /// the request without a retry. External authentication is async-only. + async fn headers(&self) -> crate::kernel_error::Result> { + let token = self.token().await?; + Ok(vec![( + "Authorization".to_string(), + format!("Bearer {token}"), + )]) + } +} + +/// A [`TokenProvider`] from a closure that returns the request headers, for +/// bindings that bridge a host-language callback. `token()` returns the +/// `Authorization: Bearer` value of those headers. +pub struct HeaderProviderFn(pub F); + +#[async_trait::async_trait] +impl TokenProvider for HeaderProviderFn +where + F: Fn() -> Fut + Send + Sync, + Fut: std::future::Future>> + Send, +{ + async fn token(&self) -> crate::kernel_error::Result { + self.headers() + .await? + .into_iter() + .find(|(name, _)| name.eq_ignore_ascii_case("authorization")) + .and_then(|(_, value)| value.strip_prefix("Bearer ").map(str::to_owned)) + .ok_or_else(|| { + crate::kernel_error::Error::unauthenticated() + .message("custom credentials provider returned no bearer token") + }) + } + + async fn headers(&self) -> crate::kernel_error::Result> { + (self.0)().await + } } impl std::fmt::Debug for AuthConfig { diff --git a/src/feature_flags/mod.rs b/src/feature_flags/mod.rs index 197ad0a6..60264580 100644 --- a/src/feature_flags/mod.rs +++ b/src/feature_flags/mod.rs @@ -201,7 +201,7 @@ impl FeatureFlagResolver { CacheLookup::Missing => { // Token acquisition can include an interactive login and must // finish before the connector-service timeout starts. - let request = match self.authenticated_request() { + let request = match self.authenticated_request().await { Ok(request) => request, Err(error) => { self.warn_fetch_failure(error); @@ -229,7 +229,7 @@ impl FeatureFlagResolver { } CacheLookup::Stale(stale) => { let loader = async { - let request = self.authenticated_request()?; + let request = self.authenticated_request().await?; self.fetch_values(request).await }; match self.cache.refresh(key, loader).await { @@ -327,7 +327,7 @@ impl FeatureFlagResolver { REQUEST_TIMEOUT.min(self.http_client.config().read_timeout) } - fn authenticated_request(&self) -> Result { + async fn authenticated_request(&self) -> Result { let url = build_endpoint(&self.host, &self.identity)?; let mut request = self .http_client @@ -336,15 +336,19 @@ impl FeatureFlagResolver { .timeout(self.request_timeout()); // Match the authenticated request header contract without routing this - // simple GET through the SQL request retry/idempotency machinery. + // simple GET through the SQL request retry/idempotency machinery. Auth + // headers replace same-named custom headers. + let auth_headers = self.http_client.auth_request_headers().await?; for (name, value) in &self.http_client.config().custom_headers { let lower_name = name.to_ascii_lowercase(); - if lower_name != "authorization" && lower_name != "x-databricks-org-id" { + if lower_name != "authorization" + && lower_name != "x-databricks-org-id" + && !crate::auth::replaced_by_auth(&auth_headers, name) + { request = request.header(name, value); } } - request = request.header("Authorization", self.http_client.auth_header()?); - for (name, value) in self.http_client.auth_extra_headers()? { + for (name, value) in auth_headers { request = request.header(name, value); } if let Some(org_id) = &self.http_client.config().org_id { @@ -617,6 +621,48 @@ mod tests { assert_eq!(resolver.get_bool("example.flag").await, Some(true)); } + /// Auth headers replace same-named custom headers (case-insensitive) on the + /// feature-flag GET too, keeping the provider's own multiple values. + #[tokio::test] + async fn auth_headers_replace_same_named_custom_headers() { + use crate::auth::test_headers::{collision_cases, FixedAuthHeaders}; + + for (custom, auth, expected) in collision_cases() { + let http_client = Arc::new( + DatabricksHttpClient::new( + HttpClientConfig { + custom_headers: custom.clone(), + ..HttpClientConfig::default() + }, + HashMap::new(), + ) + .unwrap(), + ); + http_client.set_auth_provider(Arc::new(FixedAuthHeaders(auth.clone()))); + let resolver = FeatureFlagResolver::with_cache( + "https://workspace.example.com", + http_client, + ClientIdentity::new(ClientType::Go, "1.2.3"), + Arc::new(FeatureFlagCache::default()), + ); + let request = resolver + .authenticated_request() + .await + .unwrap() + .build() + .unwrap(); + for (name, want) in expected { + let got: Vec<&str> = request + .headers() + .get_all(name) + .iter() + .map(|v| v.to_str().unwrap()) + .collect(); + assert_eq!(got, want, "{name}: custom {custom:?}, auth {auth:?}"); + } + } + } + #[tokio::test] async fn feature_flag_transport_timeout_preserves_timeout_code() { let server = MockServer::start().await; @@ -648,7 +694,7 @@ mod tests { ); let error = resolver - .fetch(resolver.authenticated_request().unwrap()) + .fetch(resolver.authenticated_request().await.unwrap()) .await .err() .expect("delayed response should exceed the request timeout"); diff --git a/src/session.rs b/src/session.rs index 16b151ef..cb79e993 100644 --- a/src/session.rs +++ b/src/session.rs @@ -403,13 +403,13 @@ impl Session { // 2. Auth provider — async because OAuth flows hit the OIDC // discovery endpoint. let auth_provider: Arc = - build_auth_provider(&config.auth, &host, &http_client).await?; - http_client.set_auth_provider(auth_provider); + build_auth_provider(&mut config.auth, &host, &http_client).await?; + http_client.set_auth_provider(Arc::clone(&auth_provider)); // Authenticate before the feature-flag prefetch, which swallows its // errors: otherwise a failed token request is sent again by - // CreateSession. Both reuse the token cached here. - http_client.auth_header()?; - http_client.auth_extra_headers()?; + // CreateSession. Both reuse the token cached here; an External + // provider hands these headers to the first request instead. + auth_provider.preflight().await?; // 3. Transport. Two-phase: the result-reader factory needs a // reference back to the transport, which owns the factory via @@ -1427,10 +1427,23 @@ fn resolve_u2m_bundle( /// Build the auth provider for a given [`AuthConfig`]. `host` is the /// workspace URL — used for OIDC discovery on M2M / U2M flows. async fn build_auth_provider( - auth: &AuthConfig, + auth: &mut AuthConfig, host: &str, http_client: &Arc, ) -> Result> { + // A host-supplied provider runs per request and is not wrapped by the + // kernel federation exchange: a host that federates does it in its own + // provider, so wrapping it here would exchange twice. The session takes + // the provider; the config keeps a placeholder for telemetry. + if let AuthConfig::External(provider) = auth { + let provider = std::mem::replace( + provider, + Box::new(crate::auth::external::ConsumedTokenProvider), + ); + return Ok(Arc::new(crate::auth::external::ExternalAuthProvider::new( + provider, + ))); + } // Build the base provider for the configured auth flow, then wrap it with // mandatory OIDC token exchange (BYOT federation). The wrapper is a no-op // for non-JWT and same-host-issuer tokens, so it is safe to apply @@ -1601,8 +1614,10 @@ async fn build_base_auth_provider( } AuthConfig::OAuthFederation { .. } => Err(Error::invalid_argument() .message("AuthConfig::OAuthFederation is reserved for v0.1; not yet wired")), - AuthConfig::External(_) => Err(Error::invalid_argument() - .message("AuthConfig::External is reserved; v0 wires PAT + OAuthM2M + OAuthU2M only")), + AuthConfig::External(_) => { + Err(Error::invalid_state() + .message("AuthConfig::External is built by build_auth_provider")) + } } } diff --git a/tests/c/session_smoke.c b/tests/c/session_smoke.c index 34b80cb6..425f24bc 100644 --- a/tests/c/session_smoke.c +++ b/tests/c/session_smoke.c @@ -149,6 +149,85 @@ static void test_open_unreachable_host_errors(void) { CHECK(err.message != NULL, "error has a message"); } +/* Host credentials callback. Session open asks for the auth headers before + * any network I/O, so a failing or invalid callback fails open fast. */ +typedef struct { + int calls; + int releases; + const char* mode; /* "fail" or "crlf" */ +} ExternalProbe; + +static int32_t probe_headers(void* user_data, KernelAuthHeaders* headers) { + ExternalProbe* probe = (ExternalProbe*)user_data; + probe->calls++; + if (strcmp(probe->mode, "fail") == 0) { + (void)kernel_auth_headers_set_error(headers, "probe provider says no"); + return 1; + } + (void)kernel_auth_headers_add(headers, "Authorization", "Bearer tok\r\nX-Injected: 1"); + return 0; +} + +static void probe_release(void* user_data) { ((ExternalProbe*)user_data)->releases++; } + +static void test_auth_external_setter(void) { + KernelSessionConfig* config = NULL; + ExternalProbe probe = {0, 0, "fail"}; + + /* Rejected calls never take ownership of user_data. */ + KernelStatusCode rc = kernel_session_config_set_auth_external(NULL, probe_headers, + probe_release, &probe); + CHECK(rc == KernelStatusCode_InvalidArgument, "set_auth_external(NULL cfg) → InvalidArgument"); + (void)kernel_session_config_new(&config); + rc = kernel_session_config_set_auth_external(config, NULL, probe_release, &probe); + CHECK(rc == KernelStatusCode_InvalidArgument, + "set_auth_external(NULL callback) → InvalidArgument"); + CHECK(probe.releases == 0, "rejected set_auth_external does not release user_data"); + + /* Replacing the callback releases it exactly once. */ + rc = kernel_session_config_set_auth_external(config, probe_headers, probe_release, &probe); + CHECK(rc == KernelStatusCode_Success, "set_auth_external succeeds"); + rc = kernel_session_config_set_auth_pat(config, "dapi-not-a-real-token"); + CHECK(probe.releases == 1, "a later set_auth_* releases the callback once"); + kernel_session_config_free(config); + CHECK(probe.releases == 1 && probe.calls == 0, "replaced callback is never called"); + + /* A failing callback fails open with its message, once, without retry. */ + config = NULL; + probe.releases = 0; + (void)kernel_session_config_new(&config); + (void)kernel_session_config_set_warehouse(config, "https://192.0.2.1", "wh123"); + (void)kernel_session_config_set_auth_external(config, probe_headers, probe_release, &probe); + kernel_session_t* session = NULL; + rc = kernel_session_open(config, &session); + CHECK(rc == KernelStatusCode_Unauthenticated, "failing callback → Unauthenticated"); + CHECK(session == NULL, "session stays null when the callback fails"); + KernelError err; + memset(&err, 0, sizeof(err)); + CHECK(kernel_get_last_error(&err) && err.message != NULL && + strstr(err.message, "probe provider says no") != NULL, + "open error carries the callback's message"); + CHECK(probe.calls == 1, "failing callback is called once (fail fast, no retry)"); + CHECK(probe.releases == 1, "failed open releases user_data once"); + + /* A header value with CR/LF is rejected and never echoed. */ + config = NULL; + probe = (ExternalProbe){0, 0, "crlf"}; + (void)kernel_session_config_new(&config); + (void)kernel_session_config_set_warehouse(config, "https://192.0.2.1", "wh123"); + (void)kernel_session_config_set_auth_external(config, probe_headers, probe_release, &probe); + rc = kernel_session_open(config, &session); + CHECK(rc == KernelStatusCode_Unauthenticated, "CR/LF header value → Unauthenticated"); + memset(&err, 0, sizeof(err)); + CHECK(kernel_get_last_error(&err) && err.message != NULL && + strstr(err.message, "X-Injected") == NULL, + "CR/LF rejection does not echo the value"); + CHECK(probe.releases == 1, "CR/LF failure releases user_data once"); + + rc = kernel_auth_headers_add(NULL, "Authorization", "Bearer x"); + CHECK(rc == KernelStatusCode_InvalidArgument, "auth_headers_add(NULL) → InvalidArgument"); +} + /* http_path + M2M setters accept valid input. */ static void test_http_path_and_m2m_setters(void) { KernelSessionConfig* config = NULL; @@ -493,6 +572,7 @@ int main(void) { test_null_guards(); test_open_requires_connection_and_auth(); test_open_unreachable_host_errors(); + test_auth_external_setter(); test_http_path_and_m2m_setters(); test_port_setter(); test_setter_null_arg_rejected(); diff --git a/tests/external_auth_wiremock.rs b/tests/external_auth_wiremock.rs new file mode 100644 index 00000000..efcaa9e8 --- /dev/null +++ b/tests/external_auth_wiremock.rs @@ -0,0 +1,678 @@ +// 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. + +//! `AuthConfig::External` end to end against a mocked SEA server, through the +//! Rust API and the C ABI: the provider runs once per authenticated request +//! (retries included), its headers reach every request, errors fail only the +//! affected operation, and the kernel federation exchange never runs. + +use std::ffi::{c_void, CString}; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::sync::Arc; +use std::time::Duration; + +use arrow_array::{Int64Array, RecordBatch}; +use arrow_ipc::writer::StreamWriter; +use arrow_schema::{DataType, Field, Schema}; +use base64::engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD}; +use base64::Engine; +use databricks_sql_kernel::config::TokenProvider; +use databricks_sql_kernel::{ + AuthConfig, ConnectionConfig, Error, ErrorCode, ExecutedStatementHandle, HttpConfig, Session, +}; +use serde_json::json; +use wiremock::matchers::{method, path}; +use wiremock::{Mock, MockServer, Request, Respond, ResponseTemplate}; + +const WAREHOUSE: &str = "test_wh"; +const SESSIONS: &str = "/api/2.0/sql/warehouses/test_wh/sessions"; +const STATEMENTS: &str = "/api/2.0/sql/statements"; + +/// A fake, unsigned JWT from a foreign issuer: the kernel federation exchange +/// would try to swap it if it wrapped `External`. +fn foreign_jwt(jti: usize) -> String { + let payload = URL_SAFE_NO_PAD.encode( + json!({"iss": "https://idp.example.com", "sub": "probe", "jti": jti, "exp": 4_102_444_800i64}) + .to_string(), + ); + format!("e30.{payload}.sig") +} + +/// Provider that returns a fresh token on every call (`Bearer tok-` or a +/// foreign JWT), an extra header and `User-Agent` / `Accept-Encoding` override +/// attempts, and can be switched to fail. +#[derive(Default)] +struct CountingProvider { + calls: AtomicUsize, + fail: AtomicBool, + jwt: bool, + no_authorization: bool, +} + +#[async_trait::async_trait] +impl TokenProvider for CountingProvider { + async fn token(&self) -> databricks_sql_kernel::Result { + unreachable!("headers() is overridden") + } + + async fn headers(&self) -> databricks_sql_kernel::Result> { + let n = self.calls.fetch_add(1, Ordering::SeqCst) + 1; + if self.fail.load(Ordering::SeqCst) { + return Err(Error::io().message("probe provider is down")); + } + let mut headers = vec![ + ("X-Ddf-Probe".to_string(), format!("p{n}")), + ("User-Agent".to_string(), "provider-override".to_string()), + ("Accept-Encoding".to_string(), "br".to_string()), + ]; + if !self.no_authorization { + let token = if self.jwt { + foreign_jwt(n) + } else { + format!("tok-{n}") + }; + headers.insert(0, ("Authorization".to_string(), format!("Bearer {token}"))); + } + Ok(headers) + } +} + +/// Shares one provider between the session and the test. +struct Shared(Arc); + +#[async_trait::async_trait] +impl TokenProvider for Shared { + async fn token(&self) -> databricks_sql_kernel::Result { + self.0.token().await + } + async fn headers(&self) -> databricks_sql_kernel::Result> { + self.0.headers().await + } +} + +/// Implements only `token()`, so the default `headers()` applies. +struct TokenOnly; + +#[async_trait::async_trait] +impl TokenProvider for TokenOnly { + async fn token(&self) -> databricks_sql_kernel::Result { + Ok("tok-default".to_string()) + } +} + +fn select_one_body(statement_id: &str) -> String { + let schema = Arc::new(Schema::new(vec![Field::new("n", DataType::Int64, false)])); + let batch = RecordBatch::try_new(schema, vec![Arc::new(Int64Array::from(vec![1]))]).unwrap(); + let mut ipc = Vec::new(); + { + let mut writer = StreamWriter::try_new(&mut ipc, &batch.schema()).unwrap(); + writer.write(&batch).unwrap(); + writer.finish().unwrap(); + } + json!({ + "statement_id": statement_id, + "status": {"state": "SUCCEEDED"}, + "manifest": { + "format": "ARROW_STREAM", + "schema": {"column_count": 1, "columns": [ + {"name": "n", "type_name": "BIGINT", "type_text": "BIGINT", "position": 0} + ]}, + "total_chunk_count": 1, "total_row_count": 1, + "total_byte_count": ipc.len(), "truncated": false, + }, + "result": {"chunk_index": 0, "row_offset": 0, "row_count": 1, + "byte_count": ipc.len(), "attachment": STANDARD.encode(&ipc)}, + }) + .to_string() +} + +async fn mock_warehouse() -> MockServer { + let server = MockServer::start().await; + Mock::given(method("POST")) + .and(path(SESSIONS)) + .respond_with( + ResponseTemplate::new(200) + .set_body_string(r#"{"session_id":"sess-ext","warehouse_id":"test_wh"}"#), + ) + .mount(&server) + .await; + Mock::given(method("POST")) + .and(path(STATEMENTS)) + .respond_with(ResponseTemplate::new(200).set_body_string(select_one_body("stmt-ext"))) + .mount(&server) + .await; + Mock::given(method("DELETE")) + .respond_with(ResponseTemplate::new(200).set_body_string("{}")) + .mount(&server) + .await; + server +} + +async fn open(server: &MockServer, auth: AuthConfig) -> databricks_sql_kernel::Result { + open_with_headers(server, auth, Vec::new()).await +} + +async fn open_with_headers( + server: &MockServer, + auth: AuthConfig, + custom_headers: Vec<(String, String)>, +) -> databricks_sql_kernel::Result { + let mut http = HttpConfig::default(); + http.retry_max_retries = 0; + http.custom_headers = custom_headers; + Session::builder() + .connection( + ConnectionConfig::from_http_path( + server.uri(), + &format!("/sql/1.0/warehouses/{WAREHOUSE}"), + ) + .unwrap(), + ) + .auth(auth) + .http(http) + .open() + .await +} + +async fn select_one(session: &Session) -> databricks_sql_kernel::Result<()> { + let mut stmt = session.statement(); + stmt.spec().sql("SELECT 1 AS n"); + let mut exec = stmt.execute().await?; + while exec.result_stream_mut().next_batch().await?.is_some() {} + exec.close().await +} + +/// Requests to the SQL API (session, statement, close), in arrival order. +async fn sql_requests(server: &MockServer) -> Vec { + server + .received_requests() + .await + .unwrap_or_default() + .into_iter() + .filter(|r| r.url.path().starts_with("/api/2.0/sql/")) + .collect() +} + +fn header<'a>(request: &'a Request, name: &str) -> Option<&'a str> { + request.headers.get(name).and_then(|v| v.to_str().ok()) +} + +#[tokio::test(flavor = "multi_thread")] +async fn provider_headers_reach_every_request_and_refresh_per_request() { + let server = mock_warehouse().await; + let provider = Arc::new(CountingProvider { + jwt: true, + ..Default::default() + }); + let session = open( + &server, + AuthConfig::External(Box::new(Shared(provider.clone()))), + ) + .await + .expect("open"); + select_one(&session).await.expect("first query"); + select_one(&session).await.expect("second query"); + session.close().await.expect("close"); + + let requests = sql_requests(&server).await; + assert!( + requests.len() >= 5, + "session, 2 statements, closes: {}", + requests.len() + ); + let mut seen = std::collections::HashSet::new(); + for r in &requests { + let auth = header(r, "authorization").expect("Authorization on every request"); + assert!( + auth.starts_with("Bearer e30."), + "provider token on the wire: {auth}" + ); + assert!( + seen.insert(auth.to_string()), + "a fresh provider call per request" + ); + assert!( + header(r, "x-ddf-probe").is_some(), + "extra header on every request" + ); + assert_ne!(header(r, "user-agent"), Some("provider-override")); + assert_eq!(header(r, "accept-encoding"), Some("identity")); + } + assert!(provider.calls.load(Ordering::SeqCst) >= requests.len()); + let exchanges = server + .received_requests() + .await + .unwrap_or_default() + .iter() + .filter(|r| r.url.path() == "/oidc/v1/token") + .count(); + assert_eq!( + exchanges, 0, + "the kernel federation exchange does not wrap External" + ); +} + +#[tokio::test(flavor = "current_thread")] +async fn token_only_provider_sends_bearer_on_a_current_thread_runtime() { + let server = mock_warehouse().await; + let session = open(&server, AuthConfig::External(Box::new(TokenOnly))) + .await + .expect("open"); + select_one(&session).await.expect("query"); + for r in sql_requests(&server).await { + assert_eq!(header(&r, "authorization"), Some("Bearer tok-default")); + } +} + +/// Gets its token from a task on the session's own runtime. +struct ViaRuntimeTask(tokio::sync::mpsc::Sender>); + +#[async_trait::async_trait] +impl TokenProvider for ViaRuntimeTask { + async fn token(&self) -> databricks_sql_kernel::Result { + let (reply, answer) = tokio::sync::oneshot::channel(); + let gone = || Error::io().message("token task gone"); + self.0.send(reply).await.map_err(|_| gone())?; + answer.await.map_err(|_| gone()) + } +} + +/// A provider awaiting a task scheduled on the session's current-thread +/// runtime: open, a query and close must all finish. Runs on its own thread +/// so a deadlock fails the test after 30 s instead of hanging it. +#[test] +fn provider_awaiting_the_session_runtime_completes_on_a_current_thread_runtime() { + let (done, outcome) = std::sync::mpsc::channel(); + std::thread::spawn(move || { + let rt = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .unwrap(); + let result = rt.block_on(async { + let server = mock_warehouse().await; + let (requests, mut inbox) = + tokio::sync::mpsc::channel::>(1); + tokio::spawn(async move { + while let Some(reply) = inbox.recv().await { + let _ = reply.send("tok-task".to_string()); + } + }); + let session = open( + &server, + AuthConfig::External(Box::new(ViaRuntimeTask(requests))), + ) + .await?; + select_one(&session).await?; + session.close().await?; + let requests = sql_requests(&server).await; + Ok::<_, Error>( + requests + .iter() + .map(|r| header(r, "authorization").map(str::to_string)) + .collect::>(), + ) + }); + let _ = done.send(result); + }); + let seen = outcome + .recv_timeout(Duration::from_secs(30)) + .expect("provider deadlocked the session's current-thread runtime") + .expect("open, query and close"); + assert!(!seen.is_empty()); + for auth in seen { + assert_eq!(auth.as_deref(), Some("Bearer tok-task")); + } +} + +#[tokio::test(flavor = "multi_thread")] +async fn provider_without_authorization_sends_only_its_headers() { + let server = mock_warehouse().await; + let provider = CountingProvider { + no_authorization: true, + ..Default::default() + }; + let session = open(&server, AuthConfig::External(Box::new(provider))) + .await + .expect("open"); + select_one(&session).await.expect("query"); + for r in sql_requests(&server).await { + assert_eq!(header(&r, "authorization"), None); + assert!(header(&r, "x-ddf-probe").is_some()); + } +} + +/// A provider header replaces a configured header of the same name (any case), +/// as on Thrift, so a stale static value never rides next to the fresh one. +#[tokio::test(flavor = "multi_thread")] +async fn provider_headers_replace_same_named_configured_headers() { + for no_authorization in [false, true] { + let server = mock_warehouse().await; + let provider = CountingProvider { + no_authorization, + ..Default::default() + }; + let custom = vec![ + ("x-ddf-probe".to_string(), "stale".to_string()), + ("X-Static".to_string(), "keep".to_string()), + ]; + let session = open_with_headers(&server, AuthConfig::External(Box::new(provider)), custom) + .await + .expect("open"); + select_one(&session).await.expect("query"); + session.close().await.expect("close"); + let requests = sql_requests(&server).await; + assert!(!requests.is_empty()); + for r in &requests { + let probe: Vec<_> = r.headers.get_all("x-ddf-probe").iter().collect(); + assert_eq!( + probe.len(), + 1, + "one value (no_authorization={no_authorization})" + ); + assert!( + probe[0].to_str().unwrap().starts_with('p'), + "the provider value wins: {:?}", + probe[0] + ); + assert_eq!(header(r, "x-static"), Some("keep")); + assert_eq!(header(r, "authorization").is_some(), !no_authorization); + } + } +} + +#[tokio::test(flavor = "multi_thread")] +async fn provider_error_at_open_fails_fast_without_a_request() { + let server = mock_warehouse().await; + let provider = Arc::new(CountingProvider::default()); + provider.fail.store(true, Ordering::SeqCst); + let err = open( + &server, + AuthConfig::External(Box::new(Shared(provider.clone()))), + ) + .await + .expect_err("open must fail"); + assert_eq!(err.code, ErrorCode::Unauthenticated); + assert!( + err.message.contains("probe provider is down"), + "{}", + err.message + ); + assert_eq!(provider.calls.load(Ordering::SeqCst), 1, "no retry"); + assert!(sql_requests(&server).await.is_empty(), "nothing sent"); +} + +/// The open-time check reuses its headers for CreateSession, so the provider +/// runs exactly once per authenticated request, as on the Thrift baseline. +#[tokio::test(flavor = "multi_thread")] +async fn provider_calls_equal_authenticated_requests() { + let server = mock_warehouse().await; + let provider = Arc::new(CountingProvider::default()); + let session = open( + &server, + AuthConfig::External(Box::new(Shared(provider.clone()))), + ) + .await + .expect("open"); + assert_eq!(sql_requests(&server).await.len(), 1, "CreateSession only"); + assert_eq!( + provider.calls.load(Ordering::SeqCst), + 1, + "no extra preflight call" + ); + session.close().await.expect("close"); + assert_eq!(sql_requests(&server).await.len(), 2, "plus CloseSession"); + assert_eq!(provider.calls.load(Ordering::SeqCst), 2); +} + +#[tokio::test(flavor = "multi_thread")] +async fn provider_error_mid_session_fails_only_that_operation() { + let server = mock_warehouse().await; + let provider = Arc::new(CountingProvider::default()); + let session = open( + &server, + AuthConfig::External(Box::new(Shared(provider.clone()))), + ) + .await + .expect("open"); + let before = sql_requests(&server).await.len(); + + provider.fail.store(true, Ordering::SeqCst); + let calls = provider.calls.load(Ordering::SeqCst); + let err = select_one(&session).await.expect_err("query must fail"); + assert_eq!(err.code, ErrorCode::Unauthenticated); + assert!( + err.message.contains("probe provider is down"), + "{}", + err.message + ); + assert_eq!( + provider.calls.load(Ordering::SeqCst), + calls + 1, + "fail fast" + ); + assert_eq!(sql_requests(&server).await.len(), before, "nothing sent"); + + provider.fail.store(false, Ordering::SeqCst); + select_one(&session).await.expect("the session still works"); +} + +/// Answers 503 to the first `CreateSession`, then succeeds. +struct FlakySessionCreate(AtomicUsize); + +impl Respond for FlakySessionCreate { + fn respond(&self, _: &Request) -> ResponseTemplate { + if self.0.fetch_add(1, Ordering::SeqCst) == 0 { + ResponseTemplate::new(503) + } else { + ResponseTemplate::new(200) + .set_body_string(r#"{"session_id":"sess-ext","warehouse_id":"test_wh"}"#) + } + } +} + +#[tokio::test(flavor = "multi_thread")] +async fn each_retry_attempt_calls_the_provider_again() { + let server = MockServer::start().await; + Mock::given(method("POST")) + .and(path(SESSIONS)) + .respond_with(FlakySessionCreate(AtomicUsize::new(0))) + .mount(&server) + .await; + let mut http = HttpConfig::default(); + http.retry_max_retries = 2; + http.retry_min_wait = Duration::from_millis(10); + http.retry_max_wait = Duration::from_millis(10); + Session::builder() + .connection( + ConnectionConfig::from_http_path(server.uri(), "/sql/1.0/warehouses/test_wh").unwrap(), + ) + .auth(AuthConfig::External(Box::new(CountingProvider::default()))) + .http(http) + .open() + .await + .expect("open after one retry"); + let creates: Vec<_> = sql_requests(&server) + .await + .into_iter() + .filter(|r| r.url.path() == SESSIONS) + .collect(); + assert_eq!(creates.len(), 2); + assert_ne!( + header(&creates[0], "authorization"), + header(&creates[1], "authorization"), + "the retry carries a fresh provider value" + ); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn parallel_statements_share_one_provider() { + let server = mock_warehouse().await; + let provider = Arc::new(CountingProvider::default()); + let session = Arc::new( + open( + &server, + AuthConfig::External(Box::new(Shared(provider.clone()))), + ) + .await + .expect("open"), + ); + let tasks: Vec<_> = (0..4) + .map(|_| { + let session = session.clone(); + tokio::spawn(async move { select_one(&session).await }) + }) + .collect(); + let done = tokio::time::timeout(Duration::from_secs(30), futures::future::join_all(tasks)) + .await + .expect("no deadlock"); + for result in done { + result.expect("task").expect("parallel query"); + } + let statements = sql_requests(&server) + .await + .into_iter() + .filter(|r| r.method.as_str() == "POST" && r.url.path() == STATEMENTS) + .count(); + assert_eq!(statements, 4); + assert!(provider.calls.load(Ordering::SeqCst) >= statements); +} + +#[tokio::test(flavor = "multi_thread")] +async fn cancel_carries_the_provider_credential() { + let server = mock_warehouse().await; + Mock::given(method("POST")) + .and(path(STATEMENTS)) + .respond_with(ResponseTemplate::new(200).set_body_string( + json!({"statement_id": "stmt-run", "status": {"state": "PENDING"}}).to_string(), + )) + .with_priority(1) + .mount(&server) + .await; + Mock::given(method("POST")) + .and(path("/api/2.0/sql/statements/stmt-run/cancel")) + .respond_with(ResponseTemplate::new(200).set_body_string("{}")) + .mount(&server) + .await; + let session = open( + &server, + AuthConfig::External(Box::new(CountingProvider::default())), + ) + .await + .expect("open"); + let mut stmt = session.statement(); + stmt.spec().sql("SELECT 1"); + let running = stmt.submit().await.expect("submit"); + running.cancel().await.expect("cancel"); + let cancel = sql_requests(&server) + .await + .into_iter() + .find(|r| r.url.path().ends_with("/cancel")) + .expect("cancel request"); + assert!(header(&cancel, "authorization").is_some_and(|v| v.starts_with("Bearer tok-"))); + assert!(header(&cancel, "x-ddf-probe").is_some()); +} + +// ─── C ABI ────────────────────────────────────────────────────────── + +mod c_abi { + use super::*; + use databricks_sql_kernel::c_abi::session::{ + kernel_auth_headers_add, kernel_session_close, kernel_session_config_new, + kernel_session_config_set_auth_external, kernel_session_config_set_http_path, + kernel_session_open, kernel_session_t, KernelAuthHeaders, KernelSessionConfig, + }; + use databricks_sql_kernel::c_abi::KernelStatusCode; + + #[derive(Default)] + struct Probe { + calls: AtomicUsize, + releases: AtomicUsize, + } + + unsafe extern "C" fn headers(user_data: *mut c_void, out: *mut KernelAuthHeaders) -> i32 { + let probe = &*(user_data as *const Probe); + let n = probe.calls.fetch_add(1, Ordering::SeqCst) + 1; + let value = CString::new(format!("Bearer c-tok-{n}")).unwrap(); + let name = CString::new("Authorization").unwrap(); + let extra = CString::new("X-Ddf-Probe").unwrap(); + let extra_value = CString::new("c").unwrap(); + // The kernel copies both strings, so they may be freed on return. + assert_eq!( + kernel_auth_headers_add(out, name.as_ptr(), value.as_ptr()), + KernelStatusCode::Success + ); + assert_eq!( + kernel_auth_headers_add(out, extra.as_ptr(), extra_value.as_ptr()), + KernelStatusCode::Success + ); + 0 + } + + unsafe extern "C" fn release(user_data: *mut c_void) { + (*(user_data as *const Probe)) + .releases + .fetch_add(1, Ordering::SeqCst); + } + + #[test] + fn callback_headers_reach_the_wire_and_user_data_is_released() { + let rt = tokio::runtime::Runtime::new().unwrap(); + let server = rt.block_on(mock_warehouse()); + let probe = Arc::new(Probe::default()); + unsafe { + let mut config: *mut KernelSessionConfig = std::ptr::null_mut(); + assert_eq!( + kernel_session_config_new(&mut config), + KernelStatusCode::Success + ); + let host = CString::new(server.uri()).unwrap(); + let http_path = CString::new("/sql/1.0/warehouses/test_wh").unwrap(); + kernel_session_config_set_http_path(config, host.as_ptr(), http_path.as_ptr()); + assert_eq!( + kernel_session_config_set_auth_external( + config, + Some(headers), + Some(release), + Arc::as_ptr(&probe) as *mut c_void, + ), + KernelStatusCode::Success + ); + let mut session: *mut kernel_session_t = std::ptr::null_mut(); + assert_eq!( + kernel_session_open(config, &mut session), + KernelStatusCode::Success + ); + assert_eq!(probe.releases.load(Ordering::SeqCst), 0, "held while open"); + assert_eq!(kernel_session_close(session), KernelStatusCode::Success); + } + let released = rt.block_on(async { + for _ in 0..100 { + if probe.releases.load(Ordering::SeqCst) == 1 { + return true; + } + tokio::time::sleep(Duration::from_millis(20)).await; + } + false + }); + assert!(released, "release runs once after close"); + let requests = rt.block_on(sql_requests(&server)); + assert!(!requests.is_empty()); + for r in &requests { + let auth = header(r, "authorization").expect("Authorization"); + assert!(auth.starts_with("Bearer c-tok-"), "{auth}"); + assert_eq!(header(r, "x-ddf-probe"), Some("c")); + } + assert!(probe.calls.load(Ordering::SeqCst) >= requests.len()); + } +}