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:
Kevin Yue committed 2026-10-19 23:47:11 +08:00
1 parent 18ed6bac1a
commit 4faa2ecb0d
158 files changed
+13752 -1038

No files matched your search

@@ -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
}
+228
View File
@@ -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));
}
}