fix(admin): anchor approval in a broker ledger, user-own settings, and carry reviewed effects
Some checks are pending
ci / test (push) Waiting to run

This commit is contained in:
Phoebus 2026-09-24 19:14:16 -07:00
parent a2c039f224
commit 0be301009b
23 changed files with 2384 additions and 201 deletions

View file

@ -84,7 +84,8 @@ The only crate that runs privileged commands.
`desktop` — the install backend, mirroring the proven order.
- `probe` — read-only hardware and disk discovery.
- `snapshot`, `update`, `admin`, `actions` — post-install foundations.
- `proactive` — quiet proactive monitors for storage, services, transactions, and reboots.
- `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`.
- `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.
@ -101,7 +102,8 @@ The only crate that runs privileged commands.
### phoebus-installer
- `orchestrate` — `Installer` runs the plan stages and stops on first failure.
- `service` — shared administration service layer (`PreparedPlan`, `PlanStore`, planning, authorization, Polkit elevation, execution, and verification) shared identically by CLI and GUI. The single authoritative validation boundary (`validate_prepared_plan`) runs before elevation and is repeated in the broker after authentication; plans bind actions, effects, candidate, target root and initiating uid, are stored per-user with an integrity seal, and are atomically claimed before execution.
- `service` — shared administration service layer (`PreparedPlan`, `PlanStore`, planning, authorization, Polkit elevation, execution, and verification) shared identically by CLI and GUI. The single authoritative validation boundary (`validate_prepared_plan`) runs before elevation and is repeated in the broker after authentication; plans bind actions, effects, candidate, target root and initiating uid, are stored per-user with an integrity seal, and are atomically claimed before execution. Execution carries the *reviewed* per-step effects forward and compares freshly resolved effects against them (only changes explained by an earlier approved step are allowed), so a material change aborts with a terminal `stale plan` outcome and every started transaction reaches a terminal result.
- `approval` — broker-controlled approval ledger (`/var/lib/phoebus/approvals`, 0700/0600, ADR 0014). The plan's integrity seal is both the binding fingerprint and the `O_EXCL` consumption key, so at most one execution may run, replay is refused even after the user deletes every file in their own plan directory, and a replacement under the same identifier is refused before the ledger is touched. The approving digest travels across authentication independently of the plan file (`--approval-digest`), the initiating identity is derived from `PKEXEC_UID`, and a crash leaves a reconciled `interrupted` record.
- `ai_setup` — one provider/endpoint/model/credential resolver shared by the CLI and the desktop bridge, so their provider setup cannot diverge. Credentials load from a 0600 file (configured path, `PHOEBUS_AI_API_KEY_FILE`, or `~/.config/phoebus/ai.key`) and never travel through QML, prompts or argv.
- `conversation` — bounded, minimized conversation history and contextual follow-up resolution (tradeoff comparisons, backend switching, and plan confirmation). Raw requests are not persisted; registered secrets are redacted; history is 0600/0700, atomic, bounded and clearable.
- `assistant_bridge` — JSON-RPC stdio bridge serving the Quickshell desktop assistant. Every plan type returns the same `plan_id`/`digest` review card; `execute` runs only the referenced reviewed plan.
@ -123,8 +125,14 @@ The only crate that runs privileged commands.
validates and the user approves. The assistant's model call additionally runs
inside an unprivileged, hardened `systemd-run` unit (`sandbox`), so the
boundary is enforced by the OS and not only by the schema.
- Approval is bound to the reviewed resolved plan: package effects are resolved
again before execution and a material change aborts.
- Approval is bound to the reviewed resolved plan: the reviewed per-step effects
are carried into execution, package effects are resolved again only as
evidence to compare against them, and a material change aborts. Privileged
consumption is anchored in a root-owned ledger (ADR 0014), so a user-editable
plan file cannot be replaced or replayed.
- Personal preferences and alert state are user-owned (0600/0700); system-wide
policy is root-owned and changed only through the authenticated typed action
`set_package_preference { system_wide: true }`.
- **Portage binary vs source verification**: Binary package recommendations are
verified with `emerge --pretend --usepkgonly`. If a package would compile from
source (`EffectSource::Source`), execution halts closed and demands a revised

View file

@ -3,6 +3,43 @@
All notable changes are recorded here. The authoritative history is `git log`;
this file is the curated, human-readable summary.
## 2026-09-25 — Approval ledger, user-owned settings, and reviewed-effect execution
- **Broker-controlled approval ledger (ADR 0014, `phoebus-installer::approval`):**
the privileged broker no longer trusts a self-consistent checksum as proof of
approval. The plan's integrity seal — covering actions, per-step effects,
candidate, target root, initiating uid and expiry — is the binding fingerprint
and the `O_EXCL` consumption key in a root-owned ledger
(`/var/lib/phoebus/approvals`, 0700 / 0600). The digest shown on the review
card travels across authentication independently of the plan file
(`--approval-digest`); a replacement plan under the same identifier is refused
even when resealed with a valid checksum; replay is refused even after the user
deletes every file in their own plan directory; at most one execution may run
under concurrent submissions. The initiating identity is derived from
`PKEXEC_UID` (the `--plan-uid` argument is untrusted input). Authentication
precedes the claim, so cancellation/refusal consumes nothing; a crash leaves a
reconciled `interrupted` record that cannot be retried automatically.
- **User-owned personal settings (`phoebus-executor::personal`):** personal
package preferences (`~/.config/phoebus/package-preferences.toml`) and
proactive snooze/dismiss state
(`~/.local/state/phoebus/proactive-state.toml`) are 0600-in-0700, atomic and
bounded, written without elevation. System defaults stay root-owned under
`/etc/phoebus` and change only through the authenticated typed action
`set_package_preference { system_wide: true }`. Personal choices take
precedence; system defaults fill the rest. The initiating user is resolved
through `PHOEBUS_UID` → `SUDO_UID` → `PKEXEC_UID` → effective uid and
`/etc/passwd`, so CLI and GUI agree under sudo/pkexec. Persistence failures are
reported as failures — the GUI never says "saved" or "dismissed" on a failed
write.
- **Reviewed effects carried through execution:** `execute_prepared` now carries
the reviewed per-step effects forward; freshly resolved effects are evidence to
compare against them, never a replacement approval. A material change aborts
with a terminal `stale plan` transaction outcome; only changes explained by an
earlier approved step in the same plan are accepted. Effect-resolution failure,
stale-plan rejection, partial execution and verification failure all record a
terminal result, preserving completed-step outcomes and the protective
snapshot.
## 2026-09-25 — Privileged-boundary, GUI-review, removal, transaction and privacy remediation
- **Single privileged validation boundary (`phoebus-installer::service`):**

View file

@ -3,70 +3,101 @@
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.
- **Last updated:** this session (2026-09-25), privileged-boundary, GUI-review,
removal, transaction and privacy remediation:
Authoritative plan validation (`validate_prepared_plan`), protected per-user
plan storage with atomic claim, truthful transaction outcomes, shared provider
credentials (`ai_setup`), AI-first default removal, corrected conversational
follow-ups, and an honest conversation-history privacy boundary.
- **Last updated:** this session (2026-09-25), the three remaining
administration defects from the latest review: (1) bind privileged execution
to the actual approved plan via a broker-controlled approval ledger, (2) make
personal settings work from a normal desktop account in user-owned storage, and
(3) carry reviewed effects through execution and finish every started
transaction truthfully. See ADR 0014.
- **Current focus:**
1. **Single privileged validation boundary (`phoebus_installer::service`)**:
- `validate_prepared_plan` runs before elevation and is repeated inside the
privileged broker after authentication. It re-derives the plan seal from
the plan's own contents (never two supplied digest strings), and rejects
expired/claimed/modified/malformed/wrong-root/wrong-uid plans.
- Plans bind the exact actions, effects, candidate, canonical target root
and initiating uid. `PreparedPlan.step_effects` revalidates multi-action
plans action-by-action (fixing an aggregate-digest bug).
- `PlanStore` is per-user (`/run/user/<uid>/phoebus/plans`, 0700 / 0600),
writes atomically, uses 128-bit ids, rejects symlinks/third-party
ownership, and claims a plan with `O_EXCL` so at most one execution runs.
- `sys --broker --execute-plan <id> --plan-uid <uid> --root <root>`; a
dropped/mismatched root is rejected rather than executing against `/`.
2. **Truthful transaction outcomes**: verification failure, action failure,
refusal and cancellation finish the transaction truthfully; completed steps
and the snapshot are retained; persistence failures surface; a malformed
broker reply is a protocol failure, not fabricated success.
3. **GUI plan review**: one review card for install/removal/general/rollback/
follow-up, with approval/cancel; executes only the referenced plan; updates
the original card; never says "completed" for a prepared plan; shows
verification; offers launch only when a concrete entry was identified. The
assistant also used the wrong `PhoebusButton` API (`text`/`enabled`) and is
corrected to `label`/`actionEnabled`.
4. **Shared provider credentials (`ai_setup`)**: CLI and GUI resolve provider,
endpoint, model and credential reference through one module; keys load from
a configured 0600 file, `PHOEBUS_AI_API_KEY_FILE` or `~/.config/phoebus/ai.key`
and are never passed through QML, prompts or argv.
5. **AI-first removal + follow-ups**: default removal uses the model with
deterministic ownership discovery underneath; only `--legacy` bypasses it.
Explicit application references beat stale context.
6. **Conversation privacy**: minimized structured history (no raw request),
active redactor, 0600/0700 atomic writes, bounded to ten turns, clearable.
1. **Approval ledger (`phoebus_installer::approval`, ADR 0014):**
- The plan's integrity seal (actions, per-step effects, candidate, target
root, initiating uid, expiry) is the binding fingerprint and the `O_EXCL`
consumption key in a **root-owned** ledger (`/var/lib/phoebus/approvals`,
0700 / 0600).
- `execute_plan_privileged` now takes the reviewed digest and passes it to
`validate_prepared_plan(..., Some(expected_digest), ...)`. The digest
travels across authentication independently of the plan file
(`sys --broker --execute-plan <id> --plan-uid <uid> --approval-digest
<sha256> --root <root>`).
- Replacement under the same identifier is refused even when resealed with a
valid checksum; replay is refused even after the user deletes every file
in their own plan directory; concurrent submissions allow one execution;
a crash leaves a reconciled `interrupted` record. `reconcile_interrupted`
runs at broker startup.
- The initiator is derived from `PKEXEC_UID`
(`approval::broker_initiator_uid`); `--plan-uid` is untrusted input.
Authentication precedes the ledger claim, so refusal consumes nothing.
2. **User-owned personal settings (`phoebus_executor::personal`):**
- `UserStorage` resolves the initiating user (`PHOEBUS_UID` → `SUDO_UID` →
`PKEXEC_UID` → effective uid; home from `/etc/passwd`) and writes 0600 in
0700 atomically.
- Personal preferences → `~/.config/phoebus/package-preferences.toml`;
proactive snooze/dismiss → `~/.local/state/phoebus/proactive-state.toml`
(bounded). System defaults remain `/etc/phoebus/...`, changed only via
`set_package_preference { system_wide: true }` through the broker.
- `chooser::load_preferences` merges system < personal (personal wins,
per-app union); proactive reads the legacy root-owned file only as a
migration fallback. Bridge failures are surfaced; the QML notifies on
failure and the profile combo now uses the exact serde values.
3. **Reviewed effects + terminal transactions (`service::execute_prepared`):**
- Reviewed per-step effects are carried forward; `resolve_effects` is now
only evidence compared with `phoebus_core::effects::approval_holds`
(earlier-step-introduced targets are the only allowance). A material
change aborts with `stale plan`; only Portage actions are compared
(other lanes are validated by `validate_prepared_plan`).
- Every path after `transaction::begin` reaches a terminal result; effect
resolution failure, stale plan, action failure and verification failure
are recorded with per-action outcomes and the snapshot retained.
- **Last verified (this session):**
- `cargo fmt --all -- --check` clean.
- `cargo test --workspace` all pass (70 phoebus-installer unit, 173
phoebus-core, 195 phoebus-executor, 26 CLI, plus integration suites).
- `cargo clippy --workspace --all-targets` runs (exit 0; pre-existing
`result_large_err`/arg-count lints remain, as at the reviewed commit).
- `make test` passes (Rust workspace + VM disk-safety suite).
- Static `sys` and `phoebus-installer` (`crt-static`) build cleanly.
- `sys install/remove firefox` without a model stop and print legacy guidance
(no mutation); `sys history --legacy` runs deterministically.
- `cargo test --workspace`: 582 passed, 0 failed, including new privileged
entry-point regressions: replacement during authentication, recomputed
checksum, deleted user plan+claim replay, concurrent execution, wrong
caller/root, expiry, interruption reconciliation, effect drift, effect
resolution failure after `begin`, and later-step failure after an earlier
success.
- `cargo clippy --workspace --all-targets` runs (exit 0; only the pre-existing
`result_large_err`, one arg-count and one `DiskPhase` lints remain).
- Static `sys` (`crt-static`) builds (`static-pie`, 6.4 MiB).
- Host-level `sys` CLI tests: system-wide preference refused without root;
personal preference saved to user storage without touching `/etc`.
- **Not yet verified this session (BLOCKED):**
- Live AI install/removal journey with an authorized provider — no credential
is present; do not invent one.
- Installed GUI/AI journey and the 12-step acceptance list — requires a
graphical, seat-providing VM and a live model. The installed encrypted disk
(`/var/tmp/phoebus-vm/disks/test-disk.qcow2`) has no LUKS passphrase available
in this environment, so it cannot be booted here.
- Installed-VM journey and the 12-step acceptance list. The existing
disposable installed disk (`/var/tmp/phoebus-vm/disks/test-disk.qcow2`)
reaches the LUKS prompt but **no passphrase in this environment opens it**:
the harness default (`phoebus-luks-test`, which is also the content of
`/home/dominic/vmlab/serve/luks.pw`) is rejected, and no other credential is
available. Do not guess or brute-force.
- No AI provider credential is present; do not invent one.
- A fresh disposable VM install would verify the installed journey but takes
~2 h (disk space is tight, 24 GiB free), so it was not attempted in this pass.
- **Public repo:** <https://git.phoebus.club/phoebus/phoebus_os>
(remote `origin`, SSH port 2222).
## Next actions (in order)
1. **AI-selected install journey (needs an authorised provider)**: boot the
installed disposable disk (`/var/tmp/phoebus-vm/disks/test-disk.qcow2`),
serve the built `sys` and a 0600 key file, then:
1. **Unlock or rebuild the installed VM (blocker).** The installed disk reaches
the LUKS prompt but its passphrase is unknown; the committed harness default
is rejected. Either supply the real passphrase or perform a fresh disposable
install (~2 h) to obtain an installed system, then run the full 12-step
acceptance list below.
2. **Installed `sys` acceptance** on the booted disk:
```sh
# serve the static sys first:
cp installer-rs/target/x86_64-unknown-linux-gnu/release/sys /home/dominic/vmlab/serve/
env DISK=/var/tmp/phoebus-vm/disks/<clone>.qcow2 \
OVMF_CODE=/usr/share/OVMF/OVMF_CODE_4M.fd \
OVMF_VARS=/var/tmp/phoebus-vm/OVMF_VARS.fd \
BOOT_CHECKS='... curl .../sys ...; SYS_BIN=/tmp/sys bash .../sys-acceptance.sh ...' \
python3 installer/tests/vm/serial-driver.py boot
```
The new broker behaviour (replacement during authentication, replay after
deleting user plan state, cancellation) is already covered by
`phoebus-installer` unit tests; the installed run confirms the sealed
elevation path and the personal-preference acceptance case.
3. **AI-selected install journey (needs an authorised provider)**: boot the
installed disk, serve the built `sys` and a 0600 key file, then:
```sh
sudo sys --ai-provider deepseek --ai-api-key-file /run/phoebus/ai.key \
install <application>
@ -76,10 +107,10 @@ commit it. It should be short and current; use `git log` for detail.
Confirm the model requests evidence, the resolver confirms the candidate,
the plan is presented before approval, and the transaction is recorded. No
credential is available here; do not invent one.
2. **Rollback VM acceptance** (`serial-driver.py rollback`) on a cloned
4. **Rollback VM acceptance** (`serial-driver.py rollback`) on a cloned
disposable image of the installed system.
3. **NVIDIA hardware acceptance (BLOCKED)**: needs an NVIDIA GPU.
4. **Interactive graphical user session** login into Mango / DankMaterialShell
5. **NVIDIA hardware acceptance (BLOCKED)**: needs an NVIDIA GPU.
6. **Interactive graphical user session** login into Mango / DankMaterialShell
under a physical seat or nested Wayland compositor.
## Known blockers / risks

View file

@ -84,7 +84,9 @@ still not VM-verified.
| AI privacy boundary (facts only) | yes | yes | no | n/a |
| AI OS sandbox (systemd hardened unit) | yes | yes | no | no |
| Installed assistant (`sys ask`) | yes | yes | fixture path only (no live call) | n/a |
| Resolved package effects + approval binding | yes | yes (empty vs unestablished) | no | n/a |
| Resolved package effects + approval binding (carried through execution) | yes | yes (empty vs unestablished; drift + prior-step allowance) | no | n/a |
| Privileged approval ledger (replacement/replay/concurrency/interruption) | yes | yes (privileged entry point) | no | n/a |
| Personal preferences + alert state (user-owned, system-default precedence) | yes | yes (save/reload/isolation/precedence/failure) | no | no |
| Transaction log (outcomes, protective snapshots) | yes | yes | no | no |
| Flatpak/Nix bounded typed actions | yes | yes | no | no |
| Shared hardware-aware source selection (all lanes) | yes | yes | no | no |

View file

@ -162,8 +162,15 @@ sys --action '{"action":"check_backend","backend":"snap"}'
| `choose firefox` | `choose_package` | read |
| `choose firefox via flatpak` | `choose_package` | read |
| `choose spotify as a gui sandboxed app` | `choose_package` | read |
| `prefer firefox via flatpak` | `set_package_preference` | mutate |
| `prefer firefox auto` | `set_package_preference` | mutate |
| `prefer firefox via flatpak` | `set_package_preference` | mutate (personal) |
| `prefer firefox auto` | `set_package_preference` | mutate (personal) |
| *(JSON only)* `system_wide: true` | `set_package_preference` | mutate (privileged) |
`prefer ...` saves the invoking user's own preference; it needs no elevation and
is stored under the user's config directory. The system-wide default is the same
action with `"system_wide": true`, which requires the authenticated broker. At
resolution time the personal choice wins and system defaults fill anything the
user has not set.
`choose` resolves real backend metadata, applies the shared policy
(ADR 0006), and prints the selected lane, version, provenance, integrity,
@ -265,8 +272,12 @@ a stdio JSON-RPC server speaking newline-delimited JSON messages:
Flatpak, Snap, AppImage, and Nix.
- `proactive_alerts`, `proactive_snooze`, `proactive_dismiss`: interacts with the
quiet proactive system monitor.
- `get_preferences`, `set_preferences`: inspects and edits user package source
profiles, project environment tool mappings, and keep-existing-source pins.
- `get_preferences`, `set_preferences`: inspects and edits the invoking user's
package source profiles, project environment tool mappings, and
keep-existing-source pins. Personal preferences are stored 0600/0700 under the
user's own config (`~/.config/phoebus/package-preferences.toml`) without
elevation; system defaults stay root-owned. A failed write is reported as an
error, never as "saved".
- `history`, `undo`: queries transaction logs and initiates recovery.
Zero business logic lives in the GUI: equivalent CLI and GUI requests produce
@ -274,28 +285,46 @@ identical validated plans given the same facts and preferences.
## Privileged execution boundary
A mutating plan is stored as a `PreparedPlan` in protected, per-user storage
A mutating plan is stored as a `PreparedPlan` in per-user storage
(`/run/user/<uid>/phoebus/plans`, mode 0700; a 0600 plan file; atomic write; a
128-bit unpredictable identifier). The plan is sealed with an integrity digest
over the reviewed fields, the target root and the initiating uid.
over the reviewed fields, the target root and the initiating uid. That seal is
the **approval fingerprint**: it covers the exact actions, per-step effects,
candidate, target root, initiating uid and expiry.
`execute_plan` validates the plan before elevation and again — authoritatively —
inside the privileged broker (`sys --broker --execute-plan <id> --plan-uid <uid>
--root <root>`). The broker:
--approval-digest <sha256> --root <root>`). The broker:
- carries the digest the review card showed the user across authentication
independently of the plan file, and refuses a plan whose recomputed digest
does not match it — so a replacement plan under the same identifier is
rejected even when it is resealed with a valid, self-consistent checksum;
- re-derives the integrity seal from the plan's own contents (it never trusts
two supplied digest strings);
- rejects expired, already-claimed, modified, malformed, wrong-root or
wrong-uid plans;
- revalidates the current package/removal state after authentication;
- atomically claims the plan (`O_EXCL`) so two concurrent requests cannot both
mutate the system, and a retry never repeats a consumed plan;
- rejects expired, modified, malformed, wrong-root or wrong-uid plans;
- derives the initiating identity from the authenticated caller context
(`PKEXEC_UID`), treating `--plan-uid` as untrusted input;
- revalidates the current package/removal state after authentication, and again
action-by-action at the execution boundary against the reviewed effects;
- anchors consumption in a **root-owned approval ledger**
(`/var/lib/phoebus/approvals`, 0700 / 0600, ADR 0014). The fingerprint is
claimed with `O_EXCL`, so at most one execution may run under concurrent
submissions, and a retry is refused even after the user deletes every file in
their own plan directory. A plan left `in_progress` by a crash is reconciled
to `interrupted` at broker startup; a consumed approval is retained.
- treats the plan file and its contents as untrusted input, resolving storage
from the uid rather than an arbitrary path.
Authentication happens outside model context through Polkit (`pkexec`), never
passwordless sudo. Cancelling or refusing authentication performs no mutation
and leaves the plan unconsumed until it expires.
and consumes nothing: authentication precedes the ledger claim. A failed,
stale-plan, verification-failed or interrupted operation reaches a truthful
terminal status.
Each transaction records the outcome per action (`completed`, `failed`,
`unattempted`) plus the protective snapshot, so a partial execution is visible
and never reported as success.
## Transaction truthfulness
@ -342,7 +371,8 @@ with no network and no model.
| 14 | Invalid Snap name | `snap_install name="Bad Name"` | rejected, nonzero |
| 15 | Invalid AppImage hash | `appimage_acquire sha256="00"` | rejected, nonzero |
| 16 | Ebuild path traversal | `custom_ebuild_prepare atom="../../x"` | rejected, nonzero |
| 17 | Mutating as non-root | `set_package_preference` | refused: needs root |
| 17 | System-wide policy as non-root | `set_package_preference system_wide:true` | refused: needs root |
| 17b | Personal preference as non-root | `set_package_preference` | saved to user config, no `/etc` write |
| 18 | Offline `sys ask` | `sys ask "<request>"` with no provider | deterministic fallback, nonzero |
| 19 | Choose with no lane | `sys --root / choose unused-xyz --legacy` | selection or clear failure, never invented |
| 20 | Conflicting backend flags | `sys install x --flatpak --nix` | rejected by CLI |
@ -357,8 +387,10 @@ When `SYS_ACCEPTANCE_MUTATE=1` is set in the disposable VM:
- `mutate-remove`: `sys -y remove app-misc/hello --legacy` uninstalls cleanly.
- `mutate-history`: `sys history --legacy` confirms both install and remove are logged.
All 23 read-only and failure acceptance cases are verified in the test suite
(`installer/tests/vm/sys-acceptance.sh` reports `PASS=23 FAIL=0`). Host unit and
The read-only and failure acceptance cases (24, including the personal-preference
case) are exercised by the test suite
(`installer/tests/vm/sys-acceptance.sh`); the broker approval/replay regression
is covered by `phoebus-installer` unit tests. Host unit and
integration tests in `crates/phoebus-installer/tests/sys_cli.rs`,
`crates/phoebus-core/`, and `crates/phoebus-executor/` cover proposal validation,
digest matching, lane policy, and cross-source removal.

View file

@ -0,0 +1,97 @@
# ADR 0014: Privileged approval ledger and user-owned personal settings
- **Status:** Accepted
- **Date:** 2026-09-25
## Context
Two administration defects remained after the shared-service hardening in
commit `3b84b8c`:
1. **Approval was bound to a user-controlled plan file.** The privileged broker
(`sys --broker --execute-plan <id> --plan-uid <uid>`) loaded the plan from the
reviewing user's directory and re-derived a self-consistency seal from the
plan's own contents. Because the seal is recomputable, a replacement plan
under the same identifier passed. The consumption marker also lived in the
same user-writable directory, so deleting it allowed a replay.
2. **Personal settings wrote to protected system paths.** The desktop bridge ran
unprivileged but wrote package preferences under `/etc/phoebus/` and
proactive snooze/dismiss state under `/var/lib/phoebus/`, which a normal
account cannot write.
A self-consistent checksum is not proof of human approval, and user-writable
files cannot anchor consumption.
## Decision
### Approval is anchored in a broker-controlled ledger
A root-owned approval ledger (`/var/lib/phoebus/approvals`, 0700; records 0600)
records every approval the broker consumes. It is keyed by the plan's integrity
seal — a fingerprint over the exact actions, per-step effects, candidate, target
root, initiating uid and expiry — and is created with `O_EXCL` so:
- at most one execution may run under concurrent submissions;
- replay is refused even when the user deletes or recreates every file in their
own plan directory (the root-owned record remains);
- a replacement plan under the same identifier has a different fingerprint and
is refused before the ledger is touched.
The plan digest shown on the review card is carried across authentication
independently of the plan file (`--approval-digest`) and compared in the broker.
The broker derives the initiating identity from the authenticated caller context
(`PKEXEC_UID`), not from the untrusted `--plan-uid` alone. A plan left
`in_progress` by a crash is reconciled to `interrupted` at broker startup, and a
retry never repeats a consumed mutation. The user-owned claim marker remains as
an optimistic early guard but is no longer the security anchor.
### Personal state is user-owned; system policy is privileged
- Personal package preferences: `<home>/.config/phoebus/package-preferences.toml`
(0600 in 0700), written unprivileged by the invoking account.
- Proactive snooze/dismiss state:
`<home>/.local/state/phoebus/proactive-state.toml` (0600 in 0700), bounded.
- System defaults remain `/etc/phoebus/package-preferences.toml`, root-owned,
changed only through the authenticated typed action
`set_package_preference { system_wide: true }`.
- The initiating user is resolved through `PHOEBUS_UID` → `SUDO_UID` →
`PKEXEC_UID` → the effective uid, and the home directory from `/etc/passwd`
(never `$HOME`, which `sudo` rewrites), so the CLI and GUI resolve the same
user's preferences.
Precedence: personal explicit choices win; system defaults apply to anything the
user has not overridden. A failed write is reported as a failure; the GUI never
reports "saved" or "dismissed" when persistence failed.
### Reviewed effects are carried through execution
Execution carries the reviewed per-step effects forward and treats freshly
resolved effects as evidence to compare against the approval, never as a
replacement approval. A material change aborts with a terminal `stale plan`
transaction outcome. Only changes explained by an earlier approved step in the
same plan are accepted.
## Consequences
- Privileged execution is bound to an independently preserved approval and a
root-owned consumption record; the plan file is untrusted input.
- A normal desktop account can save personal preferences and dismiss alerts
without elevation; system-wide policy stays authenticated.
- Every started transaction reaches a terminal result (`ok`, `failed`,
`stale plan`, `verify failed`, `interrupted`); completed steps and protective
snapshots are retained.
- The ledger env override (`PHOEBUS_APPROVALS_DIR`) and the plan-store override
(`PHOEBUS_PLANS_DIR`) are test/relocation affordances; `pkexec` strips them
from the broker environment, so they are not user-controllable on the
privileged path.
## Alternatives considered
- **Trust the caller-supplied digest alone.** Rejected: a checksum is not proof
of human approval; a root-owned consumption record is required for replay
resistance.
- **A second `pkexec` to register the approval at review time.** Rejected as
unnecessary: the digest carried across authentication plus the root-owned
ledger satisfies the properties without a second prompt.
- **Make `/etc/phoebus` and `/var/lib/phoebus` group-writable.** Rejected: it
weakens system policy ownership to fix a personal-settings problem.

View file

@ -109,12 +109,17 @@ pub enum SystemAction {
},
/// Persist (or clear) an explicit backend preference for an application.
/// The deterministic selector and the assistant both honour it.
/// The deterministic selector and the assistant both honour it. Personal
/// preferences need no privilege; `system_wide` changes the root-owned
/// default and is only applied through the authenticated broker.
SetPackagePreference {
name: String,
/// `None` clears the preference and returns to automatic selection.
#[serde(default, skip_serializing_if = "Option::is_none")]
backend: Option<Backend>,
/// Change the system-wide default rather than the user's own choice.
#[serde(default)]
system_wide: bool,
},
// ------------------------------------------------------------------
@ -303,10 +308,19 @@ impl SystemAction {
}
s
}
SystemAction::SetPackagePreference { name, backend } => match backend {
Some(backend) => format!("prefer {} for {name}", backend.as_str()),
None => format!("clear the backend preference for {name}"),
},
SystemAction::SetPackagePreference {
name,
backend,
system_wide,
} => {
let scope = if *system_wide { " (system-wide)" } else { "" };
match backend {
Some(backend) => {
format!("prefer {} for {name}{scope}", backend.as_str())
}
None => format!("clear the backend preference for {name}{scope}"),
}
}
SystemAction::DiscoverCandidates { query, .. } => {
format!("discover installation candidates for `{query}`")
}
@ -454,6 +468,16 @@ impl SystemAction {
)
}
/// Whether this action requires root. A personal package preference is
/// mutable user state, not a privileged system change, so a normal desktop
/// account may set it; a system-wide preference still requires the broker.
pub fn requires_root(&self) -> bool {
match self {
SystemAction::SetPackagePreference { system_wide, .. } => *system_wide,
other => other.is_mutating(),
}
}
pub fn validate(&self) -> Result<(), String> {
let valid_token = |s: &str| {
!s.is_empty()
@ -1164,6 +1188,7 @@ fn parse_natural_raw(text: &str) -> Option<SystemAction> {
return Some(SystemAction::SetPackagePreference {
name: name.to_string(),
backend,
system_wide: false,
});
}
}
@ -1723,6 +1748,7 @@ mod tests {
Some(SystemAction::SetPackagePreference {
name: "firefox".into(),
backend: Some(Backend::Flatpak),
system_wide: false,
})
);
assert_eq!(
@ -1730,6 +1756,7 @@ mod tests {
Some(SystemAction::SetPackagePreference {
name: "firefox".into(),
backend: None,
system_wide: false,
})
);
let pref =
@ -1737,6 +1764,13 @@ mod tests {
.unwrap();
assert_eq!(pref.risk(), Risk::Medium);
assert!(pref.is_mutating());
// A personal preference needs no privilege; the system-wide variant does.
assert!(!pref.requires_root());
let system = parse_action(
r#"{"action":"set_package_preference","name":"firefox","backend":"nix","system_wide":true}"#,
)
.unwrap();
assert!(system.requires_root());
}
#[test]

View file

@ -337,6 +337,45 @@ pub fn changed_materially(approved: &ResolvedPlan, current: &ResolvedPlan) -> bo
a != b
}
/// Whether a freshly resolved plan still matches what was approved, allowing
/// for package changes that an *earlier approved step in the same plan*
/// introduced (for example, a dependency a previous step just installed).
///
/// Unrelated changes are never accepted: every residual difference between the
/// reviewed and current effect list fails the check. Freshly resolved effects
/// are therefore treated as evidence to compare against the approval, never as
/// a replacement approval.
pub fn approval_holds(
approved: &ResolvedPlan,
current: &ResolvedPlan,
introduced_by_prior_steps: &[PackageEffect],
) -> bool {
if !changed_materially(approved, current) {
return true;
}
// Residual comparison: drop effects whose target was introduced by an
// earlier, already-approved step, then compare everything else.
let prior: std::collections::BTreeSet<&str> = introduced_by_prior_steps
.iter()
.map(|e| e.target.as_str())
.collect();
let mut a = approved.clone();
let mut b = current.clone();
a.effects.retain(|e| !prior.contains(e.target.as_str()));
b.effects.retain(|e| !prior.contains(e.target.as_str()));
// The download size and consequence text legitimately shift with the
// package set; compare the effect identity, provenance and establishment.
a.digest.clear();
b.digest.clear();
a.recovery_point = None;
b.recovery_point = None;
a.download_bytes = None;
b.download_bytes = None;
a.consequences.clear();
b.consequences.clear();
a == b
}
#[cfg(test)]
mod tests {
use super::*;
@ -393,6 +432,27 @@ Total: 5 packages (2 upgrades, 2 new, 1 uninstall), Size of downloads: 10,240 Ki
assert!(changed_materially(&a, &c));
}
#[test]
fn approval_holds_allows_effects_explained_by_earlier_steps_only() {
let approved = parse_emerge_pretend(PRETEND);
// A later re-resolution that additionally reports a dependency an
// earlier approved step installed is explained and allowed.
let with_dep = parse_emerge_pretend(&format!(
"{PRETEND}[ebuild N ] dev-libs/openssl-3.0.0\n"
));
let dep = PackageEffect {
target: "dev-libs/openssl-3.0.0".into(),
previous: None,
kind: EffectKind::New,
source: EffectSource::Source,
};
assert!(approval_holds(&approved, &with_dep, &[dep]));
// The same unrelated change is NOT allowed when no earlier step
// introduced it.
assert!(!approval_holds(&approved, &with_dep, &[]));
}
#[test]
fn empty_output_is_a_no_change_plan() {
let plan = parse_emerge_pretend("Calculating dependencies... done!\n\nTotal: 0 packages\n");

View file

@ -93,6 +93,12 @@ impl ProactiveState {
if !self.is_dismissed(&fingerprint) {
self.dismissed_fingerprints.push(fingerprint);
}
// Bound the state so it cannot grow without limit.
const MAX_DISMISSED: usize = 256;
if self.dismissed_fingerprints.len() > MAX_DISMISSED {
let overflow = self.dismissed_fingerprints.len() - MAX_DISMISSED;
self.dismissed_fingerprints.drain(0..overflow);
}
}
pub fn snooze(&mut self, duration_seconds: u64, now_unix: u64) {
@ -112,6 +118,12 @@ mod tests {
assert!(!state.is_active(200));
assert!(state.is_active(401));
// Dismissals are bounded so persisted state cannot grow without limit.
for i in 0..400 {
state.dismiss(format!("fingerprint-{i}"));
}
assert!(state.dismissed_fingerprints.len() <= 256);
state.dismiss("fp1".into());
assert!(state.is_dismissed("fp1"));
assert!(!state.is_dismissed("fp2"));

View file

@ -176,6 +176,15 @@ fn pretend_args(action: &SystemAction) -> Option<Vec<String>> {
}
}
/// Whether [`resolve_effects`] produces a real, comparable package plan for an
/// action. Only Portage transactions have `emerge --pretend` effects; other
/// lanes' effects are resolved by the install layer. Callers that compare a
/// re-resolution against a reviewed plan must use this to avoid treating a
/// "no comparable package plan" result as a material change.
pub fn resolves_effects(action: &SystemAction) -> bool {
pretend_args(action).is_some()
}
/// Resolve exactly what a package action will do. Non-Portage actions yield an
/// empty plan. A plan's digest can be bound to an approval.
pub fn resolve_effects(exec: &Exec, action: &SystemAction, root: &Path) -> Result<ResolvedPlan> {
@ -319,7 +328,7 @@ pub fn execute(
.validate()
.map_err(|e| ExecError::operation("sys", "validate action", e))?;
if action.is_mutating() && auth.is_none() {
if action.requires_root() && auth.is_none() {
return Err(ExecError::NotAuthorized(action.describe()));
}
@ -540,22 +549,52 @@ pub fn execute(
};
chooser::choose(exec, root, &need)?.render()
}
SystemAction::SetPackagePreference { name, backend } => {
let mut prefs = chooser::load_preferences(root);
SystemAction::SetPackagePreference {
name,
backend,
system_wide,
} => {
if *system_wide {
// Root-owned system default: changed only through the broker.
let mut prefs = chooser::load_system_preferences(root);
match backend {
Some(backend) => {
prefs.per_app.insert(name.clone(), *backend);
chooser::save_preferences(exec, root, &prefs)?;
format!(
"preference saved: {name} -> {}\n automatic selection applies again when \
the preferred lane is incompatible",
backend.as_str()
)
}
None => {
prefs.per_app.remove(name);
chooser::save_preferences(exec, root, &prefs)?;
format!("preference cleared for {name}")
}
}
chooser::save_system_preferences(exec, root, &prefs)?;
match backend {
Some(backend) => format!(
"system-wide preference saved: {name} -> {}\n automatic selection applies \
again when the preferred lane is incompatible",
backend.as_str()
),
None => format!("system-wide preference cleared for {name}"),
}
} else {
// Personal, unprivileged preference belonging to the invoking
// user. Stored privately under their config directory.
let storage = crate::personal::UserStorage::for_initiating_user();
let mut prefs = chooser::load_personal_preferences(&storage).unwrap_or_default();
match backend {
Some(backend) => {
prefs.per_app.insert(name.clone(), *backend);
}
None => {
prefs.per_app.remove(name);
}
}
chooser::save_personal_preferences(&storage, &prefs)?;
match backend {
Some(backend) => format!(
"preference saved for your account: {name} -> {}\n automatic selection \
applies again when the preferred lane is incompatible",
backend.as_str()
),
None => format!("preference cleared for {name}"),
}
}
}

View file

@ -17,12 +17,16 @@ use phoebus_core::selection::{
use crate::command::CommandSpec;
use crate::error::{ExecError, Result};
use crate::exec::Exec;
use crate::personal::UserStorage;
/// Persisted preferences live here, relative to the target root.
/// System-wide defaults live here, relative to the target root. Root-owned and
/// changed only through an authenticated typed action.
pub const PREFERENCES_REL: &str = "etc/phoebus/package-preferences.toml";
/// Personal preferences live here, relative to the user's home.
pub const PERSONAL_PREFERENCES_FILE: &str = "package-preferences.toml";
/// Load persisted preferences (global default and per-application choices).
pub fn load_preferences(root: &Path) -> Preferences {
/// Load the root-owned system default preferences (no personal layer).
pub fn load_system_preferences(root: &Path) -> Preferences {
let path = root.join(PREFERENCES_REL);
std::fs::read_to_string(&path)
.ok()
@ -30,8 +34,50 @@ pub fn load_preferences(root: &Path) -> Preferences {
.unwrap_or_default()
}
/// Persist preferences so an explicit choice survives across sessions.
pub fn save_preferences(exec: &Exec, root: &Path, prefs: &Preferences) -> Result<()> {
/// Load a user's personal preferences, if the file exists.
pub fn load_personal_preferences(storage: &UserStorage) -> Option<Preferences> {
let path = storage.config_file(PERSONAL_PREFERENCES_FILE);
std::fs::read_to_string(&path)
.ok()
.and_then(|text| toml::from_str(&text).ok())
}
/// Personal explicit choices win; system defaults fill anything the user has
/// not overridden. Per-application entries are unioned with the user's choice
/// taking precedence, so a system default for one app never hides a user choice
/// for another.
pub fn merge_preferences(system: Preferences, personal: Option<Preferences>) -> Preferences {
let Some(personal) = personal else {
return system;
};
let mut merged = system;
merged.default = personal.default.or(merged.default);
for (app, backend) in personal.per_app {
merged.per_app.insert(app, backend);
}
merged.allow_proprietary = personal.allow_proprietary;
merged.prefer_source = personal.prefer_source;
merged.profile = personal.profile;
for (path, env) in personal.project_environments {
merged.project_environments.insert(path, env);
}
merged.keep_existing_source = personal.keep_existing_source;
for (app, backend) in personal.inferred_preferences {
merged.inferred_preferences.insert(app, backend);
}
merged
}
/// Resolve the effective preferences for the initiating user: system defaults
/// overlaid with that user's personal choices.
pub fn load_preferences(root: &Path) -> Preferences {
let system = load_system_preferences(root);
let personal = load_personal_preferences(&UserStorage::for_initiating_user());
merge_preferences(system, personal)
}
/// Persist root-owned system defaults (system-wide policy).
pub fn save_system_preferences(exec: &Exec, root: &Path, prefs: &Preferences) -> Result<()> {
let path = root.join(PREFERENCES_REL);
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent).map_err(|e| ExecError::io(parent.to_path_buf(), e))?;
@ -46,6 +92,23 @@ pub fn save_preferences(exec: &Exec, root: &Path, prefs: &Preferences) -> Result
std::fs::write(&path, text).map_err(|e| ExecError::io(path, e))
}
/// Persist the initiating user's personal preferences privately (0600 in 0700),
/// atomically, so an unprivileged desktop account can save without touching
/// `/etc`.
pub fn save_personal_preferences(storage: &UserStorage, prefs: &Preferences) -> Result<()> {
let text = toml::to_string_pretty(prefs)
.map_err(|e| ExecError::operation("sys", "save preferences", e.to_string()))?;
let dir = storage.config_dir();
let file = storage.config_file(PERSONAL_PREFERENCES_FILE);
storage.write_private(&dir, &file, text.as_bytes())
}
/// Backwards-compatible alias for the system-wide writer. New code should use
/// [`save_system_preferences`] or [`save_personal_preferences`] explicitly.
pub fn save_preferences(exec: &Exec, root: &Path, prefs: &Preferences) -> Result<()> {
save_system_preferences(exec, root, prefs)
}
/// Read free storage for the filesystem containing `root` using `df -Pk`.
fn free_mib(exec: &Exec, root: &Path) -> u64 {
let path = if root.exists() {
@ -1117,21 +1180,63 @@ mod tests {
}
#[test]
fn preferences_roundtrip_through_disk() {
fn system_preferences_roundtrip_through_disk() {
let root = tempfile::tempdir().unwrap();
let mut prefs = Preferences::default();
prefs.per_app.insert("firefox".into(), Backend::Flatpak);
prefs.default = Some(Backend::PortageBinary);
let exec = make_exec(RecordingRunner::new());
save_preferences(&exec, root.path(), &prefs).unwrap();
let back = load_preferences(root.path());
save_system_preferences(&exec, root.path(), &prefs).unwrap();
let back = load_system_preferences(root.path());
assert_eq!(back, prefs);
}
#[test]
fn missing_preferences_file_is_the_default() {
let root = tempfile::tempdir().unwrap();
assert_eq!(load_preferences(root.path()), Preferences::default());
assert_eq!(load_system_preferences(root.path()), Preferences::default());
}
#[test]
fn personal_preferences_roundtrip_and_are_not_system_owned() {
let base = tempfile::tempdir().unwrap();
let storage = crate::personal::UserStorage::with_base(4242, base.path());
let mut prefs = Preferences::default();
prefs.per_app.insert("vlc".into(), Backend::Snap);
save_personal_preferences(&storage, &prefs).unwrap();
let back = load_personal_preferences(&storage).unwrap();
assert_eq!(back.per_app.get("vlc"), Some(&Backend::Snap));
// The personal file lives under the user's config dir, never under the
// target root's /etc.
assert!(storage
.config_file(PERSONAL_PREFERENCES_FILE)
.starts_with(base.path()));
}
#[test]
fn personal_choices_take_precedence_over_system_defaults() {
let mut system = Preferences::default();
system
.per_app
.insert("firefox".into(), Backend::PortageBinary);
system.per_app.insert("gimp".into(), Backend::Flatpak);
system.default = Some(Backend::PortageBinary);
system.allow_proprietary = true;
let mut personal = Preferences::default();
personal.per_app.insert("firefox".into(), Backend::Flatpak);
personal.default = Some(Backend::Flatpak);
personal.allow_proprietary = false;
let merged = merge_preferences(system, Some(personal));
// User's explicit choice wins for the same app...
assert_eq!(merged.per_app.get("firefox"), Some(&Backend::Flatpak));
// ...system defaults still apply to apps the user did not set...
assert_eq!(merged.per_app.get("gimp"), Some(&Backend::Flatpak));
assert_eq!(merged.default, Some(Backend::Flatpak));
// ...and the user's scalar policy wins.
assert!(!merged.allow_proprietary);
}
#[test]

View file

@ -25,6 +25,7 @@ pub mod nix;
pub mod opencode;
pub mod opencode_client;
pub mod opencode_server;
pub mod personal;
pub mod portage;
pub mod proactive;
pub mod probe;

View file

@ -0,0 +1,212 @@
//! Per-user, unprivileged storage and initiating-user resolution.
//!
//! Personal package preferences and proactive-alert state are user data, not
//! system policy. They must be writable by a normal desktop account without
//! touching `/etc` or `/var/lib`, while system-wide defaults stay root-owned and
//! are only changed through an authenticated typed action.
//!
//! Two problems are solved here:
//!
//! 1. **Where** personal state lives: `<home>/.config/phoebus/` and
//! `<home>/.local/state/phoebus/`, each created 0700 and written 0600
//! 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` →
//! 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).
use std::io::Write;
use std::path::{Path, PathBuf};
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::<u32>() {
return uid;
}
}
}
effective_uid()
}
pub fn effective_uid() -> u32 {
// Read the effective uid from /proc without unsafe or a subprocess. The
// second field of `Uid:` is the effective uid.
if let Ok(status) = std::fs::read_to_string("/proc/self/status") {
for line in status.lines() {
if let Some(rest) = line.strip_prefix("Uid:") {
if let Some(effective) = rest.split_whitespace().nth(1) {
if let Ok(uid) = effective.parse::<u32>() {
return uid;
}
}
}
}
}
std::process::Command::new("id")
.arg("-u")
.output()
.ok()
.and_then(|o| String::from_utf8_lossy(&o.stdout).trim().parse().ok())
.unwrap_or(1)
}
/// Look up a user's home directory from the passwd database. `$HOME` is not
/// trusted because `sudo`/`pkexec` rewrite it.
pub fn home_for_uid(uid: u32) -> Option<PathBuf> {
let text = std::fs::read_to_string("/etc/passwd").ok()?;
for line in text.lines() {
let fields: Vec<&str> = line.split(':').collect();
if fields.len() >= 6 {
if let Ok(line_uid) = fields[2].parse::<u32>() {
if line_uid == uid && !fields[5].trim().is_empty() {
return Some(PathBuf::from(fields[5].trim()));
}
}
}
}
None
}
/// A resolved, user-owned storage location.
#[derive(Debug, Clone)]
pub struct UserStorage {
uid: u32,
base: PathBuf,
}
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") {
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}")));
Self { uid, base }
}
/// Storage for the user who invoked the command (through sudo/pkexec).
pub fn for_initiating_user() -> Self {
Self::for_uid(initiating_uid())
}
/// An explicit base directory, for tests and callers that already resolved
/// the user's home.
pub fn with_base(uid: u32, base: impl Into<PathBuf>) -> Self {
Self {
uid,
base: base.into(),
}
}
pub fn uid(&self) -> u32 {
self.uid
}
pub fn base(&self) -> &Path {
&self.base
}
/// The 0700 config directory for this user.
pub fn config_dir(&self) -> PathBuf {
self.base.join(".config/phoebus")
}
/// The 0700 state directory for this user.
pub fn state_dir(&self) -> PathBuf {
self.base.join(".local/state/phoebus")
}
pub fn config_file(&self, name: &str) -> PathBuf {
self.config_dir().join(name)
}
pub fn state_file(&self, name: &str) -> PathBuf {
self.state_dir().join(name)
}
/// Atomically write a 0600 file inside the given (0700) directory.
pub fn write_private(&self, dir: &Path, file: &Path, bytes: &[u8]) -> Result<()> {
std::fs::create_dir_all(dir).map_err(|e| ExecError::io(dir.to_path_buf(), e))?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let _ = std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700));
}
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 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))?;
}
std::fs::rename(&tmp, file).map_err(|e| {
let _ = std::fs::remove_file(&tmp);
ExecError::io(file.to_path_buf(), e)
})?;
if let Ok(dir) = std::fs::File::open(dir) {
let _ = dir.sync_all();
}
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::*;
#[test]
fn initiator_env_resolution_order() {
// Do not mutate global env in parallel tests; assert the pure helper via
// the documented override only when it is safe.
let storage = UserStorage::for_uid(4242);
assert_eq!(storage.uid(), 4242);
}
#[test]
fn write_private_is_0600_inside_0700() {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().unwrap();
let storage = UserStorage::with_base(0, dir.path());
let cfg = storage.config_dir();
let file = storage.config_file("x.toml");
storage.write_private(&cfg, &file, b"a = 1").unwrap();
assert_eq!(
std::fs::metadata(&file).unwrap().permissions().mode() & 0o777,
0o600
);
assert_eq!(
std::fs::metadata(&cfg).unwrap().permissions().mode() & 0o777,
0o700
);
assert_eq!(std::fs::read(&file).unwrap(), b"a = 1");
}
}

View file

@ -19,32 +19,72 @@ use phoebus_core::proactive::{
use crate::command::CommandSpec;
use crate::error::{ExecError, Result};
use crate::exec::Exec;
use crate::personal::UserStorage;
use crate::transaction;
use crate::update::check_unified_updates;
pub fn state_path(root: &Path) -> PathBuf {
/// The user-owned state file (relative to the user's state dir).
pub const PROACTIVE_STATE_FILE: &str = "proactive-state.toml";
/// The legacy root-owned state path, kept as a read-only migration source only.
pub fn legacy_state_path(root: &Path) -> PathBuf {
root.join("var/lib/phoebus/proactive-state.toml")
}
pub fn load_state(root: &Path) -> ProactiveState {
let path = state_path(root);
/// Read state from an explicit path (used by tests and callers that already
/// resolved the user's storage).
pub fn load_state_at(path: &Path) -> ProactiveState {
if !path.exists() {
return ProactiveState::default();
}
std::fs::read_to_string(&path)
std::fs::read_to_string(path)
.ok()
.and_then(|t| toml::from_str(&t).ok())
.unwrap_or_default()
}
pub fn save_state(exec: &Exec, root: &Path, state: &ProactiveState) -> Result<()> {
let path = state_path(root);
if let Some(parent) = path.parent() {
/// Atomically write state to an explicit user-owned path (0600 in a 0700 dir).
pub fn save_state_at(path: &Path, state: &ProactiveState) -> Result<()> {
let parent = path.parent().unwrap_or_else(|| Path::new("."));
std::fs::create_dir_all(parent).map_err(|e| ExecError::io(parent.to_path_buf(), e))?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let _ = std::fs::set_permissions(parent, std::fs::Permissions::from_mode(0o700));
}
let text = toml::to_string_pretty(state)
.map_err(|e| ExecError::operation("proactive", "serialize state", e.to_string()))?;
std::fs::write(&path, text).map_err(|e| ExecError::io(path.clone(), e))?;
let tmp = parent.join(format!(".{}.tmp", std::process::id()));
std::fs::write(&tmp, text).map_err(|e| ExecError::io(tmp.clone(), e))?;
std::fs::rename(&tmp, path).map_err(|e| {
let _ = std::fs::remove_file(&tmp);
ExecError::io(path.to_path_buf(), e)
})?;
Ok(())
}
/// The user-owned proactive state file for this user.
pub fn state_path(storage: &UserStorage) -> PathBuf {
storage.state_file(PROACTIVE_STATE_FILE)
}
/// Load a user's proactive state. Falls back to the legacy root-owned file only
/// when the user has no state yet, so existing dismissals are not lost.
pub fn load_state(storage: &UserStorage, root: &Path) -> ProactiveState {
let path = state_path(storage);
if path.exists() {
return load_state_at(&path);
}
let legacy = legacy_state_path(root);
if legacy.exists() {
return load_state_at(&legacy);
}
ProactiveState::default()
}
pub fn save_state(exec: &Exec, storage: &UserStorage, state: &ProactiveState) -> Result<()> {
let path = state_path(storage);
save_state_at(&path, state)?;
exec.logger
.info(format!("proactive state -> {}", path.display()));
Ok(())
@ -202,12 +242,19 @@ pub fn check_system(exec: &Exec, root: &Path) -> Vec<ProactiveAlert> {
alerts
}
/// Retrieve only active, non-dismissed alerts according to persisted state.
pub fn active_alerts(exec: &Exec, root: &Path) -> (Vec<ProactiveAlert>, ProactiveState) {
/// Retrieve only active, non-dismissed alerts according to the user's persisted
/// state. Recording `last_checked_unix` is best-effort: a read path must still
/// return the current alerts even if the user's storage is temporarily
/// unwritable.
pub fn active_alerts(
exec: &Exec,
root: &Path,
storage: &UserStorage,
) -> (Vec<ProactiveAlert>, ProactiveState) {
let now = now_unix();
let mut state = load_state(root);
let mut state = load_state(storage, root);
state.last_checked_unix = now;
let _ = save_state(exec, root, &state);
let _ = save_state(exec, storage, &state);
if !state.is_active(now) {
return (Vec::new(), state);
@ -222,34 +269,44 @@ pub fn active_alerts(exec: &Exec, root: &Path) -> (Vec<ProactiveAlert>, Proactiv
(filtered, state)
}
pub fn snooze(exec: &Exec, root: &Path, duration_seconds: u64) -> Result<()> {
let mut state = load_state(root);
pub fn snooze(
exec: &Exec,
root: &Path,
storage: &UserStorage,
duration_seconds: u64,
) -> Result<()> {
let mut state = load_state(storage, root);
state.snooze(duration_seconds, now_unix());
save_state(exec, root, &state)
save_state(exec, storage, &state)
}
pub fn dismiss(exec: &Exec, root: &Path, fingerprint: &str) -> Result<()> {
let mut state = load_state(root);
pub fn dismiss(exec: &Exec, root: &Path, storage: &UserStorage, fingerprint: &str) -> Result<()> {
let mut state = load_state(storage, root);
state.dismiss(fingerprint.to_string());
save_state(exec, root, &state)
save_state(exec, storage, &state)
}
pub fn set_enabled(exec: &Exec, root: &Path, enabled: bool) -> Result<()> {
let mut state = load_state(root);
pub fn set_enabled(exec: &Exec, root: &Path, storage: &UserStorage, enabled: bool) -> Result<()> {
let mut state = load_state(storage, root);
state.enabled = enabled;
save_state(exec, root, &state)
save_state(exec, storage, &state)
}
pub fn schedule_deferred(exec: &Exec, root: &Path, schedule: DeferredSchedule) -> Result<()> {
let mut state = load_state(root);
pub fn schedule_deferred(
exec: &Exec,
root: &Path,
storage: &UserStorage,
schedule: DeferredSchedule,
) -> Result<()> {
let mut state = load_state(storage, root);
state.deferred_schedule = Some(schedule);
save_state(exec, root, &state)
save_state(exec, storage, &state)
}
pub fn cancel_deferred(exec: &Exec, root: &Path) -> Result<()> {
let mut state = load_state(root);
pub fn cancel_deferred(exec: &Exec, root: &Path, storage: &UserStorage) -> Result<()> {
let mut state = load_state(storage, root);
state.deferred_schedule = None;
save_state(exec, root, &state)
save_state(exec, storage, &state)
}
#[cfg(test)]
@ -266,20 +323,25 @@ mod tests {
Exec::new(Box::new(runner), logger, false, root.to_path_buf(), temp)
}
fn storage(base: &Path, uid: u32) -> UserStorage {
UserStorage::with_base(uid, base)
}
#[test]
fn test_proactive_state_persistence_and_filtering() {
let temp = tempdir().unwrap();
let root = temp.path();
let runner = RecordingRunner::new();
let exec = make_exec(runner, root);
let store = storage(&tempdir().unwrap().keep(), 1000);
let state = load_state(root);
let state = load_state(&store, root);
assert!(state.enabled);
assert!(state.dismissed_fingerprints.is_empty());
// Test dismiss
dismiss(&exec, root, "reboot_required").unwrap();
let state2 = load_state(root);
dismiss(&exec, root, &store, "reboot_required").unwrap();
let state2 = load_state(&store, root);
assert!(state2.is_dismissed("reboot_required"));
// Create reboot required file
@ -292,12 +354,42 @@ mod tests {
assert!(all.iter().any(|a| a.fingerprint == "reboot_required"));
// But active_alerts filters it out because it was dismissed
let (active, _) = active_alerts(&exec, root);
let (active, _) = active_alerts(&exec, root, &store);
assert!(!active.iter().any(|a| a.fingerprint == "reboot_required"));
// Test snooze
snooze(&exec, root, 3600).unwrap();
let state3 = load_state(root);
snooze(&exec, root, &store, 3600).unwrap();
let state3 = load_state(&store, root);
assert!(!state3.is_active(now_unix()));
}
#[test]
fn alert_state_is_isolated_per_user() {
let temp = tempdir().unwrap();
let root = temp.path();
let base_a = tempdir().unwrap();
let base_b = tempdir().unwrap();
let exec = make_exec(RecordingRunner::new(), root);
let alice = storage(base_a.path(), 1000);
let bob = storage(base_b.path(), 1001);
dismiss(&exec, root, &alice, "reboot_required").unwrap();
assert!(load_state(&alice, root).is_dismissed("reboot_required"));
assert!(!load_state(&bob, root).is_dismissed("reboot_required"));
}
#[test]
fn a_failed_persistence_write_is_reported_truthfully() {
let temp = tempdir().unwrap();
let root = temp.path();
let exec = make_exec(RecordingRunner::new(), root);
// Point the state file at a path that cannot be created: a file used as
// a parent directory.
let blocker = temp.path().join("blocker");
std::fs::write(&blocker, "x").unwrap();
let store = UserStorage::with_base(1000, blocker.join("not-a-dir"));
let err = dismiss(&exec, root, &store, "reboot_required").unwrap_err();
assert!(matches!(err, ExecError::Io { .. }), "{err}");
}
}

View file

@ -211,6 +211,10 @@ mod tests {
assert!(err.to_string().contains("not executable"));
}
/// Serializes tests that mutate process-global environment variables so they
/// cannot observe each other's `PHOEBUS_SYS_PATH`.
static ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
struct EnvGuard {
key: &'static str,
original: Option<std::ffi::OsString>,
@ -239,6 +243,7 @@ mod tests {
let tmp = tempfile::tempdir().unwrap();
let elf = create_mock_elf(tmp.path(), "custom_sys", true);
let _env = ENV_LOCK.lock().unwrap();
let _guard = EnvGuard::set("PHOEBUS_SYS_PATH", elf.as_os_str());
let found = find_trusted_sys_binary().expect("must find via PHOEBUS_SYS_PATH");
assert_eq!(found, elf);
@ -251,6 +256,7 @@ mod tests {
let tmp = tempfile::tempdir().unwrap();
let mock_elf = create_mock_elf(tmp.path(), "sys", 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());

View file

@ -0,0 +1,435 @@
//! Broker-controlled approval ledger for privileged plan execution.
//!
//! Plans are staged in per-user storage, which the reviewing user fully
//! controls: they can replace a plan, recompute its seal, and delete the
//! consumption marker. The privileged broker therefore keeps its own record of
//! which approvals it has already consumed.
//!
//! The ledger lives in a root-owned directory (`/var/lib/phoebus/approvals`,
//! 0700, records 0600) that the unprivileged user cannot write. It is keyed by
//! the plan's approval fingerprint — the integrity seal that binds the exact
//! actions, material effects, candidate, target root, initiating user and
//! expiry — and it is created with `O_EXCL` so:
//!
//! - at most one execution may run under concurrent submissions;
//! - a replayed plan is rejected even after the user deletes or recreates every
//! file in their own plan directory (the root-owned record remains);
//! - a replacement plan under the same identifier has a different fingerprint
//! and is refused by the expected-approval check before the ledger is touched.
//!
//! The ledger is *not* a signature scheme and does not claim to be: the
//! independently preserved fingerprint (the digest shown on the review card)
//! supplied by the approval UI is what binds the human decision. The ledger
//! anchors consumption so user-editable files cannot be used to replay or
//! replace an approved plan.
use std::io::Write;
use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};
use phoebus_executor::error::{ExecError, Result};
use serde::{Deserialize, Serialize};
/// Terminal states a consumed approval can reach. There is deliberately no
/// "retry" transition: a plan whose approval was claimed is never automatically
/// re-executed.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ApprovalStatus {
/// Claimed and executing.
InProgress,
/// Completed and verified.
Consumed,
/// The action or verification failed; completed steps are retained.
Failed,
/// The process died after claiming but before finishing.
Interrupted,
/// Claimed after the plan's TTL; recorded for truthful reporting.
Expired,
}
impl ApprovalStatus {
pub fn as_str(self) -> &'static str {
match self {
ApprovalStatus::InProgress => "in_progress",
ApprovalStatus::Consumed => "consumed",
ApprovalStatus::Failed => "failed",
ApprovalStatus::Interrupted => "interrupted",
ApprovalStatus::Expired => "expired",
}
}
pub fn is_terminal(self) -> bool {
!matches!(self, ApprovalStatus::InProgress)
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ApprovalRecord {
/// The plan's integrity seal: a content fingerprint over every reviewed
/// field, including the approval digest.
pub fingerprint: String,
pub plan_id: String,
pub digest: String,
pub initiator_uid: u32,
pub target_root: String,
pub expires_unix: u64,
pub created_unix: u64,
#[serde(default)]
pub finished_unix: u64,
pub status: String,
#[serde(default)]
pub result: String,
/// How many actions the approved plan contained, for truthful reporting.
#[serde(default)]
pub action_count: usize,
}
/// A guard proving this process claimed the approval. Dropping it does not
/// release the claim: the durable record is the anti-replay anchor.
#[derive(Debug)]
pub struct ApprovalClaim {
fingerprint: String,
}
impl ApprovalClaim {
pub fn fingerprint(&self) -> &str {
&self.fingerprint
}
}
#[derive(Debug, Clone)]
pub struct ApprovalLedger {
dir: PathBuf,
}
impl ApprovalLedger {
/// The broker's ledger. `PHOEBUS_APPROVALS_DIR` overrides the location for
/// tests and for an installed system that relocates its state.
pub fn for_broker() -> Self {
if let Ok(dir) = std::env::var("PHOEBUS_APPROVALS_DIR") {
return Self {
dir: PathBuf::from(dir),
};
}
Self {
dir: PathBuf::from("/var/lib/phoebus/approvals"),
}
}
/// An explicit directory, for tests.
pub fn with_dir(dir: impl Into<PathBuf>) -> Self {
Self { dir: dir.into() }
}
pub fn dir(&self) -> &Path {
&self.dir
}
fn ensure_dir(&self) -> Result<()> {
std::fs::create_dir_all(&self.dir).map_err(|e| ExecError::io(self.dir.clone(), e))?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let _ = std::fs::set_permissions(&self.dir, std::fs::Permissions::from_mode(0o700));
}
Ok(())
}
fn path(&self, fingerprint: &str) -> Result<PathBuf> {
if fingerprint.is_empty()
|| fingerprint.len() > 128
|| !fingerprint.bytes().all(|b| b.is_ascii_hexdigit())
{
return Err(ExecError::operation(
"approval",
"ledger path",
"approval fingerprint is not a hex digest",
));
}
Ok(self.dir.join(format!("{fingerprint}.json")))
}
/// Atomically claim an approval for execution. Fails if the fingerprint has
/// already been claimed (consumed, failed, interrupted or in progress),
/// which is what makes replay impossible after the user deletes their own
/// plan and claim files.
#[allow(clippy::too_many_arguments)]
pub fn claim(
&self,
fingerprint: &str,
plan_id: &str,
digest: &str,
initiator_uid: u32,
target_root: &str,
expires_unix: u64,
action_count: usize,
) -> Result<ApprovalClaim> {
self.ensure_dir()?;
let path = self.path(fingerprint)?;
let record = ApprovalRecord {
fingerprint: fingerprint.to_string(),
plan_id: plan_id.to_string(),
digest: digest.to_string(),
initiator_uid,
target_root: target_root.to_string(),
expires_unix,
created_unix: now_unix(),
finished_unix: 0,
status: ApprovalStatus::InProgress.as_str().to_string(),
result: "in progress".into(),
action_count,
};
let text = serde_json::to_string_pretty(&record)
.map_err(|e| ExecError::operation("approval", "serialize", e.to_string()))?;
let mut opts = std::fs::OpenOptions::new();
opts.write(true).create_new(true);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
opts.mode(0o600);
}
match opts.open(&path) {
Ok(mut file) => {
file.write_all(text.as_bytes())
.and_then(|_| file.flush())
.and_then(|_| file.sync_all())
.map_err(|e| ExecError::io(path.clone(), e))?;
Ok(ApprovalClaim {
fingerprint: fingerprint.to_string(),
})
}
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
let prior = self.get(fingerprint).unwrap_or(None);
let detail = prior
.map(|r| format!("{} ({})", r.status, r.result))
.unwrap_or_else(|| "already claimed".to_string());
Err(ExecError::operation(
"approval",
"claim",
format!(
"this approval was already used: {detail}; re-run the workflow to review a \
fresh plan instead of repeating a mutation"
),
))
}
Err(e) => Err(ExecError::io(path, e)),
}
}
/// Record the terminal status of a claimed approval. The record is retained.
pub fn finish(&self, fingerprint: &str, status: ApprovalStatus, result: &str) -> Result<()> {
let path = self.path(fingerprint)?;
let mut record = match self.get(fingerprint)? {
Some(r) => r,
None => {
return Err(ExecError::operation(
"approval",
"finish",
"no approval record to finish",
))
}
};
record.status = status.as_str().to_string();
record.result = result.to_string();
record.finished_unix = now_unix();
let text = serde_json::to_string_pretty(&record)
.map_err(|e| ExecError::operation("approval", "serialize", e.to_string()))?;
let tmp = path.with_extension(format!("{}.tmp", std::process::id()));
std::fs::write(&tmp, text).map_err(|e| ExecError::io(tmp.clone(), e))?;
std::fs::rename(&tmp, &path).map_err(|e| {
let _ = std::fs::remove_file(&tmp);
ExecError::io(path.clone(), e)
})?;
Ok(())
}
/// Read an existing record, if any.
pub fn get(&self, fingerprint: &str) -> Result<Option<ApprovalRecord>> {
let path = match self.path(fingerprint) {
Ok(p) => p,
Err(_) => return Ok(None),
};
if !path.is_file() {
return Ok(None);
}
let text = std::fs::read_to_string(&path).map_err(|e| ExecError::io(path.clone(), e))?;
let record = serde_json::from_str(&text)
.map_err(|e| ExecError::operation("approval", "deserialize", e.to_string()))?;
Ok(Some(record))
}
/// Mark any ledger record left `in_progress` as interrupted. Called at
/// broker startup so a crash is reported truthfully rather than lingering
/// as an operation that "might still be running".
pub fn reconcile_interrupted(&self) -> Result<usize> {
if !self.dir.is_dir() {
return Ok(0);
}
let entries =
std::fs::read_dir(&self.dir).map_err(|e| ExecError::io(self.dir.clone(), e))?;
let mut reconciled = 0;
for entry in entries.flatten() {
let path = entry.path();
if path.extension().and_then(|e| e.to_str()) != Some("json") {
continue;
}
let Ok(text) = std::fs::read_to_string(&path) else {
continue;
};
let Ok(mut record) = serde_json::from_str::<ApprovalRecord>(&text) else {
continue;
};
if record.status == ApprovalStatus::InProgress.as_str() {
record.status = ApprovalStatus::Interrupted.as_str().to_string();
record.result = "the executing process ended before completing".into();
record.finished_unix = now_unix();
if let Ok(text) = serde_json::to_string_pretty(&record) {
let _ = std::fs::write(&path, text);
}
reconciled += 1;
}
}
Ok(reconciled)
}
}
fn now_unix() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0)
}
/// Resolve the authenticated caller of a privileged broker invocation.
///
/// `pkexec` sets `PKEXEC_UID` to the uid of the process that requested
/// elevation; that is the authoritative initiator. The `--plan-uid` argument is
/// treated as untrusted input and only consulted when the broker already runs
/// as root for an internal (non-Polkit) invocation.
pub fn broker_initiator_uid(
explicit_plan_uid: Option<u32>,
effective_ground_uid: u32,
) -> Result<u32> {
if let Ok(value) = std::env::var("PKEXEC_UID") {
if let Ok(uid) = value.trim().parse::<u32>() {
return Ok(uid);
}
return Err(ExecError::operation(
"approval",
"caller identity",
"PKEXEC_UID was not a valid uid; refusing to execute",
));
}
if effective_ground_uid == 0 {
if let Some(uid) = explicit_plan_uid {
return Ok(uid);
}
return Err(ExecError::operation(
"approval",
"caller identity",
"--execute-plan requires the initiating uid (--plan-uid) when no authenticated \
PKEXEC_UID context is present",
));
}
Err(ExecError::operation(
"approval",
"caller identity",
"cannot establish the authenticated caller; refusing privileged execution",
))
}
#[cfg(test)]
mod tests {
use super::*;
use tempfile::tempdir;
const FP: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
#[test]
fn a_claim_can_only_be_taken_once() {
let dir = tempdir().unwrap();
let ledger = ApprovalLedger::with_dir(dir.path());
let _claim = ledger
.claim(FP, "plan-a", "digest", 1000, "/", 9999999999, 1)
.unwrap();
let err = ledger
.claim(FP, "plan-a", "digest", 1000, "/", 9999999999, 1)
.unwrap_err();
assert!(err.to_string().contains("already used"), "{err}");
}
#[test]
fn concurrent_claims_allow_at_most_one_execution() {
let dir = tempdir().unwrap();
let ledger = ApprovalLedger::with_dir(dir.path());
let handles: Vec<_> = (0..8)
.map(|_| {
let ledger = ledger.clone();
std::thread::spawn(move || {
ledger
.claim(FP, "plan-a", "digest", 1000, "/", 9999999999, 1)
.is_ok()
})
})
.collect();
let successes = handles
.into_iter()
.map(|h| h.join().expect("claim thread panicked"))
.filter(|won| *won)
.count();
assert_eq!(successes, 1, "exactly one claim may win");
}
#[test]
fn finish_records_a_terminal_status_and_retains_the_record() {
let dir = tempdir().unwrap();
let ledger = ApprovalLedger::with_dir(dir.path());
let claim = ledger
.claim(FP, "plan-a", "digest", 1000, "/", 9999999999, 2)
.unwrap();
ledger
.finish(claim.fingerprint(), ApprovalStatus::Consumed, "ok")
.unwrap();
let record = ledger.get(FP).unwrap().unwrap();
assert_eq!(record.status, "consumed");
assert!(ApprovalStatus::Consumed.is_terminal());
}
#[test]
fn reconcile_marks_leftover_in_progress_as_interrupted() {
let dir = tempdir().unwrap();
let ledger = ApprovalLedger::with_dir(dir.path());
let _claim = ledger
.claim(FP, "plan-a", "digest", 1000, "/", 9999999999, 1)
.unwrap();
assert_eq!(ledger.reconcile_interrupted().unwrap(), 1);
assert_eq!(ledger.get(FP).unwrap().unwrap().status, "interrupted");
}
#[test]
fn a_replay_is_refused_even_after_the_user_plan_files_are_gone() {
let dir = tempdir().unwrap();
let ledger = ApprovalLedger::with_dir(dir.path());
let claim = ledger
.claim(FP, "plan-a", "digest", 1000, "/", 9999999999, 1)
.unwrap();
ledger
.finish(claim.fingerprint(), ApprovalStatus::Consumed, "ok")
.unwrap();
// The user deletes nothing in the ledger; a retry cannot proceed.
assert!(ledger
.claim(FP, "plan-a", "digest", 1000, "/", 9999999999, 1)
.is_err());
}
#[test]
fn rejects_non_hex_fingerprints() {
let dir = tempdir().unwrap();
let ledger = ApprovalLedger::with_dir(dir.path());
assert!(ledger.get("../escape").unwrap().is_none());
assert!(ledger.claim("not-a-hash", "p", "d", 0, "/", 0, 0).is_err());
}
}

View file

@ -14,6 +14,7 @@ use phoebus_core::selection::Backend;
use phoebus_core::{AiBackend, InstallConfig, Preferences};
use phoebus_executor::chooser;
use phoebus_executor::install::{AiInstall, InstallRequest};
use phoebus_executor::personal::UserStorage;
use phoebus_executor::proactive;
use phoebus_executor::probe;
use phoebus_executor::transaction;
@ -241,11 +242,15 @@ pub fn handle_request(
req: BridgeRequest,
) -> BridgeResponse {
let id = req.id;
// Personal state always belongs to the invoking desktop user. When the
// bridge runs under an elevated command this resolves SUDO_UID/PKEXEC_UID,
// so the CLI and GUI see the same preferences.
let storage = UserStorage::for_initiating_user();
match req.op.as_str() {
"handshake" => {
let ai_conf = load_installed_ai_config(root);
let prefs = chooser::load_preferences(root);
let (alerts, _) = proactive::active_alerts(exec, root);
let (alerts, _) = proactive::active_alerts(exec, root, &storage);
// Check reboot required deterministically without running expensive update checks
let reboot_req = root.join("run/reboot-required").exists()
|| root.join("var/run/reboot-required").exists()
@ -265,7 +270,7 @@ pub fn handle_request(
)
}
"proactive_alerts" => {
let (alerts, state) = proactive::active_alerts(exec, root);
let (alerts, state) = proactive::active_alerts(exec, root, &storage);
BridgeResponse::ok(
id,
json!({
@ -276,16 +281,16 @@ pub fn handle_request(
}
"proactive_snooze" => {
let dur = req.duration_seconds.unwrap_or(3600);
match proactive::snooze(exec, root, dur) {
match proactive::snooze(exec, root, &storage, dur) {
Ok(()) => BridgeResponse::ok(id, json!({ "snoozed_seconds": dur })),
Err(e) => BridgeResponse::err(id, e.to_string()),
Err(e) => BridgeResponse::err(id, format!("could not save snooze: {e}")),
}
}
"proactive_dismiss" => {
let fp = req.fingerprint.unwrap_or_default();
match proactive::dismiss(exec, root, &fp) {
match proactive::dismiss(exec, root, &storage, &fp) {
Ok(()) => BridgeResponse::ok(id, json!({ "dismissed": fp })),
Err(e) => BridgeResponse::err(id, e.to_string()),
Err(e) => BridgeResponse::err(id, format!("could not save dismissal: {e}")),
}
}
"updates" => {
@ -297,10 +302,13 @@ pub fn handle_request(
BridgeResponse::ok(id, json!(prefs))
}
"set_preferences" => {
// Personal preferences are written to the user's own 0600 config,
// never to root-owned `/etc`. A write failure is reported as a
// failure so the GUI never claims "saved" when it did not persist.
if let Some(prefs) = req.preferences {
match chooser::save_preferences(exec, root, &prefs) {
match chooser::save_personal_preferences(&storage, &prefs) {
Ok(()) => BridgeResponse::ok(id, json!({ "saved": true })),
Err(e) => BridgeResponse::err(id, e.to_string()),
Err(e) => BridgeResponse::err(id, format!("could not save preferences: {e}")),
}
} else {
BridgeResponse::err(id, "missing preferences payload")
@ -645,7 +653,7 @@ fn execute_action_helper(
step_effects: vec![effects],
digest: digest.clone(),
verification: "action completed".into(),
requires_root: action.is_mutating(),
requires_root: action.requires_root(),
source: "legacy".into(),
executed: false,
target_root: service::canonical_root(root),
@ -759,6 +767,127 @@ mod tests {
)
}
fn request(op: &str) -> BridgeRequest {
BridgeRequest {
id: 1,
op: op.into(),
request: None,
application: None,
backend: None,
phrase: None,
plan_id: None,
action: None,
actions: None,
digest: None,
yes: None,
duration_seconds: None,
fingerprint: None,
preferences: None,
snapshot: None,
}
}
/// Serializes tests that redirect personal storage through the process
/// environment.
static ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
struct EnvGuard {
key: &'static str,
original: Option<std::ffi::OsString>,
}
impl EnvGuard {
fn set(key: &'static str, val: &std::ffi::OsStr) -> Self {
let original = std::env::var_os(key);
std::env::set_var(key, val);
Self { key, original }
}
}
impl Drop for EnvGuard {
fn drop(&mut self) {
match &self.original {
Some(orig) => std::env::set_var(self.key, orig),
None => std::env::remove_var(self.key),
}
}
}
#[test]
fn personal_preferences_roundtrip_and_use_user_storage() {
let _env = ENV_LOCK.lock().unwrap();
let base = tempdir().unwrap();
let _guard = EnvGuard::set("PHOEBUS_PERSONAL_DIR", base.path().as_os_str());
let temp = tempdir().unwrap();
let root = temp.path();
let exec = make_test_exec(root);
let plans = PlanStore::with_dir(tempdir().unwrap().keep());
let mut prefs = Preferences::default();
prefs.per_app.insert("vlc".into(), Backend::Snap);
let mut save = request("set_preferences");
save.preferences = Some(prefs);
let resp = handle_request(&exec, root, &plans, save);
assert!(resp.ok, "{:?}", resp.error);
// Stored in the user's own config, never root-owned /etc.
let user_file = base.path().join(".config/phoebus/package-preferences.toml");
assert!(user_file.is_file(), "expected {}", user_file.display());
assert!(!root.join("etc/phoebus/package-preferences.toml").exists());
let resp = handle_request(&exec, root, &plans, request("get_preferences"));
assert!(resp.ok);
assert_eq!(resp.result.unwrap()["per_app"]["vlc"], "snap");
}
#[test]
fn a_failed_preference_save_is_reported_as_a_failure() {
let _env = ENV_LOCK.lock().unwrap();
let blocker = tempdir().unwrap();
let not_a_dir = blocker.path().join("file");
std::fs::write(&not_a_dir, "x").unwrap();
let _guard = EnvGuard::set("PHOEBUS_PERSONAL_DIR", not_a_dir.as_os_str());
let temp = tempdir().unwrap();
let root = temp.path();
let exec = make_test_exec(root);
let plans = PlanStore::with_dir(tempdir().unwrap().keep());
let mut save = request("set_preferences");
save.preferences = Some(Preferences::default());
let resp = handle_request(&exec, root, &plans, save);
assert!(!resp.ok, "a failed write must not report success");
assert!(resp.error.unwrap().to_lowercase().contains("could not"));
}
#[test]
fn snooze_and_dismiss_persist_to_user_storage() {
let _env = ENV_LOCK.lock().unwrap();
let base = tempdir().unwrap();
let _guard = EnvGuard::set("PHOEBUS_PERSONAL_DIR", base.path().as_os_str());
let temp = tempdir().unwrap();
let root = temp.path();
let exec = make_test_exec(root);
let plans = PlanStore::with_dir(tempdir().unwrap().keep());
let mut snooze = request("proactive_snooze");
snooze.duration_seconds = Some(3600);
assert!(handle_request(&exec, root, &plans, snooze).ok);
let mut dismiss = request("proactive_dismiss");
dismiss.fingerprint = Some("reboot_required".into());
assert!(handle_request(&exec, root, &plans, dismiss).ok);
let state_file = base
.path()
.join(".local/state/phoebus/proactive-state.toml");
assert!(state_file.is_file(), "expected {}", state_file.display());
let text = std::fs::read_to_string(&state_file).unwrap();
assert!(text.contains("reboot_required"), "{text}");
}
#[test]
fn test_handshake_and_history() {
let temp = tempdir().unwrap();

View file

@ -21,6 +21,7 @@ use phoebus_executor::{
actions, authorize, chooser, probe, transaction, AutoConfirm, Confirmation,
DestructiveAuthorization, Exec, Logger, RealRunner, Result,
};
use phoebus_installer::approval;
use phoebus_installer::conversation::{self, ConversationTurn, FollowupResolution};
use phoebus_installer::service::{self, PreparedPlan};
@ -65,6 +66,11 @@ struct Cli {
#[arg(long, value_name = "UID")]
plan_uid: Option<u32>,
/// The independently preserved approval digest shown to the user at review
/// (internal broker only). The broker binds execution to this exact plan.
#[arg(long, value_name = "SHA256")]
approval_digest: Option<String>,
/// Auto-approve (unattended); still requires root.
#[arg(long, short = 'y')]
yes: bool,
@ -243,9 +249,19 @@ fn run() -> std::result::Result<(), Box<dyn std::error::Error>> {
if effective_uid() != 0 {
return Err("privileged plan execution requires root".into());
}
let initiator_uid = cli
.plan_uid
.ok_or("--execute-plan requires --plan-uid (the reviewing user)")?;
// The initiating identity comes from the authenticated caller context
// (PKEXEC_UID), never from an untrusted --plan-uid alone.
let initiator_uid = approval::broker_initiator_uid(cli.plan_uid, effective_uid())?;
let expected_digest = cli
.approval_digest
.ok_or("--execute-plan requires --approval-digest (the digest the user approved)")?;
// Root-owned ledger: a crash leaves a terminal 'interrupted' record and
// a replay cannot proceed after the user deletes their own plan files.
let approvals = approval::ApprovalLedger::for_broker();
let reconciled = approvals.reconcile_interrupted().unwrap_or(0);
if reconciled > 0 {
eprintln!("sys: recorded {reconciled} interrupted operation(s) from a previous run");
}
// The broker resolves storage from the initiating uid, never from an
// arbitrary path, and repeats the full validation itself.
let plans = service::PlanStore::for_uid(initiator_uid);
@ -253,7 +269,9 @@ fn run() -> std::result::Result<(), Box<dyn std::error::Error>> {
&exec,
&cli.root,
&plans,
&approvals,
plan_id,
&expected_digest,
initiator_uid,
true,
)?;
@ -399,11 +417,13 @@ fn execute_action(
}
};
if action.is_mutating() && effective_uid() != 0 {
// Only genuinely privileged actions require root. A personal package
// preference is mutable user state and is written by the invoking account.
if action.requires_root() && effective_uid() != 0 {
return Err("mutating actions require root; run `sudo sys ...`".into());
}
let auth: Option<DestructiveAuthorization> = if action.is_mutating() {
let auth: Option<DestructiveAuthorization> = if action.requires_root() {
let confirmation = SysConfirm {
action: action.clone(),
assume_yes: cli.yes,

View file

@ -2,6 +2,7 @@
pub mod ai_guide;
pub mod ai_setup;
pub mod approval;
pub mod assistant_bridge;
pub mod conversation;
pub mod gui_bridge;

View file

@ -18,7 +18,7 @@ use std::time::{SystemTime, UNIX_EPOCH};
use phoebus_ai::assistant::{complete_plan, AssistantPlan};
use phoebus_ai::provider::SystemFacts;
use phoebus_core::action::SystemAction;
use phoebus_core::effects::ResolvedPlan;
use phoebus_core::effects::{approval_holds, PackageEffect, ResolvedPlan};
use phoebus_core::selection::{Backend, Candidate, Rejected, SandboxLevel};
use phoebus_core::transaction::{TransactionOutcome, TransactionRecord};
use phoebus_executor::actions;
@ -29,6 +29,8 @@ use phoebus_executor::exec::Exec;
use phoebus_executor::install::{self, AiInstall, InstallRequest, InstallSource};
use phoebus_executor::transaction;
use crate::approval::{ApprovalLedger, ApprovalStatus};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
@ -1360,35 +1362,65 @@ pub fn execute_plan(
}
if plan.requires_root && initiator != 0 {
return elevate_and_execute(root, plan, initiator);
return elevate_and_execute(root, plan, initiator, expected_digest);
}
execute_prepared(exec, root, plans, plan, assume_yes)
execute_prepared(exec, root, plans, plan, assume_yes, None)
}
/// The privileged broker entry point. It repeats the full validation after
/// authentication (never trusting the unprivileged caller) and then executes.
/// The privileged broker entry point.
///
/// It repeats the full validation after authentication (never trusting the
/// unprivileged caller), binds execution to the independently preserved
/// `expected_digest` the approval UI showed the user, and anchors consumption in
/// the broker-controlled [`ApprovalLedger`]. A plan file replaced during
/// authentication no longer matches `expected_digest`; a replay is refused even
/// when the user deletes every file in their own plan directory.
#[allow(clippy::too_many_arguments)]
pub fn execute_plan_privileged(
exec: &Exec,
root: &Path,
plans: &PlanStore,
approvals: &ApprovalLedger,
plan_id: &str,
expected_digest: &str,
initiator_uid: u32,
assume_yes: bool,
) -> Result<PlanExecutionOutcome> {
let plan = plans.load(plan_id)?;
validate_prepared_plan(exec, root, &plan, None, initiator_uid)?;
execute_prepared(exec, root, plans, plan, assume_yes)
// The expected digest is the independently preserved approval the user
// reviewed. A self-consistent reseal of a replacement plan cannot match it.
validate_prepared_plan(exec, root, &plan, Some(expected_digest), initiator_uid)?;
if plan.integrity.is_empty() {
return Err(ExecError::operation(
"service",
"execute_plan_privileged",
"plan has no approval fingerprint; refusing to execute",
));
}
// `execute_prepared` authenticates *before* claiming the approval, so a
// cancelled or refused operation consumes nothing; it then anchors the
// claim in the broker-controlled ledger and records a terminal status.
execute_prepared(
exec,
root,
plans,
plan,
assume_yes,
Some((approvals, initiator_uid)),
)
}
fn elevate_and_execute(
root: &Path,
plan: PreparedPlan,
initiator: u32,
expected_digest: &str,
) -> Result<PlanExecutionOutcome> {
let sys_exe = std::env::current_exe().unwrap_or_else(|_| PathBuf::from("/usr/local/bin/sys"));
// The privileged broker is given the plan identifier and initiating uid,
// never an arbitrary path, and the exact target root. A dropped `--root`
// would (correctly) fail validation rather than execute against `/`.
// The privileged broker is given the plan identifier, the independently
// preserved approval digest, the initiating uid and the exact target root.
// A dropped `--root` would (correctly) fail validation rather than execute
// against `/`.
let output = std::process::Command::new("pkexec")
.arg(sys_exe)
.arg("--broker")
@ -1396,6 +1428,8 @@ fn elevate_and_execute(
.arg(&plan.id)
.arg("--plan-uid")
.arg(initiator.to_string())
.arg("--approval-digest")
.arg(expected_digest)
.arg("--root")
.arg(canonical_root(root))
.output()
@ -1436,16 +1470,20 @@ fn elevate_and_execute(
))
}
/// Claim a plan and run it, recording a truthful transaction outcome on every
/// exit path (success, action failure, verification failure, cancellation).
/// Authenticate, claim and run a plan, recording a truthful transaction outcome
/// on every exit path (success, action failure, verification failure,
/// cancellation, and effect drift). When `approvals` is present the claim is
/// anchored in the broker-controlled ledger and always reaches a terminal
/// status; a refused or cancelled operation claims nothing.
fn execute_prepared(
exec: &Exec,
root: &Path,
plans: &PlanStore,
plan: PreparedPlan,
assume_yes: bool,
approvals: Option<(&ApprovalLedger, u32)>,
) -> Result<PlanExecutionOutcome> {
// Authentication/refusal happens before the claim, so a refused plan is not
// Authentication/refusal happens before any claim, so a refused plan is not
// consumed and stays reviewable (until it expires).
let confirm = ServiceConfirm { assume_yes };
let auth = if plan.requires_root {
@ -1454,6 +1492,67 @@ fn execute_prepared(
None
};
// Anchor the approval in the broker-controlled ledger before mutation. The
// fingerprint is the plan's integrity seal: the exact actions, per-step
// effects, candidate, target root, initiating uid and expiry.
let claimed = match approvals {
Some((ledger, uid)) => {
ledger.claim(
&plan.integrity,
&plan.id,
&plan.digest,
uid,
&plan.target_root,
plan.expires_unix,
plan.actions.len(),
)?;
true
}
None => false,
};
let result = execute_claimed(exec, root, plans, &plan, auth.as_ref());
if claimed {
// The `claimed` flag is only set when the ledger was present.
let ledger = approvals
.map(|(ledger, _)| ledger)
.expect("ledger present when claimed");
let (status, note) = match &result {
Ok(_) => (ApprovalStatus::Consumed, "ok".to_string()),
Err(e) => (ApprovalStatus::Failed, e.to_string()),
};
if let Err(ledger_err) = ledger.finish(&plan.integrity, status, &note) {
return match result {
Ok(_) => Err(ExecError::operation(
"service",
"record approval",
format!(
"the operation completed but its approval outcome could not be \
recorded: {ledger_err}"
),
)),
Err(e) => Err(ExecError::operation(
"service",
"record approval",
format!("{e}; the approval outcome could not be recorded: {ledger_err}"),
)),
};
}
}
result
}
/// The authenticated execution body. Freshly resolved effects are compared
/// against the reviewed per-step effects; only changes explained by earlier
/// approved steps are allowed.
fn execute_claimed(
exec: &Exec,
root: &Path,
plans: &PlanStore,
plan: &PreparedPlan,
auth: Option<&phoebus_executor::auth::DestructiveAuthorization>,
) -> Result<PlanExecutionOutcome> {
// Atomic claim: at most one caller can proceed with this plan.
let _claim = plans.claim(&plan.id)?;
@ -1474,26 +1573,107 @@ fn execute_prepared(
};
let tx_id = transaction::begin(exec, root, record)?;
// Re-resolve each action's effects at the execution boundary (the same
// path a manual action takes). `validate_prepared_plan` has already
// revalidated them against the reviewed state, so this cannot smuggle a
// changed plan past approval.
let approved_steps: Vec<(SystemAction, ResolvedPlan)> = plan
.actions
.iter()
.map(|act| actions::resolve_effects(exec, act, root).map(|eff| (act.clone(), eff)))
.collect::<Result<Vec<_>>>()?;
// Carry the *reviewed* per-step effects forward. Freshly resolved effects
// below are evidence to compare against these, never a replacement
// approval.
let reviewed_steps: Vec<ResolvedPlan> =
if plan.step_effects.len() == plan.actions.len() && !plan.step_effects.is_empty() {
plan.step_effects.clone()
} else {
vec![plan.effects.clone(); plan.actions.len()]
};
let run = actions::execute_plan(exec, &approved_steps, auth.as_ref(), root);
let mut completed: Vec<(String, String)> = Vec::new();
let mut outcomes: Vec<TransactionOutcome> = Vec::new();
let mut snapshot: Option<String> = None;
let mut introduced: Vec<PackageEffect> = Vec::new();
let mut failure: Option<(String, String)> = None;
// A distinct, terminal "the approved plan no longer matches live state"
// reason: effect resolution failed, or the effects changed materially.
let mut drift: Option<String> = None;
if let Some((action_str, detail)) = &run.failure {
for (idx, action) in plan.actions.iter().enumerate() {
let described = action.describe();
if failure.is_some() || drift.is_some() {
outcomes.push(TransactionOutcome::unattempted(described));
continue;
}
// Only Portage transactions have a comparable `emerge --pretend` plan
// at this boundary. Other lanes' effects were validated by
// `validate_prepared_plan` (install revalidation / installed-copy
// checks); re-resolving them here would see an empty plan and falsely
// report drift.
let mut current = ResolvedPlan::default();
if actions::resolves_effects(action) {
let reviewed = &reviewed_steps[idx];
current = match actions::resolve_effects(exec, action, root) {
Ok(current) => current,
Err(e) => {
let detail = format!("effect resolution failed for `{described}`: {e}");
outcomes.push(TransactionOutcome::failed(
described.clone(),
detail.clone(),
));
drift = Some(format!("stale plan: {detail}"));
continue;
}
};
if !approval_holds(reviewed, &current, &introduced) {
let detail = format!(
"the reviewed effects for `{described}` changed materially before execution"
);
outcomes.push(TransactionOutcome::failed(
described.clone(),
detail.clone(),
));
drift = Some(format!("stale plan: {detail}"));
continue;
}
}
match actions::execute(exec, action, auth, root) {
Ok(result) => {
if result.snapshot.is_some() {
snapshot = result.snapshot;
}
outcomes.push(TransactionOutcome::completed(described.clone()));
completed.push((described, result.output));
// Packages this approved action installed may legitimately
// appear in a later step's re-resolution.
introduced.extend(current.effects);
}
Err(e) => {
let detail = e.to_string();
outcomes.push(TransactionOutcome::failed(
described.clone(),
detail.clone(),
));
failure = Some((described, detail));
}
}
}
if let Some(reason) = drift {
finish_or_report(
exec,
root,
tx_id,
reason.clone(),
snapshot.clone(),
outcomes.clone(),
"the stale plan was recorded",
)?;
return Err(ExecError::operation("service", "execute", reason));
}
if let Some((action_str, detail)) = &failure {
finish_or_report(
exec,
root,
tx_id,
format!("failed: {detail}"),
run.snapshot.clone(),
run.outcomes.clone(),
snapshot.clone(),
outcomes.clone(),
"the action failed",
)?;
return Err(ExecError::operation(
@ -1530,8 +1710,8 @@ fn execute_prepared(
root,
tx_id,
format!("verify failed: {e}"),
run.snapshot.clone(),
run.outcomes.clone(),
snapshot.clone(),
outcomes.clone(),
"verification failed",
)?;
return Err(e);
@ -1554,8 +1734,8 @@ fn execute_prepared(
root,
tx_id,
format!("verify failed: {err}"),
run.snapshot.clone(),
run.outcomes.clone(),
snapshot.clone(),
outcomes.clone(),
"verification failed",
)?;
return Err(ExecError::operation("service", "verify removal", err));
@ -1568,23 +1748,23 @@ fn execute_prepared(
_ => "ok".into(),
};
let launch = detect_launch(root, &plan);
let launch = detect_launch(root, plan);
finish_or_report(
exec,
root,
tx_id,
"ok",
run.snapshot.clone(),
run.outcomes.clone(),
snapshot.clone(),
outcomes.clone(),
"the transaction could not be recorded",
)?;
let outputs: Vec<String> = run.completed.into_iter().map(|(_, out)| out).collect();
let outputs: Vec<String> = completed.into_iter().map(|(_, out)| out).collect();
Ok(PlanExecutionOutcome {
completed: true,
snapshot: run.snapshot,
snapshot,
result: "ok".into(),
verification: verification_result,
output: outputs,
@ -1653,6 +1833,7 @@ fn detect_launch(root: &Path, plan: &PreparedPlan) -> Option<Vec<String>> {
#[cfg(test)]
mod tests {
use super::*;
use phoebus_core::effects::parse_emerge_pretend;
use phoebus_core::selection::Capability;
use phoebus_core::Redactor;
use phoebus_executor::command::RecordingRunner;
@ -2097,6 +2278,7 @@ mod tests {
}),
);
let store = PlanStore::with_dir(tempdir().unwrap().keep());
let approvals = ApprovalLedger::with_dir(tempdir().unwrap().keep());
let mut request = InstallRequest::new("firefox");
request.backend = Some(Backend::Flatpak);
@ -2108,7 +2290,9 @@ mod tests {
&exec,
root.path(),
&store,
&approvals,
&plan.id,
&plan.digest,
plan.initiator_uid,
true,
)
@ -2131,7 +2315,9 @@ mod tests {
&exec,
root.path(),
&store,
&approvals,
&plan.id,
&plan.digest,
plan.initiator_uid,
true,
)
@ -2150,6 +2336,7 @@ mod tests {
}),
);
let store = PlanStore::with_dir(tempdir().unwrap().keep());
let approvals = ApprovalLedger::with_dir(tempdir().unwrap().keep());
let mut request = InstallRequest::new("firefox");
request.backend = Some(Backend::Flatpak);
let plan = plan_legacy_install(&store, &exec, root.path(), &request).unwrap();
@ -2158,7 +2345,9 @@ mod tests {
&exec,
root.path(),
&store,
&approvals,
&plan.id,
&plan.digest,
plan.initiator_uid,
true,
)
@ -2195,11 +2384,14 @@ mod tests {
seal_plan(&mut plan);
store.save(&mut plan).unwrap();
let approvals = ApprovalLedger::with_dir(tempdir().unwrap().keep());
let err = execute_plan_privileged(
&exec,
root.path(),
&store,
&approvals,
&plan.id,
&plan.digest,
plan.initiator_uid,
false,
)
@ -2209,5 +2401,556 @@ mod tests {
!store.is_claimed(&plan.id),
"a refused plan is not consumed"
);
// Refusal happens before the approval is claimed, so nothing is
// consumed in the broker ledger either.
assert!(
approvals.get(&plan.integrity).unwrap().is_none(),
"a refused plan must not consume its approval"
);
}
// -----------------------------------------------------------------------
// Regression tests for the approval boundary and transaction truthfulness.
// -----------------------------------------------------------------------
const VIM_PRETEND: &str = "Calculating dependencies... done!\n\
[ebuild N ] app-editors/vim-9.1.0\n\nTotal: 1 package\n";
const WGET_PRETEND: &str = "Calculating dependencies... done!\n\
[ebuild N ] net-misc/wget-1.24.5\n\nTotal: 1 package\n";
fn command_out(text: &str, success: bool) -> phoebus_executor::command::CommandOutput {
phoebus_executor::command::CommandOutput {
status: if success { 0 } else { 1 },
success,
stdout: text.as_bytes().to_vec(),
stderr: Vec::new(),
duration: std::time::Duration::from_millis(1),
}
}
struct SequenceRunner {
responses: std::sync::Mutex<Vec<phoebus_executor::command::CommandOutput>>,
fallback: phoebus_executor::command::CommandOutput,
}
impl phoebus_executor::command::ProcessRunner for SequenceRunner {
fn execute(
&self,
_spec: &phoebus_executor::command::CommandSpec,
) -> Result<phoebus_executor::command::CommandOutput> {
let mut responses = self.responses.lock().unwrap();
if !responses.is_empty() {
return Ok(responses.remove(0));
}
Ok(self.fallback.clone())
}
}
fn portage_install_plan(
id: &str,
action: SystemAction,
reviewed: ResolvedPlan,
root: &Path,
uid: u32,
) -> PreparedPlan {
let actions = vec![action];
let digest = compute_plan_digest(&actions, None, &reviewed);
let mut plan = PreparedPlan {
id: id.into(),
created_unix: now_unix(),
expires_unix: now_unix() + 900,
kind: PlanKind::General,
summary: "install reviewed package".into(),
recommendation: "rec".into(),
application: Some("app-editors/vim".into()),
candidate: None,
alternatives: Vec::new(),
rationale: Vec::new(),
warnings: Vec::new(),
actions,
effects: reviewed.clone(),
step_effects: vec![reviewed],
digest,
verification: "verify".into(),
requires_root: true,
source: "test".into(),
executed: false,
target_root: canonical_root(root),
initiator_uid: uid,
integrity: String::new(),
};
seal_plan(&mut plan);
plan
}
fn ledger_entries(ledger: &ApprovalLedger) -> usize {
std::fs::read_dir(ledger.dir())
.map(|d| d.flatten().count())
.unwrap_or(0)
}
#[test]
fn replacing_the_plan_during_authentication_is_rejected() {
let root = tempdir().unwrap();
let exec = make_test_exec(root.path());
let store = PlanStore::with_dir(tempdir().unwrap().keep());
let approvals = ApprovalLedger::with_dir(tempdir().unwrap().keep());
let uid = effective_uid();
let mut original = sealed(
"plan-replace",
PlanKind::General,
vec![SystemAction::History],
"reviewed-digest",
root.path(),
uid,
);
store.save(&mut original).unwrap();
let approved_digest = original.digest.clone();
// Replace the plan under the same identifier with a different action and
// a valid recomputed checksum.
let mut replacement = sealed(
"plan-replace",
PlanKind::General,
vec![SystemAction::EnableService {
name: "sshd".into(),
}],
"different-digest",
root.path(),
uid,
);
replacement.requires_root = true;
seal_plan(&mut replacement);
assert_eq!(
replacement.integrity,
plan_integrity(&replacement),
"the replacement is self-consistent, yet must still be refused"
);
store.save(&mut replacement).unwrap();
let err = execute_plan_privileged(
&exec,
root.path(),
&store,
&approvals,
"plan-replace",
&approved_digest,
uid,
true,
)
.unwrap_err();
assert!(err.to_string().contains("digest mismatch"), "{err}");
// No system mutation and no approval consumed.
assert_eq!(ledger_entries(&approvals), 0, "nothing may be claimed");
}
#[test]
fn replay_is_rejected_after_the_user_deletes_their_plan_state() {
let root = tempdir().unwrap();
let exec = make_test_exec(root.path());
let store = PlanStore::with_dir(tempdir().unwrap().keep());
let approvals = ApprovalLedger::with_dir(tempdir().unwrap().keep());
let uid = effective_uid();
let mut plan = sealed(
"plan-replay",
PlanKind::General,
vec![SystemAction::History],
"d",
root.path(),
uid,
);
let path = store.save(&mut plan).unwrap();
let digest = plan.digest.clone();
let bytes = std::fs::read(&path).unwrap();
execute_plan_privileged(
&exec,
root.path(),
&store,
&approvals,
"plan-replay",
&digest,
uid,
true,
)
.unwrap();
// The user wipes their own plan and claim files and rewrites the plan
// with identical bytes (0600, as the store would): the approval is still
// consumed.
std::fs::remove_file(&path).unwrap();
let _ = std::fs::remove_file(store.dir().join("plan-replay.claim"));
std::fs::write(&path, &bytes).unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap();
}
let err = execute_plan_privileged(
&exec,
root.path(),
&store,
&approvals,
"plan-replay",
&digest,
uid,
true,
)
.unwrap_err();
assert!(err.to_string().contains("already used"), "{err}");
}
#[test]
fn concurrent_privileged_executions_allow_at_most_one() {
let root = tempdir().unwrap().keep();
let store = PlanStore::with_dir(tempdir().unwrap().keep());
let approvals = ApprovalLedger::with_dir(tempdir().unwrap().keep());
let uid = effective_uid();
let mut plan = sealed(
"plan-concurrent",
PlanKind::General,
vec![SystemAction::History],
"d",
&root,
uid,
);
store.save(&mut plan).unwrap();
let digest = plan.digest.clone();
let id = plan.id.clone();
let handles: Vec<_> = (0..8)
.map(|_| {
let root = root.clone();
let store = store.clone();
let approvals = approvals.clone();
let id = id.clone();
let digest = digest.clone();
std::thread::spawn(move || {
let exec = make_test_exec(&root);
execute_plan_privileged(
&exec, &root, &store, &approvals, &id, &digest, uid, true,
)
.is_ok()
})
})
.collect();
let successes = handles
.into_iter()
.map(|h| h.join().expect("execution thread panicked"))
.filter(|won| *won)
.count();
assert_eq!(successes, 1, "exactly one execution may proceed");
}
#[test]
fn wrong_caller_root_and_expired_plans_are_rejected() {
let root = tempdir().unwrap();
let other_root = tempdir().unwrap();
let exec = make_test_exec(root.path());
let store = PlanStore::with_dir(tempdir().unwrap().keep());
let approvals = ApprovalLedger::with_dir(tempdir().unwrap().keep());
let uid = effective_uid();
let mut plan = sealed(
"plan-guard",
PlanKind::General,
vec![SystemAction::History],
"d",
root.path(),
uid,
);
store.save(&mut plan).unwrap();
let err = execute_plan_privileged(
&exec,
root.path(),
&store,
&approvals,
"plan-guard",
&plan.digest,
uid.wrapping_add(4242),
true,
)
.unwrap_err();
assert!(
err.to_string().contains("cannot be executed by uid"),
"{err}"
);
let err = execute_plan_privileged(
&exec,
other_root.path(),
&store,
&approvals,
"plan-guard",
&plan.digest,
uid,
true,
)
.unwrap_err();
assert!(err.to_string().contains("target root mismatch"), "{err}");
let mut expired = sealed(
"plan-expired",
PlanKind::General,
vec![SystemAction::History],
"d",
root.path(),
uid,
);
expired.expires_unix = 1;
seal_plan(&mut expired);
store.save(&mut expired).unwrap();
let err = execute_plan_privileged(
&exec,
root.path(),
&store,
&approvals,
"plan-expired",
&expired.digest,
uid,
true,
)
.unwrap_err();
assert!(err.to_string().contains("expired"), "{err}");
assert_eq!(ledger_entries(&approvals), 0);
}
#[test]
fn an_interrupted_operation_is_reconciled_and_cannot_be_retried() {
let root = tempdir().unwrap();
let exec = make_test_exec(root.path());
let store = PlanStore::with_dir(tempdir().unwrap().keep());
let approvals = ApprovalLedger::with_dir(tempdir().unwrap().keep());
let uid = effective_uid();
let mut plan = sealed(
"plan-interrupted",
PlanKind::General,
vec![SystemAction::History],
"d",
root.path(),
uid,
);
store.save(&mut plan).unwrap();
// Simulate a crash after claiming but before finishing.
approvals
.claim(
&plan.integrity,
&plan.id,
&plan.digest,
uid,
&plan.target_root,
plan.expires_unix,
plan.actions.len(),
)
.unwrap();
assert_eq!(approvals.reconcile_interrupted().unwrap(), 1);
assert_eq!(
approvals.get(&plan.integrity).unwrap().unwrap().status,
"interrupted"
);
let err = execute_plan_privileged(
&exec,
root.path(),
&store,
&approvals,
&plan.id,
&plan.digest,
uid,
true,
)
.unwrap_err();
assert!(err.to_string().contains("already used"), "{err}");
}
#[test]
fn stale_effects_between_validation_and_execution_abort_the_transaction() {
let root = tempdir().unwrap();
let uid = effective_uid();
let reviewed = parse_emerge_pretend(VIM_PRETEND);
let changed = parse_emerge_pretend(WGET_PRETEND);
let runner = SequenceRunner {
responses: std::sync::Mutex::new(vec![
command_out(VIM_PRETEND, true),
command_out(WGET_PRETEND, true),
]),
fallback: command_out(WGET_PRETEND, true),
};
let exec = make_exec_with_runner(root.path(), Box::new(runner));
let store = PlanStore::with_dir(tempdir().unwrap().keep());
let approvals = ApprovalLedger::with_dir(tempdir().unwrap().keep());
let mut plan = portage_install_plan(
"plan-drift",
SystemAction::InstallPackage {
atom: "app-editors/vim".into(),
binary: None,
},
reviewed,
root.path(),
uid,
);
store.save(&mut plan).unwrap();
let digest = plan.digest.clone();
let err = execute_plan_privileged(
&exec,
root.path(),
&store,
&approvals,
"plan-drift",
&digest,
uid,
true,
)
.unwrap_err();
assert!(err.to_string().contains("stale plan"), "{err}");
let log = transaction::read(root.path()).unwrap();
assert_eq!(log.records.len(), 1);
assert!(
log.records[0].result.starts_with("stale plan"),
"{}",
log.records[0].result
);
assert!(!changed.effects.is_empty());
}
#[test]
fn effect_resolution_failure_after_transaction_begin_is_terminal() {
let root = tempdir().unwrap();
let uid = effective_uid();
let reviewed = parse_emerge_pretend(VIM_PRETEND);
let runner = SequenceRunner {
responses: std::sync::Mutex::new(vec![
command_out(VIM_PRETEND, true),
command_out("not valid emerge output\n", true),
]),
fallback: command_out("not valid emerge output\n", true),
};
let exec = make_exec_with_runner(root.path(), Box::new(runner));
let store = PlanStore::with_dir(tempdir().unwrap().keep());
let approvals = ApprovalLedger::with_dir(tempdir().unwrap().keep());
let mut plan = portage_install_plan(
"plan-resolve-fail",
SystemAction::InstallPackage {
atom: "app-editors/vim".into(),
binary: None,
},
reviewed,
root.path(),
uid,
);
store.save(&mut plan).unwrap();
let digest = plan.digest.clone();
let err = execute_plan_privileged(
&exec,
root.path(),
&store,
&approvals,
"plan-resolve-fail",
&digest,
uid,
true,
)
.unwrap_err();
assert!(
err.to_string().contains("effect resolution failed"),
"{err}"
);
let log = transaction::read(root.path()).unwrap();
assert_eq!(log.records.len(), 1);
assert!(
log.records[0].result.contains("effect resolution failed"),
"{}",
log.records[0].result
);
assert!(
approvals
.get(&plan.integrity)
.unwrap()
.is_some_and(|r| r.status == "failed"),
"the approval must reach a terminal failed status"
);
}
struct FailFlatpakRunner;
impl phoebus_executor::command::ProcessRunner for FailFlatpakRunner {
fn execute(
&self,
spec: &phoebus_executor::command::CommandSpec,
) -> Result<phoebus_executor::command::CommandOutput> {
// The target is chrooted, so the real program is `chroot` and the
// wrapped tool appears in the arguments.
if spec.program == "flatpak" || spec.args.iter().any(|a| a == "flatpak") {
return Err(ExecError::operation("test", "flatpak", "flatpak exploded"));
}
Ok(command_out("ok\n", true))
}
}
#[test]
fn a_later_step_failure_after_an_earlier_success_is_recorded_truthfully() {
let root = tempdir().unwrap();
let uid = effective_uid();
let exec = make_exec_with_runner(root.path(), Box::new(FailFlatpakRunner));
let store = PlanStore::with_dir(tempdir().unwrap().keep());
let approvals = ApprovalLedger::with_dir(tempdir().unwrap().keep());
let mut plan = sealed(
"plan-two-step",
PlanKind::General,
vec![
SystemAction::EnableService {
name: "sshd".into(),
},
SystemAction::FlatpakInstall {
app_id: "org.example.App".into(),
},
],
"d",
root.path(),
uid,
);
plan.requires_root = true;
plan.step_effects = vec![ResolvedPlan::default(), ResolvedPlan::default()];
seal_plan(&mut plan);
store.save(&mut plan).unwrap();
let digest = plan.digest.clone();
let err = execute_plan_privileged(
&exec,
root.path(),
&store,
&approvals,
"plan-two-step",
&digest,
uid,
true,
)
.unwrap_err();
assert!(err.to_string().contains("action failed"), "{err}");
let log = transaction::read(root.path()).unwrap();
assert_eq!(log.records.len(), 1);
assert!(
log.records[0].result.starts_with("failed"),
"{}",
log.records[0].result
);
let (done, failed, _) = log.records[0].outcome_counts();
assert_eq!(done, 1, "the earlier step completed");
assert_eq!(failed, 1, "the later step failed");
}
}

View file

@ -180,14 +180,43 @@ fn invalid_appimage_hash_via_json_fails_closed() {
}
#[test]
fn a_mutating_action_without_root_is_refused_before_any_command() {
fn a_system_wide_preference_without_root_is_refused_before_any_command() {
if effective_uid_is_root() {
return;
}
let root = tempfile::tempdir().expect("temp root");
let personal = tempfile::tempdir().expect("personal dir");
let mutating = sys()
.arg("--root")
.arg(root.path())
.env("PHOEBUS_PERSONAL_DIR", personal.path())
.args([
"--legacy",
"--action",
r#"{"action":"set_package_preference","name":"firefox","backend":"flatpak","system_wide":true}"#,
])
.output()
.expect("run sys");
assert!(!mutating.status.success());
assert!(String::from_utf8_lossy(&mutating.stderr).contains("root"));
// A privileged system-wide change must never write `/etc`.
assert!(!root
.path()
.join("etc/phoebus/package-preferences.toml")
.exists());
}
#[test]
fn a_personal_preference_is_saved_by_a_normal_account_outside_etc() {
if effective_uid_is_root() {
return;
}
let root = tempfile::tempdir().expect("temp root");
let personal = tempfile::tempdir().expect("personal dir");
let out = sys()
.arg("--root")
.arg(root.path())
.env("PHOEBUS_PERSONAL_DIR", personal.path())
.args([
"--legacy",
"--action",
@ -195,8 +224,25 @@ fn a_mutating_action_without_root_is_refused_before_any_command() {
])
.output()
.expect("run sys");
assert!(!mutating.status.success());
assert!(String::from_utf8_lossy(&mutating.stderr).contains("root"));
assert!(
out.status.success(),
"personal preference must succeed: {}",
String::from_utf8_lossy(&out.stderr)
);
// It is stored in the user's own 0600 config, never in root-owned /etc.
let saved = personal
.path()
.join(".config/phoebus/package-preferences.toml");
assert!(saved.is_file(), "expected {}", saved.display());
let text = std::fs::read_to_string(&saved).unwrap();
assert!(
text.contains("firefox") && text.contains("flatpak"),
"{text}"
);
assert!(!root
.path()
.join("etc/phoebus/package-preferences.toml")
.exists());
}
#[test]

View file

@ -786,14 +786,26 @@ ShellRoot {
PhoebusButton {
label: "Snooze 1h"
onClicked: {
AssistantBridge.snoozeAlerts(3600, () => refreshStatus());
AssistantBridge.snoozeAlerts(3600, reply => {
if (reply.ok)
shell.statusText = "Alerts snoozed for 1 hour.";
else
shell.statusText = "Could not save snooze: " + (reply.error || "unknown error");
refreshStatus();
});
}
}
PhoebusButton {
label: "Dismiss"
onClicked: {
AssistantBridge.dismissAlert(modelData.fingerprint, () => refreshStatus());
AssistantBridge.dismissAlert(modelData.fingerprint, reply => {
if (reply.ok)
shell.statusText = "Alert dismissed.";
else
shell.statusText = "Could not save dismissal: " + (reply.error || "unknown error");
refreshStatus();
});
}
}
}
@ -828,10 +840,22 @@ ShellRoot {
Label { text: "Profile Strategy:"; color: Theme.muted }
ComboBox {
id: profileCombo
model: ["Balanced", "FastInstallation", "NativeIntegration", "ApplicationIsolation"]
currentIndex: 0
// These are the exact serde values the backend stores.
model: ["balanced", "fast_installation", "native_integration", "application_isolation"]
currentIndex: {
const current = shell.preferences ? shell.preferences.profile : "balanced";
const idx = model.indexOf(current);
return idx >= 0 ? idx : 0;
}
}
}
Label {
text: "Personal preferences are saved to your own account, not the system."
color: Theme.muted
font.pixelSize: 11
wrapMode: Text.Wrap
}
PhoebusButton {
label: "Save Preferences"
@ -840,7 +864,11 @@ ShellRoot {
if (shell.preferences) {
shell.preferences.profile = profileCombo.currentText;
AssistantBridge.setPreferences(shell.preferences, reply => {
if (reply.ok) shell.statusText = "Preferences saved.";
// Never report success when the write failed.
if (reply.ok)
shell.statusText = "Preferences saved.";
else
shell.statusText = "Could not save preferences: " + (reply.error || "unknown error");
});
}
}

View file

@ -85,8 +85,21 @@ json_nonzero bad-appimage-hash "SHA-256" '{"action":"appimage_acquire","name":"x
json_nonzero ebuild-traversal "invalid" '{"action":"custom_ebuild_prepare","atom":"../../x","version":"1","rationale":"r","ebuild":"EAPI=8"}'
# --- Offline / model-free behaviour ---------------------------------------
# A system-wide policy change is privileged; a personal preference is not.
if [[ "$(id -u)" -ne 0 ]]; then
run_expect_nonzero nonroot-mutation "root" --legacy --action '{"action":"set_package_preference","name":"firefox","backend":"flatpak"}'
run_expect_nonzero nonroot-systemwide "root" --legacy --action '{"action":"set_package_preference","name":"firefox","backend":"flatpak","system_wide":true}'
fi
# A normal account can save a personal preference to its own storage.
PersonalDir="$WORK/personal"
mkdir -p "$PersonalDir"
if PHOEBUS_PERSONAL_DIR="$PersonalDir" "$SYS" --legacy --action '{"action":"set_package_preference","name":"firefox","backend":"flatpak"}' >"$WORK/personal-pref.out" 2>"$WORK/personal-pref.err"; then
if [[ -f "$PersonalDir/.config/phoebus/package-preferences.toml" ]]; then
report personal-preference PASS "saved to user config"
else
report personal-preference FAIL "reported success without writing user config"
fi
else
report personal-preference FAIL "rc=$? stderr=$(head -c 160 "$WORK/personal-pref.err" | tr '\n' ' ')"
fi
# With no provider, `ask` must fall back deterministically and exit nonzero.
PHOEBUS_AI_PROVIDER="" PHOEBUS_AI_BACKEND=direct \