From a8dda8cfcc9d86401610fdbdd7fdbdb6b7892087 Mon Sep 17 00:00:00 2001 From: Michael Hughes Date: Wed, 30 Sep 2026 20:11:44 -0700 Subject: [PATCH 1/3] Constrain one installed Linux proof effect to a separate agent principal and single-use lease --- docs/os/HARDWARE_QUALIFICATION.md | 76 ++++ docs/os/IMPLEMENTATION_STATUS.md | 2 +- docs/os/LINUX_PROOF_WORKFLOW.md | 79 ++++ docs/os/OS_MAINTENANCE.md | 7 + docs/os/RELEASE_CONTRACT.md | 4 +- packaging/arch/phios/PKGBUILD | 5 + packaging/linux/hardware_report.py | 62 +++ packaging/linux/proof/broker.py | 370 ++++++++++++++++++ packaging/linux/proof/phios-linux-proof | 3 + .../linux/proof/phios-proof-proposer.service | 21 + packaging/linux/proof/propose.py | 49 +++ packaging/linux/tests/proof_smoke.py | 134 +++++++ packaging/linux/tests/qemu_install.py | 19 + tests/test_linux_proof_broker_v01.py | 210 ++++++++++ 14 files changed, 1039 insertions(+), 2 deletions(-) create mode 100644 docs/os/HARDWARE_QUALIFICATION.md create mode 100644 docs/os/LINUX_PROOF_WORKFLOW.md create mode 100644 packaging/linux/hardware_report.py create mode 100644 packaging/linux/proof/broker.py create mode 100644 packaging/linux/proof/phios-linux-proof create mode 100644 packaging/linux/proof/phios-proof-proposer.service create mode 100644 packaging/linux/proof/propose.py create mode 100644 packaging/linux/tests/proof_smoke.py create mode 100644 tests/test_linux_proof_broker_v01.py diff --git a/docs/os/HARDWARE_QUALIFICATION.md b/docs/os/HARDWARE_QUALIFICATION.md new file mode 100644 index 00000000..245e7527 --- /dev/null +++ b/docs/os/HARDWARE_QUALIFICATION.md @@ -0,0 +1,76 @@ +# Named hardware qualification handoff + +The proposed first physical target is Mikey's Windows 11 Skytech desktop: +Core Ultra 9 285K, RTX 5070 12 GB and 32 GB DDR5. These are supplied candidate +details, not observed Linux compatibility. No physical hardware is qualified. +The successful QEMU tests use software rendering and provide no evidence for +this GPU, motherboard firmware, audio, network radios or physical power loss. + +| Target | Current evidence | Gate | +| --- | --- | --- | +| Disposable x64 UEFI/KVM VM, 2 CPUs, 4 GiB RAM, 32-GiB disk | Live/installed login, persistent data, bounded signed update/interruption and matched recovery passed | Fixture-free exact final artifact and Linux proof workflow must also pass | +| Supplied Skytech/Core Ultra 9/RTX 5070 machine | No boot or driver observations | Live boot, GPU/input/network/audio/firmware tests first | +| Dedicated empty physical test disk | No selected disk or test | Exact installer identity/blankness/confirmation, no-media boot, persistence, update and recovery | + +## Exact candidate first + +Use only the normal image from the **Fixture-free OS candidate (unpublished)** +workflow, after its exact source/ISO receipt passes. Do not use the separate +QA image containing disposable test credentials/services. These images are +unsigned unpublished previews, not supported installers. Verify the downloaded +ISO against its exact `SHA256SUMS`, provenance and recorded qualification +receipt before preparing removable media. On Windows: + +```powershell +Get-FileHash .\phios-linux-0.1.0-alpha.1-x86_64.iso -Algorithm SHA256 +``` + +Compare the complete digest, not a filename or another build's successful test. +The first physical gate is a live removable-media boot with no installation. +Document actual firmware configuration, UEFI mode and Secure Boot status; this +candidate does not support Secure Boot or BIOS. Preserve the existing Windows +installation and its independent backup. A hardware installation test requires +a separately identified dedicated empty disk; the current installer does not +support dual boot, partition reuse or preserving contents on its target. + +## Observations and manual results + +Inside the exact normal live image, run as the ordinary user: + +```bash +phios-hardware-report --iso-sha256 VERIFIED_ISO_SHA256 > hardware-observation.json +``` + +Replace the placeholder. The collector reads public source/kernel/UEFI, +board/firmware, PCI IDs/bound drivers and audio-card count. It performs no +effects, probes no credentials and records no hostname, account name, disk +serial, MAC/IP address, Wi-Fi SSID or user-state content. It marks the supplied +ISO hash as supplied, because it does not independently read the downloaded +ISO bytes. Absence of virtualization detection does not prove physical hardware. +All compatibility results remain `not tested` until actual observations exist. + +Record pass/fail/not available with evidence for resolution/rendering and +multiple displays; keyboard/mouse/keymap; wired networking and Wi-Fi association, +DHCP/DNS; audio playback/recording; sleep/resume; shutdown/restart; and storage +visibility. Record missing drivers and services honestly. Audio/session locking +and Wi-Fi configuration are not currently qualified product features. A blank +audio-card count or successful PCI enumeration is not audio/GPU compatibility. +Resolve observed blockers, build a new exact candidate and repeat affected +tests before moving to installation. + +Only after choosing a dedicated empty test disk should the operator review the +production installer plan and explicit confirmation described in INSTALLATION.md. +Then prove password-authenticated no-media boots, acknowledged canonical data +after restart, separate verified data-only backup, the actual signed target +transition, interrupted update, matched live-media recovery, preserved data and +inactive old authority. Physical power-loss testing is a separate storage gate, +not implied by terminating QEMU. Preserve failures and identify the exact +machine, source, ISO and transition; do not infer a supported hardware family. + +## Release holds + +Hardware results, the independently authenticated maintainer release public key +and full fingerprint, actual signed final transition, and third-party source/ +license delivery review are still missing. RELEASE_ARTIFACTS.md describes the +remaining signing/publication gates. No release key is generated on behalf of +the maintainer and no test key becomes a release identity. diff --git a/docs/os/IMPLEMENTATION_STATUS.md b/docs/os/IMPLEMENTATION_STATUS.md index daeef0b5..ad947a20 100644 --- a/docs/os/IMPLEMENTATION_STATUS.md +++ b/docs/os/IMPLEMENTATION_STATUS.md @@ -15,7 +15,7 @@ proof that PhiOS is a completed OS. Preserve the repository AGENTS.md rules. | 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 | 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 | +| R9: Qualify hardware and one Linux governed workflow | Candidate UID-separated installed-only proof-note broker, canonical bound single-use lease, independent protected ledger and read-only hardware collector/protocol | 21 focused denial/cancel/expiry/replay/durability/binding tests passed; actual sudo/PAM/UID 1001 and post-recovery VM qualification pending; supplied Skytech target remains physically unqualified | | R10: Sign and publish the exact qualified artifact | Exact native/Python/npm inventory, supplier license notices, CycloneDX SBOM and source/ISO/artifact provenance; fixture-free build/normal PAM qualification workflow | Eight focused inventory/refusal tests and validation against pinned official CycloneDX 1.6 schemas passed locally; actual image/VM CI pending; third-party source/license review, release identity, signatures and maintainer publication remain held | ## First builder handoff diff --git a/docs/os/LINUX_PROOF_WORKFLOW.md b/docs/os/LINUX_PROOF_WORKFLOW.md new file mode 100644 index 00000000..827c1194 --- /dev/null +++ b/docs/os/LINUX_PROOF_WORKFLOW.md @@ -0,0 +1,79 @@ +# Bounded installed Linux proof workflow + +This candidate demonstrates one harmless real Linux filesystem effect. It +creates one fixed 57-byte proof note inside an independent protected store. +It is not a desktop automation API, AI agent, shell executor or generic file +writer. The existing Ghost Walk browser decision/binding/lease routes remain +held. Public EffectIntent, EnforcementProfile, AuthorityEpoch and ActionLease +contracts are reused without modifying private PhiKernel/TIEKAT internals. + +## Operator sequence + +Use an experimental installed PhiOS system, with the installer-created UID +1000 account and its ordinary password-authenticated sudo administration. +The public volatile live account cannot run this broker. There is no new +NOPASSWD rule and no unattended approval flag. + +```bash +sudo systemctl start phios-proof-proposer.service +sudo phios-linux-proof inspect +sudo phios-linux-proof approve +sudo phios-linux-proof execute --approval APPROVAL_SHA256 +``` + +Replace `APPROVAL_SHA256` with the exact identity returned by approval. Review +the captured proposal, actual source/boot identity, fixed note hash, protected +store, single use and 60-second lifetime. Approval requires typing the complete +`APPROVE SHA256` review phrase. Anything else cancels before creating an +approval, binding, lease or effect. The proposal and actual OS identity are +checked again after review. Run the separately requested effect within 60 +seconds. If it expires, make and review a new approval; do not edit records. + +The static one-shot proposer runs as UID 1001 `phios-agent`, with a nologin +account, no sudo, no capabilities, no privilege escalation, a private network, +protected home/system paths and one writable private proposal directory. It +is not enabled at boot. It observes public source/boot identity and writes an +untrusted, zero-authority proposal for the fixed note. A browser, pseudo-TTY +or agent-owned proposal is never approval. A malicious process running as the +installed administrator, cached administrator sudo or arbitrary root remains +outside this principal-separation boundary; TTY access alone is not human +authentication. Sudo/PAM separates the installed administrator from the +agent principal, rather than authenticating an AI judgment. + +The root-owned Python-isolated broker accepts only that fixed proposal path, +principal, capability and text. It opens bounded regular singly linked input +without following links and captures bytes before review. It binds the actual +source and boot to the decision, exact intent, enforcement profile, capability +binding and canonical single-use ActionLease. The note destination cannot be +supplied by the agent or caller. Root-owned directory descriptors, exclusive +creation and fixed bytes constrain this effect; signed administrator code is +trusted, and a compromised root is not sandboxed by these checks. + +## Consumption, verification and recovery + +`/.snapshots/phios-linux-proof` stores immutable SHA-256-named approvals, +consumption records, notes and post-effect receipts. It is in the independent +`@snapshots` subvolume, outside `@root` rollback snapshots and user data-only +backups. Records are root-owned; directories are created 0700 and files 0600. +The broker flushes the consumption record before creating a note. A failure or +interruption may leave a consumed lease and incomplete effect requiring review; +it never silently makes that lease reusable. It flushes the note, independently +opens and verifies its exact bytes, then flushes a separate linked receipt. +No executable authority follows from viewing a receipt. + +Both wall-clock validity and Linux `CLOCK_BOOTTIME` expiry are enforced, including +time spent suspended. A new boot or source identity invalidates old approvals. +OS recovery preserves the independent ledger; it cannot reinstate a rolled-back +lease. Canonical user data and its zero-authority history stay separate. This +extends the maintenance boundary only for this fixed broker store; custom +authority stores still need an explicit reviewed recovery procedure. Losing +the disk loses this ledger, and copying files is not authority enrollment. + +Twenty-one focused tests passed for exact binding/readback, cancellation, changed +review, scope/principal/source/boot denial, expiry including clock rollback, +replay, corrupt/linked records, symlink redirection and durable consumption +failure. The external installed-VM fixture uses ordinary sudo/PAM, the actual +UID 1001 service and production commands. It must prove agent store/broker +denial, cancellation, one verified note, replay and real 60-second expiry, then +historical-authority refusal after restart and matched OS recovery. End-to-end +VM qualification is pending; this document grants no hardware/release readiness. diff --git a/docs/os/OS_MAINTENANCE.md b/docs/os/OS_MAINTENANCE.md index 4363bd2b..2e5c6085 100644 --- a/docs/os/OS_MAINTENANCE.md +++ b/docs/os/OS_MAINTENANCE.md @@ -224,3 +224,10 @@ 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. + +The bounded Linux proof broker stores its protected history in the independent +`@snapshots/phios-linux-proof` directory. Its single-use approvals are bound to +the current boot and source, and expire by both wall clock and CLOCK_BOOTTIME. +Root/EFI recovery preserves that ledger and cannot make an old-boot approval +active. See LINUX_PROOF_WORKFLOW.md; custom authority stores remain outside +this fixed procedure. diff --git a/docs/os/RELEASE_CONTRACT.md b/docs/os/RELEASE_CONTRACT.md index 8c4cd21a..581800c3 100644 --- a/docs/os/RELEASE_CONTRACT.md +++ b/docs/os/RELEASE_CONTRACT.md @@ -19,7 +19,9 @@ Python package versions and OS versions are independent. OS tags start with The default preview does not run an AI model or an autonomous agent. Ollama, vector memory, OCR, Windows UI Automation/GhostWalk and hardware bridges are optional or platform-specific. Missing capabilities must show unavailable. -No Linux desktop effect executor or lease issuance is advertised. The browser +No general Linux desktop effect executor or lease issuance is advertised. A +separate installed-only, explicitly invoked proof-note candidate is described +in LINUX_PROOF_WORKFLOW.md; its untrusted agent proposal grants no authority. The browser cannot mint operator approvals; see OPERATOR_AUTHORIZATION.md. ## Deliberately unqualified capabilities diff --git a/packaging/arch/phios/PKGBUILD b/packaging/arch/phios/PKGBUILD index 86c74aaa..8a7f1e76 100644 --- a/packaging/arch/phios/PKGBUILD +++ b/packaging/arch/phios/PKGBUILD @@ -33,4 +33,9 @@ package() { 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" + install -Dm644 packaging/linux/proof/broker.py "$pkgdir/usr/lib/phios-proof/broker.py" + install -Dm644 packaging/linux/proof/propose.py "$pkgdir/usr/lib/phios-proof/propose.py" + install -Dm755 packaging/linux/proof/phios-linux-proof "$pkgdir/usr/bin/phios-linux-proof" + install -Dm644 packaging/linux/proof/phios-proof-proposer.service "$pkgdir/usr/lib/systemd/system/phios-proof-proposer.service" + install -Dm755 packaging/linux/hardware_report.py "$pkgdir/usr/bin/phios-hardware-report" } diff --git a/packaging/linux/hardware_report.py b/packaging/linux/hardware_report.py new file mode 100644 index 00000000..b3f52743 --- /dev/null +++ b/packaging/linux/hardware_report.py @@ -0,0 +1,62 @@ +#!/usr/bin/python +"""Collect bounded public hardware observations; no qualification or authority.""" +from __future__ import annotations + +import argparse +import json +import os +import re +import subprocess +from datetime import UTC, datetime +from pathlib import Path + + +def value(path: Path, maximum: int = 256) -> str | None: + try: + with path.open() as handle: + data = handle.read(maximum + 1).strip() + return data if len(data) <= maximum and all(ord(c) >= 32 for c in data) else None + except OSError: + return None + + +def observe(iso_sha256: str | None) -> dict[str, object]: + source = value(Path('/usr/share/phios/source-commit')) + if not source or not re.fullmatch('[0-9a-f]{40}', source): + raise ValueError('run this inside the built PhiOS image') + if iso_sha256 is not None and not re.fullmatch('[0-9a-f]{64}', iso_sha256): + raise ValueError('supplied ISO identity must be a lowercase SHA-256') + devices = [] + for device in sorted(Path('/sys/bus/pci/devices').iterdir()): + if len(devices) >= 1024: + raise ValueError('PCI observation exceeds its bound') + devices.append({'pci_address': device.name, 'vendor_id': value(device / 'vendor'), + 'device_id': value(device / 'device'), 'class_id': value(device / 'class'), + 'bound_driver': (device / 'driver').resolve().name if (device / 'driver').exists() else None}) + try: + detected = subprocess.run(['/usr/bin/systemd-detect-virt'], text=True, capture_output=True, timeout=5) + virtualization = detected.stdout.strip()[:64] if detected.returncode == 0 else 'not detected; physical hardware unproven' + except (OSError, subprocess.SubprocessError): + virtualization = 'unavailable' + return {'schema_version': 'phios.hardware-observation.v1', 'observed_at': datetime.now(UTC).isoformat(), + 'source_commit': source, 'supplied_iso_sha256': iso_sha256, 'iso_bytes_independently_verified': False, + 'kernel': os.uname().release, 'architecture': os.uname().machine, + 'uefi_observed': Path('/sys/firmware/efi').is_dir(), 'virtualization_observation': virtualization, + 'board_vendor': value(Path('/sys/class/dmi/id/board_vendor')), + 'board_model': value(Path('/sys/class/dmi/id/board_name')), + 'firmware_version': value(Path('/sys/class/dmi/id/bios_version')), 'pci_devices': devices, + 'audio_cards_observed': len(list(Path('/sys/class/sound').glob('card[0-9]*'))), + 'physical_hardware_qualified': False, 'release_ready': False, 'execution_authority': False, + 'manual_tests': {name: 'not tested' for name in ['display_gpu', 'keyboard_mouse', 'wired_network', + 'wifi', 'audio', 'sleep_resume', 'shutdown_restart', 'dedicated_disk_install', 'data_persistence', + 'signed_update', 'interrupted_update', 'matched_recovery']}} + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--iso-sha256', help='Previously verified candidate hash; marked supplied, not independently verified here') + args = parser.parse_args() + try: + print(json.dumps(observe(args.iso_sha256), indent=2, sort_keys=True, allow_nan=False)) + except (OSError, ValueError) as exc: + parser.exit(1, 'Hardware observation held: ' + str(exc) + '\n') diff --git a/packaging/linux/proof/broker.py b/packaging/linux/proof/broker.py new file mode 100644 index 00000000..61e0dfc7 --- /dev/null +++ b/packaging/linux/proof/broker.py @@ -0,0 +1,370 @@ +"""Installed-only root broker for one boot-bound, single-use proof-note effect.""" +from __future__ import annotations + +import argparse +import fcntl +import hashlib +import json +import os +import pwd +import re +import stat +import sys +import time +import uuid +from contextlib import contextmanager +from datetime import UTC, datetime, timedelta +from pathlib import Path +from typing import Any, Iterator, TextIO + +from phios.action_lease import ActionLease, evaluate_action_lease +from phios.authority_epoch import AuthorityEpoch +from phios.effect_intent import EffectIntent +from phios.enforcement_profile import EnforcementProfile, EnforcementRule +from phios.mandala import AuthoritativeAuthorityEvent, AuthorityEventKind + +OWNER = 0 +STORE = Path('/.snapshots/phios-linux-proof') +PROPOSAL = Path('/var/lib/phios-agent/proposal.json') +SOURCE = Path('/usr/share/phios/source-commit') +TEXT = 'PhiOS verified one explicitly approved Linux proof note.\n' +LIMIT = 65536 +TTL = 60 + + +def boot_time_ns() -> int: + return time.clock_gettime_ns(time.CLOCK_BOOTTIME) + + +def encode(value: Any) -> bytes: + return json.dumps(value, sort_keys=True, separators=(',', ':'), ensure_ascii=True, allow_nan=False).encode() + + +def sha(value: Any) -> str: + return hashlib.sha256(encode(value)).hexdigest() + + +def pairs(values: list[tuple[str, Any]]) -> dict[str, Any]: + result: dict[str, Any] = {} + for key, value in values: + if key in result: + raise ValueError('duplicate JSON field') + result[key] = value + return result + + +def reject_constant(value: str) -> None: + raise ValueError('non-finite JSON: ' + value) + + +def decode(data: bytes) -> Any: + return json.loads(data, object_pairs_hook=pairs, parse_constant=reject_constant) + + +def check_info(info: os.stat_result, *, owner: int = 0, directory: bool = False) -> None: + kind = stat.S_ISDIR if directory else stat.S_ISREG + if not kind(info.st_mode) or info.st_uid != owner or info.st_mode & 0o022: + raise ValueError('protected owned directory/regular file required') + if not directory and (info.st_nlink != 1 or info.st_size > LIMIT): + raise ValueError('bounded singly linked regular file required') + + +def read_fd(fd: int, *, owner: int) -> bytes: + before = os.fstat(fd) + check_info(before, owner=owner) + data = os.read(fd, LIMIT + 1) + after = os.fstat(fd) + def stable(row: os.stat_result) -> tuple[int, ...]: + return (row.st_dev, row.st_ino, row.st_uid, row.st_mode, row.st_nlink, row.st_size, row.st_mtime_ns, row.st_ctime_ns) + if len(data) > LIMIT or len(data) != before.st_size or stable(before) != stable(after): + raise ValueError('captured file changed or exceeded bounds') + return data + + +def read_path(path: Path, *, owner: int, protected_parents: bool = True) -> bytes: + fd = os.open('/', os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW) + try: + for part in path.parts[1:-1]: + child = os.open(part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=fd) + os.close(fd) + fd = child + if protected_parents: + check_info(os.fstat(fd), owner=OWNER, directory=True) + child = os.open(path.name, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=fd) + try: + return read_fd(child, owner=owner) + finally: + os.close(child) + finally: + os.close(fd) + + +def context() -> dict[str, Any]: + if os.getuid() != 0 or os.geteuid() != 0 or os.environ.get('SUDO_UID') != '1000': + raise ValueError('installed UID 1000 administrator must invoke this broker through sudo') + if Path('/run/archiso/bootmnt').exists(): + raise ValueError('proof effects are disabled in the public volatile live account') + user = pwd.getpwuid(1000) + receipt = decode(read_path(Path('/var/lib/phios/install-receipt.json'), owner=OWNER)) + source = read_path(SOURCE, owner=OWNER).decode().strip() + boot = Path('/proc/sys/kernel/random/boot_id').read_text().strip().replace('-', '') + if (receipt.get('schema_version') != 'phios.blank-disk-install.v1' or receipt.get('installed') is not True + or receipt.get('plan', {}).get('username') != user.pw_name + or not re.fullmatch('[0-9a-f]{40}', source) or not re.fullmatch('[0-9a-f]{32}', boot)): + raise ValueError('installed identity/account receipt required') + mounted = [line.split(' - ', 1) for line in Path('/proc/self/mountinfo').read_text().splitlines()] + if not any(len(row) == 2 and row[0].split()[4] == '/.snapshots' and + row[1].split()[0] == 'btrfs' and '/@snapshots' == row[0].split()[3] for row in mounted): + raise ValueError('independent installed Btrfs snapshot store must be mounted') + check_info(Path('/.snapshots').lstat(), owner=OWNER, directory=True) + return {'source_commit': source, 'boot_id': boot, 'operator_uid': 1000, 'principal_uid': 1001} + + +def validate_proposal(value: Any, observed: dict[str, Any], now: datetime) -> dict[str, Any]: + required = {'schema_version', 'principal_uid', 'source_commit', 'boot_id', 'observed_at', 'nonce', + 'capability_id', 'text', 'execution_authority', 'effect_performed'} + if not isinstance(value, dict) or set(value) != required: + raise ValueError('exact bounded proposal fields required') + if (value['schema_version'] != 'phios.linux-proof-proposal.v1' or type(value['principal_uid']) is not int + or value['principal_uid'] != 1001 or value['source_commit'] != observed['source_commit'] + or value['boot_id'] != observed['boot_id'] or value['capability_id'] != 'linux.proof_note' + or value['text'] != TEXT or value['execution_authority'] is not False or value['effect_performed'] is not False + or not isinstance(value['nonce'], str) or not re.fullmatch('[0-9a-f]{32}', value['nonce'])): + raise ValueError('proposal identity/effect/scope differs from the fixed capability') + stamp = datetime.fromisoformat(value['observed_at']) + if stamp.tzinfo is None or not timedelta(0) <= now - stamp <= timedelta(minutes=10): + raise ValueError('proposal observation is stale or from the future') + return value + + +def capture(observed: dict[str, Any], now: datetime) -> dict[str, Any]: + # Every ancestor is opened without following links. Agent-owned ancestry + # is untrusted; only captured bytes, never a later read, enter the effect. + return validate_proposal(decode(read_path(PROPOSAL, owner=1001, protected_parents=False)), observed, now) + + +class Store: + def __init__(self, root: Path) -> None: + check_info(root.parent.lstat(), owner=OWNER, directory=True) + parent = os.open(root.parent, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW) + try: + try: + os.mkdir(root.name, mode=0o700, dir_fd=parent) + os.fsync(parent) + except FileExistsError: + pass + self.fd = os.open(root.name, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=parent) + try: + check_info(os.fstat(self.fd), owner=OWNER, directory=True) + except BaseException: + os.close(self.fd) + raise + finally: + os.close(parent) + self.root = root + + def close(self) -> None: + os.close(self.fd) + + @contextmanager + def directory(self, name: str) -> Iterator[int]: + if name not in {'approvals', 'consumed', 'notes', 'receipts'}: + raise ValueError('unsupported broker directory') + try: + os.mkdir(name, mode=0o700, dir_fd=self.fd) + os.fsync(self.fd) + except FileExistsError: + pass + fd = os.open(name, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=self.fd) + try: + check_info(os.fstat(fd), owner=OWNER, directory=True) + yield fd + finally: + os.close(fd) + + @contextmanager + def locked(self) -> Iterator[None]: + fd = os.open('lock', os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW | os.O_NONBLOCK, 0o600, dir_fd=self.fd) + try: + check_info(os.fstat(fd), owner=OWNER) + fcntl.flock(fd, fcntl.LOCK_EX) + yield + finally: + os.close(fd) + + def publish(self, kind: str, digest: str, data: bytes) -> None: + if not re.fullmatch('[0-9a-f]{64}', digest) or len(data) > LIMIT: + raise ValueError('bounded named broker record required') + with self.directory(kind) as directory: + fd = os.open(digest, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600, dir_fd=directory) + try: + view = memoryview(data) + while view: + count = os.write(fd, view) + if count <= 0: + raise OSError('short broker write') + view = view[count:] + os.fsync(fd) + finally: + os.close(fd) + os.fsync(directory) + + def read(self, kind: str, digest: str) -> bytes: + if not re.fullmatch('[0-9a-f]{64}', digest): + raise ValueError('exact SHA-256 broker identity required') + with self.directory(kind) as directory: + fd = os.open(digest, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=directory) + try: + return read_fd(fd, owner=OWNER) + finally: + os.close(fd) + + +def contracts(proposal: dict[str, Any], observed: dict[str, Any], decision: dict[str, Any]) -> dict[str, Any]: + start = decision['approved_at'] + until = (datetime.fromisoformat(start) + timedelta(seconds=TTL)).isoformat() + intent = EffectIntent.build(capability_id='linux.proof_note', capability_version='0.1.0', + payload_sha256=hashlib.sha256(TEXT.encode()).hexdigest(), declared_at=proposal['observed_at'], + effects_declared=('filesystem.change',), evidence_ref_sha256s=(sha(proposal),)) + policy = {'source_commit': observed['source_commit'], 'boot_id': observed['boot_id'], + 'principal_uid': 1001, 'operator_uid': 1000, 'capability_id': 'linux.proof_note', + 'fixed_store': str(STORE), 'max_uses': 1, 'ttl_seconds': TTL} + enforcement = EnforcementProfile.build(intent=intent, rules=(EnforcementRule.build( + rule_id='root-owned-single-note', effect_scope=('filesystem.change',), + constraint='Only a new SHA-256-named proof note inside the protected independent store', + layer='broker', boundary='kernel_boundary', status='enforced', + mechanism='UID-separated root-owned broker; no-follow directory FDs; fixed bytes; exclusive creation', + evidence_ref_sha256s=(sha(policy),)),)) + binding = {'schema_version': 'phios.linux-proof-binding.v1', 'decision_sha256': sha(decision), + 'proposal_sha256': sha(proposal), 'intent_sha256': intent.effect_intent_sha256, + 'enforcement_sha256': enforcement.profile_sha256, 'policy_sha256': sha(policy), 'principal_uid': 1001} + epoch = AuthorityEpoch.build(principal_id='linux-uid:1001', policy_sha256=sha(policy), + ceiling=('artifact.write',), events=(AuthoritativeAuthorityEvent( + event_id='proof-' + decision['nonce'], sequence=1, kind=AuthorityEventKind.GRANT, + permission='artifact.write', authority_source='installed-sudo-operator:1000', + effective_at=start, expires_at=until),), observed_at=start) + lease = ActionLease.issue(principal_id='linux-uid:1001', issuer_id='linux-proof-broker', + authorization_receipt_sha256=sha(binding), intent=intent, enforcement=enforcement, + authority_epoch=epoch, permissions_authorized=('artifact.write',), accepted_unenforced_effects=(), + issued_at=start, valid_from=start, valid_until=until) + return {'intent': intent.to_dict(), 'enforcement': enforcement.to_dict(), 'binding': binding, + 'authority_epoch': epoch.to_dict(), 'lease': lease.to_dict()} + + +def review_plan(proposal: dict[str, Any], observed: dict[str, Any]) -> dict[str, Any]: + return {'schema_version': 'phios.linux-proof-review.v1', 'observation': observed, 'proposal': proposal, + 'proposal_sha256': sha(proposal), 'note_sha256': hashlib.sha256(TEXT.encode()).hexdigest(), + 'store': str(STORE), 'max_uses': 1, 'ttl_seconds': TTL, 'execution_authority': False} + + +def approve(proposal: dict[str, Any], observed: dict[str, Any], *, input_stream: TextIO, output_stream: TextIO) -> str | None: + review = review_plan(proposal, observed) + print(json.dumps(review, indent=2, ensure_ascii=True), file=output_stream, flush=True) + if not input_stream.isatty() or not output_stream.isatty(): + raise ValueError('approval requires an interactive installed sudo operator') + print('Type exactly APPROVE ' + sha(review) + ' or anything else to cancel:', file=output_stream, flush=True) + if input_stream.readline().strip() != 'APPROVE ' + sha(review): + print('Cancelled; no approval, binding, lease or effect created.', file=output_stream) + return None + now = datetime.now(UTC) + if context() != observed or capture(observed, now) != proposal: + raise ValueError('proposal/OS identity changed during review') + decision = {'schema_version': 'phios.linux-proof-decision.v1', 'kind': 'APPROVE', 'operator_uid': 1000, + 'review_sha256': sha(review), 'proposal_sha256': sha(proposal), 'approved_at': now.isoformat(), + 'expires_boot_ns': boot_time_ns() + TTL * 10**9, 'nonce': uuid.uuid4().hex} + value = {'schema_version': 'phios.linux-proof-approval.v1', 'observation': observed, 'proposal': proposal, + 'decision': decision, **contracts(proposal, observed, decision)} + digest = sha(value) + store = Store(STORE) + try: + with store.locked(): + store.publish('approvals', digest, encode(value)) + finally: + store.close() + print(json.dumps({'approval_sha256': digest, 'lease_sha256': value['lease']['action_lease_sha256'], + 'execution_authority': False, 'effect_performed': False}), file=output_stream, flush=True) + return digest + + +def execute(store: Store, digest: str, observed: dict[str, Any], now: datetime) -> dict[str, Any]: + with store.locked(): + value = decode(store.read('approvals', digest)) + fields = {'schema_version', 'observation', 'proposal', 'decision', 'intent', 'enforcement', 'binding', 'authority_epoch', 'lease'} + if not isinstance(value, dict) or set(value) != fields or sha(value) != digest: + raise ValueError('approval record integrity/schema mismatch') + if value['schema_version'] != 'phios.linux-proof-approval.v1' or value['observation'] != observed: + raise ValueError('approval belongs to another boot/source/principal') + proposal = validate_proposal(value['proposal'], observed, now) + decision = value['decision'] + if (set(decision) != {'schema_version', 'kind', 'operator_uid', 'review_sha256', 'proposal_sha256', 'approved_at', 'expires_boot_ns', 'nonce'} + or decision['schema_version'] != 'phios.linux-proof-decision.v1' or decision['kind'] != 'APPROVE' + or type(decision['operator_uid']) is not int or decision['operator_uid'] != 1000 + or decision['proposal_sha256'] != sha(proposal) or decision['review_sha256'] != sha(review_plan(proposal, observed)) + or type(decision['expires_boot_ns']) is not int or decision['expires_boot_ns'] <= 0 + or not re.fullmatch('[0-9a-f]{32}', decision['nonce'])): + raise ValueError('exact operator decision required') + if decision['expires_boot_ns'] <= boot_time_ns(): + raise ValueError('effect held: lease_expired') + expected = contracts(proposal, observed, decision) + if any(value[key] != expected[key] for key in expected): + raise ValueError('exact intent/binding/enforcement/epoch/lease mismatch') + lease = ActionLease.from_dict(value['lease']) + try: + store.read('consumed', digest) + used = 1 + except FileNotFoundError: + used = 0 + evaluated = evaluate_action_lease(lease=lease, checked_at=now.isoformat(), + current_authority_epoch_sha256=expected['authority_epoch']['authority_epoch_sha256'], uses_consumed=used) + if not evaluated.usable: + raise ValueError('effect held: ' + evaluated.reason) + # Consume and sync BEFORE the effect. A crash/failure may leave an + # uncompleted note, but never reopens this lease for a second effect. + store.publish('consumed', digest, encode({'schema_version': 'phios.linux-proof-consumption.v1', + 'approval_sha256': digest, 'lease_sha256': lease.action_lease_sha256, 'consumed_at': now.isoformat(), + 'boot_id': observed['boot_id'], 'effect_performed': False})) + store.publish('notes', digest, TEXT.encode()) + actual = store.read('notes', digest) # Independent descriptor/readback. + if actual != TEXT.encode(): + raise ValueError('post-effect content verification failed; lease remains consumed') + receipt = {'schema_version': 'phios.linux-proof-receipt.v1', 'approval_sha256': digest, + 'decision_sha256': sha(decision), 'binding_sha256': sha(value['binding']), + 'lease_sha256': lease.action_lease_sha256, 'source_commit': observed['source_commit'], + 'boot_id': observed['boot_id'], 'principal_uid': 1001, 'operator_uid': 1000, + 'note_sha256': hashlib.sha256(actual).hexdigest(), 'note_bytes': len(actual), + 'post_effect_verified': True, 'effect_performed': True, 'execution_authority': False, + 'authority_replayable': False, 'release_ready': False} + store.publish('receipts', digest, encode(receipt)) + return receipt + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + commands = parser.add_subparsers(dest='command', required=True) + commands.add_parser('inspect') + commands.add_parser('approve') + run = commands.add_parser('execute') + run.add_argument('--approval', required=True) + args = parser.parse_args() + try: + observed = context() + if args.command == 'execute': + store = Store(STORE) + try: + print(json.dumps(execute(store, args.approval, observed, datetime.now(UTC)), indent=2)) + finally: + store.close() + else: + proposal = capture(observed, datetime.now(UTC)) + if args.command == 'inspect': + print(json.dumps({'observation': observed, 'proposal': proposal, 'execution_authority': False}, indent=2)) + else: + return 0 if approve(proposal, observed, input_stream=sys.stdin, output_stream=sys.stdout) else 2 + return 0 + except (OSError, ValueError, TypeError, KeyError, EOFError) as exc: + print('Linux proof held: ' + str(exc), file=sys.stderr) + return 1 + + +if __name__ == '__main__': + raise SystemExit(main()) diff --git a/packaging/linux/proof/phios-linux-proof b/packaging/linux/proof/phios-linux-proof new file mode 100644 index 00000000..14110eeb --- /dev/null +++ b/packaging/linux/proof/phios-linux-proof @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +set -euo pipefail +exec /usr/bin/python -I /usr/lib/phios-proof/broker.py "$@" diff --git a/packaging/linux/proof/phios-proof-proposer.service b/packaging/linux/proof/phios-proof-proposer.service new file mode 100644 index 00000000..e8c90b25 --- /dev/null +++ b/packaging/linux/proof/phios-proof-proposer.service @@ -0,0 +1,21 @@ +[Unit] +Description=Propose one harmless Linux proof note as the isolated agent principal + +[Service] +Type=oneshot +User=phios-agent +Group=phios-agent +ExecStart=/usr/bin/python -I /usr/lib/phios-proof/propose.py +UMask=0077 +NoNewPrivileges=yes +CapabilityBoundingSet= +ProtectSystem=strict +ProtectHome=yes +PrivateNetwork=yes +PrivateTmp=yes +RestrictNamespaces=yes +RestrictAddressFamilies=AF_UNIX +LockPersonality=yes +ReadWritePaths=/var/lib/phios-agent +InaccessiblePaths=/.snapshots /var/lib/phios +TimeoutStartSec=20 diff --git a/packaging/linux/proof/propose.py b/packaging/linux/proof/propose.py new file mode 100644 index 00000000..c273b487 --- /dev/null +++ b/packaging/linux/proof/propose.py @@ -0,0 +1,49 @@ +"""Observe public OS identity and propose one fixed harmless note as UID 1001.""" +from __future__ import annotations + +import json +import os +import re +import tempfile +import uuid +from datetime import UTC, datetime +from pathlib import Path + +TEXT = 'PhiOS verified one explicitly approved Linux proof note.\n' + + +def main() -> None: + if os.getuid() != 1001 or os.geteuid() != 1001: + raise ValueError('the isolated phios-agent principal is required') + source = Path('/usr/share/phios/source-commit').read_text().strip() + boot = Path('/proc/sys/kernel/random/boot_id').read_text().strip().replace('-', '') + if not re.fullmatch('[0-9a-f]{40}', source) or not re.fullmatch('[0-9a-f]{32}', boot): + raise ValueError('exact observed OS source and boot identity required') + root = Path('/var/lib/phios-agent') + info = root.lstat() + if root.is_symlink() or info.st_uid != 1001 or info.st_mode & 0o077: + raise ValueError('private agent directory required') + proposal = {'schema_version': 'phios.linux-proof-proposal.v1', 'principal_uid': 1001, + 'source_commit': source, 'boot_id': boot, 'observed_at': datetime.now(UTC).isoformat(), + 'nonce': uuid.uuid4().hex, 'capability_id': 'linux.proof_note', 'text': TEXT, + 'execution_authority': False, 'effect_performed': False} + fd, name = tempfile.mkstemp(prefix='.proposal-', dir=root) + try: + with os.fdopen(fd, 'w') as handle: + json.dump(proposal, handle, sort_keys=True, allow_nan=False) + handle.write('\n') + handle.flush() + os.fsync(handle.fileno()) + os.replace(name, root / 'proposal.json') + directory = os.open(root, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW) + try: + os.fsync(directory) + finally: + os.close(directory) + finally: + Path(name).unlink(missing_ok=True) + print('One proposal recorded; no approval, lease or effect created.') + + +if __name__ == '__main__': + main() diff --git a/packaging/linux/tests/proof_smoke.py b/packaging/linux/tests/proof_smoke.py new file mode 100644 index 00000000..795a9ee9 --- /dev/null +++ b/packaging/linux/tests/proof_smoke.py @@ -0,0 +1,134 @@ +"""External disposable-VM fixture, run by its password-authenticated UID 1000.""" +from __future__ import annotations + +import errno +import hashlib +import json +import os +import pty +import re +import select +import subprocess +import time +from pathlib import Path + +PASSWORD = 'phios-qa-only-2026' + + +def operator(argv: list[str], *, cancel: bool = False, approval: bool = False, expected: int = 0) -> str: + child, channel = pty.fork() + if child == 0: + os.execvp('sudo', ['sudo', '-k', *argv]) + text = '' + supplied_password = False + supplied_phrase = False + deadline = time.monotonic() + 180 + status = None + try: + while time.monotonic() < deadline: + if select.select([channel], [], [], 0.2)[0]: + try: + data = os.read(channel, 65536) + except OSError as exc: + if exc.errno != errno.EIO: + raise + data = b'' + if data: + text += data.decode(errors='replace') + if 'password for operator:' in text and not supplied_password: + os.write(channel, (PASSWORD + '\n').encode()) + supplied_password = True + match = re.search(r'Type exactly APPROVE ([0-9a-f]{64}) or anything else to cancel:', text) + if match and approval and not supplied_phrase: + answer = 'cancel' if cancel else 'APPROVE ' + match[1] + os.write(channel, (answer + '\n').encode()) + supplied_phrase = True + ended, result = os.waitpid(child, os.WNOHANG) + if ended: + status = result + drain = time.monotonic() + 1 + while time.monotonic() < drain and select.select([channel], [], [], 0.1)[0]: + try: + tail = os.read(channel, 65536) + except OSError as exc: + if exc.errno != errno.EIO: + raise + break + if not tail: + break + text += tail.decode(errors='replace') + break + if status is None: + raise RuntimeError('bounded production sudo proof command timed out') + code = os.waitstatus_to_exitcode(status) + print(text, flush=True) + if code != expected or not supplied_password or (approval and not supplied_phrase): + raise RuntimeError('actual password/production proof command status differs: ' + str(code)) + return text + finally: + os.close(channel) + if status is None: + os.kill(child, 9) + os.waitpid(child, 0) + + +def proof_workflow(source: str) -> dict[str, object]: + assert os.getuid() == 1000 + assert subprocess.run(['systemctl', 'is-active', '--quiet', 'phios-proof-proposer.service']).returncode != 0 + operator(['systemctl', 'start', 'phios-proof-proposer.service']) + report = operator(['phios-linux-proof', 'inspect']) + assert '"principal_uid": 1001' in report and source in report + cancelled = operator(['phios-linux-proof', 'approve'], approval=True, cancel=True, expected=2) + assert 'Cancelled; no approval' in cancelled + approved = operator(['phios-linux-proof', 'approve'], approval=True) + match = re.search(r'"approval_sha256": "([0-9a-f]{64})"', approved) + assert match is not None + digest = match[1] + permission = ("import os\nprint('AGENT_UID:'+str(os.getuid()),flush=True)\ntry:\n" + " open('/.snapshots/phios-linux-proof/approvals/" + digest + "')\n" + "except PermissionError:\n print('AGENT_STORE_DENIED',flush=True)\n raise SystemExit(1)") + denied = operator(['runuser', '-u', 'phios-agent', '--', 'python', '-c', permission], expected=1) + assert 'AGENT_UID:1001' in denied and 'AGENT_STORE_DENIED' in denied + denied_cli = operator(['runuser', '-u', 'phios-agent', '--', 'phios-linux-proof', 'execute', '--approval', digest], expected=1) + assert 'installed UID 1000 administrator' in denied_cli + receipt = operator(['phios-linux-proof', 'execute', '--approval', digest]) + value = json.loads(receipt[receipt.index('{'):receipt.rindex('}') + 1]) + assert value['effect_performed'] is True and value['post_effect_verified'] is True + assert value['execution_authority'] is False and value['authority_replayable'] is False + actual = operator(['cat', '/.snapshots/phios-linux-proof/notes/' + digest]) + assert 'PhiOS verified one explicitly approved Linux proof note.' in actual + replay = operator(['phios-linux-proof', 'execute', '--approval', digest], expected=1) + assert 'lease_consumed' in replay + another = operator(['phios-linux-proof', 'approve'], approval=True) + expired = re.search(r'"approval_sha256": "([0-9a-f]{64})"', another) + assert expired is not None + until = time.monotonic() + 61 + while time.monotonic() < until: + time.sleep(1) + expiry = operator(['phios-linux-proof', 'execute', '--approval', expired[1]], expected=1) + assert 'lease_expired' in expiry + absence = operator(['test', '!', '-e', '/.snapshots/phios-linux-proof/notes/' + expired[1]]) + assert 'Linux proof held' not in absence + result = {'schema_version': 'phios.linux-proof-qualification.v1', 'source_commit': source, + 'approval_sha256': digest, 'expired_approval_sha256': expired[1], 'receipt': value, + 'actual_agent_uid': 1001, 'sudo_password_authentication': True, 'agent_store_denied': True, + 'agent_broker_denied': True, 'cancel_passed': True, 'replay_refused': True, 'expiry_refused': True, + 'hardware_qualified': False, 'release_ready': False} + target = Path.home() / '.local/state/phios/qa/linux-proof.json' + fd = os.open(target, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600) + with os.fdopen(fd, 'w') as handle: + json.dump(result, handle, sort_keys=True) + handle.flush() + os.fsync(handle.fileno()) + print('PHIOS_LINUX_PROOF_OK:' + json.dumps(result), flush=True) + return result + + +def historical_proof(source: str) -> None: + value = json.loads((Path.home() / '.local/state/phios/qa/linux-proof.json').read_text()) + assert value['source_commit'] == source + denied = operator(['phios-linux-proof', 'execute', '--approval', value['approval_sha256']], expected=1) + assert 'another boot/source/principal' in denied + note = operator(['cat', '/.snapshots/phios-linux-proof/notes/' + value['approval_sha256']]) + assert 'PhiOS verified one explicitly approved Linux proof note.' in note + print('PHIOS_LINUX_PROOF_HISTORY_INACTIVE:' + hashlib.sha256(note.encode()).hexdigest(), flush=True) diff --git a/packaging/linux/tests/qemu_install.py b/packaging/linux/tests/qemu_install.py index 389f0db4..c899d0aa 100644 --- a/packaging/linux/tests/qemu_install.py +++ b/packaging/linux/tests/qemu_install.py @@ -281,6 +281,10 @@ def wait_for(pattern: str) -> re.Match[str]: send_text(qmp, PASSWORD) program = Path(__file__).with_name("installed_probe.py").read_text() + \ f"\nprobe({source!r}, {phase}, signed_update={signed_update!r})\n" + if Path(__file__).with_name('proof_smoke.py').exists(): + program = Path(__file__).with_name('proof_smoke.py').read_text() + \ + (f'\nproof_workflow({source!r})\n' if phase == 1 else f'\nhistorical_proof({source!r})\n') + \ + program.replace('from __future__ import annotations\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 + @@ -289,6 +293,21 @@ def wait_for(pattern: str) -> re.Match[str]: details = json.loads(result[1]) if details["source_commit"] != source or details["phase"] != phase: raise RuntimeError("installed receipt identity mismatch") + if Path(__file__).with_name('proof_smoke.py').exists(): + if phase == 1: + proof_match = re.search(r'PHIOS_LINUX_PROOF_OK:(\{[^\r\n]+\})', text) + if proof_match is None: + raise RuntimeError('actual governed proof receipt missing') + proof = json.loads(proof_match[1]) + if proof['source_commit'] != source or not all(proof[k] is True for k in + ['sudo_password_authentication', 'agent_store_denied', 'agent_broker_denied', + 'cancel_passed', 'replay_refused', 'expiry_refused']): + raise RuntimeError('governed proof refusal/identity evidence missing') + receipt['linux_governed_workflow'] = proof + elif 'PHIOS_LINUX_PROOF_HISTORY_INACTIVE:' not in text: + raise RuntimeError('old-boot proof authority refusal missing') + if phase == (3 if recovery else 2): + receipt['linux_governed_workflow_qualified'] = True receipt["boot_ids"].append(details["boot_id"]) receipt["record_sha256"] = details["record_sha256"] capture_display(qmp, output, name=f"screen-installed-{phase}") diff --git a/tests/test_linux_proof_broker_v01.py b/tests/test_linux_proof_broker_v01.py new file mode 100644 index 00000000..6e7d305b --- /dev/null +++ b/tests/test_linux_proof_broker_v01.py @@ -0,0 +1,210 @@ +from __future__ import annotations + +import copy +import importlib.util +import io +import os +import json +import subprocess +import sys +from datetime import UTC, datetime, timedelta +from pathlib import Path + +import pytest + +FILE = Path(__file__).resolve().parents[1] / 'packaging/linux/proof/broker.py' +spec = importlib.util.spec_from_file_location('phios_proof_broker_test', FILE) +assert spec is not None and spec.loader is not None +broker = importlib.util.module_from_spec(spec) +spec.loader.exec_module(broker) + + +@pytest.fixture +def setup(tmp_path: Path, monkeypatch: pytest.MonkeyPatch): + # Only unit-test temporary files use the CI test principal; production is UID 0. + monkeypatch.setattr(broker, 'OWNER', os.getuid()) + monkeypatch.setattr(broker, 'STORE', tmp_path / 'store') + now = datetime.now(UTC) + observed = {'source_commit': 'a' * 40, 'boot_id': 'b' * 32, 'operator_uid': 1000, 'principal_uid': 1001} + proposal = {'schema_version': 'phios.linux-proof-proposal.v1', 'principal_uid': 1001, + 'source_commit': observed['source_commit'], 'boot_id': observed['boot_id'], 'observed_at': now.isoformat(), + 'nonce': 'c' * 32, 'capability_id': 'linux.proof_note', 'text': broker.TEXT, + 'execution_authority': False, 'effect_performed': False} + monkeypatch.setattr(broker, 'context', lambda: copy.deepcopy(observed)) + monkeypatch.setattr(broker, 'capture', lambda *_: copy.deepcopy(proposal)) + return now, observed, proposal + + +class Terminal(io.StringIO): + def isatty(self) -> bool: + return True + + +def approve(setup): + _, observed, proposal = setup + digest = broker.approve(proposal, observed, + input_stream=Terminal('APPROVE ' + broker.sha(broker.review_plan(proposal, observed)) + '\n'), + output_stream=Terminal()) + assert digest is not None + return digest + + +def test_real_contract_chain_effect_independent_readback_and_replay(setup): + now, observed, _ = setup + digest = approve(setup) + store = broker.Store(broker.STORE) + try: + value = broker.decode(store.read('approvals', digest)) + assert value['intent']['execution_authority'] is False + assert value['lease']['max_uses'] == 1 and value['lease']['execution_authority'] is False + result = broker.execute(store, digest, observed, now + timedelta(seconds=1)) + assert result['post_effect_verified'] is True and result['effect_performed'] is True + assert store.read('notes', digest) == broker.TEXT.encode() + assert broker.decode(store.read('receipts', digest)) == result + with pytest.raises(ValueError, match='consumed'): + broker.execute(store, digest, observed, now + timedelta(seconds=2)) + finally: + store.close() + + +def test_cancel_and_nonterminal_create_no_store(setup): + _, observed, proposal = setup + assert broker.approve(proposal, observed, input_stream=Terminal('cancel\n'), output_stream=Terminal()) is None + assert not broker.STORE.exists() + with pytest.raises(ValueError, match='interactive'): + broker.approve(proposal, observed, input_stream=io.StringIO('yes'), output_stream=Terminal()) + assert not broker.STORE.exists() + + +def test_stale_capture_after_exact_review_creates_no_authority(setup, monkeypatch): + _, observed, proposal = setup + changed = dict(proposal, nonce='e' * 32) + monkeypatch.setattr(broker, 'capture', lambda *_: changed) + with pytest.raises(ValueError, match='changed during review'): + approve(setup) + assert not broker.STORE.exists() + + +@pytest.mark.parametrize('field,value', [('text','run a shell'), ('capability_id','shell.execute'), + ('execution_authority',True), ('principal_uid',1000), ('boot_id','d'*32), + ('source_commit','e'*40), ('nonce','../escape'), ('unknown',None), ('observed_at','2000-01-01T00:00:00+00:00')]) +def test_untrusted_proposal_is_not_an_authority_or_arbitrary_effect(setup, field, value): + now, observed, proposal = setup + with pytest.raises(ValueError): + broker.validate_proposal(dict(proposal, **{field:value}), observed, now) + + +@pytest.mark.parametrize('kind', ['expired', 'new-boot', 'new-source', 'suspended-or-clock-rollback']) +def test_expired_or_restored_authority_cannot_create_note(setup, monkeypatch, kind): + now, observed, _ = setup + digest = approve(setup) + if kind == 'expired': + now += timedelta(seconds=61) + elif kind == 'suspended-or-clock-rollback': + monkeypatch.setattr(broker, 'boot_time_ns', lambda: 10**30) + else: + observed = dict(observed, **{'boot_id' if kind=='new-boot' else 'source_commit':'d'* (32 if kind=='new-boot' else 40)}) + store = broker.Store(broker.STORE) + try: + with pytest.raises(ValueError): + broker.execute(store, digest, observed, now) + assert not (broker.STORE / 'notes' / digest).exists() + assert not (broker.STORE / 'consumed' / digest).exists() + finally: + store.close() + + +def test_consume_sync_failure_precedes_effect_and_never_reopens_lease(setup, monkeypatch): + now, observed, _ = setup + digest = approve(setup) + store = broker.Store(broker.STORE) + publish = store.publish + def failure(kind, name, data): + publish(kind, name, data) + if kind == 'consumed': + raise OSError('injected durable boundary failure') + monkeypatch.setattr(store, 'publish', failure) + try: + with pytest.raises(OSError): + broker.execute(store, digest, observed, now + timedelta(seconds=1)) + assert not (broker.STORE / 'notes' / digest).exists() + monkeypatch.setattr(store, 'publish', publish) + with pytest.raises(ValueError, match='consumed'): + broker.execute(store, digest, observed, now + timedelta(seconds=2)) + finally: + store.close() + + +def test_corrupt_or_linked_approval_held_before_consumption(setup): + now, observed, _ = setup + digest = approve(setup) + path = broker.STORE / 'approvals' / digest + data = path.read_bytes() + path.write_bytes(data[:-3]) + store = broker.Store(broker.STORE) + try: + with pytest.raises(ValueError): + broker.execute(store, digest, observed, now) + path.write_bytes(data) + os.link(path, path.with_name('extra-link')) + with pytest.raises(ValueError, match='singly linked'): + broker.execute(store, digest, observed, now) + assert not (broker.STORE / 'notes' / digest).exists() + finally: + store.close() + + +def test_symlinked_note_directory_cannot_redirect_root_effect(setup, tmp_path): + now, observed, _ = setup + digest = approve(setup) + outside = tmp_path / 'outside' + outside.mkdir() + (broker.STORE / 'notes').symlink_to(outside) + store = broker.Store(broker.STORE) + try: + with pytest.raises(OSError): + broker.execute(store, digest, observed, now + timedelta(seconds=1)) + assert list(outside.iterdir()) == [] + with pytest.raises(ValueError, match='consumed'): + broker.execute(store, digest, observed, now + timedelta(seconds=2)) + finally: + store.close() + + +def test_parser_rejects_duplicate_and_nonfinite_json(): + for value in [b'{"a":1,"a":2}', b'{"a":NaN}']: + with pytest.raises(ValueError): + broker.decode(value) + + +def test_two_processes_can_consume_only_once(setup): + _, observed, _ = setup + digest = approve(setup) + code = ''' +import importlib.util,json,os,sys +from pathlib import Path +from datetime import UTC,datetime +spec=importlib.util.spec_from_file_location('production_proof',sys.argv[1]) +module=importlib.util.module_from_spec(spec);spec.loader.exec_module(module) +module.OWNER=os.getuid();module.STORE=Path(sys.argv[2]) +store=module.Store(module.STORE) +try: + module.execute(store,sys.argv[3],json.loads(sys.argv[4]),datetime.now(UTC)) +except ValueError as error: + if 'lease_consumed' not in str(error): raise + raise SystemExit(2) +finally: + store.close() +''' + processes = [subprocess.Popen([sys.executable, '-c', code, str(FILE), str(broker.STORE), digest, json.dumps(observed)], + stdout=subprocess.PIPE, stderr=subprocess.PIPE) for _ in range(2)] + try: + results = [process.communicate(timeout=15) for process in processes] + assert sorted(process.returncode for process in processes) == [0, 2], results + assert (broker.STORE / 'notes' / digest).read_bytes() == broker.TEXT.encode() + assert len(list((broker.STORE / 'receipts').iterdir())) == 1 + finally: + for process in processes: + if process.poll() is None: + process.kill() + process.wait() From d4e0c4bda9aca66189a6a4d08f459f0a0a437a6d Mon Sep 17 00:00:00 2001 From: Michael Hughes Date: Wed, 30 Sep 2026 20:15:12 -0700 Subject: [PATCH 2/3] Requalify the fixture-free ISO when packaged runtime changes --- .github/workflows/os-release-candidate.yml | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/.github/workflows/os-release-candidate.yml b/.github/workflows/os-release-candidate.yml index 37c19f96..e74f4cd2 100644 --- a/.github/workflows/os-release-candidate.yml +++ b/.github/workflows/os-release-candidate.yml @@ -3,10 +3,11 @@ name: Fixture-free OS candidate (unpublished) on: pull_request: paths: - - 'packaging/linux/release_inventory.py' - - 'packaging/linux/validate_sbom.py' - - 'packaging/linux/sbom-schema-lock.json' - - 'packaging/linux/tests/qemu_preview.py' + - 'packaging/**' + - 'phios/**' + - 'phishell/**' + - 'pyproject.toml' + - 'build/build_iso.sh' - '.github/workflows/os-release-candidate.yml' workflow_dispatch: From 89833c263a22d59de1c99031db884ce6c903f67b Mon Sep 17 00:00:00 2001 From: Michael Hughes Date: Wed, 30 Sep 2026 20:31:02 -0700 Subject: [PATCH 3/3] Record bundled frontend suppliers and preserve the proof fixture failure --- docs/os/RELEASE_ARTIFACTS.md | 6 ++ docs/os/evidence/linux-proof-attempts.json | 62 ++++++++++++++++++ packaging/linux/release_inventory.py | 38 ++++++++++- packaging/linux/tests/proof_smoke.py | 6 ++ phishell/host/bundledInventory.d.mts | 2 + phishell/host/bundledInventory.mjs | 75 ++++++++++++++++++++++ phishell/vite.config.ts | 2 + tests/test_os_release_inventory_v01.py | 33 ++++++++-- 8 files changed, 218 insertions(+), 6 deletions(-) create mode 100644 docs/os/evidence/linux-proof-attempts.json create mode 100644 phishell/host/bundledInventory.d.mts create mode 100644 phishell/host/bundledInventory.mjs diff --git a/docs/os/RELEASE_ARTIFACTS.md b/docs/os/RELEASE_ARTIFACTS.md index 353b949a..6a49fdca 100644 --- a/docs/os/RELEASE_ARTIFACTS.md +++ b/docs/os/RELEASE_ARTIFACTS.md @@ -69,3 +69,9 @@ All generated reports remain `release_ready: false`; they do not grant execution, signing, adapter-promotion or publication authority. Main/release branch protection and required-check settings have not been changed by this candidate workflow. Protecting them remains a maintainer repository setting. + +The builder also captures actual Rollup chunk participants before npm pruning, +including Vite-generated runtime helpers. Bundled supplier metadata and license +notices are retained in the installed dist tree; the collector checks final +chunk and notice hashes and emits a separate javascript-bundled inventory. +A pruned runtime package list alone cannot describe all generated frontend code. diff --git a/docs/os/evidence/linux-proof-attempts.json b/docs/os/evidence/linux-proof-attempts.json new file mode 100644 index 00000000..f60ca1b3 --- /dev/null +++ b/docs/os/evidence/linux-proof-attempts.json @@ -0,0 +1,62 @@ +{ + "attempts": [ + { + "evidence_artifact_id": 11138998040, + "evidence_files": { + "PhiOS/PhiOS/dist/linux/build.log": "b2926f9e5a138d4ee82246fcb4e7930025a6fad1e062d813ac0163a8e6c7c274", + "PhiOS/PhiOS/dist/linux/builder-image.json": "152a89cdd304d4c82530635a884da51fa7a5667dc36e2124b922b34e1f4a818f", + "PhiOS/PhiOS/dist/linux/builder-packages.txt": "9c8e376a83e3ebbad5078dbb9fc5cc12ecd15ad57c4fa933466bad26dd09a291", + "PhiOS/PhiOS/dist/linux/fixture-inventory.json": "2ebf26541ddaa6d1e239b1a3be944946f18e8d08e78837065d11eed7921d7a60", + "PhiOS/PhiOS/dist/linux/image-packages.txt": "dd6faf936234848a574c0d3125da4eddabaa33b8f02998bc7be070250d3e29f9", + "PhiOS/PhiOS/dist/linux/javascript-packages.json": "a9026fc707306f7fb2ffb952b884197a66ccc3def539f90f938e8c4b7e4e0582", + "PhiOS/PhiOS/dist/linux/mkarchiso.log": "52dd7695fca50a2a4727e21413070068f5107385a5f5822b48a7444affad7895", + "PhiOS/PhiOS/dist/linux/native-packages.json": "ad9071bcaf5ab74f87b7915aa8e0909f95b577e472c2996aa1e1064427697090", + "PhiOS/PhiOS/dist/linux/provenance.json": "4f546f4e5ad9478f8cb8b1fde934c8bf919b62c5ba7d7e1f90b80b86e656291f", + "PhiOS/PhiOS/dist/linux/python-packages.json": "9af1ad8db48a4e1a528d082984d07efbf34539b52ddac7026ea4e9923073d5a0", + "PhiOS/PhiOS/dist/linux/release.json": "0d5499ce8f252637d7a1d6a8bdedeb8aef9829307893e348f3c1bf0795b91a75", + "PhiOS/PhiOS/dist/linux/sbom.cdx.json": "b6e74ec4d252a5e5b2b1a884d35ed806fa10d10503903a68160eaf71339f3e84", + "PhiOS/PhiOS/dist/linux/source-archive-sha256.txt": "46c01dbd154317150c0a91ae1931427ab9c15f979e33271e2f67cd87075124d7", + "PhiOS/PhiOS/dist/linux/source-commit.txt": "3b5f0f3cc3d038a55ab34daa3b9637df451584ac29ef77f1fdd433e36a2536d1", + "PhiOS/PhiOS/dist/linux/source-review.json": "0a7b94001b98bf05951f44fc47e518cc008a14cd71b871c16a73d3ff7f7086df", + "PhiOS/PhiOS/dist/linux/third-party-notices.json": "137316e3c393079fd72aa7234611db782aa5f7c540b69648dd42729f35e25493", + "_temp/phios-boot/boot-evidence.json": "89fd0b797b17370b187c1d450cc05c6f5ff51b26fd76e54f33859226de785587", + "_temp/phios-boot/qemu.log": "cfb88d1675b569a5b47b59d2b1fe103919a5649ff0a475d396d1ffde6c6b24f0", + "_temp/phios-boot/screen-first.png": "6bf190581d13131e0dfa84a0d2c48301eee4a9cae68e2d25e547335951f37d24", + "_temp/phios-boot/screen.png": "9e5130dfebfa68d901c9e339e94970c3e370bce4f7422bc196a6f679f227384c", + "_temp/phios-boot/serial.log": "b7a8e5bcd5402a5e2cc78dfca3d5ad035dcc579d174166a321f5544d23c69abb", + "_temp/phios-installed/install-live-qemu.log": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "_temp/phios-installed/install-live-serial.log": "74188764f835bf43d87ec7989e4de353cfd75f955defe6e85e1bcba41a92e05b", + "_temp/phios-installed/installed-1-qemu.log": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "_temp/phios-installed/installed-1-serial.log": "b2c8017c2eac119a0a7a087932d9465b3a150fb128ce9aab3433d65142a58956", + "_temp/phios-installed/installed-evidence.json": "0feaec08478a3f9d62f3ef66fe730d7fea3a125345a3184cc3edc7a4f906b85f", + "_temp/phios-installed/interrupted-resume-live-qemu.log": "06733008ca698aa515bfe73217fc56e15a6720fc69302592e9ab9e6c594c2e95", + "_temp/phios-installed/interrupted-resume-live-serial.log": "6330debfc5b90e9c344bc5759c0bab5bf2937f0780c6180f4743074fd8825c44", + "_temp/phios-installed/screen-install-live.png": "52e0cbfba53195e94b8e53e193f093d9b50d93ce7c52d84314ccde8725245f10", + "_temp/phios-installed/screen-installed-1-failure.png": "14e78d7ef364fe1a127090e54d5744d8e4a83a82b5ff9f975957ec858d4321aa", + "_temp/phios-installed/screen-installed-1-greeter.png": "f83a37571994ca7274939836bf77a47904c689fb6d38bb8587a11f2432aeba0e", + "_temp/phios-installed/screen-interrupted-resume-live.png": "612f17fbf548ef2042612b8617cc4b995174213c20e1d1762575d9f9805cd17e" + }, + "failure": "External fixture saved its user QA summary before the older data probe created the qa directory. FileNotFoundError occurred after all proof effect/refusal commands passed, before restart/recovery qualification. Fixture now creates its own private summary directory and flushes it.", + "head": "d4e0c4bda9aca66189a6a4d08f459f0a0a437a6d", + "image_artifact_id": 11138743361, + "iso_sha256": "400dae3ba8cce0ef834b68cd905585ecd7feec372a15abc4268dfbd68f3a02e9", + "job_id": 110201722446, + "linux_workflow_qualified": false, + "observed": [ + "production agent service", + "actual sudo password authentication", + "UID 1001 store/broker denial", + "cancellation", + "canonical bound single-use lease", + "actual note/readback receipt", + "replay refusal", + "real 60-second expiry refusal", + "successful signed package and preserved interrupted stage" + ], + "release_ready": false, + "source_commit": "0133997a0ac8b2d202170dd28a6f9c19b23c51fe", + "workflow_run": 36809656268 + } + ], + "schema_version": "phios.linux-proof-attempts.v1" +} diff --git a/packaging/linux/release_inventory.py b/packaging/linux/release_inventory.py index 5f343dd6..cbe9d0f4 100644 --- a/packaging/linux/release_inventory.py +++ b/packaging/linux/release_inventory.py @@ -112,7 +112,7 @@ def component(kind: str, name: str, version: str, *, path: str, labels: list[str def collect(root: Path) -> tuple[list[dict[str, Any]], dict[str, list[dict[str, Any]]], set[str]]: components: list[dict[str, Any]] = [] - inventory: dict[str, list[dict[str, Any]]] = {'native': [], 'python': [], 'javascript': []} + inventory: dict[str, list[dict[str, Any]]] = {'native': [], 'python': [], 'javascript': [], 'javascript-bundled': []} notices: set[str] = set() database = image_path(root, 'var/lib/pacman/local') rows = sorted(database.glob('*/desc')) @@ -183,6 +183,42 @@ def collect(root: Path) -> tuple[list[dict[str, Any]], dict[str, list[dict[str, for notice in directory.iterdir(): if notice.is_file() and re.search(r'license|copying|notice|copyright', notice.name, re.I): notices.add(notice.relative_to(root).as_posix()) + bundled = json.loads(bounded(image_path(root, 'usr/lib/phishell/dist/bundled-js-inventory.json'))) + if (not isinstance(bundled, dict) or set(bundled) != {'schema_version', 'packages', 'chunks', 'license_compliance_reviewed'} + or bundled['schema_version'] != 'phios.phishell-bundle.v1' or bundled['license_compliance_reviewed'] is not False + or not isinstance(bundled['packages'], list) or not 1 <= len(bundled['packages']) <= 2000 + or not isinstance(bundled['chunks'], list) or not 1 <= len(bundled['chunks']) <= 512): + raise ValueError('bounded actual frontend bundle inventory required') + chunk_names: set[str] = set() + for chunk in bundled['chunks']: + if set(chunk) != {'filename', 'sha256', 'size'} or chunk['filename'] in chunk_names: + raise ValueError('exact unique frontend chunk records required') + if digest(image_path(root, 'usr/lib/phishell/dist/' + chunk['filename'])) != {key: chunk[key] for key in ['sha256', 'size']}: + raise ValueError('actual frontend chunk differs from build inventory') + chunk_names.add(chunk['filename']) + origins: set[str] = set() + for row in bundled['packages']: + if (set(row) != {'name', 'version', 'license', 'package_json_sha256', 'package_path', 'modules', 'notices'} + or not isinstance(row['name'], str) or not row['name'] or not isinstance(row['version'], str) or not row['version'] + or row['package_path'] in origins or not isinstance(row['modules'], list) or not row['modules'] + or not isinstance(row['notices'], list) or len(row['notices']) > 64): + raise ValueError('exact unique bundled supplier records required') + origins.add(row['package_path']) + for module in row['modules']: + if set(module) != {'id', 'chunk', 'role'} or module['chunk'] not in chunk_names or module['role'] not in ['chunk-module', 'injected-runtime-helper']: + raise ValueError('bundled module refers to an unknown chunk/role') + for notice in row['notices']: + if (set(notice) != {'filename', 'original_name', 'sha256', 'size'} or + re.fullmatch(r'bundled-notices/[0-9a-f]{64}\.txt', notice['filename']) is None): + raise ValueError('exact bounded bundled notice record required') + relative = 'usr/lib/phishell/dist/' + notice['filename'] + if digest(image_path(root, relative)) != {key: notice[key] for key in ['sha256', 'size']}: + raise ValueError('bundled notice differs from captured build input') + notices.add(relative) + path = 'usr/lib/phishell/dist/bundled-js-inventory.json#' + row['package_path'] + labels = [row['license']] if isinstance(row['license'], str) and row['license'] else [] + inventory['javascript-bundled'].append(row) + components.append(component('npm', row['name'], row['version'], path=path, labels=labels)) inventory['native'].sort(key=lambda row: row['name']) return sorted(components, key=lambda row: row['bom-ref']), inventory, notices diff --git a/packaging/linux/tests/proof_smoke.py b/packaging/linux/tests/proof_smoke.py index 795a9ee9..5ff6df4e 100644 --- a/packaging/linux/tests/proof_smoke.py +++ b/packaging/linux/tests/proof_smoke.py @@ -115,11 +115,17 @@ def proof_workflow(source: str) -> dict[str, object]: 'agent_broker_denied': True, 'cancel_passed': True, 'replay_refused': True, 'expiry_refused': True, 'hardware_qualified': False, 'release_ready': False} target = Path.home() / '.local/state/phios/qa/linux-proof.json' + target.parent.mkdir(mode=0o700, exist_ok=True) fd = os.open(target, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600) with os.fdopen(fd, 'w') as handle: json.dump(result, handle, sort_keys=True) handle.flush() os.fsync(handle.fileno()) + directory = os.open(target.parent, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW) + try: + os.fsync(directory) + finally: + os.close(directory) print('PHIOS_LINUX_PROOF_OK:' + json.dumps(result), flush=True) return result diff --git a/phishell/host/bundledInventory.d.mts b/phishell/host/bundledInventory.d.mts new file mode 100644 index 00000000..a0bb17b4 --- /dev/null +++ b/phishell/host/bundledInventory.d.mts @@ -0,0 +1,2 @@ +import type { Plugin } from "vite"; +export function bundledInventory(): Plugin; diff --git a/phishell/host/bundledInventory.mjs b/phishell/host/bundledInventory.mjs new file mode 100644 index 00000000..d48dafbb --- /dev/null +++ b/phishell/host/bundledInventory.mjs @@ -0,0 +1,75 @@ +import { createHash } from "node:crypto"; +import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync, writeFileSync } from "node:fs"; +import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path"; + +const sha = (bytes) => createHash("sha256").update(bytes).digest("hex"); + +// Record actual Rollup chunk participants before npm pruning removes build +// inputs. Virtual Vite runtime helpers retain their actual supplier identity. +export function bundledInventory() { + return { + name: "phios-bundled-inventory", + enforce: "post", + writeBundle(options, bundle) { + const root = realpathSync(join(process.cwd(), "node_modules")); + const output = resolve(options.dir ?? "dist"); + const packages = new Map(); + const chunks = []; + for (const chunk of Object.values(bundle)) { + if (chunk.type !== "chunk") continue; + if (isAbsolute(chunk.fileName) || chunk.fileName.split("/").includes("..")) throw new Error("Unsafe chunk path"); + const bytes = readFileSync(join(output, chunk.fileName)); + chunks.push({ filename: chunk.fileName, sha256: sha(bytes), size: bytes.length }); + for (const id of Object.keys(chunk.modules)) { + const virtual = id.startsWith("\0vite/"); + const clean = id.replace(/^\0/, "").split("?", 1)[0]; + let path; + let actual; + if (virtual) path = join(root, "vite"); + else { + if (!isAbsolute(clean) || !existsSync(clean)) continue; + actual = realpathSync(clean); + if (!actual.startsWith(root + sep)) continue; + path = dirname(actual); + } + while (path.startsWith(root + sep) && !existsSync(join(path, "package.json"))) path = dirname(path); + if (!path.startsWith(root + sep)) throw new Error("Bundled supplier identity missing"); + const metadata = readFileSync(join(path, "package.json")); + const info = JSON.parse(metadata); + if (typeof info.name !== "string" || typeof info.version !== "string") throw new Error("Bundled package identity missing"); + const origin = relative(root, path).split(sep).join("/"); + if (!packages.has(origin)) packages.set(origin, { name: info.name, version: info.version, + license: typeof info.license === "string" ? info.license : null, + package_json_sha256: sha(metadata), package_path: "node_modules/" + origin, + modules: [], notices: [], _path: path }); + packages.get(origin).modules.push({ id: virtual ? clean : relative(path, actual).split(sep).join("/"), + chunk: chunk.fileName, role: virtual ? "injected-runtime-helper" : "chunk-module" }); + } + } + if (packages.size === 0 || packages.size > 2000) throw new Error("Bounded nonempty bundled inventory required"); + mkdirSync(join(output, "bundled-notices"), { recursive: true }); + const rows = [...packages.values()].sort((a, b) => a.package_path.localeCompare(b.package_path)); + for (const row of rows) { + for (const name of readdirSync(row._path).sort()) { + if (!/license|copying|notice|copyright/i.test(name)) continue; + const target = realpathSync(join(row._path, name)); + if (!target.startsWith(root + sep)) throw new Error("Notice escaped dependency root"); + const info = lstatSync(target); + if (!info.isFile()) continue; + if (info.size > 1024 * 1024) throw new Error("Bundled notice exceeds its bound"); + const bytes = readFileSync(target); + const digest = sha(bytes); + const filename = "bundled-notices/" + digest + ".txt"; + writeFileSync(join(output, filename), bytes); + row.notices.push({ filename, original_name: name, sha256: digest, size: bytes.length }); + } + row.modules.sort((a, b) => a.chunk.localeCompare(b.chunk) || a.id.localeCompare(b.id)); + delete row._path; + } + writeFileSync(join(output, "bundled-js-inventory.json"), JSON.stringify({ + schema_version: "phios.phishell-bundle.v1", packages: rows, + chunks: chunks.sort((a, b) => a.filename.localeCompare(b.filename)), + license_compliance_reviewed: false }, null, 2) + "\n"); + }, + }; +} diff --git a/phishell/vite.config.ts b/phishell/vite.config.ts index 8d48d311..94d45afd 100644 --- a/phishell/vite.config.ts +++ b/phishell/vite.config.ts @@ -1,7 +1,9 @@ import { defineConfig } from "vite"; +import { bundledInventory } from "./host/bundledInventory.mjs"; export default defineConfig({ base: "./", + plugins: [bundledInventory()], build: { outDir: "dist", sourcemap: true, diff --git a/tests/test_os_release_inventory_v01.py b/tests/test_os_release_inventory_v01.py index 41953a3e..6deccf87 100644 --- a/tests/test_os_release_inventory_v01.py +++ b/tests/test_os_release_inventory_v01.py @@ -35,6 +35,19 @@ def fixture(root: Path, output: Path) -> None: 'node_modules/react': {'version': '19.0.0', 'integrity': 'disposable'}}})) put(root, 'usr/lib/phishell/node_modules/react/package.json', json.dumps({'name': 'react', 'version': '19.0.0', 'license': 'MIT'})) put(root, 'usr/lib/phishell/node_modules/react/LICENSE', 'disposable MIT notice\n') + chunk = b'disposable compiled frontend helper' + notice = b'disposable bundled supplier notice\n' + notice_sha = hashlib.sha256(notice).hexdigest() + put(root, 'usr/lib/phishell/dist/assets/main.js', chunk) + put(root, 'usr/lib/phishell/dist/bundled-notices/' + notice_sha + '.txt', notice) + put(root, 'usr/lib/phishell/dist/bundled-js-inventory.json', json.dumps({ + 'schema_version': 'phios.phishell-bundle.v1', 'license_compliance_reviewed': False, + 'chunks': [{'filename': 'assets/main.js', 'sha256': hashlib.sha256(chunk).hexdigest(), 'size': len(chunk)}], + 'packages': [{'name': 'vite', 'version': '7.1.5', 'license': 'MIT', 'package_json_sha256': 'd'*64, + 'package_path': 'node_modules/vite', 'modules': [{'id': 'vite/modulepreload-polyfill.js', + 'chunk': 'assets/main.js', 'role': 'injected-runtime-helper'}], + 'notices': [{'filename': 'bundled-notices/' + notice_sha + '.txt', 'sha256': notice_sha, + 'size': len(notice), 'original_name': 'LICENSE'}]}]})) put(output, 'release.json', json.dumps({'os_version': '0.1.0-alpha.1', 'arch_snapshot': '2026/09/30', 'archiso_version': '91-1', 'builder_image': 'archlinux@sha256:' + 'b' * 64})) put(output, 'image-packages.txt', 'a z-1\na-b z-1\n') @@ -52,19 +65,20 @@ def test_inventory_tracks_actual_bytes_without_concluding_compliance(tmp_path: P assert provenance['release_ready'] is False assert provenance['license_source_compliance_reviewed'] is False bom = json.loads((output / 'sbom.cdx.json').read_text()) - assert len(bom['components']) == 4 - assert len({row['bom-ref'] for row in bom['components']}) == 4 + assert len(bom['components']) == 5 + assert len({row['bom-ref'] for row in bom['components']}) == 5 assert all(row['licenses'][0]['license']['acknowledgement'] == 'declared' for row in bom['components']) notices = json.loads((output / 'third-party-notices.json').read_text()) assert {row['path'] for row in notices['files']} == { - 'usr/share/licenses/shared/LICENSE', 'usr/lib/phishell/node_modules/react/LICENSE'} + 'usr/share/licenses/shared/LICENSE', 'usr/lib/phishell/node_modules/react/LICENSE', + 'usr/lib/phishell/dist/bundled-notices/' + hashlib.sha256(b'disposable bundled supplier notice\n').hexdigest() + '.txt'} assert json.loads((output / 'source-review.json').read_text())['third_party_source_compliance_reviewed'] is False for line in (output / 'SHA256SUMS').read_text().splitlines(): digest, filename = line.split(' ') assert hashlib.sha256((output / filename).read_bytes()).hexdigest() == digest -@pytest.mark.parametrize('case', ['source', 'inventory', 'npm', 'archive', 'fixture', 'trust']) +@pytest.mark.parametrize('case', ['source', 'inventory', 'npm', 'archive', 'fixture', 'trust', 'bundled-chunk', 'bundled-notice', 'bundled-reference']) def test_inconsistent_image_or_artifact_cannot_get_provenance(tmp_path: Path, case: str) -> None: root, output = tmp_path / 'root', tmp_path / 'output' fixture(root, output) @@ -78,8 +92,17 @@ def test_inconsistent_image_or_artifact_cannot_get_provenance(tmp_path: Path, ca put(output, 'phios-source.tar.gz', b'changed archive') elif case == 'fixture': put(root, inventory.FIXTURES[0], 'test fixture') - else: + elif case == 'trust': put(root, 'etc/phios/os-update-keyring.gpg', b'unrequested trust') + elif case == 'bundled-chunk': + put(root, 'usr/lib/phishell/dist/assets/main.js', b'changed compiled code') + elif case == 'bundled-notice': + next((root / 'usr/lib/phishell/dist/bundled-notices').iterdir()).write_bytes(b'changed notice') + else: + p = root / 'usr/lib/phishell/dist/bundled-js-inventory.json' + value = json.loads(p.read_text()) + value['packages'][0]['modules'][0]['chunk'] = 'unobserved.js' + p.write_text(json.dumps(value)) with pytest.raises(ValueError): inventory.record(root, output, 'a' * 40, ci_fixtures=False, epoch=1) assert not (output / 'provenance.json').exists()