mirror of
https://github.com/yuezk/GlobalProtect-openconnect.git
synced 2026-11-18 22:16:18 -05:00
feat(auth): refine embedded webview integration
This commit is contained in:
12 files changed
+401
-44
No files matched your search
@@ -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> {
|
||||
|
||||
@@ -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();
|
||||
|
||||
Reference in new issue
Block a user