diff --git a/.github/workflows/linux-image.yml b/.github/workflows/linux-image.yml index ab530a65..e2109eff 100644 --- a/.github/workflows/linux-image.yml +++ b/.github/workflows/linux-image.yml @@ -56,6 +56,8 @@ jobs: - name: Install only to a disposable virtual disk and qualify no-ISO recovery run: | python3 packaging/linux/tests/qemu_install.py \ + --recovery \ + --signed-update \ --iso dist/linux/phios-linux-0.1.0-alpha.1-x86_64.iso \ --source "$(cat dist/linux/source-commit.txt)" \ --output "$RUNNER_TEMP/phios-installed" diff --git a/docs/os/IMPLEMENTATION_STATUS.md b/docs/os/IMPLEMENTATION_STATUS.md index 4fa5bab7..bad7a19b 100644 --- a/docs/os/IMPLEMENTATION_STATUS.md +++ b/docs/os/IMPLEMENTATION_STATUS.md @@ -14,7 +14,7 @@ proof that PhiOS is a completed OS. Preserve the repository AGENTS.md rules. | R5: Produce and UEFI boot exact live ISO | Isolated Archiso/QEMU workflow | Exact source 0253b6e0fb27251fe2da37b6d8c1e31245a64290 and ISO SHA-256 recorded below; live lifecycle and two distinct boots passed | | R6: Recover durable private state | Locking/sync, transactional outbox and data-only recovery | Contention, interruption, backup/restore and schema refusal tests; installed acknowledged state survived abrupt VM restart in 36798467774; physical power-loss qualification pending | | R7: Explicit blank-disk installation | Experimental root-owned offline CLI and disposable qualification lane | 20 local refusal/cancellation/identity tests; cancellation, actual installation, no-ISO desktop boot and fresh data restoration passed on the named disposable VM; hardware beta pending | -| R8: Whole-OS update and recovery | Pending | Signed artifacts, failed update recovery; app rollback is insufficient | +| R8: Whole-OS update and recovery | Explicit public-key enrollment, signed verifier, staged package application and matched root/EFI checkpoints | Full 2,218-test CI and bounded end-to-end VM run 36805999628 passed: valid update, invalid/cancelled/replayed/dependency refusal, abrupt termination during a real package hook, unchanged active system, deliberate kernel boot failure, matched live recovery and three password-authenticated disk-only boots; arbitrary transitions and hardware remain unqualified | | R9: Qualify hardware and one Linux governed workflow | Pending | Named hardware matrix and observed effect verification | | R10: Sign and publish the exact qualified artifact | Held | Proven preceding gates, hashes, SBOM, signatures, source/license notices and maintainer release decision | @@ -46,4 +46,12 @@ Image run [36798467774](https://github.com/MichaelWave369/PhiOS/actions/runs/367 Evidence receipt: `docs/os/evidence/installation-0253b6e0.json`. [Reviewable logs and screenshots](https://github.com/MichaelWave369/PhiOS/actions/runs/36798467774/artifacts/11135321615) and [unsigned image/packages](https://github.com/MichaelWave369/PhiOS/actions/runs/36798467774/artifacts/11134958214) expire 2026-10-08 under the seven-day CI retention policy. CI-only serial-console injection and public disposable credentials are recorded; they are excluded from normal installations. The screenshot was visually inspected. Ordinary CI runs 36798467750 and 36798463744 also passed for installer head `f135a24d3d88173f611829317e4ad04ebc22eff3`. -These are bounded VM qualifications. Whole-OS updates/recovery, physical power loss, Linux governed effects, named hardware support and signed public release remain held. No adapter is promoted and no publication authority follows from the receipts. +These are bounded VM qualifications. The later bounded update/recovery qualification is recorded below. Physical power loss, Linux governed effects, named hardware support and signed public release remain held. No adapter is promoted and no publication authority follows from the receipts. + +## Signed update and matched recovery VM evidence + +Image run [36805999628](https://github.com/MichaelWave369/PhiOS/actions/runs/36805999628) passed for source `29def30a3079c99972f1606ae44ea3478d0f79d1`, ISO SHA-256 `391efdfd41e0217706b2b4028c47e9d37f7014762afc5d6831a30eb6bb2dba4b`. The disposable 32-GiB disk, two CPUs, 4 GiB RAM, UEFI/KVM, no network/host disks/shared folders and CI-only fixture bounds are unchanged. Production public-key enrollment cancellation and acceptance passed with an ephemeral test key. A real signed package was installed; missing/wrong-key/tampered/expired/replayed bundles, cancellation and a real dependency failure were refused. Abrupt termination occurred inside a real pacman installation hook; a second live boot verified the retained interrupted stage and unchanged active root, EFI and counter. + +Three distinct password/PAM and greetd disk-only desktop boots passed. After deliberate default/fallback initramfs corruption, the kernel actually panicked because it could not mount its root. Explicit live-media recovery restored the matched root/EFI checkpoint, removed the added test package and rolled-back signing trust, advanced the independent generation to two, and preserved the canonical data/acknowledged receipt hash. Root/EFI switching remains non-atomic. The successful added-package fixture does not qualify arbitrary kernel upgrades or an actual future signed release transition. + +Receipt: `docs/os/evidence/recovery-29def30a.json`. [Logs/screenshots](https://github.com/MichaelWave369/PhiOS/actions/runs/36805999628/artifacts/11137448503) and [unsigned QA image/packages](https://github.com/MichaelWave369/PhiOS/actions/runs/36805999628/artifacts/11137807998) expire 2026-10-08. The recovered desktop screenshot was visually inspected. Ordinary CI [36805999618](https://github.com/MichaelWave369/PhiOS/actions/runs/36805999618) passed 2,218 tests with six existing optional skips, including eight actual signature/expiry/revocation cases and four actual enrollment cases. All four prior failures remain in `docs/os/evidence/recovery-attempts.json`. Real hardware, fixture-free exact release-artifact qualification, source/license completion and maintainer signing/publication remain held; no adapter or execution authority is promoted. diff --git a/docs/os/OS_MAINTENANCE.md b/docs/os/OS_MAINTENANCE.md new file mode 100644 index 00000000..4363bd2b --- /dev/null +++ b/docs/os/OS_MAINTENANCE.md @@ -0,0 +1,226 @@ +# Experimental whole-OS maintenance + +The candidate beta strategy is conventional signed Arch package transitions, +with an offline Btrfs root checkpoint and a matching copy of the entire EFI +system partition. This is not an atomic or immutable OS. Application rollback +does not restore Linux, initramfs, system configuration or the bootloader. + +## Signed transition intake + +`phios-update-verify --bundle /absolute/path/to/offline-bundle` verifies bytes +only. It cannot install packages, switch a boot entry, promote an adapter or +create execution authority. The normal image intentionally ships no enrolled +maintainer signing key. Verification holds until the operator independently +authenticates and installs a public key and full fingerprint. No test key is a +release identity, and no signing private key belongs in this repository/image. + +The volatile live account has no general root shell. Enroll through the +root-owned narrow command instead, using the full independently authenticated +fingerprint: + +```bash +sudo phios-update-enroll --public-key /absolute/current-public-key.gpg --fingerprint FULL_UPPERCASE_FINGERPRINT --plan +sudo phios-update-enroll --public-key /absolute/current-public-key.gpg --fingerprint FULL_UPPERCASE_FINGERPRINT +``` + +The placeholders must be replaced. Review the exact captured public-key hash, +full fingerprint, current trust hashes and source environment, then type +`ENROLL /etc/phios SHA256`. Missing/changed identity, multiple primary keys, +secret-key material, expired/revoked keys or cancellation do not enroll trust. +The tool captures the input once, exports only the selected public key, +rechecks validity/current trust after review, and flushes protected key/policy +files before readback. It has no unattended bypass or network retrieval. +Terminal access is not proof of human identity; an administrator remains +responsible for independent fingerprint authentication. Signing-trust rotation +is an explicit local administration action, not an adapter promotion. + +An installed administrator can also perform manual Linux administration: +create root-owned `/etc/phios` +without group/other write access, install the independently authenticated +exported public key at `/etc/phios/os-update-keyring.gpg` (root:root, 0644), and +install `/etc/phios/os-update-trust.json` (root:root, 0644): + +```json +{ + "schema_version": "phios.os-update-trust.v1", + "primary_fingerprint": "REPLACE_WITH_THE_INDEPENDENTLY_AUTHENTICATED_FULL_UPPERCASE_FINGERPRINT", + "channel": "experimental" +} +``` + +The placeholder is deliberately invalid. Authenticate the fingerprint through +a separately trusted maintainer channel; downloading a key beside its own +signature does not establish trust. Key rotation/revocation requires an explicit +administrator replacement of this trust policy/keyring. No keyserver, network +retrieval, automatic enrollment or web-of-trust inference is used. GnuPG's +machine-readable status must identify the pinned primary key, SHA-256/384/512, +and an unexpired, nonrevoked key/signature. GPGV alone would not provide the +required expiry/revocation checks. + +The offline bundle contains `manifest.json`, its detached `.sig`, and each +listed package plus a detached `.sig`. Every signature must chain to the pinned +maintainer primary key. Upstream package provenance still belongs in release +build evidence; a signed release transition is not a source/license audit. +Inputs are singly linked bounded regular files, opened without following links, +copied into a private temporary directory, then hashed and signature-checked. +Only captured bytes can reach a later package consumer. Replacing the supplied +bundle after verification cannot replace those bytes. + +The strict `phios.os-package-update.v1` manifest requires exactly these fields: + +| Field | Requirement | +| --- | --- | +| `schema_version`, `channel`, `architecture` | Exact schema, `experimental`, `x86_64` | +| `from_source_commit`, `source_commit` | Exact base and target 40-character commit identities | +| `base_sequence`, `sequence` | Installed generation and exactly its successor; no replay | +| `created_at`, `expires_at` | Timezone-aware validity window, at most 90 days; accurate clock required | +| `arch_snapshot` | Valid, fixed `YYYY/MM/DD` Arch archive date | +| `state_schemas` | Exactly `{"memory":1,"data_backup":"phios.data-backup.v1"}`; unknown migrations held | +| `base_packages`, `target_packages` | Complete name/version inventories; exact base; removals held | +| `packages` | Unique name/version/filename/SHA-256/size records for every changed or added package | + +Each package record has exactly `name`, `version`, `filename`, `sha256`, `size`. +The inventory bound is 20,000 packages; the transition bound is 2,000 archives, +2 GiB per archive and 16 GiB total. Archives use `.pkg.tar.zst` or `.pkg.tar.xz`. +The source, installed package inventory and persisted generation are checked +again for every verification. Initial installation has generation zero. + +Signature verification proves authenticated bytes and a declared complete +transition. Pacman must still validate package format, dependencies and the +resulting full inventory in a prepared system root. Unsupported schema changes, +data migrations, removals or dependency conflicts must hold the update. The +verifier does not claim package installation or boot compatibility. + +## Recovery qualification gate + +`sudo phios-os-recover checkpoint --disk /dev/REPLACE --plan` performs a +read-only probe from the PhiOS UEFI live image. Supply the canonical device +path of the already installed, offline disk. It requires the installer's exact +GPT/1-GiB-ESP/single-device-Btrfs layout, stable serial/WWN, filesystem UUIDs, +and a matching installation receipt. Mounted disks, swap, holders, unexpected +filesystems, extra partitions and noncanonical aliases are refused. A Btrfs +read-only probe uses `ro,rescue=nologreplay,subvolid=5` to disable log replay +([Btrfs mount documentation](https://btrfs.readthedocs.io/en/latest/btrfs-man5.html#mount-options)). No target write occurs for `--plan` or +cancellation. The tool exposes no unattended confirmation bypass. + +Run the command without `--plan`, review the complete disk/source/boot-file +hash plan, and type the exact `CHECKPOINT /dev/... SHA256` phrase. The checkpoint +ID and metadata are stored in `@snapshots/recovery//checkpoint.json`. +Each checkpoint has an immutable root snapshot, its Btrfs UUID, SHA-256/length +inventory of the complete EFI contents, and a read-only home snapshot retained +for forensic review. The home snapshot is never activated by OS recovery. + +To restore, boot the same live media and use: + +```bash +sudo phios-os-recover restore --disk /dev/REPLACE --generation CHECKPOINT_ID --plan +sudo phios-os-recover restore --disk /dev/REPLACE --generation CHECKPOINT_ID +``` + +The placeholder paths/ID must be replaced after reviewing the actual probe. +The exact `RESTORE /dev/... SHA256` phrase binds the selected disk, immutable +root snapshot, source and matching EFI hashes. Current `/home` and `/var/log` +stay in their own subvolumes. Canonical memory schema/integrity/content hashes +and published zero-authority memory receipts are checked. Unknown schemas, +incomplete database journals, enabled memory configuration, active decisions, +bindings, leases, claims or other unknown spine state hold recovery before +activation. Use verified data-only recovery and explicitly revalidate such +state first; the tool does not guess how to invalidate a custom authority root. +Only the packaged state path and legacy `~/.phios` are covered by this preview. + +Recovery clones the immutable root into a fresh writable subvolume, retains +the failed root under a unique `@failed-...` name and preserves the prior EFI +contents beside a durable transaction journal. It then switches the root and +copies/verifies the matched EFI files. Root and EFI changes are **not atomic**. +An interruption between them requires another live-media restore of the same +checkpoint; never reboot merely because one step completed. Failed roots and +transaction evidence are never deleted automatically. Cleanup failures hold +the operation and identify remaining mounts. Filesystem/hardware corruption +that prevents mounting needs a separate storage recovery procedure. + +Restoration discards old system/EFI entropy seeds, removes rolled-back update +trust files so an earlier signing policy cannot be silently reinstated, and +increments the highest observed update generation rather than replaying its +counter. The root generation is paired with a root-owned counter in +`@snapshots/os-update-counter.json`, outside the rollback snapshots. This counter +is flushed before root activation. A missing root after an interrupted rename +therefore cannot reset an already consumed update sequence. An inconsistent +root/counter pair holds updates for explicit live recovery. Re-enroll the independently authenticated current public key before +subsequent updates. Normal password/PAM login remains required. Same-user +terminal access is not proof of human identity and arbitrary administrator +processes remain outside PhiOS's narrow governed-effect boundary. + +Before any supported installed beta, prove all of the following on the exact +image: offline root/EFI checkpoint; valid signed package installation; missing, +wrong-key, expired and tampered update refusal; interrupted package transaction; +unbootable root or initramfs; recovery using the live media; normal password +reauthentication; preservation and verification of canonical user data; inactive +historical authority; and a second disk-only boot. Root snapshots alone do not +back up `/home`, and same-disk checkpoints do not survive loss of that disk. +Maintain a verified data-only backup on separately owned storage. + +## Offline signed package application + +Boot PhiOS UEFI live media, keep the installed disk offline, and enroll the +independently authenticated current public key into the **live** environment. +The updater does not inherit trust from the disk it is about to change. + +```bash +sudo phios-os-update --disk /dev/REPLACE --bundle /absolute/offline-bundle --plan +sudo phios-os-update --disk /dev/REPLACE --bundle /absolute/offline-bundle +``` + +The read-only plan binds the explicit disk, exact current source, complete +package inventory, independent counter, entire EFI hash inventory, signed +manifest digest, pinned signer and fresh checkpoint ID. Review and type the +exact `UPDATE /dev/... SHA256` phrase. Cancellation changes no target files. +Trust, validity and every captured package signature are checked again after +confirmation. Downgrades and package removals require recovery rather than an +update. Accurate time and enough live temporary storage for the bounded bundle +are prerequisites; insufficient space holds the operation. + +The command first creates a matched recovery checkpoint, then prepares a +writable `@update-...` root. Pacman requires signatures for each captured +archive, with only the enrolled keyring and no remote repositories. Package +format/dependency failures or an incorrect complete target inventory leave +the active root and EFI unchanged. The staged root must carry exactly the +signed PhiOS source identity. Kernel/initramfs/EFI preparation occurs against +a private copy of `/boot`; only after verification does the tool retain the +prior root, activate the new root and copy/verify matching EFI contents. +No user-home snapshot or historical authorization is activated. + +Signed package scripts run with administrator privileges. The staging chroot +is not a security sandbox against a malicious signer or administrator. A +maintainer must qualify the actual complete package transition, its hooks, +state compatibility, licenses and boot behavior before signing it. + +The update journal lives beside its exact checkpoint as +`@snapshots/recovery//update-transaction.json`. Failed stage roots, +previous roots and transaction evidence remain for review. An interruption +before activation leaves the active root in place. Root/EFI activation remains +non-atomic: if interrupted during that switch, boot live media and explicitly +restore the journal's checkpoint. Success reports activation only; a disk-only +boot is still required to qualify the target. Keep a separate verified data +backup and the matching live recovery image. + +CI uses only a newly created named 32-GiB VM disk, with no network, host disks +or shared folders. It generates ephemeral signing keys in live RAM and builds +real packages with makepkg. The new fixture tests invalid/missing/wrong-key/ +expired/replayed signatures or manifests, cancellation, a valid added package, +a real dependency failure, abrupt VM termination during a pacman installation +hook, unchanged active root/EFI after that interruption, deliberate boot +corruption, matched live-media recovery and normal password/PAM desktop boots. +Those test packages and credentials are excluded from normal images and +installations. A successful fixture qualifies that bounded transition only; +it does not qualify arbitrary kernel upgrades, real hardware or a release key. + +Current status: the bounded end-to-end VM qualification passed in run +[36805999628](https://github.com/MichaelWave369/PhiOS/actions/runs/36805999628), +including enrollment, successful signed addition, refusal cases, actual +interrupted installation, a kernel boot failure, matched live recovery and +three authenticated disk-only desktop boots. Exact source/ISO hashes and +evidence digests are in `docs/os/evidence/recovery-29def30a.json`. The QA image +contains disposable fixtures and ephemeral signing identity; this evidence +does not qualify another artifact, arbitrary upgrades or hardware. +`whole_os_rollback_available` remains false for the supported product. +See IMPLEMENTATION_STATUS.md and RELEASE_CONTRACT.md for remaining gates. diff --git a/docs/os/RELEASE_CONTRACT.md b/docs/os/RELEASE_CONTRACT.md index 36f86b89..8c4cd21a 100644 --- a/docs/os/RELEASE_CONTRACT.md +++ b/docs/os/RELEASE_CONTRACT.md @@ -26,9 +26,11 @@ cannot mint operator approvals; see OPERATOR_AUTHORIZATION.md. This preview is a volatile live image. Its experimental blank-disk installer passed the named disposable VM gate (see INSTALLATION.md); it has no supported -hardware installer, whole-OS rollback, Secure Boot or BIOS support. Installed -data backup/restoration and abrupt VM restart passed; physical power-loss and -whole-system update recovery remain separate gates. No hardware compatibility claim follows from a VM boot. Agent +hardware installer, supported whole-OS rollback, Secure Boot or BIOS support. +Installed data backup/restoration, abrupt VM restart and a bounded signed +package/update plus matched root/EFI recovery passed in disposable VMs +(see IMPLEMENTATION_STATUS.md). Physical power loss, actual future release +transitions and fixture-free installed-artifact qualification remain separate gates. No hardware compatibility claim follows from a VM boot. Agent isolation requires separate OS principals and a verified restricted broker; an operator-owned shell or pseudo-TTY is not human authentication. diff --git a/docs/os/evidence/recovery-29def30a.json b/docs/os/evidence/recovery-29def30a.json new file mode 100644 index 00000000..404c6abb --- /dev/null +++ b/docs/os/evidence/recovery-29def30a.json @@ -0,0 +1,99 @@ +{ + "abrupt_virtual_restart_passed": true, + "accelerator": "kvm", + "artifact_expiry": "2026-10-08", + "boot_ids": [ + "2b19aac63c44448d9c9372326fcb82a8", + "a8117303e2984624b453f988e09881f7", + "1b3506e3a89a4c21ad31f135dc06833f" + ], + "ci_serial_console_injected": true, + "cpus": 2, + "disk_bytes": 34359738368, + "disk_serial": "PHIOS_CI_BLANK", + "ephemeral_test_key": true, + "evidence_artifact_id": 11137448503, + "evidence_files": { + "PhiOS/PhiOS/dist/linux/build.log": "0ac6084d51ac0f394a01301150e7e969142d3558e0f3832894fe59efffe0f2e6", + "PhiOS/PhiOS/dist/linux/builder-image.json": "d56dea8dbf2a26f43c9ada63bd04bc31a7365f0db7811a09ba230bad1192b6c5", + "PhiOS/PhiOS/dist/linux/builder-packages.txt": "9c8e376a83e3ebbad5078dbb9fc5cc12ecd15ad57c4fa933466bad26dd09a291", + "PhiOS/PhiOS/dist/linux/image-packages.txt": "dd6faf936234848a574c0d3125da4eddabaa33b8f02998bc7be070250d3e29f9", + "PhiOS/PhiOS/dist/linux/mkarchiso.log": "210fe06c25e034b3b8c06dbdf7e32143824db443429ae8c2434cb1f5494790ee", + "PhiOS/PhiOS/dist/linux/release.json": "0d5499ce8f252637d7a1d6a8bdedeb8aef9829307893e348f3c1bf0795b91a75", + "PhiOS/PhiOS/dist/linux/source-archive-sha256.txt": "be474ea9b44dca648d68c2a4b9f8971b2fbdbe699875af342e00e8324db6c022", + "PhiOS/PhiOS/dist/linux/source-commit.txt": "ba4278e899cd49006cff064e993e77669321afa243429bc7ce92db7639539f9e", + "_temp/phios-boot/boot-evidence.json": "8f9fc704ea011747ee80d029b77a5310be263490d45c8f078ce377cb40aeb1bd", + "_temp/phios-boot/qemu.log": "7e93b93909628e9b8dc122fb8e38c80eadcb005ae59eebc2389f10dad2a5c6c3", + "_temp/phios-boot/screen-first.png": "119720e9fd849fb46101ec2b2e37febb8ae5b047a92d4a5cc805c3bf6dfab1f4", + "_temp/phios-boot/screen.png": "6d9ec1bb565b61d9b611f0990846e1676eda1df8e885a2415efdde6775ea34b8", + "_temp/phios-boot/serial.log": "58dfdeb763934e146954e8f77e931071d1e7b4132ebe35e981911bf73a5e975e", + "_temp/phios-installed/failed-boot-qemu.log": "008c4e3799a49aa39738ac2c53e55d8f2e05ceaf38fc3e012d4090ca69c703bd", + "_temp/phios-installed/failed-boot-serial.log": "bf7aa9bdf1919f5cf386f81f3d333cead38295c3a8f48f2c016a5e9ea7ffbcfd", + "_temp/phios-installed/install-live-qemu.log": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "_temp/phios-installed/install-live-serial.log": "713c18dba07963505a9d697efd58e3ccdb1b6f0dcda3d0f6c57bd24d9c265574", + "_temp/phios-installed/installed-1-qemu.log": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "_temp/phios-installed/installed-1-serial.log": "069926fbd0102fc95fee13bccccc63d331d1056e3693d659d955b77d76aabf5c", + "_temp/phios-installed/installed-2-qemu.log": "008c4e3799a49aa39738ac2c53e55d8f2e05ceaf38fc3e012d4090ca69c703bd", + "_temp/phios-installed/installed-2-serial.log": "cc21a0726b72c15dad5884d86e383ceef3a8b3d47c493cb37b6fb76965c978c6", + "_temp/phios-installed/installed-3-qemu.log": "008c4e3799a49aa39738ac2c53e55d8f2e05ceaf38fc3e012d4090ca69c703bd", + "_temp/phios-installed/installed-3-serial.log": "c3c16fcb40e7375a74afd31580149848e3145d17fac6c189814f73537225a753", + "_temp/phios-installed/installed-evidence.json": "ba4b6a1fff1c4306b69080ffc7e15b90843be35ba555f5728c074c4616c4ba05", + "_temp/phios-installed/interrupted-resume-live-qemu.log": "008c4e3799a49aa39738ac2c53e55d8f2e05ceaf38fc3e012d4090ca69c703bd", + "_temp/phios-installed/interrupted-resume-live-serial.log": "a016304728dc00b63de3e8e9e39bd83218ab6599ec441d6960219f227a354290", + "_temp/phios-installed/recovery-live-qemu.log": "008c4e3799a49aa39738ac2c53e55d8f2e05ceaf38fc3e012d4090ca69c703bd", + "_temp/phios-installed/recovery-live-serial.log": "b89678271414d6a10d4eb28f552c1fc2f39a1016354faac05a06da0c9a06d86d", + "_temp/phios-installed/screen-failed-boot.png": "2cdd8a3c4c53bb7404010369d7aa1cff488f9740ac6ce5809c06c6eee545707f", + "_temp/phios-installed/screen-install-live.png": "6a3a045d248fe3842923183b859dab9516506191ef743d9c7f5553cba12735eb", + "_temp/phios-installed/screen-installed-1-greeter.png": "7ac572d1e19f89901e98628f8aabb11ca2507db1eb09b91123c0276cdbc0a9cc", + "_temp/phios-installed/screen-installed-1.png": "d597e9a1637fd8bb4a56fd19a1545da8cf643c89514180000f67ca04a783684a", + "_temp/phios-installed/screen-installed-2-greeter.png": "f83a37571994ca7274939836bf77a47904c689fb6d38bb8587a11f2432aeba0e", + "_temp/phios-installed/screen-installed-2.png": "7dab04b52ac853b325b9d3f4d9b38deccd143cec10df7e44846b3f2a66376775", + "_temp/phios-installed/screen-installed-3-greeter.png": "f83a37571994ca7274939836bf77a47904c689fb6d38bb8587a11f2432aeba0e", + "_temp/phios-installed/screen-installed-3.png": "9b5ded8d8dfb09063f51e79931f78ef324ca7f3ce0d0c44ecb63df623e1f5e50", + "_temp/phios-installed/screen-interrupted-resume-live.png": "4e6b5724fd7a17cfd8e449dd4f681bc6a89007f3c579e5a755010b883f8403cf", + "_temp/phios-installed/screen-recovery-live.png": "73a96888001aacb49325bc6680d5bcf561122e2ee0d3621de6c48fbb3493e500" + }, + "fixture_free": false, + "hardware_qualified": false, + "host_disks_attached": false, + "image_artifact_id": 11137807998, + "installed": true, + "interrupted_signed_transaction_observed": true, + "interrupted_update_active_root_preserved": true, + "iso_sha256": "391efdfd41e0217706b2b4028c47e9d37f7014762afc5d6831a30eb6bb2dba4b", + "iso_signed": false, + "job_id": 110190346637, + "live_boot_ids": [ + "6385ea7a68784bd4bbbd1c613f66661d", + "73e4c51c65d14265b729a226ebc0647a" + ], + "maintenance_head": "bb127d34227df6a7182580eaaca1ed04eb419bc2", + "matched_root_efi_restored": true, + "network": false, + "no_iso_boot_passed": true, + "ordinary_ci_existing_skips": 6, + "ordinary_ci_passed": 2218, + "ordinary_ci_run": 36805999618, + "public_disposable_credentials": true, + "ram_mib": 4096, + "record_sha256": "c481900567db858427663a26909e82a9d30fe2e083c929cb68683a9823e87bb4", + "recovery_checkpoint_generation": "aa3e52dc779a4c47a7fe9dff1a3092ce", + "recovery_requested": true, + "release_ready": false, + "schema_version": "phios.os-qualification-summary.v1", + "screenshot_visually_reviewed": true, + "shared_folders": false, + "signed_package_application_qualified": true, + "signed_update_refusals_observed": true, + "signed_update_requested": true, + "signed_update_transaction": { + "ephemeral_test_key": true, + "generation": "aa3e52dc779a4c47a7fe9dff1a3092ce", + "sequence": 1, + "signer": "39B4F5E46B179B7D91E7550F1C5219F76EBB7BB3" + }, + "simulated_boot_failure_observed": true, + "source_commit": "29def30a3079c99972f1606ae44ea3478d0f79d1", + "whole_os_recovery_passed": true, + "workflow_run": 36805999628 +} diff --git a/docs/os/evidence/recovery-attempts.json b/docs/os/evidence/recovery-attempts.json new file mode 100644 index 00000000..7dd1d251 --- /dev/null +++ b/docs/os/evidence/recovery-attempts.json @@ -0,0 +1,107 @@ +{ + "schema_version": "phios.recovery-attempt-evidence.v1", + "scope": "isolated UEFI KVM; fresh named 32-GiB disk; no network, host disks or shared folders", + "attempts": [ + { + "run_id": 36800067643, + "job_id": 110172173242, + "evidence_artifact_id": 11135382068, + "source_commit": "960bd3261b6b52df3335cdc9bec6a31980036d92", + "iso_sha256": "3e92086a8fad705e0edb9e6075a51d7a357830aae010e985af9c933113139817", + "checkpoint_created": false, + "whole_os_recovery_passed": false, + "release_ready": false, + "cause": "partition sysfs has no slaves directory", + "guest_error": "OS maintenance held: [Errno 2] No such file or directory: '/sys/dev/block/254:1/slaves'", + "files": { + "installed-evidence.json": { + "sha256": "84a2f5a6b02a765a237f10f2d5200251308acba6cd419014c6a94ff05edbf7bb", + "size": 1915 + }, + "install-live-serial.log": { + "sha256": "3e5d07c6e03c82f5d0010eb730a0bc13a702b7d21ec5ac4d90f45758c28ec6df", + "size": 57478 + } + }, + "evidence_url": "https://github.com/MichaelWave369/PhiOS/actions/runs/36800067643/artifacts/11135382068" + }, + { + "run_id": 36801548013, + "job_id": 110176775131, + "evidence_artifact_id": 11135933656, + "source_commit": "344667c3df6b0c2d5d223a5cf24a5ccb8760da8d", + "iso_sha256": "6e42c980e2f2fb81c0f396efd1c2384def52e5cc017e424003b393a51d4cc73b", + "checkpoint_created": false, + "whole_os_recovery_passed": false, + "release_ready": false, + "cause": "kernel rejected standalone nologreplay; use rescue=nologreplay", + "guest_error": "OS maintenance held: mount failed (exit 32): mount: /run/phios-recovery-r5kj676i/top: fsconfig() failed: btrfs: Unknown parameter 'nologreplay'.", + "files": { + "installed-evidence.json": { + "sha256": "4288acb8787d190ffbd181d79c6f6acf09593c55bcfd107b800848db3686a126", + "size": 1915 + }, + "install-live-serial.log": { + "sha256": "7493a51c566db4200dba78f93775962f3cb019a4a2330c424cdab7c94b17446d", + "size": 62870 + } + }, + "evidence_url": "https://github.com/MichaelWave369/PhiOS/actions/runs/36801548013/artifacts/11135933656" + }, + { + "run_id": 36802991205, + "job_id": 110181227245, + "evidence_artifact_id": 11136259045, + "source_commit": "1067477a6a389f364fc178f38e04a8847b046a2d", + "iso_sha256": "54c3cffa72ca4ab155e27952f3a99cab01f3a93626d130adb0d2b6001e19a02d", + "checkpoint_created": true, + "signature_refusals_observed": [], + "whole_os_recovery_passed": false, + "release_ready": false, + "cause": "makepkg fixture omitted source-file declarations; package() lacked data", + "guest_error": "see preserved package-builder traceback", + "files": { + "installed-evidence.json": { + "sha256": "17ca79b71182175e398e4f0fc3cfe26e5487218641e2d89c5eaf71ab7e14cc1b", + "size": 2199 + }, + "install-live-serial.log": { + "sha256": "a81a31bb7dafda38979895d25ed593afe5a377b7cedea7140bc035996d87f941", + "size": 62458 + } + }, + "evidence_url": "https://github.com/MichaelWave369/PhiOS/actions/runs/36802991205/artifacts/11136259045" + }, + { + "run_id": 36804253734, + "job_id": 110185006892, + "evidence_artifact_id": 11137416163, + "source_commit": "91f5ed68d1134add6b2bee025ec62ef967c01126", + "iso_sha256": "50fac795aae54942a4f0eb0a95a8df6e9604d6bc630b7db579409270fa9c12a1", + "checkpoint_created": true, + "signature_refusals_observed": [ + "missing-signature", + "wrong-key", + "tampered", + "expired" + ], + "whole_os_recovery_passed": false, + "release_ready": false, + "cause": "staged subvolume was not a mountpoint; mkinitcpio root detection error correctly held activation", + "guest_error": "OS update held: arch-chroot failed (exit 0): ==> Building image from preset: /etc/mkinitcpio.d/linux.preset: 'default'", + "files": { + "installed-evidence.json": { + "sha256": "db14179be3170434eaf7a2d6cfe035a147dbef255ba12871328ff036ffbdb0fb", + "size": 2199 + }, + "install-live-serial.log": { + "sha256": "ace627dfa8e1d1834581a47f4d748ba7474fd35269e2fd27cc98bff9062dc287", + "size": 274612 + } + }, + "evidence_url": "https://github.com/MichaelWave369/PhiOS/actions/runs/36804253734/artifacts/11137416163" + } + ], + "hardware_qualified": false, + "release_ready": false +} diff --git a/packaging/arch/phios/PKGBUILD b/packaging/arch/phios/PKGBUILD index 966ce24b..86c74aaa 100644 --- a/packaging/arch/phios/PKGBUILD +++ b/packaging/arch/phios/PKGBUILD @@ -6,7 +6,7 @@ pkgdesc='PhiOS operator shell, verification spine and governed local runtime' arch=('any') url='https://github.com/MichaelWave369/PhiOS' license=('MIT') -depends=('python' 'python-psutil' 'python-mcp>=1.26' 'python-mcp<2') +depends=('python' 'python-psutil' 'python-mcp>=1.26' 'python-mcp<2' 'gnupg') makedepends=('python-build' 'python-installer' 'python-setuptools' 'python-wheel') source=('phios-source.tar.gz') sha256sums=("${PHIOS_SOURCE_SHA256:?hashed source archive required}") @@ -25,4 +25,12 @@ package() { install -Dm644 PHIOS_SOURCE_COMMIT "$pkgdir/usr/share/phios/source-commit" install -Dm644 packaging/linux/installer/install.py "$pkgdir/usr/lib/phios-installer/install.py" install -Dm755 packaging/linux/installer/phios-install "$pkgdir/usr/bin/phios-install" + install -Dm644 packaging/linux/updates/verify.py "$pkgdir/usr/lib/phios-updates/verify.py" + install -Dm755 packaging/linux/updates/phios-update-verify "$pkgdir/usr/bin/phios-update-verify" + install -Dm644 packaging/linux/updates/recover.py "$pkgdir/usr/lib/phios-updates/recover.py" + install -Dm755 packaging/linux/updates/phios-os-recover "$pkgdir/usr/bin/phios-os-recover" + install -Dm644 packaging/linux/updates/apply.py "$pkgdir/usr/lib/phios-updates/apply.py" + install -Dm755 packaging/linux/updates/phios-os-update "$pkgdir/usr/bin/phios-os-update" + install -Dm644 packaging/linux/updates/enroll.py "$pkgdir/usr/lib/phios-updates/enroll.py" + install -Dm755 packaging/linux/updates/phios-update-enroll "$pkgdir/usr/bin/phios-update-enroll" } diff --git a/packaging/linux/installer/install.py b/packaging/linux/installer/install.py index 1cccf2f6..81ce7b43 100644 --- a/packaging/linux/installer/install.py +++ b/packaging/linux/installer/install.py @@ -206,6 +206,9 @@ def configure(root: Path, username: str, password: str, hostname: str, root_uuid write(root, "boot/loader/entries/phios.conf", "title PhiOS Linux development installation\n" "linux /vmlinuz-linux\ninitrd /initramfs-linux.img\n" f"options root=UUID={root_uuid} rw rootflags=subvol=@root\n") + write(root, "boot/loader/entries/phios-fallback.conf", "title PhiOS Linux fallback initramfs\n" + "linux /vmlinuz-linux\ninitrd /initramfs-linux-fallback.img\n" + f"options root=UUID={root_uuid} rw rootflags=subvol=@root\n") release = json.loads((root / "usr/share/phios/linux-release.json").read_text()) write(root, "etc/os-release", 'NAME="PhiOS Linux Preview"\nID=phios\nID_LIKE=arch\n' f'PRETTY_NAME="PhiOS Linux {release["os_version"]} Experimental Installation"\nVERSION_ID="{release["os_version"]}"\n') diff --git a/packaging/linux/prepare_profile.py b/packaging/linux/prepare_profile.py index 18a61187..f1784daa 100644 --- a/packaging/linux/prepare_profile.py +++ b/packaging/linux/prepare_profile.py @@ -44,6 +44,9 @@ def write(name: str, content: str) -> None: """ (destination / "pacman.conf").write_text(pacman) shutil.copyfile(repo / "packaging/linux/packages.x86_64", destination / "packages.x86_64") + if smoke: + with (destination / 'packages.x86_64').open('a') as packages: + packages.write('\nfakeroot\n') version = release["os_version"] (destination / "profiledef.sh").write_text(f"""#!/usr/bin/env bash # Built on the signed Archiso {release['archiso_version']} releng template. @@ -108,9 +111,9 @@ def write(name: str, content: str) -> None: "d /home/phios/.local/state 0700 phios phios -\n" "d /home/phios/.local/state/phios 0700 phios phios -\n" "d /var/lib/phios-agent 0700 phios-agent phios-agent -\n") - # The volatile public account can invoke this one root-owned interactive - # installer; it receives no unrestricted sudo shell. - write("etc/sudoers.d/phios-live-installer", "phios ALL=(root) NOPASSWD: /usr/bin/phios-install\n") + # The volatile account can invoke only these root-owned interactive + # maintenance commands; it receives no unrestricted sudo shell. + write("etc/sudoers.d/phios-live-installer", "phios ALL=(root) NOPASSWD: /usr/bin/phios-install, /usr/bin/phios-os-recover, /usr/bin/phios-os-update, /usr/bin/phios-update-enroll\n") write("etc/greetd/config.toml", '[terminal]\nvt = 1\n[default_session]\n' 'command = "tuigreet --cmd phios-session"\nuser = "phios-greeter"\n' '[initial_session]\ncommand = "phios-session"\nuser = "phios"\n') @@ -141,6 +144,7 @@ def write(name: str, content: str) -> None: (root / "etc/systemd/system/serial-getty@ttyS0.service").symlink_to("/dev/null") write("usr/local/bin/phios-live-smoke", (repo / "packaging/linux/tests/live-smoke.sh").read_text()) write("usr/local/bin/phios-live-install-smoke.py", (repo / "packaging/linux/tests/install_smoke.py").read_text()) + write("usr/local/bin/phios-live-update-smoke.py", (repo / "packaging/linux/tests/update_smoke.py").read_text()) write("etc/systemd/system/phios-live-smoke.service", "[Unit]\nDescription=CI live-image qualification fixture\n" "After=greetd.service\n[Service]\nType=oneshot\nExecStart=/usr/local/bin/phios-live-smoke\n" "TimeoutStartSec=1800\nStandardOutput=tty\nStandardError=tty\nTTYPath=/dev/ttyS0\n") diff --git a/packaging/linux/tests/install_smoke.py b/packaging/linux/tests/install_smoke.py index 03369bbd..0b8b48f7 100644 --- a/packaging/linux/tests/install_smoke.py +++ b/packaging/linux/tests/install_smoke.py @@ -5,6 +5,7 @@ """ from __future__ import annotations +import importlib.util import json import os import pty @@ -21,9 +22,19 @@ def command(*args: str, data: str | None = None) -> str: return subprocess.check_output(args, input=data, text=True, stderr=subprocess.STDOUT) -def drive_installer(*, cancel: bool) -> None: +def drive_installer(*, cancel: bool, recovery: list[str] | None = None, update: Path | None = None, + reject: bool = False, plan: bool = False, interrupt: bool = False, + enroll: tuple[Path, str] | None = None) -> str: pid, fd = pty.fork() if pid == 0: + if enroll is not None: + os.execv('/usr/bin/phios-update-enroll', ['phios-update-enroll', '--public-key', str(enroll[0]), + '--fingerprint', enroll[1]]) + if update is not None: + os.execv('/usr/bin/phios-os-update', ['phios-os-update', '--disk', '/dev/vda', '--bundle', str(update), + *(['--plan'] if plan else [])]) + if recovery is not None: + os.execv('/usr/bin/phios-os-recover', ['phios-os-recover', *recovery, '--disk', '/dev/vda']) os.execv("/usr/bin/phios-install", ["phios-install", "--disk", "/dev/vda", "--username", "operator"]) text = "" replied: set[str] = set() @@ -45,24 +56,31 @@ def drive_installer(*, cancel: bool) -> None: if prompt in text and prompt not in replied: os.write(fd, (PASSWORD + "\n").encode()) replied.add(prompt) - match = re.search(r"INSTALL /dev/vda [0-9a-f]{64}\r?\n", text) + match = re.search(r"(?:INSTALL|CHECKPOINT|RESTORE|UPDATE|ENROLL) (?:/dev/vda|/etc/phios) [0-9a-f]{64}\r?\n", text) if match and "confirm" not in replied and "> " in text[match.end():]: os.write(fd, ("cancel\n" if cancel else match[0].strip() + "\n").encode()) replied.add("confirm") + if interrupt and 'stage' not in replied: + markers = list(Path('/run').glob('phios-recovery-*/top/@update-*/.phios-ci-stage-in-progress')) + if (len(markers) == 1 and markers[0].read_text() == 'staged pacman hook reached\n' and + (markers[0].parent / 'run/phios-ci-signed-hook-ready').is_file()): + print('PHIOS_SIGNED_STAGE_IN_PROGRESS', flush=True) + replied.add('stage') ended, status = os.waitpid(pid, os.WNOHANG) if ended: - expected = 1 if cancel else 0 + expected = 1 if cancel or reject else 0 if os.waitstatus_to_exitcode(status) != expected: raise RuntimeError("production installer returned an unexpected status") - return + return text ended, status = os.waitpid(pid, os.WNOHANG) for _ in range(50): if ended: break time.sleep(0.1) ended, status = os.waitpid(pid, os.WNOHANG) - if not ended or os.waitstatus_to_exitcode(status) != (1 if cancel else 0): + if not ended or os.waitstatus_to_exitcode(status) != (1 if cancel or reject else 0): raise RuntimeError("production installer failed or timed out") + return text finally: try: ended, _ = os.waitpid(pid, os.WNOHANG) @@ -78,6 +96,36 @@ def main() -> None: row = json.loads(command("lsblk", "--nodeps", "--json", "--output", "SERIAL,TYPE,SIZE", "--bytes", "/dev/vda"))["blockdevices"][0] if os.geteuid() != 0 or row["serial"] != "PHIOS_CI_BLANK" or row["type"] != "disk" or row["size"] != 32 * 1024**3: raise RuntimeError("CI install fixture requires its exact disposable virtual disk") + command('modprobe', 'qemu_fw_cfg') + mode = Path('/sys/firmware/qemu_fw_cfg/by_name/opt/phios-ci-signed-updates/raw') + signed_updates = mode.exists() and mode.read_bytes() == b'enabled' + updater = None + if signed_updates: + spec = importlib.util.spec_from_file_location('phios_ci_update_fixture', '/usr/local/bin/phios-live-update-smoke.py') + assert spec is not None and spec.loader is not None + updater = importlib.util.module_from_spec(spec) + spec.loader.exec_module(updater) + if Path('/dev/vda1').exists(): + if updater is not None: + updater.resume_or_restore() + return + # Only the host harness's already installed disposable disk reaches + # this branch. The production live profile excludes this fixture. + root = Path('/run/phios-ci-checkpoint-read') + root.mkdir(mode=0o700) + command('mount', '-t', 'btrfs', '-o', 'ro,rescue=nologreplay,subvolid=5', '/dev/vda2', str(root)) + try: + generations = list((root / '@snapshots/recovery').glob('*/checkpoint.json')) + if len(generations) != 1: + raise RuntimeError('exactly one disposable checkpoint is required') + generation = generations[0].parent.name + finally: + command('umount', str(root)) + drive_installer(cancel=True, recovery=['restore', '--generation', generation]) + print('PHIOS_OS_RESTORE_CANCEL_OK', flush=True) + drive_installer(cancel=False, recovery=['restore', '--generation', generation]) + print('PHIOS_OS_RESTORE_OK:' + generation, flush=True) + return drive_installer(cancel=True) signatures = json.loads(command("wipefs", "--no-act", "--json", "/dev/vda"))["signatures"] if signatures: @@ -129,6 +177,20 @@ def main() -> None: finally: for path in reversed(mounts): command("umount", str(path)) + drive_installer(cancel=False, recovery=['checkpoint']) + root = Path('/run/phios-ci-checkpoint-read') + root.mkdir(mode=0o700) + command('mount', '-t', 'btrfs', '-o', 'ro,rescue=nologreplay,subvolid=5', '/dev/vda2', str(root)) + try: + generations = list((root / '@snapshots/recovery').glob('*/checkpoint.json')) + if len(generations) != 1: + raise RuntimeError('checkpoint creation did not retain exact metadata') + print('PHIOS_OS_CHECKPOINT_OK:' + generations[0].parent.name, flush=True) + finally: + command('umount', str(root)) + if updater is not None: + updater.initial() + raise RuntimeError('signed-update fixture returned without actual host interruption') print("PHIOS_INSTALLED_DISK_OK:" + receipt["plan"]["source_commit"], flush=True) diff --git a/packaging/linux/tests/installed_probe.py b/packaging/linux/tests/installed_probe.py index 020c8190..46666cfb 100644 --- a/packaging/linux/tests/installed_probe.py +++ b/packaging/linux/tests/installed_probe.py @@ -13,7 +13,7 @@ from phios.state_recovery import restore, verify_backup -def probe(source: str, phase: int) -> None: +def probe(source: str, phase: int, *, signed_update: bool = False) -> None: root = Path.home() / ".local/state/phios" assert os.getuid() == 1000 assert Path("/usr/share/phios/source-commit").read_text().strip() == source @@ -33,6 +33,15 @@ def probe(source: str, phase: int) -> None: assert read_jsonl(root / "qa/acknowledged.jsonl") == [{"source_commit": source, "execution_authority": False}] assert not (Path.home() / ".config/phios/memory.json").exists() assert not (root / "spine-v0.1/ledger/ghostwalk-authorization-decisions.jsonl").exists() + if signed_update: + package = Path('/usr/share/phios-ci-update/verified.txt') + if phase < 3: + assert package.read_bytes() == b'authenticated disposable PhiOS package update\n' + assert subprocess.check_output(['pacman', '-Q', 'phios-ci-update'], text=True).strip() == 'phios-ci-update 1.0.0-1' + else: + assert not package.exists() + assert subprocess.run(['pacman', '-Q', 'phios-ci-update'], capture_output=True).returncode == 1 + assert not Path('/usr/share/phios-ci-interrupt/verified.txt').exists() # The host enters the same fresh account at greetd; the compositor and # browser must be launched by the configured login/session services. for _ in range(90): diff --git a/packaging/linux/tests/live-smoke.sh b/packaging/linux/tests/live-smoke.sh index 6640ec38..28ce534a 100755 --- a/packaging/linux/tests/live-smoke.sh +++ b/packaging/linux/tests/live-smoke.sh @@ -1,5 +1,5 @@ #!/usr/bin/env bash -# This fixture is included only when PHIOS_CI_SMOKE=1; it performs no disk writes. +# CI-only. Disk writes require the install fixture's exact disposable disk. set -euo pipefail dump_failure() { echo PHIOS_BOOT_FAILED diff --git a/packaging/linux/tests/qemu_install.py b/packaging/linux/tests/qemu_install.py index d708a512..389f0db4 100644 --- a/packaging/linux/tests/qemu_install.py +++ b/packaging/linux/tests/qemu_install.py @@ -38,7 +38,135 @@ def stop(process: subprocess.Popen[Any], *, abrupt: bool = False) -> None: process.wait(timeout=5) -def qualify(iso: Path, source: str, output: Path) -> None: +def failed_boot(common: list[str], output: Path, receipt: dict[str, Any]) -> None: + """Require an observed kernel/root failure, never treat a timeout as proof.""" + qmp, serial = output / 'failed-boot-qmp.sock', output / 'failed-boot-serial.log' + command = common + ['-serial', f'file:{serial}', '-qmp', f'unix:{qmp},server=on,wait=off'] + receipt['commands'].append(command) + with (output / 'failed-boot-qemu.log').open('w') as log: + process = subprocess.Popen(command, stdout=log, stderr=subprocess.STDOUT) + try: + deadline = time.monotonic() + 180 + while time.monotonic() < deadline: + text = serial.read_text(errors='replace') if serial.exists() else '' + if 'Kernel panic' in text or 'Unable to mount root fs' in text: + receipt['simulated_boot_failure_observed'] = True + break + if 'login: ' in text or process.poll() is not None: + raise RuntimeError('the deliberately broken root unexpectedly booted or VM exited') + time.sleep(1) + else: + raise RuntimeError('no specific unbootable-system failure was observed') + finally: + if process.poll() is None: + capture_display(qmp, output, name='screen-failed-boot') + stop(process) + + +def recover_live(common: list[str], iso: Path, output: Path, receipt: dict[str, Any]) -> None: + qmp, serial = output / 'recovery-qmp.sock', output / 'recovery-live-serial.log' + command = common + ['-drive', f'file={iso.resolve()},if=none,id=installation,format=raw,media=cdrom,readonly=on', + '-device', 'ide-cd,drive=installation,bootindex=1', '-serial', f'file:{serial}', + '-qmp', f'unix:{qmp},server=on,wait=off'] + receipt['commands'].append(command) + with (output / 'recovery-live-qemu.log').open('w') as log: + process = subprocess.Popen(command, stdout=log, stderr=subprocess.STDOUT) + try: + deadline = time.monotonic() + 900 + login_sent = False + while time.monotonic() < deadline: + text = serial.read_text(errors='replace') if serial.exists() else '' + if 'PHIOS_BOOT_FAILED' in text or process.poll() is not None: + raise RuntimeError('live system/root/EFI recovery fixture failed') + if 'PHIOS_LOGIN_REQUIRED:' in text and not login_sent: + enter_live_login(qmp) + login_sent = True + marker = 'PHIOS_OS_RESTORE_OK:' + receipt['recovery_checkpoint_generation'] + if marker in text: + assert 'PHIOS_OS_RESTORE_CANCEL_OK' in text + receipt['matched_root_efi_restored'] = True + break + time.sleep(1) + else: + raise RuntimeError('live-media recovery timed out') + finally: + if process.poll() is None: + capture_display(qmp, output, name='screen-recovery-live') + stop(process) + if not receipt.get('matched_root_efi_restored') and serial.exists(): + print('\n'.join(serial.read_text(errors='replace').splitlines()[-160:])) + + +def install_live(common: list[str], iso: Path, output: Path, source: str, receipt: dict[str, Any], + *, signed_update: bool) -> None: + for attempt in range(2 if signed_update else 1): + prefix = 'install-live' if attempt == 0 else 'interrupted-resume-live' + qmp, serial = output / (prefix + '-qmp.sock'), output / (prefix + '-serial.log') + command = common + ['-drive', f'file={iso.resolve()},if=none,id=installation,format=raw,media=cdrom,readonly=on', + '-device', 'ide-cd,drive=installation,bootindex=1', '-serial', f'file:{serial}', + '-qmp', f'unix:{qmp},server=on,wait=off'] + receipt['commands'].append(command) + interrupted = False + with (output / (prefix + '-qemu.log')).open('w') as log: + process = subprocess.Popen(command, stdout=log, stderr=subprocess.STDOUT) + try: + deadline = time.monotonic() + (1800 if receipt['accelerator'] == 'kvm' else 3000) + login_sent = False + while time.monotonic() < deadline: + text = serial.read_text(errors='replace') if serial.exists() else '' + if 'PHIOS_BOOT_FAILED' in text or process.poll() is not None: + raise RuntimeError('live installer or signed package qualification failed') + if 'UEFI Interactive Shell' in text: + raise RuntimeError('firmware did not boot the installation ISO') + if 'PHIOS_LOGIN_REQUIRED:' in text and not login_sent: + enter_live_login(qmp) + login_sent = True + if signed_update and 'PHIOS_SIGNED_STAGE_IN_PROGRESS' in text: + if attempt != 0: + raise RuntimeError('unexpected second package interruption') + updates = re.findall(r'PHIOS_SIGNED_UPDATE_OK:(\{[^\r\n]+\})', text) + if len(updates) != 1: + raise RuntimeError('exact successful signed package transaction not observed') + for case in ['missing-signature', 'wrong-key', 'tampered', 'expired', 'replay', 'dependency']: + if 'PHIOS_SIGNED_REFUSAL_OK:' + case not in text: + raise RuntimeError('signed update refusal case missing: ' + case) + receipt['signed_update_transaction'] = json.loads(updates[0]) + receipt['signed_update_refusals_observed'] = True + receipt['interrupted_signed_transaction_observed'] = True + interrupted = True + break + if f'PHIOS_INSTALLED_DISK_OK:{source}' in text: + if signed_update: + if attempt != 1 or 'PHIOS_INTERRUPTED_UPDATE_HELD_OK' not in text: + raise RuntimeError('actual interrupted-stage recovery not observed') + receipt['interrupted_update_active_root_preserved'] = True + elif 'PHIOS_INSTALL_CANCEL_OK' not in text or 'PHIOS_INSTALLED_SEED_OK:' not in text: + raise RuntimeError('production cancellation and data seed not observed') + generations = re.findall(r'PHIOS_OS_CHECKPOINT_OK:([0-9a-f]{32})', text) + if receipt['recovery_requested']: + if len(generations) != 1: + raise RuntimeError('explicit recovery checkpoint not observed') + receipt['recovery_checkpoint_generation'] = generations[0] + if signed_update and generations[0] != receipt['signed_update_transaction']['generation']: + raise RuntimeError('recovery selected a different update checkpoint') + receipt['installed'] = True + return + time.sleep(1) + else: + raise RuntimeError('live install/update qualification timed out') + finally: + if process.poll() is None: + try: + capture_display(qmp, output, name='screen-' + prefix) + except (OSError, ValueError, RuntimeError) as exc: + receipt['display_capture_error'] = str(exc) + stop(process, abrupt=interrupted) + if not receipt['installed'] and not interrupted and serial.exists(): + print('\n'.join(serial.read_text(errors='replace').splitlines()[-160:])) + raise RuntimeError('disposable installed target never qualified') + + +def qualify(iso: Path, source: str, output: Path, *, recovery: bool = False, signed_update: bool = False) -> None: if not re.fullmatch(r"[0-9a-f]{40}", source) or not iso.is_file() or output.exists(): raise ValueError("exact source/ISO and a new owned evidence destination are required") output.mkdir(mode=0o700, parents=True) @@ -59,6 +187,10 @@ def qualify(iso: Path, source: str, output: Path) -> None: "-device", "virtio-blk-pci,drive=target,serial=PHIOS_CI_BLANK,bootindex=2", "-nic", "none", "-vga", "none", "-device", "virtio-vga", "-display", "none", "-monitor", "none"] + if signed_update: + if not recovery: + raise ValueError('signed-update qualification includes matched root/EFI recovery') + common += ['-fw_cfg', 'name=opt/phios-ci-signed-updates,string=enabled'] digest = hashlib.sha256() with iso.open("rb") as handle: for block in iter(lambda: handle.read(1024**2), b""): @@ -67,53 +199,17 @@ def qualify(iso: Path, source: str, output: Path) -> None: "iso_sha256": digest.hexdigest(), "accelerator": accelerator, "disk_serial": "PHIOS_CI_BLANK", "disk_bytes": 32 * 1024**3, "commands": [], "installed": False, "no_iso_boot_passed": False, "abrupt_virtual_restart_passed": False, "boot_ids": [], "ci_serial_console_injected": True, - "hardware_qualified": False, "release_ready": False} + "hardware_qualified": False, "release_ready": False, 'recovery_requested': recovery, + 'simulated_boot_failure_observed': False, 'matched_root_efi_restored': False, + 'whole_os_recovery_passed': False, 'signed_package_application_qualified': False} + receipt.update(signed_update_requested=signed_update, signed_update_refusals_observed=False, + interrupted_signed_transaction_observed=False, interrupted_update_active_root_preserved=False) try: - # Installer first boot: the CI-only live fixture drives both cancellation - # and exact typed confirmation through the unmodified production CLI. - qmp = output / "live-qmp.sock" - serial = output / "install-live-serial.log" - # OVMF must receive one consistent boot-order mechanism. Mixing a - # device bootindex with -boot d excluded the CD and selected the empty - # target. Give the installation CD explicit priority over that target. - command = common + ["-drive", f"file={iso.resolve()},if=none,id=installation,format=raw,media=cdrom,readonly=on", - "-device", "ide-cd,drive=installation,bootindex=1", "-serial", f"file:{serial}", - "-qmp", f"unix:{qmp},server=on,wait=off"] - receipt["commands"].append(command) - with (output / "install-live-qemu.log").open("w") as log: - process = subprocess.Popen(command, stdout=log, stderr=subprocess.STDOUT) - try: - deadline = time.monotonic() + (1800 if accelerated else 3000) - login_sent = False - while time.monotonic() < deadline: - text = serial.read_text(errors="replace") if serial.exists() else "" - if "PHIOS_BOOT_FAILED" in text or process.poll() is not None: - raise RuntimeError("live installer qualification failed") - if "UEFI Interactive Shell" in text: - raise RuntimeError("firmware did not boot the installation ISO") - if "PHIOS_LOGIN_REQUIRED:" in text and not login_sent: - enter_live_login(qmp) - login_sent = True - if f"PHIOS_INSTALLED_DISK_OK:{source}" in text: - assert "PHIOS_INSTALL_CANCEL_OK" in text and "PHIOS_INSTALLED_SEED_OK:" in text - receipt["installed"] = True - break - time.sleep(1) - else: - raise RuntimeError("installation qualification timed out") - finally: - if process.poll() is None: - try: - capture_display(qmp, output, name="screen-install-live") - except (OSError, ValueError, RuntimeError) as exc: - receipt["display_capture_error"] = str(exc) - stop(process) - if not receipt["installed"] and serial.exists(): - print("\n".join(serial.read_text(errors="replace").splitlines()[-160:])) + install_live(common, iso, output, source, receipt, signed_update=signed_update) # Boot the new disk twice with no ISO attached, normal password/PAM # logins and actual greetd keyboard input. Between boots kill QEMU so # acknowledged data must survive loss of the guest's memory. - for phase in [1, 2]: + for phase in ([1, 2, 3] if recovery else [1, 2]): qmp = output / f"installed-{phase}-qmp.sock" serial_socket = output / f"installed-{phase}-serial.sock" command = common + ["-serial", f"unix:{serial_socket},server=on,wait=off", @@ -183,7 +279,8 @@ def wait_for(pattern: str) -> re.Match[str]: send_text(qmp, "operator") time.sleep(1) send_text(qmp, PASSWORD) - program = Path(__file__).with_name("installed_probe.py").read_text() + f"\nprobe({source!r}, {phase})\n" + program = Path(__file__).with_name("installed_probe.py").read_text() + \ + f"\nprobe({source!r}, {phase}, signed_update={signed_update!r})\n" # Keep each input line below the terminal's canonical # line bound; a growing base64 -c command can exceed it. channel.sendall(("python - <<'PHIOS_INSTALLED_PROBE'\n" + program + @@ -195,6 +292,17 @@ def wait_for(pattern: str) -> re.Match[str]: receipt["boot_ids"].append(details["boot_id"]) receipt["record_sha256"] = details["record_sha256"] capture_display(qmp, output, name=f"screen-installed-{phase}") + if recovery and phase == 2: + # Test-only administration through normal sudo + # password authentication; never shipped as a + # production effect or a confirmation bypass. + damage = "from pathlib import Path; import os; " + \ + "[Path('/boot/'+p).write_bytes(b'intentional CI boot corruption') for p in " + \ + "['initramfs-linux.img','initramfs-linux-fallback.img']]; " + \ + "Path('/usr/bin/wayfire').rename('/usr/bin/wayfire.failed-ci'); " + \ + "os.sync(); print('PHIOS_OS_DAMAGE_OK:'+str(os.geteuid()),flush=True)" + channel.sendall((f"printf '%s\\n' '{PASSWORD}' | sudo -S python -c \"{damage}\"\n").encode()) + wait_for(r'PHIOS_OS_DAMAGE_OK:0') finally: if process.poll() is None and not (output / f"screen-installed-{phase}.ppm").exists(): try: @@ -202,10 +310,20 @@ def wait_for(pattern: str) -> re.Match[str]: except (OSError, ValueError, RuntimeError): pass stop(process, abrupt=(phase == 1)) - if len(set(receipt["boot_ids"])) != 2: + if recovery and phase == 2: + failed_boot(common, output, receipt) + recover_live(common, iso, output, receipt) + if len(set(receipt["boot_ids"])) != (3 if recovery else 2): raise RuntimeError("a distinct installed reboot was not observed") receipt["no_iso_boot_passed"] = True receipt["abrupt_virtual_restart_passed"] = True + if recovery: + receipt['whole_os_recovery_passed'] = (receipt['simulated_boot_failure_observed'] and + receipt['matched_root_efi_restored']) + if signed_update: + receipt['signed_package_application_qualified'] = (receipt['whole_os_recovery_passed'] and + receipt['signed_update_refusals_observed'] and receipt['interrupted_signed_transaction_observed'] and + receipt['interrupted_update_active_root_preserved']) print("Disposable installation, no-ISO graphical login, data restore and abrupt virtual restart passed") except BaseException as exc: receipt["error"] = str(exc) @@ -219,5 +337,7 @@ def wait_for(pattern: str) -> re.Match[str]: parser.add_argument("--iso", required=True, type=Path) parser.add_argument("--source", required=True) parser.add_argument("--output", required=True, type=Path) + parser.add_argument('--recovery', action='store_true', help='Also damage and recover only this disposable installed disk') + parser.add_argument('--signed-update', action='store_true', help='Also qualify signed packages and actual interrupted staging') args = parser.parse_args() - qualify(args.iso, args.source, args.output.resolve()) + qualify(args.iso, args.source, args.output.resolve(), recovery=args.recovery, signed_update=args.signed_update) diff --git a/packaging/linux/tests/update_smoke.py b/packaging/linux/tests/update_smoke.py new file mode 100644 index 00000000..9be12fd0 --- /dev/null +++ b/packaging/linux/tests/update_smoke.py @@ -0,0 +1,278 @@ +"""CI-only signed package and interrupted-staging qualification fixture. + +Never included in normal images. Private signing keys exist only in the live +VM's volatile /run. Only the named, fresh 32-GiB disposable target is supported. +""" +from __future__ import annotations + +import hashlib +import importlib.util +import json +import os +import shutil +import subprocess +import tempfile +from contextlib import contextmanager +from datetime import UTC, datetime, timedelta +from pathlib import Path +from typing import Any, Iterator + +spec = importlib.util.spec_from_file_location('phios_ci_installer', '/usr/local/bin/phios-live-install-smoke.py') +assert spec is not None and spec.loader is not None +installer = importlib.util.module_from_spec(spec) +spec.loader.exec_module(installer) +spec = importlib.util.spec_from_file_location('phios_ci_application', '/usr/lib/phios-updates/apply.py') +assert spec is not None and spec.loader is not None +apply = importlib.util.module_from_spec(spec) +spec.loader.exec_module(apply) + +PLAN = '@snapshots/phios-ci-qualification.json' +PACKAGE = 'phios-ci-update' +FILE = 'usr/share/' + PACKAGE + '/verified.txt' +CONTENT = b'authenticated disposable PhiOS package update\n' + + +def command(*args: str, **kwargs: Any) -> str: + try: + return subprocess.check_output(args, text=True, stderr=subprocess.STDOUT, **kwargs) + except subprocess.CalledProcessError as exc: + print((exc.output or '')[-6000:], flush=True) + raise + + +@contextmanager +def disk(*, writable: bool = False) -> Iterator[tuple[Path, Path]]: + identity = apply.recover.inventory('/dev/vda') + if identity['serial_or_wwn'] != 'PHIOS_CI_BLANK' or identity['size_bytes'] != 32 * 1024**3: + raise ValueError('signed-update fixture requires its exact disposable disk') + with apply.recover.mounted(identity, writable=writable) as pair: + yield pair + + +def state(top: Path, esp: Path) -> dict[str, Any]: + root = top / '@root' + source = (root / 'usr/share/phios/source-commit').read_text().strip() + return {'source_commit': source, 'packages': apply.packages(root), 'sequence': apply.sequence(top, source), + 'boot_files': apply.recover.boot_inventory(esp)} + + +def signer(base: Path, label: str) -> tuple[Path, str, bytes]: + home = base / label + home.mkdir(mode=0o700) + command('gpg', '--no-options', '--homedir', str(home), '--batch', '--pinentry-mode', 'loopback', + '--passphrase', '', '--quick-generate-key', 'PhiOS Disposable ' + label + ' ', + 'ed25519', 'sign', '1d') + listing = command('gpg', '--no-options', '--homedir', str(home), '--with-colons', '--list-keys') + fingerprint = next(row.split(':')[9] for row in listing.splitlines() if row.startswith('fpr:')) + public = subprocess.check_output(['gpg', '--no-options', '--homedir', str(home), '--export', fingerprint]) + return home, fingerprint, public + + +def sign(home: Path, path: Path) -> None: + command('gpg', '--no-options', '--homedir', str(home), '--batch', '--yes', '--pinentry-mode', 'loopback', + '--passphrase', '', '--detach-sign', str(path)) + + +def package(base: Path, name: str, *, missing_dependency: bool = False, interrupt: bool = False) -> Path: + # Use Arch's actual package builder, including PKGINFO, BUILDINFO and MTREE. + # Only this CI profile adds fakeroot. There are no network dependencies. + work = Path(tempfile.mkdtemp(prefix='phios-ci-package-', dir='/home/phios')) + try: + work.chmod(0o700) + (work / 'data').write_bytes(CONTENT) + shutil.copyfile('/usr/share/licenses/phios/LICENSE', work / 'LICENSE') + build = "pkgname=" + name + "\npkgver=1.0.0\npkgrel=1\narch=('any')\n" + \ + "pkgdesc='Disposable PhiOS qualification package'\nlicense=('MIT')\noptions=('!strip' '!debug')\n" + build += "source=('data' 'LICENSE')\nsha256sums=(" + ' '.join( + "'" + hashlib.sha256((work / source).read_bytes()).hexdigest() + "'" for source in ['data', 'LICENSE']) + ')\n' + if missing_dependency: + build += "depends=('phios-ci-never-exists=999')\n" + if interrupt: + build += "install=interrupt.install\n" + (work / 'interrupt.install').write_text('post_install() {\n' + " printf 'staged pacman hook reached\\n' > /.phios-ci-stage-in-progress\n" + ' /usr/bin/sync\n /usr/bin/touch /run/phios-ci-signed-hook-ready\n /usr/bin/sleep 600\n}\n') + build += 'package() {\n install -Dm644 data "$pkgdir/usr/share/$pkgname/verified.txt"\n' + \ + ' install -Dm644 LICENSE "$pkgdir/usr/share/licenses/$pkgname/LICENSE"\n}\n' + (work / 'PKGBUILD').write_text(build) + for path in [work, *work.iterdir()]: + os.chown(path, 1000, 1000) + command('runuser', '-u', 'phios', '--', 'bash', '-c', + 'cd "$1"; exec makepkg --nodeps --force --noconfirm', 'phios-ci-build', str(work), timeout=120) + archives = [path for path in work.glob('*.pkg.tar.*') if not path.name.endswith('.sig')] + if len(archives) != 1: + raise ValueError('actual makepkg output must be exactly one archive') + target = base / archives[0].name + shutil.copyfile(archives[0], target) + return target + finally: + shutil.rmtree(work) + + +def bundle(base: Path, name: str, current: dict[str, Any], key: tuple[Path, str, bytes], + *, missing_dependency: bool = False, interrupt: bool = False) -> Path: + destination = base / ('bundle-' + name) + destination.mkdir(mode=0o700) + archive = package(destination, name, missing_dependency=missing_dependency, interrupt=interrupt) + now = datetime.now(UTC) + payload = {'schema_version': 'phios.os-package-update.v1', 'channel': 'experimental', 'architecture': 'x86_64', + 'from_source_commit': current['source_commit'], 'source_commit': current['source_commit'], + 'base_sequence': current['sequence'], 'sequence': current['sequence'] + 1, + 'created_at': now.isoformat(), 'expires_at': (now + timedelta(days=1)).isoformat(), + 'arch_snapshot': '2026/09/30', 'state_schemas': dict(apply.verify.SCHEMAS), + 'base_packages': current['packages'], 'target_packages': sorted([*current['packages'], + {'name': name, 'version': '1.0.0-1'}], key=lambda row: row['name']), + 'packages': [{'name': name, 'version': '1.0.0-1', 'filename': archive.name, + 'sha256': hashlib.sha256(archive.read_bytes()).hexdigest(), 'size': archive.stat().st_size}]} + manifest = destination / 'manifest.json' + manifest.write_text(json.dumps(payload, sort_keys=True)) + sign(key[0], manifest) + sign(key[0], archive) + return destination + + +def initial() -> None: + with tempfile.TemporaryDirectory(prefix='phios-ci-signing-', dir='/run') as temporary: + base = Path(temporary) + accepted, wrong = signer(base, 'accepted'), signer(base, 'untrusted') + try: + # Test-only manual enrollment into the volatile live environment; + # no trust or private key was shipped by the production image. + exported = base / 'enrollment-public-key.gpg' + exported.write_bytes(accepted[2]) + exported.chmod(0o600) + installer.drive_installer(cancel=True, enroll=(exported, accepted[1])) + if apply.verify.TRUST.exists() or apply.verify.KEYRING.exists(): + raise ValueError('cancelled enrollment changed signing trust') + installer.drive_installer(cancel=False, enroll=(exported, accepted[1])) + policy, _public = apply.verify.load_trust() + if policy['primary_fingerprint'] != accepted[1]: + raise ValueError('production enrollment did not retain the authenticated fingerprint') + print('PHIOS_SIGNING_ENROLLMENT_OK', flush=True) + with disk() as (top, esp): + before = state(top, esp) + valid = bundle(base, PACKAGE, before, accepted) + for case in ['missing-signature', 'wrong-key', 'tampered', 'expired']: + invalid = base / case + shutil.copytree(valid, invalid) + manifest = invalid / 'manifest.json' + payload = json.loads(manifest.read_text()) + archive = invalid / payload['packages'][0]['filename'] + if case == 'missing-signature': + (invalid / (archive.name + '.sig')).unlink() + elif case == 'wrong-key': + sign(wrong[0], manifest) + sign(wrong[0], archive) + elif case == 'tampered': + data = bytearray(archive.read_bytes()) + data[-1] ^= 1 + archive.write_bytes(data) + else: + payload.update(created_at=(datetime.now(UTC) - timedelta(days=1)).isoformat(), + expires_at=(datetime.now(UTC) - timedelta(hours=1)).isoformat()) + manifest.write_text(json.dumps(payload, sort_keys=True)) + sign(accepted[0], manifest) + result = installer.drive_installer(cancel=False, update=invalid, reject=True, plan=True) + if 'OS update held:' not in result: + raise ValueError('invalid signed bundle did not fail at the production update boundary') + with disk() as (top, esp): + if state(top, esp) != before: + raise ValueError('rejected bundle changed active root or EFI') + print('PHIOS_SIGNED_REFUSAL_OK:' + case, flush=True) + installer.drive_installer(cancel=True, update=valid) + with disk() as (top, esp): + if state(top, esp) != before: + raise ValueError('cancelled signed update changed the active system') + result = installer.drive_installer(cancel=False, update=valid) + with disk() as (top, esp): + current = state(top, esp) + if current['sequence'] != 1 or (top / '@root' / FILE).read_bytes() != CONTENT: + raise ValueError('signed package or persistent generation was not actually installed') + expected = sorted([*before['packages'], {'name': PACKAGE, 'version': '1.0.0-1'}], key=lambda row: row['name']) + if current['packages'] != expected: + raise ValueError('actual installed inventory differs from the signed complete target') + matches = [path for path in (top / '@snapshots/recovery').glob('*/update-transaction.json') + if json.loads(path.read_text()).get('activated') is True] + if len(matches) != 1: + raise ValueError('exactly one successful update transaction required') + generation = matches[0].parent.name + installer.drive_installer(cancel=False, update=valid, reject=True, plan=True) + with disk() as (top, esp): + if state(top, esp) != current: + raise ValueError('replayed transition changed the active system') + print('PHIOS_SIGNED_REFUSAL_OK:replay', flush=True) + bad = bundle(base, 'phios-ci-bad-dependency', current, accepted, missing_dependency=True) + result = installer.drive_installer(cancel=False, update=bad, reject=True) + if 'phios-ci-never-exists' not in result or 'OS update held:' not in result: + raise ValueError('missing dependency did not fail through actual pacman') + with disk() as (top, esp): + if state(top, esp) != current: + raise ValueError('failed staged dependency transaction changed active root or EFI') + print('PHIOS_SIGNED_REFUSAL_OK:dependency', flush=True) + interrupted = bundle(base, 'phios-ci-interrupt', current, accepted, interrupt=True) + manifest_hash = hashlib.sha256((interrupted / 'manifest.json').read_bytes()).hexdigest() + with disk(writable=True) as (top, _esp): + apply.recover.write_json(top / PLAN, {'schema_version': 'phios.disposable-update-qualification.v1', + 'stage': 'awaiting actual VM interruption', 'restore_generation': generation, + 'before_interruption': current, 'interrupted_manifest_sha256': manifest_hash}) + command('btrfs', 'filesystem', 'sync', str(top)) + os.sync() + print('PHIOS_SIGNED_UPDATE_OK:' + json.dumps({'generation': generation, 'sequence': 1, + 'signer': accepted[1], 'ephemeral_test_key': True}), flush=True) + # The host kills this VM only after the actual pacman post_install + # hook has written and synced its marker inside the staged root. + installer.drive_installer(cancel=False, update=interrupted, interrupt=True) + raise RuntimeError('host did not interrupt the actual staged package transaction') + finally: + for key in [accepted, wrong]: + subprocess.run(['gpgconf', '--homedir', str(key[0]), '--kill', 'all'], capture_output=True, timeout=15) + + +def resume_or_restore() -> None: + with disk() as (top, esp): + plan = json.loads(apply.recover.regular(top / PLAN)) + if plan.get('schema_version') != 'phios.disposable-update-qualification.v1': + raise ValueError('unsupported disposable fixture state') + generation = plan['restore_generation'] + if plan['stage'] == 'awaiting actual VM interruption': + if state(top, esp) != plan['before_interruption'] or (top / '@root/usr/share/phios-ci-interrupt/verified.txt').exists(): + raise ValueError('interrupted staging changed the active installed system') + journals = [path for path in (top / '@snapshots/recovery').glob('*/update-transaction.json') + if json.loads(path.read_text()).get('manifest_sha256') == plan['interrupted_manifest_sha256']] + if len(journals) != 1: + raise ValueError('interrupted transaction journal missing or ambiguous') + journal = json.loads(journals[0].read_text()) + marker = top / journal['staged_root'] / '.phios-ci-stage-in-progress' + if journal['activated'] is not False or not marker.is_file() or 'installing signed packages' not in journal['stage']: + raise ValueError('interruption was not during actual staged pacman execution') + source = plan['before_interruption']['source_commit'] + resumed = True + elif plan['stage'] == 'ready for deliberate boot failure and recovery': + resumed = False + else: + raise ValueError('unexpected disposable fixture stage') + if resumed: + with disk(writable=True) as (top, _esp): + plan['stage'] = 'ready for deliberate boot failure and recovery' + apply.recover.write_json(top / PLAN, plan) + command('btrfs', 'filesystem', 'sync', str(top)) + os.sync() + print('PHIOS_INTERRUPTED_UPDATE_HELD_OK', flush=True) + print('PHIOS_OS_CHECKPOINT_OK:' + generation, flush=True) + print('PHIOS_INSTALLED_DISK_OK:' + source, flush=True) + return + installer.drive_installer(cancel=True, recovery=['restore', '--generation', generation]) + print('PHIOS_OS_RESTORE_CANCEL_OK', flush=True) + installer.drive_installer(cancel=False, recovery=['restore', '--generation', generation]) + with disk() as (top, _esp): + source = (top / '@root/usr/share/phios/source-commit').read_text().strip() + if apply.sequence(top, source) != 2 or (top / '@root' / FILE).exists(): + raise ValueError('recovery did not remove the added package and advance the independent counter') + if (top / '@root/etc/phios/os-update-keyring.gpg').exists() or (top / '@root/etc/phios/os-update-trust.json').exists(): + raise ValueError('rolled-back signing trust remained active') + print('PHIOS_SIGNED_UPDATE_RECOVERY_OK', flush=True) + print('PHIOS_OS_RESTORE_OK:' + generation, flush=True) + + +if __name__ == '__main__': + raise RuntimeError('fixture is invoked only by the exact disposable installer fixture') diff --git a/packaging/linux/updates/apply.py b/packaging/linux/updates/apply.py new file mode 100644 index 00000000..057f4e2b --- /dev/null +++ b/packaging/linux/updates/apply.py @@ -0,0 +1,245 @@ +"""Apply a pinned signed offline transition to a staged experimental OS root.""" +from __future__ import annotations + +import argparse +import hashlib +import importlib.util +import json +import os +import shutil +import subprocess +import sys +import uuid +from datetime import UTC, datetime +from pathlib import Path +from typing import Any + + +def sibling(name: str) -> Any: + # Isolated Python does not import the script directory. Load only these + # fixed, packaged root-owned siblings, never a caller-provided module. + spec = importlib.util.spec_from_file_location('phios_os_' + name, Path(__file__).with_name(name + '.py')) + if spec is None or spec.loader is None: + raise ValueError('packaged OS maintenance module missing') + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +recover, verify = sibling('recover'), sibling('verify') + + +def packages(root: Path) -> list[dict[str, str]]: + for name in ['var', 'var/lib', 'var/lib/pacman', 'var/lib/pacman/local']: + recover.safe_directory(root / name) + text = recover.run('pacman', '--dbpath', str(root / 'var/lib/pacman'), '-Q') + rows = [dict(zip(['name', 'version'], line.split(), strict=True)) for line in text.splitlines()] + verify.inventory(rows) + return rows + + +def sequence(top: Path, source: str) -> int: + value = recover.generation_record(top / '@root/var/lib/phios/os-update-generation.json', 'phios.os-update-generation.v1') + anchor = recover.generation_record(top / '@snapshots/os-update-counter.json', 'phios.os-update-counter.v1') + if value is None and anchor is None: + return 0 + if (value is None or anchor is None or value['source_commit'] != source or anchor['source_commit'] != source or + value['sequence'] != anchor['sequence']): + raise ValueError('root and independent update counter differ; use explicit live recovery') + return value['sequence'] + + +def generated_file(root: Path, relative: str, data: bytes, *, mode: int = 0o600) -> None: + path = root / relative + path.parent.mkdir(parents=True, exist_ok=True, mode=0o700) + recover.safe_directory(path.parent) + if path.is_symlink(): + path.unlink() + fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | os.O_NOFOLLOW, mode) + with os.fdopen(fd, 'wb') as handle: + handle.write(data) + handle.flush() + os.fsync(handle.fileno()) + path.chmod(mode) + + +def supported_versions(payload: dict[str, Any], baseline: list[dict[str, str]]) -> None: + before = verify.inventory(baseline) + for row in payload['packages']: + if row['name'] in before and int(recover.run('vercmp', row['version'], before[row['name']]).strip()) < 0: + raise ValueError('package downgrades require explicit OS recovery, not update') + + +def execute(plan: dict[str, Any], payload: dict[str, Any], private: Path, + trust: tuple[dict[str, Any], bytes]) -> dict[str, Any]: + identity, generation = plan['disk'], plan['checkpoint_generation'] + # Recheck key enrollment and validity after terminal review; keep using the + # captured, signature-verified package bytes, never reread the supplied bundle. + if verify.load_trust() != trust: + raise ValueError('signing trust changed after review') + verify.validate_manifest(payload, source=plan['installed']['source_commit'], sequence=plan['base_sequence'], + installed=plan['base_packages'], now=datetime.now(UTC)) + for row in payload['packages']: + verify.verify_signature(private / 'gnupg', private / (row['filename'] + '.sig'), private / row['filename'], + trust[0]['primary_fingerprint'], now=datetime.now(UTC)) + supported_versions(payload, plan['base_packages']) + recover.execute(identity, 'checkpoint', generation, {'installed': plan['installed'], 'boot_files': plan['boot_files']}) + with recover.mounted(identity, writable=True) as (top, esp): + current = recover.installed(top, identity) + if (current != plan['installed'] or packages(top / '@root') != plan['base_packages'] or + sequence(top, current['source_commit']) != plan['base_sequence'] or + recover.boot_inventory(esp) != plan['boot_files']): + raise ValueError('installed source, inventory, generation or boot files changed after review') + recover.ensure_no_active_authority(top, current['install_receipt']['plan']['username']) + folder = top / '@snapshots/recovery' / generation + journal = {'schema_version': 'phios.os-package-update-transaction.v1', 'generation': generation, + 'manifest_sha256': plan['manifest_sha256'], 'source_commit': payload['source_commit'], + 'sequence': payload['sequence'], 'stage': 'preparing staged root', 'activated': False, + 'atomic': False, 'authority_restored': False, 'release_ready': False} + token = uuid.uuid4().hex + staged, previous = top / ('@update-' + token), top / ('@previous-' + token) + journal.update(staged_root=staged.name, previous_root=previous.name) + recover.write_json(folder / 'update-transaction.json', journal) + staged_mounted = False + try: + recover.run('btrfs', 'subvolume', 'snapshot', str(top / '@root'), str(staged)) + # arch-chroot/mkinitcpio need the staged root to be an actual + # mountpoint so root filesystem detection sees Btrfs correctly. + recover.run('mount', '--bind', str(staged), str(staged)) + staged_mounted = True + inputs = staged / '.phios-update-inputs' + inputs.mkdir(mode=0o700) + (inputs / 'cache').mkdir(mode=0o700) + (inputs / 'gnupg').mkdir(mode=0o700) + generated_file(inputs, 'public-keys.gpg', trust[1]) + generated_file(inputs, 'ownertrust.txt', (trust[0]['primary_fingerprint'] + ':6:\n').encode()) + generated_file(inputs, 'gnupg/gpg.conf', b'no-auto-key-retrieve\nauto-key-locate clear\n') + generated_file(inputs, 'pacman.conf', b'[options]\nArchitecture = x86_64\n' + b'SigLevel = Required DatabaseOptional\nLocalFileSigLevel = Required\n' + b'GPGDir = /.phios-update-inputs/gnupg\nCacheDir = /.phios-update-inputs/cache\n') + for row in payload['packages']: + for filename in [row['filename'], row['filename'] + '.sig']: + shutil.copyfile(private / filename, inputs / filename) + (inputs / filename).chmod(0o600) + with (inputs / row['filename']).open('rb') as handle: + if hashlib.file_digest(handle, 'sha256').hexdigest() != row['sha256']: + raise ValueError('captured package changed before staged installation') + recover.run('rsync', '-r', '--exclude=/' + recover.ENTROPY, str(esp) + '/', str(staged / 'boot') + '/') + try: + recover.run('arch-chroot', str(staged), 'gpg', '--no-options', '--homedir', '/.phios-update-inputs/gnupg', + '--batch', '--import', '/.phios-update-inputs/public-keys.gpg') + recover.run('arch-chroot', str(staged), 'gpg', '--no-options', '--homedir', '/.phios-update-inputs/gnupg', + '--batch', '--import-ownertrust', '/.phios-update-inputs/ownertrust.txt') + journal['stage'] = 'installing signed packages in staged root; active root unchanged' + recover.write_json(folder / 'update-transaction.json', journal) + recover.run('arch-chroot', str(staged), 'pacman', '--config', '/.phios-update-inputs/pacman.conf', + '-U', '--noconfirm', *['/.phios-update-inputs/' + row['filename'] for row in payload['packages']]) + finally: + # GnuPG agents retain their chroot. Reap only this private + # staging home's agents before unmounting the selected disk. + recover.run('arch-chroot', str(staged), 'gpgconf', '--homedir', '/.phios-update-inputs/gnupg', '--kill', 'all') + if verify.inventory(packages(staged)) != verify.inventory(payload['target_packages']): + raise ValueError('staged full inventory differs from the signed target') + if recover.regular(staged / 'usr/share/phios/source-commit').decode().strip() != payload['source_commit']: + raise ValueError('staged PhiOS source identity differs from the signed target') + kernels = list((staged / 'usr/lib/modules').glob('*/vmlinuz')) + if len(kernels) != 1: + raise ValueError('exactly one staged Linux kernel is required') + shutil.copyfile(kernels[0], staged / 'boot/vmlinuz-linux') + recover.run('arch-chroot', str(staged), 'mkinitcpio', '-P') + for relative in ['EFI/BOOT/BOOTX64.EFI', 'EFI/systemd/systemd-bootx64.efi']: + shutil.copyfile(staged / 'usr/lib/systemd/boot/efi/systemd-bootx64.efi', staged / 'boot' / relative) + generated_file(staged, 'etc/pacman.d/mirrorlist', + f'Server = https://archive.archlinux.org/repos/{payload["arch_snapshot"]}/$repo/os/$arch\n'.encode(), mode=0o644) + generated_file(staged, 'etc/phios/os-update-trust.json', json.dumps(trust[0], sort_keys=True).encode(), mode=0o644) + generated_file(staged, 'etc/phios/os-update-keyring.gpg', trust[1], mode=0o644) + recover.write_json(staged / 'var/lib/phios/os-update-generation.json', { + 'schema_version': 'phios.os-update-generation.v1', 'sequence': payload['sequence'], + 'source_commit': payload['source_commit']}) + journal['target_boot_files'] = recover.boot_inventory(staged / 'boot') + target_efi = folder / 'efi-target' + target_efi.mkdir(mode=0o700) + recover.run('rsync', '-r', str(staged / 'boot') + '/', str(target_efi) + '/') + shutil.rmtree(inputs) + for path in (staged / 'boot').iterdir(): + shutil.rmtree(path) if path.is_dir() else path.unlink() + recover.run('umount', str(staged)) + staged_mounted = False + journal['stage'] = 'switching root; live recovery may be required' + recover.write_json(folder / 'update-transaction.json', journal) + recover.write_json(top / '@snapshots/os-update-counter.json', { + 'schema_version': 'phios.os-update-counter.v1', 'sequence': payload['sequence'], + 'source_commit': payload['source_commit']}) + recover.run('btrfs', 'filesystem', 'sync', str(top)) + os.rename(top / '@root', previous) + recover.run('btrfs', 'filesystem', 'sync', str(top)) + os.rename(staged, top / '@root') + recover.run('btrfs', 'filesystem', 'sync', str(top)) + journal['stage'] = 'switching matched EFI; do not reboot' + recover.write_json(folder / 'update-transaction.json', journal) + recover.run('rsync', '-r', '--delete', '--exclude=/' + recover.ENTROPY, str(target_efi) + '/', str(esp) + '/') + (esp / recover.ENTROPY).unlink(missing_ok=True) + if recover.boot_inventory(esp) != journal['target_boot_files']: + raise ValueError('updated EFI files failed verification; use live recovery checkpoint') + os.sync() + journal.update(stage='activated; disk-only boot remains unqualified', activated=True) + recover.write_json(folder / 'update-transaction.json', journal) + recover.run('btrfs', 'filesystem', 'sync', str(top)) + os.sync() + return journal + except BaseException as exc: + journal['error'] = str(exc) + recover.write_json(folder / 'update-transaction.json', journal) + recover.run('btrfs', 'filesystem', 'sync', str(top)) + os.sync() + raise + finally: + if staged_mounted: + recover.run('umount', str(staged)) + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--disk', required=True) + parser.add_argument('--bundle', type=Path, required=True) + parser.add_argument('--plan', action='store_true', help='Read-only target probe and signed-byte verification') + args = parser.parse_args() + try: + if os.geteuid() != 0 or not Path('/run/archiso/bootmnt').is_dir() or not Path('/sys/firmware/efi').is_dir(): + raise ValueError('run the root-owned updater from PhiOS UEFI live media with the target offline') + identity, trust = recover.inventory(args.disk), verify.load_trust() + with recover.mounted(identity, writable=False) as (top, esp): + installed = recover.installed(top, identity) + recover.ensure_no_active_authority(top, installed['install_receipt']['plan']['username']) + baseline, counter = packages(top / '@root'), sequence(top, installed['source_commit']) + boot = recover.boot_inventory(esp) + with verify.verified_bundle(args.bundle, source=installed['source_commit'], sequence=counter, + installed=baseline, trust=trust) as (payload, private): + supported_versions(payload, baseline) + plan = {'schema_version': 'phios.os-update-plan.v1', 'operation': 'update', 'disk': identity, + 'installed': installed, 'base_sequence': counter, 'base_packages': baseline, 'boot_files': boot, + 'signed_transition': payload, 'signer': trust[0]['primary_fingerprint'], + 'manifest_sha256': hashlib.sha256((private / 'manifest.json').read_bytes()).hexdigest(), + 'checkpoint_generation': uuid.uuid4().hex, 'atomic': False, 'release_ready': False} + print(json.dumps(plan, indent=2, sort_keys=True), flush=True) + if args.plan: + return 0 + if not sys.stdin.isatty() or not sys.stdout.isatty(): + raise ValueError('interactive terminal review required; no unattended bypass') + print('A matched recovery checkpoint is created first. Root/EFI activation is not atomic.\n' + 'Keep live recovery media and a separate verified data backup.\n' + 'Type the exact signed transition confirmation, or Ctrl-C to cancel:\n' + recover.phrase(plan), flush=True) + if input('> ') != recover.phrase(plan): + raise ValueError('confirmation did not match; no target writes performed') + print(json.dumps(execute(plan, payload, private, trust), indent=2, sort_keys=True)) + return 0 + except (KeyboardInterrupt, EOFError): + print('OS update cancelled; preserve transaction evidence if writes had begun.') + return 130 + except (OSError, ValueError, RuntimeError, subprocess.SubprocessError) as exc: + print(f'OS update held: {exc}', file=sys.stderr) + return 1 + + +if __name__ == '__main__': + raise SystemExit(main()) diff --git a/packaging/linux/updates/enroll.py b/packaging/linux/updates/enroll.py new file mode 100644 index 00000000..b554d261 --- /dev/null +++ b/packaging/linux/updates/enroll.py @@ -0,0 +1,154 @@ +"""Explicitly enroll one independently authenticated public OS-update key.""" +from __future__ import annotations + +import argparse +import hashlib +import importlib.util +import json +import os +import re +import stat +import subprocess +import sys +import tempfile +import uuid +from datetime import UTC, datetime +from pathlib import Path +from typing import Any + +spec = importlib.util.spec_from_file_location('phios_enroll_verifier', Path(__file__).with_name('verify.py')) +assert spec is not None and spec.loader is not None +verify = importlib.util.module_from_spec(spec) +spec.loader.exec_module(verify) + + +def gpg(home: Path, *args: str) -> bytes: + result = subprocess.run(['/usr/bin/gpg', '--no-options', '--homedir', str(home), '--batch', + '--no-auto-key-retrieve', '--auto-key-locate', 'clear', *args], env=verify.ENV, capture_output=True, timeout=60) + if result.returncode: + raise ValueError('public key parsing/import/export failed; no trust enrolled') + return result.stdout + + +def public_key(home: Path, captured: Path, fingerprint: str, *, now: datetime) -> bytes: + if re.fullmatch(r'(?:[0-9A-F]{40}|[0-9A-F]{64})', fingerprint) is None: + raise ValueError('independently authenticated full uppercase fingerprint required') + rows = [line.split(':') for line in gpg(home, '--with-colons', '--import-options', 'show-only', + '--dry-run', '--import', str(captured)).decode().splitlines()] + if any(row[0].startswith(('sec', 'ssb')) for row in rows): + raise ValueError('secret key material refused; provide only an exported public key') + if len([row for row in rows if row[0] == 'pub']) != 1: + raise ValueError('exactly one public primary key required') + found = next((row[9] for row in rows if row[0] == 'fpr'), '') + if found != fingerprint: + raise ValueError('public key differs from independently authenticated fingerprint') + gpg(home, '--import', str(captured)) + rows = [line.split(':') for line in gpg(home, '--with-colons', '--list-keys', fingerprint).decode().splitlines()] + primary = [row for row in rows if row[0] == 'pub'] + if (len(primary) != 1 or primary[0][1] in ('r', 'e', 'd') or + int(primary[0][5]) > int(now.timestamp()) + 300 or + (primary[0][6] not in ('', '0') and int(primary[0][6]) <= int(now.timestamp()))): + raise ValueError('expired, revoked, disabled or future primary key refused') + if any(line.split(':')[0].startswith(('sec', 'ssb')) for line in + gpg(home, '--with-colons', '--list-secret-keys').decode().splitlines()): + raise ValueError('secret keys must never enter enrollment') + exported = gpg(home, '--export', fingerprint) + if not 0 < len(exported) <= 8 * 1024**2: + raise ValueError('bounded public key export required') + return exported + + +def existing() -> dict[str, str | None]: + result: dict[str, str | None] = {} + for path in [verify.TRUST, verify.KEYRING]: + result[path.name] = (hashlib.sha256(verify.protected_file(path, maximum=8 * 1024**2)).hexdigest() + if path.exists() or path.is_symlink() else None) + return result + + +def phrase(plan: dict[str, Any]) -> str: + return 'ENROLL /etc/phios ' + hashlib.sha256(json.dumps(plan, sort_keys=True, separators=(',', ':')).encode()).hexdigest() + + +def write(path: Path, data: bytes) -> None: + temporary = path.with_name(path.name + '.' + uuid.uuid4().hex + '.tmp') + fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600) + with os.fdopen(fd, 'wb') as handle: + handle.write(data) + os.fchmod(handle.fileno(), 0o644) + handle.flush() + os.fsync(handle.fileno()) + os.replace(temporary, path) + fd = os.open(path.parent, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW) + try: + os.fsync(fd) + finally: + os.close(fd) + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--public-key', required=True, type=Path) + parser.add_argument('--fingerprint', required=True) + parser.add_argument('--plan', action='store_true') + args = parser.parse_args() + try: + if os.geteuid() != 0: + raise ValueError('root-owned enrollment command requires sudo') + source = verify.protected_file(verify.SOURCE).decode().strip() + if re.fullmatch(r'[0-9a-f]{40}', source) is None: + raise ValueError('packaged PhiOS source identity required') + with tempfile.TemporaryDirectory(prefix='phios-key-enrollment-') as temporary: + private = Path(temporary) + home = private / 'gnupg' + home.mkdir(mode=0o700) + try: + directory = os.open(args.public_key.parent, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW) + try: + verify.capture(directory, args.public_key.name, private / 'public-key', maximum=8 * 1024**2) + finally: + os.close(directory) + exported = public_key(home, private / 'public-key', args.fingerprint, now=datetime.now(UTC)) + before = existing() + policy = {'schema_version': 'phios.os-update-trust.v1', 'channel': 'experimental', + 'primary_fingerprint': args.fingerprint} + plan = {'schema_version': 'phios.os-update-enrollment.v1', 'source_commit': source, + 'public_key_sha256': hashlib.sha256(exported).hexdigest(), 'policy': policy, + 'current_trust_hashes': before, 'release_ready': False} + print(json.dumps(plan, indent=2, sort_keys=True), flush=True) + if args.plan: + return 0 + if not sys.stdin.isatty() or not sys.stdout.isatty(): + raise ValueError('interactive terminal review required; no unattended enrollment') + print('Authenticate this full fingerprint through an independently trusted maintainer channel.\n' + 'This explicit local administration changes update signing trust; a key file does not authenticate itself.\n' + 'Type the exact reviewed phrase, or Ctrl-C to cancel:\n' + phrase(plan), flush=True) + if input('> ') != phrase(plan): + raise ValueError('confirmation did not match; no signing trust changed') + if existing() != before or public_key(home, private / 'public-key', args.fingerprint, now=datetime.now(UTC)) != exported: + raise ValueError('public key validity or current trust changed after review') + verify.TRUST.parent.mkdir(mode=0o755, exist_ok=True) + for parent in reversed(verify.TRUST.parents): + info = parent.lstat() + if not stat.S_ISDIR(info.st_mode) or info.st_uid != 0 or info.st_mode & 0o022: + raise ValueError('unsafe signing trust directory') + write(verify.KEYRING, exported) + write(verify.TRUST, (json.dumps(policy, sort_keys=True) + '\n').encode()) + if verify.load_trust() != (policy, exported): + raise ValueError('enrolled trust readback failed; preserve evidence and re-enroll') + print(json.dumps({'trust_enrolled': True, 'primary_fingerprint': args.fingerprint, + 'release_ready': False}, sort_keys=True)) + finally: + subprocess.run(['/usr/bin/gpgconf', '--homedir', str(home), '--kill', 'all'], + env=verify.ENV, capture_output=True, timeout=15) + return 0 + except (KeyboardInterrupt, EOFError): + print('Enrollment cancelled; inspect current trust if writes had begun.') + return 130 + except (OSError, ValueError, RuntimeError, subprocess.SubprocessError) as exc: + print('Key enrollment held: ' + str(exc), file=sys.stderr) + return 1 + + +if __name__ == '__main__': + raise SystemExit(main()) diff --git a/packaging/linux/updates/phios-os-recover b/packaging/linux/updates/phios-os-recover new file mode 100755 index 00000000..da55d628 --- /dev/null +++ b/packaging/linux/updates/phios-os-recover @@ -0,0 +1,3 @@ +#!/usr/bin/bash +set -euo pipefail +exec /usr/bin/python -I /usr/lib/phios-updates/recover.py "$@" diff --git a/packaging/linux/updates/phios-os-update b/packaging/linux/updates/phios-os-update new file mode 100755 index 00000000..c0056a5e --- /dev/null +++ b/packaging/linux/updates/phios-os-update @@ -0,0 +1,3 @@ +#!/usr/bin/bash +set -euo pipefail +exec /usr/bin/python -I /usr/lib/phios-updates/apply.py "$@" diff --git a/packaging/linux/updates/phios-update-enroll b/packaging/linux/updates/phios-update-enroll new file mode 100755 index 00000000..df0819bb --- /dev/null +++ b/packaging/linux/updates/phios-update-enroll @@ -0,0 +1,3 @@ +#!/usr/bin/bash +set -euo pipefail +exec /usr/bin/python -I /usr/lib/phios-updates/enroll.py "$@" diff --git a/packaging/linux/updates/phios-update-verify b/packaging/linux/updates/phios-update-verify new file mode 100755 index 00000000..8624d73e --- /dev/null +++ b/packaging/linux/updates/phios-update-verify @@ -0,0 +1,3 @@ +#!/usr/bin/bash +set -euo pipefail +exec /usr/bin/python -I /usr/lib/phios-updates/verify.py "$@" diff --git a/packaging/linux/updates/recover.py b/packaging/linux/updates/recover.py new file mode 100644 index 00000000..77f8b4b1 --- /dev/null +++ b/packaging/linux/updates/recover.py @@ -0,0 +1,489 @@ +"""Offline matched Btrfs/EFI checkpoints for the experimental PhiOS installer.""" +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import re +import shutil +import stat +import subprocess +import sys +import tempfile +import uuid +from contextlib import contextmanager +from pathlib import Path +from typing import Any, Iterator + +ENV = {'PATH': '/usr/bin', 'LANG': 'C.UTF-8', 'HOME': '/root'} +FORMAT = 'phios.os-checkpoint.v1' +SCHEMA = {'memory': 1, 'data_backup': 'phios.data-backup.v1'} +GEN = r'[0-9a-f]{32}' +ENTROPY = 'loader/random-seed' + + +def run(*args: str) -> str: + command = shutil.which(args[0], path=ENV['PATH']) + if command is None: + raise ValueError(f'required program unavailable: {args[0]}') + result = subprocess.run([command, *args[1:]], env=ENV, capture_output=True, text=True, timeout=600) + if result.returncode or '==> ERROR:' in result.stdout or '==> ERROR:' in result.stderr: + raise RuntimeError(f'{args[0]} failed (exit {result.returncode}): {(result.stdout + result.stderr)[-6000:]}') + return result.stdout + + +def regular(path: Path, *, owner: int = 0, maximum: int = 2 * 1024**2) -> bytes: + info = path.lstat() + if (not stat.S_ISREG(info.st_mode) or info.st_uid != owner or info.st_mode & 0o022 or + info.st_nlink != 1 or info.st_size > maximum): + raise ValueError('unsafe checkpoint/installed metadata file') + fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW) + with os.fdopen(fd, 'rb') as handle: + actual = os.fstat(handle.fileno()) + if (actual.st_dev, actual.st_ino, actual.st_size, actual.st_mtime_ns, actual.st_ctime_ns) != ( + info.st_dev, info.st_ino, info.st_size, info.st_mtime_ns, info.st_ctime_ns): + raise ValueError('metadata changed during intake') + data = handle.read(maximum + 1) + if len(data) > maximum: + raise ValueError('metadata exceeds its bound') + return data + + +def safe_directory(path: Path, *, owner: int = 0) -> None: + info = path.lstat() + if not stat.S_ISDIR(info.st_mode) or info.st_uid != owner or info.st_mode & 0o022: + raise ValueError('unsafe checkpoint/installed directory') + + +def write_json(path: Path, data: dict[str, Any]) -> None: + safe_directory(path.parent) + temporary = path.with_name(path.name + '.' + uuid.uuid4().hex + '.tmp') + fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600) + with os.fdopen(fd, 'w') as handle: + json.dump(data, handle, indent=2, sort_keys=True, allow_nan=False) + handle.write('\n') + handle.flush() + os.fsync(handle.fileno()) + os.replace(temporary, path) + directory = os.open(path.parent, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW) + try: + os.fsync(directory) + finally: + os.close(directory) + + +def validate_disk(row: dict[str, Any], *, busy: bool) -> dict[str, Any]: + path = row.get('path') + if (not isinstance(path, str) or re.fullmatch(r'/dev/(sd[a-z]+|vd[a-z]+|nvme[0-9]+n[0-9]+|mmcblk[0-9]+)', path) is None or + row.get('type') != 'disk' or row.get('ro') not in (False, 0) or row.get('pttype') != 'gpt' or + type(row.get('size')) is not int or row['size'] < 16 * 1024**3 or busy): + raise ValueError('an idle, canonical whole PhiOS installation disk is required') + serial = row.get('serial') or row.get('wwn') + if not isinstance(serial, str) or not serial.strip() or any(ord(c) < 32 or ord(c) == 127 for c in serial): + raise ValueError('stable disk identity is required') + children = row.get('children') + suffix = 'p' if path[-1].isdigit() else '' + if not isinstance(children, list) or len(children) != 2: + raise ValueError('only the installer two-partition layout is supported') + children = sorted(children, key=lambda item: item.get('path', '')) + for index, (child, filesystem) in enumerate(zip(children, ['vfat', 'btrfs'], strict=True), start=1): + if (child.get('path') != f'{path}{suffix}{index}' or child.get('type') != 'part' or + child.get('fstype') != filesystem or child.get('children') or + any(child.get('mountpoints') or []) or child.get('ro') not in (False, 0)): + raise ValueError('partition identity, filesystem or mounted state is unsupported') + if any(row.get('mountpoints') or []) or children[0].get('size') != 1024**3: + raise ValueError('mounted target or unexpected ESP size') + root_uuid, esp_uuid = children[1].get('uuid'), children[0].get('uuid') + if (not isinstance(root_uuid, str) or re.fullmatch(r'[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}', root_uuid) is None or + not isinstance(esp_uuid, str) or re.fullmatch(r'[0-9A-F]{4}-[0-9A-F]{4}', esp_uuid) is None): + raise ValueError('invalid installed filesystem UUID') + return {'path': path, 'serial_or_wwn': serial.strip(), 'size_bytes': row['size'], + 'major_minor': row.get('maj:min'), 'root_uuid': root_uuid, 'esp_uuid': esp_uuid, + 'esp': children[0]['path'], 'system': children[1]['path']} + + +def block_dependencies(sys_device: Path, *, partition: bool) -> bool: + # Kernel partition kobjects have holders and a partition marker, but no + # slaves directory. Only the parent whole-disk kobject has slaves. + if (sys_device / 'partition').is_file() != partition: + raise ValueError('sysfs block type differs from the selected disk layout') + holders = list((sys_device / 'holders').iterdir()) + slaves = [] if partition else list((sys_device / 'slaves').iterdir()) + return bool(holders or slaves) + + +def inventory(device: str) -> dict[str, Any]: + path = Path(device) + if not path.is_absolute() or path.resolve() != path or not stat.S_ISBLK(path.stat().st_mode): + raise ValueError('canonical real whole disk required') + run('udevadm', 'settle') + rows = json.loads(run('lsblk', '--json', '--bytes', '--paths', '--tree', '--output', + 'PATH,TYPE,SIZE,RO,SERIAL,WWN,MOUNTPOINTS,FSTYPE,PTTYPE,UUID,MAJ:MIN', device))['blockdevices'] + if len(rows) != 1: + raise ValueError('ambiguous target') + nodes = [rows[0], *rows[0].get('children', [])] + mounted = {line.split()[2] for line in Path('/proc/self/mountinfo').read_text().splitlines()} + swap_devices = {Path(line.split()[0]).stat().st_rdev for line in Path('/proc/swaps').read_text().splitlines()[1:]} + busy = False + for node in nodes: + info = Path(node['path']).stat() + number = f'{os.major(info.st_rdev)}:{os.minor(info.st_rdev)}' + sys_device = Path('/sys/dev/block') / number + partition = node.get('type') == 'part' + if partition and sys_device.resolve().parent != (Path('/sys/dev/block') / rows[0]['maj:min']).resolve(): + raise ValueError('sysfs partition parent differs from the selected whole disk') + if (number != node.get('maj:min') or number in mounted or info.st_rdev in swap_devices or + block_dependencies(sys_device, partition=partition)): + busy = True + return validate_disk(rows[0], busy=busy) + + +@contextmanager +def mounted(identity: dict[str, Any], *, writable: bool) -> Iterator[tuple[Path, Path]]: + if inventory(identity['path']) != identity: + raise ValueError('disk changed after review; no target writes performed') + workspace = Path(tempfile.mkdtemp(prefix='phios-recovery-', dir='/run')) + top, esp = workspace / 'top', workspace / 'efi' + top.mkdir(mode=0o700) + esp.mkdir(mode=0o700) + mounts: list[Path] = [] + try: + options = 'rw,subvolid=5' if writable else 'ro,rescue=nologreplay,subvolid=5' + run('mount', '-t', 'btrfs', '-o', options, identity['system'], str(top)) + mounts.append(top) + # Multi-device Btrfs would cross the selected-disk boundary. + if len(list((Path('/sys/fs/btrfs') / identity['root_uuid'] / 'devices').iterdir())) != 1: + raise ValueError('multi-device Btrfs is unsupported') + run('mount', '-t', 'vfat', '-o', ('rw' if writable else 'ro') + ',umask=0077', identity['esp'], str(esp)) + mounts.append(esp) + yield top, esp + finally: + failures = [] + for path in reversed(mounts): + try: + run('umount', str(path)) + except (OSError, ValueError, RuntimeError) as exc: + failures.append(str(exc)) + if failures: + raise RuntimeError('recovery mounts remain active; preserve evidence and do not reboot: ' + '; '.join(failures)) + shutil.rmtree(workspace) + + +def boot_inventory(esp: Path, *, owner: int = 0) -> dict[str, dict[str, Any]]: + result: dict[str, dict[str, Any]] = {} + total = 0 + safe_directory(esp, owner=owner) + for current, dirs, files in os.walk(esp, followlinks=False): + directory = Path(current) + for name in dirs: + safe_directory(directory / name, owner=owner) + for name in files: + path = directory / name + relative = path.relative_to(esp).as_posix() + if relative == ENTROPY: + continue + info = path.lstat() + if not stat.S_ISREG(info.st_mode) or info.st_uid != owner or info.st_nlink != 1: + raise ValueError('EFI contents contain nonregular files or links') + total += info.st_size + if len(result) >= 512 or total > 1024**3: + raise ValueError('EFI file inventory exceeds its bound') + digest = hashlib.sha256() + fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW) + with os.fdopen(fd, 'rb') as handle: + for chunk in iter(lambda: handle.read(1024**2), b''): + digest.update(chunk) + result[relative] = {'size': info.st_size, 'sha256': digest.hexdigest()} + if not {'vmlinuz-linux', 'initramfs-linux.img', 'initramfs-linux-fallback.img', + 'EFI/BOOT/BOOTX64.EFI', 'loader/entries/phios.conf'} <= result.keys(): + raise ValueError('matching installed kernel, initramfs and fallback EFI loader required') + return result + + +def installed(top: Path, identity: dict[str, Any]) -> dict[str, Any]: + for name in ['@root', '@home', '@log', '@snapshots']: + safe_directory(top / name) + run('btrfs', 'subvolume', 'show', str(top / name)) + root = top / '@root' + for relative in ['var', 'var/lib', 'var/lib/phios', 'usr', 'usr/share', 'usr/share/phios']: + safe_directory(root / relative) + receipt = json.loads(regular(root / 'var/lib/phios/install-receipt.json')) + target = receipt.get('plan', {}).get('target', {}) + source = regular(root / 'usr/share/phios/source-commit').decode().strip() + if (receipt.get('schema_version') != 'phios.blank-disk-install.v1' or receipt.get('installed') is not True or + receipt.get('root_uuid') != identity['root_uuid'] or receipt.get('esp_uuid') != identity['esp_uuid'] or + target.get('serial_or_wwn') != identity['serial_or_wwn'] or target.get('size_bytes') != identity['size_bytes'] or + re.fullmatch(r'[0-9a-f]{40}', source) is None): + raise ValueError('selected disk does not match a supported PhiOS installation receipt') + return {'source_commit': source, 'install_receipt': receipt} + + +def validate_checkpoint(data: Any, identity: dict[str, Any], generation: str) -> dict[str, Any]: + keys = {'schema_version', 'generation', 'disk', 'source_commit', 'state_schemas', 'root_snapshot_uuid', + 'boot_files', 'installed', 'home_snapshot_restored', 'authority_restored', 'release_ready'} + if (not isinstance(data, dict) or set(data) != keys or data['schema_version'] != FORMAT or + data['generation'] != generation or re.fullmatch(GEN, generation) is None or + data['disk'] != {key: identity[key] for key in ['serial_or_wwn', 'size_bytes', 'root_uuid', 'esp_uuid']} or + data['state_schemas'] != SCHEMA or type(data['state_schemas'].get('memory')) is not int or + not isinstance(data['source_commit'], str) or re.fullmatch(r'[0-9a-f]{40}', data['source_commit']) is None or + any(data[key] is not False for key in ['home_snapshot_restored', 'authority_restored', 'release_ready'])): + raise ValueError('unsupported or wrong-disk checkpoint') + installed_info, boot = data['installed'], data['boot_files'] + if (not isinstance(data['root_snapshot_uuid'], str) or + re.fullmatch(r'[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}', data['root_snapshot_uuid']) is None or + not isinstance(installed_info, dict) or set(installed_info) != {'source_commit', 'install_receipt'} or + installed_info['source_commit'] != data['source_commit'] or not isinstance(installed_info['install_receipt'], dict) or + installed_info['install_receipt'].get('schema_version') != 'phios.blank-disk-install.v1' or + installed_info['install_receipt'].get('installed') is not True or + installed_info['install_receipt'].get('root_uuid') != identity['root_uuid'] or + installed_info['install_receipt'].get('esp_uuid') != identity['esp_uuid'] or + not isinstance(installed_info['install_receipt'].get('plan'), dict) or + not isinstance(installed_info['install_receipt']['plan'].get('username'), str) or + re.fullmatch(r'[a-z][a-z0-9_-]{0,30}', installed_info['install_receipt']['plan']['username']) is None or + not isinstance(boot, dict) or not 5 <= len(boot) <= 512): + raise ValueError('invalid checkpoint root, installed identity or boot inventory') + total = 0 + for name, file in boot.items(): + if (not isinstance(name, str) or Path(name).is_absolute() or '..' in Path(name).parts or + not isinstance(file, dict) or set(file) != {'size', 'sha256'} or type(file['size']) is not int or + file['size'] < 0 or not isinstance(file['sha256'], str) or re.fullmatch(r'[0-9a-f]{64}', file['sha256']) is None): + raise ValueError('invalid checkpoint boot-file hash or path') + total += file['size'] + if total > 1024**3: + raise ValueError('checkpoint boot inventory exceeds its bound') + return data + + +def snapshot_uuid(path: Path) -> str: + text = run('btrfs', 'subvolume', 'show', str(path)) + matches = re.findall(r'^\s*UUID:\s*([0-9a-f-]{36})\s*$', text, flags=re.M) + if len(matches) != 1: + raise ValueError('ambiguous Btrfs snapshot identity') + return matches[0] + + +def checkpoint_data(top: Path, esp: Path, identity: dict[str, Any], generation: str) -> tuple[dict[str, Any], Path]: + folder = top / '@snapshots/recovery' / generation + for path in [top / '@snapshots', folder.parent, folder, folder / 'root', folder / 'efi']: + safe_directory(path) + data = validate_checkpoint(json.loads(regular(folder / 'checkpoint.json')), identity, generation) + if (run('btrfs', 'property', 'get', '-t', 's', str(folder / 'root'), 'ro').strip() != 'ro=true' or + snapshot_uuid(folder / 'root') != data['root_snapshot_uuid'] or + boot_inventory(folder / 'efi') != data['boot_files'] or + regular(folder / 'root/usr/share/phios/source-commit').decode().strip() != data['source_commit']): + raise ValueError('checkpoint root or matching boot files failed integrity checks') + return data, folder + + +def ensure_no_active_authority(top: Path, username: str, *, uid: int = 1000) -> None: + """Preserve current home data; refuse rollback over active/unknown authority.""" + if re.fullmatch(r'[a-z][a-z0-9_-]{0,30}', username) is None: + raise ValueError('invalid installed account') + home = top / '@home' / username + safe_directory(home, owner=uid) + # Custom state roots need a separately reviewed maintenance procedure. + for relative in ['.local/state/phios', '.phios']: + state = home / relative + if not state.exists(): + continue + for parent in [*reversed(state.parents), state]: + if parent == home or parent.is_relative_to(home): + safe_directory(parent, owner=uid) + database = state / 'memory/canonical.sqlite3' + published: list[dict[str, Any]] = [] + if database.exists(): + safe_directory(database.parent, owner=uid) + info = database.lstat() + if (not stat.S_ISREG(info.st_mode) or info.st_uid != uid or info.st_mode & 0o022 or + info.st_nlink != 1 or any(database.with_name(database.name + suffix).exists() + for suffix in ['-wal', '-journal'])): + raise ValueError('canonical state requires explicit data recovery before OS rollback') + # The trusted live runtime validates schema, structural integrity, + # record hashes and zero-authority outbox receipts without mutation. + from phios.state_recovery import _database + published = [row for row, is_published in _database(database) if is_published] + spine = state / 'spine-v0.1' + if not spine.exists(): + if published: + raise ValueError('published memory has no matching active receipt ledger') + continue + safe_directory(spine, owner=uid) + actual_receipts: list[dict[str, Any]] = [] + for path in spine.rglob('*'): + if path.is_dir() and not path.is_symlink(): + safe_directory(path, owner=uid) + continue + if path.relative_to(spine).as_posix() != 'ledger/mandala-receipts.jsonl': + raise ValueError('active spine/authority history requires data-only recovery and explicit revalidation first') + # This allowlist never restores an old decision/binding/lease. The + # memory ledger remains in current @home and must be zero-authority. + rows = regular(path, owner=uid, maximum=128 * 1024**2).splitlines() + for row in rows: + value = json.loads(row) + if (not isinstance(value, dict) or not isinstance(value.get('operation_id'), str) or + value.get('action_authority') is not False or value.get('execution_authority') is not False): + raise ValueError('memory history contains authority; recovery held') + actual_receipts.append(value) + if sorted(actual_receipts, key=lambda row: row['operation_id']) != sorted(published, key=lambda row: row['operation_id']): + raise ValueError('memory receipt history does not match current canonical state') + config = home / '.config/phios/memory.json' + if config.exists(): + if json.loads(regular(config, owner=uid)).get('enabled') is not False: + raise ValueError('disable memory configuration and review state before OS rollback') + + +def phrase(plan: dict[str, Any]) -> str: + digest = hashlib.sha256(json.dumps(plan, sort_keys=True, separators=(',', ':'), allow_nan=False).encode()).hexdigest() + return f"{plan['operation'].upper()} {plan['disk']['path']} {digest}" + + +def generation_record(path: Path, schema: str) -> dict[str, Any] | None: + if not path.exists() and not path.is_symlink(): + return None + value = json.loads(regular(path)) + if (not isinstance(value, dict) or set(value) != {'schema_version', 'sequence', 'source_commit'} or + value['schema_version'] != schema or type(value['sequence']) is not int or value['sequence'] < 0 or + not isinstance(value['source_commit'], str) or re.fullmatch(r'[0-9a-f]{40}', value['source_commit']) is None): + raise ValueError('update generation requires explicit recovery review') + return value + + +def recovery_sequence(top: Path, saved_root: Path) -> int: + # This counter lives outside root snapshots. Even if activation stopped + # between root renames, an older root cannot reset the consumed sequence. + values = [generation_record(top / '@snapshots/os-update-counter.json', 'phios.os-update-counter.v1')] + for root in [top / '@root', saved_root]: + values.append(generation_record(root / 'var/lib/phios/os-update-generation.json', 'phios.os-update-generation.v1')) + return max((value['sequence'] for value in values if value is not None), default=0) + 1 + + +def execute(identity: dict[str, Any], operation: str, generation: str, reviewed: dict[str, Any]) -> dict[str, Any]: + with mounted(identity, writable=True) as (top, esp): + # Recheck reviewed source/checkpoint/boot identity before creating a + # checkpoint or activating restored root/EFI contents. + if operation == 'checkpoint': + current = installed(top, identity) + if current != reviewed['installed'] or boot_inventory(esp) != reviewed['boot_files']: + raise ValueError('installed source or boot files changed after review') + ensure_no_active_authority(top, current['install_receipt']['plan']['username']) + base = top / '@snapshots/recovery' + if not base.exists(): + base.mkdir(mode=0o700) + safe_directory(base) + folder = base / generation + folder.mkdir(mode=0o700) + run('btrfs', 'subvolume', 'snapshot', '-r', str(top / '@root'), str(folder / 'root')) + run('btrfs', 'subvolume', 'snapshot', '-r', str(top / '@home'), str(folder / 'home-forensic-only')) + (folder / 'efi').mkdir(mode=0o700) + run('rsync', '-r', '--exclude=/' + ENTROPY, str(esp) + '/', str(folder / 'efi') + '/') + if boot_inventory(folder / 'efi') != reviewed['boot_files']: + raise ValueError('checkpoint EFI copy differs from reviewed boot files') + data = {'schema_version': FORMAT, 'generation': generation, + 'disk': {key: identity[key] for key in ['serial_or_wwn', 'size_bytes', 'root_uuid', 'esp_uuid']}, + 'source_commit': current['source_commit'], 'state_schemas': SCHEMA, + 'root_snapshot_uuid': snapshot_uuid(folder / 'root'), 'boot_files': reviewed['boot_files'], + 'installed': current, 'home_snapshot_restored': False, 'authority_restored': False, 'release_ready': False} + write_json(folder / 'checkpoint.json', data) + run('btrfs', 'filesystem', 'sync', str(top)) + os.sync() + return data + data, folder = checkpoint_data(top, esp, identity, generation) + if data != reviewed['checkpoint']: + raise ValueError('checkpoint changed after review') + next_sequence = recovery_sequence(top, folder / 'root') + if next_sequence != reviewed['next_sequence']: + raise ValueError('update counter changed after review') + ensure_no_active_authority(top, data['installed']['install_receipt']['plan']['username']) + transaction = folder / ('restore-' + uuid.uuid4().hex) + transaction.mkdir(mode=0o700) + (transaction / 'efi-before').mkdir(mode=0o700) + run('rsync', '-r', '--exclude=/' + ENTROPY, str(esp) + '/', str(transaction / 'efi-before') + '/') + token = uuid.uuid4().hex + staged, failed = top / ('@recovered-' + token), top / ('@failed-' + token) + journal = {'schema_version': 'phios.os-restore-transaction.v1', 'generation': generation, + 'failed_root': failed.name, 'staged_root': staged.name, 'stage': 'preparing', + 'home_restored': False, 'authority_restored': False, 'release_ready': False} + write_json(transaction / 'transaction.json', journal) + run('btrfs', 'subvolume', 'snapshot', str(folder / 'root'), str(staged)) + seed = staged / 'var/lib/systemd/random-seed' + seed.unlink(missing_ok=True) + # An older root must never silently reinstate an earlier trust policy. + for name in ['os-update-trust.json', 'os-update-keyring.gpg']: + (staged / 'etc/phios' / name).unlink(missing_ok=True) + write_json(staged / 'var/lib/phios/os-update-generation.json', { + 'schema_version': 'phios.os-update-generation.v1', + 'sequence': next_sequence, 'source_commit': data['source_commit']}) + write_json(top / '@snapshots/os-update-counter.json', { + 'schema_version': 'phios.os-update-counter.v1', + 'sequence': next_sequence, 'source_commit': data['source_commit']}) + run('btrfs', 'filesystem', 'sync', str(top)) + journal['stage'] = 'switching root; keep live recovery media' + write_json(transaction / 'transaction.json', journal) + if (top / '@root').exists(): + os.rename(top / '@root', failed) + run('btrfs', 'filesystem', 'sync', str(top)) + os.rename(staged, top / '@root') + run('btrfs', 'filesystem', 'sync', str(top)) + journal['stage'] = 'restoring matching EFI; do not reboot' + write_json(transaction / 'transaction.json', journal) + run('rsync', '-r', '--delete', '--exclude=/' + ENTROPY, str(folder / 'efi') + '/', str(esp) + '/') + (esp / ENTROPY).unlink(missing_ok=True) + if boot_inventory(esp) != data['boot_files']: + raise ValueError('restored EFI verification failed; preserve transaction and use live recovery') + os.sync() + journal['stage'] = 'restored; disk-only boot remains unqualified' + write_json(transaction / 'transaction.json', journal) + run('btrfs', 'filesystem', 'sync', str(top)) + os.sync() + return journal + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('operation', choices=['checkpoint', 'restore']) + parser.add_argument('--disk', required=True) + parser.add_argument('--generation', help='Exact checkpoint ID required for restore') + parser.add_argument('--plan', action='store_true', help='Read-only probe; never changes the target') + args = parser.parse_args() + try: + if os.geteuid() != 0 or not Path('/run/archiso/bootmnt').is_dir() or not Path('/sys/firmware/efi').is_dir(): + raise ValueError('run this root-owned tool from a PhiOS UEFI live image with the target offline') + generation = args.generation if args.operation == 'restore' else uuid.uuid4().hex + if generation is None or re.fullmatch(GEN, generation) is None: + raise ValueError('exact checkpoint generation required') + identity = inventory(args.disk) + with mounted(identity, writable=False) as (top, esp): + plan = {'schema_version': 'phios.os-maintenance-plan.v1', 'operation': args.operation, + 'disk': identity, 'generation': generation, 'home_restored': False, + 'authority_restored': False, 'atomic': False, 'release_ready': False} + if args.operation == 'checkpoint': + plan.update(installed=installed(top, identity), boot_files=boot_inventory(esp)) + ensure_no_active_authority(top, plan['installed']['install_receipt']['plan']['username']) + else: + data, folder = checkpoint_data(top, esp, identity, generation) + ensure_no_active_authority(top, data['installed']['install_receipt']['plan']['username']) + plan['checkpoint'] = data + plan['next_sequence'] = recovery_sequence(top, folder / 'root') + print(json.dumps(plan, indent=2, sort_keys=True), flush=True) + if args.plan: + return 0 + if not sys.stdin.isatty() or not sys.stdout.isatty(): + raise ValueError('interactive terminal review required; no unattended bypass') + print('Same-disk recovery is not a backup. Preserve a verified data backup on separate storage.\n' + 'Root/EFI activation is not atomic. Keep live recovery media available.\n' + 'Type the exact reviewed confirmation, or Ctrl-C to cancel:\n' + phrase(plan), flush=True) + if input('> ') != phrase(plan): + raise ValueError('confirmation did not match; no target writes performed') + print(json.dumps(execute(identity, args.operation, generation, plan), indent=2, sort_keys=True)) + return 0 + except (KeyboardInterrupt, EOFError): + print('Maintenance cancelled; preserve transaction evidence if writes had begun.') + return 130 + except (OSError, ValueError, RuntimeError, subprocess.SubprocessError) as exc: + print(f'OS maintenance held: {exc}', file=sys.stderr) + return 1 + + +if __name__ == '__main__': + raise SystemExit(main()) diff --git a/packaging/linux/updates/verify.py b/packaging/linux/updates/verify.py new file mode 100644 index 00000000..022cb5c7 --- /dev/null +++ b/packaging/linux/updates/verify.py @@ -0,0 +1,255 @@ +"""Verify a complete offline OS package transition; never install or mint authority.""" +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import re +import stat +import subprocess +import tempfile +from contextlib import contextmanager +from datetime import UTC, datetime, timedelta +from pathlib import Path +from typing import Any, Iterator + +TRUST = Path('/etc/phios/os-update-trust.json') +KEYRING = Path('/etc/phios/os-update-keyring.gpg') +SOURCE = Path('/usr/share/phios/source-commit') +GENERATION = Path('/var/lib/phios/os-update-generation.json') +ENV = {'PATH': '/usr/bin', 'LANG': 'C.UTF-8', 'HOME': '/root'} +SCHEMAS = {'memory': 1, 'data_backup': 'phios.data-backup.v1'} +SHA = r'[0-9a-f]{64}' +PACKAGE = r'[a-z0-9][a-z0-9@._+\-]{0,127}' + + +def stable_identity(info: os.stat_result) -> tuple[int, ...]: + # Reads can update atime. Compare ownership, identity and modification + # fields, including nanoseconds, instead of mistaking atime for mutation. + return (info.st_dev, info.st_ino, info.st_mode, info.st_uid, info.st_gid, + info.st_nlink, info.st_size, info.st_mtime_ns, info.st_ctime_ns) + + +def strict_json(data: bytes) -> Any: + def pairs(items: list[tuple[str, Any]]) -> dict[str, Any]: + result: dict[str, Any] = {} + for key, value in items: + if key in result: + raise ValueError('duplicate JSON key') + result[key] = value + return result + + def invalid(value: str) -> None: + raise ValueError(f'non-finite JSON number: {value}') + + return json.loads(data, object_pairs_hook=pairs, parse_constant=invalid) + + +def protected_file(path: Path, *, maximum: int = 2 * 1024**2) -> bytes: + """Root-owned trust/installed metadata; inspect every ancestor without links.""" + if not path.is_absolute() or '..' in path.parts: + raise ValueError('an absolute protected path is required') + for parent in [*reversed(path.parents), path]: + info = parent.lstat() + if stat.S_ISLNK(info.st_mode) or info.st_uid != 0 or info.st_mode & 0o022: + raise ValueError('trust or installed metadata has unsafe owner, permissions or links') + info = path.lstat() + if not stat.S_ISREG(info.st_mode) or info.st_nlink != 1 or info.st_size > maximum: + raise ValueError('protected metadata must be one bounded regular file') + fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW) + with os.fdopen(fd, 'rb') as handle: + if stable_identity(os.fstat(handle.fileno())) != stable_identity(info): + raise ValueError('protected metadata changed during intake') + data = handle.read(maximum + 1) + if stable_identity(os.fstat(handle.fileno())) != stable_identity(info): + raise ValueError('protected metadata changed during intake') + if len(data) > maximum: + raise ValueError('protected metadata exceeds its bound') + return data + + +def load_trust() -> tuple[dict[str, Any], bytes]: + policy = strict_json(protected_file(TRUST)) + if (not isinstance(policy, dict) or set(policy) != {'schema_version', 'primary_fingerprint', 'channel'} or + policy['schema_version'] != 'phios.os-update-trust.v1' or policy['channel'] != 'experimental' or + not isinstance(policy['primary_fingerprint'], str) or + re.fullmatch(r'(?:[0-9A-F]{40}|[0-9A-F]{64})', policy['primary_fingerprint']) is None): + raise ValueError('unsupported trust policy; maintainer enrollment is required') + return policy, protected_file(KEYRING, maximum=8 * 1024**2) + + +def inventory(rows: Any) -> dict[str, str]: + if not isinstance(rows, list) or not 1 <= len(rows) <= 20000: + raise ValueError('complete bounded package inventory required') + packages: dict[str, str] = {} + for row in rows: + if (not isinstance(row, dict) or set(row) != {'name', 'version'} or + not isinstance(row['name'], str) or re.fullmatch(PACKAGE, row['name']) is None or + not isinstance(row['version'], str) or not 1 <= len(row['version']) <= 256 or + any(c.isspace() or ord(c) < 32 or ord(c) == 127 for c in row['version']) or + row['name'] in packages): + raise ValueError('invalid or duplicate package identity') + packages[row['name']] = row['version'] + return packages + + +def validate_manifest(payload: Any, *, source: str, sequence: int, installed: list[dict[str, str]], + now: datetime) -> dict[str, Any]: + keys = {'schema_version', 'channel', 'architecture', 'from_source_commit', 'source_commit', + 'base_sequence', 'sequence', 'created_at', 'expires_at', 'arch_snapshot', + 'state_schemas', 'base_packages', 'target_packages', 'packages'} + if not isinstance(payload, dict) or set(payload) != keys: + raise ValueError('unknown update manifest fields or schema') + if (payload['schema_version'] != 'phios.os-package-update.v1' or payload['channel'] != 'experimental' or + payload['architecture'] != 'x86_64' or payload['state_schemas'] != SCHEMAS or + type(payload['state_schemas'].get('memory')) is not int): + raise ValueError('unsupported channel, architecture or state schema; no implicit migration') + if (payload['from_source_commit'] != source or re.fullmatch(r'[0-9a-f]{40}', source) is None or + not isinstance(payload['source_commit'], str) or + re.fullmatch(r'[0-9a-f]{40}', payload['source_commit']) is None or + type(payload['base_sequence']) is not int or payload['base_sequence'] != sequence or + type(payload['sequence']) is not int or payload['sequence'] != sequence + 1): + raise ValueError('stale, replayed or wrong-source update transition') + if not isinstance(payload['arch_snapshot'], str) or re.fullmatch(r'20\d\d/\d\d/\d\d', payload['arch_snapshot']) is None: + raise ValueError('exact Arch snapshot is required') + datetime.strptime(payload['arch_snapshot'], '%Y/%m/%d') + try: + created, expires = [datetime.fromisoformat(payload[key]) for key in ['created_at', 'expires_at']] + except (TypeError, ValueError) as exc: + raise ValueError('invalid update validity window') from exc + if (created.tzinfo is None or expires.tzinfo is None or created > now + timedelta(minutes=5) or + not created < expires or not now < expires or expires - created > timedelta(days=90)): + raise ValueError('expired, future or unbounded update validity window') + before, after = inventory(payload['base_packages']), inventory(payload['target_packages']) + if before != inventory(installed) or not before.keys() <= after.keys(): + raise ValueError('update requires the exact base inventory; removals are unsupported') + rows = payload['packages'] + if not isinstance(rows, list) or not 1 <= len(rows) <= 2000: + raise ValueError('bounded signed package set required') + names: set[str] = set() + files: set[str] = set() + size = 0 + for row in rows: + if (not isinstance(row, dict) or set(row) != {'name', 'version', 'filename', 'sha256', 'size'} or + not isinstance(row['name'], str) or row['name'] not in after or row['name'] in names or + row['version'] != after[row['name']] or not isinstance(row['filename'], str) or + re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9@._+\-]{0,240}\.pkg\.tar\.(zst|xz)', row['filename']) is None or + row['filename'] in files or not isinstance(row['sha256'], str) or + re.fullmatch(SHA, row['sha256']) is None or type(row['size']) is not int or + not 0 < row['size'] <= 2 * 1024**3): + raise ValueError('invalid, repeated or unsafe update package') + names.add(row['name']) + files.add(row['filename']) + size += row['size'] + if size > 16 * 1024**3 or any(before.get(name) != version and name not in names for name, version in after.items()): + raise ValueError('package set exceeds its bound or omits a target change') + return payload + + +def capture(directory: int, name: str, destination: Path, *, maximum: int) -> dict[str, Any]: + """Copy untrusted bytes once; verify and later use only this private copy.""" + if Path(name).name != name or name.startswith('-'): + raise ValueError('unsafe bundle filename') + fd = os.open(name, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=directory) + digest = hashlib.sha256() + total = 0 + with os.fdopen(fd, 'rb') as reader: + info = os.fstat(reader.fileno()) + if not stat.S_ISREG(info.st_mode) or info.st_nlink != 1 or not 0 < info.st_size <= maximum: + raise ValueError('bundle input is not a bounded, singly linked regular file') + out = os.open(destination, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600) + with os.fdopen(out, 'wb') as writer: + for data in iter(lambda: reader.read(1024**2), b''): + total += len(data) + if total > maximum: + raise ValueError('bundle input grew beyond its bound') + writer.write(data) + digest.update(data) + writer.flush() + os.fsync(writer.fileno()) + if stable_identity(os.fstat(reader.fileno())) != stable_identity(info) or total != info.st_size: + raise ValueError('bundle input changed during capture') + return {'sha256': digest.hexdigest(), 'size': total} + + +def verify_signature(home: Path, signature: Path, content: Path, fingerprint: str, *, now: datetime) -> None: + result = subprocess.run(['/usr/bin/gpg', '--no-options', '--homedir', str(home), '--batch', + '--no-auto-key-retrieve', '--auto-key-locate', 'clear', '--status-fd', '1', '--verify', + str(signature), str(content)], env=ENV, capture_output=True, text=True, timeout=60) + statuses = [line.split()[1:] for line in result.stdout.splitlines() if line.startswith('[GNUPG:] ')] + refused = {'BADSIG', 'ERRSIG', 'EXPSIG', 'EXPKEYSIG', 'REVKEYSIG', 'KEYEXPIRED', 'SIGEXPIRED', 'NO_PUBKEY', 'FAILURE'} + valid = [row[1:] for row in statuses if row[0] == 'VALIDSIG'] + if result.returncode or any(row[0] in refused for row in statuses) or len(valid) != 1: + raise ValueError('signature is missing, invalid, expired, revoked or ambiguous') + row = valid[0] + if (len(row) < 9 or (row[9] if len(row) > 9 else row[0]) != fingerprint or + row[7] not in {'8', '9', '10'} or int(row[2]) > int(now.timestamp()) + 300 or + (int(row[3]) != 0 and int(row[3]) <= int(now.timestamp()))): + raise ValueError('signature signer, digest or validity does not match pinned trust') + + +@contextmanager +def verified_bundle(bundle: Path, *, source: str, sequence: int, installed: list[dict[str, str]], + trust: tuple[dict[str, Any], bytes] | None = None, + now: datetime | None = None) -> Iterator[tuple[dict[str, Any], Path]]: + """Caller must keep this context alive through any eventual package use.""" + policy, public_keys = trust if trust is not None else load_trust() + now = now or datetime.now(UTC) + with tempfile.TemporaryDirectory(prefix='phios-verified-update-') as temporary: + private = Path(temporary) + home = private / 'gnupg' + home.mkdir(mode=0o700) + keys = private / 'public-keys.gpg' + keys.write_bytes(public_keys) + keys.chmod(0o600) + subprocess.run(['/usr/bin/gpg', '--no-options', '--homedir', str(home), '--batch', '--import', str(keys)], + env=ENV, capture_output=True, check=True, timeout=60) + directory = os.open(bundle, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW) + try: + capture(directory, 'manifest.json', private / 'manifest.json', maximum=2 * 1024**2) + capture(directory, 'manifest.json.sig', private / 'manifest.json.sig', maximum=65536) + verify_signature(home, private / 'manifest.json.sig', private / 'manifest.json', policy['primary_fingerprint'], now=now) + payload = validate_manifest(strict_json((private / 'manifest.json').read_bytes()), + source=source, sequence=sequence, installed=installed, now=now) + for package in payload['packages']: + filename = package['filename'] + identity = capture(directory, filename, private / filename, maximum=package['size']) + if identity != {'sha256': package['sha256'], 'size': package['size']}: + raise ValueError('signed package hash or length mismatch') + capture(directory, filename + '.sig', private / (filename + '.sig'), maximum=65536) + verify_signature(home, private / (filename + '.sig'), private / filename, policy['primary_fingerprint'], now=now) + finally: + os.close(directory) + yield payload, private + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--bundle', type=Path, required=True) + args = parser.parse_args() + try: + source = protected_file(SOURCE).decode().strip() + sequence = 0 + if GENERATION.exists(): + generation = strict_json(protected_file(GENERATION)) + if (set(generation) != {'schema_version', 'sequence', 'source_commit'} or + generation['schema_version'] != 'phios.os-update-generation.v1' or + generation['source_commit'] != source or type(generation['sequence']) is not int or generation['sequence'] < 0): + raise ValueError('installed update generation is invalid') + sequence = generation['sequence'] + result = subprocess.run(['/usr/bin/pacman', '-Q'], env=ENV, capture_output=True, text=True, check=True, timeout=30) + installed = [dict(zip(['name', 'version'], row.split(), strict=True)) for row in result.stdout.splitlines()] + with verified_bundle(args.bundle, source=source, sequence=sequence, installed=installed) as (payload, _private): + print(json.dumps({'schema_version': 'phios.os-update-verification.v1', + 'source_commit': payload['source_commit'], 'sequence': payload['sequence'], + 'signed_package_count': len(payload['packages']), 'signed_bytes_verified': True, + 'installed': False, 'execution_authority': False, 'release_ready': False}, indent=2)) + return 0 + except (OSError, ValueError, subprocess.SubprocessError) as exc: + print(f'OS update verification held: {exc}') + return 1 + + +if __name__ == '__main__': + raise SystemExit(main()) diff --git a/tests/test_durable_state_v01.py b/tests/test_durable_state_v01.py index 60eb2b26..141de089 100644 --- a/tests/test_durable_state_v01.py +++ b/tests/test_durable_state_v01.py @@ -6,6 +6,7 @@ import sqlite3 import subprocess import sys +import time from concurrent.futures import ThreadPoolExecutor from pathlib import Path @@ -30,8 +31,18 @@ def test_concurrent_processes_preserve_exact_complete_records(tmp_path: Path) -> """ children = [subprocess.Popen([sys.executable, "-c", script, str(path), str(i)]) for i in range(4)] - for child in children: - assert child.wait(timeout=30) == 0 + # Shared CI disks can take longer to complete mandatory fsyncs. This checks + # exact durability/concurrency, not a 30-second storage latency promise. + # Keep one finite deadline and reap every child even when a check fails. + deadline = time.monotonic() + 120 + try: + for child in children: + assert child.wait(timeout=max(0.1, deadline - time.monotonic())) == 0 + finally: + for child in children: + if child.poll() is None: + child.kill() + child.wait(timeout=5) rows = read_jsonl(path) assert {row["id"] for row in rows} == {f"{i}:{j}" for i in range(4) for j in range(15)} assert len(rows) == 60 diff --git a/tests/test_os_checkpoint_v01.py b/tests/test_os_checkpoint_v01.py new file mode 100644 index 00000000..3cdcec5a --- /dev/null +++ b/tests/test_os_checkpoint_v01.py @@ -0,0 +1,203 @@ +from __future__ import annotations + +import copy +import importlib.util +import json +import os +import sqlite3 +from pathlib import Path +from typing import Any + +import pytest + +from phios.memory import MemoryStore + +FILE = Path(__file__).resolve().parents[1] / 'packaging/linux/updates/recover.py' +spec = importlib.util.spec_from_file_location('phios_os_recovery', FILE) +assert spec is not None and spec.loader is not None +recover = importlib.util.module_from_spec(spec) +spec.loader.exec_module(recover) + + +def disk() -> dict[str, Any]: + return {'path': '/dev/vda', 'type': 'disk', 'ro': False, 'pttype': 'gpt', 'size': 32 * 1024**3, + 'serial': 'disposable-test-only', 'maj:min': '252:0', 'mountpoints': [None], 'children': [ + {'path': '/dev/vda1', 'type': 'part', 'ro': False, 'size': 1024**3, 'fstype': 'vfat', + 'uuid': 'ABCD-1234', 'mountpoints': [None]}, + {'path': '/dev/vda2', 'type': 'part', 'ro': False, 'size': 31 * 1024**3, 'fstype': 'btrfs', + 'uuid': 'a' * 8 + '-' + ('a' * 4 + '-') * 3 + 'a' * 12, 'mountpoints': [None]}]} + + +@pytest.mark.parametrize('case', ['mounted', 'holder', 'wrong-layout', 'read-only', 'no-identity', + 'wrong-uuid', 'whole-device-alias', 'extra-device', 'wrong-esp-size']) +def test_recovery_never_accepts_unrelated_or_busy_disks(case: str) -> None: + row = disk() + busy = False + if case == 'mounted': + row['children'][1]['mountpoints'] = ['/'] + elif case == 'holder': + busy = True + elif case == 'wrong-layout': + row['children'][1]['fstype'] = 'ext4' + elif case == 'read-only': + row['ro'] = True + elif case == 'no-identity': + row['serial'] = None + elif case == 'wrong-uuid': + row['children'][1]['uuid'] = 'not-a-uuid' + elif case == 'whole-device-alias': + row['path'] = '/dev/disk/by-id/unreviewed' + elif case == 'extra-device': + row['children'].append(row['children'][1]) + elif case == 'wrong-esp-size': + row['children'][0]['size'] = 512 * 1024**2 + with pytest.raises(ValueError): + recover.validate_disk(row, busy=busy) + + +def checkpoint(identity: dict[str, Any]) -> dict[str, Any]: + return {'schema_version': recover.FORMAT, 'generation': 'b' * 32, + 'disk': {key: identity[key] for key in ['serial_or_wwn', 'size_bytes', 'root_uuid', 'esp_uuid']}, + 'source_commit': 'c' * 40, 'state_schemas': copy.deepcopy(recover.SCHEMA), + 'root_snapshot_uuid': 'd' * 8 + '-' + ('d' * 4 + '-') * 3 + 'd' * 12, + 'boot_files': {name: {'size': 1, 'sha256': 'e' * 64} for name in + ['vmlinuz-linux', 'initramfs-linux.img', 'initramfs-linux-fallback.img', + 'EFI/BOOT/BOOTX64.EFI', 'loader/entries/phios.conf']}, + 'installed': {'source_commit': 'c' * 40, 'install_receipt': { + 'schema_version': 'phios.blank-disk-install.v1', 'installed': True, + 'root_uuid': identity['root_uuid'], 'esp_uuid': identity['esp_uuid'], 'plan': {'username': 'operator'}}}, + 'home_snapshot_restored': False, 'authority_restored': False, 'release_ready': False} + + +def test_partition_sysfs_has_no_slaves_but_still_refuses_holders(tmp_path: Path) -> None: + (tmp_path / 'partition').write_text('1\n') + (tmp_path / 'holders').mkdir() + assert not recover.block_dependencies(tmp_path, partition=True) + (tmp_path / 'holders/dm-0').touch() + assert recover.block_dependencies(tmp_path, partition=True) + with pytest.raises(ValueError, match='block type'): + recover.block_dependencies(tmp_path, partition=False) + + +def test_whole_disk_requires_slaves_probe_and_refuses_dependencies(tmp_path: Path) -> None: + (tmp_path / 'holders').mkdir() + with pytest.raises(FileNotFoundError): + recover.block_dependencies(tmp_path, partition=False) + (tmp_path / 'slaves').mkdir() + assert not recover.block_dependencies(tmp_path, partition=False) + (tmp_path / 'slaves/sda').touch() + assert recover.block_dependencies(tmp_path, partition=False) + with pytest.raises(ValueError, match='block type'): + recover.block_dependencies(tmp_path, partition=True) + + +@pytest.mark.parametrize('case', ['disk', 'generation', 'schema', 'authority', 'home', 'unknown']) +def test_checkpoint_cannot_cross_disks_restore_authority_or_invent_schema(case: str) -> None: + identity = recover.validate_disk(disk(), busy=False) + data = checkpoint(identity) + assert recover.validate_checkpoint(copy.deepcopy(data), identity, 'b' * 32) == data + if case == 'disk': + data['disk']['root_uuid'] = 'different' + elif case == 'generation': + data['generation'] = 'e' * 32 + elif case == 'schema': + data['state_schemas']['memory'] = 2 + elif case == 'authority': + data['authority_restored'] = True + elif case == 'home': + data['home_snapshot_restored'] = True + elif case == 'unknown': + data['implicit_migration'] = True + with pytest.raises(ValueError): + recover.validate_checkpoint(data, identity, 'b' * 32) + + +def test_review_binds_boot_hash_root_snapshot_and_disk_identity() -> None: + identity = recover.validate_disk(disk(), busy=False) + plan = {'operation': 'restore', 'disk': identity, 'checkpoint': checkpoint(identity)} + original = recover.phrase(plan) + for change in ['disk', 'boot', 'snapshot']: + altered = copy.deepcopy(plan) + if change == 'disk': + altered['disk']['serial_or_wwn'] = 'replacement' + elif change == 'boot': + altered['checkpoint']['boot_files']['vmlinuz-linux'] = {'sha256': 'f' * 64, 'size': 1} + else: + altered['checkpoint']['root_snapshot_uuid'] = 'e' * 36 + assert recover.phrase(altered) != original + + +def boot_files(root: Path) -> None: + for name in ['vmlinuz-linux', 'initramfs-linux.img', 'initramfs-linux-fallback.img', + 'EFI/BOOT/BOOTX64.EFI', 'loader/entries/phios.conf']: + path = root / name + path.parent.mkdir(parents=True, exist_ok=True, mode=0o700) + path.write_bytes(('disposable test ' + name).encode()) + + +def test_matched_boot_inventory_detects_missing_changed_or_linked_files(tmp_path: Path) -> None: + boot_files(tmp_path) + initial = recover.boot_inventory(tmp_path, owner=os.getuid()) + (tmp_path / 'loader/random-seed').write_bytes(b'entropy must not be replayed') + assert recover.boot_inventory(tmp_path, owner=os.getuid()) == initial + (tmp_path / 'vmlinuz-linux').write_bytes(b'different kernel') + assert recover.boot_inventory(tmp_path, owner=os.getuid()) != initial + (tmp_path / 'vmlinuz-linux').unlink() + with pytest.raises(ValueError): + recover.boot_inventory(tmp_path, owner=os.getuid()) + (tmp_path / 'vmlinuz-linux').symlink_to(tmp_path / 'initramfs-linux.img') + with pytest.raises(ValueError): + recover.boot_inventory(tmp_path, owner=os.getuid()) + + +def test_metadata_refuses_links_hardlinks_and_writable_trust(tmp_path: Path) -> None: + path = tmp_path / 'checkpoint.json' + path.write_text('{}') + path.chmod(0o666) + with pytest.raises(ValueError): + recover.regular(path, owner=os.getuid()) + path.chmod(0o600) + os.link(path, tmp_path / 'alias') + with pytest.raises(ValueError): + recover.regular(path, owner=os.getuid()) + + +def state_home(top: Path) -> tuple[Path, Path]: + home = top / '@home/operator' + root = home / '.local/state/phios' + root.mkdir(parents=True, mode=0o700) + return home, root + + +def test_authority_history_requires_explicit_data_recovery_without_mutation(tmp_path: Path) -> None: + _home, root = state_home(tmp_path) + ledger = root / 'spine-v0.1/ledger/ghostwalk-action-lease-records.jsonl' + ledger.parent.mkdir(parents=True, mode=0o700) + ledger.write_text('{"execution_authority":true}\n') + original = ledger.read_bytes() + with pytest.raises(ValueError, match='authority history'): + recover.ensure_no_active_authority(tmp_path, 'operator', uid=os.getuid()) + assert ledger.read_bytes() == original + + +def test_unknown_canonical_schema_is_held_without_data_changes(tmp_path: Path) -> None: + _home, root = state_home(tmp_path) + database = root / 'memory/canonical.sqlite3' + MemoryStore(database) + with sqlite3.connect(database) as conn: + conn.execute("UPDATE store_metadata SET value='99' WHERE key='schema_version'") + original = database.read_bytes() + with pytest.raises(ValueError, match='schema'): + recover.ensure_no_active_authority(tmp_path, 'operator', uid=os.getuid()) + assert database.read_bytes() == original + + +def test_enabled_configuration_requires_revalidation_before_rollback(tmp_path: Path) -> None: + home, _root = state_home(tmp_path) + config = home / '.config/phios/memory.json' + config.parent.mkdir(parents=True, mode=0o700) + config.write_text(json.dumps({'enabled': True})) + original = config.read_bytes() + with pytest.raises(ValueError, match='disable memory'): + recover.ensure_no_active_authority(tmp_path, 'operator', uid=os.getuid()) + assert config.read_bytes() == original diff --git a/tests/test_os_update_application_v01.py b/tests/test_os_update_application_v01.py new file mode 100644 index 00000000..b5f54b73 --- /dev/null +++ b/tests/test_os_update_application_v01.py @@ -0,0 +1,120 @@ +from __future__ import annotations + +import importlib.util +import json +import os +from functools import partial +from pathlib import Path +from typing import Any + +import pytest + +FILE = Path(__file__).resolve().parents[1] / 'packaging/linux/updates/apply.py' +spec = importlib.util.spec_from_file_location('phios_os_application', FILE) +assert spec is not None and spec.loader is not None +apply = importlib.util.module_from_spec(spec) +spec.loader.exec_module(apply) + + +@pytest.fixture(autouse=True) +def metadata_owner_for_unprivileged_tests(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(apply.recover, 'regular', partial(apply.recover.regular, owner=os.getuid())) + + +def write_counter(path: Path, sequence: Any, *, schema: str, source: str = 'a' * 40) -> None: + path.parent.mkdir(parents=True, exist_ok=True, mode=0o700) + path.write_text(json.dumps({'schema_version': schema, 'sequence': sequence, 'source_commit': source})) + path.chmod(0o600) + + +def test_recovery_counter_survives_missing_active_root_and_older_snapshot(tmp_path: Path) -> None: + write_counter(tmp_path / '@snapshots/os-update-counter.json', 8, schema='phios.os-update-counter.v1') + saved = tmp_path / 'saved-root' + write_counter(saved / 'var/lib/phios/os-update-generation.json', 2, schema='phios.os-update-generation.v1') + assert apply.recover.recovery_sequence(tmp_path, saved) == 9 + assert not (tmp_path / '@root').exists() + + +@pytest.mark.parametrize('case', ['missing-root-counter', 'missing-anchor', 'mismatch', 'wrong-source', 'boolean', 'unknown-schema']) +def test_update_holds_inconsistent_or_unrecognized_persistent_counters(tmp_path: Path, case: str) -> None: + root_counter = tmp_path / '@root/var/lib/phios/os-update-generation.json' + anchor = tmp_path / '@snapshots/os-update-counter.json' + write_counter(root_counter, 3, schema='phios.os-update-generation.v1') + write_counter(anchor, 3, schema='phios.os-update-counter.v1') + assert apply.sequence(tmp_path, 'a' * 40) == 3 + if case == 'missing-root-counter': + root_counter.unlink() + elif case == 'missing-anchor': + anchor.unlink() + elif case == 'mismatch': + write_counter(anchor, 4, schema='phios.os-update-counter.v1') + elif case == 'wrong-source': + write_counter(anchor, 3, schema='phios.os-update-counter.v1', source='b' * 40) + elif case == 'boolean': + write_counter(anchor, True, schema='phios.os-update-counter.v1') + else: + write_counter(anchor, 3, schema='unknown') + before = {p: p.read_bytes() for p in [root_counter, anchor] if p.exists()} + with pytest.raises(ValueError): + apply.sequence(tmp_path, 'a' * 40) + assert {p: p.read_bytes() for p in before} == before + + +def test_initial_installation_has_counter_zero(tmp_path: Path) -> None: + assert apply.sequence(tmp_path, 'a' * 40) == 0 + + +def test_counter_alias_cannot_hide_a_consumed_transition(tmp_path: Path) -> None: + target = tmp_path / 'unsafe' + write_counter(target, 9, schema='phios.os-update-counter.v1') + (tmp_path / '@snapshots').mkdir(mode=0o700) + (tmp_path / '@snapshots/os-update-counter.json').symlink_to(target) + with pytest.raises(ValueError): + apply.recover.recovery_sequence(tmp_path, tmp_path / 'saved') + + +def test_trust_change_after_confirmation_cannot_create_a_checkpoint(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(apply.verify, 'load_trust', lambda: ({'primary_fingerprint': 'B' * 40}, b'changed')) + effects = [] + monkeypatch.setattr(apply.recover, 'execute', lambda *args: effects.append(args)) + with pytest.raises(ValueError, match='trust changed'): + apply.execute({'disk': {}, 'checkpoint_generation': 'c' * 32}, {}, tmp_path, + ({'primary_fingerprint': 'A' * 40}, b'reviewed')) + assert effects == [] + + +def test_expiration_after_confirmation_cannot_create_a_checkpoint(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + trust = ({'primary_fingerprint': 'A' * 40}, b'reviewed') + monkeypatch.setattr(apply.verify, 'load_trust', lambda: trust) + def expired(*args: Any, **kwargs: Any) -> None: + raise ValueError('expired validity window') + monkeypatch.setattr(apply.verify, 'validate_manifest', expired) + effects = [] + monkeypatch.setattr(apply.recover, 'execute', lambda *args: effects.append(args)) + plan = {'disk': {}, 'checkpoint_generation': 'c' * 32, 'installed': {'source_commit': 'a' * 40}, + 'base_sequence': 0, 'base_packages': [{'name': 'linux', 'version': '2-1'}]} + with pytest.raises(ValueError, match='expired'): + apply.execute(plan, {}, tmp_path, trust) + assert effects == [] + + +def test_native_version_comparison_holds_downgrades_but_allows_reinstall(monkeypatch: pytest.MonkeyPatch) -> None: + seen = [] + def compare(*args: str) -> str: + seen.append(args) + return '-1\n' if args[1] == '1-1' else '0\n' + monkeypatch.setattr(apply.recover, 'run', compare) + baseline = [{'name': 'linux', 'version': '2-1'}] + with pytest.raises(ValueError, match='downgrades'): + apply.supported_versions({'packages': [{'name': 'linux', 'version': '1-1'}]}, baseline) + apply.supported_versions({'packages': [{'name': 'linux', 'version': '2-1'}, {'name': 'new', 'version': '1-1'}]}, baseline) + assert seen == [('vercmp', '1-1', '2-1'), ('vercmp', '2-1', '2-1')] + + +def test_command_failure_preserves_stdout_hook_diagnostics(monkeypatch: pytest.MonkeyPatch) -> None: + from subprocess import CompletedProcess + monkeypatch.setattr(apply.recover.shutil, 'which', lambda *args, **kwargs: '/usr/bin/mkinitcpio') + monkeypatch.setattr(apply.recover.subprocess, 'run', lambda *args, **kwargs: + CompletedProcess(args, 0, stdout='==> ERROR: boot image failed\n', stderr='')) + with pytest.raises(RuntimeError, match='boot image failed'): + apply.recover.run('mkinitcpio', '-P') diff --git a/tests/test_signed_os_update_v01.py b/tests/test_signed_os_update_v01.py new file mode 100644 index 00000000..804dc570 --- /dev/null +++ b/tests/test_signed_os_update_v01.py @@ -0,0 +1,243 @@ +from __future__ import annotations + +import copy +import hashlib +import importlib.util +import json +import os +import subprocess +from datetime import UTC, datetime, timedelta +from pathlib import Path +from typing import Any, Iterator + +import pytest + +FILE = Path(__file__).resolve().parents[1] / 'packaging/linux/updates/verify.py' +spec = importlib.util.spec_from_file_location('phios_os_update_verifier', FILE) +assert spec is not None and spec.loader is not None +verify = importlib.util.module_from_spec(spec) +spec.loader.exec_module(verify) +BASE = [{'name': 'linux', 'version': '6.18-1'}, {'name': 'phios', 'version': '1.0.0-1'}] +CONTENT = b'public disposable package-signature fixture, not a deployable package' +FILENAME = 'phios-1.0.0-2-any.pkg.tar.xz' +EXPIRED_KEY_TIME = int(datetime.now(UTC).timestamp()) - 2 * 86400 + + +def manifest() -> dict[str, Any]: + now = datetime.now(UTC) + return {'schema_version': 'phios.os-package-update.v1', 'channel': 'experimental', + 'architecture': 'x86_64', 'from_source_commit': 'a' * 40, 'source_commit': 'b' * 40, + 'base_sequence': 0, 'sequence': 1, 'created_at': now.isoformat(), + 'expires_at': (now + timedelta(days=1)).isoformat(), 'arch_snapshot': '2026/09/30', + 'state_schemas': dict(verify.SCHEMAS), 'base_packages': copy.deepcopy(BASE), + 'target_packages': [BASE[0], {'name': 'phios', 'version': '1.0.0-2'}], + 'packages': [{'name': 'phios', 'version': '1.0.0-2', 'filename': FILENAME, + 'sha256': hashlib.sha256(CONTENT).hexdigest(), 'size': len(CONTENT)}]} + + +@pytest.mark.parametrize('case', ['future-schema', 'boolean-schema', 'wrong-source', 'replay', + 'boolean-sequence', 'expired', 'future', 'unbounded', 'timezone', 'inventory', 'removal', + 'omitted-change', 'path', 'duplicate', 'extra-field', 'oversized', 'bad-date']) +def test_invalid_transitions_are_held_before_signature_or_package_use(case: str) -> None: + payload = manifest() + if case == 'future-schema': + payload['state_schemas']['memory'] = 2 + elif case == 'boolean-schema': + payload['state_schemas']['memory'] = True + elif case == 'wrong-source': + payload['from_source_commit'] = 'c' * 40 + elif case == 'replay': + payload['sequence'] = 0 + elif case == 'boolean-sequence': + payload['sequence'] = True + elif case == 'expired': + payload['expires_at'] = (datetime.now(UTC) - timedelta(days=1)).isoformat() + elif case == 'future': + payload['created_at'] = (datetime.now(UTC) + timedelta(days=1)).isoformat() + elif case == 'unbounded': + payload['expires_at'] = (datetime.now(UTC) + timedelta(days=100)).isoformat() + elif case == 'timezone': + payload['created_at'] = '2026-09-30T00:00:00' + elif case == 'inventory': + payload['base_packages'][0]['version'] = '6.17-1' + elif case == 'removal': + payload['target_packages'].pop(0) + elif case == 'omitted-change': + payload['target_packages'][0] = {'name': 'linux', 'version': '6.19-1'} + elif case == 'path': + payload['packages'][0]['filename'] = '../' + FILENAME + elif case == 'duplicate': + payload['packages'].append(payload['packages'][0]) + elif case == 'extra-field': + payload['auto_promote'] = True + elif case == 'oversized': + payload['packages'][0]['size'] = 3 * 1024**3 + elif case == 'bad-date': + payload['arch_snapshot'] = '2026/02/31' + with pytest.raises(ValueError): + verify.validate_manifest(payload, source='a' * 40, sequence=0, installed=BASE, now=datetime.now(UTC)) + + +@pytest.mark.parametrize('data', [b'{"a":1,"a":2}', b'{"a":NaN}', b'{"a":Infinity}']) +def test_ambiguous_json_is_held(data: bytes) -> None: + with pytest.raises(ValueError): + verify.strict_json(data) + + +def test_private_capture_survives_later_bundle_replacement(tmp_path: Path) -> None: + bundle = tmp_path / 'bundle' + bundle.mkdir() + source = bundle / FILENAME + source.write_bytes(CONTENT) + directory = os.open(bundle, os.O_RDONLY | os.O_DIRECTORY) + try: + destination = tmp_path / 'private' + result = verify.capture(directory, FILENAME, destination, maximum=len(CONTENT)) + source.write_bytes(b'changed after verification') + assert destination.read_bytes() == CONTENT + assert result == {'sha256': hashlib.sha256(CONTENT).hexdigest(), 'size': len(CONTENT)} + assert destination.stat().st_mode & 0o777 == 0o600 + finally: + os.close(directory) + + +@pytest.mark.parametrize('kind', ['symlink', 'hardlink', 'fifo']) +def test_nonregular_or_alias_inputs_are_held(tmp_path: Path, kind: str) -> None: + target = tmp_path / 'target' + target.write_bytes(CONTENT) + name = tmp_path / FILENAME + if kind == 'symlink': + name.symlink_to(target) + elif kind == 'hardlink': + os.link(target, name) + else: + os.mkfifo(name) + directory = os.open(tmp_path, os.O_RDONLY | os.O_DIRECTORY) + try: + with pytest.raises((OSError, ValueError)): + verify.capture(directory, FILENAME, tmp_path / 'private', maximum=len(CONTENT)) + assert not (tmp_path / 'private').exists() + finally: + os.close(directory) + + +@pytest.fixture(scope='module') +def signing_keys(tmp_path_factory: pytest.TempPathFactory) -> Iterator[list[tuple[Path, str, bytes]]]: + keys = [] + homes = [] + try: + for label in ['accepted', 'untrusted', 'expired']: + home = tmp_path_factory.mktemp('phios-disposable-key-' + label) + home.chmod(0o700) + homes.append(home) + # These ephemeral keys are never retained or supplied to a release. + subprocess.run(['/usr/bin/gpg', '--no-options', '--homedir', str(home), '--batch', + *(['--faked-system-time', str(EXPIRED_KEY_TIME)] if label == 'expired' else []), + '--pinentry-mode', 'loopback', '--passphrase', '', '--quick-generate-key', + f'PhiOS Disposable Test {label} <{label}@example.invalid>', 'ed25519', 'sign', '1d'], + check=True, capture_output=True, timeout=60) + listing = subprocess.check_output(['/usr/bin/gpg', '--no-options', '--homedir', str(home), + '--with-colons', '--list-keys'], text=True) + fingerprint = next(row.split(':')[9] for row in listing.splitlines() if row.startswith('fpr:')) + public = subprocess.check_output(['/usr/bin/gpg', '--no-options', '--homedir', str(home), '--export', fingerprint]) + keys.append((home, fingerprint, public)) + yield keys + finally: + for home in homes: + subprocess.run(['gpgconf', '--homedir', str(home), '--kill', 'all'], capture_output=True, timeout=15) + + +def sign(home: Path, path: Path, *, at: int | None = None) -> None: + subprocess.run(['/usr/bin/gpg', '--no-options', '--homedir', str(home), '--batch', '--yes', + *(['--faked-system-time', str(at)] if at is not None else []), + '--pinentry-mode', 'loopback', '--passphrase', '', '--detach-sign', str(path)], + check=True, capture_output=True, timeout=30) + + +@pytest.mark.parametrize('case', ['valid', 'manifest-tamper', 'package-tamper', 'wrong-key', 'missing-signature', + 'wrong-pin', 'expired-key', 'revoked-key']) +def test_real_detached_signatures_and_pinned_identity( + tmp_path: Path, signing_keys: list[tuple[Path, str, bytes]], case: str, +) -> None: + home, fingerprint, public = signing_keys[0] + if case == 'expired-key': + home, fingerprint, public = signing_keys[2] + bundle = tmp_path / 'bundle' + bundle.mkdir() + payload = manifest() + data = bundle / 'manifest.json' + data.write_text(json.dumps(payload)) + package = bundle / FILENAME + package.write_bytes(CONTENT) + signer = signing_keys[1][0] if case == 'wrong-key' else home + at = EXPIRED_KEY_TIME + 60 if case == 'expired-key' else None + sign(signer, data, at=at) + sign(signer, package, at=at) + if case == 'revoked-key': + revoked = tmp_path / 'revoked-public-only' + revoked.mkdir(mode=0o700) + subprocess.run(['gpg', '--no-options', '--homedir', str(revoked), '--batch', '--import'], + input=public, check=True, capture_output=True, timeout=30) + certificate = (home / 'openpgp-revocs.d' / (fingerprint + '.rev')).read_text() + armor = certificate[certificate.index('-----BEGIN PGP PUBLIC KEY BLOCK-----'):] + subprocess.run(['gpg', '--no-options', '--homedir', str(revoked), '--batch', '--import'], + input=armor.encode(), check=True, capture_output=True, timeout=30) + public = subprocess.check_output(['gpg', '--no-options', '--homedir', str(revoked), '--export', fingerprint]) + if case == 'manifest-tamper': + data.write_text(json.dumps({**payload, 'source_commit': 'c' * 40})) + elif case == 'package-tamper': + package.write_bytes(b'x' * len(CONTENT)) + elif case == 'missing-signature': + (bundle / (FILENAME + '.sig')).unlink() + elif case == 'wrong-pin': + fingerprint = signing_keys[1][1] + trust = ({'primary_fingerprint': fingerprint}, public) + if case != 'valid': + with pytest.raises((OSError, ValueError)): + with verify.verified_bundle(bundle, source='a' * 40, sequence=0, installed=BASE, trust=trust): + pytest.fail('invalid update must never reach a package consumer') + return + with verify.verified_bundle(bundle, source='a' * 40, sequence=0, installed=BASE, trust=trust) as (checked, private): + assert checked == payload + assert (private / FILENAME).read_bytes() == CONTENT + package.write_bytes(b'replaced after verification') + assert (private / FILENAME).read_bytes() == CONTENT + assert not private.exists() + + +@pytest.mark.parametrize('case', ['public', 'wrong-fingerprint', 'secret', 'expired']) +def test_real_public_key_enrollment_rejects_wrong_identity_secret_and_expired_keys( + tmp_path: Path, signing_keys: list[tuple[Path, str, bytes]], case: str, +) -> None: + spec = importlib.util.spec_from_file_location('phios_enrollment', FILE.with_name('enroll.py')) + assert spec is not None and spec.loader is not None + enroll = importlib.util.module_from_spec(spec) + spec.loader.exec_module(enroll) + signer, fingerprint, public = signing_keys[2 if case == 'expired' else 0] + if case == 'secret': + public = subprocess.check_output(['gpg', '--no-options', '--homedir', str(signer), '--batch', + '--pinentry-mode', 'loopback', '--passphrase', '', '--export-secret-keys', fingerprint]) + elif case == 'wrong-fingerprint': + fingerprint = signing_keys[1][1] + captured = tmp_path / 'supplied-key.gpg' + captured.write_bytes(public) + home = tmp_path / 'public-only-enrollment' + home.mkdir(mode=0o700) + try: + if case != 'public': + with pytest.raises(ValueError): + enroll.public_key(home, captured, fingerprint, now=datetime.now(UTC)) + else: + exported = enroll.public_key(home, captured, fingerprint, now=datetime.now(UTC)) + bundle = tmp_path / 'verified-after-enrollment' + bundle.mkdir() + data, archive = bundle / 'manifest.json', bundle / FILENAME + data.write_text(json.dumps(manifest())) + archive.write_bytes(CONTENT) + sign(signer, data) + sign(signer, archive) + with verify.verified_bundle(bundle, source='a' * 40, sequence=0, installed=BASE, + trust=({'primary_fingerprint': fingerprint}, exported)) as (_payload, private): + assert (private / FILENAME).read_bytes() == CONTENT + finally: + subprocess.run(['gpgconf', '--homedir', str(home), '--kill', 'all'], capture_output=True, timeout=15)