Compare commits

...

5 commits

Author SHA1 Message Date
33d7959c3c docs: record hardening pass evidence (stage3, boot security, rollback)
Some checks are pending
ci / test (push) Waiting to run
2026-09-25 20:13:16 -07:00
5f6999631a fix(vm): rollback gate proves a real mutation and restore
The gate could pass vacuously: the guest ran unprivileged (every
mutation refused), used a pre-installed break package, restored the
newest snapshot instead of its own, and the driver never asserted the
root marker was gone. Now the driver authenticates sudo with unique
end markers and a verified timestamp, both phases run as root with
explicit --legacy, the break uses app-misc/hello (verified absent,
verified changed), undo targets the recorded snapshot id, and the
driver asserts the break changed the package DB and the root marker
is absent after the detached reboot.
2026-09-25 20:02:43 -07:00
744059b6a2 fix(vm): provision Gentoo release key; truthful rollback gate
Live image ships gnupg plus the Gentoo release key, fingerprint-checked
at build time against the published release-key fingerprints, so the
fail-closed DIGESTS verification cannot be silently skipped.

Rollback harness: authenticate sudo (unique end markers, verified
timestamp, abort instead of hanging), run both guest phases as root,
use explicit --legacy for snapshot/break/undo, fix the verify SYS path,
emit the real systemd state, and preserve the phase-1 transcript.
2026-09-25 19:49:50 -07:00
95e0d05344 fix(core): reject unimplemented secureboot/uki at validation
The installed boot path is plain unsigned BLS. kernel.uki=true and
kernel.secureboot=true are now rejected by validate_config (which the
CLI, TUI and GUI bridge all share) with errors naming the limitation.
The plan preview reports the real BLS path unconditionally and never
renders the requested flags as active. Golden plan updated; parsing,
validation and rendering regressions added.
2026-09-25 19:49:41 -07:00
216267064c fix(executor): fail closed on every stage3 verification failure
The unpinned stage3 path warned and continued when the DIGESTS download
failed, when no SHA-512 entry matched, when gpg or the Gentoo release key
was missing, when the key import failed, and when gpg could not start.
All of these now stop the install before extraction, as do a bad
signature and a hash mismatch. The pinned path requires a valid 64-hex
pin (placeholder refused) before any network use. require_tools covers
gpg/sha256sum/sha512sum and stage_install checks them first.

16 regression tests cover every failure branch (nonzero exit and
cannot-start for hash, probe, import and verify) plus both positive
paths.
2026-09-25 19:49:37 -07:00
21 changed files with 1016 additions and 109 deletions

View file

@ -3,6 +3,47 @@
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-26 — Hardening pass: fail-closed stage3, truthful boot security, rollback acceptance
- **Stage3 verification is fail-closed (security defect fixed).** The unpinned
path previously warned and continued when the DIGESTS download failed, when
no SHA-512 entry matched, when `gpg` or the Gentoo release key was missing,
when the key import failed, and when `gpg` could not start. Every one of
these now stops the install before extraction, as do a bad signature and a
hash mismatch. The pinned path requires a valid 64-hex digest (placeholder
refused) before any network use, and its trust is documented as coming from
the independently supplied pin. `stage_install` requires
`curl/tar/gpg/sha256sum/sha512sum` up front. 16 new regression tests cover
every failure branch plus both positive paths.
- **Live image carries the verifier.** `installer/live` ships `gnupg` and the
trusted Gentoo release key (`/usr/share/openpgp-keys/gentoo-release.asc`),
provisioned by `build.sh` and checked against Gentoo's published
release-key fingerprints; the installer never fetches an unauthenticated
key. Not yet VM-proven: no full install has run with the new binary, and
the signed-DIGESTS VM proof needs a rebuilt ISO with the key.
- **Boot security is truthful.** `kernel.uki`/`kernel.secureboot = true` are
rejected at shared configuration validation (CLI/TUI/GUI bridge), and the
plan preview always reports the real unsigned-BLS path. Authenticated boot
remains an open limitation by design (separate opt-in milestone).
- **Rollback acceptance PASSED with evidence**
(`serial-rollback-20260926T030237Z-912f6386`, PASS=11 FAIL=0, exit 0, no
secret leak): snapshot → `app-misc/hello` install (package DB changed) →
`sys undo <id>` → detached reboot (DB restored, root marker absent, `/home`
survives, systemd running, recovery entry present). This corrects the
2026-09-25 pass claim, which had no transcript and did not reproduce: the
harness ran unprivileged, used pre-installed `nano`, restored "newest", and
never asserted the marker. Fixed with sudo authentication, explicit
`--legacy`, a verified break, targeted undo, and vacuous-pass guards.
Recovery-entry offline boot stays a manual gate.
- **Release candidate (local, isolated):** manifest/verify, tampered-artifact
refusal, and publish refusal against the NotRun gate report all behave;
`gates --execute` is 0 passed / 6 NotRun (all gates need VM/seat/model).
Nothing published. Desktop-under-seat, live AI, and Snap
strict-confinement/changed-revision remain explicitly open (see STATUS).
- **Tests:** `cargo test --workspace` 712/712 (was 692), `test_vmsafety.py`
18/18, `cargo fmt --check` and `clippy -D warnings` clean, release and
static-pie builds pass.
## 2026-09-26 — Code quality pass: boxed ExecError, warning-free Clippy, service/gui_bridge splits ## 2026-09-26 — Code quality pass: boxed ExecError, warning-free Clippy, service/gui_bridge splits
Structural work only; no behavior, wire-format, or serialized-plan change. Structural work only; no behavior, wire-format, or serialized-plan change.

View file

@ -3,6 +3,48 @@
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.
- **Hardening pass (2026-09-26):** stage3 fail-closed + truthful boot
security + rollback acceptance PASS.
1. **Stage3 (security defect, fixed):** the unpinned path warned and
continued on DIGESTS-download failure, missing SHA-512 entry, missing
gpg/key, failed key import, and gpg launch errors. All stop the install
before extraction now; bad signature/hash also stop it. The pinned path
requires a valid 64-hex pin (placeholder refused) before any network
use. `stage_install` checks for `gpg`/`sha256sum`/`sha512sum` first.
16 new regression tests (every failure branch, nonzero-exit and
cannot-start doubles, both positive paths). The live image ships `gnupg`
plus the Gentoo release key, fingerprint-checked at build time against
Gentoo's published fingerprints (`13EB…2910` weekly, `D99E…2058`
signing). Commits `2162670`, `744059b`.
2. **Boot security (fixed):** `uki=true`/`secureboot=true` are rejected at
`validate_config` (shared by CLI/TUI/GUI bridge); the plan preview
always reports unsigned BLS. Parsing/validation/rendering regressions +
golden updated. Commit `95e0d05`. Authenticated boot stays an open
limitation (STATUS).
3. **Rollback acceptance PASSED for real**
(`serial-rollback-20260926T030237Z-912f6386`, PASS=11 FAIL=0, exit 0, no
secret leak): fresh overlay `rollback-accept-7.qcow2` on
`fresh-install-1.qcow2` — snapshot → `app-misc/hello` install (DB
`ca39…`→`fda3…`) → `sys undo <id>` rc=0 → detached reboot (DB restored,
root marker absent, `/home` survives, systemd running, recovery entry
present). The 2026-09-25 pass claim had no transcript and did not
reproduce; fixed harness defects: sudo auth (stale-prompt match bug
found and fixed with unique markers), root phases, explicit `--legacy`,
verified break (`nano` was pre-installed), targeted undo, marker-absent
assertion, preserved phase-1 log. Commits `744059b`, `5f69996`.
4. **Release candidate (local, isolated):** manifest (2 artifacts), verify,
tamper refusal, and publish refusal against the NotRun report all behave;
`gates --execute` is 0 passed / 6 NotRun (every gate needs VM/seat/model;
`run_gates` never executes gate commands itself). Nothing published.
5. Quality gates: `cargo fmt --check`, `cargo clippy --workspace
--all-targets -- -D warnings`, `cargo test --workspace` 712/712,
release + static-pie builds, `test_vmsafety.py` 18/18, `make doctor`
19 ok / 1 disk-space warning.
- **Interface contract (unchanged):** ordinary requests use AI; only explicit
`--legacy` selects deterministic handling; source flags constrain the AI and
never bypass it; a missing model stops the workflow and offers the exact
`--legacy` command without executing it.
- **Quality pass (2026-09-26):** boxed `ExecError::Command` details - **Quality pass (2026-09-26):** boxed `ExecError::Command` details
(`CommandFailure`, 128 → 96 bytes, measured with a path-dependent probe crate; (`CommandFailure`, 128 → 96 bytes, measured with a path-dependent probe crate;
constructor + all match sites updated, error text/redaction/stderr-tail constructor + all match sites updated, error text/redaction/stderr-tail
@ -126,9 +168,21 @@ commit it. It should be short and current; use `git log` for detail.
## Not completed / blocked ## Not completed / blocked
- **Stage3 VM proof with the new binary:** unit-tested (19 stage3 tests) and
the pinned path is unchanged for real pins, but no full install has run
with the fail-closed binary yet; the next disposable install is the proof.
The unpinned (signed-DIGESTS) VM proof additionally needs a rebuilt live
ISO carrying the provisioned key (`installer/live/build.sh` now provisions
it; no ISO was rebuilt in this session).
- **Installed Mango + DMS session under a seat:** still needs a
seat-providing graphical VM (or physical VT): login, kitty, DMS
spotlight, lock/idle, polkit agent, logout, reboot
(`docs/DEVELOPMENT.md` physical-VT procedure).
- **Snap update to a different revision / strict confinement:** refresh with no - **Snap update to a different revision / strict confinement:** refresh with no
newer revision and partial confinement were VM-verified. A revision-changing newer revision and partial confinement were VM-verified. A revision-changing
refresh and AppArmor-backed strict confinement were not. refresh and AppArmor-backed strict confinement were not (need an
AppArmor-ready guest kernel with loaded policy, and a Store snap that
actually has a newer revision than installed).
- **Live AI:** a local OpenAI-compatible model (`llama-server` + a GGUF model) - **Live AI:** a local OpenAI-compatible model (`llama-server` + a GGUF model)
was served on the host; the AI workflow reached the model, but the sandboxed was served on the host; the AI workflow reached the model, but the sandboxed
call exceeded the 120 s transport timeout on CPU (`curl` exit 28). Needs a call exceeded the 120 s transport timeout on CPU (`curl` exit 28). Needs a
@ -153,11 +207,15 @@ commit it. It should be short and current; use `git log` for detail.
## Next actions (in order) ## Next actions (in order)
1. **Recovery boot** by selecting the recovery BLS entry with the network down. 1. **Stage3 install proof:** next disposable install with the fail-closed
2. **Live AI** with a faster local model/GPU or an authorized provider binary (pinned path), then a rebuilt live ISO (with the provisioned
Gentoo key) proving the signed-DIGESTS path in the VM.
2. **Recovery boot** by selecting the recovery BLS entry with the network down.
3. **Live AI** with a faster local model/GPU or an authorized provider
credential (natural-language discovery, source constraints, reviewed install). credential (natural-language discovery, source constraints, reviewed install).
3. **Nix profile GC stability** if the dangling re-run is reproducible. 4. **Installed desktop under a seat** (Mango + DMS login through reboot).
4. **Snap strict confinement and changed-revision update** in a disposable VM 5. **Nix profile GC stability** if the dangling re-run is reproducible.
6. **Snap strict confinement and changed-revision update** in a disposable VM
when an AppArmor-ready kernel and a revision-changing Store test are available. when an AppArmor-ready kernel and a revision-changing Store test are available.
## Definition of a good stopping point ## Definition of a good stopping point

View file

@ -14,7 +14,7 @@ more interesting. Status vocabulary: **Done**, **Partial**, **Next**, **Later**.
| 7 | Finish Flatpak | Partial | `flatpak 1.18.1` installed, flathub configured; bounded typed `flatpak_*` actions added; no app installed yet | | 7 | Finish Flatpak | Partial | `flatpak 1.18.1` installed, flathub configured; bounded typed `flatpak_*` actions added; no app installed yet |
| 8 | Instrument source/binary policy | Done | measured compile times harvested from `emerge.log` (326 entries); resolved-effect previews added | | 8 | Instrument source/binary policy | Done | measured compile times harvested from `emerge.log` (326 entries); resolved-effect previews added |
| 9 | Background update preparation | Partial | distfile fetch VM-verified; `--buildpkgonly` skipped while deps need merging (recorded Ready); activation explicit | | 9 | Background update preparation | Partial | distfile fetch VM-verified; `--buildpkgonly` skipped while deps need merging (recorded Ready); activation explicit |
| 10 | Snapshots / rollback | Partial | snapshot sets + history VM-verified on Btrfs; coordinated rollback, `sys undo`, recovery entry, retention and free-space gate implemented + unit-tested; destructive VM acceptance test pending | | 10 | Snapshots / rollback | Partial | snapshot sets + history VM-verified on Btrfs; `sys undo` acceptance PASSED on a fresh disposable clone (`serial-rollback-20260926T030237Z-912f6386` PASS=11 FAIL=0: DB changed then restored, root marker gone, `/home` survives, boot running); retention + free-space gate unit-tested; offline recovery-entry boot remains a manual gate |
| 11 | AI privilege and privacy architecture | Partial | typed actions + enforced privacy boundary + guided proposal review + OS-level sandbox (systemd-run hardening) + approval-bound resolved effects; live call/sandbox not VM-verified | | 11 | AI privilege and privacy architecture | Partial | typed actions + enforced privacy boundary + guided proposal review + OS-level sandbox (systemd-run hardening) + approval-bound resolved effects; live call/sandbox not VM-verified |
| 12 | `sys` operations | Done | history, enable/disable, inspect, install, prepare-updates VM-verified; target-root consistency, execution-boundary validation, truthful `ask` failure, full transaction outcomes, empty-vs-unestablished plans, start/stop/restart + flatpak/nix/snapshot commands, deterministic `--legacy` administration, audited `--broker`/`--legacy` gates, unified multi-source updates, quiet proactive assistance, shared service layer (`phoebus_installer::service`), and 23-case VM acceptance suite (`sys-acceptance.sh` 23/23 PASS) | | 12 | `sys` operations | Done | history, enable/disable, inspect, install, prepare-updates VM-verified; target-root consistency, execution-boundary validation, truthful `ask` failure, full transaction outcomes, empty-vs-unestablished plans, start/stop/restart + flatpak/nix/snapshot commands, deterministic `--legacy` administration, audited `--broker`/`--legacy` gates, unified multi-source updates, quiet proactive assistance, shared service layer (`phoebus_installer::service`), and 23-case VM acceptance suite (`sys-acceptance.sh` 23/23 PASS) |
| 13 | Kernel optimization policy | Later | conservative fragments only; SAFE/OPTIMIZED/AGGRESSIVE selection exists | | 13 | Kernel optimization policy | Later | conservative fragments only; SAFE/OPTIMIZED/AGGRESSIVE selection exists |

View file

@ -37,8 +37,13 @@ A second harness (`installer/tests/vm/appliance-driver.py` +
produced `INSTALL-RC=0`, `NO_SECRET_LEAK`, and a detached boot produced `INSTALL-RC=0`, `NO_SECRET_LEAK`, and a detached boot
(`systemd`, running, 0 failed units) whose Btrfs history contains the installer's (`systemd`, running, 0 failed units) whose Btrfs history contains the installer's
coordinated `@` + `@var` **initial known-good** snapshot and a snapshot-based coordinated `@` + `@var` **initial known-good** snapshot and a snapshot-based
recovery boot entry (see `docs/VM-BOOT-VERIFICATION.md`). `sys undo` itself is recovery boot entry (see `docs/VM-BOOT-VERIFICATION.md`). `sys undo` is
still not VM-verified. VM-verified by the rollback acceptance gate
(`serial-rollback-20260926T030237Z-912f6386`, PASS=11 FAIL=0): snapshot →
`app-misc/hello` install (package DB changed) → `sys undo <id>` → detached
reboot with the package DB restored, the root break marker gone, `/home`
preserved, systemd running, and the snapshot-based recovery entry present.
Booting that recovery entry offline remains a manual gate.
## Matrix ## Matrix
@ -52,7 +57,7 @@ still not VM-verified.
| LUKS2 format/open/close | yes | yes | yes | no | | LUKS2 format/open/close | yes | yes | yes | no |
| Btrfs subvolumes + swapfile | yes | yes | yes | no | | Btrfs subvolumes + swapfile | yes | yes | yes | no |
| fstab / crypttab generation | yes | yes | yes | no | | fstab / crypttab generation | yes | yes | yes | no |
| stage3 fetch + SHA-256 verify + extract | yes | yes | yes | n/a | | stage3 fetch + verify (pinned SHA-256 or signed DIGESTS) + extract | yes | yes (both paths; every failure branch incl. missing verifier/key/DIGESTS/entry, nonzero exit, cannot-start) | yes (pinned path; unpinned path needs the live-image key) | n/a |
| Portage config + sync + getuto | yes | yes | yes | n/a | | Portage config + sync + getuto | yes | yes | yes | n/a |
| Signed Gentoo binary install | yes | yes | yes | n/a | | Signed Gentoo binary install | yes | yes | yes | n/a |
| Source package compilation | yes | yes | yes | n/a | | Source package compilation | yes | yes | yes | n/a |
@ -76,8 +81,8 @@ still not VM-verified.
| Background update preparation | yes | yes | yes (fetch; buildpkgonly skipped) | no | | Background update preparation | yes | yes | yes (fetch; buildpkgonly skipped) | no |
| Btrfs snapshots + history | yes | yes | yes | no | | Btrfs snapshots + history | yes | yes | yes | no |
| Coordinated snapshot sets (`@` + `@var`) | yes | yes | no | no | | Coordinated snapshot sets (`@` + `@var`) | yes | yes | no | no |
| Btrfs rollback (`sys undo`) | yes | yes | no | no | | Btrfs rollback (`sys undo`) | yes | yes | yes (rollback acceptance `serial-rollback-20260926T030237Z-912f6386` PASS=11 FAIL=0) | no |
| Recovery/known-good BLS entry | yes | yes | no | no | | Recovery/known-good BLS entry | yes | yes | present + snapshot-based (asserted in the rollback run; offline boot is a manual gate) | no |
| Snapshot retention + free-space gate | yes | yes | no | no | | Snapshot retention + free-space gate | yes | yes | no | no |
| AI typed proposals + evidence review | yes | yes | fixture end-to-end | n/a | | AI typed proposals + evidence review | yes | yes | fixture end-to-end | n/a |
| AI guided install (DeepSeek/OpenAI) | yes | yes | fixture path only (no live call) | n/a | | AI guided install (DeepSeek/OpenAI) | yes | yes | fixture path only (no live call) | n/a |
@ -96,7 +101,7 @@ still not VM-verified.
| Installed `sys` acceptance matrix (read-only/failure) | yes | yes | yes (installed VM: `PASS=38 FAIL=0`, catalogue + regression group) | no | | Installed `sys` acceptance matrix (read-only/failure) | yes | yes | yes (installed VM: `PASS=38 FAIL=0`, catalogue + regression group) | no |
| Portage config readable for non-root queries (`normalize_config_permissions`) | yes | yes (modes + keyring exclusion) | yes (fresh VM install: 0755/0644 out of the box; non-root `search` returns 3 results, `updates` reports 10) | no | | Portage config readable for non-root queries (`normalize_config_permissions`) | yes | yes (modes + keyring exclusion) | yes (fresh VM install: 0755/0644 out of the box; non-root `search` returns 3 results, `updates` reports 10) | no |
| Privileged catalogue mutations (install/remove/depclean/cache/apply updates, alternate-root) | yes | yes (unit) | yes (fresh installed VM via root: 7/7 PASS) | no | | Privileged catalogue mutations (install/remove/depclean/cache/apply updates, alternate-root) | yes | yes (unit) | yes (fresh installed VM via root: 7/7 PASS) | no |
| Rollback acceptance (snapshot -> change -> `sys undo` -> detached verify) | yes | yes | yes (clone: package DB restored, root marker gone, `/home` survives, boot running) | no | | Rollback acceptance (snapshot -> change -> `sys undo` -> detached verify) | yes | yes | yes (`serial-rollback-20260926T030237Z-912f6386` PASS=11 FAIL=0 on a fresh disposable clone: package DB changed then restored, root marker gone, `/home` survives, boot running, no secret leak) | no |
| Privileged `--broker` plan execution + replay rejection in a VM (pkexec path) | yes | yes (privileged entry point) | yes (non-root `pkexec` with a terminal polkit agent: cancelled auth, broker JSON success, replay rejected; required the shipped policy + wheel-admin rule) | n/a | | Privileged `--broker` plan execution + replay rejection in a VM (pkexec path) | yes | yes (privileged entry point) | yes (non-root `pkexec` with a terminal polkit agent: cancelled auth, broker JSON success, replay rejected; required the shipped policy + wheel-admin rule) | n/a |
| Cache-cleanup preview is non-destructive (real `eclean`/`nix-store`) | yes | yes (preview uses `--pretend --deep` / `--print-dead`; sorted bound items) | yes (real `eclean`: upstream preview, cancelled approval, approved run, drift refusal, failed cleaner; user data preserved) | n/a | | Cache-cleanup preview is non-destructive (real `eclean`/`nix-store`) | yes | yes (preview uses `--pretend --deep` / `--print-dead`; sorted bound items) | yes (real `eclean`: upstream preview, cancelled approval, approved run, drift refusal, failed cleaner; user data preserved) | n/a |
| Reverse-dependency inspection includes installed targets | yes | yes (self-reference compares the dependent, not the target) | yes (real `sys-libs/glibc`, `sys-libs/zlib` dependents) | n/a | | Reverse-dependency inspection includes installed targets | yes | yes (self-reference compares the dependent, not the target) | yes (real `sys-libs/glibc`, `sys-libs/zlib` dependents) | n/a |
@ -145,17 +150,17 @@ still not VM-verified.
| GUI readiness refresh / AI revalidation / keyboard nav | yes | yes (Rust) | VM harness regressions | n/a | | GUI readiness refresh / AI revalidation / keyboard nav | yes | yes (Rust) | VM harness regressions | n/a |
| Mandatory AI requires a validated interaction | yes | yes | bridge + CLI | n/a | | Mandatory AI requires a validated interaction | yes | yes | bridge + CLI | n/a |
| GURU packaging (scoped keywords) | yes | yes | no (build/install unverified) | no | | GURU packaging (scoped keywords) | yes | yes | no (build/install unverified) | no |
| Release gates + atomic publish | yes | yes | no | n/a | | Release gates + atomic publish | yes | yes (NotRun-is-not-pass; tamper/publish-refusal exercised via host CLI) | no (no end-to-end candidate: VM/graphical/model gates need a runner) | n/a |
| `sys` verbs | yes | yes | yes | no | | `sys` verbs | yes | yes | yes | no |
| OpenCode pinned bootstrap | yes | yes | no | n/a | | OpenCode pinned bootstrap | yes | yes | no | n/a |
| Release manifest/verify | yes | yes | no | n/a | | Release manifest/verify | yes | yes (host CLI: manifest, verify, tampered-artifact refusal) | no | n/a |
| NVIDIA PCI device classification + branch/flavor policy | yes | yes | no | no | | NVIDIA PCI device classification + branch/flavor policy | yes | yes | no | no |
| NVIDIA installed Gentoo integration (Portage/modprobe/dracut/initramfs) | yes | yes | no | no | | NVIDIA installed Gentoo integration (Portage/modprobe/dracut/initramfs) | yes | yes | no | no |
| NVIDIA live ISO payload (bundled modules/firmware/userspace) | yes | yes (verifier + guards) | no | no | | NVIDIA live ISO payload (bundled modules/firmware/userspace) | yes | yes (verifier + guards) | no | no |
| NVIDIA kernel/module/initramfs update coordination (`@module-rebuild`) | yes | yes | no | no | | NVIDIA kernel/module/initramfs update coordination (`@module-rebuild`) | yes | yes | no | no |
| NVIDIA live GPU decision + real nouveau fallback | yes | yes (fixtures + CLI) | no | no | | NVIDIA live GPU decision + real nouveau fallback | yes | yes (fixtures + CLI) | no | no |
| Live GUI broker scoped sudoers (no `NOPASSWD: ALL`) | yes | yes (`visudo`) | no | n/a | | Live GUI broker scoped sudoers (no `NOPASSWD: ALL`) | yes | yes (`visudo`) | no | n/a |
| Rollback acceptance harness mode | yes | yes (bash -n/unit) | destructive gate unrun | no | | Rollback acceptance harness mode | yes | yes (bash -n/unit + vacuous-pass guards) | yes (destructive gate `serial-rollback-20260926T030237Z-912f6386` PASS=11 FAIL=0) | no |
| Desktop assistant GUI (`phoebus-assistant`) | yes | yes | yes (live VM layout) | no | | Desktop assistant GUI (`phoebus-assistant`) | yes | yes | yes (live VM layout) | no |
| Desktop assistant JSON-RPC bridge (`sys --assistant-bridge`) | yes | yes | yes (acceptance matrix) | n/a | | Desktop assistant JSON-RPC bridge (`sys --assistant-bridge`) | yes | yes | yes (acceptance matrix) | n/a |
| AI-first administration contract (`sys install`, `please`, `ask`) | yes | yes | yes (acceptance matrix) | no | | AI-first administration contract (`sys install`, `please`, `ask`) | yes | yes | yes (acceptance matrix) | no |
@ -179,7 +184,7 @@ still not VM-verified.
| Conversation-history privacy (minimized, redacted, 0600, bounded, clearable) | yes | yes | no | n/a | | Conversation-history privacy (minimized, redacted, 0600, bounded, clearable) | yes | yes | no | n/a |
| Target desktop QML assets & Polkit policy provisioning | yes | yes | yes (live VM layout) | no | | Target desktop QML assets & Polkit policy provisioning | yes | yes | yes (live VM layout) | no |
| Desktop assistant unprivileged execution & Polkit elevation | yes | yes | yes (live VM layout) | no | | Desktop assistant unprivileged execution & Polkit elevation | yes | yes | yes (live VM layout) | no |
| UKI | no (deferred) | no | no | no | | UKI / Secure Boot | no (deferred; `uki`/`secureboot = true` rejected at validation) | no (rejection + truthful plan rendering covered) | no | no |
## Known limitations ## Known limitations
@ -226,23 +231,37 @@ still not VM-verified.
fetched to `/tmp/sys` on a disposable overlay of the pristine installed fetched to `/tmp/sys` on a disposable overlay of the pristine installed
image, non-root user, no mutations): guest `PASS=38 FAIL=0`, driver image, non-root user, no mutations): guest `PASS=38 FAIL=0`, driver
`PASS=41 FAIL=0` (`serial-boot-20260926T014746Z-3089a820`). `PASS=41 FAIL=0` (`serial-boot-20260926T014746Z-3089a820`).
- **UKI** is deferred; the dracut UKI generator did not embed the kernel - **Authenticated boot (UKI / UEFI Secure Boot) is not implemented and is an
command line, so BLS is used (and verified). open security limitation.** The installed boot path is plain unsigned BLS
- **Rollback (`sys undo`) is NOT VM-verified.** It is implemented and (systemd-boot + dracut; the dracut UKI generator did not embed the kernel
unit-tested end to end at the command/text layer (snapshot sets, root/var command line, so BLS is used and verified). `kernel.uki = true` and
generation, fstab and BLS rewriting, kernel selection, interruption resume, `kernel.secureboot = true` are rejected at configuration validation, and the
retention, free-space gate). The harness now **automates the acceptance install-plan preview always reports the real BLS path, so no interface can
sequence** (`serial-driver.py rollback` + `rollback-guest.sh` / imply these modes are active. A future Secure Boot/UKI implementation is a
`rollback-verify.sh`): a known-good package-database fingerprint and `/home` separate opt-in milestone (signed artifacts, key lifecycle, update/rollback
marker, `sys snapshot`, a controlled reversible package install, `sys undo`, handling, disposable-VM boot tests with Secure Boot enabled); it must not be
detached reboot, then package-state/home comparison, kernel-module check and enabled or advertised until that complete path passes.
recovery-entry/status evidence. The destructive gate itself is **unrun in - **Rollback (`sys undo`) is VM-verified** (`serial-rollback-20260926T030237Z-912f6386`,
this session**: a full GUI install was occupying the only disposable disk. PASS=11 FAIL=0, exit 0, no secret leak in either transcript). The gate runs on
`make doctor` now reports ~29 GiB free (the disk blocker recorded in the last a fresh disposable overlay of the installed image: a known-good
handoff has eased), but the acceptance run needs a dedicated already-installed package-database fingerprint and `/home` marker, `sys snapshot --legacy`, a
disposable clone; the exact commands are in `docs/HANDOFF.md`. Booting the controlled reversible `app-misc/hello` install `--legacy --portage` (the
recovery entry offline is still a manual step. `sys undo` is present; treat the fingerprint is asserted changed, so the run cannot pass vacuously),
VM gate as unpassed before relying on it. `sys undo <snapshot-id> --legacy`, power off, then a detached reboot that
asserts the package database restored, the root break marker absent, `/home`
surviving, systemd running, kernel modules present, the snapshot-based
recovery entry present, and rollback status recorded. Both transcripts are
kept (`serial-phase1.log`, `serial.log`).
Correction: the 2026-09-25 claim of a passing rollback had no run transcript
and did not reproduce — the committed harness then ran the guest
unprivileged, used the pre-installed `nano` as the break, restored "newest"
instead of its own snapshot, and never asserted the root marker was gone.
Those harness defects are fixed in this session (sudo authentication with
unique end markers, explicit `--legacy`, verified break, targeted undo,
marker-absent assertion) and the gate above is the evidence. Booting the
recovery entry itself offline (no network, no model) remains a manual,
un-automated gate: select "Phoebus Recovery (known-good snapshot)" in the
systemd-boot menu.
- **Mango + DankMaterialShell** is the canonical Phoebus desktop - **Mango + DankMaterialShell** is the canonical Phoebus desktop
(`desktop.profile = "mango"`, Flatpak on). It is implemented with Mango (`desktop.profile = "mango"`, Flatpak on). It is implemented with Mango
0.17.2, DMS (pinned release), Quickshell 0.3.1 and scenefx 0.5 from the GURU 0.17.2, DMS (pinned release), Quickshell 0.3.1 and scenefx 0.5 from the GURU
@ -276,7 +295,13 @@ still not VM-verified.
enforced. enforced.
- **Release automation** now has gates, a report, atomic publish and signing - **Release automation** now has gates, a report, atomic publish and signing
command helpers, but no gate has been executed by a configured CI runner; the command helpers, but no gate has been executed by a configured CI runner; the
report records unexecuted gates as `NotRun`. report records unexecuted gates as `NotRun`. A local isolated candidate run
(2026-09-26) exercised manifest generation (2 artifacts), verification,
tampered-artifact refusal, and publish refusal against a NotRun gate report;
`gates --execute` reports 0 passed / 6 NotRun because every candidate gate
requires a VM, a graphical seat, or a model. No release was published and
`latest.iso` untouched. Minimal repeatable setup: register a Forgejo Actions
runner (`act_runner`) so `.forgejo/workflows/ci.yml` executes the gates.
- The desktop transaction compiles heavily because desktop USE does not match - The desktop transaction compiles heavily because desktop USE does not match
the signed binhost (~26 min for the desktop set on 8 vCPUs in the test VM). the signed binhost (~26 min for the desktop set on 8 vCPUs in the test VM).
The official Gentoo binhost is OpenRC/hardened, so a systemd system can only The official Gentoo binhost is OpenRC/hardened, so a systemd system can only
@ -289,5 +314,5 @@ still not VM-verified.
- The installer rebuilds `sys-apps/systemd` from source because - The installer rebuilds `sys-apps/systemd` from source because
boot/policykit/cryptsetup USE differ from the binhost. boot/policykit/cryptsetup USE differ from the binhost.
- `sys undo` is implemented with the default-subvolume, fstab, kernel-cmdline - `sys undo` is implemented with the default-subvolume, fstab, kernel-cmdline
and BLS handling described in ADR 0007; its destructive VM acceptance test is and BLS handling described in ADR 0007; its destructive VM acceptance gate
the remaining safety gate. passed in this session (`serial-rollback-20260926T030237Z-912f6386`).

View file

@ -409,6 +409,34 @@ harness requires, and no already-installed disposable clone is available.
Booting the recovery entry offline is still a manual step. `sys undo` therefore Booting the recovery entry offline is still a manual step. `sys undo` therefore
remains **unverified**, not passing. remains **unverified**, not passing.
**2026-09-26 update — rollback acceptance PASSED.**
`serial-driver.py rollback` on a fresh disposable overlay
(`rollback-accept-7.qcow2`, backing `fresh-install-1.qcow2`, original
preserved; backing chain validated with `qemu-img info --backing-chain`):
driver `serial-rollback-20260926T030237Z-912f6386` **PASS=11 FAIL=0**,
exit 0, no secret leak in either transcript (both kept:
`serial-phase1.log`, `serial.log` under
`/var/tmp/phoebus-vm/serial-rollback-20260926T030237Z-23d1bc0c/`).
- Phase 1: known-good DB fingerprint `ca398d71…`, `sys snapshot --legacy`
→ `@-20260926T030259-rollback-acceptance`, controlled
`app-misc/hello` install `--legacy --portage` → fingerprint changed to
`fda3780a…` (a no-op break would fail the gate here), root marker written,
`sys undo @-20260926T030259-rollback-acceptance --legacy` → rc=0.
- Phase 2 (detached): DB fingerprint back to `ca398d71…`, `/home` marker
identical, root marker **absent**, `systemctl is-system-running` →
`running`, kernel modules present, `phoebus-recovery.conf` present with
`systemd.unit=rescue.target` and a `@snapshots/` root, rollback status
recorded.
- Harness defects fixed to earn this (all previously allowed vacuous
passes): sudo authentication with unique end markers and a verified
timestamp, both phases as root, explicit `--legacy`, break package
verified absent then verified changed (`nano` was already in the base
image), undo targeting the recorded snapshot id, driver assertions for a
changed break and an absent root marker.
- Still manual: booting the recovery entry itself offline (select it in the
systemd-boot menu with no network).
**2026-09-23 update — NVIDIA gates still NOT run.** The live driver decision, **2026-09-23 update — NVIDIA gates still NOT run.** The live driver decision,
the hardened payload verifier and the installed lifecycle are implemented and the hardened payload verifier and the installed lifecycle are implemented and
covered by Rust/fixture tests, but no NVIDIA-accelerated boot has been observed: covered by Rust/fixture tests, but no NVIDIA-accelerated boot has been observed:

View file

@ -795,4 +795,20 @@ STAGE3_SHA256='abc'\n";
let text = "[storage]\nfilesystem = \"zfs\"\n"; let text = "[storage]\nfilesystem = \"zfs\"\n";
assert!(InstallConfig::from_toml(text).is_err()); assert!(InstallConfig::from_toml(text).is_err());
} }
#[test]
fn boot_security_keys_parse_so_validation_can_reject_them() {
// The keys stay parseable (legacy + TOML) so a request is rejected
// with a named field error, never silently ignored.
let legacy = InstallConfig::from_legacy("KERNEL_UKI='yes'\nSECUREBOOT='yes'\n").unwrap();
assert!(legacy.kernel.uki);
assert!(legacy.kernel.secureboot);
let toml = InstallConfig::from_toml("[kernel]\nuki = true\nsecureboot = true\n").unwrap();
assert!(toml.kernel.uki);
assert!(toml.kernel.secureboot);
// Defaults stay plain BLS.
let defaults = InstallConfig::default();
assert!(!defaults.kernel.uki);
assert!(!defaults.kernel.secureboot);
}
} }

View file

@ -142,10 +142,10 @@ impl InstallPlan {
" Bootloader : {} (BLS entries)\n", " Bootloader : {} (BLS entries)\n",
"systemd-boot" "systemd-boot"
)); ));
o.push_str(&format!( // Authenticated boot is not implemented. Report the actual BLS boot
" Unified UKI : {} (deferred; BLS used)\n", // path unconditionally: never render the requested flags as active.
if config.kernel.uki { "yes" } else { "no" } o.push_str(" Unified UKI : not implemented (BLS entries used)\n");
)); o.push_str(" Secure Boot : not implemented (boot chain unsigned)\n");
let profile = match config.kernel.profile { let profile = match config.kernel.profile {
KernelProfile::Safe => "safe", KernelProfile::Safe => "safe",
KernelProfile::Optimized => "optimized", KernelProfile::Optimized => "optimized",
@ -300,4 +300,23 @@ mod tests {
let boot = names.iter().position(|n| *n == "boot_install").unwrap(); let boot = names.iter().position(|n| *n == "boot_install").unwrap();
assert!(kernel < nvidia && nvidia < boot); assert!(kernel < nvidia && nvidia < boot);
} }
#[test]
fn boot_preview_reports_plain_bls_and_never_an_active_uki() {
let cfg = InstallConfig::default();
let text = InstallPlan::for_config(&cfg).render_human(&cfg, None);
assert!(text.contains("systemd-boot (BLS entries)"));
assert!(text.contains("Unified UKI : not implemented (BLS entries used)"));
assert!(text.contains("Secure Boot : not implemented (boot chain unsigned)"));
// Even a config that requests UKI/Secure Boot must not render them
// as active (validation rejects such configs; the preview is the
// backstop).
let mut requested = InstallConfig::default();
requested.kernel.uki = true;
requested.kernel.secureboot = true;
let text = InstallPlan::for_config(&requested).render_human(&requested, None);
assert!(!text.contains("Unified UKI : yes"), "{text}");
assert!(!text.contains("Secure Boot : enabled"), "{text}");
assert!(text.contains("not implemented"), "{text}");
}
} }

View file

@ -226,6 +226,23 @@ pub fn validate_config(config: &InstallConfig) -> Vec<ValidationIssue> {
"keep at least 2 kernels so a known-good kernel is available", "keep at least 2 kernels so a known-good kernel is available",
)); ));
} }
// Authenticated boot is not implemented: the installed boot path is
// plain BLS (systemd-boot + dracut, no signing, no UKI). Accepting these
// flags would imply a security property the system does not provide, so
// they are rejected here — before the CLI, TUI, GUI, or plan preview can
// present them as active. See the "UKI" row in docs/STATUS.md.
if config.kernel.uki {
issues.push(ValidationIssue::new(
"uki",
"Unified Kernel Images are not implemented; the installer uses plain BLS entries (uki must be false)",
));
}
if config.kernel.secureboot {
issues.push(ValidationIssue::new(
"secureboot",
"UEFI Secure Boot is not implemented; the boot chain is unsigned (secureboot must be false)",
));
}
if config.packages.accept_license.trim().is_empty() { if config.packages.accept_license.trim().is_empty() {
issues.push(ValidationIssue::new( issues.push(ValidationIssue::new(
"accept_license", "accept_license",
@ -332,4 +349,37 @@ mod tests {
.iter() .iter()
.all(|i| i.field != "target_disk")); .all(|i| i.field != "target_disk"));
} }
#[test]
fn unimplemented_boot_security_flags_are_rejected() {
// Parsing still accepts the legacy keys so the error names the field;
// validation rejects them because the boot path is plain unsigned BLS.
let mut cfg = InstallConfig::default();
cfg.system.hostname = "phoebus".into();
cfg.system.timezone = "UTC".into();
cfg.user.username = "alice".into();
cfg.storage.disk = "/dev/vda".into();
assert!(validate_config(&cfg).iter().all(|i| i.field != "uki"));
assert!(validate_config(&cfg)
.iter()
.all(|i| i.field != "secureboot"));
cfg.kernel.uki = true;
let issues = validate_config(&cfg);
let uki = issues
.iter()
.find(|i| i.field == "uki")
.expect("uki rejected");
assert!(uki.message.contains("not implemented"), "{uki}");
cfg.kernel.uki = false;
cfg.kernel.secureboot = true;
let issues = validate_config(&cfg);
let sb = issues
.iter()
.find(|i| i.field == "secureboot")
.expect("secureboot rejected");
assert!(sb.message.contains("not implemented"), "{sb}");
assert!(sb.message.contains("unsigned"), "{sb}");
}
} }

View file

@ -1,9 +1,21 @@
//! Gentoo stage3 acquisition and verification. //! Gentoo stage3 acquisition and verification.
//! //!
//! The stage3 tarball may be pinned (URL + SHA-256) or resolved from the //! Two verification paths, both fail closed:
//! Gentoo mirror. Unpinned downloads verify the signed DIGESTS file and its //!
//! SHA-512 entry. Signature verification fails closed when gpg and the Gentoo //! - Pinned (URL + SHA-256): the pin must be a valid 64-digit hex digest. Its
//! release key are available. //! trust comes from being supplied independently of the download (test
//! config, build manifest), never from the mirror. The tarball hash must
//! match before extraction.
//! - Unpinned (mirror resolution, the default): the tarball must be
//! accompanied by Gentoo's signed DIGESTS file. The DIGESTS signature must
//! verify against the trusted Gentoo release key with `gpg`, and the
//! tarball's SHA-512 must match the signed entry, following Gentoo's stage3
//! verification guidance (`gpg --verify <tarball>.DIGESTS`, then compare the
//! SHA-512 hash).
//!
//! A missing verifier, key, DIGESTS file, or hash entry stops the install. A
//! bad signature or a mismatched hash stops the install. Nothing warns and
//! continues.
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
@ -13,8 +25,24 @@ use crate::command::{CommandOutput, CommandSpec};
use crate::error::{ExecError, Result}; use crate::error::{ExecError, Result};
use crate::exec::Exec; use crate::exec::Exec;
/// Trusted Gentoo release public key shipped in the live installer image.
/// The build provisions this file and checks its fingerprint against Gentoo's
/// published release-key information
/// (https://www.gentoo.org/downloads/signatures/); the installer never
/// fetches an unauthenticated key.
pub const GENTOO_RELEASE_KEY: &str = "/usr/share/openpgp-keys/gentoo-release.asc";
/// Path of the trusted Gentoo release key. `PHOEBUS_GENTOO_RELEASE_KEY`
/// overrides it for tests; production always uses [`GENTOO_RELEASE_KEY`].
pub fn release_key_path() -> PathBuf {
match std::env::var("PHOEBUS_GENTOO_RELEASE_KEY") {
Ok(dir) if !dir.is_empty() => PathBuf::from(dir),
_ => PathBuf::from(GENTOO_RELEASE_KEY),
}
}
pub fn require_tools(exec: &Exec) -> Result<()> { pub fn require_tools(exec: &Exec) -> Result<()> {
exec.require_tools(&["curl", "tar"]) exec.require_tools(&["curl", "tar", "gpg", "sha256sum", "sha512sum"])
} }
/// Resolve the stage3 download URL. /// Resolve the stage3 download URL.
@ -45,8 +73,10 @@ pub fn resolve_url(exec: &Exec, config: &InstallConfig) -> Result<String> {
} }
fn hash_file(exec: &Exec, program: &str, path: &Path) -> Result<String> { fn hash_file(exec: &Exec, program: &str, path: &Path) -> Result<String> {
let out = exec.runner.execute( // Routed through `Exec::run` so a nonzero exit status fails closed; only
&CommandSpec::new("stage_install", "hash stage3", program).arg(path.to_string_lossy()), // the hash on a successful run is accepted.
let out = exec.run(
CommandSpec::new("stage_install", "hash stage3", program).arg(path.to_string_lossy()),
)?; )?;
out.stdout_lossy() out.stdout_lossy()
.split_whitespace() .split_whitespace()
@ -55,8 +85,30 @@ fn hash_file(exec: &Exec, program: &str, path: &Path) -> Result<String> {
.ok_or_else(|| ExecError::operation("stage_install", "hash", "empty hash output")) .ok_or_else(|| ExecError::operation("stage_install", "hash", "empty hash output"))
} }
/// A pinned SHA-256 must be 64 hex digits and not a placeholder. The pin is
/// trusted only because it was supplied independently of the download.
fn validate_pin(pin: &str) -> Result<()> {
let valid = pin.len() == 64
&& pin.chars().all(|c| c.is_ascii_hexdigit())
&& !pin.chars().all(|c| c == '0');
if !valid {
return Err(ExecError::operation(
"stage_install",
"verify stage3",
"pinned STAGE3_SHA256 must be 64 hex digits (a real digest supplied \
independently of the download); refusing to install",
));
}
Ok(())
}
/// Download and verify the stage3 tarball into `state_dir`. /// Download and verify the stage3 tarball into `state_dir`.
pub fn fetch(exec: &Exec, config: &InstallConfig, state_dir: &Path) -> Result<PathBuf> { pub fn fetch(exec: &Exec, config: &InstallConfig, state_dir: &Path) -> Result<PathBuf> {
// The pinned path trusts the independently supplied digest, never the
// mirror: require a valid pin before any network use.
if !config.stage3.sha256.is_empty() {
validate_pin(&config.stage3.sha256)?;
}
let url = resolve_url(exec, config)?; let url = resolve_url(exec, config)?;
let dest = state_dir.join("stage3-systemd.tar.xz"); let dest = state_dir.join("stage3-systemd.tar.xz");
std::fs::create_dir_all(state_dir).map_err(|e| ExecError::io(state_dir.to_path_buf(), e))?; std::fs::create_dir_all(state_dir).map_err(|e| ExecError::io(state_dir.to_path_buf(), e))?;
@ -70,8 +122,9 @@ pub fn fetch(exec: &Exec, config: &InstallConfig, state_dir: &Path) -> Result<Pa
)?; )?;
if !config.stage3.sha256.is_empty() { if !config.stage3.sha256.is_empty() {
// The pin was validated above; require the download to match it.
let got = hash_file(exec, "sha256sum", &dest)?; let got = hash_file(exec, "sha256sum", &dest)?;
if got != config.stage3.sha256 { if !got.eq_ignore_ascii_case(&config.stage3.sha256) {
return Err(ExecError::operation( return Err(ExecError::operation(
"stage_install", "stage_install",
"verify stage3", "verify stage3",
@ -91,17 +144,24 @@ pub fn fetch(exec: &Exec, config: &InstallConfig, state_dir: &Path) -> Result<Pa
} }
fn verify_digests(exec: &Exec, url: &str, dest: &Path) -> Result<()> { fn verify_digests(exec: &Exec, url: &str, dest: &Path) -> Result<()> {
verify_digests_with_key(exec, url, dest, &release_key_path())
}
fn verify_digests_with_key(exec: &Exec, url: &str, dest: &Path, key: &Path) -> Result<()> {
let digests = dest.with_extension("xz.DIGESTS"); let digests = dest.with_extension("xz.DIGESTS");
let spec = CommandSpec::new("stage_install", "download stage3 DIGESTS", "curl") let spec = CommandSpec::new("stage_install", "download stage3 DIGESTS", "curl")
.args(["-fsSL", "-o"]) .args(["-fsSL", "-o"])
.arg(digests.to_string_lossy().to_string()) .arg(digests.to_string_lossy().to_string())
.arg(format!("{url}.DIGESTS")); .arg(format!("{url}.DIGESTS"));
if exec.run(spec).is_err() { if let Err(e) = exec.run(spec) {
exec.logger let _ = std::fs::remove_file(&digests);
.warn("could not fetch stage3 DIGESTS; checksum not verified"); return Err(ExecError::operation(
return Ok(()); "stage_install",
"verify stage3",
format!("could not fetch the signed stage3 DIGESTS; refusing to install an unverified stage3 ({e})"),
));
} }
if let Err(e) = verify_signature(exec, &digests) { if let Err(e) = verify_signature_with_key(exec, &digests, key) {
let _ = std::fs::remove_file(&digests); let _ = std::fs::remove_file(&digests);
return Err(e); return Err(e);
} }
@ -110,12 +170,14 @@ fn verify_digests(exec: &Exec, url: &str, dest: &Path) -> Result<()> {
let want = parse_digests_sha512(&text, base); let want = parse_digests_sha512(&text, base);
let _ = std::fs::remove_file(&digests); let _ = std::fs::remove_file(&digests);
let Some(want) = want else { let Some(want) = want else {
exec.logger return Err(ExecError::operation(
.warn("no SHA-512 entry found in DIGESTS; checksum not verified"); "stage_install",
return Ok(()); "verify stage3",
"no SHA-512 entry for the stage3 tarball in the signed DIGESTS; refusing to install",
));
}; };
let got = hash_file(exec, "sha512sum", dest)?; let got = hash_file(exec, "sha512sum", dest)?;
if got != want { if !got.eq_ignore_ascii_case(&want) {
return Err(ExecError::operation( return Err(ExecError::operation(
"stage_install", "stage_install",
"verify stage3", "verify stage3",
@ -160,43 +222,51 @@ pub fn parse_digests_sha512(text: &str, target_filename: &str) -> Option<String>
None None
} }
fn verify_signature(exec: &Exec, digests: &Path) -> Result<()> { fn verify_signature_with_key(exec: &Exec, digests: &Path, key: &Path) -> Result<()> {
let key = "/usr/share/openpgp-keys/gentoo-release.asc"; // Probe the verifier through the runner (not merely PATH) so a missing
if crate::exec::find_in_path("gpg").is_none() || !Path::new(key).is_file() { // or broken gpg stops the install, including under test doubles.
exec.logger if let Err(e) =
.warn("gpg or Gentoo release key unavailable; skipping signature check"); exec.run(CommandSpec::new("stage_install", "check stage3 verifier", "gpg").arg("--version"))
return Ok(()); {
return Err(ExecError::operation(
"stage_install",
"verify stage3 DIGESTS signature",
format!("gpg is required to authenticate the stage3 DIGESTS signature but is unavailable; refusing to install ({e})"),
));
}
if !key.is_file() {
return Err(ExecError::operation(
"stage_install",
"verify stage3 DIGESTS signature",
format!(
"trusted Gentoo release key is missing at {}; refusing to install",
key.display()
),
));
} }
let home = tempfile::tempdir().map_err(|e| ExecError::io(std::env::temp_dir(), e))?; let home = tempfile::tempdir().map_err(|e| ExecError::io(std::env::temp_dir(), e))?;
let home_str = home.path().to_string_lossy().to_string(); let home_str = home.path().to_string_lossy().to_string();
let import = CommandSpec::new("stage_install", "import Gentoo release key", "gpg") let import = CommandSpec::new("stage_install", "import Gentoo release key", "gpg")
.args(["--batch", "--quiet", "--import", key]) .args(["--batch", "--quiet", "--import"])
.arg(key.to_string_lossy().to_string())
.env("GNUPGHOME", &home_str); .env("GNUPGHOME", &home_str);
if exec.runner.execute(&import).is_err() { if let Err(e) = exec.run(import) {
exec.logger return Err(ExecError::operation(
.warn("could not import Gentoo release key; skipping signature check"); "stage_install",
return Ok(()); "verify stage3 DIGESTS signature",
format!("could not import the Gentoo release key; refusing to install ({e})"),
));
} }
let verify = CommandSpec::new("stage_install", "verify stage3 DIGESTS signature", "gpg") let verify = CommandSpec::new("stage_install", "verify stage3 DIGESTS signature", "gpg")
.args(["--batch", "--verify"]) .args(["--batch", "--verify"])
.arg(digests.to_string_lossy().to_string()) .arg(digests.to_string_lossy().to_string())
.env("GNUPGHOME", &home_str); .env("GNUPGHOME", &home_str);
match exec.runner.execute(&verify) { // `Exec::run` fails closed on both a nonzero exit (bad signature) and a
Ok(out) => { // process that cannot start; either stops the install before extraction.
let out = exec.run(verify)?;
exec.logger.output(&out.stdout); exec.logger.output(&out.stdout);
exec.logger.output(&out.stderr); exec.logger.output(&out.stderr);
if out.success {
Ok(()) Ok(())
} else {
Err(ExecError::operation(
"stage_install",
"verify stage3 DIGESTS signature",
"signature verification FAILED",
))
}
}
Err(_) => Ok(()),
}
} }
pub fn extract(exec: &Exec, root: &Path, tarball: &Path) -> Result<()> { pub fn extract(exec: &Exec, root: &Path, tarball: &Path) -> Result<()> {
@ -223,6 +293,110 @@ pub fn dry_output() -> CommandOutput {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
use crate::command::{NeverRunner, ProcessRunner, RecordingRunner};
use crate::log::Logger;
use phoebus_core::Redactor;
use std::collections::VecDeque;
use std::sync::Mutex;
use std::time::Duration;
fn make_exec(runner: RecordingRunner) -> Exec {
let path = tempfile::tempdir().unwrap().keep();
let logger = Logger::open(path.join("l.log"), Redactor::new(), false);
Exec::new(Box::new(runner), logger, false, path.join("root"), path)
}
fn ok_out(stdout: &str) -> CommandOutput {
CommandOutput {
status: 0,
success: true,
stdout: stdout.as_bytes().to_vec(),
stderr: Vec::new(),
duration: Duration::from_millis(1),
}
}
fn fail_out(stderr: &str) -> CommandOutput {
CommandOutput {
status: 1,
success: false,
stdout: Vec::new(),
stderr: stderr.as_bytes().to_vec(),
duration: Duration::from_millis(1),
}
}
/// Test double that answers successive commands from a queue, so tests can
/// drive multi-step flows (probe ok, import fails, ...) that share one
/// program name.
struct SeqRunner {
recorded: Mutex<Vec<CommandSpec>>,
queue: Mutex<VecDeque<CommandOutput>>,
}
impl SeqRunner {
fn new(outputs: Vec<CommandOutput>) -> Self {
Self {
recorded: Mutex::new(Vec::new()),
queue: Mutex::new(outputs.into()),
}
}
fn programs(&self) -> Vec<String> {
self.recorded
.lock()
.unwrap()
.iter()
.map(|s| s.program.clone())
.collect()
}
}
impl ProcessRunner for SeqRunner {
fn execute(&self, spec: &CommandSpec) -> Result<CommandOutput> {
self.recorded.lock().unwrap().push(spec.clone());
self.queue.lock().unwrap().pop_front().ok_or_else(|| {
ExecError::operation(
&spec.stage,
&spec.operation,
"no canned response left in the test runner",
)
})
}
}
fn seq_exec(outputs: Vec<CommandOutput>) -> (Exec, std::sync::Arc<SeqRunner>) {
let path = tempfile::tempdir().unwrap().keep();
let logger = Logger::open(path.join("l.log"), Redactor::new(), false);
let runner = std::sync::Arc::new(SeqRunner::new(outputs));
struct Shared(std::sync::Arc<SeqRunner>);
impl ProcessRunner for Shared {
fn execute(&self, spec: &CommandSpec) -> Result<CommandOutput> {
self.0.execute(spec)
}
}
let exec = Exec::new(
Box::new(Shared(runner.clone())),
logger,
false,
path.join("root"),
path,
);
(exec, runner)
}
fn pinned_config(sha256: &str) -> InstallConfig {
let mut config = InstallConfig::default();
config.stage3.url = "https://example.invalid/stage3.tar.xz".into();
config.stage3.sha256 = sha256.into();
config
}
fn digest_text(name: &str, hash: &str) -> String {
format!(
"-----BEGIN PGP SIGNED MESSAGE-----\nHash: SHA256\n\n# SHA512 HASH\n{hash} {name}\n-----BEGIN PGP SIGNATURE-----\n"
)
}
#[test] #[test]
fn parse_digests_picks_sha512_over_blake2b() { fn parse_digests_picks_sha512_over_blake2b() {
@ -256,4 +430,280 @@ e6ae2b1930064878203ab8d134fc081a252c8073730628222ee1cc4a201a56ed9c64dc7b19f1fa40
Some("0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef") Some("0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef")
); );
} }
#[test]
fn pinned_pin_format_is_required() {
assert!(validate_pin(&"a".repeat(64)).is_ok());
assert!(validate_pin(&"A".repeat(64)).is_ok());
assert!(validate_pin("").is_err());
assert!(validate_pin("abc").is_err());
assert!(validate_pin(&"a".repeat(63)).is_err());
assert!(validate_pin(&"a".repeat(65)).is_err());
assert!(validate_pin(&format!("{}g", "a".repeat(63))).is_err());
// A placeholder pin carries no trust and is refused.
assert!(validate_pin(&"0".repeat(64)).is_err());
}
#[test]
fn pinned_path_verifies_a_matching_download() {
let pin = "b".repeat(64);
let runner = RecordingRunner::new();
runner.set_response(
"sha256sum",
ok_out(&format!("{pin} stage3-systemd.tar.xz")),
);
let exec = make_exec(runner.clone());
let state = tempfile::tempdir().unwrap();
let dest = fetch(&exec, &pinned_config(&pin), state.path()).unwrap();
assert_eq!(
dest.file_name().unwrap().to_string_lossy(),
"stage3-systemd.tar.xz"
);
// The mirror's DIGESTS path is never consulted for a pinned tarball.
assert!(
!runner
.recorded()
.iter()
.any(|s| s.args.iter().any(|a| a.contains("DIGESTS"))),
"pinned verification must not fetch DIGESTS"
);
}
#[test]
fn pinned_path_rejects_a_mismatch() {
let runner = RecordingRunner::new();
runner.set_response("sha256sum", ok_out(&format!("{} x", "c".repeat(64))));
let exec = make_exec(runner);
let state = tempfile::tempdir().unwrap();
let err = fetch(&exec, &pinned_config(&"d".repeat(64)), state.path()).unwrap_err();
assert!(err.to_string().contains("mismatch"), "{err}");
}
#[test]
fn pinned_path_rejects_a_placeholder_pin_before_any_hash() {
let runner = RecordingRunner::new();
let exec = make_exec(runner.clone());
let state = tempfile::tempdir().unwrap();
let err = fetch(&exec, &pinned_config(&"0".repeat(64)), state.path()).unwrap_err();
assert!(err.to_string().contains("64 hex digits"), "{err}");
// Fail fast: neither the download nor the hash may run.
assert!(
runner.is_empty(),
"invalid pin must stop before any command"
);
}
#[test]
fn pinned_path_rejects_a_malformed_pin() {
let runner = RecordingRunner::new();
let exec = make_exec(runner.clone());
let state = tempfile::tempdir().unwrap();
let err = fetch(&exec, &pinned_config("not-a-digest"), state.path()).unwrap_err();
assert!(err.to_string().contains("64 hex digits"), "{err}");
assert!(
runner.is_empty(),
"invalid pin must stop before any command"
);
}
#[test]
fn hash_command_nonzero_exit_fails_closed() {
let runner = RecordingRunner::new();
runner.fail("sha512sum", "cannot read file");
let exec = make_exec(runner);
let err = hash_file(&exec, "sha512sum", Path::new("/nonexistent")).unwrap_err();
assert!(err.to_string().contains("sha512sum"), "{err}");
}
#[test]
fn hash_command_that_cannot_start_fails_closed() {
let path = tempfile::tempdir().unwrap().keep();
let logger = Logger::open(path.join("l.log"), Redactor::new(), false);
let exec = Exec::new(
Box::new(NeverRunner),
logger,
false,
path.join("root"),
path,
);
let err = hash_file(&exec, "sha512sum", Path::new("/nonexistent")).unwrap_err();
assert!(err.to_string().contains("disabled"), "{err}");
}
#[test]
fn digests_download_failure_stops_install() {
let runner = RecordingRunner::new();
runner.fail("curl", "network down");
let exec = make_exec(runner);
let dir = tempfile::tempdir().unwrap();
let dest = dir.path().join("stage3.tar.xz");
let key = dir.path().join("gentoo-release.asc");
std::fs::write(&key, "key").unwrap();
let err =
verify_digests_with_key(&exec, "https://example.invalid/stage3.tar.xz", &dest, &key)
.unwrap_err();
assert!(err.to_string().contains("DIGESTS"), "{err}");
assert!(err.to_string().contains("refusing"), "{err}");
}
#[test]
fn missing_sha512_entry_stops_install() {
let runner = RecordingRunner::new();
let exec = make_exec(runner);
let dir = tempfile::tempdir().unwrap();
let dest = dir.path().join("stage3.tar.xz");
// A signed DIGESTS with no entry for our tarball.
std::fs::write(
dest.with_extension("xz.DIGESTS"),
digest_text("other-file.tar.xz", &"e".repeat(128)),
)
.unwrap();
let key = dir.path().join("gentoo-release.asc");
std::fs::write(&key, "key").unwrap();
let err =
verify_digests_with_key(&exec, "https://example.invalid/stage3.tar.xz", &dest, &key)
.unwrap_err();
assert!(err.to_string().contains("SHA-512 entry"), "{err}");
}
#[test]
fn missing_release_key_stops_install() {
let runner = RecordingRunner::new();
let exec = make_exec(runner);
let dir = tempfile::tempdir().unwrap();
let digests = dir.path().join("stage3.DIGESTS");
std::fs::write(&digests, "signed").unwrap();
let err =
verify_signature_with_key(&exec, &digests, &dir.path().join("absent-release.asc"))
.unwrap_err();
assert!(err.to_string().contains("missing"), "{err}");
assert!(err.to_string().contains("refusing"), "{err}");
}
#[test]
fn verifier_that_cannot_start_stops_install() {
let path = tempfile::tempdir().unwrap().keep();
let logger = Logger::open(path.join("l.log"), Redactor::new(), false);
let exec = Exec::new(
Box::new(NeverRunner),
logger,
false,
path.join("root"),
path,
);
let dir = tempfile::tempdir().unwrap();
let digests = dir.path().join("stage3.DIGESTS");
std::fs::write(&digests, "signed").unwrap();
let key = dir.path().join("gentoo-release.asc");
std::fs::write(&key, "key").unwrap();
let err = verify_signature_with_key(&exec, &digests, &key).unwrap_err();
assert!(err.to_string().contains("unavailable"), "{err}");
}
#[test]
fn failed_key_import_stops_install() {
// Probe ok, import exits nonzero.
let (exec, runner) = seq_exec(vec![ok_out("gpg 2.4"), fail_out("no key")]);
let dir = tempfile::tempdir().unwrap();
let digests = dir.path().join("stage3.DIGESTS");
std::fs::write(&digests, "signed").unwrap();
let key = dir.path().join("gentoo-release.asc");
std::fs::write(&key, "key").unwrap();
let err = verify_signature_with_key(&exec, &digests, &key).unwrap_err();
assert!(err.to_string().contains("import"), "{err}");
assert_eq!(runner.programs(), vec!["gpg", "gpg"]);
}
#[test]
fn bad_signature_stops_install() {
// Probe ok, import ok, verification exits nonzero.
let (exec, _) = seq_exec(vec![ok_out("gpg 2.4"), ok_out("imported"), fail_out("BAD")]);
let dir = tempfile::tempdir().unwrap();
let digests = dir.path().join("stage3.DIGESTS");
std::fs::write(&digests, "signed").unwrap();
let key = dir.path().join("gentoo-release.asc");
std::fs::write(&key, "key").unwrap();
let err = verify_signature_with_key(&exec, &digests, &key).unwrap_err();
assert!(err.to_string().contains("verify stage3 DIGESTS"), "{err}");
}
#[test]
fn unpinned_signed_digests_path_succeeds() {
let want = "f".repeat(128);
let (exec, runner) = seq_exec(vec![
ok_out("digests fetched"),
ok_out("gpg 2.4"),
ok_out("imported"),
ok_out("gpg: Good signature"),
ok_out(&format!("{want} stage3.tar.xz")),
]);
let dir = tempfile::tempdir().unwrap();
let dest = dir.path().join("stage3.tar.xz");
std::fs::write(
dest.with_extension("xz.DIGESTS"),
digest_text("stage3.tar.xz", &want),
)
.unwrap();
let key = dir.path().join("gentoo-release.asc");
std::fs::write(&key, "key").unwrap();
verify_digests_with_key(&exec, "https://example.invalid/stage3.tar.xz", &dest, &key)
.unwrap();
assert_eq!(
runner.programs(),
vec!["curl", "gpg", "gpg", "gpg", "sha512sum"]
);
// The DIGESTS copy is discarded after use.
assert!(!dest.with_extension("xz.DIGESTS").exists());
}
#[test]
fn unpinned_hash_mismatch_stops_install() {
let (exec, _) = seq_exec(vec![
ok_out("digests fetched"),
ok_out("gpg 2.4"),
ok_out("imported"),
ok_out("gpg: Good signature"),
ok_out(&format!("{} stage3.tar.xz", "1".repeat(128))),
]);
let dir = tempfile::tempdir().unwrap();
let dest = dir.path().join("stage3.tar.xz");
std::fs::write(
dest.with_extension("xz.DIGESTS"),
digest_text("stage3.tar.xz", &"2".repeat(128)),
)
.unwrap();
let key = dir.path().join("gentoo-release.asc");
std::fs::write(&key, "key").unwrap();
let err =
verify_digests_with_key(&exec, "https://example.invalid/stage3.tar.xz", &dest, &key)
.unwrap_err();
assert!(err.to_string().contains("mismatch"), "{err}");
}
#[test]
fn fetch_with_unavailable_verifier_fails_before_extraction() {
let runner = RecordingRunner::new();
runner.fail("gpg", "not installed");
let exec = make_exec(runner.clone());
let state = tempfile::tempdir().unwrap();
let mut config = InstallConfig::default();
config.stage3.url = "https://example.invalid/stage3.tar.xz".into();
let err = fetch(&exec, &config, state.path()).unwrap_err();
assert!(err.to_string().contains("DIGESTS"), "{err}");
// The tarball download ran, but no hash and no extraction followed.
assert!(!runner.programs().contains(&"sha512sum".to_string()));
assert!(!runner.programs().contains(&"tar".to_string()));
}
#[test]
fn release_key_path_override_is_honoured() {
// The only test that touches this variable; every other stage3 test
// passes its key explicitly, so no parallel test can observe it.
let dir = tempfile::tempdir().unwrap();
let custom = dir.path().join("custom.asc");
std::env::set_var("PHOEBUS_GENTOO_RELEASE_KEY", &custom);
assert_eq!(release_key_path(), custom);
std::env::remove_var("PHOEBUS_GENTOO_RELEASE_KEY");
assert_eq!(release_key_path(), PathBuf::from(GENTOO_RELEASE_KEY));
}
} }

View file

@ -365,6 +365,9 @@ impl Installer {
.info("[dry-run] would fetch and extract the stage3"); .info("[dry-run] would fetch and extract the stage3");
return Ok(()); return Ok(());
} }
// Fail fast when the stage3 verifier (gpg, hashes, download tools) is
// missing: an unverifiable stage3 must never reach extraction.
stage3::require_tools(&self.exec)?;
stage3::fetch(&self.exec, &self.config, &self.exec.state_dir)?; stage3::fetch(&self.exec, &self.config, &self.exec.state_dir)?;
let tarball = self.exec.state_dir.join("stage3-systemd.tar.xz"); let tarball = self.exec.state_dir.join("stage3-systemd.tar.xz");
stage3::extract(&self.exec, std::path::Path::new(&self.exec.root), &tarball) stage3::extract(&self.exec, std::path::Path::new(&self.exec.root), &tarball)

View file

@ -32,7 +32,8 @@ Storage:
Boot and kernel: Boot and kernel:
Bootloader : systemd-boot (BLS entries) Bootloader : systemd-boot (BLS entries)
Unified UKI : no (deferred; BLS used) Unified UKI : not implemented (BLS entries used)
Secure Boot : not implemented (boot chain unsigned)
Kernel : sys-kernel/gentoo-kernel-bin (safe profile) Kernel : sys-kernel/gentoo-kernel-bin (safe profile)
Keep kernels : 3 Keep kernels : 3

View file

@ -38,7 +38,11 @@ The build runs entirely unprivileged and never touches a host disk:
UEFI/BIOS boot path. UEFI/BIOS boot path.
No `curl | sh`, no live/git packages, and signature verification is never No `curl | sh`, no live/git packages, and signature verification is never
disabled. Debian packages are used only on the live medium. disabled. Debian packages are used only on the live medium. The live image
ships `gnupg` plus the trusted Gentoo release key at
`/usr/share/openpgp-keys/gentoo-release.asc` (provisioned by `build.sh` and
checked against Gentoo's published release-key fingerprints), so the
installer's signed-DIGESTS stage3 verification cannot be silently skipped.
## Build ## Build

View file

@ -39,7 +39,7 @@ say() { printf '\n== %s ==\n' "$*"; }
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
say "preflight" say "preflight"
for c in mmdebstrap xorriso mksquashfs curl dpkg-deb unshare sha256sum; do for c in mmdebstrap xorriso mksquashfs curl dpkg-deb unshare sha256sum gpg; do
command -v "$c" >/dev/null || { echo "missing tool: $c" >&2; exit 1; } command -v "$c" >/dev/null || { echo "missing tool: $c" >&2; exit 1; }
done done
if ! command -v magick >/dev/null 2>&1 \ if ! command -v magick >/dev/null 2>&1 \
@ -315,6 +315,52 @@ status=disabled
EOF EOF
fi fi
# Provision the trusted Gentoo release key for stage3 DIGESTS verification.
# The installer authenticates the signed DIGESTS with gpg against
# /usr/share/openpgp-keys/gentoo-release.asc and refuses to install without
# it, so the live image must ship that key. The key bundle is fetched once
# here at build time (never unauthenticated at install time) and accepted
# only when its fingerprint matches Gentoo's published release-key
# information (https://www.gentoo.org/downloads/signatures/).
gentoo_keydir="$rootfs/usr/share/openpgp-keys"
gentoo_key="$gentoo_keydir/gentoo-release.asc"
weekly_fp="13EBBDBEDE7A12775DFDB1BABB572E0E2D182910"
signing_fp="D99EAC7379A850BCE47DA5F29E6438C817072058"
keyring_tmp="$(mktemp -d)"
curl -fsSL --retry 3 -o "$keyring_tmp/service-keys.gpg" \
"https://qa-reports.gentoo.org/output/service-keys.gpg"
GNUPGHOME="$keyring_tmp" gpg --batch --quiet \
--import "$keyring_tmp/service-keys.gpg"
if ! GNUPGHOME="$keyring_tmp" gpg --batch --with-colons \
--list-keys "$weekly_fp" 2>/dev/null | grep -q "$weekly_fp"; then
echo "Gentoo weekly release key $weekly_fp missing from the fetched bundle;" >&2
echo "refusing to ship an untrusted stage3 verification key" >&2
rm -rf "$keyring_tmp"
exit 1
fi
install -d -m 0755 "$gentoo_keydir"
if ! GNUPGHOME="$keyring_tmp" gpg --batch --quiet --armor \
--export "$weekly_fp" "$signing_fp" > "$gentoo_key" 2>/dev/null; then
GNUPGHOME="$keyring_tmp" gpg --batch --quiet --armor \
--export "$weekly_fp" > "$gentoo_key"
fi
[[ -s "$gentoo_key" ]] || {
echo "failed to provision the Gentoo release key" >&2
rm -rf "$keyring_tmp"
exit 1
}
chmod 0644 "$gentoo_key"
verify_tmp="$(mktemp -d)"
GNUPGHOME="$verify_tmp" gpg --batch --quiet --import "$gentoo_key"
if ! GNUPGHOME="$verify_tmp" gpg --batch --with-colons \
--list-keys "$weekly_fp" 2>/dev/null | grep -q "$weekly_fp"; then
echo "provisioned Gentoo release key failed its fingerprint check" >&2
rm -rf "$keyring_tmp" "$verify_tmp"
exit 1
fi
rm -rf "$keyring_tmp" "$verify_tmp"
echo "Gentoo release key provisioned and fingerprint-checked: $gentoo_key"
# Branding: shared vector assets, the app icon and the live-only marker. # Branding: shared vector assets, the app icon and the live-only marker.
install_asset brand-emblem /usr/share/phoebus/branding/emblem.svg install_asset brand-emblem /usr/share/phoebus/branding/emblem.svg
install_asset brand-wordmark /usr/share/phoebus/branding/wordmark.svg install_asset brand-wordmark /usr/share/phoebus/branding/wordmark.svg

View file

@ -32,6 +32,9 @@ dosfstools
btrfs-progs btrfs-progs
util-linux util-linux
e2fsprogs e2fsprogs
# gpg authenticates the Gentoo stage3 DIGESTS signature at install time.
# Without it the installer refuses to install (fail closed).
gnupg
# --- GPU detection and the NVIDIA accelerated driver -------------------------- # --- GPU detection and the NVIDIA accelerated driver --------------------------
# The live medium bundles NVIDIA's accelerated stack so a supported GPU boots # The live medium bundles NVIDIA's accelerated stack so a supported GPU boots

View file

@ -72,13 +72,22 @@ embed a console via `KERNEL_CONSOLE` (`GENTOO_KERNEL_CONSOLE` equivalent).
**already-installed** disposable disk: **already-installed** disposable disk:
1. boot the installed disk, unlock LUKS and log in; 1. boot the installed disk, unlock LUKS and log in;
2. fetch `sys` and `rollback-guest.sh` from the host (the target does not yet 2. fetch `sys` and `rollback-guest.sh` from the host (the installed system
install `sys`; see `docs/HANDOFF.md`), record the `/var/db/pkg` fingerprint carries `/usr/local/bin/sys`; the host copy is a fallback), authenticate
and a `/home` marker, create a recovery point with `sys snapshot`, install a `sudo` (the password is sent only at sudo's own no-echo prompt, never on a
small package (a controlled, reversible update) and run `sys undo`; command line), record the `/var/db/pkg` fingerprint and a `/home` marker,
3. power off, boot the disk detached, and run `rollback-verify.sh`, comparing create a recovery point with `sys snapshot`, install a small package (a
the package fingerprint and the `/home` marker, checking kernel modules, and controlled, reversible update) and run `sys undo` — all as root, because
reading the snapshot recovery entry and `sys rollback status`. unprivileged runs would be refused and prove nothing;
3. power off, boot the disk detached, and run `rollback-verify.sh` (also as
root), comparing the package fingerprint and the `/home` marker, checking
kernel modules, systemd state, and reading the snapshot recovery entry and
`sys rollback status`.
Both transcripts are kept (`serial-phase1.log`, `serial.log`). The guest
scripts refuse to run unprivileged (`ROLLBACK-NEEDS-ROOT` /
`AFTER-NEEDS-ROOT`) so a lost `sudo` timestamp fails loudly instead of
recording vacuous passes.
Serve the fixtures as well as the installer: Serve the fixtures as well as the installer:

View file

@ -25,6 +25,9 @@ KERNEL_PROFILE='safe'
KERNEL_UKI='no' KERNEL_UKI='no'
KERNEL_CONSOLE='console=tty0 console=ttyS0,115200' KERNEL_CONSOLE='console=tty0 console=ttyS0,115200'
KEEP_KERNELS='3' KEEP_KERNELS='3'
# Authenticated boot is not implemented: KERNEL_UKI and SECUREBOOT must stay
# 'no'. The installer rejects 'yes' rather than implying an unsigned BLS
# boot chain is signed.
PACKAGE_POLICY='balanced' PACKAGE_POLICY='balanced'
FEATURES_BINPKG='yes' FEATURES_BINPKG='yes'
@ -37,4 +40,7 @@ FLATPAK='yes'
NIX_ENABLED='no' NIX_ENABLED='no'
STAGE3_URL='http://10.0.2.2:8000/stage3.tar.xz' STAGE3_URL='http://10.0.2.2:8000/stage3.tar.xz'
# Paste the real digest of the served file here (`sha256sum stage3.tar.xz`
# on the host). A placeholder or malformed pin refuses to install; empty
# means "verify against Gentoo's signed DIGESTS with gpg".
STAGE3_SHA256='0000000000000000000000000000000000000000000000000000000000000000' STAGE3_SHA256='0000000000000000000000000000000000000000000000000000000000000000'

View file

@ -12,6 +12,14 @@
# real installed command path, not a mock. # real installed command path, not a mock.
set -uo pipefail set -uo pipefail
# The snapshot/break/undo steps mutate the system and must run as root. The
# driver authenticates sudo before invoking this script; fail fast rather
# than recording vacuous "success" markers as an unprivileged user.
if [ "$(id -u)" != "0" ]; then
echo "===ROLLBACK-NEEDS-ROOT id=$(id -u)==="
exit 1
fi
SERVE="${SERVE_URL:-http://10.0.2.2:8000}" SERVE="${SERVE_URL:-http://10.0.2.2:8000}"
if [[ -n "${SYS_BIN:-}" ]]; then if [[ -n "${SYS_BIN:-}" ]]; then
SYS="$SYS_BIN" SYS="$SYS_BIN"
@ -24,6 +32,17 @@ USER_NAME="${USERNAME:-phoebus}"
WORK=/tmp/phoebus-rollback WORK=/tmp/phoebus-rollback
mkdir -p "$WORK" mkdir -p "$WORK"
# The controlled break must genuinely mutate the system: a package that is
# already installed would make the whole acceptance vacuous (snapshot and
# restore of an identical tree). GNU hello is tiny and never in the base set.
BREAK_PKG="app-misc/hello"
BREAK_CAT="app-misc"
BREAK_NAME="hello"
if ls -d "/var/db/pkg/$BREAK_CAT/$BREAK_NAME-"* >/dev/null 2>&1; then
echo "===ROLLBACK-BREAK-PRESENT $BREAK_PKG already installed; refusing a vacuous run==="
exit 1
fi
pkg_fingerprint() { pkg_fingerprint() {
# The package database, not a marker file: a rollback must restore it. # The package database, not a marker file: a rollback must restore it.
find /var/db/pkg -mindepth 2 -maxdepth 2 -type d 2>/dev/null \ find /var/db/pkg -mindepth 2 -maxdepth 2 -type d 2>/dev/null \
@ -38,23 +57,42 @@ printf '%s\n' "$HOME_MARKER" > "/home/$USER_NAME/rollback-marker.txt"
PKGS_BEFORE="$(pkg_fingerprint)" PKGS_BEFORE="$(pkg_fingerprint)"
echo "===ROLLBACK-KNOWN-GOOD pkgs=$PKGS_BEFORE kernel=$KERNEL home=$HOME_MARKER===" echo "===ROLLBACK-KNOWN-GOOD pkgs=$PKGS_BEFORE kernel=$KERNEL home=$HOME_MARKER==="
# 2. Create the recovery point through the supported interface. # 2. Create the recovery point through the supported interface. Explicit
"$SYS" -y snapshot "rollback acceptance" > "$WORK/snapshot.out" 2>&1 # `--legacy` selects deterministic handling (no model); without it the
# request would enter the AI workflow and stop with no provider.
"$SYS" -y snapshot "rollback acceptance" --legacy > "$WORK/snapshot.out" 2>&1
SNAP_ID="$(sed -n 's/^protective snapshot: //p' "$WORK/snapshot.out" | tail -1)" SNAP_ID="$(sed -n 's/^protective snapshot: //p' "$WORK/snapshot.out" | tail -1)"
echo "===ROLLBACK-SNAPSHOT id=$SNAP_ID===" echo "===ROLLBACK-SNAPSHOT id=$SNAP_ID==="
if [[ -z "$SNAP_ID" ]]; then
echo "--- snapshot.out ---"
sed -n '1,20p' "$WORK/snapshot.out"
exit 1
fi
# 3. Controlled, reversible update failure. A small package install is a real # 3. Controlled, reversible update failure. A small package install is a real
# update: it changes both the root subvolume and /var/db/pkg, and a snapshot # update: it changes both the root subvolume and /var/db/pkg, and a snapshot
# can restore it. A root marker proves the root generation too. # can restore it. A root marker proves the root generation too. The break
# must change the package database; otherwise the restore comparison below
# would pass without proving anything.
printf 'broken by rollback acceptance\n' > /etc/phoebus/rollback-broken.txt 2>/dev/null || true printf 'broken by rollback acceptance\n' > /etc/phoebus/rollback-broken.txt 2>/dev/null || true
"$SYS" -y install app-editors/nano > "$WORK/break.out" 2>&1 "$SYS" -y install "$BREAK_PKG" --legacy --portage > "$WORK/break.out" 2>&1
echo "===ROLLBACK-BROKEN pkgs=$(pkg_fingerprint)===" PKGS_BROKEN="$(pkg_fingerprint)"
echo "===ROLLBACK-BROKEN pkgs=$PKGS_BROKEN==="
if [[ "$PKGS_BROKEN" == "$PKGS_BEFORE" ]]; then
echo "--- break.out ---"
sed -n '1,30p' "$WORK/break.out"
echo "===ROLLBACK-BREAK-NOOP the break did not change the package database==="
exit 1
fi
# 4. Invoke the real sys undo path. # 4. Invoke the real sys undo path, targeting our own snapshot id so the
"$SYS" -y undo > "$WORK/undo.out" 2>&1 # restore point is exact (not "newest", which a protective snapshot taken
# by the break step would win). Restoring our snapshot must remove both
# the installed package and the root marker.
"$SYS" -y undo "$SNAP_ID" --legacy > "$WORK/undo.out" 2>&1
RC=$? RC=$?
echo "===ROLLBACK-UNDO rc=$RC===" echo "===ROLLBACK-UNDO rc=$RC id=$SNAP_ID==="
"$SYS" rollback status > "$WORK/status.out" 2>&1 || true "$SYS" rollback status --legacy > "$WORK/status.out" 2>&1 || true
sed -n '1,40p' "$WORK/status.out" sed -n '1,40p' "$WORK/status.out"
echo "===ROLLBACK-DONE===" echo "===ROLLBACK-DONE==="

View file

@ -8,7 +8,23 @@
# alone would not prove package-state consistency. # alone would not prove package-state consistency.
set -uo pipefail set -uo pipefail
SYS="${SYS_BIN:-/tmp/sys}" # Verification reads the system state (subvolumes, ESP entries) and must run
# as root; the driver authenticates sudo before invoking this script.
if [ "$(id -u)" != "0" ]; then
echo "===AFTER-NEEDS-ROOT id=$(id -u)==="
echo "===AFTER-DONE==="
exit 1
fi
# `sys` is installed into the target by the installer; fall back to the host
# copy only if it is somehow absent.
if [[ -n "${SYS_BIN:-}" ]]; then
SYS="$SYS_BIN"
elif [[ -x /usr/local/bin/sys ]]; then
SYS=/usr/local/bin/sys
else
SYS=/tmp/sys
fi
USER_NAME="${USERNAME:-phoebus}" USER_NAME="${USERNAME:-phoebus}"
pkg_fingerprint() { pkg_fingerprint() {
@ -18,6 +34,7 @@ pkg_fingerprint() {
HOME_MARKER="$(cat "/home/$USER_NAME/rollback-marker.txt" 2>/dev/null || echo missing)" HOME_MARKER="$(cat "/home/$USER_NAME/rollback-marker.txt" 2>/dev/null || echo missing)"
echo "===AFTER-KNOWN-GOOD pkgs=$(pkg_fingerprint) kernel=$(uname -r) home=$HOME_MARKER===" echo "===AFTER-KNOWN-GOOD pkgs=$(pkg_fingerprint) kernel=$(uname -r) home=$HOME_MARKER==="
echo "===AFTER-SYSTEMD $(systemctl is-system-running 2>&1)==="
if [ -e /etc/phoebus/rollback-broken.txt ]; then if [ -e /etc/phoebus/rollback-broken.txt ]; then
echo "===AFTER-BROKEN-MARKER present===" echo "===AFTER-BROKEN-MARKER present==="
else else
@ -48,6 +65,6 @@ cat /efi/loader/entries/phoebus-recovery.conf \
/boot/efi/loader/entries/phoebus-recovery.conf 2>/dev/null || true /boot/efi/loader/entries/phoebus-recovery.conf 2>/dev/null || true
echo "===AFTER-STATUS===" echo "===AFTER-STATUS==="
"$SYS" rollback status 2>&1 || true "$SYS" rollback status --legacy 2>&1 || true
echo "===AFTER-DONE===" echo "===AFTER-DONE==="

View file

@ -178,6 +178,39 @@ def _unlock_and_login(child, results, tag):
results.assert_true(f"{tag}-login", logged_in, f"{tag}: could not log in") results.assert_true(f"{tag}-login", logged_in, f"{tag}: could not log in")
def _sudo_auth(child, results, tag):
"""Authenticate sudo for the rollback acceptance guest scripts.
The snapshot/break/undo/verify steps mutate the system and must run as
root. The password is sent only at sudo's own prompt (terminal echo
disabled, like the login password), so it never lands in the serial
transcript the way a command-line credential would. Returns True when the
timestamp stuck; the caller must abort the phase otherwise, or every
later `sudo` would block on a prompt nobody answers.
"""
try:
# Unique markers, never a bare `[$#] ` alternative: the buffer still
# holds the previous shell prompt when this runs, and a generic
# prompt pattern would match that stale text immediately — skipping
# the password while sudo is still starting (the next typed line
# would then be consumed as the password and rejected).
child.sendline("sudo -v; echo SUDO-V-$(printf DONE)")
idx = child.expect([r"[Pp]assword(?: for [^:]+)?:", "SUDO-V-DONE"], timeout=60)
if idx == 0:
child.sendline(USER_PW)
child.expect("SUDO-V-DONE", timeout=60)
# Prove the timestamp stuck: without it every later `sudo` would block
# on a password prompt nobody answers, hanging the run until timeout.
child.sendline("sudo -n true && echo SUDO-OK-$(printf READY)")
idx = child.expect(["SUDO-OK-READY", r"[Pp]assword"], timeout=30)
except (pexpect.TIMEOUT, pexpect.EOF):
idx = -1
if idx != 0:
results.fail(f"{tag}-sudo", "sudo authentication did not stick")
return False
return True
def _fetch_sys(child): def _fetch_sys(child):
# The installed system should already carry /usr/local/bin/sys; only fall # The installed system should already carry /usr/local/bin/sys; only fall
# back to fetching the host build when it is absent. # back to fetching the host build when it is absent.
@ -214,7 +247,9 @@ def do_rollback(results, paths, disks):
try: try:
_unlock_and_login(child, results, "rollback-before") _unlock_and_login(child, results, "rollback-before")
_fetch_sys(child) _fetch_sys(child)
child.sendline(f"curl -fsSL {ROLLBACK_URL} -o /tmp/rb.sh && bash /tmp/rb.sh") if not _sudo_auth(child, results, "rollback-before"):
return
child.sendline(f"curl -fsSL {ROLLBACK_URL} -o /tmp/rb.sh && sudo bash /tmp/rb.sh")
child.expect( child.expect(
["===ROLLBACK-DONE===", "curl:", pexpect.TIMEOUT, pexpect.EOF], ["===ROLLBACK-DONE===", "curl:", pexpect.TIMEOUT, pexpect.EOF],
timeout=int(os.environ.get("ROLLBACK_TIMEOUT", "7200")), timeout=int(os.environ.get("ROLLBACK_TIMEOUT", "7200")),
@ -234,13 +269,24 @@ def do_rollback(results, paths, disks):
log.close() log.close()
before = _parse_marker(phase1, "ROLLBACK-KNOWN-GOOD") before = _parse_marker(phase1, "ROLLBACK-KNOWN-GOOD")
broken = _parse_marker(phase1, "ROLLBACK-BROKEN")
undo = _parse_marker(phase1, "ROLLBACK-UNDO") undo = _parse_marker(phase1, "ROLLBACK-UNDO")
if before is None: if before is None:
results.fail("rollback-known-good", "the guest did not record the known-good state") results.fail("rollback-known-good", "the guest did not record the known-good state")
if broken is None or broken.get("pkgs") == (before or {}).get("pkgs"):
results.fail("rollback-break-broke", f"the controlled break did not change the package database: {broken}")
return
if undo is None or undo.get("rc") != "0": if undo is None or undo.get("rc") != "0":
results.fail("rollback-undo", f"sys undo did not succeed: {undo}") results.fail("rollback-undo", f"sys undo did not succeed: {undo}")
# No rollback happened: a detached "verify" would compare identical
# states and report vacuous passes. Stop instead of pretending.
return
# Phase 2: boot the disk detached and verify the restored generation. # Phase 2: boot the disk detached and verify the restored generation.
# The phase-1 transcript is preserved under its own name first: reopening
# the same log would destroy the evidence for why phase 1 passed/failed.
phase1_log = paths.serial_log.with_name("serial-phase1.log")
paths.serial_log.rename(phase1_log)
env, args = _installed_args(paths, disks) env, args = _installed_args(paths, disks)
log = open(paths.serial_log, "w") log = open(paths.serial_log, "w")
child = spawn(args, env, log) child = spawn(args, env, log)
@ -248,11 +294,13 @@ def do_rollback(results, paths, disks):
try: try:
_unlock_and_login(child, results, "rollback-after") _unlock_and_login(child, results, "rollback-after")
_fetch_sys(child) _fetch_sys(child)
child.sendline(f"curl -fsSL {ROLLBACK_VERIFY_URL} -o /tmp/rbv.sh && bash /tmp/rbv.sh") if not _sudo_auth(child, results, "rollback-after"):
return
child.sendline(f"curl -fsSL {ROLLBACK_VERIFY_URL} -o /tmp/rbv.sh && sudo bash /tmp/rbv.sh")
child.expect("===AFTER-DONE===", child.expect("===AFTER-DONE===",
timeout=int(os.environ.get("ROLLBACK_VERIFY_TIMEOUT", "900"))) timeout=int(os.environ.get("ROLLBACK_VERIFY_TIMEOUT", "900")))
phase2 = paths.serial_log.read_text(errors="replace") phase2 = paths.serial_log.read_text(errors="replace")
results.assert_true("rollback-systemd-running", "running" in phase2, results.assert_true("rollback-systemd-running", "===AFTER-SYSTEMD running===" in phase2,
"systemd did not report running after rollback") "systemd did not report running after rollback")
after = _parse_marker(phase2, "AFTER-KNOWN-GOOD") after = _parse_marker(phase2, "AFTER-KNOWN-GOOD")
if before is None or after is None: if before is None or after is None:
@ -270,6 +318,11 @@ def do_rollback(results, paths, disks):
) )
results.assert_true("rollback-modules-present", "===AFTER-MODULES ok===" in phase2, results.assert_true("rollback-modules-present", "===AFTER-MODULES ok===" in phase2,
"no kernel modules for the running kernel") "no kernel modules for the running kernel")
# The break wrote this marker after our snapshot; the targeted undo
# restores our snapshot exactly, so the marker must be gone. Its
# survival would prove the wrong generation was restored.
results.assert_true("rollback-root-restored", "===AFTER-BROKEN-MARKER absent===" in phase2,
"the root break marker survived the rollback")
results.assert_true( results.assert_true(
"rollback-recovery-entry", "rollback-recovery-entry",
"systemd.unit=rescue.target" in phase2 and "@snapshots/" in phase2, "systemd.unit=rescue.target" in phase2 and "@snapshots/" in phase2,

View file

@ -23,6 +23,9 @@ KERNEL_PROFILE='safe'
KERNEL_UKI='no' KERNEL_UKI='no'
KERNEL_CONSOLE='console=tty0 console=ttyS0,115200' KERNEL_CONSOLE='console=tty0 console=ttyS0,115200'
KEEP_KERNELS='3' KEEP_KERNELS='3'
# Authenticated boot is not implemented: KERNEL_UKI and SECUREBOOT must stay
# 'no'. The installer rejects 'yes' rather than implying an unsigned BLS
# boot chain is signed.
PACKAGE_POLICY='balanced' PACKAGE_POLICY='balanced'
FEATURES_BINPKG='yes' FEATURES_BINPKG='yes'
@ -33,6 +36,10 @@ DESKTOP_PROFILE='mango'
FLATPAK='yes' FLATPAK='yes'
# Pinned stage3 served from the host HTTP server so the SHA-256 is verified # Pinned stage3 served from the host HTTP server so the SHA-256 is verified
# without a second download. Replace with a real Gentoo URL for other setups. # without re-downloading from the internet. Replace with a real Gentoo URL for other setups.
# STAGE3_SHA256 must be the real 64-digit hex digest of the served file
# (run `sha256sum stage3.tar.xz` on the host and paste it here): empty means
# "verify against Gentoo's signed DIGESTS with gpg" (needs the release key in
# the live image), while a placeholder or malformed pin refuses to install.
STAGE3_URL='http://10.0.2.2:8000/stage3.tar.xz' STAGE3_URL='http://10.0.2.2:8000/stage3.tar.xz'
STAGE3_SHA256='0000000000000000000000000000000000000000000000000000000000000000' STAGE3_SHA256='0000000000000000000000000000000000000000000000000000000000000000'

View file

@ -247,6 +247,39 @@ class HarnessScriptsTest(unittest.TestCase):
driver = (self.VM_DIR / "serial-driver.py").read_text() driver = (self.VM_DIR / "serial-driver.py").read_text()
self.assertIn('"rollback"', driver) self.assertIn('"rollback"', driver)
self.assertIn("do_rollback", driver) self.assertIn("do_rollback", driver)
# The acceptance mutates the system: the driver must authenticate sudo
# (password only at sudo's own prompt) and run both guest phases as
# root, or every privileged step would fail as the login user.
self.assertIn("_sudo_auth", driver)
self.assertIn("sudo bash /tmp/rb.sh", driver)
self.assertIn("sudo bash /tmp/rbv.sh", driver)
# The sudo handshake must use unique end markers: a bare `[$#] `
# alternative would match the stale prompt left by the previous
# command and skip the password while sudo is still starting.
auth = driver.split("def _sudo_auth", 1)[1].split("\ndef ", 1)[0]
self.assertIn("SUDO-V-DONE", auth)
self.assertNotIn('r"[$#] "', auth)
# The timestamp is verified before use, and a failed phase 1 aborts
# instead of reporting vacuous phase-2 passes.
self.assertIn("SUDO-OK-READY", driver)
self.assertIn("vacuous", driver)
# Phase 1 evidence must survive phase 2.
self.assertIn("serial-phase1.log", driver)
for name in ("rollback-guest.sh", "rollback-verify.sh"):
text = (self.VM_DIR / name).read_text()
self.assertIn('id -u', text, f"{name} must refuse to run unprivileged")
verify = (self.VM_DIR / "rollback-verify.sh").read_text()
self.assertIn("/usr/local/bin/sys", verify)
self.assertIn("AFTER-SYSTEMD", verify)
# The acceptance must prove a real mutation and a real restore: the
# break package must be absent up front, the break must change the
# package database, and the driver must assert the root marker is gone.
guest = (self.VM_DIR / "rollback-guest.sh").read_text()
self.assertIn("ROLLBACK-BREAK-PRESENT", guest)
self.assertIn("ROLLBACK-BREAK-NOOP", guest)
self.assertIn("--legacy", guest)
self.assertIn("rollback-break-broke", driver)
self.assertIn("rollback-root-restored", driver)
if __name__ == "__main__": if __name__ == "__main__":