feat(auth): refine embedded webview integration

This commit is contained in:
Kevin Yue committed 2026-07-21 22:21:17 +08:00
1 parent 537e12d706
commit c0c517806e
12 files changed
+401 -44

No files matched your search

+1 -1
View File
@@ -28,7 +28,7 @@ compile-time.workspace = true
home = "=0.5.11"
# webview auth dependencies
tauri = { workspace = true, optional = true }
tauri = { workspace = true, optional = true, features = ["devtools"] }
[features]
default = ["webview-auth"]
+37 -1
View File
@@ -1,5 +1,7 @@
use auth::{BrowserAuthenticator, auth_prelogin};
use clap::Parser;
#[cfg(feature = "webview-auth")]
use gpapi::auth::AuthWindowTheme;
use gpapi::{
auth::{AuthenticationCancelled, SamlAuthData, SamlAuthResult},
clap::{Args, InfoLevelVerbosity, args::Os, handle_error},
@@ -96,6 +98,14 @@ struct Cli {
#[arg(long, help = "Clean the cache of the embedded browser")]
pub clean: bool,
#[cfg(feature = "webview-auth")]
#[arg(long, help = "Set the embedded authentication window title")]
window_title: Option<String>,
#[cfg(feature = "webview-auth")]
#[arg(long, value_enum, default_value_t = AuthWindowTheme::default(), help = "Set the embedded authentication window appearance")]
window_theme: AuthWindowTheme,
#[command(flatten)]
verbose: InfoLevelVerbosity,
}
@@ -166,7 +176,16 @@ impl Cli {
}
#[cfg(feature = "webview-auth")]
crate::webview_auth::authenticate(server, gp_params, auth_request, self.clean, openssl_conf).await?;
crate::webview_auth::authenticate(
server,
gp_params,
auth_request,
self.clean,
self.window_title.clone(),
self.window_theme,
openssl_conf,
)
.await?;
Ok(())
}
@@ -314,4 +333,21 @@ mod tests {
assert_eq!(cli.sslkey.as_deref(), Some("/tmp/client.key"));
assert_eq!(cli.key_password.as_deref(), Some("secret"));
}
#[cfg(feature = "webview-auth")]
#[test]
fn auth_window_options_parse() {
let cli = Cli::try_parse_from([
"gpauth",
"portal.example.com",
"--window-title",
"GP Connect Login",
"--window-theme",
"dark",
])
.expect("gpauth window options should parse");
assert_eq!(cli.window_title.as_deref(), Some("GP Connect Login"));
assert_eq!(cli.window_theme, AuthWindowTheme::Dark);
}
}
+8 -3
View File
@@ -1,5 +1,5 @@
use auth::WebviewAuthenticator;
use gpapi::gp_params::GpParams;
use auth::{WebviewAuthenticator, apply_auth_theme};
use gpapi::{auth::AuthWindowTheme, gp_params::GpParams};
use log::info;
use tauri::RunEvent;
use tempfile::NamedTempFile;
@@ -11,19 +11,24 @@ pub async fn authenticate(
gp_params: GpParams,
auth_request: String,
clean: bool,
window_title: Option<String>,
window_theme: AuthWindowTheme,
mut openssl_conf: Option<NamedTempFile>,
) -> anyhow::Result<()> {
let auth_host_id = gp_params.os_profile().host_identity().host_id().to_string();
tauri::Builder::default()
.setup(move |app| {
apply_auth_theme(app.handle(), window_theme);
let app_handle = app.handle().clone();
tauri::async_runtime::spawn(async move {
let authenticator = WebviewAuthenticator::new(&server, &gp_params)
.with_auth_request(&auth_request)
.with_webview_user_agent(gp_params.os_profile().webview_user_agent())
.with_clean(clean);
.with_clean(clean)
.with_window_title(window_title.as_deref().unwrap_or("GlobalProtect Login"))
.with_window_theme(window_theme);
let auth_result = authenticator.authenticate(&app_handle).await;
print_auth_result(auth_result, Some(&auth_host_id));
+16 -2
View File
@@ -1,4 +1,3 @@
#[cfg(debug_assertions)]
use std::path::PathBuf;
use std::sync::{
Arc,
@@ -13,6 +12,8 @@ use clap::Parser;
use common::constants::GP_SERVICE_LOCK_FILE;
use gpapi::clap::InfoLevelVerbosity;
use gpapi::logger;
#[cfg(debug_assertions)]
use gpapi::utils::lock_file::dev_service_lock_file_path;
use gpapi::{
process::gui_launcher::GuiLauncher,
service::{request::WsRequest, vpn_state::VpnState},
@@ -88,7 +89,7 @@ impl Cli {
info!("gpservice started: {}", VERSION);
let pid = std::process::id();
let lock_file = Arc::new(LockFile::new(GP_SERVICE_LOCK_FILE, pid));
let lock_file = Arc::new(LockFile::new(self.service_lock_file_path()?, pid));
if lock_file.check_health().await {
bail!("Another instance of the service is already running");
@@ -230,6 +231,19 @@ impl Cli {
false
}
fn service_lock_file_path(&self) -> anyhow::Result<PathBuf> {
#[cfg(debug_assertions)]
if self.dev_standalone {
let socket = self
.dev_bootstrap_socket
.as_ref()
.context("--dev-bootstrap-socket is required with --dev-standalone")?;
return Ok(dev_service_lock_file_path(socket));
}
Ok(PathBuf::from(GP_SERVICE_LOCK_FILE))
}
fn init_logger(&self) -> Arc<Redaction> {
let redaction = Arc::new(Redaction::new());
let level = self.verbose.log_level_filter().to_level().unwrap_or(log::Level::Info);
+1 -1
View File
@@ -17,4 +17,4 @@ mod platform_impl;
)))]
compile_error!("webview-auth is only supported on macOS and GTK/WebKitGTK Unix targets");
pub use webview_auth::WebviewAuthenticator;
pub use webview_auth::{WebviewAuthenticator, apply_auth_theme};
+138 -8
View File
@@ -1,17 +1,147 @@
use anyhow::bail;
use block2::RcBlock;
use log::warn;
use objc2::runtime::AnyObject;
use objc2_foundation::{NSError, NSObject, NSObjectNSKeyValueCoding, NSString, NSURL, NSURLRequest};
use objc2_web_kit::WKWebView;
use std::{ffi::c_void, ptr};
use anyhow::{Context, bail};
use block2::{DynBlock, RcBlock};
use objc2::{
DefinedClass, MainThreadOnly, define_class,
ffi::{OBJC_ASSOCIATION_RETAIN_NONATOMIC, objc_setAssociatedObject},
msg_send,
rc::Retained,
runtime::{AnyObject, ProtocolObject, Sel},
};
use objc2_foundation::{
MainThreadMarker, NSError, NSObject, NSObjectNSKeyValueCoding, NSObjectProtocol, NSString, NSURL,
NSURLAuthenticationChallenge, NSURLAuthenticationMethodServerTrust, NSURLCredential, NSURLRequest,
NSURLSessionAuthChallengeDisposition,
};
use objc2_web_kit::{WKNavigationDelegate, WKWebView};
use tauri::webview::PlatformWebview;
use super::webview_auth::PlatformWebviewExt;
static TLS_NAVIGATION_DELEGATE_KEY: u8 = 0;
struct TlsNavigationDelegateIvars {
original: Retained<ProtocolObject<dyn WKNavigationDelegate>>,
}
define_class!(
#[unsafe(super = NSObject)]
#[thread_kind = MainThreadOnly]
#[ivars = TlsNavigationDelegateIvars]
struct TlsNavigationDelegate;
unsafe impl NSObjectProtocol for TlsNavigationDelegate {}
#[allow(non_snake_case)]
unsafe impl WKNavigationDelegate for TlsNavigationDelegate {
#[unsafe(method(webView:didReceiveAuthenticationChallenge:completionHandler:))]
unsafe fn webView_didReceiveAuthenticationChallenge_completionHandler(
&self,
_webview: &WKWebView,
challenge: &NSURLAuthenticationChallenge,
completion_handler: &DynBlock<dyn Fn(NSURLSessionAuthChallengeDisposition, *mut NSURLCredential)>,
) {
let protection_space = challenge.protectionSpace();
let is_server_trust = protection_space
.authenticationMethod()
.isEqualToString(unsafe { NSURLAuthenticationMethodServerTrust });
if !is_server_trust {
completion_handler.call((challenge_disposition(false), ptr::null_mut()));
return;
}
let server_trust: *mut AnyObject = msg_send![&*protection_space, serverTrust];
if server_trust.is_null() {
completion_handler.call((challenge_disposition(false), ptr::null_mut()));
return;
}
let credential: Retained<NSURLCredential> =
msg_send![objc2::class!(NSURLCredential), credentialForTrust: server_trust];
completion_handler.call((challenge_disposition(true), Retained::as_ptr(&credential).cast_mut()));
}
}
impl TlsNavigationDelegate {
#[unsafe(method(respondsToSelector:))]
fn responds_to_selector(&self, selector: Sel) -> bool {
let responds: bool = unsafe { msg_send![super(self), respondsToSelector: selector] };
responds || self.ivars().original.respondsToSelector(selector)
}
#[unsafe(method(forwardingTargetForSelector:))]
fn forwarding_target_for_selector(&self, selector: Sel) -> *mut AnyObject {
if self.ivars().original.respondsToSelector(selector) {
Retained::as_ptr(&self.ivars().original).cast_mut().cast()
} else {
unsafe { msg_send![super(self), forwardingTargetForSelector: selector] }
}
}
}
);
impl TlsNavigationDelegate {
fn new(original: Retained<ProtocolObject<dyn WKNavigationDelegate>>, mtm: MainThreadMarker) -> Retained<Self> {
let this = Self::alloc(mtm).set_ivars(TlsNavigationDelegateIvars { original });
unsafe { msg_send![super(this), init] }
}
}
fn challenge_disposition(is_server_trust: bool) -> NSURLSessionAuthChallengeDisposition {
if is_server_trust {
NSURLSessionAuthChallengeDisposition::UseCredential
} else {
NSURLSessionAuthChallengeDisposition::PerformDefaultHandling
}
}
fn install_tls_navigation_delegate(webview: &WKWebView) -> anyhow::Result<()> {
let original = unsafe { webview.navigationDelegate() }.context("WebView navigation delegate is unavailable")?;
let mtm = MainThreadMarker::new().context("WebView must be configured on the main thread")?;
let delegate = TlsNavigationDelegate::new(original, mtm);
unsafe {
objc_setAssociatedObject(
webview as *const WKWebView as *mut AnyObject,
&TLS_NAVIGATION_DELEGATE_KEY as *const u8 as *const c_void,
Retained::as_ptr(&delegate).cast_mut().cast(),
OBJC_ASSOCIATION_RETAIN_NONATOMIC,
);
webview.setNavigationDelegate(Some(ProtocolObject::from_ref(&*delegate)));
}
Ok(())
}
#[cfg(test)]
mod tests {
use objc2_foundation::NSURLSessionAuthChallengeDisposition;
use super::challenge_disposition;
#[test]
fn accepts_server_trust_challenges() {
assert_eq!(
challenge_disposition(true),
NSURLSessionAuthChallengeDisposition::UseCredential
);
}
#[test]
fn preserves_default_handling_for_other_challenges() {
assert_eq!(
challenge_disposition(false),
NSURLSessionAuthChallengeDisposition::PerformDefaultHandling
);
}
}
impl PlatformWebviewExt for PlatformWebview {
fn ignore_tls_errors(&self) -> anyhow::Result<()> {
warn!("Ignoring TLS errors is not supported on macOS");
Ok(())
let webview: &WKWebView = unsafe { &*self.inner().cast() };
install_tls_navigation_delegate(webview)
}
fn user_agent(&self) -> anyhow::Result<String> {
+58 -17
View File
@@ -2,10 +2,10 @@ use std::{sync::Arc, time::Duration};
use anyhow::bail;
use gpapi::{
auth::{AuthenticationCancelled, SamlAuthData},
auth::{AuthWindowTheme, AuthenticationCancelled, SamlAuthData},
gp_params::GpParams,
os_profile::{WebviewUserAgent, WebviewUserAgentTransform},
utils::redact::redact_uri,
utils::{redact::redact_uri, window::get_title_bar_height},
};
use log::{info, warn};
use tauri::{
@@ -53,10 +53,28 @@ pub struct WebviewAuthenticator<'a> {
auth_request: Option<&'a str>,
webview_user_agent: Option<WebviewUserAgent>,
clean: bool,
window_title: &'a str,
window_theme: AuthWindowTheme,
is_retrying: tokio::sync::RwLock<bool>,
}
fn native_theme(theme: AuthWindowTheme) -> Option<tauri::Theme> {
match theme {
AuthWindowTheme::System => None,
AuthWindowTheme::Light => Some(tauri::Theme::Light),
AuthWindowTheme::Dark => Some(tauri::Theme::Dark),
}
}
pub fn apply_auth_theme(app_handle: &AppHandle, theme: AuthWindowTheme) {
app_handle.set_theme(native_theme(theme));
}
fn present_after_setup(clean: bool) -> bool {
clean
}
impl<'a> WebviewAuthenticator<'a> {
pub fn new(server: &'a str, gp_params: &'a GpParams) -> Self {
Self {
@@ -65,6 +83,8 @@ impl<'a> WebviewAuthenticator<'a> {
auth_request: None,
webview_user_agent: None,
clean: false,
window_title: "GlobalProtect Login",
window_theme: AuthWindowTheme::System,
is_retrying: Default::default(),
}
}
@@ -84,6 +104,16 @@ impl<'a> WebviewAuthenticator<'a> {
self
}
pub fn with_window_title(mut self, window_title: &'a str) -> Self {
self.window_title = window_title;
self
}
pub fn with_window_theme(mut self, window_theme: AuthWindowTheme) -> Self {
self.window_theme = window_theme;
self
}
pub async fn authenticate(&self, app_handle: &AppHandle) -> anyhow::Result<SamlAuthData> {
let auth_messenger = Arc::new(AuthMessenger::new());
let auth_messenger_clone = Arc::clone(&auth_messenger);
@@ -112,15 +142,15 @@ impl<'a> WebviewAuthenticator<'a> {
});
};
let title_bar_height = if cfg!(target_os = "macos") { 28.0 } else { 0.0 };
let auth_window = WebviewWindow::builder(app_handle, "auth_window", WebviewUrl::default())
let auth_window_builder = WebviewWindow::builder(app_handle, "auth_window", WebviewUrl::default())
.on_page_load(on_page_load)
.title("GlobalProtect Login")
.inner_size(900.0, 650.0 + title_bar_height)
.title(self.window_title)
.theme(native_theme(self.window_theme))
.devtools(true);
let auth_window = auth_window_builder
.inner_size(900.0, 650.0 + get_title_bar_height())
.focused(true)
// when clean is true, the window is expected to be shown because the cookies are cleared
.visible(self.clean)
.visible(false)
.center()
.build()?;
@@ -128,6 +158,10 @@ impl<'a> WebviewAuthenticator<'a> {
.setup_auth_window(&auth_window, Arc::clone(&auth_messenger))
.await?;
if present_after_setup(self.clean) {
self.raise_window(&auth_window);
}
loop {
match auth_messenger.subscribe().await? {
AuthEvent::Close => bail!(AuthenticationCancelled),
@@ -284,14 +318,8 @@ impl<'a> WebviewAuthenticator<'a> {
info!("Raising auth window...");
#[cfg(target_os = "macos")]
let result = auth_window.show();
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
let result = {
use gpapi::utils::window::WindowExt;
auth_window.raise()
};
use gpapi::utils::window::WindowExt;
let result = auth_window.raise();
if let Err(err) = result {
warn!("Failed to raise window: {}", err);
@@ -377,6 +405,19 @@ fn prepend_webview_user_agent_prefix(prefix: &str, default_user_agent: &str) ->
mod tests {
use super::*;
#[test]
fn maps_auth_window_theme_to_native_theme() {
assert_eq!(native_theme(AuthWindowTheme::System), None);
assert_eq!(native_theme(AuthWindowTheme::Light), Some(tauri::Theme::Light));
assert_eq!(native_theme(AuthWindowTheme::Dark), Some(tauri::Theme::Dark));
}
#[test]
fn presents_clean_auth_after_setup() {
assert!(present_after_setup(true));
assert!(!present_after_setup(false));
}
#[test]
fn prepends_prefix_to_default_user_agent() {
let user_agent = prepend_webview_user_agent_prefix("PAN GlobalProtect/6.3.3", "Mozilla/5.0").unwrap();
+19
View File
@@ -12,6 +12,25 @@ use crate::{error::AuthDataParseError, utils::base64::decode_to_string};
pub type AuthDataParseResult = anyhow::Result<SamlAuthData, AuthDataParseError>;
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "clap", derive(clap::ValueEnum))]
pub enum AuthWindowTheme {
#[default]
System,
Light,
Dark,
}
impl AuthWindowTheme {
pub fn as_str(self) -> &'static str {
match self {
Self::System => "system",
Self::Light => "light",
Self::Dark => "dark",
}
}
}
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct SamlAuthData {
+30
View File
@@ -4,6 +4,8 @@ use anyhow::bail;
use common::binary_paths;
use tokio::process::Command;
#[cfg(feature = "webview-auth")]
use crate::auth::AuthWindowTheme;
use crate::{auth::SamlAuthResult, credential::Credential, os_profile::OsProfile};
use super::command_traits::CommandExt;
@@ -27,6 +29,10 @@ pub struct SamlAuthLauncher<'a> {
clean: bool,
#[cfg(feature = "webview-auth")]
default_browser: bool,
#[cfg(feature = "webview-auth")]
window_title: Option<&'a str>,
#[cfg(feature = "webview-auth")]
window_theme: Option<AuthWindowTheme>,
browser: Option<&'a str>,
verbose: Option<&'a str>,
}
@@ -52,6 +58,10 @@ impl<'a> SamlAuthLauncher<'a> {
clean: false,
#[cfg(feature = "webview-auth")]
default_browser: false,
#[cfg(feature = "webview-auth")]
window_title: None,
#[cfg(feature = "webview-auth")]
window_theme: None,
browser: None,
verbose: None,
}
@@ -122,6 +132,18 @@ impl<'a> SamlAuthLauncher<'a> {
self
}
#[cfg(feature = "webview-auth")]
pub fn window_title(mut self, window_title: &'a str) -> Self {
self.window_title = Some(window_title);
self
}
#[cfg(feature = "webview-auth")]
pub fn window_theme(mut self, window_theme: AuthWindowTheme) -> Self {
self.window_theme = Some(window_theme);
self
}
pub fn browser(mut self, browser: Option<&'a str>) -> Self {
self.browser = browser;
self
@@ -194,6 +216,14 @@ impl<'a> SamlAuthLauncher<'a> {
if self.default_browser {
auth_cmd.arg("--default-browser");
}
if let Some(window_title) = self.window_title {
auth_cmd.arg("--window-title").arg(window_title);
}
if let Some(window_theme) = self.window_theme {
auth_cmd.arg("--window-theme").arg(window_theme.as_str());
}
}
if let Some(browser) = self.browser {
+27 -8
View File
@@ -1,19 +1,38 @@
use super::lock_file::gpservice_lock_info;
use std::path::Path;
async fn read_port() -> anyhow::Result<String> {
let lock_info = gpservice_lock_info().await?;
Ok(lock_info.port.to_string())
}
use super::lock_file::{gpservice_lock_info, gpservice_lock_info_at};
pub async fn http_endpoint() -> anyhow::Result<String> {
let port = read_port().await?;
let port = gpservice_lock_info().await?.port;
Ok(format!("http://127.0.0.1:{}", port))
}
pub async fn ws_endpoint() -> anyhow::Result<String> {
let port = read_port().await?;
let port = gpservice_lock_info().await?.port;
Ok(format!("ws://127.0.0.1:{}/ws", port))
}
pub async fn ws_endpoint_from_lock_file(path: impl AsRef<Path>) -> anyhow::Result<String> {
let port = gpservice_lock_info_at(path).await?.port;
Ok(format!("ws://127.0.0.1:{}/ws", port))
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn websocket_endpoint_uses_the_selected_lock_file() {
let temp = tempfile::tempdir().unwrap();
let lock_file = temp.path().join("gpservice.lock");
std::fs::write(&lock_file, "123:4242").unwrap();
assert_eq!(
ws_endpoint_from_lock_file(lock_file).await.unwrap(),
"ws://127.0.0.1:4242/ws"
);
}
}
+18 -2
View File
@@ -1,4 +1,4 @@
use std::path::PathBuf;
use std::path::{Path, PathBuf};
use common::constants::GP_SERVICE_LOCK_FILE;
use thiserror::Error;
@@ -9,6 +9,10 @@ pub struct LockFile {
pid: u32,
}
pub fn dev_service_lock_file_path(bootstrap_socket: impl AsRef<Path>) -> PathBuf {
bootstrap_socket.as_ref().with_file_name("gpservice.lock")
}
impl LockFile {
pub fn new<P: Into<PathBuf>>(path: P, pid: u32) -> Self {
Self { path: path.into(), pid }
@@ -95,7 +99,11 @@ impl LockInfo {
}
pub async fn gpservice_lock_info() -> Result<LockInfo, LockFileError> {
LockInfo::from_file(GP_SERVICE_LOCK_FILE).await
gpservice_lock_info_at(GP_SERVICE_LOCK_FILE).await
}
pub async fn gpservice_lock_info_at(path: impl AsRef<Path>) -> Result<LockInfo, LockFileError> {
LockInfo::from_file(path).await
}
#[cfg(test)]
@@ -126,4 +134,12 @@ mod tests {
Err(LockFileError::InvalidPort(_))
));
}
#[test]
fn dev_service_lock_file_is_next_to_the_bootstrap_socket() {
assert_eq!(
dev_service_lock_file_path("/var/run/gpservice-dev-123/dev-bootstrap.sock"),
PathBuf::from("/var/run/gpservice-dev-123/gpservice.lock")
);
}
}
+48 -1
View File
@@ -1,11 +1,40 @@
use tauri::WebviewWindow;
/// Returns the frame-to-content height difference for a standard titled macOS window.
/// This is nonzero only on macOS.
pub fn get_title_bar_height() -> f64 {
#[cfg(target_os = "macos")]
{
macos_title_bar_height(os_info::get().version())
}
#[cfg(not(target_os = "macos"))]
{
0.0
}
}
#[cfg(target_os = "macos")]
fn macos_title_bar_height(version: &os_info::Version) -> f64 {
if version.ge(&os_info::Version::from_string("26.0.0")) {
32.0
} else {
28.0
}
}
pub trait WindowExt {
fn raise(&self) -> anyhow::Result<()>;
}
impl WindowExt for WebviewWindow {
#[cfg(any(target_os = "macos", target_os = "windows"))]
#[cfg(target_os = "macos")]
fn raise(&self) -> anyhow::Result<()> {
self.show()?;
self.set_focus()?;
Ok(())
}
#[cfg(target_os = "windows")]
fn raise(&self) -> anyhow::Result<()> {
self.show()?;
Ok(())
@@ -17,6 +46,24 @@ impl WindowExt for WebviewWindow {
}
}
#[cfg(test)]
mod tests {
use super::*;
#[cfg(target_os = "macos")]
#[test]
fn uses_the_current_macos_title_bar_height() {
assert_eq!(macos_title_bar_height(&os_info::Version::from_string("25.9.0")), 28.0);
assert_eq!(macos_title_bar_height(&os_info::Version::from_string("26.0.0")), 32.0);
}
#[cfg(not(target_os = "macos"))]
#[test]
fn native_title_bar_height_is_zero_without_a_native_macos_title_bar() {
assert_eq!(get_title_bar_height(), 0.0);
}
}
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
mod unix {
use std::{process::ExitStatus, time::Duration};