Repository navigation
[PECOBLR-3792] Add JWT private-key M2M authentication - #249
Conversation
There was a problem hiding this comment.
Verdict: 1 Medium
Solid, well-tested port of the JDBC JWT private-key M2M flow — key loading, algorithm validation, RFC 7523 claims, and token lifecycle all look correct and are covered by unit/wiremock tests. One medium efficiency concern: the client-assertion JWT is signed on every get_auth_header call (i.e. every HTTP request) even on the fresh-token fast path, rather than only when a token refresh occurs.
| // and `exp`. | ||
| let client_assertion = self.build_client_assertion()?; | ||
|
|
||
| let token = self.token_store.get_or_refresh(move || { |
There was a problem hiding this comment.
🟡 Medium — build_client_assertion() is invoked unconditionally at the top of get_auth_header, before TokenStore::get_or_refresh. Since auth_header() runs on every outbound request (http.rs:818, inside execute_impl), and get_or_refresh returns early on the FRESH fast path without ever calling the refresh closure, the common case signs a fresh JWT (RSA/EC signing) on every single request and then throws it away — the assertion is only actually consumed when a token refresh happens.
The m2m provider avoids any per-request crypto: it only clones strings up front and builds the OAuth client inside the refresh closure. The stated rationale here ("signing needs &self and can't move into the 'static closure") doesn't fully hold: signing_key is Arc<JwtSigningKey> and client_id/jwt_kid/token_endpoint are all cheaply cloneable, so the assertion could be built inside the closure (which already captures owned clones) and would then only be signed when a refresh actually runs. As written, every query pays an RSA signature it discards.
Consider moving the sign into the refresh closure (capturing Arc<JwtSigningKey> + the claim inputs) so signing happens only on the empty/expired/stale-refresh paths.
There was a problem hiding this comment.
Verdict: 1 Medium · 1 Low
Solid, well-tested port of the JDBC JWT private-key M2M flow; the auth wiring, config validation, redaction, and algorithm handling all look correct. Two non-blocking issues: a Medium unreachable error-handling block in jwt_m2m.rs (the manual !status.is_success() branch can never run because execute_without_auth already errors via ? on any non-2xx, so the intended JDBC-parity message and server body are never surfaced), and a Low note that the decrypted private-key PEM is not zeroized despite the repo's stated posture.
| ), | ||
| ("client_assertion", client_assertion), | ||
| ]; | ||
| if !scopes.is_empty() { |
There was a problem hiding this comment.
🟡 Medium — This manual non-success branch is unreachable. execute_without_auth returns Ok(response) only when status.is_success() (http.rs:844 → return Ok(response) at 853); every non-2xx status falls through to the retryable-status check and then return Err(http_error(...)) at 914. Because the call one line above uses ?:
let response = http_client
.execute_without_auth(request, RequestType::AuthTokenRequest)
.await?;
let status = response.status();
if !status.is_success() { /* never runs */ }response is guaranteed to be a success response, so !status.is_success() is always false. The consequences:
- The
// Mirror JDBC's "Failed to retrieve custom M2M token: …"comment is misleading — that message and the JDBC-parity.context("client credentials grant (jwt-bearer assertion)")never surface. - The server response
body(e.g.{"error":"invalid_client","error_description":...}) that this block reads viaresponse.text()is never included in the error; users see only the generichttp_errorproduced insideexecute_without_auth.
The test jwt_m2m_server_rejection_surfaces_error passes only because it accepts msg.contains("401"), which http_error already provides — it does not actually exercise this block. If you want the detailed body/JDBC wording, surface it from the execute_without_auth error path (or capture the body there); otherwise drop the dead block and its comment.
| ))); | ||
| } | ||
|
|
||
| let encrypted = EncryptedPrivateKeyInfo::try_from(doc.as_bytes()).map_err(|e| { |
There was a problem hiding this comment.
🔵 Low — The decrypted private-key material is left in plaintext on the heap without zeroization. decrypt_pkcs8_pem re-encodes the decrypted key to an unencrypted PKCS#8 PEM String (decrypted.to_pem(...).map(|pem| pem.to_string())) and read_key_pem also holds the raw PEM String; both are dropped normally, leaving the private key sitting in freed heap memory. The repo already pulls in zeroize specifically to "Wipe derived key material on drop" (Cargo.toml:115), so this path is inconsistent with the established posture for sensitive key bytes. Consider wrapping the decrypted PEM in a zeroizing container (or explicitly zeroizing before drop) so the plaintext key does not linger. (Note: jsonwebtoken::EncodingKey itself does not zeroize, so this is partial hardening, but it removes the most obvious plaintext copy.)
There was a problem hiding this comment.
Verdict: 1 Low
Looks good — a clean, well-tested port of JWT private-key M2M auth. Verified the token-exchange relies correctly on execute_without_auth's 2xx-only success contract, the rand/PKCS#8 usage matches existing crate patterns, and rsa/p256 are genuinely dev-only (absent from the napi/pyo3 lockfiles). One low-severity accuracy nit in the osv-scanner suppression wording.
| # 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 |
There was a problem hiding this comment.
🔵 Low — The suppression justification asserts "verified: no jsonwebtoken::decode / Validation calls anywhere in src/" (and the reason field repeats "never decodes/validates JWTs (verified: no decode/Validation calls in src/)"). This is inaccurate: the #[cfg(test)] module in src/auth/oauth/jwt_m2m.rs does call jsonwebtoken::decode, decode_header, and construct a Validation in jwt_m2m_assertion_carries_rfc7523_claims.
The substantive security claim still holds — the vulnerable code path is unreachable in the shipped artifact, since test code is never linked into the crate, and the decode there operates on self-generated tokens. But the literal "anywhere in src/" wording is what a future re-reviewer will grep against when ignoreUntil lapses, and that grep will hit the test usage and cast doubt on the audit trail. Suggest narrowing the wording to "no decode/Validation calls in non-test (shipped) code" or "in the runtime signing path" to keep the re-review check accurate.
Do you just need an Azure workspace? |
There was a problem hiding this comment.
Verdict: 2 Low
Solid, well-tested addition — the JWT private-key M2M flow closely mirrors the existing shared-secret M2M provider, correctly reuses TokenStore/OIDC machinery, redacts secrets in Debug, zeroizes key material, and validates the key/algorithm at construction. The token-endpoint error path correctly relies on execute_without_auth (verified: returns Err with status+body on non-2xx). Two low-severity audit-accuracy notes only: the osv-scanner suppression's "no decode/Validation in src/" claim is contradicted by the new test module, and the deny.toml rsa-advisory ignore is unconditionally global.
| # 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 |
There was a problem hiding this comment.
🔵 Low — The suppression justification asserts "verified: no jsonwebtoken::decode / Validation calls anywhere in src/", but this same PR adds a test in src/auth/oauth/jwt_m2m.rs (jwt_m2m_assertion_carries_rfc7523_claims) that does use jsonwebtoken::{decode, decode_header, Algorithm, DecodingKey, Validation}; and calls decode::<serde_json::Value>(...) with a Validation. The security conclusion is still sound — those calls are #[cfg(test)]-only and never ship, so the runtime genuinely only signs — but the literal claim is now false. A future re-reviewer (prompted by the ignoreUntil lapse) who greps src/ for decode/Validation to reconfirm will hit these test matches and be misled. Suggest narrowing the wording to "no decode/Validation calls in non-test (shipped) code" so the audit trail stays accurate.
| # 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. |
There was a problem hiding this comment.
🔵 Low — The RUSTSEC-2023-0071 (rsa Marvin attack) ignore is global by advisory ID — cargo-deny's [advisories].ignore has no per-package/dev-only scoping. The justification correctly notes rsa is dev-only today, but if a future change ever pulls rsa into the runtime graph (e.g. adopting a jsonwebtoken 10.x rust_crypto backend, exactly the path the Cargo.toml note contemplates), this entry will silently keep suppressing the advisory in shipped code, defeating the CI gate. Consider pairing the ignore with a [bans] deny that forbids rsa outside dev-dependencies, or at minimum note in the comment that the ignore is unconditional and must be removed the moment rsa moves to a runtime dep.
6b17849 to
82661b6
Compare
There was a problem hiding this comment.
Verdict: 1 Low
Looks good — clean, well-tested port of JDBC's JWT private-key M2M flow. The new JwtClientCredentialsProvider correctly mirrors the existing m2m.rs lifecycle (verified TokenStore reuse, scope defaulting, and that execute_without_auth returns Ok only for 2xx so the token-exchange path needs no manual non-success branch). One low-severity note: the module documents SEC1/PKCS#1 PEM support but tests only exercise PKCS#8. Nit: the token-parse failure message in jwt_m2m.rs ("Failed to retrieve custom M2M token") reads like a copy leftover — the word "custom" doesn't correspond to anything user-facing.
| assert_eq!(header["alg"], "RS256"); | ||
| assert_eq!(header["kid"], "my-kid"); | ||
| } | ||
|
|
There was a problem hiding this comment.
🔵 Low — The module documents three unencrypted PEM formats as supported — PKCS#8 (BEGIN PRIVATE KEY), SEC1 EC (BEGIN EC PRIVATE KEY), and PKCS#1 RSA (BEGIN RSA PRIVATE KEY) — but test_keys only generates PKCS#8 (to_pkcs8_pem / SecretKey::to_pkcs8_pem). So build_encoding_key's from_ec_pem / from_rsa_pem paths are only ever exercised with PKCS#8 input. jsonwebtoken 9's from_ec_pem in particular is known to be picky about SEC1 vs PKCS#8 EC keys; if a user supplies an openssl-default BEGIN EC PRIVATE KEY (SEC1) the documented "handed directly" behavior is unverified and may fail. Consider adding a SEC1 EC and a PKCS#1 RSA fixture (both trivially derivable via to_sec1_pem / to_pkcs1_pem) to lock in the documented format coverage, or narrow the doc to the formats actually tested.
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 <rahul.singhal@databricks.com>
There was a problem hiding this comment.
Verdict: 1 Medium
Looks good — a faithful, well-tested port of JDBC's JwtPrivateKeyClientCredentials. The manual client_assertion form POST matches the JDBC form (client_id intentionally omitted), the provider correctly reuses the existing TokenStore/OIDC lifecycle, secrets are redacted in Debug, and coverage is thorough across kernel/pyo3/napi/C-ABI. One medium: the napi binding can't override the token endpoint, which per the PR's own e2e notes blocks the Azure/Entra private_key_jwt case. Nits (not filed inline): decrypt_pkcs8_pem's error strings interpolate {e} with no separator after "key" (e.g. "Cannot decrypt private JWT key {e}"); and the h2/RUSTSEC-2026-0258 suppression is a pre-existing-on-main advisory unrelated to this change, bundled here — well-justified but worth landing separately if possible.
| options.jwt_passphrase.clone(), | ||
| options.jwt_algorithm.clone(), | ||
| options.oauth_scopes.clone(), | ||
| None, |
There was a problem hiding this comment.
🟡 Medium — The napi OAuthM2mJwt arm hardcodes the token-endpoint override to None, and ConnectionOptions exposes no tokenUrl/jwtTokenUrl field, so Node consumers can only reach a token endpoint that OIDC discovery returns.
That's a functional gap specifically for this flow. Per this PR's own e2e docs (live_jwt_session, tests/v0_execute_e2e.rs:56-60), the Databricks AWS-native OIDC endpoint does not advertise private_key_jwt; Azure/Entra workspaces require pointing the token endpoint at the IdP directly (DATABRICKS_JWT_TOKEN_URL). The pyo3 binding (pyo3/src/auth.rs, forwards oauth.token_url) and the C ABI (kernel_session_config_set_auth_m2m_jwt's token_url) both expose this override; only napi omits it, leaving Node users unable to use JWT M2M against the very IdPs the feature targets.
It is consistent with napi's existing client-secret M2M (also no token_url), but client-secret M2M works via discovery whereas private_key_jwt frequently cannot — so the omission bites harder here. Consider adding a jwtTokenUrl (or general tokenUrl) option and threading it into this arm.
|
/merge |
What
Adds OAuth 2.0 machine-to-machine authentication using a JWT private-key client assertion (RFC 7523) instead of a client secret. Ported from the JDBC driver's
JwtPrivateKeyClientCredentials. Resolves PECOBLR-3792.The kernel signs a short-lived JWT with a PEM/PKCS#8 private key and sends it as the
client_assertionin the client-credentials grant; the authorization server verifies it against the service principal's registered public key.How
Kernel
AuthConfig::OAuthM2MPrivateKeyvariant +oauth_m2m_private_keyconstructor (config.rs)JwtClientCredentialsProvider(auth/oauth/jwt_m2m.rs) — OIDC discovery,TokenStorelifecycle, and a manualclient_assertionform POST. Reuses the existing M2M machinery; the only real delta vs.m2m.rsis sending a signed assertion instead of a secret (theoauth2crate'sexchange_client_credentials()can't send an assertion).auth/oauth/jwt_key.rs) — PEM/PKCS#8 parsing, RSA + EC, unencrypted and PBES2 passphrase-encrypted keys, viajsonwebtoken+pkcs8.Bindings
Session(auth_type="oauth-m2m-jwt", jwt_key_file=…, jwt_kid=…, jwt_passphrase=…, jwt_algorithm=…)AuthMode.OAuthM2mJwt+jwtKeyFile/jwtKid/jwtPassphrase/jwtAlgorithmoptionsDependencies
jsonwebtoken(backed byring, already in the graph via rustls — no new heavyweight dep) +pkcs8. Noopenssl.rsa+p256for in-process test-key generation.deny.toml.Feature parity with JDBC
This ports
JwtPrivateKeyClientCredentials+PrivateKeyClientCredentialProvider. The table below maps each JDBC capability to its kernel status.Behavior parity
client_credentialsgrant w/ JWT assertionclient_assertion_type=urn:ietf:params:oauth:client-assertion-type:jwt-beareriss/sub=client_id,aud=token endpoint,jti,iat,exp)jwt_m2m_assertion_carries_rfc7523_claimskidin JWT headerOidcEndpoints::discovertoken_url/token_url_overrideTokenStore(fresh/stale/expired state machine)all-apis)Intentional divergences (behavior deliberately differs)
Unsupported algorithm → loud error, not silent RS256 fallback. JDBC's
determineSignatureAlgorithmsilently returns RS256 for any unrecognised algorithm (includingES512and typos likeHS256). The kernel instead returns a clearInvalidArgumentat construction time listing the supported algorithms. Rationale: a silent fallback signs with the wrong algorithm and surfaces later as an opaque server-sideinvalid_clientrejection with no hint at the real cause — strictly worse for the user. This is the one place we consciously do not match JDBC's behavior.JWT
expuses a small positive window, notexp == iat. JDBC sets the assertion'sexpequal to itsiat(a zero-length validity window that only works because servers tolerate clock skew — effectively a latent bug). The kernel gives the single-use assertion a short positive lifetime instead.Gaps vs. JDBC (not supported)
ES512 (P-521 curve). Not supported.
ring(backingjsonwebtoken) has no P-521, and the only Rust path is theopensslcrate — which would reintroduce the system-OpenSSL / Node-module-load clash the kernel deliberately eliminated (see thereqwest/[features]TLS notes inCargo.toml). 8 of JDBC's 9 algorithms are covered; ES512 is rare in practice (RS256/ES256 dominate). Rejected loudly (see divergence 1) rather than silently mis-signed. A follow-up can evaluate a scoped P-521 path only if a customer needs it.Legacy encrypted-key schemes. Encrypted PKCS#8 support covers modern PBES2 (PBKDF2/scrypt + AES-CBC) — what current OpenSSL emits by default. Legacy schemes BouncyCastle also accepts (PBES1, 3DES-based encryption, PKCS#12-style) are not covered by the RustCrypto
pkcs8crate. Any key from roughly the last decade works; the fix for an older key is a one-line re-encrypt (openssl pkcs8 -topk8 -v2 aes-256-cbc) that the caller controls. Failure surfaces as a clear "Cannot decrypt private JWT key" error naming the unsupported scheme.authType()string. JDBC exposes"custom-oauth-m2m"viaCredentialsProvider.authType(). N/A in the kernel — auth is selected by theAuthConfigenum variant, not a string, so there is nothing to match. (This is why JDBC'sshould_ReturnCorrectAuthTypetest has no kernel counterpart.)Testing
Every JDBC test for this feature has a kernel equivalent except the N/A
should_ReturnCorrectAuthType:testDetermineSignatureAlgorithm→parse_algorithm_maps_supported_names/_defaults_to_rs256/_rejects_es512_loudly/_rejects_unknowntestRetrieveToken→jwt_m2m_token_exchange_sends_assertiontestRetrieveTokenExceptionHandling→jwt_m2m_server_rejection_surfaces_errortestFetchSignedJWTWithRSAKey→jwt_m2m_assertion_carries_rfc7523_claimsshould_FetchSignedJWT_WithECKey→loads_ec_p256_key_and_signs_es256should_GetToken_UsesCache→jwt_m2m_caches_token_across_callsshould_ThrowException_When_ClientId/JwtKeyFile/JwtKidIsNull→oauth_m2m_private_key_rejects_missing_*(+ pyo3/napi binding equivalents)should_HandleInvalidKeyFile→jwt_m2m_missing_key_file_failsjwt_m2m_token_url_override_skips_discovery+ discovery path in exchange testsPlus kernel-only coverage JDBC lacks:
loads_and_decrypts_pbes2_encrypted_key,wrong_passphrase_fails_with_clear_error,passphrase_on_unencrypted_key_is_rejected,ec_algorithm_with_rsa_key_fails.Test keys are generated in-process (
test_keys.rs) rather than committed as PEM fixtures — no secrets in the tree, noopensslCLI dependency. Green locally:cargo test(kernel): 791 lib tests + all integration/doc tests--features dyn-symbols)-D warningsclean across all three cratesError-message alignment: shared failure cases use JDBC's wording (
Failed to parse private key,Cannot decrypt private JWT key,Failed to retrieve custom M2M token,Error signing the JWT); the two intentional divergences keep their own clearer messages.End-to-end
Verified live against an Azure Databricks workspace. The kernel's
OAuthM2MPrivateKeyprovider signs a client-assertion JWT with the service principal's private key, Entra ID verifies it against the public certificate registered on the app registration and issues a token, and that token authenticates a SQL session —SELECT 1returns1. Covered by the#[ignore]djwt_m2m_select_one_round_triptest (v0_execute_e2e.rs), driven byDATABRICKS_JWT_*env vars.This flow (RFC 7523
private_key_jwt) authenticates against the token endpoint of the workspace's configured OAuth IdP (Entra ID for Azure Databricks), not Databricks' native OIDC endpoint — matching the JDBC/Simba design (spec). The kernel points at the IdP viatoken_url(OIDC discovery otherwise), with the resource scope (<databricks-resource-id>/.default) supplied viaDATABRICKS_JWT_SCOPES. Note: Entra identifies the signing cert by its SHA-1 thumbprint, sojwt_kidis thatx5tvalue — the kernel passes it straight through the JWT header. (Databricks' AWS-native OIDC endpoints don't advertiseprivate_key_jwt; this flow targets IdP-backed workspaces.)Non-live coverage exercises the full path — key load → assertion signing → client-assertion token exchange → token parse — including cryptographic signature verification of the assertion against the public key (
jwt_m2m_assertion_carries_rfc7523_claims) and a wiremock token-exchange round-trip.Notes for reviewers
napi/index.d.tswas hand-edited (+23 lines) rather than fully regenerated, to avoid ~2700 lines of unrelated churn from a newer napi CLI version. I verified the JWT surface matches a realnapi buildbyte-for-byte;index.jsis untouched (no new top-level#[napi]exports).This pull request and its description were written by Isaac.