feat(macos): improve bundled app integration

This commit is contained in:
Kevin Yue committed 2026-07-19 22:26:19 +08:00
1 parent 822d10528f
commit bd064713a8
8 files changed
+182 -29

No files matched your search

+1 -2
View File
@@ -11,14 +11,13 @@ tauri-build = { version = "2", features = [], optional = true }
[dependencies]
common = { path = "../../crates/common" }
gpapi = { path = "../../crates/gpapi", features = ["clap"] }
gpapi = { path = "../../crates/gpapi", features = ["clap", "logger"] }
auth = { path = "../../crates/auth", features = ["browser-auth"] }
# Shared dependencies
anyhow.workspace = true
clap.workspace = true
env_logger.workspace = true
log.workspace = true
serde_json.workspace = true
tokio = { workspace = true, features = ["rt-multi-thread"] }
+5 -3
View File
@@ -206,9 +206,11 @@ impl Cli {
}
fn init_logger(cli: &Cli) {
env_logger::builder()
.filter_level(cli.verbose.log_level_filter())
.init();
if let Some(level) = cli.verbose.log_level_filter().to_level() {
gpapi::logger::init(level, "com.yuezk.gpgui", "gpauth");
} else {
log::set_max_level(log::LevelFilter::Off);
}
}
pub async fn run() {
+49 -6
View File
@@ -18,6 +18,8 @@ use gpapi::{
service::{request::WsRequest, vpn_state::VpnState},
utils::{env_utils, lock_file::LockFile, redact::Redaction, shutdown_signal},
};
#[cfg(target_os = "macos")]
use log::{Log, Metadata, Record};
use log::{info, warn};
use tokio::sync::{mpsc, watch};
use uuid::Uuid;
@@ -35,6 +37,28 @@ const VERSION: &str = concat!(
")"
);
#[cfg(target_os = "macos")]
struct RedactingMacosLogger {
logger: logger::MacosLogger,
redaction: Arc<Redaction>,
}
#[cfg(target_os = "macos")]
impl Log for RedactingMacosLogger {
fn enabled(&self, metadata: &Metadata<'_>) -> bool {
self.logger.enabled(metadata)
}
fn log(&self, record: &Record<'_>) {
if self.enabled(record.metadata()) {
let message = self.redaction.redact_str(&record.args().to_string());
self.logger.write(record.level(), record.target(), &message);
}
}
fn flush(&self) {}
}
#[derive(Parser)]
#[command(version = VERSION)]
struct Cli {
@@ -77,15 +101,22 @@ impl Cli {
let gui_restart_requested = Arc::new(AtomicBool::new(false));
let registry = Arc::new(SessionRegistry::new(Uuid::new_v4()));
let externally_brokered = self.externally_brokered();
let brokered_helpers_dir = externally_brokered
.then(|| std::env::current_exe().ok()?.parent().map(ToOwned::to_owned))
.flatten();
let brokered_scripts_dir = if externally_brokered {
let executable = std::env::current_exe().context("Failed to locate the gpservice executable")?;
let contents_dir = executable
.parent()
.and_then(std::path::Path::parent)
.context("gpservice is not inside a macOS application bundle")?;
Some(contents_dir.join("Resources/Scripts"))
} else {
None
};
let dispatcher = Arc::new(RequestDispatcher::new(
ws_req_tx.clone(),
Arc::clone(&gui_restart_requested),
Arc::clone(&redaction),
!externally_brokered,
brokered_helpers_dir,
brokered_scripts_dir,
));
let mut vpn_task = VpnTask::new(ws_req_rx, vpn_state_tx, externally_brokered);
@@ -201,6 +232,20 @@ impl Cli {
fn init_logger(&self) -> Arc<Redaction> {
let redaction = Arc::new(Redaction::new());
let level = self.verbose.log_level_filter().to_level().unwrap_or(log::Level::Info);
#[cfg(target_os = "macos")]
if logger::macos_unified_log_enabled() {
logger::init_with_logger(
level,
RedactingMacosLogger {
logger: logger::MacosLogger::new("com.yuezk.gpgui", "gpservice"),
redaction: Arc::clone(&redaction),
},
);
return redaction;
}
let redaction_clone = Arc::clone(&redaction);
let inner_logger = env_logger::builder()
@@ -219,8 +264,6 @@ impl Cli {
})
.build();
let level = self.verbose.log_level_filter().to_level().unwrap_or(log::Level::Info);
logger::init_with_logger(level, inner_logger);
redaction
+35 -9
View File
@@ -30,7 +30,7 @@ pub struct RequestDispatcher {
redaction: Arc<Redaction>,
install_lock: Mutex<()>,
gui_management_enabled: bool,
brokered_helpers_dir: Option<std::path::PathBuf>,
brokered_scripts_dir: Option<std::path::PathBuf>,
}
impl RequestDispatcher {
@@ -39,7 +39,7 @@ impl RequestDispatcher {
gui_restart_requested: Arc<AtomicBool>,
redaction: Arc<Redaction>,
gui_management_enabled: bool,
brokered_helpers_dir: Option<std::path::PathBuf>,
brokered_scripts_dir: Option<std::path::PathBuf>,
) -> Self {
Self {
ws_req_tx,
@@ -47,7 +47,7 @@ impl RequestDispatcher {
redaction,
install_lock: Mutex::new(()),
gui_management_enabled,
brokered_helpers_dir,
brokered_scripts_dir,
}
}
@@ -97,11 +97,11 @@ impl RequestDispatcher {
}
fn validate_connect_paths(&self, request: &gpapi::service::request::ConnectRequest) -> Result<(), &'static str> {
let Some(helpers) = &self.brokered_helpers_dir else {
let Some(scripts) = &self.brokered_scripts_dir else {
return Ok(());
};
let expected_script = helpers.join("vpnc-script").to_string_lossy().into_owned();
let expected_wrapper = helpers.join("hipreport.sh").to_string_lossy().into_owned();
let expected_script = scripts.join("vpnc-script").to_string_lossy().into_owned();
let expected_wrapper = scripts.join("hipreport.sh").to_string_lossy().into_owned();
if request.args().vpnc_script().as_deref() != Some(expected_script.as_str()) {
return Err("macOS VPN script must be the bundled script");
}
@@ -329,7 +329,7 @@ mod tests {
Arc::new(AtomicBool::new(false)),
Arc::new(Redaction::new()),
false,
Some(std::path::PathBuf::from("/app/Contents/Helpers")),
Some(std::path::PathBuf::from("/app/Contents/Resources/Scripts")),
);
let ServiceResult::Rejected(rejection) = dispatcher.dispatch(WsRequest::RestartGui).await else {
panic!("brokered mode accepted GUI restart");
@@ -339,12 +339,38 @@ mod tests {
let gateway = Gateway::new("Gateway".into(), "vpn.example.com".into());
let info = gpapi::service::vpn_state::ConnectInfo::new("portal.example.com".into(), gateway.clone(), vec![gateway]);
let request = ConnectRequest::new(info, "cookie".into())
.with_vpnc_script(Some("/app/Contents/Helpers/vpnc-script".to_string()))
.with_csd_wrapper(Some("/app/Contents/Helpers/hipreport.sh".to_string()))
.with_vpnc_script(Some("/app/Contents/Resources/Scripts/vpnc-script".to_string()))
.with_csd_wrapper(Some("/app/Contents/Resources/Scripts/hipreport.sh".to_string()))
.with_certificate(Some("/Users/example/client.pem".to_string()));
let ServiceResult::Rejected(rejection) = dispatcher.dispatch(WsRequest::Connect(Box::new(request))).await else {
panic!("brokered mode accepted a root-readable identity path");
};
assert_eq!(rejection.code(), ServiceErrorCode::InvalidRequest);
}
#[test]
fn brokered_mode_accepts_only_resource_script_paths() {
let (request_tx, _request_rx) = mpsc::channel(1);
let dispatcher = RequestDispatcher::new(
request_tx,
Arc::new(AtomicBool::new(false)),
Arc::new(Redaction::new()),
false,
Some(std::path::PathBuf::from("/app/Contents/Resources/Scripts")),
);
let gateway = Gateway::new("Gateway".into(), "vpn.example.com".into());
let info = gpapi::service::vpn_state::ConnectInfo::new("portal.example.com".into(), gateway.clone(), vec![gateway]);
let bundled = ConnectRequest::new(info.clone(), "cookie".into())
.with_vpnc_script(Some("/app/Contents/Resources/Scripts/vpnc-script".to_string()))
.with_csd_wrapper(Some("/app/Contents/Resources/Scripts/hipreport.sh".to_string()));
assert_eq!(dispatcher.validate_connect_paths(&bundled), Ok(()));
let old_layout = ConnectRequest::new(info, "cookie".into())
.with_vpnc_script(Some("/app/Contents/Helpers/vpnc-script".to_string()))
.with_csd_wrapper(Some("/app/Contents/Helpers/hipreport.sh".to_string()));
assert_eq!(
dispatcher.validate_connect_paths(&old_layout),
Err("macOS VPN script must be the bundled script")
);
}
}