Repository navigation
[PECOBLR-2158] Encrypt the U2M token cache and add an EnableTokenCache-style opt-out - #216
Conversation
Brings the kernel's OAuth token cache in line with the JDBC driver, and
adds the sync-metadata header JDBC already sends.
TOKEN CACHE
The cache held a long-lived refresh token as PLAINTEXT JSON, and there
was no way to turn it off: no setter, no session-conf key, no env var, no
feature flag. Two problems fall out of that.
The confidentiality one is obvious. The availability one is not, and it
is the reason this needed a knob rather than just encryption: when a
cached refresh token is expired or revoked, u2m.rs deliberately does NOT
fall back to the browser flow (it returns `unauthenticated` instead, so a
headless server does not block for the ~120s callback timeout — see the
comment there). That is right for servers, but with no opt-out a poisoned
cache file wedges U2M auth and the user's only recovery is finding and
deleting a file under ~/.config/databricks-sql-kernel/oauth/.
Worth stating plainly, since it was the original worry: filesystem
failures were already SAFE. `save()` returns `()` and `load()` returns
`Option`, and all six failure paths were `warn! + return`. Verified
against an unwritable config dir — permission denied, warn only, auth
proceeds. (`dirs::config_dir()` also does not return None when HOME is
unset on Linux; it falls back to the passwd database. So the realistic
container case is an unwritable passwd-derived home, which lands on
`create_dir_all` and still only warns.) Nothing here changes that.
New `TokenCacheConfig { enabled, passphrase }` with `resolve()` as the
single decision point, matching JDBC exactly:
enabled (default) + passphrase -> encrypted cache
enabled (default) + none/blank -> InvalidArgument at connect
disabled -> no disk I/O, no passphrase needed
The middle row is deliberate JDBC parity (ClientConfigurator.java:226 —
"No token cache passphrase configured") and it IS a behaviour change:
plain U2M connections that cache today will now fail until they supply a
passphrase or opt out. That is the point — there is no plaintext
fallback, so we would otherwise be silently weaker than JDBC at identical
settings. A blank passphrase is rejected alongside an absent one because
it is almost always an unexpanded config placeholder.
Disabling stops DISK PERSISTENCE ONLY; the in-memory TokenStore still
reuses and refreshes for the session's lifetime, so it does not
re-trigger the browser on every refresh. Same as JDBC's NoOpTokenCache.
The crypto (cache_crypto.rs) is AES-256-CBC + PBKDF2-HMAC-SHA256, 65_536
iterations, random 16-byte salt and IV per save, payload
base64(salt || iv || ciphertext). Every parameter is fixed by
compatibility with JDBC's EncryptedFileTokenCache rather than chosen
fresh — AES-GCM would be the better default for new code, and the module
doc says so and explains why integrity adds little for this threat model
(0o600 file in a 0o700 dir; an attacker who can rewrite it can usually
read the passphrase too).
Compatibility is not assumed. A payload was generated by running JDBC's
own crypto under OpenJDK 21, and the test that decrypts it is checked in
as a literal so it runs in CI with no JDK. The reverse direction was
confirmed too: Java decrypts what this writes back to the original JSON.
New `kernel_session_config_set_token_cache(config, enabled, passphrase)`
exposes this over the C ABI. Chosen over the client-only session_conf
route used by cloudfetch_max_chunks_in_memory because auth posture is a
first-class connection property, not result tuning, and a typed setter
beats a stringly-typed bag for something that can fail the connection.
The napi binding and the U2M e2e test explicitly DISABLE the cache:
neither has anywhere to keep a passphrase, and defaulting them to enabled
would fail every U2M connection from Node. Wiring a passphrase through
`options` is what would turn it back on.
SEA SYNC METADATA
Adds `x-databricks-sea-can-run-fully-sync: true` on metadata queries,
gated on the same three conditions as JDBC (DatabricksSdkClient.java:704):
flag enabled, statement is metadata, execution synchronous. Advisory —
a server that does not recognise it ignores it.
`RequestType::ExecuteMetadataQuery` already carried the distinction, so
this is one chokepoint in `call_execute_api` rather than nine `list_*`
methods. The async gate comes free: `submit_statement` hardcodes
`ExecuteStatement`, so a metadata query only reaches here synchronously.
Exposed as `kernel_session_config_set_sea_sync_metadata`, default on.
TESTS
Every U2M test that seeds the cache had to move from `new_with_config`
to `new_with_full_config`: the former now disables disk caching, so those
tests would have kept passing while exercising nothing. One of them
(test_u2m_cache_miss_with_expired_refresh) caught this by failing
outright, which is how the vacuous-pass risk in the rest was found.
The new save/load roundtrip test asserts the tokens are NOT readable on
disk and that a wrong passphrase misses; removing the encrypt call makes
it fail, so it is a real assertion. It also pins the file at 0o600 —
encryption is not a reason to widen what the plaintext version had.
It reaches the real save/load through new path-injecting seams
(`cache_dir_under` / `cache_file_path_in` / `save_to` / `load_from`)
rather than `XDG_CONFIG_HOME`. The env var is process-global: redirecting
it raced the U2M tests, which passed alone and failed only under a full
parallel run, and serialized the suite from 10s to 124s.
735 unit + all integration suites pass. clippy clean. cargo-deny
licenses and advisories both ok — the four RustCrypto crates are dual
Apache-2.0/MIT, already allow-listed, so deny.toml is unchanged.
Co-authored-by: Isaac
Signed-off-by: Vikrant Puppala <vikrant.puppala@databricks.com>
e1171af to
cbb3b50
Compare
There was a problem hiding this comment.
Verdict: 1 High
One blocker: the token_cache field added to AuthConfig::OAuthU2M was wired through every site except the pyo3 binding (pyo3/src/auth.rs), which builds against this source tree via path = ".." and constructs the variant as an exhaustive struct literal — a guaranteed compile break for the Python wheel (and its tests). The rest of the change is solid: the crypto module is well-tested (including JDBC interop and tamper/whitespace/length edge cases), resolve() centralizes the enabled-without-passphrase policy with good coverage, and the napi/e2e sites correctly disable the cache.
Other findings
- 🟠 High — The pyo3 binding will fail to compile against this PR.
AuthConfig::OAuthU2Mgained a requiredtoken_cache: Option<TokenCacheConfig>field (src/config.rs:347), and pyo3 builds against this exact source tree (databricks-sql-kernel = { path = ".." }inpyo3/Cargo.toml). The struct literal here constructs the variant withouttoken_cache:
Ok(AuthConfig::OAuthU2M {
client_id,
redirect_port: oauth.redirect_port,
scopes,
token_url_override: oauth.token_url,
callback_timeout: oauth.callback_timeout_secs.map(Duration::from_secs),
})That is a hard missing field \token_cache`error (Rust struct literals are exhaustive unless..Default::default()is used). The four exhaustivematcharms in this file's tests (lines 340, 372, 400, 423) will likewise fail withpattern does not mention field `token_cache`, breaking cargo test -p databricks-sql-kernel-pyo3underpyo3-checks.yml`.
The napi binding was updated (napi/src/database.rs disables the cache with an explicit Some(TokenCacheConfig { enabled: false, passphrase: None })), and every in-crate site (src/session.rs, src/c_abi/session.rs) was updated too — pyo3 is the one consumer that was missed. It needs the same treatment as napi: the Node binding has nowhere to keep a passphrase, and the default (enabled: true, passphrase: None) would fail every U2M connection from Python at connect time. Add token_cache: Some(TokenCacheConfig { enabled: false, passphrase: None }) to the construction (and the field to the test match arms), or explicitly wire a passphrase option through OAuthParams.
CI caught this: the PyO3 build failed on every Python version (3.9-3.14) with `missing field token_cache`. My earlier check for affected call sites grepped for `oauth_u2m` and so found the napi binding but missed this one, which constructs the `AuthConfig::OAuthU2M` struct variant directly. Same resolution as napi, for the same reason: `OAuthParams` exposes no passphrase option, and the cache now defaults to enabled-and-requiring-one, so leaving the default would make every Python U2M connection fail at connect time. Consequence worth stating rather than burying: this drops cross-connection SSO reuse for Python U2M — each new session runs the browser flow instead of picking up a cached refresh token. In-process reuse via TokenStore is unaffected. Restoring persistence means surfacing a passphrase through `OAuthParams` (the equivalent of JDBC's TokenCachePassPhrase). Also corrects the `PYSQL_OAUTH_CLIENT_ID` doc comment, which claimed the default client id yields "the same SSO token cache entry" as the standalone Thrift connector. That was already only half right — the kernel writes to its own directory and the Thrift connector caches U2M tokens in memory only — and with disk caching off it would be plainly wrong. The client identity and cache-key isolation it describes still hold. The `u2m_defaults_to_python_client_id` test now binds `token_cache` and asserts it is disabled, so the binding cannot silently regain a cache it has no passphrase for. Left as a `cargo test` assertion rather than a comment because the failure mode (connect-time error on every U2M connection) is not something a reader would infer from the struct literal. pyo3: 14 tests pass, clippy clean. Signed-off-by: Vikrant Puppala <vikrant.puppala@databricks.com> Co-authored-by: Isaac
There was a problem hiding this comment.
Verdict: 1 Low
Solid, well-tested change — the crypto module has strong coverage (JDBC interop fixture, roundtrip, tamper/wrong-passphrase/malformed cases), the resolve() gating is correctly scoped to the U2M auth arm so PAT/M2M are untouched, and the sync-metadata header is properly gated to the synchronous ExecuteMetadataQuery path. One low-severity heads-up about the intentional ABI default behaviour change for existing U2M C consumers.
| ignore_transactions: true, | ||
| // Match JDBC's EnableSeaSyncMetadata=1. | ||
| sea_sync_metadata: true, | ||
| // Match JDBC's EnableTokenCache=1 (passphrase still required). |
There was a problem hiding this comment.
🔵 Low — The C ABI now defaults the token cache to enabled with no passphrase, and TokenCacheConfig::resolve() turns that combination into a hard InvalidArgument at kernel_session_open time (for U2M auth only). This is a behaviour change on a stability surface: any existing C-ABI consumer that authenticates via U2M and never calls kernel_session_config_set_token_cache used to get a working (plaintext) cache and will now fail to connect until it either supplies a passphrase or explicitly disables the cache.
The change is intentional and well-documented (JDBC parity, no plaintext fallback), and PAT/M2M are correctly unaffected since resolve() is only invoked in the OAuthU2M arm — so this is a heads-up rather than a defect. Worth confirming downstream C/ODBC/Go consumers are updated in lockstep, and calling the break out in release notes so U2M integrations aren't surprised at connect time.
Two changes, both narrowing the API surface this PR adds.
TOKEN CACHE: reference-driver parity instead of JDBC parity
The previous commit made enabled-without-passphrase a hard InvalidArgument
at connect, matching JDBC's ClientConfigurator ("No token cache passphrase
configured"). That was the wrong bar to copy for this surface.
The reference ODBC driver ships EnableTokenCache=1 with TokenCachePassPhrase
empty and still connects. So a U2M DSN that never set a passphrase — the
default shape — works against the reference and would have failed against
us. For a driver whose whole Beta bar is drop-in DSN compatibility, that is
a regression dressed up as strictness. (JDBC's own TokenCachePassPhrase has
no default either, so in practice JDBC fails on its own default config; not
a precedent worth matching.)
`resolve()` is now infallible: no passphrase, or a blank one, yields a
machine-local derived key rather than an error. There is still no plaintext
mode — the file is always AES-256-CBC.
Blank is treated as absent rather than honoured literally. A blank
passphrase is nearly always an unexpanded placeholder (`$TOKEN_PASS` that
never got substituted), and keying every machine's cache off `""` would be
strictly weaker than the derived fallback.
On what the derived key is worth: it is obfuscation against the wrong
reader, not defence against a local attacker, and `derived_passphrase`'s doc
says so in those words. It protects a cache file that gets copied off the
box — backup, container image layer, support bundle, synced home directory —
and stops `cat` from yielding a live credential. It does not stop anyone who
can run code as this user, who can derive the same key by construction. A
caller-supplied passphrase remains strictly stronger and the docs say when
to use one.
Composed from username + a fixed version tag. Deliberately NOT the hostname:
containers get a fresh random hostname per start, which would silently make
every restart a cache miss — the "why am I getting a browser prompt every
time" failure the cache exists to prevent. Deliberately not a random
per-install file either: more state to create, protect, and fail to create,
buying nothing over the 0o600 mode already set.
Consequence: pyo3 and napi no longer disable the cache. They were only
disabling it because they cannot supply a passphrase and the default would
have failed their connections. With a derived-key fallback they take the
default, so Python and Node regain cross-connection SSO reuse instead of
re-running the browser flow per session. The pyo3 doc comment about sharing
a cache *entry* with the Thrift connector is restored to its accurate form
(client identity is aligned; the on-disk cache is not, since Thrift caches
in memory only).
The U2M e2e test still disables the cache, but for the reason that actually
applies to it: keeping runs independent, so a token cached by an earlier run
cannot skip the browser flow the test exercises.
SEA SYNC METADATA: drop the flag
Removes kernel_session_config_set_sea_sync_metadata, the DefaultOpts and
TransportConfig fields, the C header declaration, and the default test. The
`x-databricks-sea-can-run-fully-sync` header now goes out unconditionally on
metadata queries.
The header is advisory — a server that does not recognise it ignores it and
the query still succeeds — so a knob whose only two settings are "faster"
and "same but slower" is a support liability, not a feature. JDBC exposes
EnableSeaSyncMetadata for this; we deliberately do not.
Worth recording for whoever reads the header code next: server-side,
`runAsync = !(canRunFullySync && shouldGetDirectResults && isFromKnownDriver)`,
so the header is a no-op for any driver whose UA prefix is not in the
`databricks.sqlexecapi.known_driver_prefixes` SAFE flag. The gating that
matters is server-side, which is another reason a client flag adds nothing.
737 unit tests + all integration suites pass. clippy clean across the
kernel, pyo3, and napi. New tests pin that the derived key is deterministic
(a non-reproducible fallback would mean a cache miss on every connection),
that it round-trips a token without leaking it in the payload, and that a
different key cannot open it — so the fallback is a real key and not a
shared constant.
Signed-off-by: Vikrant Puppala <vikrant.puppala@databricks.com>
Co-authored-by: Isaac
There was a problem hiding this comment.
Verdict: 1 Low
Looks good — solid, well-tested change. The crypto module, TokenCacheConfig::resolve, and the U2M passphrase threading are all thoroughly covered (including a JDBC interop fixture and an on-disk owner-only-permissions assertion), and the cache-disabling constructors are only reached from tests — production goes through new_with_full_config. One low-severity gap: the new SEA sync-metadata header has no test despite an existing wiremock harness.
| // async path routes through `submit_statement` with | ||
| // `RequestType::ExecuteStatement`, so `ExecuteMetadataQuery` only ever | ||
| // reaches here on the synchronous path. | ||
| if request_type == RequestType::ExecuteMetadataQuery { |
There was a problem hiding this comment.
🔵 Low — The new x-databricks-sea-can-run-fully-sync header is emitted unconditionally on every metadata query, but nothing asserts it is actually sent. This is a protocol-level (wire) change, and the repo already has a v0_metadata_wiremock.rs harness plus wiremock's request-recording (server.received_requests(), used in v0_async_execute_wiremock.rs) that could pin it. Without a test, a future refactor of the request-builder chain could silently drop the header (or add it to the async ExecuteStatement path) with no failing test. Consider adding a wiremock assertion that a metadata query carries the header and a regular execute does not.
Note the header value is advisory and unknown-header-tolerant server-side, so the functional risk today is low — this is a coverage gap, not a correctness bug.
Brings the U2M token cache in line with the JDBC driver, and adds the sync-metadata header JDBC already sends.
Why
The cache held a long-lived refresh token as plaintext JSON, and there was no way to turn it off — no setter, no session-conf key, no env var, no feature flag. Two problems fall out of that.
The confidentiality one is obvious. The availability one is not, and it is the reason this needed a knob and not just encryption: when a cached refresh token is expired or revoked,
u2m.rsdeliberately does not fall back to the browser flow — it returnsunauthenticated, so a headless server doesn't block for the ~120s callback timeout. That's right for servers, but with no opt-out a poisoned cache file wedges U2M auth and the user's only recovery is finding and deleting a file under~/.config/databricks-sql-kernel/oauth/.Worth stating plainly, since it was the original concern: filesystem failures were already safe.
save()returns(),load()returnsOption, and all six failure paths werewarn! + return. Verified against an unwritable config dir — permission denied, warn only, auth proceeds. (dirs::config_dir()also does not returnNonewhenHOMEis unset on Linux; it falls back to the passwd database, so the realistic container case is an unwritable passwd-derived home, which lands oncreate_dir_alland still only warns.) Nothing here changes that.Token cache
New
TokenCacheConfig { enabled, passphrase }withresolve()as the single decision point, matching JDBC exactly:enabledpassphrasetrue(default)true(default)falseNo connection ever fails over this, which is a deliberate departure from JDBC. The reference ODBC driver ships
EnableTokenCache=1withTokenCachePassPhraseempty and still connects, so failing there would break drop-in compatibility for the default DSN shape. JDBC does throw in that case (ClientConfigurator.java:226), and since itsTokenCachePassPhrasehas no default either, JDBC effectively fails on its own default config — not a precedent worth matching.A blank passphrase is treated as absent rather than honoured: it's nearly always an unexpanded placeholder, and keying every machine off
""would be strictly weaker than the derived fallback.What the derived key is worth. It is obfuscation against the wrong reader, not defence against a local attacker, and the code says so in those words. It protects a cache file copied off the box — backup, container image layer, support bundle, synced home directory — and stops
catfrom yielding a live credential. It does not stop anyone who can run code as this user, who can derive the same key by construction. A caller-supplied passphrase remains strictly stronger.Composed from username + a fixed version tag. Deliberately not the hostname: containers get a fresh random hostname per start, which would silently make every restart a cache miss — the exact "why am I getting a browser prompt every time" failure the cache exists to prevent.
Disabling stops disk persistence only. The in-memory
TokenStorestill reuses and refreshes for the session's lifetime, so it does not re-trigger the browser on every refresh — same as JDBC'sNoOpTokenCache.Crypto
AES-256-CBC + PBKDF2-HMAC-SHA256, 65,536 iterations, random 16-byte salt and IV per save, payload
base64(salt ‖ iv ‖ ciphertext).Every parameter is fixed by compatibility with JDBC's
EncryptedFileTokenCacherather than chosen fresh. AES-GCM would be the better default for new code; the module doc says so and explains why integrity adds little for this threat model (0o600file in a0o700dir — an attacker who can rewrite it can usually read the passphrase too).Compatibility is verified, not assumed. A payload was generated by running JDBC's own crypto under OpenJDK 21; the test that decrypts it is checked in as a literal so it runs in CI with no JDK present. The reverse direction was confirmed too — Java decrypts what this writes, back to the original JSON.
C ABI
kernel_session_config_set_token_cache(config, enabled, passphrase)Chosen over the client-only
session_confroute used bycloudfetch_max_chunks_in_memory: auth posture is a first-class connection property, not result tuning, and a typed setter beats a stringly-typed bag for something that can fail the connection.The pyo3 and napi bindings take the default rather than disabling the cache, so Python and Node get cross-connection SSO reuse encrypted under the derived key. The U2M e2e test still disables it, for the reason that actually applies there: keeping runs independent, so a token cached by an earlier run cannot skip the browser flow the test exercises.
SEA sync metadata
Adds
x-databricks-sea-can-run-fully-sync: trueon synchronous metadata queries, unconditionally — with no config knob. The header is advisory (a server that doesn't recognise it ignores it), so a flag whose only two settings are "faster" and "same but slower" is a support liability rather than a feature. JDBC exposesEnableSeaSyncMetadatafor this; we deliberately don't.RequestType::ExecuteMetadataQueryalready carried the distinction, so this is one chokepoint incall_execute_apirather than ninelist_*methods. The async gate comes free:submit_statementhardcodesExecuteStatement, so a metadata query only reaches here synchronously.Worth knowing for whoever reads this next: server-side,
runAsync = !(canRunFullySync && shouldGetDirectResults && isFromKnownDriver), so the header is a no-op for any driver whose UA prefix isn't in thedatabricks.sqlexecapi.known_driver_prefixesSAFE flag. The gating that matters is server-side — another reason a client flag adds nothing.Tests
Every U2M test that seeds the cache had to move from
new_with_configtonew_with_full_config: the former now disables disk caching, so those tests would have kept passing while exercising nothing. One (test_u2m_cache_miss_with_expired_refresh) failed outright, which is how the vacuous-pass risk in the rest was found.The new save/load roundtrip test asserts the tokens are not readable on disk and that a wrong passphrase misses. Removing the encrypt call makes it fail, so it's a real assertion. It also pins the file at
0o600— encryption is not a reason to widen what the plaintext version had.It reaches the real save/load through new path-injecting seams (
cache_dir_under/cache_file_path_in/save_to/load_from) rather thanXDG_CONFIG_HOME. That env var is process-global: redirecting it raced the U2M tests, which passed alone and failed only under a full parallel run, and serialized the suite from 10s to 124s.Verification
cargo clippycleancargo deny check licenses→ ok;advisories→ ok. The four RustCrypto crates are dual Apache-2.0/MIT, both already allow-listed, sodeny.tomlis unchanged.Follow-up
The ODBC driver currently lists
EnableTokenCacheas an unsupported option whose behaviour already matches the default. Once this is pinned there it graduates into a real connection parameter, withTokenCachePassPhrasealongside it as the opt-in upgrade from the derived key.This pull request and its description were written by Isaac.