From 293cd5693038f77300bd3e09d427531ade9e9a8c Mon Sep 17 00:00:00 2001 From: Kevin Yue Date: Mon, 6 Jul 2026 13:51:03 +0800 Subject: [PATCH] feat: add browser-launcher crate and integrate with authentication flow --- .github/workflows/build.yaml | 21 +++ Cargo.lock | 15 ++- crates/auth/Cargo.toml | 8 +- crates/auth/src/browser/browser_auth.rs | 116 ++++------------ crates/browser-launcher/Cargo.toml | 19 +++ crates/browser-launcher/src/lib.rs | 171 ++++++++++++++++++++++++ 6 files changed, 251 insertions(+), 99 deletions(-) create mode 100644 crates/browser-launcher/Cargo.toml create mode 100644 crates/browser-launcher/src/lib.rs diff --git a/.github/workflows/build.yaml b/.github/workflows/build.yaml index 2f56da3..7f0d9c9 100644 --- a/.github/workflows/build.yaml +++ b/.github/workflows/build.yaml @@ -39,6 +39,27 @@ concurrency: cancel-in-progress: true jobs: + test-gp: + runs-on: ubuntu-latest + steps: + - name: Checkout GlobalProtect-openconnect + uses: actions/checkout@v6 + with: + token: ${{ secrets.GH_PAT }} + repository: yuezk/GlobalProtect-openconnect + ref: ${{ github.event_name == 'workflow_dispatch' && inputs.gp_branch || github.ref }} + submodules: recursive + - name: Run Rust tests in Docker + run: | + docker run --rm \ + --user root \ + -e COREPACK_INTEGRITY_KEYS=0 \ + -e LIBXML2_STATIC=1 \ + -v "$(pwd):/workspace" \ + -w /workspace \ + yuezk/gpdev:binary-builder-tauri2 \ + cargo test --workspace + tarball: runs-on: ubuntu-latest steps: diff --git a/Cargo.lock b/Cargo.lock index cfc4033..d302589 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -218,6 +218,7 @@ version = "2.6.4" dependencies = [ "anyhow", "block2", + "browser-launcher", "common", "gpapi", "html-escape", @@ -225,16 +226,13 @@ dependencies = [ "objc2", "objc2-foundation", "objc2-web-kit", - "open", "regex", "tauri", "tiny_http", "tokio", "tokio-util", "uuid", - "webbrowser", "webkit2gtk", - "which", ] [[package]] @@ -419,6 +417,17 @@ dependencies = [ "alloc-stdlib", ] +[[package]] +name = "browser-launcher" +version = "2.6.4" +dependencies = [ + "anyhow", + "log", + "open", + "webbrowser", + "which", +] + [[package]] name = "bs58" version = "0.5.1" diff --git a/crates/auth/Cargo.toml b/crates/auth/Cargo.toml index 1324834..d5efcd0 100644 --- a/crates/auth/Cargo.toml +++ b/crates/auth/Cargo.toml @@ -17,9 +17,7 @@ log.workspace = true tokio.workspace = true # Browser auth dependencies -webbrowser = { version = "1", optional = true } -open = { version = "5", optional = true } -which = { workspace = true, optional = true } +browser-launcher = { path = "../browser-launcher", default-features = false, features = ["launcher"], optional = true } tiny_http = { version = "0.12", optional = true } uuid = { version = "1", optional = true, features = ["v4"] } @@ -40,9 +38,7 @@ objc2-web-kit = { version = "0.3", optional = true } [features] browser-auth = [ - "dep:webbrowser", - "dep:open", - "dep:which", + "dep:browser-launcher", "dep:tiny_http", "dep:uuid", ] diff --git a/crates/auth/src/browser/browser_auth.rs b/crates/auth/src/browser/browser_auth.rs index 9ba8706..ff247f4 100644 --- a/crates/auth/src/browser/browser_auth.rs +++ b/crates/auth/src/browser/browser_auth.rs @@ -1,5 +1,6 @@ use std::{env::temp_dir, fs, os::unix::fs::PermissionsExt}; +use browser_launcher::Browser as LaunchBrowser; use common::constants::GP_CALLBACK_PORT_FILENAME; use gpapi::auth::SamlAuthData; use log::info; @@ -10,50 +11,14 @@ use tokio::{ use crate::browser::auth_server::AuthServer; -pub enum Browser<'a> { - Auto, - Default, - Chrome, - Firefox, - Remote, - Other(&'a str), -} - -impl<'a> Browser<'a> { - pub fn from_str(browser: &'a str) -> Self { - match browser.to_lowercase().as_str() { - "auto" => Browser::Auto, - "default" => Browser::Default, - "chrome" => Browser::Chrome, - "firefox" => Browser::Firefox, - "remote" => Browser::Remote, - _ => Browser::Other(browser), - } - } - - fn as_str(&self) -> &str { - match self { - Browser::Auto => "auto", - Browser::Default => "default", - Browser::Chrome => "chrome", - Browser::Firefox => "firefox", - Browser::Remote => "remote", - Browser::Other(browser) => browser, - } - } -} - pub struct BrowserAuthenticator<'a> { auth_request: &'a str, - browser: Browser<'a>, + browser: &'a str, } impl<'a> BrowserAuthenticator<'a> { pub fn new(auth_request: &'a str, browser: &'a str) -> Self { - Self { - auth_request, - browser: Browser::from_str(browser), - } + Self { auth_request, browser } } pub async fn authenticate(&self) -> anyhow::Result { @@ -66,10 +31,9 @@ impl<'a> BrowserAuthenticator<'a> { auth_server.serve_request(&auth_request); }); - match self.browser { - Browser::Remote => { - info!( - r#" + if is_remote_browser(self.browser) { + info!( + r#" ==== Manual Authentication Required ==== @@ -82,37 +46,19 @@ After completing the authentication, please paste the authentication data back t Note that the URL is only valid for a single use. "#, - auth_url - ); - return read_auth_data_from_stdin(); - } - Browser::Default => { - info!("Launching the default browser..."); - webbrowser::open(&auth_url)?; - } - Browser::Auto => { - if let Some(app) = find_auto_browser_path() { - info!("Launching browser: {}", app); - open::with_detached(&auth_url, app)?; - } else { - info!("No preferred browser found; launching the default browser..."); - webbrowser::open(&auth_url)?; - } - } - _ => { - let app = find_browser_path(&self.browser); - - info!("Launching browser: {}", app); - open::with_detached(auth_url, app)?; - } + auth_url + ); + return read_auth_data_from_stdin(); } + browser_launcher::open_url(&auth_url, LaunchBrowser::from_name(self.browser))?; + info!("Please continue the authentication process in the default browser"); wait_auth_data().await } async fn determine_addr(&self) -> anyhow::Result { - if matches!(self.browser, Browser::Remote) { + if is_remote_browser(self.browser) { let local_ip = detect_local_ip().await?; Ok(format!("{}:0", local_ip)) } else { @@ -121,6 +67,10 @@ Note that the URL is only valid for a single use. } } +fn is_remote_browser(browser: &str) -> bool { + browser.eq_ignore_ascii_case("remote") +} + /// Detect the local IP address by creating a UDP socket and connecting to an external address async fn detect_local_ip() -> anyhow::Result { let socket = UdpSocket::bind("0.0.0.0:0").await?; @@ -134,27 +84,6 @@ async fn detect_local_ip() -> anyhow::Result { Ok(ip.to_string()) } -fn find_browser_path(browser: &Browser) -> String { - match browser { - Browser::Chrome => find_chrome_path().unwrap_or_else(|| browser.as_str().to_string()), - _ => browser.as_str().to_string(), - } -} - -fn find_auto_browser_path() -> Option { - find_chrome_path().or_else(|| find_program_path("firefox")) -} - -fn find_chrome_path() -> Option { - ["google-chrome-stable", "google-chrome", "chromium"] - .iter() - .find_map(|browser_name| find_program_path(browser_name)) -} - -fn find_program_path(name: &str) -> Option { - which::which(name).ok().map(|path| path.to_string_lossy().to_string()) -} - async fn wait_auth_data() -> anyhow::Result { // Start a local server to receive the browser authentication data let listener = TcpListener::bind("127.0.0.1:0").await?; @@ -200,8 +129,15 @@ mod tests { use super::*; #[test] - fn browser_auto_is_distinct_from_system_default() { - assert!(matches!(Browser::from_str("auto"), Browser::Auto)); - assert!(matches!(Browser::from_str("default"), Browser::Default)); + fn shared_launcher_keeps_auto_distinct_from_system_default() { + assert_eq!(LaunchBrowser::from_name("auto"), LaunchBrowser::Auto); + assert_eq!(LaunchBrowser::from_name("default"), LaunchBrowser::Default); + } + + #[test] + fn browser_remote_remains_auth_specific() { + assert!(is_remote_browser("remote")); + assert!(is_remote_browser("REMOTE")); + assert_ne!(LaunchBrowser::from_name("remote"), LaunchBrowser::Default); } } diff --git a/crates/browser-launcher/Cargo.toml b/crates/browser-launcher/Cargo.toml new file mode 100644 index 0000000..099b99b --- /dev/null +++ b/crates/browser-launcher/Cargo.toml @@ -0,0 +1,19 @@ +[package] +name = "browser-launcher" +rust-version.workspace = true +version.workspace = true +authors.workspace = true +homepage.workspace = true +edition.workspace = true +license.workspace = true + +[dependencies] +anyhow.workspace = true +log.workspace = true +open = { version = "5", optional = true } +webbrowser = { version = "1", optional = true } +which = { workspace = true, optional = true } + +[features] +default = [] +launcher = ["dep:open", "dep:webbrowser", "dep:which"] diff --git a/crates/browser-launcher/src/lib.rs b/crates/browser-launcher/src/lib.rs new file mode 100644 index 0000000..6955ff6 --- /dev/null +++ b/crates/browser-launcher/src/lib.rs @@ -0,0 +1,171 @@ +#[cfg(feature = "launcher")] +use log::info; + +#[cfg(any(feature = "launcher", test))] +const CHROME_BROWSERS: &[&str] = &["google-chrome-stable", "google-chrome", "chromium"]; +#[cfg(any(feature = "launcher", test))] +const EDGE_BROWSERS: &[&str] = &[ + "microsoft-edge-stable", + "microsoft-edge", + "microsoft-edge-beta", + "microsoft-edge-dev", +]; +#[cfg(any(feature = "launcher", test))] +const FIREFOX_BROWSER: &str = "firefox"; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Browser<'a> { + Auto, + Default, + Chrome, + Edge, + Firefox, + Other(&'a str), +} + +impl<'a> Browser<'a> { + pub fn from_config(value: Option<&'a str>) -> Self { + let Some(value) = value.filter(|value| !value.trim().is_empty()) else { + return Browser::Auto; + }; + + Self::from_name(value) + } + + pub fn from_name(value: &'a str) -> Self { + match value.trim().to_lowercase().as_str() { + "auto" => Browser::Auto, + "default" => Browser::Default, + "chrome" => Browser::Chrome, + "edge" => Browser::Edge, + "firefox" => Browser::Firefox, + _ => Browser::Other(value), + } + } + + #[cfg(feature = "launcher")] + fn as_str(&self) -> &str { + match self { + Browser::Auto => "auto", + Browser::Default => "default", + Browser::Chrome => "chrome", + Browser::Edge => "edge", + Browser::Firefox => FIREFOX_BROWSER, + Browser::Other(browser) => browser, + } + } +} + +#[cfg(feature = "launcher")] +pub fn open_url(url: &str, browser: Browser<'_>) -> anyhow::Result<()> { + match browser { + Browser::Auto => { + if let Some(browser) = find_auto_browser() { + open_with_browser(url, &browser).or_else(|_| open_default_browser(url)) + } else { + open_default_browser(url) + } + } + Browser::Default => open_default_browser(url), + Browser::Chrome => { + let browser = find_chrome_browser().unwrap_or_else(|| browser.as_str().to_string()); + open_with_browser(url, &browser) + } + Browser::Edge => { + let browser = find_edge_browser().unwrap_or_else(|| browser.as_str().to_string()); + open_with_browser(url, &browser) + } + Browser::Firefox | Browser::Other(_) => open_with_browser(url, browser.as_str()), + } +} + +#[cfg(feature = "launcher")] +fn open_default_browser(url: &str) -> anyhow::Result<()> { + if webbrowser::open(url).is_ok() { + return Ok(()); + } + + open::that_detached(url).map_err(Into::into) +} + +#[cfg(feature = "launcher")] +fn open_with_browser(url: &str, browser: &str) -> anyhow::Result<()> { + info!("Launching browser: {}", browser); + open::with_detached(url, browser).map_err(Into::into) +} + +#[cfg(feature = "launcher")] +fn find_auto_browser() -> Option { + find_chrome_browser() + .or_else(find_edge_browser) + .or_else(|| find_program(FIREFOX_BROWSER)) +} + +#[cfg(feature = "launcher")] +fn find_chrome_browser() -> Option { + CHROME_BROWSERS.iter().find_map(|browser| find_program(browser)) +} + +#[cfg(feature = "launcher")] +fn find_edge_browser() -> Option { + EDGE_BROWSERS.iter().find_map(|browser| find_program(browser)) +} + +#[cfg(feature = "launcher")] +fn find_program(name: &str) -> Option { + which::which(name).ok().map(|path| path.to_string_lossy().to_string()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn empty_config_uses_auto() { + assert_eq!(Browser::from_config(None), Browser::Auto); + assert_eq!(Browser::from_config(Some("")), Browser::Auto); + assert_eq!(Browser::from_config(Some(" ")), Browser::Auto); + } + + #[test] + fn known_browser_names_are_case_insensitive() { + assert_eq!(Browser::from_name("AUTO"), Browser::Auto); + assert_eq!(Browser::from_name("Default"), Browser::Default); + assert_eq!(Browser::from_name("Chrome"), Browser::Chrome); + assert_eq!(Browser::from_name("EDGE"), Browser::Edge); + assert_eq!(Browser::from_name("Firefox"), Browser::Firefox); + } + + #[test] + fn custom_browser_names_are_preserved() { + assert_eq!(Browser::from_name("/opt/browser"), Browser::Other("/opt/browser")); + assert_eq!( + Browser::from_config(Some(" custom-browser ")), + Browser::Other(" custom-browser ") + ); + } + + #[test] + fn auto_candidates_try_chrome_then_edge_then_firefox() { + let candidates = CHROME_BROWSERS + .iter() + .chain(EDGE_BROWSERS) + .chain([FIREFOX_BROWSER].iter()) + .copied() + .collect::>(); + + assert_eq!( + candidates, + vec![ + "google-chrome-stable", + "google-chrome", + "chromium", + "microsoft-edge-stable", + "microsoft-edge", + "microsoft-edge-beta", + "microsoft-edge-dev", + "firefox", + ] + ); + } +}