mirror of
https://github.com/yuezk/GlobalProtect-openconnect.git
synced 2026-11-18 22:16:18 -05:00
feat: prepare 3.1.0 with connection details and improved authentication
Add tunnel statistics and an optional CLI dashboard, native sign-in controls and recovery, and broader client certificate support. Include platform integration fixes and the approved release notes.
This commit is contained in:
158 files changed
+13752
-1038
No files matched your search
@@ -0,0 +1,54 @@
|
||||
pub const TOOLBAR_HEIGHT: f64 = 40.0;
|
||||
pub const LOADING_ADDRESS: &str = "Loading sign-in page…";
|
||||
|
||||
/// Display web addresses with query strings and fragments, but without credentials.
|
||||
pub fn display_address(uri: Option<&str>) -> String {
|
||||
let Some(mut url) = uri.and_then(|uri| url::Url::parse(uri).ok()) else {
|
||||
return LOADING_ADDRESS.to_string();
|
||||
};
|
||||
if !matches!(url.scheme(), "http" | "https") || url.host_str().is_none() {
|
||||
return LOADING_ADDRESS.to_string();
|
||||
}
|
||||
|
||||
let _ = url.set_username("");
|
||||
let _ = url.set_password(None);
|
||||
url.into()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn hides_credentials_but_preserves_query_and_fragment() {
|
||||
assert_eq!(
|
||||
display_address(Some(
|
||||
"https://user:[email protected]:8443/saml?SAMLRequest=secret#token"
|
||||
)),
|
||||
"https://login.example:8443/saml?SAMLRequest=secret#token"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preserves_scheme_host_and_encoded_path() {
|
||||
assert_eq!(
|
||||
display_address(Some("http://example.com/a%20b")),
|
||||
"http://example.com/a%20b"
|
||||
);
|
||||
assert_eq!(display_address(Some("https://[::1]:8443/")), "https://[::1]:8443/");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn uses_placeholder_for_local_pages_and_callbacks() {
|
||||
for uri in [
|
||||
None,
|
||||
Some(""),
|
||||
Some("invalid"),
|
||||
Some("about:blank"),
|
||||
Some("data:text/html,secret"),
|
||||
Some("globalprotectcallback:secret"),
|
||||
] {
|
||||
assert_eq!(display_address(uri), LOADING_ADDRESS);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,9 @@
|
||||
use super::tls::TlsFailure;
|
||||
use anyhow::bail;
|
||||
use gpapi::{auth::SamlAuthData, error::AuthDataParseError};
|
||||
use log::{error, info};
|
||||
use regex::Regex;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use tokio::sync::{RwLock, mpsc};
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
@@ -14,36 +16,30 @@ pub(crate) enum AuthDataLocation {
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) enum AuthError {
|
||||
/// Failed to load page due to TLS error
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
TlsError,
|
||||
/// 1. Found auth data in headers/body but it's invalid
|
||||
/// 2. Loaded an empty page, failed to load page. etc.
|
||||
/// A certificate or TLS handshake failure in the native webview.
|
||||
Tls(TlsFailure),
|
||||
/// The authentication service returned a temporary failure.
|
||||
TemporarilyUnavailable,
|
||||
/// A sign-in request could not be loaded.
|
||||
LoadFailed(anyhow::Error),
|
||||
/// Found auth data in headers/body but it's invalid.
|
||||
Invalid(anyhow::Error, AuthDataLocation),
|
||||
/// No auth data found in headers/body
|
||||
NotFound(AuthDataLocation),
|
||||
}
|
||||
|
||||
impl AuthError {
|
||||
pub fn invalid_from_body(err: anyhow::Error) -> Self {
|
||||
Self::Invalid(err, AuthDataLocation::Body)
|
||||
}
|
||||
|
||||
pub fn not_found_in_body() -> Self {
|
||||
Self::NotFound(AuthDataLocation::Body)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
impl AuthError {
|
||||
pub fn not_found_in_headers() -> Self {
|
||||
Self::NotFound(AuthDataLocation::Headers)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) enum AuthEvent {
|
||||
Data(SamlAuthData, AuthDataLocation),
|
||||
Error(AuthError),
|
||||
Data(u64, SamlAuthData, AuthDataLocation),
|
||||
Error(u64, AuthError),
|
||||
NoAuthData(u64, AuthDataLocation),
|
||||
PageLoaded(u64),
|
||||
Retry,
|
||||
RequestTlsException,
|
||||
TlsAccepted(u64),
|
||||
RaiseWindow,
|
||||
Close,
|
||||
}
|
||||
@@ -52,6 +48,7 @@ pub struct AuthMessenger {
|
||||
tx: mpsc::UnboundedSender<AuthEvent>,
|
||||
rx: RwLock<mpsc::UnboundedReceiver<AuthEvent>>,
|
||||
raise_window_cancel_token: RwLock<Option<CancellationToken>>,
|
||||
generation: AtomicU64,
|
||||
}
|
||||
|
||||
impl AuthMessenger {
|
||||
@@ -62,6 +59,7 @@ impl AuthMessenger {
|
||||
tx,
|
||||
rx: RwLock::new(rx),
|
||||
raise_window_cancel_token: Default::default(),
|
||||
generation: AtomicU64::new(0),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -79,12 +77,12 @@ impl AuthMessenger {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn send_auth_error(&self, err: AuthError) {
|
||||
self.send_auth_event(AuthEvent::Error(err));
|
||||
pub fn generation(&self) -> u64 {
|
||||
self.generation.load(Ordering::SeqCst)
|
||||
}
|
||||
|
||||
fn send_auth_data(&self, data: SamlAuthData, location: AuthDataLocation) {
|
||||
self.send_auth_event(AuthEvent::Data(data, location));
|
||||
pub fn begin_attempt(&self) {
|
||||
self.generation.fetch_add(1, Ordering::SeqCst);
|
||||
}
|
||||
|
||||
pub fn schedule_raise_window(&self, delay: u64) {
|
||||
@@ -132,9 +130,9 @@ impl AuthMessenger {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn read_from_html(&self, html: &str) {
|
||||
pub fn read_from_html(&self, html: &str, generation: u64) {
|
||||
if html.contains("Temporarily Unavailable") {
|
||||
return self.send_auth_error(AuthError::invalid_from_body(anyhow::anyhow!("Temporarily Unavailable")));
|
||||
return self.send_auth_event(AuthEvent::Error(generation, AuthError::TemporarilyUnavailable));
|
||||
}
|
||||
|
||||
let auth_result = SamlAuthData::from_html(html).or_else(|err| {
|
||||
@@ -149,18 +147,20 @@ impl AuthMessenger {
|
||||
});
|
||||
|
||||
match auth_result {
|
||||
Ok(data) => self.send_auth_data(data, AuthDataLocation::Body),
|
||||
Err(AuthDataParseError::NotFound) => self.send_auth_error(AuthError::not_found_in_body()),
|
||||
Err(err) => self.send_auth_error(AuthError::invalid_from_body(err.into())),
|
||||
Ok(data) => self.send_auth_event(AuthEvent::Data(generation, data, AuthDataLocation::Body)),
|
||||
Err(AuthDataParseError::NotFound) => {
|
||||
self.send_auth_event(AuthEvent::NoAuthData(generation, AuthDataLocation::Body))
|
||||
}
|
||||
Err(err) => self.send_auth_event(AuthEvent::Error(generation, AuthError::invalid_from_body(err.into()))),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
pub fn read_from_response(&self, auth_response: &impl super::webview_auth::GetHeader) {
|
||||
pub fn read_from_response(&self, auth_response: &impl super::webview_auth::GetHeader, generation: u64) {
|
||||
use log::warn;
|
||||
|
||||
let Some(status) = auth_response.get_header("saml-auth-status") else {
|
||||
return self.send_auth_error(AuthError::not_found_in_headers());
|
||||
return self.send_auth_event(AuthEvent::NoAuthData(generation, AuthDataLocation::Headers));
|
||||
};
|
||||
|
||||
// Do not send auth error when reading from headers, as the html body may contain the auth data
|
||||
@@ -174,7 +174,7 @@ impl AuthMessenger {
|
||||
let portal_userauthcookie = auth_response.get_header("portal-userauthcookie");
|
||||
|
||||
match SamlAuthData::new(username, prelogin_cookie, portal_userauthcookie) {
|
||||
Ok(auth_data) => self.send_auth_data(auth_data, AuthDataLocation::Headers),
|
||||
Ok(auth_data) => self.send_auth_event(AuthEvent::Data(generation, auth_data, AuthDataLocation::Headers)),
|
||||
Err(err) => {
|
||||
warn!("Failed to read auth data from headers: {}", err);
|
||||
}
|
||||
@@ -193,6 +193,43 @@ fn extract_gpcallback(html: &str) -> Option<String> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn ordinary_sign_in_page_is_an_observation_with_its_original_generation() {
|
||||
let messenger = AuthMessenger::new();
|
||||
messenger.read_from_html("<html><h1>Sign in</h1></html>", 7);
|
||||
assert!(matches!(
|
||||
messenger.subscribe().await.unwrap(),
|
||||
AuthEvent::NoAuthData(7, AuthDataLocation::Body)
|
||||
));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn distinguishes_temporary_failure_from_rejected_authentication() {
|
||||
let messenger = AuthMessenger::new();
|
||||
messenger.read_from_html("<html>Temporarily Unavailable</html>", 0);
|
||||
assert!(matches!(
|
||||
messenger.subscribe().await.unwrap(),
|
||||
AuthEvent::Error(0, AuthError::TemporarilyUnavailable)
|
||||
));
|
||||
messenger.read_from_html("<saml-auth-status>0</saml-auth-status>", 0);
|
||||
assert!(matches!(
|
||||
messenger.subscribe().await.unwrap(),
|
||||
AuthEvent::Error(0, AuthError::Invalid(..))
|
||||
));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn html_callbacks_keep_the_generation_that_started_the_read() {
|
||||
let messenger = AuthMessenger::new();
|
||||
let generation = messenger.generation();
|
||||
messenger.begin_attempt();
|
||||
messenger.read_from_html("<html>Temporarily Unavailable</html>", generation);
|
||||
match messenger.subscribe().await.unwrap() {
|
||||
AuthEvent::Error(generation, _) => assert_ne!(generation, messenger.generation()),
|
||||
_ => panic!("Expected an authentication error"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extract_gpcallback_some() {
|
||||
let html = r#"
|
||||
|
||||
+244
-55
@@ -1,8 +1,9 @@
|
||||
use std::sync::Arc;
|
||||
use std::{cell::Cell, rc::Rc, sync::Arc};
|
||||
|
||||
use anyhow::bail;
|
||||
use anyhow::{Context, bail};
|
||||
use gpapi::utils::redact::redact_uri;
|
||||
use log::warn;
|
||||
use gtk::prelude::*;
|
||||
use log::{info, warn};
|
||||
use tauri::webview::PlatformWebview;
|
||||
use webkit2gtk::{
|
||||
LoadEvent, SettingsExt, TLSErrorsPolicy, URIResponseExt, WebResource, WebResourceExt, WebViewExt,
|
||||
@@ -10,10 +11,26 @@ use webkit2gtk::{
|
||||
};
|
||||
|
||||
use super::{
|
||||
auth_messenger::AuthError,
|
||||
auth_messenger::{AuthError, AuthEvent, AuthMessenger},
|
||||
recovery::RecoveryStatus,
|
||||
webview_auth::{GetHeader, PlatformWebviewExt},
|
||||
};
|
||||
|
||||
#[path = "gtk_recovery.rs"]
|
||||
mod recovery_row;
|
||||
#[path = "gtk_tls.rs"]
|
||||
mod tls;
|
||||
|
||||
fn action_button(label: &str) -> anyhow::Result<gtk::Button> {
|
||||
let button = gtk::Button::with_label(label);
|
||||
let spacing = gtk::CssProvider::new();
|
||||
spacing.load_from_data(b"button { padding: 4px 12px; }")?;
|
||||
button
|
||||
.style_context()
|
||||
.add_provider(&spacing, gtk::STYLE_PROVIDER_PRIORITY_APPLICATION);
|
||||
Ok(button)
|
||||
}
|
||||
|
||||
impl GetHeader for WebResource {
|
||||
fn get_header(&self, key: &str) -> Option<String> {
|
||||
self
|
||||
@@ -25,6 +42,62 @@ impl GetHeader for WebResource {
|
||||
}
|
||||
|
||||
impl PlatformWebviewExt for PlatformWebview {
|
||||
fn install_auth_controls(&self, window: &tauri::WebviewWindow, messenger: Arc<AuthMessenger>) -> anyhow::Result<()> {
|
||||
use super::address_bar::display_address;
|
||||
|
||||
let entry = gtk::Entry::new();
|
||||
entry.set_editable(false);
|
||||
entry.set_can_focus(true);
|
||||
entry.set_direction(gtk::TextDirection::Ltr);
|
||||
entry.set_text(&display_address(self.inner().uri().as_deref()));
|
||||
let header = gtk::Box::new(gtk::Orientation::Vertical, 4);
|
||||
header.style_context().add_class(gtk::STYLE_CLASS_TOOLBAR);
|
||||
header.style_context().add_class(gtk::STYLE_CLASS_PRIMARY_TOOLBAR);
|
||||
header.style_context().add_class("gpauth-header");
|
||||
// One native header owns the outer padding and the gap between its rows.
|
||||
// Keep theme colors, borders, focus styling, and natural button sizes.
|
||||
let spacing = gtk::CssProvider::new();
|
||||
spacing.load_from_data(b".gpauth-header { padding: 6px; } entry { min-height: 22px; padding: 2px 6px; }")?;
|
||||
entry
|
||||
.style_context()
|
||||
.add_provider(&spacing, gtk::STYLE_PROVIDER_PRIORITY_APPLICATION);
|
||||
header
|
||||
.style_context()
|
||||
.add_provider(&spacing, gtk::STYLE_PROVIDER_PRIORITY_APPLICATION);
|
||||
header.pack_start(&entry, false, false, 0);
|
||||
header.show_all();
|
||||
recovery_row::install(&self.inner(), &header, Arc::clone(&messenger))?;
|
||||
let container = window.default_vbox()?;
|
||||
container.pack_start(&header, false, false, 0);
|
||||
container.reorder_child(&header, 0);
|
||||
let separator = gtk::Separator::new(gtk::Orientation::Horizontal);
|
||||
container.pack_start(&separator, false, false, 0);
|
||||
container.reorder_child(&separator, 1);
|
||||
separator.show();
|
||||
|
||||
// Observe the top-level URI, including redirects and history API changes.
|
||||
let address = entry.clone();
|
||||
self.inner().connect_uri_notify(move |webview| {
|
||||
address.set_text(&display_address(webview.uri().as_deref()));
|
||||
address.set_position(0);
|
||||
});
|
||||
tls::install(&self.inner(), Arc::clone(&messenger));
|
||||
install_navigation_observers(&self.inner(), messenger, entry);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn set_recovery_status(&self, status: RecoveryStatus) -> anyhow::Result<()> {
|
||||
recovery_row::update(&self.inner(), status)
|
||||
}
|
||||
|
||||
fn stop_loading(&self) {
|
||||
self.inner().stop_loading();
|
||||
}
|
||||
|
||||
fn confirm_tls_exception(&self) -> anyhow::Result<()> {
|
||||
tls::confirm(&self.inner())
|
||||
}
|
||||
|
||||
fn ignore_tls_errors(&self) -> anyhow::Result<()> {
|
||||
if let Some(manager) = self.inner().website_data_manager() {
|
||||
manager.set_tls_errors_policy(TLSErrorsPolicy::Ignore);
|
||||
@@ -34,7 +107,7 @@ impl PlatformWebviewExt for PlatformWebview {
|
||||
}
|
||||
|
||||
fn user_agent(&self) -> anyhow::Result<String> {
|
||||
let Some(settings) = self.inner().settings() else {
|
||||
let Some(settings) = WebViewExt::settings(&self.inner()) else {
|
||||
bail!("Failed to get webview settings");
|
||||
};
|
||||
|
||||
@@ -45,7 +118,7 @@ impl PlatformWebviewExt for PlatformWebview {
|
||||
}
|
||||
|
||||
fn set_user_agent(&self, user_agent: &str) -> anyhow::Result<()> {
|
||||
let Some(settings) = self.inner().settings() else {
|
||||
let Some(settings) = WebViewExt::settings(&self.inner()) else {
|
||||
bail!("Failed to get webview settings");
|
||||
};
|
||||
|
||||
@@ -54,72 +127,188 @@ impl PlatformWebviewExt for PlatformWebview {
|
||||
}
|
||||
|
||||
fn load_url(&self, url: &str) -> anyhow::Result<()> {
|
||||
prepare_navigation(&self.inner())?;
|
||||
self.inner().load_uri(url);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn load_html(&self, html: &str) -> anyhow::Result<()> {
|
||||
prepare_navigation(&self.inner())?;
|
||||
self.inner().load_html(html, None);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn get_html(&self, callback: Box<dyn Fn(anyhow::Result<String>) + 'static>) {
|
||||
let script = "document.documentElement.outerHTML";
|
||||
self
|
||||
.inner()
|
||||
.evaluate_javascript(script, None, None, Cancellable::NONE, move |result| match result {
|
||||
Ok(value) => callback(Ok(value.to_string())),
|
||||
Err(err) => callback(Err(anyhow::anyhow!(err))),
|
||||
});
|
||||
const NAVIGATION_KEY: &str = "gpauth-navigation";
|
||||
|
||||
#[derive(Default)]
|
||||
struct NavigationAttempts {
|
||||
pending: Cell<Option<u64>>,
|
||||
current: Cell<Option<u64>>,
|
||||
}
|
||||
|
||||
impl NavigationAttempts {
|
||||
fn started(&self, generation: u64) {
|
||||
self.current.set(Some(self.pending.take().unwrap_or(generation)));
|
||||
}
|
||||
}
|
||||
|
||||
pub trait PlatformWebviewOnResponse {
|
||||
fn on_response(&self, callback: Box<dyn Fn(anyhow::Result<WebResource, AuthError>) + 'static>);
|
||||
struct NavigationObserver {
|
||||
attempts: NavigationAttempts,
|
||||
messenger: Arc<AuthMessenger>,
|
||||
}
|
||||
|
||||
impl PlatformWebviewOnResponse for PlatformWebview {
|
||||
fn on_response(&self, callback: Box<dyn Fn(anyhow::Result<WebResource, AuthError>) + 'static>) {
|
||||
let wv = self.inner();
|
||||
let callback = Arc::new(callback);
|
||||
let callback_clone = Arc::clone(&callback);
|
||||
fn prepare_navigation(webview: &webkit2gtk::WebView) -> anyhow::Result<()> {
|
||||
let observer =
|
||||
unsafe { webview.data::<Rc<NavigationObserver>>(NAVIGATION_KEY) }.context("Navigation observer is unavailable")?;
|
||||
let observer = unsafe { observer.as_ref() };
|
||||
observer.attempts.pending.set(Some(observer.messenger.generation()));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
wv.connect_load_changed(move |wv, event| {
|
||||
if event != LoadEvent::Finished {
|
||||
return;
|
||||
fn install_navigation_observers(webview: &webkit2gtk::WebView, messenger: Arc<AuthMessenger>, address: gtk::Entry) {
|
||||
let observer = Rc::new(NavigationObserver {
|
||||
attempts: NavigationAttempts::default(),
|
||||
messenger,
|
||||
});
|
||||
unsafe {
|
||||
webview.set_data(NAVIGATION_KEY, Rc::clone(&observer));
|
||||
}
|
||||
let loading = Rc::clone(&observer);
|
||||
webview.connect_load_changed(move |webview, event| {
|
||||
match event {
|
||||
LoadEvent::Started => {
|
||||
loading.attempts.started(loading.messenger.generation());
|
||||
loading.messenger.cancel_raise_window();
|
||||
}
|
||||
|
||||
let Some(web_resource) = wv.main_resource() else {
|
||||
return;
|
||||
};
|
||||
|
||||
let uri = web_resource.uri().unwrap_or("".into());
|
||||
if uri.is_empty() {
|
||||
callback_clone(Err(AuthError::invalid_from_body(anyhow::anyhow!("Empty URI"))));
|
||||
} else {
|
||||
callback_clone(Ok(web_resource));
|
||||
LoadEvent::Committed => {
|
||||
if let Some(generation) = loading.attempts.current.get() {
|
||||
info!(
|
||||
"Started loading page: {}",
|
||||
redact_uri(webview.uri().as_deref().unwrap_or_default())
|
||||
);
|
||||
read_navigation_html(webview, Arc::clone(&loading.messenger), generation);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
wv.connect_load_failed_with_tls_errors(move |_wv, uri, cert, err| {
|
||||
let redacted_uri = redact_uri(uri);
|
||||
warn!(
|
||||
"Failed to load uri: {} with error: {}, cert: {}",
|
||||
redacted_uri, err, cert
|
||||
);
|
||||
|
||||
callback(Err(AuthError::TlsError));
|
||||
true
|
||||
});
|
||||
|
||||
wv.connect_load_failed(move |_wv, _event, uri, err| {
|
||||
let redacted_uri = redact_uri(uri);
|
||||
if !uri.starts_with("globalprotectcallback:") {
|
||||
warn!("Failed to load uri: {} with error: {}", redacted_uri, err);
|
||||
LoadEvent::Finished => {
|
||||
// WebKitGTK finishes a cancelled load before starting its replacement.
|
||||
// Retain that load's generation instead of relabeling it at callback time.
|
||||
let Some(generation) = loading.attempts.current.take() else {
|
||||
return;
|
||||
};
|
||||
info!(
|
||||
"Finished loading page: {}",
|
||||
redact_uri(webview.uri().as_deref().unwrap_or_default())
|
||||
);
|
||||
read_navigation_html(webview, Arc::clone(&loading.messenger), generation);
|
||||
if let Some(resource) = webview.main_resource() {
|
||||
let uri = resource.uri().unwrap_or_default();
|
||||
if uri.is_empty() {
|
||||
loading.messenger.send_auth_event(AuthEvent::Error(
|
||||
generation,
|
||||
AuthError::invalid_from_body(anyhow::anyhow!("Empty URI")),
|
||||
));
|
||||
} else {
|
||||
loading.messenger.read_from_response(&resource, generation);
|
||||
}
|
||||
}
|
||||
loading.messenger.send_auth_event(AuthEvent::PageLoaded(generation));
|
||||
}
|
||||
// NOTE: Don't send error here, since load_changed event will be triggered after this
|
||||
// true to stop other handlers from being invoked for the event. false to propagate the event further.
|
||||
true
|
||||
});
|
||||
_ => {}
|
||||
}
|
||||
});
|
||||
|
||||
let tls = Rc::clone(&observer);
|
||||
let tls_address = address.clone();
|
||||
webview.connect_load_failed_with_tls_errors(move |webview, uri, cert, err| {
|
||||
warn!(
|
||||
"Failed to load uri: {} with error: {}, cert: {}",
|
||||
redact_uri(uri),
|
||||
err,
|
||||
cert
|
||||
);
|
||||
if let Some(generation) = tls.attempts.current.take() {
|
||||
if generation != tls.messenger.generation() {
|
||||
return true;
|
||||
}
|
||||
show_failed_address(&tls_address, uri);
|
||||
let failure = tls::record_failure(webview, uri, cert, err, generation);
|
||||
tls
|
||||
.messenger
|
||||
.send_auth_event(AuthEvent::Error(generation, AuthError::Tls(failure)));
|
||||
}
|
||||
true
|
||||
});
|
||||
|
||||
webview.connect_load_failed(move |_webview, _event, uri, err| {
|
||||
if let Some(generation) = observer.attempts.current.take() {
|
||||
if generation != observer.messenger.generation() {
|
||||
return true;
|
||||
}
|
||||
if !uri.starts_with("globalprotectcallback:") && !err.matches(webkit2gtk::NetworkError::Cancelled) {
|
||||
warn!("Failed to load uri: {} with error: {}", redact_uri(uri), err);
|
||||
show_failed_address(&address, uri);
|
||||
let error = if err.kind::<webkit2gtk::gio::TlsError>().is_some() {
|
||||
AuthError::Tls(super::tls::TlsFailure {
|
||||
host: url::Url::parse(uri)
|
||||
.ok()
|
||||
.and_then(|uri| uri.host_str().map(str::to_owned))
|
||||
.unwrap_or_default(),
|
||||
reason: super::tls::TlsFailureReason::Handshake,
|
||||
can_continue: false,
|
||||
})
|
||||
} else {
|
||||
AuthError::LoadFailed(anyhow::anyhow!("{}", err))
|
||||
};
|
||||
observer.messenger.send_auth_event(AuthEvent::Error(generation, error));
|
||||
}
|
||||
}
|
||||
true
|
||||
});
|
||||
}
|
||||
|
||||
// A failed provisional load may leave WebView.uri unset.
|
||||
fn show_failed_address(entry: >k::Entry, uri: &str) {
|
||||
entry.set_text(&super::address_bar::display_address(Some(uri)));
|
||||
entry.set_position(0);
|
||||
}
|
||||
|
||||
fn read_navigation_html(webview: &webkit2gtk::WebView, messenger: Arc<AuthMessenger>, generation: u64) {
|
||||
webview.evaluate_javascript(
|
||||
"document.documentElement.outerHTML",
|
||||
None,
|
||||
None,
|
||||
Cancellable::NONE,
|
||||
move |result| match result {
|
||||
Ok(value) => messenger.read_from_html(&value.to_string(), generation),
|
||||
Err(err) => warn!("Failed to get html: {}", err),
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::NavigationAttempts;
|
||||
|
||||
#[test]
|
||||
fn cancelled_load_keeps_its_generation_until_replacement_starts() {
|
||||
let attempts = NavigationAttempts::default();
|
||||
attempts.started(0);
|
||||
attempts.pending.set(Some(2));
|
||||
// The previous load's cancellation/finish arrives after retry generation advances.
|
||||
assert_eq!(attempts.current.take(), Some(0));
|
||||
attempts.started(2);
|
||||
assert_eq!(attempts.current.take(), Some(2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn requested_generation_survives_attempt_changes_before_native_start() {
|
||||
let attempts = NavigationAttempts::default();
|
||||
attempts.pending.set(Some(2));
|
||||
attempts.started(3);
|
||||
assert_eq!(attempts.current.take(), Some(2));
|
||||
// User navigation after that load starts in the current attempt.
|
||||
attempts.started(3);
|
||||
assert_eq!(attempts.current.take(), Some(3));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use anyhow::Context;
|
||||
use gtk::prelude::*;
|
||||
use webkit2gtk::WebView;
|
||||
|
||||
use super::super::{
|
||||
auth_messenger::{AuthEvent, AuthMessenger},
|
||||
recovery::RecoveryStatus,
|
||||
};
|
||||
|
||||
const CONTROLS_KEY: &str = "gpauth-recovery-controls";
|
||||
|
||||
struct RecoveryRow {
|
||||
row: gtk::Box,
|
||||
spinner: gtk::Spinner,
|
||||
label: gtk::Label,
|
||||
retry: gtk::Button,
|
||||
proceed: gtk::Button,
|
||||
cancel: gtk::Button,
|
||||
detail: gtk::Label,
|
||||
}
|
||||
|
||||
pub(super) fn install(webview: &WebView, header: >k::Box, messenger: Arc<AuthMessenger>) -> anyhow::Result<()> {
|
||||
let row = gtk::Box::new(gtk::Orientation::Horizontal, 8);
|
||||
// Align status text with the address text's 6px inset and native 1px border.
|
||||
row.set_margin_start(7);
|
||||
let spinner = gtk::Spinner::new();
|
||||
spinner.set_valign(gtk::Align::Center);
|
||||
let label = gtk::Label::new(None);
|
||||
label.set_xalign(0.0);
|
||||
label.set_ellipsize(gtk::pango::EllipsizeMode::End);
|
||||
let detail = gtk::Label::new(None);
|
||||
detail.set_xalign(0.0);
|
||||
detail.set_ellipsize(gtk::pango::EllipsizeMode::End);
|
||||
detail.style_context().add_class("dim-label");
|
||||
detail.set_no_show_all(true);
|
||||
let copy = gtk::Box::new(gtk::Orientation::Vertical, 2);
|
||||
copy.set_valign(gtk::Align::Center);
|
||||
copy.pack_start(&label, false, false, 0);
|
||||
copy.pack_start(&detail, false, false, 0);
|
||||
copy.show();
|
||||
let retry = super::action_button("Try Again")?;
|
||||
retry.set_valign(gtk::Align::Center);
|
||||
let proceed = super::action_button("Continue Anyway…")?;
|
||||
proceed.set_valign(gtk::Align::Center);
|
||||
proceed.set_no_show_all(true);
|
||||
let cancel = super::action_button("Cancel")?;
|
||||
cancel.set_valign(gtk::Align::Center);
|
||||
// Showing or raising the window must not override recovery-state visibility.
|
||||
row.set_no_show_all(true);
|
||||
spinner.set_no_show_all(true);
|
||||
retry.set_no_show_all(true);
|
||||
label.show();
|
||||
cancel.set_no_show_all(true);
|
||||
let retry_messenger = Arc::clone(&messenger);
|
||||
retry.connect_clicked(move |_| retry_messenger.send_auth_event(AuthEvent::Retry));
|
||||
let proceed_messenger = Arc::clone(&messenger);
|
||||
proceed.connect_clicked(move |_| proceed_messenger.send_auth_event(AuthEvent::RequestTlsException));
|
||||
cancel.connect_clicked(move |_| messenger.send_auth_event(AuthEvent::Close));
|
||||
row.pack_start(&spinner, false, false, 0);
|
||||
row.pack_start(©, true, true, 0);
|
||||
row.pack_start(&retry, false, false, 0);
|
||||
row.pack_start(&proceed, false, false, 0);
|
||||
row.pack_start(&cancel, false, false, 0);
|
||||
header.pack_start(&row, false, false, 0);
|
||||
// The WebView owns the controls for exactly its native lifetime, on the GTK thread.
|
||||
unsafe {
|
||||
webview.set_data(
|
||||
CONTROLS_KEY,
|
||||
RecoveryRow {
|
||||
row,
|
||||
spinner,
|
||||
label,
|
||||
retry,
|
||||
proceed,
|
||||
cancel,
|
||||
detail,
|
||||
},
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn update(webview: &WebView, status: RecoveryStatus) -> anyhow::Result<()> {
|
||||
let controls = unsafe { webview.data::<RecoveryRow>(CONTROLS_KEY) }.context("Recovery controls are unavailable")?;
|
||||
let controls = unsafe { controls.as_ref() };
|
||||
controls.label.set_text(status.message());
|
||||
controls.detail.set_text(status.detail());
|
||||
controls.detail.set_visible(!status.detail().is_empty());
|
||||
controls.retry.set_visible(status.can_retry());
|
||||
controls.proceed.set_visible(status.can_continue());
|
||||
controls.cancel.set_visible(status.blocks_page());
|
||||
controls.spinner.set_visible(status.is_busy());
|
||||
if status.is_busy() {
|
||||
controls.spinner.start();
|
||||
} else {
|
||||
controls.spinner.stop();
|
||||
}
|
||||
controls.row.set_visible(status != RecoveryStatus::Hidden);
|
||||
webview.set_sensitive(!status.blocks_page());
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
use std::{
|
||||
cell::{Cell, RefCell},
|
||||
rc::Rc,
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
use anyhow::Context;
|
||||
use gtk::prelude::*;
|
||||
use webkit2gtk::{
|
||||
WebContextExt, WebView, WebViewExt,
|
||||
gio::{TlsCertificate, TlsCertificateFlags},
|
||||
};
|
||||
|
||||
use super::super::{
|
||||
auth_messenger::{AuthEvent, AuthMessenger},
|
||||
tls::{TlsFailure, TlsFailureReason},
|
||||
};
|
||||
|
||||
const TLS_KEY: &str = "gpauth-tls";
|
||||
|
||||
#[derive(Clone)]
|
||||
struct PendingCertificate {
|
||||
generation: u64,
|
||||
certificate: TlsCertificate,
|
||||
failure: TlsFailure,
|
||||
}
|
||||
|
||||
struct TlsState {
|
||||
pending: RefCell<Option<PendingCertificate>>,
|
||||
confirmation_open: Cell<bool>,
|
||||
messenger: Arc<AuthMessenger>,
|
||||
}
|
||||
|
||||
pub(super) fn install(webview: &WebView, messenger: Arc<AuthMessenger>) {
|
||||
unsafe {
|
||||
webview.set_data(
|
||||
TLS_KEY,
|
||||
Rc::new(TlsState {
|
||||
pending: RefCell::new(None),
|
||||
confirmation_open: Cell::new(false),
|
||||
messenger,
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn state(webview: &WebView) -> anyhow::Result<Rc<TlsState>> {
|
||||
let data = unsafe { webview.data::<Rc<TlsState>>(TLS_KEY) }.context("TLS controls are unavailable")?;
|
||||
Ok(unsafe { data.as_ref() }.clone())
|
||||
}
|
||||
|
||||
pub(super) fn record_failure(
|
||||
webview: &WebView,
|
||||
uri: &str,
|
||||
certificate: &TlsCertificate,
|
||||
flags: TlsCertificateFlags,
|
||||
generation: u64,
|
||||
) -> TlsFailure {
|
||||
let reason = if flags.contains(TlsCertificateFlags::EXPIRED) {
|
||||
TlsFailureReason::Expired
|
||||
} else if flags.contains(TlsCertificateFlags::NOT_ACTIVATED) {
|
||||
TlsFailureReason::NotYetValid
|
||||
} else if flags.contains(TlsCertificateFlags::BAD_IDENTITY) {
|
||||
TlsFailureReason::HostnameMismatch
|
||||
} else if flags.contains(TlsCertificateFlags::UNKNOWN_CA) {
|
||||
TlsFailureReason::Untrusted
|
||||
} else {
|
||||
TlsFailureReason::InvalidCertificate
|
||||
};
|
||||
let host = url::Url::parse(uri)
|
||||
.ok()
|
||||
.filter(|uri| uri.scheme() == "https")
|
||||
.and_then(|uri| uri.host_str().map(str::to_owned));
|
||||
let failure = TlsFailure {
|
||||
host: host.clone().unwrap_or_default(),
|
||||
reason,
|
||||
can_continue: reason.is_certificate_error() && host.is_some(),
|
||||
};
|
||||
if let Ok(state) = state(webview) {
|
||||
*state.pending.borrow_mut() = host.map(|_| PendingCertificate {
|
||||
generation,
|
||||
certificate: certificate.clone(),
|
||||
failure: failure.clone(),
|
||||
});
|
||||
}
|
||||
failure
|
||||
}
|
||||
|
||||
pub(super) fn confirm(webview: &WebView) -> anyhow::Result<()> {
|
||||
let state = state(webview)?;
|
||||
let pending = state
|
||||
.pending
|
||||
.borrow()
|
||||
.clone()
|
||||
.context("No certificate error is awaiting confirmation")?;
|
||||
if pending.generation != state.messenger.generation() || state.confirmation_open.get() {
|
||||
return Ok(());
|
||||
}
|
||||
let parent = webview
|
||||
.toplevel()
|
||||
.and_then(|widget| widget.downcast::<gtk::Window>().ok())
|
||||
.context("Auth window is unavailable")?;
|
||||
let dialog = gtk::Dialog::builder()
|
||||
.transient_for(&parent)
|
||||
.modal(true)
|
||||
.destroy_with_parent(true)
|
||||
.title("Certificate Warning")
|
||||
.use_header_bar(0)
|
||||
.resizable(false)
|
||||
.build();
|
||||
let content = dialog.content_area();
|
||||
content.set_spacing(12);
|
||||
content.set_margin_top(18);
|
||||
content.set_margin_bottom(18);
|
||||
content.set_margin_start(18);
|
||||
content.set_margin_end(18);
|
||||
let title = gtk::Label::new(None);
|
||||
title.set_markup(&format!(
|
||||
"<b>{}</b>",
|
||||
gtk::glib::markup_escape_text(&pending.failure.confirmation_title())
|
||||
));
|
||||
let message = gtk::Label::new(Some(&pending.failure.confirmation_message()));
|
||||
for label in [&title, &message] {
|
||||
label.set_xalign(0.0);
|
||||
label.set_line_wrap(true);
|
||||
label.set_line_wrap_mode(gtk::pango::WrapMode::WordChar);
|
||||
label.set_max_width_chars(48);
|
||||
content.pack_start(label, false, false, 0);
|
||||
}
|
||||
let actions = gtk::ButtonBox::new(gtk::Orientation::Horizontal);
|
||||
actions.set_layout(gtk::ButtonBoxStyle::End);
|
||||
actions.set_spacing(8);
|
||||
actions.set_margin_top(6);
|
||||
content.pack_start(&actions, false, false, 0);
|
||||
for (label, response) in [
|
||||
("Cancel", gtk::ResponseType::Cancel),
|
||||
("Continue Anyway", gtk::ResponseType::Accept),
|
||||
] {
|
||||
let button = super::action_button(label)?;
|
||||
button.set_can_default(true);
|
||||
let weak_dialog = dialog.downgrade();
|
||||
button.connect_clicked(move |_| {
|
||||
if let Some(dialog) = weak_dialog.upgrade() {
|
||||
dialog.response(response);
|
||||
}
|
||||
});
|
||||
actions.pack_start(&button, false, false, 0);
|
||||
actions.set_child_non_homogeneous(&button, true);
|
||||
if response == gtk::ResponseType::Cancel {
|
||||
dialog.set_default(Some(&button));
|
||||
}
|
||||
}
|
||||
state.confirmation_open.set(true);
|
||||
let weak = webview.downgrade();
|
||||
dialog.connect_response(move |dialog, response| {
|
||||
state.confirmation_open.set(false);
|
||||
if response == gtk::ResponseType::Accept && pending.generation == state.messenger.generation() {
|
||||
if let Some(webview) = weak.upgrade() {
|
||||
let current = state.pending.borrow().as_ref().is_some_and(|current| {
|
||||
current.generation == pending.generation
|
||||
&& current.certificate == pending.certificate
|
||||
&& current.failure.host == pending.failure.host
|
||||
});
|
||||
if current {
|
||||
if let Some(context) = webview.context() {
|
||||
// This single-window auth process discards its WebContext on exit.
|
||||
context.allow_tls_certificate_for_host(&pending.certificate, &pending.failure.host);
|
||||
state.pending.borrow_mut().take();
|
||||
state
|
||||
.messenger
|
||||
.send_auth_event(AuthEvent::TlsAccepted(pending.generation));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
dialog.close();
|
||||
});
|
||||
dialog.show_all();
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,58 +1,149 @@
|
||||
use std::{ffi::c_void, ptr};
|
||||
use std::{
|
||||
cell::{Cell, RefCell},
|
||||
collections::HashMap,
|
||||
ffi::c_void,
|
||||
ptr,
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
use anyhow::{Context, bail};
|
||||
use block2::{DynBlock, RcBlock};
|
||||
use gpapi::utils::redact::redact_uri;
|
||||
use log::{info, warn};
|
||||
use objc2::{
|
||||
DefinedClass, MainThreadOnly, define_class,
|
||||
ffi::{OBJC_ASSOCIATION_RETAIN_NONATOMIC, objc_setAssociatedObject},
|
||||
DefinedClass, MainThreadOnly, Message, define_class,
|
||||
ffi::{OBJC_ASSOCIATION_RETAIN_NONATOMIC, objc_getAssociatedObject, objc_setAssociatedObject},
|
||||
msg_send,
|
||||
rc::Retained,
|
||||
runtime::{AnyObject, ProtocolObject, Sel},
|
||||
sel,
|
||||
};
|
||||
use objc2_foundation::{
|
||||
MainThreadMarker, NSError, NSObject, NSObjectNSKeyValueCoding, NSObjectProtocol, NSString, NSURL,
|
||||
NSURLAuthenticationChallenge, NSURLAuthenticationMethodServerTrust, NSURLCredential, NSURLRequest,
|
||||
NSURLAuthenticationChallenge, NSURLAuthenticationMethodServerTrust, NSURLCredential, NSURLErrorCancelled,
|
||||
NSURLErrorDomain, NSURLErrorFailingURLErrorKey, NSURLErrorUnsupportedURL, NSURLRequest,
|
||||
NSURLSessionAuthChallengeDisposition,
|
||||
};
|
||||
use objc2_web_kit::{WKNavigationDelegate, WKWebView};
|
||||
use objc2_web_kit::{WKNavigation, WKNavigationDelegate, WKWebView};
|
||||
use tauri::webview::PlatformWebview;
|
||||
|
||||
use super::webview_auth::PlatformWebviewExt;
|
||||
use super::{
|
||||
auth_messenger::{AuthError, AuthEvent, AuthMessenger},
|
||||
recovery::RecoveryStatus,
|
||||
webview_auth::PlatformWebviewExt,
|
||||
};
|
||||
|
||||
static TLS_NAVIGATION_DELEGATE_KEY: u8 = 0;
|
||||
#[path = "macos/address_bar.rs"]
|
||||
mod address_bar;
|
||||
#[path = "macos/recovery_row.rs"]
|
||||
mod recovery_row;
|
||||
#[path = "macos/tls.rs"]
|
||||
mod tls;
|
||||
|
||||
struct TlsNavigationDelegateIvars {
|
||||
static AUTH_NAVIGATION_DELEGATE_KEY: u8 = 0;
|
||||
|
||||
struct AuthNavigationDelegateIvars {
|
||||
original: Retained<ProtocolObject<dyn WKNavigationDelegate>>,
|
||||
messenger: Arc<AuthMessenger>,
|
||||
ignore_tls_errors: Cell<bool>,
|
||||
navigations: RefCell<HashMap<usize, (Retained<WKNavigation>, u64)>>,
|
||||
tls: RefCell<tls::TlsState>,
|
||||
}
|
||||
|
||||
define_class!(
|
||||
#[unsafe(super = NSObject)]
|
||||
#[thread_kind = MainThreadOnly]
|
||||
#[ivars = TlsNavigationDelegateIvars]
|
||||
struct TlsNavigationDelegate;
|
||||
#[ivars = AuthNavigationDelegateIvars]
|
||||
struct AuthNavigationDelegate;
|
||||
|
||||
unsafe impl NSObjectProtocol for TlsNavigationDelegate {}
|
||||
unsafe impl NSObjectProtocol for AuthNavigationDelegate {}
|
||||
|
||||
#[allow(non_snake_case)]
|
||||
unsafe impl WKNavigationDelegate for TlsNavigationDelegate {
|
||||
unsafe impl WKNavigationDelegate for AuthNavigationDelegate {
|
||||
#[unsafe(method(webView:didStartProvisionalNavigation:))]
|
||||
unsafe fn webView_didStartProvisionalNavigation(&self, webview: &WKWebView, navigation: Option<&WKNavigation>) {
|
||||
self.track_navigation(navigation);
|
||||
self.ivars().messenger.cancel_raise_window();
|
||||
let original = &self.ivars().original;
|
||||
if original.respondsToSelector(sel!(webView:didStartProvisionalNavigation:)) {
|
||||
unsafe { original.webView_didStartProvisionalNavigation(webview, navigation); }
|
||||
}
|
||||
}
|
||||
|
||||
#[unsafe(method(webView:didCommitNavigation:))]
|
||||
unsafe fn webView_didCommitNavigation(&self, webview: &WKWebView, navigation: Option<&WKNavigation>) {
|
||||
if let Some(generation) = self.navigation_generation(navigation) {
|
||||
info!("Started loading page: {}", navigation_address(webview));
|
||||
read_navigation_html(webview, Arc::clone(&self.ivars().messenger), generation);
|
||||
}
|
||||
let original = &self.ivars().original;
|
||||
if original.respondsToSelector(sel!(webView:didCommitNavigation:)) {
|
||||
unsafe { original.webView_didCommitNavigation(webview, navigation); }
|
||||
}
|
||||
}
|
||||
|
||||
#[unsafe(method(webView:didFinishNavigation:))]
|
||||
unsafe fn webView_didFinishNavigation(&self, webview: &WKWebView, navigation: Option<&WKNavigation>) {
|
||||
if let Some(generation) = self.finish_navigation(navigation) {
|
||||
info!("Finished loading page: {}", navigation_address(webview));
|
||||
read_navigation_html(webview, Arc::clone(&self.ivars().messenger), generation);
|
||||
self.ivars().messenger.send_auth_event(AuthEvent::PageLoaded(generation));
|
||||
}
|
||||
let original = &self.ivars().original;
|
||||
if original.respondsToSelector(sel!(webView:didFinishNavigation:)) {
|
||||
unsafe { original.webView_didFinishNavigation(webview, navigation); }
|
||||
}
|
||||
}
|
||||
|
||||
#[unsafe(method(webView:didFailProvisionalNavigation:withError:))]
|
||||
unsafe fn webView_didFailProvisionalNavigation_withError(&self, webview: &WKWebView, navigation: Option<&WKNavigation>, error: &NSError) {
|
||||
self.report_load_failure(webview, navigation, error);
|
||||
let original = &self.ivars().original;
|
||||
if original.respondsToSelector(sel!(webView:didFailProvisionalNavigation:withError:)) {
|
||||
unsafe { original.webView_didFailProvisionalNavigation_withError(webview, navigation, error); }
|
||||
}
|
||||
}
|
||||
|
||||
#[unsafe(method(webView:didFailNavigation:withError:))]
|
||||
unsafe fn webView_didFailNavigation_withError(&self, webview: &WKWebView, navigation: Option<&WKNavigation>, error: &NSError) {
|
||||
self.report_load_failure(webview, navigation, error);
|
||||
let original = &self.ivars().original;
|
||||
if original.respondsToSelector(sel!(webView:didFailNavigation:withError:)) {
|
||||
unsafe { original.webView_didFailNavigation_withError(webview, navigation, error); }
|
||||
}
|
||||
}
|
||||
|
||||
#[unsafe(method(webView:didReceiveAuthenticationChallenge:completionHandler:))]
|
||||
unsafe fn webView_didReceiveAuthenticationChallenge_completionHandler(
|
||||
&self,
|
||||
_webview: &WKWebView,
|
||||
webview: &WKWebView,
|
||||
challenge: &NSURLAuthenticationChallenge,
|
||||
completion_handler: &DynBlock<dyn Fn(NSURLSessionAuthChallengeDisposition, *mut NSURLCredential)>,
|
||||
) {
|
||||
// Preserve Wry's normal authentication challenge handling unless the caller
|
||||
// approved this certificate or requested the ignore-TLS-errors behavior.
|
||||
let protection_space = challenge.protectionSpace();
|
||||
let is_server_trust = protection_space
|
||||
.authenticationMethod()
|
||||
.isEqualToString(unsafe { NSURLAuthenticationMethodServerTrust });
|
||||
|
||||
let is_server_trust = protection_space.authenticationMethod().isEqualToString(unsafe { NSURLAuthenticationMethodServerTrust });
|
||||
let server_trust: *mut AnyObject = if is_server_trust {
|
||||
msg_send![&*protection_space, serverTrust]
|
||||
} else { ptr::null_mut() };
|
||||
let approved = std::ptr::NonNull::new(server_trust.cast::<objc2_security::SecTrust>()).is_some_and(|trust| {
|
||||
self.ivars().tls.borrow().allows(&protection_space.host().to_string(), unsafe { trust.as_ref() })
|
||||
});
|
||||
if !self.ivars().ignore_tls_errors.get() && !approved {
|
||||
let original = &self.ivars().original;
|
||||
if original.respondsToSelector(sel!(webView:didReceiveAuthenticationChallenge:completionHandler:)) {
|
||||
unsafe { original.webView_didReceiveAuthenticationChallenge_completionHandler(webview, challenge, completion_handler); }
|
||||
} else {
|
||||
completion_handler.call((challenge_disposition(false), ptr::null_mut()));
|
||||
}
|
||||
return;
|
||||
}
|
||||
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;
|
||||
@@ -64,7 +155,7 @@ define_class!(
|
||||
}
|
||||
}
|
||||
|
||||
impl TlsNavigationDelegate {
|
||||
impl AuthNavigationDelegate {
|
||||
#[unsafe(method(respondsToSelector:))]
|
||||
fn responds_to_selector(&self, selector: Sel) -> bool {
|
||||
let responds: bool = unsafe { msg_send![super(self), respondsToSelector: selector] };
|
||||
@@ -82,10 +173,92 @@ define_class!(
|
||||
}
|
||||
);
|
||||
|
||||
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] }
|
||||
impl AuthNavigationDelegate {
|
||||
fn track_navigation(&self, navigation: Option<&WKNavigation>) {
|
||||
if let Some(navigation) = navigation {
|
||||
let key = navigation as *const WKNavigation as usize;
|
||||
self
|
||||
.ivars()
|
||||
.navigations
|
||||
.borrow_mut()
|
||||
.entry(key)
|
||||
.or_insert_with(|| (navigation.retain(), self.ivars().messenger.generation()));
|
||||
}
|
||||
}
|
||||
|
||||
fn navigation_generation(&self, navigation: Option<&WKNavigation>) -> Option<u64> {
|
||||
let key = navigation? as *const WKNavigation as usize;
|
||||
self
|
||||
.ivars()
|
||||
.navigations
|
||||
.borrow()
|
||||
.get(&key)
|
||||
.map(|(_, generation)| *generation)
|
||||
}
|
||||
|
||||
fn finish_navigation(&self, navigation: Option<&WKNavigation>) -> Option<u64> {
|
||||
let key = navigation? as *const WKNavigation as usize;
|
||||
self
|
||||
.ivars()
|
||||
.navigations
|
||||
.borrow_mut()
|
||||
.remove(&key)
|
||||
.map(|(_, generation)| generation)
|
||||
}
|
||||
|
||||
fn report_load_failure(&self, webview: &WKWebView, navigation: Option<&WKNavigation>, error: &NSError) {
|
||||
let Some(generation) = self.finish_navigation(navigation) else {
|
||||
return;
|
||||
};
|
||||
if generation != self.ivars().messenger.generation() {
|
||||
return;
|
||||
}
|
||||
let is_url_error = error.domain().isEqualToString(unsafe { NSURLErrorDomain });
|
||||
if is_url_error && error.code() == NSURLErrorCancelled {
|
||||
return;
|
||||
}
|
||||
if is_url_error && error.code() == NSURLErrorUnsupportedURL {
|
||||
let callback = error
|
||||
.userInfo()
|
||||
.objectForKey(unsafe { NSURLErrorFailingURLErrorKey })
|
||||
.and_then(|value| value.downcast::<NSURL>().ok())
|
||||
.and_then(|url| url.scheme());
|
||||
if callback.is_some_and(|scheme| scheme.to_string() == "globalprotectcallback") {
|
||||
return;
|
||||
}
|
||||
}
|
||||
let messenger = &self.ivars().messenger;
|
||||
if let Some(failure) = self.ivars().tls.borrow_mut().record_failure(webview, error, generation) {
|
||||
messenger.send_auth_event(AuthEvent::Error(generation, failure));
|
||||
return;
|
||||
}
|
||||
// Log codes rather than NSError descriptions, which may contain callback URLs.
|
||||
messenger.send_auth_event(AuthEvent::Error(
|
||||
generation,
|
||||
AuthError::LoadFailed(anyhow::anyhow!(
|
||||
"Navigation failed: {} ({})",
|
||||
error.domain(),
|
||||
error.code()
|
||||
)),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
fn navigation_delegate(webview: &WKWebView) -> Option<Retained<AuthNavigationDelegate>> {
|
||||
unsafe {
|
||||
let pointer = objc_getAssociatedObject(
|
||||
webview as *const WKWebView as *mut AnyObject,
|
||||
&AUTH_NAVIGATION_DELEGATE_KEY as *const u8 as *const c_void,
|
||||
)
|
||||
.cast::<AuthNavigationDelegate>();
|
||||
Retained::retain(pointer.cast_mut())
|
||||
}
|
||||
}
|
||||
|
||||
fn track_requested_navigation(webview: &WKWebView, navigation: Option<&WKNavigation>) {
|
||||
let delegate = navigation_delegate(webview);
|
||||
if let Some(delegate) = delegate {
|
||||
delegate.track_navigation(navigation);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -97,15 +270,22 @@ fn challenge_disposition(is_server_trust: bool) -> NSURLSessionAuthChallengeDisp
|
||||
}
|
||||
}
|
||||
|
||||
fn install_tls_navigation_delegate(webview: &WKWebView) -> anyhow::Result<()> {
|
||||
fn install_navigation_delegate(webview: &WKWebView, messenger: Arc<AuthMessenger>) -> 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);
|
||||
let delegate = AuthNavigationDelegate::alloc(mtm).set_ivars(AuthNavigationDelegateIvars {
|
||||
original,
|
||||
messenger,
|
||||
ignore_tls_errors: Cell::new(false),
|
||||
tls: RefCell::new(tls::TlsState::default()),
|
||||
navigations: RefCell::new(HashMap::new()),
|
||||
});
|
||||
let delegate: Retained<AuthNavigationDelegate> = unsafe { msg_send![super(delegate), init] };
|
||||
|
||||
unsafe {
|
||||
objc_setAssociatedObject(
|
||||
webview as *const WKWebView as *mut AnyObject,
|
||||
&TLS_NAVIGATION_DELEGATE_KEY as *const u8 as *const c_void,
|
||||
&AUTH_NAVIGATION_DELEGATE_KEY as *const u8 as *const c_void,
|
||||
Retained::as_ptr(&delegate).cast_mut().cast(),
|
||||
OBJC_ASSOCIATION_RETAIN_NONATOMIC,
|
||||
);
|
||||
@@ -139,9 +319,47 @@ mod tests {
|
||||
}
|
||||
|
||||
impl PlatformWebviewExt for PlatformWebview {
|
||||
fn install_auth_controls(&self, window: &tauri::WebviewWindow, messenger: Arc<AuthMessenger>) -> anyhow::Result<()> {
|
||||
let webview: &WKWebView = unsafe { &*self.inner().cast() };
|
||||
address_bar::install(webview)?;
|
||||
install_navigation_delegate(webview, Arc::clone(&messenger))?;
|
||||
recovery_row::install(webview, messenger)?;
|
||||
let window_handle = window.clone();
|
||||
window.on_window_event(move |event| {
|
||||
if matches!(
|
||||
event,
|
||||
tauri::WindowEvent::Resized(_) | tauri::WindowEvent::ScaleFactorChanged { .. }
|
||||
) {
|
||||
let _ = window_handle.with_webview(|webview| {
|
||||
let webview: &WKWebView = unsafe { &*webview.inner().cast() };
|
||||
address_bar::resize(webview);
|
||||
});
|
||||
}
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn set_recovery_status(&self, status: RecoveryStatus) -> anyhow::Result<()> {
|
||||
let webview: &WKWebView = unsafe { &*self.inner().cast() };
|
||||
recovery_row::update(webview, status)
|
||||
}
|
||||
|
||||
fn stop_loading(&self) {
|
||||
let webview: &WKWebView = unsafe { &*self.inner().cast() };
|
||||
unsafe {
|
||||
webview.stopLoading();
|
||||
}
|
||||
}
|
||||
|
||||
fn confirm_tls_exception(&self) -> anyhow::Result<()> {
|
||||
tls::confirm(unsafe { &*self.inner().cast::<WKWebView>() })
|
||||
}
|
||||
|
||||
fn ignore_tls_errors(&self) -> anyhow::Result<()> {
|
||||
let webview: &WKWebView = unsafe { &*self.inner().cast() };
|
||||
install_tls_navigation_delegate(webview)
|
||||
let delegate = navigation_delegate(webview).context("Auth navigation delegate is unavailable")?;
|
||||
delegate.ivars().ignore_tls_errors.set(true);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn user_agent(&self) -> anyhow::Result<String> {
|
||||
@@ -173,7 +391,8 @@ impl PlatformWebviewExt for PlatformWebview {
|
||||
let url = NSURL::URLWithString(&NSString::from_str(url)).ok_or_else(|| anyhow::anyhow!("Invalid URL"))?;
|
||||
let request = NSURLRequest::requestWithURL(&url);
|
||||
|
||||
wv.loadRequest(&request);
|
||||
let navigation = wv.loadRequest(&request);
|
||||
track_requested_navigation(wv, navigation.as_deref());
|
||||
}
|
||||
|
||||
Ok(())
|
||||
@@ -182,31 +401,31 @@ impl PlatformWebviewExt for PlatformWebview {
|
||||
fn load_html(&self, html: &str) -> anyhow::Result<()> {
|
||||
unsafe {
|
||||
let wv: &WKWebView = &*self.inner().cast();
|
||||
wv.loadHTMLString_baseURL(&NSString::from_str(html), None);
|
||||
let navigation = wv.loadHTMLString_baseURL(&NSString::from_str(html), None);
|
||||
track_requested_navigation(wv, navigation.as_deref());
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn get_html(&self, callback: Box<dyn Fn(anyhow::Result<String>) + 'static>) {
|
||||
unsafe {
|
||||
let wv: &WKWebView = &*self.inner().cast();
|
||||
fn navigation_address(webview: &WKWebView) -> String {
|
||||
let url = unsafe { webview.URL() }.and_then(|url| url.absoluteString());
|
||||
redact_uri(&url.map(|url| url.to_string()).unwrap_or_default())
|
||||
}
|
||||
|
||||
let js_callback = RcBlock::new(move |body: *mut AnyObject, err: *mut NSError| {
|
||||
if let Some(err) = err.as_ref() {
|
||||
let code = err.code();
|
||||
let message = err.localizedDescription();
|
||||
callback(Err(anyhow::anyhow!("Error {}: {}", code, message)));
|
||||
} else {
|
||||
let body: &NSString = &*body.cast();
|
||||
callback(Ok(body.to_string()));
|
||||
}
|
||||
});
|
||||
|
||||
wv.evaluateJavaScript_completionHandler(
|
||||
&NSString::from_str("document.documentElement.outerHTML"),
|
||||
Some(&js_callback),
|
||||
);
|
||||
fn read_navigation_html(webview: &WKWebView, messenger: Arc<AuthMessenger>, generation: u64) {
|
||||
let callback = RcBlock::new(move |body: *mut AnyObject, error: *mut NSError| {
|
||||
if let Some(error) = unsafe { error.as_ref() } {
|
||||
warn!("Failed to get html: {} ({})", error.domain(), error.code());
|
||||
} else if let Some(body) = unsafe { body.as_ref() }.and_then(|body| body.downcast_ref::<NSString>()) {
|
||||
messenger.read_from_html(&body.to_string(), generation);
|
||||
}
|
||||
});
|
||||
unsafe {
|
||||
webview.evaluateJavaScript_completionHandler(
|
||||
&NSString::from_str("document.documentElement.outerHTML"),
|
||||
Some(&callback),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,240 @@
|
||||
use std::{ffi::c_void, ptr};
|
||||
|
||||
use anyhow::Context;
|
||||
use objc2::{
|
||||
DefinedClass, MainThreadOnly, Message, define_class,
|
||||
ffi::{OBJC_ASSOCIATION_RETAIN_NONATOMIC, objc_getAssociatedObject, objc_setAssociatedObject},
|
||||
msg_send,
|
||||
rc::Retained,
|
||||
runtime::{AnyObject, ProtocolObject},
|
||||
};
|
||||
use objc2_app_kit::{
|
||||
NSAccessibility, NSAutoresizingMaskOptions, NSBox, NSBoxType, NSColor, NSFont, NSLayoutConstraint,
|
||||
NSLayoutConstraintOrientation, NSLineBreakMode, NSTextView, NSToolbar, NSToolbarDelegate, NSToolbarDisplayMode,
|
||||
NSToolbarItem, NSToolbarItemIdentifier, NSWindowTitleVisibility, NSWindowToolbarStyle,
|
||||
};
|
||||
use objc2_foundation::{
|
||||
MainThreadMarker, NSArray, NSDictionary, NSKeyValueChangeKey, NSKeyValueObservingOptions, NSObject,
|
||||
NSObjectNSKeyValueObserverRegistration, NSObjectProtocol, NSPoint, NSRect, NSSize, NSString,
|
||||
};
|
||||
use objc2_web_kit::WKWebView;
|
||||
|
||||
use super::super::address_bar::{LOADING_ADDRESS, display_address};
|
||||
|
||||
static ADDRESS_TOOLBAR_KEY: u8 = 0;
|
||||
const ADDRESS_ITEM_ID: &str = "com.yuezk.gpauth.address";
|
||||
|
||||
define_class!(
|
||||
#[unsafe(super = NSTextView)]
|
||||
#[thread_kind = MainThreadOnly]
|
||||
struct AddressView;
|
||||
|
||||
impl AddressView {
|
||||
#[unsafe(method(intrinsicContentSize))]
|
||||
fn intrinsic_content_size(&self) -> NSSize {
|
||||
// URL length must not determine the toolbar item's width.
|
||||
NSSize::new(-1.0, 22.0)
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
struct AddressToolbarIvars {
|
||||
webview: Retained<WKWebView>,
|
||||
address_view: Retained<NSTextView>,
|
||||
separator: Retained<NSBox>,
|
||||
}
|
||||
|
||||
define_class!(
|
||||
// The content view retains the delegate because NSToolbar's delegate is weak.
|
||||
// Drop unregisters URL observation before releasing the retained webview.
|
||||
#[unsafe(super = NSObject)]
|
||||
#[thread_kind = MainThreadOnly]
|
||||
#[ivars = AddressToolbarIvars]
|
||||
struct AddressToolbar;
|
||||
|
||||
unsafe impl NSObjectProtocol for AddressToolbar {}
|
||||
|
||||
unsafe impl NSToolbarDelegate for AddressToolbar {
|
||||
#[unsafe(method_id(toolbar:itemForItemIdentifier:willBeInsertedIntoToolbar:))]
|
||||
fn toolbar_item(
|
||||
&self,
|
||||
_toolbar: &NSToolbar,
|
||||
identifier: &NSToolbarItemIdentifier,
|
||||
inserting: bool,
|
||||
) -> Option<Retained<NSToolbarItem>> {
|
||||
if !inserting || !identifier.isEqualToString(&NSString::from_str(ADDRESS_ITEM_ID)) {
|
||||
None
|
||||
} else {
|
||||
let item = NSToolbarItem::initWithItemIdentifier(NSToolbarItem::alloc(self.mtm()), identifier);
|
||||
item.setLabel(&NSString::from_str("Sign-in page address"));
|
||||
item.setBordered(true);
|
||||
item.setView(Some(&self.ivars().address_view));
|
||||
Some(item)
|
||||
}
|
||||
}
|
||||
|
||||
#[unsafe(method_id(toolbarDefaultItemIdentifiers:))]
|
||||
fn default_items(&self, _toolbar: &NSToolbar) -> Retained<NSArray<NSToolbarItemIdentifier>> {
|
||||
NSArray::from_retained_slice(&[NSString::from_str(ADDRESS_ITEM_ID)])
|
||||
}
|
||||
|
||||
#[unsafe(method_id(toolbarAllowedItemIdentifiers:))]
|
||||
fn allowed_items(&self, _toolbar: &NSToolbar) -> Retained<NSArray<NSToolbarItemIdentifier>> {
|
||||
NSArray::from_retained_slice(&[NSString::from_str(ADDRESS_ITEM_ID)])
|
||||
}
|
||||
}
|
||||
|
||||
impl AddressToolbar {
|
||||
#[unsafe(method(observeValueForKeyPath:ofObject:change:context:))]
|
||||
fn observe_url(
|
||||
&self,
|
||||
_key_path: Option<&NSString>,
|
||||
_object: Option<&AnyObject>,
|
||||
_change: Option<&NSDictionary<NSKeyValueChangeKey, AnyObject>>,
|
||||
_context: *mut c_void,
|
||||
) {
|
||||
let uri = unsafe { self.ivars().webview.URL() }.and_then(|url| url.absoluteString());
|
||||
let address = display_address(uri.as_ref().map(|uri| uri.to_string()).as_deref());
|
||||
self.ivars().address_view.setString(&NSString::from_str(&address));
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
impl Drop for AddressToolbar {
|
||||
fn drop(&mut self) {
|
||||
// This private observer registers only URL and remains on the main thread.
|
||||
unsafe {
|
||||
self
|
||||
.ivars()
|
||||
.webview
|
||||
.removeObserver_forKeyPath(self, &NSString::from_str("URL"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn install(webview: &WKWebView) -> anyhow::Result<()> {
|
||||
let mtm = MainThreadMarker::new().context("Toolbar must be installed on the main thread")?;
|
||||
let parent = unsafe { webview.superview() }.context("Webview has no containing view")?;
|
||||
let window = webview.window().context("Webview has no window")?;
|
||||
parent.setWantsLayer(true);
|
||||
let address_view: Retained<AddressView> =
|
||||
unsafe { msg_send![AddressView::alloc(mtm), initWithFrame: NSRect::default()] };
|
||||
// Use one native text layout for display and selection.
|
||||
address_view.setString(&NSString::from_str(LOADING_ADDRESS));
|
||||
address_view.setDrawsBackground(false);
|
||||
// Keep NSTextView's visible-rect cursor tracking inside the address bar.
|
||||
address_view.setClipsToBounds(true);
|
||||
address_view.setRichText(false);
|
||||
address_view.setHorizontallyResizable(false);
|
||||
address_view.setVerticallyResizable(false);
|
||||
address_view.setTextContainerInset(NSSize::new(6.0, 3.0));
|
||||
address_view.setEditable(false);
|
||||
address_view.setSelectable(true);
|
||||
address_view.setFont(Some(&NSFont::systemFontOfSize(12.0)));
|
||||
address_view.setContentHuggingPriority_forOrientation(1.0, NSLayoutConstraintOrientation::Horizontal);
|
||||
address_view.setAccessibilityLabel(Some(&NSString::from_str("Sign-in page address")));
|
||||
if let Some(container) = unsafe { address_view.textContainer() } {
|
||||
container.setWidthTracksTextView(true);
|
||||
container.setLineFragmentPadding(0.0);
|
||||
container.setMaximumNumberOfLines(1);
|
||||
container.setLineBreakMode(NSLineBreakMode::ByTruncatingTail);
|
||||
}
|
||||
// AppKit measures the toolbar item's minimum and maximum width from its view.
|
||||
NSLayoutConstraint::activateConstraints(&NSArray::from_retained_slice(&[
|
||||
address_view.widthAnchor().constraintGreaterThanOrEqualToConstant(200.0),
|
||||
address_view.widthAnchor().constraintLessThanOrEqualToConstant(10000.0),
|
||||
address_view.heightAnchor().constraintEqualToConstant(22.0),
|
||||
]));
|
||||
let separator = NSBox::new(mtm);
|
||||
separator
|
||||
.setAutoresizingMask(NSAutoresizingMaskOptions::ViewWidthSizable | NSAutoresizingMaskOptions::ViewMinYMargin);
|
||||
separator.setBoxType(NSBoxType::Custom);
|
||||
separator.setBorderWidth(0.0);
|
||||
separator.setCornerRadius(0.0);
|
||||
separator.setFillColor(&NSColor::separatorColor());
|
||||
parent.addSubview(&separator);
|
||||
let delegate = AddressToolbar::alloc(mtm).set_ivars(AddressToolbarIvars {
|
||||
webview: webview.retain(),
|
||||
address_view: Retained::into_super(address_view),
|
||||
separator,
|
||||
});
|
||||
let delegate: Retained<AddressToolbar> = unsafe { msg_send![super(delegate), init] };
|
||||
// Observe the current URL independently of navigation callbacks.
|
||||
unsafe {
|
||||
webview.addObserver_forKeyPath_options_context(
|
||||
&delegate,
|
||||
&NSString::from_str("URL"),
|
||||
NSKeyValueObservingOptions::Initial,
|
||||
ptr::null_mut(),
|
||||
);
|
||||
objc_setAssociatedObject(
|
||||
Retained::as_ptr(&parent).cast_mut().cast(),
|
||||
&ADDRESS_TOOLBAR_KEY as *const u8 as *const c_void,
|
||||
Retained::as_ptr(&delegate).cast_mut().cast(),
|
||||
OBJC_ASSOCIATION_RETAIN_NONATOMIC,
|
||||
);
|
||||
}
|
||||
let toolbar = NSToolbar::initWithIdentifier(NSToolbar::alloc(mtm), &NSString::from_str("com.yuezk.gpauth.toolbar"));
|
||||
toolbar.setAllowsUserCustomization(false);
|
||||
toolbar.setDisplayMode(NSToolbarDisplayMode::IconOnly);
|
||||
toolbar.setDelegate(Some(ProtocolObject::from_ref(&*delegate)));
|
||||
window.setTitleVisibility(NSWindowTitleVisibility::Visible);
|
||||
if objc2::available!(macos = 11.0) {
|
||||
window.setToolbarStyle(NSWindowToolbarStyle::Expanded);
|
||||
}
|
||||
window.setToolbar(Some(&toolbar));
|
||||
window.setInitialFirstResponder(Some(webview));
|
||||
resize(webview);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn address_view(webview: &WKWebView) -> Option<Retained<NSTextView>> {
|
||||
let parent = unsafe { webview.superview() }?;
|
||||
let delegate = unsafe {
|
||||
objc_getAssociatedObject(
|
||||
Retained::as_ptr(&parent).cast_mut().cast(),
|
||||
&ADDRESS_TOOLBAR_KEY as *const u8 as *const c_void,
|
||||
)
|
||||
.cast::<AddressToolbar>()
|
||||
.as_ref()
|
||||
}?;
|
||||
Some(delegate.ivars().address_view.clone())
|
||||
}
|
||||
|
||||
pub(super) fn show_address(webview: &WKWebView, uri: &str) {
|
||||
if let Some(view) = address_view(webview) {
|
||||
view.setString(&NSString::from_str(&display_address(Some(uri))));
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn resize(webview: &WKWebView) {
|
||||
let Some(parent) = (unsafe { webview.superview() }) else {
|
||||
return;
|
||||
};
|
||||
let Some(window) = webview.window() else {
|
||||
return;
|
||||
};
|
||||
// Keep the native separator outside WebKit so page backgrounds cannot cover it.
|
||||
let content = parent.convertRect_fromView(window.contentLayoutRect(), None);
|
||||
let separator_height = 1.0 / window.backingScaleFactor();
|
||||
let recovery_height = super::recovery_row::layout(webview, content);
|
||||
let page_height = (content.size.height - recovery_height - separator_height).max(0.0);
|
||||
let delegate = unsafe {
|
||||
objc_getAssociatedObject(
|
||||
Retained::as_ptr(&parent).cast_mut().cast(),
|
||||
&ADDRESS_TOOLBAR_KEY as *const u8 as *const c_void,
|
||||
)
|
||||
.cast::<AddressToolbar>()
|
||||
.as_ref()
|
||||
};
|
||||
if let Some(delegate) = delegate {
|
||||
delegate.ivars().separator.setFrame(NSRect::new(
|
||||
NSPoint::new(content.origin.x, content.origin.y + page_height),
|
||||
NSSize::new(content.size.width, separator_height),
|
||||
));
|
||||
}
|
||||
webview.setFrame(NSRect::new(
|
||||
content.origin,
|
||||
NSSize::new(content.size.width, page_height),
|
||||
));
|
||||
}
|
||||
@@ -0,0 +1,332 @@
|
||||
use std::{
|
||||
cell::{Cell, RefCell},
|
||||
ffi::c_void,
|
||||
ptr,
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
use anyhow::Context;
|
||||
use block2::RcBlock;
|
||||
use objc2::{
|
||||
DefinedClass, MainThreadOnly, Message, define_class,
|
||||
ffi::{OBJC_ASSOCIATION_RETAIN_NONATOMIC, objc_getAssociatedObject, objc_setAssociatedObject},
|
||||
msg_send,
|
||||
rc::{Retained, Weak},
|
||||
runtime::AnyObject,
|
||||
sel,
|
||||
};
|
||||
use objc2_app_kit::{
|
||||
NSAutoresizingMaskOptions, NSBezelStyle, NSBox, NSBoxType, NSButton, NSColor, NSControlSize, NSEvent, NSEventMask,
|
||||
NSEventModifierFlags, NSFont, NSLineBreakMode, NSProgressIndicator, NSProgressIndicatorStyle, NSTextField,
|
||||
NSTitlePosition, NSView,
|
||||
};
|
||||
use objc2_foundation::{MainThreadMarker, NSObject, NSObjectProtocol, NSPoint, NSRect, NSSize, NSString};
|
||||
use objc2_web_kit::WKWebView;
|
||||
|
||||
use super::super::{
|
||||
auth_messenger::{AuthEvent, AuthMessenger},
|
||||
recovery::RecoveryStatus,
|
||||
};
|
||||
|
||||
static RECOVERY_ROW_KEY: u8 = 0;
|
||||
|
||||
struct RecoveryRowIvars {
|
||||
webview: Retained<WKWebView>,
|
||||
messenger: Arc<AuthMessenger>,
|
||||
row: Retained<NSBox>,
|
||||
blocker: Retained<NSView>,
|
||||
label: Retained<NSTextField>,
|
||||
detail: Retained<NSTextField>,
|
||||
proceed: Retained<NSButton>,
|
||||
status: Cell<RecoveryStatus>,
|
||||
spinner: Retained<NSProgressIndicator>,
|
||||
retry: Retained<NSButton>,
|
||||
cancel: Retained<NSButton>,
|
||||
keyboard_monitor: RefCell<Option<Retained<AnyObject>>>,
|
||||
}
|
||||
|
||||
define_class!(
|
||||
#[unsafe(super = NSObject)]
|
||||
#[thread_kind = MainThreadOnly]
|
||||
#[ivars = RecoveryRowIvars]
|
||||
struct RecoveryRow;
|
||||
|
||||
unsafe impl NSObjectProtocol for RecoveryRow {}
|
||||
|
||||
impl RecoveryRow {
|
||||
#[unsafe(method(retry:))]
|
||||
fn retry(&self, _sender: &AnyObject) {
|
||||
self.ivars().messenger.send_auth_event(AuthEvent::Retry);
|
||||
}
|
||||
|
||||
#[unsafe(method(continueTls:))]
|
||||
fn continue_tls(&self, _sender: &AnyObject) {
|
||||
self.ivars().messenger.send_auth_event(AuthEvent::RequestTlsException);
|
||||
}
|
||||
|
||||
#[unsafe(method(cancel:))]
|
||||
fn cancel(&self, _sender: &AnyObject) {
|
||||
self.ivars().messenger.send_auth_event(AuthEvent::Close);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
impl Drop for RecoveryRow {
|
||||
fn drop(&mut self) {
|
||||
if let Some(monitor) = self.ivars().keyboard_monitor.borrow_mut().take() {
|
||||
unsafe {
|
||||
NSEvent::removeMonitor(&monitor);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl RecoveryRow {
|
||||
fn handle_key(&self, event: &NSEvent) -> bool {
|
||||
let controls = self.ivars();
|
||||
if !controls.status.get().blocks_page() {
|
||||
return false;
|
||||
}
|
||||
let Some(window) = controls.webview.window() else {
|
||||
return false;
|
||||
};
|
||||
if window.attachedSheet().is_some() || event.window(self.mtm()).as_deref() != Some(&*window) {
|
||||
return false;
|
||||
}
|
||||
let responder = window.firstResponder();
|
||||
let modifiers = event.modifierFlags();
|
||||
if event.keyCode() == 48 && !modifiers.intersects(NSEventModifierFlags::Command | NSEventModifierFlags::Control) {
|
||||
// Explicit traversal also works when the system skips buttons in its default key loop.
|
||||
let Some(address) = super::address_bar::address_view(&controls.webview) else {
|
||||
return false;
|
||||
};
|
||||
let mut views: Vec<&NSView> = vec![&address];
|
||||
if !controls.retry.isHidden() {
|
||||
views.push(&controls.retry);
|
||||
}
|
||||
if !controls.proceed.isHidden() {
|
||||
views.push(&controls.proceed);
|
||||
}
|
||||
views.push(&controls.cancel);
|
||||
let current = responder.as_ref().and_then(|responder| {
|
||||
views.iter().position(|view| {
|
||||
ptr::eq(
|
||||
(*view) as *const NSView as *const c_void,
|
||||
Retained::as_ptr(responder).cast(),
|
||||
)
|
||||
})
|
||||
});
|
||||
let next = match current {
|
||||
Some(index) if modifiers.contains(NSEventModifierFlags::Shift) => (index + views.len() - 1) % views.len(),
|
||||
Some(index) => (index + 1) % views.len(),
|
||||
None => views.len() - 1,
|
||||
};
|
||||
window.makeFirstResponder(Some(views[next]));
|
||||
return true;
|
||||
}
|
||||
// If WebKit regains focus programmatically, do not deliver keys to the covered page.
|
||||
if responder
|
||||
.as_deref()
|
||||
.and_then(|responder| responder.downcast_ref::<NSView>())
|
||||
.is_some_and(|view| view.isDescendantOf(&controls.webview))
|
||||
{
|
||||
window.makeFirstResponder(Some(&controls.cancel));
|
||||
return true;
|
||||
}
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn install(webview: &WKWebView, messenger: Arc<AuthMessenger>) -> anyhow::Result<()> {
|
||||
let mtm = MainThreadMarker::new().context("Recovery controls require the main thread")?;
|
||||
let parent = unsafe { webview.superview() }.context("Webview has no containing view")?;
|
||||
let row = NSBox::new(mtm);
|
||||
// AppKit may resize the parent after the application's window resize callback.
|
||||
row.setAutoresizingMask(NSAutoresizingMaskOptions::ViewWidthSizable | NSAutoresizingMaskOptions::ViewMinYMargin);
|
||||
row.setBoxType(NSBoxType::Custom);
|
||||
row.setTitlePosition(NSTitlePosition::NoTitle);
|
||||
row.setContentViewMargins(NSSize::new(0.0, 0.0));
|
||||
row.setBorderWidth(0.0);
|
||||
row.setCornerRadius(0.0);
|
||||
row.setFillColor(&NSColor::windowBackgroundColor());
|
||||
let label = NSTextField::labelWithString(&NSString::new(), mtm);
|
||||
label.setFont(Some(&NSFont::systemFontOfSize(12.0)));
|
||||
label.setLineBreakMode(NSLineBreakMode::ByTruncatingTail);
|
||||
label.setAutoresizingMask(NSAutoresizingMaskOptions::ViewWidthSizable);
|
||||
let detail = NSTextField::labelWithString(&NSString::new(), mtm);
|
||||
detail.setFont(Some(&NSFont::systemFontOfSize(11.0)));
|
||||
detail.setTextColor(Some(&NSColor::secondaryLabelColor()));
|
||||
detail.setLineBreakMode(NSLineBreakMode::ByTruncatingTail);
|
||||
detail.setAutoresizingMask(NSAutoresizingMaskOptions::ViewWidthSizable);
|
||||
let spinner = NSProgressIndicator::new(mtm);
|
||||
spinner.setStyle(NSProgressIndicatorStyle::Spinning);
|
||||
spinner.setControlSize(NSControlSize::Small);
|
||||
spinner.setIndeterminate(true);
|
||||
let retry = unsafe { NSButton::buttonWithTitle_target_action(&NSString::from_str("Try Again"), None, None, mtm) };
|
||||
let cancel = unsafe { NSButton::buttonWithTitle_target_action(&NSString::from_str("Cancel"), None, None, mtm) };
|
||||
let proceed =
|
||||
unsafe { NSButton::buttonWithTitle_target_action(&NSString::from_str("Continue Anyway…"), None, None, mtm) };
|
||||
for button in [&retry, &proceed, &cancel] {
|
||||
button.setAutoresizingMask(NSAutoresizingMaskOptions::ViewMinXMargin);
|
||||
button.setBezelStyle(NSBezelStyle::Push);
|
||||
button.setControlSize(NSControlSize::Small);
|
||||
button.setFont(Some(&NSFont::systemFontOfSize(12.0)));
|
||||
row.addSubview(button);
|
||||
}
|
||||
row.addSubview(&label);
|
||||
row.addSubview(&detail);
|
||||
row.addSubview(&spinner);
|
||||
let blocker = NSView::new(mtm);
|
||||
blocker
|
||||
.setAutoresizingMask(NSAutoresizingMaskOptions::ViewWidthSizable | NSAutoresizingMaskOptions::ViewHeightSizable);
|
||||
parent.addSubview(&blocker);
|
||||
parent.addSubview(&row);
|
||||
row.setHidden(true);
|
||||
blocker.setHidden(true);
|
||||
let controller = RecoveryRow::alloc(mtm).set_ivars(RecoveryRowIvars {
|
||||
webview: webview.retain(),
|
||||
messenger,
|
||||
row,
|
||||
blocker,
|
||||
label,
|
||||
detail,
|
||||
proceed,
|
||||
status: Cell::new(RecoveryStatus::Hidden),
|
||||
spinner,
|
||||
retry,
|
||||
cancel,
|
||||
keyboard_monitor: RefCell::new(None),
|
||||
});
|
||||
let controller: Retained<RecoveryRow> = unsafe { msg_send![super(controller), init] };
|
||||
let weak_controller = Weak::from_retained(&controller);
|
||||
let handler = RcBlock::new(move |event: std::ptr::NonNull<NSEvent>| {
|
||||
let blocked = weak_controller
|
||||
.load()
|
||||
.is_some_and(|controller| controller.handle_key(unsafe { event.as_ref() }));
|
||||
if blocked { ptr::null_mut() } else { event.as_ptr() }
|
||||
});
|
||||
let monitor = unsafe { NSEvent::addLocalMonitorForEventsMatchingMask_handler(NSEventMask::KeyDown, &handler) }
|
||||
.context("Failed to guard keyboard input during sign-in recovery")?;
|
||||
*controller.ivars().keyboard_monitor.borrow_mut() = Some(monitor);
|
||||
unsafe {
|
||||
controller.ivars().retry.setTarget(Some(&controller));
|
||||
controller.ivars().retry.setAction(Some(sel!(retry:)));
|
||||
controller.ivars().proceed.setTarget(Some(&controller));
|
||||
controller.ivars().proceed.setAction(Some(sel!(continueTls:)));
|
||||
controller.ivars().cancel.setTarget(Some(&controller));
|
||||
controller.ivars().cancel.setAction(Some(sel!(cancel:)));
|
||||
objc_setAssociatedObject(
|
||||
Retained::as_ptr(&parent).cast_mut().cast(),
|
||||
&RECOVERY_ROW_KEY as *const u8 as *const c_void,
|
||||
Retained::as_ptr(&controller).cast_mut().cast(),
|
||||
OBJC_ASSOCIATION_RETAIN_NONATOMIC,
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn controller(webview: &WKWebView) -> Option<Retained<RecoveryRow>> {
|
||||
let parent = unsafe { webview.superview() }?;
|
||||
unsafe {
|
||||
let pointer = objc_getAssociatedObject(
|
||||
Retained::as_ptr(&parent).cast_mut().cast(),
|
||||
&RECOVERY_ROW_KEY as *const u8 as *const c_void,
|
||||
)
|
||||
.cast::<RecoveryRow>();
|
||||
Retained::retain(pointer.cast_mut())
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn update(webview: &WKWebView, status: RecoveryStatus) -> anyhow::Result<()> {
|
||||
let controller = controller(webview).context("Recovery controls are unavailable")?;
|
||||
let controls = controller.ivars();
|
||||
let was_blocking = controls.status.replace(status).blocks_page();
|
||||
let hidden = status == RecoveryStatus::Hidden;
|
||||
controls.label.setStringValue(&NSString::from_str(status.message()));
|
||||
controls.detail.setStringValue(&NSString::from_str(status.detail()));
|
||||
controls.detail.setHidden(status.detail().is_empty());
|
||||
controls.retry.setHidden(!status.can_retry());
|
||||
controls.proceed.setHidden(!status.can_continue());
|
||||
controls.cancel.setHidden(!status.blocks_page());
|
||||
controls.spinner.setHidden(!status.is_busy());
|
||||
unsafe {
|
||||
if status.is_busy() {
|
||||
controls.spinner.startAnimation(None);
|
||||
} else {
|
||||
controls.spinner.stopAnimation(None);
|
||||
}
|
||||
}
|
||||
controls.row.setHidden(hidden);
|
||||
controls.blocker.setHidden(!status.blocks_page());
|
||||
if was_blocking != status.blocks_page() {
|
||||
if let Some(window) = webview.window() {
|
||||
if !status.blocks_page() {
|
||||
window.makeFirstResponder(Some(webview));
|
||||
} else {
|
||||
window.makeFirstResponder(Some(&controls.cancel));
|
||||
}
|
||||
}
|
||||
}
|
||||
super::address_bar::resize(webview);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Position the row above the page and return the height reserved for it.
|
||||
pub(super) fn layout(webview: &WKWebView, content: NSRect) -> f64 {
|
||||
let Some(controller) = controller(webview) else {
|
||||
return 0.0;
|
||||
};
|
||||
let controls = controller.ivars();
|
||||
if controls.row.isHidden() {
|
||||
return 0.0;
|
||||
}
|
||||
let height = if controls.status.get().detail().is_empty() {
|
||||
36.0
|
||||
} else {
|
||||
52.0
|
||||
};
|
||||
let width = content.size.width;
|
||||
controls.row.setFrame(NSRect::new(
|
||||
NSPoint::new(content.origin.x, content.origin.y + content.size.height - height),
|
||||
NSSize::new(width, height),
|
||||
));
|
||||
controls.blocker.setFrame(NSRect::new(
|
||||
content.origin,
|
||||
NSSize::new(width, (content.size.height - height).max(0.0)),
|
||||
));
|
||||
controls.cancel.setFrame(NSRect::new(
|
||||
NSPoint::new(width - 80.0, (height - 26.0) / 2.0),
|
||||
NSSize::new(72.0, 26.0),
|
||||
));
|
||||
controls.retry.setFrame(NSRect::new(
|
||||
NSPoint::new(
|
||||
width - 162.0 - if controls.proceed.isHidden() { 0.0 } else { 132.0 },
|
||||
(height - 26.0) / 2.0,
|
||||
),
|
||||
NSSize::new(78.0, 26.0),
|
||||
));
|
||||
controls.proceed.setFrame(NSRect::new(
|
||||
NSPoint::new(width - 212.0, (height - 26.0) / 2.0),
|
||||
NSSize::new(128.0, 26.0),
|
||||
));
|
||||
controls
|
||||
.spinner
|
||||
.setFrame(NSRect::new(NSPoint::new(12.0, 10.0), NSSize::new(16.0, 16.0)));
|
||||
let left = if controls.spinner.isHidden() { 12.0 } else { 36.0 };
|
||||
let right = if !controls.proceed.isHidden() {
|
||||
width - 220.0
|
||||
} else if !controls.retry.isHidden() {
|
||||
width - 170.0
|
||||
} else {
|
||||
width - 88.0
|
||||
};
|
||||
controls.label.setFrame(NSRect::new(
|
||||
NSPoint::new(left, height - 26.0),
|
||||
NSSize::new((right - left).max(0.0), 17.0),
|
||||
));
|
||||
controls.detail.setFrame(NSRect::new(
|
||||
NSPoint::new(left, 7.0),
|
||||
NSSize::new((right - left).max(0.0), 15.0),
|
||||
));
|
||||
height
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
use anyhow::Context;
|
||||
use block2::RcBlock;
|
||||
use objc2::{DefinedClass, MainThreadOnly, rc::Weak};
|
||||
use objc2_app_kit::{NSAlert, NSAlertSecondButtonReturn, NSAlertStyle};
|
||||
use objc2_foundation::{
|
||||
NSError, NSString, NSURL, NSURLErrorDomain, NSURLErrorFailingURLErrorKey, NSURLErrorFailingURLPeerTrustErrorKey,
|
||||
NSUnderlyingErrorKey,
|
||||
};
|
||||
use objc2_security::{SecTrust, errSecHostNameMismatch};
|
||||
use objc2_web_kit::WKWebView;
|
||||
|
||||
use super::super::{
|
||||
auth_messenger::{AuthError, AuthEvent},
|
||||
tls::{TlsFailure, TlsFailureReason},
|
||||
};
|
||||
|
||||
#[derive(Clone)]
|
||||
struct CertificateException {
|
||||
host: String,
|
||||
certificate: Vec<u8>,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct PendingCertificate {
|
||||
generation: u64,
|
||||
failure: TlsFailure,
|
||||
exception: CertificateException,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct TlsState {
|
||||
pending: Option<PendingCertificate>,
|
||||
exceptions: Vec<CertificateException>,
|
||||
}
|
||||
|
||||
impl TlsState {
|
||||
fn approve(&mut self, pending: &PendingCertificate, generation: u64) -> bool {
|
||||
if pending.generation != generation
|
||||
|| self.pending.as_ref().is_none_or(|current| {
|
||||
current.generation != pending.generation
|
||||
|| current.exception.certificate != pending.exception.certificate
|
||||
|| current.exception.host != pending.exception.host
|
||||
})
|
||||
{
|
||||
return false;
|
||||
}
|
||||
self.exceptions.push(pending.exception.clone());
|
||||
self.pending = None;
|
||||
true
|
||||
}
|
||||
|
||||
pub fn record_failure(&mut self, webview: &WKWebView, error: &NSError, generation: u64) -> Option<AuthError> {
|
||||
if !error.domain().isEqualToString(unsafe { NSURLErrorDomain }) {
|
||||
return None;
|
||||
}
|
||||
let reason = match error.code() {
|
||||
-1200 => TlsFailureReason::Handshake,
|
||||
-1201 => TlsFailureReason::Expired,
|
||||
-1202 => TlsFailureReason::InvalidCertificate,
|
||||
-1203 => TlsFailureReason::Untrusted,
|
||||
-1204 => TlsFailureReason::NotYetValid,
|
||||
_ => return None,
|
||||
};
|
||||
let reason = if has_hostname_mismatch(error, 0) {
|
||||
TlsFailureReason::HostnameMismatch
|
||||
} else {
|
||||
reason
|
||||
};
|
||||
let url = error
|
||||
.userInfo()
|
||||
.objectForKey(unsafe { NSURLErrorFailingURLErrorKey })?
|
||||
.downcast::<NSURL>()
|
||||
.ok()?;
|
||||
let host = url.host()?.to_string().to_ascii_lowercase();
|
||||
if let Some(uri) = url.absoluteString() {
|
||||
super::address_bar::show_address(webview, &uri.to_string());
|
||||
}
|
||||
let trust = error
|
||||
.userInfo()
|
||||
.objectForKey(unsafe { NSURLErrorFailingURLPeerTrustErrorKey });
|
||||
let certificate = trust.and_then(|trust| {
|
||||
// Foundation documents this entry as a SecTrustRef.
|
||||
let trust = unsafe { &*(objc2::rc::Retained::as_ptr(&trust).cast::<SecTrust>()) };
|
||||
certificate_data(trust)
|
||||
});
|
||||
let failure = TlsFailure {
|
||||
host: host.clone(),
|
||||
reason,
|
||||
can_continue: reason.is_certificate_error() && certificate.is_some(),
|
||||
};
|
||||
self.pending = certificate
|
||||
.filter(|_| failure.can_continue)
|
||||
.map(|certificate| PendingCertificate {
|
||||
generation,
|
||||
failure: failure.clone(),
|
||||
exception: CertificateException { host, certificate },
|
||||
});
|
||||
Some(AuthError::Tls(failure))
|
||||
}
|
||||
|
||||
pub fn allows(&self, host: &str, trust: &SecTrust) -> bool {
|
||||
if self.exceptions.is_empty() {
|
||||
return false;
|
||||
}
|
||||
let Some(certificate) = certificate_data(trust) else {
|
||||
return false;
|
||||
};
|
||||
self
|
||||
.exceptions
|
||||
.iter()
|
||||
.any(|exception| exception.host.eq_ignore_ascii_case(host) && exception.certificate == certificate)
|
||||
}
|
||||
}
|
||||
|
||||
fn has_hostname_mismatch(error: &NSError, depth: usize) -> bool {
|
||||
if depth > 4 {
|
||||
return false;
|
||||
}
|
||||
if error.code() == errSecHostNameMismatch as isize {
|
||||
return true;
|
||||
}
|
||||
error
|
||||
.userInfo()
|
||||
.objectForKey(unsafe { NSUnderlyingErrorKey })
|
||||
.and_then(|value| value.downcast::<NSError>().ok())
|
||||
.is_some_and(|error| has_hostname_mismatch(&error, depth + 1))
|
||||
}
|
||||
|
||||
fn certificate_data(trust: &SecTrust) -> Option<Vec<u8>> {
|
||||
// Retain the leaf immediately. No trust evaluation or mutation runs here.
|
||||
#[allow(deprecated)]
|
||||
let certificate = unsafe { trust.certificate_at_index(0) }?;
|
||||
Some(unsafe { certificate.data() }.to_vec())
|
||||
}
|
||||
|
||||
pub(super) fn confirm(webview: &WKWebView) -> anyhow::Result<()> {
|
||||
let delegate = super::navigation_delegate(webview).context("Auth navigation delegate is unavailable")?;
|
||||
let pending = delegate
|
||||
.ivars()
|
||||
.tls
|
||||
.borrow()
|
||||
.pending
|
||||
.clone()
|
||||
.context("No certificate error is awaiting confirmation")?;
|
||||
if pending.generation != delegate.ivars().messenger.generation() {
|
||||
return Ok(());
|
||||
}
|
||||
let window = webview.window().context("Auth window is unavailable")?;
|
||||
if window.attachedSheet().is_some() {
|
||||
return Ok(());
|
||||
}
|
||||
let alert = NSAlert::new(delegate.mtm());
|
||||
alert.setAlertStyle(NSAlertStyle::Warning);
|
||||
alert.setMessageText(&NSString::from_str(&pending.failure.confirmation_title()));
|
||||
alert.setInformativeText(&NSString::from_str(&pending.failure.confirmation_message()));
|
||||
alert.addButtonWithTitle(&NSString::from_str("Cancel"));
|
||||
alert.addButtonWithTitle(&NSString::from_str("Continue Anyway"));
|
||||
let weak = Weak::from_retained(&delegate);
|
||||
let handler = RcBlock::new(move |response: isize| {
|
||||
let Some(delegate) = weak.load() else {
|
||||
return;
|
||||
};
|
||||
if response != NSAlertSecondButtonReturn || pending.generation != delegate.ivars().messenger.generation() {
|
||||
return;
|
||||
}
|
||||
let mut state = delegate.ivars().tls.borrow_mut();
|
||||
if !state.approve(&pending, delegate.ivars().messenger.generation()) {
|
||||
return;
|
||||
}
|
||||
drop(state);
|
||||
delegate
|
||||
.ivars()
|
||||
.messenger
|
||||
.send_auth_event(AuthEvent::TlsAccepted(pending.generation));
|
||||
});
|
||||
alert.beginSheetModalForWindow_completionHandler(&window, Some(&handler));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn pending() -> PendingCertificate {
|
||||
PendingCertificate {
|
||||
generation: 1,
|
||||
failure: TlsFailure {
|
||||
host: "login.example".into(),
|
||||
reason: TlsFailureReason::Expired,
|
||||
can_continue: true,
|
||||
},
|
||||
exception: CertificateException {
|
||||
host: "login.example".into(),
|
||||
certificate: vec![1, 2, 3],
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn certificate_approval_rejects_stale_attempts_and_replacement_certificates() {
|
||||
let original = pending();
|
||||
let mut state = TlsState {
|
||||
pending: Some(original.clone()),
|
||||
..TlsState::default()
|
||||
};
|
||||
assert!(!state.approve(&original, 2));
|
||||
let mut replacement = original.clone();
|
||||
replacement.exception.certificate = vec![4, 5, 6];
|
||||
state.pending = Some(replacement);
|
||||
assert!(!state.approve(&original, 1));
|
||||
assert!(state.exceptions.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn certificate_approval_is_specific_to_the_host_and_consumed_once() {
|
||||
let original = pending();
|
||||
let mut state = TlsState {
|
||||
pending: Some(original.clone()),
|
||||
..TlsState::default()
|
||||
};
|
||||
let mut other_host = original.clone();
|
||||
other_host.exception.host = "other.example".into();
|
||||
assert!(!state.approve(&other_host, 1));
|
||||
assert!(state.approve(&original, 1));
|
||||
assert_eq!(state.exceptions.len(), 1);
|
||||
assert!(!state.approve(&original, 1));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,298 @@
|
||||
use super::tls::TlsFailureReason;
|
||||
|
||||
/// Native UI state for recovering an embedded sign-in session.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub(super) enum RecoveryStatus {
|
||||
#[default]
|
||||
Hidden,
|
||||
Restarting,
|
||||
Loading,
|
||||
Failed,
|
||||
Rejected,
|
||||
Tls {
|
||||
reason: TlsFailureReason,
|
||||
can_continue: bool,
|
||||
},
|
||||
CertificateBypassed,
|
||||
}
|
||||
|
||||
impl RecoveryStatus {
|
||||
pub fn message(self) -> &'static str {
|
||||
match self {
|
||||
Self::Hidden => "",
|
||||
Self::Restarting => "Restarting sign-in…",
|
||||
Self::Loading => "Loading sign-in…",
|
||||
Self::Failed => "Couldn’t restart sign-in.",
|
||||
Self::Rejected => "Sign-in wasn’t completed.",
|
||||
Self::Tls {
|
||||
reason: TlsFailureReason::Handshake,
|
||||
..
|
||||
} => "Secure connection failed.",
|
||||
Self::Tls { .. } => "Cannot verify this server’s identity.",
|
||||
Self::CertificateBypassed => "Certificate verification bypassed in this window.",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn detail(self) -> &'static str {
|
||||
match self {
|
||||
Self::Tls { reason, .. } => reason.message(),
|
||||
_ => "",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn can_continue(self) -> bool {
|
||||
match self {
|
||||
Self::Tls { reason, can_continue } => can_continue && reason.is_certificate_error(),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn blocks_page(self) -> bool {
|
||||
!matches!(self, Self::Hidden | Self::CertificateBypassed)
|
||||
}
|
||||
|
||||
pub fn accepts_auth_data(self) -> bool {
|
||||
matches!(self, Self::Hidden | Self::Loading | Self::CertificateBypassed)
|
||||
}
|
||||
|
||||
pub fn is_busy(self) -> bool {
|
||||
matches!(self, Self::Restarting | Self::Loading)
|
||||
}
|
||||
|
||||
pub fn can_retry(self) -> bool {
|
||||
matches!(
|
||||
self,
|
||||
Self::Failed
|
||||
| Self::Rejected
|
||||
| Self::Tls {
|
||||
reason: TlsFailureReason::Handshake,
|
||||
..
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct Recovery {
|
||||
status: RecoveryStatus,
|
||||
automatic_retry_used: bool,
|
||||
certificate_bypassed: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(super) enum RetrySource {
|
||||
FreshPrelogin,
|
||||
SuppliedRequest,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(super) enum RetryTiming {
|
||||
Immediate,
|
||||
AutomaticDelay,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(super) struct RetryPlan {
|
||||
pub source: RetrySource,
|
||||
pub timing: RetryTiming,
|
||||
}
|
||||
|
||||
impl Recovery {
|
||||
pub fn status(&self) -> RecoveryStatus {
|
||||
self.status
|
||||
}
|
||||
|
||||
pub fn loading(&mut self) {
|
||||
self.status = RecoveryStatus::Loading;
|
||||
}
|
||||
|
||||
pub fn load_failed(&mut self) {
|
||||
self.status = RecoveryStatus::Failed;
|
||||
}
|
||||
|
||||
pub fn tls_failed(&mut self, reason: TlsFailureReason, can_continue: bool) {
|
||||
self.status = RecoveryStatus::Tls { reason, can_continue };
|
||||
}
|
||||
|
||||
pub fn certificate_accepted(&mut self) -> Option<RetryPlan> {
|
||||
if !self.status.can_continue() {
|
||||
return None;
|
||||
}
|
||||
self.certificate_bypassed = true;
|
||||
self.status = RecoveryStatus::Restarting;
|
||||
Some(RetryPlan {
|
||||
source: RetrySource::SuppliedRequest,
|
||||
timing: RetryTiming::Immediate,
|
||||
})
|
||||
}
|
||||
|
||||
/// Temporary service failures get one automatic restart per dialog.
|
||||
/// Duplicate failures while restarting or awaiting user action are ignored.
|
||||
pub fn failure(&mut self, temporary: bool) -> Option<RetryPlan> {
|
||||
if !matches!(
|
||||
self.status,
|
||||
RecoveryStatus::Hidden | RecoveryStatus::Loading | RecoveryStatus::CertificateBypassed
|
||||
) {
|
||||
return None;
|
||||
}
|
||||
if temporary && !self.automatic_retry_used {
|
||||
self.automatic_retry_used = true;
|
||||
self.status = RecoveryStatus::Restarting;
|
||||
return Some(RetryPlan {
|
||||
source: RetrySource::FreshPrelogin,
|
||||
timing: RetryTiming::AutomaticDelay,
|
||||
});
|
||||
}
|
||||
self.status = if temporary {
|
||||
RecoveryStatus::Failed
|
||||
} else {
|
||||
RecoveryStatus::Rejected
|
||||
};
|
||||
None
|
||||
}
|
||||
|
||||
pub fn retry(&mut self) -> Option<RetryPlan> {
|
||||
if !self.status.can_retry() {
|
||||
return None;
|
||||
}
|
||||
let source = if matches!(self.status, RecoveryStatus::Tls { .. }) {
|
||||
RetrySource::SuppliedRequest
|
||||
} else {
|
||||
RetrySource::FreshPrelogin
|
||||
};
|
||||
self.status = RecoveryStatus::Restarting;
|
||||
Some(RetryPlan {
|
||||
source,
|
||||
timing: RetryTiming::Immediate,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn page_loaded(&mut self) {
|
||||
if self.status == RecoveryStatus::Loading {
|
||||
self.status = if self.certificate_bypassed {
|
||||
RecoveryStatus::CertificateBypassed
|
||||
} else {
|
||||
RecoveryStatus::Hidden
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn retry_plans_preserve_request_source_and_timing() {
|
||||
let mut recovery = Recovery::default();
|
||||
assert_eq!(
|
||||
recovery.failure(true),
|
||||
Some(RetryPlan {
|
||||
source: RetrySource::FreshPrelogin,
|
||||
timing: RetryTiming::AutomaticDelay,
|
||||
})
|
||||
);
|
||||
recovery.load_failed();
|
||||
assert_eq!(
|
||||
recovery.retry(),
|
||||
Some(RetryPlan {
|
||||
source: RetrySource::FreshPrelogin,
|
||||
timing: RetryTiming::Immediate,
|
||||
})
|
||||
);
|
||||
recovery.tls_failed(TlsFailureReason::Expired, true);
|
||||
assert_eq!(
|
||||
recovery.certificate_accepted(),
|
||||
Some(RetryPlan {
|
||||
source: RetrySource::SuppliedRequest,
|
||||
timing: RetryTiming::Immediate,
|
||||
})
|
||||
);
|
||||
assert!(recovery.certificate_accepted().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tls_failure_blocks_credentials_and_is_not_cleared_by_page_completion() {
|
||||
let mut recovery = Recovery {
|
||||
status: RecoveryStatus::Tls {
|
||||
reason: TlsFailureReason::Expired,
|
||||
can_continue: true,
|
||||
},
|
||||
..Recovery::default()
|
||||
};
|
||||
assert!(recovery.status.blocks_page());
|
||||
assert!(!recovery.status.accepts_auth_data());
|
||||
assert!(recovery.status.can_continue());
|
||||
recovery.page_loaded();
|
||||
assert!(matches!(recovery.status, RecoveryStatus::Tls { .. }));
|
||||
assert!(recovery.failure(true).is_none());
|
||||
assert!(matches!(recovery.status, RecoveryStatus::Tls { .. }));
|
||||
assert!(recovery.retry().is_none());
|
||||
assert!(recovery.status.can_continue());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn handshake_failures_never_offer_a_certificate_exception() {
|
||||
let status = RecoveryStatus::Tls {
|
||||
reason: TlsFailureReason::Handshake,
|
||||
can_continue: true,
|
||||
};
|
||||
assert!(!status.can_continue());
|
||||
assert!(status.can_retry());
|
||||
assert!(status.blocks_page());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn certificate_notice_keeps_successful_page_interactive() {
|
||||
let mut recovery = Recovery {
|
||||
certificate_bypassed: true,
|
||||
status: RecoveryStatus::Loading,
|
||||
..Recovery::default()
|
||||
};
|
||||
recovery.page_loaded();
|
||||
assert_eq!(recovery.status, RecoveryStatus::CertificateBypassed);
|
||||
assert!(!recovery.status.blocks_page());
|
||||
assert!(recovery.status.accepts_auth_data());
|
||||
assert!(recovery.failure(false).is_none());
|
||||
assert_eq!(recovery.status, RecoveryStatus::Rejected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn temporary_failure_retries_once_even_after_manual_restarts() {
|
||||
let mut recovery = Recovery::default();
|
||||
assert!(recovery.failure(true).is_some());
|
||||
assert!(recovery.failure(true).is_none());
|
||||
recovery.status = RecoveryStatus::Loading;
|
||||
recovery.page_loaded();
|
||||
assert!(recovery.failure(true).is_none());
|
||||
assert_eq!(recovery.status, RecoveryStatus::Failed);
|
||||
assert!(recovery.retry().is_some());
|
||||
recovery.status = RecoveryStatus::Loading;
|
||||
assert!(recovery.failure(true).is_none());
|
||||
assert_eq!(recovery.status, RecoveryStatus::Failed);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejected_auth_requires_user_action_and_deduplicates_errors() {
|
||||
let mut recovery = Recovery::default();
|
||||
assert!(recovery.failure(false).is_none());
|
||||
assert_eq!(recovery.status, RecoveryStatus::Rejected);
|
||||
assert!(recovery.failure(true).is_none());
|
||||
assert!(recovery.retry().is_some());
|
||||
assert!(recovery.retry().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn page_completion_does_not_clear_errors_or_pending_prelogin() {
|
||||
let mut recovery = Recovery::default();
|
||||
recovery.failure(false);
|
||||
recovery.page_loaded();
|
||||
assert_eq!(recovery.status, RecoveryStatus::Rejected);
|
||||
recovery.retry();
|
||||
recovery.page_loaded();
|
||||
assert_eq!(recovery.status, RecoveryStatus::Restarting);
|
||||
recovery.status = RecoveryStatus::Loading;
|
||||
recovery.page_loaded();
|
||||
assert_eq!(recovery.status, RecoveryStatus::Hidden);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
/// A TLS failure that can be presented without exposing request parameters.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(super) enum TlsFailureReason {
|
||||
Expired,
|
||||
NotYetValid,
|
||||
Untrusted,
|
||||
HostnameMismatch,
|
||||
InvalidCertificate,
|
||||
Handshake,
|
||||
}
|
||||
|
||||
impl TlsFailureReason {
|
||||
pub fn is_certificate_error(self) -> bool {
|
||||
self != Self::Handshake
|
||||
}
|
||||
|
||||
pub fn message(self) -> &'static str {
|
||||
match self {
|
||||
Self::Expired => "The certificate has expired.",
|
||||
Self::NotYetValid => "The certificate is not valid yet.",
|
||||
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.",
|
||||
Self::Handshake => "The server could not establish a compatible TLS connection.",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub(super) struct TlsFailure {
|
||||
pub host: String,
|
||||
pub reason: TlsFailureReason,
|
||||
pub can_continue: bool,
|
||||
}
|
||||
|
||||
impl TlsFailure {
|
||||
pub fn confirmation_title(&self) -> String {
|
||||
format!("Continue to {}?", self.host)
|
||||
}
|
||||
|
||||
pub fn confirmation_message(&self) -> String {
|
||||
format!(
|
||||
"{} Your sign-in information could be intercepted.\n\nThis exception applies only to this host until this sign-in window closes.",
|
||||
self.reason.message()
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,11 @@
|
||||
use std::{sync::Arc, time::Duration};
|
||||
use std::{future::Future, pin::Pin, sync::Arc, time::Duration};
|
||||
|
||||
use anyhow::bail;
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
use gpapi::utils::window::{WindowTypeHint, set_window_type_hint};
|
||||
use gpapi::{
|
||||
auth::{AuthWindowTheme, AuthenticationCancelled, SamlAuthData},
|
||||
error::ServerTlsError,
|
||||
gp_params::GpParams,
|
||||
os_profile::{WebviewUserAgent, WebviewUserAgentTransform},
|
||||
utils::{redact::redact_uri, window::get_title_bar_height},
|
||||
@@ -12,17 +13,26 @@ use gpapi::{
|
||||
use log::{info, warn};
|
||||
#[cfg(target_os = "macos")]
|
||||
use tauri::Manager;
|
||||
use tauri::{
|
||||
AppHandle, WebviewUrl, WebviewWindow, WindowEvent,
|
||||
webview::{PageLoadEvent, PageLoadPayload},
|
||||
};
|
||||
use tauri::{AppHandle, WebviewUrl, WebviewWindow, WindowEvent};
|
||||
use tokio::{sync::oneshot, time};
|
||||
|
||||
use crate::auth_prelogin;
|
||||
|
||||
use super::address_bar::TOOLBAR_HEIGHT;
|
||||
use super::auth_messenger::{AuthError, AuthEvent, AuthMessenger};
|
||||
use super::recovery::{Recovery, RecoveryStatus, RetryPlan, RetrySource, RetryTiming};
|
||||
|
||||
const RESTART_TIMEOUT: Duration = Duration::from_secs(30);
|
||||
|
||||
pub trait PlatformWebviewExt {
|
||||
fn install_auth_controls(&self, window: &WebviewWindow, messenger: Arc<AuthMessenger>) -> anyhow::Result<()>;
|
||||
|
||||
fn set_recovery_status(&self, status: RecoveryStatus) -> anyhow::Result<()>;
|
||||
|
||||
fn stop_loading(&self);
|
||||
|
||||
fn confirm_tls_exception(&self) -> anyhow::Result<()>;
|
||||
|
||||
fn ignore_tls_errors(&self) -> anyhow::Result<()>;
|
||||
|
||||
fn user_agent(&self) -> anyhow::Result<String>;
|
||||
@@ -33,8 +43,6 @@ pub trait PlatformWebviewExt {
|
||||
|
||||
fn load_html(&self, html: &str) -> anyhow::Result<()>;
|
||||
|
||||
fn get_html(&self, callback: Box<dyn Fn(anyhow::Result<String>) + 'static>);
|
||||
|
||||
fn load_auth_request(&self, auth_request: &str) -> anyhow::Result<()> {
|
||||
if auth_request.starts_with("http") {
|
||||
info!("Loading auth request as URL: {}", redact_uri(auth_request));
|
||||
@@ -59,8 +67,6 @@ pub struct WebviewAuthenticator<'a> {
|
||||
clean: bool,
|
||||
window_title: &'a str,
|
||||
window_theme: AuthWindowTheme,
|
||||
|
||||
is_retrying: tokio::sync::RwLock<bool>,
|
||||
}
|
||||
|
||||
fn native_theme(theme: AuthWindowTheme) -> Option<tauri::Theme> {
|
||||
@@ -89,7 +95,6 @@ impl<'a> WebviewAuthenticator<'a> {
|
||||
clean: false,
|
||||
window_title: "GlobalProtect Login",
|
||||
window_theme: AuthWindowTheme::System,
|
||||
is_retrying: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -120,39 +125,13 @@ impl<'a> WebviewAuthenticator<'a> {
|
||||
|
||||
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);
|
||||
|
||||
let on_page_load = move |auth_window: WebviewWindow, event: PageLoadPayload<'_>| {
|
||||
let auth_messenger_clone = Arc::clone(&auth_messenger_clone);
|
||||
let redacted_url = redact_uri(event.url().as_str());
|
||||
|
||||
match event.event() {
|
||||
PageLoadEvent::Started => {
|
||||
info!("Started loading page: {}", redacted_url);
|
||||
auth_messenger_clone.cancel_raise_window();
|
||||
}
|
||||
PageLoadEvent::Finished => {
|
||||
info!("Finished loading page: {}", redacted_url);
|
||||
}
|
||||
}
|
||||
|
||||
// Read auth data from the page no matter whether it's finished loading or not
|
||||
// Because we found that the finished event may not be triggered in some cases (e.g., on macOS)
|
||||
let _ = auth_window.with_webview(move |wv| {
|
||||
wv.get_html(Box::new(move |html| match html {
|
||||
Ok(html) => auth_messenger_clone.read_from_html(&html),
|
||||
Err(err) => warn!("Failed to get html: {}", err),
|
||||
}));
|
||||
});
|
||||
};
|
||||
|
||||
let auth_window_builder = WebviewWindow::builder(app_handle, "auth_window", WebviewUrl::default())
|
||||
.on_page_load(on_page_load)
|
||||
.title(self.window_title)
|
||||
.theme(native_theme(self.window_theme))
|
||||
.devtools(cfg!(any(debug_assertions, feature = "release-devtools")));
|
||||
let auth_window = auth_window_builder
|
||||
.inner_size(900.0, 650.0 + get_title_bar_height())
|
||||
.inner_size(900.0, 650.0 + get_title_bar_height() + TOOLBAR_HEIGHT)
|
||||
.min_inner_size(400.0, 300.0)
|
||||
.focused(true)
|
||||
.visible(false)
|
||||
.center()
|
||||
@@ -161,38 +140,169 @@ impl<'a> WebviewAuthenticator<'a> {
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
set_window_type_hint(&auth_window, WindowTypeHint::Dialog)?;
|
||||
|
||||
self
|
||||
.setup_auth_window(&auth_window, Arc::clone(&auth_messenger))
|
||||
.await?;
|
||||
|
||||
if present_after_setup(self.clean) {
|
||||
self.raise_window(&auth_window);
|
||||
let messenger = Arc::clone(&auth_messenger);
|
||||
let raise_task = tokio::spawn(async move {
|
||||
time::sleep(Duration::from_secs(10)).await;
|
||||
messenger.send_auth_event(AuthEvent::RaiseWindow);
|
||||
});
|
||||
let result = async {
|
||||
self
|
||||
.setup_auth_window(&auth_window, Arc::clone(&auth_messenger))
|
||||
.await?;
|
||||
if present_after_setup(self.clean) {
|
||||
self.raise_window(&auth_window);
|
||||
}
|
||||
self.wait_for_auth(&auth_window, Arc::clone(&auth_messenger)).await
|
||||
}
|
||||
.await;
|
||||
|
||||
raise_task.abort();
|
||||
auth_messenger.begin_attempt();
|
||||
auth_messenger.cancel_raise_window();
|
||||
// Preserve the authentication outcome even if native teardown fails.
|
||||
if let Err(error) = auth_window.close() {
|
||||
warn!("Failed to close authentication window: {error}");
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
async fn wait_for_auth(
|
||||
&self,
|
||||
auth_window: &WebviewWindow,
|
||||
auth_messenger: Arc<AuthMessenger>,
|
||||
) -> anyhow::Result<SamlAuthData> {
|
||||
let mut recovery = Recovery::default();
|
||||
let mut restart: Option<Pin<Box<dyn Future<Output = anyhow::Result<String>> + Send + '_>>> = None;
|
||||
let mut loading_deadline = None;
|
||||
|
||||
loop {
|
||||
match auth_messenger.subscribe().await? {
|
||||
AuthEvent::Close => bail!(AuthenticationCancelled),
|
||||
AuthEvent::RaiseWindow => self.raise_window(&auth_window),
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
AuthEvent::Error(AuthError::TlsError) => bail!(gpapi::error::PortalError::TlsError),
|
||||
AuthEvent::Error(AuthError::NotFound(location)) => {
|
||||
let event = tokio::select! {
|
||||
event = auth_messenger.subscribe() => event?,
|
||||
result = async {
|
||||
match restart.as_mut() {
|
||||
Some(restart) => restart.await,
|
||||
None => std::future::pending().await,
|
||||
}
|
||||
} => {
|
||||
restart = None;
|
||||
match result {
|
||||
Ok(auth_request) => {
|
||||
// Fence off reads and cancellation notifications from the old page.
|
||||
auth_messenger.begin_attempt();
|
||||
recovery.loading();
|
||||
loading_deadline = Some(time::Instant::now() + RESTART_TIMEOUT);
|
||||
self.load_restarted_sign_in(auth_window, &auth_messenger, auth_request)?;
|
||||
}
|
||||
Err(err) => {
|
||||
warn!("Failed to restart sign-in: {}", err);
|
||||
if err.downcast_ref::<ServerTlsError>().is_some() {
|
||||
return Err(err);
|
||||
}
|
||||
recovery.load_failed();
|
||||
}
|
||||
}
|
||||
self.update_recovery(auth_window, recovery.status())?;
|
||||
continue;
|
||||
}
|
||||
_ = async {
|
||||
match loading_deadline {
|
||||
Some(deadline) => time::sleep_until(deadline).await,
|
||||
None => std::future::pending().await,
|
||||
}
|
||||
} => {
|
||||
loading_deadline = None;
|
||||
recovery.load_failed();
|
||||
self.update_recovery(auth_window, recovery.status())?;
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let mut retry_plan = None;
|
||||
match event {
|
||||
AuthEvent::Close => {
|
||||
bail!(AuthenticationCancelled);
|
||||
}
|
||||
AuthEvent::RaiseWindow => self.raise_window(auth_window),
|
||||
AuthEvent::Data(generation, ..)
|
||||
| AuthEvent::Error(generation, _)
|
||||
| AuthEvent::NoAuthData(generation, _)
|
||||
| AuthEvent::PageLoaded(generation)
|
||||
| AuthEvent::TlsAccepted(generation)
|
||||
if generation != auth_messenger.generation() =>
|
||||
{
|
||||
continue;
|
||||
}
|
||||
AuthEvent::Error(_, AuthError::Tls(failure)) => {
|
||||
warn!("TLS failure for {}: {}", failure.host, failure.reason.message());
|
||||
restart = None;
|
||||
loading_deadline = None;
|
||||
recovery.tls_failed(failure.reason, failure.can_continue);
|
||||
}
|
||||
AuthEvent::RequestTlsException => {
|
||||
if recovery.status().can_continue() {
|
||||
auth_window.with_webview(|wv| {
|
||||
if let Err(err) = wv.confirm_tls_exception() {
|
||||
warn!("Failed to confirm certificate exception: {}", err);
|
||||
}
|
||||
})?;
|
||||
}
|
||||
}
|
||||
AuthEvent::TlsAccepted(_) => {
|
||||
retry_plan = recovery.certificate_accepted();
|
||||
}
|
||||
AuthEvent::NoAuthData(_, location) => {
|
||||
info!(
|
||||
"No auth data found in {:?}, it may not be the /SAML20/SP/ACS endpoint",
|
||||
location
|
||||
);
|
||||
self.handle_not_found(&auth_window, &auth_messenger);
|
||||
self.handle_not_found(auth_window, &auth_messenger);
|
||||
}
|
||||
AuthEvent::Error(AuthError::Invalid(err, location)) => {
|
||||
AuthEvent::Error(_, AuthError::Invalid(err, location)) => {
|
||||
warn!("Got invalid auth data in {:?}: {}", location, err);
|
||||
self.retry_auth(&auth_window).await;
|
||||
recovery.failure(false);
|
||||
}
|
||||
AuthEvent::Data(auth_data, location) => {
|
||||
AuthEvent::Error(_, AuthError::TemporarilyUnavailable) => {
|
||||
retry_plan = recovery.failure(true);
|
||||
}
|
||||
AuthEvent::Error(_, AuthError::LoadFailed(err)) => {
|
||||
if matches!(
|
||||
recovery.status(),
|
||||
RecoveryStatus::Loading | RecoveryStatus::Hidden | RecoveryStatus::CertificateBypassed
|
||||
) {
|
||||
warn!("Failed to load sign-in: {}", err);
|
||||
recovery.load_failed();
|
||||
loading_deadline = None;
|
||||
}
|
||||
}
|
||||
AuthEvent::Retry => {
|
||||
retry_plan = recovery.retry();
|
||||
}
|
||||
AuthEvent::PageLoaded(_) => {
|
||||
recovery.page_loaded();
|
||||
if !recovery.status().blocks_page() {
|
||||
loading_deadline = None;
|
||||
}
|
||||
}
|
||||
AuthEvent::Data(_, auth_data, location) => {
|
||||
if !recovery.status().accepts_auth_data() {
|
||||
continue;
|
||||
}
|
||||
info!("Got auth data from {:?}", location);
|
||||
|
||||
auth_window.close()?;
|
||||
return Ok(auth_data);
|
||||
}
|
||||
}
|
||||
if let Some(plan) = retry_plan {
|
||||
loading_deadline = None;
|
||||
auth_messenger.begin_attempt();
|
||||
auth_window.with_webview(|wv| wv.stop_loading())?;
|
||||
restart = Some(Box::pin(async move {
|
||||
time::timeout(RESTART_TIMEOUT, self.request_sign_in(plan)).await?
|
||||
}));
|
||||
}
|
||||
if recovery.status() != RecoveryStatus::Loading {
|
||||
loading_deadline = None;
|
||||
}
|
||||
self.update_recovery(auth_window, recovery.status())?;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -216,13 +326,6 @@ impl<'a> WebviewAuthenticator<'a> {
|
||||
}
|
||||
});
|
||||
|
||||
// Show the window after 10 seconds, so that the user can see the window if the auth process is stuck
|
||||
let auth_messenger_clone = Arc::clone(&auth_messenger);
|
||||
tokio::spawn(async move {
|
||||
time::sleep(Duration::from_secs(10)).await;
|
||||
auth_messenger_clone.send_auth_event(AuthEvent::RaiseWindow);
|
||||
});
|
||||
|
||||
let auth_request = match self.auth_request {
|
||||
Some(auth_request) => auth_request.to_string(),
|
||||
None => auth_prelogin(&self.server, &self.gp_params, false, false).await?,
|
||||
@@ -231,19 +334,13 @@ impl<'a> WebviewAuthenticator<'a> {
|
||||
let (tx, rx) = oneshot::channel::<anyhow::Result<()>>();
|
||||
let ignore_tls_errors = self.gp_params.ignore_tls_errors();
|
||||
let webview_user_agent = self.webview_user_agent.clone();
|
||||
let window = auth_window.clone();
|
||||
|
||||
// Set up webview
|
||||
auth_window.with_webview(move |wv| {
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
{
|
||||
use super::platform_impl::PlatformWebviewOnResponse;
|
||||
wv.on_response(Box::new(move |response| match response {
|
||||
Ok(response) => auth_messenger.read_from_response(&response),
|
||||
Err(err) => auth_messenger.send_auth_error(err),
|
||||
}));
|
||||
}
|
||||
|
||||
let controls_messenger = Arc::clone(&auth_messenger);
|
||||
let result = || -> anyhow::Result<()> {
|
||||
wv.install_auth_controls(&window, controls_messenger)?;
|
||||
if ignore_tls_errors {
|
||||
wv.ignore_tls_errors()?;
|
||||
}
|
||||
@@ -271,49 +368,48 @@ impl<'a> WebviewAuthenticator<'a> {
|
||||
auth_messenger.schedule_raise_window(2);
|
||||
}
|
||||
|
||||
async fn retry_auth(&self, auth_window: &WebviewWindow) {
|
||||
let mut is_retrying = self.is_retrying.write().await;
|
||||
if *is_retrying {
|
||||
info!("Already retrying authentication, skipping...");
|
||||
return;
|
||||
fn update_recovery(&self, auth_window: &WebviewWindow, status: RecoveryStatus) -> anyhow::Result<()> {
|
||||
if status != RecoveryStatus::Hidden {
|
||||
self.raise_window(auth_window);
|
||||
}
|
||||
|
||||
*is_retrying = true;
|
||||
drop(is_retrying);
|
||||
|
||||
if let Err(err) = self.retry_auth_impl(auth_window).await {
|
||||
warn!("Failed to retry authentication: {}", err);
|
||||
}
|
||||
|
||||
*self.is_retrying.write().await = false;
|
||||
}
|
||||
|
||||
async fn retry_auth_impl(&self, auth_window: &WebviewWindow) -> anyhow::Result<()> {
|
||||
info!("Retrying authentication...");
|
||||
|
||||
auth_window.eval( r#"
|
||||
var loading = document.createElement("div");
|
||||
loading.innerHTML = '<div style="position: absolute; width: 100%; text-align: center; font-size: 20px; font-weight: bold; top: 50%; left: 50%; transform: translate(-50%, -50%);">Got invalid token, retrying...</div>';
|
||||
loading.style = "position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(255, 255, 255, 0.85); z-index: 99999;";
|
||||
document.body.appendChild(loading);
|
||||
"#)?;
|
||||
|
||||
let auth_request = auth_prelogin(&self.server, &self.gp_params, false, false).await?;
|
||||
|
||||
let (tx, rx) = oneshot::channel::<anyhow::Result<()>>();
|
||||
let webview_user_agent = self.webview_user_agent.clone();
|
||||
auth_window.with_webview(move |wv| {
|
||||
let result = || -> anyhow::Result<()> {
|
||||
load_auth_request_with_user_agent(&wv, webview_user_agent.as_ref(), &auth_request)
|
||||
}();
|
||||
|
||||
if let Err(result) = tx.send(result) {
|
||||
warn!("Failed to send retry auth result: {:?}", result);
|
||||
if let Err(err) = wv.set_recovery_status(status) {
|
||||
warn!("Failed to update sign-in status: {}", err);
|
||||
}
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
rx.await??;
|
||||
async fn request_sign_in(&self, plan: RetryPlan) -> anyhow::Result<String> {
|
||||
info!("Restarting sign-in...");
|
||||
if plan.timing == RetryTiming::AutomaticDelay {
|
||||
time::sleep(Duration::from_secs(1)).await;
|
||||
}
|
||||
if plan.source == RetrySource::SuppliedRequest {
|
||||
if let Some(request) = self.auth_request {
|
||||
return Ok(request.to_owned());
|
||||
}
|
||||
}
|
||||
auth_prelogin(self.server, self.gp_params, false, false).await
|
||||
}
|
||||
|
||||
fn load_restarted_sign_in(
|
||||
&self,
|
||||
auth_window: &WebviewWindow,
|
||||
messenger: &Arc<AuthMessenger>,
|
||||
auth_request: String,
|
||||
) -> anyhow::Result<()> {
|
||||
let webview_user_agent = self.webview_user_agent.clone();
|
||||
let generation = messenger.generation();
|
||||
let messenger = Arc::clone(messenger);
|
||||
auth_window.with_webview(move |wv| {
|
||||
if generation != messenger.generation() {
|
||||
return;
|
||||
}
|
||||
if let Err(err) = load_auth_request_with_user_agent(&wv, webview_user_agent.as_ref(), &auth_request) {
|
||||
messenger.send_auth_event(AuthEvent::Error(generation, AuthError::LoadFailed(err)));
|
||||
}
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user