diff --git a/README.md b/README.md index 1c19c5ee..a3ddc02c 100644 --- a/README.md +++ b/README.md @@ -53,7 +53,7 @@ identity does not inherit old authority merely because continuity was demonstrat |---|---:|---| | **Shell / MCP** | active | operator interface, workflows, resources, prompts, capability surfaces | | **Spine** | **v0.24** | authority-aware observation, verification, evidence, and receipts | -| **App Platform** | **v0.50** | governed intake, build, install, launch, update, rollback, cleanup, and release lineage | +| **App Platform** | **v0.51** | governed intake, toolchain matching, build, install, launch, update, rollback, cleanup, and release lineage | | **PhiReflex** | **v0.10** | provider-neutral fast advisory layer with authenticated bounded routing influence | | **Governed Memory** | active | canonical local memory, derived semantic index, read admissibility, temporal horizon | | **Reality Ledger** | active | append-only evidence plus bounded read-only analytics | @@ -172,10 +172,10 @@ unless the broader claim is separately observed and verified. Current contract: [Spine v0.24 numeric-transition verification](docs/PHIOS_SPINE_V0.24_NUMERIC_TRANSITION_CONTRACT.md). -### App Platform v0.50 +### App Platform v0.51 The App Platform provides a governed lifecycle from public source intake through -exact-commit acquisition, reviewed build planning, Linux sandboxing, dependency staging, +exact-commit acquisition, reviewed build planning, digest-bound toolchain capsule matching, Linux sandboxing, dependency staging, offline build, artifact installation, visible/persistent launch, app cataloging, side-by-side update, separately authorized rollback, cleanup recovery, release discovery, human review, execution lineage, package lineage, and release-install proposal gating. @@ -194,7 +194,9 @@ update != rollback authority ``` Current contract: -[App Platform v0.50 release-install proposal gate](docs/PHIOS_APP_PLATFORM_V0.50_RELEASE_INSTALL_PROPOSAL_GATE.md). +[App Platform v0.51 toolchain capsules](docs/PHIOS_APP_PLATFORM_V0.51_TOOLCHAIN_CAPSULES.md). + +v0.51 is additive: capsule compatibility is review evidence only and does not grant execution, network, install, or host-write authority. ### PhiReflex v0.10 diff --git a/docs/PHIOS_APP_PLATFORM_V0.51_TOOLCHAIN_CAPSULES.md b/docs/PHIOS_APP_PLATFORM_V0.51_TOOLCHAIN_CAPSULES.md new file mode 100644 index 00000000..7a8b30e5 --- /dev/null +++ b/docs/PHIOS_APP_PLATFORM_V0.51_TOOLCHAIN_CAPSULES.md @@ -0,0 +1,210 @@ +# PhiOS App Platform v0.51 — Toolchain Capsule Contract + +## Status + +Alpha contract. + +New schemas: + +- `phios.toolchain_requirement.v0.1` +- `phios.toolchain_capsule.v0.1` +- `phios.toolchain_binding.v0.1` + +## Purpose + +v0.28 can already identify several build families and the tools they require. v0.29 can probe and execute host tools. That is useful, but it leaves a gap between: + +```text +this build needs Python / Node / Rust / Go +``` + +and: + +```text +these exact toolchain bytes are the environment reviewed for this build +``` + +v0.51 introduces a declarative, digest-bound toolchain-capsule contract. + +The central rule is: + +> A toolchain can be compatible with a build without having authority to execute it. + +## Supported v0.51 families + +The first contract recognizes exactly four Linux x86_64 families: + +| Family | Required tools | +| --- | --- | +| `node_npm` | `node`, `npm` | +| `python_pep517` | `python`, `python-build` | +| `rust_cargo` | `cargo`, `rustc` | +| `go_module` | `go` | + +Current pnpm, Yarn and Bun build plans remain valid v0.28 observations, but v0.51 classifies them as `unsupported_toolchain`. Future adapters must get their own explicit contract rather than silently borrowing Node/npm semantics. + +Static-web source that requires no build produces `no_capsule_required`. + +## Requirement derivation + +`derive_toolchain_requirement()` consumes an exact v0.28 `BuildPlan` and binds: + +- app identity; +- exact commit; +- canonical build-plan SHA-256; +- strategy; +- required tools; +- one supported family when deterministically recognized; +- status. + +Possible statuses are: + +- `capsule_required` +- `no_capsule_required` +- `unsupported_toolchain` + +Every requirement fixes: + +```text +execution_authority = false +``` + +A requirement is evidence about what a build needs. It is not permission to obtain or run a toolchain. + +## Capsule contract + +A v0.51 capsule declares: + +- bounded capsule ID; +- toolchain family; +- platform = `linux_x86_64`; +- artifact kind = `oci_image`; +- immutable artifact SHA-256; +- artifact reference; +- exact tool names and version strings; +- canonical capsule SHA-256. + +The family fixes the exact tool-name set. A Node/npm capsule cannot omit npm, add pnpm, or masquerade as a Rust capsule. + +The artifact reference is descriptive. The artifact SHA-256 is the immutable identity field. + +v0.51 does not download, inspect, start or trust the referenced OCI artifact. Artifact acquisition and verification are separate future boundaries. + +## Fixed zero-authority fields + +Every capsule and every successful binding fixes: + +```text +execution_authority = false +network_authority = false +install_authority = false +host_write_authority = false +``` + +These fields are validated, hashed, and fail closed if changed. + +Therefore: + +```text +capsule exists +!= capsule acquired + +capsule acquired +!= capsule verified + +capsule verified +!= build may execute + +capsule matches requirement +!= build may execute + +build may execute +!= network authority + +build succeeds +!= install authority +``` + +## Binding + +`bind_toolchain_capsule()` accepts only: + +- a `capsule_required` requirement; +- an exact matching family; +- an exact matching tool set. + +A successful binding records: + +- app/commit/build-plan identity; +- requirement SHA-256; +- capsule SHA-256; +- family; +- status = `compatible_for_review`; +- fixed zero-authority fields. + +The binding is review evidence only. + +## Fail-closed behavior + +v0.51 rejects: + +- unknown schema fields; +- malformed digests; +- duplicate tools; +- missing or extra family tools; +- unsupported platform or artifact kind; +- non-false authority fields; +- digest tampering; +- capsule binding for a no-build or unsupported requirement; +- family mismatch; +- tool-set mismatch. + +## Explicit non-capabilities + +v0.51 does not: + +- pull OCI images; +- invoke Docker, Podman, Bubblewrap or another container runtime; +- execute Node, npm, Python, Cargo, Rust or Go; +- install a compiler into the base PhiOS image; +- grant network access; +- grant host filesystem writes; +- replace v0.30 sandbox approval; +- replace dependency-broker approval; +- install or launch an application; +- infer trust from a version string; +- make a release-ready claim. + +## Why capsules instead of a giant ISO + +The base operating system should not need every compiler and package manager merely because a public repository might use one. + +The intended future flow is: + +```text +GitHub intake + -> exact source acquisition + -> build plan + -> toolchain requirement + -> reviewed capsule binding + -> verified capsule acquisition + -> dependency broker + -> network-denied sandbox execution + -> artifact verification + -> governed install +``` + +This keeps the base image smaller and preserves the PhiOS rule that capability and authority are separate. + +## Next boundary + +v0.52 should introduce governed capsule acquisition and verification. + +That rung should prove that the locally available capsule bytes match the exact reviewed v0.51 artifact identity before any build executor can consume them. + +It must still preserve: + +```text +verified capsule +!= execution authority +``` diff --git a/phios/apps/__init__.py b/phios/apps/__init__.py index 2afaed0a..bc269fef 100644 --- a/phios/apps/__init__.py +++ b/phios/apps/__init__.py @@ -281,6 +281,20 @@ plan_static_web_adapter, review_static_web_adapter, ) +from .toolchain_capsule import ( + TOOLCHAIN_BINDING_SCHEMA_VERSION, + TOOLCHAIN_CAPSULE_SCHEMA_VERSION, + TOOLCHAIN_REQUIREMENT_SCHEMA_VERSION, + ToolchainBinding, + ToolchainCapsule, + ToolchainFamily, + ToolchainPlatform, + ToolchainRequirement, + ToolchainRequirementStatus, + ToolchainTool, + bind_toolchain_capsule, + derive_toolchain_requirement, +) from .visible_browser import ( VISIBLE_BROWSER_PLAN_SCHEMA_VERSION, VISIBLE_BROWSER_RECEIPT_SCHEMA_VERSION, @@ -360,6 +374,9 @@ "STATIC_WEB_ADAPTER_PLAN_SCHEMA_VERSION", "STATIC_WEB_ADAPTER_REVIEW_SCHEMA_VERSION", "STATIC_WEB_SERVE_RECEIPT_SCHEMA_VERSION", + "TOOLCHAIN_BINDING_SCHEMA_VERSION", + "TOOLCHAIN_CAPSULE_SCHEMA_VERSION", + "TOOLCHAIN_REQUIREMENT_SCHEMA_VERSION", "VISIBLE_BROWSER_PLAN_SCHEMA_VERSION", "VISIBLE_BROWSER_RECEIPT_SCHEMA_VERSION", "VISIBLE_BROWSER_REVIEW_SCHEMA_VERSION", @@ -505,6 +522,13 @@ "StaticWebServeRequest", "StaticWebServeResult", "SuccessfulBuildBinding", + "ToolchainBinding", + "ToolchainCapsule", + "ToolchainFamily", + "ToolchainPlatform", + "ToolchainRequirement", + "ToolchainRequirementStatus", + "ToolchainTool", "StreamCapture", "SubprocessBuildRunner", "SubprocessNpmCommandRunner", @@ -519,7 +543,9 @@ "WaylandBubblewrapRuntimeRunner", "WaylandDisplayEvidence", "WaylandSocketIdentity", + "bind_toolchain_capsule", "default_phios_control_plane_surfaces", + "derive_toolchain_requirement", "evaluate_control_plane_isolation", "derive_npm_offline_build_plan", "inspect_public_github_app", diff --git a/phios/apps/toolchain_capsule.py b/phios/apps/toolchain_capsule.py new file mode 100644 index 00000000..bbc1219d --- /dev/null +++ b/phios/apps/toolchain_capsule.py @@ -0,0 +1,486 @@ +from __future__ import annotations + +import hashlib +import json +import re +from dataclasses import dataclass +from typing import Any, Literal, cast + +from .build_plan import BuildPlan + +TOOLCHAIN_REQUIREMENT_SCHEMA_VERSION = "phios.toolchain_requirement.v0.1" +TOOLCHAIN_CAPSULE_SCHEMA_VERSION = "phios.toolchain_capsule.v0.1" +TOOLCHAIN_BINDING_SCHEMA_VERSION = "phios.toolchain_binding.v0.1" + +ToolchainFamily = Literal["node_npm", "python_pep517", "rust_cargo", "go_module"] +ToolchainRequirementStatus = Literal[ + "capsule_required", + "no_capsule_required", + "unsupported_toolchain", +] +ToolchainPlatform = Literal["linux_x86_64"] + +_SHA256_RE = re.compile(r"^[0-9a-f]{64}$") +_CAPSULE_ID_RE = re.compile(r"^[a-z0-9][a-z0-9._-]{0,95}$") +_TOOL_RE = re.compile(r"^[a-z0-9][a-z0-9._+-]{0,63}$") + +_FAMILY_TOOLS: dict[ToolchainFamily, frozenset[str]] = { + "node_npm": frozenset({"node", "npm"}), + "python_pep517": frozenset({"python", "python-build"}), + "rust_cargo": frozenset({"cargo", "rustc"}), + "go_module": frozenset({"go"}), +} + + +def _mapping(value: Any, label: str) -> dict[str, Any]: + if not isinstance(value, dict): + raise ValueError(f"{label} must be an object") + return cast(dict[str, Any], value) + + +def _string(value: Any, label: str, *, maximum: int = 1024) -> str: + if not isinstance(value, str) or not value: + raise ValueError(f"{label} must be a non-empty string") + if len(value) > maximum: + raise ValueError(f"{label} exceeds {maximum} characters") + if any(ord(char) < 32 for char in value): + raise ValueError(f"{label} contains control characters") + return value + + +def _sha256(value: Any, label: str) -> str: + text = _string(value, label, maximum=64) + if not _SHA256_RE.fullmatch(text): + raise ValueError(f"{label} must be a lowercase SHA-256 digest") + return text + + +def _false(value: Any, label: str) -> bool: + if value is not False: + raise ValueError(f"{label} must remain false") + return False + + +def _family(value: Any, label: str = "family") -> ToolchainFamily: + if value not in _FAMILY_TOOLS: + raise ValueError(f"Unsupported {label}: {value}") + return cast(ToolchainFamily, value) + + +@dataclass(frozen=True) +class ToolchainTool: + name: str + version: str + + def __post_init__(self) -> None: + if not _TOOL_RE.fullmatch(self.name): + raise ValueError(f"Invalid tool name: {self.name}") + _string(self.version, "tool version", maximum=96) + + def to_dict(self) -> dict[str, str]: + return {"name": self.name, "version": self.version} + + @classmethod + def from_dict(cls, value: Any) -> ToolchainTool: + data = _mapping(value, "toolchain tool") + if set(data) != {"name", "version"}: + raise ValueError("toolchain tool contains missing or unknown fields") + return cls( + name=_string(data["name"], "tool name", maximum=64), + version=_string(data["version"], "tool version", maximum=96), + ) + + +@dataclass(frozen=True) +class ToolchainRequirement: + app_id: str + commit_sha: str + plan_sha256: str + strategy: str + family: ToolchainFamily | None + required_tools: tuple[str, ...] + status: ToolchainRequirementStatus + execution_authority: bool = False + schema_version: str = TOOLCHAIN_REQUIREMENT_SCHEMA_VERSION + + def __post_init__(self) -> None: + if self.schema_version != TOOLCHAIN_REQUIREMENT_SCHEMA_VERSION: + raise ValueError(f"Unsupported toolchain requirement schema: {self.schema_version}") + _string(self.app_id, "app_id", maximum=64) + if not re.fullmatch(r"^[0-9a-f]{40,64}$", self.commit_sha): + raise ValueError("commit_sha must be a lowercase hexadecimal commit identifier") + _sha256(self.plan_sha256, "plan_sha256") + _string(self.strategy, "strategy", maximum=64) + if self.status not in { + "capsule_required", + "no_capsule_required", + "unsupported_toolchain", + }: + raise ValueError(f"Unsupported toolchain requirement status: {self.status}") + if self.execution_authority is not False: + raise ValueError("toolchain requirements never grant execution authority") + if len(self.required_tools) > 16 or len(set(self.required_tools)) != len(self.required_tools): + raise ValueError("required_tools must contain at most 16 unique tools") + for tool in self.required_tools: + if not _TOOL_RE.fullmatch(tool): + raise ValueError(f"Invalid required tool: {tool}") + if self.family is not None and self.family not in _FAMILY_TOOLS: + raise ValueError(f"Unsupported toolchain family: {self.family}") + if self.status == "capsule_required" and self.family is None: + raise ValueError("capsule_required requirements must name a family") + if self.status != "capsule_required" and self.family is not None: + raise ValueError("only capsule_required requirements may name a family") + + def body_dict(self) -> dict[str, Any]: + return { + "schema_version": self.schema_version, + "app_id": self.app_id, + "commit_sha": self.commit_sha, + "plan_sha256": self.plan_sha256, + "strategy": self.strategy, + "family": self.family, + "required_tools": list(self.required_tools), + "status": self.status, + "execution_authority": False, + } + + def canonical_json(self) -> str: + return json.dumps(self.body_dict(), sort_keys=True, separators=(",", ":"), ensure_ascii=False) + + def sha256(self) -> str: + return hashlib.sha256(self.canonical_json().encode("utf-8")).hexdigest() + + def to_dict(self) -> dict[str, Any]: + result = self.body_dict() + result["requirement_sha256"] = self.sha256() + return result + + @classmethod + def from_dict(cls, value: Any) -> ToolchainRequirement: + data = _mapping(value, "toolchain requirement") + expected = { + "schema_version", + "app_id", + "commit_sha", + "plan_sha256", + "strategy", + "family", + "required_tools", + "status", + "execution_authority", + "requirement_sha256", + } + if set(data) != expected: + raise ValueError("toolchain requirement contains missing or unknown fields") + if data["schema_version"] != TOOLCHAIN_REQUIREMENT_SCHEMA_VERSION: + raise ValueError(f"Unsupported toolchain requirement schema: {data['schema_version']}") + raw_tools = data["required_tools"] + if not isinstance(raw_tools, list) or not all(isinstance(item, str) for item in raw_tools): + raise ValueError("required_tools must be an array of strings") + raw_family = data["family"] + family = None if raw_family is None else _family(raw_family) + requirement = cls( + app_id=_string(data["app_id"], "app_id", maximum=64), + commit_sha=_string(data["commit_sha"], "commit_sha", maximum=64), + plan_sha256=_sha256(data["plan_sha256"], "plan_sha256"), + strategy=_string(data["strategy"], "strategy", maximum=64), + family=family, + required_tools=tuple(raw_tools), + status=cast(ToolchainRequirementStatus, data["status"]), + execution_authority=_false(data["execution_authority"], "execution_authority"), + ) + if data["requirement_sha256"] != requirement.sha256(): + raise ValueError("toolchain requirement digest does not match canonical content") + return requirement + + +@dataclass(frozen=True) +class ToolchainCapsule: + capsule_id: str + family: ToolchainFamily + platform: ToolchainPlatform + artifact_kind: Literal["oci_image"] + artifact_ref: str + artifact_sha256: str + tools: tuple[ToolchainTool, ...] + execution_authority: bool = False + network_authority: bool = False + install_authority: bool = False + host_write_authority: bool = False + schema_version: str = TOOLCHAIN_CAPSULE_SCHEMA_VERSION + + def __post_init__(self) -> None: + if self.schema_version != TOOLCHAIN_CAPSULE_SCHEMA_VERSION: + raise ValueError(f"Unsupported toolchain capsule schema: {self.schema_version}") + if not _CAPSULE_ID_RE.fullmatch(self.capsule_id): + raise ValueError("capsule_id must use bounded lowercase identifier syntax") + if self.family not in _FAMILY_TOOLS: + raise ValueError(f"Unsupported toolchain family: {self.family}") + if self.platform != "linux_x86_64": + raise ValueError("v0.51 supports only linux_x86_64 capsules") + if self.artifact_kind != "oci_image": + raise ValueError("v0.51 supports only oci_image capsule artifacts") + _string(self.artifact_ref, "artifact_ref", maximum=512) + _sha256(self.artifact_sha256, "artifact_sha256") + if any( + value is not False + for value in ( + self.execution_authority, + self.network_authority, + self.install_authority, + self.host_write_authority, + ) + ): + raise ValueError("toolchain capsule authority fields must remain false") + names = [tool.name for tool in self.tools] + if len(names) != len(set(names)): + raise ValueError("toolchain capsule tools must not contain duplicates") + expected = _FAMILY_TOOLS[self.family] + if set(names) != expected: + raise ValueError( + f"{self.family} capsule must declare exactly: {', '.join(sorted(expected))}" + ) + + def body_dict(self) -> dict[str, Any]: + return { + "schema_version": self.schema_version, + "capsule_id": self.capsule_id, + "family": self.family, + "platform": self.platform, + "artifact_kind": self.artifact_kind, + "artifact_ref": self.artifact_ref, + "artifact_sha256": self.artifact_sha256, + "tools": [tool.to_dict() for tool in sorted(self.tools, key=lambda item: item.name)], + "execution_authority": False, + "network_authority": False, + "install_authority": False, + "host_write_authority": False, + } + + def canonical_json(self) -> str: + return json.dumps(self.body_dict(), sort_keys=True, separators=(",", ":"), ensure_ascii=False) + + def sha256(self) -> str: + return hashlib.sha256(self.canonical_json().encode("utf-8")).hexdigest() + + def to_dict(self) -> dict[str, Any]: + result = self.body_dict() + result["capsule_sha256"] = self.sha256() + return result + + @classmethod + def from_dict(cls, value: Any) -> ToolchainCapsule: + data = _mapping(value, "toolchain capsule") + expected = { + "schema_version", + "capsule_id", + "family", + "platform", + "artifact_kind", + "artifact_ref", + "artifact_sha256", + "tools", + "execution_authority", + "network_authority", + "install_authority", + "host_write_authority", + "capsule_sha256", + } + if set(data) != expected: + raise ValueError("toolchain capsule contains missing or unknown fields") + raw_tools = data["tools"] + if not isinstance(raw_tools, list): + raise ValueError("tools must be an array") + capsule = cls( + capsule_id=_string(data["capsule_id"], "capsule_id", maximum=96), + family=_family(data["family"]), + platform=cast(ToolchainPlatform, data["platform"]), + artifact_kind=cast(Literal["oci_image"], data["artifact_kind"]), + artifact_ref=_string(data["artifact_ref"], "artifact_ref", maximum=512), + artifact_sha256=_sha256(data["artifact_sha256"], "artifact_sha256"), + tools=tuple(ToolchainTool.from_dict(item) for item in raw_tools), + execution_authority=_false(data["execution_authority"], "execution_authority"), + network_authority=_false(data["network_authority"], "network_authority"), + install_authority=_false(data["install_authority"], "install_authority"), + host_write_authority=_false(data["host_write_authority"], "host_write_authority"), + ) + if data["capsule_sha256"] != capsule.sha256(): + raise ValueError("toolchain capsule digest does not match canonical content") + return capsule + + +@dataclass(frozen=True) +class ToolchainBinding: + app_id: str + commit_sha: str + plan_sha256: str + requirement_sha256: str + capsule_sha256: str + family: ToolchainFamily + status: Literal["compatible_for_review"] = "compatible_for_review" + execution_authority: bool = False + network_authority: bool = False + install_authority: bool = False + host_write_authority: bool = False + schema_version: str = TOOLCHAIN_BINDING_SCHEMA_VERSION + + def __post_init__(self) -> None: + if self.schema_version != TOOLCHAIN_BINDING_SCHEMA_VERSION: + raise ValueError(f"Unsupported toolchain binding schema: {self.schema_version}") + _string(self.app_id, "app_id", maximum=64) + if not re.fullmatch(r"^[0-9a-f]{40,64}$", self.commit_sha): + raise ValueError("commit_sha must be a lowercase hexadecimal commit identifier") + for value, label in ( + (self.plan_sha256, "plan_sha256"), + (self.requirement_sha256, "requirement_sha256"), + (self.capsule_sha256, "capsule_sha256"), + ): + _sha256(value, label) + if self.family not in _FAMILY_TOOLS: + raise ValueError(f"Unsupported toolchain family: {self.family}") + if self.status != "compatible_for_review": + raise ValueError("v0.51 binding status must be compatible_for_review") + if any( + value is not False + for value in ( + self.execution_authority, + self.network_authority, + self.install_authority, + self.host_write_authority, + ) + ): + raise ValueError("toolchain bindings never grant authority") + + def body_dict(self) -> dict[str, Any]: + return { + "schema_version": self.schema_version, + "app_id": self.app_id, + "commit_sha": self.commit_sha, + "plan_sha256": self.plan_sha256, + "requirement_sha256": self.requirement_sha256, + "capsule_sha256": self.capsule_sha256, + "family": self.family, + "status": self.status, + "execution_authority": False, + "network_authority": False, + "install_authority": False, + "host_write_authority": False, + } + + def canonical_json(self) -> str: + return json.dumps(self.body_dict(), sort_keys=True, separators=(",", ":"), ensure_ascii=False) + + def sha256(self) -> str: + return hashlib.sha256(self.canonical_json().encode("utf-8")).hexdigest() + + def to_dict(self) -> dict[str, Any]: + result = self.body_dict() + result["binding_sha256"] = self.sha256() + return result + + @classmethod + def from_dict(cls, value: Any) -> ToolchainBinding: + data = _mapping(value, "toolchain binding") + expected = { + "schema_version", + "app_id", + "commit_sha", + "plan_sha256", + "requirement_sha256", + "capsule_sha256", + "family", + "status", + "execution_authority", + "network_authority", + "install_authority", + "host_write_authority", + "binding_sha256", + } + if set(data) != expected: + raise ValueError("toolchain binding contains missing or unknown fields") + binding = cls( + app_id=_string(data["app_id"], "app_id", maximum=64), + commit_sha=_string(data["commit_sha"], "commit_sha", maximum=64), + plan_sha256=_sha256(data["plan_sha256"], "plan_sha256"), + requirement_sha256=_sha256(data["requirement_sha256"], "requirement_sha256"), + capsule_sha256=_sha256(data["capsule_sha256"], "capsule_sha256"), + family=_family(data["family"]), + status=cast(Literal["compatible_for_review"], data["status"]), + execution_authority=_false(data["execution_authority"], "execution_authority"), + network_authority=_false(data["network_authority"], "network_authority"), + install_authority=_false(data["install_authority"], "install_authority"), + host_write_authority=_false(data["host_write_authority"], "host_write_authority"), + ) + if data["binding_sha256"] != binding.sha256(): + raise ValueError("toolchain binding digest does not match canonical content") + return binding + + +def derive_toolchain_requirement(plan: BuildPlan) -> ToolchainRequirement: + required_tools = tuple(sorted(plan.required_tools)) + + if plan.status == "no_build_required" or not required_tools: + return ToolchainRequirement( + app_id=plan.app_id, + commit_sha=plan.commit_sha, + plan_sha256=plan.sha256(), + strategy=plan.strategy, + family=None, + required_tools=required_tools, + status="no_capsule_required", + ) + + family: ToolchainFamily | None = None + if ( + plan.strategy == "node_package_manager" + and plan.package_manager == "npm" + and set(required_tools) == _FAMILY_TOOLS["node_npm"] + ): + family = "node_npm" + elif ( + plan.strategy == "python_pep517_wheel" + and set(required_tools) == _FAMILY_TOOLS["python_pep517"] + ): + family = "python_pep517" + elif ( + plan.strategy == "rust_cargo_release" + and set(required_tools) == _FAMILY_TOOLS["rust_cargo"] + ): + family = "rust_cargo" + elif ( + plan.strategy == "go_module_build" + and set(required_tools) == _FAMILY_TOOLS["go_module"] + ): + family = "go_module" + + return ToolchainRequirement( + app_id=plan.app_id, + commit_sha=plan.commit_sha, + plan_sha256=plan.sha256(), + strategy=plan.strategy, + family=family, + required_tools=required_tools, + status="capsule_required" if family is not None else "unsupported_toolchain", + ) + + +def bind_toolchain_capsule( + requirement: ToolchainRequirement, + capsule: ToolchainCapsule, +) -> ToolchainBinding: + if requirement.status != "capsule_required" or requirement.family is None: + raise ValueError("only capsule_required requirements can be bound") + if requirement.family != capsule.family: + raise ValueError("toolchain capsule family does not match requirement") + capsule_tools = {tool.name for tool in capsule.tools} + if set(requirement.required_tools) != capsule_tools: + raise ValueError("toolchain capsule tools do not exactly match requirement") + + return ToolchainBinding( + app_id=requirement.app_id, + commit_sha=requirement.commit_sha, + plan_sha256=requirement.plan_sha256, + requirement_sha256=requirement.sha256(), + capsule_sha256=capsule.sha256(), + family=capsule.family, + ) diff --git a/tests/test_app_platform_v051_toolchain_capsules.py b/tests/test_app_platform_v051_toolchain_capsules.py new file mode 100644 index 00000000..ce2fa76a --- /dev/null +++ b/tests/test_app_platform_v051_toolchain_capsules.py @@ -0,0 +1,264 @@ +from __future__ import annotations + +import json +from pathlib import Path +from typing import Any + +import pytest + +from phios.apps.build_plan import plan_build_from_payloads +from phios.apps.manifest import AppManifest +from phios.apps.toolchain_capsule import ( + ToolchainBinding, + ToolchainCapsule, + ToolchainRequirement, + ToolchainTool, + bind_toolchain_capsule, + derive_toolchain_requirement, +) + + +def _manifest(runtime: str = "node", target: str = "package.json") -> AppManifest: + return AppManifest.from_dict( + { + "schema_version": "phios.app_manifest.v0.1", + "app_id": "phi.toolchain-example", + "name": "Toolchain Example", + "version": "1.0.0", + "description": "Toolchain capsule contract test", + "source": { + "repository_url": "https://github.com/example/toolchain-example", + "license_expression": "MIT", + "redistribution": "unknown", + }, + "entrypoint": {"runtime": runtime, "target": target}, + "permissions": [], + } + ) + + +def _intake(manifest: AppManifest) -> dict[str, Any]: + return { + "evidence": { + "repository_url": manifest.source.repository_url, + "head_sha": "a" * 40, + }, + "proposal": { + "status": "inferred_candidate", + "repository_url": manifest.source.repository_url, + "app_id": manifest.app_id, + "permissions_source": "not_declared", + }, + "manifest_candidate": manifest.to_dict(), + } + + +def _receipt(root: Path, manifest: AppManifest) -> dict[str, Any]: + files = [path for path in root.rglob("*") if path.is_file()] + return { + "schema_version": "phios.source_acquisition_receipt.v0.1", + "receipt_id": "11111111-1111-1111-1111-111111111111", + "timestamp_utc": "2026-10-04T00:00:00+00:00", + "app_id": manifest.app_id, + "repository_url": manifest.source.repository_url, + "commit_sha": "a" * 40, + "manifest_sha256": manifest.sha256(), + "archive_sha256": "b" * 64, + "tree_sha256": "c" * 64, + "file_count": len(files), + "total_bytes": sum(path.stat().st_size for path in files), + "workspace_path": str(root.resolve()), + "status": "acquired", + } + + +def _plan(tmp_path: Path, family: str): + tmp_path.mkdir(parents=True, exist_ok=True) + if family == "node_npm": + manifest = _manifest() + (tmp_path / "package.json").write_text( + json.dumps({"name": "example", "scripts": {"build": "vite build"}}) + ) + (tmp_path / "package-lock.json").write_text("{}") + (tmp_path / "vite.config.js").write_text("export default {}") + elif family == "node_pnpm": + manifest = _manifest() + (tmp_path / "package.json").write_text( + json.dumps( + { + "name": "example", + "packageManager": "pnpm@10.0.0", + "scripts": {"build": "vite build"}, + } + ) + ) + (tmp_path / "pnpm-lock.yaml").write_text("lockfileVersion: '9.0'\n") + (tmp_path / "vite.config.js").write_text("export default {}") + elif family == "python_pep517": + manifest = _manifest(runtime="python", target="pyproject.toml") + (tmp_path / "pyproject.toml").write_text( + '[project]\nname = "example"\nversion = "1.0.0"\n' + ) + elif family == "rust_cargo": + manifest = _manifest(runtime="native", target="Cargo.toml") + (tmp_path / "Cargo.toml").write_text( + '[package]\nname = "example"\nversion = "0.1.0"\n' + ) + (tmp_path / "Cargo.lock").write_text("# lock\n") + elif family == "go_module": + manifest = _manifest(runtime="native", target="go.mod") + (tmp_path / "go.mod").write_text("module example\n") + (tmp_path / "go.sum").write_text("example.invalid/mod v1.0.0 h1:abc\n") + elif family == "static": + manifest = _manifest(runtime="static_web", target="index.html") + (tmp_path / "index.html").write_text("phi") + else: + raise AssertionError(family) + return plan_build_from_payloads(_intake(manifest), _receipt(tmp_path, manifest)) + + +@pytest.mark.parametrize( + ("family", "expected", "tools"), + [ + ("node_npm", "node_npm", ("node", "npm")), + ("python_pep517", "python_pep517", ("python", "python-build")), + ("rust_cargo", "rust_cargo", ("cargo", "rustc")), + ("go_module", "go_module", ("go",)), + ], +) +def test_supported_build_plans_derive_zero_authority_capsule_requirements( + tmp_path: Path, family: str, expected: str, tools: tuple[str, ...] +) -> None: + plan = _plan(tmp_path, family) + requirement = derive_toolchain_requirement(plan) + + assert requirement.status == "capsule_required" + assert requirement.family == expected + assert requirement.required_tools == tools + assert requirement.plan_sha256 == plan.sha256() + assert requirement.execution_authority is False + + +def test_pnpm_is_explicitly_unsupported_in_v051(tmp_path: Path) -> None: + requirement = derive_toolchain_requirement(_plan(tmp_path, "node_pnpm")) + + assert requirement.status == "unsupported_toolchain" + assert requirement.family is None + assert requirement.required_tools == ("node", "pnpm") + + +def test_static_source_requires_no_capsule(tmp_path: Path) -> None: + requirement = derive_toolchain_requirement(_plan(tmp_path, "static")) + + assert requirement.status == "no_capsule_required" + assert requirement.family is None + assert requirement.required_tools == () + + +def _capsule(family: str = "node_npm") -> ToolchainCapsule: + tools = { + "node_npm": (ToolchainTool("node", "22.0.0"), ToolchainTool("npm", "10.0.0")), + "python_pep517": ( + ToolchainTool("python", "3.11.10"), + ToolchainTool("python-build", "1.2.2"), + ), + "rust_cargo": ( + ToolchainTool("cargo", "1.89.0"), + ToolchainTool("rustc", "1.89.0"), + ), + "go_module": (ToolchainTool("go", "1.25.1"),), + }[family] + return ToolchainCapsule( + capsule_id=f"phios.{family}.example", + family=family, # type: ignore[arg-type] + platform="linux_x86_64", + artifact_kind="oci_image", + artifact_ref=f"registry.example/phios/{family}@sha256:" + "d" * 64, + artifact_sha256="d" * 64, + tools=tools, + ) + + +def test_capsule_round_trip_is_strict_and_digest_bound() -> None: + capsule = _capsule() + payload = capsule.to_dict() + + assert ToolchainCapsule.from_dict(payload) == capsule + assert payload["execution_authority"] is False + assert payload["network_authority"] is False + assert payload["install_authority"] is False + assert payload["host_write_authority"] is False + + payload["artifact_ref"] = "registry.example/tampered" + with pytest.raises(ValueError, match="digest"): + ToolchainCapsule.from_dict(payload) + + +def test_capsule_rejects_missing_or_extra_family_tools() -> None: + with pytest.raises(ValueError, match="must declare exactly"): + ToolchainCapsule( + capsule_id="phios.node.bad", + family="node_npm", + platform="linux_x86_64", + artifact_kind="oci_image", + artifact_ref="registry.example/node", + artifact_sha256="d" * 64, + tools=(ToolchainTool("node", "22.0.0"),), + ) + + +def test_capsule_rejects_authority_smuggling() -> None: + with pytest.raises(ValueError, match="authority fields"): + ToolchainCapsule( + capsule_id="phios.node.bad-authority", + family="node_npm", + platform="linux_x86_64", + artifact_kind="oci_image", + artifact_ref="registry.example/node", + artifact_sha256="d" * 64, + tools=(ToolchainTool("node", "22.0.0"), ToolchainTool("npm", "10.0.0")), + execution_authority=True, + ) + + +def test_matching_capsule_creates_review_only_binding(tmp_path: Path) -> None: + requirement = derive_toolchain_requirement(_plan(tmp_path, "node_npm")) + capsule = _capsule() + + binding = bind_toolchain_capsule(requirement, capsule) + + assert binding.status == "compatible_for_review" + assert binding.requirement_sha256 == requirement.sha256() + assert binding.capsule_sha256 == capsule.sha256() + assert binding.execution_authority is False + assert binding.network_authority is False + assert binding.install_authority is False + assert binding.host_write_authority is False + assert ToolchainBinding.from_dict(binding.to_dict()) == binding + + +def test_cross_family_binding_is_rejected(tmp_path: Path) -> None: + requirement = derive_toolchain_requirement(_plan(tmp_path, "python_pep517")) + + with pytest.raises(ValueError, match="family"): + bind_toolchain_capsule(requirement, _capsule("node_npm")) + + +def test_no_build_and_unsupported_requirements_cannot_bind(tmp_path: Path) -> None: + no_build = derive_toolchain_requirement(_plan(tmp_path / "static", "static")) + unsupported = derive_toolchain_requirement(_plan(tmp_path / "pnpm", "node_pnpm")) + + with pytest.raises(ValueError, match="capsule_required"): + bind_toolchain_capsule(no_build, _capsule()) + with pytest.raises(ValueError, match="capsule_required"): + bind_toolchain_capsule(unsupported, _capsule()) + + +def test_requirement_round_trip_rejects_unknown_fields(tmp_path: Path) -> None: + requirement = derive_toolchain_requirement(_plan(tmp_path, "node_npm")) + payload = requirement.to_dict() + + assert ToolchainRequirement.from_dict(payload) == requirement + payload["surprise_authority"] = True + with pytest.raises(ValueError, match="unknown fields"): + ToolchainRequirement.from_dict(payload)