From d41d806c5696a59ceb7daab6bf8af8746198c110 Mon Sep 17 00:00:00 2001 From: eric-wang-1990 Date: Tue, 18 Aug 2026 09:19:28 -0700 Subject: [PATCH 01/47] docs: design for Azure Entra ID service-principal (M2M) auth (PECOBLR-4141) Adds the design doc for kernel-native Azure service-principal M2M auth: a new AuthConfig::AzureServicePrincipal variant + provider that mints an Entra token via client-credentials, an AuthProvider::extra_headers() seam for the two X-Databricks-Azure-* headers, and wiring across the pyo3, napi, and C ABI bindings. Azure U2M is unchanged (already works via workspace OIDC). Co-authored-by: Isaac Signed-off-by: eric-wang-1990 --- ...BLR-4141-azure-service-principal-design.md | 310 ++++++++++++++++++ 1 file changed, 310 insertions(+) create mode 100644 docs/designs/PECOBLR-4141-azure-service-principal-design.md diff --git a/docs/designs/PECOBLR-4141-azure-service-principal-design.md b/docs/designs/PECOBLR-4141-azure-service-principal-design.md new file mode 100644 index 00000000..2840223a --- /dev/null +++ b/docs/designs/PECOBLR-4141-azure-service-principal-design.md @@ -0,0 +1,310 @@ + + +# Azure Entra ID Service-Principal (M2M) Auth Design — PECOBLR-4141 + +## Overview + +The kernel supports PAT, OAuth M2M (Databricks client credentials), and OAuth +U2M (browser). `databricks-sql-python` users who authenticate with an **Azure +service principal** (`azure_client_id` / `azure_client_secret` / +`azure_tenant_id` / `azure_workspace_resource_id`) cannot yet run on the kernel +path: those credentials are **Microsoft Entra ID (Azure AD) app-registration** +credentials, and the token must be minted by **Entra** +(`login.microsoftonline.com`), not by the workspace OIDC endpoint the existing +M2M provider discovers. + +This design adds a kernel-native **Azure service-principal M2M** flow, forwards +the `azure_*` parameters across all four binding surfaces (Rust core, pyo3, +napi, C ABI), and reaches parity with the `databricks-sdk` `azure-client-secret` +credential strategy including its two Azure-specific request headers. + +### What is *not* in scope + +- **Azure U2M (`auth_type='azure-oauth'`) already works** and is unchanged. Kernel + U2M runs the standard workspace OIDC browser flow (`{host}/oidc/v1/authorize`); + for an `adb-*.azuredatabricks.net` workspace that federates to Entra + server-side, with no client-side Entra involvement. Confirmed against the + Databricks OAuth U2M docs and the kernel's existing U2M provider. +- **Azure CLI / MSAL / managed-identity** credential sources. Only the + client-secret service-principal flow is in scope (the `azure_*` kwargs the + ticket names). + +## Reference wire contract + +Sourced from the Databricks docs +([aad-token-manual](https://learn.microsoft.com/en-us/azure/databricks/dev-tools/auth/aad-token-manual), +[azure-sp](https://learn.microsoft.com/en-us/azure/databricks/dev-tools/auth/azure-sp)) +and `databricks-sdk-py`'s `azure.py` credential strategy — the exact behavior +`databricks-sql-python` inherits today. + +**Inner (Databricks-audience) token — always:** + +``` +POST https://login.microsoftonline.com/{tenant_id}/oauth2/v2.0/token +Content-Type: application/x-www-form-urlencoded + +grant_type = client_credentials +scope = 2ff814a6-3304-4ab8-85cb-cd0e6f879c1d/.default (URL-encoded .../%2F.default) +# client_id + client_secret via HTTP Basic auth +``` + +`2ff814a6-3304-4ab8-85cb-cd0e6f879c1d` is the **Azure Databricks application +id** — a constant across all Azure clouds. The returned token's `aud` is that +id and its `iss` is `https://sts.windows.net/{tenant_id}/`. + +**Management token — only when `azure_workspace_resource_id` is set:** a second +`client_credentials` request to the *same* endpoint with +`scope = https://management.core.windows.net/.default` (Public cloud). + +**Headers attached to Databricks API requests:** + +| Header | Sent when | +| --- | --- | +| `Authorization: Bearer ` | always | +| `X-Databricks-Azure-Workspace-Resource-Id: ` | `azure_workspace_resource_id` set | +| `X-Databricks-Azure-SP-Management-Token: ` | `azure_workspace_resource_id` set (management token fetched) | + +The management token + workspace-resource-id headers let the control plane +validate a service principal that has an Azure RBAC role on the workspace but is +not (yet) an explicit workspace member. When `azure_workspace_resource_id` is +unset, only the bearer is sent — the common SQL case where the SP is already a +workspace principal. + +**Azure cloud environments.** Login host and management scope differ by cloud; +the app-id constant does not. Values are pinned from `databricks-sdk-py`'s +`azure.py` `ENVIRONMENTS` table during implementation: + +| Environment | Login host | Management scope | +| --- | --- | --- | +| `PUBLIC` (default) | `https://login.microsoftonline.com` | `https://management.core.windows.net/.default` | +| `USGOVERNMENT` | `https://login.microsoftonline.us` | `https://management.usgovcloudapi.net/.default` | +| `CHINA` | `https://login.chinacloudapi.cn` | `https://management.chinacloudapi.cn/.default` | + +## Key design decisions + +### 1. A dedicated `AuthConfig` variant, not a reuse of `OAuthM2M` + +`OAuthM2M`'s provider discovers the *workspace* token endpoint via OIDC and +requests Databricks scopes. Azure SP needs an Entra token endpoint built from +`{login_host}/{tenant}`, a fixed resource scope, a second (management) token, +and two extra headers. Bolting these onto `OAuthM2M` would tangle two flows and +muddy its config. A new variant keeps each flow's config self-describing — +consistent with the enum's existing `#[non_exhaustive]` note that anticipated +"an Azure-AD service-principal shortcut". + +```rust +AuthConfig::AzureServicePrincipal { + azure_client_id: String, + azure_client_secret: String, + azure_tenant_id: String, + /// Enables the management-token path + both X-Databricks-Azure-* headers. + azure_workspace_resource_id: Option, + /// None ⇒ derive from the workspace host (default PUBLIC). + azure_environment: Option, + /// Carried for uniformity with the other variants; forwarded to the + /// federation wrapper. + identity_federation_client_id: Option, +} +``` + +A validating constructor `AuthConfig::azure_service_principal(...)` rejects +missing/empty `azure_client_id` / `azure_client_secret` / `azure_tenant_id` +(mirroring `oauth_m2m`), and `Debug` redacts the secret. + +### 2. Extend the `AuthProvider` trait for extra headers + +The trait returns only `Authorization` today. The two `X-Databricks-Azure-*` +headers are dynamic (the management token refreshes), so they can't be static +`custom_headers`. Add a default-empty method: + +```rust +pub trait AuthProvider: Send + Sync + Debug { + fn get_auth_header(&self) -> Result; + /// Extra headers to attach alongside `Authorization` on authenticated + /// requests. Default: none. Only the Azure SP provider overrides it. + fn extra_headers(&self) -> Result> { Ok(Vec::new()) } +} +``` + +Every existing provider (PAT / M2M / U2M) inherits the empty default unchanged. +`FederationProvider` **delegates** `extra_headers()` to its inner provider so +the Azure headers survive the wrapper. + +### 3. `FederationProvider` still wraps uniformly + +The Azure inner token's issuer (`sts.windows.net`) is foreign to the workspace +host, so `FederationProvider` will attempt an exchange at `{host}/oidc/v1/token`. +This is **correct and non-breaking** in every case: + +- **Azure workspace:** the exchange endpoint accepts the AAD assertion + (`return_original_token_if_authenticated=true` path) and returns a usable + token. If it ever fails, the existing non-breaking fallback uses the original + AAD token directly — which the Azure workspace natively accepts, *with* the + management headers still attached to the real request. +- **AWS/GCP workspace reached by an Azure SP:** exchange is *required*, and this + is exactly the mechanism that provides it (the management headers are + meaningless there and ignored as unknown `X-` headers). + +Keeping federation uniform avoids special-casing and preserves the "mandatory, +issuer-gated" design. The exchange request itself goes out via +`execute_without_auth` and so does **not** carry the Azure extra headers (they +are attached only to authenticated API requests) — deliberate, since the +assertion authenticates that call. + +### 4. `AzureEnvironment` auto-detected from host, overridable + +`None` ⇒ derive from the workspace host suffix (`.azuredatabricks.net` → +`PUBLIC`, `.databricks.azure.us` → `USGOVERNMENT`, `.databricks.azure.cn` → +`CHINA`; default `PUBLIC`). An explicit value from the caller wins. This mirrors +the SDK, which auto-detects but honors `azure_environment` / +`ARM_ENVIRONMENT`. + +## Module structure + +### `src/auth/oauth/azure.rs` (new) + +`AzureServicePrincipalProvider` implementing `AuthProvider`: + +- Constructor `new(host, azure_client_id, azure_client_secret, azure_tenant_id, + azure_workspace_resource_id, azure_environment, http_client)` (async, captures + the runtime handle like the M2M/U2M providers). +- Builds the Entra token endpoint `{login_host}/{tenant}/oauth2/v2.0/token` from + the resolved environment. +- **Inner token:** a `TokenStore` + `oauth2::BasicClient` client-credentials + exchange with scope `{DATABRICKS_RESOURCE_ID}/.default`, reusing the exact + lifecycle machinery `m2m.rs` uses (fresh/stale/expired, single-flight refresh). +- **Management token:** a *second* `TokenStore` populated only when + `azure_workspace_resource_id` is `Some`, scope + `{management_scope}` for the environment. +- `get_auth_header()` → `Bearer `. +- `extra_headers()` → `X-Databricks-Azure-Workspace-Resource-Id` + + `X-Databricks-Azure-SP-Management-Token` when the resource id is set (each + driven by a `get_or_refresh` on its store). + +Constants (module-private): `DATABRICKS_RESOURCE_ID = +"2ff814a6-3304-4ab8-85cb-cd0e6f879c1d"`, the `ENVIRONMENTS` table. + +### `src/auth/oauth/mod.rs`, `src/auth/mod.rs` + +`pub mod azure;`; re-export `AzureServicePrincipalProvider`. Add the +`extra_headers` default method to the `AuthProvider` trait. + +### `src/auth/oauth/federation.rs` + +Add `fn extra_headers(&self) -> Result> { +self.inner.extra_headers() }` to the `AuthProvider` impl. + +### `src/config.rs` + +New `AuthConfig::AzureServicePrincipal` variant, `AzureEnvironment` enum, +`azure_service_principal(...)` validating constructor, `Debug` redaction of the +secret, and `identity_federation_client_id()` arm. + +### `src/session.rs` + +New arm in `build_base_auth_provider` constructing +`AzureServicePrincipalProvider`. The existing `build_auth_provider` wraps it with +`FederationProvider` unchanged. + +### `src/client/http.rs` + +In the request-build loop, on the `with_auth` branch, after setting +`Authorization`, apply `self.auth_extra_headers()?` (a new method reading the +provider from the `OnceLock` and calling `extra_headers()`). These ride only +authenticated `execute()` requests, never `execute_without_auth` (token/OIDC +calls). The `X-Databricks-Azure-*` names are not in the reserved set. + +## Binding surfaces + +Selector name `azure-client-secret` matches the `databricks-sdk` auth-type +string, so the connector maps its detected Azure SP config onto the kernel +verbatim. + +### pyo3 (`pyo3/src/auth.rs`, `pyo3/src/session.rs`) + +- New `Session(...)` kwargs: `azure_client_id`, `azure_client_secret`, + `azure_tenant_id`, `azure_workspace_resource_id`, `azure_environment`. +- New `auth_type="azure-client-secret"` in `build_auth_config_inner`, requiring + the three mandatory `azure_*` fields (validated with the existing `non_empty` + helper) and forwarding the two optionals. +- Carried on the `OAuthParams`-adjacent path (a small `AzureParams` struct, or + extend `OAuthParams`) to keep the ctor signature tidy. + +### napi (`napi/src/database.rs`, `napi/index.d.ts` by hand) + +- New `AuthMode::AzureClientSecret` variant + `azureClientId` / + `azureClientSecret` / `azureTenantId` / `azureWorkspaceResourceId` / + `azureEnvironment` fields on `ConnectionOptions`. +- New arm in `build_auth_config` calling `AuthConfig::azure_service_principal`. + +### C ABI (`src/c_abi/session.rs`, `include/databricks_kernel.h` by hand) + +- New `AuthSpec::AzureServicePrincipal { ... }` and a setter + `kernel_session_config_set_auth_azure_client_secret(config, azure_client_id, + azure_client_secret, azure_tenant_id, azure_workspace_resource_id /*nullable*/, + azure_environment /*nullable*/)`, mutually exclusive with the other + `set_auth_*` setters (last-wins, as today). Declared in the hand-written + header; exercised in `tests/c/session_smoke.c`. + +Each binding stages its own changelog entry (`pyo3/NEXT_CHANGELOG.md`, +`napi/NEXT_CHANGELOG.md`); the core entry lives in the root `NEXT_CHANGELOG.md`. +`CONNECTION_PARAMETERS.md` documents the new variant + fields. + +## Error handling + +| Scenario | Behavior | +| --- | --- | +| Missing/empty `azure_client_id` / `_secret` / `_tenant_id` | `InvalidArgument` at config construction (binding boundary) | +| Entra token endpoint error (bad creds, 4xx/5xx) | `Unauthenticated` from `get_auth_header()` (same as M2M) | +| Management token fetch fails | surfaced from `extra_headers()` → request fails with `Unauthenticated` (we do not silently drop a header the server may require) | +| Federation exchange fails | existing non-breaking fallback: original AAD token used | +| Unknown `azure_environment` string | `InvalidArgument` at the binding boundary | + +## Testing + +- **Unit (`config.rs`):** constructor rejects missing fields; `Debug` redacts + the secret; `azure_environment` host auto-detection; `AuthConfig::azure_service_principal` + round-trips. +- **Unit (`azure.rs`):** token endpoint / scope / management-scope construction + per environment; `extra_headers()` present only when resource id set. +- **Wiremock integration (`tests/azure_sp_wiremock.rs`):** mock the Entra token + endpoint (inner + management scopes distinguished by request body) and a + workspace API endpoint; assert the outgoing request carries `Authorization: + Bearer `, `X-Databricks-Azure-Workspace-Resource-Id`, and + `X-Databricks-Azure-SP-Management-Token`; assert no extra headers when the + resource id is unset; assert federation exchange interplay (issuer foreign → + exchange attempted, fallback on failure). +- **`AuthProvider::extra_headers` default** covered by an existing provider (PAT) + returning empty, and `FederationProvider` delegating to its inner. +- **Binding boundary:** pyo3 kwarg accepted (+ unknown-kwarg `TypeError` guard); + napi field present on `ConnectionOptions`; C ABI setter records values / rejects + NULL required args + smoke-test line. +- **E2E (`#[ignore]`):** real Azure workspace + SP creds via env vars + (`DATABRICKS_HOST`, `DATABRICKS_AZURE_CLIENT_ID`, `_SECRET`, `_TENANT_ID`, + optional `_WORKSPACE_RESOURCE_ID`). + +## Deltas vs. `databricks-sdk` reference + +- **Same** two-token model, resource id, scope strings, header names, v2.0 + endpoint, and environment table. +- **Kernel-specific:** the sync-trait-over-async bridge (`block_on_in_runtime`) + and `TokenStore` lifecycle reused from the M2M provider rather than the SDK's + refreshable-credentials wrapper; the two headers delivered via the new + `AuthProvider::extra_headers()` seam rather than a per-request `HeaderFactory`. +- **Federation:** the kernel additionally runs its mandatory issuer-gated + exchange on top (a no-op-or-benign round trip on Azure workspaces, and the + required path on non-Azure workspaces) — the SDK sends the AAD token directly. From dda8553835fbbec2c8d0c4d9983e78f6ee7474bb Mon Sep 17 00:00:00 2001 From: eric-wang-1990 Date: Tue, 18 Aug 2026 09:26:42 -0700 Subject: [PATCH 02/47] docs: correct azure-oauth scope boundary and selector name - azure-oauth (U2M) is a distinct AAD-scoped flow tracked by PECOBLR-4120, not plain workspace OIDC; it needs no new kernel flow (connector-side scope synthesis in auth_bridge.py). Corrects the earlier wrong claim that it 'already works' as standard workspace OIDC. - Selector renamed azure-client-secret -> azure-sp-m2m to match the connector's AuthType enum (databricks-sql-python auth/common.py). Co-authored-by: Isaac Signed-off-by: eric-wang-1990 --- ...BLR-4141-azure-service-principal-design.md | 41 ++++++++++++------- 1 file changed, 27 insertions(+), 14 deletions(-) diff --git a/docs/designs/PECOBLR-4141-azure-service-principal-design.md b/docs/designs/PECOBLR-4141-azure-service-principal-design.md index 2840223a..365d416c 100644 --- a/docs/designs/PECOBLR-4141-azure-service-principal-design.md +++ b/docs/designs/PECOBLR-4141-azure-service-principal-design.md @@ -34,11 +34,23 @@ credential strategy including its two Azure-specific request headers. ### What is *not* in scope -- **Azure U2M (`auth_type='azure-oauth'`) already works** and is unchanged. Kernel - U2M runs the standard workspace OIDC browser flow (`{host}/oidc/v1/authorize`); - for an `adb-*.azuredatabricks.net` workspace that federates to Entra - server-side, with no client-side Entra involvement. Confirmed against the - Databricks OAuth U2M docs and the kernel's existing U2M provider. +- **Azure U2M (`auth_type='azure-oauth'`) — tracked separately by PECOBLR-4120, + not this ticket.** It is *not* plain workspace OIDC (an earlier draft of this + doc claimed so — that was wrong). The Thrift-path reference + (`AzureOAuthEndpointCollection`) uses the Azure app client id + `96eecda7-19ea-49cc-abb5-240097d554f5` on redirect port `8030`, and an **AAD + delegated scope** `{app_id}/user_impersonation offline_access` (app_id defaults + to `2ff814a6-…`, overridable via `DATABRICKS_AZURE_TENANT_ID`) — not `sql + offline_access`. Crucially, this needs **no new kernel auth flow**: the kernel + already forwards an arbitrary client id / redirect port / scope verbatim + through the existing `oauth-u2m` provider and discovers endpoints via + `{host}/oidc/…` (which an Azure workspace redirects to Azure AD). The + outstanding work there is **connector-side** — `auth_bridge.py` synthesising + the Azure scope instead of forwarding the literal `sql offline_access` (see + PECOBLR-4120, the Azure analogue of PECOBLR-4040 for `databricks-oauth`). This + design leaves Azure U2M to PECOBLR-4120 and covers only Azure SP **M2M**, whose + token *must* be minted by Entra client-credentials and so genuinely requires a + new kernel flow. - **Azure CLI / MSAL / managed-identity** credential sources. Only the client-secret service-principal flow is in scope (the `azure_*` kwargs the ticket names). @@ -230,31 +242,32 @@ calls). The `X-Databricks-Azure-*` names are not in the reserved set. ## Binding surfaces -Selector name `azure-client-secret` matches the `databricks-sdk` auth-type -string, so the connector maps its detected Azure SP config onto the kernel -verbatim. +Selector name `azure-sp-m2m` matches the connector's own `AuthType` enum value +(`databricks-sql-python` `auth/common.py`: `AZURE_SP_M2M = "azure-sp-m2m"`), so +the connector maps its detected Azure SP config onto the kernel verbatim with no +string translation. ### pyo3 (`pyo3/src/auth.rs`, `pyo3/src/session.rs`) - New `Session(...)` kwargs: `azure_client_id`, `azure_client_secret`, `azure_tenant_id`, `azure_workspace_resource_id`, `azure_environment`. -- New `auth_type="azure-client-secret"` in `build_auth_config_inner`, requiring - the three mandatory `azure_*` fields (validated with the existing `non_empty` +- New `auth_type="azure-sp-m2m"` in `build_auth_config_inner`, requiring the + three mandatory `azure_*` fields (validated with the existing `non_empty` helper) and forwarding the two optionals. - Carried on the `OAuthParams`-adjacent path (a small `AzureParams` struct, or extend `OAuthParams`) to keep the ctor signature tidy. ### napi (`napi/src/database.rs`, `napi/index.d.ts` by hand) -- New `AuthMode::AzureClientSecret` variant + `azureClientId` / - `azureClientSecret` / `azureTenantId` / `azureWorkspaceResourceId` / - `azureEnvironment` fields on `ConnectionOptions`. +- New `AuthMode::AzureSpM2m` variant + `azureClientId` / `azureClientSecret` / + `azureTenantId` / `azureWorkspaceResourceId` / `azureEnvironment` fields on + `ConnectionOptions`. - New arm in `build_auth_config` calling `AuthConfig::azure_service_principal`. ### C ABI (`src/c_abi/session.rs`, `include/databricks_kernel.h` by hand) - New `AuthSpec::AzureServicePrincipal { ... }` and a setter - `kernel_session_config_set_auth_azure_client_secret(config, azure_client_id, + `kernel_session_config_set_auth_azure_sp_m2m(config, azure_client_id, azure_client_secret, azure_tenant_id, azure_workspace_resource_id /*nullable*/, azure_environment /*nullable*/)`, mutually exclusive with the other `set_auth_*` setters (last-wins, as today). Declared in the hand-written From 0469a6e557fd9c4ed51b6cbf4d1296eaa66c9100 Mon Sep 17 00:00:00 2001 From: eric-wang-1990 Date: Tue, 18 Aug 2026 13:33:09 -0700 Subject: [PATCH 03/47] docs: rework Azure auth design to generic-override approach Drop the dedicated AzureServicePrincipal variant, azure.rs provider, AuthProvider::extra_headers() trait extension, and the Azure management token. No SQL connector (Go, Node) uses the management token, and both drive Azure as generic OAuth with Azure values rather than a distinct mode. The kernel stays a cloud-agnostic OAuth engine; Azure M2M and U2M ride the existing OAuthM2M/OAuthU2M flows via the already-present token_url / scope / client_id overrides. Kernel work shrinks to exposing token_url (+ M2M scopes) on the napi and C-ABI bindings (pyo3 already has them), an optional skip-discovery-on- override refinement, and tests/docs. Covers both PECOBLR-4141 (azure-sp-m2m) and PECOBLR-4120 (azure-oauth U2M). Co-authored-by: Isaac Signed-off-by: eric-wang-1990 --- ...BLR-4141-azure-service-principal-design.md | 479 +++++++----------- 1 file changed, 192 insertions(+), 287 deletions(-) diff --git a/docs/designs/PECOBLR-4141-azure-service-principal-design.md b/docs/designs/PECOBLR-4141-azure-service-principal-design.md index 365d416c..7202eff4 100644 --- a/docs/designs/PECOBLR-4141-azure-service-principal-design.md +++ b/docs/designs/PECOBLR-4141-azure-service-principal-design.md @@ -14,310 +14,215 @@ limitations under the License. --> -# Azure Entra ID Service-Principal (M2M) Auth Design — PECOBLR-4141 +# Azure Entra ID OAuth on the kernel via generic overrides — PECOBLR-4141 / PECOBLR-4120 ## Overview -The kernel supports PAT, OAuth M2M (Databricks client credentials), and OAuth -U2M (browser). `databricks-sql-python` users who authenticate with an **Azure -service principal** (`azure_client_id` / `azure_client_secret` / -`azure_tenant_id` / `azure_workspace_resource_id`) cannot yet run on the kernel -path: those credentials are **Microsoft Entra ID (Azure AD) app-registration** -credentials, and the token must be minted by **Entra** -(`login.microsoftonline.com`), not by the workspace OIDC endpoint the existing -M2M provider discovers. - -This design adds a kernel-native **Azure service-principal M2M** flow, forwards -the `azure_*` parameters across all four binding surfaces (Rust core, pyo3, -napi, C ABI), and reaches parity with the `databricks-sdk` `azure-client-secret` -credential strategy including its two Azure-specific request headers. - -### What is *not* in scope - -- **Azure U2M (`auth_type='azure-oauth'`) — tracked separately by PECOBLR-4120, - not this ticket.** It is *not* plain workspace OIDC (an earlier draft of this - doc claimed so — that was wrong). The Thrift-path reference - (`AzureOAuthEndpointCollection`) uses the Azure app client id - `96eecda7-19ea-49cc-abb5-240097d554f5` on redirect port `8030`, and an **AAD - delegated scope** `{app_id}/user_impersonation offline_access` (app_id defaults - to `2ff814a6-…`, overridable via `DATABRICKS_AZURE_TENANT_ID`) — not `sql - offline_access`. Crucially, this needs **no new kernel auth flow**: the kernel - already forwards an arbitrary client id / redirect port / scope verbatim - through the existing `oauth-u2m` provider and discovers endpoints via - `{host}/oidc/…` (which an Azure workspace redirects to Azure AD). The - outstanding work there is **connector-side** — `auth_bridge.py` synthesising - the Azure scope instead of forwarding the literal `sql offline_access` (see - PECOBLR-4120, the Azure analogue of PECOBLR-4040 for `databricks-oauth`). This - design leaves Azure U2M to PECOBLR-4120 and covers only Azure SP **M2M**, whose - token *must* be minted by Entra client-credentials and so genuinely requires a - new kernel flow. -- **Azure CLI / MSAL / managed-identity** credential sources. Only the - client-secret service-principal flow is in scope (the `azure_*` kwargs the - ticket names). - -## Reference wire contract - -Sourced from the Databricks docs -([aad-token-manual](https://learn.microsoft.com/en-us/azure/databricks/dev-tools/auth/aad-token-manual), -[azure-sp](https://learn.microsoft.com/en-us/azure/databricks/dev-tools/auth/azure-sp)) -and `databricks-sdk-py`'s `azure.py` credential strategy — the exact behavior -`databricks-sql-python` inherits today. - -**Inner (Databricks-audience) token — always:** - -``` -POST https://login.microsoftonline.com/{tenant_id}/oauth2/v2.0/token -Content-Type: application/x-www-form-urlencoded - -grant_type = client_credentials -scope = 2ff814a6-3304-4ab8-85cb-cd0e6f879c1d/.default (URL-encoded .../%2F.default) -# client_id + client_secret via HTTP Basic auth -``` - -`2ff814a6-3304-4ab8-85cb-cd0e6f879c1d` is the **Azure Databricks application -id** — a constant across all Azure clouds. The returned token's `aud` is that -id and its `iss` is `https://sts.windows.net/{tenant_id}/`. - -**Management token — only when `azure_workspace_resource_id` is set:** a second -`client_credentials` request to the *same* endpoint with -`scope = https://management.core.windows.net/.default` (Public cloud). - -**Headers attached to Databricks API requests:** - -| Header | Sent when | +`databricks-sql-python` users authenticating to Azure Databricks with either an +**Azure service principal** (M2M — `azure-sp-m2m`) or the **Azure browser flow** +(U2M — `azure-oauth`) must keep working when the connector runs on the kernel +backend. + +**The kernel does not need any Azure-specific auth code.** It already ships a +generic OAuth engine — `OAuthM2M` (client-credentials) and `OAuthU2M` +(authorization-code + PKCE) — whose endpoint, scope, and client-id are all +**overridable**. Azure is expressed by *driving those existing flows with Azure +values*, which the connectors already compute today. The kernel's job is only to +make every binding able to pass those overrides through. + +This supersedes an earlier draft of this doc that proposed a dedicated +`AuthConfig::AzureServicePrincipal` variant, a new provider, an +`AuthProvider::extra_headers()` trait extension, and the Azure +management-token headers. All of that is **dropped** — see +[Why not a dedicated Azure flow](#why-not-a-dedicated-azure-flow). + +## Why the kernel stays generic (evidence) + +The two sibling SQL connectors already treat Azure as *generic OAuth with Azure +values*, not a distinct auth mode, and **neither uses the Azure management +token**: + +- **Go (`databricks-sql-go`)** rolls its own OAuth, workspace-OIDC rooted, with + the cloud inferred from the hostname; its kernel path has no Azure branch at + all. Scope resource `2ff814a6-3304-4ab8-85cb-cd0e6f879c1d`. No + `X-Databricks-Azure-SP-Management-Token`. +- **Node (`databricks-sql-nodejs`)** drives Azure via `openid-client` with scope + `2ff814a6-…/.default` (M2M) / `…/user_impersonation` (U2M). Its **kernel path + explicitly rejects** the Azure-direct options with: *"the workspace-OIDC + discovery path handles Azure workspaces today without these options."* No + management token. +- Only the general-purpose `databricks-sdk` carries the management-token + machinery (`azure.py` `add_sp_management_token()`), for broad control-plane + APIs — **not** the SQL data path (SEA / Thrift warehouse queries), which is all + the kernel serves. + +So the SQL-connector-consistent design is: keep the kernel a cloud-agnostic OAuth +engine; let each connector supply the Azure endpoint / scope / client-id it +already owns. + +## What the kernel already has + +`AuthConfig` (`src/config.rs`) exposes, on both OAuth variants: + +- `OAuthM2M { client_id, client_secret, scopes, token_url_override, identity_federation_client_id }` +- `OAuthU2M { client_id, redirect_ports, scopes, token_url_override, callback_timeout, token_cache, identity_federation_client_id }` + +`token_url_override`, `scopes`, and `client_id` are exactly the knobs Azure +needs. `FederationProvider` already wraps every flow and exchanges +foreign-issuer JWTs (Azure AD tokens included) at `{host}/oidc/v1/token`, +non-breaking. The HTTP client follows redirects by default, so workspace +`/oidc/.well-known/…` discovery transparently follows an Azure workspace's +redirect to Entra. + +## How each Azure mode maps onto the existing flows + +### Azure SP M2M (`azure-sp-m2m`, PECOBLR-4141) + +Connector drives `OAuthM2M` with: + +| Field | Azure value | | --- | --- | -| `Authorization: Bearer ` | always | -| `X-Databricks-Azure-Workspace-Resource-Id: ` | `azure_workspace_resource_id` set | -| `X-Databricks-Azure-SP-Management-Token: ` | `azure_workspace_resource_id` set (management token fetched) | - -The management token + workspace-resource-id headers let the control plane -validate a service principal that has an Azure RBAC role on the workspace but is -not (yet) an explicit workspace member. When `azure_workspace_resource_id` is -unset, only the bearer is sent — the common SQL case where the SP is already a -workspace principal. - -**Azure cloud environments.** Login host and management scope differ by cloud; -the app-id constant does not. Values are pinned from `databricks-sdk-py`'s -`azure.py` `ENVIRONMENTS` table during implementation: - -| Environment | Login host | Management scope | -| --- | --- | --- | -| `PUBLIC` (default) | `https://login.microsoftonline.com` | `https://management.core.windows.net/.default` | -| `USGOVERNMENT` | `https://login.microsoftonline.us` | `https://management.usgovcloudapi.net/.default` | -| `CHINA` | `https://login.chinacloudapi.cn` | `https://management.chinacloudapi.cn/.default` | - -## Key design decisions - -### 1. A dedicated `AuthConfig` variant, not a reuse of `OAuthM2M` - -`OAuthM2M`'s provider discovers the *workspace* token endpoint via OIDC and -requests Databricks scopes. Azure SP needs an Entra token endpoint built from -`{login_host}/{tenant}`, a fixed resource scope, a second (management) token, -and two extra headers. Bolting these onto `OAuthM2M` would tangle two flows and -muddy its config. A new variant keeps each flow's config self-describing — -consistent with the enum's existing `#[non_exhaustive]` note that anticipated -"an Azure-AD service-principal shortcut". - -```rust -AuthConfig::AzureServicePrincipal { - azure_client_id: String, - azure_client_secret: String, - azure_tenant_id: String, - /// Enables the management-token path + both X-Databricks-Azure-* headers. - azure_workspace_resource_id: Option, - /// None ⇒ derive from the workspace host (default PUBLIC). - azure_environment: Option, - /// Carried for uniformity with the other variants; forwarded to the - /// federation wrapper. - identity_federation_client_id: Option, -} -``` - -A validating constructor `AuthConfig::azure_service_principal(...)` rejects -missing/empty `azure_client_id` / `azure_client_secret` / `azure_tenant_id` -(mirroring `oauth_m2m`), and `Debug` redacts the secret. - -### 2. Extend the `AuthProvider` trait for extra headers - -The trait returns only `Authorization` today. The two `X-Databricks-Azure-*` -headers are dynamic (the management token refreshes), so they can't be static -`custom_headers`. Add a default-empty method: - -```rust -pub trait AuthProvider: Send + Sync + Debug { - fn get_auth_header(&self) -> Result; - /// Extra headers to attach alongside `Authorization` on authenticated - /// requests. Default: none. Only the Azure SP provider overrides it. - fn extra_headers(&self) -> Result> { Ok(Vec::new()) } -} -``` - -Every existing provider (PAT / M2M / U2M) inherits the empty default unchanged. -`FederationProvider` **delegates** `extra_headers()` to its inner provider so -the Azure headers survive the wrapper. - -### 3. `FederationProvider` still wraps uniformly - -The Azure inner token's issuer (`sts.windows.net`) is foreign to the workspace -host, so `FederationProvider` will attempt an exchange at `{host}/oidc/v1/token`. -This is **correct and non-breaking** in every case: - -- **Azure workspace:** the exchange endpoint accepts the AAD assertion - (`return_original_token_if_authenticated=true` path) and returns a usable - token. If it ever fails, the existing non-breaking fallback uses the original - AAD token directly — which the Azure workspace natively accepts, *with* the - management headers still attached to the real request. -- **AWS/GCP workspace reached by an Azure SP:** exchange is *required*, and this - is exactly the mechanism that provides it (the management headers are - meaningless there and ignored as unknown `X-` headers). - -Keeping federation uniform avoids special-casing and preserves the "mandatory, -issuer-gated" design. The exchange request itself goes out via -`execute_without_auth` and so does **not** carry the Azure extra headers (they -are attached only to authenticated API requests) — deliberate, since the -assertion authenticates that call. - -### 4. `AzureEnvironment` auto-detected from host, overridable - -`None` ⇒ derive from the workspace host suffix (`.azuredatabricks.net` → -`PUBLIC`, `.databricks.azure.us` → `USGOVERNMENT`, `.databricks.azure.cn` → -`CHINA`; default `PUBLIC`). An explicit value from the caller wins. This mirrors -the SDK, which auto-detects but honors `azure_environment` / -`ARM_ENVIRONMENT`. - -## Module structure - -### `src/auth/oauth/azure.rs` (new) - -`AzureServicePrincipalProvider` implementing `AuthProvider`: - -- Constructor `new(host, azure_client_id, azure_client_secret, azure_tenant_id, - azure_workspace_resource_id, azure_environment, http_client)` (async, captures - the runtime handle like the M2M/U2M providers). -- Builds the Entra token endpoint `{login_host}/{tenant}/oauth2/v2.0/token` from - the resolved environment. -- **Inner token:** a `TokenStore` + `oauth2::BasicClient` client-credentials - exchange with scope `{DATABRICKS_RESOURCE_ID}/.default`, reusing the exact - lifecycle machinery `m2m.rs` uses (fresh/stale/expired, single-flight refresh). -- **Management token:** a *second* `TokenStore` populated only when - `azure_workspace_resource_id` is `Some`, scope - `{management_scope}` for the environment. -- `get_auth_header()` → `Bearer `. -- `extra_headers()` → `X-Databricks-Azure-Workspace-Resource-Id` + - `X-Databricks-Azure-SP-Management-Token` when the resource id is set (each - driven by a `get_or_refresh` on its store). - -Constants (module-private): `DATABRICKS_RESOURCE_ID = -"2ff814a6-3304-4ab8-85cb-cd0e6f879c1d"`, the `ENVIRONMENTS` table. - -### `src/auth/oauth/mod.rs`, `src/auth/mod.rs` - -`pub mod azure;`; re-export `AzureServicePrincipalProvider`. Add the -`extra_headers` default method to the `AuthProvider` trait. - -### `src/auth/oauth/federation.rs` - -Add `fn extra_headers(&self) -> Result> { -self.inner.extra_headers() }` to the `AuthProvider` impl. - -### `src/config.rs` - -New `AuthConfig::AzureServicePrincipal` variant, `AzureEnvironment` enum, -`azure_service_principal(...)` validating constructor, `Debug` redaction of the -secret, and `identity_federation_client_id()` arm. - -### `src/session.rs` - -New arm in `build_base_auth_provider` constructing -`AzureServicePrincipalProvider`. The existing `build_auth_provider` wraps it with -`FederationProvider` unchanged. +| `client_id` / `client_secret` | `azure_client_id` / `azure_client_secret` | +| `token_url_override` | `https://login.microsoftonline.com/{azure_tenant_id}/oauth2/v2.0/token` (per-cloud host) | +| `scopes` | `["2ff814a6-3304-4ab8-85cb-cd0e6f879c1d/.default"]` | -### `src/client/http.rs` - -In the request-build loop, on the `with_auth` branch, after setting -`Authorization`, apply `self.auth_extra_headers()?` (a new method reading the -provider from the `OnceLock` and calling `extra_headers()`). These ride only -authenticated `execute()` requests, never `execute_without_auth` (token/OIDC -calls). The `X-Databricks-Azure-*` names are not in the reserved set. - -## Binding surfaces - -Selector name `azure-sp-m2m` matches the connector's own `AuthType` enum value -(`databricks-sql-python` `auth/common.py`: `AZURE_SP_M2M = "azure-sp-m2m"`), so -the connector maps its detected Azure SP config onto the kernel verbatim with no -string translation. +The `oauth2` crate sends `grant_type=client_credentials` with the client id/secret +via HTTP Basic (which Entra v2.0 accepts) to the override endpoint; the returned +Entra token (audience `2ff814a6-…`, issuer `sts.windows.net/{tenant}`) is used as +the bearer. Its foreign issuer means `FederationProvider` round-trips it through +`{host}/oidc/v1/token` (required when the workspace is *not* Azure; a benign +pass-through when it is). -### pyo3 (`pyo3/src/auth.rs`, `pyo3/src/session.rs`) +### Azure U2M (`azure-oauth`, PECOBLR-4120) -- New `Session(...)` kwargs: `azure_client_id`, `azure_client_secret`, - `azure_tenant_id`, `azure_workspace_resource_id`, `azure_environment`. -- New `auth_type="azure-sp-m2m"` in `build_auth_config_inner`, requiring the - three mandatory `azure_*` fields (validated with the existing `non_empty` - helper) and forwarding the two optionals. -- Carried on the `OAuthParams`-adjacent path (a small `AzureParams` struct, or - extend `OAuthParams`) to keep the ctor signature tidy. +Connector drives `OAuthU2M` with the Azure app client id +`96eecda7-19ea-49cc-abb5-240097d554f5`, `redirect_ports=[8030]`, and scope +`["{app_id}/user_impersonation", "offline_access"]` (`app_id` defaults to +`2ff814a6-…`, overridable via `DATABRICKS_AZURE_TENANT_ID`). Authorization/token +endpoints come from the kernel's existing OIDC discovery against `{host}/oidc/…`, +which the Azure workspace redirects to Entra. + +Note the **kernel-blessed direction for Azure U2M is actually `databricks-oauth`** +(Databricks-native OAuth, which already works on Azure workspaces via +workspace-OIDC and needs *no* Azure values) — this is what the Go and Node kernel +paths use. `azure-oauth` (Entra-direct) is a legacy-compatibility path for callers +who pin it; it costs the kernel nothing beyond the override plumbing below. + +### Static workspace-resource-id header, if ever needed + +`X-Databricks-Azure-Workspace-Resource-Id` is a *static* string, so a connector +that wants it forwards it through the existing custom-headers channel +(pyo3 `http_headers`, napi `customHeaders`, C ABI +`kernel_session_config_set_custom_header`). No kernel change, no new seam. + +## Kernel-repo work (the entire change) + +pyo3 already exposes `token_url` + `oauth_scopes` + `client_id`, so **Python needs +no kernel change** — the work is in the other two bindings plus tests/docs. ### napi (`napi/src/database.rs`, `napi/index.d.ts` by hand) -- New `AuthMode::AzureSpM2m` variant + `azureClientId` / `azureClientSecret` / - `azureTenantId` / `azureWorkspaceResourceId` / `azureEnvironment` fields on - `ConnectionOptions`. -- New arm in `build_auth_config` calling `AuthConfig::azure_service_principal`. +Add an `oauthTokenUrl?: string` field to `ConnectionOptions` and forward it as +`token_url_override` in `build_auth_config` for **both** the `OAuthM2m` and +`OAuthU2m` arms (both currently hardcode `None`). `oauthScopes` / +`oauthClientId` are already forwarded. ### C ABI (`src/c_abi/session.rs`, `include/databricks_kernel.h` by hand) -- New `AuthSpec::AzureServicePrincipal { ... }` and a setter - `kernel_session_config_set_auth_azure_sp_m2m(config, azure_client_id, - azure_client_secret, azure_tenant_id, azure_workspace_resource_id /*nullable*/, - azure_environment /*nullable*/)`, mutually exclusive with the other - `set_auth_*` setters (last-wins, as today). Declared in the hand-written - header; exercised in `tests/c/session_smoke.c`. - -Each binding stages its own changelog entry (`pyo3/NEXT_CHANGELOG.md`, -`napi/NEXT_CHANGELOG.md`); the core entry lives in the root `NEXT_CHANGELOG.md`. -`CONNECTION_PARAMETERS.md` documents the new variant + fields. +- `AuthSpec::OAuthM2M` gains `scopes: Option` and + `token_endpoint: Option`; `set_auth_m2m` takes two more (nullable) + args and threads them into `AuthConfig::oauth_m2m` (currently passes + `None, None`). +- `AuthSpec::OAuthU2M` gains `token_endpoint: Option`; `set_auth_u2m` + takes one more (nullable) arg and threads it into `AuthConfig::oauth_u2m` + (currently `None`). +- Update the hand-written header and `tests/c/session_smoke.c`. + +### Core refinement (optional but recommended) + +In `m2m.rs`, when `token_endpoint_override` is `Some`, **skip OIDC discovery**: +the authorization endpoint is unused by the client-credentials grant, so +discovering it against the workspace is a needless round-trip and a needless +dependency on workspace OIDC for a pure-Entra token endpoint. Synthesize a +placeholder auth URL (unused) instead. U2M still discovers (it needs the +authorize endpoint for the browser step). + +### Docs / changelog + +`CONNECTION_PARAMETERS.md` documents the override knobs as the Azure mechanism +(with a worked `azure-sp-m2m` / `azure-oauth` example). Root + per-binding +`NEXT_CHANGELOG.md` entries. + +## Connector responsibilities (out of this repo, for reference) + +These land in `databricks-sql-python` / `-nodejs` (tracked by PECOBLR-4141 / +-4120 / the Node ticket), not here: + +- **Python `auth_bridge.py`:** for `azure-sp-m2m`, forward `client_id` / + `client_secret` / `token_url` / `scopes` as in the table above; for + `azure-oauth`, synthesise the `{app_id}/user_impersonation offline_access` + scope (the current bug is forwarding literal `sql offline_access`) and the + Azure client id / port. +- **napi consumer (Node):** stop rejecting Azure in the kernel adapter; map its + Azure options onto `oauthTokenUrl` / `oauthScopes` / `oauthClientId`. + +## Why not a dedicated Azure flow + +The earlier draft added `AuthConfig::AzureServicePrincipal`, a provider, an +`extra_headers()` trait method, and the management-token headers. Rejected +because: + +- **No SQL connector uses the management token** (Go and Node confirm), so the + `extra_headers()` seam and the second-token flow it existed for buy nothing on + the SQL data path. Supporting the "Azure RBAC role but not a workspace member" + scenario is a `databricks-sdk` control-plane concern, not a SQL one. +- A dedicated variant forks a **fourth** copy of the Azure constants (app id, + per-cloud hosts, scope format) into the kernel, when the connectors already + own and maintain them. The override approach keeps a single source of truth per + connector and makes the kernel cloud-agnostic (matching Go and Node). +- Smaller, less security-sensitive change: no new provider, no trait change, no + new auth variant. + +If a future non-SQL consumer genuinely needs the management token, revisit then; +the `extra_headers()` design in this doc's git history is the starting point. ## Error handling -| Scenario | Behavior | -| --- | --- | -| Missing/empty `azure_client_id` / `_secret` / `_tenant_id` | `InvalidArgument` at config construction (binding boundary) | -| Entra token endpoint error (bad creds, 4xx/5xx) | `Unauthenticated` from `get_auth_header()` (same as M2M) | -| Management token fetch fails | surfaced from `extra_headers()` → request fails with `Unauthenticated` (we do not silently drop a header the server may require) | -| Federation exchange fails | existing non-breaking fallback: original AAD token used | -| Unknown `azure_environment` string | `InvalidArgument` at the binding boundary | +Unchanged from the existing OAuth flows: bad Entra credentials / endpoint errors +surface as `Unauthenticated` from `get_auth_header()` (M2M) or the browser-flow +error (U2M); a failed federation exchange falls back to the original token +(non-breaking). Missing required fields are rejected at the binding boundary by +the existing `AuthConfig::oauth_m2m` / `oauth_u2m` validating constructors. ## Testing -- **Unit (`config.rs`):** constructor rejects missing fields; `Debug` redacts - the secret; `azure_environment` host auto-detection; `AuthConfig::azure_service_principal` - round-trips. -- **Unit (`azure.rs`):** token endpoint / scope / management-scope construction - per environment; `extra_headers()` present only when resource id set. -- **Wiremock integration (`tests/azure_sp_wiremock.rs`):** mock the Entra token - endpoint (inner + management scopes distinguished by request body) and a - workspace API endpoint; assert the outgoing request carries `Authorization: - Bearer `, `X-Databricks-Azure-Workspace-Resource-Id`, and - `X-Databricks-Azure-SP-Management-Token`; assert no extra headers when the - resource id is unset; assert federation exchange interplay (issuer foreign → - exchange attempted, fallback on failure). -- **`AuthProvider::extra_headers` default** covered by an existing provider (PAT) - returning empty, and `FederationProvider` delegating to its inner. -- **Binding boundary:** pyo3 kwarg accepted (+ unknown-kwarg `TypeError` guard); - napi field present on `ConnectionOptions`; C ABI setter records values / rejects - NULL required args + smoke-test line. -- **E2E (`#[ignore]`):** real Azure workspace + SP creds via env vars - (`DATABRICKS_HOST`, `DATABRICKS_AZURE_CLIENT_ID`, `_SECRET`, `_TENANT_ID`, - optional `_WORKSPACE_RESOURCE_ID`). - -## Deltas vs. `databricks-sdk` reference - -- **Same** two-token model, resource id, scope strings, header names, v2.0 - endpoint, and environment table. -- **Kernel-specific:** the sync-trait-over-async bridge (`block_on_in_runtime`) - and `TokenStore` lifecycle reused from the M2M provider rather than the SDK's - refreshable-credentials wrapper; the two headers delivered via the new - `AuthProvider::extra_headers()` seam rather than a per-request `HeaderFactory`. +- **napi:** `ConnectionOptions.oauthTokenUrl` forwarded to `token_url_override` + for M2M and U2M (unit test on `build_auth_config`); field present in + `index.d.ts`. +- **C ABI:** `set_auth_m2m` scopes + token endpoint and `set_auth_u2m` token + endpoint recorded and threaded (unit tests; NULL-optional handling); smoke-test + line in `tests/c/session_smoke.c`. +- **Wiremock (`tests/azure_oauth_wiremock.rs`):** an Azure-shaped M2M run — mock + an Entra-like token endpoint, drive `OAuthM2M` with `token_url_override` + + `2ff814a6-…/.default` scope, assert the exchange hits the override endpoint + with Basic auth and the right scope, and that the resulting foreign-issuer + token flows through `FederationProvider`. +- **Discovery-follows-redirect:** a wiremock test that OIDC discovery follows a + 302 from `{host}/oidc/.well-known/…` to an Entra-like config host (guards the + PECOBLR-4120 assumption). +- **E2E (`#[ignore]`):** real Azure workspace — `azure-sp-m2m` via env vars + (`DATABRICKS_AZURE_CLIENT_ID` / `_SECRET` / `_TENANT_ID`) driving `oauth-m2m` + with the override; and `databricks-oauth`/`azure-oauth` U2M against an Azure + workspace. +- **Core:** if the skip-discovery-on-override refinement lands, a unit test that + M2M with an override performs no discovery request. + +## Deltas vs. reference + +- **Same** Entra endpoint, `2ff814a6-…` app id, scope strings, and v2.0 endpoint + as `databricks-sdk` / Go / Node — but supplied by the connector, not baked into + the kernel. +- **Dropped** vs. `databricks-sdk`: the management token and its two + `X-Databricks-Azure-*` headers (no SQL connector uses them). - **Federation:** the kernel additionally runs its mandatory issuer-gated - exchange on top (a no-op-or-benign round trip on Azure workspaces, and the - required path on non-Azure workspaces) — the SDK sends the AAD token directly. + exchange on top, as it already does for every OAuth flow. From 01fa5590851224aa3ae61f0bcc41b8ab536f50f3 Mon Sep 17 00:00:00 2001 From: eric-wang-1990 Date: Tue, 18 Aug 2026 14:26:36 -0700 Subject: [PATCH 04/47] docs: answer PR #263 review threads in the reworked design - client_secret_basic IS in Entra v2.0's token_endpoint_auth_methods_supported, so the existing Basic-auth M2M provider works against Azure unchanged. - Cloud/environment is a property of the SP's Azure tenant; the connector builds the full token_url for the right cloud and the kernel uses it verbatim. Co-authored-by: Isaac Signed-off-by: eric-wang-1990 --- ...BLR-4141-azure-service-principal-design.md | 23 ++++++++++++++++--- 1 file changed, 20 insertions(+), 3 deletions(-) diff --git a/docs/designs/PECOBLR-4141-azure-service-principal-design.md b/docs/designs/PECOBLR-4141-azure-service-principal-design.md index 7202eff4..8f0f20e8 100644 --- a/docs/designs/PECOBLR-4141-azure-service-principal-design.md +++ b/docs/designs/PECOBLR-4141-azure-service-principal-design.md @@ -87,12 +87,29 @@ Connector drives `OAuthM2M` with: | `scopes` | `["2ff814a6-3304-4ab8-85cb-cd0e6f879c1d/.default"]` | The `oauth2` crate sends `grant_type=client_credentials` with the client id/secret -via HTTP Basic (which Entra v2.0 accepts) to the override endpoint; the returned -Entra token (audience `2ff814a6-…`, issuer `sts.windows.net/{tenant}`) is used as -the bearer. Its foreign issuer means `FederationProvider` round-trips it through +via HTTP Basic to the override endpoint; the returned Entra token (audience +`2ff814a6-…`, issuer `sts.windows.net/{tenant}`) is used as the bearer. + +> **Credential-transmission style (PR #263 review thread).** A reviewer noted the +> Azure docs *example* uses `client_secret_post` (form body), whereas the kernel's +> `exchange_client_credentials()` sends `client_secret_basic` (HTTP Basic). +> Verified non-blocking: Entra's published +> `token_endpoint_auth_methods_supported` is +> `["client_secret_post","private_key_jwt","client_secret_basic","self_signed_tls_client_auth"]` +> — `client_secret_basic` **is** supported, so no change to the M2M provider's +> credential transmission is required. Its foreign issuer means `FederationProvider` round-trips it through `{host}/oidc/v1/token` (required when the workspace is *not* Azure; a benign pass-through when it is). +> **Cloud/environment ownership (PR #263 review thread).** A reviewer correctly +> noted the Azure cloud (Public / USGov / China → login host) is a property of +> the *SP's Azure tenant*, not the workspace's host, so deriving it from the +> workspace host (as an earlier draft did) is wrong. In the generic-override +> design this is moot for the kernel: the connector builds the full +> `token_url_override` for the correct cloud and the kernel uses it verbatim — +> the kernel never infers an environment. The per-cloud host table lives in each +> connector (`databricks-sdk-py` `azure.py`, etc.). + ### Azure U2M (`azure-oauth`, PECOBLR-4120) Connector drives `OAuthU2M` with the Azure app client id From 3a509e0d5fe605d052b580c63580452d2ec28329 Mon Sep 17 00:00:00 2001 From: eric-wang-1990 Date: Tue, 18 Aug 2026 15:39:32 -0700 Subject: [PATCH 05/47] feat(auth): drive Azure Entra OAuth via generic overrides across bindings MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Azure needs no Azure-specific kernel auth flow: Azure SP M2M and Azure U2M ride the existing OAuthM2M/OAuthU2M flows with the token endpoint, scope, and client id supplied as overrides. This closes the binding gaps that prevented that. - m2m: skip OIDC discovery when a token endpoint override is set (the client-credentials grant never uses the authorization endpoint, so an Azure/Entra token endpoint no longer round-trips or depends on the workspace OIDC config). - C ABI: additive setters set_oauth_token_endpoint + set_oauth_m2m_scopes (config fields applied at build via the extracted, unit-tested auth_spec_to_config); existing set_auth_* signatures unchanged. Header + smoke test updated. - napi: ConnectionOptions.oauthTokenUrl forwarded as token_url_override for M2M and U2M; index.d.ts updated. - pyo3 already exposes token_url + oauth_scopes — no change. - Docs: CONNECTION_PARAMETERS.md Azure section; root + napi changelogs. Tests (TDD, all watched RED first): m2m override skips discovery (wiremock); c_abi m2m/u2m carry scopes + token endpoint; napi forwards oauthTokenUrl. Covers PECOBLR-4141 (azure-sp-m2m) and PECOBLR-4120 (azure-oauth U2M). Co-authored-by: Isaac Signed-off-by: eric-wang-1990 --- CONNECTION_PARAMETERS.md | 23 +++++ NEXT_CHANGELOG.md | 18 ++++ include/databricks_kernel.h | 18 ++++ napi/NEXT_CHANGELOG.md | 4 + napi/index.d.ts | 8 ++ napi/src/database.rs | 54 +++++++++- src/auth/oauth/m2m.rs | 83 ++++++++++++--- src/c_abi/session.rs | 200 ++++++++++++++++++++++++++++++------ tests/c/session_smoke.c | 8 ++ 9 files changed, 371 insertions(+), 45 deletions(-) diff --git a/CONNECTION_PARAMETERS.md b/CONNECTION_PARAMETERS.md index bb9ba706..88299421 100644 --- a/CONNECTION_PARAMETERS.md +++ b/CONNECTION_PARAMETERS.md @@ -61,6 +61,29 @@ An enum; pick one variant. Use the validating constructors | `token_url_override` | Token endpoint override. | OIDC discovery | | `callback_timeout` | How long to wait for the user to complete the browser flow. | `120s` | +**Azure Entra ID (Microsoft Entra) OAuth.** There is no dedicated Azure +variant — Azure rides the generic OAuth flows via the overrides above, with the +connector supplying the Azure endpoint / scope / client id it already owns: + +- **Azure service principal (M2M):** `OAuthM2M` with + `client_id`/`client_secret` = the Entra app credentials, + `token_url_override = https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token` + (per-cloud host), and `scopes = ["2ff814a6-3304-4ab8-85cb-cd0e6f879c1d/.default"]` + (the Azure Databricks application id). Setting a `token_url_override` also + skips workspace OIDC discovery, since the client-credentials grant never uses + the authorization endpoint. +- **Azure U2M (`azure-oauth`):** `OAuthU2M` with the Azure app client id + (`96eecda7-19ea-49cc-abb5-240097d554f5`), the Azure delegated scope + (`{app_id}/user_impersonation offline_access`), and its redirect port; + endpoints come from OIDC discovery, which an Azure workspace redirects to + Entra. (The kernel-native `databricks-oauth` U2M also works on Azure + workspaces with no Azure-specific values.) + +The bindings expose these overrides as: pyo3 `token_url` / `oauth_scopes` / +`client_id`; napi `oauthTokenUrl` / `oauthScopes` / `oauthClientId`; C ABI +`kernel_session_config_set_oauth_token_endpoint` / +`kernel_session_config_set_oauth_m2m_scopes` (+ the `set_auth_*` setters). + Two further variants are reserved but not usable in v0: `OAuthFederation` (RFC 8693 token exchange — returns `InvalidArgument` until implemented) and `External` (a caller-supplied `TokenProvider`). diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index e1369625..73a669e3 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -11,6 +11,24 @@ changes go in their respective binding's NEXT_CHANGELOG. ### Added +- Azure Entra ID OAuth support via generic overrides (no dedicated Azure auth + flow). Azure service-principal M2M rides `OAuthM2M` with an Entra + `token_url_override` + the `2ff814a6-…/.default` scope; Azure U2M rides + `OAuthU2M`. New C ABI setters expose the pieces the C surface was missing: + `kernel_session_config_set_oauth_token_endpoint()` (applied as + `token_url_override` to the selected OAuth mode) and + `kernel_session_config_set_oauth_m2m_scopes()` (M2M scopes). Both are additive + — existing `set_auth_m2m` / `set_auth_u2m` signatures are unchanged. + (PECOBLR-4141 / PECOBLR-4120.) + +### Changed + +- OAuth M2M: when a `token_url_override` is set, OIDC discovery against the + workspace is now **skipped** — the client-credentials grant never uses the + authorization endpoint, so pinning the token endpoint (e.g. an Azure/Entra + endpoint that is not the workspace's) no longer makes a needless round-trip + to, or depends on, the workspace OIDC config. + - 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/include/databricks_kernel.h b/include/databricks_kernel.h index eed49269..673928e5 100644 --- a/include/databricks_kernel.h +++ b/include/databricks_kernel.h @@ -255,6 +255,24 @@ KernelStatusCode kernel_session_config_set_identity_federation_client_id(KernelSessionConfig* config, const char* client_id); +/* Optional OAuth token-endpoint override, applied to whichever OAuth mode + * (M2M or U2M) is selected. Points the token exchange at a non-workspace + * endpoint — e.g. the Azure/Entra token endpoint + * `https://login.microsoftonline.com//oauth2/v2.0/token` for an Azure + * service principal. Unset → OIDC discovery against the workspace host. + * No effect on PAT auth. */ +KernelStatusCode +kernel_session_config_set_oauth_token_endpoint(KernelSessionConfig* config, + const char* token_endpoint); + +/* Optional OAuth M2M scopes (comma-separated), e.g. + * `2ff814a6-3304-4ab8-85cb-cd0e6f879c1d/.default` for an Azure service + * principal. Unset → kernel default (`all-apis`). Affects M2M only; U2M scopes + * are set via kernel_session_config_set_auth_u2m. */ +KernelStatusCode +kernel_session_config_set_oauth_m2m_scopes(KernelSessionConfig* config, + const char* scopes); + /* Add (or overwrite) one session-conf entry. Keys are normally server SET * parameters forwarded on the SEA wire (allowlist-filtered). A small set of * reserved keys are instead CLIENT-ONLY: they tune the kernel locally, are diff --git a/napi/NEXT_CHANGELOG.md b/napi/NEXT_CHANGELOG.md index c849058e..79f58ffa 100644 --- a/napi/NEXT_CHANGELOG.md +++ b/napi/NEXT_CHANGELOG.md @@ -14,6 +14,10 @@ layout, or npm publishing. Pure-kernel changes go in the root ### Added +- `ConnectionOptions.oauthTokenUrl` — OAuth token-endpoint override, forwarded + as `token_url_override` for both M2M and U2M. Lets a Node caller point the + token exchange at a non-workspace endpoint (e.g. the Azure/Entra token + endpoint for an Azure service principal). (PECOBLR-4141.) - `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..60417523 100644 --- a/napi/index.d.ts +++ b/napi/index.d.ts @@ -205,6 +205,14 @@ export interface ConnectionOptions { * (`["all-apis"]` for M2M; `["sql", "offline_access"]` for U2M). */ oauthScopes?: Array + /** + * OAuth token-endpoint override (M2M / U2M). Points the token exchange at a + * non-workspace endpoint — e.g. the Azure/Entra token endpoint + * `https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token` for an Azure + * service principal. Omitted ⇒ OIDC discovery against the workspace host. + * Ignored for `Pat`. + */ + oauthTokenUrl?: 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..27b1da36 100644 --- a/napi/src/database.rs +++ b/napi/src/database.rs @@ -157,6 +157,12 @@ pub struct ConnectionOptions { /// OAuth scopes override (M2M / U2M). Omitted ⇒ kernel defaults /// (`["all-apis"]` for M2M; `["sql", "offline_access"]` for U2M). pub oauth_scopes: Option>, + /// OAuth token-endpoint override (M2M / U2M). Points the token exchange + /// at a non-workspace endpoint — e.g. the Azure/Entra token endpoint + /// `https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token` for an + /// Azure service principal. Omitted ⇒ OIDC discovery against the workspace + /// host. Ignored for [`AuthMode::Pat`]. + pub oauth_token_url: 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, @@ -346,7 +352,7 @@ fn build_auth_config(options: &ConnectionOptions) -> napi::Result { options.oauth_client_id.clone(), options.oauth_client_secret.clone(), options.oauth_scopes.clone(), - None, + options.oauth_token_url.clone(), options.identity_federation_client_id.clone(), ) .map_err(napi_err_from_kernel), @@ -378,7 +384,7 @@ fn build_auth_config(options: &ConnectionOptions) -> napi::Result { .filter(|&p| p != 0) .map(|p| vec![p]), options.oauth_scopes.clone(), - None, + options.oauth_token_url.clone(), None, // `None` takes the kernel default: on-disk cache enabled, // encrypted under a machine-local derived key since this @@ -603,6 +609,7 @@ mod tests { oauth_client_secret: None, oauth_redirect_port: None, oauth_scopes: None, + oauth_token_url: None, identity_federation_client_id: None, catalog: None, schema: None, @@ -689,6 +696,49 @@ mod tests { } } + #[test] + fn oauth_token_url_forwards_as_token_url_override() { + // `oauthTokenUrl` must reach the built AuthConfig as + // `token_url_override` for BOTH M2M and U2M, so a Node caller can point + // the token exchange at an Azure/Entra endpoint. Omitting it leaves the + // override `None` (kernel OIDC discovery). + let endpoint = "https://login.microsoftonline.com/tenant/oauth2/v2.0/token"; + + let mut m2m = base(); + m2m.auth_mode = Some(AuthMode::OAuthM2m); + m2m.oauth_client_id = Some("cid".to_owned()); + m2m.oauth_client_secret = Some("sec".to_owned()); + m2m.oauth_token_url = Some(endpoint.to_owned()); + match build_auth_config(&m2m).unwrap() { + AuthConfig::OAuthM2M { + token_url_override, .. + } => assert_eq!(token_url_override.as_deref(), Some(endpoint)), + other => panic!("expected OAuthM2M, got {other:?}"), + } + + let mut u2m = base(); + u2m.auth_mode = Some(AuthMode::OAuthU2m); + u2m.oauth_token_url = Some(endpoint.to_owned()); + match build_auth_config(&u2m).unwrap() { + AuthConfig::OAuthU2M { + token_url_override, .. + } => assert_eq!(token_url_override.as_deref(), Some(endpoint)), + other => panic!("expected OAuthU2M, got {other:?}"), + } + + // Omitted → None (default OIDC discovery). + let mut none = base(); + none.auth_mode = Some(AuthMode::OAuthM2m); + none.oauth_client_id = Some("cid".to_owned()); + none.oauth_client_secret = Some("sec".to_owned()); + match build_auth_config(&none).unwrap() { + AuthConfig::OAuthM2M { + token_url_override, .. + } => assert!(token_url_override.is_none()), + other => panic!("expected OAuthM2M, got {other:?}"), + } + } + #[test] fn m2m_requires_client_id_and_secret() { let mut o = base(); diff --git a/src/auth/oauth/m2m.rs b/src/auth/oauth/m2m.rs index 5f68a795..0dd22bfe 100644 --- a/src/auth/oauth/m2m.rs +++ b/src/auth/oauth/m2m.rs @@ -194,17 +194,20 @@ impl ClientCredentialsProvider { scopes: Vec, token_endpoint_override: Option, ) -> Result { - // Discover OIDC endpoints or use override - let (token_endpoint, auth_endpoint) = if let Some(token_endpoint) = token_endpoint_override - { - // Use override for token endpoint, still discover auth endpoint - // (auth endpoint is not typically overridden for M2M since it's not used) - let endpoints = OidcEndpoints::discover(host, &http_client).await?; - (token_endpoint, endpoints.authorization_endpoint) - } else { - // Discover both endpoints via OIDC - let endpoints = OidcEndpoints::discover(host, &http_client).await?; - (endpoints.token_endpoint, endpoints.authorization_endpoint) + // Discover OIDC endpoints, or skip discovery entirely when the token + // endpoint is overridden. The client-credentials grant never uses the + // authorization endpoint, so when a caller pins the token endpoint + // (e.g. an Azure/Entra endpoint, which is NOT the workspace's) there is + // no reason to round-trip the workspace OIDC config — and doing so + // would needlessly depend on it being reachable and describing the + // right issuer. Reuse the token endpoint as the (unused) auth URL + // placeholder so the `oauth2` client still constructs. + let (token_endpoint, auth_endpoint) = match token_endpoint_override { + Some(token_endpoint) => (token_endpoint.clone(), token_endpoint), + None => { + let endpoints = OidcEndpoints::discover(host, &http_client).await?; + (endpoints.token_endpoint, endpoints.authorization_endpoint) + } }; Ok(Self { @@ -326,7 +329,7 @@ mod tests { use crate::client::http::HttpClientConfig; use crate::client::retry::{build_retry_configs, RetryConfig}; use std::collections::HashMap; - use wiremock::matchers::{header, method, path}; + use wiremock::matchers::{body_string_contains, header, method, path}; use wiremock::{Mock, MockServer, ResponseTemplate}; /// Helper to create a mock OIDC discovery response @@ -678,4 +681,60 @@ mod tests { assert_eq!(auth_header, "Bearer test-token-custom-scopes"); } + + #[tokio::test(flavor = "multi_thread")] + async fn test_m2m_override_skips_discovery() { + // When a token-endpoint override is set (e.g. an Azure/Entra endpoint, + // which is NOT the workspace's), the client-credentials grant never + // uses the authorization endpoint, so OIDC discovery against the + // workspace must be skipped entirely — no needless round-trip, and no + // dependency on the workspace OIDC config describing the right issuer. + let mock_server = MockServer::start().await; + + // Discovery must NOT be hit. + 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", mock_server.uri()), + "token_endpoint": format!("{}/oidc/v1/token", mock_server.uri()), + }))) + .expect(0) + .mount(&mock_server) + .await; + + // The exchange lands on the override endpoint with the configured + // (Azure resource) scope, via HTTP Basic. + Mock::given(method("POST")) + .and(path("/azure/tenant/oauth2/v2.0/token")) + .and(body_string_contains("grant_type=client_credentials")) + .and(body_string_contains("2ff814a6")) + .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "access_token": "azure-access-token", + "token_type": "Bearer", + "expires_in": 3600, + }))) + .expect(1) + .mount(&mock_server) + .await; + + let http_client = Arc::new( + DatabricksHttpClient::with_default_retry(HttpClientConfig::default()) + .expect("Failed to create HTTP client"), + ); + + let token_endpoint = format!("{}/azure/tenant/oauth2/v2.0/token", mock_server.uri()); + let provider = ClientCredentialsProvider::new_with_full_config( + &mock_server.uri(), + "azure-client-id", + "azure-client-secret", + http_client, + vec!["2ff814a6-3304-4ab8-85cb-cd0e6f879c1d/.default".to_string()], + Some(token_endpoint), + ) + .await + .expect("provider creation must not require discovery when overridden"); + + let auth_header = provider.get_auth_header().expect("get auth header"); + assert_eq!(auth_header, "Bearer azure-access-token"); + } } diff --git a/src/c_abi/session.rs b/src/c_abi/session.rs index 28fd4e8a..8dac113a 100644 --- a/src/c_abi/session.rs +++ b/src/c_abi/session.rs @@ -114,6 +114,18 @@ pub struct KernelSessionConfig { ignore_transactions: bool, /// SP-wide WIF client id applied to the selected auth mode. identity_federation_client_id: Option, + /// OAuth token-endpoint override (populated by + /// `kernel_session_config_set_oauth_token_endpoint`). Applied as + /// `token_url_override` to the selected OAuth mode (M2M or U2M) at build + /// time; lets a host point the token exchange at a non-workspace endpoint + /// (e.g. an Azure/Entra token endpoint for an Azure service principal). + /// `None` ⇒ OIDC discovery against the workspace host. + oauth_token_endpoint: Option, + /// Comma-separated OAuth **M2M** scopes override (populated by + /// `kernel_session_config_set_oauth_m2m_scopes`, split at build time). + /// `None` ⇒ kernel default (`all-apis`). U2M scopes are set via + /// `kernel_session_config_set_auth_u2m` instead. + oauth_m2m_scopes: Option, /// On-disk U2M token-cache policy (populated by /// `kernel_session_config_set_u2m_token_cache_config`). Defaults to enabled with /// no passphrase, in which case the cache is encrypted under a @@ -206,6 +218,8 @@ pub unsafe extern "C" fn kernel_session_config_new( // Default to ignoring transactions, matching IgnoreTransactions=1. ignore_transactions: true, identity_federation_client_id: None, + oauth_token_endpoint: None, + oauth_m2m_scopes: None, // Match the reference driver's / JDBC's EnableTokenCache=1. token_cache: TokenCacheConfig::default(), // Kernel result defaults (CloudFetch enabled, Arrow-native types). @@ -368,6 +382,45 @@ pub unsafe extern "C" fn kernel_session_config_set_identity_federation_client_id }) } +/// Set an OAuth token-endpoint override, applied as `token_url_override` to +/// whichever OAuth mode (M2M or U2M) is selected. Lets a host point the token +/// exchange at a non-workspace endpoint — e.g. the Azure/Entra token endpoint +/// `https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token` for an Azure +/// service principal. Leaving it unset uses OIDC discovery against the +/// workspace host. No-op for PAT auth. +/// +/// # Safety +/// `config` must be live and `token_endpoint` must be a NUL-terminated C string. +#[no_mangle] +pub unsafe extern "C" fn kernel_session_config_set_oauth_token_endpoint( + config: *mut KernelSessionConfig, + token_endpoint: *const c_char, +) -> KernelStatusCode { + set_on_config(config, |c| { + c.oauth_token_endpoint = Some(required_str(token_endpoint, "token_endpoint")?); + Ok(()) + }) +} + +/// Set the OAuth **M2M** scopes (comma-separated; split at build time) — e.g. +/// `2ff814a6-3304-4ab8-85cb-cd0e6f879c1d/.default` for an Azure service +/// principal. Leaving it unset uses the kernel default (`all-apis`). U2M scopes +/// are set via [`kernel_session_config_set_auth_u2m`] instead; this setter only +/// affects M2M auth. +/// +/// # Safety +/// `config` must be live and `scopes` must be a NUL-terminated C string. +#[no_mangle] +pub unsafe extern "C" fn kernel_session_config_set_oauth_m2m_scopes( + config: *mut KernelSessionConfig, + scopes: *const c_char, +) -> KernelStatusCode { + set_on_config(config, |c| { + c.oauth_m2m_scopes = Some(required_str(scopes, "scopes")?); + Ok(()) + }) +} + /// Append one HTTP header sent on every request (e.g. a partner-supplied /// `X-…` header). Call once per header; order is preserved. Both `name` /// and `value` are required. Maps to the kernel's `custom_headers`. @@ -903,6 +956,53 @@ fn merge_http_config( http } +/// Assemble the kernel [`AuthConfig`] from the C-side [`AuthSpec`] plus the +/// cross-cutting OAuth overrides captured by the additive setters +/// (`set_oauth_token_endpoint` / `set_oauth_m2m_scopes`). Pure (no I/O), so the +/// wiring is unit-testable without opening a session. +/// +/// `oauth_token_endpoint` becomes `token_url_override` on whichever OAuth mode +/// is selected (M2M or U2M); `oauth_m2m_scopes` supplies the M2M scopes (U2M +/// scopes arrive on the `AuthSpec::OAuthU2M` itself). Both are ignored for PAT. +fn auth_spec_to_config( + auth: AuthSpec, + oauth_token_endpoint: Option, + oauth_m2m_scopes: Option, + identity_federation_client_id: Option, + token_cache: TokenCacheConfig, +) -> crate::kernel_error::Result { + let auth = match auth { + AuthSpec::Pat { token } => AuthConfig::pat(Some(token), identity_federation_client_id)?, + AuthSpec::OAuthM2M { + client_id, + client_secret, + } => AuthConfig::oauth_m2m( + Some(client_id), + Some(client_secret), + oauth_m2m_scopes.and_then(|s| parse_scopes(&s)), + oauth_token_endpoint, + identity_federation_client_id, + )?, + AuthSpec::OAuthU2M { + client_id, + redirect_port, + scopes, + } => AuthConfig::oauth_u2m( + client_id, + // The C ABI exposes a single redirect port; forward it as a + // one-element candidate list (the kernel binds the first free + // port, trivially that one). Keeps the FFI unchanged. + redirect_port.map(|p| vec![p]), + scopes.and_then(|s| parse_scopes(&s)), + oauth_token_endpoint, + None, + Some(token_cache), + identity_federation_client_id, + ), + }; + Ok(auth) +} + /// Translate the C-side config into a [`Session`], driving the async /// `Session::open` on the process-wide runtime. Errors are stored in the /// thread-local buffer; the returned `KernelStatusCode` is the mapped @@ -918,6 +1018,8 @@ fn build_session(config: KernelSessionConfig) -> Result Result { - AuthConfig::pat(Some(token), identity_federation_client_id)? - } - AuthSpec::OAuthM2M { - client_id, - client_secret, - } => AuthConfig::oauth_m2m( - Some(client_id), - Some(client_secret), - None, - None, - identity_federation_client_id, - )?, - AuthSpec::OAuthU2M { - client_id, - redirect_port, - scopes, - } => AuthConfig::oauth_u2m( - client_id, - // The C ABI exposes a single redirect port; forward it as a - // one-element candidate list (the kernel binds the first - // free port, trivially that one). Keeps the FFI unchanged. - redirect_port.map(|p| vec![p]), - scopes.and_then(|s| parse_scopes(&s)), - None, - None, - Some(token_cache), - identity_federation_client_id, - ), - }; + let auth = auth_spec_to_config( + auth, + oauth_token_endpoint, + oauth_m2m_scopes, + identity_federation_client_id, + token_cache, + )?; let mut builder = Session::builder() .connection(connection) @@ -1235,6 +1313,66 @@ mod tests { use super::*; use std::ffi::CString; + #[test] + fn m2m_carries_scopes_and_token_endpoint_override() { + // The additive setters must reach the built AuthConfig so an Azure SP + // M2M config can point the client-credentials exchange at the Entra + // token endpoint with the Azure resource scope. + let token_endpoint = "https://login.microsoftonline.com/tenant/oauth2/v2.0/token"; + let auth = auth_spec_to_config( + AuthSpec::OAuthM2M { + client_id: "azure-client-id".to_string(), + client_secret: "azure-client-secret".to_string(), + }, + Some(token_endpoint.to_string()), + Some("2ff814a6-3304-4ab8-85cb-cd0e6f879c1d/.default".to_string()), + None, + TokenCacheConfig::default(), + ) + .expect("m2m config builds"); + + match auth { + AuthConfig::OAuthM2M { + scopes, + token_url_override, + .. + } => { + assert_eq!( + scopes, + Some(vec![ + "2ff814a6-3304-4ab8-85cb-cd0e6f879c1d/.default".to_string() + ]) + ); + assert_eq!(token_url_override.as_deref(), Some(token_endpoint)); + } + other => panic!("expected OAuthM2M, got {other:?}"), + } + } + + #[test] + fn u2m_carries_token_endpoint_override() { + let token_endpoint = "https://login.microsoftonline.com/tenant/oauth2/v2.0/token"; + let auth = auth_spec_to_config( + AuthSpec::OAuthU2M { + client_id: None, + redirect_port: None, + scopes: None, + }, + Some(token_endpoint.to_string()), + None, + None, + TokenCacheConfig::default(), + ) + .expect("u2m config builds"); + + match auth { + AuthConfig::OAuthU2M { + token_url_override, .. + } => assert_eq!(token_url_override.as_deref(), Some(token_endpoint)), + other => panic!("expected OAuthU2M, got {other:?}"), + } + } + #[test] fn parse_scopes_trims_and_drops_empties() { assert_eq!( diff --git a/tests/c/session_smoke.c b/tests/c/session_smoke.c index a02d14bc..5f7ef3e7 100644 --- a/tests/c/session_smoke.c +++ b/tests/c/session_smoke.c @@ -135,6 +135,14 @@ static void test_http_path_and_m2m_setters(void) { CHECK(rc == KernelStatusCode_Success, "set_http_path succeeds"); rc = kernel_session_config_set_auth_m2m(config, "client-id", "client-secret"); CHECK(rc == KernelStatusCode_Success, "set_auth_m2m succeeds"); + /* Azure SP M2M rides generic M2M: point the token exchange at the Entra + * endpoint and request the Azure Databricks resource scope. */ + rc = kernel_session_config_set_oauth_token_endpoint( + config, "https://login.microsoftonline.com/tenant/oauth2/v2.0/token"); + CHECK(rc == KernelStatusCode_Success, "set_oauth_token_endpoint succeeds"); + rc = kernel_session_config_set_oauth_m2m_scopes( + config, "2ff814a6-3304-4ab8-85cb-cd0e6f879c1d/.default"); + CHECK(rc == KernelStatusCode_Success, "set_oauth_m2m_scopes succeeds"); kernel_session_config_free(config); } From 8d99e8c2f74d231871b21b1219663dd61c42e152 Mon Sep 17 00:00:00 2001 From: eric-wang-1990 Date: Tue, 18 Aug 2026 17:07:14 -0700 Subject: [PATCH 06/47] refactor(c-abi): unify OAuth scopes into one shared set_oauth_scopes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Replace set_oauth_m2m_scopes with a generic set_oauth_scopes applied to whichever OAuth mode (M2M or U2M) is selected — matching the single oauth_scopes the pyo3 and napi bindings already share across both flows (and the already-generic set_oauth_token_endpoint). The earlier M2M-only setter was an asymmetry: U2M scopes came from set_auth_u2m while M2M needed a separate setter. For U2M the shared setter takes precedence over scopes passed positionally to set_auth_u2m (kept for back-compat). Header + smoke test + docs updated; added tests that the setter is shared and that it overrides the U2M positional scopes. Co-authored-by: Isaac Signed-off-by: eric-wang-1990 --- CONNECTION_PARAMETERS.md | 2 +- NEXT_CHANGELOG.md | 12 ++-- include/databricks_kernel.h | 13 ++-- src/c_abi/session.rs | 118 +++++++++++++++++++++++++++++------- tests/c/session_smoke.c | 4 +- 5 files changed, 115 insertions(+), 34 deletions(-) diff --git a/CONNECTION_PARAMETERS.md b/CONNECTION_PARAMETERS.md index 88299421..091fcd9e 100644 --- a/CONNECTION_PARAMETERS.md +++ b/CONNECTION_PARAMETERS.md @@ -82,7 +82,7 @@ connector supplying the Azure endpoint / scope / client id it already owns: The bindings expose these overrides as: pyo3 `token_url` / `oauth_scopes` / `client_id`; napi `oauthTokenUrl` / `oauthScopes` / `oauthClientId`; C ABI `kernel_session_config_set_oauth_token_endpoint` / -`kernel_session_config_set_oauth_m2m_scopes` (+ the `set_auth_*` setters). +`kernel_session_config_set_oauth_scopes` (+ the `set_auth_*` setters). Two further variants are reserved but not usable in v0: `OAuthFederation` (RFC 8693 token exchange — returns `InvalidArgument` diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index 73a669e3..ad64058a 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -15,11 +15,13 @@ changes go in their respective binding's NEXT_CHANGELOG. flow). Azure service-principal M2M rides `OAuthM2M` with an Entra `token_url_override` + the `2ff814a6-…/.default` scope; Azure U2M rides `OAuthU2M`. New C ABI setters expose the pieces the C surface was missing: - `kernel_session_config_set_oauth_token_endpoint()` (applied as - `token_url_override` to the selected OAuth mode) and - `kernel_session_config_set_oauth_m2m_scopes()` (M2M scopes). Both are additive - — existing `set_auth_m2m` / `set_auth_u2m` signatures are unchanged. - (PECOBLR-4141 / PECOBLR-4120.) + `kernel_session_config_set_oauth_token_endpoint()` and + `kernel_session_config_set_oauth_scopes()` — both applied to whichever OAuth + mode (M2M or U2M) is selected, matching the single `oauth_scopes` / + `token_url` the pyo3 and napi bindings already share across both flows. Both + are additive — existing `set_auth_m2m` / `set_auth_u2m` signatures are + unchanged (for U2M, `set_oauth_scopes` takes precedence over scopes passed + positionally to `set_auth_u2m`). (PECOBLR-4141 / PECOBLR-4120.) ### Changed diff --git a/include/databricks_kernel.h b/include/databricks_kernel.h index 673928e5..9d4b08f5 100644 --- a/include/databricks_kernel.h +++ b/include/databricks_kernel.h @@ -265,13 +265,16 @@ KernelStatusCode kernel_session_config_set_oauth_token_endpoint(KernelSessionConfig* config, const char* token_endpoint); -/* Optional OAuth M2M scopes (comma-separated), e.g. +/* Optional OAuth scopes (comma-separated), applied to whichever OAuth mode + * (M2M or U2M) is selected — e.g. * `2ff814a6-3304-4ab8-85cb-cd0e6f879c1d/.default` for an Azure service - * principal. Unset → kernel default (`all-apis`). Affects M2M only; U2M scopes - * are set via kernel_session_config_set_auth_u2m. */ + * principal (M2M), or `sql,offline_access` (U2M). Mirrors the single + * `oauth_scopes` the pyo3 / napi bindings expose across both flows. Unset → + * kernel per-mode default (`all-apis` for M2M; `sql offline_access` for U2M). + * For U2M it overrides any scopes passed to kernel_session_config_set_auth_u2m. */ KernelStatusCode -kernel_session_config_set_oauth_m2m_scopes(KernelSessionConfig* config, - const char* scopes); +kernel_session_config_set_oauth_scopes(KernelSessionConfig* config, + const char* scopes); /* Add (or overwrite) one session-conf entry. Keys are normally server SET * parameters forwarded on the SEA wire (allowlist-filtered). A small set of diff --git a/src/c_abi/session.rs b/src/c_abi/session.rs index 8dac113a..4b1cfc67 100644 --- a/src/c_abi/session.rs +++ b/src/c_abi/session.rs @@ -121,11 +121,14 @@ pub struct KernelSessionConfig { /// (e.g. an Azure/Entra token endpoint for an Azure service principal). /// `None` ⇒ OIDC discovery against the workspace host. oauth_token_endpoint: Option, - /// Comma-separated OAuth **M2M** scopes override (populated by - /// `kernel_session_config_set_oauth_m2m_scopes`, split at build time). - /// `None` ⇒ kernel default (`all-apis`). U2M scopes are set via - /// `kernel_session_config_set_auth_u2m` instead. - oauth_m2m_scopes: Option, + /// Comma-separated OAuth scopes override (populated by + /// `kernel_session_config_set_oauth_scopes`, split at build time), applied + /// to whichever OAuth mode (M2M or U2M) is selected — matching the single + /// `oauth_scopes` the pyo3 / napi bindings expose across both flows. `None` + /// ⇒ kernel per-mode default (`all-apis` for M2M; `sql offline_access` for + /// U2M). For U2M it takes precedence over scopes passed positionally to + /// `kernel_session_config_set_auth_u2m`. + oauth_scopes: Option, /// On-disk U2M token-cache policy (populated by /// `kernel_session_config_set_u2m_token_cache_config`). Defaults to enabled with /// no passphrase, in which case the cache is encrypted under a @@ -219,7 +222,7 @@ pub unsafe extern "C" fn kernel_session_config_new( ignore_transactions: true, identity_federation_client_id: None, oauth_token_endpoint: None, - oauth_m2m_scopes: None, + oauth_scopes: None, // Match the reference driver's / JDBC's EnableTokenCache=1. token_cache: TokenCacheConfig::default(), // Kernel result defaults (CloudFetch enabled, Arrow-native types). @@ -402,21 +405,24 @@ pub unsafe extern "C" fn kernel_session_config_set_oauth_token_endpoint( }) } -/// Set the OAuth **M2M** scopes (comma-separated; split at build time) — e.g. +/// Set the OAuth scopes (comma-separated; split at build time), applied to +/// whichever OAuth mode (M2M or U2M) is selected — e.g. /// `2ff814a6-3304-4ab8-85cb-cd0e6f879c1d/.default` for an Azure service -/// principal. Leaving it unset uses the kernel default (`all-apis`). U2M scopes -/// are set via [`kernel_session_config_set_auth_u2m`] instead; this setter only -/// affects M2M auth. +/// principal (M2M) or `sql,offline_access` (U2M). Mirrors the single +/// `oauth_scopes` the pyo3 / napi bindings expose across both flows. Leaving it +/// unset uses the kernel's per-mode default (`all-apis` for M2M; `sql +/// offline_access` for U2M). For U2M it takes precedence over any scopes passed +/// positionally to [`kernel_session_config_set_auth_u2m`]. /// /// # Safety /// `config` must be live and `scopes` must be a NUL-terminated C string. #[no_mangle] -pub unsafe extern "C" fn kernel_session_config_set_oauth_m2m_scopes( +pub unsafe extern "C" fn kernel_session_config_set_oauth_scopes( config: *mut KernelSessionConfig, scopes: *const c_char, ) -> KernelStatusCode { set_on_config(config, |c| { - c.oauth_m2m_scopes = Some(required_str(scopes, "scopes")?); + c.oauth_scopes = Some(required_str(scopes, "scopes")?); Ok(()) }) } @@ -958,16 +964,19 @@ fn merge_http_config( /// Assemble the kernel [`AuthConfig`] from the C-side [`AuthSpec`] plus the /// cross-cutting OAuth overrides captured by the additive setters -/// (`set_oauth_token_endpoint` / `set_oauth_m2m_scopes`). Pure (no I/O), so the +/// (`set_oauth_token_endpoint` / `set_oauth_scopes`). Pure (no I/O), so the /// wiring is unit-testable without opening a session. /// -/// `oauth_token_endpoint` becomes `token_url_override` on whichever OAuth mode -/// is selected (M2M or U2M); `oauth_m2m_scopes` supplies the M2M scopes (U2M -/// scopes arrive on the `AuthSpec::OAuthU2M` itself). Both are ignored for PAT. +/// `oauth_token_endpoint` and `oauth_scopes` both apply to whichever OAuth mode +/// is selected (M2M or U2M) — a single config carries exactly one mode, so one +/// shared knob each is unambiguous (matching the pyo3 / napi bindings, which +/// expose one `oauth_scopes` across both flows). For U2M, `oauth_scopes` takes +/// precedence over any scopes passed positionally to `set_auth_u2m` (kept for +/// back-compat). Both are ignored for PAT. fn auth_spec_to_config( auth: AuthSpec, oauth_token_endpoint: Option, - oauth_m2m_scopes: Option, + oauth_scopes: Option, identity_federation_client_id: Option, token_cache: TokenCacheConfig, ) -> crate::kernel_error::Result { @@ -979,7 +988,7 @@ fn auth_spec_to_config( } => AuthConfig::oauth_m2m( Some(client_id), Some(client_secret), - oauth_m2m_scopes.and_then(|s| parse_scopes(&s)), + oauth_scopes.and_then(|s| parse_scopes(&s)), oauth_token_endpoint, identity_federation_client_id, )?, @@ -993,7 +1002,9 @@ fn auth_spec_to_config( // one-element candidate list (the kernel binds the first free // port, trivially that one). Keeps the FFI unchanged. redirect_port.map(|p| vec![p]), - scopes.and_then(|s| parse_scopes(&s)), + // The shared `set_oauth_scopes` wins; fall back to the scopes + // passed positionally to `set_auth_u2m` (pre-existing path). + oauth_scopes.or(scopes).and_then(|s| parse_scopes(&s)), oauth_token_endpoint, None, Some(token_cache), @@ -1019,7 +1030,7 @@ fn build_session(config: KernelSessionConfig) -> Result Result assert_eq!(scopes, want), + other => panic!("expected OAuthM2M, got {other:?}"), + } + + let u2m = auth_spec_to_config( + AuthSpec::OAuthU2M { + client_id: None, + redirect_port: None, + scopes: None, + }, + None, + Some(scopes.to_string()), + None, + TokenCacheConfig::default(), + ) + .expect("u2m"); + match u2m { + AuthConfig::OAuthU2M { scopes, .. } => assert_eq!(scopes, want), + other => panic!("expected OAuthU2M, got {other:?}"), + } + } + + #[test] + fn oauth_scopes_setter_overrides_u2m_positional_scopes() { + // For U2M, the shared setter wins over scopes passed positionally to + // `set_auth_u2m` (kept for back-compat). + let auth = auth_spec_to_config( + AuthSpec::OAuthU2M { + client_id: None, + redirect_port: None, + scopes: Some("from-set-auth-u2m".to_string()), + }, + None, + Some("from-set-oauth-scopes".to_string()), + None, + TokenCacheConfig::default(), + ) + .expect("u2m"); + match auth { + AuthConfig::OAuthU2M { scopes, .. } => { + assert_eq!(scopes, Some(vec!["from-set-oauth-scopes".to_string()])) + } + other => panic!("expected OAuthU2M, got {other:?}"), + } + } + #[test] fn parse_scopes_trims_and_drops_empties() { assert_eq!( diff --git a/tests/c/session_smoke.c b/tests/c/session_smoke.c index 5f7ef3e7..851005d9 100644 --- a/tests/c/session_smoke.c +++ b/tests/c/session_smoke.c @@ -140,9 +140,9 @@ static void test_http_path_and_m2m_setters(void) { rc = kernel_session_config_set_oauth_token_endpoint( config, "https://login.microsoftonline.com/tenant/oauth2/v2.0/token"); CHECK(rc == KernelStatusCode_Success, "set_oauth_token_endpoint succeeds"); - rc = kernel_session_config_set_oauth_m2m_scopes( + rc = kernel_session_config_set_oauth_scopes( config, "2ff814a6-3304-4ab8-85cb-cd0e6f879c1d/.default"); - CHECK(rc == KernelStatusCode_Success, "set_oauth_m2m_scopes succeeds"); + CHECK(rc == KernelStatusCode_Success, "set_oauth_scopes succeeds"); kernel_session_config_free(config); } From 341ce093d9e3516f2e50fb4fe03fdbbb7859e328 Mon Sep 17 00:00:00 2001 From: "peco-engineer-bot[bot]" Date: Wed, 19 Aug 2026 00:19:41 +0000 Subject: [PATCH 07/47] ai: apply changes for #263 (1 review thread) Addresses: - #3809085121 at src/c_abi/session.rs:1007 Signed-off-by: peco-engineer-bot[bot] --- src/c_abi/session.rs | 33 ++++++++++++++++++++++++++++++++- 1 file changed, 32 insertions(+), 1 deletion(-) diff --git a/src/c_abi/session.rs b/src/c_abi/session.rs index 4b1cfc67..b84c8ef9 100644 --- a/src/c_abi/session.rs +++ b/src/c_abi/session.rs @@ -1004,7 +1004,12 @@ fn auth_spec_to_config( redirect_port.map(|p| vec![p]), // The shared `set_oauth_scopes` wins; fall back to the scopes // passed positionally to `set_auth_u2m` (pre-existing path). - oauth_scopes.or(scopes).and_then(|s| parse_scopes(&s)), + // Parse each source *before* choosing precedence: a present-but- + // empty shared value (`Some("")`) parses to `None`, so the + // positional fallback is preserved instead of being shadowed. + oauth_scopes + .and_then(|s| parse_scopes(&s)) + .or_else(|| scopes.and_then(|s| parse_scopes(&s))), oauth_token_endpoint, None, Some(token_cache), @@ -1449,6 +1454,32 @@ mod tests { } } + #[test] + fn empty_shared_oauth_scopes_falls_back_to_u2m_positional_scopes() { + // A present-but-empty shared value (`set_oauth_scopes("")`) parses to + // no scopes, so it must NOT shadow the positional `set_auth_u2m` + // scopes: precedence is chosen on the *parsed* result, not the raw + // `Option`. Guards the documented positional-fallback contract. + let auth = auth_spec_to_config( + AuthSpec::OAuthU2M { + client_id: None, + redirect_port: None, + scopes: Some("from-set-auth-u2m".to_string()), + }, + None, + Some(String::new()), + None, + TokenCacheConfig::default(), + ) + .expect("u2m"); + match auth { + AuthConfig::OAuthU2M { scopes, .. } => { + assert_eq!(scopes, Some(vec!["from-set-auth-u2m".to_string()])) + } + other => panic!("expected OAuthU2M, got {other:?}"), + } + } + #[test] fn parse_scopes_trims_and_drops_empties() { assert_eq!( From 86d1a5c20e3155177d4459f4dd08906d344d832e Mon Sep 17 00:00:00 2001 From: eric-wang-1990 Date: Tue, 18 Aug 2026 17:52:40 -0700 Subject: [PATCH 08/47] docs: pivot Azure design to kernel-as-auth-core (bindings thin) Team decision: the kernel owns Azure cloud-awareness (cloud detection, v2.0 endpoint construction, /aad/auth tenant discovery, Azure client/ scope/port defaults); bindings forward only their native selector + SP creds. Preserves per-driver Thrift invocation parity (azure_tenant_id optional/auto-discovered; kernel exposes both Databricks-SP oauth-m2m and Azure-AD azure-sp-m2m). Captures the live-test finding that the authorize endpoint must be {host}/oidc/oauth2/v2.0/authorize (not the discovered /oidc/v1/authorize, which 404s). Management token stays out. Co-authored-by: Isaac Signed-off-by: eric-wang-1990 --- ...BLR-4141-azure-service-principal-design.md | 382 +++++++----------- 1 file changed, 156 insertions(+), 226 deletions(-) diff --git a/docs/designs/PECOBLR-4141-azure-service-principal-design.md b/docs/designs/PECOBLR-4141-azure-service-principal-design.md index 8f0f20e8..3350daca 100644 --- a/docs/designs/PECOBLR-4141-azure-service-principal-design.md +++ b/docs/designs/PECOBLR-4141-azure-service-principal-design.md @@ -14,232 +14,162 @@ limitations under the License. --> -# Azure Entra ID OAuth on the kernel via generic overrides — PECOBLR-4141 / PECOBLR-4120 - -## Overview - -`databricks-sql-python` users authenticating to Azure Databricks with either an -**Azure service principal** (M2M — `azure-sp-m2m`) or the **Azure browser flow** -(U2M — `azure-oauth`) must keep working when the connector runs on the kernel -backend. - -**The kernel does not need any Azure-specific auth code.** It already ships a -generic OAuth engine — `OAuthM2M` (client-credentials) and `OAuthU2M` -(authorization-code + PKCE) — whose endpoint, scope, and client-id are all -**overridable**. Azure is expressed by *driving those existing flows with Azure -values*, which the connectors already compute today. The kernel's job is only to -make every binding able to pass those overrides through. - -This supersedes an earlier draft of this doc that proposed a dedicated -`AuthConfig::AzureServicePrincipal` variant, a new provider, an -`AuthProvider::extra_headers()` trait extension, and the Azure -management-token headers. All of that is **dropped** — see -[Why not a dedicated Azure flow](#why-not-a-dedicated-azure-flow). - -## Why the kernel stays generic (evidence) - -The two sibling SQL connectors already treat Azure as *generic OAuth with Azure -values*, not a distinct auth mode, and **neither uses the Azure management -token**: - -- **Go (`databricks-sql-go`)** rolls its own OAuth, workspace-OIDC rooted, with - the cloud inferred from the hostname; its kernel path has no Azure branch at - all. Scope resource `2ff814a6-3304-4ab8-85cb-cd0e6f879c1d`. No - `X-Databricks-Azure-SP-Management-Token`. -- **Node (`databricks-sql-nodejs`)** drives Azure via `openid-client` with scope - `2ff814a6-…/.default` (M2M) / `…/user_impersonation` (U2M). Its **kernel path - explicitly rejects** the Azure-direct options with: *"the workspace-OIDC - discovery path handles Azure workspaces today without these options."* No - management token. -- Only the general-purpose `databricks-sdk` carries the management-token - machinery (`azure.py` `add_sp_management_token()`), for broad control-plane - APIs — **not** the SQL data path (SEA / Thrift warehouse queries), which is all - the kernel serves. - -So the SQL-connector-consistent design is: keep the kernel a cloud-agnostic OAuth -engine; let each connector supply the Azure endpoint / scope / client-id it -already owns. - -## What the kernel already has - -`AuthConfig` (`src/config.rs`) exposes, on both OAuth variants: - -- `OAuthM2M { client_id, client_secret, scopes, token_url_override, identity_federation_client_id }` -- `OAuthU2M { client_id, redirect_ports, scopes, token_url_override, callback_timeout, token_cache, identity_federation_client_id }` - -`token_url_override`, `scopes`, and `client_id` are exactly the knobs Azure -needs. `FederationProvider` already wraps every flow and exchanges -foreign-issuer JWTs (Azure AD tokens included) at `{host}/oidc/v1/token`, -non-breaking. The HTTP client follows redirects by default, so workspace -`/oidc/.well-known/…` discovery transparently follows an Azure workspace's -redirect to Entra. - -## How each Azure mode maps onto the existing flows - -### Azure SP M2M (`azure-sp-m2m`, PECOBLR-4141) - -Connector drives `OAuthM2M` with: - -| Field | Azure value | -| --- | --- | -| `client_id` / `client_secret` | `azure_client_id` / `azure_client_secret` | -| `token_url_override` | `https://login.microsoftonline.com/{azure_tenant_id}/oauth2/v2.0/token` (per-cloud host) | -| `scopes` | `["2ff814a6-3304-4ab8-85cb-cd0e6f879c1d/.default"]` | - -The `oauth2` crate sends `grant_type=client_credentials` with the client id/secret -via HTTP Basic to the override endpoint; the returned Entra token (audience -`2ff814a6-…`, issuer `sts.windows.net/{tenant}`) is used as the bearer. - -> **Credential-transmission style (PR #263 review thread).** A reviewer noted the -> Azure docs *example* uses `client_secret_post` (form body), whereas the kernel's -> `exchange_client_credentials()` sends `client_secret_basic` (HTTP Basic). -> Verified non-blocking: Entra's published -> `token_endpoint_auth_methods_supported` is -> `["client_secret_post","private_key_jwt","client_secret_basic","self_signed_tls_client_auth"]` -> — `client_secret_basic` **is** supported, so no change to the M2M provider's -> credential transmission is required. Its foreign issuer means `FederationProvider` round-trips it through -`{host}/oidc/v1/token` (required when the workspace is *not* Azure; a benign -pass-through when it is). - -> **Cloud/environment ownership (PR #263 review thread).** A reviewer correctly -> noted the Azure cloud (Public / USGov / China → login host) is a property of -> the *SP's Azure tenant*, not the workspace's host, so deriving it from the -> workspace host (as an earlier draft did) is wrong. In the generic-override -> design this is moot for the kernel: the connector builds the full -> `token_url_override` for the correct cloud and the kernel uses it verbatim — -> the kernel never infers an environment. The per-cloud host table lives in each -> connector (`databricks-sdk-py` `azure.py`, etc.). - -### Azure U2M (`azure-oauth`, PECOBLR-4120) - -Connector drives `OAuthU2M` with the Azure app client id -`96eecda7-19ea-49cc-abb5-240097d554f5`, `redirect_ports=[8030]`, and scope -`["{app_id}/user_impersonation", "offline_access"]` (`app_id` defaults to -`2ff814a6-…`, overridable via `DATABRICKS_AZURE_TENANT_ID`). Authorization/token -endpoints come from the kernel's existing OIDC discovery against `{host}/oidc/…`, -which the Azure workspace redirects to Entra. - -Note the **kernel-blessed direction for Azure U2M is actually `databricks-oauth`** -(Databricks-native OAuth, which already works on Azure workspaces via -workspace-OIDC and needs *no* Azure values) — this is what the Go and Node kernel -paths use. `azure-oauth` (Entra-direct) is a legacy-compatibility path for callers -who pin it; it costs the kernel nothing beyond the override plumbing below. - -### Static workspace-resource-id header, if ever needed - -`X-Databricks-Azure-Workspace-Resource-Id` is a *static* string, so a connector -that wants it forwards it through the existing custom-headers channel -(pyo3 `http_headers`, napi `customHeaders`, C ABI -`kernel_session_config_set_custom_header`). No kernel change, no new seam. - -## Kernel-repo work (the entire change) - -pyo3 already exposes `token_url` + `oauth_scopes` + `client_id`, so **Python needs -no kernel change** — the work is in the other two bindings plus tests/docs. - -### napi (`napi/src/database.rs`, `napi/index.d.ts` by hand) - -Add an `oauthTokenUrl?: string` field to `ConnectionOptions` and forward it as -`token_url_override` in `build_auth_config` for **both** the `OAuthM2m` and -`OAuthU2m` arms (both currently hardcode `None`). `oauthScopes` / -`oauthClientId` are already forwarded. - -### C ABI (`src/c_abi/session.rs`, `include/databricks_kernel.h` by hand) - -- `AuthSpec::OAuthM2M` gains `scopes: Option` and - `token_endpoint: Option`; `set_auth_m2m` takes two more (nullable) - args and threads them into `AuthConfig::oauth_m2m` (currently passes - `None, None`). -- `AuthSpec::OAuthU2M` gains `token_endpoint: Option`; `set_auth_u2m` - takes one more (nullable) arg and threads it into `AuthConfig::oauth_u2m` - (currently `None`). -- Update the hand-written header and `tests/c/session_smoke.c`. - -### Core refinement (optional but recommended) - -In `m2m.rs`, when `token_endpoint_override` is `Some`, **skip OIDC discovery**: -the authorization endpoint is unused by the client-credentials grant, so -discovering it against the workspace is a needless round-trip and a needless -dependency on workspace OIDC for a pure-Entra token endpoint. Synthesize a -placeholder auth URL (unused) instead. U2M still discovers (it needs the -authorize endpoint for the browser step). - -### Docs / changelog - -`CONNECTION_PARAMETERS.md` documents the override knobs as the Azure mechanism -(with a worked `azure-sp-m2m` / `azure-oauth` example). Root + per-binding -`NEXT_CHANGELOG.md` entries. - -## Connector responsibilities (out of this repo, for reference) - -These land in `databricks-sql-python` / `-nodejs` (tracked by PECOBLR-4141 / --4120 / the Node ticket), not here: - -- **Python `auth_bridge.py`:** for `azure-sp-m2m`, forward `client_id` / - `client_secret` / `token_url` / `scopes` as in the table above; for - `azure-oauth`, synthesise the `{app_id}/user_impersonation offline_access` - scope (the current bug is forwarding literal `sql offline_access`) and the - Azure client id / port. -- **napi consumer (Node):** stop rejecting Azure in the kernel adapter; map its - Azure options onto `oauthTokenUrl` / `oauthScopes` / `oauthClientId`. - -## Why not a dedicated Azure flow - -The earlier draft added `AuthConfig::AzureServicePrincipal`, a provider, an -`extra_headers()` trait method, and the management-token headers. Rejected -because: - -- **No SQL connector uses the management token** (Go and Node confirm), so the - `extra_headers()` seam and the second-token flow it existed for buy nothing on - the SQL data path. Supporting the "Azure RBAC role but not a workspace member" - scenario is a `databricks-sdk` control-plane concern, not a SQL one. -- A dedicated variant forks a **fourth** copy of the Azure constants (app id, - per-cloud hosts, scope format) into the kernel, when the connectors already - own and maintain them. The override approach keeps a single source of truth per - connector and makes the kernel cloud-agnostic (matching Go and Node). -- Smaller, less security-sensitive change: no new provider, no trait change, no - new auth variant. - -If a future non-SQL consumer genuinely needs the management token, revisit then; -the `extra_headers()` design in this doc's git history is the starting point. - -## Error handling - -Unchanged from the existing OAuth flows: bad Entra credentials / endpoint errors -surface as `Unauthenticated` from `get_auth_header()` (M2M) or the browser-flow -error (U2M); a failed federation exchange falls back to the original token -(non-breaking). Missing required fields are rejected at the binding boundary by -the existing `AuthConfig::oauth_m2m` / `oauth_u2m` validating constructors. +# Azure Entra ID OAuth — kernel as the Azure-aware auth core (PECOBLR-4141 / 4120) + +## Direction + +**The kernel is the auth core; bindings are thin.** The kernel owns Azure +cloud-awareness — it detects the cloud from the workspace host, constructs the +correct Entra endpoints, auto-discovers the tenant, and applies the Azure client +id / scope / redirect-port defaults. Each binding forwards only its native auth +selector (+ the SP credentials for M2M); it does **not** build URLs, map scopes, +or discover tenants. + +This supersedes the earlier "generic-override, kernel stays cloud-agnostic" +draft. The generic `token_url` / `scopes` overrides added in the first cut of +this PR **remain** as primitives (the Azure layer sets them internally, and they +stay usable for non-Azure custom endpoints), but Azure resolution now lives in +the kernel. + +### Why (and the correction that motivated it) + +A live run against a real Azure workspace showed the generic approach's fatal +gap: the kernel's OIDC discovery returns `{host}/oidc/v1/authorize`, and the +workspace redirects that to a **malformed** `login.microsoftonline.com/{tenant}/ +v1/authorize` (404). Every connector instead uses `{host}/oidc/oauth2/v2.0/ +authorize`, which redirects to a valid Entra URL. Getting that right — plus +tenant discovery, per-cloud hosts, and the Azure defaults — is knowledge that +would otherwise be duplicated into every binding adapter. Putting it in the +kernel (as the Go driver's core already does) keeps it in one place. + +## Non-negotiable: invocation parity with Thrift + +Switching a connection to `use_kernel=True` must **not** change how a user +invokes Azure auth. The kernel API must let each binding preserve its exact +Thrift-path `connect()` surface: + +| Driver | Azure U2M — user passes | Azure M2M — user passes | +| --- | --- | --- | +| **Python** | `auth_type="azure-oauth"` | `auth_type="azure-sp-m2m"` + `azure_client_id` / `azure_client_secret`; **`azure_tenant_id` optional** (auto-discovered) | +| **Go** | `authType=OauthU2M` (Azure inferred from host; no azure param) | `authType=OauthM2M` + `clientID`/`clientSecret` — a *Databricks* SP (workspace OIDC), **not** Azure AD | +| **Node** | `authType='databricks-oauth'` + `azureTenantId` | `authType='databricks-oauth'` + `oauthClientId`/`Secret` + `azureTenantId` | + +Consequences the kernel API must satisfy: +- `azure_tenant_id` is **optional** everywhere (kernel discovers it) — Thrift + parity, and a correction to the first cut which wrongly required it. +- The kernel exposes **both** a Databricks-SP M2M (`oauth-m2m`, workspace OIDC) + and an Azure-AD-SP M2M (`azure-sp-m2m`, Entra) — Go's "Azure M2M" maps to the + former, Python's `azure-sp-m2m` to the latter. +- Each binding's thin adapter normalizes its native selector (Python's explicit + `auth_type`, Go's host-inference, Node's `azureTenantId` flag) onto the kernel + Azure API; the kernel accepts an explicit Azure signal and does the rest. + +## What the kernel owns — `src/auth/oauth/azure.rs` (new) + +1. **Cloud / environment detection** from the host suffix: + `.azuredatabricks.net` → Public, `.databricks.azure.us` → USGov, + `.databricks.azure.cn` → China. Per-cloud login host + Databricks app-id + table (Public/dev/staging app ids from the connector's `AzureAppId`; Gov/China + use the prod app id). Mirrors the Go driver's `azureTenants` map. +2. **Endpoint construction** (see per-flow sections). +3. **Tenant auto-discovery**: `GET {host}/aad/auth`, read the redirect to + `login.microsoftonline.com/{tenant}/…`, parse the tenant from the path. + Sovereign-aware (reads the real redirect host). Only needed for M2M. +4. **Azure defaults**: U2M client id `96eecda7-19ea-49cc-abb5-240097d554f5`, + port `8030`; scope app-id `2ff814a6-3304-4ab8-85cb-cd0e6f879c1d` (overridable + via `DATABRICKS_AZURE_TENANT_ID`, matching the connector). + +## `azure-oauth` (U2M) — PECOBLR-4120 + +Browser authorization-code + PKCE, driven by the kernel's existing U2M provider +with Azure endpoints/values: + +- **Authorize + token**: `{host}/oidc/oauth2/v2.0/authorize` and + `{host}/oidc/oauth2/v2.0/token` — the **workspace-host v2.0** paths (the Go + driver's proven pattern). No tenant needed: the workspace redirects the + authorize to Entra. This is the exact fix for the live 404 (`/oidc/v1/*` → + `/oidc/oauth2/v2.0/*`). +- **Client id** `96eecda7-…`, **scope** `{app_id}/user_impersonation + offline_access`, **redirect port** `8030`. +- The kernel gains an **authorize-endpoint override** internally so the Azure + path can pin `/oidc/oauth2/v2.0/authorize` instead of the discovered + `/oidc/v1/authorize`. (Discovery is otherwise unchanged for non-Azure U2M.) + +## `azure-sp-m2m` (M2M) — PECOBLR-4141 + +Client-credentials against **Entra directly** (no browser, so no workspace +redirect available): + +- **Token endpoint**: `{login_host}/{tenant}/oauth2/v2.0/token`, tenant + **auto-discovered** via `/aad/auth` when `azure_tenant_id` is omitted. +- **Scope**: `{effective_app_id}/.default` (app id from the host's cloud). +- **Credentials**: `azure_client_id` / `azure_client_secret` via HTTP Basic + (Entra v2.0 advertises `client_secret_basic`; verified). +- **Management token / `azure_workspace_resource_id`: still not implemented.** + No SQL connector (Go, Node) uses it; Python's Thrift path sends it but the SQL + data path doesn't require it for a workspace-member SP. An SP that is not a + workspace member (RBAC-only) remains unsupported on the kernel path, + documented. Revisit only with a concrete SQL customer need; the seam would be a + second-token + refreshing-extra-header mechanism. + +## Federation + +Unchanged. `FederationProvider` still wraps every flow; an Entra-issued token is +foreign-issuer and round-trips through `{host}/oidc/v1/token` (benign on Azure, +required for an Azure SP reaching a non-Azure workspace), with the non-breaking +fallback. + +## AuthConfig + +Two new variants (bindings map onto them): + +```rust +AuthConfig::AzureOAuthU2M { + client_id: Option, // None → 96eecda7-… + redirect_ports: Option>, // None → [8030] + app_id: Option, // scope resource; None → 2ff814a6-… / env + token_cache: Option, + identity_federation_client_id: Option, +} +AuthConfig::AzureServicePrincipal { // azure-sp-m2m + azure_client_id: String, + azure_client_secret: String, + azure_tenant_id: Option, // None → auto-discover via /aad/auth + identity_federation_client_id: Option, +} +``` + +The existing `OAuthU2M` / `OAuthM2M` variants are unchanged (Databricks-native +flows, incl. Go's Databricks-SP M2M and the workspace-OIDC databricks-oauth). + +## Thin bindings + +- **pyo3**: `auth_type="azure-oauth"` → `AzureOAuthU2M`; `auth_type="azure-sp-m2m"` + + `azure_*` kwargs → `AzureServicePrincipal`. No endpoint/scope/tenant logic. +- **napi**: `AuthMode::AzureOAuth` / `AzureSpM2m` + `azure*` fields. +- **C ABI**: `set_auth_azure_oauth` / `set_auth_azure_sp_m2m` setters. +- **Connector #919**: `auth_bridge.py` simplifies to selector-mapping only — + forwards `auth_type` + azure creds, stops constructing URLs / scopes and stops + discovering the tenant (the kernel does it). Drops the kernel-path dependency + on `AzureOAuthEndpointCollection` / `get_azure_tenant_id_from_host`. ## Testing -- **napi:** `ConnectionOptions.oauthTokenUrl` forwarded to `token_url_override` - for M2M and U2M (unit test on `build_auth_config`); field present in - `index.d.ts`. -- **C ABI:** `set_auth_m2m` scopes + token endpoint and `set_auth_u2m` token - endpoint recorded and threaded (unit tests; NULL-optional handling); smoke-test - line in `tests/c/session_smoke.c`. -- **Wiremock (`tests/azure_oauth_wiremock.rs`):** an Azure-shaped M2M run — mock - an Entra-like token endpoint, drive `OAuthM2M` with `token_url_override` + - `2ff814a6-…/.default` scope, assert the exchange hits the override endpoint - with Basic auth and the right scope, and that the resulting foreign-issuer - token flows through `FederationProvider`. -- **Discovery-follows-redirect:** a wiremock test that OIDC discovery follows a - 302 from `{host}/oidc/.well-known/…` to an Entra-like config host (guards the - PECOBLR-4120 assumption). -- **E2E (`#[ignore]`):** real Azure workspace — `azure-sp-m2m` via env vars - (`DATABRICKS_AZURE_CLIENT_ID` / `_SECRET` / `_TENANT_ID`) driving `oauth-m2m` - with the override; and `databricks-oauth`/`azure-oauth` U2M against an Azure - workspace. -- **Core:** if the skip-discovery-on-override refinement lands, a unit test that - M2M with an override performs no discovery request. - -## Deltas vs. reference - -- **Same** Entra endpoint, `2ff814a6-…` app id, scope strings, and v2.0 endpoint - as `databricks-sdk` / Go / Node — but supplied by the connector, not baked into - the kernel. -- **Dropped** vs. `databricks-sdk`: the management token and its two - `X-Databricks-Azure-*` headers (no SQL connector uses them). -- **Federation:** the kernel additionally runs its mandatory issuer-gated - exchange on top, as it already does for every OAuth flow. +- **Unit (`azure.rs`)**: cloud/env detection per host suffix; endpoint + construction (U2M workspace v2.0; M2M Entra token URL per cloud); scope + app-id defaulting + `DATABRICKS_AZURE_TENANT_ID` override. +- **Wiremock**: tenant discovery (`/aad/auth` 302 → parse tenant); `azure-sp-m2m` + hits the Entra token endpoint with Basic + `.default` scope; `azure-oauth` + uses the `/oidc/oauth2/v2.0/authorize` path (regression for the live 404). +- **Binding boundary**: pyo3 kwargs accepted; napi/C-ABI selectors record values. +- **Live (required before GA)**: `azure-oauth` U2M against a real Azure workspace + (browser) — confirm the v2.0 authorize path fixes the 404 and the query runs; + `azure-sp-m2m` with a real workspace-member Entra SP; sovereign-cloud spot check. + +## Status / evolution + +- First cut: generic overrides, kernel cloud-agnostic (shipped in this PR's early + commits). Retained as primitives. +- Live test found the `/oidc/v1/authorize` 404 → authorize must be v2.0. +- Decision (team): kernel is the auth core, bindings thin → Azure resolution + moves into the kernel (this doc). Management token stays out. From cb2bf20d1ce3bf3493ef54614b2c8cfbdb824e0a Mon Sep 17 00:00:00 2001 From: "peco-engineer-bot[bot]" Date: Wed, 19 Aug 2026 01:00:06 +0000 Subject: [PATCH 09/47] ai: apply changes for #263 (1 review thread) Addresses: - #3809259210 at CONNECTION_PARAMETERS.md:75 Signed-off-by: peco-engineer-bot[bot] --- CONNECTION_PARAMETERS.md | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/CONNECTION_PARAMETERS.md b/CONNECTION_PARAMETERS.md index 091fcd9e..0429c82a 100644 --- a/CONNECTION_PARAMETERS.md +++ b/CONNECTION_PARAMETERS.md @@ -72,12 +72,18 @@ connector supplying the Azure endpoint / scope / client id it already owns: (the Azure Databricks application id). Setting a `token_url_override` also skips workspace OIDC discovery, since the client-credentials grant never uses the authorization endpoint. -- **Azure U2M (`azure-oauth`):** `OAuthU2M` with the Azure app client id - (`96eecda7-19ea-49cc-abb5-240097d554f5`), the Azure delegated scope - (`{app_id}/user_impersonation offline_access`), and its redirect port; - endpoints come from OIDC discovery, which an Azure workspace redirects to - Entra. (The kernel-native `databricks-oauth` U2M also works on Azure - workspaces with no Azure-specific values.) +- **Azure U2M (`azure-oauth`): not yet supported on the kernel path + (unverified).** Unlike M2M, the U2M authorization-code flow needs the + *authorize* endpoint, and `token_url_override` only replaces the *token* + endpoint. U2M still discovers and uses the workspace `authorization_endpoint` + (`{host}/oidc/v1/authorize`), which on an Azure workspace redirects to a + malformed `login.microsoftonline.com/{tenant}/v1/authorize` that 404s. The + fix — kernel-owned Azure resolution pinning `{host}/oidc/oauth2/v2.0/authorize` + — is **not implemented in this PR** (see + `docs/designs/PECOBLR-4141-azure-service-principal-design.md`, PECOBLR-4120), + so there is no working generic-override recipe for Azure U2M yet. The + kernel-native `databricks-oauth` U2M flow is the supported browser option on + Azure workspaces. The bindings expose these overrides as: pyo3 `token_url` / `oauth_scopes` / `client_id`; napi `oauthTokenUrl` / `oauthScopes` / `oauthClientId`; C ABI From 197e2ce1f576e49d08f0082a399d3f9de99eb2e6 Mon Sep 17 00:00:00 2001 From: eric-wang-1990 Date: Tue, 18 Aug 2026 18:05:26 -0700 Subject: [PATCH 10/47] =?UTF-8?q?feat(auth):=20kernel-owned=20Azure=20U2M?= =?UTF-8?q?=20(azure-oauth)=20=E2=80=94=20LIVE=20VERIFIED?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The kernel is the auth core: add an AzureOAuthU2M variant + azure.rs so the kernel resolves the Azure browser flow itself — the workspace v2.0 authorize/token endpoints ({host}/oidc/oauth2/v2.0/{authorize,token}), the Azure app client id (96eecda7-...), port 8030, and the {app_id}/user_impersonation offline_access scope. Bindings just forward auth_type='azure-oauth'. Fixes the live 404: the U2M provider gained an authorization-endpoint override so the Azure path pins /oidc/oauth2/v2.0/authorize instead of the discovered /oidc/v1/authorize (which the workspace redirects to a malformed login.microsoftonline.com/{tenant}/v1/authorize). pyo3 accepts auth_type='azure-oauth'. Verified end-to-end against a live Azure workspace: browser sign-in completes, SELECT current_user() returns the signed-in user. Next slices: azure-sp-m2m kernel variant + tenant auto-discovery; napi + C-ABI thin wiring. Co-authored-by: Isaac Signed-off-by: eric-wang-1990 --- pyo3/src/auth.rs | 27 +++++++- src/auth/oauth/azure.rs | 111 +++++++++++++++++++++++++++++++++ src/auth/oauth/mod.rs | 1 + src/auth/oauth/u2m.rs | 30 +++++++-- src/config.rs | 71 +++++++++++++++++++++ src/session.rs | 43 +++++++++++++ tests/oauth_u2m_integration.rs | 4 ++ 7 files changed, 280 insertions(+), 7 deletions(-) create mode 100644 src/auth/oauth/azure.rs diff --git a/pyo3/src/auth.rs b/pyo3/src/auth.rs index d2140789..3874c765 100644 --- a/pyo3/src/auth.rs +++ b/pyo3/src/auth.rs @@ -285,8 +285,33 @@ fn build_auth_config_inner( oauth.identity_federation_client_id, )) } + "azure-oauth" => { + // Azure Entra U2M. The kernel owns Azure resolution (it is the + // auth core): it pins the workspace v2.0 authorize/token endpoints, + // the Azure app client id, port 8030, and the + // `{app_id}/user_impersonation offline_access` scope. The binding + // only forwards optional overrides — no endpoint/scope construction + // here. `app_id` (the connector's `DATABRICKS_AZURE_TENANT_ID` + // override for the scope resource) is threaded via `token_url`, + // which carries no meaning for this flow otherwise; a dedicated + // kwarg can replace it if needed. + if matches!(oauth.client_id.as_deref(), Some("")) { + return Err("auth_type='azure-oauth' client_id must be non-empty when set; \ + omit it to use the default Azure app" + .to_owned()); + } + Ok(AuthConfig::azure_oauth_u2m( + oauth.client_id, + oauth.redirect_ports, + None, // app_id: kernel default (2ff814a6-…) / DATABRICKS_AZURE_TENANT_ID + oauth.callback_timeout_secs.map(Duration::from_secs), + None, // token_cache: kernel default (enabled, machine-local key) + oauth.identity_federation_client_id, + )) + } 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-u2m', 'azure-oauth'" )), } } diff --git a/src/auth/oauth/azure.rs b/src/auth/oauth/azure.rs new file mode 100644 index 00000000..dc0d9a18 --- /dev/null +++ b/src/auth/oauth/azure.rs @@ -0,0 +1,111 @@ +// 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. + +//! Azure Entra ID cloud-awareness for the kernel's OAuth flows. +//! +//! The kernel is the auth core: rather than have each binding reconstruct the +//! Azure endpoints, scopes, and app ids, that knowledge lives here once and is +//! shared by every binding (mirroring how the Go driver's core infers the +//! cloud). This module holds the Azure constants and the endpoint/scope +//! builders used by the `azure-oauth` (U2M) and `azure-sp-m2m` (M2M) flows. +//! +//! **U2M (`azure-oauth`)** uses the **workspace-hosted v2.0** endpoints +//! (`{host}/oidc/oauth2/v2.0/{authorize,token}`) — the same pattern the Go +//! driver uses. The workspace redirects the browser to Entra, so no tenant is +//! needed. This is deliberately NOT the OIDC-discovered `{host}/oidc/v1/authorize` +//! path: a live test showed the workspace redirects that to a malformed +//! `login.microsoftonline.com/{tenant}/v1/authorize` (404), whereas the +//! `/oidc/oauth2/v2.0/authorize` path redirects to a valid Entra URL. + +/// Databricks first-party "Azure Databricks" application id (production). Used +/// as the default resource in the U2M delegated scope and as the M2M `.default` +/// resource. Constant across clouds for the scope; the connector's +/// `DATABRICKS_AZURE_TENANT_ID` env override maps onto the `app_id` argument. +pub(crate) const AZURE_DATABRICKS_APP_ID: &str = "2ff814a6-3304-4ab8-85cb-cd0e6f879c1d"; + +/// OAuth client id for the Azure U2M browser flow. Matches the connectors' +/// `PYSQL_OAUTH_AZURE_CLIENT_ID` / Go's `azureClientId`. +pub(crate) const AZURE_U2M_CLIENT_ID: &str = "96eecda7-19ea-49cc-abb5-240097d554f5"; + +/// Default localhost redirect port registered for [`AZURE_U2M_CLIENT_ID`]. +pub(crate) const AZURE_U2M_REDIRECT_PORT: u16 = 8030; + +/// The workspace-hosted v2.0 **authorize** endpoint for the Azure U2M flow. +/// The workspace redirects this to the tenant's Entra authorize URL. +pub(crate) fn u2m_authorize_url(host: &str) -> String { + format!("{}/oidc/oauth2/v2.0/authorize", host.trim_end_matches('/')) +} + +/// The workspace-hosted v2.0 **token** endpoint for the Azure U2M flow. +pub(crate) fn u2m_token_url(host: &str) -> String { + format!("{}/oidc/oauth2/v2.0/token", host.trim_end_matches('/')) +} + +/// The AAD delegated scope set for U2M: `{app_id}/user_impersonation` plus +/// `offline_access` (so a refresh token is issued). `app_id` defaults to +/// [`AZURE_DATABRICKS_APP_ID`] when the caller doesn't override it. +pub(crate) fn u2m_scopes(app_id: Option<&str>) -> Vec { + let app = app_id.unwrap_or(AZURE_DATABRICKS_APP_ID); + vec![ + format!("{app}/user_impersonation"), + "offline_access".to_string(), + ] +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn u2m_endpoints_are_workspace_v2_paths() { + // The v2.0 path is the fix for the live 404: /oidc/v1/authorize + // redirects to a malformed Entra URL, /oidc/oauth2/v2.0/authorize does not. + let host = "https://adb-123.4.azuredatabricks.net"; + assert_eq!( + u2m_authorize_url(host), + "https://adb-123.4.azuredatabricks.net/oidc/oauth2/v2.0/authorize" + ); + assert_eq!( + u2m_token_url(host), + "https://adb-123.4.azuredatabricks.net/oidc/oauth2/v2.0/token" + ); + } + + #[test] + fn u2m_endpoints_normalise_trailing_slash() { + let host = "https://adb-123.4.azuredatabricks.net/"; + assert_eq!( + u2m_authorize_url(host), + "https://adb-123.4.azuredatabricks.net/oidc/oauth2/v2.0/authorize" + ); + } + + #[test] + fn u2m_scopes_default_to_databricks_app_impersonation() { + assert_eq!( + u2m_scopes(None), + vec![ + format!("{AZURE_DATABRICKS_APP_ID}/user_impersonation"), + "offline_access".to_string() + ] + ); + } + + #[test] + fn u2m_scopes_honour_app_id_override() { + let scopes = u2m_scopes(Some("custom-app-id")); + assert_eq!(scopes[0], "custom-app-id/user_impersonation"); + assert_eq!(scopes[1], "offline_access"); + } +} diff --git a/src/auth/oauth/mod.rs b/src/auth/oauth/mod.rs index 24021d84..73def753 100644 --- a/src/auth/oauth/mod.rs +++ b/src/auth/oauth/mod.rs @@ -21,6 +21,7 @@ //! - OIDC endpoint discovery //! - File-based token caching +pub(crate) mod azure; pub mod cache; pub(crate) mod cache_crypto; pub mod callback; diff --git a/src/auth/oauth/u2m.rs b/src/auth/oauth/u2m.rs index 5a27d3b3..0a3e8b8f 100644 --- a/src/auth/oauth/u2m.rs +++ b/src/auth/oauth/u2m.rs @@ -243,6 +243,7 @@ impl AuthorizationCodeProvider { callback_timeout, None, // No token_endpoint override None, // On-disk cache disabled: no passphrase available here + None, // No authorization_endpoint override (discover) ) .await } @@ -267,12 +268,26 @@ impl AuthorizationCodeProvider { callback_timeout: Duration, token_endpoint_override: Option, cache_passphrase: Option, + authorization_endpoint_override: Option, ) -> Result { - // Discover OIDC endpoints (unless token_endpoint is overridden, we still need auth endpoint) - let endpoints = OidcEndpoints::discover(host, &http_client).await?; - - // Use override if provided, otherwise use discovered endpoint - let token_endpoint = token_endpoint_override.unwrap_or(endpoints.token_endpoint); + // Resolve the authorization + token endpoints. When BOTH are + // overridden (the Azure `azure-oauth` flow pins the workspace v2.0 + // `{host}/oidc/oauth2/v2.0/{authorize,token}` paths), skip OIDC + // discovery entirely — the discovered `{host}/oidc/v1/authorize` + // redirects to a malformed Entra URL for the Azure client, so the + // caller must be able to pin the v2.0 authorize path. Otherwise + // discover and let either override fill in. + let (token_endpoint, auth_endpoint) = + match (token_endpoint_override, authorization_endpoint_override) { + (Some(token), Some(auth)) => (token, auth), + (token_override, auth_override) => { + let endpoints = OidcEndpoints::discover(host, &http_client).await?; + ( + token_override.unwrap_or(endpoints.token_endpoint), + auth_override.unwrap_or(endpoints.authorization_endpoint), + ) + } + }; // Create token store let token_store = TokenStore::new(); @@ -304,7 +319,7 @@ impl AuthorizationCodeProvider { host: host.to_string(), client_id: client_id.to_string(), token_endpoint, - auth_endpoint: endpoints.authorization_endpoint, + auth_endpoint, token_store, http_client, scopes, @@ -663,6 +678,7 @@ mod tests { Duration::from_secs(120), None, Some(TEST_CACHE_PASSPHRASE.to_string()), + None, // No authorization_endpoint override ) .await .expect("Failed to create provider"); @@ -716,6 +732,7 @@ mod tests { Duration::from_secs(120), None, Some(TEST_CACHE_PASSPHRASE.to_string()), + None, // No authorization_endpoint override ) .await .expect("Failed to create provider"); @@ -785,6 +802,7 @@ mod tests { Duration::from_secs(5), // Short timeout for test None, Some(TEST_CACHE_PASSPHRASE.to_string()), + None, // No authorization_endpoint override ) .await .expect("Failed to create provider"); diff --git a/src/config.rs b/src/config.rs index d5f8050e..26579cba 100644 --- a/src/config.rs +++ b/src/config.rs @@ -358,6 +358,33 @@ pub enum AuthConfig { identity_federation_client_id: Option, }, + /// Azure Entra ID user-to-machine (browser) auth — the `azure-oauth` + /// flow. Unlike [`Self::OAuthU2M`] (Databricks-native OIDC), this uses + /// the workspace's **v2.0** authorize/token endpoints + /// (`{host}/oidc/oauth2/v2.0/{authorize,token}`), which the workspace + /// redirects to Microsoft Entra, and the Azure delegated scope + /// `{app_id}/user_impersonation offline_access`. The kernel resolves all + /// of that from the host, so bindings only forward the (optional) + /// overrides. No tenant is needed (the workspace redirect resolves it). + AzureOAuthU2M { + /// OAuth client id. `None` → the Azure Databricks app + /// (`96eecda7-…`). + client_id: Option, + /// Candidate localhost callback ports. `None`/empty → `[8030]`. + redirect_ports: Option>, + /// Resource app id used in the `{app_id}/user_impersonation` scope. + /// `None` → the Azure Databricks app id (`2ff814a6-…`); a binding + /// forwards the `DATABRICKS_AZURE_TENANT_ID` override here. + app_id: Option, + /// How long to wait for the browser callback. `None` → 120s. + callback_timeout: Option, + /// On-disk token-cache policy. `None` → [`TokenCacheConfig::default`]. + token_cache: Option, + /// SP-wide Workload Identity Federation client id, forwarded to the + /// federation wrapper. + identity_federation_client_id: Option, + }, + /// OAuth 2.0 token exchange (RFC 8693), for federated identity /// (e.g. exchanging a Workload Identity token for a Databricks /// access token). @@ -463,6 +490,30 @@ impl AuthConfig { } } + /// Construct a [`AuthConfig::AzureOAuthU2M`] (the `azure-oauth` browser + /// flow) from optional fields. All fields are optional — the kernel fills + /// the Azure app client id (`96eecda7-…`), port `8030`, and the + /// `{app_id}/user_impersonation offline_access` scope — so this performs no + /// validation and exists for symmetry with the other constructors so + /// bindings can forward optionals uniformly. + pub fn azure_oauth_u2m( + client_id: Option, + redirect_ports: Option>, + app_id: Option, + callback_timeout: Option, + token_cache: Option, + identity_federation_client_id: Option, + ) -> Self { + AuthConfig::AzureOAuthU2M { + client_id, + redirect_ports, + app_id, + callback_timeout, + token_cache, + identity_federation_client_id, + } + } + /// SP-wide federation client id attached to the selected base auth flow. pub(crate) fn identity_federation_client_id(&self) -> Option<&str> { match self { @@ -477,6 +528,10 @@ impl AuthConfig { | Self::OAuthU2M { identity_federation_client_id, .. + } + | Self::AzureOAuthU2M { + identity_federation_client_id, + .. } => identity_federation_client_id.as_deref(), Self::OAuthFederation { .. } | Self::External(_) => None, } @@ -546,6 +601,22 @@ impl std::fmt::Debug for AuthConfig { identity_federation_client_id, ) .finish(), + Self::AzureOAuthU2M { + client_id, + redirect_ports, + app_id, + identity_federation_client_id, + .. + } => f + .debug_struct("AzureOAuthU2M") + .field("client_id", client_id) + .field("redirect_ports", redirect_ports) + .field("app_id", app_id) + .field( + "identity_federation_client_id", + identity_federation_client_id, + ) + .finish(), Self::OAuthFederation { subject_token_type, audience, diff --git a/src/session.rs b/src/session.rs index e4870bcd..55532334 100644 --- a/src/session.rs +++ b/src/session.rs @@ -1216,6 +1216,49 @@ async fn build_base_auth_provider( timeout, token_url_override.clone(), cache_policy, + None, // Databricks-native U2M: discover the authorize endpoint + ) + .await?; + Ok(Arc::new(provider)) + } + AuthConfig::AzureOAuthU2M { + client_id, + redirect_ports, + app_id, + callback_timeout, + token_cache, + .. + } => { + // The kernel owns Azure resolution (it is the auth core): pin the + // workspace **v2.0** authorize+token endpoints (the workspace + // redirects them to Entra — the discovered /oidc/v1/authorize + // redirects to a malformed Entra URL), and fill the Azure app + // client id / port / delegated scope. No tenant needed for U2M. + use crate::auth::oauth::azure; + let client_id = client_id + .clone() + .unwrap_or_else(|| azure::AZURE_U2M_CLIENT_ID.to_string()); + let callback_ports = match redirect_ports.as_deref() { + Some(ports) if !ports.is_empty() => ports.to_vec(), + _ => vec![azure::AZURE_U2M_REDIRECT_PORT], + }; + let scopes = azure::u2m_scopes(app_id.as_deref()); + let timeout = callback_timeout.unwrap_or_else(|| Duration::from_secs(120)); + let cache_policy = token_cache + .clone() + .unwrap_or_default() + .resolve() + .map(|p| p.into_owned()); + let provider = AuthorizationCodeProvider::new_with_full_config( + host, + &client_id, + http_client, + scopes, + callback_ports, + timeout, + Some(azure::u2m_token_url(host)), + cache_policy, + Some(azure::u2m_authorize_url(host)), ) .await?; Ok(Arc::new(provider)) diff --git a/tests/oauth_u2m_integration.rs b/tests/oauth_u2m_integration.rs index 95b83782..cebd1712 100644 --- a/tests/oauth_u2m_integration.rs +++ b/tests/oauth_u2m_integration.rs @@ -122,6 +122,7 @@ async fn test_u2m_refresh_token_full_flow() { Duration::from_secs(120), None, Some(TEST_CACHE_PASSPHRASE.to_string()), + None, // No authorization_endpoint override ) .await .expect("Failed to create AuthorizationCodeProvider"); @@ -196,6 +197,7 @@ async fn test_u2m_refresh_token_stale_immediate_return() { Duration::from_secs(120), None, Some(TEST_CACHE_PASSPHRASE.to_string()), + None, // No authorization_endpoint override ) .await .expect("Failed to create provider"); @@ -276,6 +278,7 @@ async fn test_u2m_refresh_token_expired_fallback() { Duration::from_secs(5), // Short timeout for test None, Some(TEST_CACHE_PASSPHRASE.to_string()), + None, // No authorization_endpoint override ) .await .expect("Failed to create provider"); @@ -351,6 +354,7 @@ async fn test_u2m_refresh_updates_cache() { Duration::from_secs(120), None, Some(TEST_CACHE_PASSPHRASE.to_string()), + None, // No authorization_endpoint override ) .await .expect("Failed to create provider"); From 33b9833a79aabba3328ce39a12ec4a503d77ebaa Mon Sep 17 00:00:00 2001 From: eric-wang-1990 Date: Tue, 18 Aug 2026 18:07:18 -0700 Subject: [PATCH 11/47] docs: mark azure-oauth U2M as kernel-owned + live-verified MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Supersedes the review-bot doc note that azure-oauth U2M was unsupported/ unverified — the AzureOAuthU2M variant now handles it (workspace v2.0 endpoints), verified end-to-end against a live Azure workspace. Co-authored-by: Isaac Signed-off-by: eric-wang-1990 --- CONNECTION_PARAMETERS.md | 48 +++++++++++++++++++++------------------- NEXT_CHANGELOG.md | 12 ++++++++++ 2 files changed, 37 insertions(+), 23 deletions(-) diff --git a/CONNECTION_PARAMETERS.md b/CONNECTION_PARAMETERS.md index 0429c82a..f1fd3179 100644 --- a/CONNECTION_PARAMETERS.md +++ b/CONNECTION_PARAMETERS.md @@ -34,7 +34,7 @@ warehouse id and org id out of a `/sql/1.0/warehouses/{id}` path). ## `AuthConfig` — authentication (required) An enum; pick one variant. Use the validating constructors -(`AuthConfig::pat`, `::oauth_m2m`, `::oauth_u2m`). +(`AuthConfig::pat`, `::oauth_m2m`, `::oauth_u2m`, `::azure_oauth_u2m`). **`Pat`** — personal access token: @@ -61,29 +61,31 @@ An enum; pick one variant. Use the validating constructors | `token_url_override` | Token endpoint override. | OIDC discovery | | `callback_timeout` | How long to wait for the user to complete the browser flow. | `120s` | -**Azure Entra ID (Microsoft Entra) OAuth.** There is no dedicated Azure -variant — Azure rides the generic OAuth flows via the overrides above, with the -connector supplying the Azure endpoint / scope / client id it already owns: - -- **Azure service principal (M2M):** `OAuthM2M` with +**Azure Entra ID (Microsoft Entra) OAuth.** The kernel is the Azure-aware auth +core — it resolves the Azure endpoints / scope / client id from the host, so +bindings just select the flow. + +- **Azure U2M (`AzureOAuthU2M`, `azure-oauth`): supported — live-verified.** + The kernel pins the workspace **v2.0** endpoints + (`{host}/oidc/oauth2/v2.0/{authorize,token}`, which the workspace redirects to + Entra), the Azure app client id (`96eecda7-…`), port `8030`, and the + `{app_id}/user_impersonation offline_access` scope. No tenant needed (the + workspace redirect resolves it). Fields — all optional: `client_id`, + `redirect_ports` (default `[8030]`), `app_id` (scope resource; default + `2ff814a6-…`), `callback_timeout` (`120s`), `token_cache`. This is **not** the + discovered `{host}/oidc/v1/authorize` path, which redirects to a malformed + Entra URL (404) for the Azure client — the v2.0 path is the fix. +- **Azure service principal (M2M):** today via `OAuthM2M` with `client_id`/`client_secret` = the Entra app credentials, - `token_url_override = https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token` - (per-cloud host), and `scopes = ["2ff814a6-3304-4ab8-85cb-cd0e6f879c1d/.default"]` - (the Azure Databricks application id). Setting a `token_url_override` also - skips workspace OIDC discovery, since the client-credentials grant never uses - the authorization endpoint. -- **Azure U2M (`azure-oauth`): not yet supported on the kernel path - (unverified).** Unlike M2M, the U2M authorization-code flow needs the - *authorize* endpoint, and `token_url_override` only replaces the *token* - endpoint. U2M still discovers and uses the workspace `authorization_endpoint` - (`{host}/oidc/v1/authorize`), which on an Azure workspace redirects to a - malformed `login.microsoftonline.com/{tenant}/v1/authorize` that 404s. The - fix — kernel-owned Azure resolution pinning `{host}/oidc/oauth2/v2.0/authorize` - — is **not implemented in this PR** (see - `docs/designs/PECOBLR-4141-azure-service-principal-design.md`, PECOBLR-4120), - so there is no working generic-override recipe for Azure U2M yet. The - kernel-native `databricks-oauth` U2M flow is the supported browser option on - Azure workspaces. + `token_url_override = https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token`, + and `scopes = ["2ff814a6-…/.default"]`. Setting `token_url_override` also skips + workspace OIDC discovery. A dedicated kernel-owned `azure-sp-m2m` variant (with + in-kernel `/aad/auth` tenant auto-discovery, so the tenant is optional) is the + next slice — see `docs/designs/PECOBLR-4141-azure-service-principal-design.md`. + +The Azure **management token** (`X-Databricks-Azure-SP-Management-Token`) is not +implemented — no SQL connector (Go, Node) uses it; a workspace-member SP +authenticates with the data token alone. The bindings expose these overrides as: pyo3 `token_url` / `oauth_scopes` / `client_id`; napi `oauthTokenUrl` / `oauthScopes` / `oauthClientId`; C ABI diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index ad64058a..dc10618d 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -11,6 +11,18 @@ changes go in their respective binding's NEXT_CHANGELOG. ### Added +- Azure Entra U2M (`azure-oauth`) is now a kernel-owned flow + (`AuthConfig::AzureOAuthU2M` / pyo3 `auth_type="azure-oauth"`). The kernel + resolves the Azure browser flow itself — it pins the workspace v2.0 + endpoints (`{host}/oidc/oauth2/v2.0/{authorize,token}`, which the workspace + redirects to Entra), the Azure app client id (`96eecda7-…`), port `8030`, and + the `{app_id}/user_impersonation offline_access` scope — so bindings only + forward the selector. The U2M provider gained an authorization-endpoint + override so the Azure path pins `/oidc/oauth2/v2.0/authorize` instead of the + discovered `/oidc/v1/authorize` (which an Azure workspace redirects to a + malformed Entra URL). Live-verified end-to-end against an Azure workspace. + (PECOBLR-4120.) + - Azure Entra ID OAuth support via generic overrides (no dedicated Azure auth flow). Azure service-principal M2M rides `OAuthM2M` with an Entra `token_url_override` + the `2ff814a6-…/.default` scope; Azure U2M rides From 389bed6a29900fa81e3968eeb9b4829df528602b Mon Sep 17 00:00:00 2001 From: "peco-engineer-bot[bot]" Date: Wed, 19 Aug 2026 01:16:10 +0000 Subject: [PATCH 12/47] ai: apply changes for #263 (1 review thread) Addresses: - #3809314285 at pyo3/src/auth.rs:288 Signed-off-by: peco-engineer-bot[bot] --- pyo3/src/auth.rs | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/pyo3/src/auth.rs b/pyo3/src/auth.rs index 3874c765..1ca44a68 100644 --- a/pyo3/src/auth.rs +++ b/pyo3/src/auth.rs @@ -291,10 +291,11 @@ fn build_auth_config_inner( // the Azure app client id, port 8030, and the // `{app_id}/user_impersonation offline_access` scope. The binding // only forwards optional overrides — no endpoint/scope construction - // here. `app_id` (the connector's `DATABRICKS_AZURE_TENANT_ID` - // override for the scope resource) is threaded via `token_url`, - // which carries no meaning for this flow otherwise; a dedicated - // kwarg can replace it if needed. + // here. The `app_id` scope-resource override (the connector's + // `DATABRICKS_AZURE_TENANT_ID`) is NOT yet forwarded from Python: + // we always pass `None` below so the kernel default applies. A + // dedicated kwarg can wire it through if a caller needs to override + // it; `token_url` is not consulted for this flow. if matches!(oauth.client_id.as_deref(), Some("")) { return Err("auth_type='azure-oauth' client_id must be non-empty when set; \ omit it to use the default Azure app" From b29a2a1ab42bdbe4953092974392c5a6b5ced164 Mon Sep 17 00:00:00 2001 From: "peco-engineer-bot[bot]" Date: Wed, 19 Aug 2026 01:24:51 +0000 Subject: [PATCH 13/47] ai: apply changes for #263 (1 review thread) Addresses: - #3809343333 at pyo3/src/auth.rs:308 Signed-off-by: peco-engineer-bot[bot] --- pyo3/src/auth.rs | 76 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 76 insertions(+) diff --git a/pyo3/src/auth.rs b/pyo3/src/auth.rs index 1ca44a68..bdb0bbc3 100644 --- a/pyo3/src/auth.rs +++ b/pyo3/src/auth.rs @@ -301,6 +301,34 @@ fn build_auth_config_inner( omit it to use the default Azure app" .to_owned()); } + // `redirect_ports` / `callback_timeout_secs` carry the same U2M + // semantics here as in the `oauth-u2m` arm, so reject the same + // present-yet-degenerate shapes: a 0 timeout times the browser + // flow out immediately, and an empty list / 0 port entry binds an + // ephemeral port that can't match the IdP's static redirect_uri. + if oauth.callback_timeout_secs == Some(0) { + return Err( + "auth_type='azure-oauth' oauth_callback_timeout_secs must be > 0 when set \ + (0 would time out the browser flow immediately); omit it for the default" + .to_owned(), + ); + } + if let Some(ports) = oauth.redirect_ports.as_deref() { + if ports.is_empty() { + return Err( + "auth_type='azure-oauth' redirect_ports must be non-empty when set; \ + omit it for the default" + .to_owned(), + ); + } + if ports.contains(&0) { + return Err( + "auth_type='azure-oauth' redirect_ports entries must be non-zero \ + (each must be a static port the IdP redirect_uri can match)" + .to_owned(), + ); + } + } Ok(AuthConfig::azure_oauth_u2m( oauth.client_id, oauth.redirect_ports, @@ -654,6 +682,54 @@ mod tests { ); } + #[test] + fn azure_oauth_rejects_zero_callback_timeout() { + let err = build_auth_config_inner( + "azure-oauth", + None, + OAuthParams { + callback_timeout_secs: Some(0), + ..Default::default() + }, + ) + .unwrap_err(); + assert!( + err.contains("oauth_callback_timeout_secs must be > 0"), + "{err}" + ); + } + + #[test] + fn azure_oauth_rejects_empty_redirect_ports() { + let err = build_auth_config_inner( + "azure-oauth", + None, + OAuthParams { + redirect_ports: Some(vec![]), + ..Default::default() + }, + ) + .unwrap_err(); + assert!( + err.contains("redirect_ports must be non-empty"), + "got: {err}" + ); + } + + #[test] + fn azure_oauth_rejects_zero_in_redirect_ports() { + let err = build_auth_config_inner( + "azure-oauth", + None, + OAuthParams { + redirect_ports: Some(vec![8020, 0]), + ..Default::default() + }, + ) + .unwrap_err(); + assert!(err.contains("non-zero"), "got: {err}"); + } + #[test] fn unknown_auth_type_rejected() { let err = build_auth_config_inner("kerberos", None, OAuthParams::default()).unwrap_err(); From 0ee99c75bb272ee568e6683db9c872a6c0cd3157 Mon Sep 17 00:00:00 2001 From: eric-wang-1990 Date: Wed, 19 Aug 2026 00:47:22 -0700 Subject: [PATCH 14/47] feat(auth): kernel-owned Azure SP M2M (azure-sp-m2m) with optional management token MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add the `azure-sp-m2m` flow to the kernel as the Azure-aware auth core: bindings forward only the SP credentials, the kernel resolves the Entra token endpoint (`{login}/{tenant}/oauth2/v2.0/token`), the `{app_id}/.default` scope, and — when `azure_tenant_id` is omitted — the tenant itself, by parsing the workspace `/aad/auth` redirect (Thrift parity, so `connect()` is byte-identical to the Thrift path). The Azure management-token pair (`X-Databricks-Azure-SP-Management-Token` + `X-Databricks-Azure-Workspace-Resource-Id`) is an optional add-on gated on `azure_workspace_resource_id`: set it and the kernel fetches a second Entra token (ARM `.default` scope) and emits both headers so the control plane can authorize an SP that holds an Azure RBAC role but is not a workspace member; leave it unset (the common case) and the SP authenticates with the data token alone. Plumbing: a new `AuthProvider::extra_headers()` (default empty) carries dynamic per-request headers alongside `Authorization`; `FederationProvider` delegates it; the HTTP client applies it only on authenticated requests. Both tokens reuse `ClientCredentialsProvider` (so they refresh on long-lived sessions). Wired through `AuthConfig::AzureServicePrincipal` + the `azure_service_principal(...)` constructor and the pyo3 binding (`azure-sp-m2m` auth_type + `azure_*` kwargs). Unit tests cover the two-token composition (both headers with the raw management token when a resource id is set; data token only, management scope never requested, when it is not). Co-authored-by: Isaac Signed-off-by: eric-wang-1990 --- pyo3/src/auth.rs | 24 +- pyo3/src/session.rs | 12 + src/auth/mod.rs | 14 ++ src/auth/oauth/azure.rs | 420 +++++++++++++++++++++++++++++++++++ src/auth/oauth/federation.rs | 7 + src/client/http.rs | 16 ++ src/config.rs | 81 +++++++ src/session.rs | 36 +++ 8 files changed, 609 insertions(+), 1 deletion(-) diff --git a/pyo3/src/auth.rs b/pyo3/src/auth.rs index bdb0bbc3..4a10ab12 100644 --- a/pyo3/src/auth.rs +++ b/pyo3/src/auth.rs @@ -62,6 +62,13 @@ pub(crate) struct OAuthParams { pub redirect_ports: Option>, pub callback_timeout_secs: Option, pub identity_federation_client_id: Option, + /// Azure Entra service-principal credentials (`azure-sp-m2m`). The kernel + /// resolves the Entra endpoint / scope and (when `azure_tenant_id` is + /// omitted) the tenant itself. + pub azure_client_id: Option, + pub azure_client_secret: Option, + pub azure_tenant_id: Option, + pub azure_workspace_resource_id: Option, } /// Default U2M OAuth client id for the **Python** binding. @@ -338,9 +345,24 @@ fn build_auth_config_inner( oauth.identity_federation_client_id, )) } + "azure-sp-m2m" => { + // Azure Entra service-principal M2M. The kernel owns Azure + // resolution: it builds the Entra token endpoint + `.default` + // scope and auto-discovers the tenant from the workspace when + // `azure_tenant_id` is omitted. The binding forwards only the + // Entra credentials (+ optional tenant). + AuthConfig::azure_service_principal( + oauth.azure_client_id, + oauth.azure_client_secret, + oauth.azure_tenant_id, + oauth.azure_workspace_resource_id, + oauth.identity_federation_client_id, + ) + .map_err(|err| err.to_string()) + } other => Err(format!( "unsupported auth_type {other:?}; expected one of 'pat', 'oauth-m2m', \ - 'oauth-u2m', 'azure-oauth'" + 'oauth-u2m', 'azure-oauth', 'azure-sp-m2m'" )), } } diff --git a/pyo3/src/session.rs b/pyo3/src/session.rs index c5ce6c59..547267fe 100644 --- a/pyo3/src/session.rs +++ b/pyo3/src/session.rs @@ -123,6 +123,10 @@ impl Session { redirect_ports=None, oauth_callback_timeout_secs=None, identity_federation_client_id=None, + azure_client_id=None, + azure_client_secret=None, + azure_tenant_id=None, + azure_workspace_resource_id=None, tls_ca_cert=None, tls_skip_verify=false, tls_skip_hostname_verify=false, @@ -153,6 +157,10 @@ impl Session { redirect_ports: Option>, oauth_callback_timeout_secs: Option, identity_federation_client_id: Option, + azure_client_id: Option, + azure_client_secret: Option, + azure_tenant_id: Option, + azure_workspace_resource_id: Option, tls_ca_cert: Option>, tls_skip_verify: bool, tls_skip_hostname_verify: bool, @@ -200,6 +208,10 @@ impl Session { redirect_ports, callback_timeout_secs: oauth_callback_timeout_secs, identity_federation_client_id, + azure_client_id, + azure_client_secret, + azure_tenant_id, + azure_workspace_resource_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..993d55b0 100644 --- a/src/auth/mod.rs +++ b/src/auth/mod.rs @@ -29,4 +29,18 @@ use std::fmt::Debug; pub trait AuthProvider: Send + Sync + Debug { /// Returns the authorization header value for HTTP requests. fn get_auth_header(&self) -> Result; + + /// Extra headers to attach **alongside** `Authorization` on authenticated + /// requests (never on unauthenticated token/OIDC calls). Default: none. + /// + /// Overridden only by the Azure service-principal provider, which emits the + /// `X-Databricks-Azure-SP-Management-Token` + `X-Databricks-Azure-Workspace- + /// Resource-Id` pair when a workspace resource id is configured (so the + /// control plane can authorize an SP that has an Azure RBAC role but is not + /// a workspace member). These are dynamic (the management token refreshes), + /// so they cannot be static `custom_headers`. Called on every authenticated + /// request, so implementations must be cheap / internally cached. + fn extra_headers(&self) -> Result> { + Ok(Vec::new()) + } } diff --git a/src/auth/oauth/azure.rs b/src/auth/oauth/azure.rs index dc0d9a18..13b005ea 100644 --- a/src/auth/oauth/azure.rs +++ b/src/auth/oauth/azure.rs @@ -63,6 +63,244 @@ pub(crate) fn u2m_scopes(app_id: Option<&str>) -> Vec { ] } +// ─── M2M (azure-sp-m2m) ────────────────────────────────────────────────────── + +/// Entra (Azure AD) login host. The connector's SP M2M path hardcodes the +/// commercial host, so we match it; sovereign-cloud login hosts are a +/// documented follow-up (the tenant discovery below already reads the real +/// redirect host, so extending this is where sovereign support would land). +const AZURE_AAD_LOGIN_HOST: &str = "https://login.microsoftonline.com"; + +/// Per-environment Azure Databricks resource app id, keyed by host suffix — +/// used as the `{app_id}/.default` M2M scope resource. Mirrors the connectors' +/// `AzureAppId` / `get_effective_azure_login_app_id`: dev / staging have their +/// own app ids; everything else (prod commercial + sovereign) uses the prod id. +const AZURE_APP_IDS_BY_SUFFIX: &[(&str, &str)] = &[ + ( + ".dev.azuredatabricks.net", + "62a912ac-b58e-4c1d-89ea-b2dbfc7358fc", + ), + ( + ".staging.azuredatabricks.net", + "4a67d088-db5c-48f1-9ff2-0aace800ae68", + ), +]; + +/// The effective Azure Databricks resource app id for `host` (the resource in +/// the M2M `.default` scope). Falls back to [`AZURE_DATABRICKS_APP_ID`] (prod) +/// for commercial prod and sovereign hosts. +pub(crate) fn effective_app_id(host: &str) -> &'static str { + let host = host.trim_end_matches('/').to_ascii_lowercase(); + for (suffix, app_id) in AZURE_APP_IDS_BY_SUFFIX { + // Match the host component, ignoring scheme/path. + if host.contains(suffix) { + return app_id; + } + } + AZURE_DATABRICKS_APP_ID +} + +/// The Entra **token** endpoint for the M2M client-credentials grant: +/// `{login_host}/{tenant}/oauth2/v2.0/token`. Direct to Entra (no workspace +/// redirect is available for a non-browser flow). +pub(crate) fn sp_m2m_token_url(tenant: &str) -> String { + format!("{AZURE_AAD_LOGIN_HOST}/{tenant}/oauth2/v2.0/token") +} + +/// The M2M scope: `{effective_app_id}/.default`. +pub(crate) fn sp_m2m_scope(host: &str) -> String { + format!("{}/.default", effective_app_id(host)) +} + +/// The Azure Resource Manager scope for the **management token** (commercial +/// cloud). Matches the connector's `AZURE_MANAGED_RESOURCE` +/// (`https://management.core.windows.net/`), as a v2.0 `.default` scope. +pub(crate) const AZURE_MANAGEMENT_SCOPE: &str = "https://management.core.windows.net/.default"; + +/// Header carrying the SP's Azure Resource Manager token, so the Databricks +/// control plane can validate the SP's Azure RBAC role on the workspace. +const SP_MANAGEMENT_TOKEN_HEADER: &str = "X-Databricks-Azure-SP-Management-Token"; +/// Header naming the workspace's ARM resource id (paired with the management +/// token for the RBAC lookup). +const WORKSPACE_RESOURCE_ID_HEADER: &str = "X-Databricks-Azure-Workspace-Resource-Id"; + +/// Azure service-principal M2M provider. The `Authorization` bearer is the +/// Databricks-audience data token; when a workspace resource id is configured +/// it additionally emits the management-token pair via [`AuthProvider::extra_headers`] +/// so the control plane can authorize an SP that has an Azure RBAC role but is +/// not (yet) a workspace member. Both tokens are ordinary client-credentials +/// exchanges (reusing [`ClientCredentialsProvider`], which refreshes them), so +/// the management token stays fresh on long-lived sessions. +#[derive(Debug)] +pub(crate) struct AzureServicePrincipalProvider { + data: super::m2m::ClientCredentialsProvider, + /// `Some` only when `azure_workspace_resource_id` was supplied. + management: Option, +} + +#[derive(Debug)] +struct ManagementHeaders { + token_source: super::m2m::ClientCredentialsProvider, + workspace_resource_id: String, +} + +impl AzureServicePrincipalProvider { + /// Build the provider. `tenant` is the (already-resolved) Entra tenant; + /// `host` selects the resource app id for the data scope. The management + /// token source is created only when `workspace_resource_id` is `Some`. + pub(crate) async fn new( + host: &str, + azure_client_id: &str, + azure_client_secret: &str, + tenant: &str, + workspace_resource_id: Option, + http_client: std::sync::Arc, + ) -> crate::kernel_error::Result { + Self::new_with_token_url( + host, + azure_client_id, + azure_client_secret, + sp_m2m_token_url(tenant), + workspace_resource_id, + http_client, + ) + .await + } + + /// Build the provider against an explicit Entra token endpoint. `new` + /// derives that endpoint from the tenant (`sp_m2m_token_url`); this seam + /// takes it directly so tests can point both token sources at a mock server + /// (the real endpoint host, `login.microsoftonline.com`, is not + /// interceptable). Both the data-scope and management-scope client- + /// credentials grants hit the same `token_url` with different scopes. + async fn new_with_token_url( + host: &str, + azure_client_id: &str, + azure_client_secret: &str, + token_url: String, + workspace_resource_id: Option, + http_client: std::sync::Arc, + ) -> crate::kernel_error::Result { + let data = super::m2m::ClientCredentialsProvider::new_with_full_config( + host, + azure_client_id, + azure_client_secret, + http_client.clone(), + vec![sp_m2m_scope(host)], + Some(token_url.clone()), + ) + .await?; + + let management = match workspace_resource_id { + Some(rid) => { + let token_source = super::m2m::ClientCredentialsProvider::new_with_full_config( + host, + azure_client_id, + azure_client_secret, + http_client, + vec![AZURE_MANAGEMENT_SCOPE.to_string()], + Some(token_url), + ) + .await?; + Some(ManagementHeaders { + token_source, + workspace_resource_id: rid, + }) + } + None => None, + }; + + Ok(Self { data, management }) + } +} + +impl crate::auth::AuthProvider for AzureServicePrincipalProvider { + fn get_auth_header(&self) -> crate::kernel_error::Result { + self.data.get_auth_header() + } + + fn extra_headers(&self) -> crate::kernel_error::Result> { + let Some(mgmt) = &self.management else { + return Ok(Vec::new()); + }; + // The management header carries the RAW access token (no `Bearer ` + // prefix), matching the connector's `cloud_token.access_token`. + let bearer = mgmt.token_source.get_auth_header()?; + let token = bearer + .strip_prefix("Bearer ") + .unwrap_or(&bearer) + .to_string(); + Ok(vec![ + ( + WORKSPACE_RESOURCE_ID_HEADER.to_string(), + mgmt.workspace_resource_id.clone(), + ), + (SP_MANAGEMENT_TOKEN_HEADER.to_string(), token), + ]) + } +} + +/// Discover the workspace's Azure tenant id by reading the `{host}/aad/auth` +/// redirect to Entra (`https://login.microsoftonline.com/{tenant}/oauth2/…`), +/// exactly as the connector's `get_azure_tenant_id_from_host` does. The tenant +/// is the first path segment of the redirect Location. Used when the caller +/// does not pass an explicit `azure_tenant_id`, so `azure-sp-m2m` is zero-config +/// on the tenant (Thrift parity). +pub(crate) async fn discover_tenant( + host: &str, + http_client: &std::sync::Arc, +) -> crate::kernel_error::Result { + use crate::client::retry::RequestType; + use crate::kernel_error::Error; + + let url = format!("{}/aad/auth", host.trim_end_matches('/')); + let request = http_client.inner().get(&url).build().map_err(|e| { + Error::io().message(format!( + "Failed to build Azure tenant-discovery request: {e}" + )) + })?; + // The workspace `/aad/auth` 302-redirects to + // `login.microsoftonline.com/{tenant}/oauth2/authorize?…`. The kernel HTTP + // client follows redirects, so the final URL still carries the tenant as + // its first path segment (the tenant stays in the path throughout the + // Microsoft login flow). Parse it from there. + let response = http_client + .execute_without_auth(request, RequestType::AuthDiscovery) + .await?; + tenant_from_login_url(response.url()) +} + +/// Parse the Azure tenant id from the Entra login URL the workspace's +/// `/aad/auth` redirects to (`https://login.microsoftonline.com/{tenant}/…`). +/// The tenant is the first path segment; the host must be a Microsoft login +/// host (guards against a non-AAD redirect on a misconfigured workspace). +/// Extracted so the parse is unit-testable without a live workspace (the HTTP +/// round-trip itself is verified against a real Azure workspace). +fn tenant_from_login_url(final_url: &reqwest::Url) -> crate::kernel_error::Result { + use crate::kernel_error::Error; + let host = final_url + .host_str() + .unwrap_or_default() + .to_ascii_lowercase(); + if !host.contains("microsoftonline") && !host.contains("chinacloudapi") { + return Err(Error::unauthenticated().message(format!( + "Azure tenant discovery: /aad/auth did not redirect to a Microsoft \ + login host (got {host:?}); pass azure_tenant_id explicitly" + ))); + } + final_url + .path_segments() + .and_then(|mut segments| segments.next()) + .filter(|s| !s.is_empty()) + .map(str::to_string) + .ok_or_else(|| { + Error::unauthenticated().message(format!( + "Azure tenant discovery: could not parse a tenant id from {final_url}; \ + pass azure_tenant_id explicitly" + )) + }) +} + #[cfg(test)] mod tests { use super::*; @@ -108,4 +346,186 @@ mod tests { assert_eq!(scopes[0], "custom-app-id/user_impersonation"); assert_eq!(scopes[1], "offline_access"); } + + #[test] + fn m2m_token_url_is_entra_v2_per_tenant() { + assert_eq!( + sp_m2m_token_url("tenant-123"), + "https://login.microsoftonline.com/tenant-123/oauth2/v2.0/token" + ); + } + + #[test] + fn m2m_scope_is_effective_app_default() { + // Prod / commercial → the prod Databricks Azure app id. + assert_eq!( + sp_m2m_scope("https://adb-1.4.azuredatabricks.net"), + format!("{AZURE_DATABRICKS_APP_ID}/.default") + ); + } + + #[test] + fn effective_app_id_is_host_specific() { + assert_eq!( + effective_app_id("https://adb-1.azuredatabricks.net"), + AZURE_DATABRICKS_APP_ID + ); + assert_eq!( + effective_app_id("https://adb-1.dev.azuredatabricks.net"), + "62a912ac-b58e-4c1d-89ea-b2dbfc7358fc" + ); + assert_eq!( + effective_app_id("https://adb-1.staging.azuredatabricks.net"), + "4a67d088-db5c-48f1-9ff2-0aace800ae68" + ); + // Sovereign / unknown → prod app id fallback. + assert_eq!( + effective_app_id("https://adb-1.databricks.azure.us"), + AZURE_DATABRICKS_APP_ID + ); + } + + #[test] + fn tenant_parsed_from_entra_login_url() { + // Matches the real /aad/auth redirect target verified against a live + // workspace: login.microsoftonline.com/{tenant}/oauth2/authorize?… + let url = reqwest::Url::parse( + "https://login.microsoftonline.com/9f37a392-f0ae-4280-9796-f1864a10effc/oauth2/authorize?client_id=x", + ) + .unwrap(); + assert_eq!( + tenant_from_login_url(&url).unwrap(), + "9f37a392-f0ae-4280-9796-f1864a10effc" + ); + } + + #[test] + fn tenant_parse_rejects_non_microsoft_host() { + // A workspace that redirects somewhere unexpected must not yield a bogus + // "tenant" — fail so the caller passes azure_tenant_id explicitly. + let url = reqwest::Url::parse("https://evil.example.com/not-a-tenant/x").unwrap(); + assert!(tenant_from_login_url(&url).is_err()); + } + + // ─── AzureServicePrincipalProvider (two-token composition) ─────────────── + // + // The Entra token endpoint (`sp_m2m_token_url`), the `{app}/.default` scope, + // and the client-credentials exchange+refresh are each unit-tested + // elsewhere. These tests cover the composition unique to this provider: the + // `Authorization` bearer is always the *data* token, and the management + // header pair is emitted (with the raw, un-`Bearer`-prefixed token) only + // when a workspace resource id is configured. A `new_with_token_url` seam + // points both token sources at a mock server (the real `new` derives the + // same URL from the tenant, which is `login.microsoftonline.com` and not + // interceptable). + use crate::auth::AuthProvider; + use crate::client::http::{DatabricksHttpClient, HttpClientConfig}; + use std::sync::Arc; + use wiremock::matchers::{body_string_contains, method, path}; + use wiremock::{Mock, MockServer, ResponseTemplate}; + + /// Mount two token responses on the same Entra endpoint, differentiated by + /// the scope carried in the request body: the Databricks-audience data + /// scope (`{app}/.default`, contains `2ff814a6`) returns `data-token`; the + /// management scope (`management.core.windows.net`) returns `mgmt-token`. + async fn mount_dual_token_endpoint(mock_server: &MockServer) { + Mock::given(method("POST")) + .and(path("/tenant-abc/oauth2/v2.0/token")) + .and(body_string_contains("management.core.windows.net")) + .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "access_token": "mgmt-token", + "token_type": "Bearer", + "expires_in": 3600, + }))) + .mount(mock_server) + .await; + Mock::given(method("POST")) + .and(path("/tenant-abc/oauth2/v2.0/token")) + .and(body_string_contains("2ff814a6")) + .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "access_token": "data-token", + "token_type": "Bearer", + "expires_in": 3600, + }))) + .mount(mock_server) + .await; + } + + #[tokio::test(flavor = "multi_thread")] + async fn sp_m2m_with_resource_id_emits_management_header_pair() { + let mock_server = MockServer::start().await; + mount_dual_token_endpoint(&mock_server).await; + let http_client = Arc::new( + DatabricksHttpClient::with_default_retry(HttpClientConfig::default()) + .expect("http client"), + ); + let token_url = format!("{}/tenant-abc/oauth2/v2.0/token", mock_server.uri()); + + let provider = AzureServicePrincipalProvider::new_with_token_url( + "https://adb-1.4.azuredatabricks.net", + "sp-client-id", + "sp-client-secret", + token_url, + Some("/subscriptions/s/resourceGroups/rg/workspace/w".to_string()), + http_client, + ) + .await + .expect("provider builds"); + + // Authorization is always the data (Databricks-audience) token. + assert_eq!(provider.get_auth_header().unwrap(), "Bearer data-token"); + + // Both management headers present; the token is raw (no `Bearer ` prefix). + let extra = provider.extra_headers().unwrap(); + assert!(extra.contains(&( + WORKSPACE_RESOURCE_ID_HEADER.to_string(), + "/subscriptions/s/resourceGroups/rg/workspace/w".to_string() + ))); + assert!(extra.contains(&( + SP_MANAGEMENT_TOKEN_HEADER.to_string(), + "mgmt-token".to_string() + ))); + } + + #[tokio::test(flavor = "multi_thread")] + async fn sp_m2m_without_resource_id_sends_data_token_only() { + let mock_server = MockServer::start().await; + // The management scope must never be requested when no resource id is set. + Mock::given(method("POST")) + .and(path("/tenant-abc/oauth2/v2.0/token")) + .and(body_string_contains("management.core.windows.net")) + .respond_with(ResponseTemplate::new(200)) + .expect(0) + .mount(&mock_server) + .await; + Mock::given(method("POST")) + .and(path("/tenant-abc/oauth2/v2.0/token")) + .and(body_string_contains("2ff814a6")) + .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "access_token": "data-token", + "token_type": "Bearer", + "expires_in": 3600, + }))) + .mount(&mock_server) + .await; + let http_client = Arc::new( + DatabricksHttpClient::with_default_retry(HttpClientConfig::default()) + .expect("http client"), + ); + let token_url = format!("{}/tenant-abc/oauth2/v2.0/token", mock_server.uri()); + + let provider = AzureServicePrincipalProvider::new_with_token_url( + "https://adb-1.4.azuredatabricks.net", + "sp-client-id", + "sp-client-secret", + token_url, + None, + http_client, + ) + .await + .expect("provider builds"); + + assert_eq!(provider.get_auth_header().unwrap(), "Bearer data-token"); + assert!(provider.extra_headers().unwrap().is_empty()); + } } diff --git a/src/auth/oauth/federation.rs b/src/auth/oauth/federation.rs index e92fdab9..ed239bb4 100644 --- a/src/auth/oauth/federation.rs +++ b/src/auth/oauth/federation.rs @@ -425,6 +425,13 @@ impl Drop for ExchangeGuard<'_> { } impl AuthProvider for FederationProvider { + /// Delegate extra headers (e.g. the Azure SP management-token pair) to the + /// wrapped provider — the federation exchange only rewrites the bearer, not + /// the accompanying headers. + fn extra_headers(&self) -> Result> { + self.inner.extra_headers() + } + fn get_auth_header(&self) -> Result { let header = self.inner.get_auth_header()?; diff --git a/src/client/http.rs b/src/client/http.rs index 3dd26d22..48c8c25f 100644 --- a/src/client/http.rs +++ b/src/client/http.rs @@ -723,6 +723,16 @@ impl DatabricksHttpClient { provider.get_auth_header() } + /// Extra auth headers to attach alongside `Authorization` (e.g. the Azure SP + /// management-token pair). Empty for every provider except the Azure SP one. + /// Errors if the auth provider has not been set. + pub fn auth_extra_headers(&self) -> Result> { + let provider = self.auth_provider.get().ok_or_else(|| { + Error::invalid_state().message("Auth provider not set. Call set_auth_provider() first.") + })?; + provider.extra_headers() + } + /// Returns the retry config for the given request category. fn retry_config(&self, category: RequestCategory) -> &RetryConfig { self.retry_configs @@ -817,6 +827,12 @@ impl DatabricksHttpClient { if with_auth { let auth_header = self.auth_header()?; req_builder = req_builder.header("Authorization", auth_header); + // Extra auth headers (Azure SP management-token pair). Empty for + // every other provider. Applied only on authenticated requests, + // never on the token/OIDC calls that use `execute_without_auth`. + for (name, value) in self.auth_extra_headers()? { + req_builder = req_builder.header(name, value); + } } // Add org ID header for multi-tenant workspace routing diff --git a/src/config.rs b/src/config.rs index 26579cba..0468d8e7 100644 --- a/src/config.rs +++ b/src/config.rs @@ -385,6 +385,35 @@ pub enum AuthConfig { identity_federation_client_id: Option, }, + /// Azure Entra ID **service-principal** machine-to-machine auth — the + /// `azure-sp-m2m` flow. Client-credentials against Entra directly + /// (`{login_host}/{tenant}/oauth2/v2.0/token`) with the Azure app + /// credentials and the `{app_id}/.default` scope. The kernel resolves the + /// endpoint, scope, and (when `azure_tenant_id` is omitted) the tenant + /// itself — so bindings forward only the credentials. The Azure + /// management-token header pair is an optional add-on gated on + /// `azure_workspace_resource_id` (see that field); a workspace-member SP + /// authenticates with the data token alone. + AzureServicePrincipal { + /// Entra app-registration client id. + azure_client_id: String, + /// Entra app-registration client secret. + azure_client_secret: String, + /// Entra tenant id. `None` → auto-discovered from the workspace's + /// `/aad/auth` redirect (matching the Thrift connector). + azure_tenant_id: Option, + /// Azure workspace ARM resource id. When set, the kernel additionally + /// fetches an Azure-management token and sends the + /// `X-Databricks-Azure-SP-Management-Token` + + /// `X-Databricks-Azure-Workspace-Resource-Id` pair, so the control + /// plane can authorize an SP that has an Azure RBAC role but is not a + /// workspace member. `None` → data token only (the common case). + azure_workspace_resource_id: Option, + /// SP-wide Workload Identity Federation client id, forwarded to the + /// federation wrapper. + identity_federation_client_id: Option, + }, + /// OAuth 2.0 token exchange (RFC 8693), for federated identity /// (e.g. exchanging a Workload Identity token for a Databricks /// access token). @@ -514,6 +543,37 @@ impl AuthConfig { } } + /// Construct a [`AuthConfig::AzureServicePrincipal`] (the `azure-sp-m2m` + /// flow), validating that the Entra `azure_client_id` / `azure_client_secret` + /// are present and non-empty. `azure_tenant_id` is optional (the kernel + /// auto-discovers it from the workspace when omitted). + pub fn azure_service_principal( + azure_client_id: Option, + azure_client_secret: Option, + azure_tenant_id: Option, + azure_workspace_resource_id: Option, + identity_federation_client_id: Option, + ) -> crate::Result { + let azure_client_id = azure_client_id.filter(|s| !s.is_empty()).ok_or_else(|| { + crate::kernel_error::Error::invalid_argument() + .message("Azure SP auth requires a non-empty azure_client_id") + })?; + let azure_client_secret = + azure_client_secret + .filter(|s| !s.is_empty()) + .ok_or_else(|| { + crate::kernel_error::Error::invalid_argument() + .message("Azure SP auth requires a non-empty azure_client_secret") + })?; + Ok(AuthConfig::AzureServicePrincipal { + azure_client_id, + azure_client_secret, + azure_tenant_id: azure_tenant_id.filter(|s| !s.is_empty()), + azure_workspace_resource_id: azure_workspace_resource_id.filter(|s| !s.is_empty()), + identity_federation_client_id, + }) + } + /// SP-wide federation client id attached to the selected base auth flow. pub(crate) fn identity_federation_client_id(&self) -> Option<&str> { match self { @@ -532,6 +592,10 @@ impl AuthConfig { | Self::AzureOAuthU2M { identity_federation_client_id, .. + } + | Self::AzureServicePrincipal { + identity_federation_client_id, + .. } => identity_federation_client_id.as_deref(), Self::OAuthFederation { .. } | Self::External(_) => None, } @@ -617,6 +681,23 @@ impl std::fmt::Debug for AuthConfig { identity_federation_client_id, ) .finish(), + Self::AzureServicePrincipal { + azure_client_id, + azure_tenant_id, + azure_workspace_resource_id, + identity_federation_client_id, + .. + } => f + .debug_struct("AzureServicePrincipal") + .field("azure_client_id", azure_client_id) + .field("azure_client_secret", &"") + .field("azure_tenant_id", azure_tenant_id) + .field("azure_workspace_resource_id", azure_workspace_resource_id) + .field( + "identity_federation_client_id", + identity_federation_client_id, + ) + .finish(), Self::OAuthFederation { subject_token_type, audience, diff --git a/src/session.rs b/src/session.rs index 55532334..7622f4d4 100644 --- a/src/session.rs +++ b/src/session.rs @@ -1263,6 +1263,42 @@ async fn build_base_auth_provider( .await?; Ok(Arc::new(provider)) } + AuthConfig::AzureServicePrincipal { + azure_client_id, + azure_client_secret, + azure_tenant_id, + azure_workspace_resource_id, + .. + } => { + // Kernel owns Azure resolution: build the Entra token endpoint + // ({login}/{tenant}/oauth2/v2.0/token) and the {app_id}/.default + // scope, discovering the tenant from the workspace's /aad/auth + // redirect when the caller omits it (Thrift parity). When a + // workspace resource id is supplied, the provider also emits the + // management-token pair (for RBAC-only SPs); otherwise it sends the + // data token alone. + use crate::auth::oauth::azure::AzureServicePrincipalProvider; + if azure_client_id.is_empty() || azure_client_secret.is_empty() { + return Err(Error::invalid_argument().message( + "AuthConfig::AzureServicePrincipal requires non-empty \ + azure_client_id and azure_client_secret", + )); + } + let tenant = match azure_tenant_id { + Some(t) if !t.is_empty() => t.clone(), + _ => crate::auth::oauth::azure::discover_tenant(host, &http_client).await?, + }; + let provider = AzureServicePrincipalProvider::new( + host, + azure_client_id, + azure_client_secret, + &tenant, + azure_workspace_resource_id.clone(), + http_client, + ) + .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() From 7c647ec3d8f40a4ea1bbcd1a311bb107c79adbd3 Mon Sep 17 00:00:00 2001 From: "peco-engineer-bot[bot]" Date: Wed, 19 Aug 2026 08:21:42 +0000 Subject: [PATCH 15/47] ai: apply changes for #263 (2 review threads) Addresses: - #3811133273 at CONNECTION_PARAMETERS.md:86 - #3811133277 at src/auth/oauth/azure.rs:249 Signed-off-by: peco-engineer-bot[bot] --- CONNECTION_PARAMETERS.md | 44 ++++++++++++------- NEXT_CHANGELOG.md | 15 +++++-- src/auth/oauth/azure.rs | 91 ++++++++++++++++++++++++++++++++++------ src/client/http.rs | 86 +++++++++++++++++++++++++++---------- 4 files changed, 182 insertions(+), 54 deletions(-) diff --git a/CONNECTION_PARAMETERS.md b/CONNECTION_PARAMETERS.md index f1fd3179..5e43cffc 100644 --- a/CONNECTION_PARAMETERS.md +++ b/CONNECTION_PARAMETERS.md @@ -75,22 +75,38 @@ bindings just select the flow. `2ff814a6-…`), `callback_timeout` (`120s`), `token_cache`. This is **not** the discovered `{host}/oidc/v1/authorize` path, which redirects to a malformed Entra URL (404) for the Azure client — the v2.0 path is the fix. -- **Azure service principal (M2M):** today via `OAuthM2M` with - `client_id`/`client_secret` = the Entra app credentials, - `token_url_override = https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token`, - and `scopes = ["2ff814a6-…/.default"]`. Setting `token_url_override` also skips - workspace OIDC discovery. A dedicated kernel-owned `azure-sp-m2m` variant (with - in-kernel `/aad/auth` tenant auto-discovery, so the tenant is optional) is the - next slice — see `docs/designs/PECOBLR-4141-azure-service-principal-design.md`. - -The Azure **management token** (`X-Databricks-Azure-SP-Management-Token`) is not -implemented — no SQL connector (Go, Node) uses it; a workspace-member SP +- **Azure service principal M2M (`AzureServicePrincipal`, `azure-sp-m2m`): + supported.** The kernel owns Azure resolution: it builds the Entra token + endpoint (`{login_host}/{tenant}/oauth2/v2.0/token`) and the + `{app_id}/.default` data scope, and — when `azure_tenant_id` is omitted — + auto-discovers the tenant from the workspace's `/aad/auth` redirect (matching + the Thrift connector), so bindings forward only the credentials. Fields: + `azure_client_id` / `azure_client_secret` (Entra app credentials, required), + `azure_tenant_id` (optional — auto-discovered when omitted), + `azure_workspace_resource_id` (optional — see below), + `identity_federation_client_id` (optional WIF). Construct via the + `AuthConfig::azure_service_principal(...)` validating constructor. See + `docs/designs/PECOBLR-4141-azure-service-principal-design.md`. + + The generic `OAuthM2M` path (Entra `token_url_override` + + `2ff814a6-…/.default` scope) still works and requires an explicit tenant; + `azure-sp-m2m` is the preferred, zero-config-tenant flow. + +The Azure **management token** (`X-Databricks-Azure-SP-Management-Token`, paired +with `X-Databricks-Azure-Workspace-Resource-Id`) is an optional add-on to +`azure-sp-m2m`, gated on `azure_workspace_resource_id`. When that field is set, +the kernel additionally fetches an Azure-management token and sends both headers, +so the control plane can authorize an SP that holds an Azure RBAC role but is not +a workspace member. When it is unset (the common case), a workspace-member SP authenticates with the data token alone. -The bindings expose these overrides as: pyo3 `token_url` / `oauth_scopes` / -`client_id`; napi `oauthTokenUrl` / `oauthScopes` / `oauthClientId`; C ABI -`kernel_session_config_set_oauth_token_endpoint` / -`kernel_session_config_set_oauth_scopes` (+ the `set_auth_*` setters). +The bindings expose the generic OAuth overrides as: pyo3 `token_url` / +`oauth_scopes` / `client_id`; napi `oauthTokenUrl` / `oauthScopes` / +`oauthClientId`; C ABI `kernel_session_config_set_oauth_token_endpoint` / +`kernel_session_config_set_oauth_scopes` (+ the `set_auth_*` setters). The pyo3 +binding additionally exposes `azure-sp-m2m` via `auth_type="azure-sp-m2m"` with +the `azure_client_id` / `azure_client_secret` / `azure_tenant_id` (optional) / +`azure_workspace_resource_id` (optional) kwargs. Two further variants are reserved but not usable in v0: `OAuthFederation` (RFC 8693 token exchange — returns `InvalidArgument` diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index dc10618d..8f648cb1 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -23,10 +23,17 @@ changes go in their respective binding's NEXT_CHANGELOG. malformed Entra URL). Live-verified end-to-end against an Azure workspace. (PECOBLR-4120.) -- Azure Entra ID OAuth support via generic overrides (no dedicated Azure auth - flow). Azure service-principal M2M rides `OAuthM2M` with an Entra - `token_url_override` + the `2ff814a6-…/.default` scope; Azure U2M rides - `OAuthU2M`. New C ABI setters expose the pieces the C surface was missing: +- Azure Entra service-principal M2M is now a kernel-owned flow + (`AuthConfig::AzureServicePrincipal` / pyo3 `auth_type="azure-sp-m2m"`). The + kernel builds the Entra token endpoint (`{login_host}/{tenant}/oauth2/v2.0/token`) + and the `{app_id}/.default` data scope, and auto-discovers the tenant from the + workspace's `/aad/auth` redirect when `azure_tenant_id` is omitted — so bindings + forward only the credentials. Setting `azure_workspace_resource_id` additionally + emits the `X-Databricks-Azure-SP-Management-Token` + + `X-Databricks-Azure-Workspace-Resource-Id` header pair for SPs authorized via + Azure RBAC rather than workspace membership. The generic `OAuthM2M` path (Entra + `token_url_override` + the `2ff814a6-…/.default` scope, explicit tenant) still + works. New C ABI setters expose the pieces the C surface was missing: `kernel_session_config_set_oauth_token_endpoint()` and `kernel_session_config_set_oauth_scopes()` — both applied to whichever OAuth mode (M2M or U2M) is selected, matching the single `oauth_scopes` / diff --git a/src/auth/oauth/azure.rs b/src/auth/oauth/azure.rs index 13b005ea..b8f99189 100644 --- a/src/auth/oauth/azure.rs +++ b/src/auth/oauth/azure.rs @@ -250,24 +250,30 @@ pub(crate) async fn discover_tenant( host: &str, http_client: &std::sync::Arc, ) -> crate::kernel_error::Result { - use crate::client::retry::RequestType; use crate::kernel_error::Error; let url = format!("{}/aad/auth", host.trim_end_matches('/')); - let request = http_client.inner().get(&url).build().map_err(|e| { - Error::io().message(format!( - "Failed to build Azure tenant-discovery request: {e}" + // Read the tenant off the FIRST `/aad/auth` redirect hop's `Location` + // (matching the connector's `get_azure_tenant_id_from_host`), NOT the final + // URL after following the whole chain. The workspace's first 3xx points at + // `login.microsoftonline.com/{tenant}/oauth2/authorize?…`; parsing that hop + // avoids assuming the tenant stays the first path segment across every + // downstream Entra redirect (a `/common/` step or a `login.live.com` bounce + // would otherwise yield a bogus "tenant" or trip the host guard). + let location = http_client.first_redirect_location(&url).await?; + let location = location.ok_or_else(|| { + Error::unauthenticated().message(format!( + "Azure tenant discovery: {url} did not return a redirect Location; \ + pass azure_tenant_id explicitly" )) })?; - // The workspace `/aad/auth` 302-redirects to - // `login.microsoftonline.com/{tenant}/oauth2/authorize?…`. The kernel HTTP - // client follows redirects, so the final URL still carries the tenant as - // its first path segment (the tenant stays in the path throughout the - // Microsoft login flow). Parse it from there. - let response = http_client - .execute_without_auth(request, RequestType::AuthDiscovery) - .await?; - tenant_from_login_url(response.url()) + let redirect_url = reqwest::Url::parse(&location).map_err(|e| { + Error::unauthenticated().message(format!( + "Azure tenant discovery: {url} redirect Location {location:?} is not a \ + valid URL ({e}); pass azure_tenant_id explicitly" + )) + })?; + tenant_from_login_url(&redirect_url) } /// Parse the Azure tenant id from the Entra login URL the workspace's @@ -407,6 +413,65 @@ mod tests { assert!(tenant_from_login_url(&url).is_err()); } + #[tokio::test(flavor = "multi_thread")] + async fn discover_tenant_reads_first_aad_auth_redirect_hop() { + // `/aad/auth` returns a 302 whose Location is the Entra authorize URL + // carrying the tenant as its first path segment. We must read that FIRST + // hop's Location and NOT follow the redirect chain onward to + // login.microsoftonline.com (which is unreachable/uninterceptable and, + // more importantly, might traverse a non-tenant-prefixed hop). Mounting + // ONLY `/aad/auth` proves discovery never issues a second request. + use crate::client::http::{DatabricksHttpClient, HttpClientConfig}; + use std::sync::Arc; + use wiremock::matchers::{method, path}; + use wiremock::{Mock, MockServer, ResponseTemplate}; + + let mock_server = MockServer::start().await; + Mock::given(method("GET")) + .and(path("/aad/auth")) + .respond_with(ResponseTemplate::new(302).insert_header( + "location", + "https://login.microsoftonline.com/9f37a392-f0ae-4280-9796-f1864a10effc/oauth2/authorize?client_id=x", + )) + .expect(1) + .mount(&mock_server) + .await; + + let http_client = Arc::new( + DatabricksHttpClient::with_default_retry(HttpClientConfig::default()) + .expect("http client"), + ); + let tenant = discover_tenant(&mock_server.uri(), &http_client) + .await + .expect("tenant discovered"); + assert_eq!(tenant, "9f37a392-f0ae-4280-9796-f1864a10effc"); + } + + #[tokio::test(flavor = "multi_thread")] + async fn discover_tenant_errors_when_no_redirect() { + // A 200 (no Location) means the workspace isn't Azure / isn't + // redirecting — surface an explicit error steering to azure_tenant_id. + use crate::client::http::{DatabricksHttpClient, HttpClientConfig}; + use std::sync::Arc; + use wiremock::matchers::{method, path}; + use wiremock::{Mock, MockServer, ResponseTemplate}; + + let mock_server = MockServer::start().await; + Mock::given(method("GET")) + .and(path("/aad/auth")) + .respond_with(ResponseTemplate::new(200)) + .mount(&mock_server) + .await; + + let http_client = Arc::new( + DatabricksHttpClient::with_default_retry(HttpClientConfig::default()) + .expect("http client"), + ); + assert!(discover_tenant(&mock_server.uri(), &http_client) + .await + .is_err()); + } + // ─── AzureServicePrincipalProvider (two-token composition) ─────────────── // // The Entra token endpoint (`sp_m2m_token_url`), the `{app}/.default` scope, diff --git a/src/client/http.rs b/src/client/http.rs index 48c8c25f..c32394a8 100644 --- a/src/client/http.rs +++ b/src/client/http.rs @@ -474,11 +474,47 @@ impl DatabricksHttpClient { })?; } + // Follow redirects for normal traffic (reqwest's default policy). + let client = Self::build_reqwest_client(&config, reqwest::redirect::Policy::default())?; + + // Surface which TLS backend was compiled in so oncall debugging + // a handshake / unknown-CA report can tell at a glance whether + // this binary is on native-tls (system CA store) or rustls + // (Mozilla webpki-roots). The two stacks differ on cert + // validation behavior, OCSP, and TLS 1.3 quirks. + debug!( + tls_backend = if cfg!(feature = "tls-rustls") { + "rustls" + } else { + "native-tls" + }, + "DatabricksHttpClient initialised" + ); + + Ok(Self { + client, + config, + auth_provider: OnceLock::new(), + retry_configs, + }) + } + + /// Build a `reqwest::Client` from `config` with the given redirect policy. + /// + /// Factored out of `new()` so tenant discovery can obtain a client that + /// does NOT follow redirects (to read the first `/aad/auth` hop's + /// `Location`) while still honouring the workspace's TLS, proxy, timeout, + /// and user-agent configuration. + fn build_reqwest_client( + config: &HttpClientConfig, + redirect: reqwest::redirect::Policy, + ) -> Result { let mut builder = Client::builder() .connect_timeout(config.connect_timeout) .timeout(config.read_timeout) .pool_max_idle_per_host(config.max_connections_per_host) - .user_agent(&config.user_agent); + .user_agent(&config.user_agent) + .redirect(redirect); // Apply TLS configuration if config.tls.enabled == Some(false) { @@ -656,29 +692,8 @@ impl DatabricksHttpClient { debug!("HTTP client using default proxy behavior (env vars)"); } - let client = builder.build().map_err(|e| { + builder.build().map_err(|e| { Error::invalid_argument().message(format!("Failed to create HTTP client: {e}")) - })?; - - // Surface which TLS backend was compiled in so oncall debugging - // a handshake / unknown-CA report can tell at a glance whether - // this binary is on native-tls (system CA store) or rustls - // (Mozilla webpki-roots). The two stacks differ on cert - // validation behavior, OCSP, and TLS 1.3 quirks. - debug!( - tls_backend = if cfg!(feature = "tls-rustls") { - "rustls" - } else { - "native-tls" - }, - "DatabricksHttpClient initialised" - ); - - Ok(Self { - client, - config, - auth_provider: OnceLock::new(), - retry_configs, }) } @@ -758,6 +773,31 @@ impl DatabricksHttpClient { self.execute_impl(request, false, request_type).await } + /// Issue a single unauthenticated GET to `url` WITHOUT following redirects + /// and return the `Location` header of the (expected) 3xx response. + /// + /// Unlike [`execute`](Self::execute) / [`execute_without_auth`], which use a + /// redirect-following client, this builds a one-off client with a + /// no-redirect policy — reqwest fixes the redirect policy at client-build + /// time — while reusing the workspace's TLS/proxy/timeout config. Used by + /// Azure tenant discovery to read the tenant off the FIRST `/aad/auth` + /// redirect hop (matching the connector's `get_azure_tenant_id_from_host`), + /// rather than parsing the final URL after following the whole Entra + /// redirect chain (which can traverse non-tenant-prefixed hops like + /// `/common/` or a `login.live.com` bounce). No retry: a single hop is + /// enough and discovery is best-effort with an explicit-tenant fallback. + pub async fn first_redirect_location(&self, url: &str) -> Result> { + let client = Self::build_reqwest_client(&self.config, reqwest::redirect::Policy::none())?; + let response = client.get(url).send().await.map_err(|e| { + Error::network_error().message(format!("Redirect-probe request to {url} failed: {e}")) + })?; + Ok(response + .headers() + .get(reqwest::header::LOCATION) + .and_then(|v| v.to_str().ok()) + .map(str::to_string)) + } + /// Internal implementation of execute with configurable auth and retry strategy. async fn execute_impl( &self, From ff4a10cd03ff5535fad4e36a15856cb6d8da5772 Mon Sep 17 00:00:00 2001 From: "peco-engineer-bot[bot]" Date: Wed, 19 Aug 2026 08:30:28 +0000 Subject: [PATCH 16/47] ai: apply changes for #263 (1 review thread) Addresses: - #3811323186 at docs/designs/PECOBLR-4141-azure-service-principal-design.md:108 Signed-off-by: peco-engineer-bot[bot] --- ...BLR-4141-azure-service-principal-design.md | 21 ++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/docs/designs/PECOBLR-4141-azure-service-principal-design.md b/docs/designs/PECOBLR-4141-azure-service-principal-design.md index 3350daca..327997d3 100644 --- a/docs/designs/PECOBLR-4141-azure-service-principal-design.md +++ b/docs/designs/PECOBLR-4141-azure-service-principal-design.md @@ -105,12 +105,17 @@ redirect available): - **Scope**: `{effective_app_id}/.default` (app id from the host's cloud). - **Credentials**: `azure_client_id` / `azure_client_secret` via HTTP Basic (Entra v2.0 advertises `client_secret_basic`; verified). -- **Management token / `azure_workspace_resource_id`: still not implemented.** - No SQL connector (Go, Node) uses it; Python's Thrift path sends it but the SQL - data path doesn't require it for a workspace-member SP. An SP that is not a - workspace member (RBAC-only) remains unsupported on the kernel path, - documented. Revisit only with a concrete SQL customer need; the seam would be a - second-token + refreshing-extra-header mechanism. +- **Management token / `azure_workspace_resource_id`: implemented (optional + add-on).** When `azure_workspace_resource_id` is supplied, the kernel + additionally fetches an Azure-management token (scope + `https://management.core.windows.net/.default`) and emits the + `X-Databricks-Azure-SP-Management-Token` + + `X-Databricks-Azure-Workspace-Resource-Id` header pair via the provider's + `extra_headers`, so the control plane can authorize an SP that holds an Azure + RBAC role but is not a workspace member. `azure_workspace_resource_id` is + optional and defaults to `None` (data token only — the common + workspace-member case). See `AZURE_MANAGEMENT_SCOPE` / + `AzureServicePrincipalProvider::extra_headers` in `src/auth/oauth/azure.rs`. ## Federation @@ -135,6 +140,7 @@ AuthConfig::AzureServicePrincipal { // azure-sp-m2m azure_client_id: String, azure_client_secret: String, azure_tenant_id: Option, // None → auto-discover via /aad/auth + azure_workspace_resource_id: Option, // Some → also send SP management-token headers identity_federation_client_id: Option, } ``` @@ -172,4 +178,5 @@ flows, incl. Go's Databricks-SP M2M and the workspace-OIDC databricks-oauth). commits). Retained as primitives. - Live test found the `/oidc/v1/authorize` 404 → authorize must be v2.0. - Decision (team): kernel is the auth core, bindings thin → Azure resolution - moves into the kernel (this doc). Management token stays out. + moves into the kernel (this doc). Management token implemented as an optional + add-on gated on `azure_workspace_resource_id` (RBAC-only SP support). From 09b5aed2fb2a3a13d9b660c8202e8b1d5e0ae4bb Mon Sep 17 00:00:00 2001 From: eric-wang-1990 Date: Wed, 19 Aug 2026 01:50:47 -0700 Subject: [PATCH 17/47] docs: mark azure-sp-m2m as kernel-owned + live-verified (PECOBLR-4141) Co-authored-by: Isaac Signed-off-by: eric-wang-1990 --- NEXT_CHANGELOG.md | 27 +++++++++++++++++---------- 1 file changed, 17 insertions(+), 10 deletions(-) diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index 8f648cb1..5bd8a5cb 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -23,17 +23,24 @@ changes go in their respective binding's NEXT_CHANGELOG. malformed Entra URL). Live-verified end-to-end against an Azure workspace. (PECOBLR-4120.) -- Azure Entra service-principal M2M is now a kernel-owned flow +- Azure Entra service-principal M2M (`azure-sp-m2m`) is now a kernel-owned flow (`AuthConfig::AzureServicePrincipal` / pyo3 `auth_type="azure-sp-m2m"`). The - kernel builds the Entra token endpoint (`{login_host}/{tenant}/oauth2/v2.0/token`) - and the `{app_id}/.default` data scope, and auto-discovers the tenant from the - workspace's `/aad/auth` redirect when `azure_tenant_id` is omitted — so bindings - forward only the credentials. Setting `azure_workspace_resource_id` additionally - emits the `X-Databricks-Azure-SP-Management-Token` + - `X-Databricks-Azure-Workspace-Resource-Id` header pair for SPs authorized via - Azure RBAC rather than workspace membership. The generic `OAuthM2M` path (Entra - `token_url_override` + the `2ff814a6-…/.default` scope, explicit tenant) still - works. New C ABI setters expose the pieces the C surface was missing: + kernel resolves the Entra token endpoint (`{login}/{tenant}/oauth2/v2.0/token`) + and the `{effective_app_id}/.default` scope, and auto-discovers the tenant from + the workspace's `/aad/auth` redirect when `azure_tenant_id` is omitted (Thrift + parity) — so bindings forward only the SP credentials. The Azure + management-token pair (`X-Databricks-Azure-SP-Management-Token` + + `X-Databricks-Azure-Workspace-Resource-Id`) is an optional add-on gated on + `azure_workspace_resource_id`: set it and the kernel fetches a second Entra + token (ARM `.default` scope) so an SP holding only an Azure RBAC role (not a + workspace member) can authenticate; omit it and the SP uses the data token + alone. A new `AuthProvider::extra_headers()` carries the dynamic pair. Common + case (tenant auto-discovered, data token only) live-verified end-to-end against + an Azure workspace. (PECOBLR-4141.) + +- Generic Azure/Entra OAuth overrides (the pre-dedicated-flow path, still valid + for custom setups where a caller pins the endpoint/scope itself). New C ABI + setters expose the pieces the C surface was missing: `kernel_session_config_set_oauth_token_endpoint()` and `kernel_session_config_set_oauth_scopes()` — both applied to whichever OAuth mode (M2M or U2M) is selected, matching the single `oauth_scopes` / From 8c69c301680f2f3059512ed1c2fdb3e94e610031 Mon Sep 17 00:00:00 2001 From: "peco-engineer-bot[bot]" Date: Wed, 19 Aug 2026 23:22:30 +0000 Subject: [PATCH 18/47] ai: apply changes for #263 (1 review thread) Addresses: - #3817431096 at src/auth/oauth/azure.rs:106 Signed-off-by: peco-engineer-bot[bot] --- src/auth/oauth/azure.rs | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/src/auth/oauth/azure.rs b/src/auth/oauth/azure.rs index b8f99189..c90bf48b 100644 --- a/src/auth/oauth/azure.rs +++ b/src/auth/oauth/azure.rs @@ -294,6 +294,22 @@ fn tenant_from_login_url(final_url: &reqwest::Url) -> crate::kernel_error::Resul login host (got {host:?}); pass azure_tenant_id explicitly" ))); } + // The tenant parses fine on sovereign clouds (USGov `login.microsoftonline.us`, + // China `login.chinacloudapi.cn`), but the M2M token exchange + // (`sp_m2m_token_url`) and `AZURE_MANAGEMENT_SCOPE` are hardcoded to the + // commercial Entra login / ARM hosts. Rather than let discovery succeed and + // then fail confusingly at the sovereign token endpoint, reject a + // non-commercial login host here with a message that names the limitation. + // Deriving the sovereign login/management hosts is the documented follow-up. + if host != "login.microsoftonline.com" { + return Err(Error::unauthenticated().message(format!( + "Azure tenant discovery: workspace redirected to a sovereign-cloud \ + login host ({host:?}), which the service-principal M2M flow does \ + not yet support (the Entra token endpoint and management scope are \ + commercial-cloud only); pass azure_tenant_id explicitly if you have \ + configured a sovereign-cloud endpoint out of band" + ))); + } final_url .path_segments() .and_then(|mut segments| segments.next()) @@ -413,6 +429,25 @@ mod tests { assert!(tenant_from_login_url(&url).is_err()); } + #[test] + fn tenant_parse_rejects_sovereign_login_host() { + // A USGov / China workspace redirects to a sovereign Entra login host, + // from which the tenant parses fine — but the M2M token endpoint and + // management scope are hardcoded to the commercial cloud, so discovery + // must fail early with a clear message instead of succeeding and then + // failing confusingly at the commercial token endpoint. + for host in [ + "https://login.microsoftonline.us/tenant-abc/oauth2/authorize?client_id=x", + "https://login.chinacloudapi.cn/tenant-abc/oauth2/authorize?client_id=x", + ] { + let url = reqwest::Url::parse(host).unwrap(); + assert!( + tenant_from_login_url(&url).is_err(), + "expected sovereign host {host:?} to be rejected" + ); + } + } + #[tokio::test(flavor = "multi_thread")] async fn discover_tenant_reads_first_aad_auth_redirect_hop() { // `/aad/auth` returns a 302 whose Location is the Entra authorize URL From f117741b4ffcfb8e99e7e019901da624e78490f3 Mon Sep 17 00:00:00 2001 From: "peco-engineer-bot[bot]" Date: Wed, 19 Aug 2026 23:32:58 +0000 Subject: [PATCH 19/47] ai: apply changes for #263 (1 review thread) Addresses: - #3817481286 at napi/src/database.rs:168 Signed-off-by: peco-engineer-bot[bot] --- napi/src/database.rs | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/napi/src/database.rs b/napi/src/database.rs index 94fdcb7c..2fcdbcdb 100644 --- a/napi/src/database.rs +++ b/napi/src/database.rs @@ -382,7 +382,7 @@ fn build_auth_config(options: &ConnectionOptions) -> napi::Result { options.jwt_passphrase.clone(), options.jwt_algorithm.clone(), options.oauth_scopes.clone(), - None, + options.oauth_token_url.clone(), ) .map_err(napi_err_from_kernel), // napi injects no client_id/scope default: it rides the kernel's @@ -732,7 +732,7 @@ mod tests { #[test] fn oauth_token_url_forwards_as_token_url_override() { // `oauthTokenUrl` must reach the built AuthConfig as - // `token_url_override` for BOTH M2M and U2M, so a Node caller can point + // `token_url_override` for M2M, M2M-JWT, and U2M, so a Node caller can point // the token exchange at an Azure/Entra endpoint. Omitting it leaves the // override `None` (kernel OIDC discovery). let endpoint = "https://login.microsoftonline.com/tenant/oauth2/v2.0/token"; @@ -759,6 +759,19 @@ mod tests { other => panic!("expected OAuthU2M, got {other:?}"), } + let mut jwt = base(); + jwt.auth_mode = Some(AuthMode::OAuthM2mJwt); + jwt.oauth_client_id = Some("cid".to_owned()); + jwt.jwt_key_file = Some("/k.pem".to_owned()); + jwt.jwt_kid = Some("kid".to_owned()); + jwt.oauth_token_url = Some(endpoint.to_owned()); + match build_auth_config(&jwt).unwrap() { + AuthConfig::OAuthM2MPrivateKey { + token_url_override, .. + } => assert_eq!(token_url_override.as_deref(), Some(endpoint)), + other => panic!("expected OAuthM2MPrivateKey, got {other:?}"), + } + // Omitted → None (default OIDC discovery). let mut none = base(); none.auth_mode = Some(AuthMode::OAuthM2m); From 2ff22bcd1c47a8b4895e3a7b711532f23a458cb6 Mon Sep 17 00:00:00 2001 From: "peco-engineer-bot[bot]" Date: Wed, 19 Aug 2026 23:41:48 +0000 Subject: [PATCH 20/47] ai: apply changes for #263 (1 review thread) Addresses: - #3817535569 at src/auth/oauth/azure.rs:92 Signed-off-by: peco-engineer-bot[bot] --- src/auth/oauth/azure.rs | 28 +++++++++++++++++++++++++--- 1 file changed, 25 insertions(+), 3 deletions(-) diff --git a/src/auth/oauth/azure.rs b/src/auth/oauth/azure.rs index c90bf48b..f8797921 100644 --- a/src/auth/oauth/azure.rs +++ b/src/auth/oauth/azure.rs @@ -90,10 +90,22 @@ const AZURE_APP_IDS_BY_SUFFIX: &[(&str, &str)] = &[ /// the M2M `.default` scope). Falls back to [`AZURE_DATABRICKS_APP_ID`] (prod) /// for commercial prod and sovereign hosts. pub(crate) fn effective_app_id(host: &str) -> &'static str { - let host = host.trim_end_matches('/').to_ascii_lowercase(); + // Reduce to the host authority (drop scheme and any path) before matching, + // so the suffix test can't be fooled by the pattern appearing mid-string. + let host = host.to_ascii_lowercase(); + let authority = host + .split_once("://") + .map(|(_, rest)| rest) + .unwrap_or(&host); + let authority = authority + .split(['/', '?', '#']) + .next() + .unwrap_or(authority) + .trim_end_matches('.'); for (suffix, app_id) in AZURE_APP_IDS_BY_SUFFIX { - // Match the host component, ignoring scheme/path. - if host.contains(suffix) { + // Match the host suffix, not a substring: a host that merely embeds the + // pattern (e.g. `adb-1.dev.azuredatabricks.net.example.com`) is not dev/staging. + if authority.ends_with(suffix) { return app_id; } } @@ -405,6 +417,16 @@ mod tests { effective_app_id("https://adb-1.databricks.azure.us"), AZURE_DATABRICKS_APP_ID ); + // A host that merely embeds the dev/staging pattern mid-string must not + // be misclassified — suffix match, not substring. + assert_eq!( + effective_app_id("https://adb-1.dev.azuredatabricks.net.example.com"), + AZURE_DATABRICKS_APP_ID + ); + assert_eq!( + effective_app_id("https://adb-1.staging.azuredatabricks.net.evil.com"), + AZURE_DATABRICKS_APP_ID + ); } #[test] From 98a8b27a2c7ab2f657a7c242b138015e7f491641 Mon Sep 17 00:00:00 2001 From: "peco-engineer-bot[bot]" Date: Wed, 19 Aug 2026 23:50:31 +0000 Subject: [PATCH 21/47] ai: apply changes for #263 (1 review thread) Addresses: - #3817585182 at include/databricks_kernel.h:284 Signed-off-by: peco-engineer-bot[bot] --- NEXT_CHANGELOG.md | 11 ++++++----- include/databricks_kernel.h | 7 ++++--- 2 files changed, 10 insertions(+), 8 deletions(-) diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index 7f4b446d..77de62da 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -43,11 +43,12 @@ changes go in their respective binding's NEXT_CHANGELOG. setters expose the pieces the C surface was missing: `kernel_session_config_set_oauth_token_endpoint()` and `kernel_session_config_set_oauth_scopes()` — both applied to whichever OAuth - mode (M2M or U2M) is selected, matching the single `oauth_scopes` / - `token_url` the pyo3 and napi bindings already share across both flows. Both - are additive — existing `set_auth_m2m` / `set_auth_u2m` signatures are - unchanged (for U2M, `set_oauth_scopes` takes precedence over scopes passed - positionally to `set_auth_u2m`). (PECOBLR-4141 / PECOBLR-4120.) + mode (M2M, M2M-JWT, or U2M) is selected, matching the single `oauth_scopes` / + `token_url` the pyo3 and napi bindings already share across those flows. Both + are additive — existing `set_auth_m2m` / `set_auth_m2m_jwt` / `set_auth_u2m` + signatures are unchanged (for U2M and M2M-JWT, `set_oauth_scopes` / + `set_oauth_token_endpoint` take precedence over scopes/token-endpoint passed + positionally to those setters). (PECOBLR-4141 / PECOBLR-4120.) - 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 diff --git a/include/databricks_kernel.h b/include/databricks_kernel.h index 71ad962a..014dbc1d 100644 --- a/include/databricks_kernel.h +++ b/include/databricks_kernel.h @@ -272,7 +272,7 @@ kernel_session_config_set_identity_federation_client_id(KernelSessionConfig* con const char* client_id); /* Optional OAuth token-endpoint override, applied to whichever OAuth mode - * (M2M or U2M) is selected. Points the token exchange at a non-workspace + * (M2M, M2M-JWT, or U2M) is selected. Points the token exchange at a non-workspace * endpoint — e.g. the Azure/Entra token endpoint * `https://login.microsoftonline.com//oauth2/v2.0/token` for an Azure * service principal. Unset → OIDC discovery against the workspace host. @@ -282,12 +282,13 @@ kernel_session_config_set_oauth_token_endpoint(KernelSessionConfig* config, const char* token_endpoint); /* Optional OAuth scopes (comma-separated), applied to whichever OAuth mode - * (M2M or U2M) is selected — e.g. + * (M2M, M2M-JWT, or U2M) is selected — e.g. * `2ff814a6-3304-4ab8-85cb-cd0e6f879c1d/.default` for an Azure service * principal (M2M), or `sql,offline_access` (U2M). Mirrors the single * `oauth_scopes` the pyo3 / napi bindings expose across both flows. Unset → * kernel per-mode default (`all-apis` for M2M; `sql offline_access` for U2M). - * For U2M it overrides any scopes passed to kernel_session_config_set_auth_u2m. */ + * For U2M and M2M-JWT it takes precedence over any scopes passed positionally + * to kernel_session_config_set_auth_u2m / kernel_session_config_set_auth_m2m_jwt. */ KernelStatusCode kernel_session_config_set_oauth_scopes(KernelSessionConfig* config, const char* scopes); From f8dc3335b711a10f00496f459ce9af5cd6c86404 Mon Sep 17 00:00:00 2001 From: "peco-engineer-bot[bot]" Date: Thu, 20 Aug 2026 00:08:37 +0000 Subject: [PATCH 22/47] ai: apply changes for #263 (3 review threads) Addresses: - #3817630011 at src/auth/oauth/u2m.rs:282 - #3817630014 at src/c_abi/session.rs:1074 - #3817630017 at src/auth/oauth/azure.rs:124 Signed-off-by: peco-engineer-bot[bot] --- src/auth/oauth/azure.rs | 5 +++-- src/auth/oauth/u2m.rs | 48 +++++++++++++++++++++++++++++++++++++++++ src/c_abi/session.rs | 38 ++++++++++++++++++++++++++++++++ 3 files changed, 89 insertions(+), 2 deletions(-) diff --git a/src/auth/oauth/azure.rs b/src/auth/oauth/azure.rs index f8797921..e79eee90 100644 --- a/src/auth/oauth/azure.rs +++ b/src/auth/oauth/azure.rs @@ -318,8 +318,9 @@ fn tenant_from_login_url(final_url: &reqwest::Url) -> crate::kernel_error::Resul "Azure tenant discovery: workspace redirected to a sovereign-cloud \ login host ({host:?}), which the service-principal M2M flow does \ not yet support (the Entra token endpoint and management scope are \ - commercial-cloud only); pass azure_tenant_id explicitly if you have \ - configured a sovereign-cloud endpoint out of band" + hardcoded to the commercial cloud); passing azure_tenant_id \ + explicitly does not help here, since the token exchange still \ + targets the commercial Entra host regardless of tenant" ))); } final_url diff --git a/src/auth/oauth/u2m.rs b/src/auth/oauth/u2m.rs index 0a3e8b8f..3e67b99d 100644 --- a/src/auth/oauth/u2m.rs +++ b/src/auth/oauth/u2m.rs @@ -821,4 +821,52 @@ mod tests { "Should fail when falling back to browser flow in unit test" ); } + + #[tokio::test(flavor = "multi_thread")] + async fn test_u2m_both_overrides_skip_discovery() { + // The Azure `azure-oauth` flow pins BOTH the v2.0 authorize and token + // endpoints because the discovered `{host}/oidc/v1/authorize` + // redirects to a malformed Entra URL for the Azure client. When both + // overrides are set, OIDC discovery must be skipped entirely and the + // provider must carry the pinned endpoints verbatim. + let mock_server = MockServer::start().await; + + // Discovery must NOT be hit when both endpoints are pinned. + 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", mock_server.uri()), + "token_endpoint": format!("{}/oidc/v1/token", mock_server.uri()), + }))) + .expect(0) + .mount(&mock_server) + .await; + + let http_client = Arc::new( + DatabricksHttpClient::with_default_retry(HttpClientConfig::default()) + .expect("Failed to create HTTP client"), + ); + + let token_endpoint = format!("{}/oidc/oauth2/v2.0/token", mock_server.uri()); + let auth_endpoint = format!("{}/oidc/oauth2/v2.0/authorize", mock_server.uri()); + + let provider = AuthorizationCodeProvider::new_with_full_config( + &mock_server.uri(), + "azure-client-id", + http_client, + vec!["all-apis".to_string(), "offline_access".to_string()], + vec![8020], + Duration::from_secs(120), + Some(token_endpoint.clone()), + None, // On-disk cache disabled so no seeded token interferes. + Some(auth_endpoint.clone()), + ) + .await + .expect("provider creation must not require discovery when both endpoints are pinned"); + + // The pinned v2.0 endpoints are carried verbatim (discovery skipped). + assert_eq!(provider.token_endpoint, token_endpoint); + assert_eq!(provider.auth_endpoint, auth_endpoint); + // Discovery `.expect(0)` is verified on mock_server drop. + } } diff --git a/src/c_abi/session.rs b/src/c_abi/session.rs index 5fcb5a9b..7b5a10ae 100644 --- a/src/c_abi/session.rs +++ b/src/c_abi/session.rs @@ -1038,6 +1038,12 @@ fn auth_spec_to_config( identity_federation_client_id: Option, token_cache: TokenCacheConfig, ) -> crate::kernel_error::Result { + // `required_str` guards only `null`, so `set_oauth_token_endpoint(config, "")` + // yields `Some("")`. Normalize a present-but-empty endpoint to `None` here so + // the `.or(token_url)` fallbacks below survive (mirroring the scopes path, + // which parses `Some("")` to `None`) instead of shadowing the positional + // `token_url` with an empty endpoint that fails opaquely at `TokenUrl::new("")`. + let oauth_token_endpoint = oauth_token_endpoint.filter(|s| !s.is_empty()); let auth = match auth { AuthSpec::Pat { token } => AuthConfig::pat(Some(token), identity_federation_client_id)?, AuthSpec::OAuthM2M { @@ -1562,6 +1568,38 @@ mod tests { } } + #[test] + fn empty_shared_oauth_token_endpoint_falls_back_to_jwt_positional_token_url() { + // A present-but-empty shared value (`set_oauth_token_endpoint("")`) must + // NOT shadow the positional `token_url`: precedence is chosen on the + // normalized result, not the raw `Option`. Otherwise the empty + // endpoint wins and fails opaquely at `TokenUrl::new("")` during the + // first token exchange. Mirrors the scopes fallback contract above. + let positional = "https://login.microsoftonline.com/tenant/oauth2/v2.0/token"; + let auth = auth_spec_to_config( + AuthSpec::OAuthM2MJwt { + client_id: "id".to_string(), + jwt_key_file: "/tmp/key.pem".to_string(), + jwt_kid: "kid".to_string(), + jwt_passphrase: None, + jwt_algorithm: None, + scopes: None, + token_url: Some(positional.to_string()), + }, + Some(String::new()), + None, + None, + TokenCacheConfig::default(), + ) + .expect("m2m jwt"); + match auth { + AuthConfig::OAuthM2MPrivateKey { + token_url_override, .. + } => assert_eq!(token_url_override.as_deref(), Some(positional)), + other => panic!("expected OAuthM2MPrivateKey, got {other:?}"), + } + } + #[test] fn parse_scopes_trims_and_drops_empties() { assert_eq!( From af1d6d102851dba56caaebf4327594e70c762f03 Mon Sep 17 00:00:00 2001 From: "peco-engineer-bot[bot]" Date: Thu, 20 Aug 2026 00:20:12 +0000 Subject: [PATCH 23/47] ai: apply changes for #263 (1 review thread) Addresses: - #3817702317 at src/session.rs:1348 Signed-off-by: peco-engineer-bot[bot] --- src/auth/oauth/azure.rs | 73 +++++++++++++++++++++++++++++++++++++++++ src/session.rs | 6 ++++ 2 files changed, 79 insertions(+) diff --git a/src/auth/oauth/azure.rs b/src/auth/oauth/azure.rs index e79eee90..0cc287b3 100644 --- a/src/auth/oauth/azure.rs +++ b/src/auth/oauth/azure.rs @@ -124,6 +124,49 @@ pub(crate) fn sp_m2m_scope(host: &str) -> String { format!("{}/.default", effective_app_id(host)) } +/// Sovereign-cloud Azure Databricks workspace host suffixes (USGov, China). +/// The SP M2M flow's Entra token endpoint ([`sp_m2m_token_url`]) and management +/// scope ([`AZURE_MANAGEMENT_SCOPE`]) are hardcoded to the commercial cloud, so +/// these are not yet supported. +const AZURE_SOVEREIGN_HOST_SUFFIXES: &[&str] = &[".databricks.azure.us", ".databricks.azure.cn"]; + +/// Reject a sovereign-cloud workspace `host` before the SP M2M flow builds a +/// commercial-only token URL. This guard is independent of tenant resolution: +/// [`tenant_from_login_url`] only fires on the auto-discovery path, so a caller +/// that passes `azure_tenant_id` explicitly would otherwise skip the check and +/// silently authenticate against the wrong (commercial) Entra host. Mirrors the +/// [`tenant_from_login_url`] sovereign message so both paths fail identically. +pub(crate) fn reject_sovereign_host_for_sp_m2m(host: &str) -> crate::kernel_error::Result<()> { + use crate::kernel_error::Error; + // Reduce to the host authority (drop scheme and any path) before matching, + // so the suffix test can't be fooled by the pattern appearing mid-string. + let host_lower = host.to_ascii_lowercase(); + let authority = host_lower + .split_once("://") + .map(|(_, rest)| rest) + .unwrap_or(&host_lower); + let authority = authority + .split(['/', '?', '#']) + .next() + .unwrap_or(authority) + .trim_end_matches('.'); + if AZURE_SOVEREIGN_HOST_SUFFIXES + .iter() + .any(|suffix| authority.ends_with(suffix)) + { + return Err(Error::unauthenticated().message(format!( + "Azure service-principal M2M: workspace host {authority:?} is a \ + sovereign-cloud (USGov/China) host, which the service-principal \ + M2M flow does not yet support (the Entra token endpoint and \ + management scope are hardcoded to the commercial cloud); passing \ + azure_tenant_id explicitly does not help here, since the token \ + exchange still targets the commercial Entra host regardless of \ + tenant" + ))); + } + Ok(()) +} + /// The Azure Resource Manager scope for the **management token** (commercial /// cloud). Matches the connector's `AZURE_MANAGED_RESOURCE` /// (`https://management.core.windows.net/`), as a v2.0 `.default` scope. @@ -471,6 +514,36 @@ mod tests { } } + #[test] + fn sp_m2m_rejects_sovereign_host_regardless_of_tenant() { + // The explicit-tenant path skips `tenant_from_login_url`, so this + // host-based guard is the only thing that stops a USGov/China caller + // from silently building a commercial-only token URL. + for host in [ + "https://adb-1.databricks.azure.us", + "https://adb-1.databricks.azure.cn", + "adb-1.databricks.azure.us/sql/1.0/warehouses/x", + ] { + assert!( + reject_sovereign_host_for_sp_m2m(host).is_err(), + "expected sovereign host {host:?} to be rejected" + ); + } + // Commercial (and dev/staging) hosts pass the guard. + for host in [ + "https://adb-1.azuredatabricks.net", + "https://adb-1.dev.azuredatabricks.net", + // A host merely embedding the sovereign pattern mid-string is not + // sovereign — suffix match, not substring. + "https://adb-1.databricks.azure.us.example.com", + ] { + assert!( + reject_sovereign_host_for_sp_m2m(host).is_ok(), + "expected commercial host {host:?} to pass" + ); + } + } + #[tokio::test(flavor = "multi_thread")] async fn discover_tenant_reads_first_aad_auth_redirect_hop() { // `/aad/auth` returns a 302 whose Location is the Entra authorize URL diff --git a/src/session.rs b/src/session.rs index 4463ba49..ec5c5624 100644 --- a/src/session.rs +++ b/src/session.rs @@ -1344,6 +1344,12 @@ async fn build_base_auth_provider( azure_client_id and azure_client_secret", )); } + // Guard sovereign-cloud hosts here, independent of tenant + // resolution: the discovery-path guard in `tenant_from_login_url` + // is skipped when the caller passes an explicit `azure_tenant_id`, + // so without this an explicit-tenant USGov/China user would + // silently build a commercial-only token URL. + crate::auth::oauth::azure::reject_sovereign_host_for_sp_m2m(host)?; let tenant = match azure_tenant_id { Some(t) if !t.is_empty() => t.clone(), _ => crate::auth::oauth::azure::discover_tenant(host, &http_client).await?, From dfd629f0b0dc6ec375833053f2dda33dedc93763 Mon Sep 17 00:00:00 2001 From: eric-wang-1990 Date: Thu, 20 Aug 2026 09:28:38 -0700 Subject: [PATCH 24/47] =?UTF-8?q?refactor(auth):=20simplify=20azure=20?= =?UTF-8?q?=E2=80=94=20drop=20SP=20management=20token,=20derive=20U2M=20au?= =?UTF-8?q?thorize=20endpoint?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two simplifications to shrink the PR: 1. Drop the optional Azure SP management-token add-on. `azure-sp-m2m` now always uses a plain client-credentials grant against Entra (the Databricks-audience data token), so the SP must be a workspace member. This removes the whole cross-cutting mechanism: the `AuthProvider::extra_headers()` trait method, its `FederationProvider` delegation and HTTP-client application, the `AzureServicePrincipalProvider` struct + `ManagementHeaders` + management-scope/header constants, and the `azure_workspace_resource_id` field threaded through config / session / pyo3. With the management token gone the provider was a pointless wrapper, so `session.rs` builds a `ClientCredentialsProvider` directly with the Entra endpoint + `{app_id}/.default` scope. RBAC-only-SP support (via the management token) is a documented follow-up. 2. Remove the `authorization_endpoint_override` parameter from the U2M provider. Only the Azure U2M flow ever pins a token endpoint, and its v2.0 authorize/token URLs differ only in the final path segment, so the provider now derives the authorize endpoint from the token override (swapping the trailing `/token` for `/authorize`). Drops the now-unused `azure::u2m_authorize_url` builder. Kernel-owned Azure resolution (endpoints, scope, tenant auto-discovery) and the live-verified data-token path are unchanged. 1008 tests pass; clippy / fmt clean. Co-authored-by: Isaac Signed-off-by: eric-wang-1990 --- NEXT_CHANGELOG.md | 24 ++- pyo3/src/auth.rs | 2 - pyo3/src/session.rs | 3 - src/auth/mod.rs | 14 -- src/auth/oauth/azure.rs | 301 +++------------------------------ src/auth/oauth/federation.rs | 7 - src/auth/oauth/u2m.rs | 72 ++++---- src/client/http.rs | 16 -- src/config.rs | 19 +-- src/session.rs | 30 ++-- tests/oauth_u2m_integration.rs | 4 - 11 files changed, 86 insertions(+), 406 deletions(-) diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index 77de62da..a875d4da 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -17,26 +17,22 @@ changes go in their respective binding's NEXT_CHANGELOG. endpoints (`{host}/oidc/oauth2/v2.0/{authorize,token}`, which the workspace redirects to Entra), the Azure app client id (`96eecda7-…`), port `8030`, and the `{app_id}/user_impersonation offline_access` scope — so bindings only - forward the selector. The U2M provider gained an authorization-endpoint - override so the Azure path pins `/oidc/oauth2/v2.0/authorize` instead of the - discovered `/oidc/v1/authorize` (which an Azure workspace redirects to a - malformed Entra URL). Live-verified end-to-end against an Azure workspace. - (PECOBLR-4120.) + forward the selector. The U2M provider derives the authorize endpoint from the + pinned token endpoint (swapping the trailing `/token` for `/authorize`), so the + Azure path uses `/oidc/oauth2/v2.0/authorize` instead of the discovered + `/oidc/v1/authorize` (which an Azure workspace redirects to a malformed Entra + URL). Live-verified end-to-end against an Azure workspace. (PECOBLR-4120.) - Azure Entra service-principal M2M (`azure-sp-m2m`) is now a kernel-owned flow (`AuthConfig::AzureServicePrincipal` / pyo3 `auth_type="azure-sp-m2m"`). The kernel resolves the Entra token endpoint (`{login}/{tenant}/oauth2/v2.0/token`) and the `{effective_app_id}/.default` scope, and auto-discovers the tenant from the workspace's `/aad/auth` redirect when `azure_tenant_id` is omitted (Thrift - parity) — so bindings forward only the SP credentials. The Azure - management-token pair (`X-Databricks-Azure-SP-Management-Token` + - `X-Databricks-Azure-Workspace-Resource-Id`) is an optional add-on gated on - `azure_workspace_resource_id`: set it and the kernel fetches a second Entra - token (ARM `.default` scope) so an SP holding only an Azure RBAC role (not a - workspace member) can authenticate; omit it and the SP uses the data token - alone. A new `AuthProvider::extra_headers()` carries the dynamic pair. Common - case (tenant auto-discovered, data token only) live-verified end-to-end against - an Azure workspace. (PECOBLR-4141.) + parity) — so bindings forward only the SP credentials. A plain + client-credentials grant against Entra yields the Databricks-audience data + token; the SP must be a workspace member. (RBAC-only SPs via the Azure + management token are a planned follow-up.) Live-verified end-to-end against an + Azure workspace. (PECOBLR-4141.) - Generic Azure/Entra OAuth overrides (the pre-dedicated-flow path, still valid for custom setups where a caller pins the endpoint/scope itself). New C ABI diff --git a/pyo3/src/auth.rs b/pyo3/src/auth.rs index 66a79807..68afaafb 100644 --- a/pyo3/src/auth.rs +++ b/pyo3/src/auth.rs @@ -77,7 +77,6 @@ pub(crate) struct OAuthParams { pub azure_client_id: Option, pub azure_client_secret: Option, pub azure_tenant_id: Option, - pub azure_workspace_resource_id: Option, } /// Default U2M OAuth client id for the **Python** binding. @@ -389,7 +388,6 @@ fn build_auth_config_inner( oauth.azure_client_id, oauth.azure_client_secret, oauth.azure_tenant_id, - oauth.azure_workspace_resource_id, oauth.identity_federation_client_id, ) .map_err(|err| err.to_string()) diff --git a/pyo3/src/session.rs b/pyo3/src/session.rs index 50ee3886..aa7a86a2 100644 --- a/pyo3/src/session.rs +++ b/pyo3/src/session.rs @@ -130,7 +130,6 @@ impl Session { azure_client_id=None, azure_client_secret=None, azure_tenant_id=None, - azure_workspace_resource_id=None, tls_ca_cert=None, tls_skip_verify=false, tls_skip_hostname_verify=false, @@ -168,7 +167,6 @@ impl Session { azure_client_id: Option, azure_client_secret: Option, azure_tenant_id: Option, - azure_workspace_resource_id: Option, tls_ca_cert: Option>, tls_skip_verify: bool, tls_skip_hostname_verify: bool, @@ -223,7 +221,6 @@ impl Session { azure_client_id, azure_client_secret, azure_tenant_id, - azure_workspace_resource_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 910ccbdf..1a560f03 100644 --- a/src/auth/mod.rs +++ b/src/auth/mod.rs @@ -32,18 +32,4 @@ use std::fmt::Debug; pub trait AuthProvider: Send + Sync + Debug { /// Returns the authorization header value for HTTP requests. fn get_auth_header(&self) -> Result; - - /// Extra headers to attach **alongside** `Authorization` on authenticated - /// requests (never on unauthenticated token/OIDC calls). Default: none. - /// - /// Overridden only by the Azure service-principal provider, which emits the - /// `X-Databricks-Azure-SP-Management-Token` + `X-Databricks-Azure-Workspace- - /// Resource-Id` pair when a workspace resource id is configured (so the - /// control plane can authorize an SP that has an Azure RBAC role but is not - /// a workspace member). These are dynamic (the management token refreshes), - /// so they cannot be static `custom_headers`. Called on every authenticated - /// request, so implementations must be cheap / internally cached. - fn extra_headers(&self) -> Result> { - Ok(Vec::new()) - } } diff --git a/src/auth/oauth/azure.rs b/src/auth/oauth/azure.rs index 0cc287b3..00ed750b 100644 --- a/src/auth/oauth/azure.rs +++ b/src/auth/oauth/azure.rs @@ -41,13 +41,10 @@ pub(crate) const AZURE_U2M_CLIENT_ID: &str = "96eecda7-19ea-49cc-abb5-240097d554 /// Default localhost redirect port registered for [`AZURE_U2M_CLIENT_ID`]. pub(crate) const AZURE_U2M_REDIRECT_PORT: u16 = 8030; -/// The workspace-hosted v2.0 **authorize** endpoint for the Azure U2M flow. -/// The workspace redirects this to the tenant's Entra authorize URL. -pub(crate) fn u2m_authorize_url(host: &str) -> String { - format!("{}/oidc/oauth2/v2.0/authorize", host.trim_end_matches('/')) -} - -/// The workspace-hosted v2.0 **token** endpoint for the Azure U2M flow. +/// The workspace-hosted v2.0 **token** endpoint for the Azure U2M flow. The +/// authorize endpoint is derived from this by the `AuthorizationCodeProvider` +/// (swapping the trailing `/token` for `/authorize`), so there is no separate +/// authorize builder. pub(crate) fn u2m_token_url(host: &str) -> String { format!("{}/oidc/oauth2/v2.0/token", host.trim_end_matches('/')) } @@ -125,9 +122,8 @@ pub(crate) fn sp_m2m_scope(host: &str) -> String { } /// Sovereign-cloud Azure Databricks workspace host suffixes (USGov, China). -/// The SP M2M flow's Entra token endpoint ([`sp_m2m_token_url`]) and management -/// scope ([`AZURE_MANAGEMENT_SCOPE`]) are hardcoded to the commercial cloud, so -/// these are not yet supported. +/// The SP M2M flow's Entra token endpoint ([`sp_m2m_token_url`]) is hardcoded to +/// the commercial cloud, so these are not yet supported. const AZURE_SOVEREIGN_HOST_SUFFIXES: &[&str] = &[".databricks.azure.us", ".databricks.azure.cn"]; /// Reject a sovereign-cloud workspace `host` before the SP M2M flow builds a @@ -167,134 +163,6 @@ pub(crate) fn reject_sovereign_host_for_sp_m2m(host: &str) -> crate::kernel_erro Ok(()) } -/// The Azure Resource Manager scope for the **management token** (commercial -/// cloud). Matches the connector's `AZURE_MANAGED_RESOURCE` -/// (`https://management.core.windows.net/`), as a v2.0 `.default` scope. -pub(crate) const AZURE_MANAGEMENT_SCOPE: &str = "https://management.core.windows.net/.default"; - -/// Header carrying the SP's Azure Resource Manager token, so the Databricks -/// control plane can validate the SP's Azure RBAC role on the workspace. -const SP_MANAGEMENT_TOKEN_HEADER: &str = "X-Databricks-Azure-SP-Management-Token"; -/// Header naming the workspace's ARM resource id (paired with the management -/// token for the RBAC lookup). -const WORKSPACE_RESOURCE_ID_HEADER: &str = "X-Databricks-Azure-Workspace-Resource-Id"; - -/// Azure service-principal M2M provider. The `Authorization` bearer is the -/// Databricks-audience data token; when a workspace resource id is configured -/// it additionally emits the management-token pair via [`AuthProvider::extra_headers`] -/// so the control plane can authorize an SP that has an Azure RBAC role but is -/// not (yet) a workspace member. Both tokens are ordinary client-credentials -/// exchanges (reusing [`ClientCredentialsProvider`], which refreshes them), so -/// the management token stays fresh on long-lived sessions. -#[derive(Debug)] -pub(crate) struct AzureServicePrincipalProvider { - data: super::m2m::ClientCredentialsProvider, - /// `Some` only when `azure_workspace_resource_id` was supplied. - management: Option, -} - -#[derive(Debug)] -struct ManagementHeaders { - token_source: super::m2m::ClientCredentialsProvider, - workspace_resource_id: String, -} - -impl AzureServicePrincipalProvider { - /// Build the provider. `tenant` is the (already-resolved) Entra tenant; - /// `host` selects the resource app id for the data scope. The management - /// token source is created only when `workspace_resource_id` is `Some`. - pub(crate) async fn new( - host: &str, - azure_client_id: &str, - azure_client_secret: &str, - tenant: &str, - workspace_resource_id: Option, - http_client: std::sync::Arc, - ) -> crate::kernel_error::Result { - Self::new_with_token_url( - host, - azure_client_id, - azure_client_secret, - sp_m2m_token_url(tenant), - workspace_resource_id, - http_client, - ) - .await - } - - /// Build the provider against an explicit Entra token endpoint. `new` - /// derives that endpoint from the tenant (`sp_m2m_token_url`); this seam - /// takes it directly so tests can point both token sources at a mock server - /// (the real endpoint host, `login.microsoftonline.com`, is not - /// interceptable). Both the data-scope and management-scope client- - /// credentials grants hit the same `token_url` with different scopes. - async fn new_with_token_url( - host: &str, - azure_client_id: &str, - azure_client_secret: &str, - token_url: String, - workspace_resource_id: Option, - http_client: std::sync::Arc, - ) -> crate::kernel_error::Result { - let data = super::m2m::ClientCredentialsProvider::new_with_full_config( - host, - azure_client_id, - azure_client_secret, - http_client.clone(), - vec![sp_m2m_scope(host)], - Some(token_url.clone()), - ) - .await?; - - let management = match workspace_resource_id { - Some(rid) => { - let token_source = super::m2m::ClientCredentialsProvider::new_with_full_config( - host, - azure_client_id, - azure_client_secret, - http_client, - vec![AZURE_MANAGEMENT_SCOPE.to_string()], - Some(token_url), - ) - .await?; - Some(ManagementHeaders { - token_source, - workspace_resource_id: rid, - }) - } - None => None, - }; - - Ok(Self { data, management }) - } -} - -impl crate::auth::AuthProvider for AzureServicePrincipalProvider { - fn get_auth_header(&self) -> crate::kernel_error::Result { - self.data.get_auth_header() - } - - fn extra_headers(&self) -> crate::kernel_error::Result> { - let Some(mgmt) = &self.management else { - return Ok(Vec::new()); - }; - // The management header carries the RAW access token (no `Bearer ` - // prefix), matching the connector's `cloud_token.access_token`. - let bearer = mgmt.token_source.get_auth_header()?; - let token = bearer - .strip_prefix("Bearer ") - .unwrap_or(&bearer) - .to_string(); - Ok(vec![ - ( - WORKSPACE_RESOURCE_ID_HEADER.to_string(), - mgmt.workspace_resource_id.clone(), - ), - (SP_MANAGEMENT_TOKEN_HEADER.to_string(), token), - ]) - } -} - /// Discover the workspace's Azure tenant id by reading the `{host}/aad/auth` /// redirect to Entra (`https://login.microsoftonline.com/{tenant}/oauth2/…`), /// exactly as the connector's `get_azure_tenant_id_from_host` does. The tenant @@ -351,19 +219,19 @@ fn tenant_from_login_url(final_url: &reqwest::Url) -> crate::kernel_error::Resul } // The tenant parses fine on sovereign clouds (USGov `login.microsoftonline.us`, // China `login.chinacloudapi.cn`), but the M2M token exchange - // (`sp_m2m_token_url`) and `AZURE_MANAGEMENT_SCOPE` are hardcoded to the - // commercial Entra login / ARM hosts. Rather than let discovery succeed and - // then fail confusingly at the sovereign token endpoint, reject a - // non-commercial login host here with a message that names the limitation. - // Deriving the sovereign login/management hosts is the documented follow-up. + // (`sp_m2m_token_url`) is hardcoded to the commercial Entra login host. + // Rather than let discovery succeed and then fail confusingly at the + // sovereign token endpoint, reject a non-commercial login host here with a + // message that names the limitation. Deriving the sovereign login host is + // the documented follow-up. if host != "login.microsoftonline.com" { return Err(Error::unauthenticated().message(format!( "Azure tenant discovery: workspace redirected to a sovereign-cloud \ login host ({host:?}), which the service-principal M2M flow does \ - not yet support (the Entra token endpoint and management scope are \ - hardcoded to the commercial cloud); passing azure_tenant_id \ - explicitly does not help here, since the token exchange still \ - targets the commercial Entra host regardless of tenant" + not yet support (the Entra token endpoint is hardcoded to the \ + commercial cloud); passing azure_tenant_id explicitly does not help \ + here, since the token exchange still targets the commercial Entra \ + host regardless of tenant" ))); } final_url @@ -384,14 +252,11 @@ mod tests { use super::*; #[test] - fn u2m_endpoints_are_workspace_v2_paths() { - // The v2.0 path is the fix for the live 404: /oidc/v1/authorize - // redirects to a malformed Entra URL, /oidc/oauth2/v2.0/authorize does not. + fn u2m_token_url_is_workspace_v2_path() { + // The v2.0 path is the fix for the live 404: the discovered + // /oidc/v1/token path's sibling authorize redirects to a malformed Entra + // URL, whereas /oidc/oauth2/v2.0/{token,authorize} does not. let host = "https://adb-123.4.azuredatabricks.net"; - assert_eq!( - u2m_authorize_url(host), - "https://adb-123.4.azuredatabricks.net/oidc/oauth2/v2.0/authorize" - ); assert_eq!( u2m_token_url(host), "https://adb-123.4.azuredatabricks.net/oidc/oauth2/v2.0/token" @@ -399,11 +264,11 @@ mod tests { } #[test] - fn u2m_endpoints_normalise_trailing_slash() { + fn u2m_token_url_normalises_trailing_slash() { let host = "https://adb-123.4.azuredatabricks.net/"; assert_eq!( - u2m_authorize_url(host), - "https://adb-123.4.azuredatabricks.net/oidc/oauth2/v2.0/authorize" + u2m_token_url(host), + "https://adb-123.4.azuredatabricks.net/oidc/oauth2/v2.0/token" ); } @@ -602,126 +467,4 @@ mod tests { .await .is_err()); } - - // ─── AzureServicePrincipalProvider (two-token composition) ─────────────── - // - // The Entra token endpoint (`sp_m2m_token_url`), the `{app}/.default` scope, - // and the client-credentials exchange+refresh are each unit-tested - // elsewhere. These tests cover the composition unique to this provider: the - // `Authorization` bearer is always the *data* token, and the management - // header pair is emitted (with the raw, un-`Bearer`-prefixed token) only - // when a workspace resource id is configured. A `new_with_token_url` seam - // points both token sources at a mock server (the real `new` derives the - // same URL from the tenant, which is `login.microsoftonline.com` and not - // interceptable). - use crate::auth::AuthProvider; - use crate::client::http::{DatabricksHttpClient, HttpClientConfig}; - use std::sync::Arc; - use wiremock::matchers::{body_string_contains, method, path}; - use wiremock::{Mock, MockServer, ResponseTemplate}; - - /// Mount two token responses on the same Entra endpoint, differentiated by - /// the scope carried in the request body: the Databricks-audience data - /// scope (`{app}/.default`, contains `2ff814a6`) returns `data-token`; the - /// management scope (`management.core.windows.net`) returns `mgmt-token`. - async fn mount_dual_token_endpoint(mock_server: &MockServer) { - Mock::given(method("POST")) - .and(path("/tenant-abc/oauth2/v2.0/token")) - .and(body_string_contains("management.core.windows.net")) - .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ - "access_token": "mgmt-token", - "token_type": "Bearer", - "expires_in": 3600, - }))) - .mount(mock_server) - .await; - Mock::given(method("POST")) - .and(path("/tenant-abc/oauth2/v2.0/token")) - .and(body_string_contains("2ff814a6")) - .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ - "access_token": "data-token", - "token_type": "Bearer", - "expires_in": 3600, - }))) - .mount(mock_server) - .await; - } - - #[tokio::test(flavor = "multi_thread")] - async fn sp_m2m_with_resource_id_emits_management_header_pair() { - let mock_server = MockServer::start().await; - mount_dual_token_endpoint(&mock_server).await; - let http_client = Arc::new( - DatabricksHttpClient::with_default_retry(HttpClientConfig::default()) - .expect("http client"), - ); - let token_url = format!("{}/tenant-abc/oauth2/v2.0/token", mock_server.uri()); - - let provider = AzureServicePrincipalProvider::new_with_token_url( - "https://adb-1.4.azuredatabricks.net", - "sp-client-id", - "sp-client-secret", - token_url, - Some("/subscriptions/s/resourceGroups/rg/workspace/w".to_string()), - http_client, - ) - .await - .expect("provider builds"); - - // Authorization is always the data (Databricks-audience) token. - assert_eq!(provider.get_auth_header().unwrap(), "Bearer data-token"); - - // Both management headers present; the token is raw (no `Bearer ` prefix). - let extra = provider.extra_headers().unwrap(); - assert!(extra.contains(&( - WORKSPACE_RESOURCE_ID_HEADER.to_string(), - "/subscriptions/s/resourceGroups/rg/workspace/w".to_string() - ))); - assert!(extra.contains(&( - SP_MANAGEMENT_TOKEN_HEADER.to_string(), - "mgmt-token".to_string() - ))); - } - - #[tokio::test(flavor = "multi_thread")] - async fn sp_m2m_without_resource_id_sends_data_token_only() { - let mock_server = MockServer::start().await; - // The management scope must never be requested when no resource id is set. - Mock::given(method("POST")) - .and(path("/tenant-abc/oauth2/v2.0/token")) - .and(body_string_contains("management.core.windows.net")) - .respond_with(ResponseTemplate::new(200)) - .expect(0) - .mount(&mock_server) - .await; - Mock::given(method("POST")) - .and(path("/tenant-abc/oauth2/v2.0/token")) - .and(body_string_contains("2ff814a6")) - .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ - "access_token": "data-token", - "token_type": "Bearer", - "expires_in": 3600, - }))) - .mount(&mock_server) - .await; - let http_client = Arc::new( - DatabricksHttpClient::with_default_retry(HttpClientConfig::default()) - .expect("http client"), - ); - let token_url = format!("{}/tenant-abc/oauth2/v2.0/token", mock_server.uri()); - - let provider = AzureServicePrincipalProvider::new_with_token_url( - "https://adb-1.4.azuredatabricks.net", - "sp-client-id", - "sp-client-secret", - token_url, - None, - http_client, - ) - .await - .expect("provider builds"); - - assert_eq!(provider.get_auth_header().unwrap(), "Bearer data-token"); - assert!(provider.extra_headers().unwrap().is_empty()); - } } diff --git a/src/auth/oauth/federation.rs b/src/auth/oauth/federation.rs index ed239bb4..e92fdab9 100644 --- a/src/auth/oauth/federation.rs +++ b/src/auth/oauth/federation.rs @@ -425,13 +425,6 @@ impl Drop for ExchangeGuard<'_> { } impl AuthProvider for FederationProvider { - /// Delegate extra headers (e.g. the Azure SP management-token pair) to the - /// wrapped provider — the federation exchange only rewrites the bearer, not - /// the accompanying headers. - fn extra_headers(&self) -> Result> { - self.inner.extra_headers() - } - fn get_auth_header(&self) -> Result { let header = self.inner.get_auth_header()?; diff --git a/src/auth/oauth/u2m.rs b/src/auth/oauth/u2m.rs index 3e67b99d..be2920dc 100644 --- a/src/auth/oauth/u2m.rs +++ b/src/auth/oauth/u2m.rs @@ -241,9 +241,8 @@ impl AuthorizationCodeProvider { scopes, vec![callback_port], callback_timeout, - None, // No token_endpoint override + None, // No token_endpoint override (discover) None, // On-disk cache disabled: no passphrase available here - None, // No authorization_endpoint override (discover) ) .await } @@ -268,26 +267,28 @@ impl AuthorizationCodeProvider { callback_timeout: Duration, token_endpoint_override: Option, cache_passphrase: Option, - authorization_endpoint_override: Option, ) -> Result { - // Resolve the authorization + token endpoints. When BOTH are - // overridden (the Azure `azure-oauth` flow pins the workspace v2.0 - // `{host}/oidc/oauth2/v2.0/{authorize,token}` paths), skip OIDC - // discovery entirely — the discovered `{host}/oidc/v1/authorize` - // redirects to a malformed Entra URL for the Azure client, so the - // caller must be able to pin the v2.0 authorize path. Otherwise - // discover and let either override fill in. - let (token_endpoint, auth_endpoint) = - match (token_endpoint_override, authorization_endpoint_override) { - (Some(token), Some(auth)) => (token, auth), - (token_override, auth_override) => { - let endpoints = OidcEndpoints::discover(host, &http_client).await?; - ( - token_override.unwrap_or(endpoints.token_endpoint), - auth_override.unwrap_or(endpoints.authorization_endpoint), - ) - } - }; + // Resolve the authorization + token endpoints. When the token endpoint + // is overridden (only the Azure `azure-oauth` flow does this, pinning + // the workspace v2.0 `{host}/oidc/oauth2/v2.0/token` path), skip OIDC + // discovery and derive the authorize endpoint from it by swapping the + // trailing `/token` for `/authorize`. This avoids a separate authorize + // override and the discovered `{host}/oidc/v1/authorize` path, which + // redirects to a malformed Entra URL for the Azure client. Otherwise + // discover both from the workspace OIDC config. + let (token_endpoint, auth_endpoint) = match token_endpoint_override { + Some(token) => { + let auth = token + .strip_suffix("/token") + .map(|base| format!("{base}/authorize")) + .unwrap_or_else(|| token.clone()); + (token, auth) + } + None => { + let endpoints = OidcEndpoints::discover(host, &http_client).await?; + (endpoints.token_endpoint, endpoints.authorization_endpoint) + } + }; // Create token store let token_store = TokenStore::new(); @@ -678,7 +679,6 @@ mod tests { Duration::from_secs(120), None, Some(TEST_CACHE_PASSPHRASE.to_string()), - None, // No authorization_endpoint override ) .await .expect("Failed to create provider"); @@ -732,7 +732,6 @@ mod tests { Duration::from_secs(120), None, Some(TEST_CACHE_PASSPHRASE.to_string()), - None, // No authorization_endpoint override ) .await .expect("Failed to create provider"); @@ -802,7 +801,6 @@ mod tests { Duration::from_secs(5), // Short timeout for test None, Some(TEST_CACHE_PASSPHRASE.to_string()), - None, // No authorization_endpoint override ) .await .expect("Failed to create provider"); @@ -823,15 +821,15 @@ mod tests { } #[tokio::test(flavor = "multi_thread")] - async fn test_u2m_both_overrides_skip_discovery() { - // The Azure `azure-oauth` flow pins BOTH the v2.0 authorize and token - // endpoints because the discovered `{host}/oidc/v1/authorize` - // redirects to a malformed Entra URL for the Azure client. When both - // overrides are set, OIDC discovery must be skipped entirely and the - // provider must carry the pinned endpoints verbatim. + async fn test_u2m_token_override_derives_authorize_and_skips_discovery() { + // The Azure `azure-oauth` flow pins the v2.0 token endpoint (the + // discovered `{host}/oidc/v1/authorize` redirects to a malformed Entra + // URL for the Azure client). When the token endpoint is overridden, OIDC + // discovery must be skipped entirely and the authorize endpoint derived + // from it (trailing `/token` → `/authorize`). let mock_server = MockServer::start().await; - // Discovery must NOT be hit when both endpoints are pinned. + // Discovery must NOT be hit when the token endpoint is pinned. Mock::given(method("GET")) .and(path("/oidc/.well-known/oauth-authorization-server")) .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ @@ -848,7 +846,6 @@ mod tests { ); let token_endpoint = format!("{}/oidc/oauth2/v2.0/token", mock_server.uri()); - let auth_endpoint = format!("{}/oidc/oauth2/v2.0/authorize", mock_server.uri()); let provider = AuthorizationCodeProvider::new_with_full_config( &mock_server.uri(), @@ -859,14 +856,17 @@ mod tests { Duration::from_secs(120), Some(token_endpoint.clone()), None, // On-disk cache disabled so no seeded token interferes. - Some(auth_endpoint.clone()), ) .await - .expect("provider creation must not require discovery when both endpoints are pinned"); + .expect("provider creation must not require discovery when the token endpoint is pinned"); - // The pinned v2.0 endpoints are carried verbatim (discovery skipped). + // The pinned token endpoint is carried verbatim; the authorize endpoint + // is derived from it (discovery skipped). assert_eq!(provider.token_endpoint, token_endpoint); - assert_eq!(provider.auth_endpoint, auth_endpoint); + assert_eq!( + provider.auth_endpoint, + format!("{}/oidc/oauth2/v2.0/authorize", mock_server.uri()) + ); // Discovery `.expect(0)` is verified on mock_server drop. } } diff --git a/src/client/http.rs b/src/client/http.rs index a95b6257..8bb882f6 100644 --- a/src/client/http.rs +++ b/src/client/http.rs @@ -738,16 +738,6 @@ impl DatabricksHttpClient { provider.get_auth_header() } - /// Extra auth headers to attach alongside `Authorization` (e.g. the Azure SP - /// management-token pair). Empty for every provider except the Azure SP one. - /// Errors if the auth provider has not been set. - pub fn auth_extra_headers(&self) -> Result> { - let provider = self.auth_provider.get().ok_or_else(|| { - Error::invalid_state().message("Auth provider not set. Call set_auth_provider() first.") - })?; - provider.extra_headers() - } - /// Returns the retry config for the given request category. fn retry_config(&self, category: RequestCategory) -> &RetryConfig { self.retry_configs @@ -867,12 +857,6 @@ impl DatabricksHttpClient { if with_auth { let auth_header = self.auth_header()?; req_builder = req_builder.header("Authorization", auth_header); - // Extra auth headers (Azure SP management-token pair). Empty for - // every other provider. Applied only on authenticated requests, - // never on the token/OIDC calls that use `execute_without_auth`. - for (name, value) in self.auth_extra_headers()? { - req_builder = req_builder.header(name, value); - } } // Add org ID header for multi-tenant workspace routing diff --git a/src/config.rs b/src/config.rs index b9b8dc85..b89a6c07 100644 --- a/src/config.rs +++ b/src/config.rs @@ -392,10 +392,10 @@ pub enum AuthConfig { /// (`{login_host}/{tenant}/oauth2/v2.0/token`) with the Azure app /// credentials and the `{app_id}/.default` scope. The kernel resolves the /// endpoint, scope, and (when `azure_tenant_id` is omitted) the tenant - /// itself — so bindings forward only the credentials. The Azure - /// management-token header pair is an optional add-on gated on - /// `azure_workspace_resource_id` (see that field); a workspace-member SP - /// authenticates with the data token alone. + /// itself — so bindings forward only the credentials. The SP authenticates + /// with the Databricks-audience data token; it must be a workspace member. + /// (Support for an RBAC-only SP via the Azure management-token header pair + /// is a planned follow-up.) AzureServicePrincipal { /// Entra app-registration client id. azure_client_id: String, @@ -404,13 +404,6 @@ pub enum AuthConfig { /// Entra tenant id. `None` → auto-discovered from the workspace's /// `/aad/auth` redirect (matching the Thrift connector). azure_tenant_id: Option, - /// Azure workspace ARM resource id. When set, the kernel additionally - /// fetches an Azure-management token and sends the - /// `X-Databricks-Azure-SP-Management-Token` + - /// `X-Databricks-Azure-Workspace-Resource-Id` pair, so the control - /// plane can authorize an SP that has an Azure RBAC role but is not a - /// workspace member. `None` → data token only (the common case). - azure_workspace_resource_id: Option, /// SP-wide Workload Identity Federation client id, forwarded to the /// federation wrapper. identity_federation_client_id: Option, @@ -581,7 +574,6 @@ impl AuthConfig { azure_client_id: Option, azure_client_secret: Option, azure_tenant_id: Option, - azure_workspace_resource_id: Option, identity_federation_client_id: Option, ) -> crate::Result { let azure_client_id = azure_client_id.filter(|s| !s.is_empty()).ok_or_else(|| { @@ -599,7 +591,6 @@ impl AuthConfig { azure_client_id, azure_client_secret, azure_tenant_id: azure_tenant_id.filter(|s| !s.is_empty()), - azure_workspace_resource_id: azure_workspace_resource_id.filter(|s| !s.is_empty()), identity_federation_client_id, }) } @@ -757,7 +748,6 @@ impl std::fmt::Debug for AuthConfig { Self::AzureServicePrincipal { azure_client_id, azure_tenant_id, - azure_workspace_resource_id, identity_federation_client_id, .. } => f @@ -765,7 +755,6 @@ impl std::fmt::Debug for AuthConfig { .field("azure_client_id", azure_client_id) .field("azure_client_secret", &"") .field("azure_tenant_id", azure_tenant_id) - .field("azure_workspace_resource_id", azure_workspace_resource_id) .field( "identity_federation_client_id", identity_federation_client_id, diff --git a/src/session.rs b/src/session.rs index ec5c5624..ec61f7d9 100644 --- a/src/session.rs +++ b/src/session.rs @@ -1276,7 +1276,6 @@ async fn build_base_auth_provider( timeout, token_url_override.clone(), cache_policy, - None, // Databricks-native U2M: discover the authorize endpoint ) .await?; Ok(Arc::new(provider)) @@ -1290,10 +1289,11 @@ async fn build_base_auth_provider( .. } => { // The kernel owns Azure resolution (it is the auth core): pin the - // workspace **v2.0** authorize+token endpoints (the workspace - // redirects them to Entra — the discovered /oidc/v1/authorize - // redirects to a malformed Entra URL), and fill the Azure app - // client id / port / delegated scope. No tenant needed for U2M. + // workspace **v2.0** token endpoint (the `AuthorizationCodeProvider` + // derives the authorize endpoint from it — the discovered + // /oidc/v1/authorize redirects to a malformed Entra URL), and fill + // the Azure app client id / port / delegated scope. No tenant needed + // for U2M (the workspace redirect resolves it). use crate::auth::oauth::azure; let client_id = client_id .clone() @@ -1318,7 +1318,6 @@ async fn build_base_auth_provider( timeout, Some(azure::u2m_token_url(host)), cache_policy, - Some(azure::u2m_authorize_url(host)), ) .await?; Ok(Arc::new(provider)) @@ -1327,17 +1326,16 @@ async fn build_base_auth_provider( azure_client_id, azure_client_secret, azure_tenant_id, - azure_workspace_resource_id, .. } => { // Kernel owns Azure resolution: build the Entra token endpoint // ({login}/{tenant}/oauth2/v2.0/token) and the {app_id}/.default // scope, discovering the tenant from the workspace's /aad/auth - // redirect when the caller omits it (Thrift parity). When a - // workspace resource id is supplied, the provider also emits the - // management-token pair (for RBAC-only SPs); otherwise it sends the - // data token alone. - use crate::auth::oauth::azure::AzureServicePrincipalProvider; + // redirect when the caller omits it (Thrift parity). This is a plain + // client-credentials grant against Entra with the Databricks-audience + // data token — the SP must be a workspace member (RBAC-only SPs, via + // the Azure management token, are a planned follow-up). + use crate::auth::oauth::azure; if azure_client_id.is_empty() || azure_client_secret.is_empty() { return Err(Error::invalid_argument().message( "AuthConfig::AzureServicePrincipal requires non-empty \ @@ -1352,15 +1350,15 @@ async fn build_base_auth_provider( crate::auth::oauth::azure::reject_sovereign_host_for_sp_m2m(host)?; let tenant = match azure_tenant_id { Some(t) if !t.is_empty() => t.clone(), - _ => crate::auth::oauth::azure::discover_tenant(host, &http_client).await?, + _ => azure::discover_tenant(host, &http_client).await?, }; - let provider = AzureServicePrincipalProvider::new( + let provider = ClientCredentialsProvider::new_with_full_config( host, azure_client_id, azure_client_secret, - &tenant, - azure_workspace_resource_id.clone(), http_client, + vec![azure::sp_m2m_scope(host)], + Some(azure::sp_m2m_token_url(&tenant)), ) .await?; Ok(Arc::new(provider)) diff --git a/tests/oauth_u2m_integration.rs b/tests/oauth_u2m_integration.rs index cebd1712..95b83782 100644 --- a/tests/oauth_u2m_integration.rs +++ b/tests/oauth_u2m_integration.rs @@ -122,7 +122,6 @@ async fn test_u2m_refresh_token_full_flow() { Duration::from_secs(120), None, Some(TEST_CACHE_PASSPHRASE.to_string()), - None, // No authorization_endpoint override ) .await .expect("Failed to create AuthorizationCodeProvider"); @@ -197,7 +196,6 @@ async fn test_u2m_refresh_token_stale_immediate_return() { Duration::from_secs(120), None, Some(TEST_CACHE_PASSPHRASE.to_string()), - None, // No authorization_endpoint override ) .await .expect("Failed to create provider"); @@ -278,7 +276,6 @@ async fn test_u2m_refresh_token_expired_fallback() { Duration::from_secs(5), // Short timeout for test None, Some(TEST_CACHE_PASSPHRASE.to_string()), - None, // No authorization_endpoint override ) .await .expect("Failed to create provider"); @@ -354,7 +351,6 @@ async fn test_u2m_refresh_updates_cache() { Duration::from_secs(120), None, Some(TEST_CACHE_PASSPHRASE.to_string()), - None, // No authorization_endpoint override ) .await .expect("Failed to create provider"); From 1e0bfd826fb0f6c31f88815ecce9a239b2ec3e5b Mon Sep 17 00:00:00 2001 From: eric-wang-1990 Date: Thu, 20 Aug 2026 10:09:40 -0700 Subject: [PATCH 25/47] test(e2e): add live azure-sp-m2m round-trip test MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Kernel-native `#[ignore]` env-gated E2E for `AuthConfig::AzureServicePrincipal`, mirroring the existing PAT / JWT-M2M live tests. Builds a Session via `azure_service_principal(...)`, opens it (tenant auto-discovered from the workspace `/aad/auth` redirect), and runs `SELECT 1`. Gated on `DATABRICKS_AZURE_CLIENT_ID` / `DATABRICKS_AZURE_CLIENT_SECRET` (optional `DATABRICKS_AZURE_TENANT_ID`); skips rather than fails when unset. Verified against a live Azure workspace: passes with a valid SP secret, and fails with AADSTS7000215 (invalid_client) on a wrong secret — confirming it genuinely performs the Entra client-credentials exchange. Co-authored-by: Isaac Signed-off-by: eric-wang-1990 --- tests/v0_execute_e2e.rs | 80 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 80 insertions(+) diff --git a/tests/v0_execute_e2e.rs b/tests/v0_execute_e2e.rs index 4e07a674..daadf507 100644 --- a/tests/v0_execute_e2e.rs +++ b/tests/v0_execute_e2e.rs @@ -120,6 +120,58 @@ async fn live_jwt_session() -> Option { ) } +/// Open a live session authenticated via the Azure Entra service-principal +/// M2M flow (`AuthConfig::AzureServicePrincipal` / `azure-sp-m2m`). +/// +/// The kernel resolves the Entra token endpoint +/// (`{login}/{tenant}/oauth2/v2.0/token`) and the `{effective_app_id}/.default` +/// scope, and auto-discovers the tenant from the workspace's `/aad/auth` +/// redirect when `DATABRICKS_AZURE_TENANT_ID` is unset. The SP must be a +/// workspace member (the data token alone authenticates it). +/// +/// Returns `None` (rather than panicking) when the Azure-specific vars are +/// absent, so the shared `v0 E2E surface` CI job skips this test instead of +/// failing it. +/// +/// Env vars (in addition to `DATABRICKS_HOST` / `DATABRICKS_HTTP_PATH`): +/// - `DATABRICKS_AZURE_CLIENT_ID` — the Entra app-registration client id +/// - `DATABRICKS_AZURE_CLIENT_SECRET` — the Entra app-registration secret +/// - `DATABRICKS_AZURE_TENANT_ID` — optional; unset → auto-discovered +async fn live_azure_sp_m2m_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, client_secret) = match ( + env_var("DATABRICKS_AZURE_CLIENT_ID"), + env_var("DATABRICKS_AZURE_CLIENT_SECRET"), + ) { + (Some(c), Some(s)) => (c, s), + _ => { + eprintln!( + "skipping azure_sp_m2m_select_one_round_trip: set \ + DATABRICKS_AZURE_CLIENT_ID and DATABRICKS_AZURE_CLIENT_SECRET to run it" + ); + return None; + } + }; + + let auth = AuthConfig::azure_service_principal( + Some(client_id), + Some(client_secret), + env_var("DATABRICKS_AZURE_TENANT_ID"), // None → auto-discover from /aad/auth + None, // no SP-wide WIF + ) + .expect("build AzureServicePrincipal config"); + + Some( + Session::builder() + .http_path(host, path) + .auth(auth) + .open() + .await + .expect("Session::open with Azure SP 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") { @@ -178,6 +230,34 @@ async fn jwt_m2m_select_one_round_trip() { session.close().await.expect("session close"); } +/// End-to-end round trip through the Azure Entra service-principal M2M flow +/// (`AuthConfig::AzureServicePrincipal`), then runs `SELECT 1`. Proves the +/// kernel discovers the tenant, exchanges the SP credentials at Entra for the +/// `{app_id}/.default` scope, and the resulting token executes a query. Skips +/// (does not fail) when the Azure SP vars are unset — see +/// [`live_azure_sp_m2m_session`] for the required env vars. +#[tokio::test(flavor = "multi_thread")] +#[ignore] +async fn azure_sp_m2m_select_one_round_trip() { + let Some(session) = live_azure_sp_m2m_session().await else { + return; // Azure SP credentials not configured — skip. + }; + let mut stmt = session.statement(); + stmt.spec().sql("SELECT 1 AS n"); + let mut exec = stmt + .execute() + .await + .expect("execute SELECT 1 via Azure SP 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() { From d3f910b18f1888caa6b1da38fd062aae855558db Mon Sep 17 00:00:00 2001 From: eric-wang-1990 Date: Thu, 20 Aug 2026 10:58:11 -0700 Subject: [PATCH 26/47] refactor(auth): drop azure-oauth (U2M); keep only azure-sp-m2m Remove the dedicated Azure Entra U2M flow (`AuthConfig::AzureOAuthU2M` / `azure-oauth`). The in-house `databricks-oauth` browser flow works against Azure workspaces (the workspace federates login to Entra) and is the default, so a dedicated Azure U2M flow adds surface without adding capability for now. Removes the variant + `azure_oauth_u2m` constructor + Debug/federation match arms (config.rs), the session build arm (session.rs), the telemetry match entries, the pyo3 `azure-oauth` arm + its tests, and the Azure U2M builders / constants (`u2m_token_url`, `u2m_scopes`, `AZURE_U2M_CLIENT_ID`, `AZURE_U2M_REDIRECT_PORT`) + their tests from azure.rs. `AZURE_DATABRICKS_APP_ID` stays (M2M scope fallback). The generic `AuthorizationCodeProvider` token-endpoint override + authorize derivation stay (now generic, for a caller-pinned U2M token endpoint). A dedicated Azure U2M flow can return later if needed. Co-authored-by: Isaac Signed-off-by: eric-wang-1990 --- NEXT_CHANGELOG.md | 12 ----- pyo3/src/auth.rs | 103 +-------------------------------------- src/auth/oauth/azure.rs | 82 +++---------------------------- src/auth/oauth/u2m.rs | 21 ++++---- src/config.rs | 71 --------------------------- src/session.rs | 42 ---------------- src/telemetry/runtime.rs | 6 +-- 7 files changed, 17 insertions(+), 320 deletions(-) diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index a875d4da..924e2280 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -11,18 +11,6 @@ changes go in their respective binding's NEXT_CHANGELOG. ### Added -- Azure Entra U2M (`azure-oauth`) is now a kernel-owned flow - (`AuthConfig::AzureOAuthU2M` / pyo3 `auth_type="azure-oauth"`). The kernel - resolves the Azure browser flow itself — it pins the workspace v2.0 - endpoints (`{host}/oidc/oauth2/v2.0/{authorize,token}`, which the workspace - redirects to Entra), the Azure app client id (`96eecda7-…`), port `8030`, and - the `{app_id}/user_impersonation offline_access` scope — so bindings only - forward the selector. The U2M provider derives the authorize endpoint from the - pinned token endpoint (swapping the trailing `/token` for `/authorize`), so the - Azure path uses `/oidc/oauth2/v2.0/authorize` instead of the discovered - `/oidc/v1/authorize` (which an Azure workspace redirects to a malformed Entra - URL). Live-verified end-to-end against an Azure workspace. (PECOBLR-4120.) - - Azure Entra service-principal M2M (`azure-sp-m2m`) is now a kernel-owned flow (`AuthConfig::AzureServicePrincipal` / pyo3 `auth_type="azure-sp-m2m"`). The kernel resolves the Entra token endpoint (`{login}/{tenant}/oauth2/v2.0/token`) diff --git a/pyo3/src/auth.rs b/pyo3/src/auth.rs index 68afaafb..56c2f3f5 100644 --- a/pyo3/src/auth.rs +++ b/pyo3/src/auth.rs @@ -325,59 +325,6 @@ fn build_auth_config_inner( oauth.identity_federation_client_id, )) } - "azure-oauth" => { - // Azure Entra U2M. The kernel owns Azure resolution (it is the - // auth core): it pins the workspace v2.0 authorize/token endpoints, - // the Azure app client id, port 8030, and the - // `{app_id}/user_impersonation offline_access` scope. The binding - // only forwards optional overrides — no endpoint/scope construction - // here. The `app_id` scope-resource override (the connector's - // `DATABRICKS_AZURE_TENANT_ID`) is NOT yet forwarded from Python: - // we always pass `None` below so the kernel default applies. A - // dedicated kwarg can wire it through if a caller needs to override - // it; `token_url` is not consulted for this flow. - if matches!(oauth.client_id.as_deref(), Some("")) { - return Err("auth_type='azure-oauth' client_id must be non-empty when set; \ - omit it to use the default Azure app" - .to_owned()); - } - // `redirect_ports` / `callback_timeout_secs` carry the same U2M - // semantics here as in the `oauth-u2m` arm, so reject the same - // present-yet-degenerate shapes: a 0 timeout times the browser - // flow out immediately, and an empty list / 0 port entry binds an - // ephemeral port that can't match the IdP's static redirect_uri. - if oauth.callback_timeout_secs == Some(0) { - return Err( - "auth_type='azure-oauth' oauth_callback_timeout_secs must be > 0 when set \ - (0 would time out the browser flow immediately); omit it for the default" - .to_owned(), - ); - } - if let Some(ports) = oauth.redirect_ports.as_deref() { - if ports.is_empty() { - return Err( - "auth_type='azure-oauth' redirect_ports must be non-empty when set; \ - omit it for the default" - .to_owned(), - ); - } - if ports.contains(&0) { - return Err( - "auth_type='azure-oauth' redirect_ports entries must be non-zero \ - (each must be a static port the IdP redirect_uri can match)" - .to_owned(), - ); - } - } - Ok(AuthConfig::azure_oauth_u2m( - oauth.client_id, - oauth.redirect_ports, - None, // app_id: kernel default (2ff814a6-…) / DATABRICKS_AZURE_TENANT_ID - oauth.callback_timeout_secs.map(Duration::from_secs), - None, // token_cache: kernel default (enabled, machine-local key) - oauth.identity_federation_client_id, - )) - } "azure-sp-m2m" => { // Azure Entra service-principal M2M. The kernel owns Azure // resolution: it builds the Entra token endpoint + `.default` @@ -394,7 +341,7 @@ fn build_auth_config_inner( } other => Err(format!( "unsupported auth_type {other:?}; expected one of 'pat', 'oauth-m2m', \ - 'oauth-m2m-jwt', 'oauth-u2m', 'azure-oauth', 'azure-sp-m2m'" + 'oauth-m2m-jwt', 'oauth-u2m', 'azure-sp-m2m'" )), } } @@ -817,54 +764,6 @@ mod tests { ); } - #[test] - fn azure_oauth_rejects_zero_callback_timeout() { - let err = build_auth_config_inner( - "azure-oauth", - None, - OAuthParams { - callback_timeout_secs: Some(0), - ..Default::default() - }, - ) - .unwrap_err(); - assert!( - err.contains("oauth_callback_timeout_secs must be > 0"), - "{err}" - ); - } - - #[test] - fn azure_oauth_rejects_empty_redirect_ports() { - let err = build_auth_config_inner( - "azure-oauth", - None, - OAuthParams { - redirect_ports: Some(vec![]), - ..Default::default() - }, - ) - .unwrap_err(); - assert!( - err.contains("redirect_ports must be non-empty"), - "got: {err}" - ); - } - - #[test] - fn azure_oauth_rejects_zero_in_redirect_ports() { - let err = build_auth_config_inner( - "azure-oauth", - None, - OAuthParams { - redirect_ports: Some(vec![8020, 0]), - ..Default::default() - }, - ) - .unwrap_err(); - assert!(err.contains("non-zero"), "got: {err}"); - } - #[test] fn unknown_auth_type_rejected() { let err = build_auth_config_inner("kerberos", None, OAuthParams::default()).unwrap_err(); diff --git a/src/auth/oauth/azure.rs b/src/auth/oauth/azure.rs index 00ed750b..698df554 100644 --- a/src/auth/oauth/azure.rs +++ b/src/auth/oauth/azure.rs @@ -18,48 +18,17 @@ //! Azure endpoints, scopes, and app ids, that knowledge lives here once and is //! shared by every binding (mirroring how the Go driver's core infers the //! cloud). This module holds the Azure constants and the endpoint/scope -//! builders used by the `azure-oauth` (U2M) and `azure-sp-m2m` (M2M) flows. +//! builders used by the `azure-sp-m2m` (service-principal M2M) flow. //! -//! **U2M (`azure-oauth`)** uses the **workspace-hosted v2.0** endpoints -//! (`{host}/oidc/oauth2/v2.0/{authorize,token}`) — the same pattern the Go -//! driver uses. The workspace redirects the browser to Entra, so no tenant is -//! needed. This is deliberately NOT the OIDC-discovered `{host}/oidc/v1/authorize` -//! path: a live test showed the workspace redirects that to a malformed -//! `login.microsoftonline.com/{tenant}/v1/authorize` (404), whereas the -//! `/oidc/oauth2/v2.0/authorize` path redirects to a valid Entra URL. +//! (Azure U2M has no dedicated flow: the in-house `databricks-oauth` browser +//! flow works against Azure workspaces, so it is the default there.) /// Databricks first-party "Azure Databricks" application id (production). Used -/// as the default resource in the U2M delegated scope and as the M2M `.default` -/// resource. Constant across clouds for the scope; the connector's -/// `DATABRICKS_AZURE_TENANT_ID` env override maps onto the `app_id` argument. +/// as the M2M `{app_id}/.default` scope resource fallback. Constant across +/// clouds; the connector's `DATABRICKS_AZURE_TENANT_ID` env override maps onto +/// the resource app id. pub(crate) const AZURE_DATABRICKS_APP_ID: &str = "2ff814a6-3304-4ab8-85cb-cd0e6f879c1d"; -/// OAuth client id for the Azure U2M browser flow. Matches the connectors' -/// `PYSQL_OAUTH_AZURE_CLIENT_ID` / Go's `azureClientId`. -pub(crate) const AZURE_U2M_CLIENT_ID: &str = "96eecda7-19ea-49cc-abb5-240097d554f5"; - -/// Default localhost redirect port registered for [`AZURE_U2M_CLIENT_ID`]. -pub(crate) const AZURE_U2M_REDIRECT_PORT: u16 = 8030; - -/// The workspace-hosted v2.0 **token** endpoint for the Azure U2M flow. The -/// authorize endpoint is derived from this by the `AuthorizationCodeProvider` -/// (swapping the trailing `/token` for `/authorize`), so there is no separate -/// authorize builder. -pub(crate) fn u2m_token_url(host: &str) -> String { - format!("{}/oidc/oauth2/v2.0/token", host.trim_end_matches('/')) -} - -/// The AAD delegated scope set for U2M: `{app_id}/user_impersonation` plus -/// `offline_access` (so a refresh token is issued). `app_id` defaults to -/// [`AZURE_DATABRICKS_APP_ID`] when the caller doesn't override it. -pub(crate) fn u2m_scopes(app_id: Option<&str>) -> Vec { - let app = app_id.unwrap_or(AZURE_DATABRICKS_APP_ID); - vec![ - format!("{app}/user_impersonation"), - "offline_access".to_string(), - ] -} - // ─── M2M (azure-sp-m2m) ────────────────────────────────────────────────────── /// Entra (Azure AD) login host. The connector's SP M2M path hardcodes the @@ -251,45 +220,6 @@ fn tenant_from_login_url(final_url: &reqwest::Url) -> crate::kernel_error::Resul mod tests { use super::*; - #[test] - fn u2m_token_url_is_workspace_v2_path() { - // The v2.0 path is the fix for the live 404: the discovered - // /oidc/v1/token path's sibling authorize redirects to a malformed Entra - // URL, whereas /oidc/oauth2/v2.0/{token,authorize} does not. - let host = "https://adb-123.4.azuredatabricks.net"; - assert_eq!( - u2m_token_url(host), - "https://adb-123.4.azuredatabricks.net/oidc/oauth2/v2.0/token" - ); - } - - #[test] - fn u2m_token_url_normalises_trailing_slash() { - let host = "https://adb-123.4.azuredatabricks.net/"; - assert_eq!( - u2m_token_url(host), - "https://adb-123.4.azuredatabricks.net/oidc/oauth2/v2.0/token" - ); - } - - #[test] - fn u2m_scopes_default_to_databricks_app_impersonation() { - assert_eq!( - u2m_scopes(None), - vec![ - format!("{AZURE_DATABRICKS_APP_ID}/user_impersonation"), - "offline_access".to_string() - ] - ); - } - - #[test] - fn u2m_scopes_honour_app_id_override() { - let scopes = u2m_scopes(Some("custom-app-id")); - assert_eq!(scopes[0], "custom-app-id/user_impersonation"); - assert_eq!(scopes[1], "offline_access"); - } - #[test] fn m2m_token_url_is_entra_v2_per_tenant() { assert_eq!( diff --git a/src/auth/oauth/u2m.rs b/src/auth/oauth/u2m.rs index be2920dc..4ebbcf2e 100644 --- a/src/auth/oauth/u2m.rs +++ b/src/auth/oauth/u2m.rs @@ -269,13 +269,12 @@ impl AuthorizationCodeProvider { cache_passphrase: Option, ) -> Result { // Resolve the authorization + token endpoints. When the token endpoint - // is overridden (only the Azure `azure-oauth` flow does this, pinning - // the workspace v2.0 `{host}/oidc/oauth2/v2.0/token` path), skip OIDC - // discovery and derive the authorize endpoint from it by swapping the - // trailing `/token` for `/authorize`. This avoids a separate authorize - // override and the discovered `{host}/oidc/v1/authorize` path, which - // redirects to a malformed Entra URL for the Azure client. Otherwise - // discover both from the workspace OIDC config. + // is overridden, skip OIDC discovery and derive the authorize endpoint + // from it by swapping the trailing `/token` for `/authorize` (the two + // are siblings under a shared base for the OAuth2 v2.0 layout the + // override targets). This avoids a separate authorize override and a + // needless discovery round-trip. Otherwise discover both from the + // workspace OIDC config. let (token_endpoint, auth_endpoint) = match token_endpoint_override { Some(token) => { let auth = token @@ -822,11 +821,9 @@ mod tests { #[tokio::test(flavor = "multi_thread")] async fn test_u2m_token_override_derives_authorize_and_skips_discovery() { - // The Azure `azure-oauth` flow pins the v2.0 token endpoint (the - // discovered `{host}/oidc/v1/authorize` redirects to a malformed Entra - // URL for the Azure client). When the token endpoint is overridden, OIDC - // discovery must be skipped entirely and the authorize endpoint derived - // from it (trailing `/token` → `/authorize`). + // When the token endpoint is overridden, OIDC discovery must be skipped + // entirely and the authorize endpoint derived from it (trailing + // `/token` → `/authorize`). let mock_server = MockServer::start().await; // Discovery must NOT be hit when the token endpoint is pinned. diff --git a/src/config.rs b/src/config.rs index b89a6c07..ff07709d 100644 --- a/src/config.rs +++ b/src/config.rs @@ -360,33 +360,6 @@ pub enum AuthConfig { identity_federation_client_id: Option, }, - /// Azure Entra ID user-to-machine (browser) auth — the `azure-oauth` - /// flow. Unlike [`Self::OAuthU2M`] (Databricks-native OIDC), this uses - /// the workspace's **v2.0** authorize/token endpoints - /// (`{host}/oidc/oauth2/v2.0/{authorize,token}`), which the workspace - /// redirects to Microsoft Entra, and the Azure delegated scope - /// `{app_id}/user_impersonation offline_access`. The kernel resolves all - /// of that from the host, so bindings only forward the (optional) - /// overrides. No tenant is needed (the workspace redirect resolves it). - AzureOAuthU2M { - /// OAuth client id. `None` → the Azure Databricks app - /// (`96eecda7-…`). - client_id: Option, - /// Candidate localhost callback ports. `None`/empty → `[8030]`. - redirect_ports: Option>, - /// Resource app id used in the `{app_id}/user_impersonation` scope. - /// `None` → the Azure Databricks app id (`2ff814a6-…`); a binding - /// forwards the `DATABRICKS_AZURE_TENANT_ID` override here. - app_id: Option, - /// How long to wait for the browser callback. `None` → 120s. - callback_timeout: Option, - /// On-disk token-cache policy. `None` → [`TokenCacheConfig::default`]. - token_cache: Option, - /// SP-wide Workload Identity Federation client id, forwarded to the - /// federation wrapper. - identity_federation_client_id: Option, - }, - /// Azure Entra ID **service-principal** machine-to-machine auth — the /// `azure-sp-m2m` flow. Client-credentials against Entra directly /// (`{login_host}/{tenant}/oauth2/v2.0/token`) with the Azure app @@ -542,30 +515,6 @@ impl AuthConfig { } } - /// Construct a [`AuthConfig::AzureOAuthU2M`] (the `azure-oauth` browser - /// flow) from optional fields. All fields are optional — the kernel fills - /// the Azure app client id (`96eecda7-…`), port `8030`, and the - /// `{app_id}/user_impersonation offline_access` scope — so this performs no - /// validation and exists for symmetry with the other constructors so - /// bindings can forward optionals uniformly. - pub fn azure_oauth_u2m( - client_id: Option, - redirect_ports: Option>, - app_id: Option, - callback_timeout: Option, - token_cache: Option, - identity_federation_client_id: Option, - ) -> Self { - AuthConfig::AzureOAuthU2M { - client_id, - redirect_ports, - app_id, - callback_timeout, - token_cache, - identity_federation_client_id, - } - } - /// Construct a [`AuthConfig::AzureServicePrincipal`] (the `azure-sp-m2m` /// flow), validating that the Entra `azure_client_id` / `azure_client_secret` /// are present and non-empty. `azure_tenant_id` is optional (the kernel @@ -610,10 +559,6 @@ impl AuthConfig { identity_federation_client_id, .. } - | Self::AzureOAuthU2M { - identity_federation_client_id, - .. - } | Self::AzureServicePrincipal { identity_federation_client_id, .. @@ -729,22 +674,6 @@ impl std::fmt::Debug for AuthConfig { identity_federation_client_id, ) .finish(), - Self::AzureOAuthU2M { - client_id, - redirect_ports, - app_id, - identity_federation_client_id, - .. - } => f - .debug_struct("AzureOAuthU2M") - .field("client_id", client_id) - .field("redirect_ports", redirect_ports) - .field("app_id", app_id) - .field( - "identity_federation_client_id", - identity_federation_client_id, - ) - .finish(), Self::AzureServicePrincipal { azure_client_id, azure_tenant_id, diff --git a/src/session.rs b/src/session.rs index ec61f7d9..38d9c4fc 100644 --- a/src/session.rs +++ b/src/session.rs @@ -1280,48 +1280,6 @@ async fn build_base_auth_provider( .await?; Ok(Arc::new(provider)) } - AuthConfig::AzureOAuthU2M { - client_id, - redirect_ports, - app_id, - callback_timeout, - token_cache, - .. - } => { - // The kernel owns Azure resolution (it is the auth core): pin the - // workspace **v2.0** token endpoint (the `AuthorizationCodeProvider` - // derives the authorize endpoint from it — the discovered - // /oidc/v1/authorize redirects to a malformed Entra URL), and fill - // the Azure app client id / port / delegated scope. No tenant needed - // for U2M (the workspace redirect resolves it). - use crate::auth::oauth::azure; - let client_id = client_id - .clone() - .unwrap_or_else(|| azure::AZURE_U2M_CLIENT_ID.to_string()); - let callback_ports = match redirect_ports.as_deref() { - Some(ports) if !ports.is_empty() => ports.to_vec(), - _ => vec![azure::AZURE_U2M_REDIRECT_PORT], - }; - let scopes = azure::u2m_scopes(app_id.as_deref()); - let timeout = callback_timeout.unwrap_or_else(|| Duration::from_secs(120)); - let cache_policy = token_cache - .clone() - .unwrap_or_default() - .resolve() - .map(|p| p.into_owned()); - let provider = AuthorizationCodeProvider::new_with_full_config( - host, - &client_id, - http_client, - scopes, - callback_ports, - timeout, - Some(azure::u2m_token_url(host)), - cache_policy, - ) - .await?; - Ok(Arc::new(provider)) - } AuthConfig::AzureServicePrincipal { azure_client_id, azure_client_secret, diff --git a/src/telemetry/runtime.rs b/src/telemetry/runtime.rs index 3fb26f24..ecac7c45 100644 --- a/src/telemetry/runtime.rs +++ b/src/telemetry/runtime.rs @@ -310,7 +310,6 @@ fn auth_type(auth: &AuthConfig) -> String { AuthConfig::OAuthM2M { .. } => "oauth-m2m", AuthConfig::OAuthM2MPrivateKey { .. } => "oauth-m2m-jwt", AuthConfig::OAuthU2M { .. } => "oauth-u2m", - AuthConfig::AzureOAuthU2M { .. } => "azure-oauth", AuthConfig::AzureServicePrincipal { .. } => "azure-sp-m2m", AuthConfig::OAuthFederation { .. } => "oauth-federation", AuthConfig::External(_) => "external", @@ -324,7 +323,6 @@ fn auth_mech(auth: &AuthConfig) -> DriverAuthMech { AuthConfig::OAuthM2M { .. } | AuthConfig::OAuthM2MPrivateKey { .. } | AuthConfig::OAuthU2M { .. } - | AuthConfig::AzureOAuthU2M { .. } | AuthConfig::AzureServicePrincipal { .. } | AuthConfig::OAuthFederation { .. } => DriverAuthMech::Oauth, AuthConfig::External(_) => DriverAuthMech::Other, @@ -337,9 +335,7 @@ fn auth_flow(auth: &AuthConfig) -> Option { AuthConfig::OAuthM2M { .. } | AuthConfig::OAuthM2MPrivateKey { .. } | AuthConfig::AzureServicePrincipal { .. } => Some(DriverAuthFlow::ClientCredentials), - AuthConfig::OAuthU2M { .. } | AuthConfig::AzureOAuthU2M { .. } => { - Some(DriverAuthFlow::BrowserBasedAuthentication) - } + AuthConfig::OAuthU2M { .. } => Some(DriverAuthFlow::BrowserBasedAuthentication), AuthConfig::OAuthFederation { .. } | AuthConfig::External(_) => None, } } From f6bdac39d2367865e4b1c72b671599c4e57e56fd Mon Sep 17 00:00:00 2001 From: "peco-engineer-bot[bot]" Date: Thu, 20 Aug 2026 18:09:19 +0000 Subject: [PATCH 27/47] ai: apply changes for #263 (3 review threads) Addresses: - #3817764317 at pyo3/src/auth.rs:74 - #3823999499 at CONNECTION_PARAMETERS.md:86 - #3823999503 at docs/designs/PECOBLR-4141-azure-service-principal-design.md:108 Signed-off-by: peco-engineer-bot[bot] --- CONNECTION_PARAMETERS.md | 15 +++++------- ...BLR-4141-azure-service-principal-design.md | 23 ++++++++++--------- pyo3/src/auth.rs | 8 +++++-- 3 files changed, 24 insertions(+), 22 deletions(-) diff --git a/CONNECTION_PARAMETERS.md b/CONNECTION_PARAMETERS.md index 5e43cffc..2f8419ad 100644 --- a/CONNECTION_PARAMETERS.md +++ b/CONNECTION_PARAMETERS.md @@ -83,7 +83,6 @@ bindings just select the flow. the Thrift connector), so bindings forward only the credentials. Fields: `azure_client_id` / `azure_client_secret` (Entra app credentials, required), `azure_tenant_id` (optional — auto-discovered when omitted), - `azure_workspace_resource_id` (optional — see below), `identity_federation_client_id` (optional WIF). Construct via the `AuthConfig::azure_service_principal(...)` validating constructor. See `docs/designs/PECOBLR-4141-azure-service-principal-design.md`. @@ -92,21 +91,19 @@ bindings just select the flow. `2ff814a6-…/.default` scope) still works and requires an explicit tenant; `azure-sp-m2m` is the preferred, zero-config-tenant flow. -The Azure **management token** (`X-Databricks-Azure-SP-Management-Token`, paired -with `X-Databricks-Azure-Workspace-Resource-Id`) is an optional add-on to -`azure-sp-m2m`, gated on `azure_workspace_resource_id`. When that field is set, -the kernel additionally fetches an Azure-management token and sends both headers, +The `azure-sp-m2m` flow authenticates a workspace-member SP with the Databricks +data token alone. (An Azure **management-token** add-on — sending +`X-Databricks-Azure-SP-Management-Token` + `X-Databricks-Azure-Workspace-Resource-Id` so the control plane can authorize an SP that holds an Azure RBAC role but is not -a workspace member. When it is unset (the common case), a workspace-member SP -authenticates with the data token alone. +a workspace member — is not implemented in v0.) The bindings expose the generic OAuth overrides as: pyo3 `token_url` / `oauth_scopes` / `client_id`; napi `oauthTokenUrl` / `oauthScopes` / `oauthClientId`; C ABI `kernel_session_config_set_oauth_token_endpoint` / `kernel_session_config_set_oauth_scopes` (+ the `set_auth_*` setters). The pyo3 binding additionally exposes `azure-sp-m2m` via `auth_type="azure-sp-m2m"` with -the `azure_client_id` / `azure_client_secret` / `azure_tenant_id` (optional) / -`azure_workspace_resource_id` (optional) kwargs. +the `azure_client_id` / `azure_client_secret` / `azure_tenant_id` (optional) +kwargs. Two further variants are reserved but not usable in v0: `OAuthFederation` (RFC 8693 token exchange — returns `InvalidArgument` diff --git a/docs/designs/PECOBLR-4141-azure-service-principal-design.md b/docs/designs/PECOBLR-4141-azure-service-principal-design.md index 327997d3..609855bd 100644 --- a/docs/designs/PECOBLR-4141-azure-service-principal-design.md +++ b/docs/designs/PECOBLR-4141-azure-service-principal-design.md @@ -105,17 +105,18 @@ redirect available): - **Scope**: `{effective_app_id}/.default` (app id from the host's cloud). - **Credentials**: `azure_client_id` / `azure_client_secret` via HTTP Basic (Entra v2.0 advertises `client_secret_basic`; verified). -- **Management token / `azure_workspace_resource_id`: implemented (optional - add-on).** When `azure_workspace_resource_id` is supplied, the kernel - additionally fetches an Azure-management token (scope - `https://management.core.windows.net/.default`) and emits the +- **Management token / `azure_workspace_resource_id`: planned (optional + add-on), not yet implemented.** When supplied, the kernel would + additionally fetch an Azure-management token (scope + `https://management.core.windows.net/.default`) and emit the `X-Databricks-Azure-SP-Management-Token` + - `X-Databricks-Azure-Workspace-Resource-Id` header pair via the provider's - `extra_headers`, so the control plane can authorize an SP that holds an Azure - RBAC role but is not a workspace member. `azure_workspace_resource_id` is - optional and defaults to `None` (data token only — the common - workspace-member case). See `AZURE_MANAGEMENT_SCOPE` / - `AzureServicePrincipalProvider::extra_headers` in `src/auth/oauth/azure.rs`. + `X-Databricks-Azure-Workspace-Resource-Id` header pair, so the control + plane can authorize an SP that holds an Azure RBAC role but is not a + workspace member. It would be optional and default to `None` (data token + only — the common workspace-member case). This slice is not in the current + cut: the `AzureServicePrincipal` variant has no `azure_workspace_resource_id` + field yet, and no management-token support exists in + `src/auth/oauth/azure.rs`. ## Federation @@ -140,7 +141,7 @@ AuthConfig::AzureServicePrincipal { // azure-sp-m2m azure_client_id: String, azure_client_secret: String, azure_tenant_id: Option, // None → auto-discover via /aad/auth - azure_workspace_resource_id: Option, // Some → also send SP management-token headers + // azure_workspace_resource_id: planned (management-token headers) — not in the current cut identity_federation_client_id: Option, } ``` diff --git a/pyo3/src/auth.rs b/pyo3/src/auth.rs index 56c2f3f5..54b10385 100644 --- a/pyo3/src/auth.rs +++ b/pyo3/src/auth.rs @@ -14,7 +14,7 @@ //! Translate Python auth kwargs into a kernel `AuthConfig`. //! -//! Supports four `auth_type` values: +//! Supports five `auth_type` values: //! //! - `"pat"` — personal access token (`access_token`). //! - `"oauth-m2m"` — OAuth 2.0 client-credentials (service principal): @@ -26,6 +26,9 @@ //! - `"oauth-u2m"` — OAuth 2.0 authorization-code + PKCE browser flow: //! optional `client_id` / `redirect_ports` / `scopes` / `token_url` / //! `oauth_callback_timeout_secs`. +//! - `"azure-sp-m2m"` — Azure Entra service-principal M2M: +//! `azure_client_id` + `azure_client_secret`, optional +//! `azure_tenant_id` (auto-discovered from the workspace when omitted). //! //! OAuth is **kernel-owned**: the kernel acquires and refreshes tokens //! itself (OIDC discovery against the workspace host, transparent @@ -141,7 +144,8 @@ const PYSQL_OAUTH_REDIRECT_PORT: u16 = 8020; /// Build a kernel `AuthConfig` from the Python kwargs the `Session` /// constructor accepts. /// -/// `auth_type` is one of `"pat"`, `"oauth-m2m"`, `"oauth-u2m"`. Thin +/// `auth_type` is one of `"pat"`, `"oauth-m2m"`, `"oauth-m2m-jwt"`, +/// `"oauth-u2m"`, `"azure-sp-m2m"`. Thin /// wrapper over [`build_auth_config_inner`] that maps its plain-`String` /// validation error onto a `PyValueError`. Keeping the logic in the /// inner fn lets the unit tests assert on the error text without an From abd730ed814058a2f806e066c771ca74e26eef35 Mon Sep 17 00:00:00 2001 From: "peco-engineer-bot[bot]" Date: Thu, 20 Aug 2026 18:11:27 +0000 Subject: [PATCH 28/47] ai: apply changes for #263 (2 review threads) Addresses: - #3824115069 at CONNECTION_PARAMETERS.md:68 - #3824115079 at NEXT_CHANGELOG.md:14 Signed-off-by: peco-engineer-bot[bot] --- CONNECTION_PARAMETERS.md | 19 ++++++++++--------- NEXT_CHANGELOG.md | 6 ++++-- 2 files changed, 14 insertions(+), 11 deletions(-) diff --git a/CONNECTION_PARAMETERS.md b/CONNECTION_PARAMETERS.md index 2f8419ad..540d7a62 100644 --- a/CONNECTION_PARAMETERS.md +++ b/CONNECTION_PARAMETERS.md @@ -34,7 +34,7 @@ warehouse id and org id out of a `/sql/1.0/warehouses/{id}` path). ## `AuthConfig` — authentication (required) An enum; pick one variant. Use the validating constructors -(`AuthConfig::pat`, `::oauth_m2m`, `::oauth_u2m`, `::azure_oauth_u2m`). +(`AuthConfig::pat`, `::oauth_m2m`, `::oauth_u2m`, `::azure_service_principal`). **`Pat`** — personal access token: @@ -65,16 +65,17 @@ An enum; pick one variant. Use the validating constructors core — it resolves the Azure endpoints / scope / client id from the host, so bindings just select the flow. -- **Azure U2M (`AzureOAuthU2M`, `azure-oauth`): supported — live-verified.** - The kernel pins the workspace **v2.0** endpoints +- **Azure U2M (`AzureOAuthU2M`, `azure-oauth`): planned — not yet in v0.** + The `AzureOAuthU2M` variant / `AuthConfig::azure_oauth_u2m(...)` constructor and + the pyo3 `auth_type="azure-oauth"` selector are **not** shipped in this release; + the design (PECOBLR-4120) is tracked in + `docs/designs/PECOBLR-4141-azure-service-principal-design.md`. When it lands the + kernel will pin the workspace **v2.0** endpoints (`{host}/oidc/oauth2/v2.0/{authorize,token}`, which the workspace redirects to Entra), the Azure app client id (`96eecda7-…`), port `8030`, and the - `{app_id}/user_impersonation offline_access` scope. No tenant needed (the - workspace redirect resolves it). Fields — all optional: `client_id`, - `redirect_ports` (default `[8030]`), `app_id` (scope resource; default - `2ff814a6-…`), `callback_timeout` (`120s`), `token_cache`. This is **not** the - discovered `{host}/oidc/v1/authorize` path, which redirects to a malformed - Entra URL (404) for the Azure client — the v2.0 path is the fix. + `{app_id}/user_impersonation offline_access` scope, with no tenant needed (the + workspace redirect resolves it). Until then, use `azure-sp-m2m` for Azure + authentication. - **Azure service principal M2M (`AzureServicePrincipal`, `azure-sp-m2m`): supported.** The kernel owns Azure resolution: it builds the Entra token endpoint (`{login_host}/{tenant}/oauth2/v2.0/token`) and the diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index 924e2280..d18dc154 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -19,8 +19,10 @@ changes go in their respective binding's NEXT_CHANGELOG. parity) — so bindings forward only the SP credentials. A plain client-credentials grant against Entra yields the Databricks-audience data token; the SP must be a workspace member. (RBAC-only SPs via the Azure - management token are a planned follow-up.) Live-verified end-to-end against an - Azure workspace. (PECOBLR-4141.) + management token are a planned follow-up.) Covered by an `#[ignore]`d + end-to-end test (`azure_sp_m2m_select_one_round_trip`) that exercises the flow + against a live Azure workspace when Azure SP credentials are configured. + (PECOBLR-4141.) - Generic Azure/Entra OAuth overrides (the pre-dedicated-flow path, still valid for custom setups where a caller pins the endpoint/scope itself). New C ABI From f362ee405899ef7cde623468c33006a1c4d351c8 Mon Sep 17 00:00:00 2001 From: "peco-engineer-bot[bot]" Date: Thu, 20 Aug 2026 18:23:44 +0000 Subject: [PATCH 29/47] ai: apply changes for #263 (1 review thread) Addresses: - #3824213060 at src/auth/oauth/u2m.rs:281 Signed-off-by: peco-engineer-bot[bot] --- src/auth/oauth/u2m.rs | 42 +++++++++++++++++++++++++++++++++++++++++- 1 file changed, 41 insertions(+), 1 deletion(-) diff --git a/src/auth/oauth/u2m.rs b/src/auth/oauth/u2m.rs index 4ebbcf2e..52fbc804 100644 --- a/src/auth/oauth/u2m.rs +++ b/src/auth/oauth/u2m.rs @@ -275,12 +275,23 @@ impl AuthorizationCodeProvider { // override targets). This avoids a separate authorize override and a // needless discovery round-trip. Otherwise discover both from the // workspace OIDC config. + // + // The override MUST end in `/token`: the authorization-code flow needs a + // distinct authorize endpoint, and there is no reliable way to derive it + // from an arbitrary token URL. Rejecting the mismatch here surfaces a + // clear error instead of later POSTing the browser authorization request + // at the token endpoint and failing in a confusing way. let (token_endpoint, auth_endpoint) = match token_endpoint_override { Some(token) => { let auth = token .strip_suffix("/token") .map(|base| format!("{base}/authorize")) - .unwrap_or_else(|| token.clone()); + .ok_or_else(|| { + Error::invalid_argument().message(format!( + "U2M token_endpoint override must end in `/token` so the \ + authorization endpoint can be derived, got: {token}" + )) + })?; (token, auth) } None => { @@ -866,4 +877,33 @@ mod tests { ); // Discovery `.expect(0)` is verified on mock_server drop. } + + #[tokio::test(flavor = "multi_thread")] + async fn test_u2m_token_override_not_ending_in_token_is_rejected() { + // An override that does not end in `/token` cannot yield an authorize + // endpoint, so provider creation must fail with a clear error instead + // of silently falling back to the token URL for the browser flow. + let http_client = Arc::new( + DatabricksHttpClient::with_default_retry(HttpClientConfig::default()) + .expect("Failed to create HTTP client"), + ); + + let result = AuthorizationCodeProvider::new_with_full_config( + "https://example.databricks.com", + "azure-client-id", + http_client, + vec!["all-apis".to_string()], + vec![8020], + Duration::from_secs(120), + Some("https://login.example.com/oauth2/v2.0/tokens".to_string()), + None, + ) + .await; + + let err = result.expect_err("override not ending in `/token` must be rejected"); + assert!( + err.to_string().contains("must end in `/token`"), + "error should explain the `/token` requirement, got: {err}" + ); + } } From 5a8334c507c9e5bc1880b35115057a1c1b49373f Mon Sep 17 00:00:00 2001 From: "peco-engineer-bot[bot]" Date: Thu, 20 Aug 2026 18:34:43 +0000 Subject: [PATCH 30/47] ai: apply changes for #263 (1 review thread) Addresses: - #3824318093 at include/databricks_kernel.h:283 Signed-off-by: peco-engineer-bot[bot] --- include/databricks_kernel.h | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/include/databricks_kernel.h b/include/databricks_kernel.h index 014dbc1d..92cf9cfa 100644 --- a/include/databricks_kernel.h +++ b/include/databricks_kernel.h @@ -276,7 +276,14 @@ kernel_session_config_set_identity_federation_client_id(KernelSessionConfig* con * endpoint — e.g. the Azure/Entra token endpoint * `https://login.microsoftonline.com//oauth2/v2.0/token` for an Azure * service principal. Unset → OIDC discovery against the workspace host. - * No effect on PAT auth. */ + * No effect on PAT auth. + * + * For U2M the override MUST end in `/token`: the kernel derives the + * authorization endpoint by swapping the trailing `/token` for `/authorize`, + * and rejects any other value with `InvalidArgument` at session open (a + * trailing slash or an IdP whose token path is not `/token` will fail). The + * Azure example above satisfies this. M2M / M2M-JWT have no such suffix + * requirement. */ KernelStatusCode kernel_session_config_set_oauth_token_endpoint(KernelSessionConfig* config, const char* token_endpoint); From f9d2bfdd1f8eba8dcfebcb9860a8cb6632bd9303 Mon Sep 17 00:00:00 2001 From: eric-wang-1990 Date: Thu, 20 Aug 2026 11:37:37 -0700 Subject: [PATCH 31/47] refactor(auth): drop azure-sp-m2m sovereign-host rejection MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Remove `AZURE_SOVEREIGN_HOST_SUFFIXES` + `reject_sovereign_host_for_sp_m2m` and the tightened discovery-path guard. No other driver does this — Python Thrift's Azure SP M2M provider hardcodes commercial Entra and does not special-case sovereign hosts; a sovereign workspace just fails naturally at the token exchange. This matches that behavior and drops non-parity surface. `tenant_from_login_url` keeps its original safety check (the /aad/auth redirect must be a Microsoft login host) — that guards against a misconfigured workspace redirecting somewhere unexpected, unrelated to sovereign clouds. The sovereign limitation stays documented on `AZURE_AAD_LOGIN_HOST`. Co-authored-by: Isaac Signed-off-by: eric-wang-1990 --- src/auth/oauth/azure.rs | 108 ---------------------------------------- src/session.rs | 6 --- 2 files changed, 114 deletions(-) diff --git a/src/auth/oauth/azure.rs b/src/auth/oauth/azure.rs index 698df554..ab9bcd25 100644 --- a/src/auth/oauth/azure.rs +++ b/src/auth/oauth/azure.rs @@ -90,48 +90,6 @@ pub(crate) fn sp_m2m_scope(host: &str) -> String { format!("{}/.default", effective_app_id(host)) } -/// Sovereign-cloud Azure Databricks workspace host suffixes (USGov, China). -/// The SP M2M flow's Entra token endpoint ([`sp_m2m_token_url`]) is hardcoded to -/// the commercial cloud, so these are not yet supported. -const AZURE_SOVEREIGN_HOST_SUFFIXES: &[&str] = &[".databricks.azure.us", ".databricks.azure.cn"]; - -/// Reject a sovereign-cloud workspace `host` before the SP M2M flow builds a -/// commercial-only token URL. This guard is independent of tenant resolution: -/// [`tenant_from_login_url`] only fires on the auto-discovery path, so a caller -/// that passes `azure_tenant_id` explicitly would otherwise skip the check and -/// silently authenticate against the wrong (commercial) Entra host. Mirrors the -/// [`tenant_from_login_url`] sovereign message so both paths fail identically. -pub(crate) fn reject_sovereign_host_for_sp_m2m(host: &str) -> crate::kernel_error::Result<()> { - use crate::kernel_error::Error; - // Reduce to the host authority (drop scheme and any path) before matching, - // so the suffix test can't be fooled by the pattern appearing mid-string. - let host_lower = host.to_ascii_lowercase(); - let authority = host_lower - .split_once("://") - .map(|(_, rest)| rest) - .unwrap_or(&host_lower); - let authority = authority - .split(['/', '?', '#']) - .next() - .unwrap_or(authority) - .trim_end_matches('.'); - if AZURE_SOVEREIGN_HOST_SUFFIXES - .iter() - .any(|suffix| authority.ends_with(suffix)) - { - return Err(Error::unauthenticated().message(format!( - "Azure service-principal M2M: workspace host {authority:?} is a \ - sovereign-cloud (USGov/China) host, which the service-principal \ - M2M flow does not yet support (the Entra token endpoint and \ - management scope are hardcoded to the commercial cloud); passing \ - azure_tenant_id explicitly does not help here, since the token \ - exchange still targets the commercial Entra host regardless of \ - tenant" - ))); - } - Ok(()) -} - /// Discover the workspace's Azure tenant id by reading the `{host}/aad/auth` /// redirect to Entra (`https://login.microsoftonline.com/{tenant}/oauth2/…`), /// exactly as the connector's `get_azure_tenant_id_from_host` does. The tenant @@ -186,23 +144,6 @@ fn tenant_from_login_url(final_url: &reqwest::Url) -> crate::kernel_error::Resul login host (got {host:?}); pass azure_tenant_id explicitly" ))); } - // The tenant parses fine on sovereign clouds (USGov `login.microsoftonline.us`, - // China `login.chinacloudapi.cn`), but the M2M token exchange - // (`sp_m2m_token_url`) is hardcoded to the commercial Entra login host. - // Rather than let discovery succeed and then fail confusingly at the - // sovereign token endpoint, reject a non-commercial login host here with a - // message that names the limitation. Deriving the sovereign login host is - // the documented follow-up. - if host != "login.microsoftonline.com" { - return Err(Error::unauthenticated().message(format!( - "Azure tenant discovery: workspace redirected to a sovereign-cloud \ - login host ({host:?}), which the service-principal M2M flow does \ - not yet support (the Entra token endpoint is hardcoded to the \ - commercial cloud); passing azure_tenant_id explicitly does not help \ - here, since the token exchange still targets the commercial Entra \ - host regardless of tenant" - ))); - } final_url .path_segments() .and_then(|mut segments| segments.next()) @@ -290,55 +231,6 @@ mod tests { assert!(tenant_from_login_url(&url).is_err()); } - #[test] - fn tenant_parse_rejects_sovereign_login_host() { - // A USGov / China workspace redirects to a sovereign Entra login host, - // from which the tenant parses fine — but the M2M token endpoint and - // management scope are hardcoded to the commercial cloud, so discovery - // must fail early with a clear message instead of succeeding and then - // failing confusingly at the commercial token endpoint. - for host in [ - "https://login.microsoftonline.us/tenant-abc/oauth2/authorize?client_id=x", - "https://login.chinacloudapi.cn/tenant-abc/oauth2/authorize?client_id=x", - ] { - let url = reqwest::Url::parse(host).unwrap(); - assert!( - tenant_from_login_url(&url).is_err(), - "expected sovereign host {host:?} to be rejected" - ); - } - } - - #[test] - fn sp_m2m_rejects_sovereign_host_regardless_of_tenant() { - // The explicit-tenant path skips `tenant_from_login_url`, so this - // host-based guard is the only thing that stops a USGov/China caller - // from silently building a commercial-only token URL. - for host in [ - "https://adb-1.databricks.azure.us", - "https://adb-1.databricks.azure.cn", - "adb-1.databricks.azure.us/sql/1.0/warehouses/x", - ] { - assert!( - reject_sovereign_host_for_sp_m2m(host).is_err(), - "expected sovereign host {host:?} to be rejected" - ); - } - // Commercial (and dev/staging) hosts pass the guard. - for host in [ - "https://adb-1.azuredatabricks.net", - "https://adb-1.dev.azuredatabricks.net", - // A host merely embedding the sovereign pattern mid-string is not - // sovereign — suffix match, not substring. - "https://adb-1.databricks.azure.us.example.com", - ] { - assert!( - reject_sovereign_host_for_sp_m2m(host).is_ok(), - "expected commercial host {host:?} to pass" - ); - } - } - #[tokio::test(flavor = "multi_thread")] async fn discover_tenant_reads_first_aad_auth_redirect_hop() { // `/aad/auth` returns a 302 whose Location is the Entra authorize URL diff --git a/src/session.rs b/src/session.rs index 38d9c4fc..dcd5b8b6 100644 --- a/src/session.rs +++ b/src/session.rs @@ -1300,12 +1300,6 @@ async fn build_base_auth_provider( azure_client_id and azure_client_secret", )); } - // Guard sovereign-cloud hosts here, independent of tenant - // resolution: the discovery-path guard in `tenant_from_login_url` - // is skipped when the caller passes an explicit `azure_tenant_id`, - // so without this an explicit-tenant USGov/China user would - // silently build a commercial-only token URL. - crate::auth::oauth::azure::reject_sovereign_host_for_sp_m2m(host)?; let tenant = match azure_tenant_id { Some(t) if !t.is_empty() => t.clone(), _ => azure::discover_tenant(host, &http_client).await?, From bbc5a51e14b353b5465dc0088defb7476387e900 Mon Sep 17 00:00:00 2001 From: "peco-engineer-bot[bot]" Date: Thu, 20 Aug 2026 18:50:52 +0000 Subject: [PATCH 32/47] ai: apply changes for #263 (1 review thread) Addresses: - #3824400893 at src/auth/oauth/azure.rs:1 Signed-off-by: peco-engineer-bot[bot] --- src/auth/oauth/azure.rs | 36 +++++++++++++++++++++++++++++------- 1 file changed, 29 insertions(+), 7 deletions(-) diff --git a/src/auth/oauth/azure.rs b/src/auth/oauth/azure.rs index ab9bcd25..7c99c19c 100644 --- a/src/auth/oauth/azure.rs +++ b/src/auth/oauth/azure.rs @@ -128,20 +128,28 @@ pub(crate) async fn discover_tenant( /// Parse the Azure tenant id from the Entra login URL the workspace's /// `/aad/auth` redirects to (`https://login.microsoftonline.com/{tenant}/…`). -/// The tenant is the first path segment; the host must be a Microsoft login -/// host (guards against a non-AAD redirect on a misconfigured workspace). -/// Extracted so the parse is unit-testable without a live workspace (the HTTP -/// round-trip itself is verified against a real Azure workspace). +/// The tenant is the first path segment; the host must be the **commercial** +/// Microsoft login host (guards against a non-AAD redirect on a misconfigured +/// workspace). Sovereign clouds (e.g. `chinacloudapi.cn`) are intentionally +/// rejected here: [`sp_m2m_token_url`] only builds against the commercial +/// [`AZURE_AAD_LOGIN_HOST`], so accepting a sovereign redirect would let +/// discovery succeed while the token exchange silently hits the wrong +/// directory. Rejecting keeps the two halves consistent until sovereign login +/// hosts are wired (the documented follow-up), and steers the caller to pass +/// `azure_tenant_id` explicitly. Extracted so the parse is unit-testable +/// without a live workspace (the HTTP round-trip itself is verified against a +/// real Azure workspace). fn tenant_from_login_url(final_url: &reqwest::Url) -> crate::kernel_error::Result { use crate::kernel_error::Error; let host = final_url .host_str() .unwrap_or_default() .to_ascii_lowercase(); - if !host.contains("microsoftonline") && !host.contains("chinacloudapi") { + if !host.contains("microsoftonline") { return Err(Error::unauthenticated().message(format!( - "Azure tenant discovery: /aad/auth did not redirect to a Microsoft \ - login host (got {host:?}); pass azure_tenant_id explicitly" + "Azure tenant discovery: /aad/auth did not redirect to the commercial \ + Microsoft login host (got {host:?}); sovereign clouds are not yet \ + supported for azure-sp-m2m — pass azure_tenant_id explicitly" ))); } final_url @@ -231,6 +239,20 @@ mod tests { assert!(tenant_from_login_url(&url).is_err()); } + #[test] + fn tenant_parse_rejects_sovereign_login_host() { + // A China sovereign workspace redirects to login.chinacloudapi.cn, but + // sp_m2m_token_url only targets the commercial AZURE_AAD_LOGIN_HOST — so + // discovery must reject sovereign hosts rather than let the token + // exchange silently hit the wrong directory. Consistency guard for the + // documented sovereign follow-up. + let url = reqwest::Url::parse( + "https://login.chinacloudapi.cn/9f37a392-f0ae-4280-9796-f1864a10effc/oauth2/authorize?client_id=x", + ) + .unwrap(); + assert!(tenant_from_login_url(&url).is_err()); + } + #[tokio::test(flavor = "multi_thread")] async fn discover_tenant_reads_first_aad_auth_redirect_hop() { // `/aad/auth` returns a 302 whose Location is the Entra authorize URL From f52a47f743c03d3cc82b0da1db2301aa41aec609 Mon Sep 17 00:00:00 2001 From: eric-wang-1990 Date: Thu, 20 Aug 2026 12:04:19 -0700 Subject: [PATCH 33/47] feat(auth): azure-sp-m2m sends the Azure SP management token (complete Azure M2M) Re-add the Azure SP management-token header for complete Azure M2M parity with the Thrift connector, so a service principal with an Azure RBAC role but no workspace membership can authenticate. `AzureServicePrincipalProvider` now always builds a second Entra token source (ARM `management.core.windows.net/.default` scope) and emits `X-Databricks-Azure-SP-Management-Token` on every authenticated request via a re-introduced `AuthProvider::extra_headers()` (delegated by `FederationProvider`, applied by the HTTP client on authed requests only). When `azure_workspace_resource_id` is set it also adds `X-Databricks-Azure-Workspace-Resource-Id`. This matches Python Thrift's `AzureServicePrincipalCredentialProvider` exactly (management token always; resource-id header conditional). Wired through `AuthConfig::AzureServicePrincipal.azure_workspace_resource_id` (+ constructor / Debug), session.rs, and pyo3 (`azure_workspace_resource_id` kwarg). Wiremock tests cover the always-management-token + conditional-resource-id composition; the live E2E gains an optional resource-id env var. Co-authored-by: Isaac Signed-off-by: eric-wang-1990 --- NEXT_CHANGELOG.md | 12 +- pyo3/src/auth.rs | 7 +- pyo3/src/session.rs | 3 + src/auth/mod.rs | 16 +++ src/auth/oauth/azure.rs | 216 +++++++++++++++++++++++++++++++++++ src/auth/oauth/federation.rs | 7 ++ src/client/http.rs | 16 +++ src/config.rs | 19 ++- src/session.rs | 17 +-- tests/v0_execute_e2e.rs | 7 +- 10 files changed, 300 insertions(+), 20 deletions(-) diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index d18dc154..7b49c926 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -16,10 +16,14 @@ changes go in their respective binding's NEXT_CHANGELOG. kernel resolves the Entra token endpoint (`{login}/{tenant}/oauth2/v2.0/token`) and the `{effective_app_id}/.default` scope, and auto-discovers the tenant from the workspace's `/aad/auth` redirect when `azure_tenant_id` is omitted (Thrift - parity) — so bindings forward only the SP credentials. A plain - client-credentials grant against Entra yields the Databricks-audience data - token; the SP must be a workspace member. (RBAC-only SPs via the Azure - management token are a planned follow-up.) Covered by an `#[ignore]`d + parity) — so bindings forward only the SP credentials. The `Authorization` + bearer is the Databricks-audience data token; the kernel **always** also sends + the Azure SP management token (`X-Databricks-Azure-SP-Management-Token`, a + second Entra token on the ARM `.default` scope), matching the Thrift + connector, so a service principal that holds an Azure RBAC role but is not a + workspace member can authenticate. When `azure_workspace_resource_id` is set, + the `X-Databricks-Azure-Workspace-Resource-Id` header is added too. A new + `AuthProvider::extra_headers()` carries the pair. Covered by an `#[ignore]`d end-to-end test (`azure_sp_m2m_select_one_round_trip`) that exercises the flow against a live Azure workspace when Azure SP credentials are configured. (PECOBLR-4141.) diff --git a/pyo3/src/auth.rs b/pyo3/src/auth.rs index 54b10385..2baaa5e8 100644 --- a/pyo3/src/auth.rs +++ b/pyo3/src/auth.rs @@ -80,6 +80,7 @@ pub(crate) struct OAuthParams { pub azure_client_id: Option, pub azure_client_secret: Option, pub azure_tenant_id: Option, + pub azure_workspace_resource_id: Option, } /// Default U2M OAuth client id for the **Python** binding. @@ -333,12 +334,14 @@ fn build_auth_config_inner( // Azure Entra service-principal M2M. The kernel owns Azure // resolution: it builds the Entra token endpoint + `.default` // scope and auto-discovers the tenant from the workspace when - // `azure_tenant_id` is omitted. The binding forwards only the - // Entra credentials (+ optional tenant). + // `azure_tenant_id` is omitted. The binding forwards the Entra + // credentials (+ optional tenant + optional workspace resource id + // for the management-token resource-id header). AuthConfig::azure_service_principal( oauth.azure_client_id, oauth.azure_client_secret, oauth.azure_tenant_id, + oauth.azure_workspace_resource_id, oauth.identity_federation_client_id, ) .map_err(|err| err.to_string()) diff --git a/pyo3/src/session.rs b/pyo3/src/session.rs index aa7a86a2..50ee3886 100644 --- a/pyo3/src/session.rs +++ b/pyo3/src/session.rs @@ -130,6 +130,7 @@ impl Session { azure_client_id=None, azure_client_secret=None, azure_tenant_id=None, + azure_workspace_resource_id=None, tls_ca_cert=None, tls_skip_verify=false, tls_skip_hostname_verify=false, @@ -167,6 +168,7 @@ impl Session { azure_client_id: Option, azure_client_secret: Option, azure_tenant_id: Option, + azure_workspace_resource_id: Option, tls_ca_cert: Option>, tls_skip_verify: bool, tls_skip_hostname_verify: bool, @@ -221,6 +223,7 @@ impl Session { azure_client_id, azure_client_secret, azure_tenant_id, + azure_workspace_resource_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 1a560f03..a5f62627 100644 --- a/src/auth/mod.rs +++ b/src/auth/mod.rs @@ -32,4 +32,20 @@ use std::fmt::Debug; pub trait AuthProvider: Send + Sync + Debug { /// Returns the authorization header value for HTTP requests. fn get_auth_header(&self) -> Result; + + /// Extra headers to attach **alongside** `Authorization` on authenticated + /// requests (never on the unauthenticated token/OIDC calls). Default: none. + /// + /// Overridden by the Azure service-principal provider, which always emits + /// the `X-Databricks-Azure-SP-Management-Token` header (and the + /// `X-Databricks-Azure-Workspace-Resource-Id` header when a workspace + /// resource id is configured) so the control plane can authorize a service + /// principal that has an Azure RBAC role but is not a workspace member — + /// matching the Thrift connector. These are dynamic (the management token + /// refreshes), so they cannot be static `custom_headers`. Called on every + /// authenticated request, so implementations must be cheap / internally + /// cached. + fn extra_headers(&self) -> Result> { + Ok(Vec::new()) + } } diff --git a/src/auth/oauth/azure.rs b/src/auth/oauth/azure.rs index 7c99c19c..0954b427 100644 --- a/src/auth/oauth/azure.rs +++ b/src/auth/oauth/azure.rs @@ -90,6 +90,123 @@ pub(crate) fn sp_m2m_scope(host: &str) -> String { format!("{}/.default", effective_app_id(host)) } +/// The Azure Resource Manager scope for the **management token** (commercial +/// cloud). Matches the connector's `AZURE_MANAGED_RESOURCE` +/// (`https://management.core.windows.net/`), as a v2.0 `.default` scope. +const AZURE_MANAGEMENT_SCOPE: &str = "https://management.core.windows.net/.default"; + +/// Header carrying the SP's Azure Resource Manager token, so the Databricks +/// control plane can validate the SP's Azure RBAC role on the workspace. +const SP_MANAGEMENT_TOKEN_HEADER: &str = "X-Databricks-Azure-SP-Management-Token"; +/// Header naming the workspace's ARM resource id (paired with the management +/// token for the RBAC lookup). +const WORKSPACE_RESOURCE_ID_HEADER: &str = "X-Databricks-Azure-Workspace-Resource-Id"; + +/// Azure service-principal M2M provider (complete parity with the Thrift +/// connector's `AzureServicePrincipalCredentialProvider`). +/// +/// The `Authorization` bearer is the Databricks-audience **data** token. It +/// **always** additionally emits the `X-Databricks-Azure-SP-Management-Token` +/// header (a second Entra token, ARM `.default` scope) — exactly as the Thrift +/// connector does — so the control plane can authorize a service principal that +/// holds an Azure RBAC role but is not a workspace member. The +/// `X-Databricks-Azure-Workspace-Resource-Id` header is added only when a +/// workspace resource id is configured. Both tokens are ordinary +/// client-credentials exchanges (reusing [`ClientCredentialsProvider`], which +/// refreshes them), so the management token stays fresh on long-lived sessions. +#[derive(Debug)] +pub(crate) struct AzureServicePrincipalProvider { + data: super::m2m::ClientCredentialsProvider, + management: super::m2m::ClientCredentialsProvider, + /// `Some` only when `azure_workspace_resource_id` was supplied. + workspace_resource_id: Option, +} + +impl AzureServicePrincipalProvider { + /// Build the provider. `tenant` is the (already-resolved) Entra tenant; + /// `host` selects the resource app id for the data scope. Both the data and + /// management token sources hit the same Entra token endpoint with + /// different scopes. + pub(crate) async fn new( + host: &str, + azure_client_id: &str, + azure_client_secret: &str, + tenant: &str, + workspace_resource_id: Option, + http_client: std::sync::Arc, + ) -> crate::kernel_error::Result { + Self::new_with_token_url( + host, + azure_client_id, + azure_client_secret, + sp_m2m_token_url(tenant), + workspace_resource_id, + http_client, + ) + .await + } + + /// Build the provider against an explicit Entra token endpoint. `new` + /// derives that endpoint from the tenant (`sp_m2m_token_url`); this seam + /// takes it directly so tests can point both token sources at a mock server + /// (the real endpoint host, `login.microsoftonline.com`, is not + /// interceptable). + async fn new_with_token_url( + host: &str, + azure_client_id: &str, + azure_client_secret: &str, + token_url: String, + workspace_resource_id: Option, + http_client: std::sync::Arc, + ) -> crate::kernel_error::Result { + let data = super::m2m::ClientCredentialsProvider::new_with_full_config( + host, + azure_client_id, + azure_client_secret, + http_client.clone(), + vec![sp_m2m_scope(host)], + Some(token_url.clone()), + ) + .await?; + let management = super::m2m::ClientCredentialsProvider::new_with_full_config( + host, + azure_client_id, + azure_client_secret, + http_client, + vec![AZURE_MANAGEMENT_SCOPE.to_string()], + Some(token_url), + ) + .await?; + Ok(Self { + data, + management, + workspace_resource_id, + }) + } +} + +impl crate::auth::AuthProvider for AzureServicePrincipalProvider { + fn get_auth_header(&self) -> crate::kernel_error::Result { + self.data.get_auth_header() + } + + fn extra_headers(&self) -> crate::kernel_error::Result> { + // The management header carries the RAW access token (no `Bearer ` + // prefix), matching the connector's `cloud_token.access_token`. Always + // sent, exactly as the Thrift connector does. + let bearer = self.management.get_auth_header()?; + let token = bearer + .strip_prefix("Bearer ") + .unwrap_or(&bearer) + .to_string(); + let mut headers = vec![(SP_MANAGEMENT_TOKEN_HEADER.to_string(), token)]; + if let Some(rid) = &self.workspace_resource_id { + headers.push((WORKSPACE_RESOURCE_ID_HEADER.to_string(), rid.clone())); + } + Ok(headers) + } +} + /// Discover the workspace's Azure tenant id by reading the `{host}/aad/auth` /// redirect to Entra (`https://login.microsoftonline.com/{tenant}/oauth2/…`), /// exactly as the connector's `get_azure_tenant_id_from_host` does. The tenant @@ -311,4 +428,103 @@ mod tests { .await .is_err()); } + + // ─── AzureServicePrincipalProvider header composition ──────────────────── + // + // The Entra token endpoint, the `{app}/.default` scope, and the + // client-credentials exchange are unit-tested elsewhere. These cover the + // composition unique to this provider: `Authorization` is always the data + // token; `X-Databricks-Azure-SP-Management-Token` is ALWAYS emitted (Thrift + // parity); `X-Databricks-Azure-Workspace-Resource-Id` only when configured. + // `new_with_token_url` points both token sources at a mock server. + use crate::auth::AuthProvider as _; + use wiremock::matchers::body_string_contains; + + /// Mount two token responses on the same Entra endpoint, differentiated by + /// the scope in the request body: the data scope (`{app}/.default`, contains + /// `2ff814a6`) returns `data-token`; the management scope + /// (`management.core.windows.net`) returns `mgmt-token`. + async fn mount_dual_token_endpoint(mock_server: &wiremock::MockServer) { + use wiremock::matchers::{method, path}; + use wiremock::{Mock, ResponseTemplate}; + Mock::given(method("POST")) + .and(path("/tenant-abc/oauth2/v2.0/token")) + .and(body_string_contains("management.core.windows.net")) + .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "access_token": "mgmt-token", "token_type": "Bearer", "expires_in": 3600, + }))) + .mount(mock_server) + .await; + Mock::given(method("POST")) + .and(path("/tenant-abc/oauth2/v2.0/token")) + .and(body_string_contains("2ff814a6")) + .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "access_token": "data-token", "token_type": "Bearer", "expires_in": 3600, + }))) + .mount(mock_server) + .await; + } + + #[tokio::test(flavor = "multi_thread")] + async fn sp_m2m_always_emits_management_token_and_resource_id_when_set() { + use crate::client::http::{DatabricksHttpClient, HttpClientConfig}; + use std::sync::Arc; + let mock_server = wiremock::MockServer::start().await; + mount_dual_token_endpoint(&mock_server).await; + let http_client = Arc::new( + DatabricksHttpClient::with_default_retry(HttpClientConfig::default()).expect("client"), + ); + let token_url = format!("{}/tenant-abc/oauth2/v2.0/token", mock_server.uri()); + let provider = AzureServicePrincipalProvider::new_with_token_url( + "https://adb-1.4.azuredatabricks.net", + "sp-client-id", + "sp-client-secret", + token_url, + Some("/subscriptions/s/resourceGroups/rg/workspace/w".to_string()), + http_client, + ) + .await + .expect("provider builds"); + + assert_eq!(provider.get_auth_header().unwrap(), "Bearer data-token"); + let extra = provider.extra_headers().unwrap(); + assert!(extra.contains(&( + SP_MANAGEMENT_TOKEN_HEADER.to_string(), + "mgmt-token".to_string() + ))); + assert!(extra.contains(&( + WORKSPACE_RESOURCE_ID_HEADER.to_string(), + "/subscriptions/s/resourceGroups/rg/workspace/w".to_string() + ))); + } + + #[tokio::test(flavor = "multi_thread")] + async fn sp_m2m_emits_management_token_without_resource_id_when_unset() { + use crate::client::http::{DatabricksHttpClient, HttpClientConfig}; + use std::sync::Arc; + let mock_server = wiremock::MockServer::start().await; + mount_dual_token_endpoint(&mock_server).await; + let http_client = Arc::new( + DatabricksHttpClient::with_default_retry(HttpClientConfig::default()).expect("client"), + ); + let token_url = format!("{}/tenant-abc/oauth2/v2.0/token", mock_server.uri()); + let provider = AzureServicePrincipalProvider::new_with_token_url( + "https://adb-1.4.azuredatabricks.net", + "sp-client-id", + "sp-client-secret", + token_url, + None, + http_client, + ) + .await + .expect("provider builds"); + + assert_eq!(provider.get_auth_header().unwrap(), "Bearer data-token"); + let extra = provider.extra_headers().unwrap(); + // Management token still present (always), but no resource-id header. + assert!(extra + .iter() + .any(|(k, v)| k == SP_MANAGEMENT_TOKEN_HEADER && v == "mgmt-token")); + assert!(!extra.iter().any(|(k, _)| k == WORKSPACE_RESOURCE_ID_HEADER)); + } } diff --git a/src/auth/oauth/federation.rs b/src/auth/oauth/federation.rs index e92fdab9..ed239bb4 100644 --- a/src/auth/oauth/federation.rs +++ b/src/auth/oauth/federation.rs @@ -425,6 +425,13 @@ impl Drop for ExchangeGuard<'_> { } impl AuthProvider for FederationProvider { + /// Delegate extra headers (e.g. the Azure SP management-token pair) to the + /// wrapped provider — the federation exchange only rewrites the bearer, not + /// the accompanying headers. + fn extra_headers(&self) -> Result> { + self.inner.extra_headers() + } + fn get_auth_header(&self) -> Result { let header = self.inner.get_auth_header()?; diff --git a/src/client/http.rs b/src/client/http.rs index 8bb882f6..a95b6257 100644 --- a/src/client/http.rs +++ b/src/client/http.rs @@ -738,6 +738,16 @@ impl DatabricksHttpClient { provider.get_auth_header() } + /// Extra auth headers to attach alongside `Authorization` (e.g. the Azure SP + /// management-token pair). Empty for every provider except the Azure SP one. + /// Errors if the auth provider has not been set. + pub fn auth_extra_headers(&self) -> Result> { + let provider = self.auth_provider.get().ok_or_else(|| { + Error::invalid_state().message("Auth provider not set. Call set_auth_provider() first.") + })?; + provider.extra_headers() + } + /// Returns the retry config for the given request category. fn retry_config(&self, category: RequestCategory) -> &RetryConfig { self.retry_configs @@ -857,6 +867,12 @@ impl DatabricksHttpClient { if with_auth { let auth_header = self.auth_header()?; req_builder = req_builder.header("Authorization", auth_header); + // Extra auth headers (Azure SP management-token pair). Empty for + // every other provider. Applied only on authenticated requests, + // never on the token/OIDC calls that use `execute_without_auth`. + for (name, value) in self.auth_extra_headers()? { + req_builder = req_builder.header(name, value); + } } // Add org ID header for multi-tenant workspace routing diff --git a/src/config.rs b/src/config.rs index ff07709d..2759a06c 100644 --- a/src/config.rs +++ b/src/config.rs @@ -365,10 +365,12 @@ pub enum AuthConfig { /// (`{login_host}/{tenant}/oauth2/v2.0/token`) with the Azure app /// credentials and the `{app_id}/.default` scope. The kernel resolves the /// endpoint, scope, and (when `azure_tenant_id` is omitted) the tenant - /// itself — so bindings forward only the credentials. The SP authenticates - /// with the Databricks-audience data token; it must be a workspace member. - /// (Support for an RBAC-only SP via the Azure management-token header pair - /// is a planned follow-up.) + /// itself — so bindings forward only the credentials. The `Authorization` + /// bearer is the Databricks-audience data token; the kernel additionally + /// always sends the Azure SP management token + /// (`X-Databricks-Azure-SP-Management-Token`), matching the Thrift + /// connector, so a service principal with an Azure RBAC role but no + /// workspace membership can authenticate. AzureServicePrincipal { /// Entra app-registration client id. azure_client_id: String, @@ -377,6 +379,11 @@ pub enum AuthConfig { /// Entra tenant id. `None` → auto-discovered from the workspace's /// `/aad/auth` redirect (matching the Thrift connector). azure_tenant_id: Option, + /// Azure workspace ARM resource id. When set, the kernel adds the + /// `X-Databricks-Azure-Workspace-Resource-Id` header alongside the + /// always-sent management token, so the control plane can resolve the + /// SP's Azure RBAC role against this specific workspace resource. + azure_workspace_resource_id: Option, /// SP-wide Workload Identity Federation client id, forwarded to the /// federation wrapper. identity_federation_client_id: Option, @@ -523,6 +530,7 @@ impl AuthConfig { azure_client_id: Option, azure_client_secret: Option, azure_tenant_id: Option, + azure_workspace_resource_id: Option, identity_federation_client_id: Option, ) -> crate::Result { let azure_client_id = azure_client_id.filter(|s| !s.is_empty()).ok_or_else(|| { @@ -540,6 +548,7 @@ impl AuthConfig { azure_client_id, azure_client_secret, azure_tenant_id: azure_tenant_id.filter(|s| !s.is_empty()), + azure_workspace_resource_id: azure_workspace_resource_id.filter(|s| !s.is_empty()), identity_federation_client_id, }) } @@ -677,6 +686,7 @@ impl std::fmt::Debug for AuthConfig { Self::AzureServicePrincipal { azure_client_id, azure_tenant_id, + azure_workspace_resource_id, identity_federation_client_id, .. } => f @@ -684,6 +694,7 @@ impl std::fmt::Debug for AuthConfig { .field("azure_client_id", azure_client_id) .field("azure_client_secret", &"") .field("azure_tenant_id", azure_tenant_id) + .field("azure_workspace_resource_id", azure_workspace_resource_id) .field( "identity_federation_client_id", identity_federation_client_id, diff --git a/src/session.rs b/src/session.rs index dcd5b8b6..d483fa72 100644 --- a/src/session.rs +++ b/src/session.rs @@ -1284,16 +1284,17 @@ async fn build_base_auth_provider( azure_client_id, azure_client_secret, azure_tenant_id, + azure_workspace_resource_id, .. } => { // Kernel owns Azure resolution: build the Entra token endpoint // ({login}/{tenant}/oauth2/v2.0/token) and the {app_id}/.default // scope, discovering the tenant from the workspace's /aad/auth - // redirect when the caller omits it (Thrift parity). This is a plain - // client-credentials grant against Entra with the Databricks-audience - // data token — the SP must be a workspace member (RBAC-only SPs, via - // the Azure management token, are a planned follow-up). - use crate::auth::oauth::azure; + // redirect when the caller omits it (Thrift parity). The provider + // always also emits the Azure SP management token; when a workspace + // resource id is supplied it adds the resource-id header too, so an + // RBAC-only SP (Azure role, not a workspace member) can authenticate. + use crate::auth::oauth::azure::{self, AzureServicePrincipalProvider}; if azure_client_id.is_empty() || azure_client_secret.is_empty() { return Err(Error::invalid_argument().message( "AuthConfig::AzureServicePrincipal requires non-empty \ @@ -1304,13 +1305,13 @@ async fn build_base_auth_provider( Some(t) if !t.is_empty() => t.clone(), _ => azure::discover_tenant(host, &http_client).await?, }; - let provider = ClientCredentialsProvider::new_with_full_config( + let provider = AzureServicePrincipalProvider::new( host, azure_client_id, azure_client_secret, + &tenant, + azure_workspace_resource_id.clone(), http_client, - vec![azure::sp_m2m_scope(host)], - Some(azure::sp_m2m_token_url(&tenant)), ) .await?; Ok(Arc::new(provider)) diff --git a/tests/v0_execute_e2e.rs b/tests/v0_execute_e2e.rs index daadf507..02e7140e 100644 --- a/tests/v0_execute_e2e.rs +++ b/tests/v0_execute_e2e.rs @@ -126,8 +126,9 @@ async fn live_jwt_session() -> Option { /// The kernel resolves the Entra token endpoint /// (`{login}/{tenant}/oauth2/v2.0/token`) and the `{effective_app_id}/.default` /// scope, and auto-discovers the tenant from the workspace's `/aad/auth` -/// redirect when `DATABRICKS_AZURE_TENANT_ID` is unset. The SP must be a -/// workspace member (the data token alone authenticates it). +/// redirect when `DATABRICKS_AZURE_TENANT_ID` is unset. It always also sends +/// the Azure SP management token; set `DATABRICKS_AZURE_WORKSPACE_RESOURCE_ID` +/// to additionally send the workspace-resource-id header (for an RBAC-only SP). /// /// Returns `None` (rather than panicking) when the Azure-specific vars are /// absent, so the shared `v0 E2E surface` CI job skips this test instead of @@ -137,6 +138,7 @@ async fn live_jwt_session() -> Option { /// - `DATABRICKS_AZURE_CLIENT_ID` — the Entra app-registration client id /// - `DATABRICKS_AZURE_CLIENT_SECRET` — the Entra app-registration secret /// - `DATABRICKS_AZURE_TENANT_ID` — optional; unset → auto-discovered +/// - `DATABRICKS_AZURE_WORKSPACE_RESOURCE_ID` — optional; adds the resource-id header async fn live_azure_sp_m2m_session() -> Option { let host = env_var("DATABRICKS_HOST").expect("DATABRICKS_HOST required"); let path = env_var("DATABRICKS_HTTP_PATH").expect("DATABRICKS_HTTP_PATH required"); @@ -158,6 +160,7 @@ async fn live_azure_sp_m2m_session() -> Option { Some(client_id), Some(client_secret), env_var("DATABRICKS_AZURE_TENANT_ID"), // None → auto-discover from /aad/auth + env_var("DATABRICKS_AZURE_WORKSPACE_RESOURCE_ID"), // None → no resource-id header None, // no SP-wide WIF ) .expect("build AzureServicePrincipal config"); From f9194a1eb5320b45a58b440258bba07c00982c27 Mon Sep 17 00:00:00 2001 From: "peco-engineer-bot[bot]" Date: Thu, 20 Aug 2026 19:07:13 +0000 Subject: [PATCH 34/47] ai: apply changes for #263 (1 review thread) Addresses: - #3824506029 at src/session.rs:1313 Signed-off-by: peco-engineer-bot[bot] --- src/auth/oauth/azure.rs | 80 ++++++++++++++++++++++++++++++++++++----- src/session.rs | 7 ++++ 2 files changed, 79 insertions(+), 8 deletions(-) diff --git a/src/auth/oauth/azure.rs b/src/auth/oauth/azure.rs index 0954b427..83a139c1 100644 --- a/src/auth/oauth/azure.rs +++ b/src/auth/oauth/azure.rs @@ -52,22 +52,40 @@ const AZURE_APP_IDS_BY_SUFFIX: &[(&str, &str)] = &[ ), ]; -/// The effective Azure Databricks resource app id for `host` (the resource in -/// the M2M `.default` scope). Falls back to [`AZURE_DATABRICKS_APP_ID`] (prod) -/// for commercial prod and sovereign hosts. -pub(crate) fn effective_app_id(host: &str) -> &'static str { - // Reduce to the host authority (drop scheme and any path) before matching, - // so the suffix test can't be fooled by the pattern appearing mid-string. +/// Azure sovereign-cloud workspace host suffixes. The M2M token exchange in +/// [`sp_m2m_token_url`] only targets the commercial [`AZURE_AAD_LOGIN_HOST`], so +/// these hosts cannot be served yet; [`reject_sovereign_host`] rejects them up +/// front with a clear message instead of letting the exchange fail opaquely +/// against the commercial directory. Wiring the matching sovereign login hosts +/// is the documented follow-up. +const AZURE_SOVEREIGN_HOST_SUFFIXES: &[&str] = &[ + ".databricks.azure.us", // Azure Government (USGov) + ".databricks.azure.cn", // Azure China +]; + +/// Reduce a workspace URL/host to its lowercase host authority (scheme and any +/// path/query/fragment dropped, trailing dot trimmed), so a suffix test can't +/// be fooled by the pattern appearing in the scheme or path (e.g. +/// `adb-1.dev.azuredatabricks.net.example.com`). +fn host_authority(host: &str) -> String { let host = host.to_ascii_lowercase(); let authority = host .split_once("://") .map(|(_, rest)| rest) .unwrap_or(&host); - let authority = authority + authority .split(['/', '?', '#']) .next() .unwrap_or(authority) - .trim_end_matches('.'); + .trim_end_matches('.') + .to_string() +} + +/// The effective Azure Databricks resource app id for `host` (the resource in +/// the M2M `.default` scope). Falls back to [`AZURE_DATABRICKS_APP_ID`] (prod) +/// for commercial prod and sovereign hosts. +pub(crate) fn effective_app_id(host: &str) -> &'static str { + let authority = host_authority(host); for (suffix, app_id) in AZURE_APP_IDS_BY_SUFFIX { // Match the host suffix, not a substring: a host that merely embeds the // pattern (e.g. `adb-1.dev.azuredatabricks.net.example.com`) is not dev/staging. @@ -78,6 +96,31 @@ pub(crate) fn effective_app_id(host: &str) -> &'static str { AZURE_DATABRICKS_APP_ID } +/// Reject a known Azure sovereign-cloud workspace `host` on the `azure-sp-m2m` +/// path. Because [`sp_m2m_token_url`] hardcodes the commercial +/// [`AZURE_AAD_LOGIN_HOST`], a sovereign workspace — even with an explicit +/// `azure_tenant_id` — would exchange credentials against the *commercial* +/// Entra directory and fail with an opaque Entra error. This mirrors the +/// sovereign rejection [`tenant_from_login_url`] already performs on the +/// discovery redirect, so both the explicit-tenant and discovery halves fail +/// the same clear way until sovereign login hosts are wired (the documented +/// follow-up). +pub(crate) fn reject_sovereign_host(host: &str) -> crate::kernel_error::Result<()> { + use crate::kernel_error::Error; + let authority = host_authority(host); + for suffix in AZURE_SOVEREIGN_HOST_SUFFIXES { + if authority.ends_with(suffix) { + return Err(Error::invalid_argument().message(format!( + "azure-sp-m2m: sovereign cloud workspace {host:?} is not yet \ + supported (the token exchange only targets the commercial \ + Microsoft login host, so an explicit azure_tenant_id would hit \ + the wrong directory) — this is a documented follow-up" + ))); + } + } + Ok(()) +} + /// The Entra **token** endpoint for the M2M client-credentials grant: /// `{login_host}/{tenant}/oauth2/v2.0/token`. Direct to Entra (no workspace /// redirect is available for a non-browser flow). @@ -370,6 +413,27 @@ mod tests { assert!(tenant_from_login_url(&url).is_err()); } + #[test] + fn reject_sovereign_host_matches_known_sovereign_suffixes() { + // USGov and China workspace hosts are rejected: sp_m2m_token_url only + // targets the commercial login host, so an explicit azure_tenant_id + // would otherwise hit the wrong directory and fail opaquely. + assert!(reject_sovereign_host("https://adb-1.11.databricks.azure.us").is_err()); + assert!(reject_sovereign_host("https://adb-1.11.databricks.azure.cn").is_err()); + } + + #[test] + fn reject_sovereign_host_allows_commercial_and_dev_staging() { + // Commercial prod, dev, and staging are all served by the commercial + // login host, so they pass the guard. + assert!(reject_sovereign_host("https://adb-1.4.azuredatabricks.net").is_ok()); + assert!(reject_sovereign_host("https://adb-1.dev.azuredatabricks.net").is_ok()); + assert!(reject_sovereign_host("https://adb-1.staging.azuredatabricks.net").is_ok()); + // A host that merely embeds a sovereign suffix mid-string is not + // sovereign — suffix match on the authority, not a substring. + assert!(reject_sovereign_host("https://adb-1.databricks.azure.us.example.com").is_ok()); + } + #[tokio::test(flavor = "multi_thread")] async fn discover_tenant_reads_first_aad_auth_redirect_hop() { // `/aad/auth` returns a 302 whose Location is the Entra authorize URL diff --git a/src/session.rs b/src/session.rs index d483fa72..8c5d569e 100644 --- a/src/session.rs +++ b/src/session.rs @@ -1301,6 +1301,13 @@ async fn build_base_auth_provider( azure_client_id and azure_client_secret", )); } + // Reject sovereign-cloud hosts up front: sp_m2m_token_url only + // targets the commercial Entra login host, so a sovereign workspace + // would fail opaquely against the wrong directory even with an + // explicit azure_tenant_id. This matches the sovereign rejection + // tenant discovery already performs, so both halves fail the same + // clear way until sovereign login hosts are wired (follow-up). + azure::reject_sovereign_host(host)?; let tenant = match azure_tenant_id { Some(t) if !t.is_empty() => t.clone(), _ => azure::discover_tenant(host, &http_client).await?, From 6f52ae34b4fb67d6481ce0dd3c06f0201da2f05e Mon Sep 17 00:00:00 2001 From: "peco-engineer-bot[bot]" Date: Thu, 20 Aug 2026 19:29:31 +0000 Subject: [PATCH 35/47] ai: apply changes for #263 (3 review threads) Addresses: - #3824612628 at src/auth/oauth/azure.rs:236 - #3824612635 at CONNECTION_PARAMETERS.md:93 - #3824612639 at docs/designs/PECOBLR-4141-azure-service-principal-design.md:86 Signed-off-by: peco-engineer-bot[bot] --- CONNECTION_PARAMETERS.md | 10 +- NEXT_CHANGELOG.md | 17 +-- ...BLR-4141-azure-service-principal-design.md | 55 +++++---- src/auth/oauth/azure.rs | 106 +++++++++++------- src/config.rs | 23 ++-- src/session.rs | 7 +- 6 files changed, 138 insertions(+), 80 deletions(-) diff --git a/CONNECTION_PARAMETERS.md b/CONNECTION_PARAMETERS.md index 540d7a62..e3242acc 100644 --- a/CONNECTION_PARAMETERS.md +++ b/CONNECTION_PARAMETERS.md @@ -84,7 +84,8 @@ bindings just select the flow. the Thrift connector), so bindings forward only the credentials. Fields: `azure_client_id` / `azure_client_secret` (Entra app credentials, required), `azure_tenant_id` (optional — auto-discovered when omitted), - `identity_federation_client_id` (optional WIF). Construct via the + `azure_workspace_resource_id` (optional — enables the management-token add-on, + see below), `identity_federation_client_id` (optional WIF). Construct via the `AuthConfig::azure_service_principal(...)` validating constructor. See `docs/designs/PECOBLR-4141-azure-service-principal-design.md`. @@ -93,10 +94,13 @@ bindings just select the flow. `azure-sp-m2m` is the preferred, zero-config-tenant flow. The `azure-sp-m2m` flow authenticates a workspace-member SP with the Databricks -data token alone. (An Azure **management-token** add-on — sending +data token alone. The Azure **management-token** add-on — sending `X-Databricks-Azure-SP-Management-Token` + `X-Databricks-Azure-Workspace-Resource-Id` so the control plane can authorize an SP that holds an Azure RBAC role but is not -a workspace member — is not implemented in v0.) +a workspace member — is emitted **only when `azure_workspace_resource_id` is set**, +matching the JDBC connector (`if (resourceId != null)`). When it is unset (the +default) neither header is sent and no ARM management-scope token is fetched, so +the common workspace-member SP is unaffected. The bindings expose the generic OAuth overrides as: pyo3 `token_url` / `oauth_scopes` / `client_id`; napi `oauthTokenUrl` / `oauthScopes` / diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index 7b49c926..da7e8c0f 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -17,13 +17,16 @@ changes go in their respective binding's NEXT_CHANGELOG. and the `{effective_app_id}/.default` scope, and auto-discovers the tenant from the workspace's `/aad/auth` redirect when `azure_tenant_id` is omitted (Thrift parity) — so bindings forward only the SP credentials. The `Authorization` - bearer is the Databricks-audience data token; the kernel **always** also sends - the Azure SP management token (`X-Databricks-Azure-SP-Management-Token`, a - second Entra token on the ARM `.default` scope), matching the Thrift - connector, so a service principal that holds an Azure RBAC role but is not a - workspace member can authenticate. When `azure_workspace_resource_id` is set, - the `X-Databricks-Azure-Workspace-Resource-Id` header is added too. A new - `AuthProvider::extra_headers()` carries the pair. Covered by an `#[ignore]`d + bearer is the Databricks-audience data token, which alone authenticates the + common workspace-member SP. When `azure_workspace_resource_id` is set, the + kernel additionally sends the Azure SP management token + (`X-Databricks-Azure-SP-Management-Token`, a second Entra token on the ARM + `.default` scope) paired with the `X-Databricks-Azure-Workspace-Resource-Id` + header, matching the JDBC connector (`if (resourceId != null)`), so a service + principal that holds an Azure RBAC role but is not a workspace member can + authenticate. When it is unset (the default) neither header is sent and no ARM + management-scope token is fetched. A new `AuthProvider::extra_headers()` + carries the pair. Covered by an `#[ignore]`d end-to-end test (`azure_sp_m2m_select_one_round_trip`) that exercises the flow against a live Azure workspace when Azure SP credentials are configured. (PECOBLR-4141.) diff --git a/docs/designs/PECOBLR-4141-azure-service-principal-design.md b/docs/designs/PECOBLR-4141-azure-service-principal-design.md index 609855bd..07043e1a 100644 --- a/docs/designs/PECOBLR-4141-azure-service-principal-design.md +++ b/docs/designs/PECOBLR-4141-azure-service-principal-design.md @@ -16,6 +16,15 @@ # Azure Entra ID OAuth — kernel as the Azure-aware auth core (PECOBLR-4141 / 4120) +> **Scope of this PR (shipped vs. planned).** This PR ships **only** the M2M +> path — `AuthConfig::AzureServicePrincipal` (`azure-sp-m2m`), its provider in +> `src/auth/oauth/azure.rs`, and the pyo3 `auth_type="azure-sp-m2m"` selector. +> Everything describing the **U2M** path — the `azure-oauth` selector, the +> `AuthConfig::AzureOAuthU2M` variant, the authorize-endpoint override, and the +> napi/C-ABI U2M setters — is **PLANNED (PECOBLR-4120), not in this PR**. Those +> sections are marked inline below; treat this document as the design target for +> the full Azure surface, not a description of the delivered code. + ## Direction **The kernel is the auth core; bindings are thin.** The kernel owns Azure @@ -79,7 +88,10 @@ Consequences the kernel API must satisfy: port `8030`; scope app-id `2ff814a6-3304-4ab8-85cb-cd0e6f879c1d` (overridable via `DATABRICKS_AZURE_TENANT_ID`, matching the connector). -## `azure-oauth` (U2M) — PECOBLR-4120 +## `azure-oauth` (U2M) — PECOBLR-4120 — **PLANNED, not in this PR** + +> Not implemented in this PR. `src/auth/oauth/azure.rs` currently has no U2M +> flow; the design below is the target for the follow-up (PECOBLR-4120). Browser authorization-code + PKCE, driven by the kernel's existing U2M provider with Azure endpoints/values: @@ -105,18 +117,18 @@ redirect available): - **Scope**: `{effective_app_id}/.default` (app id from the host's cloud). - **Credentials**: `azure_client_id` / `azure_client_secret` via HTTP Basic (Entra v2.0 advertises `client_secret_basic`; verified). -- **Management token / `azure_workspace_resource_id`: planned (optional - add-on), not yet implemented.** When supplied, the kernel would - additionally fetch an Azure-management token (scope - `https://management.core.windows.net/.default`) and emit the - `X-Databricks-Azure-SP-Management-Token` + - `X-Databricks-Azure-Workspace-Resource-Id` header pair, so the control - plane can authorize an SP that holds an Azure RBAC role but is not a - workspace member. It would be optional and default to `None` (data token - only — the common workspace-member case). This slice is not in the current - cut: the `AzureServicePrincipal` variant has no `azure_workspace_resource_id` - field yet, and no management-token support exists in - `src/auth/oauth/azure.rs`. +- **Management token / `azure_workspace_resource_id`: optional add-on, gated on + the resource id (JDBC parity: `if (resourceId != null)`).** When + `azure_workspace_resource_id` is supplied, the kernel additionally fetches an + Azure-management token (scope `https://management.core.windows.net/.default`) + and emits the `X-Databricks-Azure-SP-Management-Token` + + `X-Databricks-Azure-Workspace-Resource-Id` header pair, so the control plane + can authorize an SP that holds an Azure RBAC role but is not a workspace + member. It defaults to `None` (data token only — the common workspace-member + case); gating avoids forcing the ARM `.default` exchange, which an app + registration without ARM access cannot complete, onto every SP's request hot + path. Implemented in `src/auth/oauth/azure.rs` + (`AzureServicePrincipalProvider`). ## Federation @@ -127,9 +139,11 @@ fallback. ## AuthConfig -Two new variants (bindings map onto them): +Target surface — two variants. **`AzureServicePrincipal` ships in this PR; +`AzureOAuthU2M` is PLANNED (PECOBLR-4120) and not yet added to `config.rs`.** ```rust +// PLANNED (PECOBLR-4120) — not in this PR AuthConfig::AzureOAuthU2M { client_id: Option, // None → 96eecda7-… redirect_ports: Option>, // None → [8030] @@ -141,7 +155,7 @@ AuthConfig::AzureServicePrincipal { // azure-sp-m2m azure_client_id: String, azure_client_secret: String, azure_tenant_id: Option, // None → auto-discover via /aad/auth - // azure_workspace_resource_id: planned (management-token headers) — not in the current cut + azure_workspace_resource_id: Option, // Some → emit management-token headers (JDBC-gated) identity_federation_client_id: Option, } ``` @@ -151,10 +165,13 @@ flows, incl. Go's Databricks-SP M2M and the workspace-OIDC databricks-oauth). ## Thin bindings -- **pyo3**: `auth_type="azure-oauth"` → `AzureOAuthU2M`; `auth_type="azure-sp-m2m"` - + `azure_*` kwargs → `AzureServicePrincipal`. No endpoint/scope/tenant logic. -- **napi**: `AuthMode::AzureOAuth` / `AzureSpM2m` + `azure*` fields. -- **C ABI**: `set_auth_azure_oauth` / `set_auth_azure_sp_m2m` setters. +- **pyo3**: `auth_type="azure-sp-m2m"` + `azure_*` kwargs → `AzureServicePrincipal` + (shipped). `auth_type="azure-oauth"` → `AzureOAuthU2M` is **PLANNED + (PECOBLR-4120)**. No endpoint/scope/tenant logic in the binding. +- **napi**: `AzureSpM2m` + `azure*` fields (planned surface); `AzureOAuth` + U2M is **PLANNED (PECOBLR-4120)**. +- **C ABI**: `set_auth_azure_sp_m2m` setter (planned surface); + `set_auth_azure_oauth` is **PLANNED (PECOBLR-4120)**. - **Connector #919**: `auth_bridge.py` simplifies to selector-mapping only — forwards `auth_type` + azure creds, stops constructing URLs / scopes and stops discovering the tenant (the kernel does it). Drops the kernel-path dependency diff --git a/src/auth/oauth/azure.rs b/src/auth/oauth/azure.rs index 83a139c1..6904e314 100644 --- a/src/auth/oauth/azure.rs +++ b/src/auth/oauth/azure.rs @@ -145,22 +145,31 @@ const SP_MANAGEMENT_TOKEN_HEADER: &str = "X-Databricks-Azure-SP-Management-Token /// token for the RBAC lookup). const WORKSPACE_RESOURCE_ID_HEADER: &str = "X-Databricks-Azure-Workspace-Resource-Id"; -/// Azure service-principal M2M provider (complete parity with the Thrift -/// connector's `AzureServicePrincipalCredentialProvider`). +/// Azure service-principal M2M provider (parity with the JDBC/Thrift +/// connector's `AzureMSICredentialProvider` / SP credential provider). /// -/// The `Authorization` bearer is the Databricks-audience **data** token. It -/// **always** additionally emits the `X-Databricks-Azure-SP-Management-Token` -/// header (a second Entra token, ARM `.default` scope) — exactly as the Thrift -/// connector does — so the control plane can authorize a service principal that -/// holds an Azure RBAC role but is not a workspace member. The -/// `X-Databricks-Azure-Workspace-Resource-Id` header is added only when a -/// workspace resource id is configured. Both tokens are ordinary -/// client-credentials exchanges (reusing [`ClientCredentialsProvider`], which -/// refreshes them), so the management token stays fresh on long-lived sessions. +/// The `Authorization` bearer is the Databricks-audience **data** token, which +/// alone authenticates the common workspace-member SP. The Azure Resource +/// Manager **management token** add-on — the header pair +/// `X-Databricks-Azure-SP-Management-Token` and +/// `X-Databricks-Azure-Workspace-Resource-Id`, which lets the control plane +/// authorize an SP that holds an Azure RBAC role but is not a workspace +/// member — is emitted **only when a workspace resource id is configured**, +/// matching the JDBC connector (`if (resourceId != null) { … }`). +/// Gating it this way keeps the ARM `.default` exchange (and its consent +/// requirement) off the request hot path for the common case: an app +/// registration without ARM access would otherwise fail *every* authenticated +/// request on that second exchange, even though the data token alone would +/// authenticate it. When configured, the management token is an ordinary +/// client-credentials exchange (reusing [`ClientCredentialsProvider`], which +/// refreshes it), so it stays fresh on long-lived sessions. #[derive(Debug)] pub(crate) struct AzureServicePrincipalProvider { data: super::m2m::ClientCredentialsProvider, - management: super::m2m::ClientCredentialsProvider, + /// `Some` only when `azure_workspace_resource_id` was supplied — the + /// management token and its paired resource-id header are emitted together + /// or not at all (JDBC parity). + management: Option, /// `Some` only when `azure_workspace_resource_id` was supplied. workspace_resource_id: Option, } @@ -211,15 +220,26 @@ impl AzureServicePrincipalProvider { Some(token_url.clone()), ) .await?; - let management = super::m2m::ClientCredentialsProvider::new_with_full_config( - host, - azure_client_id, - azure_client_secret, - http_client, - vec![AZURE_MANAGEMENT_SCOPE.to_string()], - Some(token_url), - ) - .await?; + // Build the management-token source ONLY when a workspace resource id + // is configured (JDBC parity: `if (resourceId != null)`). Without one, + // the ARM `management.core.windows.net/.default` exchange — which an app + // registration lacking ARM access cannot complete — would run on every + // authenticated request via `extra_headers()` and break the common + // workspace-member SP case that the data token alone authenticates. + let management = match &workspace_resource_id { + Some(_) => Some( + super::m2m::ClientCredentialsProvider::new_with_full_config( + host, + azure_client_id, + azure_client_secret, + http_client, + vec![AZURE_MANAGEMENT_SCOPE.to_string()], + Some(token_url), + ) + .await?, + ), + None => None, + }; Ok(Self { data, management, @@ -234,19 +254,25 @@ impl crate::auth::AuthProvider for AzureServicePrincipalProvider { } fn extra_headers(&self) -> crate::kernel_error::Result> { + // The management token + resource-id header pair is emitted only when a + // workspace resource id was configured (JDBC parity: `if (resourceId != + // null)`). In the common workspace-member case both are absent and the + // data token in the `Authorization` bearer authenticates alone — so the + // ARM `.default` exchange never runs on the request hot path. + let (Some(management), Some(rid)) = (&self.management, &self.workspace_resource_id) else { + return Ok(Vec::new()); + }; // The management header carries the RAW access token (no `Bearer ` - // prefix), matching the connector's `cloud_token.access_token`. Always - // sent, exactly as the Thrift connector does. - let bearer = self.management.get_auth_header()?; + // prefix), matching the connector's `cloud_token.access_token`. + let bearer = management.get_auth_header()?; let token = bearer .strip_prefix("Bearer ") .unwrap_or(&bearer) .to_string(); - let mut headers = vec![(SP_MANAGEMENT_TOKEN_HEADER.to_string(), token)]; - if let Some(rid) = &self.workspace_resource_id { - headers.push((WORKSPACE_RESOURCE_ID_HEADER.to_string(), rid.clone())); - } - Ok(headers) + Ok(vec![ + (SP_MANAGEMENT_TOKEN_HEADER.to_string(), token), + (WORKSPACE_RESOURCE_ID_HEADER.to_string(), rid.clone()), + ]) } } @@ -498,9 +524,11 @@ mod tests { // The Entra token endpoint, the `{app}/.default` scope, and the // client-credentials exchange are unit-tested elsewhere. These cover the // composition unique to this provider: `Authorization` is always the data - // token; `X-Databricks-Azure-SP-Management-Token` is ALWAYS emitted (Thrift - // parity); `X-Databricks-Azure-Workspace-Resource-Id` only when configured. - // `new_with_token_url` points both token sources at a mock server. + // token; the `X-Databricks-Azure-SP-Management-Token` + + // `X-Databricks-Azure-Workspace-Resource-Id` pair is emitted ONLY when a + // workspace resource id is configured (JDBC parity), and neither header is + // present otherwise. `new_with_token_url` points both token sources at a + // mock server. use crate::auth::AuthProvider as _; use wiremock::matchers::body_string_contains; @@ -530,7 +558,7 @@ mod tests { } #[tokio::test(flavor = "multi_thread")] - async fn sp_m2m_always_emits_management_token_and_resource_id_when_set() { + async fn sp_m2m_emits_management_token_and_resource_id_when_set() { use crate::client::http::{DatabricksHttpClient, HttpClientConfig}; use std::sync::Arc; let mock_server = wiremock::MockServer::start().await; @@ -563,7 +591,7 @@ mod tests { } #[tokio::test(flavor = "multi_thread")] - async fn sp_m2m_emits_management_token_without_resource_id_when_unset() { + async fn sp_m2m_omits_management_token_when_resource_id_unset() { use crate::client::http::{DatabricksHttpClient, HttpClientConfig}; use std::sync::Arc; let mock_server = wiremock::MockServer::start().await; @@ -583,12 +611,12 @@ mod tests { .await .expect("provider builds"); + // The data token alone authenticates the common workspace-member SP. assert_eq!(provider.get_auth_header().unwrap(), "Bearer data-token"); + // Without a workspace resource id, neither the management token nor the + // resource-id header is emitted (JDBC parity) — so the ARM `.default` + // exchange never runs on the request hot path. let extra = provider.extra_headers().unwrap(); - // Management token still present (always), but no resource-id header. - assert!(extra - .iter() - .any(|(k, v)| k == SP_MANAGEMENT_TOKEN_HEADER && v == "mgmt-token")); - assert!(!extra.iter().any(|(k, _)| k == WORKSPACE_RESOURCE_ID_HEADER)); + assert!(extra.is_empty()); } } diff --git a/src/config.rs b/src/config.rs index 2759a06c..5d00859f 100644 --- a/src/config.rs +++ b/src/config.rs @@ -366,11 +366,14 @@ pub enum AuthConfig { /// credentials and the `{app_id}/.default` scope. The kernel resolves the /// endpoint, scope, and (when `azure_tenant_id` is omitted) the tenant /// itself — so bindings forward only the credentials. The `Authorization` - /// bearer is the Databricks-audience data token; the kernel additionally - /// always sends the Azure SP management token - /// (`X-Databricks-Azure-SP-Management-Token`), matching the Thrift - /// connector, so a service principal with an Azure RBAC role but no - /// workspace membership can authenticate. + /// bearer is the Databricks-audience data token, which authenticates the + /// common workspace-member SP on its own. The Azure Resource Manager + /// management-token add-on (`X-Databricks-Azure-SP-Management-Token` + + /// `X-Databricks-Azure-Workspace-Resource-Id`) is emitted only when + /// `azure_workspace_resource_id` is set — matching the JDBC connector + /// (`if (resourceId != null)`) — so an SP with an Azure RBAC role but no + /// workspace membership can authenticate without forcing the extra ARM + /// token exchange on every other SP. AzureServicePrincipal { /// Entra app-registration client id. azure_client_id: String, @@ -379,10 +382,12 @@ pub enum AuthConfig { /// Entra tenant id. `None` → auto-discovered from the workspace's /// `/aad/auth` redirect (matching the Thrift connector). azure_tenant_id: Option, - /// Azure workspace ARM resource id. When set, the kernel adds the - /// `X-Databricks-Azure-Workspace-Resource-Id` header alongside the - /// always-sent management token, so the control plane can resolve the - /// SP's Azure RBAC role against this specific workspace resource. + /// Azure workspace ARM resource id. When set, the kernel fetches the + /// ARM management token and emits it together with the + /// `X-Databricks-Azure-Workspace-Resource-Id` header, so the control + /// plane can resolve the SP's Azure RBAC role against this specific + /// workspace resource. When unset (the default), neither header is + /// sent and the data token authenticates alone. azure_workspace_resource_id: Option, /// SP-wide Workload Identity Federation client id, forwarded to the /// federation wrapper. diff --git a/src/session.rs b/src/session.rs index 8c5d569e..1a0074c7 100644 --- a/src/session.rs +++ b/src/session.rs @@ -1291,9 +1291,10 @@ async fn build_base_auth_provider( // ({login}/{tenant}/oauth2/v2.0/token) and the {app_id}/.default // scope, discovering the tenant from the workspace's /aad/auth // redirect when the caller omits it (Thrift parity). The provider - // always also emits the Azure SP management token; when a workspace - // resource id is supplied it adds the resource-id header too, so an - // RBAC-only SP (Azure role, not a workspace member) can authenticate. + // emits the Azure SP management token + resource-id header pair only + // when a workspace resource id is supplied (JDBC parity), so an + // RBAC-only SP (Azure role, not a workspace member) can authenticate + // while the common workspace-member SP is unaffected. use crate::auth::oauth::azure::{self, AzureServicePrincipalProvider}; if azure_client_id.is_empty() || azure_client_secret.is_empty() { return Err(Error::invalid_argument().message( From b0e36f842799044409adb151363178d772dceb1c Mon Sep 17 00:00:00 2001 From: "peco-engineer-bot[bot]" Date: Thu, 20 Aug 2026 19:42:07 +0000 Subject: [PATCH 36/47] ai: apply changes for #263 (1 review thread) Addresses: - #3824759344 at tests/v0_execute_e2e.rs:129 Signed-off-by: peco-engineer-bot[bot] --- tests/v0_execute_e2e.rs | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/tests/v0_execute_e2e.rs b/tests/v0_execute_e2e.rs index 02e7140e..b739b73e 100644 --- a/tests/v0_execute_e2e.rs +++ b/tests/v0_execute_e2e.rs @@ -126,9 +126,12 @@ async fn live_jwt_session() -> Option { /// The kernel resolves the Entra token endpoint /// (`{login}/{tenant}/oauth2/v2.0/token`) and the `{effective_app_id}/.default` /// scope, and auto-discovers the tenant from the workspace's `/aad/auth` -/// redirect when `DATABRICKS_AZURE_TENANT_ID` is unset. It always also sends -/// the Azure SP management token; set `DATABRICKS_AZURE_WORKSPACE_RESOURCE_ID` -/// to additionally send the workspace-resource-id header (for an RBAC-only SP). +/// redirect when `DATABRICKS_AZURE_TENANT_ID` is unset. Set +/// `DATABRICKS_AZURE_WORKSPACE_RESOURCE_ID` (for an RBAC-only SP) to make the +/// kernel exchange for the Azure SP management token and send it together with +/// the workspace-resource-id header; when it is unset, neither is emitted (no +/// ARM `.default` exchange runs), matching the JDBC `if (resourceId != null)` +/// parity. /// /// Returns `None` (rather than panicking) when the Azure-specific vars are /// absent, so the shared `v0 E2E surface` CI job skips this test instead of From c3e93af83971aef75ca1f4f737fba1f1b485b2a4 Mon Sep 17 00:00:00 2001 From: "peco-engineer-bot[bot]" Date: Thu, 20 Aug 2026 19:51:44 +0000 Subject: [PATCH 37/47] ai: apply changes for #263 (1 review thread) Addresses: - #3824840562 at src/auth/oauth/u2m.rs:281 Signed-off-by: peco-engineer-bot[bot] --- NEXT_CHANGELOG.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index da7e8c0f..275c6e06 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -65,6 +65,18 @@ changes go in their respective binding's NEXT_CHANGELOG. endpoint that is not the workspace's) no longer makes a needless round-trip to, or depends on, the workspace OIDC config. +- **Breaking (OAuth U2M override semantics):** when a `token_url_override` is + set for the U2M authorization-code flow, OIDC discovery is now **skipped** and + the authorization endpoint is **derived** from the override by swapping a + trailing `/token` → `/authorize` (the OAuth2 v2.0 sibling layout the override + targets). Previously the kernel still ran discovery and used the *discovered* + `authorization_endpoint`, overriding only the token endpoint. Consequently the + override now **must end in `/token`** — a mismatch is rejected with + `InvalidArgument` at session open instead of failing later. Callers who set a + U2M `token_url` whose token path is not `/token`, or whose real authorize + endpoint is not the `/authorize` sibling of that token path, must update the + override (or drop it to fall back to discovery). + - 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 From 829897cd7daba363dc77d64f66f575fff0deb0a5 Mon Sep 17 00:00:00 2001 From: "peco-engineer-bot[bot]" Date: Thu, 20 Aug 2026 19:55:30 +0000 Subject: [PATCH 38/47] ai: apply changes for #263 (1 review thread) Addresses: - #3824840562 at src/auth/oauth/u2m.rs:281 Signed-off-by: peco-engineer-bot[bot] --- CHANGELOG.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index aca699b1..0f3717a2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,6 +24,24 @@ cadences and may not move in lockstep with the crate. multi-statement transactions (Private Preview; requires catalog-managed tables server-side). +### Changed +- **BREAKING (U2M `token_url` override semantics)** — when a U2M + (`oauth-u2m`) `token_endpoint_override` / `token_url` is set, the + kernel now **skips OIDC discovery entirely** and derives the + authorization endpoint from the override by swapping a trailing + `/token` → `/authorize` (siblings under a shared base, matching the + Azure `{host}/oidc/oauth2/v2.0/token` layout the override targets). + Previously the token endpoint was overridden but the *authorize* + endpoint still came from the discovered `authorization_endpoint`. + Consequences for pre-existing callers who set a U2M `token_url`: + the override **must end in `/token`** or session open now fails with + `InvalidArgument`; and if the real authorize endpoint is not a + `/authorize` sibling of the token path, the derived URL will differ + from what discovery previously returned. Callers relying on the old + discover-then-override behavior must drop the override (letting + discovery supply both endpoints) or supply a `/token`-suffixed URL + whose `/authorize` sibling is correct. + ### Fixed - **Metadata conformance (catalog match-all wildcard)** — a *literal* catalog `%`, `*`, or `""` reaching `Metadata::list_schemas` / From 8e053f86b248bad78ceb9b341925bf1a99c375ec Mon Sep 17 00:00:00 2001 From: "peco-engineer-bot[bot]" Date: Thu, 20 Aug 2026 20:07:54 +0000 Subject: [PATCH 39/47] ai: apply changes for #263 (1 review thread) Addresses: - #3824937168 at src/auth/oauth/azure.rs:334 Signed-off-by: peco-engineer-bot[bot] --- src/auth/oauth/azure.rs | 38 +++++++++++++++++++++++++++++++++++++- 1 file changed, 37 insertions(+), 1 deletion(-) diff --git a/src/auth/oauth/azure.rs b/src/auth/oauth/azure.rs index 6904e314..58e66f0e 100644 --- a/src/auth/oauth/azure.rs +++ b/src/auth/oauth/azure.rs @@ -331,7 +331,16 @@ fn tenant_from_login_url(final_url: &reqwest::Url) -> crate::kernel_error::Resul .host_str() .unwrap_or_default() .to_ascii_lowercase(); - if !host.contains("microsoftonline") { + // Anchor the guard on the host authority, not a loose substring, mirroring + // `host_authority`/`effective_app_id`/`reject_sovereign_host` elsewhere in + // this module. A substring test (`contains("microsoftonline")`) would also + // admit sovereign login hosts (`login.microsoftonline.us` USGov, + // `login.microsoftonline.de`) and spoofed hosts + // (`login.microsoftonline.com.attacker.example`), handing an + // attacker-/wrong-directory-controlled first path segment to + // `sp_m2m_token_url`, which hardcodes the commercial host. Require the + // commercial `*.microsoftonline.com` authority so the comment holds. + if host != "microsoftonline.com" && !host.ends_with(".microsoftonline.com") { return Err(Error::unauthenticated().message(format!( "Azure tenant discovery: /aad/auth did not redirect to the commercial \ Microsoft login host (got {host:?}); sovereign clouds are not yet \ @@ -439,6 +448,33 @@ mod tests { assert!(tenant_from_login_url(&url).is_err()); } + #[test] + fn tenant_parse_rejects_sovereign_microsoftonline_hosts() { + // login.microsoftonline.us (USGov) / .de satisfy a loose + // `contains("microsoftonline")` test but are NOT the commercial host + // sp_m2m_token_url targets — the authority-anchored guard must reject + // them so discovery can't feed a tenant to the wrong directory. + for host in [ + "https://login.microsoftonline.us/tenant-abc/oauth2/authorize?client_id=x", + "https://login.microsoftonline.de/tenant-abc/oauth2/authorize?client_id=x", + ] { + let url = reqwest::Url::parse(host).unwrap(); + assert!(tenant_from_login_url(&url).is_err()); + } + } + + #[test] + fn tenant_parse_rejects_spoofed_microsoftonline_host() { + // A host that merely embeds the commercial host as a prefix + // (`login.microsoftonline.com.attacker.example`) must not pass — + // suffix match on the authority, not a substring. + let url = reqwest::Url::parse( + "https://login.microsoftonline.com.attacker.example/tenant-abc/oauth2/authorize?client_id=x", + ) + .unwrap(); + assert!(tenant_from_login_url(&url).is_err()); + } + #[test] fn reject_sovereign_host_matches_known_sovereign_suffixes() { // USGov and China workspace hosts are rejected: sp_m2m_token_url only From 0f45652339621bb48dd77f032caaf03132fd9e21 Mon Sep 17 00:00:00 2001 From: "peco-engineer-bot[bot]" Date: Thu, 20 Aug 2026 20:16:48 +0000 Subject: [PATCH 40/47] ai: apply changes for #263 (2 review threads) Addresses: - #3825010408 at CHANGELOG.md:27 - #3825010413 at pyo3/src/auth.rs:29 Signed-off-by: peco-engineer-bot[bot] --- CHANGELOG.md | 18 ------------------ pyo3/src/auth.rs | 4 +++- 2 files changed, 3 insertions(+), 19 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0f3717a2..aca699b1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,24 +24,6 @@ cadences and may not move in lockstep with the crate. multi-statement transactions (Private Preview; requires catalog-managed tables server-side). -### Changed -- **BREAKING (U2M `token_url` override semantics)** — when a U2M - (`oauth-u2m`) `token_endpoint_override` / `token_url` is set, the - kernel now **skips OIDC discovery entirely** and derives the - authorization endpoint from the override by swapping a trailing - `/token` → `/authorize` (siblings under a shared base, matching the - Azure `{host}/oidc/oauth2/v2.0/token` layout the override targets). - Previously the token endpoint was overridden but the *authorize* - endpoint still came from the discovered `authorization_endpoint`. - Consequences for pre-existing callers who set a U2M `token_url`: - the override **must end in `/token`** or session open now fails with - `InvalidArgument`; and if the real authorize endpoint is not a - `/authorize` sibling of the token path, the derived URL will differ - from what discovery previously returned. Callers relying on the old - discover-then-override behavior must drop the override (letting - discovery supply both endpoints) or supply a `/token`-suffixed URL - whose `/authorize` sibling is correct. - ### Fixed - **Metadata conformance (catalog match-all wildcard)** — a *literal* catalog `%`, `*`, or `""` reaching `Metadata::list_schemas` / diff --git a/pyo3/src/auth.rs b/pyo3/src/auth.rs index 2baaa5e8..c846f9a0 100644 --- a/pyo3/src/auth.rs +++ b/pyo3/src/auth.rs @@ -28,7 +28,9 @@ //! `oauth_callback_timeout_secs`. //! - `"azure-sp-m2m"` — Azure Entra service-principal M2M: //! `azure_client_id` + `azure_client_secret`, optional -//! `azure_tenant_id` (auto-discovered from the workspace when omitted). +//! `azure_tenant_id` (auto-discovered from the workspace when omitted) +//! / `azure_workspace_resource_id` (opts into the Azure management +//! token by setting the management-token resource-id header). //! //! OAuth is **kernel-owned**: the kernel acquires and refreshes tokens //! itself (OIDC discovery against the workspace host, transparent From 11c4fbd7e5eaf00ef3129698e7a150f595348d4a Mon Sep 17 00:00:00 2001 From: "peco-engineer-bot[bot]" Date: Thu, 20 Aug 2026 20:23:43 +0000 Subject: [PATCH 41/47] ai: apply changes for #263 (1 review thread) Addresses: - #3825062693 at NEXT_CHANGELOG.md:62 Signed-off-by: peco-engineer-bot[bot] --- NEXT_CHANGELOG.md | 29 +++++++++++++++++------------ 1 file changed, 17 insertions(+), 12 deletions(-) diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index 275c6e06..5a0344ea 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -9,6 +9,23 @@ changes go in their respective binding's NEXT_CHANGELOG. ## [Unreleased] +### Breaking + +- **OAuth U2M override semantics** — when a `token_url_override` is set for the + U2M authorization-code flow, OIDC discovery is now **skipped** and the + authorization endpoint is **derived** from the override by swapping a trailing + `/token` → `/authorize` (the OAuth2 v2.0 sibling layout the override targets). + Previously the kernel still ran discovery and used the *discovered* + `authorization_endpoint`, overriding only the token endpoint. Consequently the + override now **must end in `/token`** — a mismatch is rejected with + `InvalidArgument` at session open instead of failing later. + **Migration:** any caller that pinned a U2M `token_url` whose token path is not + `/token`, or whose real authorize endpoint is not the `/authorize` sibling of + that token path, must update the override (or drop it to fall back to + discovery). This is API-visible to downstream bindings: pyo3 already exposed + `token_url` for `auth_type="oauth-u2m"` before this release, so a Python caller + pinning a non-`/token` U2M endpoint will now fail where it previously worked. + ### Added - Azure Entra service-principal M2M (`azure-sp-m2m`) is now a kernel-owned flow @@ -65,18 +82,6 @@ changes go in their respective binding's NEXT_CHANGELOG. endpoint that is not the workspace's) no longer makes a needless round-trip to, or depends on, the workspace OIDC config. -- **Breaking (OAuth U2M override semantics):** when a `token_url_override` is - set for the U2M authorization-code flow, OIDC discovery is now **skipped** and - the authorization endpoint is **derived** from the override by swapping a - trailing `/token` → `/authorize` (the OAuth2 v2.0 sibling layout the override - targets). Previously the kernel still ran discovery and used the *discovered* - `authorization_endpoint`, overriding only the token endpoint. Consequently the - override now **must end in `/token`** — a mismatch is rejected with - `InvalidArgument` at session open instead of failing later. Callers who set a - U2M `token_url` whose token path is not `/token`, or whose real authorize - endpoint is not the `/authorize` sibling of that token path, must update the - override (or drop it to fall back to discovery). - - 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 From c16ca0ad0af814f124b772cccf5464efb3139d9e Mon Sep 17 00:00:00 2001 From: "peco-engineer-bot[bot]" Date: Thu, 20 Aug 2026 20:33:20 +0000 Subject: [PATCH 42/47] ai: apply changes for #263 (1 review thread) Addresses: - #3825110399 at src/auth/mod.rs:38 Signed-off-by: peco-engineer-bot[bot] --- src/auth/mod.rs | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/src/auth/mod.rs b/src/auth/mod.rs index a5f62627..7763605e 100644 --- a/src/auth/mod.rs +++ b/src/auth/mod.rs @@ -36,12 +36,14 @@ pub trait AuthProvider: Send + Sync + Debug { /// Extra headers to attach **alongside** `Authorization` on authenticated /// requests (never on the unauthenticated token/OIDC calls). Default: none. /// - /// Overridden by the Azure service-principal provider, which always emits - /// the `X-Databricks-Azure-SP-Management-Token` header (and the - /// `X-Databricks-Azure-Workspace-Resource-Id` header when a workspace - /// resource id is configured) so the control plane can authorize a service - /// principal that has an Azure RBAC role but is not a workspace member — - /// matching the Thrift connector. These are dynamic (the management token + /// Overridden by the Azure service-principal provider, which emits the + /// `X-Databricks-Azure-SP-Management-Token` / + /// `X-Databricks-Azure-Workspace-Resource-Id` header pair only when a + /// workspace resource id is configured (JDBC parity: `if (resourceId != + /// null)`); in the common workspace-member case neither header is emitted + /// and no ARM `.default` exchange runs. When present, the pair lets the + /// control plane authorize a service principal that has an Azure RBAC role + /// but is not a workspace member — matching the Thrift connector. These are dynamic (the management token /// refreshes), so they cannot be static `custom_headers`. Called on every /// authenticated request, so implementations must be cheap / internally /// cached. From f430b70b3ce2695f084838062eec892ac982a310 Mon Sep 17 00:00:00 2001 From: eric-wang-1990 Date: Thu, 20 Aug 2026 13:43:04 -0700 Subject: [PATCH 43/47] =?UTF-8?q?refactor(auth):=20revert=20u2m.rs=20to=20?= =?UTF-8?q?main=20=E2=80=94=20azure-sp-m2m=20is=20M2M-only?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The U2M provider's derive-authorize-from-token change was added solely for the azure-oauth (U2M) flow, which has been removed. azure-sp-m2m uses the M2M provider (m2m.rs), never the U2M authorization-code provider, so this PR should not touch u2m.rs at all. Restore it to main (its `token_endpoint_override` handling — discover the authorize endpoint — is unchanged and still serves the generic U2M token-endpoint override). Co-authored-by: Isaac Signed-off-by: eric-wang-1990 --- src/auth/oauth/u2m.rs | 117 +++--------------------------------------- 1 file changed, 7 insertions(+), 110 deletions(-) diff --git a/src/auth/oauth/u2m.rs b/src/auth/oauth/u2m.rs index 52fbc804..5a27d3b3 100644 --- a/src/auth/oauth/u2m.rs +++ b/src/auth/oauth/u2m.rs @@ -241,7 +241,7 @@ impl AuthorizationCodeProvider { scopes, vec![callback_port], callback_timeout, - None, // No token_endpoint override (discover) + None, // No token_endpoint override None, // On-disk cache disabled: no passphrase available here ) .await @@ -268,37 +268,11 @@ impl AuthorizationCodeProvider { token_endpoint_override: Option, cache_passphrase: Option, ) -> Result { - // Resolve the authorization + token endpoints. When the token endpoint - // is overridden, skip OIDC discovery and derive the authorize endpoint - // from it by swapping the trailing `/token` for `/authorize` (the two - // are siblings under a shared base for the OAuth2 v2.0 layout the - // override targets). This avoids a separate authorize override and a - // needless discovery round-trip. Otherwise discover both from the - // workspace OIDC config. - // - // The override MUST end in `/token`: the authorization-code flow needs a - // distinct authorize endpoint, and there is no reliable way to derive it - // from an arbitrary token URL. Rejecting the mismatch here surfaces a - // clear error instead of later POSTing the browser authorization request - // at the token endpoint and failing in a confusing way. - let (token_endpoint, auth_endpoint) = match token_endpoint_override { - Some(token) => { - let auth = token - .strip_suffix("/token") - .map(|base| format!("{base}/authorize")) - .ok_or_else(|| { - Error::invalid_argument().message(format!( - "U2M token_endpoint override must end in `/token` so the \ - authorization endpoint can be derived, got: {token}" - )) - })?; - (token, auth) - } - None => { - let endpoints = OidcEndpoints::discover(host, &http_client).await?; - (endpoints.token_endpoint, endpoints.authorization_endpoint) - } - }; + // Discover OIDC endpoints (unless token_endpoint is overridden, we still need auth endpoint) + let endpoints = OidcEndpoints::discover(host, &http_client).await?; + + // Use override if provided, otherwise use discovered endpoint + let token_endpoint = token_endpoint_override.unwrap_or(endpoints.token_endpoint); // Create token store let token_store = TokenStore::new(); @@ -330,7 +304,7 @@ impl AuthorizationCodeProvider { host: host.to_string(), client_id: client_id.to_string(), token_endpoint, - auth_endpoint, + auth_endpoint: endpoints.authorization_endpoint, token_store, http_client, scopes, @@ -829,81 +803,4 @@ mod tests { "Should fail when falling back to browser flow in unit test" ); } - - #[tokio::test(flavor = "multi_thread")] - async fn test_u2m_token_override_derives_authorize_and_skips_discovery() { - // When the token endpoint is overridden, OIDC discovery must be skipped - // entirely and the authorize endpoint derived from it (trailing - // `/token` → `/authorize`). - let mock_server = MockServer::start().await; - - // Discovery must NOT be hit when the token endpoint is pinned. - 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", mock_server.uri()), - "token_endpoint": format!("{}/oidc/v1/token", mock_server.uri()), - }))) - .expect(0) - .mount(&mock_server) - .await; - - let http_client = Arc::new( - DatabricksHttpClient::with_default_retry(HttpClientConfig::default()) - .expect("Failed to create HTTP client"), - ); - - let token_endpoint = format!("{}/oidc/oauth2/v2.0/token", mock_server.uri()); - - let provider = AuthorizationCodeProvider::new_with_full_config( - &mock_server.uri(), - "azure-client-id", - http_client, - vec!["all-apis".to_string(), "offline_access".to_string()], - vec![8020], - Duration::from_secs(120), - Some(token_endpoint.clone()), - None, // On-disk cache disabled so no seeded token interferes. - ) - .await - .expect("provider creation must not require discovery when the token endpoint is pinned"); - - // The pinned token endpoint is carried verbatim; the authorize endpoint - // is derived from it (discovery skipped). - assert_eq!(provider.token_endpoint, token_endpoint); - assert_eq!( - provider.auth_endpoint, - format!("{}/oidc/oauth2/v2.0/authorize", mock_server.uri()) - ); - // Discovery `.expect(0)` is verified on mock_server drop. - } - - #[tokio::test(flavor = "multi_thread")] - async fn test_u2m_token_override_not_ending_in_token_is_rejected() { - // An override that does not end in `/token` cannot yield an authorize - // endpoint, so provider creation must fail with a clear error instead - // of silently falling back to the token URL for the browser flow. - let http_client = Arc::new( - DatabricksHttpClient::with_default_retry(HttpClientConfig::default()) - .expect("Failed to create HTTP client"), - ); - - let result = AuthorizationCodeProvider::new_with_full_config( - "https://example.databricks.com", - "azure-client-id", - http_client, - vec!["all-apis".to_string()], - vec![8020], - Duration::from_secs(120), - Some("https://login.example.com/oauth2/v2.0/tokens".to_string()), - None, - ) - .await; - - let err = result.expect_err("override not ending in `/token` must be rejected"); - assert!( - err.to_string().contains("must end in `/token`"), - "error should explain the `/token` requirement, got: {err}" - ); - } } From 7b441a8fc0707919a75f9cc8b6ba8e7b178cc9f9 Mon Sep 17 00:00:00 2001 From: "peco-engineer-bot[bot]" Date: Thu, 20 Aug 2026 20:45:04 +0000 Subject: [PATCH 44/47] ai: apply changes for #263 (1 review thread) Addresses: - #3825179963 at src/client/http.rs:782 Signed-off-by: peco-engineer-bot[bot] --- src/auth/oauth/azure.rs | 8 ++++++++ src/client/http.rs | 14 ++++++++++++-- 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/src/auth/oauth/azure.rs b/src/auth/oauth/azure.rs index 58e66f0e..3a3f1891 100644 --- a/src/auth/oauth/azure.rs +++ b/src/auth/oauth/azure.rs @@ -282,6 +282,14 @@ impl crate::auth::AuthProvider for AzureServicePrincipalProvider { /// is the first path segment of the redirect Location. Used when the caller /// does not pass an explicit `azure_tenant_id`, so `azure-sp-m2m` is zero-config /// on the tenant (Thrift parity). +/// +/// This single `/aad/auth` probe is NOT retry-aware (see +/// [`DatabricksHttpClient::first_redirect_location`]), and its error is +/// propagated with `?` here and again in `build_base_auth_provider`, with no +/// automatic fallback at the call site. A transient network blip (5xx / +/// timeout / connection reset) during discovery therefore fails `Session::open` +/// outright; passing an explicit `azure_tenant_id` skips discovery and avoids +/// this probe. pub(crate) async fn discover_tenant( host: &str, http_client: &std::sync::Arc, diff --git a/src/client/http.rs b/src/client/http.rs index a95b6257..a94170d4 100644 --- a/src/client/http.rs +++ b/src/client/http.rs @@ -784,8 +784,18 @@ impl DatabricksHttpClient { /// redirect hop (matching the connector's `get_azure_tenant_id_from_host`), /// rather than parsing the final URL after following the whole Entra /// redirect chain (which can traverse non-tenant-prefixed hops like - /// `/common/` or a `login.live.com` bounce). No retry: a single hop is - /// enough and discovery is best-effort with an explicit-tenant fallback. + /// `/common/` or a `login.live.com` bounce). + /// + /// NOT retry-aware: unlike [`execute`](Self::execute) / + /// [`execute_without_auth`], this one-off client does NOT run the kernel's + /// retry ladder, so a transient 5xx / timeout / connection reset on this + /// single probe surfaces as an error. Because the only caller + /// (`azure::discover_tenant`) propagates that error with `?` and there is + /// no automatic retry or fallback at the call site, a transient blip during + /// discovery is fatal to `Session::open` for a zero-config-tenant + /// `azure-sp-m2m` caller; the recourse is to re-run with an explicit + /// `azure_tenant_id` (which skips discovery entirely). A single hop is + /// sufficient for discovery, so no retry is attempted here. pub async fn first_redirect_location(&self, url: &str) -> Result> { let client = Self::build_reqwest_client(&self.config, reqwest::redirect::Policy::none())?; let response = client.get(url).send().await.map_err(|e| { From 22908e53d0e7a2299da0e332a90a760be804f595 Mon Sep 17 00:00:00 2001 From: "peco-engineer-bot[bot]" Date: Thu, 20 Aug 2026 20:53:58 +0000 Subject: [PATCH 45/47] ai: apply changes for #263 (2 review threads) Addresses: - #3825250644 at include/databricks_kernel.h:281 - #3825250652 at NEXT_CHANGELOG.md:14 Signed-off-by: peco-engineer-bot[bot] --- NEXT_CHANGELOG.md | 17 ----------------- include/databricks_kernel.h | 11 +++++------ 2 files changed, 5 insertions(+), 23 deletions(-) diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index 5a0344ea..da7e8c0f 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -9,23 +9,6 @@ changes go in their respective binding's NEXT_CHANGELOG. ## [Unreleased] -### Breaking - -- **OAuth U2M override semantics** — when a `token_url_override` is set for the - U2M authorization-code flow, OIDC discovery is now **skipped** and the - authorization endpoint is **derived** from the override by swapping a trailing - `/token` → `/authorize` (the OAuth2 v2.0 sibling layout the override targets). - Previously the kernel still ran discovery and used the *discovered* - `authorization_endpoint`, overriding only the token endpoint. Consequently the - override now **must end in `/token`** — a mismatch is rejected with - `InvalidArgument` at session open instead of failing later. - **Migration:** any caller that pinned a U2M `token_url` whose token path is not - `/token`, or whose real authorize endpoint is not the `/authorize` sibling of - that token path, must update the override (or drop it to fall back to - discovery). This is API-visible to downstream bindings: pyo3 already exposed - `token_url` for `auth_type="oauth-u2m"` before this release, so a Python caller - pinning a non-`/token` U2M endpoint will now fail where it previously worked. - ### Added - Azure Entra service-principal M2M (`azure-sp-m2m`) is now a kernel-owned flow diff --git a/include/databricks_kernel.h b/include/databricks_kernel.h index 92cf9cfa..0e06cd14 100644 --- a/include/databricks_kernel.h +++ b/include/databricks_kernel.h @@ -278,12 +278,11 @@ kernel_session_config_set_identity_federation_client_id(KernelSessionConfig* con * service principal. Unset → OIDC discovery against the workspace host. * No effect on PAT auth. * - * For U2M the override MUST end in `/token`: the kernel derives the - * authorization endpoint by swapping the trailing `/token` for `/authorize`, - * and rejects any other value with `InvalidArgument` at session open (a - * trailing slash or an IdP whose token path is not `/token` will fail). The - * Azure example above satisfies this. M2M / M2M-JWT have no such suffix - * requirement. */ + * The override replaces the token endpoint ONLY. For U2M the authorization + * endpoint always comes from OIDC discovery against the workspace host — it is + * never derived from this override — so no particular suffix is required and no + * value is rejected at session open. M2M / M2M-JWT likewise only have their + * token endpoint replaced. */ KernelStatusCode kernel_session_config_set_oauth_token_endpoint(KernelSessionConfig* config, const char* token_endpoint); From 132975dc869d321dbb8d3f6adc4ce8b389b532cc Mon Sep 17 00:00:00 2001 From: eric-wang-1990 Date: Thu, 20 Aug 2026 17:42:21 -0700 Subject: [PATCH 46/47] refactor(auth): drop azure-sp-m2m sovereign-host rejection (again) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit No other driver rejects sovereign hosts — Python Thrift's Azure SP provider hardcodes commercial Entra and lets a sovereign workspace fail naturally at the token exchange. Match that: remove `reject_sovereign_host` + `AZURE_SOVEREIGN_HOST_SUFFIXES` and the up-front session.rs guard. Kept the review bot's genuine improvements: the shared `host_authority` helper, and `tenant_from_login_url`'s authority-*anchored* host check (rejects a spoofed `login.microsoftonline.com.attacker.example`, which a loose `contains()` would admit). That check now accepts the Microsoft/Azure AD login authorities — commercial and sovereign (`login.microsoftonline.us`, `login.chinacloudapi.cn`) — so discovery parses the tenant and a sovereign workspace fails at the commercial token exchange, rather than being special-cased. Sovereign support remains a documented follow-up in azure.rs. Co-authored-by: Isaac Signed-off-by: eric-wang-1990 --- src/auth/oauth/azure.rs | 132 +++++++++------------------------------- src/session.rs | 7 --- 2 files changed, 30 insertions(+), 109 deletions(-) diff --git a/src/auth/oauth/azure.rs b/src/auth/oauth/azure.rs index 3a3f1891..4e4566fd 100644 --- a/src/auth/oauth/azure.rs +++ b/src/auth/oauth/azure.rs @@ -52,17 +52,6 @@ const AZURE_APP_IDS_BY_SUFFIX: &[(&str, &str)] = &[ ), ]; -/// Azure sovereign-cloud workspace host suffixes. The M2M token exchange in -/// [`sp_m2m_token_url`] only targets the commercial [`AZURE_AAD_LOGIN_HOST`], so -/// these hosts cannot be served yet; [`reject_sovereign_host`] rejects them up -/// front with a clear message instead of letting the exchange fail opaquely -/// against the commercial directory. Wiring the matching sovereign login hosts -/// is the documented follow-up. -const AZURE_SOVEREIGN_HOST_SUFFIXES: &[&str] = &[ - ".databricks.azure.us", // Azure Government (USGov) - ".databricks.azure.cn", // Azure China -]; - /// Reduce a workspace URL/host to its lowercase host authority (scheme and any /// path/query/fragment dropped, trailing dot trimmed), so a suffix test can't /// be fooled by the pattern appearing in the scheme or path (e.g. @@ -96,31 +85,6 @@ pub(crate) fn effective_app_id(host: &str) -> &'static str { AZURE_DATABRICKS_APP_ID } -/// Reject a known Azure sovereign-cloud workspace `host` on the `azure-sp-m2m` -/// path. Because [`sp_m2m_token_url`] hardcodes the commercial -/// [`AZURE_AAD_LOGIN_HOST`], a sovereign workspace — even with an explicit -/// `azure_tenant_id` — would exchange credentials against the *commercial* -/// Entra directory and fail with an opaque Entra error. This mirrors the -/// sovereign rejection [`tenant_from_login_url`] already performs on the -/// discovery redirect, so both the explicit-tenant and discovery halves fail -/// the same clear way until sovereign login hosts are wired (the documented -/// follow-up). -pub(crate) fn reject_sovereign_host(host: &str) -> crate::kernel_error::Result<()> { - use crate::kernel_error::Error; - let authority = host_authority(host); - for suffix in AZURE_SOVEREIGN_HOST_SUFFIXES { - if authority.ends_with(suffix) { - return Err(Error::invalid_argument().message(format!( - "azure-sp-m2m: sovereign cloud workspace {host:?} is not yet \ - supported (the token exchange only targets the commercial \ - Microsoft login host, so an explicit azure_tenant_id would hit \ - the wrong directory) — this is a documented follow-up" - ))); - } - } - Ok(()) -} - /// The Entra **token** endpoint for the M2M client-credentials grant: /// `{login_host}/{tenant}/oauth2/v2.0/token`. Direct to Entra (no workspace /// redirect is available for a non-browser flow). @@ -322,37 +286,36 @@ pub(crate) async fn discover_tenant( /// Parse the Azure tenant id from the Entra login URL the workspace's /// `/aad/auth` redirects to (`https://login.microsoftonline.com/{tenant}/…`). -/// The tenant is the first path segment; the host must be the **commercial** -/// Microsoft login host (guards against a non-AAD redirect on a misconfigured -/// workspace). Sovereign clouds (e.g. `chinacloudapi.cn`) are intentionally -/// rejected here: [`sp_m2m_token_url`] only builds against the commercial -/// [`AZURE_AAD_LOGIN_HOST`], so accepting a sovereign redirect would let -/// discovery succeed while the token exchange silently hits the wrong -/// directory. Rejecting keeps the two halves consistent until sovereign login -/// hosts are wired (the documented follow-up), and steers the caller to pass -/// `azure_tenant_id` explicitly. Extracted so the parse is unit-testable -/// without a live workspace (the HTTP round-trip itself is verified against a -/// real Azure workspace). +/// The tenant is the first path segment; the host must be a Microsoft / Azure AD +/// login host (guards against a non-AAD redirect on a misconfigured workspace). +/// Extracted so the parse is unit-testable without a live workspace (the HTTP +/// round-trip itself is verified against a real Azure workspace). fn tenant_from_login_url(final_url: &reqwest::Url) -> crate::kernel_error::Result { use crate::kernel_error::Error; let host = final_url .host_str() .unwrap_or_default() .to_ascii_lowercase(); - // Anchor the guard on the host authority, not a loose substring, mirroring - // `host_authority`/`effective_app_id`/`reject_sovereign_host` elsewhere in - // this module. A substring test (`contains("microsoftonline")`) would also - // admit sovereign login hosts (`login.microsoftonline.us` USGov, - // `login.microsoftonline.de`) and spoofed hosts - // (`login.microsoftonline.com.attacker.example`), handing an - // attacker-/wrong-directory-controlled first path segment to - // `sp_m2m_token_url`, which hardcodes the commercial host. Require the - // commercial `*.microsoftonline.com` authority so the comment holds. - if host != "microsoftonline.com" && !host.ends_with(".microsoftonline.com") { + // Anchor the guard on the host authority *suffix*, not a loose substring: a + // `contains("microsoftonline")` test would admit a spoofed host such as + // `login.microsoftonline.com.attacker.example`, handing an + // attacker-controlled first path segment to the token exchange. Accept the + // known Microsoft/Azure AD login authorities — commercial and sovereign + // (USGov `login.microsoftonline.us`, China `login.chinacloudapi.cn`). A + // sovereign workspace then fails naturally at the (commercial) token + // exchange, matching the Thrift connector; no sovereign special-casing here. + const MS_LOGIN_HOST_SUFFIXES: &[&str] = &[ + ".microsoftonline.com", // commercial + ".microsoftonline.us", // Azure Government (USGov) + ".chinacloudapi.cn", // Azure China + ]; + if !MS_LOGIN_HOST_SUFFIXES + .iter() + .any(|suffix| host.ends_with(suffix)) + { return Err(Error::unauthenticated().message(format!( - "Azure tenant discovery: /aad/auth did not redirect to the commercial \ - Microsoft login host (got {host:?}); sovereign clouds are not yet \ - supported for azure-sp-m2m — pass azure_tenant_id explicitly" + "Azure tenant discovery: /aad/auth did not redirect to a Microsoft \ + login host (got {host:?}); pass azure_tenant_id explicitly" ))); } final_url @@ -443,31 +406,17 @@ mod tests { } #[test] - fn tenant_parse_rejects_sovereign_login_host() { - // A China sovereign workspace redirects to login.chinacloudapi.cn, but - // sp_m2m_token_url only targets the commercial AZURE_AAD_LOGIN_HOST — so - // discovery must reject sovereign hosts rather than let the token - // exchange silently hit the wrong directory. Consistency guard for the - // documented sovereign follow-up. - let url = reqwest::Url::parse( - "https://login.chinacloudapi.cn/9f37a392-f0ae-4280-9796-f1864a10effc/oauth2/authorize?client_id=x", - ) - .unwrap(); - assert!(tenant_from_login_url(&url).is_err()); - } - - #[test] - fn tenant_parse_rejects_sovereign_microsoftonline_hosts() { - // login.microsoftonline.us (USGov) / .de satisfy a loose - // `contains("microsoftonline")` test but are NOT the commercial host - // sp_m2m_token_url targets — the authority-anchored guard must reject - // them so discovery can't feed a tenant to the wrong directory. + fn tenant_parse_accepts_sovereign_login_hosts() { + // Sovereign Microsoft/Azure AD login hosts (USGov login.microsoftonline.us, + // China login.chinacloudapi.cn) are accepted — the tenant parses fine. A + // sovereign workspace then fails naturally at the (commercial) token + // exchange, matching the Thrift connector (no sovereign special-casing). for host in [ "https://login.microsoftonline.us/tenant-abc/oauth2/authorize?client_id=x", - "https://login.microsoftonline.de/tenant-abc/oauth2/authorize?client_id=x", + "https://login.chinacloudapi.cn/tenant-abc/oauth2/authorize?client_id=x", ] { let url = reqwest::Url::parse(host).unwrap(); - assert!(tenant_from_login_url(&url).is_err()); + assert_eq!(tenant_from_login_url(&url).unwrap(), "tenant-abc"); } } @@ -483,27 +432,6 @@ mod tests { assert!(tenant_from_login_url(&url).is_err()); } - #[test] - fn reject_sovereign_host_matches_known_sovereign_suffixes() { - // USGov and China workspace hosts are rejected: sp_m2m_token_url only - // targets the commercial login host, so an explicit azure_tenant_id - // would otherwise hit the wrong directory and fail opaquely. - assert!(reject_sovereign_host("https://adb-1.11.databricks.azure.us").is_err()); - assert!(reject_sovereign_host("https://adb-1.11.databricks.azure.cn").is_err()); - } - - #[test] - fn reject_sovereign_host_allows_commercial_and_dev_staging() { - // Commercial prod, dev, and staging are all served by the commercial - // login host, so they pass the guard. - assert!(reject_sovereign_host("https://adb-1.4.azuredatabricks.net").is_ok()); - assert!(reject_sovereign_host("https://adb-1.dev.azuredatabricks.net").is_ok()); - assert!(reject_sovereign_host("https://adb-1.staging.azuredatabricks.net").is_ok()); - // A host that merely embeds a sovereign suffix mid-string is not - // sovereign — suffix match on the authority, not a substring. - assert!(reject_sovereign_host("https://adb-1.databricks.azure.us.example.com").is_ok()); - } - #[tokio::test(flavor = "multi_thread")] async fn discover_tenant_reads_first_aad_auth_redirect_hop() { // `/aad/auth` returns a 302 whose Location is the Entra authorize URL diff --git a/src/session.rs b/src/session.rs index 1a0074c7..536621c8 100644 --- a/src/session.rs +++ b/src/session.rs @@ -1302,13 +1302,6 @@ async fn build_base_auth_provider( azure_client_id and azure_client_secret", )); } - // Reject sovereign-cloud hosts up front: sp_m2m_token_url only - // targets the commercial Entra login host, so a sovereign workspace - // would fail opaquely against the wrong directory even with an - // explicit azure_tenant_id. This matches the sovereign rejection - // tenant discovery already performs, so both halves fail the same - // clear way until sovereign login hosts are wired (follow-up). - azure::reject_sovereign_host(host)?; let tenant = match azure_tenant_id { Some(t) if !t.is_empty() => t.clone(), _ => azure::discover_tenant(host, &http_client).await?, From d963da6e0a625c9ce13062088e17b57f47717fa6 Mon Sep 17 00:00:00 2001 From: eric-wang-1990 Date: Thu, 20 Aug 2026 22:42:36 -0700 Subject: [PATCH 47/47] fix(auth): mint Azure SP management token via v1.0 resource grant MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The management token (X-Databricks-Azure-SP-Management-Token) was minted via the Entra v2.0 client-credentials grant with scope=https://management.core.windows.net/.default, which yields an aud claim of https://management.core.windows.net (no trailing slash). The Databricks control plane strict-matches aud against https://management.core.windows.net/ (with slash) and rejected the token with HTTP 400 IncorrectClaimException. Mint it instead via the Entra v1.0 resource= grant ({login}/{tenant}/oauth2/token), whose aud is the requested resource verbatim — trailing slash included. The v1.0 endpoint returns expires_in as a JSON string, which the oauth2 crate's strict parser rejects, so the v1.0 path fetches and parses the token response leniently. Verified end-to-end against a live Azure workspace + RBAC-only SP. Co-authored-by: Isaac Signed-off-by: eric-wang-1990 --- NEXT_CHANGELOG.md | 12 ++- src/auth/oauth/azure.rs | 79 ++++++++++++---- src/auth/oauth/m2m.rs | 194 +++++++++++++++++++++++++++++++++++++++- 3 files changed, 260 insertions(+), 25 deletions(-) diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index da7e8c0f..ef950a86 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -20,12 +20,16 @@ changes go in their respective binding's NEXT_CHANGELOG. bearer is the Databricks-audience data token, which alone authenticates the common workspace-member SP. When `azure_workspace_resource_id` is set, the kernel additionally sends the Azure SP management token - (`X-Databricks-Azure-SP-Management-Token`, a second Entra token on the ARM - `.default` scope) paired with the `X-Databricks-Azure-Workspace-Resource-Id` + (`X-Databricks-Azure-SP-Management-Token`, a second Entra token for the Azure + Resource Manager) paired with the `X-Databricks-Azure-Workspace-Resource-Id` header, matching the JDBC connector (`if (resourceId != null)`), so a service principal that holds an Azure RBAC role but is not a workspace member can - authenticate. When it is unset (the default) neither header is sent and no ARM - management-scope token is fetched. A new `AuthProvider::extra_headers()` + authenticate. That token is minted via the Entra **v1.0** `resource=` grant + (`{login}/{tenant}/oauth2/token`) so its `aud` is + `https://management.core.windows.net/` verbatim — trailing slash included — + which the control plane requires; the v2.0 `.default` form drops the slash and + is rejected. When the resource id is unset (the default) neither header is sent + and no management token is fetched. A new `AuthProvider::extra_headers()` carries the pair. Covered by an `#[ignore]`d end-to-end test (`azure_sp_m2m_select_one_round_trip`) that exercises the flow against a live Azure workspace when Azure SP credentials are configured. diff --git a/src/auth/oauth/azure.rs b/src/auth/oauth/azure.rs index 4e4566fd..5636e64d 100644 --- a/src/auth/oauth/azure.rs +++ b/src/auth/oauth/azure.rs @@ -92,15 +92,27 @@ pub(crate) fn sp_m2m_token_url(tenant: &str) -> String { format!("{AZURE_AAD_LOGIN_HOST}/{tenant}/oauth2/v2.0/token") } +/// Derive the Entra **v1.0** token endpoint (`.../oauth2/token`) from the +/// **v2.0** data endpoint (`.../oauth2/v2.0/token`) by dropping the `/v2.0` +/// segment. Deriving (rather than rebuilding from the tenant) preserves the +/// caller's host — real (`login.microsoftonline.com`) or the test seam's mock +/// server. The v1.0 `resource=` grant mints a token whose `aud` is the resource +/// verbatim — trailing slash included — which the v2.0 `.default` form drops. +fn management_token_url_from(data_token_url: &str) -> String { + data_token_url.replace("/oauth2/v2.0/token", "/oauth2/token") +} + /// The M2M scope: `{effective_app_id}/.default`. pub(crate) fn sp_m2m_scope(host: &str) -> String { format!("{}/.default", effective_app_id(host)) } -/// The Azure Resource Manager scope for the **management token** (commercial -/// cloud). Matches the connector's `AZURE_MANAGED_RESOURCE` -/// (`https://management.core.windows.net/`), as a v2.0 `.default` scope. -const AZURE_MANAGEMENT_SCOPE: &str = "https://management.core.windows.net/.default"; +/// The Azure Resource Manager **resource** for the **management token** +/// (commercial cloud). Matches the connector's `AZURE_MANAGED_RESOURCE`. Sent +/// as a v1.0 `resource=` value (not a v2.0 `.default` scope) so the minted +/// token's `aud` is exactly `https://management.core.windows.net/` — trailing +/// slash included — which Databricks requires. +const AZURE_MANAGEMENT_RESOURCE: &str = "https://management.core.windows.net/"; /// Header carrying the SP's Azure Resource Manager token, so the Databricks /// control plane can validate the SP's Azure RBAC role on the workspace. @@ -191,17 +203,26 @@ impl AzureServicePrincipalProvider { // authenticated request via `extra_headers()` and break the common // workspace-member SP case that the data token alone authenticates. let management = match &workspace_resource_id { - Some(_) => Some( - super::m2m::ClientCredentialsProvider::new_with_full_config( - host, - azure_client_id, - azure_client_secret, - http_client, - vec![AZURE_MANAGEMENT_SCOPE.to_string()], - Some(token_url), + Some(_) => { + // The management token uses the Azure AD **v1.0** `resource=` + // grant (against `{login}/{tenant}/oauth2/token`, no `/v2.0`) so + // its `aud` is `https://management.core.windows.net/` verbatim — + // trailing slash included — which Databricks strict-matches. The + // v2.0 `scope=/.default` form drops that slash. Derive + // the v1.0 endpoint from the (v2.0) data `token_url` so the test + // seam's mock host carries over. + let management_token_url = management_token_url_from(&token_url); + Some( + super::m2m::ClientCredentialsProvider::new_with_resource_v1( + azure_client_id, + azure_client_secret, + http_client, + AZURE_MANAGEMENT_RESOURCE.to_string(), + management_token_url, + ) + .await?, ) - .await?, - ), + } None => None, }; Ok(Self { @@ -343,6 +364,23 @@ mod tests { ); } + #[test] + fn management_token_url_drops_v2_segment() { + // The management token's v1.0 `resource=` grant hits `.../oauth2/token`, + // derived from the v2.0 data endpoint by dropping `/v2.0`. The host + // (real or mock) is preserved. + assert_eq!( + management_token_url_from( + "https://login.microsoftonline.com/tenant-123/oauth2/v2.0/token" + ), + "https://login.microsoftonline.com/tenant-123/oauth2/token" + ); + assert_eq!( + management_token_url_from("http://127.0.0.1:8080/tenant-abc/oauth2/v2.0/token"), + "http://127.0.0.1:8080/tenant-abc/oauth2/token" + ); + } + #[test] fn m2m_scope_is_effective_app_default() { // Prod / commercial → the prod Databricks Azure app id. @@ -504,15 +542,18 @@ mod tests { use crate::auth::AuthProvider as _; use wiremock::matchers::body_string_contains; - /// Mount two token responses on the same Entra endpoint, differentiated by - /// the scope in the request body: the data scope (`{app}/.default`, contains - /// `2ff814a6`) returns `data-token`; the management scope - /// (`management.core.windows.net`) returns `mgmt-token`. + /// Mount two token responses, one per Entra endpoint the provider calls: + /// the data token via the **v2.0** `scope=` grant (`.../oauth2/v2.0/token`, + /// body contains the app id `2ff814a6`) returns `data-token`; the management + /// token via the **v1.0** `resource=` grant (`.../oauth2/token`, body + /// contains `management.core.windows.net`) returns `mgmt-token`. The distinct + /// paths (v1.0 vs v2.0) mirror production and keep the two matchers + /// unambiguous. async fn mount_dual_token_endpoint(mock_server: &wiremock::MockServer) { use wiremock::matchers::{method, path}; use wiremock::{Mock, ResponseTemplate}; Mock::given(method("POST")) - .and(path("/tenant-abc/oauth2/v2.0/token")) + .and(path("/tenant-abc/oauth2/token")) .and(body_string_contains("management.core.windows.net")) .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ "access_token": "mgmt-token", "token_type": "Bearer", "expires_in": 3600, diff --git a/src/auth/oauth/m2m.rs b/src/auth/oauth/m2m.rs index 0dd22bfe..5dcce20c 100644 --- a/src/auth/oauth/m2m.rs +++ b/src/auth/oauth/m2m.rs @@ -90,8 +90,17 @@ pub struct ClientCredentialsProvider { token_store: TokenStore, /// HTTP client for token endpoint requests http_client: Arc, - /// OAuth scopes to request (typically "all-apis") + /// OAuth scopes to request (typically "all-apis"). Empty when `resource` + /// is set (a v1.0 `resource=` grant). scopes: Vec, + /// Azure AD **v1.0** `resource=` value for the client-credentials grant, + /// used instead of `scope=`. When `Some`, the token request sends + /// `resource=` (and no `scope`) to the v1.0 `/oauth2/token` + /// endpoint, yielding a token whose `aud` claim is that resource verbatim + /// (e.g. `https://management.core.windows.net/`, with the trailing slash + /// Databricks' control plane requires). The v2.0 `scope=/.default` + /// form drops that trailing slash from `aud`, which the server rejects. + resource: Option, /// Tokio runtime handle captured from the constructing context; /// used to drive the async token exchange from the sync /// `get_auth_header` trait method safely whether or not the @@ -218,6 +227,7 @@ impl ClientCredentialsProvider { token_store: TokenStore::new(), http_client, scopes, + resource: None, // `new_with_full_config` is `async`, so we're guaranteed // to be inside a tokio runtime here. Capture that handle // so `get_auth_header` can dispatch correctly later via @@ -228,6 +238,34 @@ impl ClientCredentialsProvider { runtime_handle: RuntimeHandle::current(), }) } + + /// Construct a provider that mints tokens via the Azure AD **v1.0** + /// `resource=` client-credentials grant against `token_endpoint` (the v1.0 + /// `{login}/{tenant}/oauth2/token` path), rather than the v2.0 + /// `scope=/.default` form. The resulting token's `aud` claim is + /// `resource` verbatim — required for the Azure SP **management token**, + /// whose `aud` Databricks strict-matches as `https://management.core.windows.net/` + /// (trailing slash), which the v2.0 `.default` form drops. No OIDC discovery + /// (the endpoint is always supplied). + pub async fn new_with_resource_v1( + client_id: &str, + client_secret: &str, + http_client: Arc, + resource: String, + token_endpoint: String, + ) -> Result { + Ok(Self { + client_id: client_id.to_string(), + client_secret: client_secret.to_string(), + auth_endpoint: token_endpoint.clone(), + token_endpoint, + token_store: TokenStore::new(), + http_client, + scopes: Vec::new(), + resource: Some(resource), + runtime_handle: RuntimeHandle::current(), + }) + } } impl AuthProvider for ClientCredentialsProvider { @@ -255,6 +293,7 @@ impl AuthProvider for ClientCredentialsProvider { let token_endpoint = self.token_endpoint.clone(); let auth_endpoint = self.auth_endpoint.clone(); let scopes = self.scopes.clone(); + let resource = self.resource.clone(); // Get or refresh token via TokenStore let runtime_handle = self.runtime_handle.clone(); @@ -267,6 +306,21 @@ impl AuthProvider for ClientCredentialsProvider { // a direct `block_on` when called from a plain thread // (e.g. the future C ABI shim). See `crate::util::runtime`. block_on_in_runtime(&runtime_handle, async { + // A v1.0 `resource=` grant (Azure SP management token) needs a + // lenient response parse — the Azure AD v1.0 token endpoint + // returns `expires_in` as a JSON *string*, which the `oauth2` + // crate's strict parser rejects. Fetch it directly instead. + if let Some(resource) = &resource { + return fetch_v1_resource_token( + &http_client, + &token_endpoint, + &client_id, + &client_secret, + resource, + ) + .await; + } + // Build the OAuth client let oauth_client = BasicClient::new(ClientId::new(client_id)) .set_client_secret(ClientSecret::new(client_secret)) @@ -279,7 +333,7 @@ impl AuthProvider for ClientCredentialsProvider { .message(format!("Invalid token endpoint URL: {}", e)) })?); - // Build the token request + // v2.0 client-credentials grant: send `scope=` per requested scope. let mut token_request = oauth_client.exchange_client_credentials(); for scope in &scopes { token_request = token_request.add_scope(Scope::new(scope.clone())); @@ -323,6 +377,96 @@ impl AuthProvider for ClientCredentialsProvider { } } +/// Fetch an Azure AD **v1.0** `resource=` client-credentials token directly, +/// tolerating the v1.0 endpoint's quirk of returning `expires_in` (and the +/// other lifetime fields) as JSON *strings* rather than numbers — which the +/// `oauth2` crate's strict `StandardTokenResponse` parser rejects with "Failed +/// to parse server response". +/// +/// Credentials go in the form body (`client_secret_post`); the token's `aud` +/// claim is the requested `resource` verbatim (e.g. +/// `https://management.core.windows.net/`, trailing slash included). +async fn fetch_v1_resource_token( + http_client: &Arc, + token_endpoint: &str, + client_id: &str, + client_secret: &str, + resource: &str, +) -> Result { + let response = http_client + .inner() + .post(token_endpoint) + .form(&[ + ("grant_type", "client_credentials"), + ("client_id", client_id), + ("client_secret", client_secret), + ("resource", resource), + ]) + .send() + .await + .map_err(|e| { + Error::unauthenticated() + .message(format!("Azure v1.0 resource token exchange failed: {}", e)) + .context("client credentials grant") + })?; + + let status = response.status(); + let body = response.text().await.map_err(|e| { + Error::unauthenticated() + .message(format!( + "Azure v1.0 resource token: reading response body: {}", + e + )) + .context("client credentials grant") + })?; + if !status.is_success() { + return Err(Error::unauthenticated() + .message(format!( + "Azure v1.0 resource token exchange failed: HTTP {}: {}", + status.as_u16(), + body + )) + .context("client credentials grant")); + } + + // Parse leniently: `expires_in` may be a string ("3599") or a number. + let json: serde_json::Value = serde_json::from_str(&body).map_err(|e| { + Error::unauthenticated() + .message(format!("Azure v1.0 resource token: invalid JSON: {}", e)) + .context("client credentials grant") + })?; + let access_token = json + .get("access_token") + .and_then(|v| v.as_str()) + .ok_or_else(|| { + Error::unauthenticated() + .message("Azure v1.0 resource token: response missing access_token") + .context("client credentials grant") + })? + .to_string(); + let token_type = json + .get("token_type") + .and_then(|v| v.as_str()) + .unwrap_or("Bearer") + .to_string(); + let expires_in = json + .get("expires_in") + .and_then(|v| { + v.as_str() + .and_then(|s| s.parse::().ok()) + .or_else(|| v.as_i64()) + }) + .unwrap_or(3600); + + Ok(OAuthToken::new( + access_token, + token_type, + expires_in, + None, // No refresh token for M2M + vec![resource.to_string()], + )) +} + #[cfg(test)] mod tests { use super::*; @@ -398,6 +542,52 @@ mod tests { assert_eq!(auth_header, "Bearer test-access-token-m2m"); } + #[tokio::test(flavor = "multi_thread")] + async fn v1_resource_grant_tolerates_string_expires_in() { + // The Azure AD v1.0 `/oauth2/token` endpoint returns `expires_in` (and + // the other lifetime fields) as JSON *strings*, which the `oauth2` + // crate's strict parser rejects with "Failed to parse server response". + // `new_with_resource_v1` fetches directly and parses leniently. It also + // sends the credentials + `resource=` in the form body (no OIDC + // discovery, no scope). + let mock_server = MockServer::start().await; + Mock::given(method("POST")) + .and(path("/tenant-abc/oauth2/token")) + .and(body_string_contains("grant_type=client_credentials")) + .and(body_string_contains("management.core.windows.net")) + .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "token_type": "Bearer", + "expires_in": "3599", // v1.0 quirk: string, not number + "ext_expires_in": "3599", + "expires_on": "1787294104", + "not_before": "1787290204", + "resource": "https://management.core.windows.net/", + "access_token": "mgmt-access-token", + }))) + .expect(1) + .mount(&mock_server) + .await; + + let http_client = Arc::new( + DatabricksHttpClient::with_default_retry(HttpClientConfig::default()) + .expect("Failed to create HTTP client"), + ); + let provider = ClientCredentialsProvider::new_with_resource_v1( + "sp-client-id", + "sp-client-secret", + http_client, + "https://management.core.windows.net/".to_string(), + format!("{}/tenant-abc/oauth2/token", mock_server.uri()), + ) + .await + .expect("provider builds"); + + assert_eq!( + provider.get_auth_header().expect("get_auth_header"), + "Bearer mgmt-access-token" + ); + } + #[tokio::test(flavor = "multi_thread")] async fn test_m2m_auto_refresh() { let mock_server = MockServer::start().await;