fix(windows): restore browser auth focus and configure tunnel branding

This commit is contained in:
Kevin Yue committed 2026-11-18 13:56:13 +08:00
1 parent 8bb061d53f
commit ab3908b809
8 files changed
+72 -5

No files matched your search

Generated
+1
View File
@@ -321,6 +321,7 @@ dependencies = [
"webkit2gtk", "webkit2gtk",
"webview2-com", "webview2-com",
"windows", "windows",
"windows-sys 0.61.2",
"winreg 0.55.0", "winreg 0.55.0",
] ]
+1
View File
@@ -102,6 +102,7 @@ tempfile.workspace = true
uzers = { workspace = true, optional = true } uzers = { workspace = true, optional = true }
[target.'cfg(windows)'.dependencies] [target.'cfg(windows)'.dependencies]
windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_System_Pipes", "Win32_UI_WindowsAndMessaging"] }
# Child webviews let the Windows host own layout beside native controls. # Child webviews let the Windows host own layout beside native controls.
tauri = { workspace = true, optional = true, features = ["unstable"] } tauri = { workspace = true, optional = true, features = ["unstable"] }
webview2-com = { version = "0.39", optional = true } webview2-com = { version = "0.39", optional = true }
+40 -1
View File
@@ -1,15 +1,19 @@
//! Per-user Windows named pipe for browser authentication callbacks. //! Per-user Windows named pipe for browser authentication callbacks.
use anyhow::{Context, bail}; use anyhow::{Context, bail};
use gpapi::{auth::SamlAuthData, error::AuthDataParseError}; use gpapi::{auth::SamlAuthData, error::AuthDataParseError};
use std::{io, os::windows::io::AsRawHandle};
use tokio::{ use tokio::{
io::{AsyncReadExt, AsyncWriteExt}, io::{AsyncReadExt, AsyncWriteExt},
net::windows::named_pipe::{ClientOptions, NamedPipeServer}, net::windows::named_pipe::{ClientOptions, NamedPipeClient, NamedPipeServer},
time::timeout, time::timeout,
}; };
#[path = "protocol.rs"] #[path = "protocol.rs"]
mod protocol; mod protocol;
pub use protocol::validate_auth_callback; pub use protocol::validate_auth_callback;
use protocol::*; use protocol::*;
use windows_sys::Win32::{
System::Pipes::GetNamedPipeServerProcessId, UI::WindowsAndMessaging::AllowSetForegroundWindow,
};
pub struct AuthCallbackReceiver { pub struct AuthCallbackReceiver {
listener: NamedPipeServer, listener: NamedPipeServer,
@@ -52,6 +56,9 @@ impl AuthCallbackReceiver {
let _ = timeout(IO_TIMEOUT, stream.read_u8()).await; let _ = timeout(IO_TIMEOUT, stream.read_u8()).await;
self.listener.disconnect()?; self.listener.disconnect()?;
if let Some(result) = result { if let Some(result) = result {
if let Err(error) = delegate_foreground_to_parent() {
log::debug!("Could not delegate authentication foreground permission to the parent: {error}");
}
return result; return result;
} }
} }
@@ -76,6 +83,12 @@ pub async fn forward_auth_callback(callback: &str) -> anyhow::Result<()> {
stream.write_all(callback.as_bytes()).await?; stream.write_all(callback.as_bytes()).await?;
let version = stream.read_u8().await?; let version = stream.read_u8().await?;
let status = stream.read_u8().await?; let status = stream.read_u8().await?;
// The receiver waits for our acknowledgement before returning to its caller.
if version == PROTOCOL_VERSION && status == STATUS_ACCEPTED {
if let Err(error) = delegate_foreground_to_receiver(&stream) {
log::debug!("Could not delegate browser foreground permission to the authenticator: {error}");
}
}
stream.write_u8(status).await?; stream.write_u8(status).await?;
anyhow::ensure!( anyhow::ensure!(
version == PROTOCOL_VERSION, version == PROTOCOL_VERSION,
@@ -91,6 +104,32 @@ pub async fn forward_auth_callback(callback: &str) -> anyhow::Result<()> {
.context("Timed out forwarding the authentication callback")? .context("Timed out forwarding the authentication callback")?
} }
fn delegate_foreground_to_receiver(stream: &NamedPipeClient) -> io::Result<()> {
let mut process_id = 0;
unsafe {
if GetNamedPipeServerProcessId(stream.as_raw_handle(), &mut process_id) == 0 {
return Err(io::Error::last_os_error());
}
}
allow_foreground(process_id)
}
fn delegate_foreground_to_parent() -> anyhow::Result<()> {
let Some(process_id) = std::env::var_os(gpapi::process::auth_launcher::AUTH_PARENT_PROCESS_ID_ENV) else {
return Ok(());
};
let process_id = process_id.to_string_lossy().parse::<u32>()?;
allow_foreground(process_id)?;
Ok(())
}
fn allow_foreground(process_id: u32) -> io::Result<()> {
if unsafe { AllowSetForegroundWindow(process_id) } == 0 {
return Err(io::Error::last_os_error());
}
Ok(())
}
pub fn ensure_auth_callback_handler() -> anyhow::Result<()> { pub fn ensure_auth_callback_handler() -> anyhow::Result<()> {
use winreg::{RegKey, enums::HKEY_CURRENT_USER}; use winreg::{RegKey, enums::HKEY_CURRENT_USER};
let executable = common::binary_paths::gpauth(); let executable = common::binary_paths::gpauth();
+19
View File
@@ -21,6 +21,10 @@ use super::rendering_recovery::{RenderingCrash, StderrDiagnostic, eligible, is_c
const MAX_AUTH_RESULT_BYTES: usize = 256 * 1024; const MAX_AUTH_RESULT_BYTES: usize = 256 * 1024;
#[cfg(windows)]
/// The caller that receives foreground permission after browser authentication.
pub const AUTH_PARENT_PROCESS_ID_ENV: &str = "GPAUTH_PARENT_PROCESS_ID";
pub struct SamlAuthLauncher<'a> { pub struct SamlAuthLauncher<'a> {
cancellation: CancellationToken, cancellation: CancellationToken,
server: &'a str, server: &'a str,
@@ -197,6 +201,8 @@ impl<'a> SamlAuthLauncher<'a> {
/// argument that never gets appended. /// argument that never gets appended.
fn build_command(&self, program: &Path) -> Command { fn build_command(&self, program: &Path) -> Command {
let mut auth_cmd = Command::new(program); let mut auth_cmd = Command::new(program);
#[cfg(windows)]
auth_cmd.env(AUTH_PARENT_PROCESS_ID_ENV, std::process::id().to_string());
auth_cmd.arg(self.server); auth_cmd.arg(self.server);
if self.gateway { if self.gateway {
@@ -493,6 +499,19 @@ mod tests {
.collect() .collect()
} }
#[cfg(windows)]
#[test]
fn auth_child_receives_its_foreground_parent() {
let command = SamlAuthLauncher::new("portal.example.com").build_command(Path::new("gpauth"));
let parent = command
.as_std()
.get_envs()
.find(|(name, _)| *name == AUTH_PARENT_PROCESS_ID_ENV)
.and_then(|(_, value)| value)
.expect("the authenticator must know its foreground recipient");
assert_eq!(parent, std::process::id().to_string().as_str());
}
/// gpauth writes to the same stderr as its parent, so a caller reading the /// gpauth writes to the same stderr as its parent, so a caller reading the
/// parent's JSON would hit gpauth's text records mid-stream unless the format /// parent's JSON would hit gpauth's text records mid-stream unless the format
/// is passed down. /// is passed down.
+5
View File
@@ -11,6 +11,11 @@
the payload. Each installer accepts only its native Windows architecture. ARM64 the payload. Each installer accepts only its native Windows architecture. ARM64
requires Windows 11; x64 requires Windows 10 build 19041 or newer. requires Windows 11; x64 requires Windows 10 build 19041 or newer.
The native library build accepts `scripts/build-openconnect-windows.ps1 -TunnelType 'GP Connect'`
(the default). This passes OpenConnect's `--with-wintun-tunnel-type` build option;
OpenConnect itself defaults to `OpenConnect`. Wintun appends ` Tunnel` to the
selected type. The gateway-based connection name is unchanged.
`BUILD_VERSION` must contain four numeric components. `PRODUCT_VERSION` must `BUILD_VERSION` must contain four numeric components. `PRODUCT_VERSION` must
match the payload's `build-info.json`. `DISPLAY_VERSION` is the full release match the payload's `build-info.json`. `DISPLAY_VERSION` is the full release
identity, including the snapshot build when applicable. The payload must contain matching identity, including the snapshot build when applicable. The payload must contain matching
+3 -2
View File
@@ -5,7 +5,8 @@ param(
[string]$MsysRoot = 'C:\msys64', [string]$MsysRoot = 'C:\msys64',
[ValidateSet('mingw64','ucrt64','clangarm64')][string]$MsysSubsystem = 'mingw64', [ValidateSet('mingw64','ucrt64','clangarm64')][string]$MsysSubsystem = 'mingw64',
[string]$Prefix, [string]$Prefix,
[int]$Jobs = 4 [int]$Jobs = 4,
[ValidateNotNullOrEmpty()][string]$TunnelType = 'GP Connect'
) )
$ErrorActionPreference = 'Stop' $ErrorActionPreference = 'Stop'
$repo = Split-Path $PSScriptRoot -Parent $repo = Split-Path $PSScriptRoot -Parent
@@ -14,7 +15,7 @@ $Prefix = [System.IO.Path]::GetFullPath($Prefix)
$bash = Join-Path $MsysRoot 'usr\bin\bash.exe' $bash = Join-Path $MsysRoot 'usr\bin\bash.exe'
if (!(Test-Path $bash)) { throw 'MSYS2 is required to build OpenConnect.' } if (!(Test-Path $bash)) { throw 'MSYS2 is required to build OpenConnect.' }
$ErrorActionPreference = 'Continue' $ErrorActionPreference = 'Continue'
& $bash "$PSScriptRoot/build-openconnect-windows.sh" $repo $Prefix $Jobs $MsysSubsystem & $bash "$PSScriptRoot/build-openconnect-windows.sh" $repo $Prefix $Jobs $MsysSubsystem $TunnelType
$nativeExit = $LASTEXITCODE $nativeExit = $LASTEXITCODE
$ErrorActionPreference = 'Stop' $ErrorActionPreference = 'Stop'
if ($nativeExit -ne 0) { throw 'OpenConnect compilation failed.' } if ($nativeExit -ne 0) { throw 'OpenConnect compilation failed.' }
+2 -1
View File
@@ -6,6 +6,7 @@ export PATH="/$subsystem/bin:/usr/bin:$PATH"
repo=$(cygpath -u "$1") repo=$(cygpath -u "$1")
prefix=$(cygpath -u "$2") prefix=$(cygpath -u "$2")
jobs=$3 jobs=$3
tunnel_type=$5
export ACLOCAL_PATH="/$subsystem/share/aclocal" export ACLOCAL_PATH="/$subsystem/share/aclocal"
source_dir="$repo/crates/openconnect/deps/openconnect" source_dir="$repo/crates/openconnect/deps/openconnect"
build_dir="$repo/target/openconnect-windows" build_dir="$repo/target/openconnect-windows"
@@ -22,7 +23,7 @@ fi
--enable-shared --disable-static --disable-nls --disable-docs --disable-dsa-tests \ --enable-shared --disable-static --disable-nls --disable-docs --disable-dsa-tests \
--without-libproxy --without-stoken --without-libpcsclite --without-libpskc \ --without-libproxy --without-stoken --without-libpcsclite --without-libpskc \
--without-gssapi --with-gnutls --without-openssl --with-gnutls-tss2=no \ --without-gssapi --with-gnutls --without-openssl --with-gnutls-tss2=no \
--with-vpnc-script=unused --with-vpnc-script=unused --with-wintun-tunnel-type="$tunnel_type"
grep -q '^#define OPENCONNECT_GNUTLS 1$' config.h grep -q '^#define OPENCONNECT_GNUTLS 1$' config.h
make -j"$jobs" libopenconnect.la make -j"$jobs" libopenconnect.la
make install-libLTLIBRARIES make install-libLTLIBRARIES