From 5b3f3c44e5a2b13c2011703187ada8e2820d66ee Mon Sep 17 00:00:00 2001 From: Phoebus Date: Tue, 29 Sep 2026 00:18:31 -0700 Subject: [PATCH] fix(sys): close AI credential, privacy and privilege-gate gaps --- docs/CHANGELOG.md | 42 +++++++++ docs/HANDOFF.md | 28 ++++++ docs/STATUS.md | 23 +++-- .../crates/phoebus-ai/src/assistant.rs | 55 +++++++++++- installer-rs/crates/phoebus-ai/src/install.rs | 27 +++++- .../crates/phoebus-ai/src/provider.rs | 34 ++++++- .../crates/phoebus-core/src/action.rs | 23 ++++- .../crates/phoebus-executor/src/ai.rs | 88 +++++++++++++++++++ .../phoebus-executor/src/opencode_client.rs | 39 ++++++++ .../phoebus-installer/src/service/mod.rs | 10 ++- .../phoebus-installer/src/service/tests.rs | 19 ++++ 11 files changed, 370 insertions(+), 18 deletions(-) diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 4051b92..cf4769c 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -5,6 +5,48 @@ this file is the curated, human-readable summary. ## Unreleased — Fast defaults with user-controlled source builds +- **`sys`/AI boundary hardening pass (2026-09-28).** A read-audit of every + mutation route plus the AI path found six host-provable defects, all fixed + with regression tests. (1) **Root-gate backdoor removed:** the service layer + honoured `PHOEBUS_ALLOW_UNPRIVILEGED_EXEC=1` and reported uid 0, which let a + non-root desktop-assistant client skip `pkexec` elevation and the root-owned + approval ledger and execute a root-requiring plan in-process; privilege is now + derived from the process identity only. (2) **Credential injection closed:** + `load_api_key` interpolated the key into a curl config `header = "..."` + directive, so a key containing `"`, `\`, whitespace or a control character + could inject curl options; such credentials are now refused. (3) **Derived + OpenCode token redaction:** the base64 Basic/Bearer token actually sent was + not registered with the redactor, so a server echoing the `Authorization` + header could leak it; the token is now registered too. (4) **Privacy allowlist + hole:** `SystemFacts::validate_no_forbidden` did not scan `cpu_features`, so a + forbidden path there could reach the model; every string field is now + scanned. (5) **Endpoint credentials:** `validate_endpoint` accepted userinfo + (`https://user:pass@host/...`); the authority is now rejected while an `@` in + the path/query stays valid. (6) **AI typed-action schema bypass:** the + assistant/install parsers used `serde_json::from_value` directly, and serde's + `deny_unknown_fields` does not cover internally tagged unit variants, so an + action with a smuggled extra key (`{"action":"depclean","shell":"sh"}`) was + accepted on the AI path but rejected by `parse_action`; all paths now route + through the shared `phoebus-core::action::validate_action_value`. New tests: + `service::an_environment_variable_cannot_forge_root`, + `ai::api_key_content_must_be_safe_for_a_curl_config`, + `ai::sandboxed_send_uses_systemd_run_and_keeps_the_key_on_stdin`, + `opencode_client::a_bearer_token_is_redacted_too`, + `provider::every_string_field_is_scanned_for_forbidden_paths`, + `assistant::{plan_actions,investigation_requests}_reject_smuggled_extra_keys`, + `install::investigation_requests_reject_smuggled_extra_keys`, + `action::validate_action_value_rejects_unit_variant_extra_keys`. Gates: + `cargo fmt`, `clippy --workspace --all-targets -- -D warnings`, `cargo test + --workspace` 837 passed / 0 failed, release build. **NotRun, with reasons:** + VM exercise of the `systemd-run` sandbox (needs a fresh disposable install and + a seat/polkit agent; host probe shows the system manager's `manage-units` + requires authentication and the full property set is invalid for + `systemd-run --user`); source-conversion and tuned-kernel + build/boot/fallback journeys (need a disposable 60–80 GiB install + reboot); + Snap changed-revision/strict confinement (external AppArmor + Store + prerequisite); Flatpak/Snap **install** commit/revision drift (installs bind + the human version only; carrying commit/revision through install plans is a + separate change). - **`sys` adversarial input battery + hardening (2026-09-28).** New host-level `tests/sys_adversarial.rs` (54 cases across 11 attack categories: shell injection in every operand type, empty/NUL inputs, extreme lengths, Unicode diff --git a/docs/HANDOFF.md b/docs/HANDOFF.md index f614143..997d586 100644 --- a/docs/HANDOFF.md +++ b/docs/HANDOFF.md @@ -3,6 +3,34 @@ Rolling note between work sessions. **Update this file before you finish**, then commit it. It should be short and current; use `git log` for detail. +- **Boundary-hardening pass (2026-09-28, IMPLEMENTED + UNIT-TESTED, VM NOT + RUN):** six host-provable defects fixed with regression tests. (1) Removed + the `PHOEBUS_ALLOW_UNPRIVILEGED_EXEC=1` env backdoor: it made + `service::effective_uid()` report uid 0, letting a non-root desktop-assistant + client skip `pkexec` + the approval ledger and run a root-requiring plan + in-process. (2) `load_api_key` now refuses a credential containing `"`, `\`, + whitespace or a control character (it is interpolated into a curl config + `header = "..."`). (3) The OpenCode base64 Basic/Bearer token is now + registered with the redactor (only the plaintext was). (4) + `SystemFacts::validate_no_forbidden` now scans `cpu_features` (it was + omitted). (5) `validate_endpoint` refuses userinfo + (`https://user:pass@host/...`). (6) The AI assistant/install parsers now use + `phoebus-core::action::validate_action_value`, closing a unit-variant + `deny_unknown_fields` bypass (`{"action":"depclean","shell":"sh"}` was + accepted on the AI path). Gates: fmt clean, `clippy --workspace + --all-targets -- -D warnings` clean, `cargo test --workspace` 837 passed / 0 + failed, release build. **NotRun:** VM `systemd-run` sandbox exercise — host + probe shows system `manage-units` requires polkit auth and the full property + set is invalid for `--user` (DynamicUser unsupported; PrivateDevices fails); + a VM run as the `phoebus` user on a seat is required to settle whether the + sandbox is usable unprivileged or must switch to `--user` with a reduced + property set. Also NotRun: source-conversion/tuned-kernel journeys (need a + disposable install + reboot); Snap changed-revision/strict confinement + (external prerequisite). Identified but deliberately unchanged: Flatpak/Snap + **install** drift binds the human version only (no commit/revision); + `SnapRefresh` has no review binding; `UpdateSystem`/world-update has no + post-verification; `PrepareUpdates` records `ok` with a truthful + "prebuild skipped" note. Recorded as hypotheses, not reported holes. - **`sys` adversarial battery + hardening (2026-09-28, IMPLEMENTED + UNIT-TESTED, VM NOT RUN):** new `installer-rs/crates/phoebus-installer/tests/ sys_adversarial.rs` (54 cases: shell injection per operand, empty/NUL, diff --git a/docs/STATUS.md b/docs/STATUS.md index 95d7a7f..4d0867c 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -94,8 +94,11 @@ Booting that recovery entry offline remains a manual gate. | Snapshot retention + free-space gate | yes | yes | no | no | | AI typed proposals + evidence review | yes | yes | fixture end-to-end | n/a | | AI guided install (DeepSeek/OpenAI) | yes | yes | fixture path only (no live call) | n/a | -| AI privacy boundary (facts only) | yes | yes | no | n/a | -| AI OS sandbox (systemd hardened unit) | yes | yes | no | no | +| AI privacy boundary (facts only) | yes | yes (every string field scanned, incl. `cpu_features`; forbidden path in `cpu_features` refused) | no | n/a | +| Provider credential + endpoint boundary | yes | yes (unsafe key characters refused before curl config; userinfo endpoint refused; derived base64 token redacted) | no | n/a | +| AI typed-action schema (exact, incl. unit-variant extra keys) | yes | yes (plan/step/investigate actions via `validate_action_value`; smuggled extra key refused) | no | n/a | +| Privilege derived only from the process identity | yes | yes (an environment variable cannot forge uid 0; the removed `PHOEBUS_ALLOW_UNPRIVILEGED_EXEC` regression test) | no | n/a | +| AI OS sandbox (systemd hardened unit) | yes | yes (argv + sandboxed-send via `systemd-run`, key/body on stdin) | no — **host probe 2026-09-28: system `manage-units` needs polkit auth and the full property set is invalid for `--user`; VM seat run required to settle `systemd-run` vs `--user`** | no | | Installed assistant (`sys ask`) | yes | yes | yes (live call 2026-09-28: `sys ask "list installed packages"` via `--ai-backend opencode` to host `opencode serve` through a guest loopback tunnel, model `opencode-go/muse-spark-1.3-contributor`, valid Assistant Plan + approval digest, `AI_LIVE_RC=0`; the `show system status` phrasing elicits schema-noncompliant JSON from this model and is fail-closed rejected) | n/a | | Resolved package effects + approval binding (carried through execution) | yes | yes (empty vs unestablished; drift + prior-step allowance) | no | n/a | | Privileged approval ledger (replacement/replay/concurrency/interruption) | yes | yes (privileged entry point) | no | n/a | @@ -380,10 +383,18 @@ Booting that recovery entry offline remains a manual gate. includes bounded seat socket wait. Graphical desktop seat verification under headless wlroots is proven; graphical verification under a physical seat remains an open hardware gate. -- **AI sandbox** is implemented (`systemd-run` hardening properties, tested at - the argv level) and fails closed without `systemd-run`; it has not been - exercised in a VM. Only typed actions and the privacy boundary were previously - enforced. +- **AI sandbox** is implemented (`systemd-run` hardening properties; argv and + the sandboxed-send path — `systemd-run` program, key/body on stdin — are + unit-tested) and fails closed without `systemd-run`; it has not been + exercised in a VM. A 2026-09-28 host probe found that the system manager's + `org.freedesktop.systemd1.manage-units` policy requires authentication + (`auth_admin_keep`), and that the full property set is invalid for + `systemd-run --user` (`DynamicUser=yes` unsupported, `PrivateDevices=yes` + fails). Whether the sandbox is therefore usable by an unprivileged assistant + user on a seat, or must switch to `--user` with a reduced property set, is a + **hypothesis requiring a disposable-VM seat run**; the sandbox was + deliberately not changed without that proof. Only typed actions and the + privacy boundary were previously enforced. - **Release automation** now has executable gates, a report, atomic publish and signing command helpers, but no gate has been executed by a configured CI runner. `gates --execute` runs each gate's real command in its own diff --git a/installer-rs/crates/phoebus-ai/src/assistant.rs b/installer-rs/crates/phoebus-ai/src/assistant.rs index 9449c5e..78a755b 100644 --- a/installer-rs/crates/phoebus-ai/src/assistant.rs +++ b/installer-rs/crates/phoebus-ai/src/assistant.rs @@ -113,13 +113,26 @@ private files. A human reviews and authenticates every mutation."; /// Parse and validate an assistant plan, fail-closed. pub fn parse_plan(text: &str) -> Result { - let plan: AssistantPlan = serde_json::from_str(text)?; + let value: serde_json::Value = serde_json::from_str(text)?; + let plan: AssistantPlan = serde_json::from_value(value.clone())?; if plan.version != 1 { return Err(AiError::UnsupportedVersion(plan.version)); } if plan.summary.trim().is_empty() { return Err(AiError::Rejected("plan has no summary".into())); } + // Enforce the exact action schema. serde's `deny_unknown_fields` does not + // cover internally tagged unit variants, so an action with a smuggled extra + // key would otherwise be accepted on the AI path but rejected by + // `phoebus_core::action::parse_action` on the deterministic path. + if let Some(raw_actions) = value.get("actions").and_then(|a| a.as_array()) { + for (index, action) in plan.actions.iter().enumerate() { + if let Some(raw) = raw_actions.get(index) { + phoebus_core::action::validate_action_value(raw) + .map_err(|e| AiError::Rejected(format!("{}: {e}", action.describe())))?; + } + } + } for action in &plan.actions { action .validate() @@ -139,6 +152,20 @@ pub fn parse_plan(text: &str) -> Result { Ok(plan) } +/// Parse a JSON array of typed actions through the exact schema validator. +fn parse_action_list(value: &serde_json::Value) -> Result, AiError> { + let values = value + .as_array() + .ok_or_else(|| AiError::Rejected("expected a JSON array of actions".into()))?; + values + .iter() + .map(|v| { + phoebus_core::action::validate_action_value(v) + .map_err(|e| AiError::Rejected(format!("invalid action: {e}"))) + }) + .collect() +} + /// Build the chat request for a user instruction plus system facts. pub fn build_request( provider: ProviderKind, @@ -277,8 +304,8 @@ pub fn parse_step(text: &str) -> Result { return Err(AiError::Rejected(format!("unexpected field `{key}`"))); } } - let requests: Vec = serde_json::from_value( - obj.get("requests") + let requests = parse_action_list( + &obj.get("requests") .cloned() .ok_or_else(|| AiError::Rejected("missing `requests`".into()))?, )?; @@ -476,6 +503,28 @@ mod tests { assert!(parse_plan(text).is_err()); } + #[test] + fn plan_actions_reject_smuggled_extra_keys() { + // `deny_unknown_fields` does not cover internally tagged unit variants, + // so an extra key on `history`/`depclean` must be rejected explicitly on + // the AI path too. + let depclean = r#"{"version":1,"summary":"x","actions":[{"action":"depclean","shell":"sh"}],"rationale":[{"action":"depclean","reason":"x"}]}"#; + assert!(parse_plan(depclean).is_err()); + let history = r#"{"version":1,"summary":"x","actions":[{"action":"history","x":1}],"rationale":[{"action":"history","reason":"x"}]}"#; + assert!(parse_plan(history).is_err()); + let good = r#"{"version":1,"summary":"x","actions":[{"action":"history"}],"rationale":[{"action":"history","reason":"x"}]}"#; + assert!(parse_plan(good).is_ok()); + } + + #[test] + fn investigation_requests_reject_smuggled_extra_keys() { + let step = + r#"{"version":1,"kind":"investigate","requests":[{"action":"history","shell":"sh"}]}"#; + assert!(parse_step(step).is_err()); + let good = r#"{"version":1,"kind":"investigate","requests":[{"action":"history"}]}"#; + assert!(parse_step(good).is_ok()); + } + #[test] fn actions_require_a_reason() { let text = r#"{"version":1,"summary":"x","actions":[{"action":"enable_service","name":"sshd"}],"rationale":[]}"#; diff --git a/installer-rs/crates/phoebus-ai/src/install.rs b/installer-rs/crates/phoebus-ai/src/install.rs index 6f29b69..e65bef9 100644 --- a/installer-rs/crates/phoebus-ai/src/install.rs +++ b/installer-rs/crates/phoebus-ai/src/install.rs @@ -282,7 +282,7 @@ pub fn parse_step(text: &str) -> Result { Ok(InstallStep::Ask { question }) } "investigate" => { - let requests: Vec = serde_json::from_value(get("requests")?)?; + let requests = parse_action_list(&get("requests")?)?; for request in &requests { if !is_investigation_action(request) { return Err(AiError::Rejected(format!( @@ -308,10 +308,25 @@ pub fn parse_step(text: &str) -> Result { } } +/// Parse a JSON array of typed actions through the exact schema validator, so +/// an extra key on an internally tagged unit variant fails closed (serde's +/// `deny_unknown_fields` does not cover those). +fn parse_action_list(value: &serde_json::Value) -> Result, AiError> { + let values = value + .as_array() + .ok_or_else(|| AiError::Rejected("expected a JSON array of actions".into()))?; + values + .iter() + .map(|v| { + phoebus_core::action::validate_action_value(v) + .map_err(|e| AiError::Rejected(format!("invalid action: {e}"))) + }) + .collect() +} + fn messages_body(request: &ChatRequest) -> Result { Ok(serde_json::to_string(request)?) } - /// Run the bounded investigation and return a structurally valid proposal. /// /// `validate` is the deterministic resolver's check (provided by the caller). @@ -532,6 +547,14 @@ mod tests { assert!(parse_step(bad).unwrap_err().to_string().contains("invalid")); } + #[test] + fn investigation_requests_reject_smuggled_extra_keys() { + let step = r#"{"version":2,"kind":"investigate","requests":[{"action":"check_backend","backend":"flatpak","shell":"sh"}]}"#; + assert!(parse_step(step).is_err()); + let good = r#"{"version":2,"kind":"investigate","requests":[{"action":"check_backend","backend":"flatpak"}]}"#; + assert!(parse_step(good).is_ok()); + } + #[test] fn investigation_then_proposal_succeeds() { let transport = crate::provider::ScriptedTransport::new(vec![ diff --git a/installer-rs/crates/phoebus-ai/src/provider.rs b/installer-rs/crates/phoebus-ai/src/provider.rs index afd0691..4e43b73 100644 --- a/installer-rs/crates/phoebus-ai/src/provider.rs +++ b/installer-rs/crates/phoebus-ai/src/provider.rs @@ -185,7 +185,11 @@ impl SystemFacts { &self.encryption, &self.recommended_kernel_profile, ]; - for value in strings.into_iter().chain(self.gpu_vendors.iter()) { + for value in strings + .into_iter() + .chain(self.cpu_features.iter()) + .chain(self.gpu_vendors.iter()) + { if is_forbidden_path(value) { return Err(AiError::PrivateData(value.clone())); } @@ -241,6 +245,17 @@ pub fn validate_endpoint(url: &str) -> Result<(), AiError> { "endpoint contains a character that is unsafe in a transport config".into(), )); } + // A userinfo component (`https://user:pass@host/...`) embeds credentials in + // the URL, where they can leak through error messages or a captured log. The + // explicit-endpoint feature never needs them, so refuse them. + if let Some((_, rest)) = trimmed.split_once("://") { + let authority = rest.split(['/', '?', '#']).next().unwrap_or(""); + if authority.contains('@') { + return Err(AiError::Provider( + "endpoint must not embed credentials (userinfo)".into(), + )); + } + } Ok(()) } @@ -570,6 +585,18 @@ mod tests { )); } + #[test] + fn every_string_field_is_scanned_for_forbidden_paths() { + // `cpu_features` is a `Vec` alongside `gpu_vendors`; every such + // field must be scanned or a personal path can reach the model. + let mut facts = facts(); + facts.cpu_features = vec!["/home/alice/.ssh/id_rsa".into()]; + assert!( + matches!(facts.validate_no_forbidden(), Err(AiError::PrivateData(_))), + "a forbidden path in cpu_features must be refused" + ); + } + #[test] fn history_is_capped_and_sorted() { let mut history = HashMap::new(); @@ -639,6 +666,11 @@ mod tests { assert!(validate_endpoint("scp://host/path").is_err()); assert!(validate_endpoint("https://x/v1\"\nheader = \"A: b").is_err()); assert!(validate_endpoint("https://x/v1 with space").is_err()); + // Embedded credentials would leak through logs/errors. + assert!(validate_endpoint("https://user:pass@api.example.com/v1").is_err()); + assert!(validate_endpoint("http://token@127.0.0.1:8080/v1").is_err()); + // An `@` in the path or query is not userinfo and stays valid. + assert!(validate_endpoint("https://api.example.com/v1?email=a@b").is_ok()); assert!(validate_endpoint("").is_err()); } diff --git a/installer-rs/crates/phoebus-core/src/action.rs b/installer-rs/crates/phoebus-core/src/action.rs index bfeb214..22d4f46 100644 --- a/installer-rs/crates/phoebus-core/src/action.rs +++ b/installer-rs/crates/phoebus-core/src/action.rs @@ -1705,10 +1705,19 @@ fn parse_natural_raw(text: &str) -> Option { pub fn parse_action(json: &str) -> Result { let value: serde_json::Value = serde_json::from_str(json)?; + validate_action_value(&value) +} + +/// Validate an already-parsed action value against the exact schema. +/// +/// `deny_unknown_fields` does not reject extra keys on internally tagged *unit* +/// variants (e.g. `{"action":"history","x":1}`), so every parse path that +/// accepts a `serde_json::Value` — including the AI proposal/assistant parsers, +/// which do not go through [`parse_action`] — must use this function and fail +/// closed on an unknown key. The typed-action boundary is otherwise weaker on +/// the AI path than on the deterministic one. +pub fn validate_action_value(value: &serde_json::Value) -> Result { let action: SystemAction = serde_json::from_value(value.clone())?; - // `deny_unknown_fields` does not reject extra keys on internally tagged - // *unit* variants (e.g. `{"action":"history","x":1}`), so compare the - // input keys against the canonical serialisation and fail closed. if let (Some(input), Some(canonical)) = ( value.as_object(), serde_json::to_value(&action)?.as_object(), @@ -1760,6 +1769,14 @@ mod tests { assert!(parse_action(r#"{"action":"snap_list","extra":true}"#).is_err()); } + #[test] + fn validate_action_value_rejects_unit_variant_extra_keys() { + use serde_json::json; + assert!(validate_action_value(&json!({"action": "history", "shell": "sh"})).is_err()); + assert!(validate_action_value(&json!({"action": "depclean", "shell": "sh"})).is_err()); + assert!(validate_action_value(&json!({"action": "history"})).is_ok()); + } + #[test] fn accepts_bare_package_names() { assert_eq!( diff --git a/installer-rs/crates/phoebus-executor/src/ai.rs b/installer-rs/crates/phoebus-executor/src/ai.rs index 7c6a5d0..1d3406b 100644 --- a/installer-rs/crates/phoebus-executor/src/ai.rs +++ b/installer-rs/crates/phoebus-executor/src/ai.rs @@ -37,6 +37,20 @@ pub fn load_api_key(path: &Path) -> Result { "API key file is empty", )); } + // The key is interpolated into a curl config file, so a quote, backslash, + // whitespace or control character could break out of the + // `header = "Authorization: Bearer ..."` directive and inject additional + // curl options. Such a credential is malformed; refuse it. + if key + .chars() + .any(|c| c.is_whitespace() || c.is_control() || c == '"' || c == '\\') + { + return Err(ExecError::operation( + "ai", + "read API key", + "API key contains a character that is unsafe in a transport config", + )); + } Ok(SecretString::new(key)) } @@ -200,6 +214,34 @@ mod tests { assert_eq!(load_api_key(&path).unwrap().expose(), "sk-test"); } + #[test] + fn api_key_content_must_be_safe_for_a_curl_config() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("key"); + let write = |value: &str| { + std::fs::write(&path, value).unwrap(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap(); + }; + // A quote breaks out of the `header = "..."` directive; a backslash or a + // control character could inject another curl option. + for unsafe_key in [ + "sk-ok\"\nheader = \"X-Injected: yes", + "sk-ok\\nheader = \"X-Injected: yes", + "sk-\nsecret", + "sk-\tsecret", + "sk-\rsecret", + ] { + write(unsafe_key); + assert!( + load_api_key(&path).is_err(), + "unsafe credential must be refused: {unsafe_key:?}" + ); + } + // A realistic token is still accepted. + write("sk-abc_123-XYZ.="); + assert_eq!(load_api_key(&path).unwrap().expose(), "sk-abc_123-XYZ.="); + } + #[test] fn curl_transport_keeps_the_key_out_of_arguments_and_logs() { let runner = RecordingRunner::new(); @@ -238,6 +280,52 @@ mod tests { assert_eq!(exec.redactor().redact("sk-secret-value"), ""); } + #[test] + fn sandboxed_send_uses_systemd_run_and_keeps_the_key_on_stdin() { + if !crate::sandbox::available() { + eprintln!("systemd-run unavailable; sandboxed transport path not exercised here"); + return; + } + let runner = RecordingRunner::new(); + runner.set_response( + "systemd-run", + CommandOutput { + status: 0, + success: true, + stdout: b"{}".to_vec(), + stderr: Vec::new(), + duration: Duration::from_millis(1), + }, + ); + let exec = make_exec(runner.clone()); + let transport = + CurlTransport::new(&exec, Some(SecretString::new("sk-secret-value"))).sandboxed(); + transport + .send( + ProviderKind::OpenAi, + "https://example.invalid/v1/chat/completions", + r#"{"model":"m"}"#, + ) + .unwrap(); + + let specs = runner.recorded(); + let spec = &specs[0]; + assert_eq!(spec.program, "systemd-run"); + assert!( + spec.args.iter().any(|a| a.contains("DynamicUser=yes")), + "the sandbox properties must be present: {:?}", + spec.args + ); + assert!( + !spec.args.iter().any(|a| a.contains("sk-secret-value")), + "the key must not be in argv: {:?}", + spec.args + ); + let stdin = String::from_utf8(spec.stdin.clone().unwrap()).unwrap(); + assert!(stdin.contains("Authorization: Bearer sk-secret-value")); + assert!(stdin.contains("data = ")); + } + #[test] fn curl_transport_refuses_an_unsafe_endpoint() { let runner = RecordingRunner::new(); diff --git a/installer-rs/crates/phoebus-executor/src/opencode_client.rs b/installer-rs/crates/phoebus-executor/src/opencode_client.rs index 4cb4c86..5f521a3 100644 --- a/installer-rs/crates/phoebus-executor/src/opencode_client.rs +++ b/installer-rs/crates/phoebus-executor/src/opencode_client.rs @@ -162,12 +162,17 @@ impl HttpClient for CurlHttpClient<'_> { let token = encode(format!("{}:{}", request.auth_user, password.expose()).as_bytes()); self.exec.register_secret(password); + // The derived token is what actually travels, so it must be + // redacted too: a server that echoes the Authorization header + // would otherwise leak the base64 form into the log. + self.exec.register_secret(&SecretString::new(token.clone())); format!("header = \"Authorization: Basic {token}\"\n") } (Some(password), true) => { use base64_lite::encode; let token = encode(password.expose().as_bytes()); self.exec.register_secret(password); + self.exec.register_secret(&SecretString::new(token.clone())); format!("header = \"Authorization: Bearer {token}\"\n") } _ => String::new(), @@ -910,6 +915,40 @@ mod tests { assert!(stdin.contains(&base64_lite::encode(b"opencode:s3cret-pw"))); // And it is registered for redaction. assert_eq!(exec.redactor().redact("s3cret-pw"), ""); + // The derived base64 token is what actually travels, so an endpoint + // that echoes the Authorization header must not leak it either. + assert_eq!( + exec.redactor() + .redact(&base64_lite::encode(b"opencode:s3cret-pw")), + "" + ); + } + + #[test] + fn a_bearer_token_is_redacted_too() { + let runner = RecordingRunner::new(); + runner.set_response( + "curl", + CommandOutput { + status: 0, + success: true, + stdout: b"\n__PHOEBUS_STATUS__200".to_vec(), + stderr: Vec::new(), + duration: std::time::Duration::from_millis(1), + }, + ); + let dir = tempfile::tempdir().unwrap().keep(); + let logger = crate::log::Logger::open(dir.join("l.log"), Redactor::new(), false); + let exec = crate::exec::Exec::new(Box::new(runner), logger, false, &dir, &dir); + let http = CurlHttpClient::new(&exec); + let mut request = HttpRequest::get("http://127.0.0.1:4096/provider"); + request.auth = Some(SecretString::new("s3cret-pw")); + request.auth_user = String::new(); + http.request(&request).unwrap(); + assert_eq!( + exec.redactor().redact(&base64_lite::encode(b"s3cret-pw")), + "" + ); } #[test] diff --git a/installer-rs/crates/phoebus-installer/src/service/mod.rs b/installer-rs/crates/phoebus-installer/src/service/mod.rs index 48b50b8..60677da 100644 --- a/installer-rs/crates/phoebus-installer/src/service/mod.rs +++ b/installer-rs/crates/phoebus-installer/src/service/mod.rs @@ -243,10 +243,14 @@ fn now_unix() -> u64 { .unwrap_or(0) } +/// The effective uid of the current process. +/// +/// Privilege is derived from the process identity only. It must never be +/// influenceable by an environment variable: a non-root desktop-assistant +/// client could otherwise make the service believe it is root, skip `pkexec` +/// elevation, bypass the root-owned approval ledger, and execute a +/// root-requiring plan in-process. pub fn effective_uid() -> u32 { - if std::env::var("PHOEBUS_ALLOW_UNPRIVILEGED_EXEC").as_deref() == Ok("1") { - return 0; - } std::process::Command::new("id") .arg("-u") .output() diff --git a/installer-rs/crates/phoebus-installer/src/service/tests.rs b/installer-rs/crates/phoebus-installer/src/service/tests.rs index 21a3eb6..84f8c3b 100644 --- a/installer-rs/crates/phoebus-installer/src/service/tests.rs +++ b/installer-rs/crates/phoebus-installer/src/service/tests.rs @@ -32,6 +32,25 @@ fn make_test_exec(root: &Path) -> Exec { ) } +#[test] +fn an_environment_variable_cannot_forge_root() { + // Privilege is derived from the process identity, never from the + // environment. A regression would let a non-root desktop-assistant client + // skip pkexec and the root-owned approval ledger and run a root-requiring + // plan in-process. + let real = effective_uid(); + std::env::set_var("PHOEBUS_ALLOW_UNPRIVILEGED_EXEC", "1"); + let forged = effective_uid(); + std::env::remove_var("PHOEBUS_ALLOW_UNPRIVILEGED_EXEC"); + assert_eq!( + forged, real, + "an environment variable forged the effective uid" + ); + if real != 0 { + assert_ne!(forged, 0, "a non-root process must never report uid 0"); + } +} + fn sample_candidate() -> Candidate { let mut cand = Candidate::new(Backend::Flatpak, "org.mozilla.firefox", "flathub"); cand.version = Some("120.0".into());