Skip to content

Make Codex and Claude Code subscriptions go further: a local model router that gives routine agent work to economical models and keeps your strongest model for the hard parts.

fix: preserve subscription proxy policy across service startup and recovery (#40)

澄潭e1ee6bf540fc
diff --git a/contracts/compatibility-support.v1.json b/contracts/compatibility-support.v1.json
index 8c98326a..f572a700 100644
--- a/contracts/compatibility-support.v1.json
+++ b/contracts/compatibility-support.v1.json
@@ -315,6 +315,7 @@
"hiroute.standalone-install/v1",
"hiroute.standalone-protected-input-request/v1",
"hiroute.standalone-protected-input-response/v1",
+ "hiroute.standalone-proxy-environment/v1",
"hiroute.standalone-service-doctor/v1",
"hiroute.standalone-service-logs/v1",
"hiroute.standalone-service-status/v1",
@@ -950,6 +951,19 @@
"crates/daemon/src/control/runtime/agent_connection.rs",
"crates/integrations/src/agents/filesystem_config.rs"
]
+ },
+ {
+ "contract": "hiroute.cpa-owner/v1",
+ "field": "proxy_environment_sha256",
+ "mode": "recovery_read_only",
+ "owner": "cpa-bridge",
+ "reason": "Pre-policy orphan records omit the launch environment fingerprint. Authenticate the exact child and replace it before admission; current writers always record the selected policy.",
+ "removal_condition": "Remove after no retained live orphan or supported recovery state predates proxy-policy recording.",
+ "allowed_paths": [
+ "crates/cpa-bridge/src/owner.rs",
+ "crates/cpa-bridge/src/runtime.rs",
+ "crates/cpa-bridge/src/runtime/tests/proxy_recovery.rs"
+ ]
}
]
}
diff --git a/crates/cli/src/lib.rs b/crates/cli/src/lib.rs
index 30cd91d6..815dd688 100644
--- a/crates/cli/src/lib.rs
+++ b/crates/cli/src/lib.rs
@@ -799,20 +799,6 @@ mod tests {
assert!(!root_help().contains(HIDDEN_AGENT_GRANT_HELPER_VERB_V1));
}
- #[test]
- fn released_control_command_reaches_transport() {
- let execution = execute(["system", "status", "--output", "json"]);
- assert_eq!(execution.exit_code, 6);
- let value: Value = serde_json::from_str(&execution.stdout).unwrap();
- assert_eq!(value["error"]["code"], "DAEMON_UNAVAILABLE");
- assert_eq!(execution.stderr, DAEMON_UNAVAILABLE_HINT);
- assert!(execution.stderr.contains("hiroute service status"));
- assert!(execution.stderr.contains("hiroute service start"));
- assert!(execution.stderr.contains("Desktop"));
- assert!(execution.stderr.contains("隔离实例"));
- assert!(execution.stderr.contains("不会自动启动或重放请求"));
- }
-
#[test]
fn unstaged_planned_command_is_not_callable() {
let execution = execute(["settings", "show", "--output", "json"]);
diff --git a/crates/cli/src/service.rs b/crates/cli/src/service.rs
index 851c4a4b..3814d643 100644
--- a/crates/cli/src/service.rs
+++ b/crates/cli/src/service.rs
@@ -41,6 +41,9 @@ pub(crate) fn status() -> Result<ServiceStatus, ServiceFailure> {
pub(crate) fn start(timeout: Duration) -> Result<ServiceStatus, ServiceFailure> {
let (layout, _) = installed()?;
+ if !manager_active(&layout) {
+ capture_proxy_environment(&layout)?;
+ }
manager_start(&layout)?;
wait_ready(timeout)?;
status()
@@ -55,11 +58,18 @@ pub(crate) fn stop(timeout: Duration) -> Result<ServiceStatus, ServiceFailure> {
pub(crate) fn restart(timeout: Duration) -> Result<ServiceStatus, ServiceFailure> {
let (layout, _) = installed()?;
+ capture_proxy_environment(&layout)?;
manager_restart(&layout)?;
wait_ready(timeout)?;
status()
}
+fn capture_proxy_environment(layout: &StandaloneLayout) -> Result<(), ServiceFailure> {
+ hiroute_host_runtime::ServiceProxyEnvironment::capture(std::env::vars_os())
+ .and_then(|environment| environment.store(&layout.home))
+ .map_err(|_| ServiceFailure::Unavailable)
+}
+
pub(crate) fn set_autostart(enable: bool) -> Result<ServiceStatus, ServiceFailure> {
let (_layout, _) = installed()?;
#[cfg(target_os = "linux")]
@@ -201,10 +211,14 @@ pub(crate) fn foreground_run() -> u8 {
#[cfg(unix)]
{
use std::os::unix::process::CommandExt;
- let Ok((_, record)) = installed() else {
+ let Ok((layout, record)) = installed() else {
eprintln!("standalone installation is unavailable");
return 6;
};
+ if capture_proxy_environment(&layout).is_err() {
+ eprintln!("standalone proxy environment is unavailable");
+ return 6;
+ }
let daemon = record.install_root.join("hirouted");
if !executable(&daemon) {
eprintln!("standalone daemon is unavailable");
@@ -320,7 +334,7 @@ fn service_definition(layout: &StandaloneLayout) -> PathBuf {
#[cfg(target_os = "macos")]
fn manager_start(layout: &StandaloneLayout) -> Result<(), ServiceFailure> {
let domain = format!("gui/{}", nix::unistd::geteuid().as_raw());
- if !manager_active(layout) {
+ if !manager_loaded(layout) {
let template = launchd_template(layout);
run_checked(Command::new("/bin/launchctl").args([
"bootstrap",
@@ -337,7 +351,7 @@ fn manager_start(layout: &StandaloneLayout) -> Result<(), ServiceFailure> {
#[cfg(target_os = "macos")]
fn manager_stop(_layout: &StandaloneLayout) -> Result<(), ServiceFailure> {
- if !manager_active(_layout) {
+ if !manager_loaded(_layout) {
return Ok(());
}
let service = format!("gui/{}/{}", nix::unistd::geteuid().as_raw(), SERVICE_LABEL);
@@ -351,6 +365,20 @@ fn manager_restart(layout: &StandaloneLayout) -> Result<(), ServiceFailure> {
#[cfg(target_os = "macos")]
fn manager_active(_layout: &StandaloneLayout) -> bool {
+ Command::new("/bin/launchctl")
+ .args([
+ "print",
+ &format!("gui/{}/{}", nix::unistd::geteuid().as_raw(), SERVICE_LABEL),
+ ])
+ .stderr(std::process::Stdio::null())
+ .output()
+ .is_ok_and(|output| launchd_process_running(&output))
+}
+
+// A registered RunAtLoad=false job is loaded even when it has no process.
+// Keep registration separate from the activity check used to capture proxy policy.
+#[cfg(target_os = "macos")]
+fn manager_loaded(_layout: &StandaloneLayout) -> bool {
Command::new("/bin/launchctl")
.args([
"print",
@@ -362,6 +390,16 @@ fn manager_active(_layout: &StandaloneLayout) -> bool {
.is_ok_and(|status| status.success())
}
+#[cfg(any(target_os = "macos", test))]
+fn launchd_process_running(output: &Output) -> bool {
+ output.status.success()
+ && String::from_utf8_lossy(&output.stdout).lines().any(|line| {
+ line.strip_prefix("\tpid = ")
+ .and_then(|pid| pid.parse::<u32>().ok())
+ .is_some_and(|pid| pid > 0)
+ })
+}
+
#[cfg(target_os = "macos")]
fn autostart_status(layout: &StandaloneLayout) -> Result<bool, ServiceFailure> {
let target = layout
@@ -472,6 +510,26 @@ fn check(checks: &mut Vec<serde_json::Value>, healthy: &mut bool, name: &str, ok
mod tests {
use super::*;
+ #[test]
+ fn loaded_launchd_job_without_process_is_inactive_for_proxy_capture() {
+ for stdout in [
+ "gui/501/ai.hiroute.cli = {\n\tstate = not running\n}\n",
+ "gui/501/ai.hiroute.cli = {\n\tstate = exited\n\tenvironment = {\n\t\tpid = 42\n\t}\n}\n",
+ "gui/501/ai.hiroute.cli = {\n\tpid = 0\n}\n",
+ ] {
+ assert!(!launchd_process_running(&Output {
+ status: success_status(),
+ stdout: stdout.as_bytes().to_vec(),
+ stderr: Vec::new(),
+ }));
+ }
+ assert!(launchd_process_running(&Output {
+ status: success_status(),
+ stdout: b"gui/501/ai.hiroute.cli = {\n\tstate = running\n\tpid = 42\n}\n".to_vec(),
+ stderr: Vec::new(),
+ }));
+ }
+
#[test]
fn log_output_is_bounded_from_the_tail() {
let output = Output {
diff --git a/crates/cli/tests/service_proxy.rs b/crates/cli/tests/service_proxy.rs
new file mode 100644
index 00000000..a02cdd36
--- /dev/null
+++ b/crates/cli/tests/service_proxy.rs
@@ -0,0 +1,154 @@
+#![cfg(target_os = "linux")]
+
+use std::fs;
+use std::os::unix::fs::PermissionsExt;
+use std::process::Command;
+
+fn private_home() -> tempfile::TempDir {
+ tempfile::Builder::new()
+ .permissions(fs::Permissions::from_mode(0o700))
+ .tempdir()
+ .unwrap()
+}
+
+fn snapshot_path(home: &std::path::Path) -> std::path::PathBuf {
+ home.join(".local/share/hiroute/service/proxy-environment.json")
+}
+
+fn variables(home: &std::path::Path) -> serde_json::Map<String, serde_json::Value> {
+ let value: serde_json::Value =
+ serde_json::from_slice(&fs::read(snapshot_path(home)).unwrap()).unwrap();
+ assert_eq!(value["schema"], "hiroute.standalone-proxy-environment/v1");
+ value["variables"].as_object().unwrap().clone()
+}
+
+fn executable(path: &std::path::Path, contents: &str) {
+ fs::write(path, contents).unwrap();
+ fs::set_permissions(path, fs::Permissions::from_mode(0o700)).unwrap();
+}
+
+fn installation(home: &std::path::Path) -> Command {
+ let directory = home.join(".local/share/hiroute");
+ fs::create_dir_all(&directory).unwrap();
+ fs::create_dir_all(home.join("bin")).unwrap();
+ for parent in [".local", ".local/share", ".local/share/hiroute"] {
+ fs::set_permissions(home.join(parent), fs::Permissions::from_mode(0o700)).unwrap();
+ }
+ fs::write(
+ directory.join("standalone.json"),
+ serde_json::to_vec(&serde_json::json!({
+ "schema_version": "hiroute.standalone-install/v1", "version":"0.1.0",
+ "target":"x86_64-unknown-linux-gnu", "install_root":home.join("bin"),
+ "service_definition":home.join("unit")
+ }))
+ .unwrap(),
+ )
+ .unwrap();
+ fs::set_permissions(
+ directory.join("standalone.json"),
+ fs::Permissions::from_mode(0o600),
+ )
+ .unwrap();
+ executable(
+ &home.join("bin/systemctl"),
+ r#"#!/bin/sh
+if [ "$2" = is-active ]; then test "$TEST_SERVICE_ACTIVE" = 1; exit $?; fi
+printf '%s\n' "$@" > "$HOME/manager-call"
+test -f "$HOME/.local/share/hiroute/service/proxy-environment.json" || exit 89
+# The fixture deliberately refuses startup. Readiness must not be fabricated.
+exit 90
+"#,
+ );
+ let mut command = Command::new(env!("CARGO_BIN_EXE_hiroute"));
+ command
+ .env_clear()
+ .env("HOME", home)
+ .env("PATH", home.join("bin"))
+ .env("HTTPS_PROXY", "http://user:[email protected]:1187")
+ .env("NO_PROXY", "localhost,127.0.0.1")
+ .env("OPENAI_API_KEY", "private-provider-key");
+ command
+}
+
+#[test]
+fn service_start_restart_capture_before_manager_without_forwarding_values_in_arguments() {
+ for verb in ["start", "restart"] {
+ let home = private_home();
+ let result = installation(home.path())
+ .args(["service", verb, "--output", "json"])
+ .output()
+ .unwrap();
+ assert!(
+ !result.status.success(),
+ "refused service startup must remain unavailable"
+ );
+ let variables = variables(home.path());
+ assert_eq!(variables.len(), 2);
+ assert_eq!(
+ variables.get("HTTPS_PROXY").unwrap(),
+ "http://user:[email protected]:1187"
+ );
+ for bytes in [
+ &result.stdout,
+ &result.stderr,
+ &fs::read(home.path().join("manager-call")).unwrap(),
+ ] {
+ let text = String::from_utf8_lossy(bytes);
+ assert!(!text.contains("private-proxy"));
+ assert!(!text.contains("private-provider-key"));
+ }
+ }
+}
+
+#[test]
+fn active_start_keeps_policy_and_invalid_capture_never_calls_manager_start() {
+ let home = private_home();
+ let _ = installation(home.path());
+ fs::create_dir(snapshot_path(home.path()).parent().unwrap()).unwrap();
+ fs::set_permissions(
+ snapshot_path(home.path()).parent().unwrap(),
+ fs::Permissions::from_mode(0o700),
+ )
+ .unwrap();
+ fs::write(
+ snapshot_path(home.path()),
+ br#"{"schema":"hiroute.standalone-proxy-environment/v1","variables":{}}"#,
+ )
+ .unwrap();
+ fs::set_permissions(
+ snapshot_path(home.path()),
+ fs::Permissions::from_mode(0o600),
+ )
+ .unwrap();
+ let result = installation(home.path())
+ .env("TEST_SERVICE_ACTIVE", "1")
+ .args(["service", "start", "--output", "json"])
+ .output()
+ .unwrap();
+ assert!(!result.status.success());
+ assert_eq!(variables(home.path()).len(), 0);
+ fs::remove_file(home.path().join("manager-call")).unwrap();
+ let result = installation(home.path())
+ .env("HTTPS_PROXY", "http://proxy\nprivate-proxy")
+ .args(["service", "restart", "--output", "json"])
+ .output()
+ .unwrap();
+ assert!(!result.status.success());
+ assert!(!home.path().join("manager-call").exists());
+ assert!(!String::from_utf8_lossy(&result.stdout).contains("private-proxy"));
+}
+
+#[test]
+fn foreground_run_captures_before_exec() {
+ let home = private_home();
+ let mut command = installation(home.path());
+ executable(
+ &home.path().join("bin/hirouted"),
+ r#"#!/bin/sh
+test -f "$HOME/.local/share/hiroute/service/proxy-environment.json" || exit 89
+test "$1" = --role && test "$2" = all && test "$3" = --standalone
+"#,
+ );
+ assert!(command.args(["service", "run"]).status().unwrap().success());
+ assert_eq!(variables(home.path()).len(), 2);
+}
diff --git a/crates/cli/tests/transport_unavailable.rs b/crates/cli/tests/transport_unavailable.rs
new file mode 100644
index 00000000..9b5306d0
--- /dev/null
+++ b/crates/cli/tests/transport_unavailable.rs
@@ -0,0 +1,25 @@
+use std::process::Command;
+
+#[test]
+fn released_control_command_reaches_isolated_transport() {
+ let runtime = tempfile::tempdir().unwrap();
+ let output = Command::new(env!("CARGO_BIN_EXE_hiroute"))
+ .env("HOME", runtime.path())
+ .env("HIROUTE_RUNTIME_DIR", runtime.path())
+ .args(["system", "status", "--output", "json"])
+ .output()
+ .unwrap();
+ assert_eq!(output.status.code(), Some(6));
+ let value: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
+ assert_eq!(value["error"]["code"], "DAEMON_UNAVAILABLE");
+ let stderr = String::from_utf8(output.stderr).unwrap();
+ for hint in [
+ "hiroute service status",
+ "hiroute service start",
+ "Desktop",
+ "隔离实例",
+ "不会自动启动或重放请求",
+ ] {
+ assert!(stderr.contains(hint));
+ }
+}
diff --git a/crates/cpa-bridge/src/lib.rs b/crates/cpa-bridge/src/lib.rs
index cc1ba141..100935a1 100644
--- a/crates/cpa-bridge/src/lib.rs
+++ b/crates/cpa-bridge/src/lib.rs
@@ -15,6 +15,7 @@ mod errors;
mod http;
mod owner;
mod process;
+mod proxy_environment;
mod runtime;
mod state;
mod subscription;
diff --git a/crates/cpa-bridge/src/owner.rs b/crates/cpa-bridge/src/owner.rs
index 6ec7f0a3..7b95801b 100644
--- a/crates/cpa-bridge/src/owner.rs
+++ b/crates/cpa-bridge/src/owner.rs
@@ -24,6 +24,9 @@ pub(crate) struct OwnerRecord {
pub(crate) address: SocketAddr,
pub(crate) binary_version: String,
pub(crate) binary_sha256_hex: String,
+ /// Recovery-only omission: authenticate and replace pre-policy orphan processes.
+ #[serde(default)]
+ pub(crate) proxy_environment_sha256: Option<String>,
}
impl OwnerRecord {
@@ -41,6 +44,7 @@ impl OwnerRecord {
address: "127.0.0.1:1".parse().expect("literal address"),
binary_version: version,
binary_sha256_hex: digest,
+ proxy_environment_sha256: None,
};
value.validate()?;
Ok(value)
@@ -69,6 +73,12 @@ impl OwnerRecord {
|| self.binary_version.is_empty()
|| self.binary_version.len() > 64
|| self.binary_sha256_hex.len() != 64
+ || self
+ .proxy_environment_sha256
+ .as_ref()
+ .is_some_and(|digest| {
+ digest.len() != 64 || !digest.bytes().all(|byte| byte.is_ascii_hexdigit())
+ })
|| !self
.binary_sha256_hex
.bytes()
diff --git a/crates/cpa-bridge/src/process.rs b/crates/cpa-bridge/src/process.rs
index 746f139e..d2e45e77 100644
--- a/crates/cpa-bridge/src/process.rs
+++ b/crates/cpa-bridge/src/process.rs
@@ -15,6 +15,7 @@ pub struct CpaLaunch {
pub config_path: PathBuf,
pub work_dir: PathBuf,
pub(crate) management_password: Arc<crate::config::SecretText>,
+ pub(crate) proxy_environment: crate::proxy_environment::ProxyEnvironment,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
@@ -38,25 +39,6 @@ pub trait CpaProcessBackend: Send + Sync {
fn pid_is_running(&self, pid: u32) -> Result<bool, CpaProcessError>;
}
-// Keep private upstream credentials and shell execution hooks out of the child.
-fn proxy_environment(
- vars: impl IntoIterator<Item = (std::ffi::OsString, std::ffi::OsString)>,
-) -> impl Iterator<Item = (std::ffi::OsString, std::ffi::OsString)> {
- vars.into_iter().filter(|(key, _)| {
- matches!(
- key.to_str(),
- Some(
- "HTTP_PROXY"
- | "HTTPS_PROXY"
- | "NO_PROXY"
- | "http_proxy"
- | "https_proxy"
- | "no_proxy"
- )
- )
- })
-}
-
#[derive(Clone, Copy, Debug, Default)]
pub struct StdCpaProcessBackend;
@@ -72,7 +54,7 @@ impl CpaProcessBackend for StdCpaProcessBackend {
.arg("--local-model")
.arg("--local-password-stdin")
.env_clear()
- .envs(proxy_environment(std::env::vars_os()))
+ .envs(launch.proxy_environment.iter())
.current_dir(&launch.work_dir)
.stdin(Stdio::piped())
.stdout(Stdio::null())
diff --git a/crates/cpa-bridge/src/process_tests.rs b/crates/cpa-bridge/src/process_tests.rs
index b526f9d2..9bcbe12e 100644
--- a/crates/cpa-bridge/src/process_tests.rs
+++ b/crates/cpa-bridge/src/process_tests.rs
@@ -13,6 +13,9 @@ fn bootstrap_secret_uses_a_closed_pipe_and_never_argv_or_environment() {
format!(
r#"#!/bin/sh
test -z "$MANAGEMENT_PASSWORD" || exit 10
+test -z "$BASH_ENV" || exit 14
+test "$HTTPS_PROXY" = 'http://user:[email protected]:1187' || exit 15
+test "$NO_PROXY" = 'localhost,127.0.0.1' || exit 16
test "$4" = '--local-password-stdin' || exit 11
test "$#" = 4 || exit 12
value=$(cat)
@@ -34,8 +37,17 @@ printf 'pipe-eof-ok' > result
management_password: Arc::new(
crate::config::SecretText::from_owned(secret.into()).unwrap(),
),
+ proxy_environment: crate::proxy_environment::ProxyEnvironment::capture([
+ (
+ "HTTPS_PROXY".into(),
+ "http://user:[email protected]:1187".into(),
+ ),
+ ("NO_PROXY".into(), "localhost,127.0.0.1".into()),
+ ("BASH_ENV".into(), "/must-not-run".into()),
+ ]),
};
assert!(!format!("{launch:?}").contains(secret));
+ assert!(!format!("{launch:?}").contains("proxy-secret"));
// An executable script on the validation workbench can briefly report ETXTBSY
// just after the fixture is written. Retry only that fixture/filesystem race;
// every other launch error must still fail this pipe-contract regression.
@@ -82,11 +94,13 @@ fn proxy_environment_preserves_bypass_without_forwarding_credentials_or_hooks()
"BASH_ENV",
"HOME",
];
- let selected: Vec<_> =
- proxy_environment(vars.map(|key| (key.into(), "sentinel".into()))).collect();
+ let environment = crate::proxy_environment::ProxyEnvironment::capture(
+ vars.map(|key| (key.into(), "sentinel".into())),
+ );
+ let selected: Vec<_> = environment.iter().collect();
assert_eq!(selected.len(), 6);
- for (i, (key, value)) in selected.iter().enumerate() {
- assert_eq!(key, vars[i]);
+ for (key, value) in selected {
+ assert!(vars[..6].contains(&key.to_str().unwrap()));
assert_eq!(value, "sentinel");
}
}
diff --git a/crates/cpa-bridge/src/proxy_environment.rs b/crates/cpa-bridge/src/proxy_environment.rs
new file mode 100644
index 00000000..0a3403c9
--- /dev/null
+++ b/crates/cpa-bridge/src/proxy_environment.rs
@@ -0,0 +1,52 @@
+use std::collections::BTreeMap;
+use std::ffi::OsString;
+
+use sha2::{Digest, Sha256};
+
+/// Captured once per runtime. Debug never exposes credentials in proxy URLs.
+#[derive(Clone)]
+pub(crate) struct ProxyEnvironment(BTreeMap<OsString, OsString>);
+
+impl ProxyEnvironment {
+ pub(crate) fn capture(values: impl IntoIterator<Item = (OsString, OsString)>) -> Self {
+ Self(
+ values
+ .into_iter()
+ .filter(|(key, _)| {
+ matches!(
+ key.to_str(),
+ Some(
+ "HTTP_PROXY"
+ | "HTTPS_PROXY"
+ | "NO_PROXY"
+ | "http_proxy"
+ | "https_proxy"
+ | "no_proxy"
+ )
+ )
+ })
+ .collect(),
+ )
+ }
+
+ pub(crate) fn iter(&self) -> impl Iterator<Item = (&OsString, &OsString)> {
+ self.0.iter()
+ }
+
+ pub(crate) fn digest(&self) -> String {
+ let mut digest = Sha256::new();
+ for (key, value) in &self.0 {
+ for bytes in [key.as_encoded_bytes(), value.as_encoded_bytes()] {
+ digest.update((bytes.len() as u64).to_le_bytes());
+ digest.update(bytes);
+ }
+ }
+ format!("{:x}", digest.finalize())
+ }
+}
+
+impl std::fmt::Debug for ProxyEnvironment {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.write_str("ProxyEnvironment([REDACTED])")
+ }
+}
diff --git a/crates/cpa-bridge/src/runtime.rs b/crates/cpa-bridge/src/runtime.rs
index f9d46d64..7c1d510f 100644
--- a/crates/cpa-bridge/src/runtime.rs
+++ b/crates/cpa-bridge/src/runtime.rs
@@ -79,6 +79,7 @@ pub struct ManagedCpaRuntime {
pub(crate) epochs: Arc<RuntimeEpochState>,
/// Lifecycle diagnostics; a no-op port keeps library and test hosts unchanged.
diagnostics: DiagnosticsPort,
+ proxy_environment: crate::proxy_environment::ProxyEnvironment,
}
/// Read-only discovery boundary exposed to Local Control. The returned values contain only
@@ -197,6 +198,9 @@ impl ManagedCpaRuntime {
inner: Mutex::new(RuntimeInner::default()),
epochs: Arc::new(RuntimeEpochState::new()),
diagnostics: DiagnosticsPort::default(),
+ proxy_environment: crate::proxy_environment::ProxyEnvironment::capture(
+ std::env::vars_os(),
+ ),
})
}
@@ -206,6 +210,16 @@ impl ManagedCpaRuntime {
self
}
+ /// Override only the CPA child's proxy environment with a host-owned snapshot.
+ /// This must be configured before the runtime starts.
+ pub fn with_proxy_environment(
+ mut self,
+ values: impl IntoIterator<Item = (std::ffi::OsString, std::ffi::OsString)>,
+ ) -> Self {
+ self.proxy_environment = crate::proxy_environment::ProxyEnvironment::capture(values);
+ self
+ }
+
fn emit(&self, event: DiagnosticEvent) {
self.diagnostics.handle().try_emit(event);
}
@@ -301,13 +315,14 @@ impl ManagedCpaRuntime {
);
let layout = self.prepare_layout()?;
let nonce = SecretText::generate()?.expose().to_owned();
- let fresh_record = OwnerRecord::claim(
+ let mut fresh_record = OwnerRecord::claim(
std::process::id(),
nonce.clone(),
artifact.version().to_string(),
artifact.sha256_hex().to_owned(),
)
.map_err(|_| CpaLifecycleError::OwnerState)?;
+ fresh_record.proxy_environment_sha256 = Some(self.proxy_environment.digest());
let claim = OwnerLease::acquire(&layout.lock_dir, &fresh_record, nonce.clone())
.map_err(|_| CpaLifecycleError::OwnerState)?;
let mut live = match claim {
@@ -329,8 +344,7 @@ impl ManagedCpaRuntime {
let lease =
OwnerLease::reclaim_stale(&layout.lock_dir, &record, &transferred, nonce)
.map_err(|_| CpaLifecycleError::OwnerState)?;
- // Adoption attaches to a live process: it never spawns, so it never
- // reports a spawn step.
+ // Authenticate the orphan before adopting or replacing its launch policy.
self.adopt_orphan(
lease,
record,
@@ -604,13 +618,32 @@ impl ManagedCpaRuntime {
Ok((transferred, secrets, process, accounts, auth_lease))
})();
match attempt {
- Ok((transferred, secrets, process, accounts, auth_lease)) => {
+ Ok((mut transferred, secrets, mut process, accounts, auth_lease)) => {
self.emit_stage(
CpaStageKind::ReadyWait,
CpaStageOutcome::Completed,
ready_started.elapsed().as_millis() as u64,
generation,
);
+ let digest = self.proxy_environment.digest();
+ if transferred.proxy_environment_sha256.as_deref() != Some(digest.as_str()) {
+ // The management capability has authenticated this exact orphan twice.
+ // Never serve through an old/unknown proxy policy after owner recovery.
+ if let Err(error) = process.shutdown(self.spec.shutdown_timeout) {
+ let _ = lease.restore_stale(&stale_record);
+ return Err(error.into());
+ }
+ drop(auth_lease);
+ transferred.proxy_environment_sha256 = Some(digest);
+ return self.start_fresh(
+ lease,
+ transferred,
+ artifact,
+ layout,
+ expected,
+ generation,
+ );
+ }
Ok(LiveRuntime {
lease,
auth_lease: Some(auth_lease),
@@ -653,6 +686,7 @@ impl ManagedCpaRuntime {
config_path: layout.config_path.clone(),
work_dir: layout.work_dir.clone(),
management_password: secrets.management.clone(),
+ proxy_environment: self.proxy_environment.clone(),
})
.map_err(CpaLifecycleError::from)
}
diff --git a/crates/cpa-bridge/src/runtime/tests.rs b/crates/cpa-bridge/src/runtime/tests.rs
index 2a279952..5cf1db77 100644
--- a/crates/cpa-bridge/src/runtime/tests.rs
+++ b/crates/cpa-bridge/src/runtime/tests.rs
@@ -49,6 +49,8 @@ const VERSION: &str = crate::MANAGED_CPA_ARTIFACT_VERSION;
#[path = "tests/borrowed_stock.rs"]
mod borrowed_stock;
+#[path = "tests/proxy_recovery.rs"]
+mod proxy_recovery;
#[path = "tests/routing_batch.rs"]
mod routing_batch;
@@ -67,6 +69,7 @@ struct FakeBackend {
spawn_count: AtomicUsize,
attach_count: AtomicUsize,
processes: Mutex<BTreeMap<u32, Arc<FakeProcess>>>,
+ proxy_environments: Mutex<Vec<crate::proxy_environment::ProxyEnvironment>>,
}
#[derive(Default)]
@@ -103,6 +106,9 @@ impl FakeBackend {
impl CpaProcessBackend for FakeBackend {
fn spawn(&self, launch: &CpaLaunch) -> Result<Box<dyn CpaProcessHandle>, CpaProcessError> {
+ self.proxy_environments
+ .lock()
+ .push(launch.proxy_environment.clone());
let bytes = std::fs::read(&launch.config_path).map_err(CpaProcessError::Spawn)?;
CpaManagedConfigContract::validate_rendered(&bytes)
.map_err(|_| CpaProcessError::InvalidLaunch)?;
diff --git a/crates/cpa-bridge/src/runtime/tests/proxy_recovery.rs b/crates/cpa-bridge/src/runtime/tests/proxy_recovery.rs
new file mode 100644
index 00000000..1d70f73f
--- /dev/null
+++ b/crates/cpa-bridge/src/runtime/tests/proxy_recovery.rs
@@ -0,0 +1,59 @@
+use super::*;
+
+#[test]
+fn changed_or_unrecorded_proxy_policy_replaces_only_an_authenticated_orphan() {
+ for legacy in [false, true] {
+ let root = tempfile::tempdir().unwrap();
+ let backend = Arc::new(FakeBackend::default());
+ let control = Arc::new(FakeControl::default());
+ let first = fixture_runtime(&root, backend.clone(), control.clone(), 2)
+ .with_proxy_environment([("HTTPS_PROXY".into(), "http://old-proxy:1187".into())]);
+ let CpaHealth::Ready { pid, .. } = first.start().unwrap() else {
+ panic!("not ready");
+ };
+ let owner_path = root.path().join("state/fixture-cpa/owner.lock/owner.json");
+ let mut owner: serde_json::Value =
+ serde_json::from_slice(&std::fs::read(&owner_path).unwrap()).unwrap();
+ owner["owner_pid"] = json!(u32::MAX - 1);
+ if legacy {
+ owner
+ .as_object_mut()
+ .unwrap()
+ .remove("proxy_environment_sha256");
+ }
+ private_atomic_write(&owner_path, &serde_json::to_vec(&owner).unwrap()).unwrap();
+ drop(first.inner.lock().live.as_mut().unwrap().auth_lease.take());
+ std::mem::forget(first);
+
+ // Empty is intentional: the shell removed all proxy variables.
+ let second =
+ fixture_runtime(&root, backend.clone(), control.clone(), 2).with_proxy_environment([]);
+ control.set_fail_probes(true);
+ assert!(matches!(
+ second.start(),
+ Err(CpaLifecycleError::ControlUnavailable)
+ ));
+ assert!(backend.pid_is_running(pid).unwrap());
+ assert_eq!(backend.spawn_count(), 1);
+ assert_eq!(backend.attach_count(), 0);
+
+ control.set_fail_probes(false);
+ let CpaHealth::Ready {
+ pid: replacement,
+ adopted,
+ ..
+ } = second.start().unwrap()
+ else {
+ panic!("not ready");
+ };
+ assert_ne!(pid, replacement);
+ assert!(!adopted);
+ assert!(!backend.pid_is_running(pid).unwrap());
+ assert_eq!(backend.attach_count(), 1);
+ assert_eq!(backend.spawn_count(), 2);
+ let environments = backend.proxy_environments.lock();
+ assert_eq!(environments[0].iter().count(), 1);
+ assert_eq!(environments[1].iter().count(), 0);
+ second.shutdown().unwrap();
+ }
+}
diff --git a/crates/daemon/src/control/bin.rs b/crates/daemon/src/control/bin.rs
index 2575fd29..f1d1a777 100644
--- a/crates/daemon/src/control/bin.rs
+++ b/crates/daemon/src/control/bin.rs
@@ -147,6 +147,7 @@ fn diagnostics_elapsed_ms(diagnostics: &DiagnosticRuntime) -> u64 {
fn classify_role_all_error(error: &RoleAllError) -> StartupFailureCode {
match error {
RoleAllError::InvalidConfiguration => StartupFailureCode::InvalidConfiguration,
+ RoleAllError::StandaloneProxyUnavailable => StartupFailureCode::DependencyUnavailable,
RoleAllError::JoinTimeout(_) => StartupFailureCode::Internal,
RoleAllError::Component(component, detail) => match *component {
"Storage" if detail.starts_with("UPGRADE_SOURCE_UNSUPPORTED") => {
diff --git a/crates/daemon/src/role_all.rs b/crates/daemon/src/role_all.rs
index 6eeb173f..7bbe64e0 100644
--- a/crates/daemon/src/role_all.rs
+++ b/crates/daemon/src/role_all.rs
@@ -286,6 +286,16 @@ pub fn start_role_all(config: RoleAllConfig) -> Result<RoleAllHandle, RoleAllErr
.stage_end(StartupStage::ArtifactValidate, StageOutcome::Completed);
cpa
}
+ Err(RoleAllError::StandaloneProxyUnavailable) => {
+ // Invalid proxy state disables subscription access, not unrelated control/API work.
+ config.diagnostics.stage_end(
+ StartupStage::ArtifactValidate,
+ StageOutcome::Failed {
+ code: StartupFailureCode::DependencyUnavailable,
+ },
+ );
+ None
+ }
Err(error) => {
config.diagnostics.stage_end(
StartupStage::ArtifactValidate,
@@ -553,16 +563,23 @@ fn start_cpa(
shutdown_timeout: Duration::from_secs(5),
restart_policy: RestartPolicy::default(),
};
- let runtime = Arc::new(
- ManagedCpaRuntime::new(
- spec,
- Arc::new(catalog),
- Arc::new(PinnedCpaBinaryLocator::new(artifact)),
- )
- .map_err(|error| RoleAllError::Component("CPA", error.to_string()))?
- .with_diagnostics(config.diagnostics.clone()),
- );
- Ok(runtime)
+ let mut runtime = ManagedCpaRuntime::new(
+ spec,
+ Arc::new(catalog),
+ Arc::new(PinnedCpaBinaryLocator::new(artifact)),
+ )
+ .map_err(|error| RoleAllError::Component("CPA", error.to_string()))?
+ .with_diagnostics(config.diagnostics.clone());
+ if config.released_commands_only {
+ let layout = hiroute_host_runtime::StandaloneLayout::from_environment()
+ .map_err(|_| RoleAllError::InvalidConfiguration)?;
+ if let Some(environment) = hiroute_host_runtime::ServiceProxyEnvironment::load(&layout.home)
+ .map_err(|_| RoleAllError::StandaloneProxyUnavailable)?
+ {
+ runtime = runtime.with_proxy_environment(environment.variables());
+ }
+ }
+ Ok(Arc::new(runtime))
}
fn selected_codex_auth() -> Result<PathBuf, RoleAllError> {
@@ -623,6 +640,8 @@ impl CpaDownstreamCredentialPort for RoleAllCpaCredentials {
#[derive(Clone, Debug, thiserror::Error, Eq, PartialEq)]
pub enum RoleAllError {
+ #[error("standalone subscription proxy configuration is unavailable")]
+ StandaloneProxyUnavailable,
#[error("role=all configuration is invalid")]
InvalidConfiguration,
#[error("{0} component failed: {1}")]
diff --git a/crates/host-runtime/src/lib.rs b/crates/host-runtime/src/lib.rs
index 225497e5..956a12b9 100644
--- a/crates/host-runtime/src/lib.rs
+++ b/crates/host-runtime/src/lib.rs
@@ -9,12 +9,14 @@
mod desktop_package;
mod gateway_listener;
mod releases;
+mod service_proxy;
mod standalone;
mod upgrade;
pub use desktop_package::*;
pub use gateway_listener::*;
pub use releases::*;
+pub use service_proxy::*;
pub use standalone::*;
pub use upgrade::*;
diff --git a/crates/host-runtime/src/service_proxy.rs b/crates/host-runtime/src/service_proxy.rs
new file mode 100644
index 00000000..29594f84
--- /dev/null
+++ b/crates/host-runtime/src/service_proxy.rs
@@ -0,0 +1,204 @@
+//! Private handoff from the standalone CLI to its independently launched service.
+use std::collections::BTreeMap;
+use std::ffi::OsString;
+use std::fs::{self, File, OpenOptions};
+use std::io::{Read, Write};
+use std::path::{Path, PathBuf};
+
+use serde::{Deserialize, Serialize};
+use thiserror::Error;
+
+const SCHEMA: &str = "hiroute.standalone-proxy-environment/v1";
+const MAX_BYTES: u64 = 16 * 1024;
+const KEYS: [&str; 6] = [
+ "HTTP_PROXY",
+ "HTTPS_PROXY",
+ "NO_PROXY",
+ "http_proxy",
+ "https_proxy",
+ "no_proxy",
+];
+
+#[derive(Clone, Deserialize, Serialize)]
+#[serde(deny_unknown_fields)]
+pub struct ServiceProxyEnvironment {
+ schema: String,
+ variables: BTreeMap<String, String>,
+}
+
+impl std::fmt::Debug for ServiceProxyEnvironment {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.write_str("ServiceProxyEnvironment([REDACTED])")
+ }
+}
+
+#[derive(Clone, Copy, Debug, Error)]
+#[error("STANDALONE_PROXY_ENVIRONMENT_INVALID")]
+pub struct ServiceProxyError;
+
+impl ServiceProxyEnvironment {
+ pub fn capture(
+ values: impl IntoIterator<Item = (OsString, OsString)>,
+ ) -> Result<Self, ServiceProxyError> {
+ let mut variables = BTreeMap::new();
+ for (key, value) in values {
+ if let Some(key) = key.to_str().filter(|key| KEYS.contains(key)) {
+ variables.insert(
+ key.to_owned(),
+ value.into_string().map_err(|_| ServiceProxyError)?,
+ );
+ }
+ }
+ let result = Self {
+ schema: SCHEMA.into(),
+ variables,
+ };
+ result.validate()?;
+ Ok(result)
+ }
+
+ pub fn variables(&self) -> impl Iterator<Item = (OsString, OsString)> + '_ {
+ self.variables
+ .iter()
+ .map(|(key, value)| (key.into(), value.into()))
+ }
+
+ fn validate(&self) -> Result<(), ServiceProxyError> {
+ if self.schema != SCHEMA
+ || self.variables.iter().any(|(key, value)| {
+ !KEYS.contains(&key.as_str()) || value.contains(['\0', '\r', '\n'])
+ })
+ || serde_json::to_vec(self)
+ .map_err(|_| ServiceProxyError)?
+ .len() as u64
+ > MAX_BYTES
+ {
+ return Err(ServiceProxyError);
+ }
+ Ok(())
+ }
+
+ /// This lives beside the fixed installation marker, independent of shell XDG overrides.
+ pub fn path(home: &Path) -> PathBuf {
+ home.join(".local/share/hiroute/service/proxy-environment.json")
+ }
+
+ pub fn store(&self, home: &Path) -> Result<(), ServiceProxyError> {
+ self.validate()?;
+ let path = Self::path(home);
+ validate_directories(home, true)?;
+ if let Some(file) = open_private(&path)? {
+ drop(file);
+ }
+ let mut random = [0u8; 16];
+ getrandom::fill(&mut random).map_err(|_| ServiceProxyError)?;
+ let suffix: String = random.iter().map(|byte| format!("{byte:02x}")).collect();
+ let temporary = path.with_file_name(format!(".proxy-{suffix}.tmp"));
+ let result = (|| {
+ let mut options = OpenOptions::new();
+ options.write(true).create_new(true);
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::OpenOptionsExt;
+ options.mode(0o600).custom_flags(nix::libc::O_NOFOLLOW);
+ }
+ let mut file = options.open(&temporary).map_err(|_| ServiceProxyError)?;
+ file.write_all(&serde_json::to_vec(self).map_err(|_| ServiceProxyError)?)
+ .and_then(|()| file.sync_all())
+ .map_err(|_| ServiceProxyError)?;
+ fs::rename(&temporary, &path).map_err(|_| ServiceProxyError)
+ })();
+ let _ = fs::remove_file(&temporary);
+ result
+ }
+
+ pub fn load(home: &Path) -> Result<Option<Self>, ServiceProxyError> {
+ if !validate_directories(home, false)? {
+ return Ok(None);
+ }
+ let Some(file) = open_private(&Self::path(home))? else {
+ return Ok(None);
+ };
+ let mut bytes = Vec::new();
+ file.take(MAX_BYTES + 1)
+ .read_to_end(&mut bytes)
+ .map_err(|_| ServiceProxyError)?;
+ if bytes.len() as u64 > MAX_BYTES {
+ return Err(ServiceProxyError);
+ }
+ let result: Self = serde_json::from_slice(&bytes).map_err(|_| ServiceProxyError)?;
+ result.validate()?;
+ Ok(Some(result))
+ }
+}
+
+fn validate_directories(home: &Path, create: bool) -> Result<bool, ServiceProxyError> {
+ if !home.is_absolute() {
+ return Err(ServiceProxyError);
+ }
+ let mut path = home.to_path_buf();
+ for component in ["", ".local", "share", "hiroute", "service"] {
+ path.push(component);
+ match fs::symlink_metadata(&path) {
+ Ok(metadata) => {
+ if !metadata.is_dir() {
+ return Err(ServiceProxyError);
+ }
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::{MetadataExt, PermissionsExt};
+ if metadata.uid() != nix::unistd::geteuid().as_raw()
+ || metadata.permissions().mode() & 0o022 != 0
+ {
+ return Err(ServiceProxyError);
+ }
+ }
+ }
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound && create => {
+ let mut builder = fs::DirBuilder::new();
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::DirBuilderExt;
+ builder.mode(0o700);
+ }
+ builder.create(&path).map_err(|_| ServiceProxyError)?;
+ }
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(false),
+ Err(_) => return Err(ServiceProxyError),
+ }
+ }
+ Ok(true)
+}
+
+fn open_private(path: &Path) -> Result<Option<File>, ServiceProxyError> {
+ let mut options = OpenOptions::new();
+ options.read(true);
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::OpenOptionsExt;
+ options.custom_flags(nix::libc::O_NOFOLLOW | nix::libc::O_NONBLOCK);
+ }
+ let file = match options.open(path) {
+ Ok(file) => file,
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
+ Err(_) => return Err(ServiceProxyError),
+ };
+ let metadata = file.metadata().map_err(|_| ServiceProxyError)?;
+ if !metadata.is_file() {
+ return Err(ServiceProxyError);
+ }
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::{MetadataExt, PermissionsExt};
+ if metadata.uid() != nix::unistd::geteuid().as_raw()
+ || metadata.permissions().mode() & 0o077 != 0
+ {
+ return Err(ServiceProxyError);
+ }
+ }
+ Ok(Some(file))
+}
+
+#[cfg(test)]
+#[path = "service_proxy_tests.rs"]
+mod tests;
diff --git a/crates/host-runtime/src/service_proxy_tests.rs b/crates/host-runtime/src/service_proxy_tests.rs
new file mode 100644
index 00000000..815bbdec
--- /dev/null
+++ b/crates/host-runtime/src/service_proxy_tests.rs
@@ -0,0 +1,104 @@
+use super::*;
+
+fn private_home() -> tempfile::TempDir {
+ let mut builder = tempfile::Builder::new();
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ builder.permissions(fs::Permissions::from_mode(0o700));
+ }
+ builder.tempdir().unwrap()
+}
+
+fn snapshot(values: &[(&str, &str)]) -> ServiceProxyEnvironment {
+ ServiceProxyEnvironment::capture(values.iter().map(|(k, v)| (k.into(), v.into()))).unwrap()
+}
+
+#[test]
+fn handoff_is_private_bounded_redacted_and_replaces_the_whole_environment() {
+ let home = private_home();
+ assert!(
+ ServiceProxyEnvironment::load(home.path())
+ .unwrap()
+ .is_none()
+ );
+ let value = snapshot(&[
+ (
+ "https_proxy",
+ "http://user:[email protected]:1187",
+ ),
+ ("NO_PROXY", "localhost,.example.test"),
+ ("OPENAI_API_KEY", "must-not-forward"),
+ ("BASH_ENV", "must-not-execute"),
+ ]);
+ value.store(home.path()).unwrap();
+ let loaded = ServiceProxyEnvironment::load(home.path()).unwrap().unwrap();
+ assert_eq!(loaded.variables, value.variables);
+ assert_eq!(loaded.variables.len(), 2);
+ assert!(!format!("{loaded:?}").contains("private-proxy-password"));
+ let path = ServiceProxyEnvironment::path(home.path());
+ let bytes = fs::read(&path).unwrap();
+ assert!(!String::from_utf8(bytes).unwrap().contains("must-not"));
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ assert_eq!(
+ fs::metadata(&path).unwrap().permissions().mode() & 0o777,
+ 0o600
+ );
+ }
+ snapshot(&[]).store(home.path()).unwrap();
+ assert!(
+ ServiceProxyEnvironment::load(home.path())
+ .unwrap()
+ .unwrap()
+ .variables
+ .is_empty()
+ );
+}
+
+#[test]
+fn unknown_malformed_and_oversized_snapshots_fail_without_exposing_values() {
+ let home = private_home();
+ snapshot(&[]).store(home.path()).unwrap();
+ let path = ServiceProxyEnvironment::path(home.path());
+ for data in [
+ format!(r#"{{"schema":"{SCHEMA}","variables":{{"LD_PRELOAD":"secret"}}}}"#),
+ format!(r#"{{"schema":"{SCHEMA}","variables":{{}},"extra":"secret"}}"#),
+ "secret invalid JSON".into(),
+ "x".repeat(MAX_BYTES as usize + 1),
+ ] {
+ fs::write(&path, data).unwrap();
+ let error = ServiceProxyEnvironment::load(home.path()).unwrap_err();
+ assert!(!error.to_string().contains("secret"));
+ }
+ for value in [
+ "http://proxy\nLD_PRELOAD=bad".to_owned(),
+ "x".repeat(MAX_BYTES as usize),
+ ] {
+ assert!(ServiceProxyEnvironment::capture([("HTTPS_PROXY".into(), value.into())]).is_err());
+ }
+}
+
+#[cfg(unix)]
+#[test]
+fn refuses_symlink_parents_files_and_nonprivate_files() {
+ use std::os::unix::fs::{PermissionsExt, symlink};
+ let home = private_home();
+ let other = private_home();
+ symlink(other.path(), home.path().join(".local")).unwrap();
+ assert!(snapshot(&[]).store(home.path()).is_err());
+ assert!(ServiceProxyEnvironment::load(home.path()).is_err());
+ fs::remove_file(home.path().join(".local")).unwrap();
+ snapshot(&[]).store(home.path()).unwrap();
+ let path = ServiceProxyEnvironment::path(home.path());
+ fs::set_permissions(&path, fs::Permissions::from_mode(0o644)).unwrap();
+ assert!(ServiceProxyEnvironment::load(home.path()).is_err());
+ assert!(snapshot(&[]).store(home.path()).is_err());
+ fs::remove_file(&path).unwrap();
+ let target = other.path().join("untouched");
+ symlink(&target, &path).unwrap();
+ assert!(ServiceProxyEnvironment::load(home.path()).is_err());
+ assert!(snapshot(&[]).store(home.path()).is_err());
+ assert!(!target.exists());
+}
diff --git a/docs/standalone-cli.md b/docs/standalone-cli.md
index dafb3247..1146e2ec 100644
--- a/docs/standalone-cli.md
+++ b/docs/standalone-cli.md
@@ -105,6 +105,24 @@ hiroute service autostart disable --output json
Login autostart and starting the current session are separate actions. `SIGTERM` and `SIGINT`
request an orderly shutdown.
+### Subscription network proxy
+
+Enable your proxy in the terminal before `hiroute service start`, `restart`, or `run`.
+These commands capture `HTTP_PROXY`, `HTTPS_PROXY`, `NO_PROXY` and their lowercase
+forms for managed subscription requests, including model discovery. HTTPS targets
+use `HTTPS_PROXY`; `NO_PROXY` excludes matching targets. `ALL_PROXY`, PAC and OS
+network settings are not read. HiRoute does not execute shell startup files.
+
+The CLI saves the six-variable snapshot in an owner-only file at
+`~/.local/share/hiroute/service/proxy-environment.json`. This lets a separately
+started systemd/launchd service use the terminal's configuration without modifying
+other services. Only CPA consumes it; local management stays direct. Login autostart
+reuses the saved snapshot. To change proxies, update your shell and run
+`hiroute service restart`; `start` on an already-running service leaves it unchanged.
+To clear a saved proxy, unset all six variables and restart. Proxy failure does not
+fall back to direct connections. Do not share the private snapshot: proxy URLs may
+contain credentials. This does not change native Codex login or token refresh ownership.
+
## Discover the current public contract first
The CLI has two public-contract layers:
diff --git a/docs/standalone-cli.zh-CN.md b/docs/standalone-cli.zh-CN.md
index 13db7a9d..78482180 100644
--- a/docs/standalone-cli.zh-CN.md
+++ b/docs/standalone-cli.zh-CN.md
@@ -95,6 +95,20 @@ hiroute service autostart disable --output json
登录自启与当前会话启动是两个动作。`SIGTERM`/`SIGINT` 会触发有序停机。
+### 订阅网络代理
+
+先在终端开启代理,再执行 `hiroute service start`、`restart` 或 `run`。
+这些命令读取 `HTTP_PROXY`、`HTTPS_PROXY`、`NO_PROXY` 及其小写形式,供订阅目录发现
+和推理使用。HTTPS 目标使用 `HTTPS_PROXY`,`NO_PROXY` 控制绕过目标。不读取
+`ALL_PROXY`、PAC 或操作系统网络设置,也不执行 shell 启动文件。
+
+CLI 将这六个变量保存到仅当前用户可读的
+`~/.local/share/hiroute/service/proxy-environment.json`,使单独启动的 systemd/launchd
+服务能使用终端配置,不修改其他服务的环境。只有 CPA 消费此配置,本地管理通信保持直连;
+登录自启复用已保存配置。修改代理后执行 `hiroute service restart`;对已运行服务执行
+`start` 不更新配置。清除代理时,先 unset 全部六个变量再重启。代理失败不会回退直连。
+代理地址可能包含密码,不要分享此私有文件。这不改变原生 Codex 的登录和 token 刷新归属。
+
## 先发现当前公开合同
CLI 有两层公开合同:
diff --git a/scripts/ci-shards.py b/scripts/ci-shards.py
index 5ab5aaef..ae911e2a 100755
--- a/scripts/ci-shards.py
+++ b/scripts/ci-shards.py
@@ -31,6 +31,8 @@ INTEGRATION_SHARDS = {
("hiroute-diagnostics", "writer_bounds"),
("hiroute-cli", "contracts"),
("hiroute-cli", "desktop_locator"),
+ ("hiroute-cli", "service_proxy"),
+ ("hiroute-cli", "transport_unavailable"),
("hiroute-cli", "work_plans"),
("hiroute-cli", "worker_dependencies"),
("hiroute-integrations", "agent_profiles"),
diff --git a/scripts/install-standalone.py b/scripts/install-standalone.py
index 5d9ad79b..23e38271 100755
--- a/scripts/install-standalone.py
+++ b/scripts/install-standalone.py
@@ -334,6 +334,24 @@ def service_bytes(paths, daemon, cpa, cpa_digest):
return paths["data"] / "service/ai.hiroute.cli.plist", plistlib.dumps(value, sort_keys=True)
+def prepare_service_directory(home):
+ """Make the fixed proxy snapshot path safe before any recursive mkdir uses umask."""
+ metadata = home.lstat()
+ if (not stat.S_ISDIR(metadata.st_mode)
+ or metadata.st_uid != os.geteuid() or metadata.st_mode & 0o022):
+ raise ValueError("standalone service HOME is unsafe")
+ current = home
+ for part in (".local", "share", "hiroute", "service"):
+ current = current / part
+ if current.exists() or current.is_symlink():
+ metadata = current.lstat()
+ if (not stat.S_ISDIR(metadata.st_mode)
+ or metadata.st_uid != os.geteuid() or metadata.st_mode & 0o022):
+ raise ValueError(f"standalone service parent is unsafe: {current}")
+ else:
+ current.mkdir(mode=0o700)
+
+
def current_owned_link(path, owned_root, expected_name):
if not path.is_symlink():
return False
@@ -536,6 +554,7 @@ def install(args):
version_parent = version_root.parent
resource_parent = resource_root.parent
+ prepare_service_directory(paths["home"])
version_parent.mkdir(parents=True, exist_ok=True)
resource_parent.mkdir(parents=True, exist_ok=True)
staged_bin = Path(tempfile.mkdtemp(prefix=f".{version}.", dir=version_parent))
diff --git a/scripts/test-standalone-install.py b/scripts/test-standalone-install.py
index 692897c3..557b8f57 100755
--- a/scripts/test-standalone-install.py
+++ b/scripts/test-standalone-install.py
@@ -35,7 +35,7 @@ class StandaloneFixture(unittest.TestCase):
self.repo = self.root / "repo"
self.home = self.root / "home"
self.output = self.root / "output"
- self.home.mkdir()
+ self.home.mkdir(mode=0o700)
skill = self.repo / "assets/skills/hiroute-management/SKILL.md"
docs = self.repo / "docs/standalone-cli.md"
skill.parent.mkdir(parents=True)
@@ -178,6 +178,38 @@ class MacInstallerTests(StandaloneFixture):
@unittest.skipUnless(os.name == "posix" and os.uname().sysname == "Linux", "Linux layout test")
class InstallerTests(StandaloneFixture):
+ def test_unsafe_service_home_is_rejected_without_permission_changes(self):
+ manifest, archive = self.build()
+ self.home.chmod(0o775)
+ with self.environment(), patch.object(installer.subprocess, "run"), patch("builtins.print"):
+ with self.assertRaisesRegex(ValueError, "service HOME is unsafe"):
+ installer.install(self.install_args(manifest, archive))
+ self.assertEqual(self.home.stat().st_mode & 0o777, 0o775)
+ self.assertFalse((self.home / ".local").exists())
+
+ def test_service_parents_are_private_even_with_group_writable_umask(self):
+ manifest, archive = self.build()
+ previous = os.umask(0o002)
+ try:
+ with self.environment(), patch.object(installer.subprocess, "run"), patch("builtins.print"):
+ installer.install(self.install_args(manifest, archive))
+ for relative in (".local", ".local/share", ".local/share/hiroute", ".local/share/hiroute/service"):
+ self.assertEqual((self.home / relative).stat().st_mode & 0o777, 0o700)
+ finally:
+ os.umask(previous)
+
+ def test_service_parent_rejects_symlinks_and_preserves_existing_permissions(self):
+ local = self.home / ".local"
+ local.symlink_to(self.root, target_is_directory=True)
+ with self.assertRaisesRegex(ValueError, "service parent is unsafe"):
+ installer.prepare_service_directory(self.home)
+ local.unlink()
+ local.mkdir()
+ local.chmod(0o775)
+ with self.assertRaisesRegex(ValueError, "service parent is unsafe"):
+ installer.prepare_service_directory(self.home)
+ self.assertEqual(local.stat().st_mode & 0o777, 0o775)
+
def test_install_lock_rejects_concurrent_mutation(self):
with self.environment():
paths = installer.layout(self.home)
@@ -271,6 +303,8 @@ class InstallerTests(StandaloneFixture):
resource_root = self.home / ".local/share/hiroute/0.1.0"
version_root.mkdir(parents=True)
resource_root.mkdir(parents=True)
+ for relative in (".local", ".local/share", ".local/share/hiroute"):
+ (self.home / relative).chmod(0o700)
(version_root / "stale").write_text("old\n")
(resource_root / "stale").write_text("old\n")
marker_path = self.home / ".local/share/hiroute/standalone.json"