Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions NEXT_CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,16 @@ changes go in their respective binding's NEXT_CHANGELOG.
value is ignored (default preserved) with a warning rather than failing session
creation. The key is client-only — it is consumed before session creation and never
reaches the SEA wire. Benefits ODBC too.
- Auth: mandatory OIDC token exchange (BYOT federation) — when an authenticated
token was 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), the kernel
now exchanges it for an in-house Databricks token at `<host>/oidc/v1/token` before
using it, transparently across PAT / M2M / U2M. Gated by the token's `iss` claim
(non-JWT and same-host tokens pass through with no HTTP call) and falls back to the
original token if the exchange fails, so existing flows are unaffected. New optional
`identity_federation_client_id` fields on the PAT, M2M, and U2M `AuthConfig`
variants select SP-wide WIF; unset means BYOT / account-wide WIF. Follows the
ADBC wire contract (`grant_type=jwt-bearer`, `assertion`, `scope=sql`).

### Updated

Expand Down
66 changes: 36 additions & 30 deletions docs/designs/token-federation-design.md
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,8 @@ provider construction is split into `build_auth_provider` (which wraps) and
`build_base_auth_provider` (which matches the auth flow):

```
build_auth_provider(auth, host, identity_federation_client_id, http_client)
build_auth_provider(auth, host, http_client)
├── identity_federation_client_id = auth.identity_federation_client_id()
├── base = build_base_auth_provider(auth, host, http_client)
│ └── match auth { Pat | OAuthM2M | OAuthU2M => existing construction }
└── FederationProvider::new(base, host, identity_federation_client_id, http_client)
Expand Down Expand Up @@ -192,11 +193,11 @@ We adapt `TokenStore`'s pattern in two ways it doesn't cover: the follower check
the published entry is for **its** source token (if the upstream credential rotated
mid-wait, it falls back rather than returning another token's result), and the
leader **always publishes an outcome** — on failure it stores the original token
(short TTL) so followers read the same non-breaking fallback instead of spinning to
a timeout. On any exchange failure every caller uses the original token (spec:
"continue with the existing JWT token instead of throwing"). The leader's latency
is bounded by the **Auth-category retry budget** (30s / 3 retries — see
`build_retry_configs_for_session`), not the global ladder; followers additionally
with a 60-second retry delay so followers read the same non-breaking fallback
instead of spinning to a timeout. On any exchange failure every caller uses the
original token (spec: "continue with the existing JWT token instead of throwing").
The leader's latency is bounded by the **Auth-category retry budget** (30s / 3
retries — see `build_retry_configs_for_session`), not the global ladder; followers additionally
cap their wait so a wedged leader can't hang them indefinitely.

---
Expand Down Expand Up @@ -229,7 +230,7 @@ pub struct FederationProvider {
token_endpoint: String, // {host}/oidc/v1/token, built directly
workspace_host: String, // normalized host, for iss-host comparison
identity_federation_client_id: Option<String>,
http_client: Arc<DatabricksHttpClient>,
http_client: Weak<DatabricksHttpClient>,
runtime_handle: tokio::runtime::Handle,
cache: RwLock<Option<CacheEntry>>, // single slot: (source_token, exchanged)
exchanging: AtomicBool, // single-flight leader election
Expand All @@ -240,11 +241,15 @@ impl FederationProvider {
inner: Arc<dyn AuthProvider>,
host: &str,
identity_federation_client_id: Option<String>,
http_client: Arc<DatabricksHttpClient>,
http_client: &Arc<DatabricksHttpClient>,
) -> Result<Self>;
}
```

The HTTP client owns the installed auth provider, so the federation wrapper
retains only a weak client reference and does not introduce a cycle for PAT
sessions.

`get_auth_header()` logic:

1. `let header = self.inner.get_auth_header()?;` → strip `"Bearer "` → `source`.
Expand All @@ -265,10 +270,10 @@ impl FederationProvider {
the original token.
5. **Leader success** → store `(source, OAuthToken)` (from `expires_in`), return
`Bearer <new token>`.
**Leader failure** → log at `warn!`, store the original token (short TTL) so
followers and subsequent callers read the same fallback instead of re-hitting a
failing endpoint, and **return the original `header`** (spec's non-breaking
fallback). The error is never surfaced to the caller.
**Leader failure** → log at `warn!`, store the original token with a 60-second
retry delay so followers and subsequent callers read the same fallback instead
of re-hitting a failing endpoint, and **return the original `header`** (spec's
non-breaking fallback). The error is never surfaced to the caller.

`block_on_in_runtime` uses `block_in_place`, which panics on a **current-thread**
runtime. Every shipped consumer (pyo3, napi, C ABI) drives the kernel on a
Expand Down Expand Up @@ -297,45 +302,46 @@ Add `pub mod jwt;` and `pub mod federation;`; re-export `FederationProvider`.

### `src/config.rs`

One caller-facing field (no wrapper struct, no `enabled`):
The supported base-auth variants each carry the optional federation selector:

```rust
/// SP-wide Workload Identity Federation client id. `None` → BYOT /
/// account-wide WIF, where the exchange sends
/// `return_original_token_if_authenticated=true` instead.
pub identity_federation_client_id: Option<String>,
AuthConfig::Pat { token, identity_federation_client_id }
AuthConfig::OAuthM2M { ..., identity_federation_client_id }
AuthConfig::OAuthU2M { ..., identity_federation_client_id }
```

Placed on `SessionConfig` (top level, since it applies across PAT/M2M/U2M) and
threaded through the builder.
`None` selects BYOT / account-wide WIF, where the exchange sends
`return_original_token_if_authenticated=true`. The reserved
`AuthConfig::OAuthFederation` variant is unchanged: it represents a separate,
caller-supplied RFC 8693 flow and is not this mandatory decorator.

### `src/session.rs`

Split provider construction into `build_auth_provider` (wraps) and
`build_base_auth_provider` (matches the auth flow), as shown in
[Integration point](#integration-point). `SessionBuilder` gains an
`identity_federation_client_id(...)` setter, threaded onto `SessionConfig`.
[Integration point](#integration-point). `build_auth_provider` reads the
federation client id from the selected `AuthConfig` variant before wrapping the
base provider.

### `src/kernel_error.rs`

No new variant. Exchange failures use existing `Error::unauthenticated()` /
`Error::network_error()` for the `warn!` log only; they are swallowed into the
fallback and never returned.

### Bindings — exposing `identity_federation_client_id` on every boundary
### Bindings — follow-up work

The exchange itself works through all consumers unchanged (it is gated by the
token issuer, not config), but the SP-wide WIF *selector* must be reachable from
each surface, or Python / Node / ODBC / Go / C callers can only ever take the
BYOT / account-wide WIF branch. It is threaded through:
token issuer, not config). This core change leaves the bindings passing `None`;
a follow-up will expose the SP-wide WIF selector on each surface:

- **C ABI** (`src/c_abi/session.rs`, consumed by ODBC and Go): new
- **C ABI** (`src/c_abi/session.rs`, consumed by ODBC and Go): add a
`kernel_session_config_set_identity_federation_client_id()` setter, stored on
`KernelSessionConfig` and forwarded to the builder; declared in
`KernelSessionConfig` and attached to the selected `AuthConfig`; declared in
`include/databricks_kernel.h` (hand-written header).
- **pyo3** (`pyo3/src/session.rs`): new optional `identity_federation_client_id`
keyword on `Session(...)`.
- **napi** (`napi/src/database.rs`): new optional `identityFederationClientId`
- **pyo3** (`pyo3/src/session.rs`): add an optional
`identity_federation_client_id` keyword on `Session(...)`.
- **napi** (`napi/src/database.rs`): add an optional `identityFederationClientId`
field on `ConnectionOptions`; the generated `napi/index.d.ts` is updated by hand.

Each binding stages its own changelog entry (`pyo3/NEXT_CHANGELOG.md`,
Expand Down
4 changes: 2 additions & 2 deletions docs/migration-plan.md
Original file line number Diff line number Diff line change
Expand Up @@ -239,8 +239,8 @@ follow-ups in a later PR.
### PR 2 — Session

**Goal.**
`Session::builder().http_path(host, http_path).auth(AuthConfig::Pat{token}).open().await`
returns a working session against a Databricks workspace. First
A session built with `AuthConfig::Pat { token, identity_federation_client_id: None }`
works against a Databricks workspace. First
user-visible piece of the v0 surface; gives us a real E2E test.

**What changes.**
Expand Down
13 changes: 11 additions & 2 deletions pyo3/src/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,10 @@ fn build_auth_config_inner(
if token.is_empty() {
return Err("access_token must not be empty".to_owned());
}
Ok(AuthConfig::Pat { token })
Ok(AuthConfig::Pat {
token,
identity_federation_client_id: None,
})
}
"oauth-m2m" => {
// Client credentials grant: both halves are mandatory.
Expand All @@ -145,6 +148,7 @@ fn build_auth_config_inner(
client_secret,
scopes: oauth.scopes,
token_url_override: oauth.token_url,
identity_federation_client_id: None,
})
}
"oauth-u2m" => {
Expand Down Expand Up @@ -229,6 +233,7 @@ fn build_auth_config_inner(
// passphrase through `OAuthParams` — the equivalent of JDBC's
// TokenCachePassPhrase — would strengthen it further.
token_cache: None,
identity_federation_client_id: None,
})
}
other => Err(format!(
Expand Down Expand Up @@ -264,7 +269,7 @@ mod tests {
fn pat_builds() {
let cfg =
build_auth_config_inner("pat", Some("dapi123".into()), OAuthParams::default()).unwrap();
assert!(matches!(cfg, AuthConfig::Pat { token } if token == "dapi123"));
assert!(matches!(cfg, AuthConfig::Pat { token, .. } if token == "dapi123"));
}

#[test]
Expand Down Expand Up @@ -327,11 +332,13 @@ mod tests {
client_secret,
scopes,
token_url_override,
identity_federation_client_id,
} => {
assert_eq!(client_id, "id");
assert_eq!(client_secret, "sec");
assert_eq!(scopes, Some(vec!["all-apis".to_string()]));
assert_eq!(token_url_override.as_deref(), Some("https://example/token"));
assert!(identity_federation_client_id.is_none());
}
other => panic!("expected OAuthM2M, got {other:?}"),
}
Expand All @@ -357,6 +364,7 @@ mod tests {
token_url_override,
callback_timeout,
token_cache,
identity_federation_client_id,
} => {
assert_eq!(client_id.as_deref(), Some("databricks-sql-python"));
assert!(redirect_port.is_none());
Expand All @@ -374,6 +382,7 @@ mod tests {
token_cache.is_none(),
"Python U2M should defer to the kernel's token-cache default"
);
assert!(identity_federation_client_id.is_none());
}
other => panic!("expected OAuthU2M, got {other:?}"),
}
Expand Down
2 changes: 1 addition & 1 deletion src/auth/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ pub mod oauth;
pub mod pat;

pub use config::{AuthConfig, AuthType};
pub use oauth::{AuthorizationCodeProvider, ClientCredentialsProvider};
pub use oauth::{AuthorizationCodeProvider, ClientCredentialsProvider, FederationProvider};
pub use pat::PersonalAccessToken;

use crate::kernel_error::Result;
Expand Down
Loading
Loading