diff --git a/Cargo.lock b/Cargo.lock index a490857..8b67597 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2146,6 +2146,7 @@ dependencies = [ "directories", "dns-lookup", "env_logger", + "file-rotate", "getrandom 0.4.3", "gtk", "humantime", @@ -2202,7 +2203,6 @@ dependencies = [ "common", "compile-time", "gpapi", - "home", "log", "serde_json", "tauri", @@ -2460,15 +2460,6 @@ dependencies = [ "digest 0.11.3", ] -[[package]] -name = "home" -version = "0.5.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cc627f471c528ff0c4a49e1d5e60450c8f6461dd6d10ba9dcd3a61d3dff7728d" -dependencies = [ - "windows-sys 0.61.2", -] - [[package]] name = "html-escape" version = "0.3.0" diff --git a/apps/gpauth/Cargo.toml b/apps/gpauth/Cargo.toml index f92edb5..1a11b4c 100644 --- a/apps/gpauth/Cargo.toml +++ b/apps/gpauth/Cargo.toml @@ -23,8 +23,6 @@ serde_json.workspace = true tokio = { workspace = true, features = ["rt-multi-thread"] } compile-time.workspace = true -home = "0.5.12" - # webview auth dependencies tauri = { workspace = true, optional = true } diff --git a/crates/auth/src/callback/windows.rs b/crates/auth/src/callback/windows.rs index 66e32f9..42500c7 100644 --- a/crates/auth/src/callback/windows.rs +++ b/crates/auth/src/callback/windows.rs @@ -99,6 +99,8 @@ pub fn ensure_auth_callback_handler() -> anyhow::Result<()> { let (scheme, _) = root.create_subkey(r"Software\Classes\globalprotectcallback")?; scheme.set_value("", &"URL:GlobalProtect authentication callback")?; scheme.set_value("URL Protocol", &"")?; + let (application, _) = scheme.create_subkey("Application")?; + application.set_value("ApplicationName", &"GP Connect Login")?; let (command, _) = scheme.create_subkey(r"shell\open\command")?; // URL association activation requires a shell path, not Rust's verbatim // canonical path (\\?\C:\...), even though CreateProcess accepts both. diff --git a/crates/auth/src/webview/recovery.rs b/crates/auth/src/webview/recovery.rs index a3db72a..9fa36a6 100644 --- a/crates/auth/src/webview/recovery.rs +++ b/crates/auth/src/webview/recovery.rs @@ -22,7 +22,7 @@ impl RecoveryStatus { Self::Hidden => "", Self::Restarting => "Restarting sign-in…", Self::Loading => "Loading sign-in…", - Self::Failed => "Couldn’t restart sign-in.", + Self::Failed => "Couldn’t load sign-in.", Self::Rejected => "Sign-in wasn’t completed.", Self::Tls { reason: TlsFailureReason::Handshake, @@ -55,6 +55,7 @@ impl RecoveryStatus { matches!(self, Self::Hidden | Self::Loading | Self::CertificateBypassed) } + #[cfg(not(windows))] pub fn is_busy(self) -> bool { matches!(self, Self::Restarting | Self::Loading) } diff --git a/crates/auth/src/webview/tls.rs b/crates/auth/src/webview/tls.rs index f96015a..0f5c6ce 100644 --- a/crates/auth/src/webview/tls.rs +++ b/crates/auth/src/webview/tls.rs @@ -2,7 +2,9 @@ #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(super) enum TlsFailureReason { Expired, + #[cfg(not(windows))] NotYetValid, + #[cfg(not(windows))] Untrusted, HostnameMismatch, InvalidCertificate, @@ -17,7 +19,9 @@ impl TlsFailureReason { pub fn message(self) -> &'static str { match self { Self::Expired => "The certificate has expired.", + #[cfg(not(windows))] Self::NotYetValid => "The certificate is not valid yet.", + #[cfg(not(windows))] Self::Untrusted => "The certificate was issued by an untrusted authority.", Self::HostnameMismatch => "The certificate does not match this server’s hostname.", Self::InvalidCertificate => "The server’s certificate could not be verified.", diff --git a/crates/auth/src/webview/windows/controls.rs b/crates/auth/src/webview/windows/controls.rs index 73eee74..142f98a 100644 --- a/crates/auth/src/webview/windows/controls.rs +++ b/crates/auth/src/webview/windows/controls.rs @@ -18,6 +18,7 @@ const SUBCLASS: usize = 0x47504155; const ADDRESS_SUBCLASS: usize = 0x47504156; const ADDRESS_HEIGHT: i32 = 24; const TOOLBAR_HEIGHT: i32 = 34; +const RECOVERY_PADDING: i32 = 4; const RETRY: usize = 101; const PROCEED: usize = 102; const CANCEL: usize = 103; @@ -31,6 +32,7 @@ pub(super) struct Controls { proceed: HWND, cancel: HWND, status: Cell, + recovery_bounds: Cell, font: Cell>, } @@ -75,6 +77,7 @@ impl Controls { proceed: child(w!("BUTTON"), "Continue Anyway…", WS_TABSTOP, PROCEED)?, cancel: child(w!("BUTTON"), "Cancel", WS_TABSTOP, CANCEL)?, status: Cell::new(RecoveryStatus::Hidden), + recovery_bounds: Cell::new(RECT::default()), font: Cell::new(None), }; unsafe { @@ -186,33 +189,63 @@ impl Controls { Some(LPARAM(&text as *const _ as isize)), ); let status = self.status.get(); - let header = if status == RecoveryStatus::Hidden { - TOOLBAR_HEIGHT - } else { - TOOLBAR_HEIGHT + 68 - }; - MoveWindow( - self.message, - px(8), - px(TOOLBAR_HEIGHT + 2), - (width - px(16)).max(0), - px(38), - true, - )?; - let mut right = width - px(8); - for (hwnd, visible, size) in [ + let buttons = [ (self.cancel, status.blocks_page(), 70), (self.proceed, status.can_continue(), 136), (self.retry, status.can_retry(), 84), - ] { + ]; + let button_width: i32 = buttons + .iter() + .filter(|(_, visible, _)| *visible) + .map(|(_, _, size)| size + 6) + .sum(); + let stacked = width < px(700) && button_width > 0; + let message_height = if status.detail().is_empty() { 20 } else { 40 }; + let row_height = message_height.max(28); + let recovery_content_height = if stacked { message_height + 8 + 28 } else { row_height }; + // Equal padding surrounds the controls; the divider occupies one physical pixel. + let recovery_height = px(recovery_content_height + 2 * RECOVERY_PADDING) + 1; + let header_height = if status == RecoveryStatus::Hidden { + px(TOOLBAR_HEIGHT) + } else { + px(TOOLBAR_HEIGHT) + recovery_height + }; + self.recovery_bounds.set(RECT { + left: 0, + top: px(TOOLBAR_HEIGHT), + right: width, + bottom: header_height, + }); + let message_width = if stacked { + width - px(24) + } else { + width - px(24 + button_width) + }; + MoveWindow( + self.message, + px(12), + px(TOOLBAR_HEIGHT + RECOVERY_PADDING + if stacked { 0 } else { (row_height - message_height) / 2 }), + message_width.max(0), + px(message_height), + true, + )?; + let button_top = TOOLBAR_HEIGHT + + RECOVERY_PADDING + + if stacked { + message_height + 8 + } else { + (row_height - 28) / 2 + }; + let mut right = width - px(8); + for (hwnd, visible, size) in buttons { if visible { right -= px(size); - MoveWindow(hwnd, right, px(TOOLBAR_HEIGHT + 38), px(size), px(28), true)?; + MoveWindow(hwnd, right, px(button_top), px(size), px(28), true)?; right -= px(6); } } - let content_height = (bounds.bottom - px(header)).max(0); - MoveWindow(self.webview_host, 0, px(header), width, content_height, true)?; + let content_height = (bounds.bottom - header_height).max(0); + MoveWindow(self.webview_host, 0, header_height, width, content_height, true)?; state.controller.SetBounds(RECT { left: 0, top: 0, @@ -291,12 +324,36 @@ unsafe extern "system" fn window_proc( key: usize, ) -> LRESULT { let state = STATES.with_borrow(|states| states.get(&key).cloned()); + if msg == WM_CTLCOLORSTATIC { + unsafe { + let dc = HDC(wparam.0 as *mut _); + let is_message = state + .as_ref() + .is_some_and(|state| state.controls.message.0 as isize == lparam.0); + let background = if is_message { COLOR_3DFACE } else { COLOR_WINDOW }; + SetTextColor(dc, COLORREF(GetSysColor(COLOR_WINDOWTEXT))); + SetBkColor(dc, COLORREF(GetSysColor(background))); + return LRESULT(GetSysColorBrush(background).0 as isize); + } + } // Paint the native toolbar and recovery surface outside the child webview. if msg == WM_ERASEBKGND { unsafe { let mut bounds = RECT::default(); if GetClientRect(hwnd, &mut bounds).is_ok() { - FillRect(HDC(wparam.0 as *mut _), &bounds, GetSysColorBrush(COLOR_WINDOW)); + let dc = HDC(wparam.0 as *mut _); + FillRect(dc, &bounds, GetSysColorBrush(COLOR_WINDOW)); + if let Some(state) = &state { + let row = state.controls.recovery_bounds.get(); + if row.bottom > row.top { + FillRect(dc, &row, GetSysColorBrush(COLOR_3DFACE)); + let divider = RECT { + top: row.bottom - 1, + ..row + }; + FillRect(dc, ÷r, GetSysColorBrush(COLOR_3DLIGHT)); + } + } } } return LRESULT(1); diff --git a/crates/browser-launcher/Cargo.toml b/crates/browser-launcher/Cargo.toml index d0a0973..354f324 100644 --- a/crates/browser-launcher/Cargo.toml +++ b/crates/browser-launcher/Cargo.toml @@ -10,9 +10,7 @@ license = "MIT" [dependencies] anyhow.workspace = true log.workspace = true -open = { version = "5", optional = true } webbrowser = { version = "1", optional = true } -which = { workspace = true, optional = true } [features] default = [] @@ -20,3 +18,9 @@ launcher = ["dep:open", "dep:webbrowser", "dep:which", "dep:winreg"] [target.'cfg(windows)'.dependencies] winreg = { version = "0.55", optional = true } + +[target.'cfg(unix)'.dependencies] +open = { version = "5", optional = true } + +[target.'cfg(all(unix, not(target_os = "macos")))'.dependencies] +which = { workspace = true, optional = true } diff --git a/crates/gpapi/Cargo.toml b/crates/gpapi/Cargo.toml index 78c0a1f..9440df7 100644 --- a/crates/gpapi/Cargo.toml +++ b/crates/gpapi/Cargo.toml @@ -46,6 +46,9 @@ snow.workspace = true zeroize = { workspace = true, features = ["serde"] } getrandom = "0.4" +# Used only by the opt-in certificate interoperability tests. +openssl = { workspace = true, optional = true } + # Optional dependencies for features tauri = { workspace = true, optional = true } clap = { workspace = true, optional = true } @@ -76,7 +79,6 @@ cc = "1" pkg-config = "0.3" [dev-dependencies] -openssl.workspace = true libloading = "0.9" proptest.workspace = true tokio = { workspace = true, features = ["test-util"] } @@ -87,14 +89,32 @@ desktop = ["tokio/process", "tokio/signal", "dep:directories", "dep:nix", "dep:u tauri = ["desktop", "dep:tauri", "dep:gtk", "dep:os_info"] clap = ["desktop", "dep:clap", "dep:clap-verbosity-flag"] webview-auth = [] -logger = ["desktop", "dep:env_logger", "dep:log-reload", "dep:oslog"] +openssl-tests = ["dep:openssl"] +logger = ["desktop", "dep:env_logger", "dep:log-reload", "dep:oslog", "dep:file-rotate"] [target.'cfg(unix)'.dependencies] nix = { version = "0.31", features = ["fs", "signal", "process"], optional = true } uzers = { workspace = true, optional = true } [target.'cfg(windows)'.dependencies] +file-rotate = { version = "0.8.0", optional = true } windows-sys = { version = "0.61", features = ["Win32_NetworkManagement_IpHelper", "Win32_NetworkManagement_Ndis", "Win32_Networking_WinSock", "Win32_Foundation", "Win32_Security", "Win32_Security_Authorization", "Win32_Storage_FileSystem", "Win32_System_Pipes", "Win32_System_Threading", "Win32_System_Services", "Win32_Globalization", "Win32_System_Environment", "Win32_System_JobObjects", "Win32_System_IO"] } [target.'cfg(windows)'.dev-dependencies] windows-sys = { version = "0.61", features = ["Win32_UI_Shell"] } + +[[test]] +name = "certificate_compatibility" +required-features = ["openssl-tests"] + +[[test]] +name = "client_certificate_chain" +required-features = ["openssl-tests"] + +[[test]] +name = "client_certificate_extensions" +required-features = ["openssl-tests"] + +[[test]] +name = "client_certificate_tls12_hash" +required-features = ["openssl-tests"] diff --git a/crates/gpapi/README.md b/crates/gpapi/README.md new file mode 100644 index 0000000..efc4e03 --- /dev/null +++ b/crates/gpapi/README.md @@ -0,0 +1,16 @@ +# gpapi tests + +Ordinary tests do not require OpenSSL. To run the Windows logger regression test: + +```sh +cargo test -p gpapi --features logger --lib logger::windows::tests +``` + +The certificate interoperability suite uses OpenSSL as an independent TLS and +signature implementation. Full CI enables it explicitly: + +```sh +cargo test -p gpapi --features logger,openssl-tests +``` + +This optional suite requires OpenSSL development headers and libraries. diff --git a/crates/gpapi/src/error/server_tls.rs b/crates/gpapi/src/error/server_tls.rs index ec13926..75e4dc8 100644 --- a/crates/gpapi/src/error/server_tls.rs +++ b/crates/gpapi/src/error/server_tls.rs @@ -109,6 +109,7 @@ fn classify_with_identity(error: &(dyn Error + 'static), has_client_identity: bo #[cfg(test)] mod tests { use super::*; + #[cfg(feature = "openssl-tests")] use openssl::{ asn1::Asn1Time, hash::MessageDigest, @@ -180,10 +181,12 @@ mod tests { ); } + #[cfg(feature = "openssl-tests")] fn server(tls: bool) -> (String, thread::JoinHandle<()>) { server_with_client_auth(tls, SslVerifyMode::NONE) } + #[cfg(feature = "openssl-tests")] fn server_with_client_auth(tls: bool, verify: SslVerifyMode) -> (String, thread::JoinHandle<()>) { let key = PKey::from_rsa(Rsa::generate(2048).unwrap()).unwrap(); let mut name = X509NameBuilder::new().unwrap(); @@ -233,6 +236,7 @@ mod tests { (address, worker) } + #[cfg(feature = "openssl-tests")] #[tokio::test] async fn prelogin_returns_typed_certificate_failure_with_only_the_server_origin() { use crate::{ @@ -254,6 +258,7 @@ mod tests { assert_eq!(tls.server, address); } + #[cfg(feature = "openssl-tests")] #[tokio::test] async fn certificate_bypass_allows_prelogin() { use crate::{ @@ -270,6 +275,7 @@ mod tests { assert!(matches!(result.unwrap(), crate::portal::Prelogin::Saml(_))); } + #[cfg(feature = "openssl-tests")] #[tokio::test] async fn incompatible_tls_is_not_a_certificate_error_even_with_bypass() { let (address, worker) = server(false); @@ -303,7 +309,7 @@ mod tests { assert_eq!(classify(&error), None); } - #[cfg(feature = "desktop")] + #[cfg(all(feature = "desktop", unix))] #[test] fn rendering_recovery_retains_client_certificate_requirement() { use crate::process::rendering_recovery::{RecoveryState, RenderingCrash}; @@ -330,6 +336,7 @@ mod tests { ); } + #[cfg(feature = "openssl-tests")] #[tokio::test] async fn required_client_certificate_is_not_bypassed_by_ignoring_server_trust() { use crate::{ @@ -371,6 +378,7 @@ mod tests { } } + #[cfg(feature = "openssl-tests")] #[tokio::test] async fn prelogin_explains_peer_rejection_of_an_already_configured_identity() { use crate::{ @@ -403,6 +411,7 @@ mod tests { assert!(!error.to_string().contains("passphrase")); } + #[cfg(feature = "openssl-tests")] #[tokio::test] async fn prelogin_accepts_a_valid_identity_and_an_optional_certificate_request() { use crate::{ @@ -435,6 +444,7 @@ mod tests { } } + #[cfg(feature = "openssl-tests")] #[tokio::test] async fn imported_identity_formats_complete_mutual_tls_prelogin() { use crate::{ diff --git a/crates/gpapi/src/logger.rs b/crates/gpapi/src/logger.rs index c6c3f46..adba6e0 100644 --- a/crates/gpapi/src/logger.rs +++ b/crates/gpapi/src/logger.rs @@ -12,6 +12,20 @@ pub const MACOS_UNIFIED_LOG_BACKEND: &str = "macos-unified"; type BoxedLogger = Box; static LOG_HANDLE: OnceLock>> = OnceLock::new(); +#[cfg(windows)] +mod windows; +#[cfg(windows)] +pub use windows::init_file; + +/// Keep helper diagnostics with the application's records when a file logger owns them. +pub fn diagnostic_writer() -> Box { + #[cfg(windows)] + if let Some(writer) = windows::diagnostic_writer() { + return writer; + } + Box::new(std::io::stderr()) +} + pub fn init(level: Level, subsystem: &str, category: &str, log_format: LogFormat) { #[cfg(target_os = "macos")] if log_format == LogFormat::Text && macos_unified_log_enabled() { diff --git a/crates/gpapi/src/logger/windows.rs b/crates/gpapi/src/logger/windows.rs new file mode 100644 index 0000000..c4d3531 --- /dev/null +++ b/crates/gpapi/src/logger/windows.rs @@ -0,0 +1,98 @@ +use file_rotate::{ContentLimit, FileRotate, compression::Compression, suffix::AppendCount}; +use std::{ + fs::{self, OpenOptions}, + io::{self, Write}, + path::Path, + sync::{Arc, Mutex, OnceLock}, +}; + +const ROTATE_BYTES: usize = 5 * 1024 * 1024; +const ARCHIVE_COUNT: usize = 3; +static DIAGNOSTICS: OnceLock = OnceLock::new(); + +#[derive(Clone)] +struct DiagnosticWriter(Arc>>); + +impl DiagnosticWriter { + fn open(path: &Path) -> io::Result { + if let Some(parent) = path.parent().filter(|parent| !parent.as_os_str().is_empty()) { + fs::create_dir_all(parent)?; + } + // FileRotate's constructor suppresses open errors, so check the destination first. + OpenOptions::new().create(true).append(true).open(path)?; + Ok(Self(Arc::new(Mutex::new(FileRotate::new( + path, + AppendCount::new(ARCHIVE_COUNT), + ContentLimit::BytesSurpassed(ROTATE_BYTES), + Compression::None, + None, + ))))) + } +} + +impl Write for DiagnosticWriter { + fn write(&mut self, bytes: &[u8]) -> io::Result { + self + .0 + .lock() + .map_err(|_| io::Error::other("Log writer lock is poisoned"))? + .write(bytes) + } + + fn flush(&mut self) -> io::Result<()> { + self + .0 + .lock() + .map_err(|_| io::Error::other("Log writer lock is poisoned"))? + .flush() + } +} + +pub fn init_file(path: &Path, level: log::Level) -> io::Result<()> { + let writer = DiagnosticWriter::open(path)?; + let logger = super::build_env_logger(crate::log_format::LogFormat::Text) + .target(env_logger::Target::Pipe(Box::new(writer.clone()))) + .build(); + DIAGNOSTICS + .set(writer) + .map_err(|_| io::Error::other("File logging is already initialized"))?; + super::init_with_logger(level, logger); + Ok(()) +} + +pub(super) fn diagnostic_writer() -> Option> { + DIAGNOSTICS + .get() + .map(|writer| Box::new(writer.clone()) as Box) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn gui_and_helper_writers_share_rotation_and_keep_only_three_archives() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("logs/gui.log"); + let mut gui = DiagnosticWriter::open(&path).unwrap(); + let mut helper = gui.clone(); + for marker in b'0'..=b'5' { + let writer = if marker % 2 == 0 { &mut gui } else { &mut helper }; + writer.write_all(&vec![marker; ROTATE_BYTES + 1]).unwrap(); + } + helper.flush().unwrap(); + drop((gui, helper)); + assert_eq!(fs::read(&path).unwrap(), vec![b'5'; ROTATE_BYTES + 1]); + for (suffix, marker) in [(1, b'4'), (2, b'3'), (3, b'2')] { + assert_eq!( + fs::read(path.with_extension(format!("log.{suffix}"))).unwrap(), + vec![marker; ROTATE_BYTES + 1] + ); + } + assert_eq!(fs::read_dir(path.parent().unwrap()).unwrap().count(), 4); + let mut reopened = DiagnosticWriter::open(&path).unwrap(); + reopened.write_all(b"after restart\n").unwrap(); + reopened.flush().unwrap(); + assert_eq!(fs::read(&path).unwrap(), b"after restart\n"); + } +} diff --git a/crates/gpapi/src/os_profile/desktop/windows.rs b/crates/gpapi/src/os_profile/desktop/windows.rs index 3ddb825..904eb62 100644 --- a/crates/gpapi/src/os_profile/desktop/windows.rs +++ b/crates/gpapi/src/os_profile/desktop/windows.rs @@ -1,4 +1,5 @@ -use std::process::Command; +use std::{os::windows::process::CommandExt, process::Command}; +use windows_sys::Win32::System::Threading::CREATE_NO_WINDOW; use super::{ClientOs, NativeHostIdentitySnapshot, fallback_hostname, primary_mac_colon, resolve_host_id}; @@ -36,6 +37,7 @@ impl RuntimeNativeHostIdentity { fn collect_windows_serial_number() -> Option { let output = Command::new("wmic") + .creation_flags(CREATE_NO_WINDOW) .args(["bios", "get", "serialnumber"]) .output() .ok()?; @@ -54,7 +56,11 @@ fn windows_machine_seed() -> Option { } fn collect_windows_csproduct_uuid() -> Option { - let output = Command::new("wmic").args(["csproduct", "get", "uuid"]).output().ok()?; + let output = Command::new("wmic") + .creation_flags(CREATE_NO_WINDOW) + .args(["csproduct", "get", "uuid"]) + .output() + .ok()?; let stdout = String::from_utf8(output.stdout).ok()?; stdout @@ -67,6 +73,7 @@ fn collect_windows_csproduct_uuid() -> Option { fn collect_windows_machine_guid() -> Option { let output = Command::new("reg") + .creation_flags(CREATE_NO_WINDOW) .args(["query", r"HKLM\SOFTWARE\Microsoft\Cryptography", "/v", "MachineGuid"]) .output() .ok()?; diff --git a/crates/gpapi/src/process/auth_launcher.rs b/crates/gpapi/src/process/auth_launcher.rs index af22f1b..c54028a 100644 --- a/crates/gpapi/src/process/auth_launcher.rs +++ b/crates/gpapi/src/process/auth_launcher.rs @@ -306,12 +306,16 @@ impl<'a> SamlAuthLauncher<'a> { } }; let mut diagnostic = StderrDiagnostic::default(); + #[cfg(feature = "logger")] + let mut stderr = crate::logger::diagnostic_writer(); + #[cfg(not(feature = "logger"))] + let mut stderr = std::io::stderr(); let output = run_observed( command, &check, Some(MAX_AUTH_RESULT_BYTES), &mut |bytes| diagnostic.push(bytes), - &mut std::io::stderr(), + &mut stderr, stdin, )?; Ok::<_, std::io::Error>((output.output, diagnostic.matched())) @@ -366,11 +370,14 @@ fn decode_auth_output(output: std::process::Output, rendering_failure: bool) -> mod tests { use super::*; use crate::os_profile::{ClientOs, OsProfileBuilder}; + #[cfg(unix)] + use std::os::unix::process::ExitStatusExt; + #[cfg(windows)] + use std::os::windows::process::ExitStatusExt; #[test] fn server_tls_result_survives_process_decoding_as_a_typed_error() { use crate::error::{ServerTlsError, ServerTlsErrorKind}; - use std::os::unix::process::ExitStatusExt; let output = std::process::Output { status: std::process::ExitStatus::from_raw(0), stdout: br#"{"serverTlsError":{"server":"https://vpn.example.com:8443","kind":"certificate"}}"#.to_vec(), @@ -389,7 +396,6 @@ mod tests { #[test] fn client_certificate_required_result_survives_process_decoding() { use crate::error::{ServerTlsError, ServerTlsErrorKind}; - use std::os::unix::process::ExitStatusExt; let output = std::process::Output { status: std::process::ExitStatus::from_raw(0), stdout: br#"{"serverTlsError":{"server":"https://vpn.example.com","kind":"clientCertificateRequired"}}"#.to_vec(), @@ -549,11 +555,14 @@ mod tests { #[test] fn failed_authenticator_discards_partial_or_valid_stdout_before_decoding() { - use std::os::unix::process::ExitStatusExt; + #[cfg(unix)] + let status = std::process::ExitStatus::from_raw(71 << 8); + #[cfg(windows)] + let status = std::process::ExitStatus::from_raw(0xC0000005); for stdout in [b"{partial".to_vec(), br#"{"cancelled":null}"#.to_vec()] { let error = decode_auth_output( std::process::Output { - status: std::process::ExitStatus::from_raw(71 << 8), + status, stdout, stderr: Vec::new(), }, @@ -566,7 +575,6 @@ mod tests { #[test] fn successful_malformed_auth_output_is_not_a_rendering_crash() { - use std::os::unix::process::ExitStatusExt; let error = decode_auth_output( std::process::Output { status: std::process::ExitStatus::from_raw(0), @@ -580,6 +588,7 @@ mod tests { assert_eq!(error.to_string(), "Failed to parse auth data"); } + #[cfg(unix)] #[tokio::test] async fn custom_authenticator_crash_does_not_request_recovery() { use std::os::unix::fs::PermissionsExt; @@ -615,8 +624,11 @@ mod tests { std::fs::write(&custom, "custom").unwrap(); assert!(is_bundled_authenticator(&bundled, &bundled)); assert!(!is_bundled_authenticator(&custom, &bundled)); - let alias = directory.path().join("auth-alias"); - std::os::unix::fs::symlink(&bundled, &alias).unwrap(); - assert!(is_bundled_authenticator(&alias, &bundled)); + #[cfg(unix)] + { + let alias = directory.path().join("auth-alias"); + std::os::unix::fs::symlink(&bundled, &alias).unwrap(); + assert!(is_bundled_authenticator(&alias, &bundled)); + } } } diff --git a/crates/gpapi/src/process/mod.rs b/crates/gpapi/src/process/mod.rs index 5d78dcb..2568c76 100644 --- a/crates/gpapi/src/process/mod.rs +++ b/crates/gpapi/src/process/mod.rs @@ -22,9 +22,9 @@ pub mod auth_launcher; pub mod desktop_launcher; #[cfg(unix)] pub mod gui_launcher; -#[cfg(any(target_os = "linux", test))] +#[cfg(any(target_os = "linux", all(test, unix)))] pub mod gui_switch; -#[cfg(any(target_os = "linux", test))] +#[cfg(any(target_os = "linux", all(test, unix)))] mod nsh_runtime; #[cfg(unix)] pub mod users; diff --git a/crates/gpapi/src/process/rendering_recovery.rs b/crates/gpapi/src/process/rendering_recovery.rs index 49ef3f0..615668f 100644 --- a/crates/gpapi/src/process/rendering_recovery.rs +++ b/crates/gpapi/src/process/rendering_recovery.rs @@ -198,6 +198,7 @@ mod tests { assert!(!eligible_with_inheritance(&command, false)); } + #[cfg(unix)] #[test] fn recovery_is_once_and_preserves_cancellation_and_both_failures() { use std::os::unix::process::ExitStatusExt; @@ -219,6 +220,7 @@ mod tests { assert!(error.to_string().contains("71")); assert!(error.to_string().contains("second exit 72")); } + #[cfg(unix)] #[test] fn explicit_termination_is_not_a_rendering_crash() { use std::os::unix::process::ExitStatusExt; diff --git a/crates/gpapi/src/session/desktop/network/native.rs b/crates/gpapi/src/session/desktop/network/native.rs index a495feb..8d5a175 100644 --- a/crates/gpapi/src/session/desktop/network/native.rs +++ b/crates/gpapi/src/session/desktop/network/native.rs @@ -172,6 +172,7 @@ mod tests { ); } + #[cfg(unix)] #[tokio::test] async fn cancellation_kills_and_joins_the_running_resolver_process() { let file = tempfile::NamedTempFile::new().unwrap(); diff --git a/crates/gpapi/src/utils/certificate/native_key.rs b/crates/gpapi/src/utils/certificate/native_key.rs index 802bcfa..71e2dc0 100644 --- a/crates/gpapi/src/utils/certificate/native_key.rs +++ b/crates/gpapi/src/utils/certificate/native_key.rs @@ -204,6 +204,7 @@ impl Signer for ClientSigner { #[cfg(test)] mod tests { use super::*; + #[cfg(feature = "openssl-tests")] use openssl::{ hash::MessageDigest, pkey::PKey, @@ -220,6 +221,7 @@ mod tests { .unwrap() } + #[cfg(feature = "openssl-tests")] fn native_key(bytes: &[u8]) -> ClientKey { let key = rustls_pemfile::private_key(&mut std::io::Cursor::new(bytes)) .unwrap() @@ -227,6 +229,7 @@ mod tests { ClientKey::load(&key).unwrap() } + #[cfg(feature = "openssl-tests")] #[test] fn rsa_signatures_use_the_offered_scheme_and_tls_pss_salt_length() { let bytes = fixture("rsa-pkcs8.pem"); @@ -255,6 +258,7 @@ mod tests { assert!(key.choose_scheme(&[SignatureScheme::ECDSA_NISTP256_SHA256]).is_none()); } + #[cfg(feature = "openssl-tests")] #[test] fn p256_signatures_verify_with_an_independent_backend() { let bytes = fixture("ec-pkcs8.pem"); @@ -281,6 +285,7 @@ mod tests { } } + #[cfg(feature = "openssl-tests")] #[test] fn a_key_remains_usable_when_shared_clients_sign_concurrently() { let key = native_key(&fixture("rsa-pkcs8.pem")); diff --git a/crates/gpapi/src/utils/request.rs b/crates/gpapi/src/utils/request.rs index 97cc05f..a345a41 100644 --- a/crates/gpapi/src/utils/request.rs +++ b/crates/gpapi/src/utils/request.rs @@ -266,6 +266,7 @@ mod tests { #[test] fn unencrypted_key_ignores_unused_password_and_archive_owned_file_is_private() { + #[cfg(unix)] use std::os::unix::fs::PermissionsExt; let identity = ClientIdentity::from_data( Zeroizing::new(CERTIFICATE.to_vec()), @@ -280,6 +281,7 @@ mod tests { let path = files.certificate().to_owned(); assert!(path.ends_with(".p12")); assert!(files.key().is_none()); + #[cfg(unix)] assert_eq!(fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600); drop(files); assert!(!Path::new(&path).exists()); diff --git a/crates/gpapi/tests/identity_encoding.rs b/crates/gpapi/tests/identity_encoding.rs index 1f76146..0ce6f4d 100644 --- a/crates/gpapi/tests/identity_encoding.rs +++ b/crates/gpapi/tests/identity_encoding.rs @@ -93,12 +93,19 @@ fn traditional_encrypted_pem_preserves_password_errors() { let result = load(&certificate, &key, password); if password == Some(PASSWORD) { let identity = result.unwrap_or_else(|error| panic!("{key:?}: {error}")); - let actual = openssl::pkey::PKey::private_key_from_pem(identity.key_data().unwrap()).unwrap(); - let expected = openssl::pkey::PKey::private_key_from_pem(&bytes(&format!("{algorithm}-pkcs8.pem"))).unwrap(); - assert!( - actual.public_eq(&expected), - "{key:?}: imported key differs from the fixture" - ); + let public_key = |pem: &[u8]| { + let key = rustls_pemfile::private_key(&mut std::io::Cursor::new(pem)) + .unwrap() + .unwrap(); + rustls::crypto::ring::sign::any_supported_type(&key) + .unwrap() + .public_key() + .unwrap() + .into_owned() + }; + let actual = public_key(identity.key_data().unwrap()); + let expected = public_key(&bytes(&format!("{algorithm}-pkcs8.pem"))); + assert!(actual == expected, "{key:?}: imported key differs from the fixture"); assert!(identity.key_password().is_none()); } else { let error = result.unwrap_err(); diff --git a/packaging/windows/machine-install.ps1 b/packaging/windows/machine-install.ps1 index acfb4d2..058bce7 100644 --- a/packaging/windows/machine-install.ps1 +++ b/packaging/windows/machine-install.ps1 @@ -149,7 +149,7 @@ function Set-InstallationMetadata([string]$InstalledVersion) { $shortcut = $shell.CreateShortcut($shortcutPath) $shortcut.TargetPath = Join-Path $destination 'gpgui.exe' $shortcut.WorkingDirectory = $destination - $shortcut.Description = 'GP Connect' + $shortcut.Description = 'A GUI client for GlobalProtect VPN' $shortcut.IconLocation = (Join-Path $destination 'gpgui.exe') + ',0' $shortcut.Save() if (Test-Path -LiteralPath (Join-Path $destination 'uninstall.exe')) { diff --git a/scripts/test-private-desktop.sh b/scripts/test-private-desktop.sh index 20b7ce8..008c3bc 100644 --- a/scripts/test-private-desktop.sh +++ b/scripts/test-private-desktop.sh @@ -60,6 +60,6 @@ run_stage 'Frontend tests' 5m \ run_stage 'Frontend build' 10m \ docker exec --workdir "$workspace" "$container" pnpm --filter gpgui build run_stage 'Compile Rust tests' 30m \ - docker exec --workdir "$workspace" "$container" cargo test --workspace --locked --no-run + docker exec --workdir "$workspace" "$container" cargo test --workspace --locked --features gpapi/openssl-tests --no-run run_stage 'Rust tests' 10m \ - docker exec --workdir "$workspace" "$container" cargo test --workspace --locked + docker exec --workdir "$workspace" "$container" cargo test --workspace --locked --features gpapi/openssl-tests diff --git a/scripts/tests/windows-webview.ps1 b/scripts/tests/windows-webview.ps1 index 49b13ce..02014f4 100644 --- a/scripts/tests/windows-webview.ps1 +++ b/scripts/tests/windows-webview.ps1 @@ -1,4 +1,5 @@ # Run in an unlocked Windows desktop. Start windows-webview-server.py first. +# Use a GUI-subsystem binary; ordinary debug builds intentionally open a console. [CmdletBinding()] param( [Parameter(Mandatory)][string]$Binary, @@ -10,13 +11,29 @@ Add-Type -AssemblyName UIAutomationClient Add-Type -AssemblyName UIAutomationTypes Add-Type @' using System; +using System.Collections.Generic; using System.Runtime.InteropServices; +using System.Text; public class GPWebviewFixture { [StructLayout(LayoutKind.Sequential)] public struct POINT { public int X, Y; } [DllImport("user32.dll")] public static extern bool PostMessage(IntPtr h, uint m, IntPtr w, IntPtr l); [DllImport("user32.dll")] public static extern IntPtr WindowFromPoint(POINT p); [DllImport("user32.dll")] public static extern bool SetWindowPos(IntPtr h, IntPtr after, int x, int y, int w, int height, uint flags); [DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr h); + delegate bool WindowCallback(IntPtr h, IntPtr l); + [DllImport("user32.dll")] static extern bool EnumWindows(WindowCallback callback, IntPtr l); + [DllImport("user32.dll")] static extern bool IsWindowVisible(IntPtr h); + [DllImport("user32.dll", CharSet = CharSet.Unicode)] static extern int GetClassName(IntPtr h, StringBuilder name, int length); + public static long[] ConsoleWindows() { + var windows = new List(); + EnumWindows((h, l) => { + var name = new StringBuilder(256); + GetClassName(h, name, name.Capacity); + if (IsWindowVisible(h) && (name.ToString() == "ConsoleWindowClass" || name.ToString() == "CASCADIA_HOSTING_WINDOW_CLASS")) windows.Add(h.ToInt64()); + return true; + }, IntPtr.Zero); + return windows.ToArray(); + } } '@ $work = Join-Path $env:TEMP ('gp-webview-test-' + [Guid]::NewGuid().ToString('N')) @@ -31,8 +48,19 @@ function Start-Auth([string]$Request, [string[]]$Extra = @()) { $script:stdout = Join-Path $work "$script:index.json" $script:stderr = Join-Path $work "$script:index.log" $arguments = @($FixtureUrl, '--saml-request', ('"' + $Request + '"'), '--window-title', '"GP Auth Fixture"', '--os', 'Windows') + $Extra + $consoles = @([GPWebviewFixture]::ConsoleWindows()) $script:current = Start-Process -FilePath $Binary -ArgumentList $arguments -PassThru -RedirectStandardOutput $script:stdout -RedirectStandardError $script:stderr $null = $script:current.Handle + # Watch startup: device-information commands finish before the sign-in window appears. + $deadline = [DateTime]::UtcNow.AddSeconds(15) + do { + foreach ($console in [GPWebviewFixture]::ConsoleWindows()) { + if ($console -notin $consoles) { throw "Authentication opened a console in case $script:index" } + } + if ($script:current.HasExited -or $script:current.MainWindowHandle -ne [IntPtr]::Zero) { break } + Start-Sleep -Milliseconds 20 + $script:current.Refresh() + } while ([DateTime]::UtcNow -lt $deadline) } function Finish-Auth([bool]$Success) { if (!$script:current.WaitForExit(20000)) { throw "Authentication timed out in case $script:index" } @@ -128,6 +156,11 @@ try { Invoke-Control 'Cancel' Finish-Auth $false 'PASS: rejected sign-in recovery' + Start-Auth ($FixtureUrl + '/missing') + $null = Wait-Control ('Couldn' + [char]0x2019 + 't load sign-in.') + Invoke-Control 'Try Again' + Finish-Auth $true + 'PASS: initial page-load failure and fresh-prelogin retry' Start-Auth ($FixtureUrl + '/temporary') Finish-Auth $true 'PASS: automatic fresh-prelogin recovery'