diff --git a/CONNECTION_PARAMETERS.md b/CONNECTION_PARAMETERS.md index 6abcec12..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_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 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/napi/src/database.rs b/napi/src/database.rs index b856c774..37d07ede 100644 --- a/napi/src/database.rs +++ b/napi/src/database.rs @@ -368,7 +368,15 @@ 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). + // 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, @@ -722,29 +730,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 1e4f3d78..d2140789 100644 --- a/pyo3/src/auth.rs +++ b/pyo3/src/auth.rs @@ -20,7 +20,7 @@ //! - `"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` / +//! optional `client_id` / `redirect_ports` / `scopes` / `token_url` / //! `oauth_callback_timeout_secs`. //! //! OAuth is **kernel-owned**: the kernel acquires and refreshes tokens @@ -50,7 +50,16 @@ 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). 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 ports (`databricks-sql-python` → the discrete + /// set `8020`/`8025`, not a contiguous range). + /// `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, } @@ -167,14 +176,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("")) { @@ -184,13 +194,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 \ @@ -198,6 +201,26 @@ fn build_auth_config_inner( .to_owned(), ); } + // `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 for 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 @@ -234,15 +257,20 @@ 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, }; Ok(AuthConfig::oauth_u2m( client_id, - redirect_port, + redirect_ports, scopes, oauth.token_url, oauth.callback_timeout_secs.map(Duration::from_secs), @@ -395,7 +423,7 @@ mod tests { match cfg { AuthConfig::OAuthU2M { client_id, - redirect_port, + redirect_ports, scopes, token_url_override, callback_timeout, @@ -404,8 +432,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)); + // 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()]) @@ -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( @@ -441,7 +524,7 @@ mod tests { AuthConfig::OAuthU2M { client_id, scopes, - redirect_port, + redirect_ports, .. } => { assert_eq!(client_id.as_deref(), Some("my-custom-app")); @@ -449,7 +532,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:?}"), } @@ -486,7 +569,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() @@ -495,12 +578,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(), @@ -527,20 +611,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 a0ec22e2..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,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, tls_ca_cert=None, @@ -150,7 +150,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, tls_ca_cert: Option>, @@ -197,7 +197,7 @@ 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 047bc587..2ad9630c 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_first_free(&[8030]).await?; /// let redirect_uri = server.redirect_uri(); /// println!("Redirect URI: {}", redirect_uri); /// @@ -106,35 +106,80 @@ impl Drop for CallbackServer { } impl CallbackServer { - /// Creates a new callback server listening on the specified port. + /// Creates a callback server on the first bindable port in `ports`. /// - /// The server binds to `127.0.0.1:{port}` and is ready to receive one callback. + /// 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 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. /// - /// # Arguments - /// - /// * `port` - Port number to listen on (typically 8030) + /// [`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. /// - /// # Returns + /// # Arguments /// - /// 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 + /// * `ports` - Candidate ports to try, in preference order (must be non-empty). /// /// # Errors /// - /// 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| { - Error::io() - .message(format!("Failed to bind callback server to {}: {}", addr, e)) - .context("OAuth callback server") - })?; + /// - `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_first_free(ports: &[u16]) -> Result { + if ports.is_empty() { + return Err(Error::invalid_argument() + .message("CallbackServer::new_first_free 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() @@ -416,7 +461,7 @@ mod tests { #[tokio::test] async fn test_callback_captures_code() { // Start callback server - let server = CallbackServer::new(0) + let server = CallbackServer::new_first_free(&[0]) .await .expect("Failed to create server"); let port = server.port; @@ -459,7 +504,7 @@ mod tests { #[tokio::test] async fn test_callback_validates_state() { - let server = CallbackServer::new(0) + let server = CallbackServer::new_first_free(&[0]) .await .expect("Failed to create server"); let port = server.port; @@ -504,7 +549,7 @@ mod tests { #[tokio::test] async fn test_callback_timeout() { - let server = CallbackServer::new(0) + let server = CallbackServer::new_first_free(&[0]) .await .expect("Failed to create server"); @@ -524,7 +569,7 @@ mod tests { #[tokio::test] async fn test_callback_missing_code() { - let server = CallbackServer::new(0) + let server = CallbackServer::new_first_free(&[0]) .await .expect("Failed to create server"); let port = server.port; @@ -555,7 +600,7 @@ mod tests { #[tokio::test] async fn test_callback_auth_error() { - let server = CallbackServer::new(0) + let server = CallbackServer::new_first_free(&[0]) .await .expect("Failed to create server"); let port = server.port; @@ -618,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(0) + let server = CallbackServer::new_first_free(&[0]) .await .expect("Failed to create server"); let uri = server.redirect_uri(); @@ -637,4 +682,71 @@ mod tests { .unwrap(); assert!(port > 0, "Expected a non-zero port, got: {}", port); } + + #[tokio::test] + 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_first_free_single_port_binds() { + // A one-element range behaves like new(0): binds an OS-assigned port. + let server = CallbackServer::new_first_free(&[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_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. + 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_first_free(&[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_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(); + 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_first_free(&[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..5a27d3b3 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_first_free(&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/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 b1e1d158..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_port` 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. @@ -320,18 +320,26 @@ 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). client_id: Option, - /// Localhost port for the OAuth callback listener. `None` → - /// `8030` (the redirect port registered for - /// `databricks-sql-connector`). - redirect_port: Option, + /// Candidate localhost callback ports, tried in order; the first + /// one free is bound (busy-port fallback). `None`/empty → the + /// `[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 + /// of the OAuth app; a multi-port list mirrors the Thrift + /// 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 /// refresh token, which the kernel caches and refreshes @@ -425,13 +433,19 @@ 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, 8031, 8032, 8033, 8034]` default window. pub fn oauth_u2m( client_id: Option, - redirect_port: Option, + redirect_ports: Option>, scopes: Option>, token_url_override: Option, callback_timeout: Option, @@ -440,7 +454,7 @@ impl AuthConfig { ) -> Self { AuthConfig::OAuthU2M { client_id, - redirect_port, + redirect_ports, scopes, token_url_override, callback_timeout, @@ -518,14 +532,14 @@ impl std::fmt::Debug for AuthConfig { .finish(), Self::OAuthU2M { client_id, - redirect_port, + redirect_ports, scopes, identity_federation_client_id, .. } => f .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 +1693,37 @@ mod tests { ); } + #[test] + 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:?}"), + } + } + + #[test] + 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, .. } => { + assert_eq!(redirect_ports, Some(vec![8020, 8021, 8022])); + } + other => panic!("expected OAuthU2M, got {other:?}"), + } + } + #[test] fn auth_variants_carry_identity_federation_client_id() { let auths = [ @@ -1695,7 +1740,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..e4870bcd 100644 --- a/src/session.rs +++ b/src/session.rs @@ -1059,12 +1059,26 @@ 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"; -/// 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 { @@ -1076,15 +1090,24 @@ 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_port: Option, + redirect_ports: Option<&[u16]>, scopes: Option<&[String]>, -) -> (String, u16, Vec) { +) -> (String, Vec, Vec) { + // 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(), + _ => DEFAULT_U2M_REDIRECT_PORTS.to_vec(), + }; ( 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), @@ -1157,7 +1180,7 @@ async fn build_base_auth_provider( } AuthConfig::OAuthU2M { client_id, - redirect_port, + redirect_ports, scopes, token_url_override, callback_timeout, @@ -1167,8 +1190,13 @@ 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_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 +1212,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 +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). - let (client_id, port, scopes) = resolve_u2m_bundle(None, None, None); + // 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!(port, 8030); + assert_eq!(ports, vec![8030, 8031, 8032, 8033, 8034]); assert_eq!( scopes, vec!["sql".to_string(), "offline_access".to_string()] @@ -1219,14 +1248,35 @@ 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, 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]), 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_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_or_none_ports_use_default() { + // 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); + } } #[cfg(test)] 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..26489b05 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, @@ -144,6 +144,61 @@ 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. +// +// 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 \ +// ~/.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 { + // 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()]), + 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() {