Skip to content

fix(auth): share M2M tokens across connections and retry exchanges - #398

Closed
vuanhphung wants to merge 1 commit into
mainfrom
fix/m2m-shared-auth
Closed

vuanhphung wants to merge 1 commit into
mainfrom
fix/m2m-shared-auth

Conversation

@vuanhphung

@vuanhphung vuanhphung commented Oct 15, 2026 •

Copy link
Copy Markdown
Collaborator

Each kernel connection currently repeats OIDC discovery and the OAuth client-credentials exchange, causing token-request bursts when opening connections concurrently. Share discovery and token state in a bounded process-wide cache keyed by workspace, credentials, scopes, endpoint/resource, and transport settings. Concurrent refreshes are coalesced while HTTP clients and runtimes remain connection-owned.

Route token exchanges through the existing auth retry policy, including Retry-After. Preserve HTTP error metadata for waiting callers and release Tokio workers while they wait; invalid credentials remain non-retryable authentication errors.

Thrift-mode comparison

The drivers reuse tokens through auth/token-source objects. Sharing across connections depends on reusing those objects; none of these default Thrift paths provides a process-wide credential-identity cache.

Mode Cache scope / key Concurrent refresh Token-request retries
Go Thrift One oauth2.TokenSource per connector/authenticator; no explicit cache-map key. Pooled connections reuse it. Authenticate mutex plus ReuseTokenSource serialize acquisition/renewal. OAuth2 uses the standard HTTP client. The outer Thrift request loop can retry auth failures, but does not receive the token endpoint's Retry-After.
Python Thrift: SDK M2M ExternalAuthProvider invokes credentials_provider() per connection. Sharing requires the callback to return the same SDK header factory/token source. The example creates a new factory each time. Controlled by the supplied SDK/provider. Controlled by the SDK/provider's HTTP transport, separately from the connector's Thrift retry policy.
Python Thrift: built-in Azure M2M ClientCredentialsTokenSource.token caches one token per source; the provider callback constructs separate resource-token sources. No refresh lock in the built-in token source. Token POSTs use UnifiedHttpClient / DatabricksRetryPolicy, including Retry-After.
Node.js Thrift Default OAuthPersistenceCache belongs to the auth instance and is keyed by host. A fresh default auth instance gets a fresh cache. No mutex or shared in-flight acquisition/refresh promise. Discovery and grants go through openid-client, without the driver's Thrift retry-policy wrapper.
Kernel (this PR) Process-wide cache of matching auth identities: workspace, credentials, scopes, endpoint/resource, and transport settings. Salted hash keys; 256 entries, one-hour idle expiry. Shared token store coalesces acquisition/renewal and releases waiting Tokio workers. Existing Auth policy: three retries, 30-second budget, Retry-After, and preserved HTTP error metadata.

The kernel bindings construct an auth provider per connection. Sharing token state inside the kernel preserves reuse across those provider instances without sharing connection-owned HTTP clients or runtimes.

Validated with the full cargo test suite, including doc tests, Clippy with warnings denied, and formatting checks. Mock tests verify 32 independent connections perform one discovery and one token exchange, plus refresh sharing, cache isolation, retry exhaustion, and reuse across runtimes.

Signed-off-by: Vu Anh Phung <vu.phung@databricks.com>

@oss-reviewer-bot oss-reviewer-bot Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verdict: 2 Low

Looks good — solid, well-tested change. Shared M2M token/discovery caching, retry-routed token exchanges, and the refresh_error propagation are correctly ordered and backed by thorough wiremock + unit coverage; new deps are already in Cargo.toml and the custom Debug impl correctly stops leaking client_secret. Two low-severity notes only: a new block_in_place panic path on current-thread runtimes (relies on the multi-thread invariant), and loss of OAuth error_description in error messages.

// Waiting must release a runtime worker, just like the leader's
// HTTP exchange, or concurrent sessions can starve its I/O.
if tokio::runtime::Handle::try_current().is_ok() {
tokio::task::block_in_place(|| self.wait_for_refresh())

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Low — The new waiter path wraps wait_for_refresh() in tokio::task::block_in_place guarded only by Handle::try_current().is_ok(), not by runtime flavor. block_in_place panics on a current-thread runtime. Before this change a follower simply called wait_for_refresh() directly (blocking the worker but never panicking), so this introduces a new panic path for callers driving get_auth_header() from inside a single-threaded tokio runtime.

In practice the kernel's session runtime is multi-thread (documented invariant in src/util/runtime.rs), and this mirrors the existing block_on_in_runtime guard, so the realistic blast radius is small. But note that block_on_current_runtime in the same util module does branch on handle.runtime_flavor() before calling block_in_place — matching that pattern here would make the fallback panic-free rather than relying on the multi-thread invariant holding for every embedder.

Comment thread src/client/http.rs
}
return err
.with_error_code(code)
.message(format!("{context}: OAuth {code}"));

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Low — The new OAuth-error branch collapses the message to "{context}: OAuth {code}", surfacing only the short error code and discarding any error_description present in the OAuth error body. OAuth providers routinely put the actionable detail (e.g. "client secret expired", "scope X not granted") in error_description; previously the m2m path folded the raw body into the message via oauth2's ServerResponse/the v1 path's explicit body inclusion. Consider appending error_description when present so operators keep the diagnostic text. Non-blocking — the error_code and http_status are preserved, which is the important part for programmatic handling.

This branch was previously deployed

1 inactive deployment
azure-prod — 00aa23d9 Deployed Oct 15, 2026 by oss-reviewer-bot[bot] via followup #1993
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant