Privileged helper for system proxy (#796)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Gregory SchierandClaude Opus 5.5 authored and GitHub committed 2026-10-30 00:41:00 -07:00
1 parent 4d38a482f6
commit f7aea62c07
33 files changed
+3536 -176

No files matched your search

+99 -6
View File
@@ -8,6 +8,7 @@ pub mod convert;
pub mod db;
pub mod flows;
pub mod har;
pub mod helper;
pub mod macos;
pub mod models;
pub mod save;
@@ -20,6 +21,7 @@ use crate::client::ControlClient;
use crate::control::{ControlFile, ControlInfo, ControlServer, Owner};
use crate::convert::DroppedHeader;
use crate::db::ProxyQueryManager;
use crate::helper::HelperState;
use crate::macos::{SystemProxyBackend, SystemProxyStatus};
use crate::models::{Flow, FlowBody, FlowIden, ModelPayload, ProxyHeader, find_header};
use crate::save::{ClientDb, SaveFlowRequest, SaveFlowResponse, WorkspaceSummary};
@@ -364,18 +366,63 @@ impl ProxyCtx {
}
}
/// The helper once it is enabled; until then, and while the password dialog still has the
/// user's settings to put back, the dialog. The CLI daemon always uses `sudo`.
pub fn system_proxy_backend(&self) -> SystemProxyBackend {
self.backend_for(self.helper_state())
}
fn backend_for(&self, helper: HelperState) -> SystemProxyBackend {
match self.owner {
Owner::App => SystemProxyBackend::AdminPrompt,
Owner::Cli => SystemProxyBackend::Sudo,
// What the dialog saved only it can restore, as the helper never saw it: settings
// for routing it turned on, and settings parked for a service that was missing,
// which its next capture uses if the service is back.
Owner::App if helper == HelperState::Enabled && !self.snapshot_path().exists() => {
SystemProxyBackend::Helper
}
Owner::App => SystemProxyBackend::AdminPrompt,
}
}
/// The helper's registration, as far as this process can use it.
pub fn helper_state(&self) -> HelperState {
match self.owner {
Owner::App => helper::state(),
Owner::Cli => HelperState::Unavailable,
}
}
/// Where the password dialog and `sudo` keep the settings they replaced.
fn snapshot_path(&self) -> PathBuf {
self.data_dir.join(macos::SNAPSHOT_FILE)
}
/// Judged against the running engine's port, or the configured one while it is stopped.
/// Blocks.
pub fn system_proxy_status(&self) -> Result<SystemProxyStatus, String> {
let port = self.port().unwrap_or(self.settings()?.port);
macos::status(port, self.system_proxy_backend())
let helper = self.helper_state();
macos::status(port, self.backend_for(helper), helper)
}
/// Registers the helper, opening System Settings for the user to allow it. Blocks.
pub fn register_helper(&self) -> Result<SystemProxyStatus, String> {
helper::register()?;
self.system_proxy_status()
}
/// Removes the helper, which first puts back the settings it replaced, so the system proxy
/// is off afterwards. Blocks.
pub fn unregister_helper(&self) -> Result<SystemProxyStatus, String> {
let turn = self.system_proxy_turn.lock().map_err(|_| "lock poisoned".to_string())?;
let restores = self.system_proxy_backend() == SystemProxyBackend::Helper;
helper::unregister()?;
if restores {
self.system_proxy_on.store(false, Ordering::SeqCst);
}
drop(turn);
self.system_proxy_status()
}
/// Points this Mac's web traffic at the running engine, or stops, at once, through the
@@ -465,14 +512,15 @@ impl ProxyCtx {
return Ok(());
}
}
macos::set(enabled, port, self.system_proxy_backend())
macos::set(enabled, port, self.system_proxy_backend(), &self.snapshot_path())
}
/// Turns off a system proxy left pointing at one of `ports` by an owner that crashed, so
/// the Mac is not left offline. Leaves it alone when something is serving on the port.
/// Blocks.
/// the Mac is not left offline, putting back the settings it replaced when they were
/// saved. Leaves it alone when something is serving on the port. Blocks.
pub fn reset_stale_system_proxy(&self, ports: &[u16]) -> Result<(), String> {
let mut ports = ports.to_vec();
ports.extend(macos::saved_port(&self.snapshot_path()));
ports.sort_unstable();
ports.dedup();
for port in ports {
@@ -486,7 +534,7 @@ impl ProxyCtx {
}
// Covers disabled services too, and asks for nothing when none point at the port.
debug!("Turning off any stale system proxy on port {port}");
macos::set(false, port, self.system_proxy_backend())?;
macos::set(false, port, self.system_proxy_backend(), &self.snapshot_path())?;
}
Ok(())
}
@@ -863,6 +911,14 @@ pub struct SystemProxySetRequest {
pub enabled: bool,
}
#[derive(Deserialize, TS)]
#[ts(export, export_to = "gen_rpc.ts")]
pub struct HelperRegisterRequest {}
#[derive(Deserialize, TS)]
#[ts(export, export_to = "gen_rpc.ts")]
pub struct HelperUnregisterRequest {}
// -- Handlers --
fn execute_action(ctx: &ProxyCtx, invocation: ActionInvocation) -> Result<bool, RpcError> {
@@ -1096,6 +1152,20 @@ async fn system_proxy_set(
blocking(move || ctx.set_system_proxy(req.enabled)).await
}
async fn helper_register(
ctx: ProxyCtx,
_req: HelperRegisterRequest,
) -> Result<SystemProxyStatus, RpcError> {
blocking(move || ctx.register_helper()).await
}
async fn helper_unregister(
ctx: ProxyCtx,
_req: HelperUnregisterRequest,
) -> Result<SystemProxyStatus, RpcError> {
blocking(move || ctx.unregister_helper()).await
}
async fn blocking<T: Send + 'static>(
f: impl FnOnce() -> Result<T, String> + Send + 'static,
) -> Result<T, RpcError> {
@@ -1362,6 +1432,8 @@ define_rpc! {
filter_body(FilterBodyRequest) -> FilterBodyResponse,
get_flow_body(GetFlowBodyRequest) -> GetFlowBodyResponse,
get_proxy_state(GetProxyStateRequest) -> GetProxyStateResponse,
helper_register(HelperRegisterRequest) -> SystemProxyStatus,
helper_unregister(HelperUnregisterRequest) -> SystemProxyStatus,
list_workspaces(ListWorkspacesRequest) -> ListWorkspacesResponse,
preview_save(PreviewSaveRequest) -> SavePreview,
save_flow(SaveFlowToYaakRequest) -> SavedFlow,
@@ -1380,6 +1452,27 @@ define_rpc! {
mod tests {
use super::*;
#[test]
fn settings_the_password_prompt_parked_keep_it_over_the_helper() {
use yaak_proxy_helper::networksetup::{ProxySetting, ServiceProxy, Snapshot};
let dir = tempfile::tempdir().unwrap();
let (events, _rx) = RpcEventEmitter::new();
let ctx = ProxyCtx::new(dir.path(), events).unwrap();
assert_eq!(ctx.backend_for(HelperState::Enabled), SystemProxyBackend::Helper);
// A restore parked an unplugged adapter's settings, at port 0.
let corp = ProxySetting { enabled: true, server: "corp-proxy".into(), port: 3128 };
let parked = Snapshot {
services: vec![ServiceProxy::new("USB LAN", corp.clone(), corp)],
..Snapshot::default()
};
std::fs::write(ctx.snapshot_path(), serde_json::to_vec(&parked).unwrap()).unwrap();
assert_eq!(macos::saved_port(&ctx.snapshot_path()), None, "routes nothing");
// Only the password prompt's capture would use them when the adapter is back.
assert_eq!(ctx.backend_for(HelperState::Enabled), SystemProxyBackend::AdminPrompt);
assert_eq!(ctx.backend_for(HelperState::NotRegistered), SystemProxyBackend::AdminPrompt);
}
#[test]
fn a_request_is_recorded_by_the_state_when_it_started() {
let mut log = RecordingLog::default();