feat: add launch guard and secure multi-user service ownership (#7569)

* feat(service): isolate macOS launch and owner runtime

* ci(windows): run owner security tests

* chore(deps): use kode-bridge v0.4.1 tag

* fix(macos): classify installed service state

* fix(macos): classify marked unavailable service

* fix(macos): gate core startup on service migration

* fix(macos): scope service init to supported platforms

* feat(macos): prompt before migrating installed service

* fix(macos): shorten sidecar IPC path

* build(service): pin helper protocol and artifacts

* fix(core): require confirmed service and sidecar readiness

* fix(macos): harden launch roots and singleton state

* fix(ui): refresh migration state before restart

* fix(macos): linearize service migration lifecycle

* fix(ui): keep service migration state fresh

* feat(service): track authenticated owner sessions

* fix(service): preserve newer owner sessions

* feat(macos): route service proxy changes through helper

* fix(macos): serialize service proxy guard

* fix(macos): close service proxy owner lifecycle

* fix(macos): close remaining proxy stop races

* fix(app): do not cancel controlled service stop

* fix(lifecycle): keep controlled updates cancellation-safe

* fix(macos): stage dev core for service

* test(macos): exercise staged core cleanup

* fix(dev): await controlled macOS exit

* chore: update changelog

* fix(macos): recover sidecar after service install failure

Allow the existing sidecar to continue when service installation leaves the manager in InstallRequired, then settle the session state as SidecarAllowed. Show neutral status text while the migration dialog waits for its final state.

* fix(macos): stage dev service tools before elevation

* fix(macos): localize launch guard prompts

* fix(service): address cross-platform integration issues

* feat: support seamless service migration

* fix: pass Windows service installer path safely

* fix(prebuild): derive service release from Cargo dependency

* fix(dev): preserve service installation state

* fix: resolve clippy warnings in service lifecycle
This commit is contained in:
wonfen
2026-07-24 09:01:49 +08:00
committed by GitHub
parent c079da6c99
commit 23dda47641
90 changed files with 9711 additions and 900 deletions
+11 -2
View File
@@ -43,7 +43,6 @@ pub async fn restart_app() {
// 设置退出标志
handle::Handle::global().set_is_exiting();
utils::server::shutdown_embedded_server();
Config::apply_all_and_save_file().await;
logging!(info, Type::System, "开始异步清理资源");
@@ -53,9 +52,19 @@ pub async fn restart_app() {
info,
Type::System,
"资源清理完成,退出代码: {}",
if cleanup_result { 0 } else { 1 }
if cleanup_result.all_success { 0 } else { 1 }
);
if !cleanup_result.core_stopped {
handle::Handle::global().clear_is_exiting();
handle::Handle::notice_message(
"set_config::error",
"Failed to stop the core safely; restart was cancelled",
);
return;
}
utils::server::shutdown_embedded_server();
let app_handle = handle::Handle::app_handle();
app_handle.restart();
}
+4 -3
View File
@@ -1,6 +1,6 @@
use crate::{
config::{Config, IVerge},
core::{CoreManager, autostart, handle, hotkey, logger::Logger, sysopt, tray},
core::{CoreManager, autostart, handle, hotkey, logger::Logger, tray},
module::{auto_backup::AutoBackupManager, lightweight},
};
use anyhow::Result;
@@ -223,8 +223,9 @@ async fn process_terminated_flags(update_flags: UpdateFlags, patch: &IVerge) ->
clash_verge_i18n::set_locale(language.as_str());
}
if update_flags.contains(UpdateFlags::SYS_PROXY) {
sysopt::Sysopt::global().update_sysproxy().await?;
sysopt::Sysopt::global().refresh_guard().await;
let manager = CoreManager::global();
let _lifecycle = manager.lifecycle_lock.lock().await;
manager.apply_proxy_after_start().await?;
}
if update_flags.contains(UpdateFlags::HOTKEY)
&& let Some(hotkeys) = &patch.hotkeys
+352 -114
View File
@@ -1,10 +1,103 @@
use crate::config::Config;
use crate::core::{CoreManager, handle, sysopt};
use crate::core::{CoreManager, handle};
use crate::module::lightweight;
use crate::utils;
use crate::utils::window_manager::WindowManager;
use clash_verge_logging::{Type, logging};
use tokio::time::{Duration, timeout};
use tokio::time::Duration;
#[cfg(target_os = "macos")]
use tokio::time::timeout;
#[derive(Debug, Clone, Copy)]
pub struct CleanupResult {
pub all_success: bool,
pub core_stopped: bool,
}
const fn should_abort_exit_after_cleanup(core_stopped: bool) -> bool {
!core_stopped
}
async fn run_exit_cleanup_transition<Stop, StopFuture, Ancillary, AncillaryFuture>(
stop_core: Stop,
ancillary_cleanup: Ancillary,
) -> CleanupResult
where
Stop: FnOnce() -> StopFuture,
StopFuture: std::future::Future<Output = bool>,
Ancillary: FnOnce() -> AncillaryFuture,
AncillaryFuture: std::future::Future<Output = bool>,
{
if !stop_core().await {
return CleanupResult {
all_success: false,
core_stopped: false,
};
}
CleanupResult {
all_success: ancillary_cleanup().await,
core_stopped: true,
}
}
async fn run_interactive_cleanup_transition<Stop, StopFuture, Ancillary, AncillaryFuture>(
stop_core: Stop,
ancillary_cleanup: Ancillary,
) -> CleanupResult
where
Stop: FnOnce() -> StopFuture,
StopFuture: std::future::Future<Output = bool>,
Ancillary: FnOnce() -> AncillaryFuture,
AncillaryFuture: std::future::Future<Output = bool>,
{
run_exit_cleanup_transition(stop_core, ancillary_cleanup).await
}
async fn run_session_ending_cleanup_transition<Stop, StopFuture, DeadlineFuture, Ancillary, AncillaryFuture>(
stop_core: Stop,
stop_deadline: DeadlineFuture,
ancillary_cleanup: Ancillary,
) -> CleanupResult
where
Stop: FnOnce() -> StopFuture,
StopFuture: std::future::Future<Output = bool>,
DeadlineFuture: std::future::Future<Output = ()>,
Ancillary: FnOnce() -> AncillaryFuture,
AncillaryFuture: std::future::Future<Output = bool>,
{
run_exit_cleanup_transition(
|| async {
tokio::select! {
biased;
stopped = stop_core() => stopped,
() = stop_deadline => false,
}
},
ancillary_cleanup,
)
.await
}
async fn restore_dns_after_core_stop() -> bool {
#[cfg(target_os = "macos")]
match timeout(
Duration::from_millis(1000),
crate::utils::resolve::dns::restore_public_dns(),
)
.await
{
Ok(_) => {
logging!(info, Type::Window, "DNS设置已恢复");
true
}
Err(_) => {
logging!(warn, Type::Window, "Warning: 恢复DNS设置超时");
false
}
}
#[cfg(not(target_os = "macos"))]
true
}
pub async fn open_or_close_dashboard() {
if lightweight::is_in_lightweight_mode() {
@@ -16,12 +109,11 @@ pub async fn open_or_close_dashboard() {
logging!(info, Type::Window, "Window toggle result: {result:?}");
}
pub async fn quit() {
pub async fn quit() -> clash_verge_signal::ShutdownOutcome {
logging!(debug, Type::System, "启动退出流程");
// 设置退出标志
handle::Handle::global().set_is_exiting();
utils::server::shutdown_embedded_server();
Config::apply_all_and_save_file().await;
logging!(info, Type::System, "开始异步清理资源");
@@ -31,135 +123,116 @@ pub async fn quit() {
info,
Type::System,
"资源清理完成,退出代码: {}",
if cleanup_result { 0 } else { 1 }
if cleanup_result.all_success { 0 } else { 1 }
);
if should_abort_exit_after_cleanup(cleanup_result.core_stopped) {
handle::Handle::global().clear_is_exiting();
handle::Handle::notice_message(
"set_config::error",
"Failed to stop the core safely; quit was cancelled",
);
return clash_verge_signal::ShutdownOutcome::Canceled;
}
utils::server::shutdown_embedded_server();
let app_handle = handle::Handle::app_handle();
app_handle.exit(if cleanup_result { 0 } else { 1 });
app_handle.exit(if cleanup_result.all_success { 0 } else { 1 });
clash_verge_signal::ShutdownOutcome::Committed
}
pub async fn clean_async() -> bool {
logging!(info, Type::System, "开始执行异步清理操作...");
pub async fn clean_async() -> CleanupResult {
logging!(
info,
Type::System,
"Starting interactive cleanup; controlled core stop will be awaited to completion"
);
// 重置系统代理
let proxy_task = tokio::task::spawn(async {
let sys_proxy_enabled = Config::verge().await.data_arc().enable_system_proxy.unwrap_or(false);
if !sys_proxy_enabled {
logging!(info, Type::Window, "系统代理未启用,跳过重置");
return true;
}
logging!(info, Type::Window, "开始重置系统代理...");
match timeout(Duration::from_millis(1500), sysopt::Sysopt::global().reset_sysproxy()).await {
Ok(Ok(_)) => {
logging!(info, Type::Window, "系统代理已重置");
true
}
Ok(Err(e)) => {
logging!(warn, Type::Window, "Warning: 重置系统代理失败: {e}");
false
}
Err(_) => {
logging!(warn, Type::Window, "Warning: 重置系统代理超时,继续退出");
false
}
}
});
// 关闭 Tun 模式 + 停止核心服务
let core_task = tokio::task::spawn(async {
logging!(info, Type::System, "disable tun");
let tun_enabled = Config::verge().await.data_arc().enable_tun_mode.unwrap_or(false);
if tun_enabled {
let disable_tun = serde_json::json!({ "tun": { "enable": false } });
logging!(info, Type::System, "send disable tun request to mihomo");
match timeout(
Duration::from_millis(1000),
handle::Handle::mihomo().await.patch_base_config(&disable_tun),
)
.await
{
Ok(Ok(_)) => {
logging!(info, Type::Window, "TUN模式已禁用");
let result = run_interactive_cleanup_transition(
|| async {
logging!(info, Type::System, "Stopping core for interactive quit or restart");
match CoreManager::global().stop_core().await {
Ok(()) => {
logging!(info, Type::Window, "Core stopped for interactive quit or restart");
true
}
Ok(Err(e)) => {
logging!(warn, Type::Window, "Warning: 禁用TUN模式失败: {e}");
}
Err(_) => {
Err(error) => {
logging!(
warn,
Type::Window,
"Warning: 禁用TUN模式超时(可能系统正在关机),继续退出流程"
"Controlled core stop failed; interactive quit or restart must remain cancelled: {error:#}"
);
false
}
}
}
#[cfg(target_os = "windows")]
let stop_timeout = Duration::from_secs(2);
#[cfg(not(target_os = "windows"))]
let stop_timeout = Duration::from_secs(3);
logging!(info, Type::System, "stop core");
match timeout(stop_timeout, CoreManager::global().stop_core()).await {
Ok(_) => {
logging!(info, Type::Window, "core已停止");
true
}
Err(_) => {
logging!(
warn,
Type::Window,
"Warning: 停止core超时(可能系统正在关机),继续退出"
);
false
}
}
});
// DNS恢复(仅macOS)
let dns_task = tokio::task::spawn(async {
#[cfg(target_os = "macos")]
match timeout(
Duration::from_millis(1000),
crate::utils::resolve::dns::restore_public_dns(),
)
.await
{
Ok(_) => {
logging!(info, Type::Window, "DNS设置已恢复");
true
}
Err(_) => {
logging!(warn, Type::Window, "Warning: 恢复DNS设置超时");
false
}
}
#[cfg(not(target_os = "macos"))]
true
});
// 并行执行清理任务
let (proxy_result, core_result, dns_result) = tokio::join!(proxy_task, core_task, dns_task);
let proxy_success = proxy_result.unwrap_or_default();
let core_success = core_result.unwrap_or_default();
let dns_success = dns_result.unwrap_or_default();
let all_success = proxy_success && core_success && dns_success;
},
restore_dns_after_core_stop,
)
.await;
logging!(
info,
Type::System,
"异步关闭操作完成 - 代理: {}, 核心: {}, DNS: {}, 总体: {}",
proxy_success,
core_success,
dns_success,
all_success
"Interactive cleanup complete - core stopped: {}, all cleanup successful: {}",
result.core_stopped,
result.all_success
);
all_success
result
}
pub async fn clean_session_ending_best_effort() -> CleanupResult {
#[cfg(target_os = "windows")]
let stop_timeout = Duration::from_secs(2);
#[cfg(not(target_os = "windows"))]
let stop_timeout = Duration::from_secs(3);
logging!(
info,
Type::System,
"Starting bounded session-ending best-effort cleanup"
);
let result = run_session_ending_cleanup_transition(
|| async {
logging!(info, Type::System, "Stopping core during session-ending best-effort cleanup");
match CoreManager::global().stop_core().await {
Ok(()) => {
logging!(info, Type::Window, "Core stopped during session-ending best-effort cleanup");
true
}
Err(error) => {
logging!(
warn,
Type::Window,
"Session-ending best-effort core stop failed; OS or session exit is already in progress: {error:#}"
);
false
}
}
},
async move {
tokio::time::sleep(stop_timeout).await;
logging!(
warn,
Type::Window,
"Session-ending best-effort core stop timed out after {} seconds; OS or session exit is already in progress",
stop_timeout.as_secs()
);
},
restore_dns_after_core_stop,
)
.await;
logging!(
info,
Type::System,
"Session-ending best-effort cleanup finished - core stopped: {}, all cleanup successful: {}",
result.core_stopped,
result.all_success
);
result
}
#[cfg(target_os = "macos")]
@@ -183,3 +256,168 @@ pub async fn hide() {
}
handle::Handle::global().set_activation_policy_accessory();
}
#[cfg(test)]
mod tests {
use super::{
run_interactive_cleanup_transition, run_session_ending_cleanup_transition, should_abort_exit_after_cleanup,
};
use parking_lot::Mutex;
use std::{
future::pending,
sync::{
Arc,
atomic::{AtomicBool, Ordering},
},
task::Poll,
};
use tokio::sync::Barrier;
struct CancellationProbe {
cancelled: Arc<AtomicBool>,
completed: Arc<AtomicBool>,
}
impl Drop for CancellationProbe {
fn drop(&mut self) {
if !self.completed.load(Ordering::Acquire) {
self.cancelled.store(true, Ordering::Release);
}
}
}
#[test]
fn exit_aborts_when_controlled_core_stop_fails() {
assert!(should_abort_exit_after_cleanup(false));
assert!(!should_abort_exit_after_cleanup(true));
}
#[tokio::test]
async fn interactive_cleanup_awaits_barrier_controlled_stop_without_cancellation() {
let calls = Arc::new(Mutex::new(Vec::new()));
let stop_started = Arc::new(Barrier::new(2));
let release_stop = Arc::new(Barrier::new(2));
let stop_cancelled = Arc::new(AtomicBool::new(false));
let stop_completed = Arc::new(AtomicBool::new(false));
let mut cleanup = Box::pin(run_interactive_cleanup_transition(
{
let calls = Arc::clone(&calls);
let stop_started = Arc::clone(&stop_started);
let release_stop = Arc::clone(&release_stop);
let stop_cancelled = Arc::clone(&stop_cancelled);
let stop_completed = Arc::clone(&stop_completed);
move || async move {
let _probe = CancellationProbe {
cancelled: stop_cancelled,
completed: Arc::clone(&stop_completed),
};
calls.lock().push("core_stop");
stop_started.wait().await;
release_stop.wait().await;
stop_completed.store(true, Ordering::Release);
true
}
},
{
let calls = Arc::clone(&calls);
move || async move {
calls.lock().push("ancillary_cleanup");
true
}
},
));
assert!(matches!(futures::poll!(cleanup.as_mut()), Poll::Pending));
stop_started.wait().await;
assert!(matches!(futures::poll!(cleanup.as_mut()), Poll::Pending));
assert!(!stop_cancelled.load(Ordering::Acquire));
assert_eq!(&*calls.lock(), &["core_stop"]);
release_stop.wait().await;
let result = cleanup.await;
assert!(result.core_stopped);
assert!(result.all_success);
assert!(!stop_cancelled.load(Ordering::Acquire));
assert_eq!(&*calls.lock(), &["core_stop", "ancillary_cleanup"]);
}
#[tokio::test]
async fn interactive_cleanup_does_not_run_ancillary_cleanup_after_stop_failure() {
let calls = Mutex::new(Vec::new());
let result = run_interactive_cleanup_transition(
|| async {
calls.lock().push("core_stop");
false
},
|| async {
calls.lock().push("ancillary_cleanup");
true
},
)
.await;
assert!(!result.core_stopped);
assert!(!result.all_success);
assert_eq!(&*calls.lock(), &["core_stop"]);
}
#[tokio::test]
async fn session_ending_cleanup_may_cancel_stop_and_skips_ancillary_after_timeout() {
let calls = Arc::new(Mutex::new(Vec::new()));
let stop_started = Arc::new(Barrier::new(2));
let deadline_started = Arc::new(Barrier::new(2));
let release_deadline = Arc::new(Barrier::new(2));
let stop_cancelled = Arc::new(AtomicBool::new(false));
let stop_completed = Arc::new(AtomicBool::new(false));
let mut cleanup = Box::pin(run_session_ending_cleanup_transition(
{
let calls = Arc::clone(&calls);
let stop_started = Arc::clone(&stop_started);
let stop_cancelled = Arc::clone(&stop_cancelled);
let stop_completed = Arc::clone(&stop_completed);
move || async move {
let _probe = CancellationProbe {
cancelled: stop_cancelled,
completed: stop_completed,
};
calls.lock().push("core_stop");
stop_started.wait().await;
pending::<bool>().await
}
},
{
let deadline_started = Arc::clone(&deadline_started);
let release_deadline = Arc::clone(&release_deadline);
async move {
deadline_started.wait().await;
release_deadline.wait().await;
}
},
{
let calls = Arc::clone(&calls);
move || async move {
calls.lock().push("ancillary_cleanup");
true
}
},
));
assert!(matches!(futures::poll!(cleanup.as_mut()), Poll::Pending));
stop_started.wait().await;
deadline_started.wait().await;
assert!(matches!(futures::poll!(cleanup.as_mut()), Poll::Pending));
assert!(!stop_cancelled.load(Ordering::Acquire));
release_deadline.wait().await;
let result = cleanup.await;
assert!(!result.core_stopped);
assert!(!result.all_success);
assert!(stop_cancelled.load(Ordering::Acquire));
assert_eq!(&*calls.lock(), &["core_stop"]);
}
}