diff --git a/docs/NBGA_OBSERVATION_PROVIDER_V0.1.md b/docs/NBGA_OBSERVATION_PROVIDER_V0.1.md new file mode 100644 index 00000000..b74710b9 --- /dev/null +++ b/docs/NBGA_OBSERVATION_PROVIDER_V0.1.md @@ -0,0 +1,113 @@ +# NBG-A qualification observation provider v0.1 + +This experimental provider makes the reviewed #284 public contract usable on the +current PhiOS/Linux continuation. It reads a fixed public qualification packet, +checks its document bytes and returns normalized Memory Receipts with directional +documentary paths. It is an offline reader of historical evidence, not a live +PhiKernel memory service or a new source of release authority. + +## Read the observations + +The Arch package installs the packet and its four public documents under +`/usr/share/phios/nbga`. From Foot in a candidate containing this change: + +```sh +python -m phios.adapters.nbga_observation +``` + +To inspect the launcher retest after checking the complete packet: + +```sh +python -m phios.adapters.nbga_observation \ + --bubble-id bubble:phios:virtualbox:launcher-0f17bac1 +``` + +From the repository root, use its public evidence directory explicitly: + +```sh +python -m phios.adapters.nbga_observation --evidence-root docs/os/evidence +``` + +Success returns JSON and exit status 0. Missing, altered, unsupported or malformed +evidence returns an unavailable JSON result and exit status 2, without any partial +observations or host paths. This command creates no files and starts no service. +The previous #286 ISO does not contain this new provider. + +## Evidence and paths + +| Bubble | Evidence preserved | +| --- | --- | +| `original-1c16c473` | Owner-reported renderer failure with 3D off, invisible pointer after enabling 3D, separate cursor override and session-target rebinding | +| `failed-attempt-146e470f` | Reviewed failed normal CI rebinding attempt; installation/recovery skipped; screenshot/QA pass did not qualify that normal image | +| `automatic-9510024d` | Owner-local #283 automatic startup and cold cycle; unresolved blank lock screen, untested PAM unlock, refused sudo poweroff | +| `launcher-0f17bac1` | Owner-local #286 navigation/window/shortcut checks and cold cycle; older ISO rejected, Wofi drun workaround, unavailable canonical-history backend | + +Full bubble identities begin `bubble:phios:virtualbox:`. The `documented-follow-up` +Gear path identifies the sequence of reviewed records. It does not prove a causal +relationship or execute a transformation. `event_head` identifies the last +documentary evidence reference; it is not an implemented append-only runtime log. + +The provider's code pins the complete packet to SHA-256 +`d61f0bd49de27f770e62d36871dbd335f82684c526a8631b19da6dc2b5651608`. +The packet pins each document's complete digest and size. Every document is read +and checked before a query filter is applied. Updating the packet requires a +reviewed code-pin change; a packet cannot provide its own trusted digest. Python +callers supplying a custom `expected_packet_sha256` own that external trust input. + +`evidence_integrity=verified-against-pins` means the selected documentary bytes +match these reviewed pins. It does not independently authenticate the original +Windows tester, prove a reported event occurred or hash the historical ISO, +screenshots, packages and logs referenced inside the documents. The packet is +not a maintainer-signed publication artifact. Those underlying items retain the +exact producer/reviewer/owner-reported status recorded in the original receipts. + +Memory Receipts preserve `owner-reported` or `reviewed-ci-record` trust states, +with no manufactured numeric confidence. Their public `provenance_root` hashes a +domain-separated record of the packet digest and referenced document pins. This +identifies documentary lineage; it is not a private PhiKernel governance root, +an anchor promotion or proof that an observation is true. + +## Refusals and authority + +The reader rejects packet/digest/size mismatches, missing or non-regular files, +symbolic-link evidence, traversal/URL filenames, duplicate packet JSON fields, unknown +schemas/fields, non-finite JSON numbers, unbounded data, unresolved/repeated +references, disconnected/cyclic paths, conflicting Gear definitions and attempts +to assert `verified` trust. Complete references and path endpoints must resolve +within the checked packet. + +The existing NBG-A public parser remains unchanged from #284. Private payloads, +authority grants and unknown contract fields remain refused. No network request, +process execution, memory write, anchor, decay, manifest commit, adapter promotion, +model selection or OS policy change is introduced by the reader. It bypasses no +existing governed canonical-memory service or read/compare permission. + +Bubble Zero is explicitly **unavailable: no continuity backend**. No roots, +checkpoint or restored identity are invented. The result retains +`publication_authority=false` and `release_ready=false`. + +## Qualification and next step + +Focused tests cover the real documentary sequence, deterministic read-only +queries, failures surviving filtering, external pins, file/schema/path refusals, +lineage checks, trust-state limits and CLI refusal output. The existing external +desktop probe additionally invokes the installed reader with Python isolated +mode as UID 1000 during live/installed VM checks. It also alters a copied prior +failure document in a disposable user-owned directory and requires refusal of +the latest-observation query without any partial results. It records the packet digest, +four checked documents, tamper refusal and unavailable continuity backend alongside its current +source identity. Historical #286 observations do not qualify the new boot. + +This continuation copies the three reviewed #284 contract files onto the #287 +branch chain; those sibling PRs and prior qualified source/ISO/failure receipts +remain unchanged. PhiOS's Arch package revision increases to 2; software and OS +release versions remain unchanged. Changed candidate bytes require their own +full normal/QA qualification and a fresh owner-local field test before claiming +VirtualBox compatibility for this candidate. + +The next rung can consume a genuine normalized runtime observation behind the +existing PhiKernel boundary. Persistence, Bubble Zero verification and A-TEAM +mutation operations require separately reviewed contracts and a persistent +installed test environment. A live ISO's temporary overlay does not establish +cold-power-cycle memory reconstruction. Private PhiKernel/TIEKAT implementation +internals remain outside public PhiOS. diff --git a/docs/NBGA_RUNTIME_CONTRACT_V0.1.md b/docs/NBGA_RUNTIME_CONTRACT_V0.1.md new file mode 100644 index 00000000..46371d8f --- /dev/null +++ b/docs/NBGA_RUNTIME_CONTRACT_V0.1.md @@ -0,0 +1,163 @@ +# NBG-A Public Runtime Contract v0.1 + +**Status:** experimental, additive, read-only boundary + +**Scope:** PhiOS consumption of normalized PhiKernel continuity and memory observations + +**Non-goal:** publication of PhiKernel or TIEKAT implementation internals + +NBG-A is the working name for the Nested Bubble/Gear Architecture used by the A-TEAM +memory lifecycle: + +- **Anchor** preserves continuity-critical invariants. +- **Triage** classifies incoming state without granting authority. +- **Episodic** represents bounded events and their evidence. +- **Abstract** exposes higher-order observables while retaining provenance. +- **Manifest** reconstructs usable working state from trusted continuity roots. + +PhiOS consumes only the normalized boundary described here. Storage engines, graph +algorithms, decay rules, routing logic, model prompts, private state, and TIEKAT +implementation details remain behind the PhiKernel boundary. + +## Contract invariants + +1. **Identity is not the model.** +2. **An observable is not the internal state.** +3. **Capability is not authority.** +4. **A trusted memory retains a path to why it is trusted.** +5. **Public observations do not grant write, promotion, routing, or execution authority.** +6. **Unknown fields fail closed rather than silently widening the contract.** + +v0.1 intentionally exposes no mutation operation. Anchor promotion, triage decisions, +decay, consolidation, manifest commits, and continuity-root updates remain internal and +governed. A later public mutation contract requires a separate reviewed rung. + +## Memory Receipt + +Schema: + +`phikernel.nbga.memory-receipt.v1` + +A Memory Receipt carries one normalized observable and enough public lineage to explain +how it was retrieved: + +```json +{ + "schema_version": "phikernel.nbga.memory-receipt.v1", + "bubble_id": "bubble:project:decision", + "bubble_version": 3, + "observable": "Normalized human-readable state", + "trust_state": "verified", + "confidence": 1.0, + "evidence": ["event:123"], + "gear_path": [ + { + "gear_id": "gear:evidence", + "transform": "evidence", + "source": "bubble:project", + "destination": "bubble:project:decision" + } + ], + "event_head": "event:123", + "provenance_root": "sha256:..." +} +``` + +### Bubble + +At the public boundary, a Bubble is identified by `bubble_id` and `bubble_version`. +PhiOS receives its `observable`, not its private payload or internal state. + +### Gear path + +A Gear Hop is a directional, named transformation between two public Bubble identities: + +```text +source --[transform / gear_id]--> destination +``` + +The public contract describes the path. It does not expose how PhiKernel implements the +transformation. + +### Evidence and provenance + +`evidence`, `event_head`, and `provenance_root` make retrieval proof-carrying. +They are references, not an authority grant. PhiOS may present or compare them but may +not infer permission to mutate PhiKernel state. + +## Bubble Zero Status + +Schema: + +`phikernel.nbga.bubble-zero-status.v1` + +Bubble Zero is exposed only as a minimal continuity projection: + +```json +{ + "schema_version": "phikernel.nbga.bubble-zero-status.v1", + "system_id": "phios", + "epoch": 7, + "verified": true, + "governance_root": "sha256:...", + "event_log_head": "sha256:...", + "topology_root": "sha256:...", + "anchor_root": "sha256:...", + "commitment_root": "sha256:...", + "last_checkpoint": "checkpoint:7" +} +``` + +This projection answers only: + +- which continuity identity is being observed, +- which epoch is current, +- whether the exposed root set verified, +- and which normalized roots/checkpoint identify that state. + +It does not expose secrets, raw state, internal payload references, capability grants, +or authority grants. + +## Fail-closed fields + +The PhiOS parser rejects public payloads containing known private/authority-bearing +fields such as `internal_state`, `raw_state`, `private_state`, `payload`, +`payload_ref`, `secret`, `authority`, `authority_grant`, or +`capability_grant`. + +It also rejects unknown top-level fields. Contract growth therefore requires an explicit +schema revision instead of accidental widening. + +## First acceptance target + +The first end-to-end NBG-A acceptance experiment should use already-understood PhiOS +qualification evidence: + +1. ingest a bounded compatibility/qualification episode, +2. expose a higher-order verified observable, +3. retain evidence and a directional Gear path, +4. restart the runtime, +5. recover Bubble Zero, +6. retrieve the observable again with the same provenance lineage. + +The experiment is successful only if restart/reconstruction preserves the trusted +observable and its evidence path without making the model, vector index, or PhiOS +presentation layer authoritative. + +## Rollout + +v0.1 is intentionally additive: + +```text +qualified PhiOS/Linux candidate + | + v +existing PhiKernel adapter + | + +--> existing runtime behavior (unchanged) + | + +--> NBG-A normalized parser (new, read-only) +``` + +No existing adapter is promoted, no routing default changes, and no release authority is +implied by this contract. diff --git a/docs/os/APP_AVAILABILITY.md b/docs/os/APP_AVAILABILITY.md index 8b953798..fbd81405 100644 --- a/docs/os/APP_AVAILABILITY.md +++ b/docs/os/APP_AVAILABILITY.md @@ -44,6 +44,11 @@ initial overlapping windows do not hide the entry point. inference quality. - **Network settings:** Super+N. - **SOMA/Spine tools:** in Foot, run `phi-spine --help`. +- **Experimental NBG-A evidence reader:** in a candidate containing the provider, + run `python -m phios.adapters.nbga_observation` in Foot. It reads pinned public + qualification documents; it does not connect the unavailable ledger backend + or implement persistent memory. See + [NBGA_OBSERVATION_PROVIDER_V0.1.md](../NBGA_OBSERVATION_PROVIDER_V0.1.md). - **Lock:** Super+L; enter the account password to unlock. The separate VirtualBox wrong-password/unlock test remains pending. diff --git a/docs/os/evidence/nbga-virtualbox-observations.json b/docs/os/evidence/nbga-virtualbox-observations.json new file mode 100644 index 00000000..dcb0bdc9 --- /dev/null +++ b/docs/os/evidence/nbga-virtualbox-observations.json @@ -0,0 +1,121 @@ +{ + "schema_version": "phios.nbga.observation-packet.v1", + "packet_id": "phios:virtualbox:qualification:2026-10-01", + "evidence": [ + { + "id": "document:virtualbox:original-1c16c473", + "filename": "virtualbox-field-1c16c473.json", + "sha256": "e9d47ac8263e455793c6024282b31fad72923d2463e9c71deb8332bb00af214c", + "size_bytes": 5201 + }, + { + "id": "document:virtualbox:failed-attempt-146e470f", + "filename": "virtualbox-compatibility-attempts.json", + "sha256": "b1ecd3de4b4d71da93368b45b10f82c1abf9da06f56a818bd01bae0f96a0c2f9", + "size_bytes": 2864 + }, + { + "id": "document:virtualbox:automatic-9510024d", + "filename": "virtualbox-field-9510024d.json", + "sha256": "e89dfdab97661582d20921d177f6dc5ad6181cb4609b433eb94227ec2722b001", + "size_bytes": 6805 + }, + { + "id": "document:virtualbox:launcher-0f17bac1", + "filename": "virtualbox-field-0f17bac1.json", + "sha256": "dd36b28b76a2e4d652bd8f6ba63f973f256ddef539357b65ebc654695428b9da", + "size_bytes": 9566 + } + ], + "observations": [ + { + "bubble_id": "bubble:phios:virtualbox:original-1c16c473", + "bubble_version": 1, + "observable": "Owner-reported PR #281 live test on ISO 376fd601f66b13dccd6a08644a7b807129f315882d355fd376d0934a80ae29aa: renderer failed with 3D off; enabling 3D rendered the desktop but the pointer was invisible. WLR_NO_HARDWARE_CURSORS=1 restored the pointer; restarting the session target restored PhiShell/Waybar. These are separate steps. Physical hardware and automatic startup were not qualified by this report.", + "trust_state": "owner-reported", + "evidence": [ + "document:virtualbox:original-1c16c473" + ], + "gear_path": [], + "event_head": "document:virtualbox:original-1c16c473" + }, + { + "bubble_id": "bubble:phios:virtualbox:failed-attempt-146e470f", + "bubble_version": 1, + "observable": "Reviewed CI failure record for run 36913191826, source 146e470f6d9ee0e5ff8700cf3fab5e779c9ddacd, ISO f544ce35f4ae09ecf67b18f19b079a94489c65f10a8bd8cd74a8f3626c2abab2: normal qualification failed at the live rebinding probe and installation/recovery was skipped. Rendered screenshots and a passing separate QA lane did not qualify that normal image.", + "trust_state": "reviewed-ci-record", + "evidence": [ + "document:virtualbox:original-1c16c473", + "document:virtualbox:failed-attempt-146e470f" + ], + "gear_path": [ + { + "gear_id": "gear:virtualbox:follow-up-1", + "transform": "documented-follow-up", + "source": "bubble:phios:virtualbox:original-1c16c473", + "destination": "bubble:phios:virtualbox:failed-attempt-146e470f" + } + ], + "event_head": "document:virtualbox:failed-attempt-146e470f" + }, + { + "bubble_id": "bubble:phios:virtualbox:automatic-9510024d", + "bubble_version": 1, + "observable": "Owner-local PR #283 report records ISO 33bfb34251d7f65abe7f8a9d600c21794d051640a305d50c1bca9b21364c2c68 hash match, automatic PhiShell/Waybar/cursor startup and ACPI shutdown/cold boot. The blank Super+L observation remains unresolved: wrong-password refusal/PAM unlock was not tested. Sudo poweroff was refused; ACPI shutdown passed. Physical hardware and VirtualBox installation remain unqualified.", + "trust_state": "owner-reported", + "evidence": [ + "document:virtualbox:original-1c16c473", + "document:virtualbox:failed-attempt-146e470f", + "document:virtualbox:automatic-9510024d" + ], + "gear_path": [ + { + "gear_id": "gear:virtualbox:follow-up-1", + "transform": "documented-follow-up", + "source": "bubble:phios:virtualbox:original-1c16c473", + "destination": "bubble:phios:virtualbox:failed-attempt-146e470f" + }, + { + "gear_id": "gear:virtualbox:follow-up-2", + "transform": "documented-follow-up", + "source": "bubble:phios:virtualbox:failed-attempt-146e470f", + "destination": "bubble:phios:virtualbox:automatic-9510024d" + } + ], + "event_head": "document:virtualbox:automatic-9510024d" + }, + { + "bubble_id": "bubble:phios:virtualbox:launcher-0f17bac1", + "bubble_version": 1, + "observable": "Owner-local PR #286 report records ISO 8635a5f1277ca01ef7174b6e3b325e3cf9e972572070eb84d7395b9cec3dcd08 hash match and successful Apps/Home/Start/search, four tool window lifecycles, desktop/cursor startup and Chromium/Foot before and after cold boot under VirtualBox 7.2.20r175154. The older mismatched ISO was rejected before boot; Wofi required clearing literal drun. The reviewed screenshot shows canonical history unavailable. External runtimes, VirtualBox lock/unlock and physical hardware remain unqualified.", + "trust_state": "owner-reported", + "evidence": [ + "document:virtualbox:original-1c16c473", + "document:virtualbox:failed-attempt-146e470f", + "document:virtualbox:automatic-9510024d", + "document:virtualbox:launcher-0f17bac1" + ], + "gear_path": [ + { + "gear_id": "gear:virtualbox:follow-up-1", + "transform": "documented-follow-up", + "source": "bubble:phios:virtualbox:original-1c16c473", + "destination": "bubble:phios:virtualbox:failed-attempt-146e470f" + }, + { + "gear_id": "gear:virtualbox:follow-up-2", + "transform": "documented-follow-up", + "source": "bubble:phios:virtualbox:failed-attempt-146e470f", + "destination": "bubble:phios:virtualbox:automatic-9510024d" + }, + { + "gear_id": "gear:virtualbox:follow-up-3", + "transform": "documented-follow-up", + "source": "bubble:phios:virtualbox:automatic-9510024d", + "destination": "bubble:phios:virtualbox:launcher-0f17bac1" + } + ], + "event_head": "document:virtualbox:launcher-0f17bac1" + } + ] +} diff --git a/packaging/arch/phios/PKGBUILD b/packaging/arch/phios/PKGBUILD index 8a7f1e76..207ee536 100644 --- a/packaging/arch/phios/PKGBUILD +++ b/packaging/arch/phios/PKGBUILD @@ -1,7 +1,7 @@ # Build only from the local, hashed archive made by build-linux.sh. pkgname=phios pkgver=1.0.0 -pkgrel=1 +pkgrel=2 pkgdesc='PhiOS operator shell, verification spine and governed local runtime' arch=('any') url='https://github.com/MichaelWave369/PhiOS' @@ -23,6 +23,10 @@ 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" + for receipt in nbga-virtualbox-observations.json virtualbox-field-1c16c473.json \ + virtualbox-compatibility-attempts.json virtualbox-field-9510024d.json virtualbox-field-0f17bac1.json; do + install -Dm644 "docs/os/evidence/$receipt" "$pkgdir/usr/share/phios/nbga/$receipt" + done install -Dm644 packaging/linux/installer/install.py "$pkgdir/usr/lib/phios-installer/install.py" install -Dm755 packaging/linux/installer/phios-install "$pkgdir/usr/bin/phios-install" install -Dm644 packaging/linux/updates/verify.py "$pkgdir/usr/lib/phios-updates/verify.py" diff --git a/packaging/linux/tests/desktop_probe.py b/packaging/linux/tests/desktop_probe.py index a3dda89a..49b40336 100644 --- a/packaging/linux/tests/desktop_probe.py +++ b/packaging/linux/tests/desktop_probe.py @@ -4,6 +4,7 @@ import json import os import shlex +import shutil import socket import struct import subprocess @@ -107,6 +108,32 @@ def running(pids: dict) -> bool: def desktop_services(source: str, *, wired: bool = False) -> dict: assert os.getuid() == 1000 and os.geteuid() == 1000 assert Path('/usr/share/phios/source-commit').read_text().strip() == source + # Execute the installed offline provider as the ordinary live/installed user. + # Its packet describes historical evidence, never this boot's qualification. + nbga = json.loads(subprocess.check_output( + ['python', '-I', '-m', 'phios.adapters.nbga_observation'], text=True, timeout=10)) + assert nbga['provider_mode'] == 'read-only' and nbga['evidence_integrity'] == 'verified-against-pins' + assert len(nbga['checked_documents']) == len(nbga['observations']) == 4 + assert nbga['observations'][-1]['trust_state'] == 'owner-reported' + assert nbga['observations'][-1]['confidence'] is None + assert nbga['bubble_zero']['availability'] == 'unavailable' + assert nbga['release_ready'] is False and nbga['publication_authority'] is False + with tempfile.TemporaryDirectory(prefix='phios-nbga-probe-') as temporary: + evidence = Path(temporary) + packaged = Path('/usr/share/phios/nbga') + for filename in ['nbga-virtualbox-observations.json'] + [item['filename'] for item in nbga['checked_documents']]: + shutil.copyfile(packaged / filename, evidence / filename) + failed_record = evidence / 'virtualbox-compatibility-attempts.json' + content = failed_record.read_bytes() + failed_record.write_bytes(b'[' + content[1:]) + refused = subprocess.run(['python', '-I', '-m', 'phios.adapters.nbga_observation', + '--evidence-root', str(evidence), '--bubble-id', 'bubble:phios:virtualbox:launcher-0f17bac1'], + capture_output=True, text=True, timeout=10) + refusal = json.loads(refused.stdout) + assert refused.returncode == 2 and refused.stderr == '' + assert refusal['availability'] == 'unavailable' and 'observations' not in refusal + assert refusal['reason'] == 'evidence document integrity mismatch' + assert refusal['publication_authority'] is False units = ['phios-audio.target', 'pipewire.service', 'pipewire-pulse.service', 'wireplumber.service', 'phios-policykit.service'] for _ in range(60): active = all(subprocess.run(['systemctl', '--user', 'is-active', '--quiet', unit]).returncode == 0 @@ -143,7 +170,11 @@ def desktop_services(source: str, *, wired: bool = False) -> dict: subprocess.run(['pw-play', '--target', str(sinks[0]['id']), str(path)], check=True, timeout=30) for unit in ['NetworkManager.service', 'systemd-resolved.service']: subprocess.run(['systemctl', 'is-active', '--quiet', unit], check=True) - observed = {'source_commit': source, 'uid': os.getuid(), 'user_audio_services': True, 'nonroot_graphical_policykit_agent': True, + observed = {'source_commit': source, 'uid': os.getuid(), + 'nbga_public_packet_sha256': nbga['packet_sha256'], 'nbga_checked_document_count': 4, + 'nbga_readonly_observation_passed': True, 'nbga_continuity_backend_available': False, + 'nbga_prior_failure_tamper_refused': True, + 'user_audio_services': True, 'nonroot_graphical_policykit_agent': True, 'emulated_alsa_device_observed': True, 'virtual_pcm_playback_completed': True, 'host_audio_attached': False, 'wired_dhcp_observed': False, 'wifi_radio_qualified': False, 'physical_audio_qualified': False, 'release_ready': False} diff --git a/phios/adapters/nbga.py b/phios/adapters/nbga.py new file mode 100644 index 00000000..cc306486 --- /dev/null +++ b/phios/adapters/nbga.py @@ -0,0 +1,238 @@ +"""Normalized public NBG-A contract for PhiOS <-> PhiKernel integration. + +This module intentionally models only the stable, observable boundary. It does not +encode PhiKernel storage, routing, decay, or TIEKAT implementation internals. +""" + +from __future__ import annotations + +import math +from dataclasses import dataclass +from typing import Mapping + +MEMORY_RECEIPT_SCHEMA = "phikernel.nbga.memory-receipt.v1" +BUBBLE_ZERO_STATUS_SCHEMA = "phikernel.nbga.bubble-zero-status.v1" + +_FORBIDDEN_FIELDS = frozenset( + { + "authority", + "authority_grant", + "capability_grant", + "internal_state", + "payload", + "payload_ref", + "private_state", + "raw_state", + "secret", + "secrets", + } +) + + +class NBGContractError(ValueError): + """Raised when an NBG-A public-contract payload is invalid or overexposes state.""" + + +def _require_mapping(value: object, field: str) -> Mapping[str, object]: + if not isinstance(value, Mapping): + raise NBGContractError(f"{field} must be an object") + return value + + +def _validate_keys( + payload: Mapping[str, object], + *, + required: frozenset[str], + optional: frozenset[str] = frozenset(), +) -> None: + keys = set(payload) + leaked = keys & _FORBIDDEN_FIELDS + if leaked: + raise NBGContractError( + "public NBG-A payload exposes forbidden field(s): " + ", ".join(sorted(leaked)) + ) + missing = required - keys + if missing: + raise NBGContractError("missing required field(s): " + ", ".join(sorted(missing))) + unknown = keys - required - optional + if unknown: + raise NBGContractError("unknown public-contract field(s): " + ", ".join(sorted(unknown))) + + +def _require_str(value: object, field: str) -> str: + if not isinstance(value, str) or not value.strip(): + raise NBGContractError(f"{field} must be a non-empty string") + return value + + +def _require_int(value: object, field: str, *, minimum: int = 0) -> int: + if isinstance(value, bool) or not isinstance(value, int) or value < minimum: + raise NBGContractError(f"{field} must be an integer >= {minimum}") + return value + + +def _require_bool(value: object, field: str) -> bool: + if not isinstance(value, bool): + raise NBGContractError(f"{field} must be a boolean") + return value + + +def _require_confidence(value: object) -> float: + if isinstance(value, bool) or not isinstance(value, (int, float)): + raise NBGContractError("confidence must be a number from 0 to 1") + result = float(value) + if not math.isfinite(result) or not 0.0 <= result <= 1.0: + raise NBGContractError("confidence must be a finite number from 0 to 1") + return result + + +def _require_string_tuple(value: object, field: str) -> tuple[str, ...]: + if not isinstance(value, list): + raise NBGContractError(f"{field} must be an array") + return tuple(_require_str(item, f"{field}[]") for item in value) + + +@dataclass(frozen=True, slots=True) +class GearHop: + """One normalized directional transformation in a proof-carrying retrieval path.""" + + gear_id: str + transform: str + source: str + destination: str + + @classmethod + def from_payload(cls, value: object) -> "GearHop": + payload = _require_mapping(value, "gear_path[]") + _validate_keys( + payload, + required=frozenset({"gear_id", "transform", "source", "destination"}), + ) + return cls( + gear_id=_require_str(payload["gear_id"], "gear_id"), + transform=_require_str(payload["transform"], "transform"), + source=_require_str(payload["source"], "source"), + destination=_require_str(payload["destination"], "destination"), + ) + + +@dataclass(frozen=True, slots=True) +class MemoryReceipt: + """Observable memory plus the path and evidence used to retrieve it.""" + + bubble_id: str + bubble_version: int + observable: str + trust_state: str + confidence: float | None + evidence: tuple[str, ...] + gear_path: tuple[GearHop, ...] + event_head: str + provenance_root: str + + @classmethod + def from_payload(cls, value: object) -> "MemoryReceipt": + payload = _require_mapping(value, "memory receipt") + _validate_keys( + payload, + required=frozenset( + { + "schema_version", + "bubble_id", + "bubble_version", + "observable", + "trust_state", + "evidence", + "gear_path", + "event_head", + "provenance_root", + } + ), + optional=frozenset({"confidence"}), + ) + if payload["schema_version"] != MEMORY_RECEIPT_SCHEMA: + raise NBGContractError("unsupported memory receipt schema_version") + + raw_path = payload["gear_path"] + if not isinstance(raw_path, list): + raise NBGContractError("gear_path must be an array") + + confidence = None + if "confidence" in payload and payload["confidence"] is not None: + confidence = _require_confidence(payload["confidence"]) + + return cls( + bubble_id=_require_str(payload["bubble_id"], "bubble_id"), + bubble_version=_require_int(payload["bubble_version"], "bubble_version", minimum=1), + observable=_require_str(payload["observable"], "observable"), + trust_state=_require_str(payload["trust_state"], "trust_state"), + confidence=confidence, + evidence=_require_string_tuple(payload["evidence"], "evidence"), + gear_path=tuple(GearHop.from_payload(item) for item in raw_path), + event_head=_require_str(payload["event_head"], "event_head"), + provenance_root=_require_str(payload["provenance_root"], "provenance_root"), + ) + + +@dataclass(frozen=True, slots=True) +class BubbleZeroStatus: + """Minimal continuity status exposed across the PhiKernel public boundary.""" + + system_id: str + epoch: int + verified: bool + governance_root: str + event_log_head: str + topology_root: str + anchor_root: str + commitment_root: str + last_checkpoint: str | None + + @classmethod + def from_payload(cls, value: object) -> "BubbleZeroStatus": + payload = _require_mapping(value, "Bubble Zero status") + _validate_keys( + payload, + required=frozenset( + { + "schema_version", + "system_id", + "epoch", + "verified", + "governance_root", + "event_log_head", + "topology_root", + "anchor_root", + "commitment_root", + "last_checkpoint", + } + ), + ) + if payload["schema_version"] != BUBBLE_ZERO_STATUS_SCHEMA: + raise NBGContractError("unsupported Bubble Zero schema_version") + + checkpoint = payload["last_checkpoint"] + if checkpoint is not None: + checkpoint = _require_str(checkpoint, "last_checkpoint") + + return cls( + system_id=_require_str(payload["system_id"], "system_id"), + epoch=_require_int(payload["epoch"], "epoch"), + verified=_require_bool(payload["verified"], "verified"), + governance_root=_require_str(payload["governance_root"], "governance_root"), + event_log_head=_require_str(payload["event_log_head"], "event_log_head"), + topology_root=_require_str(payload["topology_root"], "topology_root"), + anchor_root=_require_str(payload["anchor_root"], "anchor_root"), + commitment_root=_require_str(payload["commitment_root"], "commitment_root"), + last_checkpoint=checkpoint, + ) + + +__all__ = [ + "BUBBLE_ZERO_STATUS_SCHEMA", + "MEMORY_RECEIPT_SCHEMA", + "BubbleZeroStatus", + "GearHop", + "MemoryReceipt", + "NBGContractError", +] diff --git a/phios/adapters/nbga_observation.py b/phios/adapters/nbga_observation.py new file mode 100644 index 00000000..88112d33 --- /dev/null +++ b/phios/adapters/nbga_observation.py @@ -0,0 +1,274 @@ +"""Offline NBG-A observations from explicitly selected, pinned public documents. + +Document integrity is checked against a packet digest supplied by trusted code or +the caller. It does not verify the underlying field event or initialize PhiKernel. +""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import re +import stat +from dataclasses import asdict, dataclass +from pathlib import Path +from typing import Sequence + +from phios.adapters.nbga import MEMORY_RECEIPT_SCHEMA, GearHop, MemoryReceipt, NBGContractError + +PACKET_SCHEMA = "phios.nbga.observation-packet.v1" +RESULT_SCHEMA = "phios.nbga.observation-result.v1" +PACKET_FILENAME = "nbga-virtualbox-observations.json" +PINNED_PACKET_SHA256 = "d61f0bd49de27f770e62d36871dbd335f82684c526a8631b19da6dc2b5651608" +DEFAULT_EVIDENCE_ROOT = Path("/usr/share/phios/nbga") +MAX_DOCUMENT_BYTES = 128 * 1024 +MAX_RECORDS = 64 +MAX_HOPS = 32 +_DIGEST = re.compile(r"[0-9a-f]{64}\Z") +_IDENTIFIER = re.compile(r"[a-z0-9][a-z0-9:._-]{0,255}\Z") +_FILENAME = re.compile(r"[a-z0-9][a-z0-9._-]{0,127}\.json\Z") + + +class ObservationUnavailableError(NBGContractError): + """The entire observation is refused when its public evidence cannot be checked.""" + + +def _keys(value: object, required: set[str]) -> dict[str, object]: + if not isinstance(value, dict) or set(value) != required: + raise ObservationUnavailableError("invalid or unknown packet fields") + return value + + +def _text(value: object, *, identifier: bool = False) -> str: + if not isinstance(value, str) or not value.strip(): + raise ObservationUnavailableError("invalid observation text") + try: + oversized = len(value.encode("utf-8")) > 4096 + except UnicodeError as exc: + raise ObservationUnavailableError("invalid observation text encoding") from exc + if oversized or (identifier and not _IDENTIFIER.fullmatch(value)): + raise ObservationUnavailableError("observation text exceeds its allowed format") + return value + + +def _digest(value: object) -> str: + if not isinstance(value, str) or not _DIGEST.fullmatch(value): + raise ObservationUnavailableError("a full lowercase SHA-256 pin is required") + return value + + +def _integer(value: object, maximum: int) -> int: + if isinstance(value, bool) or not isinstance(value, int) or not 1 <= value <= maximum: + raise ObservationUnavailableError("invalid bounded integer") + return value + + +def _array(value: object, *, maximum: int = MAX_RECORDS, allow_empty: bool = False) -> list[object]: + if not isinstance(value, list) or len(value) > maximum or (not value and not allow_empty): + raise ObservationUnavailableError("invalid bounded observation array") + return value + + +def _json(raw: bytes) -> object: + def pairs(items: list[tuple[str, object]]) -> dict[str, object]: + result: dict[str, object] = {} + for key, value in items: + if key in result: + raise ObservationUnavailableError("duplicate JSON field") + result[key] = value + return result + + def constant(_: str) -> None: + raise ObservationUnavailableError("non-finite JSON number") + + try: + return json.loads(raw.decode("utf-8"), object_pairs_hook=pairs, parse_constant=constant) + except (UnicodeError, ValueError, RecursionError) as exc: + if isinstance(exc, ObservationUnavailableError): + raise + raise ObservationUnavailableError("invalid public observation JSON") from exc + + +def _read(root: Path, filename: str) -> bytes: + # Only a basename is accepted. No paths, discovery, URLs or subprocesses. + if not _FILENAME.fullmatch(filename): + raise ObservationUnavailableError("invalid evidence filename") + path = root / filename + try: + if path.is_symlink(): + raise ObservationUnavailableError("symbolic-link evidence is refused") + flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0) + with os.fdopen(os.open(path, flags), "rb") as stream: + before = os.fstat(stream.fileno()) + if not stat.S_ISREG(before.st_mode) or before.st_size > MAX_DOCUMENT_BYTES: + raise ObservationUnavailableError("evidence must be a bounded regular file") + raw = stream.read(MAX_DOCUMENT_BYTES + 1) + after = os.fstat(stream.fileno()) + if (len(raw) != before.st_size or len(raw) > MAX_DOCUMENT_BYTES + or (before.st_size, before.st_mtime_ns) != (after.st_size, after.st_mtime_ns)): + raise ObservationUnavailableError("evidence changed during its read") + return raw + except OSError as exc: + # Do not echo host paths or arbitrary file contents in refusal output. + raise ObservationUnavailableError("public evidence file unavailable") from exc + + +@dataclass(frozen=True, slots=True) +class EvidencePin: + id: str + filename: str + sha256: str + size_bytes: int + + +@dataclass(frozen=True, slots=True) +class ObservationReport: + packet_id: str + packet_sha256: str + evidence: tuple[EvidencePin, ...] + receipts: tuple[MemoryReceipt, ...] + + def to_payload(self) -> dict[str, object]: + receipts = [] + for receipt in self.receipts: + payload = {"schema_version": MEMORY_RECEIPT_SCHEMA, **asdict(receipt)} + payload["evidence"] = list(receipt.evidence) + payload["gear_path"] = [asdict(hop) for hop in receipt.gear_path] + receipts.append(payload) + return { + "schema_version": RESULT_SCHEMA, + "packet_id": self.packet_id, + "packet_sha256": self.packet_sha256, + "provider_mode": "read-only", + "evidence_integrity": "verified-against-pins", + "checked_documents": [asdict(pin) for pin in self.evidence], + "observations": receipts, + "bubble_zero": {"availability": "unavailable", "reason": "no continuity backend"}, + "release_ready": False, + "publication_authority": False, + } + + +def observe( + evidence_root: Path = DEFAULT_EVIDENCE_ROOT, + *, + expected_packet_sha256: str = PINNED_PACKET_SHA256, + bubble_id: str | None = None, +) -> ObservationReport: + """Read the whole pinned packet before returning any selected observation. + + A custom pin is a caller-owned trust input, never a value accepted from the + packet itself. Success checks documentary bytes, not truth or release readiness. + """ + expected = _digest(expected_packet_sha256) + try: + root = evidence_root.resolve(strict=True) + if not root.is_dir(): + raise ObservationUnavailableError("an explicit evidence directory is required") + except (OSError, ValueError, RuntimeError) as exc: + raise ObservationUnavailableError("public evidence directory unavailable") from exc + raw = _read(root, PACKET_FILENAME) + if hashlib.sha256(raw).hexdigest() != expected: + raise ObservationUnavailableError("observation packet integrity mismatch") + packet = _keys(_json(raw), {"schema_version", "packet_id", "evidence", "observations"}) + if packet["schema_version"] != PACKET_SCHEMA: + raise ObservationUnavailableError("unsupported observation packet schema") + packet_id = _text(packet["packet_id"], identifier=True) + pins: dict[str, EvidencePin] = {} + filenames: set[str] = set() + for item in _array(packet["evidence"]): + row = _keys(item, {"id", "filename", "sha256", "size_bytes"}) + pin = EvidencePin(_text(row["id"], identifier=True), _text(row["filename"]), + _digest(row["sha256"]), _integer(row["size_bytes"], MAX_DOCUMENT_BYTES)) + if pin.id in pins or pin.filename in filenames: + raise ObservationUnavailableError("duplicate evidence identity or filename") + data = _read(root, pin.filename) + if len(data) != pin.size_bytes or hashlib.sha256(data).hexdigest() != pin.sha256: + raise ObservationUnavailableError("evidence document integrity mismatch") + pins[pin.id] = pin + filenames.add(pin.filename) + + rows = [_keys(row, {"bubble_id", "bubble_version", "observable", "trust_state", "evidence", + "gear_path", "event_head"}) for row in _array(packet["observations"])] + identities = [_text(row["bubble_id"], identifier=True) for row in rows] + if len(set(identities)) != len(identities): + raise ObservationUnavailableError("duplicate observation bubble") + lineage = {identity: {_text(ref, identifier=True) for ref in _array(row["evidence"])} + for identity, row in zip(identities, rows, strict=True)} + used: set[str] = set() + definitions: dict[str, GearHop] = {} + receipts = [] + for row, identity in zip(rows, identities, strict=True): + references = tuple(_text(ref, identifier=True) for ref in _array(row["evidence"])) + if len(set(references)) != len(references) or any(ref not in pins for ref in references): + raise ObservationUnavailableError("missing or repeated evidence reference") + used.update(references) + event_head = _text(row["event_head"], identifier=True) + if event_head != references[-1]: + raise ObservationUnavailableError("documentary head must resolve to the final evidence") + trust_state = row["trust_state"] + if trust_state not in ("owner-reported", "reviewed-ci-record"): + raise ObservationUnavailableError("unsupported observation trust state") + hops = tuple(GearHop.from_payload(hop) for hop in + _array(row["gear_path"], maximum=MAX_HOPS, allow_empty=True)) + visited: set[str] = set() + for index, hop in enumerate(hops): + for value in (hop.gear_id, hop.source, hop.destination): + _text(value, identifier=True) + if hop.transform != "documented-follow-up": + raise ObservationUnavailableError("unsupported documentary transformation") + if hop.source not in identities or hop.destination not in identities: + raise ObservationUnavailableError("gear path references an unknown bubble") + if not (lineage[hop.source] | lineage[hop.destination]).issubset(references): + raise ObservationUnavailableError("gear lineage evidence is missing") + if index and hop.source != hops[index - 1].destination: + raise ObservationUnavailableError("disconnected directional gear path") + visited.add(hop.source) + if hop.destination in visited: + raise ObservationUnavailableError("cyclic directional gear path") + prior = definitions.setdefault(hop.gear_id, hop) + if prior != hop: + raise ObservationUnavailableError("conflicting gear definition") + if hops and hops[-1].destination != identity: + raise ObservationUnavailableError("gear path does not end at its observation") + provenance = json.dumps({"schema_version": "phios.nbga.document-provenance.v1", + "packet_sha256": expected, "evidence": [asdict(pins[ref]) for ref in references]}, + sort_keys=True, separators=(",", ":"), ensure_ascii=False, allow_nan=False).encode() + receipts.append(MemoryReceipt.from_payload({ + "schema_version": MEMORY_RECEIPT_SCHEMA, "bubble_id": identity, + "bubble_version": _integer(row["bubble_version"], 2**53 - 1), + "observable": _text(row["observable"]), "trust_state": trust_state, + "confidence": None, "evidence": list(references), + "gear_path": [asdict(hop) for hop in hops], "event_head": event_head, + "provenance_root": "sha256:" + hashlib.sha256(provenance).hexdigest(), + })) + if used != set(pins): + raise ObservationUnavailableError("unreferenced evidence document") + if bubble_id is not None: + selected = _text(bubble_id, identifier=True) + receipts = [receipt for receipt in receipts if receipt.bubble_id == selected] + if not receipts: + raise ObservationUnavailableError("unknown observation bubble") + return ObservationReport(packet_id, expected, tuple(pins.values()), tuple(receipts)) + + +def main(argv: Sequence[str] | None = None) -> int: + parser = argparse.ArgumentParser(description="Read pinned public NBG-A qualification observations") + parser.add_argument("--evidence-root", type=Path, default=DEFAULT_EVIDENCE_ROOT) + parser.add_argument("--bubble-id", help="Select a bubble after checking the entire evidence packet") + args = parser.parse_args(argv) + try: + result = observe(args.evidence_root, bubble_id=args.bubble_id).to_payload() + except NBGContractError as exc: + print(json.dumps({"schema_version": RESULT_SCHEMA, "availability": "unavailable", + "reason": str(exc), "release_ready": False, + "publication_authority": False}, sort_keys=True)) + return 2 + print(json.dumps(result, sort_keys=True, ensure_ascii=False, allow_nan=False)) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tests/test_nbga_contract_v01.py b/tests/test_nbga_contract_v01.py new file mode 100644 index 00000000..3147dc72 --- /dev/null +++ b/tests/test_nbga_contract_v01.py @@ -0,0 +1,126 @@ +from __future__ import annotations + +import pytest + +from phios.adapters.nbga import ( + BUBBLE_ZERO_STATUS_SCHEMA, + MEMORY_RECEIPT_SCHEMA, + BubbleZeroStatus, + MemoryReceipt, + NBGContractError, +) + + +def memory_payload() -> dict[str, object]: + return { + "schema_version": MEMORY_RECEIPT_SCHEMA, + "bubble_id": "bubble:phios:vm-qualification", + "bubble_version": 3, + "observable": "The qualified candidate completed the VirtualBox compatibility path.", + "trust_state": "verified", + "confidence": 1.0, + "evidence": ["event:qualification:36916494462", "artifact:iso:33bfb342"], + "gear_path": [ + { + "gear_id": "gear:project-to-qualification", + "transform": "evidence", + "source": "bubble:phios", + "destination": "bubble:phios:vm-qualification", + } + ], + "event_head": "event:qualification:36916494462", + "provenance_root": "sha256:receipt-root", + } + + +def bubble_zero_payload() -> dict[str, object]: + return { + "schema_version": BUBBLE_ZERO_STATUS_SCHEMA, + "system_id": "phios", + "epoch": 7, + "verified": True, + "governance_root": "sha256:governance", + "event_log_head": "sha256:event-head", + "topology_root": "sha256:topology", + "anchor_root": "sha256:anchor", + "commitment_root": "sha256:commitments", + "last_checkpoint": "checkpoint:7", + } + + +def test_memory_receipt_accepts_only_normalized_observable_state() -> None: + receipt = MemoryReceipt.from_payload(memory_payload()) + + assert receipt.bubble_id == "bubble:phios:vm-qualification" + assert receipt.bubble_version == 3 + assert receipt.trust_state == "verified" + assert receipt.gear_path[0].transform == "evidence" + assert receipt.gear_path[0].source == "bubble:phios" + assert receipt.gear_path[0].destination == "bubble:phios:vm-qualification" + + +@pytest.mark.parametrize( + "field", + ["payload", "payload_ref", "internal_state", "raw_state", "private_state", "secret"], +) +def test_memory_receipt_rejects_private_or_internal_state(field: str) -> None: + payload = memory_payload() + payload[field] = "must-not-cross-boundary" + + with pytest.raises(NBGContractError, match="forbidden"): + MemoryReceipt.from_payload(payload) + + +@pytest.mark.parametrize("field", ["authority", "authority_grant", "capability_grant"]) +def test_memory_receipt_cannot_smuggle_authority(field: str) -> None: + payload = memory_payload() + payload[field] = "elevated" + + with pytest.raises(NBGContractError, match="forbidden"): + MemoryReceipt.from_payload(payload) + + +def test_memory_receipt_fails_closed_on_unknown_contract_fields() -> None: + payload = memory_payload() + payload["implementation_hint"] = "private-routing-algorithm" + + with pytest.raises(NBGContractError, match="unknown"): + MemoryReceipt.from_payload(payload) + + +@pytest.mark.parametrize("confidence", [-0.01, 1.01, float("inf"), float("nan"), True]) +def test_memory_receipt_rejects_invalid_confidence(confidence: object) -> None: + payload = memory_payload() + payload["confidence"] = confidence + + with pytest.raises(NBGContractError, match="confidence"): + MemoryReceipt.from_payload(payload) + + +def test_bubble_zero_status_is_minimal_continuity_projection() -> None: + status = BubbleZeroStatus.from_payload(bubble_zero_payload()) + + assert status.system_id == "phios" + assert status.epoch == 7 + assert status.verified is True + assert status.last_checkpoint == "checkpoint:7" + + +def test_bubble_zero_rejects_raw_state_and_authority() -> None: + for field in ("raw_state", "authority"): + payload = bubble_zero_payload() + payload[field] = "not-public" + with pytest.raises(NBGContractError, match="forbidden"): + BubbleZeroStatus.from_payload(payload) + + +def test_contract_schema_versions_are_explicit_and_fail_closed() -> None: + receipt = memory_payload() + receipt["schema_version"] = "phikernel.nbga.memory-receipt.v2" + with pytest.raises(NBGContractError, match="schema_version"): + MemoryReceipt.from_payload(receipt) + + status = bubble_zero_payload() + status["schema_version"] = "phikernel.nbga.bubble-zero-status.v2" + with pytest.raises(NBGContractError, match="schema_version"): + BubbleZeroStatus.from_payload(status) diff --git a/tests/test_nbga_observation_v01.py b/tests/test_nbga_observation_v01.py new file mode 100644 index 00000000..99867a8e --- /dev/null +++ b/tests/test_nbga_observation_v01.py @@ -0,0 +1,206 @@ +from __future__ import annotations + +import hashlib +import json +import os +import shutil +import subprocess +import sys +from pathlib import Path + +import pytest + +from phios.adapters.nbga import MemoryReceipt, NBGContractError +from phios.adapters.nbga_observation import ( + MAX_DOCUMENT_BYTES, + PACKET_FILENAME, + PINNED_PACKET_SHA256, + observe, +) + +ROOT = Path(__file__).parents[1] +EVIDENCE = ROOT / "docs/os/evidence" +LATEST = "bubble:phios:virtualbox:launcher-0f17bac1" + + +@pytest.fixture +def packet_root(tmp_path: Path) -> Path: + packet = json.loads((EVIDENCE / PACKET_FILENAME).read_bytes()) + shutil.copyfile(EVIDENCE / PACKET_FILENAME, tmp_path / PACKET_FILENAME) + for item in packet["evidence"]: + shutil.copyfile(EVIDENCE / item["filename"], tmp_path / item["filename"]) + return tmp_path + + +def changed_packet(root: Path, change) -> str: + packet = json.loads((root / PACKET_FILENAME).read_bytes()) + change(packet) + raw = (json.dumps(packet, ensure_ascii=False, allow_nan=False) + "\n").encode() + (root / PACKET_FILENAME).write_bytes(raw) + # Test-owned pins permit schema refusal tests to reach the parser. Production + # uses the independent code pin, never a digest read from the packet itself. + return hashlib.sha256(raw).hexdigest() + + +def test_real_packet_preserves_failures_sources_and_reported_trust(): + result = observe(EVIDENCE) + payload = result.to_payload() + assert len(result.evidence) == len(result.receipts) == 4 + assert result.packet_sha256 == PINNED_PACKET_SHA256 + original, failure, automatic, latest = result.receipts + assert "renderer failed with 3D off" in original.observable + assert "WLR_NO_HARDWARE_CURSORS=1 restored the pointer" in original.observable + assert "restarting the session target restored PhiShell/Waybar" in original.observable + assert "installation/recovery was skipped" in failure.observable + assert failure.trust_state == "reviewed-ci-record" + assert "wrong-password refusal/PAM unlock was not tested" in automatic.observable + assert "8635a5f1277ca01ef7174b6e3b325e3cf9e972572070eb84d7395b9cec3dcd08" in latest.observable + assert "canonical history unavailable" in latest.observable + assert latest.trust_state == "owner-reported" and latest.confidence is None + assert len(latest.gear_path) == 3 and latest.gear_path[-1].destination == LATEST + assert payload["bubble_zero"] == {"availability": "unavailable", "reason": "no continuity backend"} + assert payload["release_ready"] is payload["publication_authority"] is False + for receipt in payload["observations"]: + assert MemoryReceipt.from_payload(receipt).provenance_root.startswith("sha256:") + + +def test_repeated_reads_are_deterministic_and_create_no_files(packet_root: Path): + before = {p.name: p.read_bytes() for p in packet_root.iterdir()} + first = observe(packet_root).to_payload() + assert observe(packet_root).to_payload() == first + assert {p.name: p.read_bytes() for p in packet_root.iterdir()} == before + assert observe(packet_root, bubble_id=LATEST).receipts == (observe(packet_root).receipts[-1],) + + +@pytest.mark.parametrize("alteration", ["missing", "content", "size", "symlink", "directory", "large"]) +def test_unavailable_or_changed_prior_failure_blocks_latest_query(packet_root: Path, alteration: str): + path = packet_root / "virtualbox-compatibility-attempts.json" + if alteration == "content": + raw = path.read_bytes() + path.write_bytes(raw.replace(b"failed at", b"passed at", 1)) + elif alteration == "size": + path.write_bytes(path.read_bytes() + b" ") + elif alteration == "large": + path.write_bytes(b"x" * (MAX_DOCUMENT_BYTES + 1)) + else: + path.unlink() + if alteration == "symlink": + path.symlink_to(EVIDENCE / path.name) + elif alteration == "directory": + path.mkdir() + with pytest.raises(NBGContractError): + observe(packet_root, bubble_id=LATEST) + + +@pytest.mark.skipif(not hasattr(os, "mkfifo"), reason="FIFO refusal is a POSIX case") +def test_fifo_evidence_is_refused_without_waiting_for_a_writer(packet_root: Path): + path = packet_root / "virtualbox-compatibility-attempts.json" + path.unlink() + os.mkfifo(path) + with pytest.raises(NBGContractError): + observe(packet_root) + + +def test_packet_cannot_self_assert_its_own_pin(packet_root: Path): + changed_packet(packet_root, lambda packet: packet["observations"][-1].update(trust_state="verified")) + with pytest.raises(NBGContractError, match="packet integrity"): + observe(packet_root) + + +@pytest.mark.parametrize("field", ["raw_state", "payload_ref", "authority_grant", "unknown"]) +@pytest.mark.parametrize("level", ["packet", "observation", "evidence", "gear"]) +def test_private_authority_or_unknown_fields_fail_closed(packet_root: Path, field: str, level: str): + def change(packet): + target = {"packet": packet, "observation": packet["observations"][-1], + "evidence": packet["evidence"][0], "gear": packet["observations"][-1]["gear_path"][0]}[level] + target[field] = "must-not-cross" + expected = changed_packet(packet_root, change) + with pytest.raises(NBGContractError): + observe(packet_root, expected_packet_sha256=expected) + + +@pytest.mark.parametrize("filename", ["../outside.json", "/outside.json", "sub/file.json", "sub\\file.json", "https://example.test/file.json"]) +def test_evidence_filenames_cannot_escape_the_selected_directory(packet_root: Path, filename: str): + expected = changed_packet(packet_root, lambda packet: packet["evidence"][0].update(filename=filename)) + with pytest.raises(NBGContractError, match="filename"): + observe(packet_root, expected_packet_sha256=expected) + + +@pytest.mark.parametrize("case", ["unknown-schema", "duplicate-id", "duplicate-file", "duplicate-bubble", "missing-ref", "missing-lineage", "repeated-ref", "head", "trust", "confidence", "version-bool", "size-bool", "digest", "disconnected", "cycle", "unknown-bubble", "wrong-end", "conflicting-gear", "unreferenced", "oversized-array", "oversized-text"]) +def test_malformed_lineage_and_unearned_verification_are_refused(packet_root: Path, case: str): + def change(packet): + latest = packet["observations"][-1] + if case == "unknown-schema": + packet["schema_version"] += "-unknown" + elif case == "duplicate-id": + packet["evidence"][1]["id"] = packet["evidence"][0]["id"] + elif case == "duplicate-file": + packet["evidence"][1]["filename"] = packet["evidence"][0]["filename"] + elif case == "duplicate-bubble": + latest["bubble_id"] = packet["observations"][0]["bubble_id"] + elif case == "missing-ref": + latest["evidence"][0] = "document:missing" + elif case == "missing-lineage": + latest["evidence"].pop(0) + elif case == "repeated-ref": + latest["evidence"][0] = latest["evidence"][1] + elif case == "head": + latest["event_head"] = "document:missing" + elif case == "trust": + latest["trust_state"] = "verified" + elif case == "confidence": + latest["confidence"] = 1.0 + elif case == "version-bool": + latest["bubble_version"] = True + elif case == "size-bool": + packet["evidence"][0]["size_bytes"] = True + elif case == "digest": + packet["evidence"][0]["sha256"] = "sha256:..." + elif case == "disconnected": + latest["gear_path"][1]["source"] = latest["bubble_id"] + elif case == "cycle": + latest["gear_path"][1]["destination"] = latest["gear_path"][0]["source"] + elif case == "unknown-bubble": + latest["gear_path"][0]["source"] = "bubble:missing" + elif case == "wrong-end": + latest["gear_path"].pop() + elif case == "conflicting-gear": + latest["gear_path"][-1]["gear_id"] = latest["gear_path"][0]["gear_id"] + elif case == "unreferenced": + packet["observations"].pop() + elif case == "oversized-array": + packet["observations"] *= 65 + elif case == "oversized-text": + latest["observable"] = "x" * 4097 + expected = changed_packet(packet_root, change) + with pytest.raises(NBGContractError): + observe(packet_root, expected_packet_sha256=expected) + + +@pytest.mark.parametrize("wire", [b'{"schema_version":1,"schema_version":2}', b'{"value":NaN}', b'\xff', b'{']) +def test_ambiguous_nonfinite_or_invalid_json_is_refused(packet_root: Path, wire: bytes): + (packet_root / PACKET_FILENAME).write_bytes(wire) + with pytest.raises(NBGContractError): + observe(packet_root, expected_packet_sha256=hashlib.sha256(wire).hexdigest()) + + +@pytest.mark.parametrize("pin", ["", "sha256:...", "A" * 64]) +def test_explicit_pin_must_be_a_complete_canonical_digest(packet_root: Path, pin: str): + with pytest.raises(NBGContractError, match="SHA-256"): + observe(packet_root, expected_packet_sha256=pin) + + +def test_cli_success_refusal_and_no_host_path_disclosure(packet_root: Path): + command = [sys.executable, "-m", "phios.adapters.nbga_observation", "--evidence-root", str(packet_root)] + success = subprocess.run(command + ["--bubble-id", LATEST], capture_output=True, text=True, timeout=5) + assert success.returncode == 0 and success.stderr == "" + assert len(json.loads(success.stdout)["observations"]) == 1 + unknown = subprocess.run(command + ["--bubble-id", "bubble:missing"], capture_output=True, text=True, timeout=5) + assert unknown.returncode == 2 and "observations" not in json.loads(unknown.stdout) + (packet_root / "virtualbox-compatibility-attempts.json").unlink() + failed = subprocess.run(command + ["--bubble-id", LATEST], capture_output=True, text=True, timeout=5) + payload = json.loads(failed.stdout) + assert failed.returncode == 2 and failed.stderr == "" + assert payload["availability"] == "unavailable" and "observations" not in payload + assert str(packet_root) not in failed.stdout + assert payload["publication_authority"] is False