diff --git a/CONNECTION_PARAMETERS.md b/CONNECTION_PARAMETERS.md index bb9ba706..e3242acc 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_service_principal`). **`Pat`** — personal access token: @@ -61,6 +61,55 @@ 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.** 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`): 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, 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 + `{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 — 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`. + + 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-sp-m2m` flow authenticates a workspace-member SP with the Databricks +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 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` / +`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) +kwargs. + 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 49c4f784..f29a642c 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -11,6 +11,42 @@ changes go in their respective binding's NEXT_CHANGELOG. ### Added +- 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 `Authorization` + 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 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. 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. + (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, 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 signs a short-lived JWT with a PEM/PKCS#8 private key (RSA or EC; unencrypted or @@ -34,6 +70,15 @@ changes go in their respective binding's NEXT_CHANGELOG. validate-on-borrow / connection-test probe. Runs SQL, so it must be called from a native (non-async-runtime) thread. Backed by the new `Session::test_connection()`. Benefits ODBC (databricks/databricks-odbc#298). + +### 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/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..07043e1a --- /dev/null +++ b/docs/designs/PECOBLR-4141-azure-service-principal-design.md @@ -0,0 +1,200 @@ + + +# 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 +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 — **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: + +- **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`: 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 + +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 + +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] + 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 + azure_workspace_resource_id: Option, // Some → emit management-token headers (JDBC-gated) + 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-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 + on `AzureOAuthEndpointCollection` / `get_azure_tenant_id_from_host`. + +## Testing + +- **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 implemented as an optional + add-on gated on `azure_workspace_resource_id` (RBAC-only SP support). diff --git a/include/databricks_kernel.h b/include/databricks_kernel.h index 05b22cfa..7161f153 100644 --- a/include/databricks_kernel.h +++ b/include/databricks_kernel.h @@ -271,6 +271,34 @@ 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, 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. + * No effect on PAT auth. + * + * 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); + +/* Optional OAuth scopes (comma-separated), applied to whichever OAuth mode + * (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 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); + /* 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 feb2302e..8484cf0d 100644 --- a/napi/NEXT_CHANGELOG.md +++ b/napi/NEXT_CHANGELOG.md @@ -26,7 +26,8 @@ layout, or npm publishing. Pure-kernel changes go in the root configured IdP token endpoint (e.g. Entra ID for Azure Databricks). Required for `AuthMode.OAuthM2mJwt` against an external-IdP-backed workspace, since Databricks-native OIDC does not advertise the `private_key_jwt` method. Applies to - `AuthMode.OAuthM2m` too. Forwards to the kernel's `token_url_override`. + `AuthMode.OAuthM2m` and `AuthMode.OAuthU2m` too. Forwards to the kernel's + `token_url_override`. - `ConnectionOptions.identityFederationClientId` selects SP-wide Workload Identity Federation during mandatory token exchange. diff --git a/napi/src/database.rs b/napi/src/database.rs index 96c946b6..15575a33 100644 --- a/napi/src/database.rs +++ b/napi/src/database.rs @@ -414,7 +414,7 @@ fn build_auth_config(options: &ConnectionOptions) -> napi::Result { .filter(|&p| p != 0) .map(|p| vec![p]), options.oauth_scopes.clone(), - None, + options.token_url.clone(), None, // `None` takes the kernel default: on-disk cache enabled, // encrypted under a machine-local derived key since this @@ -730,6 +730,62 @@ mod tests { } } + #[test] + fn token_url_forwards_as_override() { + // `tokenUrl` must reach the built AuthConfig as + // `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"; + + 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.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.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:?}"), + } + + 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.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); + 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/pyo3/src/auth.rs b/pyo3/src/auth.rs index 992f209b..c846f9a0 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,11 @@ //! - `"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) +//! / `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 @@ -71,6 +76,13 @@ pub(crate) struct OAuthParams { pub jwt_passphrase: Option, pub jwt_algorithm: 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. @@ -135,7 +147,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 @@ -319,9 +332,25 @@ 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 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()) + } other => Err(format!( "unsupported auth_type {other:?}; expected one of 'pat', 'oauth-m2m', \ - 'oauth-m2m-jwt', 'oauth-u2m'" + 'oauth-m2m-jwt', 'oauth-u2m', 'azure-sp-m2m'" )), } } diff --git a/pyo3/src/session.rs b/pyo3/src/session.rs index 83e4b245..50ee3886 100644 --- a/pyo3/src/session.rs +++ b/pyo3/src/session.rs @@ -127,6 +127,10 @@ impl Session { jwt_passphrase=None, jwt_algorithm=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, @@ -161,6 +165,10 @@ impl Session { jwt_passphrase: Option, jwt_algorithm: 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, @@ -212,6 +220,10 @@ impl Session { jwt_passphrase, jwt_algorithm, 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 1a560f03..7763605e 100644 --- a/src/auth/mod.rs +++ b/src/auth/mod.rs @@ -32,4 +32,22 @@ 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 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. + fn extra_headers(&self) -> Result> { + Ok(Vec::new()) + } } diff --git a/src/auth/oauth/azure.rs b/src/auth/oauth/azure.rs new file mode 100644 index 00000000..5636e64d --- /dev/null +++ b/src/auth/oauth/azure.rs @@ -0,0 +1,635 @@ +// 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-sp-m2m` (service-principal M2M) flow. +//! +//! (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 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"; + +// ─── 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", + ), +]; + +/// 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); + authority + .split(['/', '?', '#']) + .next() + .unwrap_or(authority) + .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. + if authority.ends_with(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") +} + +/// 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 **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. +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 (parity with the JDBC/Thrift +/// connector's `AzureMSICredentialProvider` / SP credential provider). +/// +/// 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, + /// `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, +} + +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?; + // 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(_) => { + // 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?, + ) + } + None => None, + }; + 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 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`. + let bearer = management.get_auth_header()?; + let token = bearer + .strip_prefix("Bearer ") + .unwrap_or(&bearer) + .to_string(); + Ok(vec![ + (SP_MANAGEMENT_TOKEN_HEADER.to_string(), token), + (WORKSPACE_RESOURCE_ID_HEADER.to_string(), rid.clone()), + ]) + } +} + +/// 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). +/// +/// 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, +) -> crate::kernel_error::Result { + use crate::kernel_error::Error; + + let url = format!("{}/aad/auth", host.trim_end_matches('/')); + // 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" + )) + })?; + 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 +/// `/aad/auth` redirects to (`https://login.microsoftonline.com/{tenant}/…`). +/// 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 *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 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::*; + + #[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 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. + 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 + ); + // 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] + 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()); + } + + #[test] + 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.chinacloudapi.cn/tenant-abc/oauth2/authorize?client_id=x", + ] { + let url = reqwest::Url::parse(host).unwrap(); + assert_eq!(tenant_from_login_url(&url).unwrap(), "tenant-abc"); + } + } + + #[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()); + } + + #[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 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; 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; + + /// 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/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_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_omits_management_token_when_resource_id_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"); + + // 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(); + assert!(extra.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/auth/oauth/m2m.rs b/src/auth/oauth/m2m.rs index 5f68a795..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 @@ -194,17 +203,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 { @@ -215,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 @@ -225,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 { @@ -252,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(); @@ -264,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)) @@ -276,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())); @@ -320,13 +377,103 @@ 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::*; 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 @@ -395,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; @@ -678,4 +871,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/auth/oauth/mod.rs b/src/auth/oauth/mod.rs index 23acbf06..68053ada 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/test_keys.rs b/src/auth/oauth/test_keys.rs index 419bcdd0..56864c73 100644 --- a/src/auth/oauth/test_keys.rs +++ b/src/auth/oauth/test_keys.rs @@ -26,8 +26,8 @@ //! The RSA key is generated once per test binary and shared via a //! `OnceLock`, because RSA-2048 key generation is the slow part; the //! encrypted and EC variants are cheap to derive on demand. - -#![cfg(test)] +//! +//! (Module is gated `#[cfg(test)]` at its declaration in `mod.rs`.) use std::sync::OnceLock; diff --git a/src/c_abi/session.rs b/src/c_abi/session.rs index d438babe..bd0592a9 100644 --- a/src/c_abi/session.rs +++ b/src/c_abi/session.rs @@ -129,6 +129,21 @@ 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 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 @@ -221,6 +236,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_scopes: None, // Match the reference driver's / JDBC's EnableTokenCache=1. token_cache: TokenCacheConfig::default(), // Kernel result defaults (CloudFetch enabled, Arrow-native types). @@ -426,6 +443,48 @@ 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 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 (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_scopes( + config: *mut KernelSessionConfig, + scopes: *const c_char, +) -> KernelStatusCode { + set_on_config(config, |c| { + c.oauth_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`. @@ -961,6 +1020,92 @@ 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_scopes`). Pure (no I/O), so the +/// wiring is unit-testable without opening a session. +/// +/// `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_scopes: Option, + 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 { + client_id, + client_secret, + } => AuthConfig::oauth_m2m( + Some(client_id), + Some(client_secret), + oauth_scopes.and_then(|s| parse_scopes(&s)), + oauth_token_endpoint, + identity_federation_client_id, + )?, + AuthSpec::OAuthM2MJwt { + client_id, + jwt_key_file, + jwt_kid, + jwt_passphrase, + jwt_algorithm, + scopes, + token_url, + } => AuthConfig::oauth_m2m_private_key( + Some(client_id), + Some(jwt_key_file), + Some(jwt_kid), + jwt_passphrase, + jwt_algorithm, + // The shared `set_oauth_scopes` wins; fall back to scopes passed + // positionally to `set_auth_m2m_jwt` (same precedence as U2M below). + oauth_scopes + .and_then(|s| parse_scopes(&s)) + .or_else(|| scopes.and_then(|s| parse_scopes(&s))), + // The shared `set_oauth_token_endpoint` wins; fall back to the + // positional `token_url`. + oauth_token_endpoint.or(token_url), + )?, + 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]), + // The shared `set_oauth_scopes` wins; fall back to the scopes + // passed positionally to `set_auth_u2m` (pre-existing path). + // 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), + 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 @@ -976,6 +1121,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::OAuthM2MJwt { - client_id, - jwt_key_file, - jwt_kid, - jwt_passphrase, - jwt_algorithm, - scopes, - token_url, - } => AuthConfig::oauth_m2m_private_key( - Some(client_id), - Some(jwt_key_file), - Some(jwt_kid), - jwt_passphrase, - jwt_algorithm, - scopes.and_then(|s| parse_scopes(&s)), - token_url, - )?, - 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_scopes, + identity_federation_client_id, + token_cache, + )?; let mut builder = Session::builder() .connection(connection) @@ -1348,6 +1454,189 @@ 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 oauth_scopes_setter_is_shared_by_m2m_and_u2m() { + // The single `set_oauth_scopes` setter applies to whichever OAuth mode + // is selected — matching the shared `oauth_scopes` on pyo3 / napi. + let scopes = "custom-a,custom-b"; + let want = Some(vec!["custom-a".to_string(), "custom-b".to_string()]); + + let m2m = auth_spec_to_config( + AuthSpec::OAuthM2M { + client_id: "id".to_string(), + client_secret: "sec".to_string(), + }, + None, + Some(scopes.to_string()), + None, + TokenCacheConfig::default(), + ) + .expect("m2m"); + match m2m { + AuthConfig::OAuthM2M { scopes, .. } => 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 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 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!( diff --git a/src/client/http.rs b/src/client/http.rs index 6e4c0b17..a94170d4 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, }) } @@ -723,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 @@ -748,6 +773,41 @@ 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). + /// + /// 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| { + 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, @@ -817,6 +877,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 4efe1da5..5d00859f 100644 --- a/src/config.rs +++ b/src/config.rs @@ -360,6 +360,40 @@ 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 `Authorization` + /// 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, + /// 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 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. + identity_federation_client_id: Option, + }, + /// OAuth 2.0 machine-to-machine using a JWT private-key client /// assertion (RFC 7523) instead of a client secret. The kernel signs /// a short-lived JWT with the configured private key and sends it as @@ -493,6 +527,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 { @@ -507,6 +572,10 @@ impl AuthConfig { | Self::OAuthU2M { identity_federation_client_id, .. + } + | Self::AzureServicePrincipal { + identity_federation_client_id, + .. } => identity_federation_client_id.as_deref(), // JWT private-key M2M does not thread an SP-wide federation // client id yet (the flow already proves identity via the @@ -619,6 +688,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::OAuthM2MPrivateKey { client_id, jwt_key_file, diff --git a/src/session.rs b/src/session.rs index 1778c609..7a2f31bf 100644 --- a/src/session.rs +++ b/src/session.rs @@ -1309,6 +1309,43 @@ 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). The provider + // 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( + "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(), + _ => 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::OAuthM2MPrivateKey { client_id, jwt_key_file, diff --git a/src/telemetry/runtime.rs b/src/telemetry/runtime.rs index 4cb038f2..ecac7c45 100644 --- a/src/telemetry/runtime.rs +++ b/src/telemetry/runtime.rs @@ -310,6 +310,7 @@ fn auth_type(auth: &AuthConfig) -> String { AuthConfig::OAuthM2M { .. } => "oauth-m2m", AuthConfig::OAuthM2MPrivateKey { .. } => "oauth-m2m-jwt", AuthConfig::OAuthU2M { .. } => "oauth-u2m", + AuthConfig::AzureServicePrincipal { .. } => "azure-sp-m2m", AuthConfig::OAuthFederation { .. } => "oauth-federation", AuthConfig::External(_) => "external", } @@ -322,6 +323,7 @@ fn auth_mech(auth: &AuthConfig) -> DriverAuthMech { AuthConfig::OAuthM2M { .. } | AuthConfig::OAuthM2MPrivateKey { .. } | AuthConfig::OAuthU2M { .. } + | AuthConfig::AzureServicePrincipal { .. } | AuthConfig::OAuthFederation { .. } => DriverAuthMech::Oauth, AuthConfig::External(_) => DriverAuthMech::Other, } @@ -330,9 +332,9 @@ fn auth_mech(auth: &AuthConfig) -> DriverAuthMech { fn auth_flow(auth: &AuthConfig) -> Option { match auth { AuthConfig::Pat { .. } => Some(DriverAuthFlow::TokenPassthrough), - AuthConfig::OAuthM2M { .. } | AuthConfig::OAuthM2MPrivateKey { .. } => { - Some(DriverAuthFlow::ClientCredentials) - } + AuthConfig::OAuthM2M { .. } + | AuthConfig::OAuthM2MPrivateKey { .. } + | AuthConfig::AzureServicePrincipal { .. } => Some(DriverAuthFlow::ClientCredentials), AuthConfig::OAuthU2M { .. } => Some(DriverAuthFlow::BrowserBasedAuthentication), AuthConfig::OAuthFederation { .. } | AuthConfig::External(_) => None, } diff --git a/tests/c/session_smoke.c b/tests/c/session_smoke.c index a02d14bc..851005d9 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_scopes( + config, "2ff814a6-3304-4ab8-85cb-cd0e6f879c1d/.default"); + CHECK(rc == KernelStatusCode_Success, "set_oauth_scopes succeeds"); kernel_session_config_free(config); } diff --git a/tests/v0_execute_e2e.rs b/tests/v0_execute_e2e.rs index 4e07a674..b739b73e 100644 --- a/tests/v0_execute_e2e.rs +++ b/tests/v0_execute_e2e.rs @@ -120,6 +120,64 @@ 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. 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 +/// 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 +/// - `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"); + 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 + env_var("DATABRICKS_AZURE_WORKSPACE_RESOURCE_ID"), // None → no resource-id header + 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 +236,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() {