diff --git a/README.md b/README.md index b806d75..5d665ea 100644 --- a/README.md +++ b/README.md @@ -313,6 +313,12 @@ docker run --rm -it --cap-add=NET_ADMIN --device=/dev/net/tun \ connect --browser remote ``` +On a host with multiple network interfaces, use `--browser-listen` to select the IP address reachable from the browser machine: + +```bash +gpclient connect --browser remote --browser-listen 192.168.107.15 +``` + On a Linux host, add host networking if the VPN routes should affect the host network namespace: ```bash diff --git a/apps/gpauth/src/cli.rs b/apps/gpauth/src/cli.rs index 7548dc7..25cfe0c 100644 --- a/apps/gpauth/src/cli.rs +++ b/apps/gpauth/src/cli.rs @@ -15,6 +15,7 @@ use gpapi::{ }; use log::info; use serde_json::json; +use std::net::IpAddr; use tempfile::NamedTempFile; const VERSION: &str = concat!( @@ -94,12 +95,15 @@ struct Cli { #[arg( long, - help = "Use external browser authentication. With no value, auto-select Chrome, Firefox, then system default. Use `default` for the system default browser.", + help = "Use external browser authentication. With no value, auto-select Chrome, Firefox, then system default. Use `default` for the system default browser or `remote` for headless servers.", default_missing_value = "auto", num_args=0..=1 )] browser: Option, + #[arg(long, help = "Listen on this IP address when using '--browser remote'")] + browser_listen: Option, + #[cfg(feature = "webview-auth")] #[arg(long, help = "The HiDPI mode, useful for high-resolution screens")] hidpi: bool, @@ -156,6 +160,12 @@ impl Cli { } async fn run(&self) -> anyhow::Result<()> { + if self.browser_listen.is_some() + && !matches!(self.browser.as_deref(), Some(browser) if browser.eq_ignore_ascii_case("remote")) + { + anyhow::bail!("The '--browser-listen' option requires '--browser remote'"); + } + if self.ignore_tls_errors { info!("TLS errors will be ignored"); } @@ -185,7 +195,7 @@ impl Cli { if let Some(browser) = browser { let auth_host_id = gp_params.os_profile().host_identity().host_id().to_string(); - let authenticator = BrowserAuthenticator::new(&auth_request, browser); + let authenticator = BrowserAuthenticator::new(&auth_request, browser, self.browser_listen); let auth_result = authenticator.authenticate().await; print_auth_result(auth_result, Some(&auth_host_id)); @@ -351,6 +361,21 @@ mod tests { assert!(cli.external_browser_requested()); } + #[test] + fn browser_listen_accepts_ip_address() { + let cli = Cli::try_parse_from([ + "gpauth", + "portal.example.com", + "--browser", + "remote", + "--browser-listen", + "192.168.107.15", + ]) + .expect("gpauth args should parse"); + + assert_eq!(cli.browser_listen, Some("192.168.107.15".parse().unwrap())); + } + #[test] fn client_version_arg_sets_profile_client_version() { let cli = Cli::try_parse_from(["gpauth", "portal.example.com", "--client-version", "legacy-client"]) diff --git a/apps/gpclient/src/connect/args.rs b/apps/gpclient/src/connect/args.rs index 2ca0d60..662d217 100644 --- a/apps/gpclient/src/connect/args.rs +++ b/apps/gpclient/src/connect/args.rs @@ -6,7 +6,7 @@ use gpapi::{ os_profile::{ClientOs, OsProfile}, }; use log::warn; -use std::path::PathBuf; +use std::{net::IpAddr, path::PathBuf}; #[derive(Args)] pub(crate) struct ConnectArgs { @@ -146,6 +146,9 @@ pub(crate) struct ConnectArgs { num_args=0..=1 )] pub(super) browser: Option, + + #[arg(long, help = "Listen on this IP address when using '--browser remote'")] + pub(super) browser_listen: Option, } pub(super) fn build_os_profile(args: &ConnectArgs) -> OsProfile { @@ -263,6 +266,23 @@ mod tests { assert_eq!(cli.args.browser.as_deref(), Some("default")); } + #[test] + fn browser_listen_accepts_ip_address() { + use clap::Parser; + + let cli = ConnectArgsTestCli::try_parse_from([ + "test", + "portal.example.com", + "--browser", + "remote", + "--browser-listen", + "192.168.107.15", + ]) + .expect("connect args should parse"); + + assert_eq!(cli.args.browser_listen, Some("192.168.107.15".parse().unwrap())); + } + #[test] fn os_defaults_to_runtime_os() { use clap::Parser; diff --git a/apps/gpclient/src/connect/credential.rs b/apps/gpclient/src/connect/credential.rs index 52c8279..2b001c6 100644 --- a/apps/gpclient/src/connect/credential.rs +++ b/apps/gpclient/src/connect/credential.rs @@ -85,6 +85,7 @@ impl ConnectHandler<'_> { .sslkey(self.args.sslkey.as_deref()) .key_password(key_password.as_deref()) .browser(browser) + .browser_listen(self.args.browser_listen) .verbose(verbose); #[cfg(feature = "webview-auth")] diff --git a/apps/gpclient/src/connect/mod.rs b/apps/gpclient/src/connect/mod.rs index 39fc07d..4570d99 100644 --- a/apps/gpclient/src/connect/mod.rs +++ b/apps/gpclient/src/connect/mod.rs @@ -92,6 +92,12 @@ impl<'a> ConnectHandler<'a> { } pub(crate) async fn handle(&self) -> anyhow::Result<()> { + if self.args.browser_listen.is_some() + && !matches!(self.args.browser.as_deref(), Some(browser) if browser.eq_ignore_ascii_case("remote")) + { + bail!("The '--browser-listen' option requires '--browser remote'"); + } + #[cfg(feature = "webview-auth")] if self.args.default_browser && self.args.browser.is_some() { bail!("Cannot use `--default-browser` and `--browser` options at the same time"); diff --git a/crates/auth/src/browser/auth_server.rs b/crates/auth/src/browser/auth_server.rs index b1d92fb..cff76a4 100644 --- a/crates/auth/src/browser/auth_server.rs +++ b/crates/auth/src/browser/auth_server.rs @@ -1,4 +1,4 @@ -use std::io::Cursor; +use std::{io::Cursor, net::SocketAddr}; use log::info; use tiny_http::{Header, Method, Response, Server}; @@ -10,7 +10,7 @@ pub(super) struct AuthServer { } impl AuthServer { - pub fn new(addr: &str) -> anyhow::Result { + pub fn new(addr: SocketAddr) -> anyhow::Result { let server = Server::http(addr).map_err(|err| anyhow::anyhow!(err))?; let auth_id = Uuid::new_v4().to_string(); diff --git a/crates/auth/src/browser/browser_auth.rs b/crates/auth/src/browser/browser_auth.rs index 19558c2..089d4df 100644 --- a/crates/auth/src/browser/browser_auth.rs +++ b/crates/auth/src/browser/browser_auth.rs @@ -1,3 +1,5 @@ +use std::net::{IpAddr, SocketAddr}; + use browser_launcher::Browser as LaunchBrowser; use gpapi::auth::SamlAuthData; use log::info; @@ -8,11 +10,16 @@ use crate::{AuthCallbackReceiver, browser::auth_server::AuthServer, ensure_auth_ pub struct BrowserAuthenticator<'a> { auth_request: &'a str, browser: &'a str, + browser_listen: Option, } impl<'a> BrowserAuthenticator<'a> { - pub fn new(auth_request: &'a str, browser: &'a str) -> Self { - Self { auth_request, browser } + pub fn new(auth_request: &'a str, browser: &'a str, browser_listen: Option) -> Self { + Self { + auth_request, + browser, + browser_listen, + } } pub async fn authenticate(&self) -> anyhow::Result { @@ -23,7 +30,7 @@ impl<'a> BrowserAuthenticator<'a> { Some(AuthCallbackReceiver::bind()?) }; let addr = self.determine_addr().await?; - let auth_server = AuthServer::new(&addr)?; + let auth_server = AuthServer::new(addr)?; let auth_url = auth_server.auth_url(); let auth_request = self.auth_request.to_string(); @@ -57,12 +64,15 @@ Note that the URL is only valid for a single use. callback_receiver.unwrap().receive().await } - async fn determine_addr(&self) -> anyhow::Result { + async fn determine_addr(&self) -> anyhow::Result { if is_remote_browser(self.browser) { - let local_ip = detect_local_ip().await?; - Ok(format!("{}:0", local_ip)) + let local_ip = match self.browser_listen { + Some(ip) => ip, + None => detect_local_ip().await?, + }; + Ok(SocketAddr::new(local_ip, 0)) } else { - Ok("127.0.0.1:0".to_string()) + Ok(SocketAddr::from(([127, 0, 0, 1], 0))) } } } @@ -72,16 +82,16 @@ fn is_remote_browser(browser: &str) -> bool { } /// Detect the local IP address by creating a UDP socket and connecting to an external address -async fn detect_local_ip() -> anyhow::Result { +async fn detect_local_ip() -> anyhow::Result { let socket = UdpSocket::bind("0.0.0.0:0").await?; if let Err(err) = socket.connect("1.1.1.1:80").await { anyhow::bail!("Failed to connect to external address to determine local IP: {}", err); } let local_addr = socket.local_addr()?; - let ip = local_addr.ip().to_string(); + let ip = local_addr.ip(); info!("Determined local IP address: {}", ip); - Ok(ip.to_string()) + Ok(ip) } fn read_auth_data_from_stdin() -> anyhow::Result { @@ -108,4 +118,15 @@ mod tests { assert!(is_remote_browser("REMOTE")); assert_ne!(LaunchBrowser::from_name("remote"), LaunchBrowser::Default); } + + #[tokio::test] + async fn remote_browser_uses_explicit_listen_address() { + let listen_ip = "192.168.107.15".parse().unwrap(); + let authenticator = BrowserAuthenticator::new("request", "remote", Some(listen_ip)); + + assert_eq!( + authenticator.determine_addr().await.unwrap(), + SocketAddr::new(listen_ip, 0) + ); + } } diff --git a/crates/gpapi/src/process/auth_launcher.rs b/crates/gpapi/src/process/auth_launcher.rs index fdd92b0..fa54e07 100644 --- a/crates/gpapi/src/process/auth_launcher.rs +++ b/crates/gpapi/src/process/auth_launcher.rs @@ -1,4 +1,4 @@ -use std::{path::PathBuf, process::Stdio}; +use std::{net::IpAddr, path::PathBuf, process::Stdio}; use anyhow::bail; use common::binary_paths; @@ -34,6 +34,7 @@ pub struct SamlAuthLauncher<'a> { #[cfg(feature = "webview-auth")] window_theme: Option, browser: Option<&'a str>, + browser_listen: Option, verbose: Option<&'a str>, } @@ -63,6 +64,7 @@ impl<'a> SamlAuthLauncher<'a> { #[cfg(feature = "webview-auth")] window_theme: None, browser: None, + browser_listen: None, verbose: None, } } @@ -149,6 +151,11 @@ impl<'a> SamlAuthLauncher<'a> { self } + pub fn browser_listen(mut self, browser_listen: Option) -> Self { + self.browser_listen = browser_listen; + self + } + pub fn verbose(mut self, verbose: Option<&'a str>) -> Self { self.verbose = verbose; self @@ -230,6 +237,10 @@ impl<'a> SamlAuthLauncher<'a> { auth_cmd.arg("--browser").arg(browser); } + if let Some(browser_listen) = self.browser_listen { + auth_cmd.arg("--browser-listen").arg(browser_listen.to_string()); + } + if let Some(verbose) = self.verbose { auth_cmd.arg(verbose); } @@ -297,4 +308,12 @@ mod tests { assert_eq!(launcher.sslkey, Some("/tmp/client.key")); assert_eq!(launcher.key_password, Some("secret")); } + + #[test] + fn browser_listen_address_is_stored() { + let listen_ip = "192.168.107.15".parse().unwrap(); + let launcher = SamlAuthLauncher::new("portal.example.com").browser_listen(Some(listen_ip)); + + assert_eq!(launcher.browser_listen, Some(listen_ip)); + } }