fix(windows): refine authentication UI and rotate desktop logs

Brand browser callbacks as GP Connect Login and refine the native recovery controls. Share bounded rotating logs between the GUI and authentication helper.

Make OpenSSL interoperability tests opt-in, retain them in full CI, and correct platform-specific test guards and dependencies.
This commit is contained in:
Kevin Yue committed 2026-11-18 13:56:12 +08:00
1 parent 731101b4bc
commit f7fdc53be9
23 files changed
+344 -60

No files matched your search

+11 -1
View File
@@ -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::{
+14
View File
@@ -12,6 +12,20 @@ pub const MACOS_UNIFIED_LOG_BACKEND: &str = "macos-unified";
type BoxedLogger = Box<dyn Log + Send + Sync>;
static LOG_HANDLE: OnceLock<ReloadHandle<log_reload::LevelFilter<BoxedLogger>>> = 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<dyn std::io::Write + Send> {
#[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() {
+98
View File
@@ -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<DiagnosticWriter> = OnceLock::new();
#[derive(Clone)]
struct DiagnosticWriter(Arc<Mutex<FileRotate<AppendCount>>>);
impl DiagnosticWriter {
fn open(path: &Path) -> io::Result<Self> {
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<usize> {
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<Box<dyn Write + Send>> {
DIAGNOSTICS
.get()
.map(|writer| Box::new(writer.clone()) as Box<dyn Write + Send>)
}
#[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");
}
}
@@ -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<String> {
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<String> {
}
fn collect_windows_csproduct_uuid() -> Option<String> {
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<String> {
fn collect_windows_machine_guid() -> Option<String> {
let output = Command::new("reg")
.creation_flags(CREATE_NO_WINDOW)
.args(["query", r"HKLM\SOFTWARE\Microsoft\Cryptography", "/v", "MachineGuid"])
.output()
.ok()?;
+21 -9
View File
@@ -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));
}
}
}
+2 -2
View File
@@ -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;
@@ -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;
@@ -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();
@@ -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"));
+2
View File
@@ -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());