From 3995c256f4d907d315c89fb203f8f2d65dc03efd Mon Sep 17 00:00:00 2001 From: eric-wang-1990 Date: Mon, 17 Aug 2026 18:15:26 -0700 Subject: [PATCH 01/19] feat(auth): support a redirect-port range for U2M browser flow (PECOBLR-4144) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The U2M browser flow bound exactly one callback port (CallbackServer::new), so if that port was occupied — a stale prior listener, or a second concurrent connection — the flow failed. The Thrift connector tolerates this by iterating its registered redirect-URI range (databricks-sql-python -> 8020-8024) and binding the first free port; the kernel's single-port API could not. Add CallbackServer::new_in_range: try candidate ports in order, skip AddrInUse, bind the first that succeeds, and surface a clear error if all are busy. redirect_uri() already derives from the bound port, so the OAuth redirect_uri matches automatically. Thread a caller-supplied port list through additively: a new AuthConfig::OAuthU2M.redirect_ports (Option>) plus a with_redirect_ports() builder — no signature change to oauth_u2m(), so c_abi and napi keep their single-port APIs untouched. resolve_u2m_bundle picks a non-empty redirect_ports over the single redirect_port over the default. Only pyo3 exposes the list (redirect_ports on Session.__new__), the one consumer registered for a multi-port app; empty / zero-containing lists are rejected like redirect_port=0. Candidate ports must be caller-supplied because they must be registered redirect URIs of the OAuth app — an automatic +N would not be registered for the default databricks-sql-connector app (8030 only). Co-authored-by: Isaac Signed-off-by: eric-wang-1990 --- pyo3/src/auth.rs | 85 ++++++++++++++++++++- pyo3/src/session.rs | 3 + src/auth/oauth/callback.rs | 153 +++++++++++++++++++++++++++++++++++-- src/auth/oauth/u2m.rs | 23 +++--- src/config.rs | 65 +++++++++++++++- src/session.rs | 65 +++++++++++++--- 6 files changed, 364 insertions(+), 30 deletions(-) diff --git a/pyo3/src/auth.rs b/pyo3/src/auth.rs index 1e4f3d78..cffe4520 100644 --- a/pyo3/src/auth.rs +++ b/pyo3/src/auth.rs @@ -51,6 +51,11 @@ pub(crate) struct OAuthParams { pub scopes: Option>, pub token_url: Option, pub redirect_port: Option, + /// Candidate U2M redirect ports, tried in order (first free binds). + /// When set (non-empty) this takes precedence over `redirect_port` and + /// gives the busy-port fallback the Thrift connector has across its + /// registered range (`databricks-sql-python` → 8020‑8024). + pub redirect_ports: Option>, pub callback_timeout_secs: Option, pub identity_federation_client_id: Option, } @@ -198,6 +203,27 @@ fn build_auth_config_inner( .to_owned(), ); } + // `redirect_ports` (the busy-port-fallback range) is caller-supplied + // and takes precedence over `redirect_port` downstream. Reject the + // degenerate shapes for the same reason as `redirect_port=0`: an + // empty list carries no port, and a 0 entry binds an ephemeral port + // that can't match the IdP's static redirect_uri. + if let Some(ports) = oauth.redirect_ports.as_deref() { + if ports.is_empty() { + return Err( + "auth_type='oauth-u2m' redirect_ports must be non-empty when set; \ + omit it to use redirect_port or the default" + .to_owned(), + ); + } + if ports.contains(&0) { + return Err( + "auth_type='oauth-u2m' redirect_ports entries must be non-zero \ + (each must be a static port the IdP redirect_uri can match)" + .to_owned(), + ); + } + } // Default the U2M OAuth client to the Python connector's // own registered client (`databricks-sql-python`), NOT the // kernel's bare-Rust fallback (`databricks-sql-connector`). This @@ -255,7 +281,8 @@ fn build_auth_config_inner( // TokenCachePassPhrase — would strengthen it further. None, oauth.identity_federation_client_id, - )) + ) + .with_redirect_ports(oauth.redirect_ports)) } other => Err(format!( "unsupported auth_type {other:?}; expected one of 'pat', 'oauth-m2m', 'oauth-u2m'" @@ -396,6 +423,7 @@ mod tests { AuthConfig::OAuthU2M { client_id, redirect_port, + redirect_ports, scopes, token_url_override, callback_timeout, @@ -406,6 +434,8 @@ mod tests { // Python bundle pins its own app's registered port (8020), // NOT the kernel default 8030 (databricks-sql-connector). assert_eq!(redirect_port, Some(8020)); + // No range supplied → redirect_ports stays None (single-port). + assert_eq!(redirect_ports, None); assert_eq!( scopes, Some(vec!["sql".to_string(), "offline_access".to_string()]) @@ -426,6 +456,59 @@ mod tests { } } + #[test] + fn u2m_redirect_ports_are_forwarded() { + // A caller-supplied port range (the connector's registered redirect + // URIs) is carried through onto the config for busy-port fallback. + let cfg = build_auth_config_inner( + "oauth-u2m", + None, + OAuthParams { + client_id: Some("databricks-sql-python".to_string()), + redirect_ports: Some(vec![8020, 8021, 8022, 8023, 8024]), + ..Default::default() + }, + ) + .unwrap(); + match cfg { + AuthConfig::OAuthU2M { redirect_ports, .. } => { + assert_eq!(redirect_ports, Some(vec![8020, 8021, 8022, 8023, 8024])); + } + other => panic!("expected OAuthU2M, got {other:?}"), + } + } + + #[test] + fn u2m_empty_redirect_ports_rejected() { + let err = build_auth_config_inner( + "oauth-u2m", + None, + OAuthParams { + redirect_ports: Some(vec![]), + ..Default::default() + }, + ) + .unwrap_err(); + assert!( + err.contains("redirect_ports must be non-empty"), + "got: {err}" + ); + } + + #[test] + fn u2m_zero_in_redirect_ports_rejected() { + let err = build_auth_config_inner( + "oauth-u2m", + None, + OAuthParams { + redirect_ports: Some(vec![8020, 0]), + ..Default::default() + }, + ) + .unwrap_err(); + assert!(err.contains("non-zero"), "got: {err}"); + } + #[test] fn u2m_explicit_client_id_overrides_default() { let cfg = build_auth_config_inner( diff --git a/pyo3/src/session.rs b/pyo3/src/session.rs index a0ec22e2..a778f11a 100644 --- a/pyo3/src/session.rs +++ b/pyo3/src/session.rs @@ -121,6 +121,7 @@ impl Session { oauth_scopes=None, token_url=None, redirect_port=None, + redirect_ports=None, oauth_callback_timeout_secs=None, identity_federation_client_id=None, tls_ca_cert=None, @@ -151,6 +152,7 @@ impl Session { oauth_scopes: Option>, token_url: Option, redirect_port: Option, + redirect_ports: Option>, oauth_callback_timeout_secs: Option, identity_federation_client_id: Option, tls_ca_cert: Option>, @@ -198,6 +200,7 @@ impl Session { scopes: oauth_scopes, token_url, redirect_port, + redirect_ports, callback_timeout_secs: oauth_callback_timeout_secs, identity_federation_client_id, }; diff --git a/src/auth/oauth/callback.rs b/src/auth/oauth/callback.rs index 047bc587..27bb68c6 100644 --- a/src/auth/oauth/callback.rs +++ b/src/auth/oauth/callback.rs @@ -125,16 +125,90 @@ impl CallbackServer { /// /// Returns `io()` error if the server cannot bind to the specified port. pub async fn new(port: u16) -> Result { - let addr: SocketAddr = format!("127.0.0.1:{}", port).parse().map_err(|e| { - Error::invalid_argument().message(format!("Invalid port number {}: {}", port, e)) - })?; - - let listener = TcpListener::bind(addr).await.map_err(|e| { + let listener = Self::bind(port).await.map_err(|e| { Error::io() - .message(format!("Failed to bind callback server to {}: {}", addr, e)) + .message(format!( + "Failed to bind callback server to 127.0.0.1:{}: {}", + port, e + )) .context("OAuth callback server") })?; + Self::from_listener(listener) + } + + /// Creates a callback server on the first bindable port in `ports`. + /// + /// Tries each candidate port in order and keeps the first one that binds, + /// skipping ports already in use (`AddrInUse`) — the same busy-port + /// tolerance the Thrift connector's `OAuthManager` provides by iterating its + /// registered redirect-URI range (e.g. `databricks-sql-python` → 8020‑8024). + /// The kernel's single-port U2M API otherwise fails outright when its one + /// port is occupied by a stale listener or a second concurrent connection. + /// + /// [`redirect_uri`](Self::redirect_uri) reflects whichever port actually + /// bound, so the OAuth `redirect_uri` matches automatically — every port a + /// caller passes must therefore be a registered redirect URI of its OAuth + /// app. + /// + /// # Arguments + /// + /// * `ports` - Candidate ports to try, in preference order (must be non-empty). + /// + /// # Errors + /// + /// - `invalid_argument` if `ports` is empty. + /// - `io()` if a non-`AddrInUse` bind error occurs (returned immediately, + /// not retried), or if every candidate port is already in use. + pub async fn new_in_range(ports: &[u16]) -> Result { + if ports.is_empty() { + return Err(Error::invalid_argument() + .message("CallbackServer::new_in_range requires at least one candidate port")); + } + + let mut last_in_use: Option = None; + for &port in ports { + match Self::bind(port).await { + Ok(listener) => return Self::from_listener(listener), + Err(e) if e.kind() == std::io::ErrorKind::AddrInUse => { + crate::klog::debug!("Callback port {} is in use, trying next", port); + last_in_use = Some(e); + } + // A non-"address in use" failure (permission denied, etc.) is not + // something the next port would fix — surface it immediately, + // mirroring the Thrift loop which only continues on EADDRINUSE. + Err(e) => { + return Err(Error::io() + .message(format!( + "Failed to bind callback server to 127.0.0.1:{}: {}", + port, e + )) + .context("OAuth callback server")); + } + } + } + + Err(Error::io() + .message(format!( + "All candidate callback ports are in use: {:?}{}", + ports, + last_in_use + .map(|e| format!(" (last error: {})", e)) + .unwrap_or_default() + )) + .context("OAuth callback server")) + } + + /// Binds a `TcpListener` on `127.0.0.1:{port}`, returning the raw + /// `std::io::Error` so callers can distinguish `AddrInUse` (retryable across + /// a port range) from other failures. + async fn bind(port: u16) -> std::io::Result { + let addr = SocketAddr::from(([127, 0, 0, 1], port)); + TcpListener::bind(addr).await + } + /// Wraps a bound listener in a running `CallbackServer` (reads the actual + /// bound port, opens the result channel, spawns the accept task). + fn from_listener(listener: TcpListener) -> Result { // Get the actual port (in case port 0 was specified for automatic assignment) let actual_port = listener .local_addr() @@ -637,4 +711,71 @@ mod tests { .unwrap(); assert!(port > 0, "Expected a non-zero port, got: {}", port); } + + #[tokio::test] + async fn test_new_in_range_empty_is_error() { + let result = CallbackServer::new_in_range(&[]).await; + assert!(result.is_err(), "empty port list should be rejected"); + } + + #[tokio::test] + async fn test_new_in_range_single_port_binds() { + // A one-element range behaves like new(0): binds an OS-assigned port. + let server = CallbackServer::new_in_range(&[0]) + .await + .expect("should bind the single candidate port"); + assert!( + server.redirect_uri().starts_with("http://localhost:"), + "unexpected redirect_uri: {}", + server.redirect_uri() + ); + assert!(server.port > 0); + } + + #[tokio::test] + async fn test_new_in_range_skips_busy_port() { + // Occupy a port, then offer it as the first candidate followed by 0 + // (OS-assigned, always bindable). The server must skip the busy port + // and bind the next candidate instead. + let occupied = TcpListener::bind("127.0.0.1:0") + .await + .expect("failed to occupy a port"); + let busy_port = occupied.local_addr().unwrap().port(); + + let server = CallbackServer::new_in_range(&[busy_port, 0]) + .await + .expect("should fall back past the busy port"); + + assert_ne!( + server.port, busy_port, + "server should not have bound the occupied port {}", + busy_port + ); + assert!(server.port > 0); + // redirect_uri must reflect the port that actually bound. + assert_eq!( + server.redirect_uri(), + format!("http://localhost:{}", server.port) + ); + } + + #[tokio::test] + async fn test_new_in_range_all_busy_is_error() { + // Occupy two ports and offer only those two — all candidates are busy. + let l1 = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let l2 = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let p1 = l1.local_addr().unwrap().port(); + let p2 = l2.local_addr().unwrap().port(); + + // Avoid unwrap_err(): CallbackServer (the Ok type) is not Debug. + let msg = match CallbackServer::new_in_range(&[p1, p2]).await { + Ok(_) => panic!("all candidate ports busy should be an error"), + Err(e) => format!("{:?}", e), + }; + assert!( + msg.contains("in use"), + "error should mention ports in use: {}", + msg + ); + } } diff --git a/src/auth/oauth/u2m.rs b/src/auth/oauth/u2m.rs index 60cd934e..2bf5871a 100644 --- a/src/auth/oauth/u2m.rs +++ b/src/auth/oauth/u2m.rs @@ -136,8 +136,8 @@ pub struct AuthorizationCodeProvider { http_client: Arc, /// OAuth scopes to request (typically "all-apis offline_access") scopes: Vec, - /// Callback server port - callback_port: u16, + /// Candidate callback-server ports, tried in order (first free binds). + callback_ports: Vec, /// Callback timeout callback_timeout: Duration, /// Whether to open browser automatically (set to false in tests) @@ -239,7 +239,7 @@ impl AuthorizationCodeProvider { client_id, http_client, scopes, - callback_port, + vec![callback_port], callback_timeout, None, // No token_endpoint override None, // On-disk cache disabled: no passphrase available here @@ -263,7 +263,7 @@ impl AuthorizationCodeProvider { client_id: &str, http_client: Arc, scopes: Vec, - callback_port: u16, + callback_ports: Vec, callback_timeout: Duration, token_endpoint_override: Option, cache_passphrase: Option, @@ -308,7 +308,7 @@ impl AuthorizationCodeProvider { token_store, http_client, scopes, - callback_port, + callback_ports, callback_timeout, open_browser: true, cache_passphrase, @@ -359,7 +359,7 @@ impl AuthProvider for AuthorizationCodeProvider { let token_endpoint = self.token_endpoint.clone(); let auth_endpoint = self.auth_endpoint.clone(); let scopes = self.scopes.clone(); - let callback_port = self.callback_port; + let callback_ports = self.callback_ports.clone(); let callback_timeout = self.callback_timeout; let open_browser = self.open_browser; let http_client = self.http_client.clone(); @@ -479,8 +479,9 @@ impl AuthProvider for AuthorizationCodeProvider { // Generate PKCE challenge let (pkce_challenge, pkce_verifier) = PkceCodeChallenge::new_random_sha256(); - // Start callback server - let callback_server = CallbackServer::new(callback_port).await?; + // Start callback server, binding the first free candidate + // port (busy-port fallback across the registered range). + let callback_server = CallbackServer::new_in_range(&callback_ports).await?; let redirect_uri = callback_server.redirect_uri(); // Build OAuth client @@ -658,7 +659,7 @@ mod tests { "test-client-id", http_client, vec!["all-apis".to_string(), "offline_access".to_string()], - 8020, + vec![8020], Duration::from_secs(120), None, Some(TEST_CACHE_PASSPHRASE.to_string()), @@ -711,7 +712,7 @@ mod tests { "test-client-id", http_client, vec!["all-apis".to_string(), "offline_access".to_string()], - 8020, + vec![8020], Duration::from_secs(120), None, Some(TEST_CACHE_PASSPHRASE.to_string()), @@ -780,7 +781,7 @@ mod tests { "test-client-id", http_client, vec!["all-apis".to_string(), "offline_access".to_string()], - 0, // Use port 0 to avoid conflicts + vec![0], // Use port 0 to avoid conflicts Duration::from_secs(5), // Short timeout for test None, Some(TEST_CACHE_PASSPHRASE.to_string()), diff --git a/src/config.rs b/src/config.rs index b1e1d158..95895e44 100644 --- a/src/config.rs +++ b/src/config.rs @@ -330,8 +330,17 @@ pub enum AuthConfig { client_id: Option, /// Localhost port for the OAuth callback listener. `None` → /// `8030` (the redirect port registered for - /// `databricks-sql-connector`). + /// `databricks-sql-connector`). Ignored when `redirect_ports` + /// is set to a non-empty list. redirect_port: Option, + /// Candidate localhost callback ports, tried in order; the first + /// one free is bound (busy-port fallback). When `Some` and + /// non-empty this takes precedence over `redirect_port`. Every + /// port must be a registered redirect URI of the OAuth app — + /// this mirrors the Thrift connector's registered range + /// (`databricks-sql-python` → 8020‑8024). `None`/empty → fall + /// back to `redirect_port` (or the `8030` default). + redirect_ports: Option>, /// OAuth scopes. `None` → `["sql", "offline_access"]` /// (the `offline_access` scope is required to receive a /// refresh token, which the kernel caches and refreshes @@ -441,6 +450,7 @@ impl AuthConfig { AuthConfig::OAuthU2M { client_id, redirect_port, + redirect_ports: None, scopes, token_url_override, callback_timeout, @@ -449,6 +459,20 @@ impl AuthConfig { } } + /// Attach a list of candidate U2M redirect ports (busy-port fallback). + /// + /// Additive to [`AuthConfig::oauth_u2m`] so bindings can opt into the + /// port range without a constructor signature change. When set to a + /// non-empty list, the kernel binds the first free port in order and + /// derives the OAuth `redirect_uri` from it — so every port must be a + /// registered redirect URI of the OAuth app. A no-op on non-U2M variants. + pub fn with_redirect_ports(mut self, ports: Option>) -> Self { + if let AuthConfig::OAuthU2M { redirect_ports, .. } = &mut self { + *redirect_ports = ports; + } + self + } + /// SP-wide federation client id attached to the selected base auth flow. pub(crate) fn identity_federation_client_id(&self) -> Option<&str> { match self { @@ -519,6 +543,7 @@ impl std::fmt::Debug for AuthConfig { Self::OAuthU2M { client_id, redirect_port, + redirect_ports, scopes, identity_federation_client_id, .. @@ -526,6 +551,7 @@ impl std::fmt::Debug for AuthConfig { .debug_struct("OAuthU2M") .field("client_id", client_id) .field("redirect_port", redirect_port) + .field("redirect_ports", redirect_ports) .field("scopes", scopes) .field( "identity_federation_client_id", @@ -1679,6 +1705,42 @@ mod tests { ); } + #[test] + fn oauth_u2m_defaults_redirect_ports_to_none() { + let auth = AuthConfig::oauth_u2m(None, Some(8020), None, None, None, None, None); + match auth { + AuthConfig::OAuthU2M { redirect_ports, .. } => assert_eq!(redirect_ports, None), + other => panic!("expected OAuthU2M, got {other:?}"), + } + } + + #[test] + fn with_redirect_ports_sets_the_list_on_u2m() { + let auth = AuthConfig::oauth_u2m(None, None, None, None, None, None, None) + .with_redirect_ports(Some(vec![8020, 8021, 8022])); + match auth { + AuthConfig::OAuthU2M { + redirect_ports, + redirect_port, + .. + } => { + assert_eq!(redirect_ports, Some(vec![8020, 8021, 8022])); + // The single-port field is left untouched by the builder. + assert_eq!(redirect_port, None); + } + other => panic!("expected OAuthU2M, got {other:?}"), + } + } + + #[test] + fn with_redirect_ports_is_noop_on_non_u2m() { + // Applying the U2M-only builder to a PAT config must not panic or alter it. + let auth = AuthConfig::pat(Some("dapi123".to_string()), None) + .unwrap() + .with_redirect_ports(Some(vec![8020])); + assert!(matches!(auth, AuthConfig::Pat { .. })); + } + #[test] fn auth_variants_carry_identity_federation_client_id() { let auths = [ @@ -1696,6 +1758,7 @@ mod tests { AuthConfig::OAuthU2M { client_id: None, redirect_port: None, + redirect_ports: None, scopes: None, token_url_override: None, callback_timeout: None, diff --git a/src/session.rs b/src/session.rs index bc96ea86..e87d0e7f 100644 --- a/src/session.rs +++ b/src/session.rs @@ -1080,11 +1080,21 @@ fn default_u2m_scopes() -> Vec { fn resolve_u2m_bundle( client_id: Option<&str>, redirect_port: Option, + redirect_ports: Option<&[u16]>, scopes: Option<&[String]>, -) -> (String, u16, Vec) { +) -> (String, Vec, Vec) { + // Port precedence: an explicit, non-empty `redirect_ports` list (the + // busy-port-fallback range) wins; otherwise the single `redirect_port`; + // otherwise the kernel default. Every entry must be a registered redirect + // URI of the chosen OAuth app — the {client_id, ports, scopes} bundle stays + // coupled. + let ports = match redirect_ports { + Some(ports) if !ports.is_empty() => ports.to_vec(), + _ => vec![redirect_port.unwrap_or(DEFAULT_U2M_REDIRECT_PORT)], + }; ( client_id.unwrap_or(DEFAULT_U2M_CLIENT_ID).to_string(), - redirect_port.unwrap_or(DEFAULT_U2M_REDIRECT_PORT), + ports, scopes .map(<[String]>::to_vec) .unwrap_or_else(default_u2m_scopes), @@ -1158,6 +1168,7 @@ async fn build_base_auth_provider( AuthConfig::OAuthU2M { client_id, redirect_port, + redirect_ports, scopes, token_url_override, callback_timeout, @@ -1167,8 +1178,14 @@ async fn build_base_auth_provider( // Fill the coupled kernel default bundle for any unset field // (databricks-sql-connector / sql offline_access / 8030). Consumers // using a different app override the whole bundle. See PECOBLR-4039. - let (client_id, redirect_port, scopes) = - resolve_u2m_bundle(client_id.as_deref(), *redirect_port, scopes.as_deref()); + // `callback_ports` is the caller's registered redirect range (or a + // single-element default); the flow binds the first free one. + let (client_id, callback_ports, scopes) = resolve_u2m_bundle( + client_id.as_deref(), + *redirect_port, + redirect_ports.as_deref(), + scopes.as_deref(), + ); let timeout = callback_timeout.unwrap_or_else(|| Duration::from_secs(120)); // `Some(passphrase)` enables the on-disk cache, `None` disables // it. When the cache is on but the caller supplied no passphrase, @@ -1184,7 +1201,7 @@ async fn build_base_auth_provider( &client_id, http_client, scopes, - redirect_port, + callback_ports, timeout, token_url_override.clone(), cache_policy, @@ -1206,10 +1223,10 @@ mod u2m_default_tests { #[test] fn u2m_default_bundle_is_connector_sql_8030() { // Caller omits everything → kernel default databricks-sql-connector - // app bundle (PECOBLR-4039). - let (client_id, port, scopes) = resolve_u2m_bundle(None, None, None); + // app bundle (PECOBLR-4039). No port range → single default port. + let (client_id, ports, scopes) = resolve_u2m_bundle(None, None, None, None); assert_eq!(client_id, "databricks-sql-connector"); - assert_eq!(port, 8030); + assert_eq!(ports, vec![8030]); assert_eq!( scopes, vec!["sql".to_string(), "offline_access".to_string()] @@ -1221,12 +1238,38 @@ mod u2m_default_tests { // A consumer overriding for a different OAuth app supplies the whole // coupled bundle; each field is threaded through verbatim. let custom = vec!["all-apis".to_string()]; - let (client_id, port, scopes) = - resolve_u2m_bundle(Some("databricks-sql-python"), Some(8020), Some(&custom)); + let (client_id, ports, scopes) = resolve_u2m_bundle( + Some("databricks-sql-python"), + Some(8020), + None, + Some(&custom), + ); assert_eq!(client_id, "databricks-sql-python"); - assert_eq!(port, 8020); + assert_eq!(ports, vec![8020]); assert_eq!(scopes, custom); } + + #[test] + fn u2m_bundle_redirect_ports_take_precedence() { + // A non-empty redirect_ports list is the busy-port-fallback range and + // wins over the single redirect_port. + let (_, ports, _) = resolve_u2m_bundle(None, Some(8020), Some(&[9001, 9002, 9003]), None); + assert_eq!(ports, vec![9001, 9002, 9003]); + } + + #[test] + fn u2m_bundle_empty_redirect_ports_falls_back_to_single_port() { + // An empty list is treated as "unset" — fall back to redirect_port. + let (_, ports, _) = resolve_u2m_bundle(None, Some(8021), Some(&[]), None); + assert_eq!(ports, vec![8021]); + } + + #[test] + fn u2m_bundle_no_ports_at_all_uses_default() { + // Neither redirect_ports nor redirect_port → the kernel default port. + let (_, ports, _) = resolve_u2m_bundle(None, None, Some(&[]), None); + assert_eq!(ports, vec![8030]); + } } #[cfg(test)] From 5fd4b4119396bae0911820a61e1aa6b59ce9ff99 Mon Sep 17 00:00:00 2001 From: eric-wang-1990 Date: Mon, 17 Aug 2026 18:30:53 -0700 Subject: [PATCH 02/19] refactor(auth): model U2M redirect port as a single Option> MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Address review preference: instead of the additive redirect_port + redirect_ports pair, collapse to one field. AuthConfig::OAuthU2M now carries redirect_ports: Option> only, oauth_u2m() takes the list, and the with_redirect_ports() builder is removed. Single-port callers stay fully backward-compatible by wrapping their one port as a one-element list: c_abi and napi keep their u16 FFI and forward Some(vec![port]); pyo3 keeps the redirect_port Python kwarg (folded into the list) alongside the new redirect_ports. resolve_u2m_bundle takes just the list (non-empty → used verbatim; else the 8030 default). No behavior change vs the previous commit — single ports still resolve to exactly that port; only the internal shape is simplified. Co-authored-by: Isaac Signed-off-by: eric-wang-1990 --- napi/src/database.rs | 15 ++++---- pyo3/src/auth.rs | 31 ++++++++++------- src/c_abi/session.rs | 5 ++- src/config.rs | 82 ++++++++++++++++---------------------------- src/session.rs | 53 ++++++++++++---------------- 5 files changed, 83 insertions(+), 103 deletions(-) diff --git a/napi/src/database.rs b/napi/src/database.rs index b856c774..4d025c6c 100644 --- a/napi/src/database.rs +++ b/napi/src/database.rs @@ -368,7 +368,9 @@ fn build_auth_config(options: &ConnectionOptions) -> napi::Result { } Ok(AuthConfig::oauth_u2m( options.oauth_client_id.clone(), - options.oauth_redirect_port, + // Node exposes a single redirect port; forward it as a + // one-element candidate list (kernel binds the first free one). + options.oauth_redirect_port.map(|p| vec![p]), options.oauth_scopes.clone(), None, None, @@ -722,29 +724,30 @@ mod tests { match build_auth_config(&o).unwrap() { AuthConfig::OAuthU2M { client_id, - redirect_port, + redirect_ports, scopes, .. } => { assert!(client_id.is_none()); - assert!(redirect_port.is_none()); + assert!(redirect_ports.is_none()); assert!(scopes.is_none()); } other => panic!("expected OAuthU2M, got {other:?}"), } - // Explicit overrides thread through. + // Explicit overrides thread through. Node's single redirect port is + // forwarded as a one-element candidate list. 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, + redirect_ports, identity_federation_client_id, .. } => { assert_eq!(client_id.as_deref(), Some("custom-cli")); - assert_eq!(redirect_port, Some(9000)); + assert_eq!(redirect_ports, Some(vec![9000])); assert_eq!( identity_federation_client_id.as_deref(), Some("federation-client") diff --git a/pyo3/src/auth.rs b/pyo3/src/auth.rs index cffe4520..0a8493d2 100644 --- a/pyo3/src/auth.rs +++ b/pyo3/src/auth.rs @@ -266,9 +266,17 @@ fn build_auth_config_inner( None if !caller_set_client_id => Some(PYSQL_OAUTH_REDIRECT_PORT), None => None, }; + // Collapse the two Python knobs into the kernel's single + // `redirect_ports` list. An explicit `redirect_ports` (the + // connector's registered range, for busy-port fallback) wins; + // otherwise the single `redirect_port` (caller-supplied or the + // pinned databricks-sql-python default) becomes a one-element list. + let redirect_ports = oauth + .redirect_ports + .or_else(|| redirect_port.map(|p| vec![p])); Ok(AuthConfig::oauth_u2m( client_id, - redirect_port, + redirect_ports, scopes, oauth.token_url, oauth.callback_timeout_secs.map(Duration::from_secs), @@ -281,8 +289,7 @@ fn build_auth_config_inner( // TokenCachePassPhrase — would strengthen it further. None, oauth.identity_federation_client_id, - ) - .with_redirect_ports(oauth.redirect_ports)) + )) } other => Err(format!( "unsupported auth_type {other:?}; expected one of 'pat', 'oauth-m2m', 'oauth-u2m'" @@ -422,7 +429,6 @@ mod tests { match cfg { AuthConfig::OAuthU2M { client_id, - redirect_port, redirect_ports, scopes, token_url_override, @@ -432,10 +438,10 @@ mod tests { } => { assert_eq!(client_id.as_deref(), Some("databricks-sql-python")); // Python bundle pins its own app's registered port (8020), - // NOT the kernel default 8030 (databricks-sql-connector). - assert_eq!(redirect_port, Some(8020)); - // No range supplied → redirect_ports stays None (single-port). - assert_eq!(redirect_ports, None); + // NOT the kernel default 8030 (databricks-sql-connector). With + // no explicit range, the single pinned port is forwarded as a + // one-element candidate list. + assert_eq!(redirect_ports, Some(vec![8020])); assert_eq!( scopes, Some(vec!["sql".to_string(), "offline_access".to_string()]) @@ -524,7 +530,7 @@ mod tests { AuthConfig::OAuthU2M { client_id, scopes, - redirect_port, + redirect_ports, .. } => { assert_eq!(client_id.as_deref(), Some("my-custom-app")); @@ -532,7 +538,7 @@ mod tests { // bundle's defaults — a custom app owns its own scopes and // redirect port, so both defer to the kernel (None). assert!(scopes.is_none()); - assert!(redirect_port.is_none()); + assert!(redirect_ports.is_none()); } other => panic!("expected OAuthU2M, got {other:?}"), } @@ -578,12 +584,13 @@ mod tests { .unwrap(); match cfg { AuthConfig::OAuthU2M { - redirect_port, + redirect_ports, callback_timeout, identity_federation_client_id, .. } => { - assert_eq!(redirect_port, Some(9999)); + // The single caller port is forwarded as a one-element list. + assert_eq!(redirect_ports, Some(vec![9999])); assert_eq!(callback_timeout, Some(Duration::from_secs(300))); assert_eq!( identity_federation_client_id.as_deref(), diff --git a/src/c_abi/session.rs b/src/c_abi/session.rs index f00c43e8..28fd4e8a 100644 --- a/src/c_abi/session.rs +++ b/src/c_abi/session.rs @@ -965,7 +965,10 @@ fn build_session(config: KernelSessionConfig) -> Result AuthConfig::oauth_u2m( client_id, - redirect_port, + // 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, diff --git a/src/config.rs b/src/config.rs index 95895e44..5b060262 100644 --- a/src/config.rs +++ b/src/config.rs @@ -328,18 +328,15 @@ pub enum AuthConfig { /// OAuth client ID. `None` → `"databricks-sql-connector"` (the /// default OAuth app, shared by the Node and Go drivers). client_id: Option, - /// Localhost port for the OAuth callback listener. `None` → - /// `8030` (the redirect port registered for - /// `databricks-sql-connector`). Ignored when `redirect_ports` - /// is set to a non-empty list. - redirect_port: Option, /// Candidate localhost callback ports, tried in order; the first - /// one free is bound (busy-port fallback). When `Some` and - /// non-empty this takes precedence over `redirect_port`. Every - /// port must be a registered redirect URI of the OAuth app — - /// this mirrors the Thrift connector's registered range - /// (`databricks-sql-python` → 8020‑8024). `None`/empty → fall - /// back to `redirect_port` (or the `8030` default). + /// one free is bound (busy-port fallback). `None`/empty → the + /// `8030` default (registered for `databricks-sql-connector`). + /// A single fixed port is just a one-element list (`vec![p]`) — + /// which is how the single-port bindings (C ABI, N-API) forward + /// their one port. Every entry must be a registered redirect URI + /// of the OAuth app; a multi-port list mirrors the Thrift + /// connector's registered range (`databricks-sql-python` → + /// 8020‑8024) for busy-port fallback. redirect_ports: Option>, /// OAuth scopes. `None` → `["sql", "offline_access"]` /// (the `offline_access` scope is required to receive a @@ -438,9 +435,13 @@ impl AuthConfig { /// validation and exists for symmetry with [`AuthConfig::pat`] / /// [`AuthConfig::oauth_m2m`] so bindings can forward optionals /// uniformly, including the federation client id. + /// + /// `redirect_ports` is the ordered list of candidate callback ports + /// (first free binds). Single-port callers pass a one-element list + /// (`Some(vec![port])`); `None`/empty falls back to the `8030` default. pub fn oauth_u2m( client_id: Option, - redirect_port: Option, + redirect_ports: Option>, scopes: Option>, token_url_override: Option, callback_timeout: Option, @@ -449,8 +450,7 @@ impl AuthConfig { ) -> Self { AuthConfig::OAuthU2M { client_id, - redirect_port, - redirect_ports: None, + redirect_ports, scopes, token_url_override, callback_timeout, @@ -459,20 +459,6 @@ impl AuthConfig { } } - /// Attach a list of candidate U2M redirect ports (busy-port fallback). - /// - /// Additive to [`AuthConfig::oauth_u2m`] so bindings can opt into the - /// port range without a constructor signature change. When set to a - /// non-empty list, the kernel binds the first free port in order and - /// derives the OAuth `redirect_uri` from it — so every port must be a - /// registered redirect URI of the OAuth app. A no-op on non-U2M variants. - pub fn with_redirect_ports(mut self, ports: Option>) -> Self { - if let AuthConfig::OAuthU2M { redirect_ports, .. } = &mut self { - *redirect_ports = ports; - } - self - } - /// SP-wide federation client id attached to the selected base auth flow. pub(crate) fn identity_federation_client_id(&self) -> Option<&str> { match self { @@ -542,7 +528,6 @@ impl std::fmt::Debug for AuthConfig { .finish(), Self::OAuthU2M { client_id, - redirect_port, redirect_ports, scopes, identity_federation_client_id, @@ -550,7 +535,6 @@ impl std::fmt::Debug for AuthConfig { } => f .debug_struct("OAuthU2M") .field("client_id", client_id) - .field("redirect_port", redirect_port) .field("redirect_ports", redirect_ports) .field("scopes", scopes) .field( @@ -1706,8 +1690,9 @@ mod tests { } #[test] - fn oauth_u2m_defaults_redirect_ports_to_none() { - let auth = AuthConfig::oauth_u2m(None, Some(8020), None, None, None, None, None); + fn oauth_u2m_none_ports_stays_none() { + // No ports supplied → redirect_ports is None (session fills the default). + let auth = AuthConfig::oauth_u2m(None, None, None, None, None, None, None); match auth { AuthConfig::OAuthU2M { redirect_ports, .. } => assert_eq!(redirect_ports, None), other => panic!("expected OAuthU2M, got {other:?}"), @@ -1715,32 +1700,26 @@ mod tests { } #[test] - fn with_redirect_ports_sets_the_list_on_u2m() { - let auth = AuthConfig::oauth_u2m(None, None, None, None, None, None, None) - .with_redirect_ports(Some(vec![8020, 8021, 8022])); + fn oauth_u2m_carries_redirect_ports_list() { + // A caller (e.g. the connector's registered range) forwards the whole + // list; a single-port binding forwards a one-element list. + let auth = AuthConfig::oauth_u2m( + None, + Some(vec![8020, 8021, 8022]), + None, + None, + None, + None, + None, + ); match auth { - AuthConfig::OAuthU2M { - redirect_ports, - redirect_port, - .. - } => { + AuthConfig::OAuthU2M { redirect_ports, .. } => { assert_eq!(redirect_ports, Some(vec![8020, 8021, 8022])); - // The single-port field is left untouched by the builder. - assert_eq!(redirect_port, None); } other => panic!("expected OAuthU2M, got {other:?}"), } } - #[test] - fn with_redirect_ports_is_noop_on_non_u2m() { - // Applying the U2M-only builder to a PAT config must not panic or alter it. - let auth = AuthConfig::pat(Some("dapi123".to_string()), None) - .unwrap() - .with_redirect_ports(Some(vec![8020])); - assert!(matches!(auth, AuthConfig::Pat { .. })); - } - #[test] fn auth_variants_carry_identity_federation_client_id() { let auths = [ @@ -1757,7 +1736,6 @@ mod tests { }, AuthConfig::OAuthU2M { client_id: None, - redirect_port: None, redirect_ports: None, scopes: None, token_url_override: None, diff --git a/src/session.rs b/src/session.rs index e87d0e7f..cb0ad352 100644 --- a/src/session.rs +++ b/src/session.rs @@ -1079,18 +1079,17 @@ fn default_u2m_scopes() -> Vec { /// `redirect_port` (and usually `scopes`). fn resolve_u2m_bundle( client_id: Option<&str>, - redirect_port: Option, redirect_ports: Option<&[u16]>, scopes: Option<&[String]>, ) -> (String, Vec, Vec) { - // Port precedence: an explicit, non-empty `redirect_ports` list (the - // busy-port-fallback range) wins; otherwise the single `redirect_port`; - // otherwise the kernel default. Every entry must be a registered redirect - // URI of the chosen OAuth app — the {client_id, ports, scopes} bundle stays - // coupled. + // A non-empty `redirect_ports` list (the caller's registered redirect URIs, + // one or many) is used verbatim; otherwise the kernel default. Every entry + // must be a registered redirect URI of the chosen OAuth app — the + // {client_id, ports, scopes} bundle stays coupled. Single-port bindings + // forward a one-element list. let ports = match redirect_ports { Some(ports) if !ports.is_empty() => ports.to_vec(), - _ => vec![redirect_port.unwrap_or(DEFAULT_U2M_REDIRECT_PORT)], + _ => vec![DEFAULT_U2M_REDIRECT_PORT], }; ( client_id.unwrap_or(DEFAULT_U2M_CLIENT_ID).to_string(), @@ -1167,7 +1166,6 @@ async fn build_base_auth_provider( } AuthConfig::OAuthU2M { client_id, - redirect_port, redirect_ports, scopes, token_url_override, @@ -1182,7 +1180,6 @@ async fn build_base_auth_provider( // single-element default); the flow binds the first free one. let (client_id, callback_ports, scopes) = resolve_u2m_bundle( client_id.as_deref(), - *redirect_port, redirect_ports.as_deref(), scopes.as_deref(), ); @@ -1224,7 +1221,7 @@ mod u2m_default_tests { fn u2m_default_bundle_is_connector_sql_8030() { // Caller omits everything → kernel default databricks-sql-connector // app bundle (PECOBLR-4039). No port range → single default port. - let (client_id, ports, scopes) = resolve_u2m_bundle(None, None, None, None); + let (client_id, ports, scopes) = resolve_u2m_bundle(None, None, None); assert_eq!(client_id, "databricks-sql-connector"); assert_eq!(ports, vec![8030]); assert_eq!( @@ -1236,39 +1233,31 @@ mod u2m_default_tests { #[test] fn u2m_bundle_honours_caller_overrides() { // A consumer overriding for a different OAuth app supplies the whole - // coupled bundle; each field is threaded through verbatim. + // coupled bundle; each field is threaded through verbatim. A single + // fixed port arrives as a one-element list. let custom = vec!["all-apis".to_string()]; - let (client_id, ports, scopes) = resolve_u2m_bundle( - Some("databricks-sql-python"), - Some(8020), - None, - Some(&custom), - ); + let (client_id, ports, scopes) = + resolve_u2m_bundle(Some("databricks-sql-python"), Some(&[8020]), Some(&custom)); assert_eq!(client_id, "databricks-sql-python"); assert_eq!(ports, vec![8020]); assert_eq!(scopes, custom); } #[test] - fn u2m_bundle_redirect_ports_take_precedence() { - // A non-empty redirect_ports list is the busy-port-fallback range and - // wins over the single redirect_port. - let (_, ports, _) = resolve_u2m_bundle(None, Some(8020), Some(&[9001, 9002, 9003]), None); + fn u2m_bundle_uses_the_full_redirect_ports_list() { + // A multi-port list (the connector's registered range) is used verbatim + // for busy-port fallback. + let (_, ports, _) = resolve_u2m_bundle(None, Some(&[9001, 9002, 9003]), None); assert_eq!(ports, vec![9001, 9002, 9003]); } #[test] - fn u2m_bundle_empty_redirect_ports_falls_back_to_single_port() { - // An empty list is treated as "unset" — fall back to redirect_port. - let (_, ports, _) = resolve_u2m_bundle(None, Some(8021), Some(&[]), None); - assert_eq!(ports, vec![8021]); - } - - #[test] - fn u2m_bundle_no_ports_at_all_uses_default() { - // Neither redirect_ports nor redirect_port → the kernel default port. - let (_, ports, _) = resolve_u2m_bundle(None, None, Some(&[]), None); - assert_eq!(ports, vec![8030]); + fn u2m_bundle_empty_or_none_ports_use_default() { + // Both an empty list and None fall back to the kernel default port. + let (_, ports_empty, _) = resolve_u2m_bundle(None, Some(&[]), None); + assert_eq!(ports_empty, vec![8030]); + let (_, ports_none, _) = resolve_u2m_bundle(None, None, None); + assert_eq!(ports_none, vec![8030]); } } From 0caf4532e9998056cdec4f061f40bc4c298a5e04 Mon Sep 17 00:00:00 2001 From: eric-wang-1990 Date: Mon, 17 Aug 2026 18:54:29 -0700 Subject: [PATCH 03/19] test(auth): update U2M integration tests for redirect_ports list The redirect_port -> redirect_ports: Option> change also touches the integration-test targets under tests/, which cargo test --lib does not compile (only the CI unit+doc/e2e/tls jobs do): - tests/oauth_u2m_integration.rs: new_with_full_config now takes Vec; wrap each single port as vec![port] (4 sites). - tests/v0_session_e2e.rs: AuthConfig::OAuthU2M literal field redirect_port -> redirect_ports. Fixes the failing Build (tls-rustls) / Clippy / Unit+doc / Coverage / v0 E2E checks, which all stemmed from these test targets failing to compile. Co-authored-by: Isaac Signed-off-by: eric-wang-1990 --- tests/oauth_u2m_integration.rs | 8 ++++---- tests/v0_session_e2e.rs | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/tests/oauth_u2m_integration.rs b/tests/oauth_u2m_integration.rs index 78d62fb7..95b83782 100644 --- a/tests/oauth_u2m_integration.rs +++ b/tests/oauth_u2m_integration.rs @@ -118,7 +118,7 @@ async fn test_u2m_refresh_token_full_flow() { "test-client-id", http_client, vec!["all-apis".to_string(), "offline_access".to_string()], - 8020, + vec![8020], Duration::from_secs(120), None, Some(TEST_CACHE_PASSPHRASE.to_string()), @@ -192,7 +192,7 @@ async fn test_u2m_refresh_token_stale_immediate_return() { "test-client-id-stale", http_client, vec!["all-apis".to_string(), "offline_access".to_string()], - 8021, + vec![8021], Duration::from_secs(120), None, Some(TEST_CACHE_PASSPHRASE.to_string()), @@ -272,7 +272,7 @@ async fn test_u2m_refresh_token_expired_fallback() { "test-client-id-expired", http_client, vec!["all-apis".to_string(), "offline_access".to_string()], - 0, // Use port 0 to avoid conflicts + vec![0], // Use port 0 to avoid conflicts Duration::from_secs(5), // Short timeout for test None, Some(TEST_CACHE_PASSPHRASE.to_string()), @@ -347,7 +347,7 @@ async fn test_u2m_refresh_updates_cache() { "test-client-id-cache", http_client, vec!["all-apis".to_string(), "offline_access".to_string()], - 8023, + vec![8023], Duration::from_secs(120), None, Some(TEST_CACHE_PASSPHRASE.to_string()), diff --git a/tests/v0_session_e2e.rs b/tests/v0_session_e2e.rs index 77af49bc..8291f4fc 100644 --- a/tests/v0_session_e2e.rs +++ b/tests/v0_session_e2e.rs @@ -123,7 +123,7 @@ async fn open_with_oauth_u2m_against_live_warehouse() { .http_path(host, http_path) .auth(AuthConfig::OAuthU2M { client_id: None, - redirect_port: None, + redirect_ports: None, scopes: None, token_url_override: None, callback_timeout: None, From 7b3e41697583dadd7d63cb6ddc0742cebd9bc1e9 Mon Sep 17 00:00:00 2001 From: "peco-engineer-bot[bot]" Date: Tue, 18 Aug 2026 01:58:34 +0000 Subject: [PATCH 04/19] ai: apply changes for #257 (1 review thread) Addresses: - #3800251761 at pyo3/src/auth.rs:272 Signed-off-by: peco-engineer-bot[bot] --- pyo3/src/auth.rs | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/pyo3/src/auth.rs b/pyo3/src/auth.rs index 0a8493d2..ff579efc 100644 --- a/pyo3/src/auth.rs +++ b/pyo3/src/auth.rs @@ -223,6 +223,18 @@ fn build_auth_config_inner( .to_owned(), ); } + // Both knobs set is ambiguous: downstream `redirect_ports` wins + // and `redirect_port` is silently dropped. Reject it up front + // (mirroring the degenerate-shape rejections above) so the + // caller doesn't set 9000 and get a range that never honors it. + if oauth.redirect_port.is_some() { + return Err( + "auth_type='oauth-u2m' set either redirect_port or redirect_ports, \ + not both (redirect_ports would take precedence and redirect_port \ + would be ignored)" + .to_owned(), + ); + } } // Default the U2M OAuth client to the Python connector's // own registered client (`databricks-sql-python`), NOT the @@ -515,6 +527,21 @@ mod tests { assert!(err.contains("non-zero"), "got: {err}"); } + #[test] + fn u2m_both_redirect_port_and_ports_rejected() { + let err = build_auth_config_inner( + "oauth-u2m", + None, + OAuthParams { + redirect_port: Some(9000), + redirect_ports: Some(vec![8020, 8021]), + ..Default::default() + }, + ) + .unwrap_err(); + assert!(err.contains("not both"), "got: {err}"); + } + #[test] fn u2m_explicit_client_id_overrides_default() { let cfg = build_auth_config_inner( From f5f88b5879ee7e2613a7de5f699302764efb9a29 Mon Sep 17 00:00:00 2001 From: "peco-engineer-bot[bot]" Date: Tue, 18 Aug 2026 02:04:20 +0000 Subject: [PATCH 05/19] ai: apply changes for #257 (1 review thread) Addresses: - #3800363399 at pyo3/src/auth.rs:54 Signed-off-by: peco-engineer-bot[bot] --- pyo3/src/auth.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pyo3/src/auth.rs b/pyo3/src/auth.rs index ff579efc..238cc75b 100644 --- a/pyo3/src/auth.rs +++ b/pyo3/src/auth.rs @@ -20,8 +20,8 @@ //! - `"oauth-m2m"` — OAuth 2.0 client-credentials (service principal): //! `client_id` + `client_secret`, optional `scopes` / `token_url`. //! - `"oauth-u2m"` — OAuth 2.0 authorization-code + PKCE browser flow: -//! optional `client_id` / `redirect_port` / `scopes` / `token_url` / -//! `oauth_callback_timeout_secs`. +//! optional `client_id` / `redirect_port` / `redirect_ports` / `scopes` / +//! `token_url` / `oauth_callback_timeout_secs`. //! //! OAuth is **kernel-owned**: the kernel acquires and refreshes tokens //! itself (OIDC discovery against the workspace host, transparent From 9b85bc4c5e9bdfa74e5fe270073c1d543041c5b3 Mon Sep 17 00:00:00 2001 From: "peco-engineer-bot[bot]" Date: Tue, 18 Aug 2026 02:11:39 +0000 Subject: [PATCH 06/19] ai: apply changes for #257 (1 review thread) Addresses: - #3800378252 at pyo3/src/auth.rs:55 Signed-off-by: peco-engineer-bot[bot] --- pyo3/src/auth.rs | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/pyo3/src/auth.rs b/pyo3/src/auth.rs index 238cc75b..a4c0efaa 100644 --- a/pyo3/src/auth.rs +++ b/pyo3/src/auth.rs @@ -52,9 +52,10 @@ pub(crate) struct OAuthParams { pub token_url: Option, pub redirect_port: Option, /// Candidate U2M redirect ports, tried in order (first free binds). - /// When set (non-empty) this takes precedence over `redirect_port` and - /// gives the busy-port fallback the Thrift connector has across its - /// registered range (`databricks-sql-python` → 8020‑8024). + /// Mutually exclusive with `redirect_port` — setting both is rejected + /// in [`build_auth_config`]. When set (non-empty) it gives the busy-port + /// fallback the Thrift connector has across its registered range + /// (`databricks-sql-python` → 8020‑8024). pub redirect_ports: Option>, pub callback_timeout_secs: Option, pub identity_federation_client_id: Option, @@ -278,11 +279,13 @@ fn build_auth_config_inner( None if !caller_set_client_id => Some(PYSQL_OAUTH_REDIRECT_PORT), None => None, }; - // Collapse the two Python knobs into the kernel's single - // `redirect_ports` list. An explicit `redirect_ports` (the - // connector's registered range, for busy-port fallback) wins; - // otherwise the single `redirect_port` (caller-supplied or the - // pinned databricks-sql-python default) becomes a one-element list. + // Collapse the two (mutually exclusive) Python knobs into the + // kernel's single `redirect_ports` list. At most one is set here + // (both-set is rejected above): an explicit `redirect_ports` (the + // connector's registered range, for busy-port fallback) passes + // through; otherwise the single `redirect_port` (caller-supplied or + // the pinned databricks-sql-python default) becomes a one-element + // list. let redirect_ports = oauth .redirect_ports .or_else(|| redirect_port.map(|p| vec![p])); From 652ccddba0cede08faa85204745751793ae20356 Mon Sep 17 00:00:00 2001 From: eric-wang-1990 Date: Mon, 17 Aug 2026 19:12:48 -0700 Subject: [PATCH 07/19] refactor(auth): drop redundant single-port knobs (review feedback) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Address review comments on PR #257: - pyo3: remove the singular `redirect_port` from OAuthParams and the Session.__new__ kwarg. It duplicated `redirect_ports` and created the "both set → which wins" ambiguity the review bot flagged. pyo3 now exposes only `redirect_ports`; a single port is `[port]`. The databricks-sql-python default-port pinning (8020 under the default client) now yields a one-element list, and the redirect_port=0 guard is subsumed by the existing empty/zero redirect_ports checks. - callback: remove CallbackServer::new (single port). It was dead after the U2M flow moved to new_in_range; the doc example and the six new(0) tests now use new_in_range(&[0]) (a one-element range is equivalent). No behavior change: a single port still resolves to exactly that port. Co-authored-by: Isaac Signed-off-by: eric-wang-1990 --- pyo3/src/auth.rs | 107 ++++++++++--------------------------- pyo3/src/session.rs | 5 +- src/auth/oauth/callback.rs | 46 +++------------- 3 files changed, 36 insertions(+), 122 deletions(-) diff --git a/pyo3/src/auth.rs b/pyo3/src/auth.rs index a4c0efaa..453fd745 100644 --- a/pyo3/src/auth.rs +++ b/pyo3/src/auth.rs @@ -20,8 +20,8 @@ //! - `"oauth-m2m"` — OAuth 2.0 client-credentials (service principal): //! `client_id` + `client_secret`, optional `scopes` / `token_url`. //! - `"oauth-u2m"` — OAuth 2.0 authorization-code + PKCE browser flow: -//! optional `client_id` / `redirect_port` / `redirect_ports` / `scopes` / -//! `token_url` / `oauth_callback_timeout_secs`. +//! optional `client_id` / `redirect_ports` / `scopes` / `token_url` / +//! `oauth_callback_timeout_secs`. //! //! OAuth is **kernel-owned**: the kernel acquires and refreshes tokens //! itself (OIDC discovery against the workspace host, transparent @@ -50,12 +50,12 @@ pub(crate) struct OAuthParams { pub client_secret: Option, pub scopes: Option>, pub token_url: Option, - pub redirect_port: Option, - /// Candidate U2M redirect ports, tried in order (first free binds). - /// Mutually exclusive with `redirect_port` — setting both is rejected - /// in [`build_auth_config`]. When set (non-empty) it gives the busy-port - /// fallback the Thrift connector has across its registered range - /// (`databricks-sql-python` → 8020‑8024). + /// Candidate U2M redirect ports, tried in order (first free binds). A + /// single fixed port is just a one-element list (`vec![port]`); a + /// multi-port list gives the busy-port fallback the Thrift connector has + /// across its registered range (`databricks-sql-python` → 8020‑8024). + /// `None`/empty → the databricks-sql-python default (8020) when the + /// default client is in use, else the kernel default. pub redirect_ports: Option>, pub callback_timeout_secs: Option, pub identity_federation_client_id: Option, @@ -173,14 +173,15 @@ fn build_auth_config_inner( "oauth-u2m" => { // Browser flow: every field is optional and `None` lets the // kernel apply its defaults (client_id "databricks-sql-connector", - // redirect_port 8030, scopes ["sql", "offline_access"], + // redirect port 8030, scopes ["sql", "offline_access"], // callback timeout 120s). But a *present-yet-degenerate* // value is a footgun the kernel can't distinguish from an // intentional setting, so reject those here: // - client_id="" would bypass the default and bind an // empty client id; - // - redirect_port=0 binds an OS-assigned ephemeral port, - // which can't match the IdP's static redirect_uri; + // - an empty redirect_ports list, or a 0 entry (which binds an + // OS-assigned ephemeral port that can't match the IdP's + // static redirect_uri); // - callback_timeout_secs=0 means "time out immediately", // not "wait forever" (a common cross-system confusion). if matches!(oauth.client_id.as_deref(), Some("")) { @@ -190,13 +191,6 @@ fn build_auth_config_inner( .to_owned(), ); } - if oauth.redirect_port == Some(0) { - return Err( - "auth_type='oauth-u2m' redirect_port must be non-zero when set \ - (a static port the IdP redirect_uri can match); omit it for the default" - .to_owned(), - ); - } if oauth.callback_timeout_secs == Some(0) { return Err( "auth_type='oauth-u2m' oauth_callback_timeout_secs must be > 0 when set \ @@ -204,16 +198,15 @@ fn build_auth_config_inner( .to_owned(), ); } - // `redirect_ports` (the busy-port-fallback range) is caller-supplied - // and takes precedence over `redirect_port` downstream. Reject the - // degenerate shapes for the same reason as `redirect_port=0`: an - // empty list carries no port, and a 0 entry binds an ephemeral port - // that can't match the IdP's static redirect_uri. + // `redirect_ports` is the ordered list of candidate callback ports + // (a single fixed port is just `[port]`). Reject the degenerate + // shapes: an empty list carries no port, and a 0 entry binds an + // ephemeral port that can't match the IdP's static redirect_uri. if let Some(ports) = oauth.redirect_ports.as_deref() { if ports.is_empty() { return Err( "auth_type='oauth-u2m' redirect_ports must be non-empty when set; \ - omit it to use redirect_port or the default" + omit it for the default" .to_owned(), ); } @@ -224,18 +217,6 @@ fn build_auth_config_inner( .to_owned(), ); } - // Both knobs set is ambiguous: downstream `redirect_ports` wins - // and `redirect_port` is silently dropped. Reject it up front - // (mirroring the degenerate-shape rejections above) so the - // caller doesn't set 9000 and get a range that never honors it. - if oauth.redirect_port.is_some() { - return Err( - "auth_type='oauth-u2m' set either redirect_port or redirect_ports, \ - not both (redirect_ports would take precedence and redirect_port \ - would be ignored)" - .to_owned(), - ); - } } // Default the U2M OAuth client to the Python connector's // own registered client (`databricks-sql-python`), NOT the @@ -273,22 +254,17 @@ fn build_auth_config_inner( }; // Pin the databricks-sql-python app's own redirect port when // relying on the default client_id — the kernel default (8030) is - // for the databricks-sql-connector app and would mismatch. - let redirect_port = match oauth.redirect_port { - Some(p) => Some(p), - None if !caller_set_client_id => Some(PYSQL_OAUTH_REDIRECT_PORT), + // for the databricks-sql-connector app and would mismatch. An + // explicit caller list (e.g. the connector's registered range for + // busy-port fallback) is used as-is; otherwise, under the default + // client, forward the pinned databricks-sql-python port as a + // one-element list. A custom client_id with no ports defers to the + // kernel (None) — that app owns its own redirect port. + let redirect_ports = match oauth.redirect_ports { + Some(ports) => Some(ports), + None if !caller_set_client_id => Some(vec![PYSQL_OAUTH_REDIRECT_PORT]), None => None, }; - // Collapse the two (mutually exclusive) Python knobs into the - // kernel's single `redirect_ports` list. At most one is set here - // (both-set is rejected above): an explicit `redirect_ports` (the - // connector's registered range, for busy-port fallback) passes - // through; otherwise the single `redirect_port` (caller-supplied or - // the pinned databricks-sql-python default) becomes a one-element - // list. - let redirect_ports = oauth - .redirect_ports - .or_else(|| redirect_port.map(|p| vec![p])); Ok(AuthConfig::oauth_u2m( client_id, redirect_ports, @@ -530,21 +506,6 @@ mod tests { assert!(err.contains("non-zero"), "got: {err}"); } - #[test] - fn u2m_both_redirect_port_and_ports_rejected() { - let err = build_auth_config_inner( - "oauth-u2m", - None, - OAuthParams { - redirect_port: Some(9000), - redirect_ports: Some(vec![8020, 8021]), - ..Default::default() - }, - ) - .unwrap_err(); - assert!(err.contains("not both"), "got: {err}"); - } - #[test] fn u2m_explicit_client_id_overrides_default() { let cfg = build_auth_config_inner( @@ -605,7 +566,7 @@ mod tests { "oauth-u2m", None, OAuthParams { - redirect_port: Some(9999), + redirect_ports: Some(vec![9999]), callback_timeout_secs: Some(300), identity_federation_client_id: Some("federation-client".into()), ..Default::default() @@ -647,20 +608,6 @@ mod tests { assert!(err.contains("client_id must be non-empty"), "{err}"); } - #[test] - fn u2m_rejects_zero_redirect_port() { - let err = build_auth_config_inner( - "oauth-u2m", - None, - OAuthParams { - redirect_port: Some(0), - ..Default::default() - }, - ) - .unwrap_err(); - assert!(err.contains("redirect_port must be non-zero"), "{err}"); - } - #[test] fn u2m_rejects_zero_callback_timeout() { let err = build_auth_config_inner( diff --git a/pyo3/src/session.rs b/pyo3/src/session.rs index a778f11a..c5ce6c59 100644 --- a/pyo3/src/session.rs +++ b/pyo3/src/session.rs @@ -67,7 +67,7 @@ impl Session { /// `client_id` + `client_secret` (optional `oauth_scopes`, /// `token_url`). /// - `"oauth-u2m"`: browser authorization-code + PKCE flow - /// (optional `client_id`, `redirect_port`, `oauth_scopes`, + /// (optional `client_id`, `redirect_ports`, `oauth_scopes`, /// `token_url`, `oauth_callback_timeout_secs`). /// /// OAuth is kernel-owned: the kernel acquires and transparently @@ -120,7 +120,6 @@ impl Session { client_secret=None, oauth_scopes=None, token_url=None, - redirect_port=None, redirect_ports=None, oauth_callback_timeout_secs=None, identity_federation_client_id=None, @@ -151,7 +150,6 @@ impl Session { client_secret: Option, oauth_scopes: Option>, token_url: Option, - redirect_port: Option, redirect_ports: Option>, oauth_callback_timeout_secs: Option, identity_federation_client_id: Option, @@ -199,7 +197,6 @@ impl Session { client_secret, scopes: oauth_scopes, token_url, - redirect_port, redirect_ports, callback_timeout_secs: oauth_callback_timeout_secs, identity_federation_client_id, diff --git a/src/auth/oauth/callback.rs b/src/auth/oauth/callback.rs index 27bb68c6..011ebe1e 100644 --- a/src/auth/oauth/callback.rs +++ b/src/auth/oauth/callback.rs @@ -74,8 +74,8 @@ enum CallbackResult { /// use std::time::Duration; /// /// # async fn example() -> databricks_sql_kernel::Result<()> { -/// // Start callback server on port 8030 -/// let server = CallbackServer::new(8030).await?; +/// // Start callback server, binding the first free candidate port. +/// let server = CallbackServer::new_in_range(&[8030]).await?; /// let redirect_uri = server.redirect_uri(); /// println!("Redirect URI: {}", redirect_uri); /// @@ -106,36 +106,6 @@ impl Drop for CallbackServer { } impl CallbackServer { - /// Creates a new callback server listening on the specified port. - /// - /// The server binds to `127.0.0.1:{port}` and is ready to receive one callback. - /// - /// # Arguments - /// - /// * `port` - Port number to listen on (typically 8030) - /// - /// # Returns - /// - /// A configured server ready to wait for callbacks, or an error if: - /// - The port is already in use - /// - Permission denied to bind to the port - /// - Invalid port number - /// - /// # Errors - /// - /// Returns `io()` error if the server cannot bind to the specified port. - pub async fn new(port: u16) -> Result { - let listener = Self::bind(port).await.map_err(|e| { - Error::io() - .message(format!( - "Failed to bind callback server to 127.0.0.1:{}: {}", - port, e - )) - .context("OAuth callback server") - })?; - Self::from_listener(listener) - } - /// Creates a callback server on the first bindable port in `ports`. /// /// Tries each candidate port in order and keeps the first one that binds, @@ -490,7 +460,7 @@ mod tests { #[tokio::test] async fn test_callback_captures_code() { // Start callback server - let server = CallbackServer::new(0) + let server = CallbackServer::new_in_range(&[0]) .await .expect("Failed to create server"); let port = server.port; @@ -533,7 +503,7 @@ mod tests { #[tokio::test] async fn test_callback_validates_state() { - let server = CallbackServer::new(0) + let server = CallbackServer::new_in_range(&[0]) .await .expect("Failed to create server"); let port = server.port; @@ -578,7 +548,7 @@ mod tests { #[tokio::test] async fn test_callback_timeout() { - let server = CallbackServer::new(0) + let server = CallbackServer::new_in_range(&[0]) .await .expect("Failed to create server"); @@ -598,7 +568,7 @@ mod tests { #[tokio::test] async fn test_callback_missing_code() { - let server = CallbackServer::new(0) + let server = CallbackServer::new_in_range(&[0]) .await .expect("Failed to create server"); let port = server.port; @@ -629,7 +599,7 @@ mod tests { #[tokio::test] async fn test_callback_auth_error() { - let server = CallbackServer::new(0) + let server = CallbackServer::new_in_range(&[0]) .await .expect("Failed to create server"); let port = server.port; @@ -692,7 +662,7 @@ mod tests { #[tokio::test] async fn test_redirect_uri_format() { // Use port 0 to let the OS assign an available port, avoiding conflicts - let server = CallbackServer::new(0) + let server = CallbackServer::new_in_range(&[0]) .await .expect("Failed to create server"); let uri = server.redirect_uri(); From 4edb6c3f824ddb4997d845359a0e2232f5d7285a Mon Sep 17 00:00:00 2001 From: eric-wang-1990 Date: Mon, 17 Aug 2026 19:17:57 -0700 Subject: [PATCH 08/19] test(auth): add live U2M busy-port fallback E2E test (PECOBLR-4144) Interactive #[ignore] test proving the fix end-to-end: occupies port 8020, opens a U2M session as databricks-sql-python with redirect_ports=[8020, 8025], and expects the browser to redirect to http://localhost:8025 (the callback server skips the busy 8020 and binds 8025). Before this change the single-port API would have failed when 8020 was occupied. Gated by DATABRICKS_RUN_U2M=1 like the existing U2M E2E test, so CI without a browser/credentials skips it. Co-authored-by: Isaac Signed-off-by: eric-wang-1990 --- tests/v0_session_e2e.rs | 53 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) diff --git a/tests/v0_session_e2e.rs b/tests/v0_session_e2e.rs index 8291f4fc..0a793d33 100644 --- a/tests/v0_session_e2e.rs +++ b/tests/v0_session_e2e.rs @@ -144,6 +144,59 @@ async fn open_with_oauth_u2m_against_live_warehouse() { session.close().await.expect("close()"); } +// PECOBLR-4144: prove the redirect-port busy-port fallback end-to-end. +// +// The databricks-sql-python OAuth app registers multiple localhost redirect +// URIs (e.g. http://localhost:8020 and http://localhost:8025). We occupy the +// first (8020) so the kernel's `new_in_range` must skip it and bind the second +// (8025); the browser then redirects to http://localhost:8025 and the flow +// still completes. Before this change the kernel took a single port and would +// have failed outright when 8020 was busy. +// +// Manual/interactive: opens a browser. Run with: +// DATABRICKS_HOST=... DATABRICKS_HTTP_PATH=... DATABRICKS_RUN_U2M=1 \ +// ~/.cargo/bin/cargo test --test v0_session_e2e -- --ignored \ +// open_with_oauth_u2m_falls_back_past_busy_port --nocapture +#[tokio::test(flavor = "multi_thread")] +#[ignore] +async fn open_with_oauth_u2m_falls_back_past_busy_port() { + if env_var("DATABRICKS_RUN_U2M").is_none() { + eprintln!("skipping U2M fallback test — set DATABRICKS_RUN_U2M=1 to run (opens browser)"); + return; + } + let (host, http_path) = require_host_and_path(); + + // Occupy 8020 for the duration of the test so the callback server cannot + // bind it and must fall back to the next candidate (8025). A plain std + // listener on 127.0.0.1:8020 is enough to trigger AddrInUse. + let _occupied = std::net::TcpListener::bind("127.0.0.1:8020") + .expect("failed to occupy port 8020 for the fallback test"); + eprintln!("port 8020 occupied; expecting the browser to redirect to http://localhost:8025"); + + let session = Session::builder() + .http_path(host, http_path) + .auth(AuthConfig::OAuthU2M { + // The databricks-sql-python app (both 8020 and 8025 registered). + client_id: Some("databricks-sql-python".to_string()), + redirect_ports: Some(vec![8020, 8025]), + scopes: Some(vec!["sql".to_string(), "offline_access".to_string()]), + token_url_override: None, + callback_timeout: None, + // Disable the on-disk cache so the browser flow actually runs. + token_cache: Some(databricks_sql_kernel::TokenCacheConfig { + enabled: false, + passphrase: None, + }), + identity_federation_client_id: None, + }) + .open() + .await + .expect("Session::open should succeed via the 8025 fallback"); + + assert!(!session.session_id().is_empty()); + session.close().await.expect("close()"); +} + #[tokio::test] #[ignore] async fn open_drop_does_not_panic() { From ba96295f817bb087de0c72b2ba42e80b86b469c4 Mon Sep 17 00:00:00 2001 From: "peco-engineer-bot[bot]" Date: Tue, 18 Aug 2026 02:29:44 +0000 Subject: [PATCH 09/19] ai: apply changes for #257 (1 review thread) Addresses: - #3800442505 at pyo3/src/session.rs:123 Signed-off-by: peco-engineer-bot[bot] --- pyo3/src/session.rs | 66 +++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 64 insertions(+), 2 deletions(-) diff --git a/pyo3/src/session.rs b/pyo3/src/session.rs index c5ce6c59..c79cb7dd 100644 --- a/pyo3/src/session.rs +++ b/pyo3/src/session.rs @@ -67,8 +67,8 @@ impl Session { /// `client_id` + `client_secret` (optional `oauth_scopes`, /// `token_url`). /// - `"oauth-u2m"`: browser authorization-code + PKCE flow - /// (optional `client_id`, `redirect_ports`, `oauth_scopes`, - /// `token_url`, `oauth_callback_timeout_secs`). + /// (optional `client_id`, `redirect_port` / `redirect_ports`, + /// `oauth_scopes`, `token_url`, `oauth_callback_timeout_secs`). /// /// OAuth is kernel-owned: the kernel acquires and transparently /// refreshes tokens itself. @@ -120,6 +120,7 @@ impl Session { client_secret=None, oauth_scopes=None, token_url=None, + redirect_port=None, redirect_ports=None, oauth_callback_timeout_secs=None, identity_federation_client_id=None, @@ -150,6 +151,7 @@ impl Session { client_secret: Option, oauth_scopes: Option>, token_url: Option, + redirect_port: Option, redirect_ports: Option>, oauth_callback_timeout_secs: Option, identity_federation_client_id: Option, @@ -192,6 +194,12 @@ impl Session { )); } }; + // `redirect_port` is a single-port convenience kwarg kept for + // backward compatibility with existing callers (e.g. the connector's + // `Session(..., redirect_port=8020)`); `redirect_ports` is the + // multi-port list. Fold the scalar into a one-element list. + let redirect_ports = fold_redirect_ports(redirect_port, redirect_ports) + .map_err(pyo3::exceptions::PyValueError::new_err)?; let oauth = OAuthParams { client_id, client_secret, @@ -411,6 +419,28 @@ impl Session { } } +/// Reconcile the single-port `redirect_port` kwarg with the multi-port +/// `redirect_ports` list. +/// +/// `redirect_port` is kept for backward compatibility with existing +/// callers (e.g. the connector's `Session(..., redirect_port=8020)`) and +/// is folded into a one-element list. `redirect_ports` is the multi-port +/// form. Passing BOTH is ambiguous, so it is rejected rather than silently +/// picking one. Extracted as a free fn so it is unit-testable without an +/// initialized Python interpreter. +fn fold_redirect_ports( + redirect_port: Option, + redirect_ports: Option>, +) -> Result>, &'static str> { + match (redirect_port, redirect_ports) { + (Some(_), Some(_)) => { + Err("pass either redirect_port (single) or redirect_ports (list), not both") + } + (Some(p), None) => Ok(Some(vec![p])), + (None, ports) => Ok(ports), + } +} + #[cfg(test)] mod send_sync_tests { use super::*; @@ -421,3 +451,35 @@ mod send_sync_tests { assert_send_sync::(); } } + +#[cfg(test)] +mod redirect_port_tests { + use super::*; + + #[test] + fn single_redirect_port_folds_into_list() { + assert_eq!( + fold_redirect_ports(Some(8020), None).unwrap(), + Some(vec![8020]) + ); + } + + #[test] + fn redirect_ports_list_passes_through() { + assert_eq!( + fold_redirect_ports(None, Some(vec![8020, 8021])).unwrap(), + Some(vec![8020, 8021]) + ); + } + + #[test] + fn neither_set_is_none() { + assert_eq!(fold_redirect_ports(None, None).unwrap(), None); + } + + #[test] + fn both_set_is_rejected() { + let err = fold_redirect_ports(Some(8020), Some(vec![8021])).unwrap_err(); + assert!(err.contains("not both"), "unexpected error: {err}"); + } +} From aaf60ec8f3ded3863e5459a0fcb289c3f692cb9f Mon Sep 17 00:00:00 2001 From: "peco-engineer-bot[bot]" Date: Tue, 18 Aug 2026 02:36:43 +0000 Subject: [PATCH 10/19] ai: apply changes for #257 (1 review thread) Addresses: - #3800506002 at src/config.rs:339 Signed-off-by: peco-engineer-bot[bot] --- pyo3/src/auth.rs | 3 ++- src/auth/oauth/callback.rs | 3 ++- src/config.rs | 5 +++-- 3 files changed, 7 insertions(+), 4 deletions(-) diff --git a/pyo3/src/auth.rs b/pyo3/src/auth.rs index 453fd745..f3401842 100644 --- a/pyo3/src/auth.rs +++ b/pyo3/src/auth.rs @@ -53,7 +53,8 @@ pub(crate) struct OAuthParams { /// Candidate U2M redirect ports, tried in order (first free binds). A /// single fixed port is just a one-element list (`vec![port]`); a /// multi-port list gives the busy-port fallback the Thrift connector has - /// across its registered range (`databricks-sql-python` → 8020‑8024). + /// across its registered ports (`databricks-sql-python` → the discrete + /// set `8020`/`8025`, not a contiguous range). /// `None`/empty → the databricks-sql-python default (8020) when the /// default client is in use, else the kernel default. pub redirect_ports: Option>, diff --git a/src/auth/oauth/callback.rs b/src/auth/oauth/callback.rs index 011ebe1e..8d0e7ad8 100644 --- a/src/auth/oauth/callback.rs +++ b/src/auth/oauth/callback.rs @@ -111,7 +111,8 @@ impl CallbackServer { /// Tries each candidate port in order and keeps the first one that binds, /// skipping ports already in use (`AddrInUse`) — the same busy-port /// tolerance the Thrift connector's `OAuthManager` provides by iterating its - /// registered redirect-URI range (e.g. `databricks-sql-python` → 8020‑8024). + /// registered redirect URIs (e.g. `databricks-sql-python` → the discrete + /// set `8020`/`8025`, not a contiguous range). /// The kernel's single-port U2M API otherwise fails outright when its one /// port is occupied by a stale listener or a second concurrent connection. /// diff --git a/src/config.rs b/src/config.rs index 5b060262..cd4dff40 100644 --- a/src/config.rs +++ b/src/config.rs @@ -335,8 +335,9 @@ pub enum AuthConfig { /// which is how the single-port bindings (C ABI, N-API) forward /// their one port. Every entry must be a registered redirect URI /// of the OAuth app; a multi-port list mirrors the Thrift - /// connector's registered range (`databricks-sql-python` → - /// 8020‑8024) for busy-port fallback. + /// connector's registered redirect ports (`databricks-sql-python` + /// → the discrete set `8020`/`8025`, not a contiguous range) for + /// busy-port fallback. redirect_ports: Option>, /// OAuth scopes. `None` → `["sql", "offline_access"]` /// (the `offline_access` scope is required to receive a From a31df85d3cd080ededcc6d008ebc43dca76d0930 Mon Sep 17 00:00:00 2001 From: eric-wang-1990 Date: Mon, 17 Aug 2026 20:21:58 -0700 Subject: [PATCH 11/19] refactor(auth): new_first_free rename + drop pyo3 redirect_port kwarg MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Consolidated cleanup on top of the bot's latest #257 state, per maintainer decisions: - Rename CallbackServer::new_in_range -> new_first_free (it takes a discrete candidate list, not a contiguous range); updates the u2m call site and callback tests. - Drop the pyo3 redirect_port kwarg the bot re-added; pyo3 exposes only redirect_ports (a single port is [port]). Removes fold_redirect_ports and its tests. - E2E fallback test comment: state the real reason the fallback works — Databricks in-house OAuth ignores the loopback redirect port per RFC 8252 (any localhost port is accepted), not that specific ports are "registered". (Confirmed live + server-side; PECOBLR-4154 closed not-a-bug.) Co-authored-by: Isaac Signed-off-by: eric-wang-1990 --- pyo3/src/session.rs | 66 ++------------------------------------ src/auth/oauth/callback.rs | 34 ++++++++++---------- src/auth/oauth/u2m.rs | 2 +- tests/v0_session_e2e.rs | 16 +++++---- 4 files changed, 29 insertions(+), 89 deletions(-) diff --git a/pyo3/src/session.rs b/pyo3/src/session.rs index c79cb7dd..c5ce6c59 100644 --- a/pyo3/src/session.rs +++ b/pyo3/src/session.rs @@ -67,8 +67,8 @@ impl Session { /// `client_id` + `client_secret` (optional `oauth_scopes`, /// `token_url`). /// - `"oauth-u2m"`: browser authorization-code + PKCE flow - /// (optional `client_id`, `redirect_port` / `redirect_ports`, - /// `oauth_scopes`, `token_url`, `oauth_callback_timeout_secs`). + /// (optional `client_id`, `redirect_ports`, `oauth_scopes`, + /// `token_url`, `oauth_callback_timeout_secs`). /// /// OAuth is kernel-owned: the kernel acquires and transparently /// refreshes tokens itself. @@ -120,7 +120,6 @@ impl Session { client_secret=None, oauth_scopes=None, token_url=None, - redirect_port=None, redirect_ports=None, oauth_callback_timeout_secs=None, identity_federation_client_id=None, @@ -151,7 +150,6 @@ impl Session { client_secret: Option, oauth_scopes: Option>, token_url: Option, - redirect_port: Option, redirect_ports: Option>, oauth_callback_timeout_secs: Option, identity_federation_client_id: Option, @@ -194,12 +192,6 @@ impl Session { )); } }; - // `redirect_port` is a single-port convenience kwarg kept for - // backward compatibility with existing callers (e.g. the connector's - // `Session(..., redirect_port=8020)`); `redirect_ports` is the - // multi-port list. Fold the scalar into a one-element list. - let redirect_ports = fold_redirect_ports(redirect_port, redirect_ports) - .map_err(pyo3::exceptions::PyValueError::new_err)?; let oauth = OAuthParams { client_id, client_secret, @@ -419,28 +411,6 @@ impl Session { } } -/// Reconcile the single-port `redirect_port` kwarg with the multi-port -/// `redirect_ports` list. -/// -/// `redirect_port` is kept for backward compatibility with existing -/// callers (e.g. the connector's `Session(..., redirect_port=8020)`) and -/// is folded into a one-element list. `redirect_ports` is the multi-port -/// form. Passing BOTH is ambiguous, so it is rejected rather than silently -/// picking one. Extracted as a free fn so it is unit-testable without an -/// initialized Python interpreter. -fn fold_redirect_ports( - redirect_port: Option, - redirect_ports: Option>, -) -> Result>, &'static str> { - match (redirect_port, redirect_ports) { - (Some(_), Some(_)) => { - Err("pass either redirect_port (single) or redirect_ports (list), not both") - } - (Some(p), None) => Ok(Some(vec![p])), - (None, ports) => Ok(ports), - } -} - #[cfg(test)] mod send_sync_tests { use super::*; @@ -451,35 +421,3 @@ mod send_sync_tests { assert_send_sync::(); } } - -#[cfg(test)] -mod redirect_port_tests { - use super::*; - - #[test] - fn single_redirect_port_folds_into_list() { - assert_eq!( - fold_redirect_ports(Some(8020), None).unwrap(), - Some(vec![8020]) - ); - } - - #[test] - fn redirect_ports_list_passes_through() { - assert_eq!( - fold_redirect_ports(None, Some(vec![8020, 8021])).unwrap(), - Some(vec![8020, 8021]) - ); - } - - #[test] - fn neither_set_is_none() { - assert_eq!(fold_redirect_ports(None, None).unwrap(), None); - } - - #[test] - fn both_set_is_rejected() { - let err = fold_redirect_ports(Some(8020), Some(vec![8021])).unwrap_err(); - assert!(err.contains("not both"), "unexpected error: {err}"); - } -} diff --git a/src/auth/oauth/callback.rs b/src/auth/oauth/callback.rs index 8d0e7ad8..2ad9630c 100644 --- a/src/auth/oauth/callback.rs +++ b/src/auth/oauth/callback.rs @@ -75,7 +75,7 @@ enum CallbackResult { /// /// # async fn example() -> databricks_sql_kernel::Result<()> { /// // Start callback server, binding the first free candidate port. -/// let server = CallbackServer::new_in_range(&[8030]).await?; +/// let server = CallbackServer::new_first_free(&[8030]).await?; /// let redirect_uri = server.redirect_uri(); /// println!("Redirect URI: {}", redirect_uri); /// @@ -130,10 +130,10 @@ impl CallbackServer { /// - `invalid_argument` if `ports` is empty. /// - `io()` if a non-`AddrInUse` bind error occurs (returned immediately, /// not retried), or if every candidate port is already in use. - pub async fn new_in_range(ports: &[u16]) -> Result { + pub async fn new_first_free(ports: &[u16]) -> Result { if ports.is_empty() { return Err(Error::invalid_argument() - .message("CallbackServer::new_in_range requires at least one candidate port")); + .message("CallbackServer::new_first_free requires at least one candidate port")); } let mut last_in_use: Option = None; @@ -461,7 +461,7 @@ mod tests { #[tokio::test] async fn test_callback_captures_code() { // Start callback server - let server = CallbackServer::new_in_range(&[0]) + let server = CallbackServer::new_first_free(&[0]) .await .expect("Failed to create server"); let port = server.port; @@ -504,7 +504,7 @@ mod tests { #[tokio::test] async fn test_callback_validates_state() { - let server = CallbackServer::new_in_range(&[0]) + let server = CallbackServer::new_first_free(&[0]) .await .expect("Failed to create server"); let port = server.port; @@ -549,7 +549,7 @@ mod tests { #[tokio::test] async fn test_callback_timeout() { - let server = CallbackServer::new_in_range(&[0]) + let server = CallbackServer::new_first_free(&[0]) .await .expect("Failed to create server"); @@ -569,7 +569,7 @@ mod tests { #[tokio::test] async fn test_callback_missing_code() { - let server = CallbackServer::new_in_range(&[0]) + let server = CallbackServer::new_first_free(&[0]) .await .expect("Failed to create server"); let port = server.port; @@ -600,7 +600,7 @@ mod tests { #[tokio::test] async fn test_callback_auth_error() { - let server = CallbackServer::new_in_range(&[0]) + let server = CallbackServer::new_first_free(&[0]) .await .expect("Failed to create server"); let port = server.port; @@ -663,7 +663,7 @@ mod tests { #[tokio::test] async fn test_redirect_uri_format() { // Use port 0 to let the OS assign an available port, avoiding conflicts - let server = CallbackServer::new_in_range(&[0]) + let server = CallbackServer::new_first_free(&[0]) .await .expect("Failed to create server"); let uri = server.redirect_uri(); @@ -684,15 +684,15 @@ mod tests { } #[tokio::test] - async fn test_new_in_range_empty_is_error() { - let result = CallbackServer::new_in_range(&[]).await; + async fn test_new_first_free_empty_is_error() { + let result = CallbackServer::new_first_free(&[]).await; assert!(result.is_err(), "empty port list should be rejected"); } #[tokio::test] - async fn test_new_in_range_single_port_binds() { + async fn test_new_first_free_single_port_binds() { // A one-element range behaves like new(0): binds an OS-assigned port. - let server = CallbackServer::new_in_range(&[0]) + let server = CallbackServer::new_first_free(&[0]) .await .expect("should bind the single candidate port"); assert!( @@ -704,7 +704,7 @@ mod tests { } #[tokio::test] - async fn test_new_in_range_skips_busy_port() { + async fn test_new_first_free_skips_busy_port() { // Occupy a port, then offer it as the first candidate followed by 0 // (OS-assigned, always bindable). The server must skip the busy port // and bind the next candidate instead. @@ -713,7 +713,7 @@ mod tests { .expect("failed to occupy a port"); let busy_port = occupied.local_addr().unwrap().port(); - let server = CallbackServer::new_in_range(&[busy_port, 0]) + let server = CallbackServer::new_first_free(&[busy_port, 0]) .await .expect("should fall back past the busy port"); @@ -731,7 +731,7 @@ mod tests { } #[tokio::test] - async fn test_new_in_range_all_busy_is_error() { + async fn test_new_first_free_all_busy_is_error() { // Occupy two ports and offer only those two — all candidates are busy. let l1 = TcpListener::bind("127.0.0.1:0").await.unwrap(); let l2 = TcpListener::bind("127.0.0.1:0").await.unwrap(); @@ -739,7 +739,7 @@ mod tests { let p2 = l2.local_addr().unwrap().port(); // Avoid unwrap_err(): CallbackServer (the Ok type) is not Debug. - let msg = match CallbackServer::new_in_range(&[p1, p2]).await { + let msg = match CallbackServer::new_first_free(&[p1, p2]).await { Ok(_) => panic!("all candidate ports busy should be an error"), Err(e) => format!("{:?}", e), }; diff --git a/src/auth/oauth/u2m.rs b/src/auth/oauth/u2m.rs index 2bf5871a..5a27d3b3 100644 --- a/src/auth/oauth/u2m.rs +++ b/src/auth/oauth/u2m.rs @@ -481,7 +481,7 @@ impl AuthProvider for AuthorizationCodeProvider { // Start callback server, binding the first free candidate // port (busy-port fallback across the registered range). - let callback_server = CallbackServer::new_in_range(&callback_ports).await?; + let callback_server = CallbackServer::new_first_free(&callback_ports).await?; let redirect_uri = callback_server.redirect_uri(); // Build OAuth client diff --git a/tests/v0_session_e2e.rs b/tests/v0_session_e2e.rs index 0a793d33..26489b05 100644 --- a/tests/v0_session_e2e.rs +++ b/tests/v0_session_e2e.rs @@ -146,12 +146,14 @@ async fn open_with_oauth_u2m_against_live_warehouse() { // PECOBLR-4144: prove the redirect-port busy-port fallback end-to-end. // -// The databricks-sql-python OAuth app registers multiple localhost redirect -// URIs (e.g. http://localhost:8020 and http://localhost:8025). We occupy the -// first (8020) so the kernel's `new_in_range` must skip it and bind the second -// (8025); the browser then redirects to http://localhost:8025 and the flow -// still completes. Before this change the kernel took a single port and would -// have failed outright when 8020 was busy. +// Databricks in-house OAuth accepts any loopback redirect port for the +// databricks-sql-python client — it drops the port from `http://localhost` +// redirect URIs before comparison, per RFC 8252 — so binding a different port +// than the first candidate still completes the flow. We occupy 8020 so the +// kernel's `new_first_free` must skip it and bind the next candidate (8025); +// the browser then redirects to http://localhost:8025 and the flow still +// completes. Before this change the kernel took a single port and would have +// failed outright when 8020 was busy. // // Manual/interactive: opens a browser. Run with: // DATABRICKS_HOST=... DATABRICKS_HTTP_PATH=... DATABRICKS_RUN_U2M=1 \ @@ -176,7 +178,7 @@ async fn open_with_oauth_u2m_falls_back_past_busy_port() { let session = Session::builder() .http_path(host, http_path) .auth(AuthConfig::OAuthU2M { - // The databricks-sql-python app (both 8020 and 8025 registered). + // databricks-sql-python; any loopback port is accepted (RFC 8252). client_id: Some("databricks-sql-python".to_string()), redirect_ports: Some(vec![8020, 8025]), scopes: Some(vec!["sql".to_string(), "offline_access".to_string()]), From 23c856634720cd953ef9e37f7c7a7a4d966ffe66 Mon Sep 17 00:00:00 2001 From: "peco-engineer-bot[bot]" Date: Tue, 18 Aug 2026 04:35:53 +0000 Subject: [PATCH 12/19] ai: apply changes for #257 (1 review thread) Addresses: - #3800804591 at src/config.rs:337 Signed-off-by: peco-engineer-bot[bot] --- CONNECTION_PARAMETERS.md | 2 +- src/config.rs | 10 +++++----- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/CONNECTION_PARAMETERS.md b/CONNECTION_PARAMETERS.md index 6abcec12..ad0183c8 100644 --- a/CONNECTION_PARAMETERS.md +++ b/CONNECTION_PARAMETERS.md @@ -56,7 +56,7 @@ An enum; pick one variant. Use the validating constructors | Field | Description | Default | |-------|-------------|---------| | `client_id` | OAuth client id. | `"databricks-sql-connector"` | -| `redirect_port` | Localhost port for the OAuth callback listener. The default app's redirect URI is registered for `http://localhost:8030`. | `8030` | +| `redirect_ports` | Ordered candidate localhost ports for the OAuth callback listener; the first free port is bound (busy-port fallback). `None`/empty selects the default. Each port must be a registered redirect URI of the OAuth app. The default app's redirect URI is registered for `http://localhost:8030`. | `[8030]` | | `scopes` | OAuth scopes. `offline_access` is required to receive a refresh token (cached and refreshed transparently). | `["sql", "offline_access"]` | | `token_url_override` | Token endpoint override. | OIDC discovery | | `callback_timeout` | How long to wait for the user to complete the browser flow. | `120s` | diff --git a/src/config.rs b/src/config.rs index cd4dff40..da13fd90 100644 --- a/src/config.rs +++ b/src/config.rs @@ -290,7 +290,7 @@ impl TokenCacheConfig { /// Optional fields default to sensible values when set to `None`: /// - OAuth scopes default to `["all-apis"]` for M2M and /// `["sql", "offline_access"]` for U2M. -/// - U2M `redirect_port` defaults to `8030`. +/// - U2M `redirect_ports` defaults to `[8030]`. /// - U2M `client_id` defaults to `"databricks-sql-connector"`. /// - `token_url_override` defaults to OIDC discovery against the /// workspace host. @@ -320,10 +320,10 @@ pub enum AuthConfig { }, /// OAuth 2.0 user-to-machine (authorization code + PKCE, browser - /// flow). The kernel spins up a localhost listener on - /// `redirect_port`, opens the user's browser to the workspace's - /// authorize endpoint, and exchanges the returned code for a - /// token. + /// flow). The kernel spins up a localhost listener on the first + /// free `redirect_ports` candidate, opens the user's browser to + /// the workspace's authorize endpoint, and exchanges the returned + /// code for a token. OAuthU2M { /// OAuth client ID. `None` → `"databricks-sql-connector"` (the /// default OAuth app, shared by the Node and Go drivers). From 9c3f71754ebdbc78d0553b1da9979fc245f43174 Mon Sep 17 00:00:00 2001 From: "peco-engineer-bot[bot]" Date: Tue, 18 Aug 2026 04:41:32 +0000 Subject: [PATCH 13/19] ai: apply changes for #257 (1 review thread) Addresses: - #3801068476 at pyo3/src/auth.rs:59 Signed-off-by: peco-engineer-bot[bot] --- pyo3/src/auth.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/pyo3/src/auth.rs b/pyo3/src/auth.rs index f3401842..d2140789 100644 --- a/pyo3/src/auth.rs +++ b/pyo3/src/auth.rs @@ -55,8 +55,10 @@ pub(crate) struct OAuthParams { /// multi-port list gives the busy-port fallback the Thrift connector has /// across its registered ports (`databricks-sql-python` → the discrete /// set `8020`/`8025`, not a contiguous range). - /// `None`/empty → the databricks-sql-python default (8020) when the - /// default client is in use, else the kernel default. + /// `None` → the databricks-sql-python default (8020) when the + /// default client is in use, else the kernel default. At the pyo3 + /// boundary an explicit *empty* list is rejected (see + /// [`build_auth_config`]), not defaulted. pub redirect_ports: Option>, pub callback_timeout_secs: Option, pub identity_federation_client_id: Option, From cdea913c70a1a5e2f8f0c86f23fd9f44f003fa83 Mon Sep 17 00:00:00 2001 From: "peco-engineer-bot[bot]" Date: Tue, 18 Aug 2026 04:50:21 +0000 Subject: [PATCH 14/19] ai: apply changes for #257 (1 review thread) Addresses: - #3801088886 at napi/src/database.rs:373 Signed-off-by: peco-engineer-bot[bot] --- napi/src/database.rs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/napi/src/database.rs b/napi/src/database.rs index 4d025c6c..37d07ede 100644 --- a/napi/src/database.rs +++ b/napi/src/database.rs @@ -370,7 +370,13 @@ fn build_auth_config(options: &ConnectionOptions) -> napi::Result { options.oauth_client_id.clone(), // Node exposes a single redirect port; forward it as a // one-element candidate list (kernel binds the first free one). - options.oauth_redirect_port.map(|p| vec![p]), + // A `0` port would bind an OS-assigned ephemeral port that can + // never match the IdP's static redirect_uri, so map `0 -> None` + // to fall back to the kernel default (matches C ABI + pyo3). + options + .oauth_redirect_port + .filter(|&p| p != 0) + .map(|p| vec![p]), options.oauth_scopes.clone(), None, None, From 7c2ddaf96f2f3a56184608881e39cf2dd2b55779 Mon Sep 17 00:00:00 2001 From: eric-wang-1990 Date: Mon, 17 Aug 2026 23:21:15 -0700 Subject: [PATCH 15/19] feat(auth): default kernel U2M to a candidate port window (8030-8034) Previously the bare kernel default was a single port (8030), so only callers that pass an explicit port list (Python) got the busy-port fallback. Default databricks-sql-connector consumers (Node, Go, ODBC, bare Rust) failed outright if 8030 was occupied. Default redirect_ports to [8030, 8031, 8032, 8033, 8034] so they get the same first-free-port fallback. Safe without per-port app registration: databricks-sql-connector uses Databricks in-house OAuth, which drops the loopback port before comparison (RFC 8252), so any http://localhost:{port} is accepted; 8030 stays first so the common case is unchanged. Comment added explaining why. Co-authored-by: Isaac Signed-off-by: eric-wang-1990 --- src/session.rs | 33 +++++++++++++++++++++++++-------- 1 file changed, 25 insertions(+), 8 deletions(-) diff --git a/src/session.rs b/src/session.rs index cb0ad352..ed25aa6f 100644 --- a/src/session.rs +++ b/src/session.rs @@ -1063,8 +1063,22 @@ fn result_to_post_process_options( /// its own redirect URI): the `databricks-sql-connector` app, shared by the /// Node and Go drivers. See PECOBLR-4039. const DEFAULT_U2M_CLIENT_ID: &str = "databricks-sql-connector"; -/// Redirect port registered for [`DEFAULT_U2M_CLIENT_ID`]. -const DEFAULT_U2M_REDIRECT_PORT: u16 = 8030; +/// Default candidate redirect ports for [`DEFAULT_U2M_CLIENT_ID`], tried in +/// order — the kernel binds the first free one, so a bare-default consumer +/// (Node, Go, ODBC, bare Rust) gets busy-port fallback when 8030 is occupied +/// (a stale prior listener, or a second concurrent U2M connection), instead of +/// failing outright. +/// +/// Why a contiguous 8030–8034 window is safe even though only 8030 is the +/// "canonical" registered port: [`DEFAULT_U2M_CLIENT_ID`] authenticates via +/// Databricks in-house OAuth, which normalizes loopback redirect URIs by +/// **dropping the port before comparison** (RFC 8252 §7.3 — "an exact match is +/// required except for the port component"). So every `http://localhost:{port}` +/// is accepted for this client regardless of the specific port, and no +/// per-port app registration is needed. (Validated live: :8030, plus arbitrary +/// ports, all complete the flow.) The first port is the canonical 8030 so the +/// common case is unchanged. +const DEFAULT_U2M_REDIRECT_PORTS: [u16; 5] = [8030, 8031, 8032, 8033, 8034]; /// Scopes registered for [`DEFAULT_U2M_CLIENT_ID`] (`sql offline_access`). fn default_u2m_scopes() -> Vec { @@ -1089,7 +1103,7 @@ fn resolve_u2m_bundle( // forward a one-element list. let ports = match redirect_ports { Some(ports) if !ports.is_empty() => ports.to_vec(), - _ => vec![DEFAULT_U2M_REDIRECT_PORT], + _ => DEFAULT_U2M_REDIRECT_PORTS.to_vec(), }; ( client_id.unwrap_or(DEFAULT_U2M_CLIENT_ID).to_string(), @@ -1220,10 +1234,11 @@ mod u2m_default_tests { #[test] fn u2m_default_bundle_is_connector_sql_8030() { // Caller omits everything → kernel default databricks-sql-connector - // app bundle (PECOBLR-4039). No port range → single default port. + // app bundle (PECOBLR-4039), with the full default candidate-port + // window so bare-default consumers get busy-port fallback too. let (client_id, ports, scopes) = resolve_u2m_bundle(None, None, None); assert_eq!(client_id, "databricks-sql-connector"); - assert_eq!(ports, vec![8030]); + assert_eq!(ports, vec![8030, 8031, 8032, 8033, 8034]); assert_eq!( scopes, vec!["sql".to_string(), "offline_access".to_string()] @@ -1253,11 +1268,13 @@ mod u2m_default_tests { #[test] fn u2m_bundle_empty_or_none_ports_use_default() { - // Both an empty list and None fall back to the kernel default port. + // Both an empty list and None fall back to the kernel default port + // window (first is the canonical 8030; the rest are fallback candidates). + let default = vec![8030, 8031, 8032, 8033, 8034]; let (_, ports_empty, _) = resolve_u2m_bundle(None, Some(&[]), None); - assert_eq!(ports_empty, vec![8030]); + assert_eq!(ports_empty, default); let (_, ports_none, _) = resolve_u2m_bundle(None, None, None); - assert_eq!(ports_none, vec![8030]); + assert_eq!(ports_none, default); } } From db57abfd2495bc49786a1a3b86c410296462ca3d Mon Sep 17 00:00:00 2001 From: "peco-engineer-bot[bot]" Date: Tue, 18 Aug 2026 06:28:05 +0000 Subject: [PATCH 16/19] ai: apply changes for #257 (1 review thread) Addresses: - #3801541682 at CONNECTION_PARAMETERS.md:59 Signed-off-by: peco-engineer-bot[bot] --- CONNECTION_PARAMETERS.md | 2 +- src/config.rs | 11 +++++++---- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/CONNECTION_PARAMETERS.md b/CONNECTION_PARAMETERS.md index ad0183c8..bb9ba706 100644 --- a/CONNECTION_PARAMETERS.md +++ b/CONNECTION_PARAMETERS.md @@ -56,7 +56,7 @@ An enum; pick one variant. Use the validating constructors | Field | Description | Default | |-------|-------------|---------| | `client_id` | OAuth client id. | `"databricks-sql-connector"` | -| `redirect_ports` | Ordered candidate localhost ports for the OAuth callback listener; the first free port is bound (busy-port fallback). `None`/empty selects the default. Each port must be a registered redirect URI of the OAuth app. The default app's redirect URI is registered for `http://localhost:8030`. | `[8030]` | +| `redirect_ports` | Ordered candidate localhost ports for the OAuth callback listener; the first free port is bound (busy-port fallback). `None`/empty selects the default window. The default app (`databricks-sql-connector`) accepts any `http://localhost:{port}` because its in-house OAuth normalizes loopback redirect URIs by dropping the port (RFC 8252 §7.3); for other apps every port must be a registered redirect URI. | `[8030, 8031, 8032, 8033, 8034]` | | `scopes` | OAuth scopes. `offline_access` is required to receive a refresh token (cached and refreshed transparently). | `["sql", "offline_access"]` | | `token_url_override` | Token endpoint override. | OIDC discovery | | `callback_timeout` | How long to wait for the user to complete the browser flow. | `120s` | diff --git a/src/config.rs b/src/config.rs index da13fd90..d5f8050e 100644 --- a/src/config.rs +++ b/src/config.rs @@ -290,7 +290,7 @@ impl TokenCacheConfig { /// Optional fields default to sensible values when set to `None`: /// - OAuth scopes default to `["all-apis"]` for M2M and /// `["sql", "offline_access"]` for U2M. -/// - U2M `redirect_ports` defaults to `[8030]`. +/// - U2M `redirect_ports` defaults to the `[8030, 8031, 8032, 8033, 8034]` window. /// - U2M `client_id` defaults to `"databricks-sql-connector"`. /// - `token_url_override` defaults to OIDC discovery against the /// workspace host. @@ -330,7 +330,8 @@ pub enum AuthConfig { client_id: Option, /// Candidate localhost callback ports, tried in order; the first /// one free is bound (busy-port fallback). `None`/empty → the - /// `8030` default (registered for `databricks-sql-connector`). + /// `[8030, 8031, 8032, 8033, 8034]` default window (the + /// `databricks-sql-connector` app accepts any loopback port). /// A single fixed port is just a one-element list (`vec![p]`) — /// which is how the single-port bindings (C ABI, N-API) forward /// their one port. Every entry must be a registered redirect URI @@ -432,14 +433,16 @@ impl AuthConfig { /// Construct a [`AuthConfig::OAuthU2M`] from optional fields. All /// U2M fields are optional — the kernel fills `databricks-sql-connector` / - /// port 8030 / `sql offline_access` when omitted — so this performs no + /// the `[8030, 8031, 8032, 8033, 8034]` port window / `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, including the federation client id. /// /// `redirect_ports` is the ordered list of candidate callback ports /// (first free binds). Single-port callers pass a one-element list - /// (`Some(vec![port])`); `None`/empty falls back to the `8030` default. + /// (`Some(vec![port])`); `None`/empty falls back to the + /// `[8030, 8031, 8032, 8033, 8034]` default window. pub fn oauth_u2m( client_id: Option, redirect_ports: Option>, From bb6ca485fffc042c5bfaa3cec4b76b4bdb439d0e Mon Sep 17 00:00:00 2001 From: "peco-engineer-bot[bot]" Date: Tue, 18 Aug 2026 06:36:40 +0000 Subject: [PATCH 17/19] ai: apply changes for #257 (1 review thread) Addresses: - #3801587000 at src/session.rs:1104 Signed-off-by: peco-engineer-bot[bot] --- src/session.rs | 35 +++++++++++++++++++++++++++++++---- 1 file changed, 31 insertions(+), 4 deletions(-) diff --git a/src/session.rs b/src/session.rs index ed25aa6f..c02d3fa2 100644 --- a/src/session.rs +++ b/src/session.rs @@ -1101,12 +1101,22 @@ fn resolve_u2m_bundle( // must be a registered redirect URI of the chosen OAuth app — the // {client_id, ports, scopes} bundle stays coupled. Single-port bindings // forward a one-element list. + let resolved_client_id = client_id.unwrap_or(DEFAULT_U2M_CLIENT_ID); let ports = match redirect_ports { Some(ports) if !ports.is_empty() => ports.to_vec(), - _ => DEFAULT_U2M_REDIRECT_PORTS.to_vec(), + // The contiguous 8030–8034 fallback window is only safe for + // `DEFAULT_U2M_CLIENT_ID`, whose in-house OAuth drops the loopback port + // when matching redirect URIs (RFC 8252 §7.3 — see + // `DEFAULT_U2M_REDIRECT_PORTS`). A custom OAuth app registers static + // redirect URIs, so a fallback port it did not register would not match; + // default such callers to the single canonical port (binds 8030 or + // fails), matching the pre-multi-port behaviour. Custom apps that want + // busy-port fallback must supply their own registered `redirect_ports`. + _ if resolved_client_id == DEFAULT_U2M_CLIENT_ID => DEFAULT_U2M_REDIRECT_PORTS.to_vec(), + _ => vec![DEFAULT_U2M_REDIRECT_PORTS[0]], }; ( - client_id.unwrap_or(DEFAULT_U2M_CLIENT_ID).to_string(), + resolved_client_id.to_string(), ports, scopes .map(<[String]>::to_vec) @@ -1268,14 +1278,31 @@ mod u2m_default_tests { #[test] fn u2m_bundle_empty_or_none_ports_use_default() { - // Both an empty list and None fall back to the kernel default port - // window (first is the canonical 8030; the rest are fallback candidates). + // For the default client, both an empty list and None fall back to the + // kernel default port window (first is the canonical 8030; the rest are + // fallback candidates). let default = vec![8030, 8031, 8032, 8033, 8034]; let (_, ports_empty, _) = resolve_u2m_bundle(None, Some(&[]), None); assert_eq!(ports_empty, default); let (_, ports_none, _) = resolve_u2m_bundle(None, None, None); assert_eq!(ports_none, default); } + + #[test] + fn u2m_bundle_custom_client_without_ports_uses_single_canonical_port() { + // The 8030–8034 fallback window is only safe for the default client + // (RFC 8252 §7.3 loopback-port normalization). A custom OAuth app with + // no ports must NOT get fallback candidates it never registered — it + // falls back to the single canonical 8030 (bind-or-fail), matching the + // pre-multi-port behaviour. Both None and an empty list behave this way. + let (client_id, ports_none, _) = + resolve_u2m_bundle(Some("databricks-sql-python"), None, None); + assert_eq!(client_id, "databricks-sql-python"); + assert_eq!(ports_none, vec![8030]); + let (_, ports_empty, _) = + resolve_u2m_bundle(Some("databricks-sql-python"), Some(&[]), None); + assert_eq!(ports_empty, vec![8030]); + } } #[cfg(test)] From b5a3255f57be0787dd1205c05c684c7d14d00232 Mon Sep 17 00:00:00 2001 From: "peco-engineer-bot[bot]" Date: Tue, 18 Aug 2026 06:44:04 +0000 Subject: [PATCH 18/19] ai: apply changes for #257 (1 review thread) Addresses: - #3801587000 at src/session.rs:1105 Signed-off-by: peco-engineer-bot[bot] --- src/session.rs | 30 ++---------------------------- 1 file changed, 2 insertions(+), 28 deletions(-) diff --git a/src/session.rs b/src/session.rs index c02d3fa2..93c0ceb1 100644 --- a/src/session.rs +++ b/src/session.rs @@ -1101,22 +1101,12 @@ fn resolve_u2m_bundle( // must be a registered redirect URI of the chosen OAuth app — the // {client_id, ports, scopes} bundle stays coupled. Single-port bindings // forward a one-element list. - let resolved_client_id = client_id.unwrap_or(DEFAULT_U2M_CLIENT_ID); let ports = match redirect_ports { Some(ports) if !ports.is_empty() => ports.to_vec(), - // The contiguous 8030–8034 fallback window is only safe for - // `DEFAULT_U2M_CLIENT_ID`, whose in-house OAuth drops the loopback port - // when matching redirect URIs (RFC 8252 §7.3 — see - // `DEFAULT_U2M_REDIRECT_PORTS`). A custom OAuth app registers static - // redirect URIs, so a fallback port it did not register would not match; - // default such callers to the single canonical port (binds 8030 or - // fails), matching the pre-multi-port behaviour. Custom apps that want - // busy-port fallback must supply their own registered `redirect_ports`. - _ if resolved_client_id == DEFAULT_U2M_CLIENT_ID => DEFAULT_U2M_REDIRECT_PORTS.to_vec(), - _ => vec![DEFAULT_U2M_REDIRECT_PORTS[0]], + _ => DEFAULT_U2M_REDIRECT_PORTS.to_vec(), }; ( - resolved_client_id.to_string(), + client_id.unwrap_or(DEFAULT_U2M_CLIENT_ID).to_string(), ports, scopes .map(<[String]>::to_vec) @@ -1287,22 +1277,6 @@ mod u2m_default_tests { let (_, ports_none, _) = resolve_u2m_bundle(None, None, None); assert_eq!(ports_none, default); } - - #[test] - fn u2m_bundle_custom_client_without_ports_uses_single_canonical_port() { - // The 8030–8034 fallback window is only safe for the default client - // (RFC 8252 §7.3 loopback-port normalization). A custom OAuth app with - // no ports must NOT get fallback candidates it never registered — it - // falls back to the single canonical 8030 (bind-or-fail), matching the - // pre-multi-port behaviour. Both None and an empty list behave this way. - let (client_id, ports_none, _) = - resolve_u2m_bundle(Some("databricks-sql-python"), None, None); - assert_eq!(client_id, "databricks-sql-python"); - assert_eq!(ports_none, vec![8030]); - let (_, ports_empty, _) = - resolve_u2m_bundle(Some("databricks-sql-python"), Some(&[]), None); - assert_eq!(ports_empty, vec![8030]); - } } #[cfg(test)] From 6b0bc8a32a39c699b1e76a57c8849a18ee787048 Mon Sep 17 00:00:00 2001 From: eric-wang-1990 Date: Mon, 17 Aug 2026 23:49:08 -0700 Subject: [PATCH 19/19] docs(auth): finish redirect_port -> redirect_ports doc sweep Update the two remaining stale singular references in session.rs (the DEFAULT_U2M_CLIENT_ID coupled-bundle doc and the resolve_u2m_bundle doc) to the plural redirect_ports, matching the renamed field/API. Doc-only. Co-authored-by: Isaac Signed-off-by: eric-wang-1990 --- src/session.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/session.rs b/src/session.rs index 93c0ceb1..e4870bcd 100644 --- a/src/session.rs +++ b/src/session.rs @@ -1059,8 +1059,8 @@ fn result_to_post_process_options( } /// Kernel default U2M OAuth client id. The default `{client_id, scopes, -/// redirect_port}` form one coupled bundle (each OAuth app is registered with -/// its own redirect URI): the `databricks-sql-connector` app, shared by the +/// redirect_ports}` form one coupled bundle (each OAuth app is registered with +/// its own redirect URIs): the `databricks-sql-connector` app, shared by the /// Node and Go drivers. See PECOBLR-4039. const DEFAULT_U2M_CLIENT_ID: &str = "databricks-sql-connector"; /// Default candidate redirect ports for [`DEFAULT_U2M_CLIENT_ID`], tried in @@ -1090,7 +1090,7 @@ fn default_u2m_scopes() -> Vec { /// Extracted from [`build_auth_provider`] so the defaulting is unit-testable /// without OIDC discovery. Because the bundle is coupled, a caller overriding /// `client_id` for a different OAuth app must also supply the matching -/// `redirect_port` (and usually `scopes`). +/// `redirect_ports` (and usually `scopes`). fn resolve_u2m_bundle( client_id: Option<&str>, redirect_ports: Option<&[u16]>,