From ffdc37c4107502cb65a4e4abcb30f5bb26698c76 Mon Sep 17 00:00:00 2001 From: Rahul Singhal Date: Wed, 19 Aug 2026 18:04:21 +0000 Subject: [PATCH] feat(auth): add JWT private-key M2M authentication OAuth 2.0 machine-to-machine auth using a JWT private-key client assertion (RFC 7523) instead of a client secret. The kernel signs a short-lived JWT with a PEM/PKCS#8 private key (RSA or EC; unencrypted or PBES2-encrypted) and sends it as the client_assertion in the client-credentials grant; the IdP verifies it against the service principal's registered public key. Ported from JDBC's JwtPrivateKeyClientCredentials. - Kernel: AuthConfig::OAuthM2MPrivateKey + oauth_m2m_private_key constructor; JwtClientCredentialsProvider (jwt_m2m.rs) reusing the M2M OIDC/TokenStore machinery; key loading + signing (jwt_key.rs) - Parse the token response via oauth2::StandardTokenResponse - Bindings: pyo3 auth_type="oauth-m2m-jwt", napi AuthMode.OAuthM2mJwt - C ABI: kernel_session_config_set_auth_m2m_jwt (+ header, changelog) - Telemetry: classify the variant as oauth-m2m-jwt / client-credentials - Tests: unit + wiremock (incl. signature verification against the public key) and an ignored jwt_m2m_select_one_round_trip e2e verified live against an Azure Databricks warehouse via Entra ID Co-authored-by: Isaac Signed-off-by: Rahul Singhal --- Cargo.lock | 463 +++++++++++++++++++++++++- Cargo.toml | 32 ++ NEXT_CHANGELOG.md | 13 + deny.toml | 31 +- include/databricks_kernel.h | 16 + napi/Cargo.lock | 265 ++++++++++++++- napi/NEXT_CHANGELOG.md | 6 + napi/index.d.ts | 23 ++ napi/src/database.rs | 67 ++++ osv-scanner.toml | 49 ++- pyo3/Cargo.lock | 265 ++++++++++++++- pyo3/NEXT_CHANGELOG.md | 6 + pyo3/src/auth.rs | 120 ++++++- pyo3/src/session.rs | 16 +- src/auth/mod.rs | 5 +- src/auth/oauth/jwt_key.rs | 430 ++++++++++++++++++++++++ src/auth/oauth/jwt_m2m.rs | 633 ++++++++++++++++++++++++++++++++++++ src/auth/oauth/mod.rs | 5 + src/auth/oauth/test_keys.rs | 91 ++++++ src/c_abi/session.rs | 148 ++++++++- src/config.rs | 200 +++++++++++- src/session.rs | 34 +- src/telemetry/runtime.rs | 6 +- tests/v0_execute_e2e.rs | 100 ++++++ 24 files changed, 2976 insertions(+), 48 deletions(-) create mode 100644 src/auth/oauth/jwt_key.rs create mode 100644 src/auth/oauth/jwt_m2m.rs create mode 100644 src/auth/oauth/test_keys.rs diff --git a/Cargo.lock b/Cargo.lock index e3eb7560..16081301 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -8,13 +8,24 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" +[[package]] +name = "aes" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0" +dependencies = [ + "cfg-if", + "cipher 0.4.4", + "cpufeatures 0.2.17", +] + [[package]] name = "aes" version = "0.9.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8eb277bec05f56a0e0591f155a484cbd0f4f07ff2905051a48c72f004f7ed58" dependencies = [ - "cipher", + "cipher 0.5.2", "cpubits", "cpufeatures 0.3.0", "zeroize", @@ -220,12 +231,24 @@ version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" +[[package]] +name = "base16ct" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c7f02d4ea65f2c1853089ffd8d2787bdbc63de2f0d29dedbcf8ccdfa0ccd4cf" + [[package]] name = "base64" version = "0.22.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" +[[package]] +name = "base64ct" +version = "1.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" + [[package]] name = "bitflags" version = "2.13.0" @@ -251,6 +274,15 @@ dependencies = [ "zeroize", ] +[[package]] +name = "block-padding" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a8894febbff9f758034a5b8e12d87918f56dfc64a8e1fe757d65e29041538d93" +dependencies = [ + "generic-array", +] + [[package]] name = "block-padding" version = "0.4.2" @@ -272,13 +304,22 @@ version = "1.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" +[[package]] +name = "cbc" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26b52a9543ae338f279b96b0b9fed9c8093744685043739079ce85cd58f289a6" +dependencies = [ + "cipher 0.4.4", +] + [[package]] name = "cbc" version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ce2dc9ee5f88d11e0beb842c88b33c8a5cf0d1329c4b19494af42b07dbfe8896" dependencies = [ - "cipher", + "cipher 0.5.2", ] [[package]] @@ -328,6 +369,16 @@ dependencies = [ "windows-link", ] +[[package]] +name = "cipher" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" +dependencies = [ + "crypto-common 0.1.7", + "inout 0.1.4", +] + [[package]] name = "cipher" version = "0.5.2" @@ -336,7 +387,7 @@ checksum = "e8cf2a2c93cd704877c0858356ed03480ff301ee950b43f1cbe4573b088bfa6c" dependencies = [ "block-buffer 0.12.1", "crypto-common 0.2.2", - "inout", + "inout 0.2.2", "zeroize", ] @@ -363,6 +414,12 @@ version = "0.4.32" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cc14f565cf027a105f7a44ccf9e5b424348421a1d8952a8fc9d499d313107789" +[[package]] +name = "const-oid" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" + [[package]] name = "const-oid" version = "0.10.2" @@ -450,6 +507,18 @@ version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" +[[package]] +name = "crypto-bigint" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0dc92fb57ca44df6db8059111ab3af99a63d5d0f8375d9972e319a379c6bab76" +dependencies = [ + "generic-array", + "rand_core 0.6.4", + "subtle", + "zeroize", +] + [[package]] name = "crypto-common" version = "0.1.7" @@ -496,7 +565,7 @@ dependencies = [ name = "databricks-sql-kernel" version = "0.2.0" dependencies = [ - "aes", + "aes 0.9.2", "arrow-array", "arrow-buffer", "arrow-cast", @@ -506,20 +575,24 @@ dependencies = [ "arrow-select", "async-trait", "base64", - "cbc", + "cbc 0.2.1", "chrono", "dashmap", "dirs", "futures", "hex", - "hmac", + "hmac 0.13.0", + "jsonwebtoken", "log", "lz4_flex", "oauth2", "open", - "pbkdf2", + "p256", + "pbkdf2 0.13.0", + "pkcs8", "rand 0.10.2", "reqwest", + "rsa", "serde", "serde_json", "sha2 0.11.0", @@ -551,6 +624,23 @@ version = "0.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "092966b41edc516079bdf31ec78a2e0588d1d0c08f78b91d8307215928642b2b" +[[package]] +name = "der" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" +dependencies = [ + "const-oid 0.9.6", + "pem-rfc7468", + "zeroize", +] + +[[package]] +name = "deranged" +version = "0.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c" + [[package]] name = "digest" version = "0.10.7" @@ -558,7 +648,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ "block-buffer 0.10.4", + "const-oid 0.9.6", "crypto-common 0.1.7", + "subtle", ] [[package]] @@ -568,7 +660,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" dependencies = [ "block-buffer 0.12.1", - "const-oid", + "const-oid 0.10.2", "crypto-common 0.2.2", "ctutils", ] @@ -605,6 +697,40 @@ dependencies = [ "syn 2.0.118", ] +[[package]] +name = "ecdsa" +version = "0.16.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee27f32b5c5292967d2d4a9d7f1e0b0aed2c15daded5a60300e4abb9d8020bca" +dependencies = [ + "der", + "digest 0.10.7", + "elliptic-curve", + "rfc6979", + "signature", + "spki", +] + +[[package]] +name = "elliptic-curve" +version = "0.13.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5e6043086bf7973472e0c7dff2142ea0b680d30e18d9cc40f267efbf222bd47" +dependencies = [ + "base16ct", + "crypto-bigint", + "digest 0.10.7", + "ff", + "generic-array", + "group", + "pem-rfc7468", + "pkcs8", + "rand_core 0.6.4", + "sec1", + "subtle", + "zeroize", +] + [[package]] name = "equivalent" version = "1.0.2" @@ -627,6 +753,16 @@ version = "2.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f1f227452a390804cdb637b74a86990f2a7d7ba4b7d5693aac9b4dd6defd8d6" +[[package]] +name = "ff" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0b50bfb653653f9ca9095b427bed08ab8d75a137839d9ad64eb11810d5b6393" +dependencies = [ + "rand_core 0.6.4", + "subtle", +] + [[package]] name = "find-msvc-tools" version = "0.1.9" @@ -779,6 +915,7 @@ checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" dependencies = [ "typenum", "version_check", + "zeroize", ] [[package]] @@ -820,6 +957,17 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "group" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0f9ef7462f7c099f518d754361858f86d8a07af53ba9af0fe635bbccb151a63" +dependencies = [ + "ff", + "rand_core 0.6.4", + "subtle", +] + [[package]] name = "h2" version = "0.4.15" @@ -875,6 +1023,15 @@ version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" +[[package]] +name = "hmac" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" +dependencies = [ + "digest 0.10.7", +] + [[package]] name = "hmac" version = "0.13.0" @@ -1153,13 +1310,23 @@ dependencies = [ "hashbrown 0.17.1", ] +[[package]] +name = "inout" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01" +dependencies = [ + "block-padding 0.3.3", + "generic-array", +] + [[package]] name = "inout" version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4250ce6452e92010fdf7268ccc5d14faa80bb12fc741938534c58f16804e03c7" dependencies = [ - "block-padding", + "block-padding 0.4.2", "hybrid-array", ] @@ -1205,11 +1372,29 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "jsonwebtoken" +version = "9.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a87cc7a48537badeae96744432de36f4be2b4a34a05a5ef32e9dd8a1c169dde" +dependencies = [ + "base64", + "js-sys", + "pem", + "ring", + "serde", + "serde_json", + "simple_asn1", +] + [[package]] name = "lazy_static" version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" +dependencies = [ + "spin", +] [[package]] name = "lexical-core" @@ -1403,6 +1588,22 @@ dependencies = [ "num-traits", ] +[[package]] +name = "num-bigint-dig" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e661dda6640fad38e827a6d4a310ff4763082116fe217f279885c97f511bb0b7" +dependencies = [ + "lazy_static", + "libm", + "num-integer", + "num-iter", + "num-traits", + "rand 0.8.6", + "smallvec", + "zeroize", +] + [[package]] name = "num-complex" version = "0.4.6" @@ -1412,6 +1613,12 @@ dependencies = [ "num-traits", ] +[[package]] +name = "num-conv" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" + [[package]] name = "num-integer" version = "0.1.46" @@ -1421,6 +1628,16 @@ dependencies = [ "num-traits", ] +[[package]] +name = "num-iter" +version = "0.1.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c92800bd69a1eac91786bcfe9da64a897eb72911b8dc3095decbd07429e8048b" +dependencies = [ + "num-integer", + "num-traits", +] + [[package]] name = "num-traits" version = "0.2.19" @@ -1526,6 +1743,18 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" +[[package]] +name = "p256" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9863ad85fa8f4460f9c48cb909d38a0d689dba1f6f6988a5e3e0d31071bcd4b" +dependencies = [ + "ecdsa", + "elliptic-curve", + "primeorder", + "sha2 0.10.9", +] + [[package]] name = "parking_lot" version = "0.12.5" @@ -1549,6 +1778,16 @@ dependencies = [ "windows-link", ] +[[package]] +name = "pbkdf2" +version = "0.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8ed6a7761f76e3b9f92dfb0a60a6a6477c61024b775147ff0973a02653abaf2" +dependencies = [ + "digest 0.10.7", + "hmac 0.12.1", +] + [[package]] name = "pbkdf2" version = "0.13.0" @@ -1556,7 +1795,26 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "112d82ceb8c5bf524d9af484d4e4970c9fd5a0cc15ba14ad93dccd28873b0629" dependencies = [ "digest 0.11.3", - "hmac", + "hmac 0.13.0", +] + +[[package]] +name = "pem" +version = "3.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d30c53c26bc5b31a98cd02d20f25a7c8567146caf63ed593a9d87b2775291be" +dependencies = [ + "base64", + "serde_core", +] + +[[package]] +name = "pem-rfc7468" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88b39c9bfcfc231068454382784bb460aae594343fb030d46e9f50a645418412" +dependencies = [ + "base64ct", ] [[package]] @@ -1571,6 +1829,44 @@ version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" +[[package]] +name = "pkcs1" +version = "0.7.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8ffb9f10fa047879315e6625af03c164b16962a5368d724ed16323b68ace47f" +dependencies = [ + "der", + "pkcs8", + "spki", +] + +[[package]] +name = "pkcs5" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e847e2c91a18bfa887dd028ec33f2fe6f25db77db3619024764914affe8b69a6" +dependencies = [ + "aes 0.8.4", + "cbc 0.1.2", + "der", + "pbkdf2 0.12.2", + "scrypt", + "sha2 0.10.9", + "spki", +] + +[[package]] +name = "pkcs8" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7" +dependencies = [ + "der", + "pkcs5", + "rand_core 0.6.4", + "spki", +] + [[package]] name = "pkg-config" version = "0.3.33" @@ -1586,6 +1882,12 @@ dependencies = [ "zerovec", ] +[[package]] +name = "powerfmt" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" + [[package]] name = "ppv-lite86" version = "0.2.21" @@ -1595,6 +1897,15 @@ dependencies = [ "zerocopy", ] +[[package]] +name = "primeorder" +version = "0.13.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "353e1ca18966c16d9deb1c69278edbc5f194139612772bd9537af60ac231e1e6" +dependencies = [ + "elliptic-curve", +] + [[package]] name = "proc-macro2" version = "1.0.106" @@ -1830,6 +2141,16 @@ dependencies = [ "webpki-roots", ] +[[package]] +name = "rfc6979" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dd2a808d456c4a54e300a23e9f5a67e122c3024119acbfd73e3bf664491cb2" +dependencies = [ + "hmac 0.12.1", + "subtle", +] + [[package]] name = "ring" version = "0.17.14" @@ -1844,6 +2165,26 @@ dependencies = [ "windows-sys 0.52.0", ] +[[package]] +name = "rsa" +version = "0.9.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8573f03f5883dcaebdfcf4725caa1ecb9c15b2ef50c43a07b816e06799bb12d" +dependencies = [ + "const-oid 0.9.6", + "digest 0.10.7", + "num-bigint-dig", + "num-integer", + "num-traits", + "pkcs1", + "pkcs8", + "rand_core 0.6.4", + "signature", + "spki", + "subtle", + "zeroize", +] + [[package]] name = "rustc-hash" version = "2.1.3" @@ -1919,6 +2260,15 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" +[[package]] +name = "salsa20" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97a22f5af31f73a954c10289c93e8a50cc23d971e80ee446f1f6f7137a088213" +dependencies = [ + "cipher 0.4.4", +] + [[package]] name = "schannel" version = "0.1.29" @@ -1934,6 +2284,31 @@ version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" +[[package]] +name = "scrypt" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0516a385866c09368f0b5bcd1caff3366aace790fcd46e2bb032697bb172fd1f" +dependencies = [ + "pbkdf2 0.12.2", + "salsa20", + "sha2 0.10.9", +] + +[[package]] +name = "sec1" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3e97a565f76233a6003f9f5c54be1d9c5bdfa3eccfb189469f11ec4901c47dc" +dependencies = [ + "base16ct", + "der", + "generic-array", + "pkcs8", + "subtle", + "zeroize", +] + [[package]] name = "security-framework" version = "3.7.0" @@ -2076,12 +2451,34 @@ dependencies = [ "libc", ] +[[package]] +name = "signature" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" +dependencies = [ + "digest 0.10.7", + "rand_core 0.6.4", +] + [[package]] name = "simd-adler32" version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "703d5c7ef118737c72f1af64ad2f6f8c5e1921f818cdcb97b8fe6fc69bf66214" +[[package]] +name = "simple_asn1" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d585997b0ac10be3c5ee635f1bab02d512760d14b7c468801ac8a01d9ae5f1d" +dependencies = [ + "num-bigint", + "num-traits", + "thiserror 2.0.19", + "time", +] + [[package]] name = "slab" version = "0.4.12" @@ -2104,6 +2501,22 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "spin" +version = "0.9.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e" + +[[package]] +name = "spki" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d" +dependencies = [ + "base64ct", + "der", +] + [[package]] name = "stable_deref_trait" version = "1.2.1" @@ -2220,6 +2633,36 @@ dependencies = [ "cfg-if", ] +[[package]] +name = "time" +version = "0.3.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134" +dependencies = [ + "deranged", + "num-conv", + "powerfmt", + "serde_core", + "time-core", + "time-macros", +] + +[[package]] +name = "time-core" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" + +[[package]] +name = "time-macros" +version = "0.2.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85" +dependencies = [ + "num-conv", + "time-core", +] + [[package]] name = "tiny-keccak" version = "2.0.2" diff --git a/Cargo.toml b/Cargo.toml index bf75044d..a181b8ce 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -113,11 +113,43 @@ pbkdf2 = { version = "0.13.0", default-features = false, features = ["hmac"] } hmac = "0.13.0" # PRF backing PBKDF2 zeroize = "1.9" # Wipe derived key material on drop +# JWT private-key client-credentials auth (service-principal M2M with a +# signed client assertion instead of a client secret). Mirrors the JDBC +# driver's JwtPrivateKeyClientCredentials. We sign with `jsonwebtoken` +# (RS/PS/ES families, backed by `ring` — already in the graph via rustls, +# so this adds no new heavyweight dependency) and load PEM/PKCS#8 keys +# with the RustCrypto `pkcs8`/`sec1` family. This deliberately avoids the +# `openssl` crate to preserve the pure-Rust/rustls posture the napi +# binding depends on (see the `reqwest` / `[features]` TLS notes above); +# the one accepted gap vs. JDBC/BouncyCastle is ES512 (P-521), which +# `ring` does not support. All crates are dual Apache-2.0/MIT. +# +# Pinned to 9.x deliberately. jsonwebtoken 10.x dropped the built-in +# `ring` backend and forces an explicit crypto backend, both of which +# regress us: `rust_crypto` pulls `rsa` (RUSTSEC-2023-0071, Marvin) into +# the RUNTIME crate, and `aws_lc_rs` links a C library (AWS-LC) that +# breaks the pure-Rust posture and adds a recurring C-CVE maintenance +# tail. 9.x's advisory GHSA-h395-gr6q-cpjc is in the DECODE/validation +# path, which the kernel never exercises (it only signs), so it is +# suppressed with justification in `osv-scanner.toml` rather than paying +# the 10.x cost. Revisit if jsonwebtoken ships a ring-backed 10.x. +jsonwebtoken = { version = "9", default-features = false, features = ["use_pem"] } # JWT signing (RS256/384/512, PS256/384/512, ES256/384); use_pem = PEM key loading (adds pem + simple_asn1, no TLS) +pkcs8 = { version = "0.10", features = ["encryption", "pem", "std"] } # PKCS#8 PEM parsing + PBES2 passphrase decryption + [dev-dependencies] tokio = { version = "1", features = ["rt-multi-thread", "macros"] } wiremock = "0.6" tempfile = "3" log = "0.4" +# Test-only private-key generation for the JWT auth tests. Keys are +# generated in-process (RSA + P-256, plus a PBES2-encrypted PKCS#8 +# variant) rather than committed as PEM fixtures, so the repo's secret +# scanner has nothing to flag and the tests need no `openssl` CLI (which +# the repo deliberately avoids — not present on Windows). These are the +# RustCrypto siblings of the `pkcs8` runtime dep. dev-only: never linked +# into the shipped crate. +rsa = { version = "0.9", features = ["pem"] } +p256 = { version = "0.13", features = ["pkcs8", "pem"] } # TLS backend selection. # diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index e1369625..60b0fe60 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -11,6 +11,19 @@ changes go in their respective binding's NEXT_CHANGELOG. ### Added +- Auth: `AuthConfig::OAuthM2MPrivateKey` — OAuth 2.0 machine-to-machine using a JWT + private-key client assertion (RFC 7523) instead of a client secret. The kernel + signs a short-lived JWT with a PEM/PKCS#8 private key (RSA or EC; unencrypted or + PBES2-passphrase-encrypted) and sends it as the `client_assertion` in the + client-credentials grant. Supported algorithms: `RS256`/`384`/`512`, + `PS256`/`384`/`512`, `ES256`, `ES384` (default `RS256`); `ES512` is not supported + and is rejected with a clear error. Construct via `AuthConfig::oauth_m2m_private_key`. +- C ABI: `kernel_session_config_set_auth_m2m_jwt()` — expose the JWT private-key M2M + flow over the C ABI (for ODBC / Go consumers), alongside the existing + `set_auth_pat` / `set_auth_m2m` / `set_auth_u2m` setters. Required `client_id` / + `jwt_key_file` / `jwt_kid`; optional `jwt_passphrase` (encrypted PKCS#8), + `jwt_algorithm` (NULL → `RS256`), `scopes` (comma-separated; NULL → `all-apis`), + and `token_url` (NULL → OIDC discovery). Maps to `AuthConfig::oauth_m2m_private_key`. - C ABI: `kernel_session_config_set_retry_config()` — expose the crate's existing HTTP retry knobs (`HttpConfig::retry_min_wait` / `retry_max_wait` / `retry_max_retries` / `overall_timeout`) over the C ABI so a host can make its own diff --git a/deny.toml b/deny.toml index c7d37efb..adab1499 100644 --- a/deny.toml +++ b/deny.toml @@ -20,7 +20,36 @@ all-features = true [advisories] yanked = "warn" -ignore = [] +ignore = [ + # RUSTSEC-2023-0071 — "Marvin Attack": RSA timing sidechannel in the + # `rsa` crate. No fixed version exists (only 0.10 release candidates; + # stable 0.9.x is still affected), so it cannot be cleared by a bump. + # + # `rsa` is a DEV-ONLY dependency here: it generates RSA test keys + # in-process for the JWT auth unit tests (`src/auth/oauth/test_keys.rs`) + # so we don't commit PEM fixtures (secret scanner) or shell out to + # `openssl` (not on Windows). Verified dev-only via `cargo tree -i rsa` + # — it is never linked into the shipped kernel, pyo3, or napi artifacts, + # so the timing sidechannel is not reachable by any driver consumer. + # The runtime signing path uses `jsonwebtoken` (ring), not `rsa`. + # + # We keep `rsa` (rather than dropping RSA test coverage for EC-only) + # because RS256 is the JDBC default and the most common real-world key + # type, so exercising the RSA load+sign path in tests has value. + # Re-evaluate when `rsa` ships a constant-time stable release. + "RUSTSEC-2023-0071", + # RUSTSEC-2026-0258 — "h2 unbounded empty DATA frames". A DoS advisory + # in `h2 0.4.15`, pulled in transitively via `hyper` <- `reqwest` + # (`cargo tree -i h2`); not a direct dependency and unrelated to this + # crate's code. 0.4.15 is already the latest 0.4.x (a `cargo update -p + # h2` is a no-op), so it cannot be cleared by a bump; clearing it needs + # an upstream `hyper`/`reqwest` release that requires the fixed `h2`. + # The advisory concerns a server-side frame-flood; the kernel is an + # HTTP *client* to Databricks SEA, so the attack surface is not exercised + # here. Pre-existing on `main` (fires against the shared reqwest stack, + # not this PR). Re-evaluate when the reqwest/hyper stack picks up the fix. + "RUSTSEC-2026-0258", +] [licenses] # Permissive licenses we allow in transitive deps. Adding a new diff --git a/include/databricks_kernel.h b/include/databricks_kernel.h index eed49269..a51baf4d 100644 --- a/include/databricks_kernel.h +++ b/include/databricks_kernel.h @@ -238,6 +238,22 @@ KernelStatusCode kernel_session_config_set_auth_pat(KernelSessionConfig* config, KernelStatusCode kernel_session_config_set_auth_m2m(KernelSessionConfig* config, const char* client_id, const char* client_secret); +/* OAuth M2M via a JWT private-key client assertion (RFC 7523): the kernel signs + * a short-lived JWT with the private key and sends it as the client_assertion + * instead of a client secret. `client_id`, `jwt_key_file` (PEM/PKCS#8 private + * key path), and `jwt_kid` (key id in the JWT header) are required. Optional + * (pass NULL to omit): `jwt_passphrase` (encrypted PKCS#8 key), `jwt_algorithm` + * (RS256/384/512, PS256/384/512, ES256, ES384; NULL → RS256), `scopes` + * (comma-separated; NULL → kernel default `all-apis`), and `token_url` (explicit + * token endpoint; NULL → discover via OIDC). */ +KernelStatusCode kernel_session_config_set_auth_m2m_jwt(KernelSessionConfig* config, + const char* client_id, + const char* jwt_key_file, + const char* jwt_kid, + const char* jwt_passphrase, + const char* jwt_algorithm, + const char* scopes, + const char* token_url); /* OAuth U2M (user-to-machine: authorization code + PKCE, browser flow). * All args optional: `client_id` NULL → `databricks-sql-connector` client; * `redirect_port` 0 → kernel default (8030); `scopes` (comma-separated) diff --git a/napi/Cargo.lock b/napi/Cargo.lock index 8c4b4a20..fe76a0cb 100644 --- a/napi/Cargo.lock +++ b/napi/Cargo.lock @@ -8,13 +8,24 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" +[[package]] +name = "aes" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0" +dependencies = [ + "cfg-if", + "cipher 0.4.4", + "cpufeatures 0.2.17", +] + [[package]] name = "aes" version = "0.9.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8eb277bec05f56a0e0591f155a484cbd0f4f07ff2905051a48c72f004f7ed58" dependencies = [ - "cipher", + "cipher 0.5.2", "cpubits", "cpufeatures 0.3.0", "zeroize", @@ -216,6 +227,12 @@ version = "0.22.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" +[[package]] +name = "base64ct" +version = "1.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" + [[package]] name = "bitflags" version = "2.13.0" @@ -241,6 +258,15 @@ dependencies = [ "zeroize", ] +[[package]] +name = "block-padding" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a8894febbff9f758034a5b8e12d87918f56dfc64a8e1fe757d65e29041538d93" +dependencies = [ + "generic-array", +] + [[package]] name = "block-padding" version = "0.4.2" @@ -262,13 +288,22 @@ version = "1.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" +[[package]] +name = "cbc" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26b52a9543ae338f279b96b0b9fed9c8093744685043739079ce85cd58f289a6" +dependencies = [ + "cipher 0.4.4", +] + [[package]] name = "cbc" version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ce2dc9ee5f88d11e0beb842c88b33c8a5cf0d1329c4b19494af42b07dbfe8896" dependencies = [ - "cipher", + "cipher 0.5.2", ] [[package]] @@ -318,6 +353,16 @@ dependencies = [ "windows-link", ] +[[package]] +name = "cipher" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" +dependencies = [ + "crypto-common 0.1.7", + "inout 0.1.4", +] + [[package]] name = "cipher" version = "0.5.2" @@ -326,7 +371,7 @@ checksum = "e8cf2a2c93cd704877c0858356ed03480ff301ee950b43f1cbe4573b088bfa6c" dependencies = [ "block-buffer 0.12.1", "crypto-common 0.2.2", - "inout", + "inout 0.2.2", "zeroize", ] @@ -353,6 +398,12 @@ version = "0.4.32" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cc14f565cf027a105f7a44ccf9e5b424348421a1d8952a8fc9d499d313107789" +[[package]] +name = "const-oid" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" + [[package]] name = "const-oid" version = "0.10.2" @@ -491,7 +542,7 @@ dependencies = [ name = "databricks-sql-kernel" version = "0.2.0" dependencies = [ - "aes", + "aes 0.9.2", "arrow-array", "arrow-buffer", "arrow-cast", @@ -501,17 +552,19 @@ dependencies = [ "arrow-select", "async-trait", "base64", - "cbc", + "cbc 0.2.1", "chrono", "dashmap", "dirs", "futures", "hex", - "hmac", + "hmac 0.13.0", + "jsonwebtoken", "lz4_flex", "oauth2", "open", - "pbkdf2", + "pbkdf2 0.13.0", + "pkcs8", "rand 0.10.2", "reqwest", "serde", @@ -545,6 +598,23 @@ dependencies = [ "tracing-subscriber", ] +[[package]] +name = "der" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" +dependencies = [ + "const-oid 0.9.6", + "pem-rfc7468", + "zeroize", +] + +[[package]] +name = "deranged" +version = "0.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c" + [[package]] name = "digest" version = "0.10.7" @@ -553,6 +623,7 @@ checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ "block-buffer 0.10.4", "crypto-common 0.1.7", + "subtle", ] [[package]] @@ -562,7 +633,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" dependencies = [ "block-buffer 0.12.1", - "const-oid", + "const-oid 0.10.2", "crypto-common 0.2.2", "ctutils", ] @@ -811,6 +882,15 @@ version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" +[[package]] +name = "hmac" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" +dependencies = [ + "digest 0.10.7", +] + [[package]] name = "hmac" version = "0.13.0" @@ -1055,13 +1135,23 @@ dependencies = [ "icu_properties", ] +[[package]] +name = "inout" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01" +dependencies = [ + "block-padding 0.3.3", + "generic-array", +] + [[package]] name = "inout" version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4250ce6452e92010fdf7268ccc5d14faa80bb12fc741938534c58f16804e03c7" dependencies = [ - "block-padding", + "block-padding 0.4.2", "hybrid-array", ] @@ -1107,6 +1197,21 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "jsonwebtoken" +version = "9.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a87cc7a48537badeae96744432de36f4be2b4a34a05a5ef32e9dd8a1c169dde" +dependencies = [ + "base64", + "js-sys", + "pem", + "ring", + "serde", + "serde_json", + "simple_asn1", +] + [[package]] name = "lazy_static" version = "1.5.0" @@ -1365,6 +1470,12 @@ dependencies = [ "num-traits", ] +[[package]] +name = "num-conv" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" + [[package]] name = "num-integer" version = "0.1.46" @@ -1449,6 +1560,16 @@ dependencies = [ "windows-link", ] +[[package]] +name = "pbkdf2" +version = "0.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8ed6a7761f76e3b9f92dfb0a60a6a6477c61024b775147ff0973a02653abaf2" +dependencies = [ + "digest 0.10.7", + "hmac 0.12.1", +] + [[package]] name = "pbkdf2" version = "0.13.0" @@ -1456,7 +1577,26 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "112d82ceb8c5bf524d9af484d4e4970c9fd5a0cc15ba14ad93dccd28873b0629" dependencies = [ "digest 0.11.3", - "hmac", + "hmac 0.13.0", +] + +[[package]] +name = "pem" +version = "3.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d30c53c26bc5b31a98cd02d20f25a7c8567146caf63ed593a9d87b2775291be" +dependencies = [ + "base64", + "serde_core", +] + +[[package]] +name = "pem-rfc7468" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88b39c9bfcfc231068454382784bb460aae594343fb030d46e9f50a645418412" +dependencies = [ + "base64ct", ] [[package]] @@ -1471,6 +1611,33 @@ version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" +[[package]] +name = "pkcs5" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e847e2c91a18bfa887dd028ec33f2fe6f25db77db3619024764914affe8b69a6" +dependencies = [ + "aes 0.8.4", + "cbc 0.1.2", + "der", + "pbkdf2 0.12.2", + "scrypt", + "sha2 0.10.9", + "spki", +] + +[[package]] +name = "pkcs8" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7" +dependencies = [ + "der", + "pkcs5", + "rand_core 0.6.4", + "spki", +] + [[package]] name = "potential_utf" version = "0.1.5" @@ -1480,6 +1647,12 @@ dependencies = [ "zerovec", ] +[[package]] +name = "powerfmt" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" + [[package]] name = "ppv-lite86" version = "0.2.21" @@ -1785,12 +1958,32 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" +[[package]] +name = "salsa20" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97a22f5af31f73a954c10289c93e8a50cc23d971e80ee446f1f6f7137a088213" +dependencies = [ + "cipher 0.4.4", +] + [[package]] name = "scopeguard" version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" +[[package]] +name = "scrypt" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0516a385866c09368f0b5bcd1caff3366aace790fcd46e2bb032697bb172fd1f" +dependencies = [ + "pbkdf2 0.12.2", + "salsa20", + "sha2 0.10.9", +] + [[package]] name = "semver" version = "1.0.28" @@ -1916,6 +2109,18 @@ version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "703d5c7ef118737c72f1af64ad2f6f8c5e1921f818cdcb97b8fe6fc69bf66214" +[[package]] +name = "simple_asn1" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d585997b0ac10be3c5ee635f1bab02d512760d14b7c468801ac8a01d9ae5f1d" +dependencies = [ + "num-bigint", + "num-traits", + "thiserror 2.0.18", + "time", +] + [[package]] name = "slab" version = "0.4.12" @@ -1938,6 +2143,16 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "spki" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d" +dependencies = [ + "base64ct", + "der", +] + [[package]] name = "stable_deref_trait" version = "1.2.1" @@ -2030,6 +2245,36 @@ dependencies = [ "cfg-if", ] +[[package]] +name = "time" +version = "0.3.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134" +dependencies = [ + "deranged", + "num-conv", + "powerfmt", + "serde_core", + "time-core", + "time-macros", +] + +[[package]] +name = "time-core" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" + +[[package]] +name = "time-macros" +version = "0.2.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85" +dependencies = [ + "num-conv", + "time-core", +] + [[package]] name = "tiny-keccak" version = "2.0.2" diff --git a/napi/NEXT_CHANGELOG.md b/napi/NEXT_CHANGELOG.md index c849058e..58da3936 100644 --- a/napi/NEXT_CHANGELOG.md +++ b/napi/NEXT_CHANGELOG.md @@ -14,6 +14,12 @@ layout, or npm publishing. Pure-kernel changes go in the root ### Added +- `AuthMode.OAuthM2mJwt` — OAuth 2.0 machine-to-machine auth using a JWT private-key + client assertion instead of a client secret. New `ConnectionOptions` fields + `jwtKeyFile` (required), `jwtKid` (required), `jwtPassphrase` (optional, for + encrypted PKCS#8 keys), and `jwtAlgorithm` (optional, default `RS256`), alongside + the existing `oauthClientId` / `oauthScopes`. Forwards to the kernel's + `AuthConfig::OAuthM2MPrivateKey`. - `ConnectionOptions.identityFederationClientId` selects SP-wide Workload Identity Federation during mandatory token exchange. diff --git a/napi/index.d.ts b/napi/index.d.ts index f401c31e..bf15780b 100644 --- a/napi/index.d.ts +++ b/napi/index.d.ts @@ -112,6 +112,11 @@ export const enum AuthMode { Pat = 'Pat', /** OAuth 2.0 machine-to-machine — `oauthClientId` + `oauthClientSecret`. */ OAuthM2m = 'OAuthM2m', + /** + * OAuth 2.0 machine-to-machine with a JWT private-key client + * assertion — `oauthClientId` + `jwtKeyFile` + `jwtKid`. + */ + OAuthM2mJwt = 'OAuthM2mJwt', /** * OAuth 2.0 user-to-machine (browser flow) — optional `oauthClientId` * + `oauthRedirectPort`. @@ -205,6 +210,24 @@ export interface ConnectionOptions { * (`["all-apis"]` for M2M; `["sql", "offline_access"]` for U2M). */ oauthScopes?: Array + /** + * Path to the PEM private-key file. Required for + * [`AuthMode::OAuthM2mJwt`]. + */ + jwtKeyFile?: string + /** JWT key id (`kid`). Required for [`AuthMode::OAuthM2mJwt`]. */ + jwtKid?: string + /** + * Passphrase for an encrypted PKCS#8 key. Optional for + * [`AuthMode::OAuthM2mJwt`] (omit for an unencrypted key). + */ + jwtPassphrase?: string + /** + * JWT signing algorithm (`RS256`/`384`/`512`, `PS256`/`384`/`512`, + * `ES256`, `ES384`). Optional for [`AuthMode::OAuthM2mJwt`] + * (omitted ⇒ kernel default `RS256`). + */ + jwtAlgorithm?: string /** * SP-wide Workload Identity Federation client id used during mandatory * token exchange. Omitted selects BYOT / account-wide WIF. diff --git a/napi/src/database.rs b/napi/src/database.rs index 37d07ede..b9791350 100644 --- a/napi/src/database.rs +++ b/napi/src/database.rs @@ -76,6 +76,9 @@ pub enum AuthMode { Pat, /// OAuth 2.0 machine-to-machine — `oauthClientId` + `oauthClientSecret`. OAuthM2m, + /// OAuth 2.0 machine-to-machine with a JWT private-key client + /// assertion — `oauthClientId` + `jwtKeyFile` + `jwtKid`. + OAuthM2mJwt, /// OAuth 2.0 user-to-machine (browser flow) — optional `oauthClientId` /// + `oauthRedirectPort`. OAuthU2m, @@ -157,6 +160,18 @@ pub struct ConnectionOptions { /// OAuth scopes override (M2M / U2M). Omitted ⇒ kernel defaults /// (`["all-apis"]` for M2M; `["sql", "offline_access"]` for U2M). pub oauth_scopes: Option>, + /// Path to the PEM private-key file. Required for + /// [`AuthMode::OAuthM2mJwt`]. + pub jwt_key_file: Option, + /// JWT key id (`kid`). Required for [`AuthMode::OAuthM2mJwt`]. + pub jwt_kid: Option, + /// Passphrase for an encrypted PKCS#8 key. Optional for + /// [`AuthMode::OAuthM2mJwt`] (omit for an unencrypted key). + pub jwt_passphrase: Option, + /// JWT signing algorithm (`RS256`/`384`/`512`, `PS256`/`384`/`512`, + /// `ES256`, `ES384`). Optional for [`AuthMode::OAuthM2mJwt`] + /// (omitted ⇒ kernel default `RS256`). + pub jwt_algorithm: Option, /// SP-wide Workload Identity Federation client id used during mandatory /// token exchange. Omitted selects BYOT / account-wide WIF. pub identity_federation_client_id: Option, @@ -350,6 +365,20 @@ fn build_auth_config(options: &ConnectionOptions) -> napi::Result { options.identity_federation_client_id.clone(), ) .map_err(napi_err_from_kernel), + // JWT private-key client assertion. client_id + jwt_key_file + + // jwt_kid are mandatory; passphrase/algorithm are optional (the + // kernel defaults the algorithm to RS256 and validates the + // key/algorithm/passphrase at session open). + AuthMode::OAuthM2mJwt => AuthConfig::oauth_m2m_private_key( + options.oauth_client_id.clone(), + options.jwt_key_file.clone(), + options.jwt_kid.clone(), + options.jwt_passphrase.clone(), + options.jwt_algorithm.clone(), + options.oauth_scopes.clone(), + None, + ) + .map_err(napi_err_from_kernel), // napi injects no client_id/scope default: it rides the kernel's // single U2M default bundle (databricks-sql-connector / sql // offline_access / port 8030), which already IS the standalone Node @@ -603,6 +632,10 @@ mod tests { oauth_client_secret: None, oauth_redirect_port: None, oauth_scopes: None, + jwt_key_file: None, + jwt_kid: None, + jwt_passphrase: None, + jwt_algorithm: None, identity_federation_client_id: None, catalog: None, schema: None, @@ -719,6 +752,40 @@ mod tests { } } + #[test] + fn m2m_jwt_requires_client_id_key_file_and_kid() { + let mut o = base(); + o.auth_mode = Some(AuthMode::OAuthM2mJwt); + assert_invalid_arg(build_auth_config(&o).unwrap_err(), "client_id"); + o.oauth_client_id = Some("cid".to_owned()); + assert_invalid_arg(build_auth_config(&o).unwrap_err(), "jwt_key_file"); + o.jwt_key_file = Some("/k.pem".to_owned()); + assert_invalid_arg(build_auth_config(&o).unwrap_err(), "jwt_kid"); + o.jwt_kid = Some("kid".to_owned()); + o.jwt_passphrase = Some("pass".to_owned()); + o.jwt_algorithm = Some("ES256".to_owned()); + o.oauth_scopes = Some(vec!["all-apis".to_owned()]); + match build_auth_config(&o).unwrap() { + AuthConfig::OAuthM2MPrivateKey { + client_id, + jwt_key_file, + jwt_kid, + jwt_passphrase, + jwt_algorithm, + scopes, + .. + } => { + assert_eq!(client_id, "cid"); + assert_eq!(jwt_key_file, "/k.pem"); + assert_eq!(jwt_kid, "kid"); + assert_eq!(jwt_passphrase.as_deref(), Some("pass")); + assert_eq!(jwt_algorithm.as_deref(), Some("ES256")); + assert_eq!(scopes, Some(vec!["all-apis".to_owned()])); + } + other => panic!("expected OAuthM2MPrivateKey, got {other:?}"), + } + } + #[test] fn u2m_fields_are_all_optional() { let mut o = base(); diff --git a/osv-scanner.toml b/osv-scanner.toml index 8fdc6643..02316c80 100644 --- a/osv-scanner.toml +++ b/osv-scanner.toml @@ -23,4 +23,51 @@ # separately so this file stays empty on the initial landing; once we # have real suppressions to enforce against, wire it up. -# (intentionally empty — add entries here as needed) +[[IgnoredVulns]] +id = "GHSA-h395-gr6q-cpjc" +# CVE-2026-25537 — a type-confusion bug in jsonwebtoken's claim-VALIDATION +# logic: when DECODING a token, a standard claim (nbf/exp) supplied with the +# wrong JSON type deserializes to FailedToParse, which the validator treats +# like NotPresent and skips the check, letting an attacker bypass nbf/exp. +# Fixed in jsonwebtoken 10.3.0. +# +# Not reachable here: the kernel only SIGNS client assertions +# (`jsonwebtoken::encode` in `src/auth/oauth/jwt_key.rs`) and never decodes +# or validates JWTs — verified: no `jsonwebtoken::decode` / `Validation` +# calls anywhere in `src/`. The vulnerable code path is never invoked. +# +# We stay on 9.x (ring-backed) rather than upgrade: jsonwebtoken 10.x drops +# the ring backend and forces either `rust_crypto` (pulls `rsa` / +# RUSTSEC-2023-0071 into the runtime crate) or `aws_lc_rs` (C library, breaks +# the pure-Rust posture the napi binding depends on). Neither is warranted to +# close a bug we cannot trigger. See the Cargo.toml note on the jsonwebtoken +# pin. Precedent: databricks-sql-go suppresses an unreachable advisory the +# same way (PR #362, GO-2026-5932). +# +# ignoreUntil forces a periodic re-review: when it lapses OSV re-reports the +# finding, and someone must reconfirm we still never decode (and re-evaluate a +# ring-backed 10.x if one exists) before renewing. +ignoreUntil = 2027-02-14 +reason = "jsonwebtoken claim-validation bug (CVE-2026-25537) is in the decode path; the kernel only signs, never decodes/validates JWTs (verified: no decode/Validation calls in src/). Upgrade to 10.x deferred — it forces rust_crypto (rsa/RUSTSEC-2023-0071 in runtime) or aws_lc_rs (C dep). Re-review on expiry." + +[[IgnoredVulns]] +id = "RUSTSEC-2026-0258" +# "h2 unbounded empty DATA frames" — a DoS advisory in `h2 0.4.15`, pulled in +# transitively via `hyper` <- `reqwest` (`cargo tree -i h2`). Not a direct +# dependency and unrelated to this crate's code; pre-existing on `main` (fires +# against the shared reqwest/hyper stack, not this PR). +# +# Not reachable in the way the advisory describes: it concerns a SERVER +# accepting a flood of empty DATA frames; the kernel is an HTTP *client* to +# Databricks SEA and never runs an h2 server, so the affected entrypoint is +# not exposed. +# +# Cannot be cleared by a bump: 0.4.15 is already the latest 0.4.x +# (`cargo update -p h2` is a no-op); clearing it needs an upstream +# `reqwest`/`hyper` release that pulls the fixed `h2`. +# +# ignoreUntil forces periodic re-review: when it lapses OSV re-reports the +# finding, and someone must reconfirm the client-only posture (and re-check +# for a reqwest/hyper release carrying the fix) before renewing. +ignoreUntil = 2027-02-14 +reason = "h2 (RUSTSEC-2026-0258) DoS is a server-side empty-DATA-frame flood; the kernel is an HTTP client only and runs no h2 server. Transitive via reqwest/hyper, pre-existing on main, latest 0.4.x so no bump available. Re-review on expiry." diff --git a/pyo3/Cargo.lock b/pyo3/Cargo.lock index 982aa7a1..a0492194 100644 --- a/pyo3/Cargo.lock +++ b/pyo3/Cargo.lock @@ -8,13 +8,24 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" +[[package]] +name = "aes" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0" +dependencies = [ + "cfg-if", + "cipher 0.4.4", + "cpufeatures 0.2.17", +] + [[package]] name = "aes" version = "0.9.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8eb277bec05f56a0e0591f155a484cbd0f4f07ff2905051a48c72f004f7ed58" dependencies = [ - "cipher", + "cipher 0.5.2", "cpubits", "cpufeatures 0.3.0", "zeroize", @@ -237,6 +248,12 @@ version = "0.22.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" +[[package]] +name = "base64ct" +version = "1.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" + [[package]] name = "bitflags" version = "2.13.0" @@ -262,6 +279,15 @@ dependencies = [ "zeroize", ] +[[package]] +name = "block-padding" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a8894febbff9f758034a5b8e12d87918f56dfc64a8e1fe757d65e29041538d93" +dependencies = [ + "generic-array", +] + [[package]] name = "block-padding" version = "0.4.2" @@ -283,13 +309,22 @@ version = "1.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" +[[package]] +name = "cbc" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26b52a9543ae338f279b96b0b9fed9c8093744685043739079ce85cd58f289a6" +dependencies = [ + "cipher 0.4.4", +] + [[package]] name = "cbc" version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ce2dc9ee5f88d11e0beb842c88b33c8a5cf0d1329c4b19494af42b07dbfe8896" dependencies = [ - "cipher", + "cipher 0.5.2", ] [[package]] @@ -339,6 +374,16 @@ dependencies = [ "windows-link", ] +[[package]] +name = "cipher" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" +dependencies = [ + "crypto-common 0.1.7", + "inout 0.1.4", +] + [[package]] name = "cipher" version = "0.5.2" @@ -347,7 +392,7 @@ checksum = "e8cf2a2c93cd704877c0858356ed03480ff301ee950b43f1cbe4573b088bfa6c" dependencies = [ "block-buffer 0.12.1", "crypto-common 0.2.2", - "inout", + "inout 0.2.2", "zeroize", ] @@ -374,6 +419,12 @@ version = "0.4.32" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cc14f565cf027a105f7a44ccf9e5b424348421a1d8952a8fc9d499d313107789" +[[package]] +name = "const-oid" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" + [[package]] name = "const-oid" version = "0.10.2" @@ -497,7 +548,7 @@ dependencies = [ name = "databricks-sql-kernel" version = "0.2.0" dependencies = [ - "aes", + "aes 0.9.2", "arrow-array", "arrow-buffer", "arrow-cast", @@ -507,17 +558,19 @@ dependencies = [ "arrow-select", "async-trait", "base64", - "cbc", + "cbc 0.2.1", "chrono", "dashmap", "dirs", "futures", "hex", - "hmac", + "hmac 0.13.0", + "jsonwebtoken", "lz4_flex", "oauth2", "open", - "pbkdf2", + "pbkdf2 0.13.0", + "pkcs8", "rand 0.10.2", "reqwest", "serde", @@ -547,6 +600,23 @@ dependencies = [ "tracing", ] +[[package]] +name = "der" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" +dependencies = [ + "const-oid 0.9.6", + "pem-rfc7468", + "zeroize", +] + +[[package]] +name = "deranged" +version = "0.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c" + [[package]] name = "digest" version = "0.10.7" @@ -555,6 +625,7 @@ checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ "block-buffer 0.10.4", "crypto-common 0.1.7", + "subtle", ] [[package]] @@ -564,7 +635,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" dependencies = [ "block-buffer 0.12.1", - "const-oid", + "const-oid 0.10.2", "crypto-common 0.2.2", "ctutils", ] @@ -819,6 +890,15 @@ version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" +[[package]] +name = "hmac" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" +dependencies = [ + "digest 0.10.7", +] + [[package]] name = "hmac" version = "0.13.0" @@ -1063,13 +1143,23 @@ dependencies = [ "icu_properties", ] +[[package]] +name = "inout" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01" +dependencies = [ + "block-padding 0.3.3", + "generic-array", +] + [[package]] name = "inout" version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4250ce6452e92010fdf7268ccc5d14faa80bb12fc741938534c58f16804e03c7" dependencies = [ - "block-padding", + "block-padding 0.4.2", "hybrid-array", ] @@ -1115,6 +1205,21 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "jsonwebtoken" +version = "9.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a87cc7a48537badeae96744432de36f4be2b4a34a05a5ef32e9dd8a1c169dde" +dependencies = [ + "base64", + "js-sys", + "pem", + "ring", + "serde", + "serde_json", + "simple_asn1", +] + [[package]] name = "lazy_static" version = "1.5.0" @@ -1299,6 +1404,12 @@ dependencies = [ "num-traits", ] +[[package]] +name = "num-conv" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" + [[package]] name = "num-integer" version = "0.1.46" @@ -1383,6 +1494,16 @@ dependencies = [ "windows-link", ] +[[package]] +name = "pbkdf2" +version = "0.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8ed6a7761f76e3b9f92dfb0a60a6a6477c61024b775147ff0973a02653abaf2" +dependencies = [ + "digest 0.10.7", + "hmac 0.12.1", +] + [[package]] name = "pbkdf2" version = "0.13.0" @@ -1390,7 +1511,26 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "112d82ceb8c5bf524d9af484d4e4970c9fd5a0cc15ba14ad93dccd28873b0629" dependencies = [ "digest 0.11.3", - "hmac", + "hmac 0.13.0", +] + +[[package]] +name = "pem" +version = "3.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d30c53c26bc5b31a98cd02d20f25a7c8567146caf63ed593a9d87b2775291be" +dependencies = [ + "base64", + "serde_core", +] + +[[package]] +name = "pem-rfc7468" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88b39c9bfcfc231068454382784bb460aae594343fb030d46e9f50a645418412" +dependencies = [ + "base64ct", ] [[package]] @@ -1405,6 +1545,33 @@ version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" +[[package]] +name = "pkcs5" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e847e2c91a18bfa887dd028ec33f2fe6f25db77db3619024764914affe8b69a6" +dependencies = [ + "aes 0.8.4", + "cbc 0.1.2", + "der", + "pbkdf2 0.12.2", + "scrypt", + "sha2 0.10.9", + "spki", +] + +[[package]] +name = "pkcs8" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7" +dependencies = [ + "der", + "pkcs5", + "rand_core 0.6.4", + "spki", +] + [[package]] name = "portable-atomic" version = "1.13.1" @@ -1420,6 +1587,12 @@ dependencies = [ "zerovec", ] +[[package]] +name = "powerfmt" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" + [[package]] name = "ppv-lite86" version = "0.2.21" @@ -1793,12 +1966,32 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" +[[package]] +name = "salsa20" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97a22f5af31f73a954c10289c93e8a50cc23d971e80ee446f1f6f7137a088213" +dependencies = [ + "cipher 0.4.4", +] + [[package]] name = "scopeguard" version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" +[[package]] +name = "scrypt" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0516a385866c09368f0b5bcd1caff3366aace790fcd46e2bb032697bb172fd1f" +dependencies = [ + "pbkdf2 0.12.2", + "salsa20", + "sha2 0.10.9", +] + [[package]] name = "semver" version = "1.0.28" @@ -1924,6 +2117,18 @@ version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "703d5c7ef118737c72f1af64ad2f6f8c5e1921f818cdcb97b8fe6fc69bf66214" +[[package]] +name = "simple_asn1" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d585997b0ac10be3c5ee635f1bab02d512760d14b7c468801ac8a01d9ae5f1d" +dependencies = [ + "num-bigint", + "num-traits", + "thiserror 2.0.18", + "time", +] + [[package]] name = "slab" version = "0.4.12" @@ -1946,6 +2151,16 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "spki" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d" +dependencies = [ + "base64ct", + "der", +] + [[package]] name = "stable_deref_trait" version = "1.2.1" @@ -2044,6 +2259,36 @@ dependencies = [ "cfg-if", ] +[[package]] +name = "time" +version = "0.3.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134" +dependencies = [ + "deranged", + "num-conv", + "powerfmt", + "serde_core", + "time-core", + "time-macros", +] + +[[package]] +name = "time-core" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" + +[[package]] +name = "time-macros" +version = "0.2.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85" +dependencies = [ + "num-conv", + "time-core", +] + [[package]] name = "tiny-keccak" version = "2.0.2" diff --git a/pyo3/NEXT_CHANGELOG.md b/pyo3/NEXT_CHANGELOG.md index 191ce3b4..ff26f707 100644 --- a/pyo3/NEXT_CHANGELOG.md +++ b/pyo3/NEXT_CHANGELOG.md @@ -13,6 +13,12 @@ changes go in the root `NEXT_CHANGELOG.md`. ### Added +- `Session(auth_type="oauth-m2m-jwt", ...)` — OAuth 2.0 machine-to-machine auth using + a JWT private-key client assertion instead of a client secret. New keyword args + `jwt_key_file` (required), `jwt_kid` (required), `jwt_passphrase` (optional, for + encrypted PKCS#8 keys), and `jwt_algorithm` (optional, default `RS256`), alongside + the existing `client_id` / `oauth_scopes` / `token_url`. Forwards to the kernel's + `AuthConfig::OAuthM2MPrivateKey`. - `Session(..., identity_federation_client_id=...)` selects SP-wide Workload Identity Federation during mandatory token exchange. diff --git a/pyo3/src/auth.rs b/pyo3/src/auth.rs index d2140789..992f209b 100644 --- a/pyo3/src/auth.rs +++ b/pyo3/src/auth.rs @@ -14,11 +14,15 @@ //! Translate Python auth kwargs into a kernel `AuthConfig`. //! -//! Supports three `auth_type` values: +//! Supports four `auth_type` values: //! //! - `"pat"` — personal access token (`access_token`). //! - `"oauth-m2m"` — OAuth 2.0 client-credentials (service principal): //! `client_id` + `client_secret`, optional `scopes` / `token_url`. +//! - `"oauth-m2m-jwt"` — OAuth 2.0 client-credentials with a JWT +//! private-key client assertion (RFC 7523): `client_id` + +//! `jwt_key_file` + `jwt_kid`, optional `jwt_passphrase` / +//! `jwt_algorithm` / `scopes` / `token_url`. //! - `"oauth-u2m"` — OAuth 2.0 authorization-code + PKCE browser flow: //! optional `client_id` / `redirect_ports` / `scopes` / `token_url` / //! `oauth_callback_timeout_secs`. @@ -61,6 +65,11 @@ pub(crate) struct OAuthParams { /// [`build_auth_config`]), not defaulted. pub redirect_ports: Option>, pub callback_timeout_secs: Option, + // JWT private-key M2M (`auth_type="oauth-m2m-jwt"`). + pub jwt_key_file: Option, + pub jwt_kid: Option, + pub jwt_passphrase: Option, + pub jwt_algorithm: Option, pub identity_federation_client_id: Option, } @@ -173,6 +182,31 @@ fn build_auth_config_inner( ) .map_err(|err| err.to_string()) } + "oauth-m2m-jwt" => { + // JWT private-key client assertion: client_id + key file + + // kid are mandatory; passphrase/algorithm are optional (the + // kernel defaults the algorithm to RS256 and validates the + // key/algorithm/passphrase at session open). + let client_id = non_empty( + oauth.client_id, + "auth_type='oauth-m2m-jwt' requires client_id", + )?; + let jwt_key_file = non_empty( + oauth.jwt_key_file, + "auth_type='oauth-m2m-jwt' requires jwt_key_file", + )?; + let jwt_kid = non_empty(oauth.jwt_kid, "auth_type='oauth-m2m-jwt' requires jwt_kid")?; + AuthConfig::oauth_m2m_private_key( + Some(client_id), + Some(jwt_key_file), + Some(jwt_kid), + oauth.jwt_passphrase, + oauth.jwt_algorithm, + oauth.scopes, + oauth.token_url, + ) + .map_err(|e| e.message) + } "oauth-u2m" => { // Browser flow: every field is optional and `None` lets the // kernel apply its defaults (client_id "databricks-sql-connector", @@ -286,7 +320,8 @@ fn build_auth_config_inner( )) } other => Err(format!( - "unsupported auth_type {other:?}; expected one of 'pat', 'oauth-m2m', 'oauth-u2m'" + "unsupported auth_type {other:?}; expected one of 'pat', 'oauth-m2m', \ + 'oauth-m2m-jwt', 'oauth-u2m'" )), } } @@ -410,6 +445,87 @@ mod tests { } } + #[test] + fn m2m_jwt_requires_client_id_key_file_and_kid() { + // Missing client_id. + let err = build_auth_config_inner( + "oauth-m2m-jwt", + None, + OAuthParams { + jwt_key_file: Some("/k.pem".into()), + jwt_kid: Some("kid".into()), + ..Default::default() + }, + ) + .unwrap_err(); + assert!(err.contains("client_id"), "{err}"); + + // Missing key file. + let err = build_auth_config_inner( + "oauth-m2m-jwt", + None, + OAuthParams { + client_id: Some("id".into()), + jwt_kid: Some("kid".into()), + ..Default::default() + }, + ) + .unwrap_err(); + assert!(err.contains("jwt_key_file"), "{err}"); + + // Missing kid. + let err = build_auth_config_inner( + "oauth-m2m-jwt", + None, + OAuthParams { + client_id: Some("id".into()), + jwt_key_file: Some("/k.pem".into()), + ..Default::default() + }, + ) + .unwrap_err(); + assert!(err.contains("jwt_kid"), "{err}"); + } + + #[test] + fn m2m_jwt_builds_with_all_fields() { + let cfg = build_auth_config_inner( + "oauth-m2m-jwt", + None, + OAuthParams { + client_id: Some("id".into()), + jwt_key_file: Some("/k.pem".into()), + jwt_kid: Some("kid".into()), + jwt_passphrase: Some("pass".into()), + jwt_algorithm: Some("ES256".into()), + scopes: Some(vec!["all-apis".into()]), + token_url: Some("https://example/token".into()), + ..Default::default() + }, + ) + .unwrap(); + match cfg { + AuthConfig::OAuthM2MPrivateKey { + client_id, + jwt_key_file, + jwt_kid, + jwt_passphrase, + jwt_algorithm, + scopes, + token_url_override, + } => { + assert_eq!(client_id, "id"); + assert_eq!(jwt_key_file, "/k.pem"); + assert_eq!(jwt_kid, "kid"); + assert_eq!(jwt_passphrase.as_deref(), Some("pass")); + assert_eq!(jwt_algorithm.as_deref(), Some("ES256")); + assert_eq!(scopes, Some(vec!["all-apis".to_string()])); + assert_eq!(token_url_override.as_deref(), Some("https://example/token")); + } + other => panic!("expected OAuthM2MPrivateKey, got {other:?}"), + } + } + #[test] fn u2m_defaults_client_id_and_scopes_to_python_connector() { // U2M takes no mandatory fields. The Python binding defaults the diff --git a/pyo3/src/session.rs b/pyo3/src/session.rs index c5ce6c59..83e4b245 100644 --- a/pyo3/src/session.rs +++ b/pyo3/src/session.rs @@ -122,6 +122,10 @@ impl Session { token_url=None, redirect_ports=None, oauth_callback_timeout_secs=None, + jwt_key_file=None, + jwt_kid=None, + jwt_passphrase=None, + jwt_algorithm=None, identity_federation_client_id=None, tls_ca_cert=None, tls_skip_verify=false, @@ -152,6 +156,10 @@ impl Session { token_url: Option, redirect_ports: Option>, oauth_callback_timeout_secs: Option, + jwt_key_file: Option, + jwt_kid: Option, + jwt_passphrase: Option, + jwt_algorithm: Option, identity_federation_client_id: Option, tls_ca_cert: Option>, tls_skip_verify: bool, @@ -187,8 +195,8 @@ impl Session { ); return Err(pyo3::exceptions::PyValueError::new_err( "Session requires auth: pass access_token (PAT) or set \ - auth_type to 'oauth-m2m' / 'oauth-u2m' with the matching \ - credentials", + auth_type to 'oauth-m2m' / 'oauth-m2m-jwt' / 'oauth-u2m' \ + with the matching credentials", )); } }; @@ -199,6 +207,10 @@ impl Session { token_url, redirect_ports, callback_timeout_secs: oauth_callback_timeout_secs, + jwt_key_file, + jwt_kid, + jwt_passphrase, + jwt_algorithm, identity_federation_client_id, }; let auth_config = build_auth_config(&resolved_auth_type, access_token, oauth)?; diff --git a/src/auth/mod.rs b/src/auth/mod.rs index 5f200f13..1a560f03 100644 --- a/src/auth/mod.rs +++ b/src/auth/mod.rs @@ -19,7 +19,10 @@ pub mod oauth; pub mod pat; pub use config::{AuthConfig, AuthType}; -pub use oauth::{AuthorizationCodeProvider, ClientCredentialsProvider, FederationProvider}; +pub use oauth::{ + AuthorizationCodeProvider, ClientCredentialsProvider, FederationProvider, + JwtClientCredentialsProvider, +}; pub use pat::PersonalAccessToken; use crate::kernel_error::Result; diff --git a/src/auth/oauth/jwt_key.rs b/src/auth/oauth/jwt_key.rs new file mode 100644 index 00000000..1e277cec --- /dev/null +++ b/src/auth/oauth/jwt_key.rs @@ -0,0 +1,430 @@ +// 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. + +//! Private-key loading and JWT client-assertion signing. +//! +//! This module is the net-new crypto behind the JWT private-key +//! client-credentials flow (see [`super::jwt_m2m`]). It provides the two +//! capabilities the kernel lacked — loading a PEM/PKCS#8 private key off +//! disk and producing a signed JWT. +//! +//! # Algorithm coverage +//! +//! We sign with the `jsonwebtoken` crate, which is backed by `ring` +//! (already in the dependency graph via rustls, so no new heavyweight +//! dependency). Supported algorithms: `RS256/384/512`, `PS256/384/512`, +//! `ES256`, `ES384`. Default is `RS256`. +//! +//! `ES512` (P-521) is **not** supported: `ring` has no P-521, and the +//! only Rust path to it is the `openssl` crate, which would reintroduce +//! the system-OpenSSL / Node module-load clash the kernel deliberately +//! avoids (see the TLS notes in `Cargo.toml`). We reject an unsupported +//! algorithm loudly at construction time rather than silently falling +//! back to `RS256`: a silent fallback would sign with the wrong algorithm +//! and surface as an opaque server-side `invalid_client` rejection with no +//! hint at the real cause. +//! +//! # Key format coverage +//! +//! Keys are loaded from PEM. Unencrypted PKCS#8 (`BEGIN PRIVATE KEY`), +//! SEC1 EC (`BEGIN EC PRIVATE KEY`), and PKCS#1 RSA (`BEGIN RSA PRIVATE +//! KEY`) are handed to `jsonwebtoken` directly. Passphrase-encrypted +//! PKCS#8 (`BEGIN ENCRYPTED PRIVATE KEY`) is first decrypted via the +//! `pkcs8` crate (PBES2: PBKDF2/scrypt + AES-CBC — what modern OpenSSL +//! emits) and re-encoded to an unencrypted PKCS#8 PEM in memory before +//! signing. Legacy encryption schemes BouncyCastle also accepts (PBES1, +//! 3DES) are not covered; the fix is a one-line re-encrypt to a modern +//! cipher, which the caller controls. + +use std::path::Path; + +use jsonwebtoken::{Algorithm, EncodingKey, Header}; +use serde::Serialize; +use zeroize::Zeroizing; + +use crate::kernel_error::{Error, Result}; + +/// PEM label for an unencrypted PKCS#8 private key. +const PEM_LABEL_PRIVATE_KEY: &str = "PRIVATE KEY"; +/// PEM label for a passphrase-encrypted PKCS#8 private key. +const PEM_LABEL_ENCRYPTED_PRIVATE_KEY: &str = "ENCRYPTED PRIVATE KEY"; + +/// Whether a signing key is RSA- or EC-based. Determines which +/// `jsonwebtoken::EncodingKey` constructor and which algorithm family +/// applies. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum KeyKind { + Rsa, + Ec, +} + +/// A loaded private key plus the JWT signing algorithm to use with it. +/// +/// The key is parsed once (from a PEM file) and cached in the provider, +/// so signing does no per-request key loading. The [`EncodingKey`] is opaque +/// signing material; it does not implement `Debug`, so this struct +/// intentionally does not derive it (and the provider redacts around it). +pub(crate) struct JwtSigningKey { + encoding_key: EncodingKey, + algorithm: Algorithm, +} + +impl JwtSigningKey { + /// Load and prepare a signing key from a PEM file. + /// + /// * `key_path` — path to the PEM-encoded private key. + /// * `passphrase` — passphrase for an encrypted PKCS#8 key, or `None` + /// for an unencrypted key. + /// * `algorithm` — JWT algorithm name (e.g. `"RS256"`, `"ES256"`). + /// `None` defaults to `RS256`. + /// + /// Returns an error if the file cannot be read, the algorithm is + /// unsupported, the key cannot be decrypted/parsed, or the key type + /// does not match the algorithm family (e.g. an EC key with `RS256`). + pub(crate) fn load( + key_path: &str, + passphrase: Option<&str>, + algorithm: Option<&str>, + ) -> Result { + let algorithm = parse_algorithm(algorithm)?; + let kind = key_kind_for(algorithm); + + let pem = read_key_pem(key_path, passphrase)?; + let encoding_key = build_encoding_key(&pem, kind)?; + + Ok(Self { + encoding_key, + algorithm, + }) + } + + /// Sign the given claims into a serialized (compact) JWT. + /// + /// The `kid` (key id) is written into the JWT header alongside the + /// algorithm so the authorization server can select the matching + /// registered public key. + pub(crate) fn sign(&self, kid: &str, claims: &C) -> Result { + let mut header = Header::new(self.algorithm); + header.kid = Some(kid.to_string()); + jsonwebtoken::encode(&header, claims, &self.encoding_key) + .map_err(|e| Error::invalid_argument().message(format!("Error signing the JWT: {e}"))) + } +} + +/// Map a JWT algorithm name onto a supported [`Algorithm`]. +/// +/// `None` defaults to `RS256`. Unsupported values — including `ES512`, +/// which `ring` cannot sign — are rejected loudly rather than silently +/// coerced. +fn parse_algorithm(algorithm: Option<&str>) -> Result { + let Some(name) = algorithm else { + return Ok(Algorithm::RS256); + }; + match name { + "RS256" => Ok(Algorithm::RS256), + "RS384" => Ok(Algorithm::RS384), + "RS512" => Ok(Algorithm::RS512), + "PS256" => Ok(Algorithm::PS256), + "PS384" => Ok(Algorithm::PS384), + "PS512" => Ok(Algorithm::PS512), + "ES256" => Ok(Algorithm::ES256), + "ES384" => Ok(Algorithm::ES384), + other => Err(Error::invalid_argument().message(format!( + "unsupported JWT algorithm '{other}'. Supported: RS256, RS384, RS512, \ + PS256, PS384, PS512, ES256, ES384 (ES512 is not supported)" + ))), + } +} + +/// The key family required by a given signing algorithm. +fn key_kind_for(algorithm: Algorithm) -> KeyKind { + match algorithm { + Algorithm::ES256 | Algorithm::ES384 => KeyKind::Ec, + // RS* and PS* are all RSA. EdDSA / HS* are unreachable here + // (parse_algorithm never yields them), so treat the remainder + // as RSA. + _ => KeyKind::Rsa, + } +} + +/// Read the private-key PEM from disk, decrypting it first if a +/// passphrase is supplied. +/// +/// Returns an unencrypted PEM string ready for `jsonwebtoken`, wrapped in +/// [`Zeroizing`] so the plaintext private-key bytes are wiped from the +/// heap on drop (consistent with the token-cache crypto's `zeroize` +/// posture — see `Cargo.toml`). When a passphrase is given, the on-disk +/// key is expected to be an encrypted PKCS#8 (`BEGIN ENCRYPTED PRIVATE +/// KEY`); it is decrypted and re-encoded to an unencrypted PKCS#8 PEM in +/// memory. +fn read_key_pem(key_path: &str, passphrase: Option<&str>) -> Result> { + // A missing/unreadable file and a parse failure both surface under the + // same "Failed to parse private key: …" message. Wrap the raw file + // contents in `Zeroizing`: for an unencrypted key this string *is* the + // plaintext private key. + let raw = Zeroizing::new(std::fs::read_to_string(Path::new(key_path)).map_err(|e| { + Error::invalid_argument().message(format!("Failed to parse private key: {e}")) + })?); + + match passphrase { + Some(pass) => decrypt_pkcs8_pem(&raw, pass), + None => Ok(raw), + } +} + +/// Decrypt a passphrase-protected PKCS#8 PEM and return an unencrypted +/// PKCS#8 PEM, wrapped in [`Zeroizing`] so the decrypted private key is +/// wiped from the heap on drop. +fn decrypt_pkcs8_pem(encrypted_pem: &str, passphrase: &str) -> Result> { + use pkcs8::der::pem::LineEnding; + use pkcs8::{EncryptedPrivateKeyInfo, SecretDocument}; + + // Parse the PEM wrapper. The label must be ENCRYPTED PRIVATE KEY; + // anything else means the caller passed a passphrase for a key that + // is not an encrypted PKCS#8 (a common misconfiguration). + // All failures below surface under a single "Cannot decrypt private JWT + // key …" message. + let (label, doc) = SecretDocument::from_pem(encrypted_pem).map_err(|e| { + Error::invalid_argument().message(format!("Cannot decrypt private JWT key {e}")) + })?; + if label != PEM_LABEL_ENCRYPTED_PRIVATE_KEY { + return Err(Error::invalid_argument().message(format!( + "Cannot decrypt private JWT key: a passphrase was supplied but the key \ + PEM is labelled '{label}', not '{PEM_LABEL_ENCRYPTED_PRIVATE_KEY}'; only \ + encrypted PKCS#8 keys use a passphrase" + ))); + } + + let encrypted = EncryptedPrivateKeyInfo::try_from(doc.as_bytes()).map_err(|e| { + Error::invalid_argument().message(format!("Cannot decrypt private JWT key {e}")) + })?; + + let decrypted: SecretDocument = encrypted.decrypt(passphrase).map_err(|e| { + Error::invalid_argument().message(format!( + "Cannot decrypt private JWT key (wrong passphrase, or an unsupported \ + encryption scheme — only modern PBES2 with PBKDF2/scrypt + AES is \ + supported): {e}" + )) + })?; + + // `to_pem` already returns a `Zeroizing`; keep it wrapped + // (rather than `.to_string()`-ing into a bare String) so the decrypted + // plaintext PEM is zeroized on drop. + decrypted + .to_pem(PEM_LABEL_PRIVATE_KEY, LineEnding::LF) + .map_err(|e| { + Error::invalid_argument().message(format!("Cannot decrypt private JWT key {e}")) + }) +} + +/// Build a `jsonwebtoken::EncodingKey` from an unencrypted PEM, choosing +/// the RSA or EC constructor to match the algorithm family. +fn build_encoding_key(pem: &str, kind: KeyKind) -> Result { + let pem_bytes = pem.as_bytes(); + let result = match kind { + KeyKind::Rsa => EncodingKey::from_rsa_pem(pem_bytes), + KeyKind::Ec => EncodingKey::from_ec_pem(pem_bytes), + }; + result.map_err(|e| { + let expected = match kind { + KeyKind::Rsa => "an RSA key (for an RS*/PS* algorithm)", + KeyKind::Ec => "an EC key (for an ES* algorithm)", + }; + // Keep the "Failed to parse private key: …" prefix and add an + // actionable hint about the key-type/algorithm mismatch. + Error::invalid_argument().message(format!( + "Failed to parse private key: expected {expected}; check that the key \ + type matches the configured algorithm: {e}" + )) + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parse_algorithm_defaults_to_rs256() { + assert_eq!(parse_algorithm(None).unwrap(), Algorithm::RS256); + } + + #[test] + fn parse_algorithm_maps_supported_names() { + for (name, alg) in [ + ("RS256", Algorithm::RS256), + ("RS384", Algorithm::RS384), + ("RS512", Algorithm::RS512), + ("PS256", Algorithm::PS256), + ("PS384", Algorithm::PS384), + ("PS512", Algorithm::PS512), + ("ES256", Algorithm::ES256), + ("ES384", Algorithm::ES384), + ] { + assert_eq!(parse_algorithm(Some(name)).unwrap(), alg, "{name}"); + } + } + + #[test] + fn parse_algorithm_rejects_es512_loudly() { + let err = parse_algorithm(Some("ES512")).unwrap_err(); + let msg = format!("{err:?}"); + assert!(msg.contains("ES512"), "{msg}"); + assert!(msg.contains("not supported"), "{msg}"); + } + + #[test] + fn parse_algorithm_rejects_unknown() { + assert!(parse_algorithm(Some("HS256")).is_err()); + assert!(parse_algorithm(Some("nonsense")).is_err()); + } + + #[test] + fn key_kind_matches_family() { + assert_eq!(key_kind_for(Algorithm::RS256), KeyKind::Rsa); + assert_eq!(key_kind_for(Algorithm::PS512), KeyKind::Rsa); + assert_eq!(key_kind_for(Algorithm::ES256), KeyKind::Ec); + assert_eq!(key_kind_for(Algorithm::ES384), KeyKind::Ec); + } + + /// Assert that a `JwtSigningKey::load` result is an error whose debug + /// string contains `needle`. `JwtSigningKey` (the Ok variant) is not + /// `Debug`, so `expect_err()` can't be used directly. + fn assert_load_err(result: Result, needle: &str) { + match result { + Ok(_) => panic!("expected load error containing {needle:?}"), + Err(e) => { + let msg = format!("{e:?}"); + assert!(msg.contains(needle), "error {msg:?} missing {needle:?}"); + } + } + } + + use crate::auth::oauth::test_keys; + + /// Write a PEM string to a temp file and return (tempdir guard, path). + /// The guard must be kept alive for the file to exist. + fn key_file(pem: &str) -> (tempfile::TempDir, String) { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("k.pem"); + std::fs::write(&path, pem).unwrap(); + let p = path.to_str().unwrap().to_string(); + (dir, p) + } + + #[test] + fn loads_unencrypted_rsa_key() { + let (_d, path) = key_file(&test_keys::rsa_pkcs8_pem()); + JwtSigningKey::load(&path, None, Some("RS256")).expect("unencrypted RSA key should load"); + } + + #[test] + fn loads_and_decrypts_pbes2_encrypted_key() { + let (_d, path) = key_file(&test_keys::rsa_encrypted_pkcs8_pem()); + JwtSigningKey::load(&path, Some(test_keys::TEST_KEY_PASSPHRASE), Some("RS256")) + .expect("encrypted PKCS#8 key should decrypt and load"); + } + + #[test] + fn wrong_passphrase_fails_with_clear_error() { + let (_d, path) = key_file(&test_keys::rsa_encrypted_pkcs8_pem()); + assert_load_err( + JwtSigningKey::load(&path, Some("wrong-pass"), Some("RS256")), + "decrypt", + ); + } + + #[test] + fn passphrase_on_unencrypted_key_is_rejected() { + let (_d, path) = key_file(&test_keys::rsa_pkcs8_pem()); + assert_load_err( + JwtSigningKey::load(&path, Some("x"), Some("RS256")), + "ENCRYPTED PRIVATE KEY", + ); + } + + #[test] + fn ec_algorithm_with_rsa_key_fails() { + // Key/algorithm family mismatch must be caught at load time. + let (_d, path) = key_file(&test_keys::rsa_pkcs8_pem()); + assert_load_err( + JwtSigningKey::load(&path, None, Some("ES256")), + "Failed to parse private key", + ); + } + + #[test] + fn loads_ec_p256_key_and_signs_es256() { + // An EC key signs an ES256 JWT. + let (_d, path) = key_file(&test_keys::ec_p256_pkcs8_pem()); + let key = JwtSigningKey::load(&path, None, Some("ES256")) + .expect("EC P-256 key should load for ES256"); + + #[derive(serde::Serialize)] + struct Claims { + sub: String, + } + let jwt = key + .sign("ec-kid", &Claims { sub: "c".into() }) + .expect("sign"); + use base64::Engine; + let header_json = base64::engine::general_purpose::URL_SAFE_NO_PAD + .decode(jwt.split('.').next().unwrap()) + .unwrap(); + let header: serde_json::Value = serde_json::from_slice(&header_json).unwrap(); + assert_eq!(header["alg"], "ES256"); + assert_eq!(header["kid"], "ec-kid"); + } + + #[test] + fn signs_a_jwt_with_kid_header() { + let (_d, path) = key_file(&test_keys::rsa_pkcs8_pem()); + let key = JwtSigningKey::load(&path, None, Some("RS256")).unwrap(); + + #[derive(serde::Serialize)] + struct Claims { + sub: String, + } + let jwt = key + .sign( + "my-kid", + &Claims { + sub: "client-1".into(), + }, + ) + .expect("sign"); + + // A compact JWS is header.payload.signature. + let parts: Vec<&str> = jwt.split('.').collect(); + assert_eq!(parts.len(), 3, "expected compact JWS"); + + // Decode the header and confirm alg + kid. + use base64::Engine; + let header_json = base64::engine::general_purpose::URL_SAFE_NO_PAD + .decode(parts[0]) + .unwrap(); + let header: serde_json::Value = serde_json::from_slice(&header_json).unwrap(); + assert_eq!(header["alg"], "RS256"); + assert_eq!(header["kid"], "my-kid"); + } + + #[test] + fn build_encoding_key_rejects_garbage() { + // `EncodingKey` (the Ok variant) is not `Debug`, so match rather + // than `unwrap_err()`. + match build_encoding_key("not a pem", KeyKind::Rsa) { + Ok(_) => panic!("garbage PEM should not parse"), + Err(e) => assert!(format!("{e:?}").contains("Failed to parse private key")), + } + } +} diff --git a/src/auth/oauth/jwt_m2m.rs b/src/auth/oauth/jwt_m2m.rs new file mode 100644 index 00000000..d18d1224 --- /dev/null +++ b/src/auth/oauth/jwt_m2m.rs @@ -0,0 +1,633 @@ +// 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. + +//! M2M OAuth using a JWT private-key client assertion. +//! +//! This is the private-key variant of the client-credentials grant (see +//! [`super::m2m`] for the shared-secret variant). Instead of sending a +//! `client_secret`, the provider signs a short-lived JWT with a private +//! key and sends it as an RFC 7523 `client_assertion`. The authorization +//! server verifies the signature against the service principal's +//! registered public key and returns an access token. +//! +//! The OAuth lifecycle — OIDC discovery, in-memory token caching, refresh +//! on expiry — is identical to [`super::m2m::ClientCredentialsProvider`] +//! and reuses the same [`TokenStore`] and [`OidcEndpoints`] machinery. The +//! only substantive differences are: +//! +//! 1. The key is loaded and cached once at construction ([`JwtSigningKey`]). +//! 2. The token request is a manual form POST carrying `client_assertion` +//! (the `oauth2` crate's `exchange_client_credentials()` helper cannot +//! send a client-assertion, only a client secret). +//! +//! M2M tokens are not cached to disk (same rationale as [`super::m2m`]): +//! the private key is always available for re-authentication. + +use std::sync::Arc; + +use oauth2::basic::BasicTokenType; +use oauth2::{EmptyExtraTokenFields, StandardTokenResponse, TokenResponse as _}; +use tokio::runtime::Handle as RuntimeHandle; + +use crate::auth::oauth::jwt_key::JwtSigningKey; +use crate::auth::oauth::oidc::OidcEndpoints; +use crate::auth::oauth::token::OAuthToken; +use crate::auth::oauth::token_store::TokenStore; +use crate::auth::AuthProvider; +use crate::client::http::DatabricksHttpClient; +use crate::client::retry::RequestType; +use crate::kernel_error::{Error, Result}; +use crate::util::runtime::block_on_in_runtime; + +/// RFC 7523 client-assertion type for a JWT bearer assertion. +const JWT_BEARER_ASSERTION_TYPE: &str = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"; + +/// Lifetime of the signed client-assertion JWT. +/// +/// The assertion is given a small positive validity window (`exp` strictly +/// after `iat`); it is single-use and consumed immediately by the token +/// exchange, so a short window is ample. +const ASSERTION_LIFETIME_SECONDS: i64 = 300; + +/// Fallback token TTL when the token endpoint omits `expires_in`. +const DEFAULT_TOKEN_TTL_SECONDS: i64 = 3600; + +/// Claims for the signed client-assertion JWT. +/// +/// Per RFC 7523: `iss` and `sub` are both the client id, `aud` is the +/// token endpoint, `jti` is a unique id (replay protection), and `iat` +/// / `exp` bound the validity window. +#[derive(Debug, serde::Serialize)] +struct AssertionClaims { + iss: String, + sub: String, + aud: String, + jti: String, + iat: i64, + exp: i64, +} + +/// The OAuth token endpoint's JSON response, parsed via the `oauth2` +/// crate's standard type so this path shares the same response model as +/// [`super::m2m::ClientCredentialsProvider`] rather than a bespoke struct. +type TokenResponse = StandardTokenResponse; + +/// Generate a unique JWT id (`jti`) for replay protection: 128 random +/// bits rendered as hex. Uses the `rand` crate already pulled in for +/// retry jitter, avoiding a `uuid` dependency. +fn new_jti() -> String { + use rand::RngExt; + let bytes: [u8; 16] = rand::rng().random(); + hex::encode(bytes) +} + +/// OAuth provider for M2M authentication via a JWT private-key client +/// assertion. +/// +/// Discovers the token endpoint via OIDC at construction, loads and +/// caches the signing key, then signs a fresh assertion on each token +/// fetch. Tokens are managed by [`TokenStore`] with automatic refresh, +/// exactly like [`super::m2m::ClientCredentialsProvider`]. +pub struct JwtClientCredentialsProvider { + /// OAuth client id (service principal). Also the JWT `iss`/`sub`. + client_id: String, + /// Key id written into the JWT header so the server can select the + /// registered public key. + jwt_kid: String, + /// Discovered token endpoint. Also the JWT `aud`. + token_endpoint: String, + /// Loaded + cached signing key (parsed once at construction). + signing_key: Arc, + /// Thread-safe token store managing the token lifecycle. + token_store: TokenStore, + /// HTTP client for token endpoint requests. + http_client: Arc, + /// OAuth scopes to request. + scopes: Vec, + /// Tokio runtime handle captured at construction so the sync + /// `get_auth_header` can drive the async token exchange safely. + /// See [`super::m2m`] and [`crate::util::runtime::block_on_in_runtime`]. + runtime_handle: RuntimeHandle, +} + +// `JwtSigningKey` holds opaque signing material and does not implement +// `Debug`; redact it (and never expose client_id-adjacent secrets) in the +// provider's own `Debug`. +impl std::fmt::Debug for JwtClientCredentialsProvider { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("JwtClientCredentialsProvider") + .field("client_id", &self.client_id) + .field("jwt_kid", &self.jwt_kid) + .field("token_endpoint", &self.token_endpoint) + .field("signing_key", &"") + .field("scopes", &self.scopes) + .finish() + } +} + +impl JwtClientCredentialsProvider { + /// Create a new JWT private-key M2M provider. + /// + /// Loads the signing key and discovers the token endpoint (unless + /// overridden) before returning. The first `get_auth_header()` call + /// triggers the initial token exchange. + /// + /// # Arguments + /// + /// * `host` — Databricks workspace URL (for OIDC discovery). + /// * `client_id` — OAuth client id for the service principal. + /// * `jwt_key_file` — path to the PEM-encoded private key. + /// * `jwt_kid` — key id for the JWT header. + /// * `jwt_passphrase` — passphrase for an encrypted PKCS#8 key, else `None`. + /// * `jwt_algorithm` — JWT algorithm name (`None` → `RS256`). + /// * `http_client` — shared HTTP client. + /// * `scopes` — OAuth scopes to request. + /// * `token_endpoint_override` — token endpoint URL, or `None` to discover via OIDC. + #[allow(clippy::too_many_arguments)] + pub async fn new( + host: &str, + client_id: &str, + jwt_key_file: &str, + jwt_kid: &str, + jwt_passphrase: Option<&str>, + jwt_algorithm: Option<&str>, + http_client: Arc, + scopes: Vec, + token_endpoint_override: Option, + ) -> Result { + // Load + validate the key up front so a bad key/algorithm/passphrase + // fails at session open, not deep inside the first HTTP retry loop. + let signing_key = Arc::new(JwtSigningKey::load( + jwt_key_file, + jwt_passphrase, + jwt_algorithm, + )?); + + let token_endpoint = match token_endpoint_override { + Some(endpoint) => endpoint, + None => { + OidcEndpoints::discover(host, &http_client) + .await? + .token_endpoint + } + }; + + Ok(Self { + client_id: client_id.to_string(), + jwt_kid: jwt_kid.to_string(), + token_endpoint, + signing_key, + token_store: TokenStore::new(), + http_client, + scopes, + runtime_handle: RuntimeHandle::current(), + }) + } +} + +/// Build and sign a fresh client-assertion JWT. +/// +/// Free function (not a method) so it can be called from inside the +/// `'static` refresh closure in [`JwtClientCredentialsProvider::get_auth_header`] +/// — the closure captures owned clones (`Arc` + the claim +/// inputs) rather than borrowing `self`. That keeps signing off the +/// fresh-token fast path: a JWT is only signed when a token fetch/refresh +/// actually runs, not on every request. A fresh assertion per refresh is +/// correct — each carries its own `jti` and `exp`. +fn build_client_assertion( + signing_key: &JwtSigningKey, + client_id: &str, + jwt_kid: &str, + token_endpoint: &str, +) -> Result { + let now = chrono::Utc::now().timestamp(); + let claims = AssertionClaims { + iss: client_id.to_string(), + sub: client_id.to_string(), + aud: token_endpoint.to_string(), + jti: new_jti(), + iat: now, + exp: now + ASSERTION_LIFETIME_SECONDS, + }; + signing_key.sign(jwt_kid, &claims) +} + +impl AuthProvider for JwtClientCredentialsProvider { + /// Returns a valid `Bearer` token, refreshing via a signed + /// client-assertion exchange when the cached token is empty/expired. + /// + /// Lifecycle semantics match [`super::m2m::ClientCredentialsProvider`] + /// (fresh → cached, stale → background refresh, expired → blocking + /// refresh), coordinated by [`TokenStore`] and safe across threads. + fn get_auth_header(&self) -> Result { + let http_client = self.http_client.clone(); + let token_endpoint = self.token_endpoint.clone(); + let scopes = self.scopes.clone(); + let runtime_handle = self.runtime_handle.clone(); + // Capture cheap owned clones for the `'static` refresh closure so + // the assertion can be *signed inside it* — signing (RSA/EC crypto) + // then only happens on the empty/expired/stale-refresh paths, not on + // every request's fresh-token fast path. `signing_key` is an `Arc`, + // the rest are `String`s. + let signing_key = self.signing_key.clone(); + let client_id = self.client_id.clone(); + let jwt_kid = self.jwt_kid.clone(); + + let token = self.token_store.get_or_refresh(move || { + // Sign a fresh assertion only now that a refresh is actually + // running (fresh-token calls return before reaching here). + let client_assertion = + build_client_assertion(&signing_key, &client_id, &jwt_kid, &token_endpoint)?; + block_on_in_runtime(&runtime_handle, async { + let mut form: Vec<(&str, String)> = vec![ + ("grant_type", "client_credentials".to_string()), + ( + "client_assertion_type", + JWT_BEARER_ASSERTION_TYPE.to_string(), + ), + ("client_assertion", client_assertion), + ]; + if !scopes.is_empty() { + form.push(("scope", scopes.join(" "))); + } + + let request = http_client + .inner() + .post(&token_endpoint) + .form(&form) + .build() + .map_err(|e| { + Error::invalid_argument() + .message(format!("failed to build token request: {e}")) + })?; + + // `execute_without_auth` returns `Ok` only for a 2xx + // response; any non-success status (e.g. a 401 with an + // `{"error":"invalid_client",…}` body from the token + // endpoint) is already turned into an `Err` — with the + // status and parsed server body embedded by `http_error` — + // and surfaced here via `?`. So there is no non-success + // branch to handle: a returned `response` is a success. + let response = http_client + .execute_without_auth(request, RequestType::AuthTokenRequest) + .await?; + + let parsed: TokenResponse = response.json().await.map_err(|e| { + Error::io().message(format!("Failed to retrieve custom M2M token: {e}")) + })?; + + let expires_in = parsed + .expires_in() + .map(|d| d.as_secs() as i64) + .unwrap_or(DEFAULT_TOKEN_TTL_SECONDS); + // `.scopes()` yields `None` when the endpoint omits `scope` + // (and never a spurious empty-string scope), so fall back to + // the requested scopes in that case. + let granted_scopes = parsed + .scopes() + .map(|s| s.iter().map(|scope| scope.to_string()).collect()) + .unwrap_or_else(|| scopes.clone()); + + Ok(OAuthToken::new( + parsed.access_token().secret().to_string(), + parsed.token_type().as_ref().to_string(), + expires_in, + None, // No refresh token for M2M. + granted_scopes, + )) + }) + })?; + + Ok(format!("Bearer {}", token.access_token)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::client::http::HttpClientConfig; + use wiremock::matchers::{body_string_contains, method, path}; + use wiremock::{Mock, MockServer, ResponseTemplate}; + + use crate::auth::oauth::test_keys; + + fn http_client() -> Arc { + Arc::new( + DatabricksHttpClient::with_default_retry(HttpClientConfig::default()) + .expect("http client"), + ) + } + + /// Generate a fresh unencrypted RSA test key, write it to a temp file, + /// and return its path plus the tempdir guard (dropped by the caller + /// to clean up). Keys are generated in-process — see + /// [`crate::auth::oauth::test_keys`]. + fn write_test_key() -> (tempfile::TempDir, String) { + let dir = tempfile::tempdir().expect("tempdir"); + let path = dir.path().join("key.pem"); + std::fs::write(&path, test_keys::rsa_pkcs8_pem()).expect("write key"); + let path_str = path.to_str().unwrap().to_string(); + (dir, path_str) + } + + async fn mock_oidc(server: &MockServer) { + Mock::given(method("GET")) + .and(path("/oidc/.well-known/oauth-authorization-server")) + .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "authorization_endpoint": format!("{}/oidc/v1/authorize", server.uri()), + "token_endpoint": format!("{}/oidc/v1/token", server.uri()), + }))) + .mount(server) + .await; + } + + #[tokio::test(flavor = "multi_thread")] + async fn jwt_m2m_token_exchange_sends_assertion() { + let server = MockServer::start().await; + mock_oidc(&server).await; + + // The token endpoint must receive a jwt-bearer client_assertion, + // not a client secret. + Mock::given(method("POST")) + .and(path("/oidc/v1/token")) + .and(body_string_contains("client_assertion")) + .and(body_string_contains( + "urn%3Aietf%3Aparams%3Aoauth%3Aclient-assertion-type%3Ajwt-bearer", + )) + .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "access_token": "jwt-m2m-access-token", + "token_type": "Bearer", + "expires_in": 3600, + "scope": "all-apis" + }))) + .expect(1) + .mount(&server) + .await; + + let (_dir, key_path) = write_test_key(); + let provider = JwtClientCredentialsProvider::new( + &server.uri(), + "test-client-id", + &key_path, + "test-kid", + None, + Some("RS256"), + http_client(), + vec!["all-apis".to_string()], + None, + ) + .await + .expect("provider"); + + let header = provider.get_auth_header().expect("auth header"); + assert_eq!(header, "Bearer jwt-m2m-access-token"); + } + + #[tokio::test(flavor = "multi_thread")] + async fn jwt_m2m_assertion_carries_rfc7523_claims() { + // The signed assertion's sub/iss must be the client id and aud the + // token endpoint. We assert this end-to-end by capturing the form the + // token endpoint receives and decoding the client_assertion. + use std::sync::{Arc as StdArc, Mutex}; + + let server = MockServer::start().await; + mock_oidc(&server).await; + let token_url = format!("{}/oidc/v1/token", server.uri()); + + let captured: StdArc>> = StdArc::new(Mutex::new(None)); + let captured_for_mock = captured.clone(); + Mock::given(method("POST")) + .and(path("/oidc/v1/token")) + .respond_with(move |req: &wiremock::Request| { + let body = String::from_utf8_lossy(&req.body).to_string(); + *captured_for_mock.lock().unwrap() = Some(body); + ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "access_token": "t", "token_type": "Bearer", "expires_in": 3600 + })) + }) + .mount(&server) + .await; + + let (_dir, key_path) = write_test_key(); + let provider = JwtClientCredentialsProvider::new( + &server.uri(), + "test-client-id", + &key_path, + "test-kid", + None, + Some("RS256"), + http_client(), + vec!["all-apis".to_string()], + None, + ) + .await + .expect("provider"); + provider.get_auth_header().expect("auth header"); + + // Extract client_assertion from the urlencoded form body. A JWT is + // base64url (no '%' escapes) so the raw form value is the assertion + // as-is; only '=' padding would be percent-encoded, and compact JWS + // uses no padding. Parse the `k=v&…` pairs directly to avoid adding + // a url-decoding dependency to the test. + let body = captured.lock().unwrap().clone().expect("body captured"); + let assertion = body + .split('&') + .find_map(|pair| pair.strip_prefix("client_assertion=")) + .expect("client_assertion present") + .to_string(); + + // Verify the assertion's signature against the public key matching + // the signing key (not just decode the claims): a valid signature is + // what the authorization server actually checks. `jsonwebtoken::decode` + // fails if the RS256 signature does not verify. + use jsonwebtoken::{decode, decode_header, Algorithm, DecodingKey, Validation}; + let header = decode_header(&assertion).expect("decode JWS header"); + assert_eq!(header.alg, Algorithm::RS256); + assert_eq!(header.kid.as_deref(), Some("test-kid")); + + let decoding_key = + DecodingKey::from_rsa_pem(test_keys::rsa_public_spki_pem().as_bytes()).unwrap(); + let mut validation = Validation::new(Algorithm::RS256); + validation.set_audience(&[&token_url]); + let decoded = decode::(&assertion, &decoding_key, &validation) + .expect("assertion signature must verify against the public key"); + + let claims = decoded.claims; + assert_eq!(claims["sub"], "test-client-id"); + assert_eq!(claims["iss"], "test-client-id"); + assert_eq!(claims["aud"], token_url); + assert!(claims["jti"].is_string()); + // exp must be strictly after iat (positive validity window). + assert!(claims["exp"].as_i64().unwrap() > claims["iat"].as_i64().unwrap()); + } + + #[tokio::test(flavor = "multi_thread")] + async fn jwt_m2m_caches_token_across_calls() { + // A second call returns the cached token without a second exchange. + // The mock asserts exactly one POST. + let server = MockServer::start().await; + mock_oidc(&server).await; + Mock::given(method("POST")) + .and(path("/oidc/v1/token")) + .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "access_token": "cached-token", "token_type": "Bearer", "expires_in": 3600 + }))) + .expect(1) + .mount(&server) + .await; + + let (_dir, key_path) = write_test_key(); + let provider = JwtClientCredentialsProvider::new( + &server.uri(), + "test-client-id", + &key_path, + "test-kid", + None, + None, + http_client(), + vec!["all-apis".to_string()], + None, + ) + .await + .expect("provider"); + + let h1 = provider.get_auth_header().expect("first"); + let h2 = provider.get_auth_header().expect("second"); + assert_eq!(h1, "Bearer cached-token"); + assert_eq!(h2, h1); + // .expect(1) on the mock verifies only one exchange happened. + } + + #[tokio::test(flavor = "multi_thread")] + async fn jwt_m2m_token_url_override_skips_discovery() { + // With an explicit token endpoint, no OIDC discovery mock is + // mounted; the provider must still work. + let server = MockServer::start().await; + let token_url = format!("{}/custom/token", server.uri()); + Mock::given(method("POST")) + .and(path("/custom/token")) + .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "access_token": "override-token", "token_type": "Bearer", "expires_in": 3600 + }))) + .mount(&server) + .await; + + let (_dir, key_path) = write_test_key(); + let provider = JwtClientCredentialsProvider::new( + &server.uri(), + "test-client-id", + &key_path, + "test-kid", + None, + None, + http_client(), + vec!["all-apis".to_string()], + Some(token_url), + ) + .await + .expect("provider"); + + assert_eq!( + provider.get_auth_header().expect("header"), + "Bearer override-token" + ); + } + + #[tokio::test(flavor = "multi_thread")] + async fn jwt_m2m_bad_algorithm_fails_at_construction() { + let server = MockServer::start().await; + mock_oidc(&server).await; + + let (_dir, key_path) = write_test_key(); + let result = JwtClientCredentialsProvider::new( + &server.uri(), + "test-client-id", + &key_path, + "test-kid", + None, + Some("ES512"), + http_client(), + vec!["all-apis".to_string()], + None, + ) + .await; + + let err = result.expect_err("ES512 should be rejected"); + assert!(format!("{err:?}").contains("ES512")); + } + + #[tokio::test(flavor = "multi_thread")] + async fn jwt_m2m_missing_key_file_fails() { + let server = MockServer::start().await; + mock_oidc(&server).await; + + let result = JwtClientCredentialsProvider::new( + &server.uri(), + "test-client-id", + "/nonexistent/key.pem", + "test-kid", + None, + None, + http_client(), + vec!["all-apis".to_string()], + None, + ) + .await; + + assert!(result.is_err(), "missing key file should fail"); + } + + #[tokio::test(flavor = "multi_thread")] + async fn jwt_m2m_server_rejection_surfaces_error() { + let server = MockServer::start().await; + mock_oidc(&server).await; + + Mock::given(method("POST")) + .and(path("/oidc/v1/token")) + .respond_with(ResponseTemplate::new(401).set_body_json(serde_json::json!({ + "error": "invalid_client" + }))) + .mount(&server) + .await; + + let (_dir, key_path) = write_test_key(); + let provider = JwtClientCredentialsProvider::new( + &server.uri(), + "test-client-id", + &key_path, + "test-kid", + None, + None, + http_client(), + vec!["all-apis".to_string()], + None, + ) + .await + .expect("provider"); + + let err = provider.get_auth_header().expect_err("should fail on 401"); + let msg = format!("{err:?}"); + // The 401 is turned into an error by `execute_without_auth`'s + // `http_error`, which folds the server body into the message. Assert + // BOTH the status and the server-supplied `invalid_client` reason + // surface — this exercises the real error path (not a manual branch + // in the provider) and proves the token-endpoint's body reaches the + // caller. + assert!(msg.contains("401"), "expected HTTP status in error: {msg}"); + assert!( + msg.contains("invalid_client"), + "expected server error body in error: {msg}" + ); + } +} diff --git a/src/auth/oauth/mod.rs b/src/auth/oauth/mod.rs index 24021d84..23acbf06 100644 --- a/src/auth/oauth/mod.rs +++ b/src/auth/oauth/mod.rs @@ -26,8 +26,12 @@ pub(crate) mod cache_crypto; pub mod callback; pub mod federation; pub(crate) mod jwt; +pub(crate) mod jwt_key; +pub mod jwt_m2m; pub mod m2m; pub mod oidc; +#[cfg(test)] +pub(crate) mod test_keys; pub mod token; pub(crate) mod token_store; pub mod u2m; @@ -36,6 +40,7 @@ pub mod u2m; pub use cache::TokenCache; pub use callback::CallbackServer; pub use federation::FederationProvider; +pub use jwt_m2m::JwtClientCredentialsProvider; pub use m2m::ClientCredentialsProvider; pub use oidc::OidcEndpoints; pub use token::OAuthToken; diff --git a/src/auth/oauth/test_keys.rs b/src/auth/oauth/test_keys.rs new file mode 100644 index 00000000..419bcdd0 --- /dev/null +++ b/src/auth/oauth/test_keys.rs @@ -0,0 +1,91 @@ +// 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. + +//! Test-only private-key generation for the JWT auth tests. +//! +//! Keys are generated **in-process** (via the RustCrypto `rsa` / `p256` +//! dev-dependencies) rather than committed as PEM fixtures. Two reasons: +//! +//! 1. The repo's secret scanner blocks committed `BEGIN PRIVATE KEY` +//! material, even test keys. +//! 2. Generating at test time keeps the suite self-contained and needs no +//! `openssl` CLI, which the repo deliberately avoids (not present on +//! Windows — see the note in `client/http.rs`). +//! +//! The RSA key is generated once per test binary and shared via a +//! `OnceLock`, because RSA-2048 key generation is the slow part; the +//! encrypted and EC variants are cheap to derive on demand. + +#![cfg(test)] + +use std::sync::OnceLock; + +use pkcs8::{EncodePrivateKey, EncodePublicKey, LineEnding}; +// Use the `rand_core` re-exported by `rsa` (v0.6) so keygen matches the +// RNG trait version the RustCrypto keygen APIs expect — and so we don't +// pull in a second top-level `rand` that would clash with the kernel's +// runtime `rand` (v0.10) in test builds. +use rsa::rand_core::OsRng; +use rsa::RsaPrivateKey; + +/// Passphrase used for the encrypted-key fixture. +pub(crate) const TEST_KEY_PASSPHRASE: &str = "test-passphrase"; + +/// Cached RSA-2048 key (generation is the expensive step; do it once). +fn shared_rsa_key() -> &'static RsaPrivateKey { + static KEY: OnceLock = OnceLock::new(); + KEY.get_or_init(|| RsaPrivateKey::new(&mut OsRng, 2048).expect("generate test RSA key")) +} + +/// An unencrypted RSA private key as PKCS#8 PEM (`BEGIN PRIVATE KEY`). +pub(crate) fn rsa_pkcs8_pem() -> String { + shared_rsa_key() + .to_pkcs8_pem(LineEnding::LF) + .expect("encode RSA PKCS#8 PEM") + .to_string() +} + +/// The RSA public key matching [`rsa_pkcs8_pem`], as SPKI PEM +/// (`BEGIN PUBLIC KEY`), for verifying a signature produced by the +/// private key. +pub(crate) fn rsa_public_spki_pem() -> String { + use rsa::RsaPublicKey; + RsaPublicKey::from(shared_rsa_key()) + .to_public_key_pem(LineEnding::LF) + .expect("encode RSA public SPKI PEM") +} + +/// The shared RSA key encrypted as a passphrase-protected PKCS#8 +/// (`BEGIN ENCRYPTED PRIVATE KEY`) under [`TEST_KEY_PASSPHRASE`]. +/// +/// Uses the `pkcs8` crate's default PBES2 scheme (scrypt + AES-256-CBC). +/// Scrypt is one of the two KDFs the production decrypt path supports, so +/// this exercises the real encrypt→decrypt round-trip. (Note: OpenSSL's +/// `-v2 aes-256-cbc` default is *PBKDF2* rather than scrypt; the pkcs8 +/// crate decrypts both, and the PBKDF2 constructor is not exposed for +/// encryption here, so the fixture uses the crate default.) +pub(crate) fn rsa_encrypted_pkcs8_pem() -> String { + shared_rsa_key() + .to_pkcs8_encrypted_pem(&mut OsRng, TEST_KEY_PASSPHRASE, LineEnding::LF) + .expect("encrypt RSA PKCS#8") + .to_string() +} + +/// A fresh P-256 EC private key as PKCS#8 PEM (for `ES256`). +pub(crate) fn ec_p256_pkcs8_pem() -> String { + let key = p256::SecretKey::random(&mut OsRng); + key.to_pkcs8_pem(LineEnding::LF) + .expect("encode EC PKCS#8 PEM") + .to_string() +} diff --git a/src/c_abi/session.rs b/src/c_abi/session.rs index 28fd4e8a..10a64a68 100644 --- a/src/c_abi/session.rs +++ b/src/c_abi/session.rs @@ -49,14 +49,15 @@ enum ConnectionSpec { HttpPath { host: String, http_path: String }, } -/// Auth choice captured from the C-side setters. v0 C ABI wires PAT and -/// OAuth M2M; other [`AuthConfig`] variants stay Rust-crate-only. +/// Auth choice captured from the C-side setters. The C ABI wires PAT, +/// OAuth M2M (shared-secret and JWT private-key), and OAuth U2M; other +/// [`AuthConfig`] variants stay Rust-crate-only. /// -/// NOTE (secret handling): `token` / `client_secret` are copied out of -/// the C string into owned `String`s and are not zeroized on drop, so -/// plaintext lingers in freed heap. This matches the rest of the crate -/// (no `zeroize`/`secrecy` anywhere); when the crate adopts a -/// zeroize-on-drop policy, these copies must be included. +/// NOTE (secret handling): `token` / `client_secret` / `jwt_passphrase` +/// are copied out of the C string into owned `String`s and are not +/// zeroized on drop, so plaintext lingers in freed heap. This matches the +/// rest of the crate (no `zeroize`/`secrecy` anywhere); when the crate +/// adopts a zeroize-on-drop policy, these copies must be included. enum AuthSpec { Pat { token: String, @@ -65,6 +66,20 @@ enum AuthSpec { client_id: String, client_secret: String, }, + /// OAuth M2M via a JWT private-key client assertion. `client_id`, + /// `jwt_key_file`, and `jwt_kid` are required; `jwt_passphrase` (for an + /// encrypted PKCS#8 key), `jwt_algorithm` (`None` ⇒ `RS256`), `scopes` + /// (comma-separated; `None` ⇒ kernel default `all-apis`), and + /// `token_url` (`None` ⇒ OIDC discovery) are optional. + OAuthM2MJwt { + client_id: String, + jwt_key_file: String, + jwt_kid: String, + jwt_passphrase: Option, + jwt_algorithm: Option, + scopes: Option, + token_url: Option, + }, /// OAuth user-to-machine (authorization code + PKCE, browser flow). /// All fields optional — the kernel fills `databricks-sql-connector` / /// port 8030 / `sql offline_access` when omitted. @@ -316,6 +331,49 @@ pub unsafe extern "C" fn kernel_session_config_set_auth_m2m( }) } +/// Set OAuth M2M authentication via a JWT private-key client assertion +/// (RFC 7523). Instead of a client secret, the kernel signs a short-lived +/// JWT with the configured private key and sends it as the +/// `client_assertion` in the client-credentials grant. Mutually exclusive +/// with the other `set_auth_*` setters — the last one called wins. +/// +/// `client_id`, `jwt_key_file` (path to a PEM/PKCS#8 private key), and +/// `jwt_kid` (key id written into the JWT header) are required. The rest +/// are optional (pass NULL to omit): `jwt_passphrase` (for an encrypted +/// PKCS#8 key), `jwt_algorithm` (`RS256`/`384`/`512`, `PS256`/`384`/`512`, +/// `ES256`, `ES384`; NULL → `RS256`), `scopes` (a comma-separated list; +/// NULL → the kernel default `all-apis`), and `token_url` (an explicit +/// token endpoint; NULL → discover via OIDC). +/// +/// # Safety +/// `config` must be a live config handle; the required args must be +/// NUL-terminated C strings, and the optional args, if non-null, must be +/// NUL-terminated C strings. +#[no_mangle] +pub unsafe extern "C" fn kernel_session_config_set_auth_m2m_jwt( + config: *mut KernelSessionConfig, + client_id: *const c_char, + jwt_key_file: *const c_char, + jwt_kid: *const c_char, + jwt_passphrase: *const c_char, + jwt_algorithm: *const c_char, + scopes: *const c_char, + token_url: *const c_char, +) -> KernelStatusCode { + set_on_config(config, |c| { + c.auth = Some(AuthSpec::OAuthM2MJwt { + client_id: required_str(client_id, "client_id")?, + jwt_key_file: required_str(jwt_key_file, "jwt_key_file")?, + jwt_kid: required_str(jwt_kid, "jwt_kid")?, + jwt_passphrase: optional_str(jwt_passphrase, "jwt_passphrase")?, + jwt_algorithm: optional_str(jwt_algorithm, "jwt_algorithm")?, + scopes: optional_str(scopes, "scopes")?, + token_url: optional_str(token_url, "token_url")?, + }); + Ok(()) + }) +} + /// Set OAuth U2M (user-to-machine: authorization code + PKCE, browser /// flow) authentication. Mutually exclusive with the other `set_auth_*` /// setters — the last one called wins. @@ -932,7 +990,8 @@ fn build_session(config: KernelSessionConfig) -> Result Result AuthConfig::oauth_m2m_private_key( + Some(client_id), + Some(jwt_key_file), + Some(jwt_kid), + jwt_passphrase, + jwt_algorithm, + scopes.and_then(|s| parse_scopes(&s)), + token_url, + )?, AuthSpec::OAuthU2M { client_id, redirect_port, @@ -1284,6 +1360,62 @@ mod tests { } } + /// The JWT private-key M2M setter captures the required and optional + /// fields verbatim; NULL optionals record as `None`. Guards the C-side + /// wiring into `AuthSpec::OAuthM2MJwt` (which then maps to + /// `AuthConfig::oauth_m2m_private_key` at open). + #[test] + fn set_auth_m2m_jwt_records_fields() { + unsafe { + let mut config: *mut KernelSessionConfig = std::ptr::null_mut(); + assert_eq!( + kernel_session_config_new(&mut config), + KernelStatusCode::Success + ); + let client_id = CString::new("sp-client-id").unwrap(); + let key_file = CString::new("/keys/jwt.pem").unwrap(); + let kid = CString::new("kid-1").unwrap(); + let passphrase = CString::new("secret").unwrap(); + let algorithm = CString::new("ES256").unwrap(); + let scopes = CString::new("all-apis,sql").unwrap(); + assert_eq!( + kernel_session_config_set_auth_m2m_jwt( + config, + client_id.as_ptr(), + key_file.as_ptr(), + kid.as_ptr(), + passphrase.as_ptr(), + algorithm.as_ptr(), + scopes.as_ptr(), + std::ptr::null(), // token_url omitted → OIDC discovery + ), + KernelStatusCode::Success + ); + + match config.as_ref().unwrap().auth.as_ref().unwrap() { + AuthSpec::OAuthM2MJwt { + client_id, + jwt_key_file, + jwt_kid, + jwt_passphrase, + jwt_algorithm, + scopes, + token_url, + } => { + assert_eq!(client_id, "sp-client-id"); + assert_eq!(jwt_key_file, "/keys/jwt.pem"); + assert_eq!(jwt_kid, "kid-1"); + assert_eq!(jwt_passphrase.as_deref(), Some("secret")); + assert_eq!(jwt_algorithm.as_deref(), Some("ES256")); + assert_eq!(scopes.as_deref(), Some("all-apis,sql")); + assert_eq!(*token_url, None); + } + _ => panic!("expected AuthSpec::OAuthM2MJwt"), + } + kernel_session_config_free(config); + } + } + /// The retry setter records the backoff/attempt knobs as a `RetrySpec` (in /// milliseconds → `Duration`); an untouched config leaves `None` so the /// kernel's default policy applies. `max_retries = 0` is valid (disables diff --git a/src/config.rs b/src/config.rs index 8ac22266..f636ae23 100644 --- a/src/config.rs +++ b/src/config.rs @@ -360,6 +360,34 @@ pub enum AuthConfig { identity_federation_client_id: Option, }, + /// OAuth 2.0 machine-to-machine using a JWT private-key client + /// assertion (RFC 7523) instead of a client secret. The kernel signs + /// a short-lived JWT with the configured private key and sends it as + /// the `client_assertion` in the client-credentials grant; the + /// authorization server verifies it against the service principal's + /// registered public key. + /// + /// Supported `jwt_algorithm` values: `RS256`/`384`/`512`, + /// `PS256`/`384`/`512`, `ES256`, `ES384` (`None` → `RS256`). `ES512` + /// is not supported. + OAuthM2MPrivateKey { + client_id: String, + /// Path to the PEM-encoded private key file. + jwt_key_file: String, + /// Key id written into the JWT header (`kid`) so the server can + /// select the matching registered public key. + jwt_kid: String, + /// Passphrase for an encrypted PKCS#8 key. `None` for an + /// unencrypted key. + jwt_passphrase: Option, + /// JWT signing algorithm name. `None` → `RS256`. + jwt_algorithm: Option, + /// OAuth scopes to request. `None` → `["all-apis"]`. + scopes: Option>, + /// Token endpoint override. `None` → discover via OIDC. + token_url_override: Option, + }, + /// OAuth 2.0 token exchange (RFC 8693), for federated identity /// (e.g. exchanging a Workload Identity token for a Databricks /// access token). @@ -480,9 +508,52 @@ impl AuthConfig { identity_federation_client_id, .. } => identity_federation_client_id.as_deref(), - Self::OAuthFederation { .. } | Self::External(_) => None, + // JWT private-key M2M does not thread an SP-wide federation + // client id yet (the flow already proves identity via the + // signed assertion); wire it here if/when that's needed. + Self::OAuthM2MPrivateKey { .. } | Self::OAuthFederation { .. } | Self::External(_) => { + None + } } } + + /// Construct a [`AuthConfig::OAuthM2MPrivateKey`] from optional + /// fields, validating that the required `client_id`, `jwt_key_file`, + /// and `jwt_kid` are present and non-empty. `jwt_passphrase` / + /// `jwt_algorithm` / `scopes` / `token_url_override` are optional and + /// forwarded as-is (the kernel fills defaults and validates the key / + /// algorithm at session open). + pub fn oauth_m2m_private_key( + client_id: Option, + jwt_key_file: Option, + jwt_kid: Option, + jwt_passphrase: Option, + jwt_algorithm: Option, + scopes: Option>, + token_url_override: Option, + ) -> crate::Result { + let client_id = client_id.filter(|s| !s.is_empty()).ok_or_else(|| { + crate::kernel_error::Error::invalid_argument() + .message("OAuth M2M private-key auth requires a non-empty client_id") + })?; + let jwt_key_file = jwt_key_file.filter(|s| !s.is_empty()).ok_or_else(|| { + crate::kernel_error::Error::invalid_argument() + .message("OAuth M2M private-key auth requires a non-empty jwt_key_file") + })?; + let jwt_kid = jwt_kid.filter(|s| !s.is_empty()).ok_or_else(|| { + crate::kernel_error::Error::invalid_argument() + .message("OAuth M2M private-key auth requires a non-empty jwt_kid") + })?; + Ok(AuthConfig::OAuthM2MPrivateKey { + client_id, + jwt_key_file, + jwt_kid, + jwt_passphrase, + jwt_algorithm, + scopes, + token_url_override, + }) + } } /// Caller-supplied token provider trait. @@ -548,6 +619,22 @@ impl std::fmt::Debug for AuthConfig { identity_federation_client_id, ) .finish(), + Self::OAuthM2MPrivateKey { + client_id, + jwt_key_file, + jwt_kid, + jwt_algorithm, + scopes, + .. + } => f + .debug_struct("OAuthM2MPrivateKey") + .field("client_id", client_id) + .field("jwt_key_file", jwt_key_file) + .field("jwt_kid", jwt_kid) + .field("jwt_passphrase", &"") + .field("jwt_algorithm", jwt_algorithm) + .field("scopes", scopes) + .finish(), Self::OAuthFederation { subject_token_type, audience, @@ -1739,6 +1826,117 @@ mod tests { } } + // ─── OAuthM2MPrivateKey (JWT) constructor ────────────────────── + // Mirrors JDBC's builder null-checks (should_ThrowException_When_*). + + #[test] + fn oauth_m2m_private_key_rejects_missing_or_empty_client_id() { + let err = AuthConfig::oauth_m2m_private_key( + None, + Some("/k.pem".to_string()), + Some("kid".to_string()), + None, + None, + None, + None, + ) + .unwrap_err(); + assert!(format!("{err:?}").contains("client_id")); + + let err = AuthConfig::oauth_m2m_private_key( + Some(String::new()), + Some("/k.pem".to_string()), + Some("kid".to_string()), + None, + None, + None, + None, + ) + .unwrap_err(); + assert!(format!("{err:?}").contains("client_id")); + } + + #[test] + fn oauth_m2m_private_key_rejects_missing_key_file() { + let err = AuthConfig::oauth_m2m_private_key( + Some("cid".to_string()), + None, + Some("kid".to_string()), + None, + None, + None, + None, + ) + .unwrap_err(); + assert!(format!("{err:?}").contains("jwt_key_file")); + } + + #[test] + fn oauth_m2m_private_key_rejects_missing_kid() { + let err = AuthConfig::oauth_m2m_private_key( + Some("cid".to_string()), + Some("/k.pem".to_string()), + None, + None, + None, + None, + None, + ) + .unwrap_err(); + assert!(format!("{err:?}").contains("jwt_kid")); + } + + #[test] + fn oauth_m2m_private_key_accepts_all_fields() { + match AuthConfig::oauth_m2m_private_key( + Some("cid".to_string()), + Some("/k.pem".to_string()), + Some("kid".to_string()), + Some("pass".to_string()), + Some("ES256".to_string()), + Some(vec!["all-apis".to_string()]), + Some("https://h/token".to_string()), + ) + .unwrap() + { + AuthConfig::OAuthM2MPrivateKey { + client_id, + jwt_key_file, + jwt_kid, + jwt_passphrase, + jwt_algorithm, + scopes, + token_url_override, + } => { + assert_eq!(client_id, "cid"); + assert_eq!(jwt_key_file, "/k.pem"); + assert_eq!(jwt_kid, "kid"); + assert_eq!(jwt_passphrase.as_deref(), Some("pass")); + assert_eq!(jwt_algorithm.as_deref(), Some("ES256")); + assert_eq!(scopes, Some(vec!["all-apis".to_string()])); + assert_eq!(token_url_override.as_deref(), Some("https://h/token")); + } + other => panic!("expected OAuthM2MPrivateKey, got {other:?}"), + } + } + + #[test] + fn debug_oauth_m2m_private_key_redacts_passphrase() { + let cfg = AuthConfig::oauth_m2m_private_key( + Some("cid".to_string()), + Some("/k.pem".to_string()), + Some("kid".to_string()), + Some("super-secret-pass".to_string()), + Some("RS256".to_string()), + None, + None, + ) + .unwrap(); + let dbg = format!("{cfg:?}"); + assert!(dbg.contains(""), "{dbg}"); + assert!(!dbg.contains("super-secret-pass"), "{dbg}"); + } + #[test] fn oauth_u2m_carries_identity_federation_client_id() { let auth = AuthConfig::oauth_u2m( diff --git a/src/session.rs b/src/session.rs index 021b76cf..23b6b2b3 100644 --- a/src/session.rs +++ b/src/session.rs @@ -47,7 +47,7 @@ use crate::auth::{ AuthProvider, AuthorizationCodeProvider, ClientCredentialsProvider, FederationProvider, - PersonalAccessToken, + JwtClientCredentialsProvider, PersonalAccessToken, }; use crate::client::http::TlsConfig as HttpTlsConfig; use crate::client::retry::{ @@ -1269,6 +1269,38 @@ async fn build_base_auth_provider( .await?; Ok(Arc::new(provider)) } + AuthConfig::OAuthM2MPrivateKey { + client_id, + jwt_key_file, + jwt_kid, + jwt_passphrase, + jwt_algorithm, + scopes, + token_url_override, + } => { + if client_id.is_empty() || jwt_key_file.is_empty() || jwt_kid.is_empty() { + return Err(Error::invalid_argument().message( + "AuthConfig::OAuthM2MPrivateKey requires non-empty client_id, \ + jwt_key_file, and jwt_kid", + )); + } + let scopes = scopes + .clone() + .unwrap_or_else(|| vec!["all-apis".to_string()]); + let provider = JwtClientCredentialsProvider::new( + host, + client_id, + jwt_key_file, + jwt_kid, + jwt_passphrase.as_deref(), + jwt_algorithm.as_deref(), + http_client, + scopes, + token_url_override.clone(), + ) + .await?; + Ok(Arc::new(provider)) + } AuthConfig::OAuthFederation { .. } => Err(Error::invalid_argument() .message("AuthConfig::OAuthFederation is reserved for v0.1; not yet wired")), AuthConfig::External(_) => Err(Error::invalid_argument() diff --git a/src/telemetry/runtime.rs b/src/telemetry/runtime.rs index 78312742..f9f8bfc3 100644 --- a/src/telemetry/runtime.rs +++ b/src/telemetry/runtime.rs @@ -285,6 +285,7 @@ fn auth_type(auth: &AuthConfig) -> String { match auth { AuthConfig::Pat { .. } => "pat", AuthConfig::OAuthM2M { .. } => "oauth-m2m", + AuthConfig::OAuthM2MPrivateKey { .. } => "oauth-m2m-jwt", AuthConfig::OAuthU2M { .. } => "oauth-u2m", AuthConfig::OAuthFederation { .. } => "oauth-federation", AuthConfig::External(_) => "external", @@ -296,6 +297,7 @@ fn auth_mech(auth: &AuthConfig) -> DriverAuthMech { match auth { AuthConfig::Pat { .. } => DriverAuthMech::Pat, AuthConfig::OAuthM2M { .. } + | AuthConfig::OAuthM2MPrivateKey { .. } | AuthConfig::OAuthU2M { .. } | AuthConfig::OAuthFederation { .. } => DriverAuthMech::Oauth, AuthConfig::External(_) => DriverAuthMech::Other, @@ -305,7 +307,9 @@ fn auth_mech(auth: &AuthConfig) -> DriverAuthMech { fn auth_flow(auth: &AuthConfig) -> Option { match auth { AuthConfig::Pat { .. } => Some(DriverAuthFlow::TokenPassthrough), - AuthConfig::OAuthM2M { .. } => Some(DriverAuthFlow::ClientCredentials), + AuthConfig::OAuthM2M { .. } | AuthConfig::OAuthM2MPrivateKey { .. } => { + Some(DriverAuthFlow::ClientCredentials) + } AuthConfig::OAuthU2M { .. } => Some(DriverAuthFlow::BrowserBasedAuthentication), AuthConfig::OAuthFederation { .. } | AuthConfig::External(_) => None, } diff --git a/tests/v0_execute_e2e.rs b/tests/v0_execute_e2e.rs index 18285a90..4e07a674 100644 --- a/tests/v0_execute_e2e.rs +++ b/tests/v0_execute_e2e.rs @@ -48,6 +48,78 @@ async fn live_session() -> Session { .expect("Session::open against live workspace") } +/// Open a live session authenticated via the JWT private-key M2M flow +/// (`AuthConfig::OAuthM2MPrivateKey`). +/// +/// This grant (RFC 7523 `private_key_jwt`) authenticates against the token +/// endpoint of the workspace's configured OAuth identity provider — e.g. +/// Entra ID for an Azure Databricks workspace — which verifies the signed +/// client assertion against the public key/certificate registered on the +/// service principal *in that IdP*. Databricks' AWS-native OIDC endpoint +/// does not advertise `private_key_jwt`, so point `DATABRICKS_JWT_TOKEN_URL` +/// at the IdP token endpoint for those workspaces. +/// +/// Env vars (in addition to `DATABRICKS_HOST` / `DATABRICKS_HTTP_PATH`): +/// - `DATABRICKS_JWT_CLIENT_ID` — the service principal's client/application id +/// - `DATABRICKS_JWT_KEY_FILE` — path to the PEM private key +/// - `DATABRICKS_JWT_KID` — key id matching the registered public key +/// - `DATABRICKS_JWT_PASSPHRASE` — optional, for an encrypted PKCS#8 key +/// - `DATABRICKS_JWT_ALGORITHM` — optional, defaults to `RS256` +/// - `DATABRICKS_JWT_TOKEN_URL` — optional IdP token endpoint override; when +/// unset the kernel discovers the endpoint via the workspace's OIDC config +/// +/// Returns `None` (rather than panicking) when the JWT-specific vars are +/// absent, so the shared `v0 E2E surface` CI job — which only provides PAT / +/// client-secret credentials — skips this test instead of failing it. +async fn live_jwt_session() -> Option { + let host = env_var("DATABRICKS_HOST").expect("DATABRICKS_HOST required"); + let path = env_var("DATABRICKS_HTTP_PATH").expect("DATABRICKS_HTTP_PATH required"); + let (client_id, key_file, kid) = match ( + env_var("DATABRICKS_JWT_CLIENT_ID"), + env_var("DATABRICKS_JWT_KEY_FILE"), + env_var("DATABRICKS_JWT_KID"), + ) { + (Some(c), Some(f), Some(k)) => (c, f, k), + _ => { + eprintln!( + "skipping jwt_m2m_select_one_round_trip: set DATABRICKS_JWT_CLIENT_ID, \ + DATABRICKS_JWT_KEY_FILE, and DATABRICKS_JWT_KID to run it" + ); + return None; + } + }; + // Some IdPs (e.g. Entra ID) require a resource-specific scope such as + // `/.default` rather than the Databricks-native + // `all-apis`; allow overriding via `DATABRICKS_JWT_SCOPES` (space- or + // comma-separated). Unset → kernel default (`all-apis`). + let scopes = env_var("DATABRICKS_JWT_SCOPES").map(|s| { + s.split([' ', ',']) + .filter(|p| !p.is_empty()) + .map(str::to_string) + .collect::>() + }); + + let auth = AuthConfig::oauth_m2m_private_key( + Some(client_id), + Some(key_file), + Some(kid), + env_var("DATABRICKS_JWT_PASSPHRASE"), + env_var("DATABRICKS_JWT_ALGORITHM"), + scopes, // None → kernel default (all-apis) + env_var("DATABRICKS_JWT_TOKEN_URL"), // IdP token endpoint; None → OIDC discovery + ) + .expect("build OAuthM2MPrivateKey config"); + + Some( + Session::builder() + .http_path(host, path) + .auth(auth) + .open() + .await + .expect("Session::open with JWT private-key M2M against live workspace"), + ) +} + async fn drain_rows(stream: &mut ResultStream) -> usize { let mut total = 0; while let Some(rb) = stream.next_batch().await.expect("next_batch") { @@ -78,6 +150,34 @@ async fn select_one_round_trip() { session.close().await.expect("session close"); } +/// **JWT private-key M2M against a live workspace.** Authenticates as a +/// service principal via a signed client-assertion JWT +/// (`AuthConfig::OAuthM2MPrivateKey`), then runs `SELECT 1`. Proves the +/// full flow end-to-end: key load → OIDC discovery → assertion signing → +/// client-credentials token exchange → authenticated query. See +/// [`live_jwt_session`] for the required env vars. +/// +/// Uses the multi-threaded runtime: the JWT provider runs a blocking token +/// exchange inside `get_auth_header`, which requires it. +#[tokio::test(flavor = "multi_thread")] +#[ignore] +async fn jwt_m2m_select_one_round_trip() { + let Some(session) = live_jwt_session().await else { + return; // JWT credentials not configured — skip (see live_jwt_session). + }; + let mut stmt = session.statement(); + stmt.spec().sql("SELECT 1 AS n"); + let mut exec = stmt.execute().await.expect("execute SELECT 1 via JWT M2M"); + + let stream = exec.result_stream_mut(); + stream.next_batch().await.unwrap().unwrap(); + let row = stream.next_row_in_batch().expect("one row"); + assert_eq!(row.get_i64(0).unwrap(), Some(1)); + + exec.close().await.expect("close"); + session.close().await.expect("session close"); +} + #[tokio::test] #[ignore] async fn select_with_positional_params() {