From c58710d87b2d7f115639d12423f6a50ccbb0a951 Mon Sep 17 00:00:00 2001 From: Vikrant Puppala Date: Wed, 13 May 2026 10:26:10 +0000 Subject: [PATCH] =?UTF-8?q?feat(pyo3):=20External=20auth=20=E2=80=94=20Pyt?= =?UTF-8?q?hon-callable=20token=20provider?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Phase 1 step 5. Wires a Python callable into the kernel's AuthConfig::External slot so the connector can delegate OAuth / MSAL / federation flows back to its own auth provider rather than re-implementing them in Rust. New Python surface: - Session(host, http_path, *, auth_type='external', token_callback, catalog=None, schema=None) — `token_callback` is a no-arg callable returning `str`. The kernel invokes it once per HTTP request that needs auth; the callable owns its own caching / refresh. - Session(host, http_path, *, auth_type='pat', access_token, ...) — explicit PAT form. - Session(host, http_path, *, access_token, ...) — implicit PAT (auth_type defaults to "pat" when access_token is provided), kept for backward compatibility with Phase 1 callers. Errors map cleanly: - Python exception inside the callback → KernelError(code= 'Unauthenticated', message='Python token_callback raised: ...') - Non-string return → KernelError(code='Unauthenticated', message='Python token_callback must return str: ...') - Empty string → KernelError(code='Unauthenticated', message='... returned an empty string') Implementation notes: - New `auth.rs` module owns the kwargs→AuthConfig translation and the `PythonTokenProvider` trampoline (impl async TokenProvider for a Py). GIL is re-acquired on the kernel-spawned tokio worker via Python::attach. - pyo3's `extension-module` feature moved to an opt-in Cargo feature so `cargo test -p databricks-sql-kernel-pyo3` can link libpython and run the trampoline's unit tests. Maturin enables the feature via pyproject.toml when building the wheel. - 4 Rust unit tests cover token roundtrip, Python exception mapping, non-string-return rejection, empty-string rejection. These run on cargo test without any live deps. KNOWN LIMITATION (to be addressed in a follow-up kernel PR): The kernel's `build_auth_provider` currently returns `InvalidArgument` for `AuthConfig::External` ("reserved; v0 wires PAT + OAuthM2M + OAuthU2M only"). End-to-end use of `Session(auth_type='external', ...)` will surface that error verbatim until the kernel wires External into its HTTP-client auth path. This is a separate kernel PR (likely a small ExternalAuthProvider adapter using tokio::task::block_in_place + Handle::current().block_on to drive the async TokenProvider from the sync AuthProvider trait). The PyO3 trampoline itself is fully covered by the unit tests in this PR; the wrapper layer is done. Co-authored-by: Isaac Signed-off-by: Vikrant Puppala --- Cargo.lock | 1 + pyo3/Cargo.toml | 15 ++- pyo3/pyproject.toml | 2 +- pyo3/smoke.py | 70 ++++++++++++++ pyo3/src/auth.rs | 217 ++++++++++++++++++++++++++++++++++++++++++++ pyo3/src/lib.rs | 7 +- pyo3/src/session.rs | 60 ++++++++---- 7 files changed, 351 insertions(+), 21 deletions(-) create mode 100644 pyo3/src/auth.rs diff --git a/Cargo.lock b/Cargo.lock index 353520e1..5e2b469a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -385,6 +385,7 @@ dependencies = [ "arrow-array", "arrow-pyarrow", "arrow-schema", + "async-trait", "databricks-sql-kernel", "pyo3", "tokio", diff --git a/pyo3/Cargo.toml b/pyo3/Cargo.toml index ebd3cfbf..f59fc8be 100644 --- a/pyo3/Cargo.toml +++ b/pyo3/Cargo.toml @@ -36,7 +36,13 @@ crate-type = ["cdylib"] databricks-sql-kernel = { path = ".." } # pyo3 — abi3-py39 lets one wheel cover Python 3.9+. -pyo3 = { version = "0.26", features = ["extension-module", "abi3-py39"] } +# +# `extension-module` is gated behind a Cargo feature so that +# `cargo test -p databricks-sql-kernel-pyo3` can build a normal +# binary that links against libpython (needed to run unit tests +# that call `Python::attach`). Maturin enables the feature via +# pyproject.toml when building the wheel. +pyo3 = { version = "0.26", features = ["abi3-py39"] } # Multi-thread runtime — one per Session, owned on the Rust side. tokio = { version = "1", features = ["rt-multi-thread"] } @@ -46,3 +52,10 @@ tokio = { version = "1", features = ["rt-multi-thread"] } arrow-array = "57" arrow-schema = "57" arrow-pyarrow = "57" + +# Required to implement the kernel's #[async_trait] TokenProvider on +# the Python-callable trampoline used by AuthConfig::External. +async-trait = "0.1" + +[features] +extension-module = ["pyo3/extension-module"] diff --git a/pyo3/pyproject.toml b/pyo3/pyproject.toml index cdaeade0..3d9e7663 100644 --- a/pyo3/pyproject.toml +++ b/pyo3/pyproject.toml @@ -13,4 +13,4 @@ dependencies = ["pyarrow>=14"] [tool.maturin] module-name = "databricks_sql_kernel" -features = ["pyo3/extension-module"] +features = ["extension-module"] diff --git a/pyo3/smoke.py b/pyo3/smoke.py index 49fc4658..c831eaf4 100644 --- a/pyo3/smoke.py +++ b/pyo3/smoke.py @@ -270,6 +270,76 @@ def main() -> None: check("message" in attrs, "attrs has 'message'") s2.close() + # --- External auth (Python-callable token provider) --- + # + # NOTE: the kernel today rejects `AuthConfig::External` at + # `build_auth_provider` ("reserved; v0 wires PAT + OAuthM2M + + # OAuthU2M only"). Until a follow-up kernel PR wires it into + # the HTTP client's `AuthProvider` adapter, opening a live + # session with `auth_type='external'` surfaces that kernel + # error. The smoke test verifies: + # + # 1. The wrapper accepts and validates the new kwargs. + # 2. Bad kwargs surface as `ValueError` at construction time + # (before the kernel ever sees them). + # 3. Calling `Session(auth_type='external', ...)` surfaces the + # kernel's "reserved" error verbatim — proving the path + # reaches the kernel and the trampoline is wired correctly. + # + # The trampoline itself (Python callback → Rust → kernel + # `TokenProvider`) is covered by Rust unit tests in + # `pyo3/src/auth.rs` so we know the GIL handoff works. + + banner("input validation — missing auth") + try: + k.Session(host=HOST, http_path=HTTP_PATH) + check(False, "no auth should have raised ValueError") + except ValueError as e: + check(True, f"ValueError as expected: {e}") + + banner("input validation — auth_type='external' without callback") + try: + k.Session(host=HOST, http_path=HTTP_PATH, auth_type="external") + check(False, "should have raised") + except ValueError as e: + check("token_callback" in str(e), f"ValueError mentions token_callback: {e}") + + banner("input validation — non-callable callback") + try: + k.Session( + host=HOST, + http_path=HTTP_PATH, + auth_type="external", + token_callback="not-callable", + ) + check(False, "should have raised") + except ValueError as e: + check("callable" in str(e), f"ValueError mentions callable: {e}") + + banner("auth_type='external' surfaces the kernel's 'reserved' error today") + + def ok_callback(): + return TOKEN + + try: + k.Session( + host=HOST, + http_path=HTTP_PATH, + auth_type="external", + token_callback=ok_callback, + ) + check(False, "should have raised until kernel wires AuthConfig::External") + except k.KernelError as e: + attrs = e.args[1] + check( + attrs.get("code") == "InvalidArgument", + f"code=InvalidArgument, got: {attrs.get('code')}", + ) + check( + "External" in attrs.get("message", ""), + f"message names External: {attrs.get('message')}", + ) + print("\nAll smoke checks passed.") diff --git a/pyo3/src/auth.rs b/pyo3/src/auth.rs new file mode 100644 index 00000000..e410568b --- /dev/null +++ b/pyo3/src/auth.rs @@ -0,0 +1,217 @@ +// 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. + +//! Translation from Python auth kwargs to a kernel `AuthConfig`. +//! +//! Phase-1 surface covers PAT (Step 1) and `External` (this step). +//! `External` lets the connector keep ownership of its own OAuth / +//! MSAL / federation flows: it passes a Python callable that returns +//! a fresh bearer token, and the kernel calls it whenever it needs +//! one. +//! +//! Future steps add the kernel-driven OAuth variants +//! (`AuthConfig::OAuthM2M`, `OAuthU2M`, `OAuthFederation`) — useful +//! for callers that want the kernel to own the flow rather than +//! delegating back to Python. + +use async_trait::async_trait; +use databricks_sql_kernel::config::TokenProvider; +use databricks_sql_kernel::{AuthConfig, Error, Result as KResult}; +use pyo3::exceptions::PyValueError; +use pyo3::prelude::*; + +/// A `TokenProvider` that delegates to a Python callable. The +/// callable is invoked once per HTTP request that needs auth, with +/// the GIL re-acquired on the calling tokio worker thread. +/// +/// `Py` is `Send + Sync` in pyo3 (it's a reference-counted +/// pointer into the Python heap, not a borrow), so this struct +/// satisfies the kernel's `TokenProvider: Send + Sync` bound. +struct PythonTokenProvider { + callback: Py, +} + +impl PythonTokenProvider { + fn new(callback: Py) -> Self { + Self { callback } + } +} + +#[async_trait] +impl TokenProvider for PythonTokenProvider { + async fn token(&self) -> KResult { + // The kernel calls us from a tokio worker without the GIL. + // Acquire it for the duration of one Python call, extract + // the result as a String, then drop the GIL again before + // returning the future to the kernel. + // + // Note: this is a *sync* GIL-held call to the user's Python + // callable. For typical auth providers (in-process token + // cache lookup, occasional refresh) this is fine and matches + // the connector's own auth-provider contract. If a wrapper + // ever needs to await Python coroutines here, the pattern + // is to make the callback return a token directly and own + // the async work itself. + Python::attach(|py| { + let result = self.callback.call0(py).map_err(|e| { + Error::unauthenticated().message(format!("Python token_callback raised: {e}")) + })?; + let token: String = result.extract(py).map_err(|e| { + Error::unauthenticated() + .message(format!("Python token_callback must return str: {e}")) + })?; + if token.is_empty() { + return Err(Error::unauthenticated() + .message("Python token_callback returned an empty string")); + } + Ok(token) + }) + } +} + +/// Build a kernel `AuthConfig` from the Python kwargs the `Session` +/// constructor accepts. Centralised here so the auth-kwarg surface +/// stays in one place. +/// +/// `auth_type` is one of: +/// - `"pat"` — requires `access_token: str`. +/// - `"external"` — requires `token_callback: Callable[[], str]`. +pub(crate) fn build_auth_config( + auth_type: &str, + access_token: Option, + token_callback: Option>, +) -> PyResult { + match auth_type { + "pat" => { + let token = access_token + .ok_or_else(|| PyValueError::new_err("auth_type='pat' requires access_token"))?; + if token.is_empty() { + return Err(PyValueError::new_err("access_token must not be empty")); + } + Ok(AuthConfig::Pat { token }) + } + "external" => { + let callback = token_callback.ok_or_else(|| { + PyValueError::new_err( + "auth_type='external' requires token_callback (a no-arg callable returning str)", + ) + })?; + // Sanity check at construction time so a misspelled or + // non-callable arg surfaces immediately rather than on + // the first HTTP request. + Python::attach(|py| -> PyResult<()> { + if !callback.bind(py).is_callable() { + return Err(PyValueError::new_err("token_callback must be callable")); + } + Ok(()) + })?; + Ok(AuthConfig::External(Box::new(PythonTokenProvider::new( + callback, + )))) + } + other => Err(PyValueError::new_err(format!( + "unknown auth_type {other:?}; expected one of: pat, external" + ))), + } +} + +#[cfg(test)] +mod tests { + //! End-to-end coverage for the Python→Rust→kernel auth bridge. + //! + //! These tests exercise the `TokenProvider` trampoline without + //! needing a live workspace — we construct a `PythonTokenProvider` + //! directly, run its async `token()` method on a tokio runtime, + //! and check the value flows back correctly. This is the layer + //! the rest of Step 5 builds on; if it breaks we want to catch + //! it without spinning a Session against dogfood. + //! + //! `Python::initialize()` initialises the Python interpreter on + //! first call; subsequent calls are no-ops. + + use super::*; + use databricks_sql_kernel::ErrorCode; + use pyo3::ffi::c_str; + + fn rt() -> tokio::runtime::Runtime { + tokio::runtime::Builder::new_multi_thread() + .enable_all() + .build() + .unwrap() + } + + #[test] + fn python_token_provider_returns_callback_value() { + Python::initialize(); + let callback: Py = Python::attach(|py| { + py.eval(c_str!("lambda: 'token-xyz'"), None, None) + .unwrap() + .unbind() + }); + let provider = PythonTokenProvider::new(callback); + let got = rt().block_on(provider.token()).unwrap(); + assert_eq!(got, "token-xyz"); + } + + #[test] + fn python_token_provider_maps_python_exception_to_unauthenticated() { + Python::initialize(); + let callback: Py = Python::attach(|py| { + // Lambda raising RuntimeError. Done as exec+lookup so we + // can carry a statement (`raise ...`) instead of an + // expression. + let globals = pyo3::types::PyDict::new(py); + py.run( + c_str!("def cb():\n raise RuntimeError('simulated MSAL failure')\n"), + Some(&globals), + None, + ) + .unwrap(); + globals.get_item("cb").unwrap().unwrap().unbind() + }); + let provider = PythonTokenProvider::new(callback); + let err = rt().block_on(provider.token()).unwrap_err(); + assert_eq!(err.code, ErrorCode::Unauthenticated); + assert!( + err.message.contains("simulated MSAL failure"), + "message should preserve the Python exception text: {}", + err.message + ); + } + + #[test] + fn python_token_provider_rejects_non_string_return() { + Python::initialize(); + let callback: Py = Python::attach(|py| { + py.eval(c_str!("lambda: 12345"), None, None) + .unwrap() + .unbind() + }); + let provider = PythonTokenProvider::new(callback); + let err = rt().block_on(provider.token()).unwrap_err(); + assert_eq!(err.code, ErrorCode::Unauthenticated); + assert!(err.message.contains("must return str"), "{}", err.message); + } + + #[test] + fn python_token_provider_rejects_empty_string() { + Python::initialize(); + let callback: Py = + Python::attach(|py| py.eval(c_str!("lambda: ''"), None, None).unwrap().unbind()); + let provider = PythonTokenProvider::new(callback); + let err = rt().block_on(provider.token()).unwrap_err(); + assert_eq!(err.code, ErrorCode::Unauthenticated); + assert!(err.message.contains("empty"), "{}", err.message); + } +} diff --git a/pyo3/src/lib.rs b/pyo3/src/lib.rs index 3c4fbb18..daa3bbc9 100644 --- a/pyo3/src/lib.rs +++ b/pyo3/src/lib.rs @@ -15,14 +15,17 @@ //! Python bindings for the Databricks SQL Kernel. //! //! Phase 1 surface today: `Session`, `Statement`, `ExecutedStatement`, -//! `ExecutedAsyncStatement`, `Metadata`, `ResultStream`. PAT auth -//! only. Both synchronous `execute()` and async `submit()` paths +//! `ExecutedAsyncStatement`, `Metadata`, `ResultStream`. Auth: PAT +//! plus `External` (Python-callable token provider — used by the +//! connector to delegate OAuth back to its own auth provider). +//! Both synchronous `execute()` and async `submit()` paths //! supported. Built as the `databricks_sql_kernel` extension module //! via `maturin develop` / `maturin build`. //! //! The kernel's API is async — every method call from Python detaches //! the GIL and `block_on`s on the session-owned tokio runtime. +mod auth; mod errors; mod executed_async; mod fetch; diff --git a/pyo3/src/session.rs b/pyo3/src/session.rs index 801ebccc..3c048423 100644 --- a/pyo3/src/session.rs +++ b/pyo3/src/session.rs @@ -20,10 +20,11 @@ //! 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; use crate::errors::to_py_err; use crate::metadata::Metadata; use crate::statement::Statement; -use databricks_sql_kernel::{AuthConfig, Session as KSession}; +use databricks_sql_kernel::Session as KSession; use pyo3::prelude::*; use std::sync::Arc; use tokio::runtime::{Builder, Runtime}; @@ -50,24 +51,52 @@ pub(crate) struct SessionInner { impl Session { /// Open a new session against the given workspace. /// - /// PAT auth only in this phase. `host` may be bare - /// (`my-workspace.databricks.com`) or fully-qualified - /// (`https://...`). `http_path` is the SQL endpoint path. + /// `host` may be bare (`my-workspace.databricks.com`) or + /// fully-qualified (`https://...`). `http_path` is the SQL + /// endpoint path. + /// + /// Auth selection: + /// + /// - `auth_type="pat"` (default when `access_token` is provided): + /// `access_token` carries the bearer token. Kernel uses it + /// verbatim for every request. + /// - `auth_type="external"`: `token_callback` is a no-arg + /// Python callable that returns a fresh bearer token. The + /// kernel invokes it once per HTTP request needing auth; + /// the callable owns its own caching / refresh. Use this to + /// delegate OAuth / MSAL / federation to the connector's + /// existing auth provider. + /// + /// Omitting `auth_type` is equivalent to `"pat"` for backward + /// compatibility with Phase-1 callers that only had PAT. #[new] - #[pyo3(signature = (host, http_path, *, access_token, catalog=None, schema=None))] + #[pyo3(signature = (host, http_path, *, auth_type=None, access_token=None, token_callback=None, catalog=None, schema=None))] + #[allow(clippy::too_many_arguments)] fn new( py: Python<'_>, host: String, http_path: String, - access_token: String, + auth_type: Option, + access_token: Option, + token_callback: Option>, catalog: Option, schema: Option, ) -> PyResult { - if access_token.is_empty() { - return Err(pyo3::exceptions::PyValueError::new_err( - "access_token must not be empty", - )); - } + // Resolve auth_type: default to "pat" only when the caller + // also passed access_token. This keeps existing PAT callers + // working without changes while still rejecting ambiguous + // calls like `Session(host, http_path)` with no auth. + let resolved_auth_type = match auth_type.as_deref() { + Some(t) => t.to_owned(), + None if access_token.is_some() => "pat".to_owned(), + None => { + return Err(pyo3::exceptions::PyValueError::new_err( + "Session requires auth: pass auth_type='pat' with access_token, \ + or auth_type='external' with token_callback", + )); + } + }; + let auth_config = build_auth_config(&resolved_auth_type, access_token, token_callback)?; // One tokio runtime per session. Multi-thread so CloudFetch // chunk downloads can overlap with the main poll loop. Worker @@ -90,12 +119,9 @@ impl Session { let rt = runtime.clone(); let open_result = py.detach(|| { rt.block_on(async { - let mut builder = - KSession::builder() - .http_path(host, http_path) - .auth(AuthConfig::Pat { - token: access_token, - }); + let mut builder = KSession::builder() + .http_path(host, http_path) + .auth(auth_config); if catalog.is_some() || schema.is_some() { let mut defaults = databricks_sql_kernel::DefaultOpts::default(); defaults.catalog = catalog;