diff --git a/Cargo.lock b/Cargo.lock index 18e2edce..db2145b8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -8,6 +8,18 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" +[[package]] +name = "aes" +version = "0.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8eb277bec05f56a0e0591f155a484cbd0f4f07ff2905051a48c72f004f7ed58" +dependencies = [ + "cipher", + "cpubits", + "cpufeatures 0.3.0", + "zeroize", +] + [[package]] name = "ahash" version = "0.8.12" @@ -234,6 +246,16 @@ name = "block-buffer" version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" +dependencies = [ + "hybrid-array", + "zeroize", +] + +[[package]] +name = "block-padding" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "710f1dd022ef4e93f8a438b4ba958de7f64308434fa6a87104481645cc30068b" dependencies = [ "hybrid-array", ] @@ -250,6 +272,15 @@ version = "1.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" +[[package]] +name = "cbc" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce2dc9ee5f88d11e0beb842c88b33c8a5cf0d1329c4b19494af42b07dbfe8896" +dependencies = [ + "cipher", +] + [[package]] name = "cc" version = "1.2.66" @@ -297,6 +328,24 @@ dependencies = [ "windows-link", ] +[[package]] +name = "cipher" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8cf2a2c93cd704877c0858356ed03480ff301ee950b43f1cbe4573b088bfa6c" +dependencies = [ + "block-buffer 0.12.1", + "crypto-common 0.2.2", + "inout", + "zeroize", +] + +[[package]] +name = "cmov" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a" + [[package]] name = "compression-codecs" version = "0.4.38" @@ -356,6 +405,12 @@ version = "0.8.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" +[[package]] +name = "cpubits" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15b85f9c39137c3a891689859392b1bd49812121d0d61c9caf00d46ed5ce06ae" + [[package]] name = "cpufeatures" version = "0.2.17" @@ -414,6 +469,15 @@ dependencies = [ "hybrid-array", ] +[[package]] +name = "ctutils" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d5515a3834141de9eafb9717ad39eea8247b5674e6066c404e8c4b365d2a29e" +dependencies = [ + "cmov", +] + [[package]] name = "dashmap" version = "6.2.1" @@ -432,6 +496,7 @@ dependencies = [ name = "databricks-sql-kernel" version = "0.2.0" dependencies = [ + "aes", "arrow-array", "arrow-buffer", "arrow-cast", @@ -441,15 +506,18 @@ dependencies = [ "arrow-select", "async-trait", "base64", + "cbc", "chrono", "dashmap", "dirs", "futures", "hex", + "hmac", "log", "lz4_flex", "oauth2", "open", + "pbkdf2", "rand 0.10.2", "reqwest", "serde", @@ -462,6 +530,7 @@ dependencies = [ "tracing", "tracing-subscriber", "wiremock", + "zeroize", ] [[package]] @@ -501,6 +570,7 @@ dependencies = [ "block-buffer 0.12.1", "const-oid", "crypto-common 0.2.2", + "ctutils", ] [[package]] @@ -805,6 +875,15 @@ version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" +[[package]] +name = "hmac" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6303bc9732ae41b04cb554b844a762b4115a61bfaa81e3e83050991eeb56863f" +dependencies = [ + "digest 0.11.3", +] + [[package]] name = "http" version = "1.4.2" @@ -857,6 +936,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "818356c5132c1fede50f837ca96afbe78ff42413047f4abb886217845e1b6c8c" dependencies = [ "typenum", + "zeroize", ] [[package]] @@ -1073,6 +1153,16 @@ dependencies = [ "hashbrown 0.17.1", ] +[[package]] +name = "inout" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4250ce6452e92010fdf7268ccc5d14faa80bb12fc741938534c58f16804e03c7" +dependencies = [ + "block-padding", + "hybrid-array", +] + [[package]] name = "ipnet" version = "2.12.0" @@ -1459,6 +1549,16 @@ dependencies = [ "windows-link", ] +[[package]] +name = "pbkdf2" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "112d82ceb8c5bf524d9af484d4e4970c9fd5a0cc15ba14ad93dccd28873b0629" +dependencies = [ + "digest 0.11.3", + "hmac", +] + [[package]] name = "percent-encoding" version = "2.3.2" diff --git a/Cargo.toml b/Cargo.toml index b1154b25..bf75044d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -101,6 +101,18 @@ sha2 = "0.11" # SHA-256 for token cache key generation open = "5" # Browser launch for interactive OAuth flows dirs = "6" # Cross-platform config directory (~/.config/) +# Token-cache encryption at rest. The cached OAuth payload holds a +# long-lived refresh token, so it is encrypted with AES-256-CBC under a +# PBKDF2-HMAC-SHA256 key derived from a caller-supplied passphrase. The +# parameters mirror the JDBC driver's EncryptedFileTokenCache so both +# drivers give the same file the same protection. All four are RustCrypto +# crates, dual Apache-2.0/MIT (both already allow-listed in deny.toml). +aes = { version = "0.9.2", features = ["zeroize"] } # AES-256 block cipher +cbc = { version = "0.2.1", features = ["alloc", "block-padding", "zeroize"] } # CBC mode + PKCS#7 padding +pbkdf2 = { version = "0.13.0", default-features = false, features = ["hmac"] } # Passphrase-based key derivation +hmac = "0.13.0" # PRF backing PBKDF2 +zeroize = "1.9" # Wipe derived key material on drop + [dev-dependencies] tokio = { version = "1", features = ["rt-multi-thread", "macros"] } wiremock = "0.6" diff --git a/include/databricks_kernel.h b/include/databricks_kernel.h index a2188e6f..8e545518 100644 --- a/include/databricks_kernel.h +++ b/include/databricks_kernel.h @@ -346,6 +346,34 @@ KernelStatusCode kernel_session_config_set_retry_config(KernelSessionConfig* con KernelStatusCode kernel_session_config_set_ignore_transactions(KernelSessionConfig* config, bool ignore); +/* Configure the on-disk OAuth token cache for U2M (browser) auth. Mirrors + * the EnableTokenCache / TokenCachePassPhrase pair exposed by the reference + * ODBC driver and JDBC. + * + * `enabled = true` (the default) persists the refresh token under + * ~/.config/databricks-sql-kernel/oauth/ so the user is not sent through + * the browser on every connection. The file is ALWAYS encrypted + * (AES-256-CBC, PBKDF2-HMAC-SHA256) — there is no plaintext mode. A + * non-NULL `passphrase` keys it; NULL or blank falls back to a + * machine-local derived key, matching the reference driver, which caches + * with an empty TokenCachePassPhrase. Supplying a passphrase is stronger: + * the derived key defends against the cache file being read elsewhere (a + * backup, an image layer, a support bundle), not against an attacker who + * can already run code as this user. + * + * `enabled = false` disables DISK PERSISTENCE ONLY; tokens are still + * reused and refreshed in memory for the session's lifetime, so this does + * not re-trigger the browser flow on every refresh. Use it when the + * process must not write credentials to disk at all. `passphrase` is + * ignored in that case. + * + * Only U2M auth touches the cache; PAT and M2M ignore this setting. + * + * The on-disk format is wire-compatible with the JDBC driver's + * EncryptedFileTokenCache (given the same passphrase). */ +KernelStatusCode kernel_session_config_set_token_cache(KernelSessionConfig* config, bool enabled, + const char* passphrase); + /* ─── Session lifecycle ───────────────────────────────────────────────*/ /* diff --git a/napi/Cargo.lock b/napi/Cargo.lock index 90a14f46..8c4b4a20 100644 --- a/napi/Cargo.lock +++ b/napi/Cargo.lock @@ -8,6 +8,18 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" +[[package]] +name = "aes" +version = "0.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8eb277bec05f56a0e0591f155a484cbd0f4f07ff2905051a48c72f004f7ed58" +dependencies = [ + "cipher", + "cpubits", + "cpufeatures 0.3.0", + "zeroize", +] + [[package]] name = "ahash" version = "0.8.12" @@ -224,6 +236,16 @@ name = "block-buffer" version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" +dependencies = [ + "hybrid-array", + "zeroize", +] + +[[package]] +name = "block-padding" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "710f1dd022ef4e93f8a438b4ba958de7f64308434fa6a87104481645cc30068b" dependencies = [ "hybrid-array", ] @@ -240,6 +262,15 @@ version = "1.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" +[[package]] +name = "cbc" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce2dc9ee5f88d11e0beb842c88b33c8a5cf0d1329c4b19494af42b07dbfe8896" +dependencies = [ + "cipher", +] + [[package]] name = "cc" version = "1.2.66" @@ -287,6 +318,24 @@ dependencies = [ "windows-link", ] +[[package]] +name = "cipher" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8cf2a2c93cd704877c0858356ed03480ff301ee950b43f1cbe4573b088bfa6c" +dependencies = [ + "block-buffer 0.12.1", + "crypto-common 0.2.2", + "inout", + "zeroize", +] + +[[package]] +name = "cmov" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a" + [[package]] name = "compression-codecs" version = "0.4.38" @@ -345,6 +394,12 @@ version = "0.8.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" +[[package]] +name = "cpubits" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15b85f9c39137c3a891689859392b1bd49812121d0d61c9caf00d46ed5ce06ae" + [[package]] name = "cpufeatures" version = "0.2.17" @@ -409,6 +464,15 @@ version = "1.0.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fb22e947478ccf9dc44d8922042c677a63fbb88f2cb468521d1145816e5087cb" +[[package]] +name = "ctutils" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d5515a3834141de9eafb9717ad39eea8247b5674e6066c404e8c4b365d2a29e" +dependencies = [ + "cmov", +] + [[package]] name = "dashmap" version = "6.2.1" @@ -427,6 +491,7 @@ dependencies = [ name = "databricks-sql-kernel" version = "0.2.0" dependencies = [ + "aes", "arrow-array", "arrow-buffer", "arrow-cast", @@ -436,14 +501,17 @@ dependencies = [ "arrow-select", "async-trait", "base64", + "cbc", "chrono", "dashmap", "dirs", "futures", "hex", + "hmac", "lz4_flex", "oauth2", "open", + "pbkdf2", "rand 0.10.2", "reqwest", "serde", @@ -454,6 +522,7 @@ dependencies = [ "tokio-util", "tracing", "tracing-subscriber", + "zeroize", ] [[package]] @@ -495,6 +564,7 @@ dependencies = [ "block-buffer 0.12.1", "const-oid", "crypto-common 0.2.2", + "ctutils", ] [[package]] @@ -741,6 +811,15 @@ version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" +[[package]] +name = "hmac" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6303bc9732ae41b04cb554b844a762b4115a61bfaa81e3e83050991eeb56863f" +dependencies = [ + "digest 0.11.3", +] + [[package]] name = "http" version = "1.4.2" @@ -787,6 +866,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "818356c5132c1fede50f837ca96afbe78ff42413047f4abb886217845e1b6c8c" dependencies = [ "typenum", + "zeroize", ] [[package]] @@ -975,6 +1055,16 @@ dependencies = [ "icu_properties", ] +[[package]] +name = "inout" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4250ce6452e92010fdf7268ccc5d14faa80bb12fc741938534c58f16804e03c7" +dependencies = [ + "block-padding", + "hybrid-array", +] + [[package]] name = "ipnet" version = "2.12.0" @@ -1359,6 +1449,16 @@ dependencies = [ "windows-link", ] +[[package]] +name = "pbkdf2" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "112d82ceb8c5bf524d9af484d4e4970c9fd5a0cc15ba14ad93dccd28873b0629" +dependencies = [ + "digest 0.11.3", + "hmac", +] + [[package]] name = "percent-encoding" version = "2.3.2" diff --git a/napi/src/database.rs b/napi/src/database.rs index bc769d24..ddf139df 100644 --- a/napi/src/database.rs +++ b/napi/src/database.rs @@ -394,6 +394,11 @@ fn build_auth_config(options: &ConnectionOptions) -> napi::Result { options.oauth_scopes.clone(), None, 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, )) } } diff --git a/pyo3/Cargo.lock b/pyo3/Cargo.lock index f1d717c7..982aa7a1 100644 --- a/pyo3/Cargo.lock +++ b/pyo3/Cargo.lock @@ -8,6 +8,18 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" +[[package]] +name = "aes" +version = "0.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8eb277bec05f56a0e0591f155a484cbd0f4f07ff2905051a48c72f004f7ed58" +dependencies = [ + "cipher", + "cpubits", + "cpufeatures 0.3.0", + "zeroize", +] + [[package]] name = "ahash" version = "0.8.12" @@ -245,6 +257,16 @@ name = "block-buffer" version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" +dependencies = [ + "hybrid-array", + "zeroize", +] + +[[package]] +name = "block-padding" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "710f1dd022ef4e93f8a438b4ba958de7f64308434fa6a87104481645cc30068b" dependencies = [ "hybrid-array", ] @@ -261,6 +283,15 @@ version = "1.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" +[[package]] +name = "cbc" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce2dc9ee5f88d11e0beb842c88b33c8a5cf0d1329c4b19494af42b07dbfe8896" +dependencies = [ + "cipher", +] + [[package]] name = "cc" version = "1.2.66" @@ -308,6 +339,24 @@ dependencies = [ "windows-link", ] +[[package]] +name = "cipher" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8cf2a2c93cd704877c0858356ed03480ff301ee950b43f1cbe4573b088bfa6c" +dependencies = [ + "block-buffer 0.12.1", + "crypto-common 0.2.2", + "inout", + "zeroize", +] + +[[package]] +name = "cmov" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a" + [[package]] name = "compression-codecs" version = "0.4.38" @@ -357,6 +406,12 @@ version = "0.8.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" +[[package]] +name = "cpubits" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15b85f9c39137c3a891689859392b1bd49812121d0d61c9caf00d46ed5ce06ae" + [[package]] name = "cpufeatures" version = "0.2.17" @@ -415,6 +470,15 @@ dependencies = [ "hybrid-array", ] +[[package]] +name = "ctutils" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d5515a3834141de9eafb9717ad39eea8247b5674e6066c404e8c4b365d2a29e" +dependencies = [ + "cmov", +] + [[package]] name = "dashmap" version = "6.2.1" @@ -433,6 +497,7 @@ dependencies = [ name = "databricks-sql-kernel" version = "0.2.0" dependencies = [ + "aes", "arrow-array", "arrow-buffer", "arrow-cast", @@ -442,14 +507,17 @@ dependencies = [ "arrow-select", "async-trait", "base64", + "cbc", "chrono", "dashmap", "dirs", "futures", "hex", + "hmac", "lz4_flex", "oauth2", "open", + "pbkdf2", "rand 0.10.2", "reqwest", "serde", @@ -460,6 +528,7 @@ dependencies = [ "tokio-util", "tracing", "tracing-subscriber", + "zeroize", ] [[package]] @@ -497,6 +566,7 @@ dependencies = [ "block-buffer 0.12.1", "const-oid", "crypto-common 0.2.2", + "ctutils", ] [[package]] @@ -749,6 +819,15 @@ version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" +[[package]] +name = "hmac" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6303bc9732ae41b04cb554b844a762b4115a61bfaa81e3e83050991eeb56863f" +dependencies = [ + "digest 0.11.3", +] + [[package]] name = "http" version = "1.4.2" @@ -795,6 +874,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "818356c5132c1fede50f837ca96afbe78ff42413047f4abb886217845e1b6c8c" dependencies = [ "typenum", + "zeroize", ] [[package]] @@ -983,6 +1063,16 @@ dependencies = [ "icu_properties", ] +[[package]] +name = "inout" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4250ce6452e92010fdf7268ccc5d14faa80bb12fc741938534c58f16804e03c7" +dependencies = [ + "block-padding", + "hybrid-array", +] + [[package]] name = "ipnet" version = "2.12.0" @@ -1138,9 +1228,9 @@ checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154" [[package]] name = "lz4_flex" -version = "0.13.1" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7ef0d4ed8669f8f8826eb00dc878084aa8f253506c4fd5e8f58f5bce72ddb97e" +checksum = "ecbdfe44b1bd960b68170b417450a628c43f7cf56bb3c5317e61cb230ee7f226" dependencies = [ "twox-hash", ] @@ -1293,6 +1383,16 @@ dependencies = [ "windows-link", ] +[[package]] +name = "pbkdf2" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "112d82ceb8c5bf524d9af484d4e4970c9fd5a0cc15ba14ad93dccd28873b0629" +dependencies = [ + "digest 0.11.3", + "hmac", +] + [[package]] name = "percent-encoding" version = "2.3.2" diff --git a/pyo3/src/auth.rs b/pyo3/src/auth.rs index e8eeea6c..cca1c74c 100644 --- a/pyo3/src/auth.rs +++ b/pyo3/src/auth.rs @@ -186,12 +186,17 @@ fn build_auth_config_inner( // kernel's bare-Rust fallback (`databricks-cli`). This // matches the standalone Thrift connector // (`PYSQL_OAUTH_CLIENT_ID` in databricks-sql-python's - // auth.py) so a user gets the same OAuth app identity — and - // the same SSO token cache entry — whether they use the - // Thrift backend or `use_kernel=True`. It also keeps the - // kernel's per-{host,client_id,scopes} token cache distinct - // from the napi (Node) binding's, which defaults to its own - // client. + // auth.py) so a user gets the same OAuth app identity whether + // they use the Thrift backend or `use_kernel=True`. It also + // keeps the kernel's per-{host,client_id,scopes} cache key + // distinct from the napi (Node) binding's, which defaults to + // its own client. + // + // Note this does NOT share a token cache *entry* with the + // standalone Thrift connector: the kernel writes to its own + // `~/.config/databricks-sql-kernel/oauth/` directory, and the + // Thrift connector caches U2M tokens in memory only. What is + // aligned is the OAuth app identity, not the on-disk cache. // // When BOTH defaults are in play (caller passed no // `client_id` and no `scopes`), also default the scopes to @@ -216,6 +221,14 @@ fn build_auth_config_inner( scopes, token_url_override: oauth.token_url, callback_timeout: 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. + token_cache: None, }) } other => Err(format!( @@ -343,6 +356,7 @@ mod tests { scopes, token_url_override, callback_timeout, + token_cache, } => { assert_eq!(client_id.as_deref(), Some("databricks-sql-python")); assert!(redirect_port.is_none()); @@ -352,6 +366,14 @@ mod tests { ); assert!(token_url_override.is_none()); assert!(callback_timeout.is_none()); + // Left as `None` so the kernel default applies: on-disk cache + // enabled, encrypted under a machine-local derived key. Pinned + // because overriding it here would silently drop the + // cross-connection SSO reuse the cache exists to provide. + assert!( + token_cache.is_none(), + "Python U2M should defer to the kernel's token-cache default" + ); } other => panic!("expected OAuthU2M, got {other:?}"), } diff --git a/src/auth/oauth/cache.rs b/src/auth/oauth/cache.rs index c317a90b..35862324 100644 --- a/src/auth/oauth/cache.rs +++ b/src/auth/oauth/cache.rs @@ -17,7 +17,14 @@ //! This module provides disk persistence for OAuth tokens across connections. //! The cache is separate from the Python SDK cache to avoid compatibility issues. //! Cache I/O errors are logged as warnings but never block authentication. +//! +//! The payload is **always encrypted** under a caller-supplied passphrase +//! (see [`super::cache_crypto`]) because it carries a long-lived refresh +//! token. Whether caching happens at all, and which passphrase is used, is +//! decided upstream by [`crate::config::TokenCacheConfig`]; reaching this +//! module already implies caching is enabled and a passphrase was supplied. +use super::cache_crypto; use super::token::OAuthToken; use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; @@ -76,22 +83,34 @@ impl TokenCache { /// Returns the cache directory path. /// Location: `~/.config/databricks-sql-kernel/oauth/` fn cache_dir() -> Option { - dirs::config_dir().map(|mut path| { - path.push("databricks-sql-kernel"); - path.push("oauth"); - path - }) + Self::cache_dir_under(dirs::config_dir()?) + } + + /// Returns the cache directory beneath an explicit config root. + /// + /// Split out from [`Self::cache_dir`] so tests can point the cache at a + /// temp directory without touching `XDG_CONFIG_HOME` — process-global + /// env state that would race against tests running in parallel. + fn cache_dir_under(config_root: PathBuf) -> Option { + let mut path = config_root; + path.push("databricks-sql-kernel"); + path.push("oauth"); + Some(path) } /// Returns the full cache file path for the given cache key. fn cache_file_path(host: &str, client_id: &str, scopes: &[String]) -> Option { - let cache_key = CacheKey::new(host, client_id, scopes); - let filename = cache_key.to_filename(); + Self::cache_dir().map(|dir| Self::cache_file_path_in(&dir, host, client_id, scopes)) + } - Self::cache_dir().map(|mut path| { - path.push(filename); - path - }) + /// Returns the cache file path for a key inside an explicit directory. + fn cache_file_path_in( + dir: &std::path::Path, + host: &str, + client_id: &str, + scopes: &[String], + ) -> PathBuf { + dir.join(CacheKey::new(host, client_id, scopes).to_filename()) } /// Loads a cached token if available. @@ -113,33 +132,59 @@ impl TokenCache { /// # Returns /// /// `Some(OAuthToken)` if a cached token is found, `None` otherwise. - pub fn load(host: &str, client_id: &str, scopes: &[String]) -> Option { + pub fn load( + host: &str, + client_id: &str, + scopes: &[String], + passphrase: &str, + ) -> Option { let cache_path = Self::cache_file_path(host, client_id, scopes)?; + Self::load_from(&cache_path, passphrase) + } + /// [`Self::load`] against an explicit path, so tests can exercise the + /// real decrypt-and-parse logic without depending on the user's config + /// directory. + fn load_from(cache_path: &std::path::Path, passphrase: &str) -> Option { // Check if cache file exists if !cache_path.exists() { crate::klog::debug!("Token cache miss: file does not exist at {:?}", cache_path); return None; } - // Read and deserialize the cache file - match fs::read_to_string(&cache_path) { - Ok(contents) => match serde_json::from_str::(&contents) { - Ok(token) => { - crate::klog::debug!("Token cache hit: loaded from {:?}", cache_path); - Some(token) - } - Err(e) => { - crate::klog::warn!( - "Token cache corrupted at {:?}, ignoring: {}", - cache_path, - e - ); - None - } - }, + // Read and decrypt the cache file + let raw = match fs::read(cache_path) { + Ok(raw) => raw, Err(e) => { crate::klog::warn!("Failed to read token cache at {:?}: {}", cache_path, e); + return None; + } + }; + + // A decrypt failure is reported as a miss, not an error: the usual + // cause is a passphrase change (or a file written under a different + // one), and the recovery — re-authenticate and overwrite — is the + // same as for a genuinely absent cache. Logged at WARN because it + // also covers a truncated or tampered file, which is worth seeing. + let plaintext = match cache_crypto::decrypt(&raw, passphrase) { + Some(plaintext) => plaintext, + None => { + crate::klog::warn!( + "Token cache at {:?} could not be decrypted (wrong passphrase, or the file \ + is corrupt); ignoring it and re-authenticating", + cache_path + ); + return None; + } + }; + + match serde_json::from_slice::(&plaintext) { + Ok(token) => { + crate::klog::debug!("Token cache hit: loaded from {:?}", cache_path); + Some(token) + } + Err(e) => { + crate::klog::warn!("Token cache corrupted at {:?}, ignoring: {}", cache_path, e); None } } @@ -158,7 +203,13 @@ impl TokenCache { /// * `client_id` - The OAuth client ID /// * `scopes` - The list of OAuth scopes /// * `token` - The token to save - pub fn save(host: &str, client_id: &str, scopes: &[String], token: &OAuthToken) { + pub fn save( + host: &str, + client_id: &str, + scopes: &[String], + token: &OAuthToken, + passphrase: &str, + ) { let cache_path = match Self::cache_file_path(host, client_id, scopes) { Some(path) => path, None => { @@ -166,7 +217,13 @@ impl TokenCache { return; } }; + Self::save_to(&cache_path, token, passphrase); + } + /// [`Self::save`] against an explicit path, so tests can exercise the + /// real encrypt-and-write logic (including the permission tightening) + /// without writing into the user's config directory. + fn save_to(cache_path: &std::path::Path, token: &OAuthToken, passphrase: &str) { // Create cache directory if it doesn't exist, with 700 permissions (owner only) if let Some(parent) = cache_path.parent() { if let Err(e) = fs::create_dir_all(parent) { @@ -181,14 +238,17 @@ impl TokenCache { } } - // Serialize token to JSON - let json = match serde_json::to_string_pretty(token) { + // Serialize token to JSON, then encrypt. `to_string` rather than + // `to_string_pretty`: the bytes are ciphertext, so the pretty-printed + // whitespace is unreadable anyway and only pads the payload. + let json = match serde_json::to_string(token) { Ok(j) => j, Err(e) => { crate::klog::warn!("Failed to serialize token for cache: {}", e); return; } }; + let json = cache_crypto::encrypt(json.as_bytes(), passphrase); // Write to a temporary file first, then rename for atomicity let temp_path = cache_path.with_extension("tmp"); @@ -220,7 +280,7 @@ impl TokenCache { } // Atomically rename temp file to final cache file - if let Err(e) = fs::rename(&temp_path, &cache_path) { + if let Err(e) = fs::rename(&temp_path, cache_path) { crate::klog::warn!( "Failed to rename temp cache file {:?} to {:?}: {}", temp_path, @@ -253,6 +313,73 @@ mod tests { ) } + /// End-to-end exercise of the REAL save / load pair. + /// + /// The other tests in this module hand-build the cache file, so none of + /// them would notice if `save` stopped encrypting or `load` stopped + /// decrypting. This one drives the actual write/read path and asserts on + /// the bytes that land on disk. + /// + /// Uses the path-injecting `save_to` / `load_from` rather than + /// redirecting `XDG_CONFIG_HOME`: the env var is process-global, and + /// mutating it here raced against the U2M tests that also read the + /// cache, failing them only under a full parallel run. + #[test] + fn save_then_load_roundtrips_and_file_is_encrypted() { + const PASSPHRASE: &str = "test-passphrase"; + + let temp_dir = TempDir::new().expect("Failed to create temp dir"); + let cache_dir = TokenCache::cache_dir_under(temp_dir.path().to_path_buf()) + .expect("cache dir under an explicit root always resolves"); + let cache_path = TokenCache::cache_file_path_in( + &cache_dir, + "https://roundtrip.cloud.databricks.com", + "client-roundtrip", + &["all-apis".to_string()], + ); + + let token = create_test_token(); + TokenCache::save_to(&cache_path, &token, PASSPHRASE); + + // 1. The round trip preserves the token. + let loaded = + TokenCache::load_from(&cache_path, PASSPHRASE).expect("saved token should load back"); + assert_eq!(loaded.access_token, token.access_token); + assert_eq!(loaded.refresh_token, token.refresh_token); + + // 2. The file on disk does NOT contain the tokens in the clear. This + // is the actual security property being added. + let on_disk = fs::read(&cache_path).expect("cache file should exist"); + let as_text = String::from_utf8_lossy(&on_disk); + assert!( + !as_text.contains("test-refresh-token"), + "refresh token must not be readable on disk" + ); + assert!( + !as_text.contains("test-access-token"), + "access token must not be readable on disk" + ); + + // 3. A different passphrase must not decrypt it — the file is + // genuinely keyed, not merely obfuscated. + assert!( + TokenCache::load_from(&cache_path, "wrong-passphrase").is_none(), + "load with the wrong passphrase must miss, not succeed" + ); + + // 4. The cache file is owner-only (0o600): encryption is not an + // excuse to widen the permissions the plaintext version had. + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let mode = fs::metadata(&cache_path) + .expect("cache file metadata") + .permissions() + .mode(); + assert_eq!(mode & 0o777, 0o600, "cache file must stay owner-only"); + } + } + #[test] fn test_cache_key_deterministic() { // Same inputs should produce the same filename @@ -349,6 +476,7 @@ mod tests { "https://nonexistent.cloud.databricks.com", "client-999", &["all-apis".to_string()], + "any-passphrase", ); assert!( diff --git a/src/auth/oauth/cache_crypto.rs b/src/auth/oauth/cache_crypto.rs new file mode 100644 index 00000000..334b8c43 --- /dev/null +++ b/src/auth/oauth/cache_crypto.rs @@ -0,0 +1,368 @@ +// 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. + +//! Passphrase-based encryption for the on-disk OAuth token cache. +//! +//! The cached payload contains a long-lived refresh token, so it is +//! encrypted at rest rather than written as plaintext JSON. The scheme is +//! chosen for **wire compatibility with the JDBC driver's** +//! `EncryptedFileTokenCache`, so both drivers protect the same file the +//! same way and neither is the weak link: +//! +//! * AES-256-CBC with PKCS#7 padding +//! * key = PBKDF2-HMAC-SHA256(passphrase, salt, 65_536 iterations, 256 bits) +//! * payload = `base64(salt ‖ iv ‖ ciphertext)`, with a random 16-byte +//! salt and 16-byte IV generated per save +//! +//! Deliberately NOT authenticated encryption. AES-GCM would be the better +//! default for new code, but the format is fixed by JDBC compatibility; +//! CBC gives confidentiality without integrity, so a tampered file is +//! detected only indirectly — corrupt padding or non-JSON plaintext makes +//! the load fail, and the caller treats that as a cache miss and +//! re-authenticates. That is an acceptable failure mode here because the +//! file is `0o600` in a `0o700` directory and a local attacker who can +//! rewrite it can generally also read the passphrase, so integrity adds +//! little over confidentiality for this specific threat model. + +use aes::cipher::block_padding::Pkcs7; +use aes::cipher::{BlockModeDecrypt, BlockModeEncrypt, KeyIvInit}; +use base64::engine::general_purpose::STANDARD as BASE64; +use base64::Engine; +use hmac::Hmac; +use sha2::Sha256; +use zeroize::Zeroize; + +type Aes256CbcEnc = cbc::Encryptor; +type Aes256CbcDec = cbc::Decryptor; + +/// Random per-file salt length, in bytes. Matches JDBC's `SALT_SIZE`. +const SALT_LEN: usize = 16; +/// AES block size / IV length, in bytes. Matches JDBC's `IV_SIZE`. +const IV_LEN: usize = 16; +/// AES-256 key length, in bytes (JDBC's `KEY_LENGTH` of 256 bits). +const KEY_LEN: usize = 32; +/// PBKDF2 iteration count. Matches JDBC's `ITERATION_COUNT`; changing it +/// would make previously written cache files undecryptable. +const PBKDF2_ITERATIONS: u32 = 65_536; + +/// Fixed component of the machine-local fallback passphrase. Changing this +/// invalidates every cache file written without an explicit passphrase +/// (which degrades to a cache miss and one re-authentication, not an error). +const DERIVED_PASSPHRASE_TAG: &str = "databricks-sql-kernel/token-cache/v1"; + +/// Passphrase used when the caller enabled the token cache but supplied no +/// passphrase of their own. +/// +/// # Why this exists +/// +/// The reference ODBC driver ships `EnableTokenCache=1` with an empty +/// `TokenCachePassPhrase` and still caches, so refusing to cache (or failing +/// the connection) would break drop-in compatibility. But writing the +/// refresh token as plaintext is not acceptable either. So we encrypt under +/// a key derived from machine-local material instead. +/// +/// # What this actually protects against — and what it does not +/// +/// Be clear-eyed about this: a key derived from data available on the +/// machine is **obfuscation against the wrong reader, not defence against a +/// local attacker.** It protects against: +/// +/// * the cache file being copied off the box — into a backup, a container +/// image layer, a support bundle, a synced home directory — and read +/// somewhere else; +/// * a different user on the same host reading the bytes (though the +/// `0o600` file mode in a `0o700` directory is the real control there); +/// * casual inspection: `cat`-ing the file, or a log/telemetry scraper that +/// slurps config directories, no longer yields a usable credential. +/// +/// It does **not** protect against an attacker who can already run code as +/// this user on this machine: they can derive the same key by construction. +/// A caller-supplied passphrase is the only thing that defends against +/// that, which is why the doc on [`crate::config::TokenCacheConfig`] says +/// supplying one is strictly stronger. +/// +/// # Composition +/// +/// The username plus a fixed version tag. Deliberately *not* the hostname: +/// containers get a fresh random hostname per start, which would silently +/// make the cache unreadable on every restart — the exact "why do I keep +/// getting a browser prompt" failure this whole feature exists to avoid. +/// Deliberately not a random per-install file either: that is a second piece +/// of state to create, protect, and fail to create, and it would buy nothing +/// over the file mode we already set. +pub(crate) fn derived_passphrase() -> String { + // No username available (unusual — a daemon with no passwd entry) is not + // a failure: fall back to the tag alone. The cache is then readable by + // anything that knows the tag, which is no worse than the plaintext this + // replaces, and the file mode still applies. + let user = std::env::var("USER") + .or_else(|_| std::env::var("USERNAME")) // Windows + .or_else(|_| std::env::var("LOGNAME")) + .unwrap_or_default(); + format!("{DERIVED_PASSPHRASE_TAG}\u{1f}{user}") +} + +/// Derive the AES key from `passphrase` and a per-file `salt`. +/// +/// Returned in a [`Zeroizing`]-style wrapper so the key material is wiped +/// when it goes out of scope rather than lingering in freed memory. +fn derive_key(passphrase: &str, salt: &[u8]) -> Key { + let mut key = Key([0u8; KEY_LEN]); + // Infallible for HMAC-SHA256: `pbkdf2` only errors for output lengths + // its PRF cannot produce, and 32 bytes is always valid here. + pbkdf2::pbkdf2::>(passphrase.as_bytes(), salt, PBKDF2_ITERATIONS, &mut key.0) + .expect("PBKDF2-HMAC-SHA256 supports a 32-byte output"); + key +} + +/// AES key material that is zeroed on drop. +struct Key([u8; KEY_LEN]); + +impl Drop for Key { + fn drop(&mut self) { + self.0.zeroize(); + } +} + +/// Encrypt `plaintext` under `passphrase`, returning the base64 payload +/// `base64(salt ‖ iv ‖ ciphertext)`. +/// +/// A fresh random salt and IV are drawn per call, so encrypting the same +/// token twice yields different payloads (and reusing a key/IV pair — +/// which is what makes CBC leak equality of plaintext prefixes — cannot +/// happen across saves). +pub(super) fn encrypt(plaintext: &[u8], passphrase: &str) -> String { + let mut salt = [0u8; SALT_LEN]; + let mut iv = [0u8; IV_LEN]; + rand::fill(&mut salt); + rand::fill(&mut iv); + + let key = derive_key(passphrase, &salt); + let ciphertext = + Aes256CbcEnc::new(&key.0.into(), &iv.into()).encrypt_padded_vec::(plaintext); + + let mut combined = Vec::with_capacity(SALT_LEN + IV_LEN + ciphertext.len()); + combined.extend_from_slice(&salt); + combined.extend_from_slice(&iv); + combined.extend_from_slice(&ciphertext); + BASE64.encode(&combined) +} + +/// Decrypt a payload produced by [`encrypt`] (or by JDBC's +/// `EncryptedFileTokenCache`). +/// +/// Returns `None` — never an error — when the payload is not valid +/// base64, is too short to carry a salt and IV, or fails to decrypt under +/// `passphrase` (wrong passphrase, truncation, or tampering). Every one +/// of those is reported the same way on purpose: the caller's only +/// sensible response is to treat the cache as a miss and re-authenticate, +/// and distinguishing "wrong passphrase" from "corrupt file" in a return +/// value would invite callers to branch on it. +pub(super) fn decrypt(payload: &[u8], passphrase: &str) -> Option> { + // Tolerate surrounding whitespace / trailing newline: the payload may + // have been written by another tool or hand-inspected. + let trimmed: Vec = payload + .iter() + .copied() + .filter(|b| !b.is_ascii_whitespace()) + .collect(); + let decoded = BASE64.decode(&trimmed).ok()?; + + // Need a full salt + IV, plus at least one AES block of ciphertext. + if decoded.len() < SALT_LEN + IV_LEN + IV_LEN { + return None; + } + let (salt, rest) = decoded.split_at(SALT_LEN); + let (iv, ciphertext) = rest.split_at(IV_LEN); + + let key = derive_key(passphrase, salt); + let iv: [u8; IV_LEN] = iv.try_into().ok()?; + Aes256CbcDec::new(&key.0.into(), &iv.into()) + .decrypt_padded_vec::(ciphertext) + .ok() +} + +#[cfg(test)] +mod tests { + use super::*; + + const PASSPHRASE: &str = "correct horse battery staple"; + + #[test] + fn derived_passphrase_is_deterministic_and_non_empty() { + // Determinism is load-bearing: a non-reproducible fallback key means + // every process writes a cache the next one cannot read, which shows + // up as a browser prompt on every connection — the exact failure the + // cache exists to prevent. + let a = derived_passphrase(); + let b = derived_passphrase(); + assert_eq!(a, b); + assert!(!a.trim().is_empty()); + // Must not degenerate to just the tag with an empty user component, + // in the normal case where a username IS available. + if std::env::var("USER").is_ok() { + assert_ne!(a, format!("{DERIVED_PASSPHRASE_TAG}\u{1f}")); + } + } + + #[test] + fn derived_passphrase_round_trips_a_token() { + // The end-to-end property the reference-compatible default depends + // on: a cache written with no caller passphrase must be readable back + // by the same machine, and must not be plaintext. + let plaintext = br#"{"refresh_token":"rt-derived"}"#; + let payload = encrypt(plaintext, &derived_passphrase()); + assert!(!payload.contains("rt-derived")); + assert_eq!( + decrypt(payload.as_bytes(), &derived_passphrase()).as_deref(), + Some(plaintext.as_slice()) + ); + // And a different key must not open it, so the fallback is a real key + // and not a constant everyone shares. + assert_eq!(decrypt(payload.as_bytes(), DERIVED_PASSPHRASE_TAG), None); + } + + /// Cross-language interop: decrypt a payload produced by the JDBC + /// driver's own crypto parameters. + /// + /// The fixture is a real AES-256-CBC + PBKDF2-HMAC-SHA256(65_536) + /// payload generated by running the JDBC `EncryptedFileTokenCache` + /// encrypt path under OpenJDK 21. Checked in as a literal (rather + /// than shelling out to `java`) so the guarantee is enforced on every + /// `cargo test` run, including in CI where no JDK is present. If this + /// test fails, the two drivers can no longer read each other's cache + /// files. + #[test] + fn decrypts_payload_produced_by_jdbc() { + const JDBC_PASSPHRASE: &str = "s3cr3t-passphrase"; + const JDBC_PAYLOAD: &str = "pV8vntLCNMrc77eRRwlc844XOEVPPQKZ1LLmBvdqFxd/6E8cY3JUxR6c7mPEyBvb3mZbk294oJ8NGGrNSnJebVBEDr0c/MlypDWZzOUJ6ZTHZ8FAasa9Sdj8UgOSDDVy6+XvRIWzhqSInOeagKyI+Q=="; + const EXPECTED: &str = + r#"{"access_token":"at-123","refresh_token":"rt-456","token_type":"Bearer"}"#; + + let decrypted = decrypt(JDBC_PAYLOAD.as_bytes(), JDBC_PASSPHRASE) + .expect("JDBC-produced payload must decrypt"); + assert_eq!(String::from_utf8_lossy(&decrypted), EXPECTED); + } + + #[test] + fn roundtrip_recovers_plaintext() { + let plaintext = br#"{"access_token":"a","refresh_token":"r"}"#; + let payload = encrypt(plaintext, PASSPHRASE); + assert_eq!( + decrypt(payload.as_bytes(), PASSPHRASE).as_deref(), + Some(plaintext.as_slice()) + ); + } + + #[test] + fn ciphertext_does_not_leak_plaintext() { + // The whole point of encrypting at rest: the refresh token must not + // be recoverable by reading the file. + let payload = encrypt(b"refresh_token=SUPERSECRET", PASSPHRASE); + assert!(!payload.contains("SUPERSECRET")); + // ...and not merely base64-hidden. + let decoded = BASE64.decode(payload.as_bytes()).expect("valid base64"); + assert!(!String::from_utf8_lossy(&decoded).contains("SUPERSECRET")); + } + + #[test] + fn same_plaintext_encrypts_differently_each_time() { + // Fresh salt + IV per save, so identical tokens must not produce + // identical files (which would leak that the token was unchanged). + let a = encrypt(b"same", PASSPHRASE); + let b = encrypt(b"same", PASSPHRASE); + assert_ne!(a, b); + // Both still decrypt. + assert_eq!( + decrypt(a.as_bytes(), PASSPHRASE).as_deref(), + Some(&b"same"[..]) + ); + assert_eq!( + decrypt(b.as_bytes(), PASSPHRASE).as_deref(), + Some(&b"same"[..]) + ); + } + + #[test] + fn wrong_passphrase_fails_to_decrypt() { + let payload = encrypt(b"secret", PASSPHRASE); + assert_eq!(decrypt(payload.as_bytes(), "wrong passphrase"), None); + } + + #[test] + fn tampered_ciphertext_is_rejected() { + let payload = encrypt(b"secret", PASSPHRASE); + let mut decoded = BASE64.decode(payload.as_bytes()).expect("valid base64"); + // Flip a bit in the final ciphertext block, which PKCS#7 unpadding + // then rejects. + let last = decoded.len() - 1; + decoded[last] ^= 0xff; + let tampered = BASE64.encode(&decoded); + assert_eq!(decrypt(tampered.as_bytes(), PASSPHRASE), None); + } + + #[test] + fn malformed_payloads_return_none_not_panic() { + // Each of these hits a different guard; none may panic. + assert_eq!(decrypt(b"", PASSPHRASE), None); // empty + assert_eq!(decrypt(b"!!!not base64!!!", PASSPHRASE), None); // bad base64 + assert_eq!( + decrypt(BASE64.encode([0u8; 8]).as_bytes(), PASSPHRASE), + None + ); // too short + // Exactly salt+IV but no ciphertext block. + assert_eq!( + decrypt( + BASE64.encode([0u8; SALT_LEN + IV_LEN]).as_bytes(), + PASSPHRASE + ), + None + ); + } + + #[test] + fn surrounding_whitespace_is_tolerated() { + let payload = encrypt(b"secret", PASSPHRASE); + let padded = format!("\n {payload} \n"); + assert_eq!( + decrypt(padded.as_bytes(), PASSPHRASE).as_deref(), + Some(&b"secret"[..]) + ); + } + + #[test] + fn payload_layout_matches_jdbc() { + // salt ‖ iv ‖ ciphertext, with ciphertext a whole number of AES + // blocks. Locking the layout down keeps the format readable by + // JDBC's EncryptedFileTokenCache. + let payload = encrypt(b"x", PASSPHRASE); + let decoded = BASE64.decode(payload.as_bytes()).expect("valid base64"); + assert!(decoded.len() > SALT_LEN + IV_LEN); + let ciphertext_len = decoded.len() - SALT_LEN - IV_LEN; + assert_eq!(ciphertext_len % IV_LEN, 0); + } + + #[test] + fn empty_passphrase_still_encrypts() { + // An empty passphrase is weak but well-defined; it must not panic, + // and the caller (not this layer) is responsible for requiring a + // non-empty passphrase. + let payload = encrypt(b"secret", ""); + assert_eq!( + decrypt(payload.as_bytes(), "").as_deref(), + Some(&b"secret"[..]) + ); + assert_eq!(decrypt(payload.as_bytes(), PASSPHRASE), None); + } +} diff --git a/src/auth/oauth/mod.rs b/src/auth/oauth/mod.rs index b573d590..e3918961 100644 --- a/src/auth/oauth/mod.rs +++ b/src/auth/oauth/mod.rs @@ -22,6 +22,7 @@ //! - File-based token caching pub mod cache; +pub(crate) mod cache_crypto; pub mod callback; pub mod m2m; pub mod oidc; diff --git a/src/auth/oauth/u2m.rs b/src/auth/oauth/u2m.rs index 1ca91105..b7db6fc3 100644 --- a/src/auth/oauth/u2m.rs +++ b/src/auth/oauth/u2m.rs @@ -29,6 +29,12 @@ //! //! U2M tokens include a `refresh_token` that can be used to obtain new access tokens //! without re-launching the browser, until the refresh token itself expires. +//! +//! Steps 1 and 4 are skipped entirely when the on-disk cache is disabled +//! (see [`crate::config::TokenCacheConfig`]); the in-memory token store +//! still handles reuse and refresh for the lifetime of the session. When +//! the cache IS enabled the payload is always encrypted under the +//! configured passphrase, because it carries that long-lived refresh token. use crate::auth::oauth::cache::TokenCache; use crate::auth::oauth::callback::CallbackServer; @@ -54,6 +60,26 @@ const DEFAULT_CALLBACK_PORT: u16 = 8020; /// Default timeout for waiting for the OAuth callback. const DEFAULT_CALLBACK_TIMEOUT: Duration = Duration::from_secs(120); +/// Persist `token` to the on-disk cache, or do nothing when disk caching +/// is disabled (`passphrase` is `None`). +/// +/// Exists so the two save sites in the token-acquisition flow (post-refresh +/// and post-browser-flow) cannot drift apart, in particular so neither can +/// accidentally write an unencrypted token or write one when the user asked +/// for no cache at all. +fn save_to_cache( + passphrase: Option<&str>, + host: &str, + client_id: &str, + scopes: &[String], + token: &OAuthToken, +) { + match passphrase { + Some(passphrase) => TokenCache::save(host, client_id, scopes, token, passphrase), + None => crate::klog::debug!("Token cache disabled; not persisting token to disk"), + } +} + /// OAuth provider for U2M (User-to-Machine) authentication. /// /// Uses the OAuth 2.0 authorization code grant with PKCE to authenticate users @@ -114,6 +140,12 @@ pub struct AuthorizationCodeProvider { callback_timeout: Duration, /// Whether to open browser automatically (set to false in tests) open_browser: bool, + /// Passphrase for the on-disk token cache, or `None` when disk + /// caching is disabled. `Some` implies the cache is enabled: the + /// enabled-without-passphrase combination is rejected upstream in + /// [`crate::config::TokenCacheConfig::resolve`], so this field carries + /// both the "should I cache?" and "with what key?" decisions. + cache_passphrase: Option, /// Tokio runtime handle captured from the constructing context; /// used to drive the async token exchange from the sync /// `get_auth_header` trait method safely whether or not the @@ -125,12 +157,14 @@ pub struct AuthorizationCodeProvider { impl AuthorizationCodeProvider { /// Creates a new U2M authentication provider. /// - /// Discovers the OIDC endpoints and attempts to load a cached token from disk. - /// If a cached token with a valid refresh_token is found, it's stored in TokenStore - /// and will be refreshed automatically when stale/expired. + /// Discovers the OIDC endpoints. The first call to `get_auth_header()` + /// launches the browser flow; the resulting token is then held in memory + /// and refreshed automatically when stale/expired. /// - /// If no cached token exists or the refresh_token is expired, the first call to - /// `get_auth_header()` will launch the browser flow. + /// The on-disk token cache is **disabled** here — persisting a refresh + /// token requires an encryption passphrase, which this signature cannot + /// accept. Use [`Self::new_with_full_config`] (as + /// [`Session::open`](crate::Session::open) does) to enable it. /// /// # Arguments /// @@ -180,6 +214,10 @@ impl AuthorizationCodeProvider { /// /// This is useful for testing or when specific scopes/ports are required. /// Most users should use `new()` which provides sensible defaults. + /// + /// The on-disk token cache is **disabled** for providers built this way: + /// encrypting it requires a passphrase, and this signature has no way to + /// accept one. Use [`Self::new_with_full_config`] to enable it. pub async fn new_with_config( host: &str, client_id: &str, @@ -196,6 +234,7 @@ impl AuthorizationCodeProvider { callback_port, callback_timeout, None, // No token_endpoint override + None, // On-disk cache disabled: no passphrase available here ) .await } @@ -204,6 +243,13 @@ impl AuthorizationCodeProvider { /// /// This is used by Database when a custom token endpoint is configured. /// Most users should use `new()` or `new_with_config()` which use OIDC discovery. + /// + /// `cache_passphrase` is `Some` to enable the encrypted on-disk token + /// cache and `None` to disable it; the enabled-but-passphraseless case is + /// rejected upstream by [`crate::config::TokenCacheConfig::resolve`]. + // The "full config" constructor is a flat parameter list by design — it is + // the single place every U2M knob is threaded in from `Session::open`. + #[allow(clippy::too_many_arguments)] pub async fn new_with_full_config( host: &str, client_id: &str, @@ -212,6 +258,7 @@ impl AuthorizationCodeProvider { callback_port: u16, callback_timeout: Duration, token_endpoint_override: Option, + cache_passphrase: Option, ) -> Result { // Discover OIDC endpoints (unless token_endpoint is overridden, we still need auth endpoint) let endpoints = OidcEndpoints::discover(host, &http_client).await?; @@ -222,8 +269,13 @@ impl AuthorizationCodeProvider { // Create token store let token_store = TokenStore::new(); - // Try loading cached token - if let Some(cached_token) = TokenCache::load(host, client_id, &scopes) { + // Try loading cached token. A `None` passphrase means the on-disk + // cache is disabled, so the file is never even read — the in-memory + // TokenStore above still reuses and refreshes within this process. + if let Some(cached_token) = cache_passphrase + .as_deref() + .and_then(|passphrase| TokenCache::load(host, client_id, &scopes, passphrase)) + { // Check if the cached token has a refresh token if cached_token.refresh_token.is_some() { crate::klog::debug!("Loaded cached token with refresh_token for U2M flow"); @@ -251,6 +303,7 @@ impl AuthorizationCodeProvider { callback_port, callback_timeout, open_browser: true, + cache_passphrase, // `new_with_full_config` is `async`, so we're guaranteed // to be inside a tokio runtime here. Capture that handle // so `get_auth_header` can dispatch correctly later via @@ -302,6 +355,7 @@ impl AuthProvider for AuthorizationCodeProvider { let callback_timeout = self.callback_timeout; let open_browser = self.open_browser; let http_client = self.http_client.clone(); + let cache_passphrase = self.cache_passphrase.clone(); // Get or refresh token via TokenStore let runtime_handle = self.runtime_handle.clone(); @@ -312,8 +366,12 @@ impl AuthProvider for AuthorizationCodeProvider { // inside a runtime, direct `block_on` otherwise. See // `crate::util::runtime`. block_on_in_runtime(&runtime_handle, async { - // Try loading from cache first - if let Some(cached_token) = TokenCache::load(&host, &client_id, &scopes) { + // Try loading from cache first (skipped entirely when + // on-disk caching is disabled). + if let Some(cached_token) = cache_passphrase + .as_deref() + .and_then(|p| TokenCache::load(&host, &client_id, &scopes, p)) + { if let Some(ref refresh_token_str) = cached_token.refresh_token { // Try refreshing the token crate::klog::debug!("Attempting to refresh token via refresh_token"); @@ -371,8 +429,14 @@ impl AuthProvider for AuthorizationCodeProvider { scopes_result, ); - // Save to cache - TokenCache::save(&host, &client_id, &scopes, &token); + // Save to cache (no-op when disabled) + save_to_cache( + cache_passphrase.as_deref(), + &host, + &client_id, + &scopes, + &token, + ); return Ok(token); } Err(e) => { @@ -492,8 +556,14 @@ impl AuthProvider for AuthorizationCodeProvider { scopes_result, ); - // Save to cache - TokenCache::save(&host, &client_id, &scopes, &token); + // Save to cache (no-op when disabled) + save_to_cache( + cache_passphrase.as_deref(), + &host, + &client_id, + &scopes, + &token, + ); Ok(token) }) @@ -511,6 +581,14 @@ mod tests { use wiremock::matchers::{body_string_contains, method, path}; use wiremock::{Mock, MockServer, ResponseTemplate}; + /// Passphrase used by the cache-backed tests below. These tests seed the + /// on-disk cache and then assert the provider picks it up, so they must + /// build the provider with disk caching ENABLED (via + /// `new_with_full_config`) and with the same passphrase used to write — + /// otherwise the load silently misses and the test would pass while + /// proving nothing. + const TEST_CACHE_PASSPHRASE: &str = "unit-test-passphrase"; + /// Helper to mock OIDC discovery response async fn mock_oidc_discovery(mock_server: &MockServer) { Mock::given(method("GET")) @@ -563,16 +641,19 @@ mod tests { "test-client-id", &["all-apis".to_string(), "offline_access".to_string()], &cached_token, + TEST_CACHE_PASSPHRASE, ); // Create provider - should load cached token - let provider = AuthorizationCodeProvider::new_with_config( + let provider = AuthorizationCodeProvider::new_with_full_config( &mock_server.uri(), "test-client-id", http_client, vec!["all-apis".to_string(), "offline_access".to_string()], 8020, Duration::from_secs(120), + None, + Some(TEST_CACHE_PASSPHRASE.to_string()), ) .await .expect("Failed to create provider"); @@ -613,16 +694,19 @@ mod tests { "test-client-id", &["all-apis".to_string(), "offline_access".to_string()], &cached_token, + TEST_CACHE_PASSPHRASE, ); // Create provider - should load cached token - let provider = AuthorizationCodeProvider::new_with_config( + let provider = AuthorizationCodeProvider::new_with_full_config( &mock_server.uri(), "test-client-id", http_client, vec!["all-apis".to_string(), "offline_access".to_string()], 8020, Duration::from_secs(120), + None, + Some(TEST_CACHE_PASSPHRASE.to_string()), ) .await .expect("Failed to create provider"); @@ -676,16 +760,22 @@ mod tests { "test-client-id", &["all-apis".to_string(), "offline_access".to_string()], &cached_token, + TEST_CACHE_PASSPHRASE, ); - // Create provider with browser opening suppressed - let mut provider = AuthorizationCodeProvider::new_with_config( + // Create provider with browser opening suppressed. Must use + // `new_with_full_config` so the on-disk cache seeded above is + // actually read — `new_with_config` disables it, and the refresh + // attempt this test asserts on would never be made. + let mut provider = AuthorizationCodeProvider::new_with_full_config( &mock_server.uri(), "test-client-id", http_client, vec!["all-apis".to_string(), "offline_access".to_string()], 0, // Use port 0 to avoid conflicts Duration::from_secs(5), // Short timeout for test + None, + Some(TEST_CACHE_PASSPHRASE.to_string()), ) .await .expect("Failed to create provider"); diff --git a/src/c_abi/session.rs b/src/c_abi/session.rs index a46b02fd..0da3efa9 100644 --- a/src/c_abi/session.rs +++ b/src/c_abi/session.rs @@ -25,7 +25,9 @@ //! (default = ignore). Backed by the shared `Session` transaction methods. use super::{block_on_ffi, KernelStatusCode}; -use crate::config::{AuthConfig, ConnectionConfig, HttpConfig, ProxyConfig, TlsConfig}; +use crate::config::{ + AuthConfig, ConnectionConfig, HttpConfig, ProxyConfig, TlsConfig, TokenCacheConfig, +}; use crate::kernel_error::Error; use crate::session::Session; use std::collections::HashMap; @@ -109,6 +111,12 @@ pub struct KernelSessionConfig { /// real transactions via `kernel_session_config_set_ignore_transactions` /// with `false`. Maps to [`DefaultOpts::ignore_transactions`]. ignore_transactions: bool, + /// On-disk U2M token-cache policy (populated by + /// `kernel_session_config_set_token_cache`). Defaults to enabled with + /// no passphrase, in which case the cache is encrypted under a + /// machine-local derived key. Only U2M auth reads it — PAT and M2M never + /// touch the cache. See [`TokenCacheConfig`]. + token_cache: TokenCacheConfig, } /// C-side proxy config captured from `kernel_session_config_set_proxy`. @@ -186,6 +194,8 @@ pub unsafe extern "C" fn kernel_session_config_new( retry: None, // Default to ignoring transactions, matching IgnoreTransactions=1. ignore_transactions: true, + // Match the reference driver's / JDBC's EnableTokenCache=1. + token_cache: TokenCacheConfig::default(), }); std::ptr::write(out, Box::into_raw(config)); KernelStatusCode::Success @@ -619,6 +629,47 @@ pub unsafe extern "C" fn kernel_session_config_set_ignore_transactions( }) } +/// Configure the on-disk OAuth token cache for U2M (browser) auth. +/// +/// Mirrors the `EnableTokenCache` / `TokenCachePassPhrase` pair exposed by +/// the reference ODBC driver and JDBC: +/// +/// * `enabled = true` (the default) persists the refresh token to +/// `~/.config/databricks-sql-kernel/oauth/` so the user is not sent +/// through the browser on every connection. The file is **always +/// encrypted** (AES-256-CBC, PBKDF2-HMAC-SHA256); there is no plaintext +/// mode. A non-null `passphrase` keys it; a null or blank one falls back +/// to a machine-local derived key, matching the reference driver, which +/// caches with an empty `TokenCachePassPhrase`. Supplying a passphrase is +/// stronger — see `TokenCacheConfig` for what the fallback does and does +/// not protect against. +/// * `enabled = false` disables **disk persistence only**. Tokens are +/// still reused and refreshed in memory for the session's lifetime, so +/// this does not re-trigger the browser flow on every refresh. Use it +/// when the process must not write credentials to disk at all. +/// +/// `passphrase` is ignored when `enabled` is `false`. Only U2M auth touches +/// the cache; PAT and M2M ignore this setting entirely. +/// +/// # Safety +/// `config` must be a live config handle. `passphrase`, if non-null, must +/// point to a NUL-terminated UTF-8 string valid for the duration of the +/// call. +#[no_mangle] +pub unsafe extern "C" fn kernel_session_config_set_token_cache( + config: *mut KernelSessionConfig, + enabled: bool, + passphrase: *const c_char, +) -> KernelStatusCode { + set_on_config(config, |c| { + c.token_cache = TokenCacheConfig { + enabled, + passphrase: optional_str(passphrase, "passphrase")?, + }; + Ok(()) + }) +} + /// Shared body for the config setters: null-check the handle, clear the /// thread-local error, run `f` against the borrowed config, and store /// any error. @@ -752,6 +803,7 @@ fn build_session(config: KernelSessionConfig) -> Result Result, +} + +impl Default for TokenCacheConfig { + fn default() -> Self { + Self { + // Match the reference driver's / JDBC's EnableTokenCache=1. + enabled: true, + passphrase: None, + } + } +} + +impl TokenCacheConfig { + /// Resolve to the passphrase to encrypt with, or `None` when disk + /// caching is disabled. + /// + /// A blank passphrase is treated as absent rather than honoured: it is + /// almost always an unexpanded config placeholder (`$TOKEN_PASS` that + /// never got substituted), and deriving a key from `""` across every + /// machine would be materially weaker than the machine-local fallback. + /// + /// Infallible by design. Enabled-without-passphrase is a supported + /// configuration, not an error, so this cannot fail the connection — + /// see the type docs for why. + pub(crate) fn resolve(&self) -> Option> { + if !self.enabled { + return None; + } + match self.passphrase.as_deref() { + Some(p) if !p.trim().is_empty() => Some(std::borrow::Cow::Borrowed(p)), + _ => Some(std::borrow::Cow::Owned( + crate::auth::oauth::cache_crypto::derived_passphrase(), + )), + } + } +} + // ─── Authentication ───────────────────────────────────────────────────────── /// Authentication strategy. @@ -254,6 +333,9 @@ pub enum AuthConfig { /// How long to wait for the user to complete the browser /// flow before timing out. `None` → 120 seconds. callback_timeout: Option, + /// On-disk token-cache policy. `None` → [`TokenCacheConfig::default`] + /// (enabled, which then requires a passphrase — see that type). + token_cache: Option, }, /// OAuth 2.0 token exchange (RFC 8693), for federated identity @@ -331,6 +413,7 @@ impl AuthConfig { scopes: Option>, token_url_override: Option, callback_timeout: Option, + token_cache: Option, ) -> Self { AuthConfig::OAuthU2M { client_id, @@ -338,6 +421,7 @@ impl AuthConfig { scopes, token_url_override, callback_timeout, + token_cache, } } } @@ -1013,6 +1097,109 @@ pub(crate) fn filter_session_conf( mod tests { use super::*; + // ─── token cache policy ──────────────────────────────────────── + + #[test] + fn token_cache_defaults_to_enabled() { + // Both the reference ODBC driver and JDBC default EnableTokenCache + // to 1, with no passphrase. + assert!(TokenCacheConfig::default().enabled); + assert!(TokenCacheConfig::default().passphrase.is_none()); + } + + #[test] + fn token_cache_enabled_with_passphrase_resolves_to_it() { + let cfg = TokenCacheConfig { + enabled: true, + passphrase: Some("s3cr3t".to_string()), + }; + assert_eq!(cfg.resolve().as_deref(), Some("s3cr3t")); + } + + #[test] + fn token_cache_enabled_without_passphrase_falls_back_to_derived_key() { + // The reference ODBC driver ships EnableTokenCache=1 with an empty + // TokenCachePassPhrase and still caches, so this combination must + // NOT fail the connection — a DSN that never set a passphrase has to + // keep working. It must also not disable caching silently, which + // would reintroduce a browser prompt on every connection. + let cfg = TokenCacheConfig::default(); + let passphrase = cfg + .resolve() + .expect("enabled + no passphrase must still cache"); + assert!( + !passphrase.trim().is_empty(), + "fallback passphrase must be non-empty, else the cache would be \ + encrypted under nothing" + ); + } + + #[test] + fn token_cache_blank_passphrase_uses_the_derived_key_not_the_blank() { + // An all-whitespace passphrase is almost always an unexpanded config + // placeholder. Honouring it literally would key every machine's cache + // identically, which is strictly weaker than the machine-local + // fallback, so blank must be treated as absent. + let derived = TokenCacheConfig::default() + .resolve() + .expect("default resolves") + .into_owned(); + for blank in ["", " ", "\t\n"] { + let cfg = TokenCacheConfig { + enabled: true, + passphrase: Some(blank.to_string()), + }; + let resolved = cfg.resolve().expect("blank still caches"); + assert_ne!( + resolved.as_ref(), + blank, + "blank passphrase {blank:?} must not be used verbatim" + ); + assert_eq!( + resolved.as_ref(), + derived, + "blank passphrase {blank:?} should fall back to the derived key" + ); + } + } + + #[test] + fn token_cache_derived_key_is_stable_across_calls() { + // If the fallback were not deterministic, every process would write a + // cache the next one cannot read — a silent browser prompt on every + // connection, which is the failure this whole feature avoids. + assert_eq!( + TokenCacheConfig::default() + .resolve() + .map(|p| p.into_owned()), + TokenCacheConfig::default() + .resolve() + .map(|p| p.into_owned()) + ); + } + + #[test] + fn token_cache_disabled_resolves_to_none_without_passphrase() { + // Disabling must always be valid — it is the escape hatch for + // processes that must not write credentials to disk at all. + let cfg = TokenCacheConfig { + enabled: false, + passphrase: None, + }; + assert_eq!(cfg.resolve(), None); + } + + #[test] + fn token_cache_disabled_ignores_a_supplied_passphrase() { + // `enabled: false` wins: a leftover passphrase must not silently + // re-enable disk persistence. + let cfg = TokenCacheConfig { + enabled: false, + passphrase: Some("ignored".to_string()), + }; + assert_eq!(cfg.resolve(), None); + } + // ─── session_conf allowlist ──────────────────────────────────── #[test] diff --git a/src/lib.rs b/src/lib.rs index 48a3942f..2e45d3dd 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -125,7 +125,7 @@ pub mod c_abi; // === Public re-exports === pub use config::{ AuthConfig, ConnectionConfig, DefaultOpts, HttpConfig, LoggingConfig, ProxyConfig, - ResultConfig, SessionConfig, TelemetryConfig, TlsConfig, TransportMode, + ResultConfig, SessionConfig, TelemetryConfig, TlsConfig, TokenCacheConfig, TransportMode, }; pub use kernel_error::{Error, ErrorCode, Result}; /// The `tracing` target string stamped on every kernel log event. diff --git a/src/session.rs b/src/session.rs index 6f9e2598..d4ba714c 100644 --- a/src/session.rs +++ b/src/session.rs @@ -278,6 +278,7 @@ impl Session { // which in turn needs to be set on the transport via // OnceLock::set. So: construct, wrap in Arc, build factory, // install factory. + let defaults = config.defaults.clone().unwrap_or_default(); let transport_config = TransportConfig::default(); let sea = Arc::new(SeaRestTransport::new( http_client.clone(), @@ -296,7 +297,6 @@ impl Session { let transport: Arc = sea; // 4. Mint the session on the server. - let defaults = config.defaults.clone().unwrap_or_default(); debug!( host = %host, warehouse_id = %warehouse_id, @@ -1088,6 +1088,7 @@ async fn build_auth_provider( scopes, token_url_override, callback_timeout, + token_cache, } => { let client_id = client_id.as_deref().unwrap_or("databricks-cli"); let redirect_port = redirect_port.unwrap_or(8020); @@ -1095,6 +1096,15 @@ async fn build_auth_provider( .clone() .unwrap_or_else(|| vec!["all-apis".to_string(), "offline_access".to_string()]); let timeout = callback_timeout.unwrap_or_else(|| Duration::from_secs(120)); + // `Some(passphrase)` enables the on-disk cache, `None` disables + // it. When the cache is on but the caller supplied no passphrase, + // `resolve` substitutes a machine-local derived one rather than + // failing or writing plaintext — see `TokenCacheConfig`. + let cache_policy = token_cache + .clone() + .unwrap_or_default() + .resolve() + .map(|p| p.into_owned()); let provider = AuthorizationCodeProvider::new_with_full_config( host, client_id, @@ -1103,6 +1113,7 @@ async fn build_auth_provider( redirect_port, timeout, token_url_override.clone(), + cache_policy, ) .await?; Ok(Arc::new(provider)) diff --git a/tests/oauth_u2m_integration.rs b/tests/oauth_u2m_integration.rs index 8ea82a3d..78d62fb7 100644 --- a/tests/oauth_u2m_integration.rs +++ b/tests/oauth_u2m_integration.rs @@ -26,6 +26,15 @@ use std::time::Duration; use wiremock::matchers::{body_string_contains, method, path}; use wiremock::{Mock, MockServer, ResponseTemplate}; +/// Passphrase used to encrypt the on-disk token cache in these tests. +/// +/// The cache is only ever written encrypted, so every test that seeds it and +/// then expects the provider to read it back must (a) save under this +/// passphrase and (b) build the provider via `new_with_full_config` with the +/// same one. `new_with_config` disables disk caching outright, which would +/// leave these tests passing while exercising nothing. +const TEST_CACHE_PASSPHRASE: &str = "integration-test-passphrase"; + /// Helper function to mock OIDC discovery endpoint. /// /// Sets up a wiremock endpoint at `/oidc/.well-known/oauth-authorization-server` @@ -100,16 +109,19 @@ async fn test_u2m_refresh_token_full_flow() { "test-client-id", &["all-apis".to_string(), "offline_access".to_string()], &cached_token, + TEST_CACHE_PASSPHRASE, ); // Step 5: Create AuthorizationCodeProvider - should load cached token - let provider = AuthorizationCodeProvider::new_with_config( + let provider = AuthorizationCodeProvider::new_with_full_config( &mock_server.uri(), "test-client-id", http_client, vec!["all-apis".to_string(), "offline_access".to_string()], 8020, Duration::from_secs(120), + None, + Some(TEST_CACHE_PASSPHRASE.to_string()), ) .await .expect("Failed to create AuthorizationCodeProvider"); @@ -172,15 +184,18 @@ async fn test_u2m_refresh_token_stale_immediate_return() { "test-client-id-stale", &["all-apis".to_string(), "offline_access".to_string()], &stale_token, + TEST_CACHE_PASSPHRASE, ); - let provider = AuthorizationCodeProvider::new_with_config( + let provider = AuthorizationCodeProvider::new_with_full_config( &mock_server.uri(), "test-client-id-stale", http_client, vec!["all-apis".to_string(), "offline_access".to_string()], 8021, Duration::from_secs(120), + None, + Some(TEST_CACHE_PASSPHRASE.to_string()), ) .await .expect("Failed to create provider"); @@ -249,15 +264,18 @@ async fn test_u2m_refresh_token_expired_fallback() { "test-client-id-expired", &["all-apis".to_string(), "offline_access".to_string()], &expired_token, + TEST_CACHE_PASSPHRASE, ); - let mut provider = AuthorizationCodeProvider::new_with_config( + let mut provider = AuthorizationCodeProvider::new_with_full_config( &mock_server.uri(), "test-client-id-expired", http_client, vec!["all-apis".to_string(), "offline_access".to_string()], 0, // Use port 0 to avoid conflicts Duration::from_secs(5), // Short timeout for test + None, + Some(TEST_CACHE_PASSPHRASE.to_string()), ) .await .expect("Failed to create provider"); @@ -321,15 +339,18 @@ async fn test_u2m_refresh_updates_cache() { "test-client-id-cache", &["all-apis".to_string(), "offline_access".to_string()], &old_token, + TEST_CACHE_PASSPHRASE, ); - let provider = AuthorizationCodeProvider::new_with_config( + let provider = AuthorizationCodeProvider::new_with_full_config( &mock_server.uri(), "test-client-id-cache", http_client, vec!["all-apis".to_string(), "offline_access".to_string()], 8023, Duration::from_secs(120), + None, + Some(TEST_CACHE_PASSPHRASE.to_string()), ) .await .expect("Failed to create provider"); @@ -346,6 +367,7 @@ async fn test_u2m_refresh_updates_cache() { &mock_server.uri(), "test-client-id-cache", &["all-apis".to_string(), "offline_access".to_string()], + TEST_CACHE_PASSPHRASE, ); assert!(cached_token.is_some(), "Cache should contain updated token"); diff --git a/tests/v0_session_e2e.rs b/tests/v0_session_e2e.rs index 4081283d..958039b8 100644 --- a/tests/v0_session_e2e.rs +++ b/tests/v0_session_e2e.rs @@ -123,6 +123,13 @@ async fn open_with_oauth_u2m_against_live_warehouse() { scopes: None, token_url_override: None, callback_timeout: None, + // Disable the on-disk cache to keep runs independent: it defaults + // to enabled, so a token cached by an earlier run would skip the + // browser flow this test exists to exercise. + token_cache: Some(databricks_sql_kernel::TokenCacheConfig { + enabled: false, + passphrase: None, + }), }) .open() .await