Repository navigation
feat(auth): mandatory OIDC token exchange (BYOT federation) - #239
vuanhphung wants to merge 5 commits into
Conversation
b5ff963 to
815c445
Compare
There was a problem hiding this comment.
Verdict: 1 Medium · 1 Low
Solid, well-tested feature that matches the documented wire contract; the fallback (execute_without_auth returns Err on non-2xx) and the block_on_in_runtime bridge (mirrors the M2M provider) are correct, and sha2/hex/base64 are all pre-existing deps so no license gate applies. Two non-blocking items: an unbounded exchange cache (no eviction as source tokens rotate) and a missing source-rotation test that the design doc itself calls out. Nit: the failure-fallback entry is cached with a 60s TTL but OAuthToken::is_expired() applies a 40s buffer, so the retry-storm suppression window is effectively ~20s, not 60s — worth a comment if intentional.
| Ok(token) => { | ||
| let access_token = token.access_token.clone(); | ||
| if let Ok(mut cache) = self.cache.write() { | ||
| cache.insert(key, token); |
There was a problem hiding this comment.
🟡 Medium — The exchange cache is only ever inserted into (here on success, and at line 250 on the failure fallback) — there is no eviction of expired or superseded entries. Because the key is sha256(source_token) and the design explicitly re-exchanges a fresh key whenever the inner credential rotates (M2M/U2M refresh produces a new bearer), every rotation adds a new permanent map entry. In a long-lived process (server, connection pool) with periodic token refresh this is an unbounded memory growth: the old entries are expired and never read again, but they are never dropped.
Consider pruning expired entries on write (e.g. cache.retain(|_, t| !t.is_expired()) before inserting), or bounding the map size. A single-entry RwLock<Option<(key, OAuthToken)>> would also suffice, since only the current source token is ever queried.
| ) | ||
| .await | ||
| .expect("provider"); | ||
|
|
There was a problem hiding this comment.
🔵 Low — The design doc's own test plan lists a "Source rotation re-exchanges" case (inner returns token A then B → two exchanges, cache keyed per source). The wiremock suite covers the same-source cache-hit path (exchanged_token_is_cached_across_calls) but not the rotation path, which is precisely the property the per-source cache key exists to guarantee (and the ADBC PR #46 fix the design cites). A stub inner provider that returns JWT-A then JWT-B, asserting .expect(2) exchanges and distinct returned tokens, would lock in that behavior; as written a regression that keyed the cache on something coarser (e.g. issuer host) would pass every existing test.
There was a problem hiding this comment.
Verdict: 1 Medium · 1 Low
Solid, well-tested feature that mirrors the ADBC wire contract cleanly; the decorator design and non-breaking fallback are sound, and non-2xx exchange responses correctly return Err so the 401/500 fallback tests are valid. Two concerns: the federation token cache grows unbounded across a rotating-credential session (medium), and the design's headline per-source-rotation behavior is untested (low).
| inner: Arc<dyn AuthProvider>, | ||
| /// Full token-exchange endpoint URL: `{host}/oidc/v1/token`. | ||
| token_endpoint: String, | ||
| /// The workspace host (bare `host[:port]`) used to decide whether an |
There was a problem hiding this comment.
🟡 Medium — Federation cache grows unbounded over a session's lifetime — entries are never evicted.
cache is keyed on sha256(source_token) and entries are only ever inserted (both on successful exchange and on the failure fallback), never removed. is_expired() is consulted only for the current key's entry during a lookup — expired entries for previously-seen source tokens are left in the map forever.
This is exactly the case the design intends to support: keying on the source token so a rotated upstream credential (M2M re-auth every ~1h, U2M refresh) is re-exchanged fresh. But each rotation mints a new source token → a new sha256 key → a new permanent map entry. A long-lived session that periodically rotates its inner credential accumulates one dead entry per rotation, indefinitely. The failure path (60s-TTL originals) adds churn on top.
Not catastrophic per-entry, but it is a genuine unbounded-growth leak bounded only by session lifetime × rotation frequency. Consider pruning expired entries on insert (e.g. cache.retain(|_, t| !t.is_expired()) before inserting the new key), or capping the map size. The design doc's caching section discusses keying-on-source but does not mention eviction.
| #[tokio::test(flavor = "multi_thread")] | ||
| async fn exchanged_token_is_cached_across_calls() { | ||
| let server = MockServer::start().await; | ||
|
|
There was a problem hiding this comment.
🔵 Low — The central design claim — cache keyed per source token so a rotated inner credential is re-exchanged — is not tested.
The design doc's testing table lists a Source rotation re-exchanges case ("inner returns token A then B → two exchanges; cache keyed per source"), but the wiremock suite only covers the same-source case (exchanged_token_is_cached_across_calls, one exchange + cache hits). Nothing exercises an inner provider whose token changes between calls, which is the whole justification for keying on the source hash ("the same fix ADBC made in PR #46"). A regression that keyed on something coarser (or cached the first result forever) would pass every current test.
Worth adding a test with a stub inner provider that returns token A then token B and asserting two distinct exchanges occur.
There was a problem hiding this comment.
Verdict: 1 Low
Solid, well-tested change: the wire contract, WIF/BYOT param selection, host normalization, and the non-breaking fallback all match the ADBC reference, and execute_without_auth surfacing non-2xx as Err makes the 401/500 fallback tests meaningful. One low-severity robustness gap inline (non-positive expires_in isn't rejected, unlike ADBC, defeating the cache). Two nits for the summary: (1) sp_wide_wif_sends_identity_federation_client_id is weaker than the design table claims — it asserts the client-id param is present but never asserts return_original_token_if_authenticated is absent, though the match xor guarantees it; (2) the failure-fallback comment at federation.rs:271 calls the cached original a "short TTL (60)" entry, but with the 40s is_expired buffer the entry is only honored for ~20s of remaining life — harmless, but the comment overstates the throttle window.
| .message(format!("Failed to parse token-exchange response: {e}")) | ||
| })?; | ||
|
|
||
| Ok(OAuthToken::new( |
There was a problem hiding this comment.
🔵 Low — The exchange response accepts a non-positive expires_in unguarded. #[serde(default = "default_expires_in")] only supplies 3600 when the field is absent; a server response of "expires_in": 0 (or negative) is taken verbatim, so OAuthToken::new produces a token whose expires_at is already inside the 40s expiry buffer. is_expired() then returns true on the very next call, the cache slot never registers a hit, and every subsequent request re-runs the blocking network exchange — adding latency to each query and hammering /oidc/v1/token, exactly the retry-storm the cache is meant to prevent.
The ADBC reference guards against this explicitly: TokenExchangeClient.ParseTokenResponse throws "expires_in value must be positive" when expires_in <= 0. Consider rejecting a non-positive expires_in here (turning it into the normal pass-through fallback) rather than caching an immediately-expired entry.
There was a problem hiding this comment.
Verdict: 1 Low
Solid, well-scoped feature with strong test coverage (wiremock integration, single-flight concurrency, C ABI/pyo3/napi boundary tests) and correct error/fallback semantics — execute_without_auth genuinely returns Err on 401/500 so the non-breaking fallback works, and the sync→async bridge and follower busy-wait faithfully mirror the existing TokenStore pattern. One low edge-case note on host comparison inline. Nit: on a successful exchange, get_auth_header hardcodes format!("Bearer {token}") and never consults the deserialized ExchangeResponse.token_type (federation.rs:398) — harmless since Databricks always returns Bearer, but the parsed field is effectively dead.
| } | ||
|
|
||
| /// Performs the token exchange and returns the in-house token. Errors here | ||
| /// are turned into the pass-through fallback by the caller. |
There was a problem hiding this comment.
🔵 Low — issuer_is_foreign compares host_of(iss) to workspace_host including the port component, and host_of preserves whatever port is textually present (host.example.com:443 vs host.example.com are unequal). If an issuer claim carries an explicit port that the normalized workspace host omits (or vice-versa) — e.g. iss="https://host:443/oidc" against a workspace host of host — a genuinely in-house token would be classified foreign and trigger an unnecessary exchange round-trip. In practice Databricks-issued iss claims don't carry an explicit :443, so this is a latent edge rather than a live bug, but the scheme/port normalization asymmetry is worth a note. Consider stripping a default :443/:80 before comparison, mirroring whatever ConnectionConfig::normalise_host does.
There was a problem hiding this comment.
Verdict: 2 Low
Looks good — solid, well-tested implementation that faithfully mirrors the kernel's existing TokenStore single-flight convention, with a correct non-breaking fallback, issuer-gated pass-through, and clean binding surfaces. Two low-severity notes on the concurrency path (follower worker-thread blocking ceiling; coarse-grained single-flight flag causing a transient pass-through for mid-rotation callers) — both non-breaking and worth at most a tweak/comment.
| return source_token.to_string(); | ||
| } | ||
| std::thread::sleep(FOLLOWER_POLL_INTERVAL); | ||
| } |
There was a problem hiding this comment.
🔵 Low — Follower busy-wait can block a tokio worker thread for up to 60s. In the normal request path get_auth_header() is invoked synchronously from inside the async execute() loop (src/client/http.rs:818 → auth_header() → provider.get_auth_header()), i.e. on a tokio worker thread. The leader correctly hands its worker off via block_in_place (inside block_on_in_runtime), but a follower spins in while self.exchanging.load(...) { std::thread::sleep(FOLLOWER_POLL_INTERVAL) } without block_in_place, so it parks the worker thread it is running on for up to the 60s deadline.
This mirrors TokenStore's accepted follower pattern (token_store.rs:288), so it is not novel — but note two compounding factors here: (a) the follower ceiling is a full 60s (vs. the leader's ~30s Auth-category budget), and (b) an M2M/U2M request can now serialize behind two sequential single-flights (TokenStore refresh, then federation exchange). If concurrent misses ever exceed the worker-thread count, the leader's HTTP future competes with sleeping followers for progress. Consider capping the follower deadline closer to the leader's Auth budget (~30–35s) so a wedged leader can't hold a worker for a full minute.
| /// On failure, publish the original token so followers read the same | ||
| /// non-breaking fallback (spec: continue with the existing token rather | ||
| /// than throwing). | ||
| fn lead_exchange(&self, source_token: &str) -> String { |
There was a problem hiding this comment.
🔵 Low — A concurrent caller whose source token differs mid-flight silently skips its exchange. The single-flight flag exchanging is a single global AtomicBool, not keyed per source token. If a leader is exchanging token A when the inner credential rotates and a new caller arrives with token B, that caller loses the compare_exchange, becomes a follower, waits for the leader, then calls cached_for(B) — which holds A's result, not B's — and falls back to the un-exchanged original token B (follow_exchange → unwrap_or_else(|| source_token.to_string())).
This is non-breaking (that request just uses the raw foreign token, and the next call for B exchanges it), and the window is narrow (only while callers straddle a rotation). Worth a comment on exchanging documenting that the flag is deliberately coarse-grained and that cross-token followers intentionally degrade to pass-through rather than starting a nested exchange.
Wrap the base auth provider (PAT / M2M / U2M) with a FederationProvider
that exchanges a foreign-issuer JWT for an in-house Databricks token at
{host}/oidc/v1/token before use.
- jwt.rs: decode the JWT payload (no signature verification) to read the
iss claim, using the existing base64 + serde_json deps.
- federation.rs: blocking exchange via block_on_in_runtime (matching the
M2M provider's sync-trait-over-async bridge), cached per source token,
with non-breaking fallback to the original token on any failure. Wire
contract follows the BYOT spec / ADBC: grant_type=jwt-bearer, assertion,
scope=sql, and identity_federation_client_id XOR
return_original_token_if_authenticated=true.
- Gated internally by the iss-vs-host check: non-JWT (PAT) and same-host
tokens pass through with no HTTP call, so the wrapper is always-on and
needs no enable flag.
- New optional SessionConfig::identity_federation_client_id (+ builder
setter) selects SP-wide WIF.
Verified: cargo build, clippy -D warnings, fmt --check, and tests all
pass (8 federation integration tests + full 768-test lib suite).
Co-authored-by: Isaac
Signed-off-by: Vu Anh Phung <vu.phung@databricks.com>
The SP-wide WIF selector for mandatory token exchange was reachable only from the Rust SessionBuilder. Thread it through every consumer boundary so Python, Node, ODBC, Go, and C callers can select SP-wide WIF (the exchange itself, and BYOT / account-wide WIF, already worked everywhere since it is gated by the token issuer, not config). - C ABI: new kernel_session_config_set_identity_federation_client_id setter, stored on KernelSessionConfig and forwarded to the builder; declared in include/databricks_kernel.h. Consumed by ODBC and Go. - pyo3: new optional identity_federation_client_id kwarg on Session(...). - napi: new optional identityFederationClientId field on ConnectionOptions; index.d.ts updated. Tests: C ABI setter unit test (records value, rejects NULL) + C smoke check; pyo3 kwarg-accepted boundary test; napi options-boundary test. Verified build + clippy -D warnings + fmt --check + tests across core, pyo3, and napi. Co-authored-by: Isaac Signed-off-by: Vu Anh Phung <vu.phung@databricks.com>
Address review findings on the federation provider's concurrency and cache. H1: the resolver no longer holds a lock across the exchange network call. get_auth_header is sync and runs on a tokio worker, so holding a std Mutex across block_on_in_runtime(exchange) parked that worker for the whole retry budget and, under contention, could starve the runtime. Now: cache hit under a brief read lock; miss runs the exchange lock-free (idempotent — concurrent cold-start callers race and the last writer wins) and takes a brief write lock only to store. Each exchange's latency is already bounded by the Auth-category retry budget (30s / 3 retries), not the global ladder. M2: replace the insert-only HashMap<sha256, OAuthToken> with a single-slot RwLock<Option<(source_token, OAuthToken)>>. A provider tracks one active source token, so the slot is overwritten on rotation/expiry rather than leaking an entry per rotated credential; it also drops the per-request sha256 on the cache-hit path (compare the source token directly). M1: guard block_on_in_runtime against a current-thread runtime. It uses block_in_place, which panics there; the resolver now detects the flavor and falls back to the original token (same non-breaking posture as a failed exchange) instead of panicking. Tests: retries-enabled bounded-latency test (8 concurrent callers vs an always-503 endpoint finish in parallel, not serialized) guarding H1; a non-circular representative-Databricks-issuer pass-through test (M3). Co-authored-by: Isaac Signed-off-by: Vu Anh Phung <vu.phung@databricks.com>
Replace the let-concurrent-callers-race resolver with single-flight coalescing, mirroring the kernel's own TokenStore refresh coordination (and Go's CachedTokenProvider): concurrent cache misses elect one leader via a lock-free AtomicBool that runs the exchange; followers sleep-poll the cache slot and read the leader's published result. Still holds no lock across the network call. The win over racing: on a rotated/expired token a busy shared session can miss on many threads at once, and for SP-wide WIF each exchange mints a distinct server token — coalescing keeps it to one instead of N (N-1 orphaned). It also keeps only the leader in the runtime (block_in_place), not all N callers. Followers verify the published entry is for their own source token (the inner credential may rotate mid-wait) and fall back otherwise; the leader always publishes an outcome — on failure the original token (short TTL), so failures stay non-breaking per spec and followers never spin to their timeout. An RAII guard clears the flag if the leader panics. Test: the concurrency case now asserts exactly one exchange for 10 concurrent cold callers (mock .expect(1)) — the real parity check — plus a degraded-endpoint case asserting all concurrent callers fall back. Co-authored-by: Isaac Signed-off-by: Vu Anh Phung <vu.phung@databricks.com>
AuthTokenRequest is classified idempotent, so the exchange ladder retries all 5xx/429/408/timeouts except the fixed non-retryable 4xx set — not just 408/502/503/504 as the doc and the federation.rs comment previously said (which understated it: 500 and 429 are retried too). Comment-only change in federation.rs; behavior unchanged. Co-authored-by: Isaac Signed-off-by: Vu Anh Phung <vu.phung@databricks.com>
There was a problem hiding this comment.
Verdict: 1 Low
Looks good — a clean, well-tested implementation of mandatory OIDC token exchange with sound single-flight coalescing (RAII guard clears the flag, followers bounded, current-thread runtime handled), issuer re-checked per call so rotated inner tokens aren't shadowed, and non-breaking fallback on every failure path. Wiremock + C-ABI + binding coverage is comprehensive. One low-severity edge: host comparison includes the port, so an explicit :443 mismatch could trigger a redundant (still non-breaking) exchange. Nit: the current-thread-runtime pass-through branch in exchanged_or_original has no direct test.
| .http_client | ||
| .execute_without_auth(request, RequestType::AuthTokenRequest) | ||
| .await?; | ||
|
|
There was a problem hiding this comment.
🔵 Low — host_of returns the authority component including the port, and issuer_is_foreign compares the two host strings verbatim (eq_ignore_ascii_case). If the workspace host and the token's iss differ only in an explicit default port (e.g. workspace configured as https://ws.cloud.databricks.com:443 vs. an in-house issuer https://ws.cloud.databricks.com/oidc, or vice-versa), the issuer is treated as foreign and an otherwise-unnecessary token exchange is performed.
This is non-breaking (the exchange with return_original_token_if_authenticated=true still yields a usable token, and the result is cached), so it only costs one extra round-trip. But it's a surprising edge: a same-workspace token can be flagged foreign purely because of a :443 in the configured host. Consider normalizing away the default HTTPS port before comparison, or documenting that hosts must be provided without an explicit default port. All shipped tests use port-less hosts, so this path is not currently exercised.
Adds mandatory OIDC token exchange so a token issued by a party other than the target workspace (Azure AD, an external IdP, a Bring-Your-Own-Token, or a Workload Identity Federation token) is exchanged for an in-house Databricks token at
<host>/oidc/v1/tokenbefore use. This brings the kernel to parity with the JDBC and ADBC drivers.A new
FederationProviderwraps the existing base provider (PAT / M2M / U2M). It is gated internally by the token'sissclaim — non-JWT (PAT) and same-host tokens pass through with no HTTP call — so it is always-on and needs no enable flag. Any exchange failure falls back to the original token, so existing flows are unaffected. The exchange is blocking and cached per source token, using the same sync-trait-over-async bridge (block_on_in_runtime) as the M2M provider.The wire contract follows the BYOT spec / ADBC:
grant_type=jwt-bearer,assertion,scope=sql, andidentity_federation_client_id(SP-wide WIF) XORreturn_original_token_if_authenticated=true(BYOT / account-wide WIF). A new optionalSessionConfig::identity_federation_client_id(+ builder setter) selects SP-wide WIF.Design doc:
docs/designs/token-federation-design.md.Out of scope (follow-ups): Managed Identity headers on the exchange call (no MI auth flow exists yet), and the reserved
AuthConfig::OAuthFederationvariant (a separate RFC 8693 feature).Verified locally:
cargo build,cargo clippy -- -D warnings,cargo fmt --check, plus 8 federation integration tests and the full 768-test lib suite all pass.This pull request and its description were written by Isaac.