autonomy-smoke-tests Exact governed tree; evidence 7dbba7ff168e72af
autonomy-unit-tests Exact governed tree; evidence 7dbba7ff168e72af
campaign-approval-gate Exact governed tree; evidence 7dbba7ff168e72af
git-diff-check Exact governed tree; evidence 7dbba7ff168e72af
py-compile Exact governed tree; evidence 7dbba7ff168e72af
reconciliation-contract Exact governed tree; evidence 7dbba7ff168e72af
release-state-machine Exact governed tree; evidence 7dbba7ff168e72af
secret-scan Exact governed tree; evidence 7029b3eafb209066
signer-validator-contract Exact governed tree; evidence 7dbba7ff168e72af
689 lines
27 KiB
Python
689 lines
27 KiB
Python
"""Owner-registered dispatch boundary for the fixed-scope C5 installer.
|
|
|
|
The registration authorizes one exact signed installation contract and one
|
|
exact set of installed executor bytes. It is not an execution receipt; the
|
|
wrapped :class:`Installer` remains the component that durably records and
|
|
reconciles installation state.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
from dataclasses import dataclass
|
|
import argparse
|
|
import hashlib
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import re
|
|
import socket
|
|
import stat
|
|
import sys
|
|
import time
|
|
from typing import Any, Callable, Mapping
|
|
|
|
import c5_staging_installation as _installer_module
|
|
from c5_staging_installation import (
|
|
BRIDGE_EFFECTS,
|
|
BRIDGE_TARGET,
|
|
HOST,
|
|
InstallationError,
|
|
InstallationOutcomeUnknown,
|
|
ISSUER_EFFECTS,
|
|
ISSUER_TARGET,
|
|
OWNER_NAMESPACE,
|
|
R14_SOURCE_COMMIT,
|
|
REPOSITORY,
|
|
SUCCESSOR_SCHEMA,
|
|
Installer,
|
|
RegistryOwnerVerifier,
|
|
canonical_bytes,
|
|
verify_signed_contract,
|
|
)
|
|
from registered_owner_signer_adapter import RegisteredOwnerSignerAdapter
|
|
|
|
|
|
SCHEMA = "aios.c5.registered-installer-executor.v1"
|
|
PROVENANCE_SCHEMA = "aios.c5.executor-provenance.v1"
|
|
EXECUTION_DIGEST = "0779fa615e8e7971a8dcfccf0f295b1323cd9b64787e174aea4fd2affc414339"
|
|
BRIDGE_PORT = 18892
|
|
ISSUER_PORT = 18946
|
|
CAPABILITIES = frozenset({"install", "rollback", "reconcile"})
|
|
TARGET_EFFECTS = {BRIDGE_TARGET: BRIDGE_EFFECTS, ISSUER_TARGET: ISSUER_EFFECTS}
|
|
MAX_TTL_SECONDS = 900
|
|
MAX_CODE_BYTES = 16 * 1024 * 1024
|
|
DEFAULT_REGISTRY = Path("/etc/aios/single-host-signer-registry.json")
|
|
DEFAULT_PROVENANCE_MANIFEST = Path("/etc/aios/c5-executor-provenance.json")
|
|
HEX40 = re.compile(r"^[0-9a-f]{40}$")
|
|
HEX64 = re.compile(r"^[0-9a-f]{64}$")
|
|
NONCE = re.compile(r"^[A-Za-z0-9._:\-]{16,128}$")
|
|
SCOPE_ID = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._:\-]{2,127}$")
|
|
|
|
|
|
class ExecutorRegistrationError(RuntimeError):
|
|
def __init__(self, code: str) -> None:
|
|
super().__init__(code)
|
|
self.code = code
|
|
|
|
|
|
def _fail(code: str) -> None:
|
|
raise ExecutorRegistrationError(code)
|
|
|
|
|
|
def _sha256_bytes(data: bytes) -> str:
|
|
return hashlib.sha256(data).hexdigest()
|
|
|
|
|
|
def _require_digest(value: Any, pattern: re.Pattern[str], code: str) -> str:
|
|
if not isinstance(value, str) or pattern.fullmatch(value) is None:
|
|
_fail(code)
|
|
return value
|
|
|
|
|
|
def _strict_object(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
|
|
result: dict[str, Any] = {}
|
|
for key, value in pairs:
|
|
if key in result:
|
|
_fail("EXECUTOR_JSON_DUPLICATE_FIELD")
|
|
result[key] = value
|
|
return result
|
|
|
|
|
|
def _secure_bytes(
|
|
path: Path, *, require_root_owner: bool = True, maximum: int = MAX_CODE_BYTES,
|
|
) -> bytes:
|
|
path = Path(path)
|
|
if not path.is_absolute():
|
|
_fail("EXECUTOR_CODE_PATH_INVALID")
|
|
try:
|
|
if path.is_symlink() or path.resolve(strict=True) != path:
|
|
_fail("EXECUTOR_CODE_PATH_INVALID")
|
|
before = path.stat()
|
|
except OSError as exc:
|
|
raise ExecutorRegistrationError("EXECUTOR_CODE_PATH_INVALID") from exc
|
|
flags = os.O_RDONLY
|
|
if hasattr(os, "O_NOFOLLOW"):
|
|
flags |= os.O_NOFOLLOW
|
|
try:
|
|
fd = os.open(path, flags)
|
|
except OSError as exc:
|
|
raise ExecutorRegistrationError("EXECUTOR_CODE_PATH_INVALID") from exc
|
|
try:
|
|
current = os.fstat(fd)
|
|
if (
|
|
not stat.S_ISREG(current.st_mode)
|
|
or current.st_dev != before.st_dev
|
|
or current.st_ino != before.st_ino
|
|
or current.st_size < 1
|
|
or current.st_size > maximum
|
|
):
|
|
_fail("EXECUTOR_CODE_FILE_INVALID")
|
|
if require_root_owner:
|
|
if os.name != "posix" or current.st_uid != 0:
|
|
_fail("EXECUTOR_CODE_PATH_OWNER_INVALID")
|
|
if stat.S_IMODE(current.st_mode) & 0o022:
|
|
_fail("EXECUTOR_CODE_PATH_WRITABLE")
|
|
parent = path.parent
|
|
while True:
|
|
parent_stat = parent.stat()
|
|
if parent.is_symlink() or parent_stat.st_uid != 0:
|
|
_fail("EXECUTOR_CODE_PATH_OWNER_INVALID")
|
|
if stat.S_IMODE(parent_stat.st_mode) & 0o022:
|
|
_fail("EXECUTOR_CODE_PATH_WRITABLE")
|
|
if parent == parent.parent:
|
|
break
|
|
parent = parent.parent
|
|
chunks: list[bytes] = []
|
|
remaining = current.st_size
|
|
while remaining:
|
|
chunk = os.read(fd, min(remaining, 1024 * 1024))
|
|
if not chunk:
|
|
_fail("EXECUTOR_CODE_FILE_INVALID")
|
|
chunks.append(chunk)
|
|
remaining -= len(chunk)
|
|
if os.read(fd, 1):
|
|
_fail("EXECUTOR_CODE_FILE_INVALID")
|
|
return b"".join(chunks)
|
|
finally:
|
|
os.close(fd)
|
|
|
|
|
|
@dataclass(frozen=True, slots=True)
|
|
class CodeProvenance:
|
|
environment: str
|
|
instance_id: str
|
|
integration_commit: str
|
|
integration_tree: str
|
|
installer_module_path: Path
|
|
installer_script_path: Path
|
|
executor_module_path: Path
|
|
installer_module_sha256: str
|
|
installer_script_sha256: str
|
|
executor_module_sha256: str
|
|
authority_manifest_sha256: str
|
|
|
|
|
|
def _actual_installer_module_path() -> Path:
|
|
value = getattr(_installer_module, "__file__", None)
|
|
if not isinstance(value, str):
|
|
_fail("EXECUTOR_LOADED_INSTALLER_PATH_INVALID")
|
|
return Path(value).resolve(strict=True)
|
|
|
|
|
|
def _actual_executor_module_path() -> Path:
|
|
return Path(__file__).resolve(strict=True)
|
|
|
|
|
|
def load_code_provenance(
|
|
manifest: Path, *, require_root_owner: bool = True,
|
|
) -> CodeProvenance:
|
|
"""Load identity from an authority manifest and actual loaded paths."""
|
|
manifest = Path(manifest)
|
|
raw = _secure_bytes(manifest, require_root_owner=require_root_owner)
|
|
try:
|
|
value = json.loads(raw, object_pairs_hook=_strict_object)
|
|
except (UnicodeError, json.JSONDecodeError) as exc:
|
|
raise ExecutorRegistrationError("EXECUTOR_PROVENANCE_INVALID") from exc
|
|
if (
|
|
not isinstance(value, dict)
|
|
or set(value) != {
|
|
"schema", "environment", "instance_id", "integration_commit",
|
|
"integration_tree", "entries",
|
|
}
|
|
or value["schema"] != PROVENANCE_SCHEMA
|
|
or not isinstance(value["entries"], dict)
|
|
or set(value["entries"]) != {
|
|
"installer_module", "installer_script", "executor_module",
|
|
}
|
|
):
|
|
_fail("EXECUTOR_PROVENANCE_INVALID")
|
|
expected_paths = {
|
|
"installer_module": _actual_installer_module_path(),
|
|
"executor_module": _actual_executor_module_path(),
|
|
}
|
|
resolved: dict[str, Path] = {}
|
|
hashes: dict[str, str] = {}
|
|
for label, entry in value["entries"].items():
|
|
if not isinstance(entry, dict) or set(entry) != {"path", "sha256"}:
|
|
_fail("EXECUTOR_PROVENANCE_INVALID")
|
|
if not isinstance(entry["path"], str):
|
|
_fail("EXECUTOR_PROVENANCE_INVALID")
|
|
path = Path(entry["path"])
|
|
if not path.is_absolute():
|
|
_fail("EXECUTOR_CODE_PATH_INVALID")
|
|
try:
|
|
canonical = path.resolve(strict=True)
|
|
except OSError as exc:
|
|
raise ExecutorRegistrationError("EXECUTOR_CODE_PATH_INVALID") from exc
|
|
if path != canonical:
|
|
_fail("EXECUTOR_CODE_PATH_INVALID")
|
|
if label in expected_paths and canonical != expected_paths[label]:
|
|
_fail("EXECUTOR_PROVENANCE_LOADED_PATH_MISMATCH")
|
|
if label == "installer_script" and canonical.name != "c5_staging_installation.py":
|
|
_fail("EXECUTOR_INSTALLER_SCRIPT_PATH_INVALID")
|
|
digest = _sha256_bytes(
|
|
_secure_bytes(canonical, require_root_owner=require_root_owner)
|
|
)
|
|
if entry["sha256"] != digest:
|
|
_fail("EXECUTOR_PROVENANCE_CODE_MISMATCH")
|
|
resolved[label] = canonical
|
|
hashes[label] = digest
|
|
if (
|
|
not isinstance(value["environment"], str)
|
|
or SCOPE_ID.fullmatch(value["environment"]) is None
|
|
or not isinstance(value["instance_id"], str)
|
|
or SCOPE_ID.fullmatch(value["instance_id"]) is None
|
|
):
|
|
_fail("EXECUTOR_PROVENANCE_SCOPE_INVALID")
|
|
return CodeProvenance(
|
|
environment=value["environment"],
|
|
instance_id=value["instance_id"],
|
|
integration_commit=_require_digest(
|
|
value["integration_commit"], HEX40,
|
|
"EXECUTOR_INTEGRATION_COMMIT_INVALID",
|
|
),
|
|
integration_tree=_require_digest(
|
|
value["integration_tree"], HEX40,
|
|
"EXECUTOR_INTEGRATION_TREE_INVALID",
|
|
),
|
|
installer_module_path=resolved["installer_module"],
|
|
installer_script_path=resolved["installer_script"],
|
|
executor_module_path=resolved["executor_module"],
|
|
installer_module_sha256=hashes["installer_module"],
|
|
installer_script_sha256=hashes["installer_script"],
|
|
executor_module_sha256=hashes["executor_module"],
|
|
authority_manifest_sha256=_sha256_bytes(raw),
|
|
)
|
|
|
|
|
|
def _contract_binding(payload: Mapping[str, Any], digest: str) -> dict[str, Any]:
|
|
return {
|
|
"target": payload["target"],
|
|
"contract_digest": digest,
|
|
"old_snapshot_sha256": _sha256_bytes(canonical_bytes(payload["existing"])),
|
|
"new_manifest_sha256": _sha256_bytes(canonical_bytes({
|
|
"release_root": payload["release_root"],
|
|
"files": payload["files"],
|
|
"readiness": payload["readiness"],
|
|
})),
|
|
"rollback_sha256": _sha256_bytes(canonical_bytes(payload["rollback"])),
|
|
"contract_issued_at": payload["issued_at"],
|
|
"contract_expires_at": payload["expires_at"],
|
|
"contract_nonce": payload["nonce"],
|
|
}
|
|
|
|
|
|
def _issuer_dependency(payload: Mapping[str, Any], digest: str) -> dict[str, Any]:
|
|
return {
|
|
"target": payload["target"],
|
|
"contract_digest": digest,
|
|
"source_commit": payload["source_commit"],
|
|
"support_commit": payload["support_commit"],
|
|
"owner_signer_id": payload["owner_signer_id"],
|
|
"owner_key_id": payload["owner_key_id"],
|
|
"contract_nonce": payload["nonce"],
|
|
"contract_issued_at": payload["issued_at"],
|
|
"contract_expires_at": payload["expires_at"],
|
|
"rollback_sha256": _sha256_bytes(canonical_bytes(payload["rollback"])),
|
|
}
|
|
|
|
|
|
def _registration_payload(
|
|
*, executor_id: Any, nonce: Any, issued_at: Any, expires_at: Any,
|
|
contract_payload: Mapping[str, Any], contract_digest: str,
|
|
provenance: CodeProvenance,
|
|
issuer_dependency: Mapping[str, Any] | None,
|
|
) -> dict[str, Any]:
|
|
return {
|
|
"schema": SCHEMA,
|
|
"executor_id": executor_id,
|
|
"owner_signer_id": contract_payload["owner_signer_id"],
|
|
"owner_key_id": contract_payload["owner_key_id"],
|
|
"host": HOST,
|
|
"repository": REPOSITORY,
|
|
"environment": provenance.environment,
|
|
"instance_id": provenance.instance_id,
|
|
"source_commit": R14_SOURCE_COMMIT,
|
|
"support_commit": contract_payload["support_commit"],
|
|
"integration_commit": provenance.integration_commit,
|
|
"integration_tree": provenance.integration_tree,
|
|
"installer_module_sha256": provenance.installer_module_sha256,
|
|
"installer_script_sha256": provenance.installer_script_sha256,
|
|
"executor_module_sha256": provenance.executor_module_sha256,
|
|
"authority_manifest_sha256": provenance.authority_manifest_sha256,
|
|
"execution_digest": EXECUTION_DIGEST,
|
|
"bridge_port": BRIDGE_PORT,
|
|
"issuer_port": ISSUER_PORT,
|
|
"capabilities": sorted(CAPABILITIES),
|
|
"effects": sorted(contract_payload["effects"]),
|
|
"issuer_dependency": dict(issuer_dependency) if issuer_dependency is not None else None,
|
|
"issued_at": issued_at,
|
|
"expires_at": expires_at,
|
|
"nonce": nonce,
|
|
**_contract_binding(contract_payload, contract_digest),
|
|
}
|
|
|
|
|
|
def _validate_issuer_dependency(
|
|
dependency: Any, contract_payload: Mapping[str, Any],
|
|
) -> None:
|
|
if contract_payload["target"] == ISSUER_TARGET:
|
|
if dependency is not None:
|
|
_fail("EXECUTOR_ISSUER_DEPENDENCY_INVALID")
|
|
return
|
|
if (
|
|
not isinstance(dependency, Mapping)
|
|
or set(dependency) != {
|
|
"target", "contract_digest", "source_commit", "support_commit",
|
|
"owner_signer_id", "owner_key_id", "contract_nonce",
|
|
"contract_issued_at", "contract_expires_at", "rollback_sha256",
|
|
}
|
|
or dependency["target"] != ISSUER_TARGET
|
|
or dependency["source_commit"] != contract_payload["source_commit"]
|
|
or dependency["support_commit"] != contract_payload["support_commit"]
|
|
or dependency["owner_signer_id"] != contract_payload["owner_signer_id"]
|
|
or dependency["owner_key_id"] != contract_payload["owner_key_id"]
|
|
or type(dependency["contract_issued_at"]) is not int
|
|
or type(dependency["contract_expires_at"]) is not int
|
|
):
|
|
_fail("EXECUTOR_ISSUER_DEPENDENCY_INVALID")
|
|
_require_digest(
|
|
dependency["contract_digest"], HEX64,
|
|
"EXECUTOR_ISSUER_DEPENDENCY_INVALID",
|
|
)
|
|
_require_digest(
|
|
dependency["rollback_sha256"], HEX64,
|
|
"EXECUTOR_ISSUER_DEPENDENCY_INVALID",
|
|
)
|
|
|
|
|
|
def _validate_payload(
|
|
payload: Mapping[str, Any], *, now: int, provenance: CodeProvenance,
|
|
contract_payload: Mapping[str, Any], contract_digest: str,
|
|
issuer_dependency: Mapping[str, Any] | None,
|
|
) -> None:
|
|
expected = _registration_payload(
|
|
executor_id=payload.get("executor_id"), nonce=payload.get("nonce"),
|
|
issued_at=payload.get("issued_at"), expires_at=payload.get("expires_at"),
|
|
contract_payload=contract_payload, contract_digest=contract_digest,
|
|
provenance=provenance, issuer_dependency=issuer_dependency,
|
|
)
|
|
if set(payload) != set(expected) or any(
|
|
payload.get(key) != value for key, value in expected.items()
|
|
):
|
|
_fail("EXECUTOR_REGISTRATION_BINDING_INVALID")
|
|
if (
|
|
not isinstance(payload["executor_id"], str)
|
|
or not payload["executor_id"]
|
|
or not isinstance(payload["nonce"], str)
|
|
or NONCE.fullmatch(payload["nonce"]) is None
|
|
):
|
|
_fail("EXECUTOR_REGISTRATION_IDENTITY_INVALID")
|
|
if (
|
|
type(payload["issued_at"]) is not int
|
|
or type(payload["expires_at"]) is not int
|
|
or payload["issued_at"] > now
|
|
or now >= payload["expires_at"]
|
|
or not 1 <= payload["expires_at"] - payload["issued_at"] <= MAX_TTL_SECONDS
|
|
or payload["issued_at"] < contract_payload["issued_at"]
|
|
or payload["expires_at"] > contract_payload["expires_at"]
|
|
):
|
|
_fail("EXECUTOR_REGISTRATION_EXPIRED")
|
|
if payload["support_commit"] != payload["integration_commit"]:
|
|
_fail("EXECUTOR_COMMIT_BINDING_INVALID")
|
|
if (
|
|
issuer_dependency is not None
|
|
and payload["expires_at"] > issuer_dependency["contract_expires_at"]
|
|
):
|
|
_fail("EXECUTOR_REGISTRATION_EXPIRED")
|
|
if (
|
|
not isinstance(payload["environment"], str)
|
|
or SCOPE_ID.fullmatch(payload["environment"]) is None
|
|
or not isinstance(payload["instance_id"], str)
|
|
or SCOPE_ID.fullmatch(payload["instance_id"]) is None
|
|
):
|
|
_fail("EXECUTOR_ENVIRONMENT_BINDING_INVALID")
|
|
if payload["source_commit"] != R14_SOURCE_COMMIT:
|
|
_fail("EXECUTOR_SOURCE_COMMIT_INVALID")
|
|
if (
|
|
contract_payload["schema"] != SUCCESSOR_SCHEMA
|
|
or contract_payload["source_commit"] != R14_SOURCE_COMMIT
|
|
):
|
|
_fail("EXECUTOR_CONTRACT_GENERATION_INVALID")
|
|
effects = TARGET_EFFECTS.get(payload["target"])
|
|
if (
|
|
effects is None
|
|
or not isinstance(payload["effects"], list)
|
|
or frozenset(payload["effects"]) != effects
|
|
or len(payload["effects"]) != len(effects)
|
|
):
|
|
_fail("EXECUTOR_EFFECTS_INVALID")
|
|
if (
|
|
not isinstance(payload["capabilities"], list)
|
|
or frozenset(payload["capabilities"]) != CAPABILITIES
|
|
or len(payload["capabilities"]) != len(CAPABILITIES)
|
|
):
|
|
_fail("EXECUTOR_CAPABILITIES_INVALID")
|
|
_validate_issuer_dependency(issuer_dependency, contract_payload)
|
|
for name in (
|
|
"installer_module_sha256", "installer_script_sha256",
|
|
"executor_module_sha256", "authority_manifest_sha256",
|
|
"execution_digest", "contract_digest", "old_snapshot_sha256",
|
|
"new_manifest_sha256", "rollback_sha256",
|
|
):
|
|
_require_digest(payload[name], HEX64, f"EXECUTOR_{name.upper()}_INVALID")
|
|
|
|
|
|
def _verified_contract(
|
|
contract: Path, installer: Installer, *, now: int,
|
|
) -> tuple[dict[str, Any], str]:
|
|
return verify_signed_contract(
|
|
contract, installer.registry_path, now=now,
|
|
require_root_owner=installer.require_root_owner,
|
|
_layout=installer.layout,
|
|
)
|
|
|
|
|
|
def _verified_issuer_dependency(
|
|
issuer_contract: Path | None, installer: Installer, *, now: int,
|
|
contract_payload: Mapping[str, Any],
|
|
) -> dict[str, Any] | None:
|
|
if contract_payload["target"] == ISSUER_TARGET:
|
|
if issuer_contract is not None:
|
|
_fail("EXECUTOR_ISSUER_DEPENDENCY_INVALID")
|
|
return None
|
|
if issuer_contract is None:
|
|
_fail("EXECUTOR_ISSUER_DEPENDENCY_REQUIRED")
|
|
payload, digest = _verified_contract(issuer_contract, installer, now=now)
|
|
if payload["schema"] != SUCCESSOR_SCHEMA or payload["source_commit"] != R14_SOURCE_COMMIT:
|
|
_fail("EXECUTOR_ISSUER_DEPENDENCY_INVALID")
|
|
dependency = _issuer_dependency(payload, digest)
|
|
_validate_issuer_dependency(dependency, contract_payload)
|
|
return dependency
|
|
|
|
|
|
def issue_registration(
|
|
*, executor_id: str, nonce: str, ttl_seconds: int, contract: Path,
|
|
installer: Installer, provenance_manifest: Path,
|
|
registered_signer: RegisteredOwnerSignerAdapter,
|
|
clock: Callable[[], int], issuer_contract: Path | None = None,
|
|
require_root_owner: bool = True,
|
|
) -> dict[str, Any]:
|
|
"""Issue authorization after deriving every scope field from trusted input."""
|
|
if type(installer) is not Installer:
|
|
_fail("EXECUTOR_INSTALLER_TYPE_INVALID")
|
|
if not isinstance(registered_signer, RegisteredOwnerSignerAdapter):
|
|
_fail("REGISTERED_SIGNER_ADAPTER_REQUIRED")
|
|
if type(ttl_seconds) is not int or not 1 <= ttl_seconds <= MAX_TTL_SECONDS:
|
|
_fail("EXECUTOR_REGISTRATION_TTL_INVALID")
|
|
now = int(clock())
|
|
provenance = load_code_provenance(
|
|
provenance_manifest, require_root_owner=require_root_owner,
|
|
)
|
|
contract_payload, contract_digest = _verified_contract(contract, installer, now=now)
|
|
dependency = _verified_issuer_dependency(
|
|
issuer_contract, installer, now=now, contract_payload=contract_payload,
|
|
)
|
|
payload = _registration_payload(
|
|
executor_id=executor_id, nonce=nonce, issued_at=now,
|
|
expires_at=now + ttl_seconds, contract_payload=contract_payload,
|
|
contract_digest=contract_digest, provenance=provenance,
|
|
issuer_dependency=dependency,
|
|
)
|
|
_validate_payload(
|
|
payload, now=now, provenance=provenance,
|
|
contract_payload=contract_payload, contract_digest=contract_digest,
|
|
issuer_dependency=dependency,
|
|
)
|
|
if registered_signer.fingerprint != payload["owner_key_id"]:
|
|
_fail("EXECUTOR_SIGNER_BINDING_INVALID")
|
|
signature = registered_signer._sign_canonical_payload(
|
|
OWNER_NAMESPACE, canonical_bytes(payload),
|
|
)
|
|
return {"payload": payload, "signature": signature}
|
|
|
|
|
|
def load_registration(path: Path, *, require_root_owner: bool = True) -> dict[str, Any]:
|
|
raw = _secure_bytes(
|
|
Path(path), require_root_owner=require_root_owner, maximum=1024 * 1024,
|
|
)
|
|
try:
|
|
value = json.loads(raw, object_pairs_hook=_strict_object)
|
|
except (UnicodeError, json.JSONDecodeError) as exc:
|
|
raise ExecutorRegistrationError("EXECUTOR_REGISTRATION_INVALID") from exc
|
|
if not isinstance(value, dict) or set(value) != {"payload", "signature"}:
|
|
_fail("EXECUTOR_REGISTRATION_FIELDS_INVALID")
|
|
return value
|
|
|
|
|
|
class RegisteredInstallerExecutor:
|
|
def __init__(
|
|
self, *, owner_verifier: RegistryOwnerVerifier, installer: Installer,
|
|
provenance_manifest: Path, clock: Callable[[], int],
|
|
host: Callable[[], str] = socket.gethostname,
|
|
require_root_owner: bool = True,
|
|
) -> None:
|
|
if type(installer) is not Installer:
|
|
_fail("EXECUTOR_INSTALLER_TYPE_INVALID")
|
|
if not isinstance(owner_verifier, RegistryOwnerVerifier):
|
|
_fail("EXECUTOR_OWNER_VERIFIER_INVALID")
|
|
self.owner_verifier = owner_verifier
|
|
self.installer = installer
|
|
self.provenance_manifest = Path(provenance_manifest)
|
|
self.clock = clock
|
|
self.host = host
|
|
self.require_root_owner = require_root_owner
|
|
self.provenance = load_code_provenance(
|
|
self.provenance_manifest, require_root_owner=require_root_owner,
|
|
)
|
|
|
|
def _check_code_provenance(self) -> None:
|
|
current = load_code_provenance(
|
|
self.provenance_manifest, require_root_owner=self.require_root_owner,
|
|
)
|
|
if current != self.provenance:
|
|
_fail("EXECUTOR_CODE_PROVENANCE_CHANGED")
|
|
|
|
def _verify(
|
|
self, registration: Mapping[str, Any], contract: Path,
|
|
) -> tuple[dict[str, Any], str, dict[str, Any]]:
|
|
self._check_code_provenance()
|
|
if (
|
|
not isinstance(registration, Mapping)
|
|
or set(registration) != {"payload", "signature"}
|
|
or not isinstance(registration["payload"], Mapping)
|
|
):
|
|
_fail("EXECUTOR_REGISTRATION_FIELDS_INVALID")
|
|
if self.host() != HOST:
|
|
_fail("EXECUTOR_HOST_MISMATCH")
|
|
now = int(self.clock())
|
|
contract_payload, contract_digest = _verified_contract(
|
|
contract, self.installer, now=now,
|
|
)
|
|
payload = dict(registration["payload"])
|
|
dependency = payload.get("issuer_dependency")
|
|
_validate_payload(
|
|
payload, now=now, provenance=self.provenance,
|
|
contract_payload=contract_payload, contract_digest=contract_digest,
|
|
issuer_dependency=dependency,
|
|
)
|
|
if payload["owner_key_id"] != self.owner_verifier.record.fingerprint:
|
|
_fail("EXECUTOR_OWNER_KEY_BINDING_INVALID")
|
|
signature = registration["signature"]
|
|
if (
|
|
not isinstance(signature, str)
|
|
or not self.owner_verifier.verify(
|
|
namespace=OWNER_NAMESPACE, payload=canonical_bytes(payload),
|
|
signature=signature, key_id=payload["owner_key_id"],
|
|
)
|
|
):
|
|
_fail("EXECUTOR_OWNER_SIGNATURE_INVALID")
|
|
return payload, contract_digest, contract_payload
|
|
|
|
def dispatch(
|
|
self, registration: Mapping[str, Any], contract: Path,
|
|
artifact: Path, operation: str, *,
|
|
issuer_contract: Path | None = None,
|
|
issuer_artifact: Path | None = None,
|
|
) -> dict[str, Any]:
|
|
payload, contract_digest, contract_payload = self._verify(registration, contract)
|
|
capability = "install" if operation in {"preflight", "install"} else operation
|
|
if capability not in CAPABILITIES:
|
|
_fail("EXECUTOR_OPERATION_INVALID")
|
|
if capability not in payload["capabilities"]:
|
|
_fail("EXECUTOR_CAPABILITY_INVALID")
|
|
if operation == "rollback" and contract_payload["target"] == BRIDGE_TARGET:
|
|
if issuer_artifact is None:
|
|
_fail("EXECUTOR_ISSUER_DEPENDENCY_REQUIRED")
|
|
actual_dependency = _verified_issuer_dependency(
|
|
issuer_contract, self.installer, now=int(self.clock()),
|
|
contract_payload=contract_payload,
|
|
)
|
|
if actual_dependency != payload["issuer_dependency"]:
|
|
_fail("EXECUTOR_ISSUER_DEPENDENCY_MISMATCH")
|
|
elif issuer_contract is not None or issuer_artifact is not None:
|
|
_fail("EXECUTOR_ISSUER_DEPENDENCY_UNEXPECTED")
|
|
if operation == "preflight":
|
|
result = self.installer.preflight(contract, artifact)
|
|
elif operation == "install":
|
|
result = self.installer.apply(contract, artifact)
|
|
elif operation == "rollback":
|
|
result = self.installer.rollback_applied(
|
|
contract, artifact, issuer_contract=issuer_contract,
|
|
issuer_artifact=issuer_artifact,
|
|
)
|
|
else:
|
|
result = self.installer.reconcile_unknown(contract, artifact)
|
|
return {
|
|
**result,
|
|
"operation": operation,
|
|
"executor_id": payload["executor_id"],
|
|
"contract_digest": contract_digest,
|
|
"code_binding": {
|
|
"integration_commit": payload["integration_commit"],
|
|
"integration_tree": payload["integration_tree"],
|
|
"installer_module_sha256": payload["installer_module_sha256"],
|
|
"installer_script_sha256": payload["installer_script_sha256"],
|
|
"executor_module_sha256": payload["executor_module_sha256"],
|
|
},
|
|
"registration_policy_digest": _sha256_bytes(canonical_bytes(payload)),
|
|
}
|
|
|
|
|
|
def _parser() -> argparse.ArgumentParser:
|
|
parser = argparse.ArgumentParser(
|
|
description="Run one Owner-registered fixed-scope C5 installer operation.",
|
|
)
|
|
parser.add_argument(
|
|
"operation", choices=("preflight", "install", "rollback", "reconcile"),
|
|
)
|
|
parser.add_argument("--registration", type=Path, required=True)
|
|
parser.add_argument("--contract", type=Path, required=True)
|
|
parser.add_argument("--artifact", type=Path, required=True)
|
|
parser.add_argument("--issuer-contract", type=Path)
|
|
parser.add_argument("--issuer-artifact", type=Path)
|
|
return parser
|
|
|
|
|
|
def main(argv: list[str] | None = None) -> int:
|
|
"""Production CLI with fixed registry and provenance authority paths."""
|
|
args = _parser().parse_args(argv)
|
|
try:
|
|
registration = load_registration(args.registration)
|
|
payload = registration.get("payload")
|
|
if not isinstance(payload, Mapping) or not isinstance(payload.get("owner_signer_id"), str):
|
|
_fail("EXECUTOR_REGISTRATION_FIELDS_INVALID")
|
|
installer = Installer(DEFAULT_REGISTRY)
|
|
verifier = RegistryOwnerVerifier(
|
|
DEFAULT_REGISTRY, owner_signer_id=payload["owner_signer_id"],
|
|
)
|
|
executor = RegisteredInstallerExecutor(
|
|
owner_verifier=verifier, installer=installer,
|
|
provenance_manifest=DEFAULT_PROVENANCE_MANIFEST,
|
|
clock=lambda: int(time.time()),
|
|
)
|
|
result = executor.dispatch(
|
|
registration, args.contract, args.artifact, args.operation,
|
|
issuer_contract=args.issuer_contract,
|
|
issuer_artifact=args.issuer_artifact,
|
|
)
|
|
print(json.dumps(result, sort_keys=True))
|
|
return 0
|
|
except InstallationOutcomeUnknown as exc:
|
|
print(
|
|
json.dumps({"status": "UNKNOWN", "error": exc.code}, sort_keys=True),
|
|
file=sys.stderr,
|
|
)
|
|
return 3
|
|
except (ExecutorRegistrationError, InstallationError, OSError, ValueError, TypeError) as exc:
|
|
print(
|
|
json.dumps(
|
|
{"status": "REJECTED", "error": getattr(exc, "code", str(exc))},
|
|
sort_keys=True,
|
|
),
|
|
file=sys.stderr,
|
|
)
|
|
return 2
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|