diff --git a/docs/designs/PECOBLR-4146-oauth-token-persistence-design.md b/docs/designs/PECOBLR-4146-oauth-token-persistence-design.md new file mode 100644 index 00000000..efcccb5c --- /dev/null +++ b/docs/designs/PECOBLR-4146-oauth-token-persistence-design.md @@ -0,0 +1,154 @@ + + +# OAuth token persistence on the kernel path (PECOBLR-4146) + +**Status:** Decided. **PuPr:** kernel-owned persistence (enable / disable / +locate the built-in encrypted disk cache). **Post-GA:** caller-supplied custom +token store, only if a named consumer needs a non-file sink. +**Parent:** PECOBLR-3727 (databricks-sql-kernel Reyden support). + +## Problem + +On the kernel path the kernel owns the OAuth **U2M** flow and, by default, +persists the refresh token to an encrypted on-disk cache +(`~/.config/databricks-sql-kernel/oauth/`, `0600`, `TokenCacheConfig.enabled = +true`, matching JDBC `EnableTokenCache=1`). Two questions follow: + +1. Should a caller be able to **turn that off / relocate it** (e.g. a policy that + forbids tokens at rest)? +2. Should a caller be able to substitute their **own token store** — the Thrift + connectors' `OAuthPersistence` (Node) / `experimental_oauth_persistence` + (Python) — backing a database, OS keychain, or in-memory object? + +## Decision + +For **PuPr**, answer (1): the kernel owns the token lifetime, and the caller can +enable/disable/locate the built-in encrypted disk cache. Answer (2) — a +caller-supplied custom store — is **post-GA**, built only when a named consumer +needs a non-file sink. + +### Rationale + +- **No demonstrated demand for custom stores.** `experimental_oauth_persistence` + was introduced in the *foundational* OAuth PR (databricks-sql-python#15, 2022) + as an extensibility hook — `experimental_`, documented "beta (private + preview)", with **no named customer** driving it. The connector ships only + `OAuthPersistenceCache` (in-memory) and `DevOnlyFilePersistence` ("only + intended for development", writes **plaintext**). It ships **no production + store**; the docstring tells prod users to "write your own". +- **The kernel already provides the missing prod store.** The kernel's built-in + disk cache is exactly the hardened, restart-surviving store the connector told + users to build — encrypted (`cache_crypto`), `0600`, cross-process — and it is + **stronger** than anything the connector ships. So the common prod U2M need + ("make the browser login survive restarts, securely") is met with **zero user + code**. +- **The default divergence is really an on/off question.** Thrift Python defaults + to *no* persistence; Thrift Node defaults to *in-memory*; the kernel defaults + to *on-disk* (JDBC convention). Reconciling this is an **enable/disable** + decision — squarely the PuPr scope. +- **No telemetry signal.** Connector telemetry records `auth_mech` + `auth_flow` + only — nothing about whether a persistence object was supplied or its type — so + custom-store adoption can't even be measured. +- **The custom-store path is the entire high-risk surface** (an async + request/response `ThreadsafeFunction` on napi; a GIL callback on pyo3), and + would ship without live-host E2E coverage. The PuPr scope is scalar config — no + callbacks, no async-FFI, trivially testable. + +Low-regret: the custom-store design is fully worked out and prototyped (see +*Post-GA*), so it can be added later with nothing lost by waiting. + +## PuPr scope — kernel-owned persistence + +The kernel already owns acquisition, refresh, in-memory reuse, and encrypted +on-disk persistence. PuPr adds **no new kernel auth machinery** — it exposes the +*existing* `TokenCacheConfig` (in `src/config.rs`, already `enabled` + +`passphrase`, already reachable over the C-ABI via +`kernel_session_config_set_u2m_token_cache_config`) through the two bindings as +scalar config: + +- **napi** — `ConnectionOptions` gains optional `tokenCacheEnabled` / + (optional) `tokenCachePassphrase` / (optional) cache-dir override. +- **pyo3** — `Session(…)` gains the matching optional kwargs. +- **Kernel** — optionally add a `dir`/`path` override field to `TokenCacheConfig` + (the default location is fine for most; the override is a nice-to-have, not + required for PuPr). + +No token-store trait, no binding callbacks. A caller who supplies nothing gets +today's encrypted-disk default; a caller can disable persistence (no token at +rest) or point it at a chosen location. + +### The default the connector adapters must choose + +The kernel defaults **on-disk**; Thrift defaults **in-memory / none**. The +connector adapters (databricks-sql-nodejs#457, databricks-sql-python#913) must +consciously pick per binding: + +- **Adopt the kernel/JDBC default** — persist to disk by default (fewer logins; + but the refresh token is now at rest where it wasn't on Thrift), or +- **Match Thrift's conservative default** — disable the kernel disk cache unless + the user opts in. + +The enable/disable knob is what makes either choice expressible. This is a +product decision, flagged on those tickets — not something the kernel picks +silently. + +### Out of scope — Go / C-ABI + +The C-ABI has no callback surface and Go has no persistence concept to forward. +Its existing `kernel_session_config_set_u2m_token_cache_config` (enable/disable + +passphrase) already covers the PuPr scope for Go. + +## Post-GA — caller-supplied custom store + +Add this **only when a named consumer needs a non-file token sink** (OS keychain, +secrets manager / Vault, corporate policy mandating "no token on disk", or a +multi-tenant server sharing tokens in a DB). Until then it stays deferred. + +**Design (prototyped — see below):** + +- Kernel: a `TokenPersistence` trait (`async load/save` over `OAuthToken`), with + today's disk cache refactored into a `DiskTokenCache` default impl, and + `AuthConfig::OAuthU2M { token_store: Option> }` (set + via the `oauth_u2m(…)` constructor, since `AuthConfig` is `#[non_exhaustive]`). +- Wire format: the kernel's `OAuthToken` serialized to JSON (lossless; the exact + bytes the disk cache stores) — avoids reconstructing expiry from a partial + token. +- Store key: the callback boundary MUST carry the full `{host, client_id, + scopes}` triple — the same key `TokenPersistence` / `DiskTokenCache` use (the + cache filename is a SHA-256 of all three; see `src/auth/oauth/cache.rs`). + Keying a caller-supplied store on `host` alone would collide two U2M sessions + to the same host with different `client_id`/`scopes` — the second `save` + overwrites the first and a `load` can return a token minted for a different + client/scope set — silently diverging from the built-in disk cache, which + keeps those as distinct entries. So the napi/pyo3 persist/load args must + include `client_id` and `scopes`, not just `host` and `token_json`. +- napi: `openSession` gains two callbacks wrapped as `ThreadsafeFunction`s; + `load`/`save` `call_async` the JS function and `await` its `Promise`. +- pyo3: a `PyTokenStore` calling the Python object under the GIL + (`Python::attach`), carried on `OAuthParams.token_store`. +- Error semantics: `load` error → cache miss (fresh login, never fails connect); + `save` error → logged and swallowed. +- The same bridge (a callback into the binding) would also unblock the + currently-rejected `token-provider` / `external-token` / `custom` authTypes and + a Go/C-ABI store. + +**Prototype status:** the full custom-store implementation (kernel trait + +`DiskTokenCache` + napi `ThreadsafeFunction` bridge + pyo3 GIL bridge) was built +and compiles / unit-tests clean; it lives in the branch history of the initial +PECOBLR-4146 PR. **It was not E2E-tested against live Node/Python U2M** — that, +plus a named requirement, is the gate before it ships. + +## Testing + +- **PuPr:** scalar-config plumbing — assert the napi/pyo3 flags map to + `TokenCacheConfig`; kernel U2M E2E with the cache enabled (survives restart) + and disabled (fresh login each run). The default disk path is already verified + E2E (U2M open + a two-run disk-cache round-trip that skips the browser on the + second run). +- **Post-GA (custom store):** the prototype's Rust mock-store unit tests, plus + the missing piece — live-host E2E through the Node and Python connectors with a + real custom in-memory store (round-trip + no deadlock on the napi TSFN / pyo3 + GIL paths). diff --git a/napi/CHANGELOG.md b/napi/CHANGELOG.md index 1fce3834..079f0cf0 100644 --- a/napi/CHANGELOG.md +++ b/napi/CHANGELOG.md @@ -9,6 +9,17 @@ they ship on independent cadences. ## [Unreleased] ### Added +- **U2M on-disk token-cache control on `openSession`** — `tokenCacheEnabled` + and `tokenCachePassphrase` let a Node caller enable/disable (or set the + AES-256 passphrase for) the kernel's built-in encrypted disk cache on the + kernel path. Omitted keeps the kernel default (enabled, machine-local key, + survives restarts); `tokenCacheEnabled: false` re-logins each fresh process; a + passphrase with no explicit flag implies enabled. Applies to `OAuthU2m`. + (PECOBLR-4146) + + The generated `index.d.ts` gains the two optional fields; `index.js` (the + loader) is unchanged — new `#[napi(object)]` fields don't alter the exported + symbol set. ### Changed diff --git a/napi/index.d.ts b/napi/index.d.ts index bc16c0d2..21cf939e 100644 --- a/napi/index.d.ts +++ b/napi/index.d.ts @@ -231,6 +231,20 @@ export interface ConnectionOptions { * authority for [`AuthMode::OAuthM2m`] / [`AuthMode::OAuthM2mJwt`]. */ tokenUrl?: string + /** + * U2M on-disk token-cache control (kernel path). Omitted ⇒ the kernel + * default (cache enabled, encrypted under a machine-local key, survives + * restarts). `false` disables on-disk persistence (re-login each fresh + * process); `true` keeps it enabled. Applies to [`AuthMode::OAuthU2m`]. + */ + tokenCacheEnabled?: boolean + /** + * Optional passphrase for the U2M on-disk token cache (AES-256 key). + * Omitted/blank ⇒ a machine-local derived key. Supplying one is stronger. + * A passphrase with no explicit `tokenCacheEnabled` implies enabled. + * Applies to [`AuthMode::OAuthU2m`]. + */ + tokenCachePassphrase?: string /** * Path to the PEM private-key file. Required for * [`AuthMode::OAuthM2mJwt`]. diff --git a/napi/src/database.rs b/napi/src/database.rs index 32bc1dd4..746a8327 100644 --- a/napi/src/database.rs +++ b/napi/src/database.rs @@ -35,7 +35,7 @@ type Buffer = Vec; use databricks_sql_kernel::{ AuthConfig, DefaultOpts, DriverSystemConfiguration, Error as KernelError, HttpConfig, - ProxyConfig, ResultConfig, Session, TelemetryConfig, TlsConfig, + ProxyConfig, ResultConfig, Session, TelemetryConfig, TlsConfig, TokenCacheConfig, }; /// NodeJS-driver-appropriate default for `pool_max_idle_per_host`. @@ -177,6 +177,16 @@ pub struct ConnectionOptions { /// which is required when that IdP — not Databricks-native OIDC — is the /// authority for [`AuthMode::OAuthM2m`] / [`AuthMode::OAuthM2mJwt`]. pub token_url: Option, + /// U2M on-disk token-cache control (kernel path). Omitted ⇒ the kernel + /// default (cache enabled, encrypted under a machine-local key, survives + /// restarts). `false` disables on-disk persistence (re-login each fresh + /// process); `true` keeps it enabled. Applies to [`AuthMode::OAuthU2m`]. + pub token_cache_enabled: Option, + /// Optional passphrase for the U2M on-disk token cache (AES-256 key). + /// Omitted/blank ⇒ a machine-local derived key. Supplying one is stronger. + /// A passphrase with no explicit `tokenCacheEnabled` implies enabled. + /// Applies to [`AuthMode::OAuthU2m`]. + pub token_cache_passphrase: Option, /// Path to the PEM private-key file. Required for /// [`AuthMode::OAuthM2mJwt`]. pub jwt_key_file: Option, @@ -498,11 +508,17 @@ fn build_auth_config(options: &ConnectionOptions) -> napi::Result { options.oauth_scopes.clone(), options.token_url.clone(), None, - // `None` takes the kernel default: on-disk cache enabled, - // encrypted under a machine-local derived key since this - // binding exposes no passphrase option. Surfacing one through - // `options` would strengthen it further. - None, + // U2M on-disk token-cache control. Both omitted ⇒ kernel + // default (enabled, machine-local key). Otherwise honor the + // caller's enable flag / passphrase; a passphrase alone + // implies enabled. + match (options.token_cache_enabled, &options.token_cache_passphrase) { + (None, None) => None, + (enabled, passphrase) => Some(TokenCacheConfig { + enabled: enabled.unwrap_or(true), + passphrase: passphrase.clone(), + }), + }, options.identity_federation_client_id.clone(), )) } @@ -834,6 +850,8 @@ mod tests { oauth_redirect_port: None, oauth_scopes: None, token_url: None, + token_cache_enabled: None, + token_cache_passphrase: None, jwt_key_file: None, jwt_kid: None, jwt_passphrase: None, @@ -1181,6 +1199,45 @@ mod tests { } } + #[test] + fn u2m_token_cache_control_maps_to_config() { + let mut o = base(); + o.auth_mode = Some(AuthMode::OAuthU2m); + + // Neither field set → None → the kernel default (enabled, machine key). + match build_auth_config(&o).unwrap() { + AuthConfig::OAuthU2M { token_cache, .. } => assert!(token_cache.is_none()), + other => panic!("expected OAuthU2M, got {other:?}"), + } + + // Explicit disable → Some(TokenCacheConfig { enabled: false }). + o.token_cache_enabled = Some(false); + match build_auth_config(&o).unwrap() { + AuthConfig::OAuthU2M { + token_cache: Some(tc), + .. + } => { + assert!(!tc.enabled); + assert!(tc.passphrase.is_none()); + } + other => panic!("expected OAuthU2M with token_cache, got {other:?}"), + } + + // Passphrase with no explicit enable flag implies enabled. + o.token_cache_enabled = None; + o.token_cache_passphrase = Some("s3cret".to_owned()); + match build_auth_config(&o).unwrap() { + AuthConfig::OAuthU2M { + token_cache: Some(tc), + .. + } => { + assert!(tc.enabled); + assert_eq!(tc.passphrase.as_deref(), Some("s3cret")); + } + other => panic!("expected OAuthU2M with token_cache, got {other:?}"), + } + } + #[test] fn u2m_rejects_explicit_empty_client_id() { // Parity with pyo3: an explicit empty oauthClientId is rejected diff --git a/pyo3/CHANGELOG.md b/pyo3/CHANGELOG.md index a639648d..032f23fd 100644 --- a/pyo3/CHANGELOG.md +++ b/pyo3/CHANGELOG.md @@ -9,6 +9,14 @@ they ship on independent cadences. ## [Unreleased] ### Added +- **U2M on-disk token-cache control** — `Session(…, token_cache_enabled=…, + token_cache_passphrase=…)` lets a caller enable/disable (or set the AES-256 + passphrase for) the kernel's built-in encrypted disk cache on the kernel path. + Omitted keeps the kernel default (enabled, machine-local key, survives + restarts); `token_cache_enabled=False` re-logins each fresh process; a + passphrase with no explicit flag implies enabled. Applies to `oauth-u2m`. + The `databricks-sql-python` connector maps its `experimental_oauth_persistence` + presence onto this enable flag (#913). (PECOBLR-4146) ### Changed diff --git a/pyo3/pyproject.toml b/pyo3/pyproject.toml index ae8bb2d5..1cb1778a 100644 --- a/pyo3/pyproject.toml +++ b/pyo3/pyproject.toml @@ -57,4 +57,7 @@ dev = [ [tool.maturin] module-name = "databricks_sql_kernel" +# The pyo3 `extension-module` feature is opt-in (see pyo3/Cargo.toml) so plain +# `cargo test` can link libpython for the unit-test binaries. Maturin builds the +# real wheel, where the interpreter supplies those symbols, so enable it here. features = ["extension-module"] diff --git a/pyo3/src/auth.rs b/pyo3/src/auth.rs index c846f9a0..821871b8 100644 --- a/pyo3/src/auth.rs +++ b/pyo3/src/auth.rs @@ -43,7 +43,7 @@ use std::time::Duration; -use databricks_sql_kernel::AuthConfig; +use databricks_sql_kernel::{AuthConfig, TokenCacheConfig}; use pyo3::exceptions::PyValueError; use pyo3::prelude::*; @@ -83,6 +83,14 @@ pub(crate) struct OAuthParams { pub azure_client_secret: Option, pub azure_tenant_id: Option, pub azure_workspace_resource_id: Option, + /// U2M on-disk token-cache control. `None` ⇒ kernel default (enabled, + /// machine-local key). `Some(false)` disables on-disk persistence; + /// `Some(true)` keeps it. A passphrase with no explicit flag implies + /// enabled. + pub token_cache_enabled: Option, + /// Optional passphrase for the U2M on-disk token cache (AES-256 key). + /// `None`/blank ⇒ a machine-local derived key. + pub token_cache_passphrase: Option, } /// Default U2M OAuth client id for the **Python** binding. @@ -321,14 +329,18 @@ fn build_auth_config_inner( scopes, oauth.token_url, oauth.callback_timeout_secs.map(Duration::from_secs), - // `None` takes the kernel default: on-disk cache ENABLED, - // encrypted under a machine-local derived key since this - // binding exposes no passphrase option. That preserves - // cross-connection SSO reuse (the point of the cache) without - // ever writing the refresh token in the clear. Surfacing a - // passphrase through `OAuthParams` — the equivalent of JDBC's - // TokenCachePassPhrase — would strengthen it further. - None, + // U2M on-disk token-cache control. Both omitted ⇒ kernel + // default (enabled, machine-local derived key — preserves + // cross-restart SSO reuse without writing the token in the + // clear). Otherwise honor the caller's enable flag / + // passphrase; a passphrase alone implies enabled. + match (oauth.token_cache_enabled, oauth.token_cache_passphrase) { + (None, None) => None, + (enabled, passphrase) => Some(TokenCacheConfig { + enabled: enabled.unwrap_or(true), + passphrase, + }), + }, oauth.identity_federation_client_id, )) } @@ -623,6 +635,55 @@ mod tests { } } + #[test] + fn u2m_token_cache_control_maps_to_config() { + // Neither field set → None → the kernel default (enabled, machine key). + match build_auth_config_inner("oauth-u2m", None, OAuthParams::default()).unwrap() { + AuthConfig::OAuthU2M { token_cache, .. } => assert!(token_cache.is_none()), + other => panic!("expected OAuthU2M, got {other:?}"), + } + // Explicit disable → Some(TokenCacheConfig { enabled: false }). + let cfg = build_auth_config_inner( + "oauth-u2m", + None, + OAuthParams { + token_cache_enabled: Some(false), + ..Default::default() + }, + ) + .unwrap(); + match cfg { + AuthConfig::OAuthU2M { + token_cache: Some(tc), + .. + } => { + assert!(!tc.enabled); + assert!(tc.passphrase.is_none()); + } + other => panic!("expected OAuthU2M with token_cache, got {other:?}"), + } + // Passphrase with no explicit flag implies enabled. + let cfg = build_auth_config_inner( + "oauth-u2m", + None, + OAuthParams { + token_cache_passphrase: Some("s3cret".to_string()), + ..Default::default() + }, + ) + .unwrap(); + match cfg { + AuthConfig::OAuthU2M { + token_cache: Some(tc), + .. + } => { + assert!(tc.enabled); + assert_eq!(tc.passphrase.as_deref(), Some("s3cret")); + } + other => panic!("expected OAuthU2M with token_cache, got {other:?}"), + } + } + #[test] fn u2m_empty_redirect_ports_rejected() { let err = build_auth_config_inner( diff --git a/pyo3/src/session.rs b/pyo3/src/session.rs index 8bc04bd0..0dac7eab 100644 --- a/pyo3/src/session.rs +++ b/pyo3/src/session.rs @@ -289,6 +289,8 @@ impl Session { azure_client_secret=None, azure_tenant_id=None, azure_workspace_resource_id=None, + token_cache_enabled=None, + token_cache_passphrase=None, tls_ca_cert=None, tls_skip_verify=false, tls_skip_hostname_verify=false, @@ -346,6 +348,10 @@ impl Session { azure_client_secret: Option, azure_tenant_id: Option, azure_workspace_resource_id: Option, + // U2M on-disk token-cache control (kernel path); overrides the kernel + // default (enabled). `False` disables on-disk persistence. + token_cache_enabled: Option, + token_cache_passphrase: Option, tls_ca_cert: Option>, tls_skip_verify: bool, tls_skip_hostname_verify: bool, @@ -420,6 +426,8 @@ impl Session { azure_client_secret, azure_tenant_id, azure_workspace_resource_id, + token_cache_enabled, + token_cache_passphrase, }; let auth_config = build_auth_config(&resolved_auth_type, access_token, oauth)?;