diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index 50b12236..e1369625 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -38,6 +38,9 @@ changes go in their respective binding's NEXT_CHANGELOG. `identity_federation_client_id` fields on the PAT, M2M, and U2M `AuthConfig` variants select SP-wide WIF; unset means BYOT / account-wide WIF. Follows the ADBC wire contract (`grant_type=jwt-bearer`, `assertion`, `scope=sql`). +- Auth constructors now accept the optional federation client id directly; + the C ABI exposes it through + `kernel_session_config_set_identity_federation_client_id()`. ### Updated diff --git a/include/databricks_kernel.h b/include/databricks_kernel.h index 44c14c88..eed49269 100644 --- a/include/databricks_kernel.h +++ b/include/databricks_kernel.h @@ -249,6 +249,12 @@ KernelStatusCode kernel_session_config_set_auth_u2m(KernelSessionConfig* config, uint16_t redirect_port, const char* scopes); +/* Optional SP-wide Workload Identity Federation client id used by mandatory + * token exchange. Unset selects BYOT / account-wide WIF. */ +KernelStatusCode +kernel_session_config_set_identity_federation_client_id(KernelSessionConfig* config, + const char* client_id); + /* 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 762d3e8d..c849058e 100644 --- a/napi/NEXT_CHANGELOG.md +++ b/napi/NEXT_CHANGELOG.md @@ -14,6 +14,9 @@ layout, or npm publishing. Pure-kernel changes go in the root ### Added +- `ConnectionOptions.identityFederationClientId` selects SP-wide Workload + Identity Federation during mandatory token exchange. + ### Updated ### Fixed diff --git a/napi/index.d.ts b/napi/index.d.ts index 6391bc42..f401c31e 100644 --- a/napi/index.d.ts +++ b/napi/index.d.ts @@ -205,6 +205,11 @@ export interface ConnectionOptions { * (`["all-apis"]` for M2M; `["sql", "offline_access"]` for U2M). */ oauthScopes?: Array + /** + * SP-wide Workload Identity Federation client id used during mandatory + * token exchange. Omitted selects BYOT / account-wide WIF. + */ + identityFederationClientId?: string /** * Default catalog for statements executed on this session. * Routed through the kernel's `DefaultOpts` and onto the SEA diff --git a/napi/src/database.rs b/napi/src/database.rs index 316c39df..b856c774 100644 --- a/napi/src/database.rs +++ b/napi/src/database.rs @@ -157,6 +157,9 @@ pub struct ConnectionOptions { /// OAuth scopes override (M2M / U2M). Omitted ⇒ kernel defaults /// (`["all-apis"]` for M2M; `["sql", "offline_access"]` for U2M). pub oauth_scopes: Option>, + /// SP-wide Workload Identity Federation client id used during mandatory + /// token exchange. Omitted selects BYOT / account-wide WIF. + pub identity_federation_client_id: Option, /// Default catalog for statements executed on this session. /// Routed through the kernel's `DefaultOpts` and onto the SEA /// `CreateSession.catalog` wire field. @@ -334,12 +337,17 @@ pub struct ConnectionOptions { /// session. fn build_auth_config(options: &ConnectionOptions) -> napi::Result { match options.auth_mode.unwrap_or_default() { - AuthMode::Pat => AuthConfig::pat(options.token.clone()).map_err(napi_err_from_kernel), + AuthMode::Pat => AuthConfig::pat( + options.token.clone(), + options.identity_federation_client_id.clone(), + ) + .map_err(napi_err_from_kernel), AuthMode::OAuthM2m => AuthConfig::oauth_m2m( options.oauth_client_id.clone(), options.oauth_client_secret.clone(), options.oauth_scopes.clone(), None, + options.identity_federation_client_id.clone(), ) .map_err(napi_err_from_kernel), // napi injects no client_id/scope default: it rides the kernel's @@ -369,6 +377,7 @@ fn build_auth_config(options: &ConnectionOptions) -> napi::Result { // binding exposes no passphrase option. Surfacing one through // `options` would strengthen it further. None, + options.identity_federation_client_id.clone(), )) } } @@ -586,6 +595,7 @@ mod tests { oauth_client_secret: None, oauth_redirect_port: None, oauth_scopes: None, + identity_federation_client_id: None, catalog: None, schema: None, session_conf: None, @@ -653,6 +663,24 @@ mod tests { ); } + #[test] + fn federation_client_id_reaches_auth_config() { + let mut o = base(); + o.token = Some("dapi-xxx".to_owned()); + o.identity_federation_client_id = Some("federation-client".to_owned()); + + match build_auth_config(&o).unwrap() { + AuthConfig::Pat { + identity_federation_client_id, + .. + } => assert_eq!( + identity_federation_client_id.as_deref(), + Some("federation-client") + ), + other => panic!("expected Pat, got {other:?}"), + } + } + #[test] fn m2m_requires_client_id_and_secret() { let mut o = base(); @@ -662,16 +690,22 @@ mod tests { assert_invalid_arg(build_auth_config(&o).unwrap_err(), "client_secret"); o.oauth_client_secret = Some("sec".to_owned()); o.oauth_scopes = Some(vec!["all-apis".to_owned()]); + o.identity_federation_client_id = Some("federation-client".to_owned()); match build_auth_config(&o).unwrap() { AuthConfig::OAuthM2M { client_id, client_secret, scopes, + identity_federation_client_id, .. } => { assert_eq!(client_id, "cid"); assert_eq!(client_secret, "sec"); assert_eq!(scopes, Some(vec!["all-apis".to_owned()])); + assert_eq!( + identity_federation_client_id.as_deref(), + Some("federation-client") + ); } other => panic!("expected OAuthM2M, got {other:?}"), } @@ -701,14 +735,20 @@ mod tests { // Explicit overrides thread through. o.oauth_client_id = Some("custom-cli".to_owned()); o.oauth_redirect_port = Some(9000); + o.identity_federation_client_id = Some("federation-client".to_owned()); match build_auth_config(&o).unwrap() { AuthConfig::OAuthU2M { client_id, redirect_port, + identity_federation_client_id, .. } => { assert_eq!(client_id.as_deref(), Some("custom-cli")); assert_eq!(redirect_port, Some(9000)); + assert_eq!( + identity_federation_client_id.as_deref(), + Some("federation-client") + ); } other => panic!("expected OAuthU2M, got {other:?}"), } diff --git a/pyo3/NEXT_CHANGELOG.md b/pyo3/NEXT_CHANGELOG.md index fff7b1cb..191ce3b4 100644 --- a/pyo3/NEXT_CHANGELOG.md +++ b/pyo3/NEXT_CHANGELOG.md @@ -13,6 +13,9 @@ changes go in the root `NEXT_CHANGELOG.md`. ### Added +- `Session(..., identity_federation_client_id=...)` selects SP-wide Workload + Identity Federation during mandatory token exchange. + ### Updated ### Fixed diff --git a/pyo3/src/auth.rs b/pyo3/src/auth.rs index 52c5ce3a..1e4f3d78 100644 --- a/pyo3/src/auth.rs +++ b/pyo3/src/auth.rs @@ -52,6 +52,7 @@ pub(crate) struct OAuthParams { pub token_url: Option, pub redirect_port: Option, pub callback_timeout_secs: Option, + pub identity_federation_client_id: Option, } /// Default U2M OAuth client id for the **Python** binding. @@ -144,10 +145,8 @@ fn build_auth_config_inner( if token.is_empty() { return Err("access_token must not be empty".to_owned()); } - Ok(AuthConfig::Pat { - token, - identity_federation_client_id: None, - }) + AuthConfig::pat(Some(token), oauth.identity_federation_client_id) + .map_err(|err| err.to_string()) } "oauth-m2m" => { // Client credentials grant: both halves are mandatory. @@ -156,13 +155,14 @@ fn build_auth_config_inner( oauth.client_secret, "auth_type='oauth-m2m' requires client_secret", )?; - Ok(AuthConfig::OAuthM2M { - client_id, - client_secret, - scopes: oauth.scopes, - token_url_override: oauth.token_url, - identity_federation_client_id: None, - }) + AuthConfig::oauth_m2m( + Some(client_id), + Some(client_secret), + oauth.scopes, + oauth.token_url, + oauth.identity_federation_client_id, + ) + .map_err(|err| err.to_string()) } "oauth-u2m" => { // Browser flow: every field is optional and `None` lets the @@ -240,12 +240,12 @@ fn build_auth_config_inner( None if !caller_set_client_id => Some(PYSQL_OAUTH_REDIRECT_PORT), None => None, }; - Ok(AuthConfig::OAuthU2M { + Ok(AuthConfig::oauth_u2m( client_id, redirect_port, scopes, - token_url_override: oauth.token_url, - callback_timeout: oauth.callback_timeout_secs.map(Duration::from_secs), + oauth.token_url, + oauth.callback_timeout_secs.map(Duration::from_secs), // `None` takes the kernel default: on-disk cache ENABLED, // encrypted under a machine-local derived key since this // binding exposes no passphrase option. That preserves @@ -253,9 +253,9 @@ fn build_auth_config_inner( // ever writing the refresh token in the clear. Surfacing a // passphrase through `OAuthParams` — the equivalent of JDBC's // TokenCachePassPhrase — would strengthen it further. - token_cache: None, - identity_federation_client_id: None, - }) + None, + oauth.identity_federation_client_id, + )) } other => Err(format!( "unsupported auth_type {other:?}; expected one of 'pat', 'oauth-m2m', 'oauth-u2m'" @@ -288,9 +288,22 @@ mod tests { #[test] fn pat_builds() { - let cfg = - build_auth_config_inner("pat", Some("dapi123".into()), OAuthParams::default()).unwrap(); - assert!(matches!(cfg, AuthConfig::Pat { token, .. } if token == "dapi123")); + let cfg = build_auth_config_inner( + "pat", + Some("dapi123".into()), + OAuthParams { + identity_federation_client_id: Some("federation-client".into()), + ..Default::default() + }, + ) + .unwrap(); + assert!(matches!( + cfg, + AuthConfig::Pat { + token, + identity_federation_client_id: Some(client_id), + } if token == "dapi123" && client_id == "federation-client" + )); } #[test] @@ -343,6 +356,7 @@ mod tests { client_secret: Some("sec".into()), scopes: Some(vec!["all-apis".into()]), token_url: Some("https://example/token".into()), + identity_federation_client_id: Some("federation-client".into()), ..Default::default() }, ) @@ -359,7 +373,10 @@ mod tests { assert_eq!(client_secret, "sec"); assert_eq!(scopes, Some(vec!["all-apis".to_string()])); assert_eq!(token_url_override.as_deref(), Some("https://example/token")); - assert!(identity_federation_client_id.is_none()); + assert_eq!( + identity_federation_client_id.as_deref(), + Some("federation-client") + ); } other => panic!("expected OAuthM2M, got {other:?}"), } @@ -471,6 +488,7 @@ mod tests { OAuthParams { redirect_port: Some(9999), callback_timeout_secs: Some(300), + identity_federation_client_id: Some("federation-client".into()), ..Default::default() }, ) @@ -479,10 +497,15 @@ mod tests { AuthConfig::OAuthU2M { redirect_port, callback_timeout, + identity_federation_client_id, .. } => { assert_eq!(redirect_port, Some(9999)); assert_eq!(callback_timeout, Some(Duration::from_secs(300))); + assert_eq!( + identity_federation_client_id.as_deref(), + Some("federation-client") + ); } other => panic!("expected OAuthU2M, got {other:?}"), } diff --git a/pyo3/src/session.rs b/pyo3/src/session.rs index d2d30940..a0ec22e2 100644 --- a/pyo3/src/session.rs +++ b/pyo3/src/session.rs @@ -73,6 +73,10 @@ impl Session { /// OAuth is kernel-owned: the kernel acquires and transparently /// refreshes tokens itself. /// + /// `identity_federation_client_id` selects SP-wide Workload Identity + /// Federation during mandatory token exchange. Omit it for BYOT / + /// account-wide WIF. + /// /// TLS: all knobs are optional relaxations / additions on top of /// the secure default (validate system trust store, verify chain /// + hostname). `tls_ca_cert` adds a PEM CA bundle (bytes); @@ -118,6 +122,7 @@ impl Session { token_url=None, redirect_port=None, oauth_callback_timeout_secs=None, + identity_federation_client_id=None, tls_ca_cert=None, tls_skip_verify=false, tls_skip_hostname_verify=false, @@ -147,6 +152,7 @@ impl Session { token_url: Option, redirect_port: Option, oauth_callback_timeout_secs: Option, + identity_federation_client_id: Option, tls_ca_cert: Option>, tls_skip_verify: bool, tls_skip_hostname_verify: bool, @@ -193,6 +199,7 @@ impl Session { token_url, redirect_port, callback_timeout_secs: oauth_callback_timeout_secs, + identity_federation_client_id, }; let auth_config = build_auth_config(&resolved_auth_type, access_token, oauth)?; diff --git a/pyo3/tests/test_auth.py b/pyo3/tests/test_auth.py index 3e2cee99..12bf9138 100644 --- a/pyo3/tests/test_auth.py +++ b/pyo3/tests/test_auth.py @@ -59,3 +59,12 @@ def test_unknown_auth_type_raises_value_error(): auth_type="something-else", access_token="x", ) + + +def test_identity_federation_client_id_is_accepted_kwarg(): + with pytest.raises(ValueError, match="access_token"): + k.Session( + host="x.databricks.com", + http_path="/sql/1.0/warehouses/abc", + identity_federation_client_id="federation-client", + ) diff --git a/src/c_abi/session.rs b/src/c_abi/session.rs index 9e065245..f00c43e8 100644 --- a/src/c_abi/session.rs +++ b/src/c_abi/session.rs @@ -112,6 +112,8 @@ pub struct KernelSessionConfig { /// real transactions via `kernel_session_config_set_ignore_transactions` /// with `false`. Maps to [`DefaultOpts::ignore_transactions`]. ignore_transactions: bool, + /// SP-wide WIF client id applied to the selected auth mode. + identity_federation_client_id: 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 @@ -203,6 +205,7 @@ pub unsafe extern "C" fn kernel_session_config_new( retry: None, // Default to ignoring transactions, matching IgnoreTransactions=1. ignore_transactions: true, + identity_federation_client_id: None, // Match the reference driver's / JDBC's EnableTokenCache=1. token_cache: TokenCacheConfig::default(), // Kernel result defaults (CloudFetch enabled, Arrow-native types). @@ -349,6 +352,22 @@ pub unsafe extern "C" fn kernel_session_config_set_auth_u2m( }) } +/// Set the optional SP-wide Workload Identity Federation client id used by +/// mandatory token exchange. Leaving it unset selects BYOT / account-wide WIF. +/// +/// # Safety +/// `config` must be live and `client_id` must be a NUL-terminated C string. +#[no_mangle] +pub unsafe extern "C" fn kernel_session_config_set_identity_federation_client_id( + config: *mut KernelSessionConfig, + client_id: *const c_char, +) -> KernelStatusCode { + set_on_config(config, |c| { + c.identity_federation_client_id = Some(required_str(client_id, "client_id")?); + 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`. @@ -898,6 +917,7 @@ fn build_session(config: KernelSessionConfig) -> Result Result AuthConfig::pat(Some(token))?, + 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), None, None)?, + } => AuthConfig::oauth_m2m( + Some(client_id), + Some(client_secret), + None, + None, + identity_federation_client_id, + )?, AuthSpec::OAuthU2M { client_id, redirect_port, @@ -942,6 +970,7 @@ fn build_session(config: KernelSessionConfig) -> Result) -> crate::Result { + /// instead of each re-implementing it at the binding boundary. The + /// optional federation client id is forwarded unchanged. + pub fn pat( + token: Option, + identity_federation_client_id: Option, + ) -> crate::Result { match token { Some(token) if !token.is_empty() => Ok(AuthConfig::Pat { token, - identity_federation_client_id: None, + identity_federation_client_id, }), _ => Err(crate::kernel_error::Error::invalid_argument() .message("PAT auth requires a non-empty access token")), @@ -393,12 +397,14 @@ impl AuthConfig { /// Construct a [`AuthConfig::OAuthM2M`] from optional fields, /// validating that the required `client_id` / `client_secret` are /// present and non-empty. `scopes` / `token_url_override` are - /// optional and forwarded as-is (the kernel fills defaults). + /// optional and forwarded as-is (the kernel fills defaults), as is the + /// federation client id. pub fn oauth_m2m( client_id: Option, client_secret: Option, scopes: Option>, token_url_override: Option, + identity_federation_client_id: Option, ) -> crate::Result { let client_id = client_id.filter(|s| !s.is_empty()).ok_or_else(|| { crate::kernel_error::Error::invalid_argument() @@ -413,7 +419,7 @@ impl AuthConfig { client_secret, scopes, token_url_override, - identity_federation_client_id: None, + identity_federation_client_id, }) } @@ -422,7 +428,7 @@ impl AuthConfig { /// port 8030 / `sql offline_access` when omitted — so this performs no /// validation and exists for symmetry with [`AuthConfig::pat`] / /// [`AuthConfig::oauth_m2m`] so bindings can forward optionals - /// uniformly. + /// uniformly, including the federation client id. pub fn oauth_u2m( client_id: Option, redirect_port: Option, @@ -430,6 +436,7 @@ impl AuthConfig { token_url_override: Option, callback_timeout: Option, token_cache: Option, + identity_federation_client_id: Option, ) -> Self { AuthConfig::OAuthU2M { client_id, @@ -438,7 +445,7 @@ impl AuthConfig { token_url_override, callback_timeout, token_cache, - identity_federation_client_id: None, + identity_federation_client_id, } } @@ -1555,23 +1562,31 @@ mod tests { #[test] fn pat_rejects_missing_or_empty_token() { - let err = AuthConfig::pat(None).unwrap_err(); + let err = AuthConfig::pat(None, None).unwrap_err(); assert_eq!(err.code, crate::kernel_error::ErrorCode::InvalidArgument); assert!(err.message.contains("non-empty access token")); - let err = AuthConfig::pat(Some(String::new())).unwrap_err(); + let err = AuthConfig::pat(Some(String::new()), None).unwrap_err(); assert_eq!(err.code, crate::kernel_error::ErrorCode::InvalidArgument); } #[test] fn pat_accepts_non_empty_token() { - match AuthConfig::pat(Some("dapi-x".to_string())).unwrap() { + match AuthConfig::pat( + Some("dapi-x".to_string()), + Some("federation-client".to_string()), + ) + .unwrap() + { AuthConfig::Pat { token, identity_federation_client_id, } => { assert_eq!(token, "dapi-x"); - assert!(identity_federation_client_id.is_none()); + assert_eq!( + identity_federation_client_id.as_deref(), + Some("federation-client") + ); } other => panic!("expected Pat, got {other:?}"), } @@ -1579,24 +1594,38 @@ mod tests { #[test] fn oauth_m2m_rejects_missing_or_empty_client_id() { - let err = AuthConfig::oauth_m2m(None, Some("sec".to_string()), None, None).unwrap_err(); + let err = + AuthConfig::oauth_m2m(None, Some("sec".to_string()), None, None, None).unwrap_err(); assert_eq!(err.code, crate::kernel_error::ErrorCode::InvalidArgument); assert!(err.message.contains("client_id")); - let err = AuthConfig::oauth_m2m(Some(String::new()), Some("sec".to_string()), None, None) - .unwrap_err(); + let err = AuthConfig::oauth_m2m( + Some(String::new()), + Some("sec".to_string()), + None, + None, + None, + ) + .unwrap_err(); assert_eq!(err.code, crate::kernel_error::ErrorCode::InvalidArgument); assert!(err.message.contains("client_id")); } #[test] fn oauth_m2m_rejects_missing_or_empty_client_secret() { - let err = AuthConfig::oauth_m2m(Some("cid".to_string()), None, None, None).unwrap_err(); + let err = + AuthConfig::oauth_m2m(Some("cid".to_string()), None, None, None, None).unwrap_err(); assert_eq!(err.code, crate::kernel_error::ErrorCode::InvalidArgument); assert!(err.message.contains("client_secret")); - let err = AuthConfig::oauth_m2m(Some("cid".to_string()), Some(String::new()), None, None) - .unwrap_err(); + let err = AuthConfig::oauth_m2m( + Some("cid".to_string()), + Some(String::new()), + None, + None, + None, + ) + .unwrap_err(); assert_eq!(err.code, crate::kernel_error::ErrorCode::InvalidArgument); assert!(err.message.contains("client_secret")); } @@ -1608,6 +1637,7 @@ mod tests { Some("sec".to_string()), Some(vec!["all-apis".to_string()]), None, + Some("federation-client".to_string()), ) .unwrap() { @@ -1622,17 +1652,31 @@ mod tests { assert_eq!(client_secret, "sec"); assert_eq!(scopes, Some(vec!["all-apis".to_string()])); assert!(token_url_override.is_none()); - assert!(identity_federation_client_id.is_none()); + assert_eq!( + identity_federation_client_id.as_deref(), + Some("federation-client") + ); } other => panic!("expected OAuthM2M, got {other:?}"), } } #[test] - fn oauth_u2m_defaults_identity_federation_client_id() { - let auth = AuthConfig::oauth_u2m(None, None, None, None, None, None); + fn oauth_u2m_carries_identity_federation_client_id() { + let auth = AuthConfig::oauth_u2m( + None, + None, + None, + None, + None, + None, + Some("federation-client".to_string()), + ); - assert_eq!(auth.identity_federation_client_id(), None); + assert_eq!( + auth.identity_federation_client_id(), + Some("federation-client") + ); } #[test] diff --git a/tests/c/session_smoke.c b/tests/c/session_smoke.c index ca55e1ae..a02d14bc 100644 --- a/tests/c/session_smoke.c +++ b/tests/c/session_smoke.c @@ -205,6 +205,18 @@ static void test_u2m_and_header_setters(void) { kernel_session_config_free(config); } +static void test_identity_federation_client_id_setter(void) { + KernelSessionConfig* config = NULL; + (void)kernel_session_config_new(&config); + KernelStatusCode rc = + kernel_session_config_set_identity_federation_client_id(config, "federation-client"); + CHECK(rc == KernelStatusCode_Success, "set_identity_federation_client_id succeeds"); + rc = kernel_session_config_set_identity_federation_client_id(config, NULL); + CHECK(rc == KernelStatusCode_InvalidArgument, + "set_identity_federation_client_id(NULL) → InvalidArgument"); + kernel_session_config_free(config); +} + /* Client-conf setter accepts known keys, clamps, and rejects bad input. */ static void test_client_conf_setter(void) { KernelSessionConfig* config = NULL; @@ -300,6 +312,7 @@ int main(void) { test_setter_null_arg_rejected(); test_proxy_and_tls_setters(); test_u2m_and_header_setters(); + test_identity_federation_client_id_setter(); test_client_conf_setter(); test_init_logging(); test_is_open_null_guards();