fix(admin): recompute canonical digest at the privileged boundary, stabilize the approval identity, and own personal writes
Some checks are pending
ci / test (push) Waiting to run

This commit is contained in:
Phoebus 2026-09-24 19:48:27 -07:00
parent 0be301009b
commit 34f5311d37
12 changed files with 1657 additions and 326 deletions

View file

@ -103,7 +103,7 @@ The only crate that runs privileged commands.
- `orchestrate` — `Installer` runs the plan stages and stops on first failure. - `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. 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. - `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. - `approval` — broker-controlled approval ledger (`/var/lib/phoebus/approvals`, 0700/0600, ADR 0014). Records are keyed by a stable approval identity (plan id, canonical approval digest, initiating uid, target root), so at most one execution may run, replay is refused even after the user deletes every file in their own plan directory, a presentation-only edit cannot mint a fresh record, and a replacement under the same identifier is refused before the ledger is touched. Claims carry the owning process identity; terminal statuses are published atomically once and are immutable, and recovery only marks an owner that is provably gone. The approving digest travels across authentication independently of the plan file (`--approval-digest`) and is compared to a canonical digest the broker recomputes from the executable actions and reviewed effects; the initiating identity is derived from `PKEXEC_UID`.
- `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. - `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. - `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. - `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.

View file

@ -3,6 +3,40 @@
All notable changes are recorded here. The authoritative history is `git log`; All notable changes are recorded here. The authoritative history is `git log`;
this file is the curated, human-readable summary. this file is the curated, human-readable summary.
## 2026-09-25 — Adversarial approval-boundary hardening (canonical digest, stable identity, recovery)
- **Canonical approval digest recomputed at the privileged boundary.** The
broker no longer compares the independently supplied digest with the
user-owned plan's stored digest. It independently re-derives the canonical
digest from the exact executable actions, candidate and reviewed material
effects (`compute_plan_digest`) and requires it to equal both the stored
digest and the supplied `--approval-digest`. The integrity seal is treated
only as a self-consistency check, never as authentication. This closes the
"retain the approved digest, swap an action and its effects, recompute the
seal" substitution for every plan kind (Install, LegacyInstall, Removal,
General, Undo).
- **Stable approval identity for replay protection.** The ledger and `.claim`
marker are keyed by
`approval_key(plan_id, canonical_digest, initiator_uid, target_root)` instead
of the integrity seal. Editing only the summary (or other presentation
fields) and resealing can no longer mint a fresh ledger entry for an
already-consumed approval, while a newly reviewed identical operation with a
new random plan ID is still allowed.
- **Live-safe, monotonic crash recovery.** Claims record the owning process
(`pid`, `/proc/<pid>/stat` start time, kernel boot id). Terminal statuses are
published exactly once by an atomic hard link into `<key>.terminal` and can
never be overwritten or changed to another terminal status.
`reconcile_interrupted` only marks a record interrupted when its owner is
provably gone, so a second broker starting alongside a live operation cannot
mislabel it, and reconciliation cannot race a real finish.
- **Personal settings are owned by the initiating user.** `UserStorage` creates
the config/state path component by component beneath the resolved home,
rejecting symlinks and non-directories. When the write is elevated
(effective root on behalf of a non-root user) the created paths are chowned
to the initiating user's uid/gid; a non-root process acting for a different
user is refused rather than writing a root-owned file. No path outside the
home is ever chowned. Proactive state now goes through the same path.
## 2026-09-25 — Approval ledger, user-owned settings, and reviewed-effect execution ## 2026-09-25 — Approval ledger, user-owned settings, and reviewed-effect execution
- **Broker-controlled approval ledger (ADR 0014, `phoebus-installer::approval`):** - **Broker-controlled approval ledger (ADR 0014, `phoebus-installer::approval`):**

View file

@ -3,65 +3,62 @@
Rolling note between work sessions. **Update this file before you finish**, then 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. commit it. It should be short and current; use `git log` for detail.
- **Last updated:** this session (2026-09-25), the three remaining - **Last updated:** this session (2026-09-25), adversarial hardening of the
administration defects from the latest review: (1) bind privileged execution privileged approval boundary: (1) the broker recomputes the canonical
to the actual approved plan via a broker-controlled approval ledger, (2) make approval digest for every plan kind, (2) the ledger uses a stable approval
personal settings work from a normal desktop account in user-owned storage, and identity instead of the editable integrity seal, (3) crash recovery is
(3) carry reviewed effects through execution and finish every started live-safe and terminal transitions are atomic/monotonic, and (4) personal
transaction truthfully. See ADR 0014. writes are owned by the initiating user. See ADR 0014. Supersedes the
`0be3010` approval design; that commit's UX/docs changes are preserved.
- **Current focus:** - **Current focus:**
1. **Approval ledger (`phoebus_installer::approval`, ADR 0014):** 1. **Canonical digest at the privileged boundary (`service::validate_prepared_plan`):**
- The plan's integrity seal (actions, per-step effects, candidate, target - Independently re-derives `compute_plan_digest(actions, candidate,
root, initiating uid, expiry) is the binding fingerprint and the `O_EXCL` effects)` and requires it to equal both `plan.digest` and the supplied
consumption key in a **root-owned** ledger (`/var/lib/phoebus/approvals`, `--approval-digest`. Covers Install, LegacyInstall, Removal, General and
0700 / 0600). Undo. The stored `integrity` seal is only a self-consistency check and is
- `execute_plan_privileged` now takes the reviewed digest and passes it to never treated as authentication.
`validate_prepared_plan(..., Some(expected_digest), ...)`. The digest - Closes the "retain the approved digest, swap an action and effects,
travels across authentication independently of the plan file recompute the seal" attack; rejected before any command runs or approval
(`sys --broker --execute-plan <id> --plan-uid <uid> --approval-digest is consumed.
<sha256> --root <root>`). 2. **Stable approval identity (`phoebus_installer::approval`, ADR 0014):**
- Replacement under the same identifier is refused even when resealed with a - Ledger + `.claim` key = `approval_key(plan_id, canonical_digest,
valid checksum; replay is refused even after the user deletes every file initiator_uid, target_root)`. Presentation fields (summary, rationale,
in their own plan directory; concurrent submissions allow one execution; verification) are excluded, so editing them and resealing cannot mint a
a crash leaves a reconciled `interrupted` record. `reconcile_interrupted` fresh record for a consumed approval; a newly reviewed identical
runs at broker startup. operation with a new plan id is allowed.
- The initiator is derived from `PKEXEC_UID` - Claims record the owning process (`pid`, `/proc/<pid>/stat` start ticks,
(`approval::broker_initiator_uid`); `--plan-uid` is untrusted input. boot id). Terminal status is published once via an atomic hard link into
Authentication precedes the ledger claim, so refusal consumes nothing. `<key>.terminal` and is immutable. `reconcile_interrupted` only marks a
2. **User-owned personal settings (`phoebus_executor::personal`):** record interrupted when the owner is provably gone, so a live operation
- `UserStorage` resolves the initiating user (`PHOEBUS_UID` → `SUDO_UID` → (or a second broker starting concurrently) is never mislabelled, and it
`PKEXEC_UID` → effective uid; home from `/etc/passwd`) and writes 0600 in cannot race a real `finish`.
0700 atomically. 3. **Personal write ownership (`phoebus_executor::personal`):**
- Personal preferences → `~/.config/phoebus/package-preferences.toml`; - `write_private` creates the config/state path one component at a time
proactive snooze/dismiss → `~/.local/state/phoebus/proactive-state.toml` under the resolved home, rejecting symlinks and non-directories.
(bounded). System defaults remain `/etc/phoebus/...`, changed only via - Elevated writes (effective root on behalf of a non-root user) chown the
`set_package_preference { system_wide: true }` through the broker. created paths to the initiating user's uid/gid (via a standard-library
- `chooser::load_preferences` merges system < personal (personal wins, `chown` behind an injectable `OwnerFixer`). A non-root process acting for
per-app union); proactive reads the legacy root-owned file only as a a different user is refused. Proactive state now routes through the same
migration fallback. Bridge failures are surfaced; the QML notifies on path.
failure and the profile combo now uses the exact serde values. 4. **Reviewed effects + terminal transactions** (`service::execute_prepared`,
3. **Reviewed effects + terminal transactions (`service::execute_prepared`):** unchanged this session): reviewed per-step effects are carried forward and
- Reviewed per-step effects are carried forward; `resolve_effects` is now freshly resolved effects are evidence compared with
only evidence compared with `phoebus_core::effects::approval_holds` `phoebus_core::effects::approval_holds`; every path after
(earlier-step-introduced targets are the only allowance). A material `transaction::begin` reaches a terminal result.
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):** - **Last verified (this session):**
- `cargo fmt --all -- --check` clean. - `cargo fmt --all -- --check` clean.
- `cargo test --workspace`: 582 passed, 0 failed, including new privileged - `cargo test --workspace`: 598 passed, 0 failed. New adversarial tests:
entry-point regressions: replacement during authentication, recomputed swapped-action-with-retained-digest for every plan kind; replay rejected
checksum, deleted user plan+claim replay, concurrent execution, wrong after a summary edit / other presentation edits / recreating an identical
caller/root, expiry, interruption reconciliation, effect drift, effect plan under the original id; a newly reviewed identical operation with a new
resolution failure after `begin`, and later-step failure after an earlier id allowed; live claim not reconciled while an abandoned one is;
success. reconcile-vs-finish race yields one immutable terminal; terminal status not
- `cargo clippy --workspace --all-targets` runs (exit 0; only the pre-existing overwritten; elevated personal write chowns to the initiating user; a
symlinked component is refused; a non-root cross-uid personal write is
refused (unit and CLI).
- `cargo clippy --workspace --all-targets` exits 0 (only the pre-existing
`result_large_err`, one arg-count and one `DiskPhase` lints remain). `result_large_err`, one arg-count and one `DiskPhase` lints remain).
- Static `sys` (`crt-static`) builds (`static-pie`, 6.4 MiB). - `cargo build --release -p phoebus-installer` clean.
- 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):** - **Not yet verified this session (BLOCKED):**
- Installed-VM journey and the 12-step acceptance list. The existing - Installed-VM journey and the 12-step acceptance list. The existing
disposable installed disk (`/var/tmp/phoebus-vm/disks/test-disk.qcow2`) disposable installed disk (`/var/tmp/phoebus-vm/disks/test-disk.qcow2`)
@ -70,8 +67,10 @@ commit it. It should be short and current; use `git log` for detail.
`/home/dominic/vmlab/serve/luks.pw`) is rejected, and no other credential is `/home/dominic/vmlab/serve/luks.pw`) is rejected, and no other credential is
available. Do not guess or brute-force. available. Do not guess or brute-force.
- No AI provider credential is present; do not invent one. - No AI provider credential is present; do not invent one.
- A fresh disposable VM install would verify the installed journey but takes - A real privileged `chown` (running as root) could not be exercised in this
~2 h (disk space is tight, 24 GiB free), so it was not attempted in this pass. unprivileged host; the ownership logic is verified through the injectable
fixer seam and the cross-uid refusal test. A root-run confirmation is a
follow-up.
- **Public repo:** <https://git.phoebus.club/phoebus/phoebus_os> - **Public repo:** <https://git.phoebus.club/phoebus/phoebus_os>
(remote `origin`, SSH port 2222). (remote `origin`, SSH port 2222).

View file

@ -86,7 +86,11 @@ still not VM-verified.
| Installed assistant (`sys ask`) | yes | yes | fixture path only (no live call) | n/a | | Installed assistant (`sys ask`) | yes | yes | fixture path only (no live call) | n/a |
| Resolved package effects + approval binding (carried through execution) | yes | yes (empty vs unestablished; drift + prior-step allowance) | 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 | | Privileged approval ledger (replacement/replay/concurrency/interruption) | yes | yes (privileged entry point) | no | n/a |
| Canonical digest recomputed at the privileged boundary (all plan kinds) | yes | yes (adversarial: swapped action resealed, every kind) | no | n/a |
| Stable approval identity (replay after presentation edit/reseal) | yes | yes (summary/other fields/identical id/concurrent/new-id) | no | n/a |
| Live-safe monotonic recovery (owner liveness, immutable terminal) | yes | yes (live vs abandoned, reconcile/finish race) | no | n/a |
| Personal preferences + alert state (user-owned, system-default precedence) | yes | yes (save/reload/isolation/precedence/failure) | no | no | | Personal preferences + alert state (user-owned, system-default precedence) | yes | yes (save/reload/isolation/precedence/failure) | no | no |
| Personal write ownership (elevated chown, symlink refusal, cross-uid refusal) | yes | yes (ownership-fixer seam + CLI refusal) | no | no |
| Transaction log (outcomes, protective snapshots) | yes | yes | no | no | | Transaction log (outcomes, protective snapshots) | yes | yes | no | no |
| Flatpak/Nix bounded typed actions | yes | yes | no | no | | Flatpak/Nix bounded typed actions | yes | yes | no | no |
| Shared hardware-aware source selection (all lanes) | yes | yes | no | no | | Shared hardware-aware source selection (all lanes) | yes | yes | no | no |

View file

@ -276,8 +276,10 @@ a stdio JSON-RPC server speaking newline-delimited JSON messages:
package source profiles, project environment tool mappings, and package source profiles, project environment tool mappings, and
keep-existing-source pins. Personal preferences are stored 0600/0700 under the keep-existing-source pins. Personal preferences are stored 0600/0700 under the
user's own config (`~/.config/phoebus/package-preferences.toml`) without user's own config (`~/.config/phoebus/package-preferences.toml`) without
elevation; system defaults stay root-owned. A failed write is reported as an elevation; system defaults stay root-owned. When the write runs elevated the
error, never as "saved". created paths are chowned to the initiating user, a non-root process acting
for a different user is refused, and symlinked path components are rejected.
A failed write is reported as an error, never as "saved".
- `history`, `undo`: queries transaction logs and initiates recovery. - `history`, `undo`: queries transaction logs and initiates recovery.
Zero business logic lives in the GUI: equivalent CLI and GUI requests produce Zero business logic lives in the GUI: equivalent CLI and GUI requests produce
@ -289,30 +291,38 @@ 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 (`/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 128-bit unpredictable identifier). The plan is sealed with an integrity digest
over the reviewed fields, the target root and the initiating uid. That seal is 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, only a self-consistency check: the owner of the plan file can recompute it, so
candidate, target root, initiating uid and expiry. it is never treated as authentication.
`execute_plan` validates the plan before elevation and again — authoritatively — `execute_plan` validates the plan before elevation and again — authoritatively —
inside the privileged broker (`sys --broker --execute-plan <id> --plan-uid <uid> inside the privileged broker (`sys --broker --execute-plan <id> --plan-uid <uid>
--approval-digest <sha256> --root <root>`). The broker: --approval-digest <sha256> --root <root>`). The broker:
- **independently recomputes the canonical approval digest** from the exact
executable actions, candidate and reviewed material effects, and requires it
to equal both the digest stored in the plan and the independently supplied
`--approval-digest`. Retaining an approved digest while swapping an action and
resealing is therefore rejected for every plan kind (Install, LegacyInstall,
Removal, General, Undo) before any command runs;
- carries the digest the review card showed the user across authentication - carries the digest the review card showed the user across authentication
independently of the plan file, and refuses a plan whose recomputed digest independently of the plan file, so a replacement plan under the same
does not match it — so a replacement plan under the same identifier is identifier is rejected even when it is resealed with a valid, self-consistent
rejected even when it is resealed with a valid, self-consistent checksum; checksum;
- re-derives the integrity seal from the plan's own contents (it never trusts
two supplied digest strings);
- rejects expired, modified, malformed, wrong-root or wrong-uid plans; - rejects expired, modified, malformed, wrong-root or wrong-uid plans;
- derives the initiating identity from the authenticated caller context - derives the initiating identity from the authenticated caller context
(`PKEXEC_UID`), treating `--plan-uid` as untrusted input; (`PKEXEC_UID`), treating `--plan-uid` as untrusted input;
- revalidates the current package/removal state after authentication, and again - revalidates the current package/removal state after authentication, and again
action-by-action at the execution boundary against the reviewed effects; action-by-action at the execution boundary against the reviewed effects;
- anchors consumption in a **root-owned approval ledger** - anchors consumption in a **root-owned approval ledger**
(`/var/lib/phoebus/approvals`, 0700 / 0600, ADR 0014). The fingerprint is (`/var/lib/phoebus/approvals`, 0700 / 0600, ADR 0014), keyed by a stable
claimed with `O_EXCL`, so at most one execution may run under concurrent approval identity (plan id, canonical digest, initiating uid, target root).
submissions, and a retry is refused even after the user deletes every file in The key is claimed with `O_EXCL`, so at most one execution may run under
their own plan directory. A plan left `in_progress` by a crash is reconciled concurrent submissions; a retry is refused even after the user deletes every
to `interrupted` at broker startup; a consumed approval is retained. file in their own plan directory; and editing only presentation fields
(summary, rationale, verification) and resealing cannot mint a fresh record.
A newly reviewed identical operation has a new plan id and is allowed. Each
claim records its owning process; terminal statuses are published atomically
once, are immutable, and recovery only marks an owner that is provably gone;
- treats the plan file and its contents as untrusted input, resolving storage - treats the plan file and its contents as untrusted input, resolving storage
from the uid rather than an arbitrary path. from the uid rather than an arbitrary path.

View file

@ -5,45 +5,79 @@
## Context ## Context
Two administration defects remained after the shared-service hardening in Several administration defects remained after the shared-service hardening in
commit `3b84b8c`: commits `3b84b8c` and `0be3010`:
1. **Approval was bound to a user-controlled plan file.** The privileged broker 1. **The privileged boundary did not recompute the canonical digest.** For
(`sys --broker --execute-plan <id> --plan-uid <uid>`) loaded the plan from the General, Undo and Removal plans it compared the independently supplied digest
reviewing user's directory and re-derived a self-consistency seal from the with the `digest` field stored in the (user-owned) plan file, without
plan's own contents. Because the seal is recomputable, a replacement plan re-deriving it from the executable actions and reviewed effects. A plan could
under the same identifier passed. The consumption marker also lived in the therefore retain its previously approved digest, swap an action and its
same user-writable directory, so deleting it allowed a replay. effects, recompute the self-consistency seal, and pass.
2. **Personal settings wrote to protected system paths.** The desktop bridge ran 2. **Replay protection was keyed by an editable seal.** The ledger keyed records
by the plan's integrity seal, which includes presentation fields. Editing the
summary and resealing produced a new key for the same approved digest, so the
action could run twice.
3. **Crash reconciliation could mislabel a live operation.** `reconcile_interrupted`
marked every `in_progress` record interrupted whenever another broker started,
and could race a real `finish`.
4. **Personal settings could become root-owned.** `UserStorage::write_private`
created directories and files with the process's effective uid, so a `sudo`
invocation wrote root-owned files into the user's home.
5. **Personal settings wrote to protected system paths.** The desktop bridge ran
unprivileged but wrote package preferences under `/etc/phoebus/` and unprivileged but wrote package preferences under `/etc/phoebus/` and
proactive snooze/dismiss state under `/var/lib/phoebus/`, which a normal proactive snooze/dismiss state under `/var/lib/phoebus/`.
account cannot write.
A self-consistent checksum is not proof of human approval, and user-writable A self-consistent checksum is not proof of human approval, and user-writable
files cannot anchor consumption. files cannot anchor consumption. A presentation-only edit must not be able to
mint a new approval.
## Decision ## Decision
### Approval is anchored in a broker-controlled ledger ### The broker recomputes the canonical digest for every plan kind
The privileged boundary independently derives the canonical approval digest from
the exact executable `actions`, the `candidate` and the reviewed material
`effects` (`compute_plan_digest`, the same function the planner used). It must
equal both the plan's stored digest and the independently supplied
`--approval-digest`. The integrity seal stored beside the plan is a
self-consistency check the owner can recompute, so it is never treated as
authentication. This binds Install, LegacyInstall, Removal, General and Undo
plans alike; retaining an approved digest while swapping an action and resealing
is rejected before any command runs or approval is consumed.
### Consumption is anchored by a stable approval identity
A root-owned approval ledger (`/var/lib/phoebus/approvals`, 0700; records 0600) 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 records every approval the broker consumes. A record is keyed by
seal — a fingerprint over the exact actions, per-step effects, candidate, target `approval_key(plan_id, canonical_digest, initiator_uid, canonical_target_root)`
root, initiating uid and expiry — and is created with `O_EXCL` so: and published with `O_EXCL` so:
- at most one execution may run under concurrent submissions; - at most one execution may run under concurrent submissions;
- replay is refused even when the user deletes or recreates every file in their - replay is refused even when the user deletes or recreates every file in their
own plan directory (the root-owned record remains); own plan directory (the root-owned record remains);
- a replacement plan under the same identifier has a different fingerprint and - editing presentation fields (summary, recommendation, rationale, verification)
is refused before the ledger is touched. and resealing cannot mint a fresh entry for an already-consumed approval;
- a replacement plan under the same identifier has a different digest and is
refused before the ledger is touched;
- a newly reviewed identical operation has a new random plan ID and is allowed.
The plan digest shown on the review card is carried across authentication The digest shown on the review card is carried across authentication
independently of the plan file (`--approval-digest`) and compared in the broker. independently of the plan file (`--approval-digest`) and compared in the broker.
The broker derives the initiating identity from the authenticated caller context The broker derives the initiating identity from the authenticated caller context
(`PKEXEC_UID`), not from the untrusted `--plan-uid` alone. A plan left (`PKEXEC_UID`), not from the untrusted `--plan-uid` alone. The user-owned claim
`in_progress` by a crash is reconciled to `interrupted` at broker startup, and a marker remains as an optimistic early guard but is not the security anchor.
retry never repeats a consumed mutation. The user-owned claim marker remains as
an optimistic early guard but is no longer the security anchor. ### Terminal transitions are atomic, durable and monotonic
Each claim records the owning process identity (`pid`, `/proc/<pid>/stat` start
time and the kernel boot id). The terminal status is published exactly once by
atomically hard-linking a fully written record into `<key>.terminal`; the link
fails if a terminal already exists, so a terminal status can never be overwritten
or changed to another terminal status. Recovery only marks a record interrupted
when its owner is provably gone (the pid is absent, the pid was reused, or the
machine rebooted), so a live executor — including a second broker starting
concurrently with a live operation — is never mistaken for a crashed one.
### Personal state is user-owned; system policy is privileged ### Personal state is user-owned; system policy is privileged
@ -58,6 +92,13 @@ an optimistic early guard but is no longer the security anchor.
`PKEXEC_UID` → the effective uid, and the home directory from `/etc/passwd` `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 (never `$HOME`, which `sudo` rewrites), so the CLI and GUI resolve the same
user's preferences. user's preferences.
- Ownership: directories and files are created component by component beneath the
resolved home, rejecting symlinks and non-directories. When the write runs
elevated (effective root on behalf of a non-root user), the created paths are
chowned to the *initiating* user's uid/gid so the setting stays readable and
replaceable by them; `sys` refuses to write user data as a non-root process
acting for a different user. No path outside the resolved home is ever
chowned.
Precedence: personal explicit choices win; system defaults apply to anything the 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 user has not overridden. A failed write is reported as a failure; the GUI never
@ -73,8 +114,13 @@ same plan are accepted.
## Consequences ## Consequences
- Privileged execution is bound to an independently preserved approval and a - Privileged execution is bound to a canonical digest recomputed at the
root-owned consumption record; the plan file is untrusted input. boundary and to a root-owned consumption record; the plan file is untrusted
input, and a substituted-but-resealed plan is rejected before mutation.
- A presentation-only edit cannot produce a fresh approval record, while a newly
reviewed identical operation with a new plan ID is allowed.
- A crashed operation is recovered without ever mislabelling a live one, and a
terminal status is immutable.
- A normal desktop account can save personal preferences and dismiss alerts - A normal desktop account can save personal preferences and dismiss alerts
without elevation; system-wide policy stays authenticated. without elevation; system-wide policy stays authenticated.
- Every started transaction reaches a terminal result (`ok`, `failed`, - Every started transaction reaches a terminal result (`ok`, `failed`,
@ -87,9 +133,15 @@ same plan are accepted.
## Alternatives considered ## Alternatives considered
- **Trust the caller-supplied digest alone.** Rejected: a checksum is not proof - **Trust the plan's stored digest or integrity seal.** Rejected: the owner can
of human approval; a root-owned consumption record is required for replay recompute any unkeyed hash in a file they control; the canonical digest must be
resistance. re-derived from the executable actions and effects, and compared to an
independently supplied approval.
- **Key the ledger by the integrity seal.** Rejected: it includes presentation
fields, so a summary edit mints a new key and defeats replay protection.
- **Reconcile every `in_progress` record at startup.** Rejected: it mislabels
live concurrent operations and races a real finish. Owner liveness plus an
atomic, monotonic terminal publication is required.
- **A second `pkexec` to register the approval at review time.** Rejected as - **A second `pkexec` to register the approval at review time.** Rejected as
unnecessary: the digest carried across authentication plus the root-owned unnecessary: the digest carried across authentication plus the root-owned
ledger satisfies the properties without a second prompt. ledger satisfies the properties without a second prompt.

View file

@ -1200,7 +1200,8 @@ mod tests {
#[test] #[test]
fn personal_preferences_roundtrip_and_are_not_system_owned() { fn personal_preferences_roundtrip_and_are_not_system_owned() {
let base = tempfile::tempdir().unwrap(); let base = tempfile::tempdir().unwrap();
let storage = crate::personal::UserStorage::with_base(4242, base.path()); let storage =
crate::personal::UserStorage::with_base(crate::personal::effective_uid(), base.path());
let mut prefs = Preferences::default(); let mut prefs = Preferences::default();
prefs.per_app.insert("vlc".into(), Backend::Snap); prefs.per_app.insert("vlc".into(), Backend::Snap);
save_personal_preferences(&storage, &prefs).unwrap(); save_personal_preferences(&storage, &prefs).unwrap();

View file

@ -5,7 +5,7 @@
//! touching `/etc` or `/var/lib`, while system-wide defaults stay root-owned and //! touching `/etc` or `/var/lib`, while system-wide defaults stay root-owned and
//! are only changed through an authenticated typed action. //! are only changed through an authenticated typed action.
//! //!
//! Two problems are solved here: //! Three problems are solved here:
//! //!
//! 1. **Where** personal state lives: `<home>/.config/phoebus/` and //! 1. **Where** personal state lives: `<home>/.config/phoebus/` and
//! `<home>/.local/state/phoebus/`, each created 0700 and written 0600 //! `<home>/.local/state/phoebus/`, each created 0700 and written 0600
@ -16,9 +16,16 @@
//! the real/effective uid, and [`UserStorage::for_uid`] resolves that user's //! the real/effective uid, and [`UserStorage::for_uid`] resolves that user's
//! home from `/etc/passwd` rather than trusting `$HOME` (which `sudo` sets to //! home from `/etc/passwd` rather than trusting `$HOME` (which `sudo` sets to
//! root's). //! root's).
//! 3. **Ownership**: when the write runs elevated (effective root on behalf of a
//! non-root initiating user), the created directories and file are chowned
//! to the *initiating* user's uid/gid so the setting stays readable and
//! replaceable by that user. A non-root process that is not the initiating
//! user refuses to write. Paths are created component by component, reject
//! symlinks, and must stay within the resolved home, so a planted symlink
//! cannot redirect the write.
use std::io::Write; use std::io::Write;
use std::path::{Path, PathBuf}; use std::path::{Component, Path, PathBuf};
use crate::error::{ExecError, Result}; use crate::error::{ExecError, Result};
@ -60,13 +67,33 @@ pub fn effective_uid() -> u32 {
/// Look up a user's home directory from the passwd database. `$HOME` is not /// Look up a user's home directory from the passwd database. `$HOME` is not
/// trusted because `sudo`/`pkexec` rewrite it. /// trusted because `sudo`/`pkexec` rewrite it.
pub fn home_for_uid(uid: u32) -> Option<PathBuf> { pub fn home_for_uid(uid: u32) -> Option<PathBuf> {
passwd_entry(uid).map(|(_, home)| home)
}
/// The user's primary group id, from the passwd database.
pub fn primary_gid_for_uid(uid: u32) -> Option<u32> {
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 {
return fields[3].parse::<u32>().ok();
}
}
}
}
None
}
fn passwd_entry(uid: u32) -> Option<(u32, PathBuf)> {
let text = std::fs::read_to_string("/etc/passwd").ok()?; let text = std::fs::read_to_string("/etc/passwd").ok()?;
for line in text.lines() { for line in text.lines() {
let fields: Vec<&str> = line.split(':').collect(); let fields: Vec<&str> = line.split(':').collect();
if fields.len() >= 6 { if fields.len() >= 6 {
if let Ok(line_uid) = fields[2].parse::<u32>() { if let Ok(line_uid) = fields[2].parse::<u32>() {
if line_uid == uid && !fields[5].trim().is_empty() { if line_uid == uid && !fields[5].trim().is_empty() {
return Some(PathBuf::from(fields[5].trim())); return Some((line_uid, PathBuf::from(fields[5].trim())));
} }
} }
} }
@ -74,6 +101,55 @@ pub fn home_for_uid(uid: u32) -> Option<PathBuf> {
None None
} }
/// The identity that should own a user's personal files, plus the effective uid
/// of the writing process.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Ownership {
/// The initiating user that should own the files.
pub uid: u32,
/// The initiating user's primary gid (best effort; falls back to the uid).
pub gid: u32,
/// The effective uid of this process.
pub euid: u32,
}
impl Ownership {
pub fn for_uid(uid: u32) -> Self {
Self {
uid,
gid: primary_gid_for_uid(uid).unwrap_or(uid),
euid: effective_uid(),
}
}
/// A non-root process that is not the initiating user must not write user
/// data on their behalf.
pub fn may_write(self) -> bool {
self.euid == self.uid || self.euid == 0
}
/// Whether the created paths must be chowned to the initiating user. Only
/// root can do this.
pub fn needs_fix(self) -> bool {
self.euid == 0 && self.uid != 0
}
}
/// Chowns a freshly created path to the initiating user. Abstracted so the
/// ownership logic can be tested without requiring root.
pub trait OwnerFixer {
fn fix(&self, path: &Path, uid: u32, gid: u32) -> std::io::Result<()>;
}
/// The production fixer: `chown(2)` via the standard library.
pub struct RealOwnerFixer;
impl OwnerFixer for RealOwnerFixer {
fn fix(&self, path: &Path, uid: u32, gid: u32) -> std::io::Result<()> {
std::os::unix::fs::chown(path, Some(uid), Some(gid))
}
}
/// A resolved, user-owned storage location. /// A resolved, user-owned storage location.
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct UserStorage { pub struct UserStorage {
@ -136,14 +212,66 @@ impl UserStorage {
self.state_dir().join(name) self.state_dir().join(name)
} }
/// Atomically write a 0600 file inside the given (0700) directory. /// Atomically write a 0600 file inside the given (0700) directory, owned by
/// the initiating user.
pub fn write_private(&self, dir: &Path, file: &Path, bytes: &[u8]) -> Result<()> { 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))?; let ownership = Ownership::for_uid(self.uid);
#[cfg(unix)] self.write_private_as(dir, file, bytes, ownership, &RealOwnerFixer)
{ }
use std::os::unix::fs::PermissionsExt;
let _ = std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700)); /// Explicit-ownership variant, used by tests to exercise the elevated path
/// and the ownership fixer without requiring root.
pub(crate) fn write_private_as(
&self,
dir: &Path,
file: &Path,
bytes: &[u8],
ownership: Ownership,
fixer: &dyn OwnerFixer,
) -> Result<()> {
if !ownership.may_write() {
return Err(ExecError::operation(
"personal",
"write",
format!(
"refusing to write uid {} personal data as effective uid {}",
ownership.uid, ownership.euid
),
));
} }
// The file must live directly inside the target directory and both must
// be within the resolved base, so a caller cannot redirect the write.
if file.parent() != Some(dir) {
return Err(ExecError::operation(
"personal",
"write",
"the destination file is not inside the target directory",
));
}
if !self.is_within_base(dir) || !self.is_within_base(file) {
return Err(ExecError::operation(
"personal",
"write",
"refusing to write outside the user's own storage",
));
}
self.create_dir_chain(dir, ownership, fixer)?;
// After creating the chain, verify the canonical directory has not
// escaped the base through a symlink.
let base =
std::fs::canonicalize(&self.base).map_err(|e| ExecError::io(self.base.clone(), e))?;
let dir_canon =
std::fs::canonicalize(dir).map_err(|e| ExecError::io(dir.to_path_buf(), e))?;
if !dir_canon.starts_with(&base) {
return Err(ExecError::operation(
"personal",
"write",
"the destination directory resolves outside the user's storage (symlink?)",
));
}
let tmp = dir.join(format!(".{}.tmp", tmp_token())); let tmp = dir.join(format!(".{}.tmp", tmp_token()));
{ {
let mut opts = std::fs::OpenOptions::new(); let mut opts = std::fs::OpenOptions::new();
@ -159,15 +287,108 @@ impl UserStorage {
.and_then(|_| fh.sync_all()) .and_then(|_| fh.sync_all())
.map_err(|e| ExecError::io(tmp.clone(), e))?; .map_err(|e| ExecError::io(tmp.clone(), e))?;
} }
if ownership.needs_fix() {
fixer
.fix(&tmp, ownership.uid, ownership.gid)
.map_err(|e| ExecError::io(tmp.clone(), e))?;
}
std::fs::rename(&tmp, file).map_err(|e| { std::fs::rename(&tmp, file).map_err(|e| {
let _ = std::fs::remove_file(&tmp); let _ = std::fs::remove_file(&tmp);
ExecError::io(file.to_path_buf(), e) ExecError::io(file.to_path_buf(), e)
})?; })?;
if ownership.needs_fix() {
// rename preserves ownership; this also repairs a pre-existing file
// that was created root-owned by an older, buggy writer.
fixer
.fix(file, ownership.uid, ownership.gid)
.map_err(|e| ExecError::io(file.to_path_buf(), e))?;
}
if let Ok(dir) = std::fs::File::open(dir) { if let Ok(dir) = std::fs::File::open(dir) {
let _ = dir.sync_all(); let _ = dir.sync_all();
} }
Ok(()) Ok(())
} }
/// Lexical containment check: `path` must be `base` or below it.
fn is_within_base(&self, path: &Path) -> bool {
path.starts_with(&self.base)
}
/// Create `dir` component by component beneath `base`, rejecting symlinks
/// and non-directories, setting 0700, and chowning to the initiating user
/// when this process is elevated.
fn create_dir_chain(
&self,
dir: &Path,
ownership: Ownership,
fixer: &dyn OwnerFixer,
) -> Result<()> {
let meta = std::fs::symlink_metadata(&self.base)
.map_err(|e| ExecError::io(self.base.clone(), e))?;
if meta.file_type().is_symlink() || !meta.is_dir() {
return Err(ExecError::operation(
"personal",
"write",
"the user's home is not a real directory",
));
}
let rel = dir.strip_prefix(&self.base).map_err(|_| {
ExecError::operation(
"personal",
"write",
"the destination is not within the user's home",
)
})?;
let mut cur = self.base.clone();
for component in rel.components() {
let Component::Normal(name) = component else {
return Err(ExecError::operation(
"personal",
"write",
"the destination contains an unsafe path component",
));
};
cur = cur.join(name);
match std::fs::symlink_metadata(&cur) {
Ok(meta) if meta.file_type().is_symlink() => {
return Err(ExecError::operation(
"personal",
"write",
"refusing to follow a symlink while creating user storage",
));
}
Ok(meta) if meta.is_dir() => {
if ownership.needs_fix() {
// Repair (or confirm) ownership of an existing dir.
let _ = fixer.fix(&cur, ownership.uid, ownership.gid);
}
}
Ok(_) => {
return Err(ExecError::operation(
"personal",
"write",
"a path component of the user storage is not a directory",
));
}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
std::fs::create_dir(&cur).map_err(|e| ExecError::io(cur.clone(), e))?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&cur, std::fs::Permissions::from_mode(0o700))
.map_err(|e| ExecError::io(cur.clone(), e))?;
}
if ownership.needs_fix() {
fixer
.fix(&cur, ownership.uid, ownership.gid)
.map_err(|e| ExecError::io(cur.clone(), e))?;
}
}
Err(e) => return Err(ExecError::io(cur.clone(), e)),
}
}
Ok(())
}
} }
fn tmp_token() -> String { fn tmp_token() -> String {
@ -182,20 +403,27 @@ fn tmp_token() -> String {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
use std::cell::RefCell;
#[test] /// Records ownership changes instead of performing them (the test process is
fn initiator_env_resolution_order() { /// not root, so a real chown would fail).
// Do not mutate global env in parallel tests; assert the pure helper via #[derive(Default)]
// the documented override only when it is safe. struct RecordingFixer {
let storage = UserStorage::for_uid(4242); calls: RefCell<Vec<(PathBuf, u32, u32)>>,
assert_eq!(storage.uid(), 4242); }
impl OwnerFixer for RecordingFixer {
fn fix(&self, path: &Path, uid: u32, gid: u32) -> std::io::Result<()> {
self.calls.borrow_mut().push((path.to_path_buf(), uid, gid));
Ok(())
}
} }
#[test] #[test]
fn write_private_is_0600_inside_0700() { fn write_private_is_0600_inside_0700() {
use std::os::unix::fs::PermissionsExt; use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().unwrap(); let dir = tempfile::tempdir().unwrap();
let storage = UserStorage::with_base(0, dir.path()); let storage = UserStorage::with_base(effective_uid(), dir.path());
let cfg = storage.config_dir(); let cfg = storage.config_dir();
let file = storage.config_file("x.toml"); let file = storage.config_file("x.toml");
storage.write_private(&cfg, &file, b"a = 1").unwrap(); storage.write_private(&cfg, &file, b"a = 1").unwrap();
@ -209,4 +437,106 @@ mod tests {
); );
assert_eq!(std::fs::read(&file).unwrap(), b"a = 1"); assert_eq!(std::fs::read(&file).unwrap(), b"a = 1");
} }
#[test]
fn elevated_write_is_chowned_to_the_initiating_user() {
let dir = tempfile::tempdir().unwrap();
// Simulate `sudo sys`: effective root writing on behalf of a non-root
// initiating user.
let owner_uid = effective_uid() + 1;
let storage = UserStorage::with_base(owner_uid, dir.path());
let cfg = storage.config_dir();
let file = storage.config_file("prefs.toml");
let fixer = RecordingFixer::default();
storage
.write_private_as(
&cfg,
&file,
b"a = 1",
Ownership {
uid: owner_uid,
gid: owner_uid,
euid: 0,
},
&fixer,
)
.unwrap();
// The created config directory and the file were both handed to the
// initiating user, and only under that user's home.
let calls = fixer.calls.borrow();
assert!(
calls.iter().any(|(p, _, _)| p == &file),
"the file must be chowned: {calls:?}"
);
assert!(
calls.iter().any(|(p, _, _)| p == &cfg),
"the config directory must be chowned: {calls:?}"
);
assert!(
calls.iter().all(|(p, uid, gid)| p.starts_with(dir.path())
&& *uid == owner_uid
&& *gid == owner_uid),
"only paths under the home may be chowned, to the initiating user: {calls:?}"
);
// The file is readable afterwards. (A real cross-uid chown requires
// root, so the recording fixer verifies intent rather than effect.)
assert_eq!(std::fs::read(&file).unwrap(), b"a = 1");
}
#[test]
fn a_written_personal_file_is_replaceable_by_its_owner() {
let dir = tempfile::tempdir().unwrap();
let storage = UserStorage::with_base(effective_uid(), 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::read(&file).unwrap(), b"a = 1");
// The owner can replace it again (atomic overwrite).
storage.write_private(&cfg, &file, b"a = 2").unwrap();
assert_eq!(std::fs::read(&file).unwrap(), b"a = 2");
}
#[test]
fn a_non_root_process_cannot_write_for_another_user() {
let dir = tempfile::tempdir().unwrap();
let storage = UserStorage::with_base(effective_uid(), dir.path());
let cfg = storage.config_dir();
let file = storage.config_file("x.toml");
let err = storage
.write_private_as(
&cfg,
&file,
b"a = 1",
Ownership {
uid: effective_uid() + 1,
gid: effective_uid() + 1,
euid: effective_uid(),
},
&RecordingFixer::default(),
)
.unwrap_err();
assert!(err.to_string().contains("refusing to write"), "{err}");
assert!(!file.exists());
}
#[test]
fn a_symlinked_component_is_refused() {
let dir = tempfile::tempdir().unwrap();
let storage = UserStorage::with_base(effective_uid(), dir.path());
// Plant a symlink where the config directory should be.
let outside = tempfile::tempdir().unwrap();
std::os::unix::fs::symlink(outside.path(), dir.path().join(".config")).unwrap();
let cfg = storage.config_dir();
let file = storage.config_file("x.toml");
let err = storage.write_private(&cfg, &file, b"a = 1").unwrap_err();
assert!(err.to_string().contains("symlink"), "{err}");
assert!(!outside.path().join("phoebus/x.toml").exists());
}
#[test]
fn initiator_env_resolution_order() {
let storage = UserStorage::for_uid(4242);
assert_eq!(storage.uid(), 4242);
}
} }

View file

@ -43,26 +43,6 @@ pub fn load_state_at(path: &Path) -> ProactiveState {
.unwrap_or_default() .unwrap_or_default()
} }
/// 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()))?;
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. /// The user-owned proactive state file for this user.
pub fn state_path(storage: &UserStorage) -> PathBuf { pub fn state_path(storage: &UserStorage) -> PathBuf {
storage.state_file(PROACTIVE_STATE_FILE) storage.state_file(PROACTIVE_STATE_FILE)
@ -84,7 +64,12 @@ pub fn load_state(storage: &UserStorage, root: &Path) -> ProactiveState {
pub fn save_state(exec: &Exec, storage: &UserStorage, state: &ProactiveState) -> Result<()> { pub fn save_state(exec: &Exec, storage: &UserStorage, state: &ProactiveState) -> Result<()> {
let path = state_path(storage); let path = state_path(storage);
save_state_at(&path, state)?; let dir = storage.state_dir();
let text = toml::to_string_pretty(state)
.map_err(|e| ExecError::operation("proactive", "serialize state", e.to_string()))?;
// Route through `UserStorage` so an elevated write is chowned to the
// initiating user and cannot escape their home through a symlink.
storage.write_private(&dir, &path, text.as_bytes())?;
exec.logger exec.logger
.info(format!("proactive state -> {}", path.display())); .info(format!("proactive state -> {}", path.display()));
Ok(()) Ok(())
@ -323,8 +308,9 @@ mod tests {
Exec::new(Box::new(runner), logger, false, root.to_path_buf(), temp) Exec::new(Box::new(runner), logger, false, root.to_path_buf(), temp)
} }
fn storage(base: &Path, uid: u32) -> UserStorage { /// Storage owned by this process, so the ownership check passes.
UserStorage::with_base(uid, base) fn local_storage(base: &Path) -> UserStorage {
UserStorage::with_base(crate::personal::effective_uid(), base)
} }
#[test] #[test]
@ -333,7 +319,7 @@ mod tests {
let root = temp.path(); let root = temp.path();
let runner = RecordingRunner::new(); let runner = RecordingRunner::new();
let exec = make_exec(runner, root); let exec = make_exec(runner, root);
let store = storage(&tempdir().unwrap().keep(), 1000); let store = local_storage(&tempdir().unwrap().keep());
let state = load_state(&store, root); let state = load_state(&store, root);
assert!(state.enabled); assert!(state.enabled);
@ -370,8 +356,8 @@ mod tests {
let base_a = tempdir().unwrap(); let base_a = tempdir().unwrap();
let base_b = tempdir().unwrap(); let base_b = tempdir().unwrap();
let exec = make_exec(RecordingRunner::new(), root); let exec = make_exec(RecordingRunner::new(), root);
let alice = storage(base_a.path(), 1000); let alice = local_storage(base_a.path());
let bob = storage(base_b.path(), 1001); let bob = local_storage(base_b.path());
dismiss(&exec, root, &alice, "reboot_required").unwrap(); dismiss(&exec, root, &alice, "reboot_required").unwrap();
@ -388,7 +374,7 @@ mod tests {
// a parent directory. // a parent directory.
let blocker = temp.path().join("blocker"); let blocker = temp.path().join("blocker");
std::fs::write(&blocker, "x").unwrap(); std::fs::write(&blocker, "x").unwrap();
let store = UserStorage::with_base(1000, blocker.join("not-a-dir")); let store = local_storage(&blocker.join("not-a-dir"));
let err = dismiss(&exec, root, &store, "reboot_required").unwrap_err(); let err = dismiss(&exec, root, &store, "reboot_required").unwrap_err();
assert!(matches!(err, ExecError::Io { .. }), "{err}"); assert!(matches!(err, ExecError::Io { .. }), "{err}");
} }

View file

@ -6,22 +6,34 @@
//! which approvals it has already consumed. //! which approvals it has already consumed.
//! //!
//! The ledger lives in a root-owned directory (`/var/lib/phoebus/approvals`, //! 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 //! 0700, records 0600) that the unprivileged user cannot write.
//! 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; //! ## Stable approval identity
//! - 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 record is keyed by [`approval_key`], derived from the random plan ID, the
//! - a replacement plan under the same identifier has a different fingerprint //! *canonical* approval digest (recomputed from the executable actions and the
//! and is refused by the expected-approval check before the ledger is touched. //! reviewed material effects), the initiating uid and the canonical target
//! root. Presentation-only fields (summary, rationale, recommendations) are
//! deliberately absent: editing them cannot mint a fresh ledger entry for an
//! already-consumed approval. A newly reviewed identical operation gets a new
//! random plan ID and is therefore allowed, while every replay of the original
//! approval is refused.
//!
//! ## Monotonic, crash-safe terminal transitions
//!
//! A claim records the owning process identity (`pid`, process start time and
//! boot id). The terminal status is published exactly once by atomically
//! linking a fully written record into `<key>.terminal`; the link fails if a
//! terminal already exists, so a terminal status can never be overwritten or
//! changed to another terminal status. Reconciliation only marks a record
//! interrupted when its owner is provably gone (the pid no longer exists, the
//! pid was reused by a different process, or the machine rebooted), so a live
//! executor is never mistaken for a crashed one.
//! //!
//! The ledger is *not* a signature scheme and does not claim to be: the //! The ledger is *not* a signature scheme and does not claim to be: the
//! independently preserved fingerprint (the digest shown on the review card) //! independently preserved digest supplied by the approval UI is what binds the
//! supplied by the approval UI is what binds the human decision. The ledger //! human decision. The ledger anchors consumption so user-editable files cannot
//! anchors consumption so user-editable files cannot be used to replay or //! be used to replay or replace an approved plan.
//! replace an approved plan.
use std::io::Write; use std::io::Write;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
@ -30,6 +42,7 @@ use std::time::{SystemTime, UNIX_EPOCH};
use phoebus_executor::error::{ExecError, Result}; use phoebus_executor::error::{ExecError, Result};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
/// Terminal states a consumed approval can reach. There is deliberately no /// Terminal states a consumed approval can reach. There is deliberately no
/// "retry" transition: a plan whose approval was claimed is never automatically /// "retry" transition: a plan whose approval was claimed is never automatically
@ -65,12 +78,131 @@ impl ApprovalStatus {
} }
} }
/// Identity of the process that claimed an approval, used to distinguish a live
/// executor from a crashed one during reconciliation.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ProcessIdentity {
pub pid: u32,
/// The process start time (`/proc/<pid>/stat` field 22), in clock ticks.
pub start_ticks: u64,
/// The kernel boot id, so a pid reused after a reboot is never mistaken for
/// the same process.
pub boot_id: String,
}
impl ProcessIdentity {
/// Identity of the current process.
pub fn current() -> Self {
let pid = std::process::id();
let start_ticks = std::fs::read_to_string(format!("/proc/{pid}/stat"))
.ok()
.and_then(|s| parse_start_ticks(&s))
.unwrap_or(0);
Self {
pid,
start_ticks,
boot_id: boot_id(),
}
}
/// Whether the owning process is still running. A missing `/proc` entry, a
/// different start time (pid reuse) or a different boot id all mean the
/// executor is gone.
pub fn is_alive(&self) -> bool {
let current_boot = boot_id();
if !self.boot_id.is_empty() && !current_boot.is_empty() && self.boot_id != current_boot {
return false;
}
match std::fs::read_to_string(format!("/proc/{}/stat", self.pid)) {
Ok(text) => match parse_start_ticks(&text) {
// A start time of 0 means it could not be recorded; fall back to
// "present" rather than mislabel a live process.
Some(ticks) => self.start_ticks == 0 || ticks == self.start_ticks,
None => true,
},
Err(_) => false,
}
}
}
fn parse_start_ticks(stat: &str) -> Option<u64> {
// The command name is parenthesised and may contain spaces or parentheses;
// parse the fields after the last ')'.
let close = stat.rfind(')')?;
let rest = stat.get(close + 1..)?.trim_start();
let fields: Vec<&str> = rest.split_whitespace().collect();
// fields[0] is field 3 (state); starttime is field 22 -> index 19.
fields.get(19).and_then(|s| s.parse::<u64>().ok())
}
fn boot_id() -> String {
std::fs::read_to_string("/proc/sys/kernel/random/boot_id")
.map(|s| s.trim().to_string())
.unwrap_or_default()
}
/// The stable identity of an approval, independent of presentation fields.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ApprovalIdentity {
/// The ledger key: a hex fingerprint over the fields below.
pub key: String,
pub plan_id: String,
/// The canonical approval digest, independently recomputed at the
/// privileged boundary.
pub digest: String,
pub initiator_uid: u32,
pub target_root: String,
pub expires_unix: u64,
pub action_count: usize,
}
impl ApprovalIdentity {
pub fn new(
plan_id: impl Into<String>,
digest: impl Into<String>,
initiator_uid: u32,
target_root: impl Into<String>,
expires_unix: u64,
action_count: usize,
) -> Self {
let plan_id = plan_id.into();
let digest = digest.into();
let target_root = target_root.into();
let key = approval_key(&plan_id, &digest, initiator_uid, &target_root);
Self {
key,
plan_id,
digest,
initiator_uid,
target_root,
expires_unix,
action_count,
}
}
}
/// Derive the stable ledger key. Deliberately excludes summary, rationale,
/// recommendations, timestamps and the plan's self-consistency seal, all of
/// which the reviewing user can edit and recompute.
pub fn approval_key(plan_id: &str, digest: &str, initiator_uid: u32, target_root: &str) -> String {
let mut hasher = Sha256::new();
hasher.update(b"phoebus-approval-key-v1\0");
hasher.update(plan_id.as_bytes());
hasher.update(b"\0");
hasher.update(digest.as_bytes());
hasher.update(b"\0");
hasher.update(initiator_uid.to_le_bytes());
hasher.update(b"\0");
hasher.update(target_root.as_bytes());
format!("{:x}", hasher.finalize())
}
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ApprovalRecord { pub struct ApprovalRecord {
/// The plan's integrity seal: a content fingerprint over every reviewed /// The stable [`approval_key`].
/// field, including the approval digest. pub approval_key: String,
pub fingerprint: String,
pub plan_id: String, pub plan_id: String,
/// The canonical approval digest.
pub digest: String, pub digest: String,
pub initiator_uid: u32, pub initiator_uid: u32,
pub target_root: String, pub target_root: String,
@ -84,18 +216,30 @@ pub struct ApprovalRecord {
/// How many actions the approved plan contained, for truthful reporting. /// How many actions the approved plan contained, for truthful reporting.
#[serde(default)] #[serde(default)]
pub action_count: usize, pub action_count: usize,
/// The claiming process, when known (older records may lack it).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub owner: Option<ProcessIdentity>,
}
/// The outcome of a terminal transition.
#[derive(Debug, Clone)]
pub enum Finished {
/// This call recorded the terminal status.
Recorded,
/// A terminal status already existed and was left unchanged.
AlreadyTerminal(Box<ApprovalRecord>),
} }
/// A guard proving this process claimed the approval. Dropping it does not /// A guard proving this process claimed the approval. Dropping it does not
/// release the claim: the durable record is the anti-replay anchor. /// release the claim: the durable record is the anti-replay anchor.
#[derive(Debug)] #[derive(Debug)]
pub struct ApprovalClaim { pub struct ApprovalClaim {
fingerprint: String, key: String,
} }
impl ApprovalClaim { impl ApprovalClaim {
pub fn fingerprint(&self) -> &str { pub fn key(&self) -> &str {
&self.fingerprint &self.key
} }
} }
@ -106,7 +250,9 @@ pub struct ApprovalLedger {
impl ApprovalLedger { impl ApprovalLedger {
/// The broker's ledger. `PHOEBUS_APPROVALS_DIR` overrides the location for /// The broker's ledger. `PHOEBUS_APPROVALS_DIR` overrides the location for
/// tests and for an installed system that relocates its state. /// tests and for an installed system that relocates its state. `pkexec`
/// strips unknown environment variables, so this is not user-controllable
/// on the privileged path.
pub fn for_broker() -> Self { pub fn for_broker() -> Self {
if let Ok(dir) = std::env::var("PHOEBUS_APPROVALS_DIR") { if let Ok(dir) = std::env::var("PHOEBUS_APPROVALS_DIR") {
return Self { return Self {
@ -137,49 +283,68 @@ impl ApprovalLedger {
Ok(()) Ok(())
} }
fn path(&self, fingerprint: &str) -> Result<PathBuf> { fn valid_key(key: &str) -> bool {
if fingerprint.is_empty() !key.is_empty() && key.len() <= 128 && key.bytes().all(|b| b.is_ascii_hexdigit())
|| fingerprint.len() > 128 }
|| !fingerprint.bytes().all(|b| b.is_ascii_hexdigit())
{ fn main_path(&self, key: &str) -> Result<PathBuf> {
if !Self::valid_key(key) {
return Err(ExecError::operation( return Err(ExecError::operation(
"approval", "approval",
"ledger path", "ledger path",
"approval fingerprint is not a hex digest", "approval key is not a hex digest",
)); ));
} }
Ok(self.dir.join(format!("{fingerprint}.json"))) Ok(self.dir.join(format!("{key}.json")))
} }
/// Atomically claim an approval for execution. Fails if the fingerprint has fn terminal_path(&self, key: &str) -> Result<PathBuf> {
/// already been claimed (consumed, failed, interrupted or in progress), if !Self::valid_key(key) {
/// which is what makes replay impossible after the user deletes their own return Err(ExecError::operation(
/// plan and claim files. "approval",
#[allow(clippy::too_many_arguments)] "ledger path",
pub fn claim( "approval key is not a hex digest",
));
}
Ok(self.dir.join(format!("{key}.terminal")))
}
/// Atomically claim an approval for execution. Fails if the key has already
/// been claimed or terminated, which is what makes replay impossible after
/// the user deletes their own plan and claim files.
pub fn claim(&self, identity: &ApprovalIdentity) -> Result<ApprovalClaim> {
self.claim_with_owner(identity, ProcessIdentity::current())
}
/// Claim with an explicit owner identity (used by tests to simulate a live
/// or an abandoned executor).
pub fn claim_with_owner(
&self, &self,
fingerprint: &str, identity: &ApprovalIdentity,
plan_id: &str, owner: ProcessIdentity,
digest: &str,
initiator_uid: u32,
target_root: &str,
expires_unix: u64,
action_count: usize,
) -> Result<ApprovalClaim> { ) -> Result<ApprovalClaim> {
self.ensure_dir()?; self.ensure_dir()?;
let path = self.path(fingerprint)?; let path = self.main_path(&identity.key)?;
// A terminal marker is authoritative: even if the main record was
// removed (which the user cannot do to root-owned files), the approval
// stays consumed.
if self.terminal_path(&identity.key)?.exists() {
let prior = self.get(&identity.key).unwrap_or(None);
return Err(self.already_used(prior.as_ref()));
}
let record = ApprovalRecord { let record = ApprovalRecord {
fingerprint: fingerprint.to_string(), approval_key: identity.key.clone(),
plan_id: plan_id.to_string(), plan_id: identity.plan_id.clone(),
digest: digest.to_string(), digest: identity.digest.clone(),
initiator_uid, initiator_uid: identity.initiator_uid,
target_root: target_root.to_string(), target_root: identity.target_root.clone(),
expires_unix, expires_unix: identity.expires_unix,
created_unix: now_unix(), created_unix: now_unix(),
finished_unix: 0, finished_unix: 0,
status: ApprovalStatus::InProgress.as_str().to_string(), status: ApprovalStatus::InProgress.as_str().to_string(),
result: "in progress".into(), result: "in progress".into(),
action_count, action_count: identity.action_count,
owner: Some(owner),
}; };
let text = serde_json::to_string_pretty(&record) let text = serde_json::to_string_pretty(&record)
.map_err(|e| ExecError::operation("approval", "serialize", e.to_string()))?; .map_err(|e| ExecError::operation("approval", "serialize", e.to_string()))?;
@ -198,32 +363,48 @@ impl ApprovalLedger {
.and_then(|_| file.sync_all()) .and_then(|_| file.sync_all())
.map_err(|e| ExecError::io(path.clone(), e))?; .map_err(|e| ExecError::io(path.clone(), e))?;
Ok(ApprovalClaim { Ok(ApprovalClaim {
fingerprint: fingerprint.to_string(), key: identity.key.clone(),
}) })
} }
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => { Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
let prior = self.get(fingerprint).unwrap_or(None); let prior = self.get(&identity.key).unwrap_or(None);
let detail = prior Err(self.already_used(prior.as_ref()))
.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)), Err(e) => Err(ExecError::io(path, e)),
} }
} }
/// Record the terminal status of a claimed approval. The record is retained. fn already_used(&self, prior: Option<&ApprovalRecord>) -> ExecError {
pub fn finish(&self, fingerprint: &str, status: ApprovalStatus, result: &str) -> Result<()> { let detail = prior
let path = self.path(fingerprint)?; .map(|r| format!("{} ({})", r.status, r.result))
let mut record = match self.get(fingerprint)? { .unwrap_or_else(|| "already claimed".to_string());
Some(r) => r, 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"
),
)
}
/// Record the terminal status of a claimed approval. The transition is
/// atomic and monotonic: the first terminal status wins and can never be
/// overwritten or changed to another terminal status.
pub fn finish(&self, key: &str, status: ApprovalStatus, result: &str) -> Result<Finished> {
if !status.is_terminal() {
return Err(ExecError::operation(
"approval",
"finish",
"finish requires a terminal status",
));
}
self.ensure_dir()?;
let main = self.main_path(key)?;
let terminal = self.terminal_path(key)?;
// Read the current state. If it is already terminal, leave it untouched.
let mut record = match self.get(key)? {
Some(record) => record,
None => { None => {
return Err(ExecError::operation( return Err(ExecError::operation(
"approval", "approval",
@ -232,38 +413,100 @@ impl ApprovalLedger {
)) ))
} }
}; };
if record.status != ApprovalStatus::InProgress.as_str() {
return Ok(Finished::AlreadyTerminal(Box::new(record)));
}
record.status = status.as_str().to_string(); record.status = status.as_str().to_string();
record.result = result.to_string(); record.result = result.to_string();
record.finished_unix = now_unix(); record.finished_unix = now_unix();
let text = serde_json::to_string_pretty(&record) let text = serde_json::to_string_pretty(&record)
.map_err(|e| ExecError::operation("approval", "serialize", e.to_string()))?; .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))?; // Write a fully formed record to a unique temp file, then publish it
std::fs::rename(&tmp, &path).map_err(|e| { // with an atomic hard link that fails if a terminal already exists.
let _ = std::fs::remove_file(&tmp); let tmp = self
ExecError::io(path.clone(), e) .dir
})?; .join(format!(".{key}.{}.terminal.tmp", std::process::id()));
Ok(()) {
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 = match opts.open(&tmp) {
Ok(fh) => fh,
Err(e) => return Err(ExecError::io(tmp.clone(), e)),
};
fh.write_all(text.as_bytes())
.and_then(|_| fh.flush())
.and_then(|_| fh.sync_all())
.map_err(|e| ExecError::io(tmp.clone(), e))?;
}
match std::fs::hard_link(&tmp, &terminal) {
Ok(()) => {
let _ = std::fs::remove_file(&tmp);
// Mirror the terminal state into the main record (best effort;
// the terminal marker is authoritative).
let _ = write_atomic(&main, text.as_bytes());
Ok(Finished::Recorded)
}
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
let _ = std::fs::remove_file(&tmp);
match self.get(key)? {
Some(existing) => Ok(Finished::AlreadyTerminal(Box::new(existing))),
None => Err(ExecError::io(terminal, e)),
}
}
Err(e) => {
let _ = std::fs::remove_file(&tmp);
Err(ExecError::io(terminal, e))
}
}
} }
/// Read an existing record, if any. /// Read a record. The terminal marker is authoritative when present. An
pub fn get(&self, fingerprint: &str) -> Result<Option<ApprovalRecord>> { /// invalid key simply has no record.
let path = match self.path(fingerprint) { pub fn get(&self, key: &str) -> Result<Option<ApprovalRecord>> {
Ok(p) => p, if !Self::valid_key(key) {
Err(_) => return Ok(None), return Ok(None);
}; }
if let Some(record) = self.read_terminal(key)? {
return Ok(Some(record));
}
if let Some(record) = self.read_main(key)? {
return Ok(Some(record));
}
Ok(None)
}
fn read_terminal(&self, key: &str) -> Result<Option<ApprovalRecord>> {
let path = self.terminal_path(key)?;
self.read_record(&path)
}
fn read_main(&self, key: &str) -> Result<Option<ApprovalRecord>> {
let path = self.main_path(key)?;
self.read_record(&path)
}
fn read_record(&self, path: &Path) -> Result<Option<ApprovalRecord>> {
if !path.is_file() { if !path.is_file() {
return Ok(None); return Ok(None);
} }
let text = std::fs::read_to_string(&path).map_err(|e| ExecError::io(path.clone(), e))?; let text =
std::fs::read_to_string(path).map_err(|e| ExecError::io(path.to_path_buf(), e))?;
let record = serde_json::from_str(&text) let record = serde_json::from_str(&text)
.map_err(|e| ExecError::operation("approval", "deserialize", e.to_string()))?; .map_err(|e| ExecError::operation("approval", "deserialize", e.to_string()))?;
Ok(Some(record)) Ok(Some(record))
} }
/// Mark any ledger record left `in_progress` as interrupted. Called at /// Reconcile approvals whose owner is provably gone. A live executor is
/// broker startup so a crash is reported truthfully rather than lingering /// never touched: a record is only marked interrupted when its owning
/// as an operation that "might still be running". /// process no longer exists (or the machine rebooted). The transition uses
/// the same atomic terminal publication as [`finish`], so it cannot
/// overwrite a real terminal result.
pub fn reconcile_interrupted(&self) -> Result<usize> { pub fn reconcile_interrupted(&self) -> Result<usize> {
if !self.dir.is_dir() { if !self.dir.is_dir() {
return Ok(0); return Ok(0);
@ -276,19 +519,36 @@ impl ApprovalLedger {
if path.extension().and_then(|e| e.to_str()) != Some("json") { if path.extension().and_then(|e| e.to_str()) != Some("json") {
continue; continue;
} }
let Ok(text) = std::fs::read_to_string(&path) else { let Some(key) = path.file_stem().and_then(|s| s.to_str()) else {
continue; continue;
}; };
let Ok(mut record) = serde_json::from_str::<ApprovalRecord>(&text) else { if !Self::valid_key(key) {
continue;
}
// Already terminal.
if self.terminal_path(key)?.exists() {
continue;
}
let Ok(Some(record)) = self.read_main(key) else {
continue; continue;
}; };
if record.status == ApprovalStatus::InProgress.as_str() { if record.status != ApprovalStatus::InProgress.as_str() {
record.status = ApprovalStatus::Interrupted.as_str().to_string(); continue;
record.result = "the executing process ended before completing".into(); }
record.finished_unix = now_unix(); // Only reconcile when the owner is provably gone.
if let Ok(text) = serde_json::to_string_pretty(&record) { if record
let _ = std::fs::write(&path, text); .owner
} .as_ref()
.map(|owner| owner.is_alive())
.unwrap_or(false)
{
continue;
}
if let Ok(Finished::Recorded) = self.finish(
key,
ApprovalStatus::Interrupted,
"the executing process ended before completing",
) {
reconciled += 1; reconciled += 1;
} }
} }
@ -296,6 +556,32 @@ impl ApprovalLedger {
} }
} }
/// Atomically replace `path` with `bytes` (temp file + rename). Best effort.
fn write_atomic(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
let dir = path.parent().unwrap_or_else(|| Path::new("."));
let tmp = dir.join(format!(".{}.{}.tmp", std::process::id(), now_unix()));
{
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)?;
fh.write_all(bytes)?;
fh.flush()?;
fh.sync_all()?;
}
match std::fs::rename(&tmp, path) {
Ok(()) => Ok(()),
Err(e) => {
let _ = std::fs::remove_file(&tmp);
Err(e)
}
}
}
fn now_unix() -> u64 { fn now_unix() -> u64 {
SystemTime::now() SystemTime::now()
.duration_since(UNIX_EPOCH) .duration_since(UNIX_EPOCH)
@ -346,18 +632,25 @@ mod tests {
use super::*; use super::*;
use tempfile::tempdir; use tempfile::tempdir;
const FP: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"; fn identity() -> ApprovalIdentity {
ApprovalIdentity::new("plan-a", "digest-a", 1000, "/", 9999999999, 1)
}
fn dead_owner() -> ProcessIdentity {
ProcessIdentity {
pid: u32::MAX,
start_ticks: 1,
boot_id: boot_id(),
}
}
#[test] #[test]
fn a_claim_can_only_be_taken_once() { fn a_claim_can_only_be_taken_once() {
let dir = tempdir().unwrap(); let dir = tempdir().unwrap();
let ledger = ApprovalLedger::with_dir(dir.path()); let ledger = ApprovalLedger::with_dir(dir.path());
let _claim = ledger let id = identity();
.claim(FP, "plan-a", "digest", 1000, "/", 9999999999, 1) let _claim = ledger.claim(&id).unwrap();
.unwrap(); let err = ledger.claim(&id).unwrap_err();
let err = ledger
.claim(FP, "plan-a", "digest", 1000, "/", 9999999999, 1)
.unwrap_err();
assert!(err.to_string().contains("already used"), "{err}"); assert!(err.to_string().contains("already used"), "{err}");
} }
@ -365,14 +658,12 @@ mod tests {
fn concurrent_claims_allow_at_most_one_execution() { fn concurrent_claims_allow_at_most_one_execution() {
let dir = tempdir().unwrap(); let dir = tempdir().unwrap();
let ledger = ApprovalLedger::with_dir(dir.path()); let ledger = ApprovalLedger::with_dir(dir.path());
let id = identity();
let handles: Vec<_> = (0..8) let handles: Vec<_> = (0..8)
.map(|_| { .map(|_| {
let ledger = ledger.clone(); let ledger = ledger.clone();
std::thread::spawn(move || { let id = id.clone();
ledger std::thread::spawn(move || ledger.claim(&id).is_ok())
.claim(FP, "plan-a", "digest", 1000, "/", 9999999999, 1)
.is_ok()
})
}) })
.collect(); .collect();
let successes = handles let successes = handles
@ -387,49 +678,137 @@ mod tests {
fn finish_records_a_terminal_status_and_retains_the_record() { fn finish_records_a_terminal_status_and_retains_the_record() {
let dir = tempdir().unwrap(); let dir = tempdir().unwrap();
let ledger = ApprovalLedger::with_dir(dir.path()); let ledger = ApprovalLedger::with_dir(dir.path());
let claim = ledger let id = identity();
.claim(FP, "plan-a", "digest", 1000, "/", 9999999999, 2) let claim = ledger.claim(&id).unwrap();
let finished = ledger
.finish(claim.key(), ApprovalStatus::Consumed, "ok")
.unwrap(); .unwrap();
ledger assert!(matches!(finished, Finished::Recorded));
.finish(claim.fingerprint(), ApprovalStatus::Consumed, "ok") let record = ledger.get(&id.key).unwrap().unwrap();
.unwrap();
let record = ledger.get(FP).unwrap().unwrap();
assert_eq!(record.status, "consumed"); assert_eq!(record.status, "consumed");
assert!(ApprovalStatus::Consumed.is_terminal());
} }
#[test] #[test]
fn reconcile_marks_leftover_in_progress_as_interrupted() { fn terminal_status_is_monotonic_and_cannot_be_overwritten() {
let dir = tempdir().unwrap(); let dir = tempdir().unwrap();
let ledger = ApprovalLedger::with_dir(dir.path()); let ledger = ApprovalLedger::with_dir(dir.path());
let _claim = ledger let id = identity();
.claim(FP, "plan-a", "digest", 1000, "/", 9999999999, 1) let claim = ledger.claim(&id).unwrap();
ledger
.finish(claim.key(), ApprovalStatus::Consumed, "ok")
.unwrap(); .unwrap();
// A second, conflicting terminal transition must be refused and must
// not change the recorded status.
let second = ledger
.finish(claim.key(), ApprovalStatus::Failed, "boom")
.unwrap();
assert!(matches!(second, Finished::AlreadyTerminal(ref r) if r.status == "consumed"));
assert_eq!(ledger.get(&id.key).unwrap().unwrap().status, "consumed");
}
#[test]
fn a_live_operation_is_not_reconciled() {
let dir = tempdir().unwrap();
let ledger = ApprovalLedger::with_dir(dir.path());
let id = identity();
// The current process owns this claim and is running.
let _claim = ledger.claim(&id).unwrap();
assert_eq!(ledger.reconcile_interrupted().unwrap(), 0);
assert_eq!(ledger.get(&id.key).unwrap().unwrap().status, "in_progress");
}
#[test]
fn a_genuinely_abandoned_operation_is_recovered() {
let dir = tempdir().unwrap();
let ledger = ApprovalLedger::with_dir(dir.path());
let id = identity();
let _claim = ledger.claim_with_owner(&id, dead_owner()).unwrap();
assert_eq!(ledger.reconcile_interrupted().unwrap(), 1); assert_eq!(ledger.reconcile_interrupted().unwrap(), 1);
assert_eq!(ledger.get(FP).unwrap().unwrap().status, "interrupted"); assert_eq!(ledger.get(&id.key).unwrap().unwrap().status, "interrupted");
// And it cannot be retried.
assert!(ledger.claim(&id).is_err());
}
#[test]
fn reconciliation_racing_completion_yields_exactly_one_stable_terminal() {
let dir = tempdir().unwrap();
let ledger = ApprovalLedger::with_dir(dir.path());
let id = identity();
let _claim = ledger.claim_with_owner(&id, dead_owner()).unwrap();
let reconciler = {
let ledger = ledger.clone();
std::thread::spawn(move || ledger.reconcile_interrupted().is_ok())
};
let finisher = {
let ledger = ledger.clone();
let key = id.key.clone();
std::thread::spawn(move || ledger.finish(&key, ApprovalStatus::Consumed, "ok").is_ok())
};
reconciler.join().unwrap();
finisher.join().unwrap();
let first = ledger.get(&id.key).unwrap().unwrap();
assert!(ApprovalStatus::Consumed.is_terminal());
// Whatever won, the status is terminal and stable under a later finish.
let later = ledger
.finish(&id.key, ApprovalStatus::Failed, "late")
.unwrap();
assert!(matches!(later, Finished::AlreadyTerminal(_)));
let second = ledger.get(&id.key).unwrap().unwrap();
assert_eq!(
first.status, second.status,
"terminal status must not change"
);
assert!(second.status == "consumed" || second.status == "interrupted");
} }
#[test] #[test]
fn a_replay_is_refused_even_after_the_user_plan_files_are_gone() { fn a_replay_is_refused_even_after_the_user_plan_files_are_gone() {
let dir = tempdir().unwrap(); let dir = tempdir().unwrap();
let ledger = ApprovalLedger::with_dir(dir.path()); let ledger = ApprovalLedger::with_dir(dir.path());
let claim = ledger let id = identity();
.claim(FP, "plan-a", "digest", 1000, "/", 9999999999, 1) let claim = ledger.claim(&id).unwrap();
.unwrap();
ledger ledger
.finish(claim.fingerprint(), ApprovalStatus::Consumed, "ok") .finish(claim.key(), ApprovalStatus::Consumed, "ok")
.unwrap(); .unwrap();
// The user deletes nothing in the ledger; a retry cannot proceed. assert!(ledger.claim(&id).is_err());
assert!(ledger
.claim(FP, "plan-a", "digest", 1000, "/", 9999999999, 1)
.is_err());
} }
#[test] #[test]
fn rejects_non_hex_fingerprints() { fn the_key_ignores_presentation_fields_but_changes_with_identity() {
// Same id/digest/uid/root -> same key regardless of anything else.
assert_eq!(
approval_key("plan-a", "d", 1000, "/"),
approval_key("plan-a", "d", 1000, "/")
);
// A new plan id is a new approval.
assert_ne!(
approval_key("plan-a", "d", 1000, "/"),
approval_key("plan-b", "d", 1000, "/")
);
// A different digest, user or root is a different approval.
assert_ne!(
approval_key("plan-a", "d", 1000, "/"),
approval_key("plan-a", "e", 1000, "/")
);
assert_ne!(
approval_key("plan-a", "d", 1000, "/"),
approval_key("plan-a", "d", 1001, "/")
);
assert_ne!(
approval_key("plan-a", "d", 1000, "/"),
approval_key("plan-a", "d", 1000, "/alt")
);
}
#[test]
fn rejects_non_hex_keys() {
let dir = tempdir().unwrap(); let dir = tempdir().unwrap();
let ledger = ApprovalLedger::with_dir(dir.path()); let ledger = ApprovalLedger::with_dir(dir.path());
assert!(ledger.get("../escape").unwrap().is_none()); assert!(ledger.get("../escape").unwrap().is_none());
assert!(ledger.claim("not-a-hash", "p", "d", 0, "/", 0, 0).is_err()); assert!(ledger
.finish("not-a-hash", ApprovalStatus::Consumed, "x")
.is_err());
} }
} }

View file

@ -29,7 +29,7 @@ use phoebus_executor::exec::Exec;
use phoebus_executor::install::{self, AiInstall, InstallRequest, InstallSource}; use phoebus_executor::install::{self, AiInstall, InstallRequest, InstallSource};
use phoebus_executor::transaction; use phoebus_executor::transaction;
use crate::approval::{ApprovalLedger, ApprovalStatus}; use crate::approval::{ApprovalIdentity, ApprovalLedger, ApprovalStatus, Finished};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256}; use sha2::{Digest, Sha256};
@ -1176,8 +1176,26 @@ pub fn validate_prepared_plan(
"plan has expired; review and approve a fresh plan", "plan has expired; review and approve a fresh plan",
)); ));
} }
// Independently recompute the canonical approval digest from the exact
// executable actions, candidate and reviewed material effects. The
// `integrity` seal stored beside the plan is a self-consistency check the
// owning user can recompute, so it is not authentication: the canonical
// digest is. It must match the digest stored in the plan *and* the
// independently supplied approval digest. This binds every plan kind
// (Install, LegacyInstall, Removal, General, Undo) to the reviewed actions,
// so retaining an old digest while swapping an action and resealing is
// rejected before any mutation.
let canonical = compute_plan_digest(&plan.actions, plan.candidate.as_ref(), &plan.effects);
if plan.digest != canonical {
return Err(ExecError::operation(
"service",
"validate plan",
"plan digest does not match its reviewed actions and effects; the plan was \
substituted or resealed and is refused",
));
}
if let Some(digest) = expected_digest { if let Some(digest) = expected_digest {
if !digest.is_empty() && plan.digest != digest { if !digest.is_empty() && canonical != digest {
return Err(ExecError::operation( return Err(ExecError::operation(
"service", "service",
"validate plan", "validate plan",
@ -1390,13 +1408,6 @@ pub fn execute_plan_privileged(
// The expected digest is the independently preserved approval the user // The expected digest is the independently preserved approval the user
// reviewed. A self-consistent reseal of a replacement plan cannot match it. // reviewed. A self-consistent reseal of a replacement plan cannot match it.
validate_prepared_plan(exec, root, &plan, Some(expected_digest), initiator_uid)?; 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 // `execute_prepared` authenticates *before* claiming the approval, so a
// cancelled or refused operation consumes nothing; it then anchors the // cancelled or refused operation consumes nothing; it then anchors the
// claim in the broker-controlled ledger and records a terminal status. // claim in the broker-controlled ledger and records a terminal status.
@ -1493,51 +1504,68 @@ fn execute_prepared(
}; };
// Anchor the approval in the broker-controlled ledger before mutation. The // Anchor the approval in the broker-controlled ledger before mutation. The
// fingerprint is the plan's integrity seal: the exact actions, per-step // key is the *stable* approval identity (plan id, canonical digest,
// effects, candidate, target root, initiating uid and expiry. // authenticated initiating uid, target root); presentation fields are
let claimed = match approvals { // excluded, so editing the summary and resealing cannot mint a fresh entry
// for an already-consumed approval.
let approved_key = match approvals {
Some((ledger, uid)) => { Some((ledger, uid)) => {
ledger.claim( let identity = ApprovalIdentity::new(
&plan.integrity, plan.id.clone(),
&plan.id, plan.digest.clone(),
&plan.digest,
uid, uid,
&plan.target_root, plan.target_root.clone(),
plan.expires_unix, plan.expires_unix,
plan.actions.len(), plan.actions.len(),
)?; );
true ledger.claim(&identity)?;
Some(identity.key)
} }
None => false, None => None,
}; };
let result = execute_claimed(exec, root, plans, &plan, auth.as_ref()); let result = execute_claimed(exec, root, plans, &plan, auth.as_ref());
if claimed { if let (Some((ledger, _)), Some(key)) = (approvals, approved_key.as_ref()) {
// 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 { let (status, note) = match &result {
Ok(_) => (ApprovalStatus::Consumed, "ok".to_string()), Ok(_) => (ApprovalStatus::Consumed, "ok".to_string()),
Err(e) => (ApprovalStatus::Failed, e.to_string()), Err(e) => (ApprovalStatus::Failed, e.to_string()),
}; };
if let Err(ledger_err) = ledger.finish(&plan.integrity, status, &note) { // The transition is monotonic. A conflicting terminal (only possible if
return match result { // recovery had already declared the owner gone) must not be silently
Ok(_) => Err(ExecError::operation( // overwritten or reported as success.
match ledger.finish(key, status, &note) {
Ok(Finished::Recorded) => {}
Ok(Finished::AlreadyTerminal(existing)) if existing.status == status.as_str() => {}
Ok(Finished::AlreadyTerminal(existing)) => {
return Err(ExecError::operation(
"service", "service",
"record approval", "record approval",
format!( format!(
"the operation completed but its approval outcome could not be \ "the approval already reached terminal status `{}` and was not \
recorded: {ledger_err}" overwritten with `{}`",
existing.status,
status.as_str()
), ),
)), ));
Err(e) => Err(ExecError::operation( }
"service", Err(ledger_err) => {
"record approval", return match result {
format!("{e}; the approval outcome could not be recorded: {ledger_err}"), 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 result
@ -1875,15 +1903,20 @@ mod tests {
assert!(!rec.contains("avoids a lengthy build")); assert!(!rec.contains("avoids a lengthy build"));
} }
/// Build a sealed plan for validation tests. /// Build a sealed plan for validation tests. The canonical approval digest
/// is derived from the actions and reviewed effects, exactly as the
/// privileged boundary does; the trailing marker argument is retained only
/// so existing call sites read naturally and is ignored.
fn sealed( fn sealed(
id: &str, id: &str,
kind: PlanKind, kind: PlanKind,
actions: Vec<SystemAction>, actions: Vec<SystemAction>,
digest: &str, _marker: &str,
target_root: &Path, target_root: &Path,
initiator_uid: u32, initiator_uid: u32,
) -> PreparedPlan { ) -> PreparedPlan {
let effects = ResolvedPlan::default();
let digest = compute_plan_digest(&actions, None, &effects);
let mut plan = PreparedPlan { let mut plan = PreparedPlan {
id: id.into(), id: id.into(),
created_unix: now_unix(), created_unix: now_unix(),
@ -1897,9 +1930,9 @@ mod tests {
rationale: Vec::new(), rationale: Vec::new(),
warnings: Vec::new(), warnings: Vec::new(),
actions, actions,
effects: ResolvedPlan::default(), effects,
step_effects: Vec::new(), step_effects: Vec::new(),
digest: digest.into(), digest,
verification: "verify".into(), verification: "verify".into(),
requires_root: false, requires_root: false,
source: "test".into(), source: "test".into(),
@ -2056,7 +2089,7 @@ mod tests {
); );
store.save(&mut plan).unwrap(); store.save(&mut plan).unwrap();
let loaded = store.load("plan-ok").unwrap(); let loaded = store.load("plan-ok").unwrap();
validate_prepared_plan(&exec, root.path(), &loaded, Some("same-digest"), uid).unwrap(); validate_prepared_plan(&exec, root.path(), &loaded, Some(&loaded.digest), uid).unwrap();
// Tampering with any reviewed field breaks the seal. // Tampering with any reviewed field breaks the seal.
let path = store_dir.path().join("plan-ok.json"); let path = store_dir.path().join("plan-ok.json");
@ -2403,12 +2436,25 @@ mod tests {
); );
// Refusal happens before the approval is claimed, so nothing is // Refusal happens before the approval is claimed, so nothing is
// consumed in the broker ledger either. // consumed in the broker ledger either.
let key = approval_identity(&plan, plan.initiator_uid).key;
assert!( assert!(
approvals.get(&plan.integrity).unwrap().is_none(), approvals.get(&key).unwrap().is_none(),
"a refused plan must not consume its approval" "a refused plan must not consume its approval"
); );
} }
/// The stable approval identity the broker derives for a plan.
fn approval_identity(plan: &PreparedPlan, uid: u32) -> ApprovalIdentity {
ApprovalIdentity::new(
plan.id.clone(),
plan.digest.clone(),
uid,
plan.target_root.clone(),
plan.expires_unix,
plan.actions.len(),
)
}
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
// Regression tests for the approval boundary and transaction truthfulness. // Regression tests for the approval boundary and transaction truthfulness.
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
@ -2738,21 +2784,18 @@ mod tests {
); );
store.save(&mut plan).unwrap(); store.save(&mut plan).unwrap();
// Simulate a crash after claiming but before finishing. // Simulate a crash after claiming but before finishing: the owning
approvals // process is provably gone, so reconciliation recovers it.
.claim( let dead = crate::approval::ProcessIdentity {
&plan.integrity, pid: u32::MAX,
&plan.id, start_ticks: 1,
&plan.digest, boot_id: String::new(),
uid, };
&plan.target_root, let identity = approval_identity(&plan, uid);
plan.expires_unix, approvals.claim_with_owner(&identity, dead).unwrap();
plan.actions.len(),
)
.unwrap();
assert_eq!(approvals.reconcile_interrupted().unwrap(), 1); assert_eq!(approvals.reconcile_interrupted().unwrap(), 1);
assert_eq!( assert_eq!(
approvals.get(&plan.integrity).unwrap().unwrap().status, approvals.get(&identity.key).unwrap().unwrap().status,
"interrupted" "interrupted"
); );
@ -2875,9 +2918,10 @@ mod tests {
"{}", "{}",
log.records[0].result log.records[0].result
); );
let key = approval_identity(&plan, uid).key;
assert!( assert!(
approvals approvals
.get(&plan.integrity) .get(&key)
.unwrap() .unwrap()
.is_some_and(|r| r.status == "failed"), .is_some_and(|r| r.status == "failed"),
"the approval must reach a terminal failed status" "the approval must reach a terminal failed status"
@ -2953,4 +2997,451 @@ mod tests {
assert_eq!(done, 1, "the earlier step completed"); assert_eq!(done, 1, "the earlier step completed");
assert_eq!(failed, 1, "the later step failed"); assert_eq!(failed, 1, "the later step failed");
} }
// -----------------------------------------------------------------------
// Adversarial approval-boundary tests.
// -----------------------------------------------------------------------
/// Build a plan whose digest is the canonical digest for its (actions,
/// candidate, effects), sealed for storage.
fn canonical_plan(
id: &str,
kind: PlanKind,
actions: Vec<SystemAction>,
candidate: Option<Candidate>,
effects: ResolvedPlan,
root: &Path,
uid: u32,
) -> PreparedPlan {
let digest = compute_plan_digest(&actions, candidate.as_ref(), &effects);
let step_effects = vec![effects.clone(); actions.len()];
let mut plan = PreparedPlan {
id: id.into(),
created_unix: now_unix(),
expires_unix: now_unix() + 900,
kind,
summary: "test plan".into(),
recommendation: "rec".into(),
application: Some("firefox".into()),
candidate,
alternatives: Vec::new(),
rationale: Vec::new(),
warnings: Vec::new(),
actions,
effects,
step_effects,
digest,
verification: "verify".into(),
requires_root: false,
source: "test".into(),
executed: false,
target_root: canonical_root(root),
initiator_uid: uid,
integrity: String::new(),
};
seal_plan(&mut plan);
plan
}
#[test]
fn a_general_plan_with_swapped_action_and_retained_approved_digest_is_rejected() {
let root = tempdir().unwrap();
let uid = effective_uid();
let reviewed = parse_emerge_pretend(VIM_PRETEND);
let substituted = parse_emerge_pretend(WGET_PRETEND);
let runner = RecordingRunner::new();
let exec = make_exec_with_runner(root.path(), Box::new(runner.clone()));
let store = PlanStore::with_dir(tempdir().unwrap().keep());
let approvals = ApprovalLedger::with_dir(tempdir().unwrap().keep());
let mut original = portage_install_plan(
"plan-swap",
SystemAction::InstallPackage {
atom: "app-editors/vim".into(),
binary: None,
},
reviewed,
root.path(),
uid,
);
store.save(&mut original).unwrap();
let approved = original.digest.clone();
// The attacker swaps the action and its effects, recomputes the
// self-consistency seal, but deliberately retains the previously
// approved digest.
let mut forged = portage_install_plan(
"plan-swap",
SystemAction::InstallPackage {
atom: "net-misc/wget".into(),
binary: None,
},
substituted,
root.path(),
uid,
);
forged.digest = approved.clone();
seal_plan(&mut forged);
store.save(&mut forged).unwrap();
let err = execute_plan_privileged(
&exec,
root.path(),
&store,
&approvals,
"plan-swap",
&approved,
uid,
true,
)
.unwrap_err();
assert!(
err.to_string().contains("digest does not match")
|| err.to_string().contains("approval digest mismatch"),
"{err}"
);
// Rejected before any command ran or any approval was consumed.
assert!(runner.recorded().is_empty(), "no command may run");
assert_eq!(ledger_entries(&approvals), 0, "nothing may be claimed");
assert!(transaction::read(root.path()).unwrap().records.is_empty());
// A more sophisticated forgery also recomputes the stored digest, but
// the independently preserved approved digest still differs.
let mut forged2 = portage_install_plan(
"plan-swap",
SystemAction::InstallPackage {
atom: "net-misc/wget".into(),
binary: None,
},
parse_emerge_pretend(WGET_PRETEND),
root.path(),
uid,
);
seal_plan(&mut forged2);
store.save(&mut forged2).unwrap();
let err = execute_plan_privileged(
&exec,
root.path(),
&store,
&approvals,
"plan-swap",
&approved,
uid,
true,
)
.unwrap_err();
assert!(err.to_string().contains("digest"), "{err}");
assert_eq!(ledger_entries(&approvals), 0);
}
#[test]
fn canonical_digest_is_recomputed_for_every_plan_kind() {
let root = tempdir().unwrap();
let uid = effective_uid();
let exec = make_test_exec(root.path());
let cand = sample_candidate();
// (kind, reviewed action, substituted action, candidate)
let cases: Vec<(PlanKind, SystemAction, SystemAction, Option<Candidate>)> = vec![
(
PlanKind::Install,
SystemAction::FlatpakInstall {
app_id: "org.mozilla.firefox".into(),
},
SystemAction::FlatpakInstall {
app_id: "org.chromium.Chromium".into(),
},
Some(cand.clone()),
),
(
PlanKind::LegacyInstall,
SystemAction::FlatpakInstall {
app_id: "org.mozilla.firefox".into(),
},
SystemAction::FlatpakInstall {
app_id: "org.chromium.Chromium".into(),
},
Some(cand.clone()),
),
(
PlanKind::Removal,
SystemAction::RemovePackage {
atom: "app-editors/vim".into(),
},
SystemAction::RemovePackage {
atom: "net-misc/wget".into(),
},
None,
),
(
PlanKind::General,
SystemAction::EnableService {
name: "sshd".into(),
},
SystemAction::DisableService {
name: "sshd".into(),
},
None,
),
(
PlanKind::Undo,
SystemAction::Undo { snapshot: None },
SystemAction::Undo {
snapshot: Some("other-snapshot".into()),
},
None,
),
];
for (idx, (kind, reviewed_action, substituted_action, candidate)) in
cases.into_iter().enumerate()
{
let id = format!("plan-kind-{idx}");
let reviewed = canonical_plan(
&id,
kind,
vec![reviewed_action],
candidate,
ResolvedPlan::default(),
root.path(),
uid,
);
let approved = reviewed.digest.clone();
// Substitute the action, retain the approved digest, reseal.
let mut forged = canonical_plan(
&id,
kind,
vec![substituted_action],
reviewed.candidate.clone(),
ResolvedPlan::default(),
root.path(),
uid,
);
forged.digest = approved.clone();
seal_plan(&mut forged);
let err = validate_prepared_plan(&exec, root.path(), &forged, Some(&approved), uid)
.unwrap_err();
assert!(
err.to_string().contains("digest"),
"kind {kind:?} must be rejected: {err}"
);
}
}
/// Execute a plan, then edit a presentation field, reseal, delete the user
/// claim and replay. The stable ledger identity must still refuse it.
fn replay_after_presentation_edit(field: &str) {
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-edit",
PlanKind::General,
vec![SystemAction::History],
"d",
root.path(),
uid,
);
store.save(&mut plan).unwrap();
let digest = plan.digest.clone();
execute_plan_privileged(
&exec,
root.path(),
&store,
&approvals,
"plan-replay-edit",
&digest,
uid,
true,
)
.unwrap();
// The user deletes their own claim and edits only a presentation field,
// then reseals.
let _ = std::fs::remove_file(store.dir().join("plan-replay-edit.claim"));
let mut tampered = store.load("plan-replay-edit").unwrap();
match field {
"summary" => tampered.summary = "a completely different summary".into(),
"recommendation" => tampered.recommendation = "edited".into(),
"rationale" => tampered.rationale = vec!["edited rationale".into()],
"verification" => tampered.verification = "edited verification".into(),
other => panic!("unknown field {other}"),
}
seal_plan(&mut tampered);
store.save(&mut tampered).unwrap();
let err = execute_plan_privileged(
&exec,
root.path(),
&store,
&approvals,
"plan-replay-edit",
&digest,
uid,
true,
)
.unwrap_err();
assert!(err.to_string().contains("already used"), "{err}");
}
#[test]
fn replay_after_editing_only_the_summary_is_rejected() {
replay_after_presentation_edit("summary");
}
#[test]
fn replay_after_editing_other_presentation_fields_is_rejected() {
replay_after_presentation_edit("recommendation");
replay_after_presentation_edit("rationale");
replay_after_presentation_edit("verification");
}
#[test]
fn recreating_an_identical_plan_under_the_same_id_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 plan = sealed(
"plan-identical",
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-identical",
&digest,
uid,
true,
)
.unwrap();
// Recreate byte-identical plan state under the original id.
std::fs::remove_file(&path).unwrap();
let _ = std::fs::remove_file(store.dir().join("plan-identical.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-identical",
&digest,
uid,
true,
)
.unwrap_err();
assert!(err.to_string().contains("already used"), "{err}");
}
#[test]
fn a_newly_reviewed_identical_operation_with_a_new_id_is_allowed() {
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();
// Two independently reviewed plans with identical content but distinct
// random identifiers: the first may not block the second.
for id in ["plan-fresh-a", "plan-fresh-b"] {
let mut plan = sealed(
id,
PlanKind::General,
vec![SystemAction::History],
"d",
root.path(),
uid,
);
let digest = plan.digest.clone();
store.save(&mut plan).unwrap();
execute_plan_privileged(
&exec,
root.path(),
&store,
&approvals,
id,
&digest,
uid,
true,
)
.unwrap_or_else(|e| panic!("{id} should be allowed: {e}"));
}
}
#[test]
fn a_live_claim_is_not_reconciled_but_an_abandoned_one_is() {
let root = tempdir().unwrap();
let uid = effective_uid();
let store = PlanStore::with_dir(tempdir().unwrap().keep());
let approvals = ApprovalLedger::with_dir(tempdir().unwrap().keep());
let mut live = sealed(
"plan-live",
PlanKind::General,
vec![SystemAction::History],
"d",
root.path(),
uid,
);
store.save(&mut live).unwrap();
let live_identity = approval_identity(&live, uid);
// Claimed with the real, currently running process.
approvals.claim(&live_identity).unwrap();
// A second broker starting must not mark the live operation interrupted.
assert_eq!(approvals.reconcile_interrupted().unwrap(), 0);
assert_eq!(
approvals.get(&live_identity.key).unwrap().unwrap().status,
"in_progress"
);
// An abandoned claim (owner gone) is recovered.
let mut dead = sealed(
"plan-dead",
PlanKind::General,
vec![SystemAction::History],
"d",
root.path(),
uid,
);
store.save(&mut dead).unwrap();
let dead_identity = approval_identity(&dead, uid);
approvals
.claim_with_owner(
&dead_identity,
crate::approval::ProcessIdentity {
pid: u32::MAX,
start_ticks: 1,
boot_id: String::new(),
},
)
.unwrap();
assert_eq!(approvals.reconcile_interrupted().unwrap(), 1);
assert_eq!(
approvals.get(&dead_identity.key).unwrap().unwrap().status,
"interrupted"
);
}
} }

View file

@ -245,6 +245,51 @@ fn a_personal_preference_is_saved_by_a_normal_account_outside_etc() {
.exists()); .exists());
} }
#[test]
fn a_personal_preference_is_refused_when_the_initiating_uid_differs_from_the_euid() {
if effective_uid_is_root() {
return;
}
let uid = std::process::Command::new("id")
.arg("-u")
.output()
.ok()
.and_then(|o| {
String::from_utf8_lossy(&o.stdout)
.trim()
.parse::<u32>()
.ok()
})
.expect("current uid");
let root = tempfile::tempdir().expect("temp root");
let personal = tempfile::tempdir().expect("personal dir");
// Simulate `sudo` on behalf of another user without root: the initiating
// uid differs from the effective uid, so the write must be refused rather
// than creating a file owned by the wrong user.
let out = sys()
.arg("--root")
.arg(root.path())
.env("PHOEBUS_PERSONAL_DIR", personal.path())
.env("SUDO_UID", (uid + 1).to_string())
.args([
"--legacy",
"--action",
r#"{"action":"set_package_preference","name":"firefox","backend":"flatpak"}"#,
])
.output()
.expect("run sys");
assert!(!out.status.success());
assert!(
String::from_utf8_lossy(&out.stderr).contains("refusing to write"),
"stderr: {}",
String::from_utf8_lossy(&out.stderr)
);
assert!(!personal
.path()
.join(".config/phoebus/package-preferences.toml")
.exists());
}
#[test] #[test]
fn conflicting_backend_flags_are_rejected_by_the_cli() { fn conflicting_backend_flags_are_rejected_by_the_cli() {
let out = sys() let out = sys()