mirror of
https://github.com/yuezk/GlobalProtect-openconnect.git
synced 2026-11-19 14:36:15 -05:00
feat: prepare 3.0.0 release
This commit is contained in:
252 files changed
+26210
-7457
No files matched your search
+14
-8
@@ -8,20 +8,18 @@ edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
common = { path = "../common" }
|
||||
gpapi = { path = "../gpapi" }
|
||||
|
||||
# Shared dependencies
|
||||
anyhow.workspace = true
|
||||
log.workspace = true
|
||||
tokio.workspace = true
|
||||
tokio = { workspace = true, features = ["io-util", "net", "time"] }
|
||||
|
||||
# Browser auth dependencies
|
||||
webbrowser = { version = "1", optional = true }
|
||||
open = { version = "5", optional = true }
|
||||
which = { workspace = true, optional = true }
|
||||
browser-launcher = { path = "../browser-launcher", default-features = false, features = ["launcher"], optional = true }
|
||||
tiny_http = { version = "0.12", optional = true }
|
||||
uuid = { version = "1", optional = true, features = ["v4"] }
|
||||
uzers = { workspace = true, optional = true }
|
||||
|
||||
# Webview auth dependencies
|
||||
tauri = { workspace = true, optional = true }
|
||||
@@ -35,16 +33,20 @@ webkit2gtk = { version = "2", optional = true }
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
block2 = { version = "0.6", optional = true }
|
||||
objc2 = { version = "0.6", optional = true }
|
||||
objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "NSWorkspace", "block2"], optional = true }
|
||||
objc2-foundation = { version = "0.3", optional = true }
|
||||
objc2-web-kit = { version = "0.3", optional = true }
|
||||
|
||||
[features]
|
||||
browser-auth = [
|
||||
"dep:webbrowser",
|
||||
"dep:open",
|
||||
"dep:which",
|
||||
"dep:browser-launcher",
|
||||
"dep:tiny_http",
|
||||
"dep:uuid",
|
||||
"dep:uzers",
|
||||
"dep:block2",
|
||||
"dep:objc2",
|
||||
"dep:objc2-app-kit",
|
||||
"dep:objc2-foundation",
|
||||
]
|
||||
webview-auth = [
|
||||
"gpapi/tauri",
|
||||
@@ -58,3 +60,7 @@ webview-auth = [
|
||||
"dep:objc2-foundation",
|
||||
"dep:objc2-web-kit",
|
||||
]
|
||||
release-devtools = ["webview-auth", "tauri/devtools"]
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile.workspace = true
|
||||
@@ -1,4 +1,4 @@
|
||||
use std::io::Cursor;
|
||||
use std::{io::Cursor, net::SocketAddr};
|
||||
|
||||
use log::info;
|
||||
use tiny_http::{Header, Method, Response, Server};
|
||||
@@ -10,7 +10,7 @@ pub(super) struct AuthServer {
|
||||
}
|
||||
|
||||
impl AuthServer {
|
||||
pub fn new(addr: &str) -> anyhow::Result<Self> {
|
||||
pub fn new(addr: SocketAddr) -> anyhow::Result<Self> {
|
||||
let server = Server::http(addr).map_err(|err| anyhow::anyhow!(err))?;
|
||||
let auth_id = Uuid::new_v4().to_string();
|
||||
|
||||
|
||||
@@ -1,64 +1,36 @@
|
||||
use std::{env::temp_dir, fs, os::unix::fs::PermissionsExt};
|
||||
use std::net::{IpAddr, SocketAddr};
|
||||
|
||||
use common::constants::GP_CALLBACK_PORT_FILENAME;
|
||||
use browser_launcher::Browser as LaunchBrowser;
|
||||
use gpapi::auth::SamlAuthData;
|
||||
use log::info;
|
||||
use tokio::{
|
||||
io::AsyncReadExt,
|
||||
net::{TcpListener, UdpSocket},
|
||||
};
|
||||
use tokio::net::UdpSocket;
|
||||
|
||||
use crate::browser::auth_server::AuthServer;
|
||||
|
||||
pub enum Browser<'a> {
|
||||
Auto,
|
||||
Default,
|
||||
Chrome,
|
||||
Firefox,
|
||||
Remote,
|
||||
Other(&'a str),
|
||||
}
|
||||
|
||||
impl<'a> Browser<'a> {
|
||||
pub fn from_str(browser: &'a str) -> Self {
|
||||
match browser.to_lowercase().as_str() {
|
||||
"auto" => Browser::Auto,
|
||||
"default" => Browser::Default,
|
||||
"chrome" => Browser::Chrome,
|
||||
"firefox" => Browser::Firefox,
|
||||
"remote" => Browser::Remote,
|
||||
_ => Browser::Other(browser),
|
||||
}
|
||||
}
|
||||
|
||||
fn as_str(&self) -> &str {
|
||||
match self {
|
||||
Browser::Auto => "auto",
|
||||
Browser::Default => "default",
|
||||
Browser::Chrome => "chrome",
|
||||
Browser::Firefox => "firefox",
|
||||
Browser::Remote => "remote",
|
||||
Browser::Other(browser) => browser,
|
||||
}
|
||||
}
|
||||
}
|
||||
use crate::{AuthCallbackReceiver, browser::auth_server::AuthServer, ensure_auth_callback_handler};
|
||||
|
||||
pub struct BrowserAuthenticator<'a> {
|
||||
auth_request: &'a str,
|
||||
browser: Browser<'a>,
|
||||
browser: &'a str,
|
||||
browser_listen: Option<IpAddr>,
|
||||
}
|
||||
|
||||
impl<'a> BrowserAuthenticator<'a> {
|
||||
pub fn new(auth_request: &'a str, browser: &'a str) -> Self {
|
||||
pub fn new(auth_request: &'a str, browser: &'a str, browser_listen: Option<IpAddr>) -> Self {
|
||||
Self {
|
||||
auth_request,
|
||||
browser: Browser::from_str(browser),
|
||||
browser,
|
||||
browser_listen,
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn authenticate(&self) -> anyhow::Result<SamlAuthData> {
|
||||
let callback_receiver = if is_remote_browser(self.browser) {
|
||||
None
|
||||
} else {
|
||||
ensure_auth_callback_handler()?;
|
||||
Some(AuthCallbackReceiver::bind()?)
|
||||
};
|
||||
let addr = self.determine_addr().await?;
|
||||
let auth_server = AuthServer::new(&addr)?;
|
||||
let auth_server = AuthServer::new(addr)?;
|
||||
let auth_url = auth_server.auth_url();
|
||||
|
||||
let auth_request = self.auth_request.to_string();
|
||||
@@ -66,10 +38,9 @@ impl<'a> BrowserAuthenticator<'a> {
|
||||
auth_server.serve_request(&auth_request);
|
||||
});
|
||||
|
||||
match self.browser {
|
||||
Browser::Remote => {
|
||||
info!(
|
||||
r#"
|
||||
if is_remote_browser(self.browser) {
|
||||
info!(
|
||||
r#"
|
||||
|
||||
==== Manual Authentication Required ====
|
||||
|
||||
@@ -82,109 +53,45 @@ After completing the authentication, please paste the authentication data back t
|
||||
|
||||
Note that the URL is only valid for a single use.
|
||||
"#,
|
||||
auth_url
|
||||
);
|
||||
return read_auth_data_from_stdin();
|
||||
}
|
||||
Browser::Default => {
|
||||
info!("Launching the default browser...");
|
||||
webbrowser::open(&auth_url)?;
|
||||
}
|
||||
Browser::Auto => {
|
||||
if let Some(app) = find_auto_browser_path() {
|
||||
info!("Launching browser: {}", app);
|
||||
open::with_detached(&auth_url, app)?;
|
||||
} else {
|
||||
info!("No preferred browser found; launching the default browser...");
|
||||
webbrowser::open(&auth_url)?;
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
let app = find_browser_path(&self.browser);
|
||||
|
||||
info!("Launching browser: {}", app);
|
||||
open::with_detached(auth_url, app)?;
|
||||
}
|
||||
auth_url
|
||||
);
|
||||
return read_auth_data_from_stdin();
|
||||
}
|
||||
|
||||
browser_launcher::open_url(&auth_url, LaunchBrowser::from_name(self.browser))?;
|
||||
|
||||
info!("Please continue the authentication process in the default browser");
|
||||
wait_auth_data().await
|
||||
callback_receiver.unwrap().receive().await
|
||||
}
|
||||
|
||||
async fn determine_addr(&self) -> anyhow::Result<String> {
|
||||
if matches!(self.browser, Browser::Remote) {
|
||||
let local_ip = detect_local_ip().await?;
|
||||
Ok(format!("{}:0", local_ip))
|
||||
async fn determine_addr(&self) -> anyhow::Result<SocketAddr> {
|
||||
if is_remote_browser(self.browser) {
|
||||
let local_ip = match self.browser_listen {
|
||||
Some(ip) => ip,
|
||||
None => detect_local_ip().await?,
|
||||
};
|
||||
Ok(SocketAddr::new(local_ip, 0))
|
||||
} else {
|
||||
Ok("127.0.0.1:0".to_string())
|
||||
Ok(SocketAddr::from(([127, 0, 0, 1], 0)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn is_remote_browser(browser: &str) -> bool {
|
||||
browser.eq_ignore_ascii_case("remote")
|
||||
}
|
||||
|
||||
/// Detect the local IP address by creating a UDP socket and connecting to an external address
|
||||
async fn detect_local_ip() -> anyhow::Result<String> {
|
||||
async fn detect_local_ip() -> anyhow::Result<IpAddr> {
|
||||
let socket = UdpSocket::bind("0.0.0.0:0").await?;
|
||||
if let Err(err) = socket.connect("1.1.1.1:80").await {
|
||||
anyhow::bail!("Failed to connect to external address to determine local IP: {}", err);
|
||||
}
|
||||
let local_addr = socket.local_addr()?;
|
||||
let ip = local_addr.ip().to_string();
|
||||
let ip = local_addr.ip();
|
||||
info!("Determined local IP address: {}", ip);
|
||||
|
||||
Ok(ip.to_string())
|
||||
}
|
||||
|
||||
fn find_browser_path(browser: &Browser) -> String {
|
||||
match browser {
|
||||
Browser::Chrome => find_chrome_path().unwrap_or_else(|| browser.as_str().to_string()),
|
||||
_ => browser.as_str().to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
fn find_auto_browser_path() -> Option<String> {
|
||||
find_chrome_path().or_else(|| find_program_path("firefox"))
|
||||
}
|
||||
|
||||
fn find_chrome_path() -> Option<String> {
|
||||
["google-chrome-stable", "google-chrome", "chromium"]
|
||||
.iter()
|
||||
.find_map(|browser_name| find_program_path(browser_name))
|
||||
}
|
||||
|
||||
fn find_program_path(name: &str) -> Option<String> {
|
||||
which::which(name).ok().map(|path| path.to_string_lossy().to_string())
|
||||
}
|
||||
|
||||
async fn wait_auth_data() -> anyhow::Result<SamlAuthData> {
|
||||
// Start a local server to receive the browser authentication data
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await?;
|
||||
let port = listener.local_addr()?.port();
|
||||
let port_file = temp_dir().join(GP_CALLBACK_PORT_FILENAME);
|
||||
|
||||
// Write the port to a file
|
||||
fs::write(&port_file, port.to_string())?;
|
||||
fs::set_permissions(&port_file, fs::Permissions::from_mode(0o600))?;
|
||||
|
||||
// Remove the previous log file
|
||||
let callback_log = temp_dir().join("gpcallback.log");
|
||||
let _ = fs::remove_file(&callback_log);
|
||||
|
||||
info!("Listening authentication data on port {}", port);
|
||||
info!(
|
||||
"If it hangs, please check the logs at `{}` for more information",
|
||||
callback_log.display()
|
||||
);
|
||||
let (mut socket, _) = listener.accept().await?;
|
||||
|
||||
info!("Received the browser authentication data from the socket");
|
||||
let mut data = String::new();
|
||||
socket.read_to_string(&mut data).await?;
|
||||
|
||||
// Remove the port file
|
||||
fs::remove_file(&port_file)?;
|
||||
|
||||
let auth_data = SamlAuthData::from_gpcallback(&data)?;
|
||||
Ok(auth_data)
|
||||
Ok(ip)
|
||||
}
|
||||
|
||||
fn read_auth_data_from_stdin() -> anyhow::Result<SamlAuthData> {
|
||||
@@ -200,8 +107,26 @@ mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn browser_auto_is_distinct_from_system_default() {
|
||||
assert!(matches!(Browser::from_str("auto"), Browser::Auto));
|
||||
assert!(matches!(Browser::from_str("default"), Browser::Default));
|
||||
fn shared_launcher_keeps_auto_distinct_from_system_default() {
|
||||
assert_eq!(LaunchBrowser::from_name("auto"), LaunchBrowser::Auto);
|
||||
assert_eq!(LaunchBrowser::from_name("default"), LaunchBrowser::Default);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn browser_remote_remains_auth_specific() {
|
||||
assert!(is_remote_browser("remote"));
|
||||
assert!(is_remote_browser("REMOTE"));
|
||||
assert_ne!(LaunchBrowser::from_name("remote"), LaunchBrowser::Default);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn remote_browser_uses_explicit_listen_address() {
|
||||
let listen_ip = "192.168.107.15".parse().unwrap();
|
||||
let authenticator = BrowserAuthenticator::new("request", "remote", Some(listen_ip));
|
||||
|
||||
assert_eq!(
|
||||
authenticator.determine_addr().await.unwrap(),
|
||||
SocketAddr::new(listen_ip, 0)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,512 @@
|
||||
use std::{
|
||||
fs::{self, DirBuilder, OpenOptions, TryLockError},
|
||||
io::ErrorKind,
|
||||
os::unix::fs::{DirBuilderExt, FileTypeExt, MetadataExt, OpenOptionsExt, PermissionsExt},
|
||||
path::{Path, PathBuf},
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
use anyhow::{Context, bail};
|
||||
use gpapi::auth::SamlAuthData;
|
||||
use tokio::{
|
||||
io::{AsyncReadExt, AsyncWriteExt},
|
||||
net::{UnixListener, UnixStream},
|
||||
time::timeout,
|
||||
};
|
||||
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
use log::warn;
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd", test))]
|
||||
use std::ffi::OsStr;
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
use std::process::{Command, Output};
|
||||
|
||||
const CALLBACK_SCHEME: &str = "globalprotectcallback";
|
||||
const PROTOCOL_MAGIC: &[u8; 4] = b"GPAC";
|
||||
const PROTOCOL_VERSION: u8 = 1;
|
||||
const MAX_CALLBACK_SIZE: usize = 1024 * 1024;
|
||||
const IO_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
|
||||
const STATUS_ACCEPTED: u8 = 0;
|
||||
const STATUS_INVALID_CALLBACK: u8 = 1;
|
||||
const STATUS_UNSUPPORTED_VERSION: u8 = 2;
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
mod macos;
|
||||
|
||||
pub struct AuthCallbackReceiver {
|
||||
listener: UnixListener,
|
||||
socket_path: PathBuf,
|
||||
_lock_file: fs::File,
|
||||
}
|
||||
|
||||
impl AuthCallbackReceiver {
|
||||
pub fn bind() -> anyhow::Result<Self> {
|
||||
let socket_path = callback_socket_path();
|
||||
prepare_socket_directory(&socket_path)?;
|
||||
Self::bind_at(socket_path)
|
||||
}
|
||||
|
||||
fn bind_at(socket_path: PathBuf) -> anyhow::Result<Self> {
|
||||
let lock_file = acquire_lock(&socket_path)?;
|
||||
match fs::symlink_metadata(&socket_path) {
|
||||
Ok(_) => remove_stale_socket(&socket_path)?,
|
||||
Err(err) if err.kind() == ErrorKind::NotFound => {}
|
||||
Err(err) => return Err(err.into()),
|
||||
}
|
||||
finish_bind(UnixListener::bind(&socket_path)?, socket_path, lock_file)
|
||||
}
|
||||
|
||||
pub async fn receive(&self) -> anyhow::Result<SamlAuthData> {
|
||||
loop {
|
||||
let (mut stream, _) = self.listener.accept().await?;
|
||||
let callback = match timeout(IO_TIMEOUT, read_callback(&mut stream)).await {
|
||||
Ok(callback) => callback,
|
||||
Err(_) => continue,
|
||||
};
|
||||
match callback {
|
||||
Ok(callback) => match SamlAuthData::from_gpcallback(&callback) {
|
||||
Ok(auth_data) => {
|
||||
let _ = write_response(&mut stream, STATUS_ACCEPTED).await;
|
||||
return Ok(auth_data);
|
||||
}
|
||||
Err(_) => {
|
||||
let _ = write_response(&mut stream, STATUS_INVALID_CALLBACK).await;
|
||||
}
|
||||
},
|
||||
Err(CallbackReadError::UnsupportedVersion) => {
|
||||
let _ = write_response(&mut stream, STATUS_UNSUPPORTED_VERSION).await;
|
||||
}
|
||||
Err(CallbackReadError::Invalid) => {
|
||||
let _ = write_response(&mut stream, STATUS_INVALID_CALLBACK).await;
|
||||
}
|
||||
Err(CallbackReadError::Io) => continue,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for AuthCallbackReceiver {
|
||||
fn drop(&mut self) {
|
||||
if fs::symlink_metadata(&self.socket_path)
|
||||
.is_ok_and(|metadata| metadata.file_type().is_socket() && metadata.uid() == uzers::get_current_uid())
|
||||
{
|
||||
let _ = fs::remove_file(&self.socket_path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn forward_auth_callback(callback: &str) -> anyhow::Result<()> {
|
||||
validate_callback(callback)?;
|
||||
forward_auth_callback_to(callback, &callback_socket_path()).await
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
pub fn ensure_auth_callback_handler() -> anyhow::Result<()> {
|
||||
const MIME_TYPE: &str = "x-scheme-handler/globalprotectcallback";
|
||||
const HANDLER: &str = "gpgui.desktop";
|
||||
|
||||
ensure_lxqt_mime_tool()?;
|
||||
|
||||
let current_handler = query_callback_handler(MIME_TYPE)?;
|
||||
if !should_register_handler(¤t_handler) {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let output = Command::new("xdg-mime")
|
||||
.args(["default", HANDLER, MIME_TYPE])
|
||||
.output()
|
||||
.context("xdg-mime is required for external-browser authentication")?;
|
||||
if !output.status.success() {
|
||||
log_command_failure("register callback handler", &output);
|
||||
bail!("Failed to register the globalprotectcallback URL handler");
|
||||
}
|
||||
if query_callback_handler(MIME_TYPE)? != HANDLER {
|
||||
bail!("The globalprotectcallback URL handler registration did not take effect");
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
fn query_callback_handler(mime_type: &str) -> anyhow::Result<String> {
|
||||
let output = Command::new("xdg-mime")
|
||||
.args(["query", "default", mime_type])
|
||||
.output()
|
||||
.context("xdg-mime is required for external-browser authentication")?;
|
||||
if !output.status.success() {
|
||||
log_command_failure("query callback handler", &output);
|
||||
bail!("Failed to query the globalprotectcallback URL handler");
|
||||
}
|
||||
Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
fn ensure_lxqt_mime_tool() -> anyhow::Result<()> {
|
||||
if !is_lxqt_desktop(std::env::var_os("XDG_CURRENT_DESKTOP").as_deref()) {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let result = Command::new("qtxdg-mat").args(["defapp", "--help"]).output();
|
||||
match result {
|
||||
Ok(output) if output.status.success() => Ok(()),
|
||||
Ok(output) => {
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
warn!(
|
||||
"qtxdg-mat readiness check failed with {}: {}",
|
||||
output.status,
|
||||
stderr.trim()
|
||||
);
|
||||
bail!("Install qtxdg-tools for browser SSO.")
|
||||
}
|
||||
Err(err) => {
|
||||
warn!("Failed to run qtxdg-mat readiness check: {err}");
|
||||
bail!("Install qtxdg-tools for browser SSO.")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd", test))]
|
||||
fn is_lxqt_desktop(current_desktop: Option<&OsStr>) -> bool {
|
||||
current_desktop
|
||||
.and_then(OsStr::to_str)
|
||||
.is_some_and(|desktop| desktop.split(':').any(|name| name.eq_ignore_ascii_case("lxqt")))
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
fn log_command_failure(action: &str, output: &Output) {
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
warn!("xdg-mime failed to {action} with {}: {}", output.status, stderr.trim());
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
pub fn ensure_auth_callback_handler() -> anyhow::Result<()> {
|
||||
macos::ensure_auth_callback_handler()
|
||||
}
|
||||
|
||||
#[cfg(not(any(
|
||||
target_os = "linux",
|
||||
target_os = "freebsd",
|
||||
target_os = "openbsd",
|
||||
target_os = "macos"
|
||||
)))]
|
||||
pub fn ensure_auth_callback_handler() -> anyhow::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd", test))]
|
||||
fn should_register_handler(current_handler: &str) -> bool {
|
||||
current_handler != "gpgui.desktop"
|
||||
}
|
||||
|
||||
async fn forward_auth_callback_to(callback: &str, socket_path: &Path) -> anyhow::Result<()> {
|
||||
validate_callback(callback)?;
|
||||
|
||||
let (version, status) = timeout(IO_TIMEOUT, async {
|
||||
let mut stream = UnixStream::connect(socket_path)
|
||||
.await
|
||||
.context("No external-browser authentication is waiting for a callback")?;
|
||||
stream.write_all(PROTOCOL_MAGIC).await?;
|
||||
stream.write_u8(PROTOCOL_VERSION).await?;
|
||||
stream.write_u32(callback.len() as u32).await?;
|
||||
stream.write_all(callback.as_bytes()).await?;
|
||||
Ok::<_, anyhow::Error>((stream.read_u8().await?, stream.read_u8().await?))
|
||||
})
|
||||
.await
|
||||
.context("Timed out forwarding the authentication callback")??;
|
||||
if version != PROTOCOL_VERSION {
|
||||
bail!("Authentication callback protocol version mismatch");
|
||||
}
|
||||
|
||||
match status {
|
||||
STATUS_ACCEPTED => Ok(()),
|
||||
STATUS_INVALID_CALLBACK => bail!("Authentication callback was rejected"),
|
||||
STATUS_UNSUPPORTED_VERSION => bail!("Authentication callback protocol version is unsupported"),
|
||||
_ => bail!("Authentication callback handler returned an unknown status"),
|
||||
}
|
||||
}
|
||||
|
||||
fn callback_socket_path() -> PathBuf {
|
||||
let uid = uzers::get_current_uid();
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
let runtime_dir = PathBuf::from(format!("/run/user/{uid}"));
|
||||
if fs::symlink_metadata(&runtime_dir).is_ok_and(|metadata| {
|
||||
metadata.is_dir()
|
||||
&& !metadata.file_type().is_symlink()
|
||||
&& metadata.uid() == uid
|
||||
&& metadata.permissions().mode() & 0o077 == 0
|
||||
}) {
|
||||
return runtime_dir.join("gp-connect/auth-callback.sock");
|
||||
}
|
||||
}
|
||||
|
||||
PathBuf::from(format!("/tmp/gp-connect-{uid}/auth-callback.sock"))
|
||||
}
|
||||
|
||||
fn prepare_socket_directory(socket_path: &Path) -> anyhow::Result<()> {
|
||||
let directory = socket_path
|
||||
.parent()
|
||||
.ok_or_else(|| anyhow::anyhow!("Authentication callback socket has no parent directory"))?;
|
||||
|
||||
match DirBuilder::new().mode(0o700).create(directory) {
|
||||
Ok(()) => {}
|
||||
Err(err) if err.kind() == ErrorKind::AlreadyExists => {
|
||||
let metadata = fs::symlink_metadata(directory)?;
|
||||
if !metadata.is_dir() || metadata.file_type().is_symlink() {
|
||||
bail!("Authentication callback runtime path is not a directory");
|
||||
}
|
||||
if metadata.uid() != uzers::get_current_uid() {
|
||||
bail!("Authentication callback runtime directory has the wrong owner");
|
||||
}
|
||||
if metadata.permissions().mode() & 0o077 != 0 {
|
||||
bail!("Authentication callback runtime directory permissions are too broad");
|
||||
}
|
||||
}
|
||||
Err(err) => return Err(err.into()),
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn finish_bind(
|
||||
listener: UnixListener,
|
||||
socket_path: PathBuf,
|
||||
lock_file: fs::File,
|
||||
) -> anyhow::Result<AuthCallbackReceiver> {
|
||||
fs::set_permissions(&socket_path, fs::Permissions::from_mode(0o600))?;
|
||||
Ok(AuthCallbackReceiver {
|
||||
listener,
|
||||
socket_path,
|
||||
_lock_file: lock_file,
|
||||
})
|
||||
}
|
||||
|
||||
fn acquire_lock(socket_path: &Path) -> anyhow::Result<fs::File> {
|
||||
let lock_path = socket_path.with_file_name("auth-callback.lock");
|
||||
let lock_file = OpenOptions::new()
|
||||
.read(true)
|
||||
.write(true)
|
||||
.create(true)
|
||||
.truncate(false)
|
||||
.mode(0o600)
|
||||
.open(lock_path)?;
|
||||
lock_file.set_permissions(fs::Permissions::from_mode(0o600))?;
|
||||
|
||||
match lock_file.try_lock() {
|
||||
Ok(()) => Ok(lock_file),
|
||||
Err(TryLockError::WouldBlock) => bail!("Another external-browser authentication is already in progress"),
|
||||
Err(TryLockError::Error(err)) => Err(err.into()),
|
||||
}
|
||||
}
|
||||
|
||||
fn remove_stale_socket(socket_path: &Path) -> anyhow::Result<()> {
|
||||
let metadata = fs::symlink_metadata(socket_path)?;
|
||||
if !metadata.file_type().is_socket() || metadata.uid() != uzers::get_current_uid() {
|
||||
bail!("Authentication callback socket is not owned by the current user");
|
||||
}
|
||||
|
||||
fs::remove_file(socket_path)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_callback(callback: &str) -> anyhow::Result<()> {
|
||||
if callback.len() > MAX_CALLBACK_SIZE {
|
||||
bail!("Authentication callback exceeds the maximum supported size");
|
||||
}
|
||||
|
||||
let Some((scheme, data)) = callback.split_once(':') else {
|
||||
bail!("Authentication callback URL is invalid");
|
||||
};
|
||||
if scheme != CALLBACK_SCHEME || data.is_empty() {
|
||||
bail!("Authentication callback URL is invalid");
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
enum CallbackReadError {
|
||||
UnsupportedVersion,
|
||||
Invalid,
|
||||
Io,
|
||||
}
|
||||
|
||||
async fn read_callback(stream: &mut UnixStream) -> Result<String, CallbackReadError> {
|
||||
let mut magic = [0_u8; 4];
|
||||
stream.read_exact(&mut magic).await.map_err(|_| CallbackReadError::Io)?;
|
||||
if &magic != PROTOCOL_MAGIC {
|
||||
return Err(CallbackReadError::Invalid);
|
||||
}
|
||||
|
||||
let version = stream.read_u8().await.map_err(|_| CallbackReadError::Io)?;
|
||||
if version != PROTOCOL_VERSION {
|
||||
return Err(CallbackReadError::UnsupportedVersion);
|
||||
}
|
||||
|
||||
let length = stream.read_u32().await.map_err(|_| CallbackReadError::Io)? as usize;
|
||||
if length == 0 || length > MAX_CALLBACK_SIZE {
|
||||
return Err(CallbackReadError::Invalid);
|
||||
}
|
||||
|
||||
let mut payload = vec![0; length];
|
||||
stream
|
||||
.read_exact(&mut payload)
|
||||
.await
|
||||
.map_err(|_| CallbackReadError::Io)?;
|
||||
let callback = String::from_utf8(payload).map_err(|_| CallbackReadError::Invalid)?;
|
||||
validate_callback(&callback).map_err(|_| CallbackReadError::Invalid)?;
|
||||
Ok(callback)
|
||||
}
|
||||
|
||||
async fn write_response(stream: &mut UnixStream, status: u8) -> anyhow::Result<()> {
|
||||
stream.write_u8(PROTOCOL_VERSION).await?;
|
||||
stream.write_u8(status).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use tempfile::tempdir;
|
||||
|
||||
use super::*;
|
||||
|
||||
const VALID_CALLBACK: &str = "globalprotectcallback:cas-as=1&[email protected]&token=very_long_string";
|
||||
|
||||
#[test]
|
||||
fn validates_supported_callback_scheme() {
|
||||
assert!(validate_callback(VALID_CALLBACK).is_ok());
|
||||
assert!(validate_callback("https://example.com").is_err());
|
||||
assert!(validate_callback("globalprotectcallback:").is_err());
|
||||
assert!(validate_callback(&format!("globalprotectcallback:{}", "x".repeat(MAX_CALLBACK_SIZE))).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replaces_any_other_callback_handler() {
|
||||
assert!(!should_register_handler("gpgui.desktop"));
|
||||
assert!(should_register_handler(""));
|
||||
assert!(should_register_handler("gpauth.desktop"));
|
||||
assert!(should_register_handler("other-vpn.desktop"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn detects_lxqt_desktop_session() {
|
||||
assert!(is_lxqt_desktop(Some(OsStr::new("LXQt"))));
|
||||
assert!(is_lxqt_desktop(Some(OsStr::new("LXQt:KDE"))));
|
||||
assert!(is_lxqt_desktop(Some(OsStr::new("lxqt"))));
|
||||
assert!(!is_lxqt_desktop(Some(OsStr::new("LXDE"))));
|
||||
assert!(!is_lxqt_desktop(None));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn forwards_callback_to_waiting_receiver() {
|
||||
let directory = tempdir().unwrap();
|
||||
let socket_path = directory.path().join("callback.sock");
|
||||
let receiver = AuthCallbackReceiver::bind_at(socket_path.clone()).unwrap();
|
||||
assert_eq!(
|
||||
fs::symlink_metadata(&socket_path).unwrap().permissions().mode() & 0o777,
|
||||
0o600
|
||||
);
|
||||
|
||||
let sender = tokio::spawn(async move { forward_auth_callback_to(VALID_CALLBACK, &socket_path).await });
|
||||
let auth_data = receiver.receive().await.unwrap();
|
||||
|
||||
sender.await.unwrap().unwrap();
|
||||
assert_eq!(auth_data.username(), "[email protected]");
|
||||
assert_eq!(auth_data.token(), Some("very_long_string"));
|
||||
let socket_path = receiver.socket_path.clone();
|
||||
drop(receiver);
|
||||
assert!(!socket_path.exists());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rejects_bad_requests_and_keeps_waiting() {
|
||||
let directory = tempdir().unwrap();
|
||||
let socket_path = directory.path().join("callback.sock");
|
||||
let receiver = AuthCallbackReceiver::bind_at(socket_path.clone()).unwrap();
|
||||
|
||||
let sender = tokio::spawn(async move {
|
||||
assert_eq!(
|
||||
send_raw_callback(&socket_path, PROTOCOL_VERSION, "https://example.com").await,
|
||||
STATUS_INVALID_CALLBACK
|
||||
);
|
||||
assert_eq!(
|
||||
send_raw_callback(&socket_path, PROTOCOL_VERSION + 1, VALID_CALLBACK).await,
|
||||
STATUS_UNSUPPORTED_VERSION
|
||||
);
|
||||
forward_auth_callback_to(VALID_CALLBACK, &socket_path).await
|
||||
});
|
||||
let auth_data = receiver.receive().await.unwrap();
|
||||
|
||||
sender.await.unwrap().unwrap();
|
||||
assert_eq!(auth_data.username(), "[email protected]");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn ignores_sender_that_disconnects_before_sending() {
|
||||
let directory = tempdir().unwrap();
|
||||
let socket_path = directory.path().join("callback.sock");
|
||||
let receiver = AuthCallbackReceiver::bind_at(socket_path.clone()).unwrap();
|
||||
|
||||
drop(UnixStream::connect(&socket_path).await.unwrap());
|
||||
let sender = tokio::spawn(async move { forward_auth_callback_to(VALID_CALLBACK, &socket_path).await });
|
||||
let auth_data = receiver.receive().await.unwrap();
|
||||
|
||||
sender.await.unwrap().unwrap();
|
||||
assert_eq!(auth_data.username(), "[email protected]");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn replaces_owned_stale_socket() {
|
||||
let directory = tempdir().unwrap();
|
||||
let socket_path = directory.path().join("callback.sock");
|
||||
drop(std::os::unix::net::UnixListener::bind(&socket_path).unwrap());
|
||||
|
||||
let receiver = AuthCallbackReceiver::bind_at(socket_path.clone()).unwrap();
|
||||
assert!(socket_path.exists());
|
||||
drop(receiver);
|
||||
assert!(!socket_path.exists());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn reports_when_no_receiver_is_active() {
|
||||
let directory = tempdir().unwrap();
|
||||
let socket_path = directory.path().join("missing.sock");
|
||||
|
||||
let err = forward_auth_callback_to(VALID_CALLBACK, &socket_path)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(err.to_string().contains("No external-browser authentication"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_runtime_directory_with_broad_permissions() {
|
||||
let directory = tempdir().unwrap();
|
||||
let runtime_dir = directory.path().join("runtime");
|
||||
fs::create_dir(&runtime_dir).unwrap();
|
||||
fs::set_permissions(&runtime_dir, fs::Permissions::from_mode(0o755)).unwrap();
|
||||
|
||||
let err = prepare_socket_directory(&runtime_dir.join("callback.sock")).unwrap_err();
|
||||
assert!(err.to_string().contains("permissions are too broad"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rejects_second_active_receiver() {
|
||||
let directory = tempdir().unwrap();
|
||||
let socket_path = directory.path().join("callback.sock");
|
||||
let _receiver = AuthCallbackReceiver::bind_at(socket_path.clone()).unwrap();
|
||||
|
||||
let err = AuthCallbackReceiver::bind_at(socket_path).err().unwrap();
|
||||
assert!(err.to_string().contains("already in progress"));
|
||||
}
|
||||
|
||||
async fn send_raw_callback(socket_path: &Path, version: u8, callback: &str) -> u8 {
|
||||
let mut stream = UnixStream::connect(socket_path).await.unwrap();
|
||||
stream.write_all(PROTOCOL_MAGIC).await.unwrap();
|
||||
stream.write_u8(version).await.unwrap();
|
||||
stream.write_u32(callback.len() as u32).await.unwrap();
|
||||
stream.write_all(callback.as_bytes()).await.unwrap();
|
||||
assert_eq!(stream.read_u8().await.unwrap(), PROTOCOL_VERSION);
|
||||
stream.read_u8().await.unwrap()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
use std::{ffi::OsStr, os::raw::c_void, path::PathBuf, thread, time::Duration};
|
||||
|
||||
use anyhow::{Context, bail};
|
||||
use objc2_app_kit::NSWorkspace;
|
||||
use objc2_foundation::{NSBundle, NSString, NSURL};
|
||||
|
||||
const CALLBACK_SCHEME: &str = "globalprotectcallback";
|
||||
const CALLBACK_URL: &str = "globalprotectcallback:";
|
||||
const HANDLER_BUNDLE_ID: &str = "com.yuezk.gpauth";
|
||||
const LOGIN_APP_NAME: &str = "GP Connect Login.app";
|
||||
|
||||
#[link(name = "CoreServices", kind = "framework")]
|
||||
unsafe extern "C" {
|
||||
fn LSRegisterURL(url: *const c_void, update: u8) -> i32;
|
||||
}
|
||||
|
||||
pub(super) fn ensure_auth_callback_handler() -> anyhow::Result<()> {
|
||||
let workspace = NSWorkspace::sharedWorkspace();
|
||||
let app_paths = callback_app_paths();
|
||||
let selected_handler = current_handler(&workspace);
|
||||
match selected_handler.as_ref() {
|
||||
Some((handler, path))
|
||||
if handler == HANDLER_BUNDLE_ID && app_paths.iter().any(|candidate| same_path(candidate, path)) =>
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
Some((handler, _)) if handler == HANDLER_BUNDLE_ID => {}
|
||||
None => {}
|
||||
Some((handler, _)) => bail!("The globalprotectcallback URL scheme is owned by {handler}"),
|
||||
}
|
||||
|
||||
let app_path = app_paths
|
||||
.first()
|
||||
.context("GP Connect Login.app is required for external-browser authentication; install GP Connect")?;
|
||||
let app_url = file_url(app_path);
|
||||
register_app(&app_url)?;
|
||||
workspace.setDefaultApplicationAtURL_toOpenURLsWithScheme_completionHandler(
|
||||
&app_url,
|
||||
&NSString::from_str(CALLBACK_SCHEME),
|
||||
None,
|
||||
);
|
||||
|
||||
for _ in 0..50 {
|
||||
if current_handler(&workspace)
|
||||
.is_some_and(|(handler, path)| handler == HANDLER_BUNDLE_ID && same_path(app_path, &path))
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
thread::sleep(Duration::from_millis(100));
|
||||
}
|
||||
|
||||
bail!("The globalprotectcallback URL handler registration did not take effect")
|
||||
}
|
||||
|
||||
fn register_app(app_url: &NSURL) -> anyhow::Result<()> {
|
||||
// A nested application is not necessarily known to LaunchServices until it
|
||||
// has been launched. Register it explicitly before assigning its URL scheme.
|
||||
let status = unsafe { LSRegisterURL(app_url as *const NSURL as *const c_void, 1) };
|
||||
if status != 0 {
|
||||
bail!("Failed to register GP Connect Login.app with LaunchServices (OSStatus {status})");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn current_handler(workspace: &NSWorkspace) -> Option<(String, PathBuf)> {
|
||||
let callback_url = NSURL::URLWithString(&NSString::from_str(CALLBACK_URL))?;
|
||||
let app_url = workspace.URLForApplicationToOpenURL(&callback_url)?;
|
||||
let identifier = bundle_identifier(&app_url)?;
|
||||
let path = app_url.path().map(|path| PathBuf::from(path.to_string()))?;
|
||||
Some((identifier, path))
|
||||
}
|
||||
|
||||
fn callback_app_paths() -> Vec<PathBuf> {
|
||||
let mut candidates = Vec::new();
|
||||
|
||||
if let Ok(executable) = std::env::current_exe() {
|
||||
for path in executable.ancestors() {
|
||||
if path.file_name() == Some(OsStr::new("Helpers")) {
|
||||
candidates.push(path.join(LOGIN_APP_NAME));
|
||||
}
|
||||
if path.extension() == Some(OsStr::new("app")) {
|
||||
candidates.push(path.to_path_buf());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(user_dir) = std::env::var_os("HOME").filter(|path| !path.is_empty()) {
|
||||
let applications = PathBuf::from(user_dir).join("Applications");
|
||||
candidates.push(
|
||||
applications
|
||||
.join("GP Connect.app/Contents/Helpers")
|
||||
.join(LOGIN_APP_NAME),
|
||||
);
|
||||
}
|
||||
|
||||
candidates.push(PathBuf::from("/Applications/GP Connect.app/Contents/Helpers").join(LOGIN_APP_NAME));
|
||||
|
||||
candidates
|
||||
.into_iter()
|
||||
.filter(|path| path.is_dir() && bundle_identifier(&file_url(path)).as_deref() == Some(HANDLER_BUNDLE_ID))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn same_path(left: &std::path::Path, right: &std::path::Path) -> bool {
|
||||
match (left.canonicalize(), right.canonicalize()) {
|
||||
(Ok(left), Ok(right)) => left == right,
|
||||
_ => left == right,
|
||||
}
|
||||
}
|
||||
|
||||
fn file_url(path: &std::path::Path) -> objc2::rc::Retained<NSURL> {
|
||||
NSURL::fileURLWithPath(&NSString::from_str(&path.to_string_lossy()))
|
||||
}
|
||||
|
||||
fn bundle_identifier(app_url: &NSURL) -> Option<String> {
|
||||
NSBundle::bundleWithURL(app_url)?
|
||||
.bundleIdentifier()
|
||||
.map(|identifier| identifier.to_string())
|
||||
}
|
||||
@@ -7,9 +7,15 @@ use gpapi::{
|
||||
#[cfg(feature = "browser-auth")]
|
||||
mod browser;
|
||||
|
||||
#[cfg(feature = "browser-auth")]
|
||||
mod callback;
|
||||
|
||||
#[cfg(feature = "browser-auth")]
|
||||
pub use browser::*;
|
||||
|
||||
#[cfg(feature = "browser-auth")]
|
||||
pub use callback::*;
|
||||
|
||||
#[cfg(feature = "webview-auth")]
|
||||
mod webview;
|
||||
#[cfg(feature = "webview-auth")]
|
||||
|
||||
@@ -17,4 +17,4 @@ mod platform_impl;
|
||||
)))]
|
||||
compile_error!("webview-auth is only supported on macOS and GTK/WebKitGTK Unix targets");
|
||||
|
||||
pub use webview_auth::WebviewAuthenticator;
|
||||
pub use webview_auth::{WebviewAuthenticator, apply_auth_theme};
|
||||
@@ -1,17 +1,147 @@
|
||||
use anyhow::bail;
|
||||
use block2::RcBlock;
|
||||
use log::warn;
|
||||
use objc2::runtime::AnyObject;
|
||||
use objc2_foundation::{NSError, NSObject, NSObjectNSKeyValueCoding, NSString, NSURL, NSURLRequest};
|
||||
use objc2_web_kit::WKWebView;
|
||||
use std::{ffi::c_void, ptr};
|
||||
|
||||
use anyhow::{Context, bail};
|
||||
use block2::{DynBlock, RcBlock};
|
||||
use objc2::{
|
||||
DefinedClass, MainThreadOnly, define_class,
|
||||
ffi::{OBJC_ASSOCIATION_RETAIN_NONATOMIC, objc_setAssociatedObject},
|
||||
msg_send,
|
||||
rc::Retained,
|
||||
runtime::{AnyObject, ProtocolObject, Sel},
|
||||
};
|
||||
use objc2_foundation::{
|
||||
MainThreadMarker, NSError, NSObject, NSObjectNSKeyValueCoding, NSObjectProtocol, NSString, NSURL,
|
||||
NSURLAuthenticationChallenge, NSURLAuthenticationMethodServerTrust, NSURLCredential, NSURLRequest,
|
||||
NSURLSessionAuthChallengeDisposition,
|
||||
};
|
||||
use objc2_web_kit::{WKNavigationDelegate, WKWebView};
|
||||
use tauri::webview::PlatformWebview;
|
||||
|
||||
use super::webview_auth::PlatformWebviewExt;
|
||||
|
||||
static TLS_NAVIGATION_DELEGATE_KEY: u8 = 0;
|
||||
|
||||
struct TlsNavigationDelegateIvars {
|
||||
original: Retained<ProtocolObject<dyn WKNavigationDelegate>>,
|
||||
}
|
||||
|
||||
define_class!(
|
||||
#[unsafe(super = NSObject)]
|
||||
#[thread_kind = MainThreadOnly]
|
||||
#[ivars = TlsNavigationDelegateIvars]
|
||||
struct TlsNavigationDelegate;
|
||||
|
||||
unsafe impl NSObjectProtocol for TlsNavigationDelegate {}
|
||||
|
||||
#[allow(non_snake_case)]
|
||||
unsafe impl WKNavigationDelegate for TlsNavigationDelegate {
|
||||
#[unsafe(method(webView:didReceiveAuthenticationChallenge:completionHandler:))]
|
||||
unsafe fn webView_didReceiveAuthenticationChallenge_completionHandler(
|
||||
&self,
|
||||
_webview: &WKWebView,
|
||||
challenge: &NSURLAuthenticationChallenge,
|
||||
completion_handler: &DynBlock<dyn Fn(NSURLSessionAuthChallengeDisposition, *mut NSURLCredential)>,
|
||||
) {
|
||||
let protection_space = challenge.protectionSpace();
|
||||
let is_server_trust = protection_space
|
||||
.authenticationMethod()
|
||||
.isEqualToString(unsafe { NSURLAuthenticationMethodServerTrust });
|
||||
|
||||
if !is_server_trust {
|
||||
completion_handler.call((challenge_disposition(false), ptr::null_mut()));
|
||||
return;
|
||||
}
|
||||
|
||||
let server_trust: *mut AnyObject = msg_send![&*protection_space, serverTrust];
|
||||
if server_trust.is_null() {
|
||||
completion_handler.call((challenge_disposition(false), ptr::null_mut()));
|
||||
return;
|
||||
}
|
||||
|
||||
let credential: Retained<NSURLCredential> =
|
||||
msg_send![objc2::class!(NSURLCredential), credentialForTrust: server_trust];
|
||||
completion_handler.call((challenge_disposition(true), Retained::as_ptr(&credential).cast_mut()));
|
||||
}
|
||||
}
|
||||
|
||||
impl TlsNavigationDelegate {
|
||||
#[unsafe(method(respondsToSelector:))]
|
||||
fn responds_to_selector(&self, selector: Sel) -> bool {
|
||||
let responds: bool = unsafe { msg_send![super(self), respondsToSelector: selector] };
|
||||
responds || self.ivars().original.respondsToSelector(selector)
|
||||
}
|
||||
|
||||
#[unsafe(method(forwardingTargetForSelector:))]
|
||||
fn forwarding_target_for_selector(&self, selector: Sel) -> *mut AnyObject {
|
||||
if self.ivars().original.respondsToSelector(selector) {
|
||||
Retained::as_ptr(&self.ivars().original).cast_mut().cast()
|
||||
} else {
|
||||
unsafe { msg_send![super(self), forwardingTargetForSelector: selector] }
|
||||
}
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
impl TlsNavigationDelegate {
|
||||
fn new(original: Retained<ProtocolObject<dyn WKNavigationDelegate>>, mtm: MainThreadMarker) -> Retained<Self> {
|
||||
let this = Self::alloc(mtm).set_ivars(TlsNavigationDelegateIvars { original });
|
||||
unsafe { msg_send![super(this), init] }
|
||||
}
|
||||
}
|
||||
|
||||
fn challenge_disposition(is_server_trust: bool) -> NSURLSessionAuthChallengeDisposition {
|
||||
if is_server_trust {
|
||||
NSURLSessionAuthChallengeDisposition::UseCredential
|
||||
} else {
|
||||
NSURLSessionAuthChallengeDisposition::PerformDefaultHandling
|
||||
}
|
||||
}
|
||||
|
||||
fn install_tls_navigation_delegate(webview: &WKWebView) -> anyhow::Result<()> {
|
||||
let original = unsafe { webview.navigationDelegate() }.context("WebView navigation delegate is unavailable")?;
|
||||
let mtm = MainThreadMarker::new().context("WebView must be configured on the main thread")?;
|
||||
let delegate = TlsNavigationDelegate::new(original, mtm);
|
||||
|
||||
unsafe {
|
||||
objc_setAssociatedObject(
|
||||
webview as *const WKWebView as *mut AnyObject,
|
||||
&TLS_NAVIGATION_DELEGATE_KEY as *const u8 as *const c_void,
|
||||
Retained::as_ptr(&delegate).cast_mut().cast(),
|
||||
OBJC_ASSOCIATION_RETAIN_NONATOMIC,
|
||||
);
|
||||
webview.setNavigationDelegate(Some(ProtocolObject::from_ref(&*delegate)));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use objc2_foundation::NSURLSessionAuthChallengeDisposition;
|
||||
|
||||
use super::challenge_disposition;
|
||||
|
||||
#[test]
|
||||
fn accepts_server_trust_challenges() {
|
||||
assert_eq!(
|
||||
challenge_disposition(true),
|
||||
NSURLSessionAuthChallengeDisposition::UseCredential
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preserves_default_handling_for_other_challenges() {
|
||||
assert_eq!(
|
||||
challenge_disposition(false),
|
||||
NSURLSessionAuthChallengeDisposition::PerformDefaultHandling
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
impl PlatformWebviewExt for PlatformWebview {
|
||||
fn ignore_tls_errors(&self) -> anyhow::Result<()> {
|
||||
warn!("Ignoring TLS errors is not supported on macOS");
|
||||
Ok(())
|
||||
let webview: &WKWebView = unsafe { &*self.inner().cast() };
|
||||
install_tls_navigation_delegate(webview)
|
||||
}
|
||||
|
||||
fn user_agent(&self) -> anyhow::Result<String> {
|
||||
|
||||
@@ -1,13 +1,17 @@
|
||||
use std::{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::SamlAuthData,
|
||||
auth::{AuthWindowTheme, AuthenticationCancelled, SamlAuthData},
|
||||
gp_params::GpParams,
|
||||
os_profile::{WebviewUserAgent, WebviewUserAgentTransform},
|
||||
utils::redact::redact_uri,
|
||||
utils::{redact::redact_uri, window::get_title_bar_height},
|
||||
};
|
||||
use log::{info, warn};
|
||||
#[cfg(target_os = "macos")]
|
||||
use tauri::Manager;
|
||||
use tauri::{
|
||||
AppHandle, WebviewUrl, WebviewWindow, WindowEvent,
|
||||
webview::{PageLoadEvent, PageLoadPayload},
|
||||
@@ -53,10 +57,28 @@ pub struct WebviewAuthenticator<'a> {
|
||||
auth_request: Option<&'a str>,
|
||||
webview_user_agent: Option<WebviewUserAgent>,
|
||||
clean: bool,
|
||||
window_title: &'a str,
|
||||
window_theme: AuthWindowTheme,
|
||||
|
||||
is_retrying: tokio::sync::RwLock<bool>,
|
||||
}
|
||||
|
||||
fn native_theme(theme: AuthWindowTheme) -> Option<tauri::Theme> {
|
||||
match theme {
|
||||
AuthWindowTheme::System => None,
|
||||
AuthWindowTheme::Light => Some(tauri::Theme::Light),
|
||||
AuthWindowTheme::Dark => Some(tauri::Theme::Dark),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn apply_auth_theme(app_handle: &AppHandle, theme: AuthWindowTheme) {
|
||||
app_handle.set_theme(native_theme(theme));
|
||||
}
|
||||
|
||||
fn present_after_setup(clean: bool) -> bool {
|
||||
clean
|
||||
}
|
||||
|
||||
impl<'a> WebviewAuthenticator<'a> {
|
||||
pub fn new(server: &'a str, gp_params: &'a GpParams) -> Self {
|
||||
Self {
|
||||
@@ -65,6 +87,8 @@ impl<'a> WebviewAuthenticator<'a> {
|
||||
auth_request: None,
|
||||
webview_user_agent: None,
|
||||
clean: false,
|
||||
window_title: "GlobalProtect Login",
|
||||
window_theme: AuthWindowTheme::System,
|
||||
is_retrying: Default::default(),
|
||||
}
|
||||
}
|
||||
@@ -84,6 +108,16 @@ impl<'a> WebviewAuthenticator<'a> {
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_window_title(mut self, window_title: &'a str) -> Self {
|
||||
self.window_title = window_title;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_window_theme(mut self, window_theme: AuthWindowTheme) -> Self {
|
||||
self.window_theme = window_theme;
|
||||
self
|
||||
}
|
||||
|
||||
pub async fn authenticate(&self, app_handle: &AppHandle) -> anyhow::Result<SamlAuthData> {
|
||||
let auth_messenger = Arc::new(AuthMessenger::new());
|
||||
let auth_messenger_clone = Arc::clone(&auth_messenger);
|
||||
@@ -112,25 +146,32 @@ impl<'a> WebviewAuthenticator<'a> {
|
||||
});
|
||||
};
|
||||
|
||||
let title_bar_height = if cfg!(target_os = "macos") { 28.0 } else { 0.0 };
|
||||
|
||||
let auth_window = WebviewWindow::builder(app_handle, "auth_window", WebviewUrl::default())
|
||||
let auth_window_builder = WebviewWindow::builder(app_handle, "auth_window", WebviewUrl::default())
|
||||
.on_page_load(on_page_load)
|
||||
.title("GlobalProtect Login")
|
||||
.inner_size(900.0, 650.0 + title_bar_height)
|
||||
.title(self.window_title)
|
||||
.theme(native_theme(self.window_theme))
|
||||
.devtools(cfg!(any(debug_assertions, feature = "release-devtools")));
|
||||
let auth_window = auth_window_builder
|
||||
.inner_size(900.0, 650.0 + get_title_bar_height())
|
||||
.focused(true)
|
||||
// when clean is true, the window is expected to be shown because the cookies are cleared
|
||||
.visible(self.clean)
|
||||
.visible(false)
|
||||
.center()
|
||||
.build()?;
|
||||
|
||||
#[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);
|
||||
}
|
||||
|
||||
loop {
|
||||
match auth_messenger.subscribe().await? {
|
||||
AuthEvent::Close => bail!("Authentication cancelled"),
|
||||
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),
|
||||
@@ -285,13 +326,15 @@ impl<'a> WebviewAuthenticator<'a> {
|
||||
info!("Raising auth window...");
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
let result = auth_window.show();
|
||||
if let Err(err) = auth_window
|
||||
.app_handle()
|
||||
.set_activation_policy(tauri::ActivationPolicy::Regular)
|
||||
{
|
||||
warn!("Failed to show the application in the Dock: {}", err);
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
|
||||
let result = {
|
||||
use gpapi::utils::window::WindowExt;
|
||||
auth_window.raise()
|
||||
};
|
||||
use gpapi::utils::window::WindowExt;
|
||||
let result = auth_window.raise();
|
||||
|
||||
if let Err(err) = result {
|
||||
warn!("Failed to raise window: {}", err);
|
||||
@@ -377,6 +420,19 @@ fn prepend_webview_user_agent_prefix(prefix: &str, default_user_agent: &str) ->
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn maps_auth_window_theme_to_native_theme() {
|
||||
assert_eq!(native_theme(AuthWindowTheme::System), None);
|
||||
assert_eq!(native_theme(AuthWindowTheme::Light), Some(tauri::Theme::Light));
|
||||
assert_eq!(native_theme(AuthWindowTheme::Dark), Some(tauri::Theme::Dark));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn presents_clean_auth_after_setup() {
|
||||
assert!(present_after_setup(true));
|
||||
assert!(!present_after_setup(false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prepends_prefix_to_default_user_agent() {
|
||||
let user_agent = prepend_webview_user_agent_prefix("PAN GlobalProtect/6.3.3", "Mozilla/5.0").unwrap();
|
||||
|
||||
Reference in new issue
Block a user