diff --git a/.github/workflows/linux-image.yml b/.github/workflows/linux-image.yml index 0d36c0aa..ab530a65 100644 --- a/.github/workflows/linux-image.yml +++ b/.github/workflows/linux-image.yml @@ -53,12 +53,16 @@ jobs: --iso dist/linux/phios-linux-0.1.0-alpha.1-x86_64.iso \ --source "$(cat dist/linux/source-commit.txt)" \ --output "$RUNNER_TEMP/phios-boot" + - name: Install only to a disposable virtual disk and qualify no-ISO recovery + run: | + python3 packaging/linux/tests/qemu_install.py \ + --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" - name: Convert display evidence even when qualification fails if: always() run: | - if [[ -f "$RUNNER_TEMP/phios-boot/screen.ppm" ]]; then - /usr/bin/python3 -c 'from PIL import Image; from pathlib import Path; import os; [Image.open(p).save(p.with_suffix(".png")) for p in Path(os.environ["RUNNER_TEMP"] + "/phios-boot").glob("*.ppm")]' - fi + /usr/bin/python3 -c 'from PIL import Image; from pathlib import Path; import os; [Image.open(p).save(p.with_suffix(".png")) for directory in ["phios-boot", "phios-installed"] for p in Path(os.environ["RUNNER_TEMP"], directory).glob("*.ppm")]' - name: Preserve candidate and qualification evidence if: always() uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 @@ -69,6 +73,9 @@ jobs: ${{ runner.temp }}/phios-boot/*.log ${{ runner.temp }}/phios-boot/*.json ${{ runner.temp }}/phios-boot/*.png + ${{ runner.temp }}/phios-installed/*.log + ${{ runner.temp }}/phios-installed/*.json + ${{ runner.temp }}/phios-installed/*.png if-no-files-found: warn retention-days: 7 - name: Preserve reviewable logs and screenshot separately @@ -84,5 +91,8 @@ jobs: ${{ runner.temp }}/phios-boot/*.log ${{ runner.temp }}/phios-boot/*.json ${{ runner.temp }}/phios-boot/*.png + ${{ runner.temp }}/phios-installed/*.log + ${{ runner.temp }}/phios-installed/*.json + ${{ runner.temp }}/phios-installed/*.png if-no-files-found: warn retention-days: 7 diff --git a/docs/os/IMPLEMENTATION_STATUS.md b/docs/os/IMPLEMENTATION_STATUS.md index 7d8ac7ac..4fa5bab7 100644 --- a/docs/os/IMPLEMENTATION_STATUS.md +++ b/docs/os/IMPLEMENTATION_STATUS.md @@ -9,11 +9,11 @@ proof that PhiOS is a completed OS. Preserve the repository AGENTS.md rules. | --- | --- | --- | | R1: HTTP callers cannot mint operator authority | Decision, binding and lease POSTs held; explicit terminal review | HTTP rejection, cancellation and stale-review tests; same-user isolation and Windows ACL evidence remain required | | R2: Freeze a truthful Linux release contract | Candidate contract and generated metadata corrected | docs/os/RELEASE_CONTRACT.md and packaging/linux/release.json; Python and OS release tracks separate | -| R3: Install current Python and UI packages | Candidate PKGBUILDs, JS lock and native pacman adapter | CI must build/install exact source packages; fixed Arch snapshot and signed upstream inputs | -| R4: Real non-root graphical login and supervised services | Candidate Wayfire session and user service target | Live/VM qualification pending; no privileged browser or agent auto-start | -| R5: Produce and UEFI boot exact live ISO | Candidate isolated Archiso/QEMU workflow | Exact ISO/source/hash/serial/screenshot evidence required; no ready claim until observed | -| R6: Recover durable private state | Candidate locking/sync, transactional outbox and data-only recovery | Contention, interruption, backup/restore and schema refusal tests; installed reboot/power-loss evidence still required | -| R7: Explicit blank-disk installation | Pending | Disposable VM install, boot without ISO, persistence | +| R3: Install current Python and UI packages | Current-source PKGBUILDs, JS lock and native pacman adapter | Pinned Arch image package/install smoke passed in runs 36786368318 and 36798467774; signed upstream inputs; local development packages unsigned | +| R4: Real non-root graphical login and supervised services | Wayfire session and user service target | Run 36798467774 passed real live/installed login, observer/browser readiness, sidecar restart and logout; no privileged browser or agent auto-start | +| 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 | | 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 | @@ -38,4 +38,12 @@ Validation: 73 focused Python tests passed; Ruff and mypy (301 source files) pas ## Linux foundation handoff -The candidate implements release-contract, package, session and live-image build milestones. 85 focused Python release/desktop/profile tests, lint and types pass locally. PhiShell build and the Arch inventory/security transport tests pass. The CI image workflow must provide the installed-package and actual UEFI boot evidence before these milestones are called qualified. Root autologin and unrelated releng services are removed. The CI-only live qualification fixture is excluded from normal local previews. Installation, durable crash recovery, OS update/rollback, Linux effect execution, hardware beta and signed public release remain held; no code or evidence in this milestone grants those claims. +The candidate implements release-contract, package, session and live-image build milestones. 85 focused Python release/desktop/profile tests, lint and types pass locally. PhiShell build and the Arch inventory/security transport tests pass. Image run [36786368318](https://github.com/MichaelWave369/PhiOS/actions/runs/36786368318) qualified the live lifecycle for source `5339f180ad9f8dbac11906c5e962728f80853e91`, ISO SHA-256 `5f3eacd5ce24c6cb8ea0067aad23054f5ca33caa146c5600eb4d625942c049ca`. Root autologin and unrelated releng services are removed. The CI-only qualification fixture is excluded from normal local previews. + +## Installed VM evidence + +Image run [36798467774](https://github.com/MichaelWave369/PhiOS/actions/runs/36798467774) passed for source `0253b6e0fb27251fe2da37b6d8c1e31245a64290`, ISO SHA-256 `8599bbc7ff2ed35432bae23692464d4d5afa9ffdfc787699a7be88f2cfc62f5c`. A newly created 32-GiB disk, serial `PHIOS_CI_BLANK`, was the only target. The VM had x64 UEFI/KVM, two CPUs, 4 GiB RAM, no network or shared folders, and no attached host disk. Cancellation preserved the blank target; production installation, normal password/PAM and greetd logins, the actual Wayfire/PhiShell desktop, verified backup/fresh restore, and acknowledged state after abrupt virtual restart passed. Installed boot IDs were `e5ba8528af464b8192312d9aab0db869` and `caa9695c41c64c3d898e12c1bd3234f5`. + +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. diff --git a/docs/os/INSTALLATION.md b/docs/os/INSTALLATION.md new file mode 100644 index 00000000..1447cff1 --- /dev/null +++ b/docs/os/INSTALLATION.md @@ -0,0 +1,120 @@ +# Experimental blank-disk installation + +The candidate manual installer is `phios-install`, packaged behind a root-owned +isolated Python launcher. The disposable installed-image gate passed in +[run 36798467774](https://github.com/MichaelWave369/PhiOS/actions/runs/36798467774). +This remains an experimental development installation; a hardware-supported beta additionally +requires update/recovery and the declared hardware matrix. Keep the verified +live media available. An installed filesystem alone is not a completed OS +release. + +## Scope + +Supported candidate shape: x86_64, x64 UEFI with Secure Boot disabled, one +canonical disk with a stable serial/WWN, at least 16 GiB, no partitions, +mounts, swap, holders, slaves or recognized signatures. Before installation +the tool reads every byte and requires zeroed contents, including unsigned data +that has no filesystem signature. This can take time on large hardware. +Existing data is refused. There is no automatic disk selection, erase-existing +option, unattended mode, HTTP installer or confirmation bypass. + +The layout is a 1 GiB FAT32 ESP and a Btrfs filesystem with separate `@root`, +`@home`, `@log` and `@snapshots` subvolumes. Installation is unencrypted and has +no swap/hibernation setup. Btrfs subvolumes prepare a recovery layout; they do +not by themselves implement OS rollback or protect against drive failure. +BIOS, dual boot, Secure Boot, disk encryption, RAID, existing partitions and +storage migration are held. + +## Review and install + +Boot the configured PhiOS live preview. Open Foot and inspect the real disks: + +```sh +lsblk --bytes --paths --output NAME,TYPE,SIZE,MODEL,SERIAL,WWN,MOUNTPOINTS +``` + +Replace both placeholders below with a reviewed canonical path and a new +lowercase account name. `--plan` performs read-only inventory and reports the +source, disk, account, hostname, unencrypted layout and held release status: + +```sh +sudo phios-install --disk /dev/DEVICE --username YOURNAME --plan +sudo phios-install --disk /dev/DEVICE --username YOURNAME +``` + +The public volatile `phios` account can invoke this one interactive installer +through sudo; it receives no general passwordless root shell. Root/TTY checks +do not prove a human or isolate a malicious same-user process. The supported +custody boundary is the operator-controlled live boot and reviewed device. + +The tool validates the target, checks zeroed contents, requests a fresh password +(at least 12 characters), and displays a confirmation containing the exact +device path and SHA-256 of the complete reviewed plan. Type that full phrase +or cancel. A wrong phrase, EOF or cancellation before the first disk command +does not change the disk. The disk inventory and zeroed contents are rechecked +after confirmation; stale identity is held. Passwords are passed through stdin +only, never argv, logs or receipts. + +The first destructive command creates GPT on the selected empty disk. The tool +copies the immutable live squashfs, never the current live overlay or another +user's state. It creates a fresh account and private state, locks root, removes +live credentials/autologin/test fixtures, installs a normal greetd/PAM login, +generates an installed initramfs and installs systemd-boot's fallback loader. +It leaves firmware boot variables/order unchanged. Select the installed disk +in firmware if needed. The live password is never installed as an account +credential. + +Installed package repositories remain on the signed pinned Arch snapshot. +The transient unsigned local build repository is removed. A supported PhiOS +package update channel and signed OS publication are separate pending gates; +do not change mirrors or perform partial package upgrades to imply a supported +update policy. + +## Failure and first boot + +The tool preserves private stage/error evidence under `/run/phios-install-*`. +After disk writes begin, failure does not undo a partial installation or make +the disk blank again. Preserve the evidence off volatile media, inspect the +reported stage and mounts, and recover deliberately. A cleanup failure reports +remaining mounts and returns nonzero; do not reboot while cleanup is held. +There is no implicit retry or automatic wiping of failed targets. + +Successful installation writes `/var/lib/phios/install-receipt.json` with exact +source, target identity and filesystem UUIDs. `release_ready` remains false and +installed boot remains unqualified until observed. Remove the ISO, boot the +disk, authenticate the new account and verify Wayfire/PhiShell, private memory +state, package observations and services. Optional memory configuration stays +disabled unless the operator explicitly enables it. See STATE_RECOVERY.md for +data-only migration and backup; authority is never imported from the live +session. + +## Disposable qualification + +The CI lane creates a new 32 GiB qcow2 image with serial `PHIOS_CI_BLANK`; its +driver accepts no existing image or host device. Networking and shared folders +are absent. A root qualification fixture exists only in the CI live profile +and refuses any other target. It drives the same production CLI through a PTY, +first cancels and checks the disk, then types the exact reviewed confirmation. + +The fixture seeds a zero-authority canonical memory record and verified backup +as the new user, confirms removal of live credentials/test fixtures/autologin, +and injects a serial console solely into the disposable installed test target. +The host then boots without the ISO, authenticates through normal password/PAM +login, types credentials at the real greetd greeter, observes the non-root +desktop/services, restores data into a fresh root, and checks an acknowledged +write again after an abrupt virtual restart. Serial-console injection is +recorded in the receipt; no installed automatic login is introduced. Exact +ISO/source hashes, serial logs, boot IDs and screenshots accompany success or +failure. A VM restart is not hardware power-loss qualification. + +The qualified source is `0253b6e0fb27251fe2da37b6d8c1e31245a64290`; ISO SHA-256 +is `8599bbc7ff2ed35432bae23692464d4d5afa9ffdfc787699a7be88f2cfc62f5c`. +The exact receipt and evidence identities are in +`docs/os/evidence/installation-0253b6e0.json`. CI credentials +are public test-only values; normal local profiles and production installs +contain neither the fixture nor those credentials. + +References: [bootctl](https://man.archlinux.org/man/bootctl.1.en), +[lsblk](https://man.archlinux.org/man/lsblk.8.en), +[wipefs](https://man.archlinux.org/man/wipefs.8.en), +[Btrfs subvolumes](https://btrfs.readthedocs.io/en/latest/btrfs-subvolume.html). diff --git a/docs/os/RELEASE_CONTRACT.md b/docs/os/RELEASE_CONTRACT.md index 213bdc64..36f86b89 100644 --- a/docs/os/RELEASE_CONTRACT.md +++ b/docs/os/RELEASE_CONTRACT.md @@ -24,9 +24,11 @@ cannot mint operator approvals; see OPERATOR_AUTHORIZATION.md. ## Deliberately unqualified capabilities -This preview is a volatile live image. It has no qualified disk installer, -persistent installed-system recovery, whole-OS rollback, Secure Boot or BIOS -support. No hardware compatibility claim follows from a VM boot. Agent +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 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/installation-0253b6e0.json b/docs/os/evidence/installation-0253b6e0.json new file mode 100644 index 00000000..987e31b8 --- /dev/null +++ b/docs/os/evidence/installation-0253b6e0.json @@ -0,0 +1,60 @@ +{ + "abrupt_virtual_restart_passed": true, + "accelerator": "kvm", + "artifact_expiry": "2026-10-08", + "ci_serial_console_injected": true, + "cpus": 2, + "disk_bytes": 34359738368, + "disk_serial": "PHIOS_CI_BLANK", + "evidence_artifact_id": 11135321615, + "evidence_files": { + "boot-evidence.json": "9948a5f3823363d90d34aa84b05df6d54b64f8e9fcdac3e705583ce01e6b13ae", + "builder-image.json": "9526e9737def8b23a3d1297bf6c7a593b19ba1ec039ed5d3b9d10d57ed16df34", + "install-live-qemu.log": "33c482cb34b64de8cea0bd9b94549dcb837ea35745e324744900915ce1a24b8d", + "install-live-serial.log": "522b00042c3bc8ba0207e73c88d0ec37a210d325bdd4b039aba9286589b525aa", + "installed-1-qemu.log": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "installed-1-serial.log": "ae2a4903354f29b6618951c131ef72d54adc48dade1e7f5259da43e454a0b2fa", + "installed-2-qemu.log": "33c482cb34b64de8cea0bd9b94549dcb837ea35745e324744900915ce1a24b8d", + "installed-2-serial.log": "cd0438faa633b6c8199cdc01756bbf0bd1f09fe51e7a89b3ff46615be2b315e5", + "installed-evidence.json": "125aa97b8c4b7bbe96546ec98e5f580499fa3f68a093e584ea2831c4d4457f92", + "mkarchiso.log": "957c60b9135a6747d48e17a0aac118fa602b46124b1fbed4c842b44e0ca9d902", + "qemu.log": "8183afaf3dbaee427198c21759fdbcad0a6ce1a046e59b35ce77e616071ad0a2", + "release.json": "0d5499ce8f252637d7a1d6a8bdedeb8aef9829307893e348f3c1bf0795b91a75", + "screen-first.png": "b948c3898cde2934cec3760a9b8cc29f332defe1c6a23333458c3e214e56b610", + "screen-install-live.png": "e77f8927d18f259bbf3bd968fd15eb43007ee346ae2109c26aa1f60652aa4828", + "screen-installed-1-greeter.png": "f83a37571994ca7274939836bf77a47904c689fb6d38bb8587a11f2432aeba0e", + "screen-installed-1.png": "70606f87e262a8242763c47258fe828d750ea210a5781a973f36fe5a1f9716be", + "screen-installed-2-greeter.png": "f83a37571994ca7274939836bf77a47904c689fb6d38bb8587a11f2432aeba0e", + "screen-installed-2.png": "c4a706b924ef4a742e2b02ce7edac5d948210d489a299f0e41548970c6f7ee98", + "screen.png": "df5a5ac5fddf46461c0e9bd41ef1cdf615e8d4f08777e64d05bc015577a6f4b5", + "serial.log": "b3eaf114a12ca7061bc18e7f4e10590a74bc7cd5739cd788127b85ece305ae2f" + }, + "hardware_qualified": false, + "host_disks_attached": false, + "image_artifact_id": 11134958214, + "installed": true, + "installed_boot_ids": [ + "e5ba8528af464b8192312d9aab0db869", + "caa9695c41c64c3d898e12c1bd3234f5" + ], + "installer_head": "f135a24d3d88173f611829317e4ad04ebc22eff3", + "iso_sha256": "8599bbc7ff2ed35432bae23692464d4d5afa9ffdfc787699a7be88f2cfc62f5c", + "job_id": 110167226382, + "live_boot_ids": [ + "264482abc42a499f80a60606b388f914", + "a02abb74623343f2adfaa01a4f4651a8" + ], + "live_boot_passed": true, + "live_reboot_passed": true, + "network": false, + "no_iso_boot_passed": true, + "public_disposable_credentials": true, + "ram_mib": 4096, + "record_sha256": "c481900567db858427663a26909e82a9d30fe2e083c929cb68683a9823e87bb4", + "release_ready": false, + "schema_version": "phios.os-qualification-summary.v1", + "screenshot_visually_reviewed": true, + "signed": false, + "source_commit": "0253b6e0fb27251fe2da37b6d8c1e31245a64290", + "workflow_run": 36798467774 +} diff --git a/packaging/arch/phios/PKGBUILD b/packaging/arch/phios/PKGBUILD index bb33e593..966ce24b 100644 --- a/packaging/arch/phios/PKGBUILD +++ b/packaging/arch/phios/PKGBUILD @@ -23,4 +23,6 @@ package() { install -Dm644 LICENSE_HISTORY.md "$pkgdir/usr/share/doc/phios/LICENSE_HISTORY.md" install -Dm644 packaging/linux/release.json "$pkgdir/usr/share/phios/linux-release.json" 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" } diff --git a/packaging/linux/installer/install.py b/packaging/linux/installer/install.py new file mode 100644 index 00000000..1cccf2f6 --- /dev/null +++ b/packaging/linux/installer/install.py @@ -0,0 +1,362 @@ +"""Experimental offline UEFI installer; only an explicitly confirmed zeroed disk. + +Installed behind a root-owned `python -I` wrapper. No automatic disk selection, +erase-existing mode, confirmation bypass, remote request handler or shell eval. +""" +from __future__ import annotations + +import argparse +import fcntl +import getpass +import hashlib +import json +import os +import re +import shutil +import stat +import subprocess +import sys +import tempfile +import time +from pathlib import Path +from typing import Any + +ENV = {"PATH": "/usr/bin", "LANG": "C.UTF-8", "HOME": "/root"} +SOURCE = Path("/run/archiso/bootmnt/arch/x86_64/airootfs.sfs") +IDENTITY = Path("/usr/share/phios/source-commit") +MINIMUM = 16 * 1024**3 +REQUIRED = ("lsblk", "wipefs", "sgdisk", "udevadm", "mkfs.fat", "mkfs.btrfs", + "mount", "umount", "rsync", "chroot", "arch-chroot", "btrfs", "blkid", "bootctl") + + +def run(*args: str, data: str | None = None) -> str: + executable = shutil.which(args[0], path=ENV["PATH"]) + if executable is None: + raise ValueError(f"required program unavailable: {args[0]}") + result = subprocess.run([executable, *args[1:]], input=data, text=True, + stdout=subprocess.PIPE, stderr=subprocess.STDOUT, + env=ENV, check=False) + if result.returncode or "==> ERROR:" in result.stdout: + # Password input is never included in a command, exception or receipt. + raise RuntimeError(f"{args[0]} failed (exit {result.returncode}): {result.stdout[-4000:]}") + return result.stdout + + +def validate_inventory(row: dict[str, Any], signatures: list[Any], *, busy: bool) -> dict[str, Any]: + if row.get("type") != "disk" or row.get("ro") not in (False, 0): + raise ValueError("target must be a writable whole disk") + 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: + raise ValueError("unsupported or noncanonical disk path") + if row.get("children") or any(row.get("mountpoints") or []) or busy: + raise ValueError("mounted disks, swap, partitions and device holders are refused") + if signatures or row.get("fstype") or row.get("pttype"): + raise ValueError("used disks are refused; existing data is never erased by this installer") + if type(row.get("size")) is not int or row["size"] < MINIMUM: + raise ValueError("a disk of at least 16 GiB is required") + serial = row.get("serial") or row.get("wwn") + if not isinstance(serial, str) or not serial.strip(): + raise ValueError("a stable serial number or WWN is required") + if any(ord(c) < 32 or ord(c) == 127 for c in serial): + raise ValueError("disk identity contains unsafe control characters") + return {"path": path, "size_bytes": row["size"], "serial_or_wwn": serial.strip(), + "model": row.get("model"), "major_minor": row.get("maj:min")} + + +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("use the canonical /dev path of a real whole disk") + run("udevadm", "settle") + rows = json.loads(run("lsblk", "--json", "--bytes", "--paths", "--tree", "--output", + "NAME,PATH,TYPE,SIZE,RO,MODEL,SERIAL,WWN,MOUNTPOINTS,FSTYPE,PTTYPE,MAJ:MIN", device))["blockdevices"] + if len(rows) != 1: + raise ValueError("target inventory is ambiguous") + info = path.stat() + number = f"{os.major(info.st_rdev)}:{os.minor(info.st_rdev)}" + sys_device = Path("/sys/dev/block") / number + holders = sys_device / "holders" + slaves = sys_device / "slaves" + busy = bool(list(holders.iterdir()) or list(slaves.iterdir())) + # lsblk sees mounts in this namespace; inspect swap and kernel mount IDs too. + if any(line.split()[2] == number for line in Path("/proc/self/mountinfo").read_text().splitlines()): + busy = True + for line in Path("/proc/swaps").read_text().splitlines()[1:]: + swap = Path(line.split()[0]) + if swap.exists() and swap.stat().st_rdev == info.st_rdev: + busy = True + signatures = json.loads(run("wipefs", "--no-act", "--json", device))["signatures"] + identity = validate_inventory(rows[0], signatures, busy=busy) + if identity["path"] != device or identity["major_minor"] != number: + raise ValueError("block device identity changed during inventory") + return identity + + +def verify_zeroed(device: str, size: int) -> None: + """Probe every byte, including unsigned data with no filesystem signature.""" + fd = os.open(device, os.O_RDONLY | os.O_NOFOLLOW) + try: + total = 0 + while chunk := os.read(fd, 8 * 1024**2): + if chunk.count(0) != len(chunk): + raise ValueError("target is not fully zeroed; no disk writes were performed") + total += len(chunk) + if total != size: + raise ValueError("disk size changed or a read was incomplete") + finally: + os.close(fd) + + +def confirmation(identity: dict[str, Any], source: str, username: str, hostname: str) -> tuple[dict[str, Any], str]: + plan = {"schema_version": "phios.blank-disk-install-plan.v1", "target": identity, + "source_commit": source, "username": username, "hostname": hostname, + "layout": {"gpt": True, "esp_bytes": 1024**3, "filesystem": "btrfs", + "subvolumes": ["@root", "@home", "@log", "@snapshots"]}, + "encrypted": False, "secure_boot": False, "firmware_variables_changed": False, + "experimental": True, "release_ready": False} + digest = hashlib.sha256(json.dumps(plan, sort_keys=True, separators=(",", ":")).encode()).hexdigest() + return plan, f"INSTALL {identity['path']} {digest}" + + +def validate_account(username: str, hostname: str) -> None: + if re.fullmatch(r"[a-z][a-z0-9_-]{0,30}", username) is None or username in { + "root", "phios", "phios-agent", "phios-greeter", "nobody", + }: + raise ValueError("choose a new lowercase account name; live/system accounts are reserved") + if re.fullmatch(r"[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?", hostname) is None: + raise ValueError("invalid hostname") + + +def write(root: Path, name: str, content: str, *, mode: int = 0o644) -> None: + path = root / name + # The immutable source is trusted, but generated files must not follow its + # absolute symlinks out of the installation target (notably /etc/os-release). + if path.is_symlink(): + path.unlink() + path.parent.mkdir(parents=True, exist_ok=True) + fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | os.O_NOFOLLOW, mode) + with os.fdopen(fd, "w") as handle: + handle.write(content) + handle.flush() + os.fsync(handle.fileno()) + os.chmod(path, mode) + + +def configure(root: Path, username: str, password: str, hostname: str, root_uuid: str, esp_uuid: str) -> None: + for pattern in ["etc/sysusers.d/phios-live.conf", "etc/tmpfiles.d/phios-live.conf", + "etc/mkinitcpio.conf.d/archiso.conf", "etc/systemd/system/phios-live-*.service", + "etc/systemd/system/multi-user.target.wants/phios-live-*.service", + "etc/systemd/system/greetd.service.d/phios.conf", "usr/local/bin/phios-live-*", + "etc/sudoers.d/phios-live-installer", "etc/systemd/system/serial-getty@ttyS0.service"]: + for path in root.glob(pattern): + path.unlink() + if (root / "etc/machine-id").exists(): + write(root, "etc/machine-id", "") + random_seed = root / "var/lib/systemd/random-seed" + random_seed.unlink(missing_ok=True) + passwd = (root / "etc/passwd").read_text().splitlines() + if any(line.split(":")[0] == username for line in passwd): + raise ValueError("account already exists in source image") + if any(line.startswith("phios:") for line in passwd): + run("chroot", str(root), "userdel", "--force", "phios") + if any(line.split(":")[2] == "1000" and not line.startswith("phios:") for line in passwd): + raise ValueError("source has an unexpected UID 1000 account") + groups = (root / "etc/group").read_text().splitlines() + for line in groups: + if line.split(":")[2] == "1000": + if not line.startswith("phios:"): + raise ValueError("source has an unexpected GID 1000 group") + run("chroot", str(root), "groupdel", "phios") + run("chroot", str(root), "groupadd", "--gid", "1000", username) + run("chroot", str(root), "useradd", "--uid", "1000", "--gid", username, "--create-home", + "--groups", "wheel", "--shell", "/bin/bash", username) + run("chroot", str(root), "chpasswd", data=f"{username}:{password}\n") + run("chroot", str(root), "usermod", "--lock", "root") + home = root / "home" / username + for path in [home, home / ".local", home / ".local/state", home / ".local/state/phios"]: + path.mkdir(parents=True, exist_ok=True, mode=0o700) + os.chmod(path, 0o700) + os.chown(path, 1000, 1000) + write(root, "etc/sudoers.d/phios-admin", "%wheel ALL=(ALL:ALL) ALL\n", mode=0o440) + run("chroot", str(root), "visudo", "--check") + write(root, "etc/hostname", hostname + "\n") + write(root, "etc/hosts", f"127.0.0.1 localhost\n::1 localhost\n127.0.1.1 {hostname}\n") + write(root, "etc/greetd/config.toml", '[terminal]\nvt = 1\n[default_session]\n' + 'command = "tuigreet --cmd phios-session"\nuser = "phios-greeter"\n') + write(root, "etc/sysusers.d/phios-system.conf", 'u phios-agent 1001 "Reserved isolated agent" /var/lib/phios-agent /usr/bin/nologin\n' + 'u phios-greeter - "PhiOS Greeter" /var/lib/phios-greeter /usr/bin/nologin\n') + write(root, "etc/tmpfiles.d/phios-system.conf", "d /var/lib/phios-agent 0700 phios-agent phios-agent -\n") + write(root, "etc/fstab", f"UUID={root_uuid} / btrfs defaults,noatime,compress=zstd,subvol=@root 0 0\n" + f"UUID={root_uuid} /home btrfs defaults,noatime,compress=zstd,subvol=@home 0 0\n" + f"UUID={root_uuid} /var/log btrfs defaults,noatime,compress=zstd,subvol=@log 0 0\n" + f"UUID={root_uuid} /.snapshots btrfs defaults,noatime,compress=zstd,subvol=@snapshots 0 0\n" + f"UUID={esp_uuid} /boot vfat defaults,umask=0077 0 2\n") + write(root, "etc/mkinitcpio.conf", "MODULES=(btrfs)\nBINARIES=()\nFILES=()\n" + "HOOKS=(base systemd autodetect microcode modconf kms keyboard sd-vconsole block filesystems fsck)\n") + kernels = list((root / "usr/lib/modules").glob("*/vmlinuz")) + if len(kernels) != 1: + raise ValueError("exactly one packaged Linux kernel is required") + shutil.copyfile(kernels[0], root / "boot/vmlinuz-linux") + write(root, "etc/mkinitcpio.d/linux.preset", 'ALL_config="/etc/mkinitcpio.conf"\nALL_kver="/boot/vmlinuz-linux"\n' + "PRESETS=('default' 'fallback')\ndefault_image=\"/boot/initramfs-linux.img\"\n" + 'fallback_image="/boot/initramfs-linux-fallback.img"\nfallback_options="-S autodetect"\n') + run("arch-chroot", str(root), "mkinitcpio", "-P") + run("bootctl", f"--root={root}", "--esp-path=/boot", "--install-source=image", "--variables=no", "install") + write(root, "boot/loader/loader.conf", "default phios.conf\ntimeout 5\neditor no\n") + 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") + 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') + # The live file:// package repository lives only in the isolated builder. + write(root, "etc/pacman.conf", "[options]\nArchitecture = x86_64\nCheckSpace\n" + "SigLevel = Required DatabaseOptional\nLocalFileSigLevel = Required\n" + "[core]\nInclude = /etc/pacman.d/mirrorlist\n[extra]\nInclude = /etc/pacman.d/mirrorlist\n") + write(root, "etc/pacman.d/mirrorlist", f'Server = https://archive.archlinux.org/repos/{release["arch_snapshot"]}/$repo/os/$arch\n') + + +def apply(plan: dict[str, Any], password: str) -> dict[str, Any]: + identity = plan["target"] + device = identity["path"] + if inventory(device) != identity: + raise ValueError("disk changed after review; no disk writes performed") + verify_zeroed(device, identity["size_bytes"]) + workspace = Path(tempfile.mkdtemp(prefix="phios-install-", dir="/run")) + receipt = {"schema_version": "phios.blank-disk-install.v1", "plan": plan, + "stage": "prepared", "disk_modified": False, "installed": False, "release_ready": False} + mounts: list[Path] = [] + lock = os.open(device, os.O_RDONLY | os.O_NOFOLLOW) + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + try: + if inventory(device) != identity: + raise ValueError("disk changed before partitioning") + source = workspace / "source" + root = workspace / "target" + top = workspace / "top" + for path in [source, root, top]: + path.mkdir(mode=0o700) + run("mount", "-o", "loop,ro,nodev,nosuid", str(SOURCE), str(source)) + mounts.append(source) + if (source / "usr/share/phios/source-commit").read_text().strip() != plan["source_commit"]: + raise ValueError("immutable live source differs from reviewed package source") + receipt.update(stage="partitioning", disk_modified=True) + write(workspace, "receipt.json", json.dumps(receipt, indent=2) + "\n", mode=0o600) + run("sgdisk", "--clear", "--new=1:0:+1G", "--typecode=1:ef00", "--change-name=1:PHIOS_ESP", + "--new=2:0:0", "--typecode=2:8300", "--change-name=2:PHIOS_ROOT", device) + # udev observes the block-device lock. Release it before waiting for + # partition events; otherwise settle can wait on our own open lock. + os.close(lock) + lock = -1 + run("udevadm", "settle") + suffix = "p" if device[-1].isdigit() else "" + esp, system = Path(device + suffix + "1"), Path(device + suffix + "2") + for _ in range(30): + if esp.exists() and system.exists(): + break + time.sleep(0.1) + for partition in [esp, system]: + info = partition.stat() + link = (Path("/sys/dev/block") / f"{os.major(info.st_rdev)}:{os.minor(info.st_rdev)}").resolve() + if not stat.S_ISBLK(info.st_mode) or link.parent.name != Path(device).name: + raise ValueError("new partition does not belong to confirmed disk") + run("mkfs.fat", "-F", "32", "-n", "PHIOS_ESP", str(esp)) + run("mkfs.btrfs", "-L", "PHIOS_ROOT", str(system)) + run("mount", str(system), str(top)) + mounts.append(top) + for subvolume in plan["layout"]["subvolumes"]: + run("btrfs", "subvolume", "create", str(top / subvolume)) + run("mount", "-o", "subvol=@root,compress=zstd", str(system), str(root)) + mounts.append(root) + for subvolume, relative in [("@home", "home"), ("@log", "var/log"), ("@snapshots", ".snapshots")]: + path = root / relative + path.mkdir(parents=True) + run("mount", "-o", f"subvol={subvolume},compress=zstd", str(system), str(path)) + mounts.append(path) + (root / "boot").mkdir() + run("mount", str(esp), str(root / "boot")) + mounts.append(root / "boot") + receipt["stage"] = "copying immutable source" + run("rsync", "-aHAX", "--numeric-ids", "--one-file-system", "--exclude=/home/***", + "--exclude=/boot/***", "--exclude=/var/log/***", str(source) + "/", str(root) + "/") + root_uuid = run("blkid", "-s", "UUID", "-o", "value", str(system)).strip() + esp_uuid = run("blkid", "-s", "UUID", "-o", "value", str(esp)).strip() + if not re.fullmatch(r"[0-9a-f-]{36}", root_uuid) or not re.fullmatch(r"[0-9A-F]{4}-[0-9A-F]{4}", esp_uuid): + raise ValueError("invalid new filesystem UUID") + receipt["stage"] = "configuring installed system" + configure(root, plan["username"], password, plan["hostname"], root_uuid, esp_uuid) + receipt.update(stage="installed; no-ISO boot unqualified", installed=True, + root_uuid=root_uuid, esp_uuid=esp_uuid) + write(root, "var/lib/phios/install-receipt.json", json.dumps(receipt, indent=2) + "\n", mode=0o600) + os.sync() + return receipt + except BaseException as exc: + receipt["error"] = str(exc) + raise + finally: + failures = [] + for path in reversed(mounts): + try: + run("umount", str(path)) + except (ValueError, RuntimeError) as exc: + failures.append(str(exc)) + if lock >= 0: + os.close(lock) + receipt["cleanup_errors"] = failures + write(workspace, "receipt.json", json.dumps(receipt, indent=2) + "\n", mode=0o600) + print(f"Private installation evidence: {workspace}/receipt.json", flush=True) + if failures: + raise RuntimeError("installation mounts remain active; preserve evidence and do not reboot") + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--disk", required=True) + parser.add_argument("--username", required=True) + parser.add_argument("--hostname", default="phios") + parser.add_argument("--plan", action="store_true", help="Read-only inventory; never installs") + args = parser.parse_args() + try: + if os.geteuid() != 0: + raise ValueError("run the root-owned installer with sudo from the live preview") + validate_account(args.username, args.hostname) + if not SOURCE.is_file() or not Path("/sys/firmware/efi").is_dir(): + raise ValueError("the configured PhiOS x64 UEFI live image is required") + for name in REQUIRED: + if shutil.which(name, path=ENV["PATH"]) is None: + raise ValueError(f"required installer program unavailable: {name}") + source = IDENTITY.read_text().strip() + if re.fullmatch(r"[0-9a-f]{40}", source) is None: + raise ValueError("exact installed source identity is required") + identity = inventory(args.disk) + plan, phrase = confirmation(identity, source, args.username, args.hostname) + print(json.dumps(plan, indent=2), flush=True) + if args.plan: + return 0 + if not sys.stdin.isatty() or not sys.stdout.isatty(): + raise ValueError("installation requires an interactive terminal; no bypass is provided") + print("Checking every byte of the selected disk for zeroed contents...", flush=True) + verify_zeroed(args.disk, identity["size_bytes"]) + password = getpass.getpass("New account password (12 or more characters): ") + if len(password) < 12 or ":" in password or "\n" in password or "\r" in password: + raise ValueError("password must be at least 12 characters without colon or line breaks") + if getpass.getpass("Repeat new account password: ") != password: + raise ValueError("passwords do not match; no disk writes performed") + print("This creates an unencrypted experimental installation. All selected disk contents will be replaced.", flush=True) + print("Type the exact confirmation below, or press Ctrl-C to cancel:\n" + phrase, flush=True) + if input("> ") != phrase: + raise ValueError("confirmation did not match; no disk writes performed") + result = apply(plan, password) + print(json.dumps(result, indent=2), flush=True) + print("Remove live media and test the installed boot. Keep this preview available for recovery.") + return 0 + except (KeyboardInterrupt, EOFError): + print("Installation cancelled. Preserve any installation evidence if disk writes had begun.") + return 130 + except (OSError, ValueError, RuntimeError, subprocess.SubprocessError) as exc: + print(f"Installation held: {exc}", file=sys.stderr) + return 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/packaging/linux/installer/phios-install b/packaging/linux/installer/phios-install new file mode 100755 index 00000000..ad107e5c --- /dev/null +++ b/packaging/linux/installer/phios-install @@ -0,0 +1,3 @@ +#!/usr/bin/bash +set -euo pipefail +exec /usr/bin/python -I /usr/lib/phios-installer/install.py "$@" diff --git a/packaging/linux/packages.x86_64 b/packaging/linux/packages.x86_64 index 52cc6d85..89c607aa 100644 --- a/packaging/linux/packages.x86_64 +++ b/packaging/linux/packages.x86_64 @@ -14,5 +14,11 @@ greetd greetd-tuigreet iwd curl +gptfdisk +dosfstools +btrfs-progs +rsync +arch-install-scripts +sudo phios phishell diff --git a/packaging/linux/prepare_profile.py b/packaging/linux/prepare_profile.py index 74e630cf..18a61187 100644 --- a/packaging/linux/prepare_profile.py +++ b/packaging/linux/prepare_profile.py @@ -60,6 +60,7 @@ def write(name: str, content: str) -> None: airootfs_image_type="squashfs" airootfs_image_tool_options=('-comp' 'zstd' '-b' '1M') file_permissions=( + ["/etc/sudoers.d/phios-live-installer"]="0:0:440" ["/usr/local/bin/phios-live-setup"]="0:0:755" ["/usr/local/bin/phios-live-smoke"]="0:0:755" ) @@ -76,7 +77,7 @@ def write(name: str, content: str) -> None: pacman_conf="pacman.conf" airootfs_image_type="squashfs" airootfs_image_tool_options=('-comp' 'zstd' '-b' '1M') -file_permissions=(["/usr/local/bin/phios-live-setup"]="0:0:755") +file_permissions=(["/usr/local/bin/phios-live-setup"]="0:0:755" ["/etc/sudoers.d/phios-live-installer"]="0:0:440") """) entries = destination / "efiboot/loader/entries" for path in entries.iterdir(): @@ -107,6 +108,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") 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') @@ -136,9 +140,10 @@ def write(name: str, content: str) -> None: # must not reset/consume its serial evidence. (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("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=480\nStandardOutput=tty\nStandardError=tty\nTTYPath=/dev/ttyS0\n") + "TimeoutStartSec=1800\nStandardOutput=tty\nStandardError=tty\nTTYPath=/dev/ttyS0\n") (wants / "phios-live-smoke.service").symlink_to("/etc/systemd/system/phios-live-smoke.service") diff --git a/packaging/linux/tests/install_smoke.py b/packaging/linux/tests/install_smoke.py new file mode 100644 index 00000000..03369bbd --- /dev/null +++ b/packaging/linux/tests/install_smoke.py @@ -0,0 +1,136 @@ +"""CI-only live fixture: drives the production CLI on a named disposable disk. + +This file is excluded from normal profiles and never retained by the installer. +No credential, authority or installed automatic login is supplied to a release. +""" +from __future__ import annotations + +import json +import os +import pty +import re +import select +import subprocess +import time +from pathlib import Path + +PASSWORD = "phios-qa-only-2026" # Public ephemeral VM credential, never a release default. + + +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: + pid, fd = pty.fork() + if pid == 0: + os.execv("/usr/bin/phios-install", ["phios-install", "--disk", "/dev/vda", "--username", "operator"]) + text = "" + replied: set[str] = set() + deadline = time.monotonic() + 900 + try: + while time.monotonic() < deadline: + ready, _, _ = select.select([fd], [], [], 1) + if ready: + try: + data = os.read(fd, 65536) + except OSError: + break + if not data: + break + chunk = data.decode(errors="replace") + text += chunk + print(chunk, end="", flush=True) + for prompt in ["New account password (12 or more characters): ", "Repeat new account password: "]: + 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) + 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") + ended, status = os.waitpid(pid, os.WNOHANG) + if ended: + expected = 1 if cancel else 0 + if os.waitstatus_to_exitcode(status) != expected: + raise RuntimeError("production installer returned an unexpected status") + return + 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): + raise RuntimeError("production installer failed or timed out") + finally: + try: + ended, _ = os.waitpid(pid, os.WNOHANG) + if not ended: + os.kill(pid, 9) + os.waitpid(pid, 0) + except ChildProcessError: + pass + os.close(fd) + + +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") + drive_installer(cancel=True) + signatures = json.loads(command("wipefs", "--no-act", "--json", "/dev/vda"))["signatures"] + if signatures: + raise RuntimeError("cancelled installer changed the disk") + print("PHIOS_INSTALL_CANCEL_OK", flush=True) + drive_installer(cancel=False) + root = Path("/run/phios-ci-installed") + root.mkdir(mode=0o700) + mounts = [] + try: + command("mount", "-o", "subvol=@root", "/dev/vda2", str(root)) + mounts.append(root) + command("mount", "-o", "subvol=@home", "/dev/vda2", str(root / "home")) + mounts.append(root / "home") + command("mount", "/dev/vda1", str(root / "boot")) + mounts.append(root / "boot") + if ("initial_session" in (root / "etc/greetd/config.toml").read_text() or + (root / "etc/sudoers.d/phios-live-installer").exists() or + list((root / "usr/local/bin").glob("phios-live-*")) or + list((root / "etc/systemd/system").glob("phios-live-*.service"))): + raise RuntimeError("live credentials, autologin or test fixtures survived installation") + seed = ''' +from pathlib import Path +from phios.memory import MemoryOperatorRuntime, MemoryRecord, MemoryRuntimeConfig +from phios.state_recovery import backup +root=Path('/home/operator/.local/state/phios') +runtime=MemoryOperatorRuntime(state_root=root/'memory', + config=MemoryRuntimeConfig(enabled=True,principal_id='operator',scopes=('private',), + classifications=('operator',),retention_policy_id='retain'), + allowed_permissions=('memory.write','memory.read')) +record=MemoryRecord.build(record_id='installed-proof',revision=1,source_id='operator',source_kind='human', + provenance_refs=(),created_at='2026-09-30T00:00:00+00:00',scope_id='private',classification='operator', + retention_policy_id='retain',expires_at=None,epistemic_kind='source',text='Persist this acknowledged installed-OS record') +assert runtime.put(record,operation_id='installed-proof-put',task_id='ci-only').status=='ok' +assert runtime.store.get('installed-proof')==record +backup(root,root.parent/'phios-ci-data-backup') +print('PHIOS_INSTALLED_SEED_OK:'+record.record_sha256) +''' + print(command("arch-chroot", str(root), "runuser", "-u", "operator", "--", "python", "-c", seed), flush=True) + # Serial access is injected only into this disposable installed test + # target so the host can exercise password/PAM login and data checks. + entry = root / "boot/loader/entries/phios.conf" + entry.write_text(entry.read_text().rstrip() + " console=tty0 console=ttyS0,115200\n") + getty = root / "etc/systemd/system/getty.target.wants/serial-getty@ttyS0.service" + getty.parent.mkdir(parents=True, exist_ok=True) + getty.symlink_to("/usr/lib/systemd/system/serial-getty@.service") + receipt = json.loads((root / "var/lib/phios/install-receipt.json").read_text()) + os.sync() + finally: + for path in reversed(mounts): + command("umount", str(path)) + print("PHIOS_INSTALLED_DISK_OK:" + receipt["plan"]["source_commit"], flush=True) + + +if __name__ == "__main__": + main() diff --git a/packaging/linux/tests/installed_probe.py b/packaging/linux/tests/installed_probe.py new file mode 100644 index 00000000..020c8190 --- /dev/null +++ b/packaging/linux/tests/installed_probe.py @@ -0,0 +1,64 @@ +"""Run as the password-authenticated test user on the installed disposable VM.""" +from __future__ import annotations + +import json +import os +import subprocess +import time +import urllib.request +from pathlib import Path + +from phios.memory import MemoryStore +from phios.state_io import append_jsonl, read_jsonl +from phios.state_recovery import restore, verify_backup + + +def probe(source: str, phase: int) -> None: + root = Path.home() / ".local/state/phios" + assert os.getuid() == 1000 + assert Path("/usr/share/phios/source-commit").read_text().strip() == source + assert Path("/sys/firmware/efi").is_dir() + assert "archisobasedir" not in Path("/proc/cmdline").read_text() + assert not Path("/run/archiso/bootmnt").exists() + assert root.stat().st_mode & 0o777 == 0o700 + record = MemoryStore(root / "memory/canonical.sqlite3").get("installed-proof") + assert record is not None and record.text == "Persist this acknowledged installed-OS record" + backup = root.parent / "phios-ci-data-backup" + verify_backup(backup) + restored = root.parent / "phios-ci-restored" + if phase == 1: + restore(backup, restored) + append_jsonl(root / "qa/acknowledged.jsonl", {"source_commit": source, "execution_authority": False}) + assert MemoryStore(restored / "memory/canonical.sqlite3").get("installed-proof") == record + 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() + # 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): + try: + with urllib.request.urlopen("http://127.0.0.1:3969/api/v1/health", timeout=2) as response: + assert response.status == 200 + with urllib.request.urlopen("http://127.0.0.1:3969/", timeout=2) as response: + assert response.status == 200 + # Observer health precedes browser startup. Require the whole + # supervised desktop to be ready within the same bounded wait. + if any(subprocess.run(["pgrep", "-u", "1000", "-x", name], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL).returncode for name in ["wayfire", "chromium"]): + time.sleep(1) + continue + if subprocess.run(["systemctl", "--user", "is-active", "phios-observer.service", "phios-browser.service"], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=5).returncode: + time.sleep(1) + continue + break + except OSError: + time.sleep(1) + else: + subprocess.run(["journalctl", "--user", "--no-pager", "-n", "60", "-u", "phios-browser.service", + "-u", "phios-curiosity-reader.service", "-u", "phios-observer.service"], timeout=15) + raise RuntimeError("installed graphical login did not start the complete supervised desktop") + time.sleep(2) # Preserve a rendered application screenshot after process readiness. + boot_id = Path("/proc/sys/kernel/random/boot_id").read_text().strip().replace("-", "") + print("PHIOS_INSTALLED_CHECK_OK:" + json.dumps({"source_commit": source, "phase": phase, + "boot_id": boot_id, "record_sha256": record.record_sha256}), flush=True) diff --git a/packaging/linux/tests/live-smoke.sh b/packaging/linux/tests/live-smoke.sh index a17f0929..6640ec38 100755 --- a/packaging/linux/tests/live-smoke.sh +++ b/packaging/linux/tests/live-smoke.sh @@ -73,3 +73,6 @@ echo PHIOS_SESSION_RESTART_OK python -c 'import phios, phios.mcp.server, phios.ghostwalk_operator; print("Installed Python runtime:",phios.__version__)' phi version printf 'PHIOS_BOOT_OK:%s:%s\n' "$(cat /usr/share/phios/source-commit)" "$(tr -d '-' < /proc/sys/kernel/random/boot_id)" +if [[ -b /dev/vda ]]; then + python /usr/local/bin/phios-live-install-smoke.py +fi diff --git a/packaging/linux/tests/qemu_install.py b/packaging/linux/tests/qemu_install.py new file mode 100644 index 00000000..d708a512 --- /dev/null +++ b/packaging/linux/tests/qemu_install.py @@ -0,0 +1,223 @@ +"""Qualify installation only on a fresh, locally created 32 GiB virtual disk.""" +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import re +import shutil +import socket +import subprocess +import time +from pathlib import Path +from typing import Any + +from qemu_boot import capture_display, enter_live_login, qmp_request + +PASSWORD = "phios-qa-only-2026" # Same public ephemeral test credential as live fixture. + + +def send_text(qmp: Path, value: str) -> None: + for key in [*value, "ret"]: + code = "minus" if key == "-" else key + qmp_request(qmp, {"execute": "send-key", "arguments": { + "keys": [{"type": "qcode", "data": code}], "hold-time": 80}}) + time.sleep(0.12) + + +def stop(process: subprocess.Popen[Any], *, abrupt: bool = False) -> None: + if abrupt: + process.kill() + else: + process.terminate() + try: + process.wait(timeout=15) + except subprocess.TimeoutExpired: + process.kill() + process.wait(timeout=5) + + +def qualify(iso: Path, source: str, output: Path) -> 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) + code = Path("/usr/share/OVMF/OVMF_CODE_4M.fd") + variables = output / "OVMF_VARS.fd" + shutil.copyfile("/usr/share/OVMF/OVMF_VARS_4M.fd", variables) + disk = output / "target.qcow2" + # There is no caller-supplied device/disk option. Never attach a host block + # device, existing image, network, shared folder or other user's data. + subprocess.run(["qemu-img", "create", "-f", "qcow2", str(disk), "32G"], check=True) + accelerated = os.access("/dev/kvm", os.R_OK | os.W_OK) + accelerator = "kvm" if accelerated else "tcg" + common = ["qemu-system-x86_64", "-machine", f"q35,accel={accelerator}", "-cpu", + "host" if accelerated else "max", "-m", "4096", "-smp", "2", + "-drive", f"if=pflash,format=raw,readonly=on,file={code}", + "-drive", f"if=pflash,format=raw,file={variables}", + "-drive", f"file={disk},if=none,id=target,format=qcow2", + "-device", "virtio-blk-pci,drive=target,serial=PHIOS_CI_BLANK,bootindex=2", + "-nic", "none", "-vga", "none", "-device", "virtio-vga", + "-display", "none", "-monitor", "none"] + digest = hashlib.sha256() + with iso.open("rb") as handle: + for block in iter(lambda: handle.read(1024**2), b""): + digest.update(block) + receipt: dict[str, Any] = {"schema_version": "phios.installed-boot-evidence.v1", "source_commit": source, + "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} + 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:])) + # 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]: + 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", + "-qmp", f"unix:{qmp},server=on,wait=off"] + receipt["commands"].append(command) + with (output / f"installed-{phase}-qemu.log").open("w") as log: + process = subprocess.Popen(command, stdout=log, stderr=subprocess.STDOUT) + try: + deadline = time.monotonic() + 900 + while not serial_socket.exists() and time.monotonic() < deadline: + if process.poll() is not None: + raise RuntimeError("installed VM exited before serial transport") + time.sleep(0.1) + with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as channel: + channel.settimeout(1) + channel.connect(str(serial_socket)) + text = "" + with (output / f"installed-{phase}-serial.log").open("wb") as transcript: + def wait_for(pattern: str) -> re.Match[str]: + nonlocal text + while time.monotonic() < deadline: + match = re.search(pattern, text) + if match: + return match + if process.poll() is not None: + raise RuntimeError("installed guest exited during validation") + try: + chunk = channel.recv(65536) + except socket.timeout: + continue + if not chunk: + raise RuntimeError("installed serial transport closed") + transcript.write(chunk) + transcript.flush() + text += chunk.decode(errors="replace") + if "Traceback (most recent call last)" in text: + # A traceback can arrive in several serial + # reads. Preserve its actual exception and + # failing line before stopping the guest. + drain_deadline = time.monotonic() + 3 + while time.monotonic() < drain_deadline: + try: + extra = channel.recv(65536) + except socket.timeout: + continue + if not extra: + break + transcript.write(extra) + transcript.flush() + text += extra.decode(errors="replace") + print("\n".join(text.splitlines()[-40:])) + raise RuntimeError("installed data or session validation failed") + raise RuntimeError("installed password login/qualification timed out") + + wait_for(r"login: ") + channel.sendall(b"operator\n") + wait_for(r"Password:") + channel.sendall((PASSWORD + "\n").encode()) + time.sleep(2) + channel.sendall(b"printf 'PHIOS_LOGIN_OK:%s\\n' \"$(id -u)\"\n") + wait_for(r"PHIOS_LOGIN_OK:1000") + time.sleep(3) + capture_display(qmp, output, name=f"screen-installed-{phase}-greeter") + qmp_request(qmp, {"execute": "send-key", "arguments": {"keys": [ + {"type": "qcode", "data": key} for key in ["ctrl", "alt", "f1"]]}}) + time.sleep(1) + 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" + # 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 + + "\nPHIOS_INSTALLED_PROBE\n").encode()) + result = wait_for(r"PHIOS_INSTALLED_CHECK_OK:(\{[^\r\n]+\})") + details = json.loads(result[1]) + if details["source_commit"] != source or details["phase"] != phase: + raise RuntimeError("installed receipt identity mismatch") + receipt["boot_ids"].append(details["boot_id"]) + receipt["record_sha256"] = details["record_sha256"] + capture_display(qmp, output, name=f"screen-installed-{phase}") + finally: + if process.poll() is None and not (output / f"screen-installed-{phase}.ppm").exists(): + try: + capture_display(qmp, output, name=f"screen-installed-{phase}-failure") + except (OSError, ValueError, RuntimeError): + pass + stop(process, abrupt=(phase == 1)) + if len(set(receipt["boot_ids"])) != 2: + raise RuntimeError("a distinct installed reboot was not observed") + receipt["no_iso_boot_passed"] = True + receipt["abrupt_virtual_restart_passed"] = True + print("Disposable installation, no-ISO graphical login, data restore and abrupt virtual restart passed") + except BaseException as exc: + receipt["error"] = str(exc) + raise + finally: + (output / "installed-evidence.json").write_text(json.dumps(receipt, indent=2) + "\n") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--iso", required=True, type=Path) + parser.add_argument("--source", required=True) + parser.add_argument("--output", required=True, type=Path) + args = parser.parse_args() + qualify(args.iso, args.source, args.output.resolve()) diff --git a/tests/test_blank_disk_installer_v01.py b/tests/test_blank_disk_installer_v01.py new file mode 100644 index 00000000..543d8779 --- /dev/null +++ b/tests/test_blank_disk_installer_v01.py @@ -0,0 +1,116 @@ +from __future__ import annotations + +import importlib.util +from pathlib import Path +from typing import Any + +import pytest + +FILE = Path(__file__).resolve().parents[1] / "packaging/linux/installer/install.py" +spec = importlib.util.spec_from_file_location("phios_blank_disk_installer", FILE) +assert spec is not None and spec.loader is not None +installer = importlib.util.module_from_spec(spec) +spec.loader.exec_module(installer) + + +def _disk(**changes: Any) -> dict[str, Any]: + return {"path": "/dev/vda", "type": "disk", "ro": False, "size": 32 * 1024**3, + "serial": "test-only-disposable-disk", "model": "Virtual disk", "maj:min": "252:0", + "mountpoints": [None], "fstype": None, "pttype": None, **changes} + + +@pytest.mark.parametrize("changes,busy,signatures", [ + ({"children": [{"path": "/dev/vda1"}]}, False, []), + ({"mountpoints": ["/"]}, False, []), + ({}, True, []), + ({}, False, [{"type": "gpt"}]), + ({"fstype": "btrfs"}, False, []), + ({"type": "loop"}, False, []), + ({"ro": True}, False, []), + ({"serial": None}, False, []), + ({"serial": "control\x1bsequence"}, False, []), + ({"path": "/dev/disk/by-id/a"}, False, []), + ({"size": 8 * 1024**3}, False, []), +]) +def test_unsafe_targets_are_refused(changes: dict[str, Any], busy: bool, signatures: list[Any]) -> None: + with pytest.raises(ValueError): + installer.validate_inventory(_disk(**changes), signatures, busy=busy) + + +def test_confirmation_binds_exact_identity_source_account_and_layout() -> None: + identity = installer.validate_inventory(_disk(), [], busy=False) + plan, phrase = installer.confirmation(identity, "a" * 40, "operator", "phios") + assert phrase.startswith("INSTALL /dev/vda ") + for changed in [{**identity, "serial_or_wwn": "replaced"}, {**identity, "size_bytes": 64 * 1024**3}]: + assert installer.confirmation(changed, "a" * 40, "operator", "phios")[1] != phrase + assert installer.confirmation(identity, "b" * 40, "operator", "phios")[1] != phrase + assert installer.confirmation(identity, "a" * 40, "someone", "phios")[1] != phrase + assert plan["encrypted"] is False and plan["firmware_variables_changed"] is False + assert plan["release_ready"] is False + + +def test_signature_free_hidden_data_is_still_refused_without_writes(tmp_path: Path) -> None: + disk = tmp_path / "read-only-test-image" + data = bytes(1024**2) + b"important unsigned data" + bytes(1024**2) + disk.write_bytes(data) + with pytest.raises(ValueError, match="not fully zeroed"): + installer.verify_zeroed(str(disk), len(data)) + assert disk.read_bytes() == data + disk.write_bytes(bytes(len(data))) + installer.verify_zeroed(str(disk), len(data)) + with pytest.raises(ValueError, match="size changed"): + installer.verify_zeroed(str(disk), len(data) + 1) + + +def test_changed_disk_after_confirmation_never_reaches_write_commands(monkeypatch: pytest.MonkeyPatch) -> None: + identity = installer.validate_inventory(_disk(), [], busy=False) + plan, _ = installer.confirmation(identity, "a" * 40, "operator", "phios") + monkeypatch.setattr(installer, "inventory", lambda _: {**identity, "serial_or_wwn": "changed"}) + monkeypatch.setattr(installer, "run", lambda *args, **kwargs: pytest.fail(f"unexpected command {args}")) + monkeypatch.setattr(installer.tempfile, "mkdtemp", lambda **kwargs: pytest.fail("unexpected writes")) + with pytest.raises(ValueError, match="changed after review"): + installer.apply(plan, "synthetic-test-password") + + +def test_rejected_confirmation_never_calls_installer( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], +) -> None: + source = tmp_path / "source.sfs" + source.touch() + identity_file = tmp_path / "source-commit" + identity_file.write_text("a" * 40) + monkeypatch.setattr(installer, "SOURCE", source) + monkeypatch.setattr(installer, "IDENTITY", identity_file) + monkeypatch.setattr(installer.os, "geteuid", lambda: 0) + original_is_dir = Path.is_dir + monkeypatch.setattr(Path, "is_dir", lambda p: True if str(p) == "/sys/firmware/efi" else original_is_dir(p)) + monkeypatch.setattr(installer.shutil, "which", lambda *args, **kwargs: "/usr/bin/unused") + monkeypatch.setattr(installer, "inventory", lambda _: installer.validate_inventory(_disk(), [], busy=False)) + monkeypatch.setattr(installer, "verify_zeroed", lambda *args: None) + monkeypatch.setattr(installer.getpass, "getpass", lambda _: "synthetic-test-password") + monkeypatch.setattr(installer.sys.stdin, "isatty", lambda: True) + monkeypatch.setattr(installer.sys.stdout, "isatty", lambda: True) + monkeypatch.setattr(installer.sys, "argv", ["phios-install", "--disk", "/dev/vda", "--username", "operator"]) + monkeypatch.setattr("builtins.input", lambda _: "cancel") + monkeypatch.setattr(installer, "apply", lambda *args: pytest.fail("disk install must not begin")) + assert installer.main() == 1 + assert "confirmation did not match" in capsys.readouterr().err + + +def test_generated_file_replaces_absolute_source_symlink_without_following_it(tmp_path: Path) -> None: + unrelated = tmp_path / "unrelated" + unrelated.write_text("preserve") + root = tmp_path / "target" + (root / "etc").mkdir(parents=True) + (root / "etc/os-release").symlink_to(unrelated) + installer.write(root, "etc/os-release", "ID=phios\n") + assert unrelated.read_text() == "preserve" + assert not (root / "etc/os-release").is_symlink() + assert (root / "etc/os-release").read_text() == "ID=phios\n" + + +@pytest.mark.parametrize("username,hostname", [("root", "phios"), ("phios", "phios"), + ("operator;id", "phios"), ("operator", "host\nname")]) +def test_account_inputs_cannot_select_live_accounts_or_inject_commands(username: str, hostname: str) -> None: + with pytest.raises(ValueError): + installer.validate_account(username, hostname)