Spaces:
Runtime error
Runtime error
Deploy Aureon OS (deploy/selfhost stack: nginx edge + fusion API x2 + console + HNC organ + redis + postgres; paper mode) (part 5)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- aureon/operator/website_design_capabilities/motion_interaction.pyAdded+88
- aureon/operator/website_design_capabilities/performance_core_web_vitals.pyAdded+99
- aureon/operator/website_design_capabilities/research_object_rendering.pyAdded+78
- aureon/operator/website_design_capabilities/visual_identity_tokens.pyAdded+71
- aureon/operator/website_design_capability_set.pyAdded+678
- aureon/operator/website_operator.defaults.jsonAdded+417
- aureon/operator/website_operator.pyAdded
- aureon/operator/website_operator.schema.jsonAdded+227
- aureon/operator/website_operator_receipts.schema.jsonAdded+87
- aureon/operator/website_runtime_measurement_provenance.pyAdded+938
- aureon/operator/website_runtime_optimisation.pyAdded+1743
- aureon/operator/website_source_rationalisation.pyAdded+1915
- aureon/operator/wsgi.pyAdded+19
- aureon/organism/__init__.pyAdded+1
- aureon/organism/repository_layers.pyAdded+254
- aureon/plumber/__init__.pyAdded+682
- aureon/plumber/audit.pyAdded+165
- aureon/plumber/authorization_chain_v02.pyAdded+652
- aureon/plumber/breaker.pyAdded+160
- aureon/plumber/crypto.pyAdded+307
- aureon/plumber/enclave.pyAdded+428
- aureon/plumber/immune_gate.pyAdded+271
- aureon/plumber/magic_star_v02.pyAdded+1171
- aureon/plumber/observer_transcript.pyAdded+236
- aureon/plumber/os_protection.pyAdded+2081
- aureon/plumber/packet.pyAdded+1184
- aureon/plumber/production_release_broker_v03.pyAdded+2126
- aureon/plumber/proposal_forge.pyAdded+973
- aureon/plumber/protected_bootstrap_v05.pyAdded+586
- aureon/plumber/quarantine.pyAdded+135
- aureon/plumber/quorum.pyAdded+316
- aureon/plumber/receipts.pyAdded+251
- aureon/plumber/recipient_proof_v02.pyAdded+395
- aureon/plumber/release_boundary_v02.pyAdded+1199
- aureon/plumber/release_engine.pyAdded+648
- aureon/plumber/release_evidence_v02.pyAdded+437
- aureon/plumber/release_state_v02.pyAdded+453
- aureon/plumber/runtime_guard_v04.pyAdded+1952
- aureon/plumber/runtime_intrusion_ledger_v04.pyAdded
- aureon/plumber/schema.pyAdded+373
- aureon/plumber/source_identity.pyAdded+143
- aureon/plumber/spore_transport.pyAdded
- aureon/plumber/star_custody_v02.pyAdded
- aureon/plumber/sympathetic_identity.pyAdded
- aureon/plumber/temporal_identity.pyAdded
- aureon/plumber/twin_rune_seal.pyAdded
- aureon/portals/__init__.pyAdded
- aureon/portals/actions.pyAdded
- aureon/portals/ifs.pyAdded
- aureon/portals/reconcile.pyAdded
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788"""Audit purposeful motion and its equivalent reduced-motion path."""
from __future__ import annotations
import re
from collections.abc import Sequence
from pathlib import Path
from .common import CapabilityInputError, CapabilityResult, finding, read_text
SKILL_ID = "motion_interaction"
def audit_motion(root: Path, source_paths: Sequence[str]) -> CapabilityResult:
"""Detect motion, purpose annotations, reduced-motion, and hostile patterns."""
if not source_paths:
raise CapabilityInputError("source_paths must be non-empty")
evidence: list[str] = []
sources: list[str] = []
for item in source_paths:
safe, source = read_text(root, item, suffixes={".html", ".css", ".js"})
evidence.append(safe)
sources.append(source)
combined = "\n".join(sources)
lowered = combined.lower()
motion_count = len(re.findall(r"\b(?:animation|transition|requestanimationframe|gsap\.)\b", lowered))
animation_names = re.findall(r"\banimation\s*:\s*([a-z][a-z0-9-]*)", lowered)
purposeful_terms = (
"assemble",
"connect",
"evidence",
"field",
"flow",
"orbit",
"progress",
"pulse",
"reveal",
"route",
"scan",
"signal",
"weave",
)
semantic_names = [name for name in animation_names if any(term in name for term in purposeful_terms)]
purpose_count = (
lowered.count("data-motion-purpose") + lowered.count("motion-purpose:") + len(semantic_names)
)
hostile: list[str] = []
if "scroll-hijack" in lowered:
hostile.append("scroll-hijack")
if re.search(
r"addeventlistener\s*\(\s*[\"'](?:wheel|touchmove)[\"'][\s\S]{0,800}?preventdefault\s*\(",
lowered,
):
hostile.append("wheel-or-touchmove-prevent-default")
findings = (
finding(
"motion-detected", motion_count > 0, "At least one declared motion behaviour is inspectable."
),
finding(
"motion-purpose",
motion_count == 0 or purpose_count > 0,
"Motion has a documented structural purpose.",
),
finding(
"reduced-motion",
motion_count == 0 or "prefers-reduced-motion" in lowered,
"Motion provides a reduced-motion path.",
),
finding(
"no-scroll-hostility",
not hostile,
"No scroll-hijack marker was found."
if not hostile
else f"Hostile interaction markers: {', '.join(hostile)}.",
),
finding(
"bounded-infinite-motion",
"infinite" not in lowered or "prefers-reduced-motion" in lowered,
"Infinite motion is absent or guarded by reduced-motion.",
),
)
return CapabilityResult(
SKILL_ID,
findings,
evidence=tuple(evidence),
metrics={"motion_markers": motion_count, "purpose_markers": purpose_count},
)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899"""Audit static asset budgets and validate captured Core Web Vitals."""
from __future__ import annotations
from collections.abc import Mapping, Sequence
from pathlib import Path
from .common import (
CapabilityInputError,
CapabilityResult,
finding,
require_safe_relative_path,
resolve_readonly_file,
)
SKILL_ID = "performance_core_web_vitals"
_GROUPS = {
".css": "css_bytes",
".js": "javascript_bytes",
".avif": "image_bytes",
".gif": "image_bytes",
".jpg": "image_bytes",
".jpeg": "image_bytes",
".png": "image_bytes",
".svg": "image_bytes",
".webp": "image_bytes",
}
_VITAL_LIMITS = {"lcp_ms": 2500.0, "inp_ms": 200.0, "cls": 0.1}
def audit_performance(
root: Path,
asset_paths: Sequence[str],
budgets: Mapping[str, int],
live_vitals: Mapping[str, float] | None = None,
) -> CapabilityResult:
"""Measure source bytes and validate an optional externally captured vitals row."""
if not asset_paths:
raise CapabilityInputError("asset_paths must be non-empty")
allowed_budgets = {"total_bytes", "css_bytes", "javascript_bytes", "image_bytes"}
if (
not budgets
or set(budgets) - allowed_budgets
or any(not isinstance(value, int) or value <= 0 for value in budgets.values())
):
raise CapabilityInputError("budgets must contain positive integer values for supported byte groups")
totals = dict.fromkeys(allowed_budgets, 0)
evidence: list[str] = []
for item in asset_paths:
safe = require_safe_relative_path(item)
path = resolve_readonly_file(root, safe, max_bytes=50_000_000)
size = path.stat().st_size
totals["total_bytes"] += size
group = _GROUPS.get(path.suffix.lower())
if group is not None:
totals[group] += size
evidence.append(f"{safe}#bytes={size}")
budget_failures = [name for name, limit in budgets.items() if totals[name] > limit]
findings = [
finding(
"static-asset-budgets",
not budget_failures,
"All supplied static asset budgets pass."
if not budget_failures
else f"Exceeded budgets: {', '.join(sorted(budget_failures))}.",
),
]
if live_vitals is None:
findings.append(
finding(
"live-vitals-evidence",
False,
"No live LCP, INP, and CLS capture was supplied; collect it before release.",
)
)
else:
if set(live_vitals) != set(_VITAL_LIMITS) or any(
not isinstance(value, (int, float)) or isinstance(value, bool) or value < 0
for value in live_vitals.values()
):
raise CapabilityInputError(
"live_vitals must contain non-negative numeric lcp_ms, inp_ms, and cls"
)
vital_failures = [name for name, limit in _VITAL_LIMITS.items() if float(live_vitals[name]) > limit]
findings.append(
finding(
"live-vitals-thresholds",
not vital_failures,
"Captured Core Web Vitals meet the good thresholds."
if not vital_failures
else f"Vitals above threshold: {', '.join(vital_failures)}.",
)
)
evidence.append("live-vitals:externally-captured-input")
metrics: dict[str, str | int | float | bool] = dict(totals)
if live_vitals is not None:
metrics.update({name: float(value) for name, value in live_vitals.items()})
return CapabilityResult(SKILL_ID, tuple(findings), evidence=tuple(evidence), metrics=metrics)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778"""Validate render-ready DOI, ORCID, certificate, and ledger objects."""
from __future__ import annotations
import re
from collections.abc import Mapping, Sequence
from .common import CapabilityInputError, CapabilityResult, finding, require_mapping
SKILL_ID = "research_object_rendering"
_DOI = re.compile(r"^10\.\d{4,9}/\S+$", re.IGNORECASE)
_KINDS = {"doi", "orcid", "certificate", "ledger"}
def _valid_orcid(value: str) -> bool:
digits = value.replace("-", "").upper()
if not re.fullmatch(r"\d{15}[\dX]", digits):
return False
total = 0
for char in digits[:15]:
total = (total + int(char)) * 2
remainder = (12 - total % 11) % 11
expected = "X" if remainder == 10 else str(remainder)
return digits[-1] == expected
def audit_research_objects(objects: Sequence[Mapping[str, object]]) -> CapabilityResult:
"""Validate provenance fields and identifiers needed for truthful rendering."""
if not objects:
raise CapabilityInputError("objects must be non-empty")
malformed: list[str] = []
ids: list[str] = []
for index, value in enumerate(objects):
row = require_mapping(value, f"objects[{index}]")
object_id = row.get("id")
kind = row.get("kind")
title = row.get("title")
observed_at = row.get("observed_at")
source_url = row.get("source_url")
if not isinstance(object_id, str) or not object_id or object_id in ids:
raise CapabilityInputError("research object ids must be unique non-empty strings")
ids.append(object_id)
valid = (
kind in _KINDS
and isinstance(title, str)
and bool(title.strip())
and isinstance(observed_at, str)
and bool(observed_at.strip())
and isinstance(source_url, str)
and source_url.startswith("https://")
)
identifier = row.get("identifier")
if kind == "doi":
valid = valid and isinstance(identifier, str) and bool(_DOI.fullmatch(identifier))
elif kind == "orcid":
valid = valid and isinstance(identifier, str) and _valid_orcid(identifier)
elif kind in {"certificate", "ledger"}:
valid = valid and isinstance(identifier, str) and bool(identifier.strip())
if not valid:
malformed.append(object_id)
findings = (
finding(
"research-object-provenance",
not malformed,
"Every research object has a valid identifier and render provenance."
if not malformed
else f"Invalid research objects: {', '.join(malformed)}.",
),
finding("research-object-uniqueness", len(ids) == len(set(ids)), "Research object ids are unique."),
)
return CapabilityResult(
SKILL_ID,
findings,
evidence=tuple(f"research-object:{item}" for item in ids),
metrics={"object_count": len(ids)},
publishable_ids=tuple(ids) if not malformed else (),
)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071"""Audit the source-controlled CSS token system."""
from __future__ import annotations
import re
from pathlib import Path
from .common import CapabilityResult, finding, read_text
SKILL_ID = "visual_identity_tokens"
_TOKEN = re.compile(r"(--[a-z0-9-]+)\s*:\s*([^;{}]+);", re.IGNORECASE)
_FAMILY_ALIASES = {
"colour": ("color", "page", "surface", "text", "muted", "line", "mint", "cyan", "violet", "amber"),
"typography": ("font", "type", "leading", "tracking"),
"spacing": ("space", "gap", "gutter"),
"radius": ("radius",),
}
def audit_tokens(root: Path, stylesheet_path: str) -> CapabilityResult:
"""Inspect token coverage, duplicate definitions, and raw hex colour drift."""
safe, css = read_text(root, stylesheet_path, suffixes={".css"})
definitions = _TOKEN.findall(css)
names = [name.lower() for name, _ in definitions]
duplicate_names = sorted({name for name in names if names.count(name) > 1})
missing_families = [
family
for family, aliases in _FAMILY_ALIASES.items()
if not any(any(name.startswith(f"--{alias}") for alias in aliases) for name in names)
]
hex_literals = re.findall(r"#[0-9a-fA-F]{3,8}\b", css)
findings = (
finding(
"tokens-present",
bool(definitions),
"CSS must define source-controlled custom properties.",
location=safe,
),
finding(
"required-token-families",
not missing_families,
"Required token families are present."
if not missing_families
else f"Missing token families: {', '.join(missing_families)}.",
location=safe,
warning=True,
),
finding(
"unique-token-names",
not duplicate_names,
"Token names are unique."
if not duplicate_names
else f"Duplicate tokens: {', '.join(duplicate_names)}.",
location=safe,
warning=True,
),
finding(
"colour-token-ratio",
len(hex_literals) <= max(4, len([name for name in names if "color" in name]) * 2),
"Raw colour literals remain bounded relative to colour tokens.",
location=safe,
warning=True,
),
)
return CapabilityResult(
SKILL_ID,
findings,
evidence=(safe,),
metrics={"token_count": len(definitions), "raw_hex_literals": len(hex_literals)},
)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678"""Machine-readable website and design capability contracts.
This module is the small, deterministic control-plane registry for Aureon's
investor-website work. It names the required skills, gives each skill exactly
one accountable owner, and binds every skill to a versioned contract and a
repo-relative evidence location.
Discovery and validation are deliberately read-only. A valid registry does
not select a candidate, approve a claim, grant credentials, authorise a
deployment, or prove a live outcome. Production remains default-deny until
the exact current candidate/package and target pass the human AuthorityGate;
the CEO/owner/user veto is final at every stage.
"""
from __future__ import annotations
import argparse
import importlib
import json
import re
from collections.abc import Mapping, Sequence
from dataclasses import dataclass
from pathlib import PurePosixPath
from typing import Any
REGISTRY_SCHEMA = "aureon.website-design-capability-set.v1"
VERIFICATION_SCHEMA = "aureon.website-design-capability-set-verification.v1"
REGISTRY_VERSION = "2.0.0"
REGISTRY_OWNER_AGENT = "skill_writer"
EVIDENCE_ROOT = PurePosixPath("artifacts/website-operator/capability-evidence")
OWNER_AGENTS = (
"design_director",
"graphic_motion",
"frontend_implementation",
"evidence_copy",
"research_object",
"homepl_deploy",
"audit_benchmark",
"skill_writer",
)
REQUIRED_SKILL_IDS = (
"visual_identity_tokens",
"layout_typography_grid",
"motion_interaction",
"information_architecture_routing",
"evidence_bound_copywriting",
"research_object_rendering",
"diagram_connectome_graphics",
"image_svg_generative_pipeline",
"accessibility_reduced_motion",
"performance_core_web_vitals",
"homepl_deploy_cache_ssl_readback",
"claim_state_linter",
"competitor_position_audit",
"design_qa_visual_regression",
"content_inventory_connectors",
)
IMPLEMENTATION_ENTRYPOINTS = {
"visual_identity_tokens": "audit_tokens",
"layout_typography_grid": "audit_layout",
"motion_interaction": "audit_motion",
"information_architecture_routing": "audit_routing",
"evidence_bound_copywriting": "audit_copy_provenance",
"research_object_rendering": "audit_research_objects",
"diagram_connectome_graphics": "audit_diagram_fallbacks",
"image_svg_generative_pipeline": "audit_image_inventory",
"accessibility_reduced_motion": "prepare_accessibility_audit",
"performance_core_web_vitals": "audit_performance",
"homepl_deploy_cache_ssl_readback": "verify_homepl_readback",
"claim_state_linter": "lint_claim_states",
"competitor_position_audit": "audit_competitor_sources",
"design_qa_visual_regression": "evaluate_visual_regression",
"content_inventory_connectors": "reconcile_content_inventory",
}
IMPLEMENTATION_PACKAGE = "aureon.operator.website_design_capabilities"
@dataclass(frozen=True)
class LoopStep:
"""One mandatory transition in the HNC website-improvement loop."""
stage: str
contract: str
next_stage: str
def to_dict(self, ordinal: int) -> dict[str, object]:
return {
"ordinal": ordinal,
"stage": self.stage,
"contract": self.contract,
"next_stage": self.next_stage,
"evidence_required": True,
}
HNC_LOOP = (
LoopStep(
"Sense",
"Inventory the controlled source, live surface, research, stakeholder signals, "
"rights state, and current external evidence without mutation.",
"Route",
),
LoopStep(
"Route",
"Select only the registered skill and its single accountable owner for each bounded task.",
"Constraint",
),
LoopStep(
"Constraint",
"Bind claim state, provenance, rights, privacy, accessibility, performance, source, and authority limits.",
"Generate",
),
LoopStep(
"Generate",
"Create changes only in an isolated candidate whose source and intended delta are inspectable.",
"Test",
),
LoopStep(
"Test",
"Run deterministic static, functional, accessibility, performance, link, metadata, and visual checks.",
"ResonanceCheck",
),
LoopStep(
"ResonanceCheck",
"Compare the tested result with Aureon's ethos, investor journey, research evidence, and named review evidence.",
"Veto",
),
LoopStep(
"Veto",
"Stop on any unresolved claim, rights, privacy, accessibility, performance, source, visual, or security blocker.",
"AuthorityGate",
),
LoopStep(
"AuthorityGate",
"Require the current CEO/owner/user decision bound to the exact candidate/package hash and deployment target; "
"the human veto cannot be overridden.",
"Deploy",
),
LoopStep(
"Deploy",
"After a verified backup, publish only the exact authorised package to the authenticated served root.",
"ReadBack",
),
LoopStep(
"ReadBack",
"Fetch the public routes and verify status, TLS, cache behaviour, content hashes, fragments, and critical assets.",
"Ledger",
),
LoopStep(
"Ledger",
"Append immutable candidate, test, approval, backup, deployment, and live-readback evidence; never infer success.",
"Expand",
),
LoopStep(
"Expand",
"Promote only evidence-backed learning into a versioned contract improvement, then sense the system again.",
"Sense",
),
)
HNC_STAGES = tuple(step.stage for step in HNC_LOOP)
AUTHORITY_BOUNDARY = {
"deployment_default": "blocked",
"registry_grants_deployment_authority": False,
"human_authority": "ceo_owner_user",
"approval_binding": "exact-current-candidate-package-hash-and-deployment-target",
"human_veto": "final-and-non-overridable-at-every-stage",
"backup_required_before_deploy": True,
"live_readback_required": True,
"credentials_in_evidence": False,
}
@dataclass(frozen=True)
class WebsiteDesignSkill:
"""A required capability with one accountable owner and evidence contract."""
skill_id: str
owner_agent: str
obligation: str
hnc_stages: tuple[str, ...]
version: str = "1.0.0"
@property
def implementation_module(self) -> str:
return f"{IMPLEMENTATION_PACKAGE}.{self.skill_id}"
@property
def implementation_entrypoint(self) -> str:
return IMPLEMENTATION_ENTRYPOINTS[self.skill_id]
@property
def contract_id(self) -> str:
return f"aureon.website-capability.{self.skill_id}.v1"
@property
def evidence_path(self) -> str:
return (EVIDENCE_ROOT / self.skill_id).as_posix()
def to_dict(self) -> dict[str, object]:
return {
"skill_id": self.skill_id,
"required": True,
"version": self.version,
"owner_agent": self.owner_agent,
"contract": {
"id": self.contract_id,
"obligation": self.obligation,
"evidence_required": True,
},
"evidence_path": self.evidence_path,
"hnc_stages": list(self.hnc_stages),
"implementation": {
"module": self.implementation_module,
"entrypoint": self.implementation_entrypoint,
"mode": "deterministic-read-only-audit-or-prepare",
"result_schema": "aureon.website-capability-result.v1",
"side_effects_allowed": False,
"deployment_authority": "none",
},
}
SKILLS = (
WebsiteDesignSkill(
"visual_identity_tokens",
"design_director",
"Define source-controlled colour, type, spacing, depth, and state tokens; verify contrast and brand "
"consistency before candidate use.",
("Constraint", "Generate", "ResonanceCheck"),
),
WebsiteDesignSkill(
"layout_typography_grid",
"frontend_implementation",
"Implement a responsive grid and typographic hierarchy that preserve reading order, legibility, and route intent "
"across the supported viewport matrix.",
("Generate", "Test"),
),
WebsiteDesignSkill(
"motion_interaction",
"graphic_motion",
"Use purposeful, finite interaction and motion with equivalent reduced-motion and keyboard behaviour; reject "
"spectacle that obscures evidence.",
("Constraint", "Generate", "ResonanceCheck"),
),
WebsiteDesignSkill(
"information_architecture_routing",
"design_director",
"Map investor questions to a coherent route, navigation, CTA, and fragment hierarchy with no dead ends or "
"ambiguous evidence paths.",
("Route", "Constraint", "Test"),
),
WebsiteDesignSkill(
"evidence_bound_copywriting",
"evidence_copy",
"Write concise investor-facing copy bound to claim state and provenance, clearly separating research, use cases, "
"relationships, and verified adoption.",
("Constraint", "Generate", "ResonanceCheck"),
),
WebsiteDesignSkill(
"research_object_rendering",
"research_object",
"Render curated research from dated authoritative records while preserving title, authorship, identifier, date, "
"source link, and qualification without invented traction.",
("Sense", "Generate", "Test"),
),
WebsiteDesignSkill(
"diagram_connectome_graphics",
"graphic_motion",
"Express the HNC research-to-use-case system as a legible evidence-labelled diagram with an accessible textual "
"fallback and no unsupported causal claim.",
("Constraint", "Generate", "Test"),
),
WebsiteDesignSkill(
"image_svg_generative_pipeline",
"graphic_motion",
"Create and optimise public visual assets only with recorded provenance, route-scoped rights, alt text, and "
"footprint evidence; reject uncleared assets.",
("Constraint", "Generate", "Test", "Veto"),
),
WebsiteDesignSkill(
"accessibility_reduced_motion",
"audit_benchmark",
"Verify semantics, focus, keyboard flow, contrast, no-JavaScript reading, and reduced-motion behaviour; any "
"unresolved release-blocking finding is a veto.",
("Test", "Veto"),
),
WebsiteDesignSkill(
"performance_core_web_vitals",
"audit_benchmark",
"Measure fixed asset budgets and Core Web Vitals across the agreed mobile and desktop matrix; veto unexplained "
"regressions or incomplete measurements.",
("Test", "Veto"),
),
WebsiteDesignSkill(
"homepl_deploy_cache_ssl_readback",
"homepl_deploy",
"Verify the served-root backup, publish only an exactly authorised package, then prove TLS, cache, route, and "
"file-hash state by live readback without retaining credentials.",
("AuthorityGate", "Deploy", "ReadBack", "Ledger"),
),
WebsiteDesignSkill(
"claim_state_linter",
"evidence_copy",
"Classify every material public claim as evidenced, qualified, or omitted and veto stale figures, internal "
"records, overclaiming, or unsupported relationship and adoption language.",
("Sense", "Constraint", "Test", "Veto"),
),
WebsiteDesignSkill(
"competitor_position_audit",
"audit_benchmark",
"Capture dated primary-source competitor patterns, distinguish reusable design conventions from unsupported "
"imitation, and route findings into Aureon's own evidence-led position.",
("Sense", "Route", "ResonanceCheck"),
),
WebsiteDesignSkill(
"design_qa_visual_regression",
"audit_benchmark",
"Capture and compare the named browser and viewport matrix, fragments, no-JavaScript state, and critical visual "
"flows; incomplete evidence or an unresolved regression is a veto.",
("Test", "ResonanceCheck", "Veto", "Ledger"),
),
WebsiteDesignSkill(
"content_inventory_connectors",
"research_object",
"Read only the minimally necessary dated Gmail, Drive, ORCID, Substack, GitHub, and analytics evidence; redact "
"secrets, personal data, and internal figures, and never equate raw activity with adoption.",
("Sense", "Route", "Ledger", "Expand"),
),
)
SKILL_BY_ID = {skill.skill_id: skill for skill in SKILLS}
class WebsiteDesignCapabilitySetError(ValueError):
"""Raised when the checked-in capability contract is invalid."""
def discover_website_design_capability_set() -> dict[str, object]:
"""Return a fresh, JSON-serialisable view of the checked-in registry."""
return {
"schema": REGISTRY_SCHEMA,
"registry_version": REGISTRY_VERSION,
"registry_owner_agent": REGISTRY_OWNER_AGENT,
"state": "implemented-default-deny",
"authority": dict(AUTHORITY_BOUNDARY),
"owner_agents": list(OWNER_AGENTS),
"hnc_loop": [step.to_dict(ordinal) for ordinal, step in enumerate(HNC_LOOP, start=1)],
"skills": [skill.to_dict() for skill in SKILLS],
}
def _check(identifier: str, passed: bool, message: str) -> dict[str, object]:
return {"id": identifier, "passed": passed, "message": message}
def _valid_evidence_path(value: object, skill_id: str) -> bool:
if not isinstance(value, str) or not value:
return False
path = PurePosixPath(value)
return not path.is_absolute() and ".." not in path.parts and path == EVIDENCE_ROOT / skill_id
def _implementation_is_importable(module_name: str, entrypoint: str) -> bool:
"""Resolve one canonical implementation and reject aliases or rebound callables."""
try:
module = importlib.import_module(module_name)
implementation = getattr(module, entrypoint)
except (AttributeError, ImportError, ModuleNotFoundError):
return False
return (
callable(implementation)
and getattr(implementation, "__module__", None) == module_name
and getattr(implementation, "__name__", None) == entrypoint
and getattr(module, "SKILL_ID", None) == module_name.rsplit(".", maxsplit=1)[-1]
)
def validate_website_design_capability_set(
registry: Mapping[str, Any] | None = None,
) -> dict[str, object]:
"""Validate schema, ownership, contracts, evidence paths, loop, and authority.
Validation performs no filesystem or network I/O and carries no release or
deployment authority.
"""
candidate: Mapping[str, Any] = discover_website_design_capability_set() if registry is None else registry
checks: list[dict[str, object]] = []
checks.append(
_check(
"schema-version",
candidate.get("schema") == REGISTRY_SCHEMA
and candidate.get("registry_version") == REGISTRY_VERSION,
"Registry schema and version must match the checked-in contract.",
)
)
checks.append(
_check(
"registry-owner",
candidate.get("registry_owner_agent") == REGISTRY_OWNER_AGENT,
"The skill-writer agent must own registry maintenance.",
)
)
checks.append(
_check(
"authority-boundary",
candidate.get("authority") == AUTHORITY_BOUNDARY
and candidate.get("state") == "implemented-default-deny",
"The registry must remain default-deny with final CEO/owner/user control.",
)
)
loop_rows = candidate.get("hnc_loop")
loop_ok = isinstance(loop_rows, list) and len(loop_rows) == len(HNC_LOOP)
if isinstance(loop_rows, list):
for ordinal, expected in enumerate(HNC_LOOP, start=1):
if ordinal > len(loop_rows) or not isinstance(loop_rows[ordinal - 1], Mapping):
loop_ok = False
continue
row = loop_rows[ordinal - 1]
loop_ok = loop_ok and (
row.get("ordinal") == ordinal
and row.get("stage") == expected.stage
and row.get("contract") == expected.contract
and row.get("next_stage") == expected.next_stage
and row.get("evidence_required") is True
)
checks.append(
_check(
"hnc-loop-order",
loop_ok,
"The exact Sense-to-Expand loop and return to Sense must remain intact.",
)
)
owner_rows = candidate.get("owner_agents")
checks.append(
_check(
"owner-agent-catalogue",
isinstance(owner_rows, list)
and all(isinstance(owner, str) for owner in owner_rows)
and len(owner_rows) == len(set(owner_rows))
and tuple(owner_rows) == OWNER_AGENTS,
"Only the canonical owner-agent identifiers may be used.",
)
)
skill_rows = candidate.get("skills")
rows_ok = isinstance(skill_rows, list) and len(skill_rows) == len(REQUIRED_SKILL_IDS)
seen_ids: list[str] = []
seen_contracts: list[str] = []
seen_paths: list[str] = []
covered_stages: set[str] = set()
deploy_stage_skills: set[str] = set()
single_owner_ok = rows_ok
contracts_ok = rows_ok
versions_ok = rows_ok
evidence_ok = rows_ok
stages_ok = rows_ok
implementation_contracts_ok = rows_ok
implementations_importable = rows_ok
seen_implementations: list[str] = []
if isinstance(skill_rows, list):
for row in skill_rows:
if not isinstance(row, Mapping):
rows_ok = single_owner_ok = contracts_ok = versions_ok = evidence_ok = stages_ok = (
implementation_contracts_ok
) = implementations_importable = False
continue
skill_id = row.get("skill_id")
if not isinstance(skill_id, str):
rows_ok = single_owner_ok = contracts_ok = versions_ok = evidence_ok = stages_ok = (
implementation_contracts_ok
) = implementations_importable = False
continue
seen_ids.append(skill_id)
expected_skill = SKILL_BY_ID.get(skill_id)
owner = row.get("owner_agent")
single_owner_ok = (
single_owner_ok
and expected_skill is not None
and isinstance(owner, str)
and owner in OWNER_AGENTS
and owner == expected_skill.owner_agent
)
single_owner_ok = single_owner_ok and "owner_agents" not in row
rows_ok = rows_ok and row.get("required") is True
version = row.get("version")
versions_ok = (
versions_ok
and isinstance(version, str)
and bool(re.fullmatch(r"[1-9]\d*\.\d+\.\d+", version))
)
versions_ok = versions_ok and expected_skill is not None and version == expected_skill.version
contract = row.get("contract")
if isinstance(contract, Mapping):
contract_id = contract.get("id")
obligation = contract.get("obligation")
expected_contract = f"aureon.website-capability.{skill_id}.v1"
contracts_ok = contracts_ok and (
contract_id == expected_contract
and isinstance(obligation, str)
and bool(obligation.strip())
and expected_skill is not None
and obligation == expected_skill.obligation
and contract.get("evidence_required") is True
)
if isinstance(contract_id, str):
seen_contracts.append(contract_id)
else:
contracts_ok = False
evidence_path = row.get("evidence_path")
evidence_ok = evidence_ok and _valid_evidence_path(evidence_path, skill_id)
if isinstance(evidence_path, str):
seen_paths.append(evidence_path)
stages = row.get("hnc_stages")
if isinstance(stages, list) and stages:
stage_values = {stage for stage in stages if isinstance(stage, str)}
stages_ok = stages_ok and len(stage_values) == len(stages)
stages_ok = stages_ok and stage_values.issubset(set(HNC_STAGES))
stages_ok = (
stages_ok and expected_skill is not None and tuple(stages) == expected_skill.hnc_stages
)
covered_stages.update(stage_values)
if "Deploy" in stage_values:
deploy_stage_skills.add(skill_id)
else:
stages_ok = False
implementation = row.get("implementation")
if isinstance(implementation, Mapping) and expected_skill is not None:
module_name = implementation.get("module")
entrypoint = implementation.get("entrypoint")
expected_module = expected_skill.implementation_module
expected_entrypoint = expected_skill.implementation_entrypoint
contract_ok = (
module_name == expected_module
and entrypoint == expected_entrypoint
and implementation.get("mode") == "deterministic-read-only-audit-or-prepare"
and implementation.get("result_schema") == "aureon.website-capability-result.v1"
and implementation.get("side_effects_allowed") is False
and implementation.get("deployment_authority") == "none"
)
implementation_contracts_ok = implementation_contracts_ok and contract_ok
if isinstance(module_name, str) and isinstance(entrypoint, str):
binding = f"{module_name}:{entrypoint}"
seen_implementations.append(binding)
implementations_importable = (
implementations_importable
and module_name == expected_module
and entrypoint == expected_entrypoint
and _implementation_is_importable(expected_module, expected_entrypoint)
)
else:
implementations_importable = False
else:
implementation_contracts_ok = False
implementations_importable = False
expected_ids = set(REQUIRED_SKILL_IDS)
checks.extend(
[
_check(
"required-skills",
rows_ok
and len(seen_ids) == len(set(seen_ids))
and set(seen_ids) == expected_ids
and tuple(seen_ids) == REQUIRED_SKILL_IDS,
"Every canonical required skill must appear exactly once.",
),
_check(
"single-accountable-owner",
single_owner_ok,
"Every skill must name exactly one canonical owner_agent scalar.",
),
_check(
"versioned-contracts",
versions_ok
and contracts_ok
and len(seen_contracts) == len(set(seen_contracts)) == len(REQUIRED_SKILL_IDS),
"Every skill must have a semantic version and one unique non-empty evidence contract.",
),
_check(
"evidence-paths",
evidence_ok and len(seen_paths) == len(set(seen_paths)) == len(REQUIRED_SKILL_IDS),
"Every skill must have one unique safe path below the capability-evidence root.",
),
_check(
"hnc-stage-coverage",
stages_ok and covered_stages == set(HNC_STAGES),
"The registered skills must cover every mandatory HNC loop stage.",
),
_check(
"deploy-capability-separation",
deploy_stage_skills == {"homepl_deploy_cache_ssl_readback"},
"Only the Home.pl deployment skill may implement Deploy; authority still comes only from AuthorityGate.",
),
_check(
"implementation-contracts",
implementation_contracts_ok
and len(seen_implementations) == len(set(seen_implementations)) == len(REQUIRED_SKILL_IDS),
"Every skill must bind exactly once to its canonical read-only implementation contract.",
),
_check(
"implementations-importable",
implementations_importable,
"Every canonical implementation module and entrypoint must import and resolve without rebinding.",
),
]
)
passed = all(bool(check["passed"]) for check in checks)
return {
"schema": VERIFICATION_SCHEMA,
"passed": passed,
"state": "pass" if passed else "fail",
"release_eligible": False,
"deployment_authority": "none",
"checks": checks,
}
def require_valid_website_design_capability_set(
registry: Mapping[str, Any] | None = None,
) -> dict[str, object]:
"""Return a valid registry or raise without creating any external effect."""
candidate = dict(registry) if registry is not None else discover_website_design_capability_set()
verification = validate_website_design_capability_set(candidate)
if not verification["passed"]:
raw_checks = verification.get("checks")
failed = (
[str(check["id"]) for check in raw_checks if not check["passed"]]
if isinstance(raw_checks, list)
else ["verification-shape"]
)
raise WebsiteDesignCapabilitySetError("Invalid website/design capability set: " + ", ".join(failed))
return candidate
def main(argv: Sequence[str] | None = None) -> int:
"""Print the registry or its read-only verification as JSON."""
parser = argparse.ArgumentParser(
prog="aureon-website-design-capabilities",
description="Inspect Aureon's read-only website/design capability contracts.",
)
parser.add_argument(
"--validate",
action="store_true",
help="Print verification instead of the registry.",
)
args = parser.parse_args(argv)
payload = (
validate_website_design_capability_set()
if args.validate
else discover_website_design_capability_set()
)
print(json.dumps(payload, indent=2, sort_keys=True))
return 0 if not args.validate or payload["passed"] else 1
if __name__ == "__main__": # pragma: no cover - exercised through the public functions
raise SystemExit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417{ "schema": "aureon.website-operator.config.v1", "site": { "root": "website", "base_url": "https://aureonzorzatechnologies.pl/", "capacity_receipt": "data/website_operator/homepl-capacity-20260726.json", "canonical_overrides": { "downloads/index.html": "https://aureonzorzatechnologies.pl/publications/" }, "critical_routes": [ "index.html", "about/index.html", "projects/index.html", "research/index.html", "research/journal/index.html", "diligence/index.html", "funding/index.html", "funding/investor-deck/index.html", "publications/index.html", "community/index.html", "contact/index.html", "live/index.html", "updates/index.html", "vision/index.html" ] }, "ethos": { "principles": [ "One shared evidence-and-control core may support multiple mission-specific applications.", "Research is a proving ground for evidence discipline, not a shortcut to validation.", "Claim state, source provenance, boundaries, next proof and human authority stay visible.", "Submissions, acknowledgements, discussions, partners, customers, awards and investment are distinct states.", "The public website is read-only and never exposes operator, credential, grant, trading or client controls." ], "required_site_signals": [ { "id": "evidence", "pattern": "\\bevidence\\b", "severity": "error", "message": "Critical routes do not collectively establish Aureon's evidence-led operating model." }, { "id": "research", "pattern": "\\bresearch\\b", "severity": "error", "message": "Critical routes do not collectively establish the research proving ground." }, { "id": "human-authority", "pattern": "\\bhuman (?:authority|review|approval|gate)\\b", "severity": "error", "message": "Critical routes do not make retained human authority visible." }, { "id": "boundary", "pattern": "\\b(?:boundary|not an? (?:award|partner|customer|deployment|validation)|outcome pending)\\b", "severity": "error", "message": "Critical routes do not expose evidence or claim boundaries." } ], "prohibited_claim_patterns": [ { "id": "guaranteed-outcome", "pattern": "\\bguaranteed (?:result|results|return|returns|outcome|outcomes|success)\\b", "severity": "error", "message": "Guaranteed outcomes require removal; the site must state bounded evidence." }, { "id": "proven-traction", "pattern": "\\bproven (?:revenue|market traction|customer traction|commercial traction)\\b", "severity": "error", "message": "Commercial proof may be claimed only from an attributable controlled record." }, { "id": "unbounded-autonomy", "pattern": "\\bfully autonomous\\b", "severity": "error", "message": "The public site must not imply unbounded autonomous authority." }, { "id": "unsupported-superlative", "pattern": "\\b(?:industry-leading|world-leading|best-in-class)\\b", "severity": "warning", "message": "Marketing superlatives require an attributable comparison or should be replaced." } ], "claim_inputs": [ { "path": "website/data/blades.json", "schema": "aureon-sector-blades-v1", "required": true }, { "path": "website/data/research-catalogue.json", "required": true }, { "path": "website/data/funding-status.json", "required": true }, { "path": "website/data/operator-evidence.json", "required": true } ] }, "budgets": { "policy": "Performance and media budgets are independent of provider storage capacity.", "site_total_bytes": 52428800, "site_file_count": 2000, "critical_page_direct_bytes": 2621440, "per_file_bytes": { ".html": 262144, ".css": 393216, ".js": 393216, ".json": 524288, ".png": 2621440, ".jpg": 524288, ".jpeg": 524288, ".webp": 524288, ".svg": 262144, ".woff": 131072, ".woff2": 131072, ".xml": 262144 } }, "checks": { "require_reduced_motion": true, "external": [ { "id": "javascript-syntax", "enabled": true, "required": true, "command": [ "node", "--check", "{site_root}/script.js" ] }, { "id": "v28-design-system", "enabled": true, "required": true, "command": [ "node", "{repo_root}/tools/aureon_website_design_audit_v28.js" ] }, { "id": "v28-metadata-ethos", "enabled": true, "required": true, "command": [ "node", "{repo_root}/tools/aureon_metadata_ethos_audit_v28.js" ] }, { "id": "v28-composite-visual-release-gate", "enabled": true, "required": true, "command": [ "node", "{repo_root}/tools/aureon_visual_release_gate_v28.js", "--repo-root", "{repo_root}", "--manifest", "{repo_root}/docs/audits/AUREON_VISUAL_RELEASE_GATE_20260726T181742Z_V28.manifest.json" ] } ] }, "design": { "policy": "Use Harmonic Nexus only as a bounded evidence-coherence feedback structure. Objective accessibility, performance, browser, claims and release gates retain authority.", "minimum_score": 85, "competitor_source_target": 8, "competitor_max_age_days": 45, "nexus_weights": { "source_strength": 0.3, "coherence": 0.25, "repeatability": 0.2, "feasibility": 0.15, "contradiction_control": 0.1 }, "viewport_matrix": [ "360x800", "390x844", "768x1024", "1280x800", "1440x1000", "1920x1080" ], "competitor_sources": [ { "id": "credo-ai-product", "name": "Credo AI", "url": "https://www.credo.ai/product", "checked_at": "2026-07-26T09:00:00Z", "patterns": [ "dark institutional stage", "product-as-instrument framing", "demo and metric proof" ] }, { "id": "ibm-watsonx-governance", "name": "IBM watsonx.governance", "url": "https://www.ibm.com/products/watsonx-governance/model-governance", "checked_at": "2026-07-26T09:00:00Z", "patterns": [ "enterprise restraint", "factsheets and documentation", "clear buyer pathways" ] }, { "id": "collibra-ai-governance", "name": "Collibra AI Governance", "url": "https://productresources.collibra.com/docs/collibra/latest/Content/AIGovernance/co_ai-gov-product-pages.htm", "checked_at": "2026-07-26T09:00:00Z", "patterns": [ "centred proposition", "product-screen proof", "governance taxonomy" ] }, { "id": "databricks-unity-catalog", "name": "Databricks Unity Catalog", "url": "https://docs.databricks.com/aws/en/data-governance/unity-catalog/", "checked_at": "2026-07-26T09:00:00Z", "patterns": [ "strong information architecture", "tabs and progressive disclosure", "documentation-led trust" ] }, { "id": "monitaur-platform", "name": "Monitaur", "url": "https://www.monitaur.ai/platform", "checked_at": "2026-07-26T09:00:00Z", "patterns": [ "define-manage-automate narrative", "clear operating sequence", "buyer-oriented platform framing" ] }, { "id": "arize-phoenix", "name": "Arize Phoenix", "url": "https://arize.com/docs/phoenix", "checked_at": "2026-07-26T09:00:00Z", "patterns": [ "technical openness", "selectors and metrics", "trust through inspectability" ] }, { "id": "researchspace-eln", "name": "ResearchSpace", "url": "https://www.researchspace.com/eln", "checked_at": "2026-07-26T09:00:00Z", "patterns": [ "institutional research authority", "workflow clarity", "research evidence framing" ] }, { "id": "benchling-platform", "name": "Benchling", "url": "https://www.benchling.com/platform", "checked_at": "2026-07-26T09:00:00Z", "patterns": [ "calm scientific authority", "disciplined platform taxonomy", "credible proof and use-case separation" ] } ] }, "packaging": { "command": [ "powershell", "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", "{repo_root}/tools/build-homepl-v28-narrow-release.ps1", "-WebsiteRoot", "{site_root}", "-OutputDirectory", "{output_directory}", "-Release", "V29" ], "receipt_glob": "aureon-homepl-v29-*-receipt.json", "required_release_paths": [ "index.html", "about/index.html", "projects/index.html", "research/index.html", "research/journal/index.html", "diligence/index.html", "funding/index.html", "funding/investor-deck/index.html", "publications/index.html", "community/index.html", "contact/index.html", "live/index.html", "updates/index.html", "vision/index.html", "downloads/index.html", "script.js", "styles.css", "tokens.css", "data/blades.json" ], "blocked_file_names": [ ".env", ".env1", "id_rsa", "id_ed25519" ], "blocked_extensions": [ ".env", ".key", ".pem", ".pfx", ".p12" ], "allowed_file_names": [ ".htaccess" ], "allowed_extensions": [ ".css", ".gif", ".html", ".ico", ".jpeg", ".jpg", ".js", ".json", ".png", ".svg", ".txt", ".webmanifest", ".webp", ".woff", ".woff2", ".xml" ], "secret_patterns": [ "-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----", "\\bsk-[A-Za-z0-9_-]{20,}\\b", "\\bAIza[0-9A-Za-z_-]{20,}\\b", "\\b(?:password|passwd)\\s*[:=]\\s*[\"'][^\"']{8,}[\"']" ] }, "deployment": { "remote_root": "/", "backup_script": "website/backup-homepl-ftps.ps1", "publish_script": "website/publish-homepl-ftps.ps1", "readback_script": "tools/aureon_homepl_manifest_readback.ps1", "publish_command": [ "powershell", "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", "{repo_root}/website/publish-homepl-ftps.ps1", "-PackagePath", "{package}", "-ManifestPath", "{manifest}", "-WebsiteRoot", "{site_root}", "-RemoteRoot", "{remote_root}" ], "readback_command": [ "powershell", "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", "{repo_root}/tools/aureon_homepl_manifest_readback.ps1", "-ManifestPath", "{manifest}", "-SourceRoot", "{site_root}", "-PackagePath", "{package}", "-OutputPath", "{output}", "-BaseUrl", "{base_url}" ], "credential_env_names": [ "HOMEPL_FTPS_HOST", "HOMEPL_FTPS_USER", "HOMEPL_FTPS_PASSWORD" ], "required_backup_paths": [ "index.html", "styles.css", "script.js" ], "audit_max_age_hours": 12, "backup_max_age_hours": 24, "approval_max_age_hours": 4, "automatic_rollback": false, "credentials_in_receipts": false }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://aureonzorzatechnologies.pl/schemas/website-operator-config-v1.json",
"title": "Aureon Website Operator configuration",
"type": "object",
"additionalProperties": false,
"required": [
"schema",
"site",
"ethos",
"budgets",
"checks",
"packaging",
"deployment"
],
"properties": {
"schema": {
"const": "aureon.website-operator.config.v1"
},
"site": {
"type": "object",
"required": [
"root",
"base_url",
"critical_routes"
],
"properties": {
"root": {
"$ref": "#/$defs/relativePath"
},
"base_url": {
"type": "string",
"format": "uri",
"pattern": "^https://"
},
"capacity_receipt": {
"$ref": "#/$defs/relativePath"
},
"canonical_overrides": {
"type": "object",
"additionalProperties": {
"type": "string",
"format": "uri",
"pattern": "^https://"
}
},
"critical_routes": {
"type": "array",
"minItems": 1,
"uniqueItems": true,
"items": {
"$ref": "#/$defs/relativePath"
}
}
}
},
"ethos": {
"type": "object",
"required": [
"principles",
"required_site_signals",
"prohibited_claim_patterns",
"claim_inputs"
]
},
"budgets": {
"type": "object",
"required": [
"site_total_bytes",
"site_file_count",
"critical_page_direct_bytes",
"per_file_bytes"
],
"properties": {
"site_total_bytes": {
"type": "integer",
"minimum": 1
},
"site_file_count": {
"type": "integer",
"minimum": 1
},
"critical_page_direct_bytes": {
"type": "integer",
"minimum": 1
},
"per_file_bytes": {
"type": "object",
"additionalProperties": {
"type": "integer",
"minimum": 1
}
}
}
},
"checks": {
"type": "object"
},
"design": {
"type": "object",
"additionalProperties": false,
"required": [
"policy",
"minimum_score",
"competitor_source_target",
"competitor_max_age_days",
"nexus_weights",
"viewport_matrix",
"competitor_sources"
],
"properties": {
"policy": {
"type": "string",
"minLength": 1
},
"minimum_score": {
"type": "number",
"minimum": 0,
"maximum": 100
},
"competitor_source_target": {
"type": "integer",
"minimum": 1
},
"competitor_max_age_days": {
"type": "integer",
"minimum": 1
},
"nexus_weights": {
"type": "object",
"additionalProperties": false,
"required": [
"source_strength",
"coherence",
"repeatability",
"feasibility",
"contradiction_control"
],
"properties": {
"source_strength": {"type": "number", "minimum": 0},
"coherence": {"type": "number", "minimum": 0},
"repeatability": {"type": "number", "minimum": 0},
"feasibility": {"type": "number", "minimum": 0},
"contradiction_control": {"type": "number", "minimum": 0}
}
},
"viewport_matrix": {
"type": "array",
"minItems": 1,
"uniqueItems": true,
"items": {
"type": "string",
"pattern": "^[1-9][0-9]*x[1-9][0-9]*$"
}
},
"competitor_sources": {
"type": "array",
"minItems": 1,
"items": {
"type": "object",
"additionalProperties": false,
"required": ["id", "name", "url", "checked_at", "patterns"],
"properties": {
"id": {"type": "string", "minLength": 1},
"name": {"type": "string", "minLength": 1},
"url": {"type": "string", "format": "uri", "pattern": "^https://"},
"checked_at": {"type": "string", "format": "date-time"},
"patterns": {
"type": "array",
"minItems": 1,
"items": {"type": "string", "minLength": 1}
}
}
}
}
}
},
"packaging": {
"type": "object",
"required": [
"command",
"receipt_glob",
"required_release_paths",
"blocked_file_names",
"blocked_extensions",
"allowed_file_names",
"allowed_extensions"
]
},
"deployment": {
"type": "object",
"required": [
"remote_root",
"backup_script",
"publish_script",
"readback_script",
"publish_command",
"readback_command",
"credential_env_names",
"required_backup_paths",
"audit_max_age_hours",
"backup_max_age_hours",
"approval_max_age_hours",
"automatic_rollback",
"credentials_in_receipts"
],
"properties": {
"remote_root": {
"const": "/"
},
"automatic_rollback": {
"const": false
},
"credentials_in_receipts": {
"const": false
}
}
}
},
"$defs": {
"relativePath": {
"type": "string",
"minLength": 1,
"pattern": "^(?![A-Za-z]:)(?!/)(?!.*(?:^|/)\\.\\.(?:/|$)).+$"
}
}
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://aureonzorzatechnologies.pl/schemas/website-operator-receipts-v1.json",
"title": "Aureon Website Operator external receipts",
"oneOf": [
{
"$ref": "#/$defs/ownerApproval"
},
{
"$ref": "#/$defs/hostingCapacity"
}
],
"$defs": {
"sha256": {
"type": "string",
"pattern": "^[A-Fa-f0-9]{64}$"
},
"ownerApproval": {
"type": "object",
"additionalProperties": false,
"required": [
"schema",
"decision",
"scope",
"package_sha256",
"approved_at",
"expires_at",
"approved_by"
],
"properties": {
"schema": {
"const": "aureon.website-operator.owner-approval.v1"
},
"decision": {
"const": "approved"
},
"scope": {
"const": "static-website-release"
},
"package_sha256": {
"$ref": "#/$defs/sha256"
},
"approved_at": {
"type": "string",
"format": "date-time"
},
"expires_at": {
"type": "string",
"format": "date-time"
},
"approved_by": {
"type": "string",
"minLength": 1
},
"note": {
"type": "string"
}
}
},
"hostingCapacity": {
"type": "object",
"required": [
"schema",
"observed_on",
"source",
"plan",
"provider_display",
"policy"
],
"properties": {
"schema": {
"const": "aureon.website-operator.hosting-capacity.v1"
},
"observed_on": {
"type": "string",
"format": "date"
},
"source": {
"const": "authenticated-owner-panel"
},
"policy": {
"const": "capacity-is-context-not-budget"
}
}
}
}
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938"""Verify static website runtime measurement integrity without producing it.
The verifier authenticates one pre-existing measurement document, replays thecomplete ``website/`` file manifest, and checks two independently stored butbyte-identical derivative replicas. Image media type and dimensions come fromPNG, JPEG, or WebP headers rather than filenames or declarations. Headerinspection is not a full decode, and byte copies placed under a different runremain copyable static artifacts rather than independently produced evidence.
This module has no encoder, subprocess, writer, emitter, candidate, package,release, deployment, network, or credential capability. A passing result isdeliberately production-blocked and is not eligible for proposal compilation.The isolated launcher binds exact supplied source hashes, but reviewed pinsremain external governance inputs and are not established by this module."""
from __future__ import annotations
import argparseimport hashlibimport jsonimport osimport reimport statimport sysimport unicodedatafrom collections.abc import Mapping, Sequencefrom copy import deepcopyfrom datetime import UTC, datetime, timedeltafrom pathlib import Path, PurePosixPathfrom types import MappingProxyTypefrom typing import Any, Final
MEASUREMENT_SCHEMA = "aureon.website-runtime-measurement-static-integrity.v1"VERIFIED_STATE = "static-integrity-verified-production-blocked"VERIFICATION_MODE = "static-artifact-integrity-only"SOURCE_ROOT = Path("website")IMPLEMENTATION_PATH = Path("aureon/operator/website_runtime_measurement_provenance.py")TRUSTED_LAUNCHER_PATH = Path("tools/run-website-runtime-measurement-provenance.py")REPLICA_ROOT = PurePosixPath( "artifacts/website-operator/runtime-optimisations/measurement-provenance/replicas")MEASUREMENT_ROOT = PurePosixPath("artifacts/website-operator/runtime-optimisations/measurements")
MAX_JSON_BYTES = 8 * 1024 * 1024MAX_REVIEWED_SOURCE_BYTES = 2 * 1024 * 1024MAX_FILE_BYTES = 512 * 1024 * 1024MAX_TREE_BYTES = 512 * 1024 * 1024MAX_FILES = 5_000MAX_TRANSFORMATIONS = 5_000MAX_DIMENSION = 20_000MAX_PIXELS = 400_000_000MAX_CLOCK_SKEW = timedelta(minutes=5)
NO_AUTHORITY: Final[Mapping[str, object]] = MappingProxyType( { "scope": "read-only static artifact integrity verification only", "source_selection_authority": "none", "measurement_creation_authority": "none", "canonical_website_mutation": "none", "physical_source_file_removal": "none", "encoding_execution": "none", "css_transformation_execution": "none", "reference_mutation": "none", "candidate_authority": "none", "staging_authority": "none", "package_authority": "none", "release_eligible": False, "deployment_authority": "none", "network_access": "none", "credential_access": "none", })
_SHA256 = re.compile(r"[A-F0-9]{64}\Z")_SAFE_ID = re.compile(r"[a-z0-9][a-z0-9._-]{2,80}\Z")_UTC_DATE_TIME = re.compile(r"[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(?:\.[0-9]{1,6})?Z\Z")_MEDIA_TYPES = frozenset({"image/png", "image/jpeg", "image/webp"})_MEDIA_SUFFIXES: Final[Mapping[str, frozenset[str]]] = { "image/png": frozenset({".png"}), "image/jpeg": frozenset({".jpg", ".jpeg"}), "image/webp": frozenset({".webp"}),}_TOP_FIELDS = frozenset( { "schema", "observed_at", "run_id", "state", "mode", "source_manifest", "transformations", "summary", "eligible_for_proposal_compilation", "authority", "payload_sha256", })_MANIFEST_FIELDS = frozenset({"root", "file_count", "total_bytes", "manifest_sha256", "tree_sha256", "files"})_FILE_FIELDS = frozenset({"path", "bytes", "sha256"})_TRANSFORMATION_FIELDS = frozenset( { "id", "source_path", "source_sha256", "source_bytes", "source_media_type", "source_width", "source_height", "projected_runtime_path", "projected_sha256", "projected_bytes", "projected_media_type", "projected_width", "projected_height", "expected_saving_bytes", "replicas", "source_master_preserved", "execution_state", })_REPLICA_FIELDS = frozenset({"role", "path", "file_sha256", "bytes", "media_type", "width", "height"})_SUMMARY_FIELDS = frozenset( { "transformation_count", "source_bytes", "projected_bytes", "expected_saving_bytes", "replica_bytes", })
class WebsiteRuntimeMeasurementProvenanceError(ValueError): """The static measurement evidence or one of its bound files is unsafe."""
def _canonical_json_bytes(value: object) -> bytes: try: return json.dumps( value, sort_keys=True, separators=(",", ":"), ensure_ascii=False, allow_nan=False, ).encode("utf-8") except (TypeError, ValueError) as exc: raise WebsiteRuntimeMeasurementProvenanceError("Value is not canonical JSON.") from exc
def _json_sha256(value: object) -> str: return hashlib.sha256(_canonical_json_bytes(value)).hexdigest().upper()
def _bytes_sha256(value: bytes) -> str: return hashlib.sha256(value).hexdigest().upper()
def _expect_fields(value: object, expected: frozenset[str], *, label: str) -> Mapping[str, Any]: if not isinstance(value, Mapping) or set(value) != expected: raise WebsiteRuntimeMeasurementProvenanceError(f"{label} must contain exactly its defined fields.") if any(not isinstance(key, str) for key in value): raise WebsiteRuntimeMeasurementProvenanceError(f"{label} field names must be strings.") return value
def _string(value: object, *, label: str) -> str: if not isinstance(value, str): raise WebsiteRuntimeMeasurementProvenanceError(f"{label} must be a string.") return value
def _integer(value: object, *, label: str, minimum: int = 0, maximum: int = MAX_FILE_BYTES) -> int: if isinstance(value, bool) or not isinstance(value, int) or not minimum <= value <= maximum: raise WebsiteRuntimeMeasurementProvenanceError(f"{label} is outside its integer bound.") return value
def _sha256(value: object, *, label: str) -> str: result = _string(value, label=label) if _SHA256.fullmatch(result) is None: raise WebsiteRuntimeMeasurementProvenanceError(f"{label} must be 64 uppercase hexadecimal digits.") return result
def _safe_id(value: object, *, label: str) -> str: result = _string(value, label=label) if _SAFE_ID.fullmatch(result) is None: raise WebsiteRuntimeMeasurementProvenanceError(f"{label} is not a safe identifier.") return result
def _safe_relative(value: object, *, label: str) -> PurePosixPath: raw = _string(value, label=label) path = PurePosixPath(raw) if ( not raw or "\\" in raw or "\x00" in raw or raw.startswith("/") or raw.endswith("/") or "//" in raw or path.is_absolute() or any(part in {"", ".", ".."} for part in path.parts) or path.as_posix() != raw ): raise WebsiteRuntimeMeasurementProvenanceError(f"{label} is not a safe relative POSIX path.") for part in path.parts: if ( unicodedata.normalize("NFC", part) != part or part.endswith((" ", ".")) or any(ord(character) < 32 or character in '<>:"|?*' for character in part) ): raise WebsiteRuntimeMeasurementProvenanceError( f"{label} contains a non-portable or alias-prone path component." ) return path
def _is_link_or_reparse(path: Path) -> bool: details = path.lstat() attributes = int(getattr(details, "st_file_attributes", 0) or 0) reparse = int(getattr(stat, "FILE_ATTRIBUTE_REPARSE_POINT", 0x400) or 0x400) return stat.S_ISLNK(details.st_mode) or bool(attributes & reparse)
def _same_identity(left: os.stat_result, right: os.stat_result) -> bool: return ( stat.S_IFMT(left.st_mode) == stat.S_IFMT(right.st_mode) and int(left.st_dev) == int(right.st_dev) and int(left.st_ino) == int(right.st_ino) )
def _repo_root(value: Path) -> Path: root = Path(os.path.abspath(value)) for component in (root, *root.parents): if (component.exists() or component.is_symlink()) and _is_link_or_reparse(component): raise WebsiteRuntimeMeasurementProvenanceError( "Repository root may not cross a link or reparse point." ) if not root.is_dir(): raise WebsiteRuntimeMeasurementProvenanceError( "Repository root must be an ordinary, non-reparse directory." ) return root
def _joined_path(root: Path, relative: PurePosixPath, *, label: str) -> Path: target = root.joinpath(*relative.parts) current = root for part in relative.parts: current /= part if (current.exists() or current.is_symlink()) and _is_link_or_reparse(current): raise WebsiteRuntimeMeasurementProvenanceError(f"{label} may not cross a link or reparse point.") try: common = os.path.commonpath((str(root), str(target))) except ValueError as exc: raise WebsiteRuntimeMeasurementProvenanceError(f"{label} escapes the repository.") from exc if os.path.normcase(common) != os.path.normcase(str(root)): raise WebsiteRuntimeMeasurementProvenanceError(f"{label} escapes the repository.") return target
def _read_ordinary_file( path: Path, *, label: str, maximum_bytes: int = MAX_FILE_BYTES, expected_sha256: str | None = None, expected_bytes: int | None = None,) -> bytes: if not path.is_file() or _is_link_or_reparse(path): raise WebsiteRuntimeMeasurementProvenanceError(f"{label} must be an ordinary file.") before = path.lstat() if not stat.S_ISREG(before.st_mode) or int(before.st_nlink) != 1: raise WebsiteRuntimeMeasurementProvenanceError(f"{label} must be an ordinary single-link file.") size = int(before.st_size) if size > maximum_bytes or (expected_bytes is not None and size != expected_bytes): raise WebsiteRuntimeMeasurementProvenanceError(f"{label} byte count does not match its binding.") with path.open("rb") as stream: opened = os.fstat(stream.fileno()) if not _same_identity(before, opened): raise WebsiteRuntimeMeasurementProvenanceError(f"{label} changed before its handle opened.") payload = stream.read(maximum_bytes + 1) after = path.lstat() if ( len(payload) > maximum_bytes or len(payload) != size or not _same_identity(opened, after) or int(after.st_nlink) != 1 ): raise WebsiteRuntimeMeasurementProvenanceError(f"{label} changed while it was read.") if expected_sha256 is not None and _bytes_sha256(payload) != expected_sha256: raise WebsiteRuntimeMeasurementProvenanceError(f"{label} SHA-256 does not match its binding.") return payload
def _reject_constant(value: str) -> object: raise WebsiteRuntimeMeasurementProvenanceError(f"JSON constant {value!r} is not permitted.")
def _pairs_object(pairs: list[tuple[str, Any]]) -> dict[str, Any]: result: dict[str, Any] = {} for key, value in pairs: if key in result: raise WebsiteRuntimeMeasurementProvenanceError(f"Duplicate JSON field {key!r} is not permitted.") result[key] = value return result
def _load_json(payload: bytes, *, label: str) -> dict[str, Any]: if payload.startswith(b"\xef\xbb\xbf"): raise WebsiteRuntimeMeasurementProvenanceError(f"{label} may not contain a UTF-8 BOM.") try: text = payload.decode("utf-8", errors="strict") value = json.loads(text, object_pairs_hook=_pairs_object, parse_constant=_reject_constant) except (UnicodeDecodeError, json.JSONDecodeError) as exc: raise WebsiteRuntimeMeasurementProvenanceError(f"{label} is not strict UTF-8 JSON.") from exc if not isinstance(value, dict): raise WebsiteRuntimeMeasurementProvenanceError(f"{label} must be a JSON object.") return value
def _manifest_row(relative: str, payload: bytes) -> dict[str, object]: return {"path": relative, "bytes": len(payload), "sha256": _bytes_sha256(payload)}
def _snapshot_website(root: Path) -> dict[str, object]: website = _joined_path(root, PurePosixPath(SOURCE_ROOT.as_posix()), label="Website root") if not website.is_dir() or _is_link_or_reparse(website): raise WebsiteRuntimeMeasurementProvenanceError( "Website source root must be an ordinary, non-reparse directory." ) pending: list[tuple[Path, PurePosixPath]] = [(website, PurePosixPath("."))] rows: list[dict[str, object]] = [] portable_paths: set[str] = set() total = 0 while pending: directory, relative_directory = pending.pop() try: entries = sorted(os.scandir(directory), key=lambda item: item.name) except OSError as exc: raise WebsiteRuntimeMeasurementProvenanceError("Website source tree cannot be scanned.") from exc for entry in entries: entry_path = Path(entry.path) relative = ( PurePosixPath(entry.name) if relative_directory == PurePosixPath(".") else relative_directory / entry.name ) _safe_relative(relative.as_posix(), label="Website source tree path") portable = unicodedata.normalize("NFC", relative.as_posix()).casefold() if portable in portable_paths: raise WebsiteRuntimeMeasurementProvenanceError( "Website source tree contains a portable case-fold path collision." ) portable_paths.add(portable) details = entry_path.lstat() attributes = int(getattr(details, "st_file_attributes", 0) or 0) if entry.is_symlink() or bool( attributes & int(getattr(stat, "FILE_ATTRIBUTE_REPARSE_POINT", 0x400) or 0x400) ): raise WebsiteRuntimeMeasurementProvenanceError( "Website source tree may not contain links or reparse points." ) if stat.S_ISDIR(details.st_mode): pending.append((entry_path, relative)) continue if not stat.S_ISREG(details.st_mode) or int(details.st_nlink) != 1: raise WebsiteRuntimeMeasurementProvenanceError( "Website source tree may contain only ordinary single-link files." ) if len(rows) >= MAX_FILES or int(details.st_size) > MAX_TREE_BYTES - total: raise WebsiteRuntimeMeasurementProvenanceError( "Website source tree exceeds its fixed bounds." ) payload = _read_ordinary_file( entry_path, label=f"Website source file {relative.as_posix()}", maximum_bytes=MAX_TREE_BYTES - total, ) total += len(payload) rows.append(_manifest_row(relative.as_posix(), payload)) rows.sort(key=lambda row: str(row["path"])) digest = _json_sha256(rows) return { "root": SOURCE_ROOT.as_posix(), "file_count": len(rows), "total_bytes": total, "manifest_sha256": digest, "tree_sha256": digest, "files": rows, }
def _dimension(value: object, *, label: str) -> int: return _integer(value, label=label, minimum=1, maximum=MAX_DIMENSION)
def _validate_dimensions(width: int, height: int, *, label: str) -> None: if width * height > MAX_PIXELS: raise WebsiteRuntimeMeasurementProvenanceError(f"{label} pixel count exceeds its bound.")
def _png_probe(payload: bytes) -> tuple[str, int, int]: if ( len(payload) < 24 or payload[:8] != b"\x89PNG\r\n\x1a\n" or payload[12:16] != b"IHDR" or int.from_bytes(payload[8:12], "big") != 13 ): raise WebsiteRuntimeMeasurementProvenanceError("PNG header is invalid or incomplete.") return "image/png", int.from_bytes(payload[16:20], "big"), int.from_bytes(payload[20:24], "big")
def _jpeg_probe(payload: bytes) -> tuple[str, int, int]: if len(payload) < 4 or payload[:2] != b"\xff\xd8": raise WebsiteRuntimeMeasurementProvenanceError("JPEG header is invalid or incomplete.") position = 2 start_of_frame = frozenset({0xC0, 0xC1, 0xC2, 0xC3, 0xC5, 0xC6, 0xC7, 0xC9, 0xCA, 0xCB, 0xCD, 0xCE, 0xCF}) while position < len(payload): if payload[position] != 0xFF: break while position < len(payload) and payload[position] == 0xFF: position += 1 if position >= len(payload): break marker = payload[position] position += 1 if marker == 0xDA: break if marker in {0x01, *range(0xD0, 0xD9)}: continue if position + 2 > len(payload): break segment_length = int.from_bytes(payload[position : position + 2], "big") if segment_length < 2 or position + segment_length > len(payload): break if marker in start_of_frame: if segment_length < 7: break height = int.from_bytes(payload[position + 3 : position + 5], "big") width = int.from_bytes(payload[position + 5 : position + 7], "big") return "image/jpeg", width, height position += segment_length raise WebsiteRuntimeMeasurementProvenanceError("JPEG dimensions are absent from its header.")
def _webp_probe(payload: bytes) -> tuple[str, int, int]: if ( len(payload) < 30 or payload[:4] != b"RIFF" or payload[8:12] != b"WEBP" or int.from_bytes(payload[4:8], "little") + 8 != len(payload) ): raise WebsiteRuntimeMeasurementProvenanceError("WebP header is invalid or incomplete.") kind = payload[12:16] chunk_size = int.from_bytes(payload[16:20], "little") if 20 + chunk_size > len(payload): raise WebsiteRuntimeMeasurementProvenanceError("WebP chunk exceeds its file bound.") if kind == b"VP8X" and chunk_size >= 10: width = 1 + int.from_bytes(payload[24:27], "little") height = 1 + int.from_bytes(payload[27:30], "little") elif kind == b"VP8 " and chunk_size >= 10 and payload[23:26] == b"\x9d\x01\x2a": width = int.from_bytes(payload[26:28], "little") & 0x3FFF height = int.from_bytes(payload[28:30], "little") & 0x3FFF elif kind == b"VP8L" and chunk_size >= 5 and payload[20] == 0x2F: b1, b2, b3, b4 = payload[21:25] width = 1 + (((b2 & 0x3F) << 8) | b1) height = 1 + (((b4 & 0x0F) << 10) | (b3 << 2) | ((b2 & 0xC0) >> 6)) else: raise WebsiteRuntimeMeasurementProvenanceError("WebP dimensions are absent from its header.") return "image/webp", width, height
def _image_probe(payload: bytes, *, label: str) -> tuple[str, int, int]: try: if payload.startswith(b"\x89PNG"): result = _png_probe(payload) elif payload.startswith(b"\xff\xd8"): result = _jpeg_probe(payload) elif payload.startswith(b"RIFF"): result = _webp_probe(payload) else: raise WebsiteRuntimeMeasurementProvenanceError("unsupported image header") except WebsiteRuntimeMeasurementProvenanceError as exc: raise WebsiteRuntimeMeasurementProvenanceError(f"{label} has no valid PNG/JPEG/WebP header.") from exc _validate_dimensions(result[1], result[2], label=label) return result
def _require_media_path(path: PurePosixPath, media_type: str, *, label: str) -> None: if media_type not in _MEDIA_TYPES or path.suffix.lower() not in _MEDIA_SUFFIXES[media_type]: raise WebsiteRuntimeMeasurementProvenanceError( f"{label} suffix does not match its header-derived media type." )
def _require_declared_manifest(value: object, actual: Mapping[str, object]) -> list[Mapping[str, Any]]: manifest = _expect_fields(value, _MANIFEST_FIELDS, label="source_manifest") if manifest["root"] != SOURCE_ROOT.as_posix(): raise WebsiteRuntimeMeasurementProvenanceError("source_manifest.root must be website.") files = manifest["files"] if not isinstance(files, list) or len(files) > MAX_FILES: raise WebsiteRuntimeMeasurementProvenanceError("source_manifest.files exceeds its list bound.") checked: list[Mapping[str, Any]] = [] previous = "" for index, item in enumerate(files): row = _expect_fields(item, _FILE_FIELDS, label=f"source_manifest.files[{index}]") path = _safe_relative(row["path"], label=f"source_manifest.files[{index}].path").as_posix() if path <= previous: raise WebsiteRuntimeMeasurementProvenanceError( "source_manifest.files must be unique and strictly path-sorted." ) previous = path _integer(row["bytes"], label=f"source_manifest.files[{index}].bytes", maximum=MAX_TREE_BYTES) _sha256(row["sha256"], label=f"source_manifest.files[{index}].sha256") checked.append(row) digest = _json_sha256([dict(row) for row in checked]) if ( _integer(manifest["file_count"], label="source_manifest.file_count", maximum=MAX_FILES) != len(checked) or _integer(manifest["total_bytes"], label="source_manifest.total_bytes", maximum=MAX_TREE_BYTES) != sum(int(row["bytes"]) for row in checked) or _sha256(manifest["manifest_sha256"], label="source_manifest.manifest_sha256") != digest or _sha256(manifest["tree_sha256"], label="source_manifest.tree_sha256") != digest or dict(manifest) != dict(actual) ): raise WebsiteRuntimeMeasurementProvenanceError( "Declared source manifest does not exactly match the complete website tree." ) return checked
def _require_replica( root: Path, value: object, *, role: str, run_id: str, transformation_id: str, index: int,) -> tuple[Mapping[str, Any], bytes, tuple[str, int, int]]: row = _expect_fields(value, _REPLICA_FIELDS, label=f"replicas[{index}]") if row["role"] != role: raise WebsiteRuntimeMeasurementProvenanceError("Replica roles must be replica-a then replica-b.") relative = _safe_relative(row["path"], label=f"replicas[{index}].path") required_prefix = REPLICA_ROOT / run_id / transformation_id / role if relative.parts[: len(required_prefix.parts)] != required_prefix.parts: raise WebsiteRuntimeMeasurementProvenanceError(f"{role} must be stored below its fixed replica root.") expected_hash = _sha256(row["file_sha256"], label=f"replicas[{index}].file_sha256") expected_bytes = _integer(row["bytes"], label=f"replicas[{index}].bytes", minimum=1) payload = _read_ordinary_file( _joined_path(root, relative, label=f"{role} artifact"), label=f"{role} artifact", expected_sha256=expected_hash, expected_bytes=expected_bytes, ) probed = _image_probe(payload, label=f"{role} artifact") media_type = _string(row["media_type"], label=f"replicas[{index}].media_type") width = _dimension(row["width"], label=f"replicas[{index}].width") height = _dimension(row["height"], label=f"replicas[{index}].height") _validate_dimensions(width, height, label=f"replicas[{index}]") _require_media_path(relative, media_type, label=f"replicas[{index}].path") if probed != (media_type, width, height): raise WebsiteRuntimeMeasurementProvenanceError( f"{role} header does not match its media and dimension binding." ) return row, payload, probed
def _require_transformations( root: Path, value: object, manifest_rows: Sequence[Mapping[str, Any]], *, run_id: str,) -> dict[str, int]: if not isinstance(value, list) or not 1 <= len(value) <= MAX_TRANSFORMATIONS: raise WebsiteRuntimeMeasurementProvenanceError("transformations must be a bounded non-empty list.") manifest = {str(row["path"]): row for row in manifest_rows} ids: set[str] = set() source_paths: set[str] = set() projected_paths: set[str] = set() replica_paths: set[str] = set() totals = { "transformation_count": len(value), "source_bytes": 0, "projected_bytes": 0, "expected_saving_bytes": 0, "replica_bytes": 0, } for index, item in enumerate(value): row = _expect_fields(item, _TRANSFORMATION_FIELDS, label=f"transformations[{index}]") transform_id = _safe_id(row["id"], label=f"transformations[{index}].id") source_path = _safe_relative(row["source_path"], label=f"transformations[{index}].source_path") projected_path = _safe_relative( row["projected_runtime_path"], label=f"transformations[{index}].projected_runtime_path", ) if ( transform_id in ids or source_path.as_posix() in source_paths or projected_path.as_posix() in projected_paths ): raise WebsiteRuntimeMeasurementProvenanceError( "Transformation ids, source paths, and projected paths must each be unique." ) ids.add(transform_id) source_paths.add(source_path.as_posix()) projected_paths.add(projected_path.as_posix()) source_manifest_row = manifest.get(source_path.as_posix()) source_hash = _sha256(row["source_sha256"], label=f"transformations[{index}].source_sha256") source_bytes = _integer( row["source_bytes"], label=f"transformations[{index}].source_bytes", minimum=1 ) if source_manifest_row is None or dict(source_manifest_row) != { "path": source_path.as_posix(), "bytes": source_bytes, "sha256": source_hash, }: raise WebsiteRuntimeMeasurementProvenanceError( "Transformation source does not exactly bind one complete-manifest file." ) source_payload = _read_ordinary_file( _joined_path(root / SOURCE_ROOT, source_path, label="Transformation source"), label=f"Transformation source {source_path.as_posix()}", expected_sha256=source_hash, expected_bytes=source_bytes, ) source_probe = _image_probe(source_payload, label="Transformation source") source_media = _string(row["source_media_type"], label=f"transformations[{index}].source_media_type") source_width = _dimension(row["source_width"], label=f"transformations[{index}].source_width") source_height = _dimension(row["source_height"], label=f"transformations[{index}].source_height") _require_media_path(source_path, source_media, label="Transformation source_path") if source_probe != (source_media, source_width, source_height): raise WebsiteRuntimeMeasurementProvenanceError( "Transformation source header does not match its media and dimension binding." ) replicas = row["replicas"] if not isinstance(replicas, list) or len(replicas) != 2: raise WebsiteRuntimeMeasurementProvenanceError( "Every transformation requires exactly two replicas." ) replica_a, payload_a, probe_a = _require_replica( root, replicas[0], role="replica-a", run_id=run_id, transformation_id=transform_id, index=0, ) replica_b, payload_b, probe_b = _require_replica( root, replicas[1], role="replica-b", run_id=run_id, transformation_id=transform_id, index=1, ) paths = {str(replica_a["path"]), str(replica_b["path"])} if len(paths) != 2 or replica_paths.intersection(paths): raise WebsiteRuntimeMeasurementProvenanceError( "Replica artifact paths must be globally distinct." ) replica_paths.update(paths) if payload_a != payload_b or dict(replica_a) | {"role": "replica-a", "path": ""} != dict( replica_b ) | {"role": "replica-a", "path": ""}: raise WebsiteRuntimeMeasurementProvenanceError( "The two replica artifacts and their non-location bindings must be identical." ) projected_hash = _sha256(row["projected_sha256"], label=f"transformations[{index}].projected_sha256") projected_bytes = _integer( row["projected_bytes"], label=f"transformations[{index}].projected_bytes", minimum=1 ) projected_media = _string( row["projected_media_type"], label=f"transformations[{index}].projected_media_type" ) projected_width = _dimension( row["projected_width"], label=f"transformations[{index}].projected_width" ) projected_height = _dimension( row["projected_height"], label=f"transformations[{index}].projected_height" ) _require_media_path(projected_path, projected_media, label="projected_runtime_path") expected_saving = _integer( row["expected_saving_bytes"], label=f"transformations[{index}].expected_saving_bytes", minimum=1, ) if ( projected_hash != str(replica_a["file_sha256"]) or projected_bytes != int(replica_a["bytes"]) or probe_a != probe_b or probe_a != (projected_media, projected_width, projected_height) or (projected_width, projected_height) != (source_width, source_height) or source_bytes - projected_bytes != expected_saving or projected_bytes >= source_bytes or row["source_master_preserved"] is not True or row["execution_state"] != "pre-existing-static-artifacts-only" ): raise WebsiteRuntimeMeasurementProvenanceError( "Transformation integrity, dimensions, arithmetic, or static-only state is invalid." ) totals["source_bytes"] += source_bytes totals["projected_bytes"] += projected_bytes totals["expected_saving_bytes"] += expected_saving totals["replica_bytes"] += projected_bytes * 2 return totals
def require_measurement_provenance( value: object, *, repo_root: Path, source_snapshot: Mapping[str, object] | None = None,) -> dict[str, Any]: """Validate one static-integrity document and every file it binds, without writing.
This compatibility name does not imply producer, invocation, decode, or source-plan provenance. Prefer ``require_static_measurement_integrity``. """
root = _repo_root(repo_root) document = _expect_fields(value, _TOP_FIELDS, label="measurement evidence") if document["schema"] != MEASUREMENT_SCHEMA: raise WebsiteRuntimeMeasurementProvenanceError("Measurement schema is not static-integrity v1.") run_id = _safe_id(document["run_id"], label="run_id") observed_at = _string(document["observed_at"], label="observed_at") if _UTC_DATE_TIME.fullmatch(observed_at) is None: raise WebsiteRuntimeMeasurementProvenanceError( "observed_at must be an exact UTC date-time ending in Z." ) try: observed = datetime.fromisoformat(observed_at.removesuffix("Z") + "+00:00").astimezone(UTC) except ValueError as exc: raise WebsiteRuntimeMeasurementProvenanceError("observed_at is not a valid timestamp.") from exc if observed > datetime.now(UTC) + MAX_CLOCK_SKEW: raise WebsiteRuntimeMeasurementProvenanceError( "observed_at exceeds the maximum five-minute future clock skew." ) # Deliberately local and duplicated: validation must not resolve a # rebindable module-level authority object or constructor. canonical_authority: dict[str, object] = { "scope": "read-only static artifact integrity verification only", "source_selection_authority": "none", "measurement_creation_authority": "none", "canonical_website_mutation": "none", "physical_source_file_removal": "none", "encoding_execution": "none", "css_transformation_execution": "none", "reference_mutation": "none", "candidate_authority": "none", "staging_authority": "none", "package_authority": "none", "release_eligible": False, "deployment_authority": "none", "network_access": "none", "credential_access": "none", } if ( document["state"] != VERIFIED_STATE or document["mode"] != VERIFICATION_MODE or document["eligible_for_proposal_compilation"] is not False or document["authority"] != canonical_authority ): raise WebsiteRuntimeMeasurementProvenanceError( "Measurement state, mode, eligibility, and authority must remain production-blocked." ) expected_payload_hash = _sha256(document["payload_sha256"], label="payload_sha256") payload = dict(document) payload.pop("payload_sha256") if _json_sha256(payload) != expected_payload_hash: raise WebsiteRuntimeMeasurementProvenanceError("Measurement payload SHA-256 is invalid.") first_snapshot = dict(source_snapshot or _snapshot_website(root)) manifest_rows = _require_declared_manifest(document["source_manifest"], first_snapshot) totals = _require_transformations( root, document["transformations"], manifest_rows, run_id=run_id, ) summary = _expect_fields(document["summary"], _SUMMARY_FIELDS, label="summary") checked_summary = { key: _integer( summary[key], label=f"summary.{key}", minimum=1, maximum=(MAX_FILE_BYTES * MAX_TRANSFORMATIONS * 2), ) for key in _SUMMARY_FIELDS } if checked_summary != totals: raise WebsiteRuntimeMeasurementProvenanceError( "Measurement summary does not equal transformation arithmetic." ) second_snapshot = _snapshot_website(root) if first_snapshot != second_snapshot: raise WebsiteRuntimeMeasurementProvenanceError( "Website source manifest changed during static provenance verification." ) return deepcopy(dict(document))
def verify_measurement_provenance_file( *, repo_root: Path, measurement_path: str, expected_measurement_sha256: str,) -> dict[str, Any]: """Authenticate and verify an existing static-integrity file; never create one."""
root = _repo_root(repo_root) relative = _safe_relative(measurement_path, label="measurement_path") if relative.parent != MEASUREMENT_ROOT or not relative.name.endswith( ".measurement-static-integrity.v1.json" ): raise WebsiteRuntimeMeasurementProvenanceError( "Measurement evidence must be one direct controlled-root static-integrity v1 file." ) expected = _sha256(expected_measurement_sha256, label="expected_measurement_sha256") payload = _read_ordinary_file( _joined_path(root, relative, label="Measurement evidence"), label="Measurement evidence", maximum_bytes=MAX_JSON_BYTES, expected_sha256=expected, ) document = _load_json(payload, label="Measurement evidence") validated = require_measurement_provenance(document, repo_root=root) expected_name = f"{validated['run_id']}.measurement-static-integrity.v1.json" if relative.name != expected_name: raise WebsiteRuntimeMeasurementProvenanceError( "Measurement evidence filename must bind its exact run_id." ) return validated
# Preferred public names describe the bounded result. Compatibility aliases# retain the original ingress while production integration remains blocked.require_static_measurement_integrity = require_measurement_provenanceverify_static_measurement_integrity_file = verify_measurement_provenance_file
def _launcher_attestation() -> Mapping[str, object]: value = globals().get("__aureon_runtime_measurement_provenance_launcher_attestation__") expected = { "launcher_path", "launcher_sha256", "module_path", "module_sha256", "repo_root", "isolated", "no_site", "dont_write_bytecode", } if not isinstance(value, Mapping) or set(value) != expected: raise WebsiteRuntimeMeasurementProvenanceError("CLI requires an exact trusted-launcher attestation.") if ( value["isolated"] is not True or value["no_site"] is not True or value["dont_write_bytecode"] is not True or _SHA256.fullmatch(str(value["launcher_sha256"])) is None or _SHA256.fullmatch(str(value["module_sha256"])) is None ): raise WebsiteRuntimeMeasurementProvenanceError("Trusted-launcher attestation is invalid.") root = _repo_root(Path(str(value["repo_root"]))) expected_launcher = _joined_path( root, PurePosixPath(TRUSTED_LAUNCHER_PATH.as_posix()), label="Attested launcher", ) expected_module = _joined_path( root, PurePosixPath(IMPLEMENTATION_PATH.as_posix()), label="Attested module", ) attested_launcher = Path(os.path.abspath(str(value["launcher_path"]))) attested_module = Path(os.path.abspath(str(value["module_path"]))) if os.path.normcase(str(attested_launcher)) != os.path.normcase( str(expected_launcher) ) or os.path.normcase(str(attested_module)) != os.path.normcase(str(expected_module)): raise WebsiteRuntimeMeasurementProvenanceError( "Trusted-launcher attestation does not bind the exact canonical source paths." ) _read_ordinary_file( expected_launcher, label="Attested launcher", maximum_bytes=MAX_REVIEWED_SOURCE_BYTES, expected_sha256=str(value["launcher_sha256"]), ) _read_ordinary_file( expected_module, label="Attested module", maximum_bytes=MAX_REVIEWED_SOURCE_BYTES, expected_sha256=str(value["module_sha256"]), ) # These exact supplied pins establish byte continuity for this invocation. # Whether the pins are reviewed remains an external registry/governance fact. return dict(value)
def build_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser(prog="website-runtime-measurement-provenance") parser.add_argument("--repo-root", required=True) parser.add_argument("--measurement", required=True) parser.add_argument("--expected-measurement-sha256", required=True) return parser
def main(argv: Sequence[str] | None = None) -> int: if not (sys.flags.isolated and sys.flags.no_site and sys.dont_write_bytecode): raise WebsiteRuntimeMeasurementProvenanceError("CLI requires python -I -S -B.") attestation = _launcher_attestation() args = build_parser().parse_args(argv) requested_root = _repo_root(Path(args.repo_root)) attested_root = _repo_root(Path(str(attestation["repo_root"]))) if os.path.normcase(str(requested_root)) != os.path.normcase(str(attested_root)): raise WebsiteRuntimeMeasurementProvenanceError( "CLI repository root must equal the authenticated launcher repository." ) result = verify_static_measurement_integrity_file( repo_root=requested_root, measurement_path=str(args.measurement), expected_measurement_sha256=str(args.expected_measurement_sha256), ) print(f"static-integrity-valid: provenance-unverified; production-blocked ({result['run_id']})") return 0
if __name__ == "__main__": try: raise SystemExit(main()) except WebsiteRuntimeMeasurementProvenanceError as exc: print(f"blocked: {exc}", file=sys.stderr) raise SystemExit(2) from exc123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743"""Compile immutable, non-executing website runtime optimisation proposals.
The compiler consumes three explicitly named and SHA-256-bound JSON inputs:an exact website source-rationalisation plan, strict measurement evidence, andthe release-blocking browser acceptance contract. It replays the canonical``website/`` tree, computes a conceptual runtime manifest, and stops.
It deliberately has no encoder, CSS transformer, reference rewriter, copy,delete, candidate, staging, packaging, network, credential, publishing, ordeployment entrypoint. A footprint projection is never proof that a candidateexists or that any acceptance test passed."""
from __future__ import annotations
import argparseimport hashlibimport jsonimport osimport reimport statimport sysimport uuidfrom collections.abc import Mapping, Sequencefrom datetime import UTC, datetime, timedeltafrom pathlib import Pathfrom types import MappingProxyType, ModuleTypefrom typing import Any, Final
MEASUREMENT_SCHEMA = "aureon.website-runtime-optimisation-measurement-evidence.v1"PROPOSAL_SCHEMA = "aureon.website-runtime-optimisation-proposal.v1"SOURCE_PLAN_SCHEMA = "aureon.website-source-rationalisation-plan.v1"ACCEPTANCE_CONTRACT_SCHEMA = "aureon.browser-acceptance-contract.v1"PRODUCTION_MEASUREMENT_PROVENANCE_STATE = "blocked-reviewed-measurement-provenance-tool-not-installed"
SOURCE_ROOT = Path("website")IMPLEMENTATION_PATH = Path("aureon/operator/website_runtime_optimisation.py")TRUSTED_LAUNCHER_PATH = Path("tools/run-website-runtime-optimisation.py")SOURCE_PLANNER_PATH = Path("aureon/operator/website_source_rationalisation.py")SOURCE_PLANNER_LAUNCHER_PATH = Path("tools/run-website-source-rationalisation.py")RELEASE_BUILDER_PATH = Path("tools/build-homepl-v28-narrow-release.ps1")MOTION_POLICY_PATH = Path("aureon/operator/design_candidate_motion_policy_compiler.py")SECURE_WRITER_PATH = Path("aureon/operator/secure_immutable_artifact.py")ACCEPTANCE_CONTRACT_PATH = Path("data/website_operator/browser_acceptance_contract.v1.json")SOURCE_PLAN_ROOT = Path("artifacts/website-operator/source-rationalisations/plans")MEASUREMENT_ROOT = Path("artifacts/website-operator/runtime-optimisations/measurements")PROPOSAL_ROOT = Path("artifacts/website-operator/runtime-optimisations/proposals")
# Pins are deliberately updated only after source review. The runtime launcher# pin is filled after its isolated bootstrap has been reviewed and hashed.REVIEWED_TRUSTED_LAUNCHER_SHA256 = "593A1703E31328C6A42D150C4D7AAFE8C7102D483D3A6D80134F7C46DC2B748A"REVIEWED_SOURCE_PLANNER_SHA256 = "D79397371038912C26056A4C8A154671B0269DF54DDBBB2BAD0BE472D070DD09"REVIEWED_SOURCE_PLANNER_LAUNCHER_SHA256 = "827D4112E6C6042B4931E987237E1E7B6035B5A147373CDE202D9DC95184B009"REVIEWED_RELEASE_BUILDER_SHA256 = "0C42EA5FEB59DCE1583A7731189BF91223AB0F6B5DD333936BCA7E9F65438204"REVIEWED_MOTION_POLICY_SHA256 = "2685C98B8D0199A30B09B3983E7F1C48DE65EF64D76E4B9900BE8F503F251A73"REVIEWED_SECURE_WRITER_SHA256 = "D704D691A4D3221E096A470884E5D1293EA663164BB6740FE5BDD26D32B4DB81"REVIEWED_ACCEPTANCE_CONTRACT_PAYLOAD_SHA256 = ( "25C85236E40E954B9FB75B561D7EE645E3B019027D9872E71935F5CE4276E5EC")
MAX_INPUT_AGE = timedelta(hours=4)MAX_CLOCK_SKEW = timedelta(minutes=5)MAX_FILES = 5_000MAX_TREE_BYTES = 512 * 1024 * 1024MAX_JSON_BYTES = 8 * 1024 * 1024MAX_REVIEWED_SOURCE_BYTES = 4 * 1024 * 1024
FIXED_FOOTPRINT_LIMITS: Final[Mapping[str, int]] = MappingProxyType( { "max_total_bytes": 4_500_000, "max_image_bytes": 2_200_000, "max_css_bytes": 350_000, "max_single_asset_bytes": 500_000, })
NO_AUTHORITY: Final[dict[str, object]] = { "scope": "read-only runtime optimisation proposal compilation", "source_selection_authority": "none", "measurement_creation_authority": "none", "canonical_website_mutation": "none", "physical_source_file_removal": "none", "encoding_execution": "none", "css_transformation_execution": "none", "reference_mutation": "none", "candidate_authority": "none", "staging_authority": "none", "package_authority": "none", "release_eligible": False, "deployment_authority": "none", "credential_access": "none", "network_access": "none",}
MEASUREMENT_AUTHORITY: Final[dict[str, object]] = { **NO_AUTHORITY, "scope": "strict machine-readable optimisation measurement declaration only",}
ACCEPTANCE_REQUIREMENT_IDS: Final[tuple[str, ...]] = ( "owner-source-selection-and-verified-live-backup", "exact-source-and-reference-closure-rebuild", "derivative-byte-and-dimension-integrity", "fixed-runtime-footprint-budget", "twenty-route-three-engine-browser-matrix", "seven-viewport-responsive-and-zoom-matrix", "keyboard-accessibility-and-skip-link-occlusion", "no-javascript-content-and-navigation", "reduced-motion-static-parity", "interactive-data-failure-and-fragment-states", "social-crawler-metadata-and-research-freshness", "approved-source-bound-visual-regression-and-human-review",)
_IMAGE_SUFFIXES = frozenset({".apng", ".avif", ".gif", ".ico", ".jpeg", ".jpg", ".png", ".svg", ".webp"})_SHA256 = re.compile(r"[A-F0-9]{64}\Z")_SAFE_ID = re.compile(r"[a-z0-9][a-z0-9._-]{2,80}\Z")_TRANSFORM_ACTIONS = frozenset({"replace-runtime-bytes", "omit-from-runtime-closure"})_MEASUREMENT_BASES = frozenset( { "measured-derivative", "deterministic-minification-measurement", "static-reference-analysis", "browser-computed-style-analysis", })
_MANIFEST_ROW_FIELDS = frozenset({"path", "bytes", "sha256"})_SOURCE_PLAN_BINDING_FIELDS = frozenset( { "path", "file_sha256", "payload_sha256", "plan_run_id", "source_tree_sha256", "retained_tree_sha256", "retained_manifest_sha256", })_ACCEPTANCE_BINDING_FIELDS = frozenset({"path", "file_sha256", "payload_sha256", "contract_id"})_MEASUREMENT_BINDING_FIELDS = frozenset({"path", "file_sha256", "payload_sha256", "measurement_run_id"})_METHODOLOGY_FIELDS = frozenset( { "id", "tool_path", "tool_sha256", "measurement_mode", "ephemeral_workspace_only", "source_masters_preserved", "network_access", "commands_recorded", })_TRANSFORMATION_FIELDS = frozenset( { "id", "action", "source_path", "source_sha256", "source_bytes", "projected_runtime_path", "projected_sha256", "projected_bytes", "expected_saving_bytes", "measurement_basis", "source_master_preserved", "reference_mutation_required", "execution_state", })_MEASUREMENT_FIELDS = frozenset( { "schema", "measured_at", "run_id", "state", "source_plan_binding", "acceptance_contract_binding", "methodology", "transformations", "authority", "payload_sha256", })_PROPOSAL_FIELDS = frozenset( { "schema", "generated_at", "run_id", "state", "source_plan_binding", "measurement_binding", "acceptance_contract_binding", "current_runtime", "projected_runtime", "transformations", "acceptance_requirements", "execution_binding", "eligible_for_next_local_gate", "authority", "payload_sha256", })_FOOTPRINT_FIELDS = frozenset( { "tree_sha256", "manifest_sha256", "file_count", "total_bytes", "image_bytes", "css_bytes", "largest_single_asset_path", "largest_single_asset_bytes", "limits", "violation_ids", "within_fixed_footprint_limits", })_PROJECTED_FOOTPRINT_FIELDS = _FOOTPRINT_FIELDS | {"saving_bytes"}_ACCEPTANCE_REQUIREMENT_FIELDS = frozenset({"id", "required", "status", "passed"})_TOOL_BINDING_FIELDS = frozenset({"path", "sha256"})_EXECUTION_BINDING_FIELDS = frozenset( { "mode", "repo_root", "implementation", "trusted_launcher", "source_planner", "source_planner_launcher", "release_builder", "motion_policy", "secure_writer", "measurement_tool", "commands_executed", "transformations_executed", "production_writable", })_FOOTPRINT_VIOLATION_IDS = frozenset( { "resource-byte-budget-exceeded:total", "resource-byte-budget-exceeded:image", "resource-byte-budget-exceeded:css", "single-asset-budget-exceeded", })
class WebsiteRuntimeOptimisationError(ValueError): """A proposal input or requested operation is unsafe, stale, or malformed."""
def _canonical_json_bytes(value: object) -> bytes: try: return json.dumps( value, sort_keys=True, separators=(",", ":"), ensure_ascii=False, allow_nan=False, ).encode("utf-8") except (TypeError, ValueError) as exc: raise WebsiteRuntimeOptimisationError("Value is not canonical JSON.") from exc
def _json_sha256(value: object) -> str: return hashlib.sha256(_canonical_json_bytes(value)).hexdigest().upper()
def _sha256_bytes(value: bytes) -> str: return hashlib.sha256(value).hexdigest().upper()
def _utc_iso(value: datetime | None = None) -> str: resolved = (value or datetime.now(UTC)).astimezone(UTC).replace(microsecond=0) return resolved.isoformat().replace("+00:00", "Z")
def _parse_utc(value: object, *, label: str) -> datetime: if not isinstance(value, str) or not value.endswith("Z"): raise WebsiteRuntimeOptimisationError(f"{label} must be an explicit UTC timestamp.") try: parsed = datetime.fromisoformat(value[:-1] + "+00:00") except ValueError as exc: raise WebsiteRuntimeOptimisationError(f"{label} is not a valid UTC timestamp.") from exc if parsed.tzinfo is None or parsed.utcoffset() != timedelta(0): raise WebsiteRuntimeOptimisationError(f"{label} must resolve to UTC.") return parsed.astimezone(UTC)
def _require_fresh(value: object, *, now: datetime, label: str) -> datetime: parsed = _parse_utc(value, label=label) if parsed > now + MAX_CLOCK_SKEW or now - parsed > MAX_INPUT_AGE: raise WebsiteRuntimeOptimisationError(f"{label} is future-dated or older than four hours.") return parsed
def _safe_id(value: object, *, label: str) -> str: if not isinstance(value, str) or _SAFE_ID.fullmatch(value) is None: raise WebsiteRuntimeOptimisationError(f"{label} is not a safe identifier.") return value
def _require_sha256(value: object, *, label: str) -> str: if not isinstance(value, str) or _SHA256.fullmatch(value) is None: raise WebsiteRuntimeOptimisationError(f"{label} must be uppercase SHA-256.") return value
def _safe_relative_path(value: object, *, allow_empty: bool = False) -> str: if allow_empty and value == "": return "" if not isinstance(value, str) or not value or "\\" in value or "\x00" in value: raise WebsiteRuntimeOptimisationError("A path is not a safe repository-relative POSIX path.") path = Path(value) if path.is_absolute() or value.startswith("/") or any(part in {"", ".", ".."} for part in path.parts): raise WebsiteRuntimeOptimisationError("A path escapes its repository-relative boundary.") return path.as_posix()
def _is_link_or_reparse(path: Path) -> bool: details = path.lstat() attributes = int(getattr(details, "st_file_attributes", 0) or 0) reparse = int(getattr(stat, "FILE_ATTRIBUTE_REPARSE_POINT", 0x400) or 0x400) return stat.S_ISLNK(details.st_mode) or bool(attributes & reparse)
def _same_identity(left: os.stat_result, right: os.stat_result) -> bool: return ( stat.S_IFMT(left.st_mode) == stat.S_IFMT(right.st_mode) and int(left.st_dev) == int(right.st_dev) and int(left.st_ino) == int(right.st_ino) )
def _ordinary_file(path: Path, *, label: str, require_single_link: bool = True) -> Path: lexical = Path(os.path.abspath(path)) for component in (lexical, *lexical.parents): if (component.exists() or component.is_symlink()) and _is_link_or_reparse(component): raise WebsiteRuntimeOptimisationError(f"{label} may not cross a link or reparse point.") if not lexical.is_file(): raise WebsiteRuntimeOptimisationError(f"{label} must be an ordinary file.") if require_single_link and int(lexical.stat().st_nlink) != 1: raise WebsiteRuntimeOptimisationError(f"{label} must have exactly one hard link.") return lexical
def _ordinary_directory(path: Path, *, label: str) -> Path: lexical = Path(os.path.abspath(path)) for component in (lexical, *lexical.parents): if (component.exists() or component.is_symlink()) and _is_link_or_reparse(component): raise WebsiteRuntimeOptimisationError(f"{label} may not cross a link or reparse point.") if not lexical.is_dir(): raise WebsiteRuntimeOptimisationError(f"{label} must be an ordinary directory.") return lexical
def _canonical_repo_root() -> Path: implementation = Path(os.path.abspath(__file__)) if implementation.name != IMPLEMENTATION_PATH.name: raise WebsiteRuntimeOptimisationError("Runtime optimisation implementation path is unexpected.") return implementation.parents[2]
def _read_exact_file( path: Path, expected_sha256: str, *, label: str, max_bytes: int = MAX_JSON_BYTES,) -> tuple[bytes, os.stat_result]: expected = _require_sha256(expected_sha256, label=f"{label} expected SHA-256") source = _ordinary_file(path, label=label) before = source.lstat() if int(before.st_size) > max_bytes: raise WebsiteRuntimeOptimisationError(f"{label} exceeds its byte bound.") with source.open("rb") as stream: opened = os.fstat(stream.fileno()) if not _same_identity(before, opened): raise WebsiteRuntimeOptimisationError(f"{label} changed before its handle opened.") payload = stream.read(max_bytes + 1) after = source.lstat() if ( len(payload) > max_bytes or int(after.st_size) != len(payload) or not _same_identity(opened, after) or _sha256_bytes(payload) != expected ): raise WebsiteRuntimeOptimisationError(f"{label} bytes do not match the exact supplied pin.") return payload, after
def _strict_json(raw: bytes, *, label: str) -> dict[str, Any]: try: text = raw.decode("utf-8") except UnicodeDecodeError as exc: raise WebsiteRuntimeOptimisationError(f"{label} must be UTF-8 JSON.") from exc
def reject_duplicate(pairs: list[tuple[str, Any]]) -> dict[str, Any]: result: dict[str, Any] = {} for key, value in pairs: if key in result: raise WebsiteRuntimeOptimisationError(f"{label} contains duplicate JSON keys.") result[key] = value return result
try: value = json.loads( text, object_pairs_hook=reject_duplicate, parse_constant=lambda token: (_ for _ in ()).throw( WebsiteRuntimeOptimisationError(f"{label} contains non-finite {token}.") ), ) except (json.JSONDecodeError, RecursionError) as exc: raise WebsiteRuntimeOptimisationError(f"{label} is not strict JSON.") from exc if not isinstance(value, dict): raise WebsiteRuntimeOptimisationError(f"{label} must be one JSON object.") return value
def _exact_object(value: object, fields: frozenset[str], *, label: str) -> dict[str, Any]: if not isinstance(value, dict) or set(value) != fields: raise WebsiteRuntimeOptimisationError(f"{label} must contain exactly {sorted(fields)}.") return value
def _payload_hash(value: Mapping[str, Any], *, field: str = "payload_sha256") -> str: payload = dict(value) observed = _require_sha256(payload.pop(field, None), label=field) if _json_sha256(payload) != observed: raise WebsiteRuntimeOptimisationError(f"{field} does not authenticate the exact JSON payload.") return observed
def _manifest_rows(value: object, *, label: str) -> list[dict[str, object]]: if not isinstance(value, list) or len(value) > MAX_FILES: raise WebsiteRuntimeOptimisationError(f"{label} must be a bounded manifest list.") rows: list[dict[str, object]] = [] paths: set[str] = set() total = 0 for index, raw in enumerate(value): row = _exact_object(raw, _MANIFEST_ROW_FIELDS, label=f"{label}[{index}]") path = _safe_relative_path(row["path"]) sha256 = _require_sha256(row["sha256"], label=f"{label}[{index}].sha256") size = row["bytes"] if isinstance(size, bool) or not isinstance(size, int) or size < 0: raise WebsiteRuntimeOptimisationError(f"{label}[{index}].bytes must be non-negative.") if path in paths: raise WebsiteRuntimeOptimisationError(f"{label} contains a duplicate path.") paths.add(path) total += size if total > MAX_TREE_BYTES: raise WebsiteRuntimeOptimisationError(f"{label} exceeds the tree byte bound.") rows.append({"path": path, "bytes": size, "sha256": sha256}) if rows != sorted(rows, key=lambda item: str(item["path"])): raise WebsiteRuntimeOptimisationError(f"{label} must use case-sensitive path order.") return rows
def _summary(rows: Sequence[Mapping[str, object]]) -> dict[str, object]: normalised = [dict(row) for row in sorted(rows, key=lambda item: str(item["path"]))] total = sum(_row_bytes(row) for row in normalised) digest = _json_sha256(normalised) return { "tree_sha256": digest, "manifest_sha256": digest, "file_count": len(normalised), "total_bytes": total, "files": normalised, }
def _manifest(root: Path) -> list[dict[str, object]]: site = _ordinary_directory(root, label="Canonical website source") rows: list[dict[str, object]] = [] total = 0 for path in sorted(site.rglob("*"), key=lambda item: item.relative_to(site).as_posix()): if _is_link_or_reparse(path): raise WebsiteRuntimeOptimisationError( "Canonical website source contains a link or reparse point." ) if path.is_dir(): continue if not path.is_file() or int(path.stat().st_nlink) != 1: raise WebsiteRuntimeOptimisationError("Canonical website source contains a non-ordinary file.") relative = path.relative_to(site).as_posix() size = int(path.stat().st_size) total += size if len(rows) >= MAX_FILES or total > MAX_TREE_BYTES: raise WebsiteRuntimeOptimisationError("Canonical website source exceeds its manifest bounds.") payload, _ = _read_exact_file( path, hashlib.sha256(path.read_bytes()).hexdigest().upper(), label=f"Canonical source {relative}", max_bytes=max(size, 1), ) rows.append({"path": relative, "bytes": len(payload), "sha256": _sha256_bytes(payload)}) return rows
def _require_source_plan(value: object, *, now: datetime) -> dict[str, Any]: if not isinstance(value, dict): raise WebsiteRuntimeOptimisationError("Source plan must be a JSON object.") if value.get("schema") != SOURCE_PLAN_SCHEMA or value.get("state") != "proposal-only": raise WebsiteRuntimeOptimisationError("Source plan is not the proposal-only v1 contract.") _payload_hash(value) _safe_id(value.get("run_id"), label="source plan run_id") _require_fresh(value.get("generated_at"), now=now, label="source plan generated_at") authority = value.get("authority") if not isinstance(authority, Mapping) or ( authority.get("canonical_website_mutation") != "none" or authority.get("physical_source_file_removal") != "none" or authority.get("staging_authority") != "none" or authority.get("candidate_authority") != "none" or authority.get("package_authority") != "none" or authority.get("release_eligible") is not False or authority.get("deployment_authority") != "none" or authority.get("credential_access") != "none" or authority.get("network_access") != "none" ): raise WebsiteRuntimeOptimisationError("Source plan authority is not fail closed.") source = value.get("source_binding") retained = value.get("retained_projection") omitted = value.get("omitted_projection") if not all(isinstance(item, dict) for item in (source, retained, omitted)): raise WebsiteRuntimeOptimisationError("Source plan projections are missing.") assert isinstance(source, dict) assert isinstance(retained, dict) assert isinstance(omitted, dict) source_rows = _manifest_rows(source.get("files"), label="source plan source files") retained_rows = _manifest_rows(retained.get("files"), label="source plan retained files") raw_omitted = omitted.get("files") if not isinstance(raw_omitted, list): raise WebsiteRuntimeOptimisationError("Source plan omitted files must be a list.") omitted_rows: list[dict[str, object]] = [] for index, raw in enumerate(raw_omitted): if not isinstance(raw, dict) or set(raw) != {"path", "bytes", "sha256", "reason"}: raise WebsiteRuntimeOptimisationError(f"Source plan omitted files[{index}] is malformed.") if raw.get("reason") != "not-in-public-runtime-closure": raise WebsiteRuntimeOptimisationError("Source plan omission reason is not closed-world.") omitted_rows.extend( _manifest_rows( [{key: raw[key] for key in ("path", "bytes", "sha256")}], label=f"source plan omitted file {index}", ) ) partition = sorted([*retained_rows, *omitted_rows], key=lambda item: str(item["path"])) if partition != source_rows: raise WebsiteRuntimeOptimisationError("Retained and omitted projections do not partition the source.") for label, projection, rows in ( ("source", source, source_rows), ("retained", retained, retained_rows), ): expected = _summary(rows) for field in ("tree_sha256", "manifest_sha256", "file_count", "total_bytes"): if projection.get(field) != expected[field]: raise WebsiteRuntimeOptimisationError(f"Source plan {label} {field} is inconsistent.") if source.get("root") != SOURCE_ROOT.as_posix(): raise WebsiteRuntimeOptimisationError("Source plan does not bind canonical website/.") closure = value.get("closure_binding") budget = value.get("motion_budget_projection") execution = value.get("execution_binding") if not all(isinstance(item, Mapping) for item in (closure, budget, execution)): raise WebsiteRuntimeOptimisationError("Source plan tool bindings are missing.") assert isinstance(closure, Mapping) assert isinstance(budget, Mapping) assert isinstance(execution, Mapping) if ( closure.get("verify_only") is not True or closure.get("state") != "verified-complete" or closure.get("tool_sha256") != REVIEWED_RELEASE_BUILDER_SHA256 or budget.get("policy_sha256") != REVIEWED_MOTION_POLICY_SHA256 or execution.get("implementation_sha256") != REVIEWED_SOURCE_PLANNER_SHA256 or execution.get("reviewed_trusted_launcher_sha256") != REVIEWED_SOURCE_PLANNER_LAUNCHER_SHA256 or execution.get("reviewed_secure_writer_sha256") != REVIEWED_SECURE_WRITER_SHA256 or execution.get("launcher_attested") is not True ): raise WebsiteRuntimeOptimisationError("Source plan is not bound to the reviewed planning closure.") return value
def _require_acceptance_contract( value: object, *, retained: Mapping[str, Any], reviewed_payload_required: bool = True,) -> dict[str, Any]: if not isinstance(value, dict) or value.get("schema") != ACCEPTANCE_CONTRACT_SCHEMA: raise WebsiteRuntimeOptimisationError("Browser acceptance contract schema is invalid.") if set(value) != { "schema", "contractId", "mode", "origin", "authority", "sourceBinding", "routes", "browserMatrix", "releaseResultMaxima", "evidenceRequirements", "globalAssertions", "interactionAssertions", "derivativeIntegrityAssertions", "visualRegression", "progressiveEnhancementAssertions", "socialCrawlerAssertions", "researchAndArtworkBaselines", "footprintLimitsBytes", "perRoutePerformanceLimits", "knownReleaseBlockers", "payloadSha256", }: raise WebsiteRuntimeOptimisationError("Browser acceptance contract topology is not exact.") payload_field = "payloadSha256" payload = dict(value) observed = _require_sha256(payload.pop(payload_field, None), label=payload_field) if _json_sha256(payload) != observed: raise WebsiteRuntimeOptimisationError("Browser acceptance contract payload hash is invalid.") if reviewed_payload_required and observed != REVIEWED_ACCEPTANCE_CONTRACT_PAYLOAD_SHA256: raise WebsiteRuntimeOptimisationError( "Browser acceptance contract payload is not the reviewed immutable policy." ) if ( value.get("contractId") != "AUREON-WEB-V29-OPTIMISATION-ACCEPTANCE" or value.get("mode") != "release-blocking" or value.get("origin") != "https://aureonzorzatechnologies.pl" ): raise WebsiteRuntimeOptimisationError("Browser acceptance contract must be release-blocking.") authority = value.get("authority") if authority != { "scope": "read-only browser acceptance criteria", "candidateAuthority": "none", "canonicalWebsiteMutation": "none", "packageAuthority": "none", "releaseAuthority": "none", "releaseEligible": False, "deploymentAuthority": "none", "networkAccess": "none", "credentialAccess": "none", }: raise WebsiteRuntimeOptimisationError("Browser acceptance contract grants authority.") binding = value.get("sourceBinding") if not isinstance(binding, Mapping) or ( binding.get("retainedManifestSha256") != retained.get("manifest_sha256") or binding.get("retainedFileCount") != retained.get("file_count") or binding.get("retainedTotalBytes") != retained.get("total_bytes") or binding.get("htmlDocumentCount") != 20 or binding.get("indexableDocumentCount") != 17 or binding.get("noindexDocumentCount") != 3 ): raise WebsiteRuntimeOptimisationError("Browser acceptance contract source binding is stale.") verdict = value.get("releaseResultMaxima") evidence = value.get("evidenceRequirements") if ( not isinstance(verdict, Mapping) or not isinstance(evidence, Mapping) or ( verdict.get("failures") != 0 or verdict.get("errors") != 0 or verdict.get("warnings") != 0 or verdict.get("firstPartyRequestFailures") != 0 or evidence.get("manualVisualReviewRequired") is not True or evidence.get("browserReportRequired") is not True or evidence.get("screenshotManifestRequired") is not True or evidence.get("browserReportMustBindContractPayloadSha256") is not True or evidence.get("screenshotManifestMustBindSourceManifestSha256") is not True or evidence.get("derivativeManifestRequired") is not True or evidence.get("derivativeManifestMustBindMeasurementPayloadSha256") is not True ) ): raise WebsiteRuntimeOptimisationError("Browser acceptance verdict is not fail closed.") routes = value.get("routes") matrix = value.get("browserMatrix") engines = matrix.get("engines") if isinstance(matrix, Mapping) else None viewports = matrix.get("viewports") if isinstance(matrix, Mapping) else None zoom = matrix.get("zoomProfile") if isinstance(matrix, Mapping) else None if not isinstance(routes, list) or len(routes) != 20: raise WebsiteRuntimeOptimisationError("Browser acceptance contract must cover 20 routes.") expected_routes = { ("/", "index.html", "indexable"), ("/404.html", "404.html", "noindex"), ("/about/", "about/index.html", "indexable"), ("/accessibility.html", "accessibility.html", "indexable"), ("/community/", "community/index.html", "indexable"), ("/contact/", "contact/index.html", "indexable"), ("/diligence/", "diligence/index.html", "indexable"), ("/downloads/", "downloads/index.html", "noindex"), ( "/downloads/validation-metrics-ledger/", "downloads/validation-metrics-ledger/index.html", "noindex", ), ("/funding/", "funding/index.html", "indexable"), ("/funding/investor-deck/", "funding/investor-deck/index.html", "indexable"), ("/live/", "live/index.html", "indexable"), ("/privacy.html", "privacy.html", "indexable"), ( "/projects/aureon-trading-system/", "projects/aureon-trading-system/index.html", "indexable", ), ("/projects/", "projects/index.html", "indexable"), ("/publications/", "publications/index.html", "indexable"), ("/research/", "research/index.html", "indexable"), ("/research/journal/", "research/journal/index.html", "indexable"), ("/updates/", "updates/index.html", "indexable"), ("/vision/", "vision/index.html", "indexable"), } observed_routes = { (row.get("route"), row.get("documentPath"), row.get("indexing")) for row in routes if isinstance(row, Mapping) } if observed_routes != expected_routes: raise WebsiteRuntimeOptimisationError("Browser acceptance route matrix is incomplete or altered.") if set(engines or []) != { "chromium", "firefox", "webkit", }: raise WebsiteRuntimeOptimisationError("Browser acceptance contract must cover three engines.") if not isinstance(viewports, list) or { (item.get("width"), item.get("height")) for item in viewports if isinstance(item, Mapping) } != { (320, 800), (360, 800), (390, 844), (768, 1024), (1280, 800), (1440, 1000), (1920, 1080), }: raise WebsiteRuntimeOptimisationError("Browser acceptance contract must cover seven viewports.") if not isinstance(zoom, Mapping) or dict(zoom) != { "routes": "all", "engine": "chromium", "viewport": {"width": 1280, "height": 800}, "percent": [100, 200, 400], "horizontalOverflowPixels": 0, "contentLossAllowed": False, }: raise WebsiteRuntimeOptimisationError("Browser acceptance zoom coverage is incomplete.") static = value.get("footprintLimitsBytes") expected_limits = { "maximumTotal": FIXED_FOOTPRINT_LIMITS["max_total_bytes"], "maximumImages": FIXED_FOOTPRINT_LIMITS["max_image_bytes"], "maximumCss": FIXED_FOOTPRINT_LIMITS["max_css_bytes"], "maximumSingleAsset": FIXED_FOOTPRINT_LIMITS["max_single_asset_bytes"], } if static != expected_limits: raise WebsiteRuntimeOptimisationError("Browser contract footprint limits are not fixed policy.") for required in ( "globalAssertions", "interactionAssertions", "derivativeIntegrityAssertions", "visualRegression", "progressiveEnhancementAssertions", "socialCrawlerAssertions", "researchAndArtworkBaselines", "perRoutePerformanceLimits", "knownReleaseBlockers", ): if required not in value: raise WebsiteRuntimeOptimisationError(f"Browser acceptance contract lacks {required}.") global_assertions = value["globalAssertions"] interactions = value["interactionAssertions"] derivative_integrity = value["derivativeIntegrityAssertions"] visual = value["visualRegression"] progressive = value["progressiveEnhancementAssertions"] social = value["socialCrawlerAssertions"] research = value["researchAndArtworkBaselines"] performance = value["perRoutePerformanceLimits"] blockers = value["knownReleaseBlockers"] if not all( isinstance(item, Mapping) for item in ( global_assertions, interactions, derivative_integrity, visual, progressive, social, research, performance, ) ) or not isinstance(blockers, list): raise WebsiteRuntimeOptimisationError("Browser acceptance assertions are malformed.") dom = global_assertions.get("dom") accessibility = global_assertions.get("accessibility") mobile = interactions.get("mobileNavigation") fragments = interactions.get("fragmentNavigation") skip = interactions.get("skipLinkStacking") interactive_states = interactions.get("interactiveStates") data_failure_states = interactions.get("dataFailureStates") no_js = progressive.get("noJavaScript") reduced = progressive.get("reducedMotion") if not all( isinstance(item, Mapping) for item in ( dom, accessibility, mobile, fragments, skip, interactive_states, data_failure_states, no_js, reduced, ) ): raise WebsiteRuntimeOptimisationError("Browser acceptance subcontracts are malformed.") assert isinstance(dom, Mapping) assert isinstance(accessibility, Mapping) assert isinstance(mobile, Mapping) assert isinstance(fragments, Mapping) assert isinstance(skip, Mapping) assert isinstance(interactive_states, Mapping) assert isinstance(data_failure_states, Mapping) assert isinstance(no_js, Mapping) assert isinstance(reduced, Mapping) if any( dom.get(key) != expected for key, expected in { "expectedHttpStatus": 200, "unexpectedRedirects": 0, "loginWalls": 0, "titleElements": 1, "mainLandmarks": 1, "h1Elements": 1, "duplicateIds": 0, "imagesWithoutAltAttribute": 0, "brokenFirstPartyLinks": 0, "missingInternalFragmentTargets": 0, "horizontalOverflowPixels": 0, }.items() ) or any( accessibility.get(key) != expected for key, expected in { "axeCriticalViolations": 0, "axeSeriousViolations": 0, "unnamedInteractiveControls": 0, "keyboardTraps": 0, "visibleFocusRequired": True, "skipLinkRequired": True, "skipLinkTargetRequired": True, }.items() ): raise WebsiteRuntimeOptimisationError("Global DOM or accessibility maxima were weakened.") if ( mobile.get("toggleRequired") is not True or mobile.get("ariaExpandedMustTrackState") is not True or mobile.get("escapeClosesMenu") is not True or mobile.get("keyboardOperable") is not True or fragments.get("missingTargetMaximum") != 0 or set(fragments.get("requiredDestinations") or []) != { "/projects/#core", "/projects/#blades", } or skip.get("focusedSkipLinkMustBeVisible") is not True or skip.get("minimumZIndexDeltaAboveStickyHeader") != 1 or interactive_states.get("scope") != "all-interactive-controls" or interactive_states.get("requiredStates") != ["default", "keyboard-focus", "activated", "disabled-when-applicable"] or interactive_states.get("consoleErrors") != 0 or interactive_states.get("uncaughtExceptions") != 0 or data_failure_states.get("scope") != "all-data-dependent-surfaces" or data_failure_states.get("requiredStates") != ["loading", "success", "empty", "error"] or data_failure_states.get("fallbackVisibleOnError") is not True or data_failure_states.get("primaryNavigationUsableOnError") is not True or data_failure_states.get("uncaughtExceptions") != 0 ): raise WebsiteRuntimeOptimisationError("Navigation or skip-link acceptance was weakened.") if dict(derivative_integrity) != { "manifestRequired": True, "sourceAndProjectedSha256Required": True, "sourceAndProjectedByteCountsRequired": True, "sourceAndProjectedDimensionsRequired": True, "decodedProjectedDimensionsRequired": True, "allowedDimensionChange": "explicitly-declared-no-unapproved-crop", "zeroByteDerivativesMaximum": 0, }: raise WebsiteRuntimeOptimisationError("Derivative integrity acceptance is incomplete.") desktop_visual = visual.get("desktop") mobile_visual = visual.get("mobileAndTablet") if ( not isinstance(desktop_visual, Mapping) or not isinstance(mobile_visual, Mapping) or ( desktop_visual.get("maximumPixelDifferenceRatio") != 0.005 or desktop_visual.get("minimumSsim") != 0.99 or mobile_visual.get("maximumPixelDifferenceRatio") != 0.01 or mobile_visual.get("minimumSsim") != 0.985 or visual.get("baselineMismatchIsReleaseBlocking") is not True or visual.get("manualReviewDoesNotWaiveThresholds") is not True ) ): raise WebsiteRuntimeOptimisationError("Visual-regression acceptance was weakened.") if ( no_js.get("everyRouteRequired") is not True or no_js.get("primaryContentVisible") is not True or no_js.get("primaryNavigationUsable") is not True or reduced.get("everyRouteRequired") is not True or reduced.get("materialContentEquivalent") is not True or reduced.get("autoplayingMotionAllowed") is not False or reduced.get("interactionUsable") is not True ): raise WebsiteRuntimeOptimisationError("Progressive-enhancement acceptance was weakened.") floors = research.get("providerRecordFloors") if ( social.get("scope") != "all-17-indexable-routes" or social.get("crawlerRequestFailures") != 0 or social.get("absoluteHttpsUrlsRequired") is not True or research.get("researchNoteMinimumCount") != 34 or research.get("artworkEntryMinimumCount") != 6 or research.get("artworkFileMinimumCount") != 12 or floors != {"orcid": 74, "zenodo": 73} or research.get("providerSnapshotMaxAgeHours") != 24 or research.get("providerSnapshotPayloadSha256Required") is not True or research.get("publicProviderReadbackRequired") is not True or research.get("websiteSelectedDoiSetMustEqualOrcid") is not True or research.get("selectedDoiCountMinimum") != 12 or research.get("regressionAllowed") is not False ): raise WebsiteRuntimeOptimisationError("Crawler, research, or artwork acceptance was weakened.") if performance != { "maximumTtfbMs": 800, "maximumDomContentLoadedMs": 2500, "maximumLoadMs": 3500, "maximumLcpMs": 2500, "maximumCls": 0.1, "maximumRequestCount": 80, "maximumTransferBytes": 3_000_000, "maximumTotalLongTaskDurationMs": 300, }: raise WebsiteRuntimeOptimisationError("Per-route performance acceptance was weakened.") if {row.get("id") for row in blockers if isinstance(row, Mapping)} != { "projects-core-fragment-missing-live", "projects-blades-fragment-missing-live", "skip-link-obscured-by-header", "projects-current-source-hash-stale-live", }: raise WebsiteRuntimeOptimisationError("Known live release blockers are incomplete.") return value
def _require_transformation_rows(value: object) -> list[dict[str, Any]]: """Structurally validate exact non-executing transformation declarations."""
rows = value if not isinstance(rows, list) or not rows or len(rows) > MAX_FILES: raise WebsiteRuntimeOptimisationError("Measurement transformations must be a bounded non-empty list.") validated: list[dict[str, Any]] = [] identifiers: set[str] = set() source_paths: set[str] = set() for index, raw in enumerate(rows): row = _exact_object(raw, _TRANSFORMATION_FIELDS, label=f"Transformation[{index}]") identifier = _safe_id(row["id"], label=f"Transformation[{index}].id") source_path = _safe_relative_path(row["source_path"]) source_sha = _require_sha256(row["source_sha256"], label=f"Transformation[{index}].source_sha256") del source_sha source_bytes = row["source_bytes"] projected_bytes = row["projected_bytes"] savings = row["expected_saving_bytes"] if ( identifier in identifiers or source_path in source_paths or isinstance(source_bytes, bool) or not isinstance(source_bytes, int) or source_bytes <= 0 or source_bytes > MAX_TREE_BYTES or isinstance(projected_bytes, bool) or not isinstance(projected_bytes, int) or projected_bytes < 0 or projected_bytes > MAX_TREE_BYTES or projected_bytes >= source_bytes or isinstance(savings, bool) or not isinstance(savings, int) or savings <= 0 or savings > MAX_TREE_BYTES or savings != source_bytes - projected_bytes ): raise WebsiteRuntimeOptimisationError( "Transformation identifiers, paths, or byte arithmetic are invalid." ) identifiers.add(identifier) source_paths.add(source_path) if ( row["action"] not in _TRANSFORM_ACTIONS or row["measurement_basis"] not in _MEASUREMENT_BASES or row["source_master_preserved"] is not True or not isinstance(row["reference_mutation_required"], bool) or row["execution_state"] != "not-executed" ): raise WebsiteRuntimeOptimisationError("Transformation authority or evidence basis is invalid.") projected_path = _safe_relative_path(row["projected_runtime_path"], allow_empty=True) projected_sha = row["projected_sha256"] if row["action"] == "omit-from-runtime-closure": if projected_path or projected_sha != "" or projected_bytes != 0: raise WebsiteRuntimeOptimisationError( "Closure omission may not declare runtime output bytes." ) else: if not projected_path or projected_bytes <= 0: raise WebsiteRuntimeOptimisationError( "Runtime replacement requires exact projected output evidence." ) _require_sha256( projected_sha, label=f"Transformation[{index}].projected_sha256", ) validated.append(row) return validated
def _require_source_plan_binding(value: object, *, label: str) -> dict[str, Any]: binding = _exact_object(value, _SOURCE_PLAN_BINDING_FIELDS, label=label) _safe_relative_path(binding["path"]) for field in ( "file_sha256", "payload_sha256", "source_tree_sha256", "retained_tree_sha256", "retained_manifest_sha256", ): _require_sha256(binding[field], label=f"{label}.{field}") _safe_id(binding["plan_run_id"], label=f"{label}.plan_run_id") return binding
def _require_acceptance_binding(value: object, *, label: str) -> dict[str, Any]: binding = _exact_object(value, _ACCEPTANCE_BINDING_FIELDS, label=label) _safe_relative_path(binding["path"]) _require_sha256(binding["file_sha256"], label=f"{label}.file_sha256") _require_sha256(binding["payload_sha256"], label=f"{label}.payload_sha256") if not isinstance(binding["contract_id"], str) or not binding["contract_id"]: raise WebsiteRuntimeOptimisationError(f"{label}.contract_id is missing.") return binding
def require_measurement_evidence(value: object) -> dict[str, Any]: """Structurally validate a measurement declaration without proving provenance."""
evidence = _exact_object(value, _MEASUREMENT_FIELDS, label="Measurement evidence") if evidence.get("schema") != MEASUREMENT_SCHEMA or evidence.get("state") != "measurement-only": raise WebsiteRuntimeOptimisationError("Measurement evidence schema or state is invalid.") _payload_hash(evidence) _safe_id(evidence.get("run_id"), label="measurement run_id") _parse_utc(evidence.get("measured_at"), label="measurement measured_at") _require_source_plan_binding(evidence.get("source_plan_binding"), label="Measurement source-plan binding") _require_acceptance_binding( evidence.get("acceptance_contract_binding"), label="Measurement acceptance-contract binding", ) methodology = _exact_object( evidence.get("methodology"), _METHODOLOGY_FIELDS, label="Measurement methodology", ) _safe_id(methodology["id"], label="methodology.id") _safe_relative_path(methodology["tool_path"]) _require_sha256(methodology["tool_sha256"], label="methodology.tool_sha256") if ( methodology["measurement_mode"] != "read-only-source-ephemeral-derivatives" or methodology["ephemeral_workspace_only"] is not True or methodology["source_masters_preserved"] is not True or methodology["network_access"] != "none" or methodology["commands_recorded"] is not False ): raise WebsiteRuntimeOptimisationError("Measurement methodology is not non-operational.") _require_transformation_rows(evidence.get("transformations")) if evidence.get("authority") != MEASUREMENT_AUTHORITY: raise WebsiteRuntimeOptimisationError("Measurement evidence authority is not exact and fail closed.") return evidence
def _row_bytes(row: Mapping[str, object]) -> int: value = row.get("bytes") if isinstance(value, bool) or not isinstance(value, int) or value < 0: raise WebsiteRuntimeOptimisationError("Manifest row bytes are invalid.") return value
def _footprint(rows: Sequence[Mapping[str, object]]) -> dict[str, Any]: total = sum(_row_bytes(row) for row in rows) image = sum(_row_bytes(row) for row in rows if Path(str(row["path"])).suffix.lower() in _IMAGE_SUFFIXES) css = sum(_row_bytes(row) for row in rows if Path(str(row["path"])).suffix.lower() == ".css") largest = max(rows, key=_row_bytes, default={"path": "", "bytes": 0}) violations: list[str] = [] if total > FIXED_FOOTPRINT_LIMITS["max_total_bytes"]: violations.append("resource-byte-budget-exceeded:total") if image > FIXED_FOOTPRINT_LIMITS["max_image_bytes"]: violations.append("resource-byte-budget-exceeded:image") if css > FIXED_FOOTPRINT_LIMITS["max_css_bytes"]: violations.append("resource-byte-budget-exceeded:css") if _row_bytes(largest) > FIXED_FOOTPRINT_LIMITS["max_single_asset_bytes"]: violations.append("single-asset-budget-exceeded") return { "tree_sha256": _json_sha256([dict(row) for row in rows]), "manifest_sha256": _json_sha256([dict(row) for row in rows]), "file_count": len(rows), "total_bytes": total, "image_bytes": image, "css_bytes": css, "largest_single_asset_path": str(largest["path"]), "largest_single_asset_bytes": _row_bytes(largest), "limits": dict(FIXED_FOOTPRINT_LIMITS), "violation_ids": violations, "within_fixed_footprint_limits": not violations, }
def _require_footprint(value: object, *, label: str, projected: bool) -> dict[str, Any]: """Validate one non-empty footprint and its fixed-budget arithmetic."""
expected_fields = _PROJECTED_FOOTPRINT_FIELDS if projected else _FOOTPRINT_FIELDS footprint = _exact_object(value, expected_fields, label=label) tree_sha256 = _require_sha256(footprint["tree_sha256"], label=f"{label}.tree_sha256") manifest_sha256 = _require_sha256(footprint["manifest_sha256"], label=f"{label}.manifest_sha256") if tree_sha256 != manifest_sha256: raise WebsiteRuntimeOptimisationError(f"{label} tree and manifest hashes diverge.")
integer_fields = ( "file_count", "total_bytes", "image_bytes", "css_bytes", "largest_single_asset_bytes", ) integers: dict[str, int] = {} for field in integer_fields: raw = footprint[field] if isinstance(raw, bool) or not isinstance(raw, int): raise WebsiteRuntimeOptimisationError(f"{label}.{field} must be an integer.") integers[field] = raw if not 1 <= integers["file_count"] <= MAX_FILES or not 1 <= integers["total_bytes"] <= MAX_TREE_BYTES: raise WebsiteRuntimeOptimisationError(f"{label} must describe a bounded non-empty runtime.") if not ( 0 <= integers["image_bytes"] <= integers["total_bytes"] and 0 <= integers["css_bytes"] <= integers["total_bytes"] and 0 <= integers["largest_single_asset_bytes"] <= integers["total_bytes"] ): raise WebsiteRuntimeOptimisationError(f"{label} byte totals are inconsistent.") _safe_relative_path(footprint["largest_single_asset_path"]) if footprint["limits"] != FIXED_FOOTPRINT_LIMITS: raise WebsiteRuntimeOptimisationError(f"{label} weakens the fixed footprint limits.")
violation_ids = footprint["violation_ids"] if ( not isinstance(violation_ids, list) or len(violation_ids) != len(set(violation_ids)) or any(identifier not in _FOOTPRINT_VIOLATION_IDS for identifier in violation_ids) ): raise WebsiteRuntimeOptimisationError(f"{label} violation ids are invalid.") expected_violations: list[str] = [] if integers["total_bytes"] > FIXED_FOOTPRINT_LIMITS["max_total_bytes"]: expected_violations.append("resource-byte-budget-exceeded:total") if integers["image_bytes"] > FIXED_FOOTPRINT_LIMITS["max_image_bytes"]: expected_violations.append("resource-byte-budget-exceeded:image") if integers["css_bytes"] > FIXED_FOOTPRINT_LIMITS["max_css_bytes"]: expected_violations.append("resource-byte-budget-exceeded:css") if integers["largest_single_asset_bytes"] > FIXED_FOOTPRINT_LIMITS["max_single_asset_bytes"]: expected_violations.append("single-asset-budget-exceeded") if violation_ids != expected_violations or footprint["within_fixed_footprint_limits"] is not ( not expected_violations ): raise WebsiteRuntimeOptimisationError(f"{label} budget result is inconsistent.") if projected: saving = footprint["saving_bytes"] if isinstance(saving, bool) or not isinstance(saving, int) or not 1 <= saving <= MAX_TREE_BYTES: raise WebsiteRuntimeOptimisationError(f"{label}.saving_bytes must be a positive integer.") return footprint
def _project_runtime( retained_rows: Sequence[Mapping[str, object]], transformations: Sequence[Mapping[str, Any]],) -> list[dict[str, object]]: current = {str(row["path"]): dict(row) for row in retained_rows} projected = dict(current) for row in transformations: source_path = str(row["source_path"]) source = current.get(source_path) if ( source is None or source["sha256"] != row["source_sha256"] or source["bytes"] != row["source_bytes"] ): raise WebsiteRuntimeOptimisationError( "Transformation does not bind an exact retained runtime file." ) projected.pop(source_path, None) if row["action"] == "replace-runtime-bytes": output_path = str(row["projected_runtime_path"]) if output_path in projected: raise WebsiteRuntimeOptimisationError( "Projected runtime output collides with another retained path." ) projected[output_path] = { "path": output_path, "bytes": int(row["projected_bytes"]), "sha256": str(row["projected_sha256"]), } if not projected: raise WebsiteRuntimeOptimisationError("Projected runtime closure may not be empty.") return [projected[path] for path in sorted(projected)]
def _tool_binding(root: Path, relative: Path, expected: str, *, production: bool) -> dict[str, object]: path = root / relative if production: raw, _ = _read_exact_file( path, expected, label=relative.as_posix(), max_bytes=MAX_REVIEWED_SOURCE_BYTES, ) observed = _sha256_bytes(raw) else: observed = expected if observed != expected: raise WebsiteRuntimeOptimisationError(f"Reviewed source binding drifted: {relative.as_posix()}.") return {"path": relative.as_posix(), "sha256": observed}
def _require_launcher_attestation(root: Path) -> dict[str, Any]: attestation = globals().get("__aureon_runtime_optimisation_launcher_attestation__") if not isinstance(attestation, dict): raise WebsiteRuntimeOptimisationError( "Production compilation requires the isolated trusted launcher." ) expected_fields = { "launcher_path", "launcher_sha256", "planner_path", "planner_sha256", "isolated", "no_site", "dont_write_bytecode", } if set(attestation) != expected_fields: raise WebsiteRuntimeOptimisationError("Trusted launcher attestation is malformed.") launcher = _ordinary_file(root / TRUSTED_LAUNCHER_PATH, label="Runtime optimisation launcher") implementation = _ordinary_file(root / IMPLEMENTATION_PATH, label="Runtime optimisation compiler") if ( Path(str(attestation["launcher_path"])) != launcher or attestation["launcher_sha256"] != REVIEWED_TRUSTED_LAUNCHER_SHA256 or _sha256_bytes(launcher.read_bytes()) != REVIEWED_TRUSTED_LAUNCHER_SHA256 or Path(str(attestation["planner_path"])) != implementation or attestation["planner_sha256"] != _sha256_bytes(implementation.read_bytes()) or attestation["isolated"] is not True or attestation["no_site"] is not True or attestation["dont_write_bytecode"] is not True or not (sys.flags.isolated and sys.flags.no_site and sys.dont_write_bytecode) ): raise WebsiteRuntimeOptimisationError("Trusted launcher attestation does not bind this execution.") return attestation
def _controlled_input(root: Path, path: Path, *, allowed_root: Path, label: str) -> Path: candidate = _ordinary_file(path, label=label) boundary = _ordinary_directory(root / allowed_root, label=f"{label} root") if candidate.parent != boundary: raise WebsiteRuntimeOptimisationError( f"{label} must be an explicitly named file in {allowed_root.as_posix()}." ) return candidate
def _compile_runtime_optimisation_proposal( *, repo_root: Path, source_plan_path: Path, source_plan_sha256: str, measurement_path: Path, measurement_sha256: str, acceptance_contract_path: Path, acceptance_contract_sha256: str, run_id: str | None = None, now: datetime | None = None, production: bool,) -> dict[str, Any]: root = Path(os.path.abspath(repo_root)) launcher_attestation: Mapping[str, Any] | None = None if production: raise WebsiteRuntimeOptimisationError(PRODUCTION_MEASUREMENT_PROVENANCE_STATE) resolved_now = (now or datetime.now(UTC)).astimezone(UTC) resolved_run_id = _safe_id(run_id or uuid.uuid4().hex, label="proposal run_id") plan_file = _controlled_input( root, source_plan_path, allowed_root=SOURCE_PLAN_ROOT, label="Source rationalisation plan", ) evidence_file = _controlled_input( root, measurement_path, allowed_root=MEASUREMENT_ROOT, label="Runtime optimisation measurement evidence", ) acceptance_file = _ordinary_file(acceptance_contract_path, label="Browser acceptance contract") if acceptance_file != Path(os.path.abspath(root / ACCEPTANCE_CONTRACT_PATH)): raise WebsiteRuntimeOptimisationError("Browser acceptance contract path is not canonical.") plan_raw, plan_identity = _read_exact_file( plan_file, source_plan_sha256, label="Source rationalisation plan" ) evidence_raw, evidence_identity = _read_exact_file( evidence_file, measurement_sha256, label="Runtime optimisation measurement evidence", ) acceptance_raw, acceptance_identity = _read_exact_file( acceptance_file, acceptance_contract_sha256, label="Browser acceptance contract", ) plan = _require_source_plan(_strict_json(plan_raw, label="Source rationalisation plan"), now=resolved_now) evidence = require_measurement_evidence( _strict_json(evidence_raw, label="Runtime optimisation measurement evidence") ) _require_fresh(evidence["measured_at"], now=resolved_now, label="measurement measured_at") retained = plan["retained_projection"] acceptance = _require_acceptance_contract( _strict_json(acceptance_raw, label="Browser acceptance contract"), retained=retained, reviewed_payload_required=production, ) expected_source_binding = { "path": plan_file.relative_to(root).as_posix(), "file_sha256": source_plan_sha256, "payload_sha256": plan["payload_sha256"], "plan_run_id": plan["run_id"], "source_tree_sha256": plan["source_binding"]["tree_sha256"], "retained_tree_sha256": retained["tree_sha256"], "retained_manifest_sha256": retained["manifest_sha256"], } expected_acceptance_binding = { "path": ACCEPTANCE_CONTRACT_PATH.as_posix(), "file_sha256": acceptance_contract_sha256, "payload_sha256": acceptance["payloadSha256"], "contract_id": acceptance["contractId"], } if evidence["source_plan_binding"] != expected_source_binding: raise WebsiteRuntimeOptimisationError("Measurement evidence does not bind this exact source plan.") if evidence["acceptance_contract_binding"] != expected_acceptance_binding: raise WebsiteRuntimeOptimisationError( "Measurement evidence does not bind this exact browser contract." ) methodology = evidence["methodology"] measurement_tool_path = root / str(methodology["tool_path"]) _read_exact_file( measurement_tool_path, str(methodology["tool_sha256"]), label="Reviewed runtime measurement tool", max_bytes=MAX_REVIEWED_SOURCE_BYTES, ) current_source_rows = _manifest(root / SOURCE_ROOT) if current_source_rows != plan["source_binding"]["files"]: raise WebsiteRuntimeOptimisationError("Canonical website source changed after source planning.") retained_rows = _manifest_rows(retained["files"], label="retained runtime projection") projected_rows = _project_runtime(retained_rows, evidence["transformations"]) current_runtime = _footprint(retained_rows) projected_runtime = _footprint(projected_rows) projected_runtime["saving_bytes"] = current_runtime["total_bytes"] - projected_runtime["total_bytes"] implementation_sha256 = ( str(launcher_attestation["planner_sha256"]) if launcher_attestation is not None else _sha256_bytes(Path(__file__).read_bytes()) ) execution_binding = { "mode": "isolated-fixed-production" if production else "test-fixture-no-production-authority", "repo_root": str(root), "implementation": _tool_binding( root, IMPLEMENTATION_PATH, implementation_sha256, production=production, ), "trusted_launcher": _tool_binding( root, TRUSTED_LAUNCHER_PATH, REVIEWED_TRUSTED_LAUNCHER_SHA256, production=production ), "source_planner": _tool_binding( root, SOURCE_PLANNER_PATH, REVIEWED_SOURCE_PLANNER_SHA256, production=production ), "source_planner_launcher": _tool_binding( root, SOURCE_PLANNER_LAUNCHER_PATH, REVIEWED_SOURCE_PLANNER_LAUNCHER_SHA256, production=production ), "release_builder": _tool_binding( root, RELEASE_BUILDER_PATH, REVIEWED_RELEASE_BUILDER_SHA256, production=production ), "motion_policy": _tool_binding( root, MOTION_POLICY_PATH, REVIEWED_MOTION_POLICY_SHA256, production=production ), "secure_writer": _tool_binding( root, SECURE_WRITER_PATH, REVIEWED_SECURE_WRITER_SHA256, production=production ), "measurement_tool": _tool_binding( root, Path(str(methodology["tool_path"])), str(methodology["tool_sha256"]), production=production, ), "commands_executed": False, "transformations_executed": False, "production_writable": production, } proposal: dict[str, Any] = { "schema": PROPOSAL_SCHEMA, "generated_at": _utc_iso(resolved_now), "run_id": resolved_run_id, "state": "proposal-only", "source_plan_binding": expected_source_binding, "measurement_binding": { "path": evidence_file.relative_to(root).as_posix(), "file_sha256": measurement_sha256, "payload_sha256": evidence["payload_sha256"], "measurement_run_id": evidence["run_id"], }, "acceptance_contract_binding": expected_acceptance_binding, "current_runtime": current_runtime, "projected_runtime": projected_runtime, "transformations": [dict(row) for row in evidence["transformations"]], "acceptance_requirements": [ {"id": identifier, "required": True, "status": "blocked-not-run", "passed": False} for identifier in ACCEPTANCE_REQUIREMENT_IDS ], "execution_binding": execution_binding, "eligible_for_next_local_gate": False, "authority": dict(NO_AUTHORITY), } proposal["payload_sha256"] = _json_sha256(proposal) require_runtime_optimisation_proposal(proposal) # Final current-source and exact-input replay closes the pre-write TOCTOU window. if _manifest(root / SOURCE_ROOT) != current_source_rows: raise WebsiteRuntimeOptimisationError("Canonical source changed during proposal compilation.") for path, raw, identity, label in ( (plan_file, plan_raw, plan_identity, "Source rationalisation plan"), (evidence_file, evidence_raw, evidence_identity, "Measurement evidence"), (acceptance_file, acceptance_raw, acceptance_identity, "Browser acceptance contract"), ): after = path.lstat() if ( not _same_identity(identity, after) or int(after.st_size) != len(raw) or _sha256_bytes(path.read_bytes()) != _sha256_bytes(raw) ): raise WebsiteRuntimeOptimisationError(f"{label} changed during proposal compilation.") if production: for binding in execution_binding.values(): if isinstance(binding, Mapping) and set(binding) == {"path", "sha256"}: _tool_binding( root, Path(str(binding["path"])), str(binding["sha256"]), production=True, ) return proposal
def compile_runtime_optimisation_proposal( *, source_plan_path: Path, source_plan_sha256: str, measurement_path: Path, measurement_sha256: str, acceptance_contract_path: Path, acceptance_contract_sha256: str, run_id: str | None = None,) -> dict[str, Any]: """Compile one canonical proposal; production requires the isolated launcher."""
return _compile_runtime_optimisation_proposal( repo_root=_canonical_repo_root(), source_plan_path=source_plan_path, source_plan_sha256=source_plan_sha256, measurement_path=measurement_path, measurement_sha256=measurement_sha256, acceptance_contract_path=acceptance_contract_path, acceptance_contract_sha256=acceptance_contract_sha256, run_id=run_id, production=True, )
def require_runtime_optimisation_proposal(value: object) -> dict[str, Any]: """Validate the immutable proposal contract without treating it as execution proof."""
proposal = _exact_object(value, _PROPOSAL_FIELDS, label="Runtime optimisation proposal") if proposal.get("schema") != PROPOSAL_SCHEMA or proposal.get("state") != "proposal-only": raise WebsiteRuntimeOptimisationError("Runtime optimisation proposal schema or state is invalid.") _payload_hash(proposal) _safe_id(proposal.get("run_id"), label="proposal run_id") _parse_utc(proposal.get("generated_at"), label="proposal generated_at") if proposal.get("authority") != NO_AUTHORITY or proposal.get("eligible_for_next_local_gate") is not False: raise WebsiteRuntimeOptimisationError("Runtime optimisation proposal grants downstream authority.") _require_source_plan_binding(proposal.get("source_plan_binding"), label="Proposal source-plan binding") measurement_binding = _exact_object( proposal.get("measurement_binding"), _MEASUREMENT_BINDING_FIELDS, label="Proposal measurement binding", ) _safe_relative_path(measurement_binding["path"]) _require_sha256(measurement_binding["file_sha256"], label="measurement_binding.file_sha256") _require_sha256(measurement_binding["payload_sha256"], label="measurement_binding.payload_sha256") _safe_id(measurement_binding["measurement_run_id"], label="measurement_binding.measurement_run_id") _require_acceptance_binding( proposal.get("acceptance_contract_binding"), label="Proposal acceptance-contract binding", ) current_runtime = _require_footprint( proposal.get("current_runtime"), label="Current runtime footprint", projected=False ) projected_runtime = _require_footprint( proposal.get("projected_runtime"), label="Projected runtime footprint", projected=True ) if ( projected_runtime["total_bytes"] >= current_runtime["total_bytes"] or projected_runtime["saving_bytes"] != current_runtime["total_bytes"] - projected_runtime["total_bytes"] ): raise WebsiteRuntimeOptimisationError("Projected runtime saving arithmetic is inconsistent.") requirements = proposal.get("acceptance_requirements") if not isinstance(requirements, list) or [ row.get("id") for row in requirements if isinstance(row, Mapping) ] != list(ACCEPTANCE_REQUIREMENT_IDS): raise WebsiteRuntimeOptimisationError( "Runtime optimisation proposal acceptance contract is incomplete." ) for index, row in enumerate(requirements): requirement = _exact_object( row, _ACCEPTANCE_REQUIREMENT_FIELDS, label=f"Acceptance requirement[{index}]", ) if ( requirement["required"] is not True or requirement["status"] != "blocked-not-run" or requirement["passed"] is not False ): raise WebsiteRuntimeOptimisationError( "Runtime optimisation proposal fabricates acceptance evidence." ) execution = _exact_object( proposal.get("execution_binding"), _EXECUTION_BINDING_FIELDS, label="Proposal execution binding", ) if ( execution["mode"] != "test-fixture-no-production-authority" or not isinstance(execution["repo_root"], str) or not execution["repo_root"] or execution["commands_executed"] is not False or execution["transformations_executed"] is not False or execution["production_writable"] is not False ): raise WebsiteRuntimeOptimisationError("Runtime optimisation proposal claims execution.") for field in ( "implementation", "trusted_launcher", "source_planner", "source_planner_launcher", "release_builder", "motion_policy", "secure_writer", "measurement_tool", ): binding = _exact_object(execution[field], _TOOL_BINDING_FIELDS, label=f"execution_binding.{field}") _safe_relative_path(binding["path"]) _require_sha256(binding["sha256"], label=f"execution_binding.{field}.sha256") _require_transformation_rows(proposal.get("transformations")) return proposal
def _load_secure_writer(root: Path) -> ModuleType: writer = _ordinary_file(root / SECURE_WRITER_PATH, label="Reviewed immutable-artifact writer") raw, _ = _read_exact_file( writer, REVIEWED_SECURE_WRITER_SHA256, label="Reviewed immutable-artifact writer", max_bytes=MAX_REVIEWED_SOURCE_BYTES, ) module = ModuleType("_aureon_runtime_optimisation_secure_writer") module.__file__ = str(writer) module.__package__ = None sys.modules[module.__name__] = module try: exec(compile(raw, str(writer), "exec", dont_inherit=True), module.__dict__) # noqa: S102 except Exception: sys.modules.pop(module.__name__, None) raise if not callable(getattr(module, "write_new_file", None)): raise WebsiteRuntimeOptimisationError("Reviewed immutable writer lacks write_new_file.") return module
def _revalidate_proposal_inputs(root: Path, proposal: Mapping[str, Any]) -> None: """Replay exact proposal inputs immediately before the immutable write."""
source_binding = proposal.get("source_plan_binding") measurement_binding = proposal.get("measurement_binding") acceptance_binding = proposal.get("acceptance_contract_binding") execution = proposal.get("execution_binding") if not all( isinstance(item, Mapping) for item in (source_binding, measurement_binding, acceptance_binding, execution) ): raise WebsiteRuntimeOptimisationError("Proposal input bindings are malformed.") assert isinstance(source_binding, Mapping) assert isinstance(measurement_binding, Mapping) assert isinstance(acceptance_binding, Mapping) assert isinstance(execution, Mapping) plan_raw, _ = _read_exact_file( root / str(source_binding["path"]), str(source_binding["file_sha256"]), label="Source plan pre-write replay", ) evidence_raw, _ = _read_exact_file( root / str(measurement_binding["path"]), str(measurement_binding["file_sha256"]), label="Measurement evidence pre-write replay", ) acceptance_raw, _ = _read_exact_file( root / str(acceptance_binding["path"]), str(acceptance_binding["file_sha256"]), label="Browser acceptance contract pre-write replay", ) plan = _require_source_plan( _strict_json(plan_raw, label="Source plan pre-write replay"), now=datetime.now(UTC), ) evidence = require_measurement_evidence( _strict_json(evidence_raw, label="Measurement evidence pre-write replay") ) _require_fresh(evidence["measured_at"], now=datetime.now(UTC), label="measurement measured_at") _require_acceptance_contract( _strict_json(acceptance_raw, label="Browser acceptance contract pre-write replay"), retained=plan["retained_projection"], ) if _manifest(root / SOURCE_ROOT) != plan["source_binding"]["files"]: raise WebsiteRuntimeOptimisationError("Canonical source changed before proposal write.") for binding in execution.values(): if isinstance(binding, Mapping) and set(binding) == {"path", "sha256"}: _tool_binding( root, Path(str(binding["path"])), str(binding["sha256"]), production=True, )
def write_runtime_optimisation_proposal( *, source_plan_path: Path, source_plan_sha256: str, measurement_path: Path, measurement_sha256: str, acceptance_contract_path: Path, acceptance_contract_sha256: str, output_path: Path, run_id: str | None = None,) -> dict[str, Any]: """Compile and exclusively write one proposal under the controlled artifact root."""
root = _canonical_repo_root() proposal = compile_runtime_optimisation_proposal( source_plan_path=source_plan_path, source_plan_sha256=source_plan_sha256, measurement_path=measurement_path, measurement_sha256=measurement_sha256, acceptance_contract_path=acceptance_contract_path, acceptance_contract_sha256=acceptance_contract_sha256, run_id=run_id, ) output = Path(os.path.abspath(output_path)) parent = _ordinary_directory(root / PROPOSAL_ROOT, label="Runtime optimisation proposal root") if output.parent != parent or output.suffix.lower() != ".json": raise WebsiteRuntimeOptimisationError( "Proposal output must be a new JSON file in the controlled proposal root." ) writer = _load_secure_writer(root) _revalidate_proposal_inputs(root, proposal) payload = ( json.dumps(proposal, indent=2, sort_keys=True, ensure_ascii=False, allow_nan=False).encode("utf-8") + b"\n" ) writer.write_new_file(output, payload) if output.read_bytes() != payload: raise WebsiteRuntimeOptimisationError("Immutable proposal failed exact read-back.") return proposal
def build_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser(prog="website-runtime-optimisation") parser.add_argument("--source-plan", type=Path, required=True) parser.add_argument("--source-plan-sha256", required=True) parser.add_argument("--measurement", type=Path, required=True) parser.add_argument("--measurement-sha256", required=True) parser.add_argument("--acceptance-contract", type=Path, required=True) parser.add_argument("--acceptance-contract-sha256", required=True) parser.add_argument("--output", type=Path, required=True) parser.add_argument("--run-id") return parser
def main(argv: Sequence[str] | None = None) -> int: args = build_parser().parse_args(argv) try: proposal = write_runtime_optimisation_proposal( source_plan_path=args.source_plan, source_plan_sha256=args.source_plan_sha256, measurement_path=args.measurement, measurement_sha256=args.measurement_sha256, acceptance_contract_path=args.acceptance_contract, acceptance_contract_sha256=args.acceptance_contract_sha256, output_path=args.output, run_id=args.run_id, ) except (WebsiteRuntimeOptimisationError, OSError) as exc: print(f"blocked: {exc}", file=sys.stderr) return 2 print(json.dumps(proposal, sort_keys=True, separators=(",", ":"))) return 0
__all__ = [ "ACCEPTANCE_CONTRACT_SCHEMA", "ACCEPTANCE_REQUIREMENT_IDS", "FIXED_FOOTPRINT_LIMITS", "MEASUREMENT_AUTHORITY", "MEASUREMENT_SCHEMA", "NO_AUTHORITY", "PROPOSAL_SCHEMA", "WebsiteRuntimeOptimisationError", "compile_runtime_optimisation_proposal", "require_measurement_evidence", "require_runtime_optimisation_proposal", "write_runtime_optimisation_proposal",]
if __name__ == "__main__": raise SystemExit(main())1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915"""Read-only planning and owner-decision validation for website source projection.
This module deliberately stops before staging. It invokes the reviewed Home.plrelease builder only in ``-VerifyOnly`` mode, proves that its retained paths andthe omitted paths form an exact partition of the unchanged canonical website,and records a proposal with no mutation authority. A separately supplied,short-lived named-owner decision can then be validated against that exact plan.
There is no source-copy, file-removal, candidate, canonical-promotion, package,credential, network, or deployment entrypoint here. Durable artifacts arecreated once through :mod:`aureon.operator.secure_immutable_artifact`."""
from __future__ import annotations
import argparseimport base64import hashlibimport jsonimport osimport reimport statimport subprocessimport sysimport threadingimport uuidfrom collections.abc import Callable, Mapping, Sequencefrom dataclasses import dataclassfrom datetime import UTC, datetime, timedeltafrom pathlib import Pathfrom types import MappingProxyType, ModuleTypefrom typing import Any, Finalfrom urllib.parse import urlparse
PLAN_SCHEMA = "aureon.website-source-rationalisation-plan.v1"OWNER_DECISION_SCHEMA = "aureon.website-source-rationalisation-owner-decision.v1"OWNER_VALIDATION_SCHEMA = "aureon.website-source-rationalisation-owner-validation.v1"
SOURCE_ROOT = Path("website")IMPLEMENTATION_PATH = Path("aureon/operator/website_source_rationalisation.py")TRUSTED_LAUNCHER_PATH = Path("tools/run-website-source-rationalisation.py")RELEASE_BUILDER_PATH = Path("tools/build-homepl-v28-narrow-release.ps1")MOTION_POLICY_PATH = Path("aureon/operator/design_candidate_motion_policy_compiler.py")SECURE_WRITER_PATH = Path("aureon/operator/secure_immutable_artifact.py")ARTIFACT_ROOT = Path("artifacts/website-operator/source-rationalisations")PLAN_ROOT = ARTIFACT_ROOT / "plans"OWNER_DECISION_ROOT = ARTIFACT_ROOT / "owner-decisions"VALIDATION_ROOT = ARTIFACT_ROOT / "validations"RELEASE = "V29"POWERSHELL_EXECUTABLE = Path("C:/Windows/System32/WindowsPowerShell/v1.0/powershell.exe")REVIEWED_POWERSHELL_SHA256 = "3247BCFD60F6DD25F34CB74B5889AB10EF1B3EC72B4D4B3D95B5B25B534560B8"REVIEWED_RELEASE_BUILDER_SHA256 = "0C42EA5FEB59DCE1583A7731189BF91223AB0F6B5DD333936BCA7E9F65438204"REVIEWED_MOTION_POLICY_SHA256 = "2685C98B8D0199A30B09B3983E7F1C48DE65EF64D76E4B9900BE8F503F251A73"REVIEWED_SECURE_WRITER_SHA256 = "D704D691A4D3221E096A470884E5D1293EA663164BB6740FE5BDD26D32B4DB81"REVIEWED_TRUSTED_LAUNCHER_SHA256 = "827D4112E6C6042B4931E987237E1E7B6035B5A147373CDE202D9DC95184B009"FIXED_RUNNER_ID = "python-subprocess-fixed-powershell-sanitized-environment-v1"SANITIZED_ENVIRONMENT_POLICY_ID = "windows-powershell-minimal-no-inherited-environment-v1"TEST_FIXTURE_RUNNER_ID = "injected-test-fixture-no-production-authority"
MAX_OWNER_DECISION_AGE = timedelta(hours=4)MAX_FILES = 5_000MAX_TREE_BYTES = 512 * 1024 * 1024MAX_JSON_BYTES = 4 * 1024 * 1024MAX_PROCESS_OUTPUT_BYTES = 4 * 1024 * 1024MAX_REVIEWED_SOURCE_BYTES = 4 * 1024 * 1024PROCESS_TIMEOUT_SECONDS = 120
FIXED_FOOTPRINT_LIMITS: Final[Mapping[str, int]] = MappingProxyType( { "max_total_bytes": 4_500_000, "max_image_bytes": 2_200_000, "max_css_bytes": 350_000, "max_single_asset_bytes": 500_000, })
PLAN_AUTHORITY: Final[dict[str, object]] = { "scope": "read-only exact public-runtime source projection proposal", "canonical_website_mutation": "none", "physical_source_file_removal": "none", "staging_authority": "none", "candidate_authority": "none", "package_authority": "none", "release_eligible": False, "deployment_authority": "none", "credential_access": "none", "network_access": "none",}
OWNER_DECISION_AUTHORITY: Final[dict[str, object]] = { "scope": "review-only acknowledgement of one exact source-projection proposal", "canonical_website_mutation": "none", "physical_source_file_removal": "none", "staging_authority": "none", "candidate_mutation": "none", "candidate_removal_authority": "none", "package_authority": "none", "release_eligible": False, "deployment_authority": "none", "credential_access": "none", "network_access": "none",}
VALIDATION_AUTHORITY: Final[dict[str, object]] = { "scope": "read-only validation of one exact owner source-rationalisation decision", "canonical_website_mutation": "none", "physical_source_file_removal": "none", "staging_executed": False, "staging_authority": "none", "candidate_authority": "none", "package_authority": "none", "release_eligible": False, "deployment_authority": "none", "credential_access": "none", "network_access": "none",}
_IMAGE_SUFFIXES = frozenset({".apng", ".avif", ".gif", ".ico", ".jpeg", ".jpg", ".png", ".svg", ".webp"})_FONT_SUFFIXES = frozenset({".eot", ".otf", ".ttf", ".woff", ".woff2"})_MEDIA_SUFFIXES = frozenset({".m4a", ".mov", ".mp3", ".mp4", ".oga", ".ogg", ".ogv", ".wav", ".webm"})
_SHA256 = re.compile(r"[A-F0-9]{64}\Z")_RUN_ID = re.compile(r"[a-z0-9][a-z0-9._-]{2,80}\Z")_GENERIC_APPROVERS = frozenset( { "admin", "ai", "aureon os", "codex", "operator", "owner", "system", "user", })
_MANIFEST_ROW_FIELDS = frozenset({"path", "bytes", "sha256"})_OMITTED_ROW_FIELDS = frozenset({"path", "bytes", "sha256", "reason"})_SUMMARY_FIELDS = frozenset({"tree_sha256", "manifest_sha256", "file_count", "total_bytes", "files"})_OMITTED_FIELDS = frozenset({"manifest_sha256", "file_count", "total_bytes", "files"})_SOURCE_FIELDS = frozenset({"root", *_SUMMARY_FIELDS})_CLOSURE_FIELDS = frozenset( { "tool_path", "tool_sha256", "command", "release", "verify_only", "state", "entry_files", "local_reference_count", "missing_local_reference_count", "missing_fragment_reference_count", "remote_origins", "retained_manifest_sha256", })_BUDGET_FIELDS = frozenset( { "policy_path", "policy_sha256", "max_total_bytes", "projected_total_bytes", "total_overage_bytes", "max_image_bytes", "projected_image_bytes", "image_overage_bytes", "max_css_bytes", "projected_css_bytes", "css_overage_bytes", "max_single_asset_bytes", "projected_largest_single_asset_bytes", "largest_single_asset_path", "largest_single_asset_category", "single_asset_overage_bytes", "violation_ids", "within_fixed_footprint_limits", "state", "eligible_for_next_local_gate", "candidate_qa_authority", })_EXECUTION_FIELDS = frozenset( { "mode", "repo_root", "implementation_path", "implementation_sha256", "trusted_launcher_path", "reviewed_trusted_launcher_sha256", "launcher_attested", "release_builder_path", "reviewed_release_builder_sha256", "powershell_path", "reviewed_powershell_sha256", "motion_policy_path", "reviewed_motion_policy_sha256", "secure_writer_path", "reviewed_secure_writer_sha256", "runner_id", "environment_policy_id", "environment_sha256", "production_writable", })_PLAN_FIELDS = frozenset( { "schema", "generated_at", "run_id", "state", "source_binding", "closure_binding", "retained_projection", "omitted_projection", "motion_budget_projection", "execution_binding", "authority", "payload_sha256", })_DECISION_FIELDS = frozenset( { "schema", "decision", "scope", "plan_run_id", "plan_file_sha256", "plan_payload_sha256", "source_tree_sha256", "retained_tree_sha256", "omitted_manifest_sha256", "acknowledged_at", "expires_at", "acknowledged_by", "note", "authority", })_VALIDATION_FIELDS = frozenset( { "schema", "validated_at", "state", "passed", "release_eligible", "authority", "plan", "decision", "checks", "next_gate", "payload_sha256", })OWNER_VALIDATION_CHECK_IDS: Final[tuple[str, ...]] = ( "exact-owner-decision-contract", "exact-plan-binding", "fresh-owner-decision", "current-plan-inputs", "non-authoritative-boundary",)
class WebsiteSourceRationalisationError(ValueError): """A source projection or owner decision is unsafe, stale, or malformed."""
@dataclass(frozen=True)class CommandResult: """Bounded result from the fixed read-only closure command."""
returncode: int stdout: bytes stderr: bytes
CommandRunner = Callable[[Sequence[str], Path, bytes], CommandResult]
def _canonical_json_bytes(value: object) -> bytes: try: return json.dumps( value, sort_keys=True, separators=(",", ":"), ensure_ascii=False, allow_nan=False, ).encode("utf-8") except (TypeError, ValueError) as exc: raise WebsiteSourceRationalisationError( "Source-rationalisation evidence must contain only finite standard JSON values." ) from exc
def _json_sha256(value: object) -> str: return hashlib.sha256(_canonical_json_bytes(value)).hexdigest().upper()
def _sha256_bytes(value: bytes) -> str: return hashlib.sha256(value).hexdigest().upper()
def _sha256_file(path: Path) -> str: digest = hashlib.sha256() with path.open("rb") as stream: while block := stream.read(1024 * 1024): digest.update(block) return digest.hexdigest().upper()
def _same_file_identity(left: os.stat_result, right: os.stat_result) -> bool: return ( stat.S_IFMT(left.st_mode) == stat.S_IFMT(right.st_mode) and int(left.st_dev) == int(right.st_dev) and int(left.st_ino) == int(right.st_ino) )
def _read_reviewed_source_bytes(path: Path, expected_sha256: str, *, label: str) -> bytes: source = _regular_file(path, label=label) before = source.lstat() if int(before.st_size) > MAX_REVIEWED_SOURCE_BYTES: raise WebsiteSourceRationalisationError(f"{label} exceeds its reviewed source bound.") try: with source.open("rb") as stream: opened = os.fstat(stream.fileno()) if not _same_file_identity(before, opened): raise WebsiteSourceRationalisationError(f"{label} changed before its handle opened.") payload = stream.read(MAX_REVIEWED_SOURCE_BYTES + 1) except OSError as exc: raise WebsiteSourceRationalisationError(f"{label} could not be read safely.") from exc after = source.lstat() if ( len(payload) > MAX_REVIEWED_SOURCE_BYTES or not _same_file_identity(opened, after) or int(after.st_size) != len(payload) or _sha256_bytes(payload) != expected_sha256 ): raise WebsiteSourceRationalisationError(f"{label} does not match its reviewed source pin.") return payload
def _utc_iso(value: datetime | None = None) -> str: instant = (value or datetime.now(UTC)).astimezone(UTC) return instant.isoformat(timespec="seconds").replace("+00:00", "Z")
def _parse_utc(value: object, *, label: str) -> datetime: if not isinstance(value, str) or not value or not value.endswith("Z"): raise WebsiteSourceRationalisationError(f"{label} must be canonical UTC ending in Z.") try: parsed = datetime.fromisoformat(value[:-1] + "+00:00").astimezone(UTC) except ValueError as exc: raise WebsiteSourceRationalisationError(f"{label} must be valid ISO-8601.") from exc if _utc_iso(parsed) != value: raise WebsiteSourceRationalisationError(f"{label} must use second-precision canonical UTC.") return parsed
def _safe_run_id(value: object, *, label: str = "run_id") -> str: if not isinstance(value, str) or _RUN_ID.fullmatch(value) is None: raise WebsiteSourceRationalisationError(f"{label} is not a safe stable identifier.") return value
def _safe_relative_path(value: object) -> str: if not isinstance(value, str) or not value or "\\" in value or "\x00" in value: raise WebsiteSourceRationalisationError("Manifest path is not canonical.") candidate = Path(value) if candidate.is_absolute() or candidate.drive or value.startswith("/"): raise WebsiteSourceRationalisationError("Manifest path must be relative.") parts = value.split("/") if any(not part or part in {".", ".."} or ":" in part for part in parts): raise WebsiteSourceRationalisationError("Manifest path contains an unsafe component.") canonical = candidate.as_posix() if canonical != value: raise WebsiteSourceRationalisationError("Manifest path is not canonical.") return value
def _is_link_or_reparse(path: Path) -> bool: try: details = path.lstat() except OSError: return False attributes = int(getattr(details, "st_file_attributes", 0) or 0) reparse_flag = int(getattr(stat, "FILE_ATTRIBUTE_REPARSE_POINT", 0) or 0) return path.is_symlink() or bool(reparse_flag and attributes & reparse_flag)
def _regular_directory(path: Path, *, label: str) -> Path: lexical = Path(os.path.abspath(path)) for component in (lexical, *lexical.parents): if not component.exists() and not component.is_symlink(): continue if _is_link_or_reparse(component): raise WebsiteSourceRationalisationError(f"{label} may not traverse a link or reparse point.") if not lexical.is_dir(): raise WebsiteSourceRationalisationError(f"{label} must be an existing ordinary directory.") return lexical
def _regular_file(path: Path, *, label: str, require_single_link: bool = True) -> Path: lexical = Path(os.path.abspath(path)) for component in (lexical, *lexical.parents): if not component.exists() and not component.is_symlink(): continue if _is_link_or_reparse(component): raise WebsiteSourceRationalisationError(f"{label} may not traverse a link or reparse point.") if not lexical.is_file(): raise WebsiteSourceRationalisationError(f"{label} must be an existing ordinary file.") if require_single_link and int(lexical.stat().st_nlink) != 1: raise WebsiteSourceRationalisationError(f"{label} must have exactly one hard link.") return lexical
def _find_repo_root(start: Path | None = None) -> Path: candidate = (start or Path.cwd()).resolve() for root in (candidate, *candidate.parents): if (root / "pyproject.toml").is_file() and (root / SOURCE_ROOT).is_dir(): return root raise WebsiteSourceRationalisationError( "Could not locate an Aureon repository with pyproject.toml and website/." )
def _canonical_repo_root() -> Path: implementation = _regular_file(Path(__file__), label="Loaded source-rationalisation implementation") root = implementation.parents[2] if implementation != Path(os.path.abspath(root / IMPLEMENTATION_PATH)): raise WebsiteSourceRationalisationError( "Loaded source-rationalisation implementation is outside its exact canonical path." ) discovered = _find_repo_root(root) if discovered != root: raise WebsiteSourceRationalisationError("Loaded implementation has no exact canonical repository.") return root
def _require_trusted_launcher_attestation(root: Path) -> None: attestation = globals().get("__aureon_trusted_launcher_attestation__") implementation = _regular_file( root / IMPLEMENTATION_PATH, label="Attested source-rationalisation implementation", ) launcher = _regular_file(root / TRUSTED_LAUNCHER_PATH, label="Trusted isolated launcher") _read_reviewed_source_bytes( launcher, REVIEWED_TRUSTED_LAUNCHER_SHA256, label="Trusted isolated launcher", ) expected = { "launcher_path": str(launcher), "launcher_sha256": REVIEWED_TRUSTED_LAUNCHER_SHA256, "planner_path": str(implementation), "planner_sha256": _sha256_file(implementation), "isolated": True, "no_site": True, "dont_write_bytecode": True, } if not isinstance(attestation, dict) or attestation != expected: raise WebsiteSourceRationalisationError( "Production planner requires exact isolated-launcher attestation." )
def _manifest(root: Path) -> list[dict[str, object]]: source = _regular_directory(root, label="Canonical website source") source_real = source.resolve(strict=True) pending = [source] files: list[Path] = [] total_bytes = 0 seen_casefold: set[str] = set() while pending: directory = pending.pop() try: directory.resolve(strict=True).relative_to(source_real) entries = sorted(os.scandir(directory), key=lambda item: item.name) except (OSError, ValueError) as exc: raise WebsiteSourceRationalisationError( "Canonical website source changed or escaped while enumerated." ) from exc for entry in entries: path = Path(entry.path) if _is_link_or_reparse(path): raise WebsiteSourceRationalisationError( f"Canonical website source contains a link or reparse point: {path}" ) details = path.lstat() try: path.resolve(strict=True).relative_to(source_real) except (OSError, ValueError) as exc: raise WebsiteSourceRationalisationError( f"Canonical website source path escaped its root: {path}" ) from exc if stat.S_ISDIR(details.st_mode): pending.append(path) continue if not stat.S_ISREG(details.st_mode) or int(details.st_nlink) != 1: raise WebsiteSourceRationalisationError( f"Canonical website source files must be ordinary and single-link: {path}" ) relative = _safe_relative_path(path.relative_to(source).as_posix()) folded = relative.casefold() if folded in seen_casefold: raise WebsiteSourceRationalisationError( f"Canonical website source contains a case-colliding path: {relative}" ) seen_casefold.add(folded) files.append(path) total_bytes += int(details.st_size) if len(files) > MAX_FILES or total_bytes > MAX_TREE_BYTES: raise WebsiteSourceRationalisationError("Canonical website source exceeds planning bounds.") rows = [ { "path": path.relative_to(source).as_posix(), "bytes": int(path.stat().st_size), "sha256": _sha256_file(path), } for path in sorted(files, key=lambda item: item.relative_to(source).as_posix()) ] return rows
def _manifest_index( rows: object, *, label: str, require_sorted: bool = True,) -> dict[str, dict[str, object]]: if not isinstance(rows, list): raise WebsiteSourceRationalisationError(f"{label} must be a JSON array.") result: dict[str, dict[str, object]] = {} seen_casefold: set[str] = set() for item in rows: if not isinstance(item, dict) or set(item) != _MANIFEST_ROW_FIELDS: raise WebsiteSourceRationalisationError( f"{label} rows must contain exactly path, bytes, and sha256." ) path = _safe_relative_path(item.get("path")) byte_count = item.get("bytes") sha256 = item.get("sha256") if type(byte_count) is not int or byte_count < 0: raise WebsiteSourceRationalisationError(f"{label} byte count is invalid for {path}.") if not isinstance(sha256, str) or _SHA256.fullmatch(sha256) is None: raise WebsiteSourceRationalisationError(f"{label} SHA-256 is invalid for {path}.") if path in result or path.casefold() in seen_casefold: raise WebsiteSourceRationalisationError(f"{label} path is duplicated: {path}.") seen_casefold.add(path.casefold()) result[path] = {"path": path, "bytes": byte_count, "sha256": sha256} if require_sorted and list(result) != sorted(result): raise WebsiteSourceRationalisationError(f"{label} must be sorted by canonical path.") return result
def _footprint_category(path: str) -> str: suffix = Path(path).suffix.casefold() if suffix in {".html", ".htm"}: return "html" if suffix == ".css": return "css" if suffix in {".js", ".mjs", ".cjs"}: return "javascript" if suffix in _IMAGE_SUFFIXES: return "image" if suffix in _FONT_SUFFIXES: return "font" if suffix in _MEDIA_SUFFIXES: return "media" return "other"
def _manifest_byte_count(row: Mapping[str, object]) -> int: value = row.get("bytes") if type(value) is not int or value < 0: raise WebsiteSourceRationalisationError("Manifest row byte count is invalid.") return value
def _fixed_footprint_projection( rows: Sequence[Mapping[str, object]], *, policy_sha256: str,) -> dict[str, object]: categories = {"css": 0, "image": 0} largest_path = "" largest_category = "none" largest_bytes = 0 for row in rows: path = str(row["path"]) byte_count = _manifest_byte_count(row) category = _footprint_category(path) if category in categories: categories[category] += byte_count if category in {"image", "font", "media", "other"} and ( byte_count > largest_bytes or (byte_count == largest_bytes and path.casefold() < largest_path.casefold()) ): largest_path = path largest_category = category largest_bytes = byte_count
total = sum(_manifest_byte_count(row) for row in rows) maxima = { "total": FIXED_FOOTPRINT_LIMITS["max_total_bytes"], "image": FIXED_FOOTPRINT_LIMITS["max_image_bytes"], "css": FIXED_FOOTPRINT_LIMITS["max_css_bytes"], "single-asset": FIXED_FOOTPRINT_LIMITS["max_single_asset_bytes"], } observed = { "total": total, "image": categories["image"], "css": categories["css"], "single-asset": largest_bytes, } violation_ids = [ f"resource-byte-budget-exceeded:{category}" for category in ("total", "image", "css") if observed[category] > maxima[category] ] if observed["single-asset"] > maxima["single-asset"]: violation_ids.append("single-asset-budget-exceeded") return { "policy_path": MOTION_POLICY_PATH.as_posix(), "policy_sha256": policy_sha256, "max_total_bytes": maxima["total"], "projected_total_bytes": total, "total_overage_bytes": max(0, total - maxima["total"]), "max_image_bytes": maxima["image"], "projected_image_bytes": categories["image"], "image_overage_bytes": max(0, categories["image"] - maxima["image"]), "max_css_bytes": maxima["css"], "projected_css_bytes": categories["css"], "css_overage_bytes": max(0, categories["css"] - maxima["css"]), "max_single_asset_bytes": maxima["single-asset"], "projected_largest_single_asset_bytes": largest_bytes, "largest_single_asset_path": largest_path, "largest_single_asset_category": largest_category, "single_asset_overage_bytes": max(0, largest_bytes - maxima["single-asset"]), "violation_ids": violation_ids, "within_fixed_footprint_limits": not violation_ids, "state": "blocked-candidate-qa-not-run", "eligible_for_next_local_gate": False, "candidate_qa_authority": "none", }
def _execution_binding( root: Path, *, implementation_sha256: str, production: bool,) -> dict[str, object]: environment = _sanitized_environment() if production else {"test_fixture": "no-authority"} return { "mode": "fixed-production" if production else "injected-test-fixture", "repo_root": str(root), "implementation_path": IMPLEMENTATION_PATH.as_posix(), "implementation_sha256": implementation_sha256, "trusted_launcher_path": TRUSTED_LAUNCHER_PATH.as_posix(), "reviewed_trusted_launcher_sha256": REVIEWED_TRUSTED_LAUNCHER_SHA256, "launcher_attested": production, "release_builder_path": RELEASE_BUILDER_PATH.as_posix(), "reviewed_release_builder_sha256": REVIEWED_RELEASE_BUILDER_SHA256, "powershell_path": str(POWERSHELL_EXECUTABLE), "reviewed_powershell_sha256": REVIEWED_POWERSHELL_SHA256, "motion_policy_path": MOTION_POLICY_PATH.as_posix(), "reviewed_motion_policy_sha256": REVIEWED_MOTION_POLICY_SHA256, "secure_writer_path": SECURE_WRITER_PATH.as_posix(), "reviewed_secure_writer_sha256": REVIEWED_SECURE_WRITER_SHA256, "runner_id": FIXED_RUNNER_ID if production else TEST_FIXTURE_RUNNER_ID, "environment_policy_id": (SANITIZED_ENVIRONMENT_POLICY_ID if production else TEST_FIXTURE_RUNNER_ID), "environment_sha256": _json_sha256(environment), "production_writable": production, }
def _tree_sha256(rows: Sequence[Mapping[str, object]]) -> str: # Exact compatibility with design_candidate_control._tree_summary: # SHA-256(canonical JSON([{path, sha256, bytes}, ...])) in case-sensitive path order. ordered = [dict(row) for row in sorted(rows, key=lambda item: str(item["path"]))] return _json_sha256(ordered)
def _summary(rows: Sequence[Mapping[str, object]]) -> dict[str, object]: normalised = [dict(row) for row in rows] _manifest_index(normalised, label="Manifest") return { "tree_sha256": _tree_sha256(normalised), "manifest_sha256": _json_sha256(normalised), "file_count": len(normalised), "total_bytes": sum(_manifest_byte_count(row) for row in normalised), "files": normalised, }
def _sanitized_environment() -> dict[str, str]: windows_root = POWERSHELL_EXECUTABLE.parents[3] return { "COMSPEC": str(windows_root / "System32" / "cmd.exe"), "PATHEXT": ".COM;.EXE;.BAT;.CMD", "POWERSHELL_TELEMETRY_OPTOUT": "1", "SystemRoot": str(windows_root), "WINDIR": str(windows_root), }
def _default_runner(command: Sequence[str], cwd: Path, reviewed_source: bytes) -> CommandResult: if _sha256_bytes(reviewed_source) != REVIEWED_RELEASE_BUILDER_SHA256: raise WebsiteSourceRationalisationError( "Fixed runner received release-builder bytes outside the reviewed source pin." ) overflow = threading.Event() reader_errors: list[OSError] = [] stdout_buffer = bytearray() stderr_buffer = bytearray() try: process = subprocess.Popen( # noqa: S603 - fixed executable and argument vector list(command), cwd=cwd, close_fds=True, env=_sanitized_environment(), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=False, ) except OSError as exc: raise WebsiteSourceRationalisationError( "Fixed read-only release-builder verification could not complete." ) from exc
def drain(stream: Any, target: bytearray) -> None: try: while block := stream.read(64 * 1024): remaining = MAX_PROCESS_OUTPUT_BYTES + 1 - len(target) if remaining > 0: target.extend(block[:remaining]) if len(target) > MAX_PROCESS_OUTPUT_BYTES: overflow.set() try: process.kill() except OSError: pass except OSError as exc: reader_errors.append(exc)
if process.stdin is None or process.stdout is None or process.stderr is None: process.kill() raise WebsiteSourceRationalisationError("Fixed runner could not establish bounded pipes.") stdout_thread = threading.Thread(target=drain, args=(process.stdout, stdout_buffer), daemon=True) stderr_thread = threading.Thread(target=drain, args=(process.stderr, stderr_buffer), daemon=True) stdout_thread.start() stderr_thread.start() try: process.stdin.write(base64.b64encode(reviewed_source)) process.stdin.close() returncode = process.wait(timeout=PROCESS_TIMEOUT_SECONDS) except (BrokenPipeError, OSError, subprocess.TimeoutExpired) as exc: try: process.kill() process.wait(timeout=5) except (OSError, subprocess.TimeoutExpired): pass raise WebsiteSourceRationalisationError( "Fixed read-only release-builder verification could not complete." ) from exc finally: stdout_thread.join(timeout=5) stderr_thread.join(timeout=5) if stdout_thread.is_alive() or stderr_thread.is_alive() or reader_errors: raise WebsiteSourceRationalisationError("Fixed runner could not close its bounded output pipes.") if overflow.is_set(): raise WebsiteSourceRationalisationError("Release-builder verification output exceeded its bound.") return CommandResult(returncode, bytes(stdout_buffer), bytes(stderr_buffer))
def _closure_command(root: Path) -> list[str]: def encoded(value: str) -> str: return base64.b64encode(value.encode("utf-8")).decode("ascii")
wrapper = "\n".join( ( "$ErrorActionPreference = 'Stop'", "$raw = [Convert]::FromBase64String([Console]::In.ReadToEnd())", "$sha = [BitConverter]::ToString(([Security.Cryptography.SHA256]::Create()).ComputeHash($raw)).Replace('-', '')", f"if ($sha -cne '{REVIEWED_RELEASE_BUILDER_SHA256}') {{ throw 'Reviewed builder hash mismatch.' }}", "$utf8 = New-Object System.Text.UTF8Encoding($false, $true)", "$builder = [ScriptBlock]::Create($utf8.GetString($raw))", f"$website = $utf8.GetString([Convert]::FromBase64String('{encoded(str(root / SOURCE_ROOT))}'))", f"$output = $utf8.GetString([Convert]::FromBase64String('{encoded(str(root / ARTIFACT_ROOT / 'verify-only-no-output'))}'))", f"& $builder -WebsiteRoot $website -OutputDirectory $output -Release '{RELEASE}' -VerifyOnly", ) ) encoded_wrapper = base64.b64encode(wrapper.encode("utf-16-le")).decode("ascii") return [ str(POWERSHELL_EXECUTABLE), "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-EncodedCommand", encoded_wrapper, ]
def _unique_json_object(pairs: list[tuple[str, Any]]) -> dict[str, Any]: value: dict[str, Any] = {} for key, item in pairs: if key in value: raise WebsiteSourceRationalisationError(f"Duplicate JSON object key: {key}") value[key] = item return value
def _strict_json_bytes(raw: bytes, *, label: str) -> dict[str, Any]: if len(raw) > MAX_JSON_BYTES: raise WebsiteSourceRationalisationError(f"{label} exceeds the JSON input bound.") try: value = json.loads( raw.decode("utf-8-sig"), object_pairs_hook=_unique_json_object, parse_constant=lambda token: (_ for _ in ()).throw( WebsiteSourceRationalisationError(f"{label} contains non-finite JSON: {token}") ), ) except (UnicodeError, json.JSONDecodeError) as exc: raise WebsiteSourceRationalisationError(f"{label} is not strict UTF-8 JSON.") from exc if not isinstance(value, dict): raise WebsiteSourceRationalisationError(f"{label} must be a JSON object.") return value
def _closure_projection( *, root: Path, source_rows: Sequence[Mapping[str, object]], tool_bytes: bytes, runner: CommandRunner,) -> tuple[dict[str, object], list[dict[str, object]]]: if _sha256_bytes(tool_bytes) != REVIEWED_RELEASE_BUILDER_SHA256: raise WebsiteSourceRationalisationError("Release-builder execution bytes changed from their pin.") command = _closure_command(root) result = runner(command, root, tool_bytes) if result.returncode != 0: diagnostic = (result.stderr or result.stdout)[:1000].decode("utf-8", errors="replace") raise WebsiteSourceRationalisationError( "Fixed VerifyOnly release-builder command failed: " + diagnostic ) payload = _strict_json_bytes(result.stdout, label="Release-builder VerifyOnly output") expected_top = { "State", "Release", "SourceRoot", "FileCount", "TotalBytes", "PackageRoot", "RemoteRoot", "EntryFiles", "Closure", "Files", } if set(payload) != expected_top: raise WebsiteSourceRationalisationError("Release-builder VerifyOnly output fields changed.") if ( payload.get("State") != "release-plan-verified" or payload.get("Release") != RELEASE or payload.get("SourceRoot") != str(root / SOURCE_ROOT) or payload.get("PackageRoot") != "/" or payload.get("RemoteRoot") != "action-time-confirmation-required" ): raise WebsiteSourceRationalisationError("Release-builder VerifyOnly identity changed.")
raw_files = payload.get("Files") if not isinstance(raw_files, list): raise WebsiteSourceRationalisationError("Release-builder retained files are missing.") retained_rows: list[dict[str, object]] = [] for item in raw_files: if not isinstance(item, dict) or set(item) != {"Path", "Bytes", "Sha256"}: raise WebsiteSourceRationalisationError("Release-builder retained row fields changed.") retained_rows.append( { "path": _safe_relative_path(item.get("Path")), "bytes": item.get("Bytes"), "sha256": str(item.get("Sha256") or "").upper(), } ) retained_index = _manifest_index( retained_rows, label="Retained projection", require_sorted=False, ) retained_rows = [retained_index[path] for path in sorted(retained_index)] source_index = _manifest_index([dict(row) for row in source_rows], label="Source manifest") for path, row in retained_index.items(): if source_index.get(path) != row: raise WebsiteSourceRationalisationError( f"Release-builder retained row is not an exact current source file: {path}" ) if ( type(payload.get("FileCount")) is not int or payload.get("FileCount") != len(retained_rows) or type(payload.get("TotalBytes")) is not int or payload.get("TotalBytes") != sum(_manifest_byte_count(row) for row in retained_rows) ): raise WebsiteSourceRationalisationError("Release-builder retained totals are inconsistent.")
raw_entries = payload.get("EntryFiles") if not isinstance(raw_entries, list) or not all(isinstance(item, str) for item in raw_entries): raise WebsiteSourceRationalisationError("Release-builder entry files are malformed.") raw_entry_paths = [_safe_relative_path(item) for item in raw_entries] if len(raw_entry_paths) != len(set(raw_entry_paths)): raise WebsiteSourceRationalisationError("Release-builder entry files are duplicated.") entries = sorted(raw_entry_paths) if not set(entries).issubset(retained_index): raise WebsiteSourceRationalisationError( "Release-builder entry files are incomplete or non-canonical." )
closure = payload.get("Closure") expected_closure = { "state", "entry_file_count", "discovered_file_count", "local_reference_count", "included_local_reference_count", "missing_local_reference_count", "fragment_reference_count", "verified_fragment_reference_count", "missing_fragment_reference_count", "remote_reference_count", "non_file_reference_count", "remote_origins", "files_by_extension", } if not isinstance(closure, dict) or set(closure) != expected_closure: raise WebsiteSourceRationalisationError("Release-builder closure fields changed.") integer_fields = expected_closure.difference({"state", "remote_origins", "files_by_extension"}) if any(type(closure.get(field)) is not int or int(closure[field]) < 0 for field in integer_fields): raise WebsiteSourceRationalisationError("Release-builder closure counts are malformed.") if ( closure.get("state") != "verified-complete" or closure.get("missing_local_reference_count") != 0 or closure.get("missing_fragment_reference_count") != 0 or closure.get("included_local_reference_count") != closure.get("local_reference_count") or closure.get("verified_fragment_reference_count") != closure.get("fragment_reference_count") or closure.get("entry_file_count") != len(entries) or int(closure.get("entry_file_count", 0)) + int(closure.get("discovered_file_count", 0)) != len(retained_rows) ): raise WebsiteSourceRationalisationError( "Release-builder did not prove a complete dependency and fragment closure." ) raw_origins = closure.get("remote_origins") if not isinstance(raw_origins, list) or not all(isinstance(item, str) for item in raw_origins): raise WebsiteSourceRationalisationError("Release-builder remote origins are malformed.") origins = list(raw_origins) if len(origins) != len(set(origins)): raise WebsiteSourceRationalisationError("Release-builder remote origins are duplicated.") origins.sort() for origin in origins: parsed = urlparse(origin) if ( parsed.scheme != "https" or not parsed.netloc or parsed.username is not None or parsed.password is not None or parsed.path not in {"", "/"} or parsed.params or parsed.query or parsed.fragment ): raise WebsiteSourceRationalisationError( f"Release-builder returned a non-canonical HTTPS origin: {origin}" )
retained_summary = _summary(retained_rows) return ( { "tool_path": RELEASE_BUILDER_PATH.as_posix(), "tool_sha256": _sha256_bytes(tool_bytes), "command": command, "release": RELEASE, "verify_only": True, "state": "verified-complete", "entry_files": entries, "local_reference_count": closure["local_reference_count"], "missing_local_reference_count": 0, "missing_fragment_reference_count": 0, "remote_origins": origins, "retained_manifest_sha256": retained_summary["manifest_sha256"], }, retained_rows, )
def _exact_object(value: object, fields: frozenset[str], *, label: str) -> dict[str, Any]: if not isinstance(value, dict) or set(value) != fields: raise WebsiteSourceRationalisationError(f"{label} fields are incomplete or unexpected.") return value
def _require_sha256(value: object, *, label: str) -> str: if not isinstance(value, str) or _SHA256.fullmatch(value) is None: raise WebsiteSourceRationalisationError(f"{label} must be an uppercase SHA-256.") return value
def _require_summary(value: object, *, label: str) -> dict[str, Any]: summary = _exact_object(value, _SUMMARY_FIELDS, label=label) rows = summary.get("files") index = _manifest_index(rows, label=f"{label}.files") expected = _summary(list(index.values())) if summary != expected: raise WebsiteSourceRationalisationError(f"{label} does not match its exact manifest.") return summary
def _require_source_rationalisation_plan( value: object, *, root: Path, production: bool,) -> dict[str, Any]: """Require the exact recursive plan contract for one execution mode."""
plan = _exact_object(value, _PLAN_FIELDS, label="Source-rationalisation plan") if plan.get("schema") != PLAN_SCHEMA or plan.get("state") != "proposal-only": raise WebsiteSourceRationalisationError("Source-rationalisation plan identity is invalid.") _parse_utc(plan.get("generated_at"), label="plan.generated_at") _safe_run_id(plan.get("run_id")) if plan.get("authority") != PLAN_AUTHORITY: raise WebsiteSourceRationalisationError("Source-rationalisation plan authority changed.")
execution = _exact_object( plan.get("execution_binding"), _EXECUTION_FIELDS, label="plan.execution_binding", ) implementation = _regular_file( root / IMPLEMENTATION_PATH, label="Bound source-rationalisation implementation", ) expected_execution = _execution_binding( root, implementation_sha256=_sha256_file(implementation), production=production, ) if execution != expected_execution: raise WebsiteSourceRationalisationError( "Source-rationalisation implementation, runner, environment, or repository binding changed." ) reviewed_sources = ( (TRUSTED_LAUNCHER_PATH, REVIEWED_TRUSTED_LAUNCHER_SHA256, "isolated launcher"), (RELEASE_BUILDER_PATH, REVIEWED_RELEASE_BUILDER_SHA256, "release builder"), (MOTION_POLICY_PATH, REVIEWED_MOTION_POLICY_SHA256, "motion policy"), (SECURE_WRITER_PATH, REVIEWED_SECURE_WRITER_SHA256, "immutable writer"), ) for relative, expected_sha256, label in reviewed_sources: source_file = _regular_file(root / relative, label=f"Reviewed {label} source") if _sha256_file(source_file) != expected_sha256: raise WebsiteSourceRationalisationError(f"Reviewed {label} source pin changed.") powershell = _regular_file( POWERSHELL_EXECUTABLE, label="Reviewed PowerShell executable", require_single_link=False, ) if _sha256_file(powershell) != REVIEWED_POWERSHELL_SHA256: raise WebsiteSourceRationalisationError("Reviewed PowerShell binary pin changed.")
source = _exact_object(plan.get("source_binding"), _SOURCE_FIELDS, label="plan.source_binding") if source.get("root") != SOURCE_ROOT.as_posix(): raise WebsiteSourceRationalisationError("Source-rationalisation source root is not canonical.") source_summary = {key: source[key] for key in _SUMMARY_FIELDS} _require_summary(source_summary, label="plan.source_binding")
retained = _require_summary(plan.get("retained_projection"), label="plan.retained_projection") source_index = _manifest_index(source.get("files"), label="plan.source_binding.files") retained_index = _manifest_index(retained.get("files"), label="plan.retained_projection.files") if not retained_index or any(source_index.get(path) != row for path, row in retained_index.items()): raise WebsiteSourceRationalisationError("Retained projection is not an exact source subset.")
omitted = _exact_object(plan.get("omitted_projection"), _OMITTED_FIELDS, label="plan.omitted_projection") raw_omitted = omitted.get("files") if not isinstance(raw_omitted, list): raise WebsiteSourceRationalisationError("plan.omitted_projection.files must be an array.") omitted_plain: list[dict[str, object]] = [] omitted_paths: set[str] = set() for item in raw_omitted: if not isinstance(item, dict) or set(item) != _OMITTED_ROW_FIELDS: raise WebsiteSourceRationalisationError("Omitted rows use an unsupported shape.") if item.get("reason") != "not-in-public-runtime-closure": raise WebsiteSourceRationalisationError("Omitted row reason is not fixed.") row = {key: item[key] for key in _MANIFEST_ROW_FIELDS} path = _safe_relative_path(row["path"]) if path in omitted_paths: raise WebsiteSourceRationalisationError("Omitted path is duplicated.") omitted_paths.add(path) omitted_plain.append(row) omitted_index = _manifest_index(omitted_plain, label="plan.omitted_projection.files") expected_omitted = { "manifest_sha256": _json_sha256(raw_omitted), "file_count": len(raw_omitted), "total_bytes": sum(_manifest_byte_count(row) for row in omitted_plain), "files": raw_omitted, } if omitted != expected_omitted: raise WebsiteSourceRationalisationError("Omitted projection totals or digest changed.") if set(retained_index).intersection(omitted_index) or set(retained_index).union(omitted_index) != set( source_index ): raise WebsiteSourceRationalisationError( "Retained and omitted projections are not a disjoint complete source partition." ) if any(source_index[path] != row for path, row in omitted_index.items()): raise WebsiteSourceRationalisationError("Omitted projection changed a source row.")
closure = _exact_object(plan.get("closure_binding"), _CLOSURE_FIELDS, label="plan.closure_binding") if ( closure.get("tool_path") != RELEASE_BUILDER_PATH.as_posix() or closure.get("tool_sha256") != REVIEWED_RELEASE_BUILDER_SHA256 or closure.get("release") != RELEASE or closure.get("verify_only") is not True or closure.get("state") != "verified-complete" or closure.get("missing_local_reference_count") != 0 or closure.get("missing_fragment_reference_count") != 0 or closure.get("retained_manifest_sha256") != retained.get("manifest_sha256") ): raise WebsiteSourceRationalisationError("Source-rationalisation closure binding changed.") _require_sha256(closure.get("tool_sha256"), label="plan.closure_binding.tool_sha256") entries = closure.get("entry_files") if ( not isinstance(entries, list) or not entries or not all(isinstance(item, str) for item in entries) or entries != sorted(set(entries)) or not set(entries).issubset(retained_index) ): raise WebsiteSourceRationalisationError("Source-rationalisation entry-file binding changed.") origins = closure.get("remote_origins") if not isinstance(origins, list) or origins != sorted(set(origins)): raise WebsiteSourceRationalisationError("Source-rationalisation remote origins changed.") command = closure.get("command") if ( not isinstance(command, list) or not all(isinstance(item, str) for item in command) or command != _closure_command(root) ): raise WebsiteSourceRationalisationError("Source-rationalisation command binding is malformed.")
budget = _exact_object( plan.get("motion_budget_projection"), _BUDGET_FIELDS, label="plan.motion_budget_projection" ) _require_sha256(budget.get("policy_sha256"), label="plan.motion_budget_projection.policy_sha256") if budget.get("policy_sha256") != REVIEWED_MOTION_POLICY_SHA256: raise WebsiteSourceRationalisationError("Plan motion-policy source pin changed.") expected_budget = _fixed_footprint_projection( retained["files"], policy_sha256=str(budget["policy_sha256"]), ) if budget != expected_budget: raise WebsiteSourceRationalisationError("Motion-budget projection is not the fixed blocked contract.")
payload = dict(plan) payload_hash = payload.pop("payload_sha256") _require_sha256(payload_hash, label="plan.payload_sha256") if payload_hash != _json_sha256(payload): raise WebsiteSourceRationalisationError("Source-rationalisation plan payload hash changed.") return plan
def require_source_rationalisation_plan(value: object) -> dict[str, Any]: """Require a production plan bound to this loaded module's canonical repository."""
return _require_source_rationalisation_plan( value, root=_canonical_repo_root(), production=True, )
def _create_source_rationalisation_plan( *, root: Path, run_id: str | None = None, now: datetime | None = None, test_runner: CommandRunner | None = None, production: bool,) -> dict[str, Any]: """Build one plan; injected execution is permanently marked test-only."""
root = _find_repo_root(root) runner: CommandRunner if production: if root != _canonical_repo_root() or test_runner is not None: raise WebsiteSourceRationalisationError( "Production planning accepts only the canonical repository and fixed runner." ) _require_trusted_launcher_attestation(root) runner = _default_runner else: if test_runner is None: raise WebsiteSourceRationalisationError( "Test-only planning requires its injected fixture runner." ) runner = test_runner site = _regular_directory(root / SOURCE_ROOT, label="Canonical website source") if site != Path(os.path.abspath(root / SOURCE_ROOT)): raise WebsiteSourceRationalisationError("Canonical website source path changed.") tool = _regular_file(root / RELEASE_BUILDER_PATH, label="Fixed release-builder tool") policy = _regular_file(root / MOTION_POLICY_PATH, label="Fixed motion-policy compiler") writer = _regular_file(root / SECURE_WRITER_PATH, label="Reviewed immutable-artifact writer") powershell = _regular_file( POWERSHELL_EXECUTABLE, label="Reviewed PowerShell executable", require_single_link=False, ) implementation = _regular_file( root / IMPLEMENTATION_PATH, label="Bound source-rationalisation implementation", ) launcher = _regular_file(root / TRUSTED_LAUNCHER_PATH, label="Trusted isolated launcher") resolved_run_id = _safe_run_id(run_id or uuid.uuid4().hex)
source_before = _manifest(site) source_summary = _summary(source_before) tool_bytes = _read_reviewed_source_bytes( tool, REVIEWED_RELEASE_BUILDER_SHA256, label="Fixed release-builder source", ) tool_sha256_before = _sha256_bytes(tool_bytes) powershell_sha256_before = _sha256_file(powershell) if powershell_sha256_before != REVIEWED_POWERSHELL_SHA256: raise WebsiteSourceRationalisationError( "PowerShell executable does not match the reviewed binary pin; execution refused." ) policy_sha256_before = _sha256_file(policy) if policy_sha256_before != REVIEWED_MOTION_POLICY_SHA256: raise WebsiteSourceRationalisationError( "Fixed motion-policy bytes do not match the reviewed source pin." ) writer_sha256_before = _sha256_file(writer) if writer_sha256_before != REVIEWED_SECURE_WRITER_SHA256: raise WebsiteSourceRationalisationError( "Immutable-writer bytes do not match the reviewed source pin." ) implementation_sha256_before = _sha256_file(implementation) launcher_sha256_before = _sha256_bytes( _read_reviewed_source_bytes( launcher, REVIEWED_TRUSTED_LAUNCHER_SHA256, label="Trusted isolated launcher", ) ) closure, retained_rows = _closure_projection( root=root, source_rows=source_before, tool_bytes=tool_bytes, runner=runner, ) source_after = _manifest(site) if ( source_after != source_before or _sha256_file(tool) != tool_sha256_before or _sha256_file(policy) != policy_sha256_before or _sha256_file(writer) != writer_sha256_before or _sha256_file(powershell) != powershell_sha256_before or _sha256_file(implementation) != implementation_sha256_before or _sha256_file(launcher) != launcher_sha256_before ): raise WebsiteSourceRationalisationError( "Canonical source, implementation, release-builder, or motion policy changed during planning." ) if closure.get("tool_sha256") != tool_sha256_before: raise WebsiteSourceRationalisationError("Release-builder tool binding changed during planning.")
retained_summary = _summary(retained_rows) retained_paths = {str(row["path"]) for row in retained_rows} omitted_plain = [dict(row) for row in source_before if str(row["path"]) not in retained_paths] omitted_rows = [{**row, "reason": "not-in-public-runtime-closure"} for row in omitted_plain] plan: dict[str, Any] = { "schema": PLAN_SCHEMA, "generated_at": _utc_iso(now), "run_id": resolved_run_id, "state": "proposal-only", "source_binding": {"root": SOURCE_ROOT.as_posix(), **source_summary}, "closure_binding": closure, "retained_projection": retained_summary, "omitted_projection": { "manifest_sha256": _json_sha256(omitted_rows), "file_count": len(omitted_rows), "total_bytes": sum(_manifest_byte_count(row) for row in omitted_plain), "files": omitted_rows, }, "motion_budget_projection": _fixed_footprint_projection( retained_rows, policy_sha256=policy_sha256_before, ), "execution_binding": _execution_binding( root, implementation_sha256=implementation_sha256_before, production=production, ), "authority": dict(PLAN_AUTHORITY), } plan["payload_sha256"] = _json_sha256(plan) _require_source_rationalisation_plan(plan, root=root, production=production) return plan
def create_source_rationalisation_plan(*, run_id: str | None = None) -> dict[str, Any]: """Create a production proposal only for this module's canonical repository."""
return _create_source_rationalisation_plan( root=_canonical_repo_root(), run_id=run_id, production=True, )
def _create_test_only_source_rationalisation_plan( *, repo_root: Path, runner: CommandRunner, run_id: str | None = None, now: datetime | None = None,) -> dict[str, Any]: """Create a non-writable fixture plan for hostile unit tests only."""
return _create_source_rationalisation_plan( root=repo_root, run_id=run_id, now=now, test_runner=runner, production=False, )
def _json_artifact_bytes(value: Mapping[str, Any]) -> bytes: try: return ( json.dumps( dict(value), indent=2, sort_keys=True, ensure_ascii=False, allow_nan=False, ).encode("utf-8") + b"\n" ) except (TypeError, ValueError) as exc: raise WebsiteSourceRationalisationError("Artifact is not deterministic standard JSON.") from exc
def _ensure_artifact_parent(root: Path, parent: Path, *, allowed_root: Path) -> None: artifacts = _regular_directory(root / "artifacts", label="Aureon artifacts root") target_root = Path(os.path.abspath(allowed_root)) try: target_root.relative_to(artifacts) Path(os.path.abspath(parent)).relative_to(target_root) except ValueError as exc: raise WebsiteSourceRationalisationError("Artifact output escaped its fixed root.") from exc current = artifacts for part in target_root.relative_to(artifacts).parts: current /= part if not current.exists(): current.mkdir() _regular_directory(current, label="Source-rationalisation artifact directory") for part in Path(os.path.abspath(parent)).relative_to(target_root).parts: current /= part if not current.exists(): current.mkdir() _regular_directory(current, label="Source-rationalisation artifact directory")
def _load_reviewed_secure_writer(root: Path) -> Any: """Authenticate immutable-writer bytes before executing that repo-local module."""
source = _regular_file(root / SECURE_WRITER_PATH, label="Reviewed immutable-artifact writer") payload = _read_reviewed_source_bytes( source, REVIEWED_SECURE_WRITER_SHA256, label="Reviewed immutable-artifact writer", ) module = ModuleType("_aureon_reviewed_source_rationalisation_immutable_writer") module.__file__ = str(source) module.__package__ = "aureon.operator" try: exec(compile(payload, str(source), "exec", dont_inherit=True), module.__dict__) # noqa: S102 except (ImportError, OSError, SyntaxError) as exc: raise WebsiteSourceRationalisationError( "Reviewed immutable-writer import could not complete." ) from exc if not callable(getattr(module, "write_new_file", None)): raise WebsiteSourceRationalisationError("Reviewed immutable writer has no callable entrypoint.") return module
def write_source_rationalisation_plan( plan: Mapping[str, Any], output_path: Path,) -> Path: """Persist one exact plan at its fixed path without replacement."""
root = _canonical_repo_root() _require_trusted_launcher_attestation(root) controlled = require_source_rationalisation_plan(dict(plan)) run_id = str(controlled["run_id"]) expected = root / PLAN_ROOT / f"{run_id}.plan.v1.json" output = output_path if output_path.is_absolute() else root / output_path output = Path(os.path.abspath(output)) if output != Path(os.path.abspath(expected)): raise WebsiteSourceRationalisationError( "Plan output must use source-rationalisations/plans/<run-id>.plan.v1.json." ) _revalidate_plan_current(root, controlled) _ensure_artifact_parent(root, output.parent, allowed_root=root / PLAN_ROOT) raw = _json_artifact_bytes(controlled) writer = _load_reviewed_secure_writer(root) try: writer.write_new_file(output, raw) except OSError as exc: raise WebsiteSourceRationalisationError( f"Source-rationalisation plan could not be created immutably: {exc}" ) from exc if output.read_bytes() != raw: raise WebsiteSourceRationalisationError("Immutable plan failed exact byte read-back.") return output
def _read_json_file(path: Path, *, label: str) -> tuple[dict[str, Any], bytes]: file_path = _regular_file(path, label=label) raw = file_path.read_bytes() return _strict_json_bytes(raw, label=label), raw
def _relative_to_repo(root: Path, path: Path) -> str: try: return path.relative_to(root).as_posix() except ValueError as exc: raise WebsiteSourceRationalisationError("Evidence path escaped the Aureon repository.") from exc
def _controlled_input_path(root: Path, path: Path, *, allowed_root: Path, label: str) -> Path: candidate = path if path.is_absolute() else root / path lexical = _regular_file(candidate, label=label) try: lexical.relative_to(Path(os.path.abspath(allowed_root))) except ValueError as exc: raise WebsiteSourceRationalisationError(f"{label} escaped its controlled artifact root.") from exc return lexical
def _revalidate_plan_current(root: Path, plan: Mapping[str, Any]) -> None: site = _regular_directory(root / SOURCE_ROOT, label="Canonical website source") tool = _regular_file(root / RELEASE_BUILDER_PATH, label="Fixed release-builder tool") policy = _regular_file(root / MOTION_POLICY_PATH, label="Fixed motion-policy compiler") implementation = _regular_file( root / IMPLEMENTATION_PATH, label="Bound source-rationalisation implementation", ) writer = _regular_file(root / SECURE_WRITER_PATH, label="Reviewed immutable-artifact writer") powershell = _regular_file( POWERSHELL_EXECUTABLE, label="Reviewed PowerShell executable", require_single_link=False, ) source_rows = _manifest(site) current_summary = _summary(source_rows) source = plan["source_binding"] if current_summary != {key: source[key] for key in _SUMMARY_FIELDS}: raise WebsiteSourceRationalisationError("Canonical website source changed after planning.") closure = plan["closure_binding"] pinned_files = { "implementation": (implementation, plan["execution_binding"]["implementation_sha256"]), "release-builder": (tool, REVIEWED_RELEASE_BUILDER_SHA256), "motion-policy": (policy, REVIEWED_MOTION_POLICY_SHA256), "immutable-writer": (writer, REVIEWED_SECURE_WRITER_SHA256), "powershell": (powershell, REVIEWED_POWERSHELL_SHA256), } before_hashes = {label: _sha256_file(path) for label, (path, _expected) in pinned_files.items()} if any(before_hashes[label] != expected for label, (_path, expected) in pinned_files.items()): raise WebsiteSourceRationalisationError( "Implementation, release-builder, PowerShell, motion-policy, or writer pin changed." ) tool_bytes = _read_reviewed_source_bytes( tool, REVIEWED_RELEASE_BUILDER_SHA256, label="Fixed release-builder source", ) replay_closure, replay_rows = _closure_projection( root=root, source_rows=source_rows, tool_bytes=tool_bytes, runner=_default_runner, ) if ( _manifest(site) != source_rows or any( _sha256_file(path) != before_hashes[label] for label, (path, _expected) in pinned_files.items() ) or replay_closure != closure or _summary(replay_rows) != plan["retained_projection"] or closure.get("command") != _closure_command(root) ): raise WebsiteSourceRationalisationError( "Fixed VerifyOnly replay or its bound sources changed after planning." )
def _require_owner_decision_shape(decision: object) -> dict[str, Any]: value = _exact_object(decision, _DECISION_FIELDS, label="Owner source-rationalisation decision") if ( value.get("schema") != OWNER_DECISION_SCHEMA or value.get("decision") != "acknowledged-review-only" or value.get("scope") != "acknowledge-exact-source-rationalisation-proposal" or value.get("authority") != OWNER_DECISION_AUTHORITY ): raise WebsiteSourceRationalisationError("Owner decision identity or authority is invalid.") _safe_run_id(value.get("plan_run_id"), label="decision.plan_run_id") for field in ( "plan_file_sha256", "plan_payload_sha256", "source_tree_sha256", "retained_tree_sha256", "omitted_manifest_sha256", ): _require_sha256(value.get(field), label=f"decision.{field}") acknowledged_by = value.get("acknowledged_by") note = value.get("note") if ( not isinstance(acknowledged_by, str) or acknowledged_by != acknowledged_by.strip() or len(acknowledged_by) < 3 or not any(character.isalpha() for character in acknowledged_by) or acknowledged_by.casefold() in _GENERIC_APPROVERS ): raise WebsiteSourceRationalisationError("Owner decision must identify a named human approver.") if not isinstance(note, str) or note != note.strip() or not note: raise WebsiteSourceRationalisationError("Owner decision note must be non-empty canonical text.") _parse_utc(value.get("acknowledged_at"), label="decision.acknowledged_at") _parse_utc(value.get("expires_at"), label="decision.expires_at") return value
def _check(identifier: str, passed: bool, message: str, **evidence: object) -> dict[str, object]: return {"id": identifier, "passed": bool(passed), "message": message, "evidence": evidence}
def _validate_owner_source_rationalisation_decision( plan_path: Path, decision_path: Path, *, now: datetime,) -> dict[str, Any]: """Validate one decision at a caller-captured instant for deterministic replay."""
root = _canonical_repo_root() _require_trusted_launcher_attestation(root) now = now.astimezone(UTC) plan_file = _controlled_input_path( root, plan_path, allowed_root=root / PLAN_ROOT, label="Source-rationalisation plan", ) decision_file = _controlled_input_path( root, decision_path, allowed_root=root / OWNER_DECISION_ROOT, label="Owner source-rationalisation decision", ) plan, plan_raw = _read_json_file(plan_file, label="Source-rationalisation plan") require_source_rationalisation_plan(plan) run_id = str(plan["run_id"]) expected_plan = root / PLAN_ROOT / f"{run_id}.plan.v1.json" expected_decision = root / OWNER_DECISION_ROOT / f"{run_id}.decision.v1.json" if plan_file != Path(os.path.abspath(expected_plan)) or decision_file != Path( os.path.abspath(expected_decision) ): raise WebsiteSourceRationalisationError("Plan or decision does not use its exact run-bound path.") if plan_raw != _json_artifact_bytes(plan): raise WebsiteSourceRationalisationError("Persisted plan bytes are not the deterministic V1 encoding.") decision, decision_raw = _read_json_file( decision_file, label="Owner source-rationalisation decision", )
checks: list[dict[str, object]] = [] shape_error = "" try: controlled_decision = _require_owner_decision_shape(decision) shape_ok = True except WebsiteSourceRationalisationError as exc: controlled_decision = decision shape_ok = False shape_error = str(exc) checks.append( _check( "exact-owner-decision-contract", shape_ok, "Decision must use the exact named-owner review-only contract.", error=shape_error, ) )
plan_file_sha256 = _sha256_bytes(plan_raw) binding_ok = shape_ok and all( ( controlled_decision.get("plan_run_id") == run_id, controlled_decision.get("plan_file_sha256") == plan_file_sha256, controlled_decision.get("plan_payload_sha256") == plan["payload_sha256"], controlled_decision.get("source_tree_sha256") == plan["source_binding"]["tree_sha256"], controlled_decision.get("retained_tree_sha256") == plan["retained_projection"]["tree_sha256"], controlled_decision.get("omitted_manifest_sha256") == plan["omitted_projection"]["manifest_sha256"], ) ) checks.append( _check( "exact-plan-binding", binding_ok, "Owner decision must bind the exact plan bytes, source, retained tree, and omissions.", ) )
timing_ok = False if shape_ok: try: reference = (now or datetime.now(UTC)).astimezone(UTC) generated_at = _parse_utc(plan["generated_at"], label="plan.generated_at") acknowledged_at = _parse_utc( controlled_decision["acknowledged_at"], label="decision.acknowledged_at", ) expires_at = _parse_utc(controlled_decision["expires_at"], label="decision.expires_at") timing_ok = ( generated_at <= acknowledged_at <= reference < expires_at and expires_at - acknowledged_at <= MAX_OWNER_DECISION_AGE ) except WebsiteSourceRationalisationError: timing_ok = False checks.append( _check( "fresh-owner-decision", timing_ok, "Owner decision must follow the plan and remain active for at most four hours.", maximum_hours=MAX_OWNER_DECISION_AGE.total_seconds() / 3600, ) )
current_error = "" try: _revalidate_plan_current(root, plan) current_ok = True except WebsiteSourceRationalisationError as exc: current_ok = False current_error = str(exc) checks.append( _check( "current-plan-inputs", current_ok, "Canonical source, fixed VerifyOnly tool, command, and motion policy must remain unchanged.", error=current_error, ) ) checks.append( _check( "non-authoritative-boundary", shape_ok and controlled_decision.get("authority") == OWNER_DECISION_AUTHORITY, "Decision grants no staging execution, candidate, canonical, package, or deployment authority here.", ) )
passed = all(check["passed"] is True for check in checks) validation: dict[str, Any] = { "schema": OWNER_VALIDATION_SCHEMA, "validated_at": _utc_iso(now), "state": "owner-decision-validated-review-only" if passed else "blocked", "passed": passed, "release_eligible": False, "authority": dict(VALIDATION_AUTHORITY), "plan": { "path": _relative_to_repo(root, plan_file), "file_sha256": plan_file_sha256, "run_id": run_id, "payload_sha256": plan["payload_sha256"], }, "decision": { "path": _relative_to_repo(root, decision_file), "file_sha256": _sha256_bytes(decision_raw), "acknowledged_by": controlled_decision.get("acknowledged_by") if shape_ok else "", }, "checks": checks, "next_gate": ( "Review-only acknowledgement recorded; a separate implementation and authority gate is required." if passed else "Repair the exact plan or named-owner decision; no staging is authorised." ), } validation["payload_sha256"] = _json_sha256(validation) require_owner_validation(validation) return validation
def validate_owner_source_rationalisation_decision( plan_path: Path, decision_path: Path,) -> dict[str, Any]: """Validate exact canonical evidence now; never create or stage files."""
return _validate_owner_source_rationalisation_decision( plan_path, decision_path, now=datetime.now(UTC), )
def require_owner_validation(value: object) -> dict[str, Any]: """Require the exact non-authoritative validation receipt contract."""
validation = _exact_object(value, _VALIDATION_FIELDS, label="Owner decision validation") if validation.get("schema") != OWNER_VALIDATION_SCHEMA: raise WebsiteSourceRationalisationError("Owner decision validation schema is invalid.") _parse_utc(validation.get("validated_at"), label="validation.validated_at") passed = validation.get("passed") if type(passed) is not bool: raise WebsiteSourceRationalisationError("Owner decision validation passed must be boolean.") expected_state = "owner-decision-validated-review-only" if passed else "blocked" if ( validation.get("state") != expected_state or validation.get("release_eligible") is not False or validation.get("authority") != VALIDATION_AUTHORITY ): raise WebsiteSourceRationalisationError("Owner decision validation authority changed.") plan = _exact_object( validation.get("plan"), frozenset({"path", "file_sha256", "run_id", "payload_sha256"}), label="validation.plan", ) _safe_relative_path(plan.get("path")) _safe_run_id(plan.get("run_id"), label="validation.plan.run_id") _require_sha256(plan.get("file_sha256"), label="validation.plan.file_sha256") _require_sha256(plan.get("payload_sha256"), label="validation.plan.payload_sha256") decision = _exact_object( validation.get("decision"), frozenset({"path", "file_sha256", "acknowledged_by"}), label="validation.decision", ) _safe_relative_path(decision.get("path")) _require_sha256(decision.get("file_sha256"), label="validation.decision.file_sha256") if passed and (not isinstance(decision.get("acknowledged_by"), str) or not decision["acknowledged_by"]): raise WebsiteSourceRationalisationError("Passing validation lost its named approver.") checks = validation.get("checks") if ( not isinstance(checks, list) or [check.get("id") for check in checks if isinstance(check, dict)] != list(OWNER_VALIDATION_CHECK_IDS) or any( not isinstance(check, dict) or set(check) != {"id", "passed", "message", "evidence"} for check in checks ) or any(type(check["passed"]) is not bool for check in checks) or any(not isinstance(check["message"], str) or not check["message"] for check in checks) or any(not isinstance(check["evidence"], dict) for check in checks) or passed != all(check["passed"] is True for check in checks) ): raise WebsiteSourceRationalisationError("Owner decision validation checks are malformed.") if not isinstance(validation.get("next_gate"), str) or not validation["next_gate"]: raise WebsiteSourceRationalisationError("Owner decision validation next gate is missing.") payload = dict(validation) payload_hash = payload.pop("payload_sha256") _require_sha256(payload_hash, label="validation.payload_sha256") if payload_hash != _json_sha256(payload): raise WebsiteSourceRationalisationError("Owner decision validation payload hash changed.") return validation
def write_owner_validation( plan_path: Path, decision_path: Path, output_path: Path,) -> Path: """Generate, deterministically replay, and immutably persist validation."""
root = _canonical_repo_root() _require_trusted_launcher_attestation(root) captured_at = datetime.now(UTC) controlled = _validate_owner_source_rationalisation_decision( plan_path, decision_path, now=captured_at, ) run_id = str(controlled["plan"]["run_id"]) expected = root / VALIDATION_ROOT / f"{run_id}.validation.v1.json" output = output_path if output_path.is_absolute() else root / output_path output = Path(os.path.abspath(output)) if output != Path(os.path.abspath(expected)): raise WebsiteSourceRationalisationError( "Validation output must use source-rationalisations/validations/<run-id>.validation.v1.json." ) _ensure_artifact_parent(root, output.parent, allowed_root=root / VALIDATION_ROOT) raw = _json_artifact_bytes(controlled) writer = _load_reviewed_secure_writer(root) replayed = _validate_owner_source_rationalisation_decision( plan_path, decision_path, now=captured_at, ) if _json_artifact_bytes(replayed) != raw: raise WebsiteSourceRationalisationError( "Plan or decision changed between validation and immutable write replay." ) try: writer.write_new_file(output, raw) except OSError as exc: raise WebsiteSourceRationalisationError( f"Owner validation could not be created immutably: {exc}" ) from exc if output.read_bytes() != raw: raise WebsiteSourceRationalisationError("Immutable validation failed exact byte read-back.") return output
def build_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser( prog="aureon-website-source-rationalisation", description="Plan a read-only website source projection and validate exact owner evidence.", ) subparsers = parser.add_subparsers(dest="command", required=True)
plan = subparsers.add_parser("plan", help="Create a proposal-only exact source partition.") plan.add_argument("--run-id") plan.add_argument("--output", type=Path, required=True)
validate = subparsers.add_parser( "validate-decision", help="Validate a supplied named-owner decision; never stage or mutate source.", ) validate.add_argument("--plan", type=Path, required=True) validate.add_argument("--decision", type=Path, required=True) validate.add_argument("--output", type=Path, required=True) return parser
def main(argv: Sequence[str] | None = None) -> int: try: root = _canonical_repo_root() _require_trusted_launcher_attestation(root) args = build_parser().parse_args(list(argv) if argv is not None else None) if args.command == "plan": plan = create_source_rationalisation_plan(run_id=args.run_id) output = write_source_rationalisation_plan(plan, args.output) print( json.dumps( { "state": plan["state"], "output": _relative_to_repo(root, output), "payload_sha256": plan["payload_sha256"], "staging_authority": "none", }, indent=2, ) ) return 0 output = write_owner_validation(args.plan, args.decision, args.output) validation, _raw = _read_json_file(output, label="Written owner validation") require_owner_validation(validation) print( json.dumps( { "state": validation["state"], "passed": validation["passed"], "output": _relative_to_repo(root, output), "staging_executed": False, }, indent=2, ) ) return 0 if validation["passed"] else 2 except (OSError, WebsiteSourceRationalisationError) as exc: print( json.dumps( { "state": "blocked", "error": str(exc), "staging_executed": False, "canonical_website_mutation": "none", } ) ) return 2
if __name__ == "__main__": sys.exit(main())
__all__ = [ "FIXED_FOOTPRINT_LIMITS", "OWNER_DECISION_AUTHORITY", "OWNER_DECISION_SCHEMA", "OWNER_VALIDATION_SCHEMA", "PLAN_AUTHORITY", "PLAN_SCHEMA", "VALIDATION_AUTHORITY", "WebsiteSourceRationalisationError", "create_source_rationalisation_plan", "require_owner_validation", "require_source_rationalisation_plan", "validate_owner_source_rationalisation_decision", "write_owner_validation", "write_source_rationalisation_plan",]12345678910111213141516171819"""
WSGI entrypoint for the Aureon Operator / Cognition service.
Exposes a module-level ``app`` so any production WSGI server can serve it:
waitress-serve --port=8790 aureon.operator.wsgi:app
gunicorn aureon.operator.wsgi:app -b 0.0.0.0:8790
The app is fully wired (config validated, cognition eagerly built and joined to
the mycelium mesh + Queen hive) via ``operator_server.build_boot_app()``.
"""
from __future__ import annotations
from aureon.operator.operator_server import build_boot_app
app = build_boot_app()
__all__ = ["app"]1"""Read-only join of the repository layers that form the organism."""123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254"""Join the five repository layers without inventing a reading or an action.
Aureon OS is the operating layer. Skaila is evidence. Nexus is the public
field. Project Sero is the public market. The founder mirror is the decision
contract. Sample scores and simulators stay out of the join. The action gate
stays closed.
"""
from __future__ import annotations
import hashlib
import importlib.util
import os
import re
from pathlib import Path
from typing import Any, Callable, Mapping
SCHEMA = "aureon.repository-layers.v1"
_DIGEST = r"^[0-9a-f]{64}$"
_NEXUS_SOURCE = "https://services.swpc.noaa.gov/products/noaa-planetary-k-index.json"
_MARKET_SOURCE = "https://data-api.binance.vision/api/v3/ticker/price?symbol=BTCUSDT"
def _repos_root(explicit: Path | None) -> Path:
if explicit is not None:
return explicit.resolve()
env = os.environ.get("AUREON_REPOS_ROOT")
if env:
return Path(env).resolve()
return Path(__file__).resolve().parents[3]
def _contained(root: Path, relative: str) -> Path | None:
path = (root / relative).resolve()
if path != root.resolve() and root.resolve() not in path.parents:
return None
return path if path.is_file() else None
def _sha256(path: Path) -> str:
return hashlib.sha256(path.read_bytes()).hexdigest()
def _load(path: Path, name: str) -> Any:
spec = importlib.util.spec_from_file_location(name, path)
if spec is None or spec.loader is None:
raise ImportError(name)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
def _base(layer_id: str, repo: str, role: str, capability: str) -> dict[str, Any]:
return {
"id": layer_id,
"repo": repo,
"role": role,
"capability": capability,
"gate": "HOLD",
"may_act": False,
"generated_values": False,
"truth_status": "no_data",
"reason": "observation_unavailable",
"capability_sha256": None,
"observation": None,
}
def _accept_observation(observation: Mapping[str, Any], source: str, schema: str) -> dict[str, Any]:
if (
observation.get("schema") != schema
or observation.get("source") != source
or observation.get("generated_values") is not False
or observation.get("may_act") is not False
or not isinstance(observation.get("payload_sha256"), str)
):
raise ValueError("source_bound_observation_required")
if re.fullmatch(_DIGEST, observation["payload_sha256"]) is None:
raise ValueError("source_bound_observation_required")
return dict(observation)
def _field_layer(root: Path, transport: Callable[[str], bytes] | None) -> dict[str, Any]:
layer = _base("nexus", "NEXUS-LIVE-FEED-", "field", "public planetary K-index")
path = _contained(root / "NEXUS-LIVE-FEED-", "organism/public_field.py")
if path is None:
layer["reason"] = "field_capability_missing"
return layer
layer["capability_sha256"] = _sha256(path)
module = _load(path, "nexus_public_field")
if getattr(module, "SOURCE", None) != _NEXUS_SOURCE:
layer["reason"] = "field_source_rejected"
return layer
observation = module.observe_planetary_k_index(transport)
layer["observation"] = _accept_observation(observation, _NEXUS_SOURCE, "nexus.public-field.v1")
layer["truth_status"] = "real_observed"
layer["reason"] = None
return layer
def _market_layer(root: Path, transport: Callable[[str], bytes] | None) -> dict[str, Any]:
layer = _base("sero", "Aureon-Trading--Project-Sero", "market", "public BTCUSDT price")
path = _contained(root / "Aureon-Trading--Project-Sero", "organism/public_market.py")
if path is None:
layer["reason"] = "market_capability_missing"
return layer
layer["capability_sha256"] = _sha256(path)
module = _load(path, "sero_public_market")
if getattr(module, "SOURCE", None) != _MARKET_SOURCE:
layer["reason"] = "market_source_rejected"
return layer
observation = module.observe_public_price(transport)
if observation.get("order_count") != 0:
raise ValueError("market_observation_must_not_order")
layer["observation"] = _accept_observation(observation, _MARKET_SOURCE, "sero.public-market.v1")
layer["truth_status"] = "real_observed"
layer["reason"] = None
return layer
def _evidence_layer(root: Path, evidence: Mapping[str, Any] | None) -> dict[str, Any]:
layer = _base("skaila", "skaila-journey-platform", "evidence", "assessment gate")
policy = _contained(root / "skaila-journey-platform", "spec/build-pack/aureon-gate-policy.yaml")
if policy is not None:
layer["capability_sha256"] = _sha256(policy)
if not evidence:
layer["reason"] = "evidence_observation_required"
return layer
authority = evidence.get("authority")
if authority != "imported":
layer["reason"] = "sample_or_synthetic_evidence_excluded"
return layer
digest = evidence.get("manifest_sha256")
gate = evidence.get("gate")
if not isinstance(digest, str) or re.fullmatch(_DIGEST, digest) is None or gate not in {"HOLD", "RELEASE"}:
layer["reason"] = "imported_evidence_metadata_required"
return layer
readiness = evidence.get("readiness")
adoption = evidence.get("adoption")
if (
isinstance(readiness, bool)
or isinstance(adoption, bool)
or not isinstance(readiness, (int, float))
or not isinstance(adoption, (int, float))
):
layer["reason"] = "imported_evidence_metadata_required"
return layer
layer["observation"] = {
"schema": "skaila.imported-evidence.v1",
"authority": "imported",
"gate": gate,
"readiness": readiness,
"adoption": adoption,
"manifest_sha256": digest,
"generated_values": False,
"may_act": False,
}
layer["truth_status"] = "real_observed"
layer["gate"] = gate
layer["reason"] = None
return layer
def _founder_layer(root: Path) -> dict[str, Any]:
layer = _base(
"founder-mirror",
"aureon-founder-mirror",
"decision",
"draft decision contract",
)
path = _contained(root / "aureon-founder-mirror", "README.md")
if path is None:
layer["reason"] = "decision_contract_missing"
return layer
text = path.read_text(encoding="utf-8")[:4000]
if "HOLD" not in text or "never sends" not in text.lower():
layer["reason"] = "decision_contract_rejected"
return layer
layer["capability_sha256"] = hashlib.sha256(path.read_bytes()).hexdigest()
layer["observation"] = {
"schema": "founder.decision-contract.v1",
"sends": False,
"spends": False,
"signs": False,
"generated_values": False,
"may_act": False,
}
layer["truth_status"] = "real_observed"
layer["reason"] = None
return layer
def _operating_layer() -> dict[str, Any]:
layer = _base("aureon-os", "Aureon-OS", "operating", "canonical organism composition")
root = Path(__file__).resolve().parents[2]
path = _contained(root, "aureon/core/organism_composition.py")
if path is None:
layer["reason"] = "operating_capability_missing"
return layer
layer["capability_sha256"] = _sha256(path)
from aureon.core.organism_composition import get_canonical_organism_composition
seated = get_canonical_organism_composition()
layer["observation"] = {
"schema": "aureon.operating-layer.v1",
"canonical_composition_seated": seated is not None,
"generated_values": False,
"may_act": False,
}
layer["truth_status"] = "real_derived"
layer["reason"] = None if seated is not None else "canonical_composition_unseated"
return layer
def _guard(builder: Callable[[], dict[str, Any]], layer_id: str, repo: str, role: str) -> dict[str, Any]:
try:
layer = builder()
except (OSError, ValueError, TypeError, ImportError, TimeoutError) as exc:
layer = _base(layer_id, repo, role, "unavailable")
layer["reason"] = str(exc)[:160] or "observation_unavailable"
if layer.get("may_act") is not False or layer.get("generated_values") is not False:
rejected = _base(layer_id, repo, role, "rejected")
rejected["reason"] = "layer_action_rejected"
return rejected
return layer
def compose_repository_layers(
repos_root: Path | None = None,
evidence: Mapping[str, Any] | None = None,
field_transport: Callable[[str], bytes] | None = None,
market_transport: Callable[[str], bytes] | None = None,
) -> dict[str, Any]:
"""Read each layer once and return the joined hold."""
root = _repos_root(repos_root)
layers = [
_guard(_operating_layer, "aureon-os", "Aureon-OS", "operating"),
_guard(lambda: _evidence_layer(root, evidence), "skaila", "skaila-journey-platform", "evidence"),
_guard(lambda: _field_layer(root, field_transport), "nexus", "NEXUS-LIVE-FEED-", "field"),
_guard(lambda: _market_layer(root, market_transport), "sero", "Aureon-Trading--Project-Sero", "market"),
_guard(lambda: _founder_layer(root), "founder-mirror", "aureon-founder-mirror", "decision"),
]
return {
"schema": SCHEMA,
"status": "hold",
"reason": "action_authority_remains_closed",
"generated_values": False,
"action_eligible": False,
"economic_mutation": False,
"may_act": False,
"layers": layers,
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682"""Public Aureon Plumber v0/v0.2 lab, v0.3 broker, and v0.4 guard contracts.
Importing this package performs no network, filesystem mutation, encryption,
release, provider, or production action. Execution-capable adapters remain
explicitly insecure, same-process laboratory components with production
readiness disabled. The v0.3 surface is metadata-only: it exposes signed,
durable one-use contracts, not an executor, HSM, or production release service.
The v0.4 runtime guard remains an explicitly installed Python reference layer,
not a native or operating-system sandbox.
"""
from .audit import AuditEvent, assert_public_summary_safe
from .authorization_chain_v02 import (
AUTHORIZATION_CHAIN_SCHEMA,
AUTHORIZATION_ROLES,
AuthorizationChainError,
AuthorizationChainV02,
assemble_authorization_chain_v02,
build_authorization_snapshot_v02,
build_continuity_decision_v02,
build_custody_permit_v02,
validate_authorization_chain_v02,
validate_authorization_trust_v02,
)
from .breaker import (
SYNTHETIC_BREAKER_SCOPE,
SyntheticBreakerCase,
SyntheticBreakerReport,
run_synthetic_offline_breaker_lab,
)
from .crypto import (
CryptoContractError,
b64url_decode,
b64url_encode,
canonical_json_bytes,
decode_canonical_json,
domain_hash,
ed25519_public_key_hex,
generate_ed25519_private_key,
hex_decode,
load_ed25519_private_key,
load_ed25519_public_key,
sha256_hex,
sign_ed25519,
verify_ed25519,
)
from .enclave import (
INSECURE_OPT_IN_ACK,
LOCAL_DEVELOPMENT_MODE,
EnclaveCode,
EnclaveConfigurationError,
EnclaveDisposition,
LocalComputationResult,
LocalDevelopmentEnclave,
LocalEnclaveAttestation,
LocalEnclaveExecutionReceipt,
)
from .immune_gate import (
REQUIRED_GATE_CLASSES,
GateClass,
GateDecision,
GateEvidence,
GateVerdict,
build_gate_context_commitment,
evaluate_immune_gate,
)
from .magic_star_v02 import (
IMPLEMENTATION_PROFILE_SHA256,
PENTAGRAM_ROUTE,
POINT_ROLES,
POINTS,
PROFILE_DESCRIPTOR,
PROFILE_ID,
PROTOCOL_ID,
RAINBOW_FREQUENCIES,
RAINBOW_SOURCE_SHA256,
SOURCE_PROFILE_COMMITMENT,
STAR_AUTHORITY_ROLES,
AuthorityBindingV02,
MagicStarError,
MagicStarV02,
assemble_magic_star_v02,
build_authority_binding_v02,
build_candidate_center_v02,
build_epas_precondition_v02,
build_heart_precondition_v02,
build_heart_source_identity_commitment_v02,
build_magic_star_point_v02,
component_commitment_v02,
heart_receipt_commitment_v02,
sign_component_v02,
validate_distinct_authorities_v02,
validate_magic_star_v02,
verify_component_v02,
)
from .observer_transcript import (
OBSERVER_TRANSCRIPT_SCHEMA,
ObserverTranscriptV0,
build_observer_transcript,
)
from .os_protection import (
DEFAULT_MAX_INGRESS_BYTES,
MAX_OPERATOR_AAD_BYTES,
OS_DURABLE_QUARANTINE_EVIDENCE_SCHEMA,
OS_INGRESS_AAD_SCHEMA,
OS_KEY_PREFLIGHT_SCHEMA,
OS_PROTECTION_SCHEMA,
OS_QUARANTINE_EVIDENCE_PURPOSE,
OS_QUARANTINE_EVIDENCE_SCHEMA,
OS_RUNTIME_GUARD_LIFECYCLE_SCHEMA,
AdmissionOutcome,
AdmittedHNC,
ContentValidator,
IngressDisposition,
LocalOSProtectionBoundary,
MasterKeyProvider,
OpaqueHNCHandle,
OSProtectionError,
QuarantinedHNC,
QuarantineEvidenceSink,
)
from .packet import (
HNC_PAYLOAD_BINDING_SCHEMA,
HNCPayloadBindingV0,
PacketCode,
PacketContractError,
PacketDisposition,
PacketInspection,
PacketReplayGuard,
PacketTrustPolicy,
add_packet_signature,
bind_hnc_packet,
inspect_plumber_packet,
)
from .production_release_broker_v03 import (
COMMAND_SCHEMA,
DENIED_RECEIPT_SCHEMA,
DISPATCH_SCHEMA,
EXECUTOR_EVIDENCE_SCHEMA,
LEDGER_SCHEMA,
RELEASE_RECEIPT_SCHEMA,
REVIEW_SCHEMA,
AuthorityBindingV03,
DeniedReceiptV03,
DispatchClaimSignerV03,
DispatchClaimV03,
DurableTerminalLedgerV03,
ExecutorOutcome,
ExecutorTerminalEvidenceV03,
LedgerClaimDisposition,
LedgerClaimV03,
OutOfProcessReleaseExecutorV03,
ProductionReleaseBrokerError,
ProductionReleaseBrokerV03,
ProductionReleaseVerifierV03,
ReceiptDisposition,
ReleaseCommandV03,
ReleaseReceiptV03,
ReviewAuthorizationV03,
SQLiteTerminalLedgerV03,
TerminalReceiptSignerV03,
TerminalReceiptV03,
decode_dispatch_claim_v03,
decode_executor_evidence_v03,
decode_release_command_v03,
decode_review_authorization_v03,
decode_terminal_receipt_v03,
sign_dispatch_claim_v03,
sign_executor_evidence_v03,
sign_review_authorization_v03,
sign_terminal_receipt_v03,
terminal_receipt_id_v03,
)
from .proposal_forge import (
AUTHORSHIP_STATEMENT,
PROPOSAL_FORGE_PREFLIGHT_SCHEMA,
PROPOSAL_FORGE_SCHEMA,
PROPOSAL_PURPOSE,
LocalProposalForge,
OpaqueProposalHandle,
PromotionDisposition,
ProposalForgeError,
ProposalForgeOutcome,
ProposalPromotionResult,
ProposalReview,
QuarantinedProposal,
ReviewedFinalApplier,
)
from .protected_bootstrap_v05 import (
BOOTSTRAP_SCHEMA,
BOOTSTRAP_TARGET_SCHEMA,
PROTECTED_BOOTSTRAP_TARGETS_V05,
ProtectedBootstrapRequestV05,
ProtectedBootstrapResultV05,
ProtectedBootstrapTargetV05,
evaluate_protected_bootstrap_v05,
hnc_main,
local_gui_main,
main,
operator_main,
organism_main,
website_main,
)
from .quarantine import QUARANTINE_SCHEMA, QuarantineRecord
from .quorum import (
AUTHORITY_PERMIT_SCHEMA,
QUORUM_POLICY_SCHEMA,
AuthorityPermit,
AuthorityRole,
QuorumPolicyV0,
QuorumValidation,
evaluate_quorum,
)
from .receipts import (
RECEIPT_SCHEMA,
ReceiptKind,
ReceiptValidation,
ReceiptVerdict,
SignedReceipt,
sign_receipt,
validate_receipt,
)
from .recipient_proof_v02 import (
CHALLENGE_SCHEMA,
PROOF_SCHEMA,
RecipientChallengeV02,
RecipientEnrollmentV02,
RecipientProofError,
RecipientProofV02,
RecipientProofVerifierV02,
build_recipient_challenge_v02,
build_recipient_proof_v02,
verify_recipient_proof_v02,
)
from .release_boundary_v02 import (
CAPABILITY_POLICY_SCHEMA,
CAPABILITY_RECEIPT_SCHEMA,
RELEASE_BOUNDARY_SCHEMA,
CapabilityPolicyV02,
CapabilityReleaseResultV02,
ContinuityStateEvidenceV02,
EvidenceExpectationsV02,
LiveBindingEvidenceV02,
LocalDevelopmentMagicStarReleaseBoundaryV02,
LocalDevelopmentReleaseBoundaryV02,
ReleaseBoundaryError,
build_release_context_v02,
validate_capability_release_result_v02,
)
from .release_engine import (
LocalReleaseEngine,
ReleaseCode,
ReleaseDecision,
ReleaseDisposition,
ReleaseExecutionReceipt,
evaluate_local_release,
)
from .release_evidence_v02 import (
ORGAN_ROLES,
RELEASE_EVIDENCE_ROLES,
RELEASE_EVIDENCE_SCHEMA,
ReleaseEvidenceError,
ReleaseEvidenceV02,
assemble_release_evidence_v02,
build_organ_receipt_v02,
validate_release_evidence_trust_v02,
validate_release_evidence_v02,
)
from .release_state_v02 import (
EPAS_STATE_SCHEMA,
STATE_SCHEMA,
EPASChainSnapshot,
InMemoryEPASChainStoreV02,
InMemoryReleaseStateStoreV02,
OpaqueCustodyLease,
OpaqueEPASReservation,
ReleasePhase,
ReleaseStateError,
ReleaseStateSnapshot,
)
from .runtime_guard_v04 import (
RUNTIME_EFFECT_MANIFEST_SCHEMA,
RUNTIME_EFFECT_RULE_SCHEMA,
RUNTIME_GUARD_EXECUTION_SCHEMA,
RUNTIME_GUARD_LIFECYCLE_SCHEMA,
RUNTIME_GUARD_PREFLIGHT_SCHEMA,
RUNTIME_INTRUSION_PURPOSE,
RUNTIME_INTRUSION_SCHEMA,
AuditEffectRuleV04,
GuardedRuntimeCapabilityV04,
HNCRuntimeViolationRecorderV04,
RuntimeAuditGuardV04,
RuntimeEffectManifestV04,
RuntimeGuardError,
RuntimeGuardViolation,
audit_event_resource_commitment_v04,
decode_runtime_effect_manifest_v04,
)
from .runtime_intrusion_ledger_v04 import (
RUNTIME_INTRUSION_AUTHENTICATED_PROJECTION_SCHEMA,
RUNTIME_INTRUSION_ENTRY_SCHEMA,
RUNTIME_INTRUSION_LEDGER_SCHEMA,
RuntimeIntrusionLedgerError,
SQLiteRuntimeIntrusionLedgerV04,
)
from .schema import (
PLUMBER_MAGIC,
PLUMBER_PACKET_SCHEMA,
PLUMBER_SCHEMA_VERSION,
DenialCode,
PlumberPacketV0,
SchemaError,
format_timestamp,
freeze_mapping,
parse_timestamp,
require_aware_datetime,
require_ed25519_public_key,
require_ed25519_signature,
require_exact_keys,
require_fixed_decimal,
require_int,
require_mapping,
require_nonblank,
require_sha256,
thaw_json,
utc_now,
)
from .source_identity import (
SOURCE_IDENTITY_SCHEMA,
SourceIdentityV0,
build_source_identity,
build_source_identity_from_hnc_packet,
verify_source_identity,
)
from .spore_transport import (
MAX_SPORE_CIPHERTEXT_BYTES,
MAX_SPORE_FRAGMENT_BYTES,
MAX_SPORE_FRAGMENT_COUNT,
SPORE_FRAGMENT_SCHEMA,
SPORE_MANIFEST_SCHEMA,
SporeFragment,
SporeManifest,
fragment_ciphertext,
reassemble_ciphertext,
)
from .star_custody_v02 import (
PROTECTED_PACKET_MAGIC,
PROTECTED_PACKET_SCHEMA,
LocalDevelopmentStarCustodyV02,
ProtectedMagicStarPacketV02,
RegisteredCapabilityV02,
StarCustodyError,
validate_magic_star_hnc_packet_v02,
validate_magic_star_inner_carrier_capacity_v02,
)
from .sympathetic_identity import (
SYMPATHETIC_IDENTITY_SCHEMA,
SympatheticIdentityV0,
build_sympathetic_identity,
)
from .temporal_identity import (
TEMPORAL_IDENTITY_SCHEMA,
TemporalIdentityV0,
TemporalValidation,
build_temporal_identity,
validate_temporal_identity,
)
from .twin_rune_seal import TWIN_RUNE_SCHEMA, TwinRuneSealV0, build_twin_rune_seal
__all__ = [
"BOOTSTRAP_SCHEMA",
"BOOTSTRAP_TARGET_SCHEMA",
"PROTECTED_BOOTSTRAP_TARGETS_V05",
"ProtectedBootstrapRequestV05",
"ProtectedBootstrapResultV05",
"ProtectedBootstrapTargetV05",
"evaluate_protected_bootstrap_v05",
"hnc_main",
"local_gui_main",
"main",
"operator_main",
"organism_main",
"website_main",
"COMMAND_SCHEMA",
"DENIED_RECEIPT_SCHEMA",
"DISPATCH_SCHEMA",
"EXECUTOR_EVIDENCE_SCHEMA",
"LEDGER_SCHEMA",
"RELEASE_RECEIPT_SCHEMA",
"REVIEW_SCHEMA",
"AuthorityBindingV03",
"DeniedReceiptV03",
"DispatchClaimV03",
"DispatchClaimSignerV03",
"DurableTerminalLedgerV03",
"ExecutorOutcome",
"ExecutorTerminalEvidenceV03",
"LedgerClaimDisposition",
"LedgerClaimV03",
"OutOfProcessReleaseExecutorV03",
"ProductionReleaseBrokerError",
"ProductionReleaseBrokerV03",
"ProductionReleaseVerifierV03",
"ReceiptDisposition",
"ReleaseCommandV03",
"ReleaseReceiptV03",
"ReviewAuthorizationV03",
"SQLiteTerminalLedgerV03",
"TerminalReceiptSignerV03",
"TerminalReceiptV03",
"decode_executor_evidence_v03",
"decode_dispatch_claim_v03",
"decode_release_command_v03",
"decode_review_authorization_v03",
"decode_terminal_receipt_v03",
"sign_executor_evidence_v03",
"sign_dispatch_claim_v03",
"sign_review_authorization_v03",
"sign_terminal_receipt_v03",
"terminal_receipt_id_v03",
"RUNTIME_EFFECT_MANIFEST_SCHEMA",
"RUNTIME_EFFECT_RULE_SCHEMA",
"RUNTIME_GUARD_EXECUTION_SCHEMA",
"RUNTIME_GUARD_LIFECYCLE_SCHEMA",
"RUNTIME_GUARD_PREFLIGHT_SCHEMA",
"RUNTIME_INTRUSION_PURPOSE",
"RUNTIME_INTRUSION_SCHEMA",
"AuditEffectRuleV04",
"GuardedRuntimeCapabilityV04",
"HNCRuntimeViolationRecorderV04",
"RuntimeAuditGuardV04",
"RuntimeEffectManifestV04",
"RuntimeGuardError",
"RuntimeGuardViolation",
"audit_event_resource_commitment_v04",
"decode_runtime_effect_manifest_v04",
"RUNTIME_INTRUSION_AUTHENTICATED_PROJECTION_SCHEMA",
"RUNTIME_INTRUSION_ENTRY_SCHEMA",
"RUNTIME_INTRUSION_LEDGER_SCHEMA",
"RuntimeIntrusionLedgerError",
"SQLiteRuntimeIntrusionLedgerV04",
"AUTHORITY_PERMIT_SCHEMA",
"AUTHORIZATION_CHAIN_SCHEMA",
"AUTHORIZATION_ROLES",
"AUTHORSHIP_STATEMENT",
"AdmissionOutcome",
"AdmittedHNC",
"AuditEvent",
"AuthorityBindingV02",
"AuthorityPermit",
"AuthorityRole",
"AuthorizationChainError",
"AuthorizationChainV02",
"CAPABILITY_POLICY_SCHEMA",
"CAPABILITY_RECEIPT_SCHEMA",
"CHALLENGE_SCHEMA",
"CapabilityPolicyV02",
"CapabilityReleaseResultV02",
"ContentValidator",
"ContinuityStateEvidenceV02",
"CryptoContractError",
"DEFAULT_MAX_INGRESS_BYTES",
"DenialCode",
"EPASChainSnapshot",
"EPAS_STATE_SCHEMA",
"EnclaveCode",
"EnclaveConfigurationError",
"EnclaveDisposition",
"EvidenceExpectationsV02",
"GateClass",
"GateDecision",
"GateEvidence",
"GateVerdict",
"HNCPayloadBindingV0",
"HNC_PAYLOAD_BINDING_SCHEMA",
"IMPLEMENTATION_PROFILE_SHA256",
"INSECURE_OPT_IN_ACK",
"InMemoryEPASChainStoreV02",
"InMemoryReleaseStateStoreV02",
"IngressDisposition",
"LOCAL_DEVELOPMENT_MODE",
"LiveBindingEvidenceV02",
"LocalComputationResult",
"LocalDevelopmentEnclave",
"LocalDevelopmentMagicStarReleaseBoundaryV02",
"LocalDevelopmentReleaseBoundaryV02",
"LocalDevelopmentStarCustodyV02",
"LocalEnclaveAttestation",
"LocalEnclaveExecutionReceipt",
"LocalOSProtectionBoundary",
"LocalProposalForge",
"LocalReleaseEngine",
"MAX_OPERATOR_AAD_BYTES",
"MagicStarError",
"MagicStarV02",
"MasterKeyProvider",
"OBSERVER_TRANSCRIPT_SCHEMA",
"ORGAN_ROLES",
"OSProtectionError",
"OS_DURABLE_QUARANTINE_EVIDENCE_SCHEMA",
"OS_INGRESS_AAD_SCHEMA",
"OS_KEY_PREFLIGHT_SCHEMA",
"OS_PROTECTION_SCHEMA",
"OS_QUARANTINE_EVIDENCE_PURPOSE",
"OS_QUARANTINE_EVIDENCE_SCHEMA",
"OS_RUNTIME_GUARD_LIFECYCLE_SCHEMA",
"ObserverTranscriptV0",
"OpaqueCustodyLease",
"OpaqueEPASReservation",
"OpaqueHNCHandle",
"OpaqueProposalHandle",
"PENTAGRAM_ROUTE",
"PLUMBER_MAGIC",
"PLUMBER_PACKET_SCHEMA",
"PLUMBER_SCHEMA_VERSION",
"POINTS",
"POINT_ROLES",
"PROFILE_DESCRIPTOR",
"PROFILE_ID",
"PROOF_SCHEMA",
"PROPOSAL_FORGE_SCHEMA",
"PROPOSAL_FORGE_PREFLIGHT_SCHEMA",
"PROPOSAL_PURPOSE",
"PROTECTED_PACKET_MAGIC",
"PROTECTED_PACKET_SCHEMA",
"PROTOCOL_ID",
"PacketCode",
"PacketContractError",
"PacketDisposition",
"PacketInspection",
"PacketReplayGuard",
"PacketTrustPolicy",
"PlumberPacketV0",
"PromotionDisposition",
"ProposalForgeError",
"ProposalForgeOutcome",
"ProposalPromotionResult",
"ProposalReview",
"ProtectedMagicStarPacketV02",
"QUARANTINE_SCHEMA",
"QUORUM_POLICY_SCHEMA",
"QuarantineRecord",
"QuarantineEvidenceSink",
"QuarantinedHNC",
"QuarantinedProposal",
"QuorumPolicyV0",
"QuorumValidation",
"RAINBOW_FREQUENCIES",
"RAINBOW_SOURCE_SHA256",
"RECEIPT_SCHEMA",
"RELEASE_BOUNDARY_SCHEMA",
"RELEASE_EVIDENCE_ROLES",
"RELEASE_EVIDENCE_SCHEMA",
"REQUIRED_GATE_CLASSES",
"ReceiptKind",
"ReceiptValidation",
"ReceiptVerdict",
"RecipientChallengeV02",
"RecipientEnrollmentV02",
"RecipientProofError",
"RecipientProofV02",
"RecipientProofVerifierV02",
"RegisteredCapabilityV02",
"ReleaseBoundaryError",
"ReleaseCode",
"ReleaseDecision",
"ReleaseDisposition",
"ReleaseEvidenceError",
"ReleaseEvidenceV02",
"ReleaseExecutionReceipt",
"ReleasePhase",
"ReleaseStateError",
"ReleaseStateSnapshot",
"ReviewedFinalApplier",
"SOURCE_IDENTITY_SCHEMA",
"SOURCE_PROFILE_COMMITMENT",
"MAX_SPORE_CIPHERTEXT_BYTES",
"MAX_SPORE_FRAGMENT_BYTES",
"MAX_SPORE_FRAGMENT_COUNT",
"SPORE_FRAGMENT_SCHEMA",
"SPORE_MANIFEST_SCHEMA",
"STAR_AUTHORITY_ROLES",
"STATE_SCHEMA",
"SYMPATHETIC_IDENTITY_SCHEMA",
"SYNTHETIC_BREAKER_SCOPE",
"SchemaError",
"SignedReceipt",
"SourceIdentityV0",
"SporeFragment",
"SporeManifest",
"StarCustodyError",
"SympatheticIdentityV0",
"SyntheticBreakerCase",
"SyntheticBreakerReport",
"TEMPORAL_IDENTITY_SCHEMA",
"TWIN_RUNE_SCHEMA",
"TemporalIdentityV0",
"TemporalValidation",
"TwinRuneSealV0",
"add_packet_signature",
"assemble_authorization_chain_v02",
"assemble_magic_star_v02",
"assemble_release_evidence_v02",
"assert_public_summary_safe",
"b64url_decode",
"b64url_encode",
"bind_hnc_packet",
"build_authority_binding_v02",
"build_authorization_snapshot_v02",
"build_candidate_center_v02",
"build_continuity_decision_v02",
"build_custody_permit_v02",
"build_epas_precondition_v02",
"build_gate_context_commitment",
"build_heart_precondition_v02",
"build_heart_source_identity_commitment_v02",
"build_magic_star_point_v02",
"build_observer_transcript",
"build_organ_receipt_v02",
"build_recipient_challenge_v02",
"build_recipient_proof_v02",
"build_release_context_v02",
"build_source_identity",
"build_source_identity_from_hnc_packet",
"build_sympathetic_identity",
"build_temporal_identity",
"build_twin_rune_seal",
"canonical_json_bytes",
"component_commitment_v02",
"decode_canonical_json",
"domain_hash",
"ed25519_public_key_hex",
"evaluate_immune_gate",
"evaluate_local_release",
"evaluate_quorum",
"format_timestamp",
"fragment_ciphertext",
"freeze_mapping",
"generate_ed25519_private_key",
"heart_receipt_commitment_v02",
"hex_decode",
"inspect_plumber_packet",
"load_ed25519_private_key",
"load_ed25519_public_key",
"parse_timestamp",
"reassemble_ciphertext",
"require_aware_datetime",
"require_ed25519_public_key",
"require_ed25519_signature",
"require_exact_keys",
"require_fixed_decimal",
"require_int",
"require_mapping",
"require_nonblank",
"require_sha256",
"run_synthetic_offline_breaker_lab",
"sha256_hex",
"sign_component_v02",
"sign_ed25519",
"sign_receipt",
"thaw_json",
"utc_now",
"validate_authorization_chain_v02",
"validate_authorization_trust_v02",
"validate_capability_release_result_v02",
"validate_distinct_authorities_v02",
"validate_magic_star_hnc_packet_v02",
"validate_magic_star_inner_carrier_capacity_v02",
"validate_magic_star_v02",
"validate_receipt",
"validate_release_evidence_trust_v02",
"validate_release_evidence_v02",
"validate_temporal_identity",
"verify_component_v02",
"verify_ed25519",
"verify_recipient_proof_v02",
"verify_source_identity",
]
# Submodules own declarations; this package exposes one deterministic aggregate
# regardless of how imports are grouped in this file.
__all__ = sorted(__all__)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165"""In-memory, metadata-only audit records for the Plumber protocol."""
from __future__ import annotations
from collections.abc import Mapping, Sequence
from dataclasses import dataclass
from datetime import datetime
from typing import Any, Self
from .crypto import domain_hash
from .schema import (
DenialCode,
SchemaError,
format_timestamp,
freeze_mapping,
parse_timestamp,
require_exact_keys,
require_mapping,
require_nonblank,
require_sha256,
)
_FORBIDDEN_PUBLIC_KEYS = {
"plaintext",
"decrypted_payload",
"private_key",
"root_key",
"session_key",
"raw_share",
"secret_value",
}
def assert_public_summary_safe(value: Mapping[str, Any]) -> None:
"""Reject common secret-bearing fields before a summary crosses a boundary."""
def walk(item: Any) -> None:
if isinstance(item, Mapping):
for key, nested in item.items():
if not isinstance(key, str) or key.casefold() in _FORBIDDEN_PUBLIC_KEYS:
raise SchemaError(DenialCode.INVALID_SCHEMA, field="public_summary")
walk(nested)
elif isinstance(item, Sequence) and not isinstance(item, (str, bytes, bytearray)):
for nested in item:
walk(nested)
walk(value)
_AUDIT_FIELDS = (
"event_type",
"trace_id",
"packet_identity",
"session_identity",
"outcome",
"denial_codes",
"evidence_commitments",
"recorded_at",
"event_commitment",
)
@dataclass(frozen=True, slots=True)
class AuditEvent:
event_type: str
trace_id: str
packet_identity: str
session_identity: str
outcome: str
denial_codes: tuple[str, ...]
evidence_commitments: Mapping[str, str]
recorded_at: str
event_commitment: str
def __post_init__(self) -> None:
for field in ("event_type", "trace_id", "packet_identity", "session_identity", "outcome"):
require_nonblank(getattr(self, field), field=field)
parse_timestamp(self.recorded_at, field="recorded_at")
require_sha256(self.event_commitment, field="event_commitment")
if not isinstance(self.denial_codes, tuple) or any(
not isinstance(code, str) or not code for code in self.denial_codes
):
raise SchemaError(DenialCode.INVALID_TYPE, field="denial_codes")
if tuple(sorted(set(self.denial_codes))) != self.denial_codes:
raise SchemaError(DenialCode.INVALID_VALUE, field="denial_codes")
evidence = require_mapping(self.evidence_commitments, field="evidence_commitments", nonempty=False)
for key, commitment in evidence.items():
require_nonblank(key, field="evidence_commitments.key")
require_sha256(commitment, field="evidence_commitments.value")
object.__setattr__(
self,
"evidence_commitments",
freeze_mapping(evidence, field="evidence_commitments", nonempty=False),
)
if domain_hash("aureon.plumber.audit.v0", self.commitment_payload()) != self.event_commitment:
raise SchemaError(DenialCode.INVALID_VALUE, field="event_commitment")
@classmethod
def build(
cls,
*,
event_type: str,
trace_id: str,
packet_identity: str,
session_identity: str,
outcome: str,
denial_codes: Sequence[DenialCode | str] = (),
evidence_commitments: Mapping[str, str] | None = None,
recorded_at: datetime,
) -> Self:
normalized_codes = tuple(sorted({str(code) for code in denial_codes}))
normalized_evidence = dict(evidence_commitments or {})
recorded_at_text = format_timestamp(recorded_at)
values = {
"event_type": event_type,
"trace_id": trace_id,
"packet_identity": packet_identity,
"session_identity": session_identity,
"outcome": outcome,
"denial_codes": normalized_codes,
"evidence_commitments": normalized_evidence,
"recorded_at": recorded_at_text,
}
return cls(
event_type=event_type,
trace_id=trace_id,
packet_identity=packet_identity,
session_identity=session_identity,
outcome=outcome,
denial_codes=normalized_codes,
evidence_commitments=normalized_evidence,
recorded_at=recorded_at_text,
event_commitment=domain_hash("aureon.plumber.audit.v0", values),
)
@classmethod
def from_dict(cls, value: Mapping[str, Any]) -> Self:
parsed = require_exact_keys(value, _AUDIT_FIELDS, field="audit_event")
if not isinstance(parsed["denial_codes"], list):
raise SchemaError(DenialCode.INVALID_TYPE, field="denial_codes")
parsed["denial_codes"] = tuple(parsed["denial_codes"])
return cls(**parsed)
def commitment_payload(self) -> dict[str, Any]:
return {
"event_type": self.event_type,
"trace_id": self.trace_id,
"packet_identity": self.packet_identity,
"session_identity": self.session_identity,
"outcome": self.outcome,
"denial_codes": list(self.denial_codes),
"evidence_commitments": dict(self.evidence_commitments),
"recorded_at": self.recorded_at,
}
def to_dict(self) -> dict[str, Any]:
return {**self.commitment_payload(), "event_commitment": self.event_commitment}
def public_summary(self) -> dict[str, Any]:
summary = self.to_dict()
assert_public_summary_safe(summary)
return summary
__all__ = ["AuditEvent", "assert_public_summary_safe"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652"""Continuity, authorization, five permits and custody join for v0.2."""
from __future__ import annotations
import time
from collections.abc import Callable, Mapping, Sequence
from dataclasses import dataclass
from typing import Any
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
from .crypto import domain_hash
from .magic_star_v02 import (
POINT_ROLES,
PROFILE_ID,
PROTOCOL_ID,
SOURCE_PROFILE_COMMITMENT,
AuthorityBindingV02,
MagicStarError,
component_commitment_v02,
sign_component_v02,
verify_component_v02,
)
from .schema import freeze_mapping, thaw_json
AUTHORIZATION_CHAIN_SCHEMA = "aureon.plumber.magic-star.authorization-chain.v02"
AUTHORIZATION_ROLES = ("CONTINUITY", "AUTHORIZATION", *POINT_ROLES, "CUSTODY")
_MAX_COMPONENT_TTL_MS = 5 * 60 * 1000
_PROFILE_FIELDS = {
"protocol_id": PROTOCOL_ID,
"profile_id": PROFILE_ID,
"source_profile_commitment": SOURCE_PROFILE_COMMITMENT,
}
_CONTINUITY_FIELDS = {
*_PROFILE_FIELDS,
"packet_commitment",
"session_id",
"purpose",
"star_commitment",
"release_proof_commitment",
"previous_decision_head_sha256",
"revocation_epoch",
"verdict",
"issued_at_ms",
"expires_at_ms",
}
_AUTHORIZATION_FIELDS = {
*_PROFILE_FIELDS,
"packet_commitment",
"session_id",
"purpose",
"release_context_sha256",
"recipient_proof_commitment",
"star_commitment",
"epas_commitment",
"release_proof_commitment",
"continuity_commitment",
"live_binding_sha256",
"runtime_measurement_sha256",
"policy_measurement_sha256",
"verdict",
"issued_at_ms",
"expires_at_ms",
}
_PERMIT_FIELDS = {
*_PROFILE_FIELDS,
"role",
"packet_commitment",
"session_id",
"purpose",
"authorization_commitment",
"share_binding_sha256",
"verdict",
"issued_at_ms",
"expires_at_ms",
}
_CUSTODY_FIELDS = {
*_PROFILE_FIELDS,
"packet_commitment",
"session_id",
"purpose",
"star_commitment",
"release_proof_commitment",
"authorization_commitment",
"permit_roles",
"permit_commitments",
"share_bindings",
"all_five_required",
"authorized_at_ms",
"expires_at_ms",
}
class AuthorizationChainError(ValueError):
def __init__(self, code: str) -> None:
self.code = str(code)
super().__init__(self.code)
def _sha256(value: object, *, code: str) -> str:
if not isinstance(value, str) or len(value) != 64 or any(c not in "0123456789abcdef" for c in value):
raise AuthorizationChainError(code)
return value
def _identifier(value: object, *, code: str) -> str:
if (
not isinstance(value, str)
or not value
or len(value) > 128
or any(not (c.isascii() and (c.isalnum() or c in "._:/-")) for c in value)
):
raise AuthorizationChainError(code)
return value
def _uint(value: object, *, code: str) -> int:
if isinstance(value, bool) or not isinstance(value, int) or value < 0:
raise AuthorizationChainError(code)
return value
def _system_now_ms() -> int:
return time.time_ns() // 1_000_000
def _require_profile_and_shape(payload: Mapping[str, Any], fields: set[str], *, code: str) -> None:
if set(payload) != fields or any(payload.get(key) != value for key, value in _PROFILE_FIELDS.items()):
raise AuthorizationChainError(code)
def _validate_window(payload: Mapping[str, Any], *, now: int, prefix: str) -> None:
issued = _uint(payload.get("issued_at_ms"), code=f"{prefix}_issued_at_invalid")
expires = _uint(payload.get("expires_at_ms"), code=f"{prefix}_expires_at_invalid")
if issued > now or expires <= now or expires <= issued or expires - issued > _MAX_COMPONENT_TTL_MS:
raise AuthorizationChainError(f"{prefix}_time_window_invalid")
def validate_authorization_trust_v02(trust: Mapping[str, AuthorityBindingV02]) -> None:
if set(trust) != set(AUTHORIZATION_ROLES):
raise AuthorizationChainError("authorization_authority_set_incomplete")
bindings = [trust[role] for role in AUTHORIZATION_ROLES]
for role, binding in zip(AUTHORIZATION_ROLES, bindings, strict=True):
if not isinstance(binding, AuthorityBindingV02) or binding.role != role:
raise AuthorizationChainError("authorization_authority_binding_mismatch")
for attribute, code in (
("public_key_hex", "authorization_keys_not_distinct"),
("key_id", "authorization_key_ids_not_distinct"),
("principal", "authorization_principals_not_distinct"),
("issuer", "authorization_issuers_not_distinct"),
):
values = [getattr(binding, attribute) for binding in bindings]
if len(set(values)) != len(values):
raise AuthorizationChainError(code)
def build_continuity_decision_v02(
*,
packet_commitment: str,
session_id: str,
purpose: str,
star_commitment: str,
release_proof_commitment: str,
previous_decision_head_sha256: str,
revocation_epoch: int,
verdict: str,
issued_at_ms: int,
expires_at_ms: int,
authority: AuthorityBindingV02,
private_key: Ed25519PrivateKey,
) -> dict[str, Any]:
if authority.role != "CONTINUITY":
raise AuthorizationChainError("continuity_authority_role_invalid")
payload: dict[str, Any] = {
**_PROFILE_FIELDS,
"packet_commitment": _sha256(packet_commitment, code="packet_commitment_invalid"),
"session_id": _identifier(session_id, code="session_id_invalid"),
"purpose": _identifier(purpose, code="purpose_invalid"),
"star_commitment": _sha256(star_commitment, code="star_commitment_invalid"),
"release_proof_commitment": _sha256(
release_proof_commitment, code="release_proof_commitment_invalid"
),
"previous_decision_head_sha256": _sha256(
previous_decision_head_sha256, code="continuity_head_invalid"
),
"revocation_epoch": _uint(revocation_epoch, code="revocation_epoch_invalid"),
"verdict": str(verdict),
"issued_at_ms": _uint(issued_at_ms, code="continuity_issued_at_invalid"),
"expires_at_ms": _uint(expires_at_ms, code="continuity_expires_at_invalid"),
}
if payload["expires_at_ms"] <= payload["issued_at_ms"]:
raise AuthorizationChainError("continuity_time_window_invalid")
try:
return sign_component_v02(
component_type="CONTINUITY_DECISION",
authority=authority,
payload=payload,
private_key=private_key,
)
except MagicStarError as exc:
raise AuthorizationChainError(exc.code) from exc
def build_authorization_snapshot_v02(
*,
packet_commitment: str,
session_id: str,
purpose: str,
release_context_sha256: str,
recipient_proof_commitment: str,
star_commitment: str,
epas_commitment: str,
release_proof_commitment: str,
continuity_commitment: str,
live_binding_sha256: str,
runtime_measurement_sha256: str,
policy_measurement_sha256: str,
verdict: str,
issued_at_ms: int,
expires_at_ms: int,
authority: AuthorityBindingV02,
private_key: Ed25519PrivateKey,
) -> dict[str, Any]:
if authority.role != "AUTHORIZATION":
raise AuthorizationChainError("authorization_snapshot_authority_role_invalid")
payload: dict[str, Any] = {
**_PROFILE_FIELDS,
"packet_commitment": _sha256(packet_commitment, code="packet_commitment_invalid"),
"session_id": _identifier(session_id, code="session_id_invalid"),
"purpose": _identifier(purpose, code="purpose_invalid"),
"release_context_sha256": _sha256(release_context_sha256, code="release_context_invalid"),
"recipient_proof_commitment": _sha256(
recipient_proof_commitment, code="recipient_proof_commitment_invalid"
),
"star_commitment": _sha256(star_commitment, code="star_commitment_invalid"),
"epas_commitment": _sha256(epas_commitment, code="epas_commitment_invalid"),
"release_proof_commitment": _sha256(
release_proof_commitment, code="release_proof_commitment_invalid"
),
"continuity_commitment": _sha256(
continuity_commitment, code="continuity_commitment_invalid"
),
"live_binding_sha256": _sha256(live_binding_sha256, code="live_binding_invalid"),
"runtime_measurement_sha256": _sha256(
runtime_measurement_sha256, code="runtime_measurement_invalid"
),
"policy_measurement_sha256": _sha256(
policy_measurement_sha256, code="policy_measurement_invalid"
),
"verdict": str(verdict),
"issued_at_ms": _uint(issued_at_ms, code="authorization_issued_at_invalid"),
"expires_at_ms": _uint(expires_at_ms, code="authorization_expires_at_invalid"),
}
if payload["expires_at_ms"] <= payload["issued_at_ms"]:
raise AuthorizationChainError("authorization_time_window_invalid")
try:
return sign_component_v02(
component_type="AUTHORIZATION_SNAPSHOT",
authority=authority,
payload=payload,
private_key=private_key,
)
except MagicStarError as exc:
raise AuthorizationChainError(exc.code) from exc
def build_custody_permit_v02(
*,
role: str,
packet_commitment: str,
session_id: str,
purpose: str,
authorization_commitment: str,
share_binding_sha256: str,
verdict: str,
issued_at_ms: int,
expires_at_ms: int,
authority: AuthorityBindingV02,
private_key: Ed25519PrivateKey,
) -> dict[str, Any]:
if role not in POINT_ROLES or authority.role != role:
raise AuthorizationChainError("custody_permit_role_invalid")
payload: dict[str, Any] = {
**_PROFILE_FIELDS,
"role": role,
"packet_commitment": _sha256(packet_commitment, code="packet_commitment_invalid"),
"session_id": _identifier(session_id, code="session_id_invalid"),
"purpose": _identifier(purpose, code="purpose_invalid"),
"authorization_commitment": _sha256(
authorization_commitment, code="authorization_commitment_invalid"
),
"share_binding_sha256": _sha256(
share_binding_sha256, code="share_binding_invalid"
),
"verdict": str(verdict),
"issued_at_ms": _uint(issued_at_ms, code="custody_permit_issued_at_invalid"),
"expires_at_ms": _uint(expires_at_ms, code="custody_permit_expires_at_invalid"),
}
if payload["expires_at_ms"] <= payload["issued_at_ms"]:
raise AuthorizationChainError("custody_permit_time_window_invalid")
try:
return sign_component_v02(
component_type="CUSTODY_PERMIT",
authority=authority,
payload=payload,
private_key=private_key,
)
except MagicStarError as exc:
raise AuthorizationChainError(exc.code) from exc
@dataclass(frozen=True, slots=True)
class AuthorizationChainV02:
schema: str
continuity_decision: Mapping[str, Any]
authorization_snapshot: Mapping[str, Any]
permits: tuple[Mapping[str, Any], ...]
custody_authorization: Mapping[str, Any]
def __post_init__(self) -> None:
for field_name in (
"continuity_decision",
"authorization_snapshot",
"custody_authorization",
):
object.__setattr__(
self,
field_name,
freeze_mapping(getattr(self, field_name), field=field_name),
)
object.__setattr__(
self,
"permits",
tuple(
freeze_mapping(permit, field=f"permits[{index}]")
for index, permit in enumerate(self.permits)
),
)
def public_dict(self) -> dict[str, Any]:
return {
"schema": self.schema,
"continuity_decision": thaw_json(self.continuity_decision),
"authorization_snapshot": thaw_json(self.authorization_snapshot),
"permits": [thaw_json(permit) for permit in self.permits],
"custody_authorization": thaw_json(self.custody_authorization),
}
@property
def commitment(self) -> str:
return domain_hash("AUREON-PLUMBER-V02-AUTHORIZATION-CHAIN", self.public_dict())
def assemble_authorization_chain_v02(
*,
continuity_decision: Mapping[str, Any],
authorization_snapshot: Mapping[str, Any],
permits: Sequence[Mapping[str, Any]],
trust: Mapping[str, AuthorityBindingV02],
custody_authority: AuthorityBindingV02,
custody_private_key: Ed25519PrivateKey,
trusted_now_ms: Callable[[], int] = _system_now_ms,
) -> AuthorizationChainV02:
validate_authorization_trust_v02(trust)
if trust["CUSTODY"] != custody_authority:
raise AuthorizationChainError("custody_authority_mismatch")
now = _uint(trusted_now_ms(), code="trusted_time_invalid")
try:
continuity = verify_component_v02(
continuity_decision,
expected_type="CONTINUITY_DECISION",
expected_authority=trust["CONTINUITY"],
)
authorization = verify_component_v02(
authorization_snapshot,
expected_type="AUTHORIZATION_SNAPSHOT",
expected_authority=trust["AUTHORIZATION"],
)
except MagicStarError as exc:
raise AuthorizationChainError(exc.code) from exc
if continuity.get("verdict") != "ELIGIBLE" or now >= _uint(
continuity.get("expires_at_ms"), code="continuity_expires_at_invalid"
):
raise AuthorizationChainError("continuity_not_eligible")
if authorization.get("verdict") != "AUTHORIZED" or now >= _uint(
authorization.get("expires_at_ms"), code="authorization_expires_at_invalid"
):
raise AuthorizationChainError("authorization_snapshot_denied")
_require_profile_and_shape(
continuity, _CONTINUITY_FIELDS, code="continuity_profile_or_shape_invalid"
)
_require_profile_and_shape(
authorization,
_AUTHORIZATION_FIELDS,
code="authorization_profile_or_shape_invalid",
)
_validate_window(continuity, now=now, prefix="continuity")
_validate_window(authorization, now=now, prefix="authorization")
continuity_commitment = component_commitment_v02(continuity_decision)
if authorization.get("continuity_commitment") != continuity_commitment:
raise AuthorizationChainError("authorization_continuity_join_mismatch")
for field in ("packet_commitment", "session_id", "purpose", "star_commitment", "release_proof_commitment"):
if authorization.get(field) != continuity.get(field):
raise AuthorizationChainError(f"authorization_continuity_join_mismatch_{field}")
if len(permits) != len(POINT_ROLES):
raise AuthorizationChainError("all_five_custody_permits_required")
authorization_commitment = component_commitment_v02(authorization_snapshot)
permit_components: list[dict[str, Any]] = []
permit_payloads: list[dict[str, Any]] = []
for role, permit in zip(POINT_ROLES, permits, strict=True):
try:
payload = verify_component_v02(
permit,
expected_type="CUSTODY_PERMIT",
expected_authority=trust[role],
)
except MagicStarError as exc:
raise AuthorizationChainError(exc.code) from exc
if payload.get("role") != role:
raise AuthorizationChainError("custody_permit_order_or_role_mismatch")
_require_profile_and_shape(
payload, _PERMIT_FIELDS, code="custody_permit_profile_or_shape_invalid"
)
_validate_window(payload, now=now, prefix="custody_permit")
if payload.get("verdict") != "PERMIT" or now >= _uint(
payload.get("expires_at_ms"), code="custody_permit_expires_at_invalid"
):
raise AuthorizationChainError("custody_permit_denied")
if payload.get("authorization_commitment") != authorization_commitment:
raise AuthorizationChainError("custody_permit_authorization_join_mismatch")
for field in ("packet_commitment", "session_id", "purpose"):
if payload.get(field) != authorization.get(field):
raise AuthorizationChainError(f"custody_permit_join_mismatch_{field}")
permit_components.append(dict(permit))
permit_payloads.append(payload)
custody_payload = {
**_PROFILE_FIELDS,
"packet_commitment": authorization["packet_commitment"],
"session_id": authorization["session_id"],
"purpose": authorization["purpose"],
"star_commitment": authorization["star_commitment"],
"release_proof_commitment": authorization["release_proof_commitment"],
"authorization_commitment": authorization_commitment,
"permit_roles": list(POINT_ROLES),
"permit_commitments": [
component_commitment_v02(component) for component in permit_components
],
"share_bindings": [payload["share_binding_sha256"] for payload in permit_payloads],
"all_five_required": True,
"authorized_at_ms": now,
"expires_at_ms": min(
_uint(payload["expires_at_ms"], code="custody_permit_expires_at_invalid")
for payload in permit_payloads
),
}
try:
custody_authorization = sign_component_v02(
component_type="CUSTODY_AUTHORIZATION",
authority=custody_authority,
payload=custody_payload,
private_key=custody_private_key,
)
except MagicStarError as exc:
raise AuthorizationChainError(exc.code) from exc
chain = AuthorizationChainV02(
schema=AUTHORIZATION_CHAIN_SCHEMA,
continuity_decision=dict(continuity_decision),
authorization_snapshot=dict(authorization_snapshot),
permits=tuple(permit_components),
custody_authorization=custody_authorization,
)
validate_authorization_chain_v02(chain, trust=trust, trusted_now_ms=trusted_now_ms)
return chain
def validate_authorization_chain_v02(
chain: AuthorizationChainV02,
*,
trust: Mapping[str, AuthorityBindingV02],
expected_previous_decision_head_sha256: str | None = None,
expected_revocation_epoch: int | None = None,
expected_join: Mapping[str, Any] | None = None,
trusted_now_ms: Callable[[], int] = _system_now_ms,
) -> dict[str, Any]:
if not isinstance(chain, AuthorizationChainV02) or chain.schema != AUTHORIZATION_CHAIN_SCHEMA:
raise AuthorizationChainError("authorization_chain_schema_invalid")
validate_authorization_trust_v02(trust)
now = _uint(trusted_now_ms(), code="trusted_time_invalid")
try:
continuity = verify_component_v02(
chain.continuity_decision,
expected_type="CONTINUITY_DECISION",
expected_authority=trust["CONTINUITY"],
)
authorization = verify_component_v02(
chain.authorization_snapshot,
expected_type="AUTHORIZATION_SNAPSHOT",
expected_authority=trust["AUTHORIZATION"],
)
except MagicStarError as exc:
raise AuthorizationChainError(exc.code) from exc
if continuity.get("verdict") != "ELIGIBLE" or authorization.get("verdict") != "AUTHORIZED":
raise AuthorizationChainError("authorization_chain_not_approved")
_require_profile_and_shape(
continuity, _CONTINUITY_FIELDS, code="continuity_profile_or_shape_invalid"
)
_require_profile_and_shape(
authorization,
_AUTHORIZATION_FIELDS,
code="authorization_profile_or_shape_invalid",
)
_validate_window(continuity, now=now, prefix="continuity")
_validate_window(authorization, now=now, prefix="authorization")
if expected_previous_decision_head_sha256 is not None and continuity.get(
"previous_decision_head_sha256"
) != _sha256(
expected_previous_decision_head_sha256,
code="continuity_head_invalid",
):
raise AuthorizationChainError("continuity_head_mismatch")
if expected_revocation_epoch is not None and continuity.get("revocation_epoch") != _uint(
expected_revocation_epoch, code="revocation_epoch_invalid"
):
raise AuthorizationChainError("continuity_revocation_epoch_mismatch")
if authorization.get("continuity_commitment") != component_commitment_v02(
chain.continuity_decision
):
raise AuthorizationChainError("authorization_continuity_join_mismatch")
for field in ("packet_commitment", "session_id", "purpose", "star_commitment", "release_proof_commitment"):
if authorization.get(field) != continuity.get(field):
raise AuthorizationChainError(f"authorization_continuity_join_mismatch_{field}")
if len(chain.permits) != len(POINT_ROLES):
raise AuthorizationChainError("all_five_custody_permits_required")
authorization_commitment = component_commitment_v02(chain.authorization_snapshot)
permit_commitments: list[str] = []
share_bindings: list[str] = []
for role, permit in zip(POINT_ROLES, chain.permits, strict=True):
try:
payload = verify_component_v02(
permit,
expected_type="CUSTODY_PERMIT",
expected_authority=trust[role],
)
except MagicStarError as exc:
raise AuthorizationChainError(exc.code) from exc
if payload.get("role") != role or payload.get("verdict") != "PERMIT":
raise AuthorizationChainError("custody_permit_order_or_verdict_invalid")
_require_profile_and_shape(
payload, _PERMIT_FIELDS, code="custody_permit_profile_or_shape_invalid"
)
_validate_window(payload, now=now, prefix="custody_permit")
if payload.get("authorization_commitment") != authorization_commitment:
raise AuthorizationChainError("custody_permit_authorization_join_mismatch")
for field in ("packet_commitment", "session_id", "purpose"):
if payload.get(field) != authorization.get(field):
raise AuthorizationChainError(f"custody_permit_join_mismatch_{field}")
permit_commitments.append(component_commitment_v02(permit))
share_bindings.append(_sha256(payload.get("share_binding_sha256"), code="share_binding_invalid"))
try:
custody = verify_component_v02(
chain.custody_authorization,
expected_type="CUSTODY_AUTHORIZATION",
expected_authority=trust["CUSTODY"],
)
except MagicStarError as exc:
raise AuthorizationChainError(exc.code) from exc
_require_profile_and_shape(
custody, _CUSTODY_FIELDS, code="custody_authorization_profile_or_shape_invalid"
)
expected = {
"packet_commitment": authorization["packet_commitment"],
"session_id": authorization["session_id"],
"purpose": authorization["purpose"],
"star_commitment": authorization["star_commitment"],
"release_proof_commitment": authorization["release_proof_commitment"],
"authorization_commitment": authorization_commitment,
"permit_roles": list(POINT_ROLES),
"permit_commitments": permit_commitments,
"share_bindings": share_bindings,
"all_five_required": True,
}
if any(custody.get(key) != value for key, value in expected.items()):
raise AuthorizationChainError("custody_authorization_join_mismatch")
custody_authorized_at = _uint(
custody.get("authorized_at_ms"), code="custody_authorization_issued_at_invalid"
)
custody_expires = _uint(
custody.get("expires_at_ms"), code="custody_authorization_expiry_invalid"
)
expected_custody_expiry = min(
_uint(
verify_component_v02(
permit,
expected_type="CUSTODY_PERMIT",
expected_authority=trust[role],
).get("expires_at_ms"),
code="custody_permit_expires_at_invalid",
)
for role, permit in zip(POINT_ROLES, chain.permits, strict=True)
)
if custody_authorized_at > now or custody_expires <= now or custody_expires != expected_custody_expiry:
raise AuthorizationChainError("custody_authorization_time_window_invalid")
summary = {
"valid": True,
**{key: authorization[key] for key in (
"packet_commitment",
"session_id",
"purpose",
"release_context_sha256",
"recipient_proof_commitment",
"star_commitment",
"epas_commitment",
"release_proof_commitment",
"live_binding_sha256",
"runtime_measurement_sha256",
"policy_measurement_sha256",
)},
"authorization_commitment": authorization_commitment,
"custody_authorization_commitment": component_commitment_v02(
chain.custody_authorization
),
"authorization_chain_commitment": chain.commitment,
"permit_count": len(permit_commitments),
"share_bindings": share_bindings,
"expires_at_ms": min(
_uint(continuity["expires_at_ms"], code="continuity_expires_at_invalid"),
_uint(
authorization["expires_at_ms"],
code="authorization_expires_at_invalid",
),
custody_expires,
),
}
if expected_join is not None:
for key, value in expected_join.items():
if summary.get(key) != value:
raise AuthorizationChainError(f"authorization_expected_join_mismatch_{key}")
return summary
__all__ = [
"AUTHORIZATION_CHAIN_SCHEMA",
"AUTHORIZATION_ROLES",
"AuthorizationChainError",
"AuthorizationChainV02",
"assemble_authorization_chain_v02",
"build_authorization_snapshot_v02",
"build_continuity_decision_v02",
"build_custody_permit_v02",
"validate_authorization_chain_v02",
"validate_authorization_trust_v02",
]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160"""Synthetic, offline-only tamper lab for the Plumber/HNC boundary.
The lab accepts no caller packet, key, path, endpoint, or production target.
It creates one disposable in-memory fixture and suppresses decoder details,
plaintext, ciphertext, and key material from its report.
"""
from __future__ import annotations
import re
from dataclasses import dataclass
from typing import Any
from .crypto import domain_hash
from .schema import DenialCode, SchemaError, require_sha256
SYNTHETIC_BREAKER_SCOPE = "synthetic_offline_only"
_CASE_RE = re.compile(r"^[a-z][a-z0-9_]{0,63}$")
@dataclass(frozen=True, slots=True)
class SyntheticBreakerCase:
name: str
tamper_rejected: bool
result_code: str
def __post_init__(self) -> None:
if not isinstance(self.name, str) or _CASE_RE.fullmatch(self.name) is None:
raise SchemaError(DenialCode.INVALID_VALUE, field="case.name")
if type(self.tamper_rejected) is not bool:
raise SchemaError(DenialCode.INVALID_TYPE, field="case.tamper_rejected")
if self.result_code not in {"rejected", "unexpected_accept", "lab_failure"}:
raise SchemaError(DenialCode.INVALID_VALUE, field="case.result_code")
if self.tamper_rejected != (self.result_code == "rejected"):
raise SchemaError(DenialCode.INVALID_VALUE, field="case.result_code")
def public_summary(self) -> dict[str, Any]:
return {
"name": self.name,
"tamper_rejected": self.tamper_rejected,
"result_code": self.result_code,
}
@dataclass(frozen=True, slots=True)
class SyntheticBreakerReport:
lab_scope: str
synthetic_packet_commitment: str
cases: tuple[SyntheticBreakerCase, ...]
all_tamper_rejected: bool
plaintext_exposed: bool
production_validation: bool
report_commitment: str
def __post_init__(self) -> None:
if self.lab_scope != SYNTHETIC_BREAKER_SCOPE:
raise SchemaError(DenialCode.INVALID_VALUE, field="lab_scope")
require_sha256(self.synthetic_packet_commitment, field="synthetic_packet_commitment")
if not self.cases or any(not isinstance(case, SyntheticBreakerCase) for case in self.cases):
raise SchemaError(DenialCode.INVALID_TYPE, field="cases")
names = tuple(case.name for case in self.cases)
if tuple(sorted(set(names))) != names:
raise SchemaError(DenialCode.INVALID_VALUE, field="cases")
if self.all_tamper_rejected != all(case.tamper_rejected for case in self.cases):
raise SchemaError(DenialCode.INVALID_VALUE, field="all_tamper_rejected")
if self.plaintext_exposed is not False or self.production_validation is not False:
raise SchemaError(DenialCode.INVALID_VALUE, field="lab_scope")
require_sha256(self.report_commitment, field="report_commitment")
if domain_hash("aureon.plumber.synthetic-breaker-report.v0", self.commitment_payload()) != (
self.report_commitment
):
raise SchemaError(DenialCode.INVALID_VALUE, field="report_commitment")
def commitment_payload(self) -> dict[str, Any]:
return {
"lab_scope": self.lab_scope,
"synthetic_packet_commitment": self.synthetic_packet_commitment,
"cases": [case.public_summary() for case in self.cases],
"all_tamper_rejected": self.all_tamper_rejected,
"plaintext_exposed": self.plaintext_exposed,
"production_validation": self.production_validation,
}
def public_summary(self) -> dict[str, Any]:
return {**self.commitment_payload(), "report_commitment": self.report_commitment}
def run_synthetic_offline_breaker_lab() -> SyntheticBreakerReport:
"""Run the existing HNC tamper checks against a fixed synthetic fixture."""
from aureon.harmonic.hnc_quantum_packet_crypto import (
build_hnc_quantum_packet,
run_hnc_packet_breaker_checks,
)
synthetic_key = b"aureon-plumber-synthetic-key-32b"
synthetic_packet = build_hnc_quantum_packet(
b"synthetic-offline-breaker-fixture",
synthetic_key,
purpose="aureon.plumber.synthetic-breaker",
nonce=b"breaker-lab!",
)
raw_report = run_hnc_packet_breaker_checks(synthetic_packet, synthetic_key)
raw_cases = raw_report.get("checks")
if not isinstance(raw_cases, list):
raw_cases = []
cases: list[SyntheticBreakerCase] = []
for item in raw_cases:
if not isinstance(item, dict):
continue
name = item.get("name")
if not isinstance(name, str) or _CASE_RE.fullmatch(name) is None:
continue
passed = item.get("passed") is True
cases.append(
SyntheticBreakerCase(
name=name,
tamper_rejected=passed,
result_code="rejected" if passed else "unexpected_accept",
)
)
if not cases:
cases = [
SyntheticBreakerCase(
name="lab_setup",
tamper_rejected=False,
result_code="lab_failure",
)
]
ordered = tuple(sorted(cases, key=lambda item: item.name))
packet_commitment = require_sha256(
synthetic_packet.get("packet_sha256"),
field="synthetic_packet_commitment",
)
all_tamper_rejected = all(case.tamper_rejected for case in ordered)
values = {
"lab_scope": SYNTHETIC_BREAKER_SCOPE,
"synthetic_packet_commitment": packet_commitment,
"cases": [case.public_summary() for case in ordered],
"all_tamper_rejected": all_tamper_rejected,
"plaintext_exposed": False,
"production_validation": False,
}
return SyntheticBreakerReport(
lab_scope=SYNTHETIC_BREAKER_SCOPE,
synthetic_packet_commitment=packet_commitment,
cases=ordered,
all_tamper_rejected=all_tamper_rejected,
plaintext_exposed=False,
production_validation=False,
report_commitment=domain_hash("aureon.plumber.synthetic-breaker-report.v0", values),
)
__all__ = [
"SYNTHETIC_BREAKER_SCOPE",
"SyntheticBreakerCase",
"SyntheticBreakerReport",
"run_synthetic_offline_breaker_lab",
]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307"""Small, strict cryptographic helpers for the Aureon Plumber v0 protocol.
This module deliberately implements no packet encryption or key custody. It
provides deterministic encoding, hashes, and Ed25519 signatures for the
metadata contracts used by the foundational Plumber modules. Public HNC
geometry and observer values are authenticated context, never secret entropy.
"""
from __future__ import annotations
import base64
import binascii
import hashlib
import json
import re
from collections.abc import Mapping, Sequence
from typing import Any, cast
from cryptography.exceptions import InvalidSignature
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric.ed25519 import (
Ed25519PrivateKey,
Ed25519PublicKey,
)
_B64URL_RE = re.compile(r"^[A-Za-z0-9_-]+$")
_HEX_RE = re.compile(r"^[0-9a-f]+$")
class CryptoContractError(ValueError):
"""A stable, non-secret cryptographic contract failure."""
def __init__(self, code: str) -> None:
self.code = str(code)
super().__init__(self.code)
def _normalize_json_value(value: Any, *, path: str = "$") -> Any:
if value is None or isinstance(value, (bool, int)):
return value
if isinstance(value, str):
try:
value.encode("utf-8", errors="strict")
except UnicodeEncodeError as exc:
raise CryptoContractError("json_string_not_valid_utf8") from exc
return value
if isinstance(value, float):
# JSON leaves number canonicalization underspecified across runtimes.
# Protocol builders use integers or canonical decimal strings instead.
raise CryptoContractError("json_float_not_supported")
if isinstance(value, Mapping):
normalized: dict[str, Any] = {}
for key, item in value.items():
if not isinstance(key, str):
raise CryptoContractError("json_object_key_must_be_string")
if key in normalized:
raise CryptoContractError("json_duplicate_object_key")
normalized[key] = _normalize_json_value(item, path=f"{path}.{key}")
return normalized
if isinstance(value, Sequence) and not isinstance(value, (bytes, bytearray, memoryview)):
return [_normalize_json_value(item, path=f"{path}[{index}]") for index, item in enumerate(value)]
raise CryptoContractError("unsupported_json_type")
def canonical_json_bytes(value: Any) -> bytes:
"""Encode one JSON value deterministically, rejecting unsafe extensions."""
try:
normalized = _normalize_json_value(value)
rendered = json.dumps(
normalized,
sort_keys=True,
separators=(",", ":"),
ensure_ascii=True,
allow_nan=False,
)
except CryptoContractError:
raise
except RecursionError as exc:
raise CryptoContractError("json_nesting_too_deep") from exc
except (TypeError, ValueError) as exc:
raise CryptoContractError("json_encoding_failed") from exc
return rendered.encode("utf-8")
def decode_canonical_json(
data: bytes | str,
*,
require_mapping: bool = False,
max_bytes: int = 1_048_576,
) -> Any:
"""Strictly decode canonical UTF-8 JSON.
The byte representation must already equal :func:`canonical_json_bytes`.
This prevents alternate encodings from changing what a signature means.
"""
if type(max_bytes) is not int or max_bytes < 1:
raise CryptoContractError("json_input_size_invalid")
if isinstance(data, str):
try:
raw = data.encode("utf-8", errors="strict")
except UnicodeEncodeError as exc:
raise CryptoContractError("json_decoding_failed") from exc
elif isinstance(data, bytes):
raw = data
else:
raise CryptoContractError("json_input_must_be_bytes_or_string")
if not raw or len(raw) > max_bytes:
raise CryptoContractError("json_input_size_invalid")
def reject_duplicate_keys(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
result: dict[str, Any] = {}
for key, item in pairs:
if key in result:
raise CryptoContractError("json_duplicate_object_key")
result[key] = item
return result
def reject_constant(_value: str) -> Any:
raise CryptoContractError("non_finite_json_number")
try:
text = raw.decode("utf-8", errors="strict")
value = json.loads(
text,
object_pairs_hook=reject_duplicate_keys,
parse_constant=reject_constant,
)
except CryptoContractError:
raise
except RecursionError as exc:
raise CryptoContractError("json_nesting_too_deep") from exc
except (UnicodeDecodeError, json.JSONDecodeError, ValueError) as exc:
raise CryptoContractError("json_decoding_failed") from exc
try:
_normalize_json_value(value)
except RecursionError as exc:
raise CryptoContractError("json_nesting_too_deep") from exc
if canonical_json_bytes(value) != raw:
raise CryptoContractError("json_encoding_not_canonical")
if require_mapping and not isinstance(value, dict):
raise CryptoContractError("json_root_must_be_object")
return value
def sha256_hex(value: bytes | str | Mapping[str, Any] | Sequence[Any]) -> str:
if isinstance(value, bytes):
data = value
elif isinstance(value, str):
data = value.encode("utf-8")
else:
data = canonical_json_bytes(value)
return hashlib.sha256(data).hexdigest()
def domain_hash(domain: str, value: Any) -> str:
if not isinstance(domain, str):
raise CryptoContractError("hash_domain_invalid")
name = domain.strip()
if not name or "\x00" in name:
raise CryptoContractError("hash_domain_invalid")
return hashlib.sha256(name.encode("ascii", errors="strict") + b"\x00" + canonical_json_bytes(value)).hexdigest()
def b64url_encode(data: bytes) -> str:
if not isinstance(data, bytes) or not data:
raise CryptoContractError("base64url_input_must_be_nonempty_bytes")
return base64.urlsafe_b64encode(data).decode("ascii").rstrip("=")
def b64url_decode(
value: str,
*,
expected_bytes: int | None = None,
max_bytes: int | None = None,
) -> bytes:
if not isinstance(value, str):
raise CryptoContractError("base64url_encoding_invalid")
text = value
if expected_bytes is not None and (type(expected_bytes) is not int or expected_bytes < 1):
raise CryptoContractError("base64url_length_invalid")
if max_bytes is not None:
if type(max_bytes) is not int or max_bytes < 1:
raise CryptoContractError("base64url_maximum_length_invalid")
if expected_bytes is not None and expected_bytes > max_bytes:
raise CryptoContractError("base64url_length_invalid")
max_encoded_chars = (4 * max_bytes + 2) // 3
if len(text) > max_encoded_chars:
raise CryptoContractError("base64url_decoded_value_too_large")
if not text or "=" in text or _B64URL_RE.fullmatch(text) is None:
raise CryptoContractError("base64url_encoding_invalid")
try:
decoded = base64.b64decode(
text + "=" * (-len(text) % 4),
altchars=b"-_",
validate=True,
)
except (binascii.Error, ValueError) as exc:
raise CryptoContractError("base64url_encoding_invalid") from exc
if not decoded or b64url_encode(decoded) != text:
raise CryptoContractError("base64url_encoding_not_canonical")
if expected_bytes is not None and len(decoded) != expected_bytes:
raise CryptoContractError("base64url_length_invalid")
if max_bytes is not None and len(decoded) > max_bytes:
raise CryptoContractError("base64url_decoded_value_too_large")
return decoded
def hex_decode(value: str, *, expected_bytes: int) -> bytes:
if type(expected_bytes) is not int or expected_bytes < 1:
raise CryptoContractError("hex_length_invalid")
if not isinstance(value, str):
raise CryptoContractError("hex_encoding_invalid")
text = value
if len(text) != expected_bytes * 2 or _HEX_RE.fullmatch(text) is None:
raise CryptoContractError("hex_encoding_invalid")
try:
return bytes.fromhex(text)
except ValueError as exc: # pragma: no cover - guarded by the regex
raise CryptoContractError("hex_encoding_invalid") from exc
def generate_ed25519_private_key() -> Ed25519PrivateKey:
"""Generate an in-memory key. The caller owns all custody decisions."""
return Ed25519PrivateKey.generate()
def ed25519_public_key_hex(key: Ed25519PrivateKey | Ed25519PublicKey) -> str:
public_key = key.public_key() if isinstance(key, Ed25519PrivateKey) else key
if not isinstance(public_key, Ed25519PublicKey):
raise CryptoContractError("ed25519_key_type_invalid")
return cast(
str,
public_key.public_bytes(
encoding=serialization.Encoding.Raw,
format=serialization.PublicFormat.Raw,
).hex(),
)
def load_ed25519_public_key(value: str | bytes | Ed25519PublicKey) -> Ed25519PublicKey:
if isinstance(value, Ed25519PublicKey):
return value
raw = value if isinstance(value, bytes) else hex_decode(value, expected_bytes=32)
if len(raw) != 32:
raise CryptoContractError("ed25519_public_key_length_invalid")
try:
return Ed25519PublicKey.from_public_bytes(raw)
except ValueError as exc:
raise CryptoContractError("ed25519_public_key_invalid") from exc
def load_ed25519_private_key(value: str | bytes | Ed25519PrivateKey) -> Ed25519PrivateKey:
if isinstance(value, Ed25519PrivateKey):
return value
raw = value if isinstance(value, bytes) else hex_decode(value, expected_bytes=32)
if len(raw) != 32:
raise CryptoContractError("ed25519_private_key_length_invalid")
try:
return Ed25519PrivateKey.from_private_bytes(raw)
except ValueError as exc:
raise CryptoContractError("ed25519_private_key_invalid") from exc
def sign_ed25519(
private_key: str | bytes | Ed25519PrivateKey,
value: Any,
*,
domain: str,
) -> str:
message = bytes.fromhex(domain_hash(domain, value))
return cast(str, load_ed25519_private_key(private_key).sign(message).hex())
def verify_ed25519(
public_key: str | bytes | Ed25519PublicKey,
value: Any,
signature_hex: str,
*,
domain: str,
) -> bool:
try:
signature = hex_decode(signature_hex, expected_bytes=64)
message = bytes.fromhex(domain_hash(domain, value))
load_ed25519_public_key(public_key).verify(signature, message)
except (CryptoContractError, InvalidSignature, ValueError, TypeError):
return False
return True
__all__ = [
"CryptoContractError",
"b64url_decode",
"b64url_encode",
"canonical_json_bytes",
"decode_canonical_json",
"domain_hash",
"ed25519_public_key_hex",
"generate_ed25519_private_key",
"hex_decode",
"load_ed25519_private_key",
"load_ed25519_public_key",
"sha256_hex",
"sign_ed25519",
"verify_ed25519",
]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428"""Explicitly insecure, local-development-only Plumber execution boundary.
This is not a secure enclave and must never be represented as one. It exists
only to exercise purpose binding and fail-closed orchestration on a developer
machine. Decrypted bytes are passed to one in-process callback, overwritten
afterward where Python permits, and are never returned by this module.
"""
from __future__ import annotations
import re
from collections.abc import Callable, Mapping, Sequence
from dataclasses import dataclass
from datetime import datetime
from enum import StrEnum
from typing import Any
from .crypto import domain_hash
from .packet import PacketContractError, bind_hnc_packet
from .schema import (
DenialCode,
SchemaError,
format_timestamp,
freeze_mapping,
require_aware_datetime,
require_nonblank,
require_sha256,
)
LOCAL_DEVELOPMENT_MODE = "local-development"
INSECURE_OPT_IN_ACK = "I_ACKNOWLEDGE_INSECURE_LOCAL_DEVELOPMENT_ONLY"
_SAFE_CODE_RE = re.compile(r"^[a-z][a-z0-9_.-]{0,63}$")
class EnclaveConfigurationError(ValueError):
def __init__(self, code: str) -> None:
self.code = code
super().__init__(code)
class EnclaveDisposition(StrEnum):
COMPLETED_LOCAL = "completed_local"
HOLD = "hold"
DENY = "deny"
class EnclaveCode(StrEnum):
PURPOSE_NOT_ALLOWED = "purpose_not_allowed"
HNC_PACKET_INVALID = "hnc_packet_invalid"
HNC_DECODE_DENIED = "hnc_decode_denied"
PROCESSOR_FAILED = "processor_failed"
PROCESSOR_RESULT_INVALID = "processor_result_invalid"
@dataclass(frozen=True, slots=True)
class LocalComputationResult:
"""The only callback result accepted across the local enclave boundary."""
outcome_code: str
result_commitment: str
evidence_commitments: Mapping[str, str]
def __post_init__(self) -> None:
if not isinstance(self.outcome_code, str) or _SAFE_CODE_RE.fullmatch(self.outcome_code) is None:
raise SchemaError(DenialCode.INVALID_VALUE, field="outcome_code")
require_sha256(self.result_commitment, field="result_commitment")
frozen = freeze_mapping(
self.evidence_commitments,
field="evidence_commitments",
nonempty=False,
)
for name, commitment in frozen.items():
require_nonblank(name, field="evidence_commitments.key")
require_sha256(commitment, field="evidence_commitments.value")
object.__setattr__(self, "evidence_commitments", frozen)
@dataclass(frozen=True, slots=True)
class LocalEnclaveAttestation:
mode: str
enabled: bool
allowed_purpose_commitments: tuple[str, ...]
local_development_only: bool
production_capable: bool
attestation_commitment: str
def __post_init__(self) -> None:
if self.mode != LOCAL_DEVELOPMENT_MODE or self.enabled is not True:
raise SchemaError(DenialCode.INVALID_VALUE, field="enclave_attestation")
if self.local_development_only is not True or self.production_capable is not False:
raise SchemaError(DenialCode.INVALID_VALUE, field="enclave_attestation")
if not self.allowed_purpose_commitments or tuple(sorted(set(self.allowed_purpose_commitments))) != (
self.allowed_purpose_commitments
):
raise SchemaError(DenialCode.INVALID_VALUE, field="allowed_purpose_commitments")
for commitment in self.allowed_purpose_commitments:
require_sha256(commitment, field="allowed_purpose_commitments")
require_sha256(self.attestation_commitment, field="attestation_commitment")
if domain_hash("aureon.plumber.local-enclave-attestation.v0", self.commitment_payload()) != (
self.attestation_commitment
):
raise SchemaError(DenialCode.INVALID_VALUE, field="attestation_commitment")
def commitment_payload(self) -> dict[str, Any]:
return {
"mode": self.mode,
"enabled": self.enabled,
"allowed_purpose_commitments": list(self.allowed_purpose_commitments),
"local_development_only": self.local_development_only,
"production_capable": self.production_capable,
}
def public_summary(self) -> dict[str, Any]:
return {**self.commitment_payload(), "attestation_commitment": self.attestation_commitment}
@dataclass(frozen=True, slots=True)
class LocalEnclaveExecutionReceipt:
disposition: EnclaveDisposition
packet_commitment: str
purpose_commitment: str
processor_id: str
outcome_code: str
result_commitment: str
evidence_commitment: str
executed_at: str
denial_codes: tuple[str, ...]
local_development_only: bool
production_release: bool
receipt_commitment: str
def __post_init__(self) -> None:
try:
disposition = EnclaveDisposition(self.disposition)
except ValueError as exc:
raise SchemaError(DenialCode.INVALID_VALUE, field="disposition") from exc
object.__setattr__(self, "disposition", disposition)
if not isinstance(self.processor_id, str) or _SAFE_CODE_RE.fullmatch(self.processor_id) is None:
raise SchemaError(DenialCode.INVALID_VALUE, field="processor_id")
if not isinstance(self.outcome_code, str) or _SAFE_CODE_RE.fullmatch(self.outcome_code) is None:
raise SchemaError(DenialCode.INVALID_VALUE, field="outcome_code")
for field in (
"packet_commitment",
"purpose_commitment",
"result_commitment",
"evidence_commitment",
"receipt_commitment",
):
require_sha256(getattr(self, field), field=field)
if tuple(sorted(set(self.denial_codes))) != self.denial_codes:
raise SchemaError(DenialCode.INVALID_VALUE, field="denial_codes")
if (disposition is EnclaveDisposition.COMPLETED_LOCAL) != (not self.denial_codes):
raise SchemaError(DenialCode.INVALID_VALUE, field="disposition")
if self.local_development_only is not True or self.production_release is not False:
raise SchemaError(DenialCode.INVALID_VALUE, field="execution_scope")
from .schema import parse_timestamp
parse_timestamp(self.executed_at, field="executed_at")
if domain_hash("aureon.plumber.local-enclave-receipt.v0", self.commitment_payload()) != (
self.receipt_commitment
):
raise SchemaError(DenialCode.INVALID_VALUE, field="receipt_commitment")
@classmethod
def build(
cls,
*,
disposition: EnclaveDisposition,
packet_commitment: str,
purpose_commitment: str,
processor_id: str,
outcome_code: str,
result_commitment: str,
evidence_commitment: str,
executed_at: datetime,
denial_codes: Sequence[EnclaveCode | str] = (),
) -> LocalEnclaveExecutionReceipt:
codes = tuple(sorted({str(code) for code in denial_codes}))
executed_at_text = format_timestamp(executed_at)
values = {
"disposition": str(disposition),
"packet_commitment": packet_commitment,
"purpose_commitment": purpose_commitment,
"processor_id": processor_id,
"outcome_code": outcome_code,
"result_commitment": result_commitment,
"evidence_commitment": evidence_commitment,
"executed_at": executed_at_text,
"denial_codes": list(codes),
"local_development_only": True,
"production_release": False,
}
return cls(
disposition=disposition,
packet_commitment=packet_commitment,
purpose_commitment=purpose_commitment,
processor_id=processor_id,
outcome_code=outcome_code,
result_commitment=result_commitment,
evidence_commitment=evidence_commitment,
executed_at=executed_at_text,
denial_codes=codes,
local_development_only=True,
production_release=False,
receipt_commitment=domain_hash("aureon.plumber.local-enclave-receipt.v0", values),
)
def commitment_payload(self) -> dict[str, Any]:
return {
"disposition": str(self.disposition),
"packet_commitment": self.packet_commitment,
"purpose_commitment": self.purpose_commitment,
"processor_id": self.processor_id,
"outcome_code": self.outcome_code,
"result_commitment": self.result_commitment,
"evidence_commitment": self.evidence_commitment,
"executed_at": self.executed_at,
"denial_codes": list(self.denial_codes),
"local_development_only": self.local_development_only,
"production_release": self.production_release,
}
def public_summary(self) -> dict[str, Any]:
return {**self.commitment_payload(), "receipt_commitment": self.receipt_commitment}
class LocalDevelopmentEnclave:
"""Opt-in local callback runner; deliberately not a production enclave."""
def __init__(
self,
*,
allowed_purposes: Sequence[str],
insecure_opt_in: str,
mode: str = LOCAL_DEVELOPMENT_MODE,
) -> None:
if mode != LOCAL_DEVELOPMENT_MODE:
raise EnclaveConfigurationError("local_development_mode_required")
if insecure_opt_in != INSECURE_OPT_IN_ACK:
raise EnclaveConfigurationError("insecure_opt_in_required")
if isinstance(allowed_purposes, (str, bytes, bytearray)) or not isinstance(allowed_purposes, Sequence):
raise EnclaveConfigurationError("allowed_purposes_invalid")
parsed = tuple(sorted({require_nonblank(item, field="allowed_purpose") for item in allowed_purposes}))
if not parsed:
raise EnclaveConfigurationError("allowed_purposes_invalid")
self._allowed_purposes = parsed
def attestation(self) -> LocalEnclaveAttestation:
commitments = tuple(
sorted(domain_hash("aureon.plumber.purpose.v0", purpose) for purpose in self._allowed_purposes)
)
values = {
"mode": LOCAL_DEVELOPMENT_MODE,
"enabled": True,
"allowed_purpose_commitments": list(commitments),
"local_development_only": True,
"production_capable": False,
}
return LocalEnclaveAttestation(
mode=LOCAL_DEVELOPMENT_MODE,
enabled=True,
allowed_purpose_commitments=commitments,
local_development_only=True,
production_capable=False,
attestation_commitment=domain_hash(
"aureon.plumber.local-enclave-attestation.v0",
values,
),
)
def execute_hnc_packet(
self,
hnc_packet: Mapping[str, Any],
*,
master_key: bytes | str,
expected_purpose: str,
processor_id: str,
processor: Callable[[memoryview], LocalComputationResult],
now: datetime,
) -> LocalEnclaveExecutionReceipt:
current = require_aware_datetime(now, field="now")
require_nonblank(expected_purpose, field="expected_purpose", max_length=1024)
if not isinstance(processor_id, str) or _SAFE_CODE_RE.fullmatch(processor_id) is None:
raise SchemaError(DenialCode.INVALID_VALUE, field="processor_id")
if not callable(processor):
raise SchemaError(DenialCode.INVALID_TYPE, field="processor")
purpose_commitment = domain_hash("aureon.plumber.purpose.v0", expected_purpose)
fallback_packet_commitment = domain_hash(
"aureon.plumber.invalid-local-input.v0",
{"purpose_commitment": purpose_commitment},
)
try:
binding = bind_hnc_packet(hnc_packet)
fallback_packet_commitment = binding.hnc_packet_commitment
except PacketContractError:
return self._denied_receipt(
disposition=EnclaveDisposition.DENY,
code=EnclaveCode.HNC_PACKET_INVALID,
packet_commitment=fallback_packet_commitment,
purpose_commitment=purpose_commitment,
processor_id=processor_id,
now=current,
)
if expected_purpose not in self._allowed_purposes or binding.purpose_commitment != purpose_commitment:
return self._denied_receipt(
disposition=EnclaveDisposition.DENY,
code=EnclaveCode.PURPOSE_NOT_ALLOWED,
packet_commitment=binding.hnc_packet_commitment,
purpose_commitment=purpose_commitment,
processor_id=processor_id,
now=current,
)
try:
from aureon.harmonic.hnc_quantum_packet_crypto import (
HNCPacketError,
decode_hnc_quantum_packet,
)
try:
decoded = decode_hnc_quantum_packet(
hnc_packet,
master_key,
expected_purpose=expected_purpose,
)
except HNCPacketError:
return self._denied_receipt(
disposition=EnclaveDisposition.DENY,
code=EnclaveCode.HNC_DECODE_DENIED,
packet_commitment=binding.hnc_packet_commitment,
purpose_commitment=purpose_commitment,
processor_id=processor_id,
now=current,
)
buffer = bytearray(decoded.plaintext)
del decoded
view = memoryview(buffer)
try:
result = processor(view)
except Exception:
return self._denied_receipt(
disposition=EnclaveDisposition.HOLD,
code=EnclaveCode.PROCESSOR_FAILED,
packet_commitment=binding.hnc_packet_commitment,
purpose_commitment=purpose_commitment,
processor_id=processor_id,
now=current,
)
finally:
view.release()
buffer[:] = b"\x00" * len(buffer)
except Exception:
return self._denied_receipt(
disposition=EnclaveDisposition.HOLD,
code=EnclaveCode.PROCESSOR_FAILED,
packet_commitment=binding.hnc_packet_commitment,
purpose_commitment=purpose_commitment,
processor_id=processor_id,
now=current,
)
if not isinstance(result, LocalComputationResult):
return self._denied_receipt(
disposition=EnclaveDisposition.DENY,
code=EnclaveCode.PROCESSOR_RESULT_INVALID,
packet_commitment=binding.hnc_packet_commitment,
purpose_commitment=purpose_commitment,
processor_id=processor_id,
now=current,
)
evidence_commitment = domain_hash(
"aureon.plumber.local-computation-evidence.v0",
dict(result.evidence_commitments),
)
return LocalEnclaveExecutionReceipt.build(
disposition=EnclaveDisposition.COMPLETED_LOCAL,
packet_commitment=binding.hnc_packet_commitment,
purpose_commitment=purpose_commitment,
processor_id=processor_id,
outcome_code=result.outcome_code,
result_commitment=result.result_commitment,
evidence_commitment=evidence_commitment,
executed_at=current,
)
@staticmethod
def _denied_receipt(
*,
disposition: EnclaveDisposition,
code: EnclaveCode,
packet_commitment: str,
purpose_commitment: str,
processor_id: str,
now: datetime,
) -> LocalEnclaveExecutionReceipt:
result_commitment = domain_hash(
"aureon.plumber.no-local-result.v0",
{
"packet_commitment": packet_commitment,
"purpose_commitment": purpose_commitment,
"code": str(code),
},
)
return LocalEnclaveExecutionReceipt.build(
disposition=disposition,
packet_commitment=packet_commitment,
purpose_commitment=purpose_commitment,
processor_id=processor_id,
outcome_code=str(code),
result_commitment=result_commitment,
evidence_commitment=domain_hash(
"aureon.plumber.no-local-evidence.v0",
{"result_commitment": result_commitment},
),
executed_at=now,
denial_codes=(code,),
)
__all__ = [
"INSECURE_OPT_IN_ACK",
"LOCAL_DEVELOPMENT_MODE",
"EnclaveCode",
"EnclaveConfigurationError",
"EnclaveDisposition",
"LocalComputationResult",
"LocalDevelopmentEnclave",
"LocalEnclaveAttestation",
"LocalEnclaveExecutionReceipt",
]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271"""Fail-closed immune-gate aggregation for Plumber v0."""
from __future__ import annotations
from collections.abc import Sequence
from dataclasses import dataclass
from datetime import datetime
from enum import StrEnum
from typing import Any
from .crypto import domain_hash
from .schema import (
DenialCode,
SchemaError,
format_timestamp,
parse_timestamp,
require_aware_datetime,
require_nonblank,
require_sha256,
)
class GateClass(StrEnum):
FIELD = "field"
IDENTITY = "identity"
TEMPORAL = "temporal"
HEART = "heart"
CONSCIENCE = "conscience"
GOVERNANCE = "governance"
class GateVerdict(StrEnum):
APPROVED = "approved"
DENIED = "denied"
REQUIRED_GATE_CLASSES = tuple(GateClass)
@dataclass(frozen=True, slots=True)
class GateEvidence:
gate_class: GateClass
receipt_commitment: str
valid: bool
context_commitment: str | None = None
denial_codes: tuple[str, ...] = ()
def __post_init__(self) -> None:
try:
parsed_class = GateClass(self.gate_class)
except ValueError as exc:
raise SchemaError(DenialCode.INVALID_VALUE, field="gate_class") from exc
object.__setattr__(self, "gate_class", parsed_class)
require_sha256(self.receipt_commitment, field="receipt_commitment")
if type(self.valid) is not bool:
raise SchemaError(DenialCode.INVALID_TYPE, field="valid")
if self.context_commitment is not None:
require_sha256(self.context_commitment, field="context_commitment")
if not isinstance(self.denial_codes, tuple) or any(
not isinstance(code, str) or not code for code in self.denial_codes
):
raise SchemaError(DenialCode.INVALID_TYPE, field="denial_codes")
if tuple(sorted(set(self.denial_codes))) != self.denial_codes:
raise SchemaError(DenialCode.INVALID_VALUE, field="denial_codes")
if self.valid and self.denial_codes:
raise SchemaError(DenialCode.INVALID_VALUE, field="denial_codes")
def to_dict(self) -> dict[str, Any]:
return {
"gate_class": str(self.gate_class),
"receipt_commitment": self.receipt_commitment,
"valid": self.valid,
"context_commitment": self.context_commitment,
"denial_codes": list(self.denial_codes),
}
@dataclass(frozen=True, slots=True)
class GateDecision:
verdict: GateVerdict
evaluated_classes: tuple[str, ...]
missing_classes: tuple[str, ...]
denial_codes: tuple[str, ...]
packet_inspection_commitment: str
context_commitment: str
evidence_commitment: str
evaluated_at: str
expires_at: str
decision_commitment: str
quarantine_required: bool
def __post_init__(self) -> None:
try:
verdict = GateVerdict(self.verdict)
except ValueError as exc:
raise SchemaError(DenialCode.INVALID_VALUE, field="verdict") from exc
object.__setattr__(self, "verdict", verdict)
for field in (
"packet_inspection_commitment",
"context_commitment",
"evidence_commitment",
"decision_commitment",
):
require_sha256(getattr(self, field), field=field)
expected_classes = tuple(sorted(str(item) for item in REQUIRED_GATE_CLASSES))
if tuple(sorted(set(self.evaluated_classes))) != self.evaluated_classes:
raise SchemaError(DenialCode.INVALID_VALUE, field="evaluated_classes")
if tuple(sorted(set(self.missing_classes))) != self.missing_classes:
raise SchemaError(DenialCode.INVALID_VALUE, field="missing_classes")
if set(self.evaluated_classes) | set(self.missing_classes) != set(expected_classes):
raise SchemaError(DenialCode.INVALID_VALUE, field="evaluated_classes")
if set(self.evaluated_classes) & set(self.missing_classes):
raise SchemaError(DenialCode.INVALID_VALUE, field="missing_classes")
if tuple(sorted(set(self.denial_codes))) != self.denial_codes:
raise SchemaError(DenialCode.INVALID_VALUE, field="denial_codes")
if type(self.quarantine_required) is not bool:
raise SchemaError(DenialCode.INVALID_TYPE, field="quarantine_required")
if (verdict is GateVerdict.APPROVED) == self.quarantine_required:
raise SchemaError(DenialCode.INVALID_VALUE, field="quarantine_required")
if verdict is GateVerdict.APPROVED and (
self.evaluated_classes != expected_classes
or self.missing_classes
or self.denial_codes
):
raise SchemaError(DenialCode.INVALID_VALUE, field="verdict")
evaluated = parse_timestamp(self.evaluated_at, field="evaluated_at")
expires = parse_timestamp(self.expires_at, field="expires_at")
if expires <= evaluated:
raise SchemaError(DenialCode.INVALID_VALUE, field="expires_at")
if domain_hash("aureon.plumber.immune-decision.v0", self.commitment_payload()) != self.decision_commitment:
raise SchemaError(DenialCode.INVALID_VALUE, field="decision_commitment")
def commitment_payload(self) -> dict[str, Any]:
return {
"verdict": str(self.verdict),
"evaluated_classes": list(self.evaluated_classes),
"missing_classes": list(self.missing_classes),
"denial_codes": list(self.denial_codes),
"packet_inspection_commitment": self.packet_inspection_commitment,
"context_commitment": self.context_commitment,
"evidence_commitment": self.evidence_commitment,
"evaluated_at": self.evaluated_at,
"expires_at": self.expires_at,
"quarantine_required": self.quarantine_required,
}
def public_summary(self) -> dict[str, Any]:
return {
"verdict": str(self.verdict),
"evaluated_classes": list(self.evaluated_classes),
"missing_classes": list(self.missing_classes),
"denial_codes": list(self.denial_codes),
"packet_inspection_commitment": self.packet_inspection_commitment,
"context_commitment": self.context_commitment,
"evidence_commitment": self.evidence_commitment,
"evaluated_at": self.evaluated_at,
"expires_at": self.expires_at,
"decision_commitment": self.decision_commitment,
"quarantine_required": self.quarantine_required,
"release_state": "not_released",
}
def evaluate_immune_gate(
evidence: Sequence[GateEvidence],
*,
packet_inspection_commitment: str,
evaluated_at: datetime,
expires_at: datetime,
) -> GateDecision:
if isinstance(evidence, (str, bytes, bytearray)) or not isinstance(evidence, Sequence):
raise SchemaError(DenialCode.INVALID_TYPE, field="evidence")
inspection_commitment = require_sha256(
packet_inspection_commitment,
field="packet_inspection_commitment",
)
evaluated_at_text = format_timestamp(
require_aware_datetime(evaluated_at, field="evaluated_at")
)
expires_at_text = format_timestamp(
require_aware_datetime(expires_at, field="expires_at")
)
if parse_timestamp(expires_at_text, field="expires_at") <= parse_timestamp(
evaluated_at_text,
field="evaluated_at",
):
raise SchemaError(DenialCode.INVALID_VALUE, field="expires_at")
by_class: dict[GateClass, GateEvidence] = {}
denials: set[str] = set()
for item in evidence:
if not isinstance(item, GateEvidence):
raise SchemaError(DenialCode.INVALID_TYPE, field="evidence")
if item.gate_class in by_class:
denials.add(str(DenialCode.INVALID_SCHEMA))
else:
by_class[item.gate_class] = item
if not item.valid:
denials.update(item.denial_codes or (str(DenialCode.POLICY_RECEIPT_INVALID),))
missing = tuple(sorted(str(item) for item in set(REQUIRED_GATE_CLASSES) - set(by_class)))
if missing:
denials.add(str(DenialCode.POLICY_RECEIPT_MISSING))
serialized = [by_class[key].to_dict() for key in sorted(by_class, key=str)]
supplied_contexts = {
item.context_commitment
for item in by_class.values()
if item.context_commitment is not None
}
if len(supplied_contexts) > 1 or (
supplied_contexts and any(item.context_commitment is None for item in by_class.values())
):
denials.add("gate_context_mismatch")
context_commitment = (
next(iter(supplied_contexts))
if len(supplied_contexts) == 1
else domain_hash("aureon.plumber.unbound-gate-context.v0", serialized)
)
evidence_commitment = domain_hash("aureon.plumber.immune-evidence.v0", serialized)
denial_tuple = tuple(sorted(denials))
verdict = GateVerdict.DENIED if denial_tuple else GateVerdict.APPROVED
payload = {
"verdict": str(verdict),
"evaluated_classes": sorted(str(item) for item in by_class),
"missing_classes": list(missing),
"denial_codes": list(denial_tuple),
"packet_inspection_commitment": inspection_commitment,
"context_commitment": context_commitment,
"evidence_commitment": evidence_commitment,
"evaluated_at": evaluated_at_text,
"expires_at": expires_at_text,
"quarantine_required": verdict is GateVerdict.DENIED,
}
return GateDecision(
verdict=verdict,
evaluated_classes=tuple(sorted(str(item) for item in by_class)),
missing_classes=missing,
denial_codes=denial_tuple,
packet_inspection_commitment=inspection_commitment,
context_commitment=context_commitment,
evidence_commitment=evidence_commitment,
evaluated_at=evaluated_at_text,
expires_at=expires_at_text,
decision_commitment=domain_hash("aureon.plumber.immune-decision.v0", payload),
quarantine_required=verdict is GateVerdict.DENIED,
)
def build_gate_context_commitment(
*, packet_identity: str, session_identity: str, purpose_commitment: str
) -> str:
require_nonblank(packet_identity, field="packet_identity")
require_nonblank(session_identity, field="session_identity")
require_sha256(purpose_commitment, field="purpose_commitment")
return domain_hash(
"aureon.plumber.immune-gate-context.v0",
{
"packet_identity": packet_identity,
"session_identity": session_identity,
"purpose_commitment": purpose_commitment,
},
)
__all__ = [
"GateClass",
"GateDecision",
"GateEvidence",
"GateVerdict",
"REQUIRED_GATE_CLASSES",
"evaluate_immune_gate",
"build_gate_context_commitment",
]1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171"""Machine-validated Magic Star evidence for the Aureon Plumber v0.2 lab path.
Geometry, the Rainbow and EPAS labels are authenticated public context. They
are never entropy, nonces, shares, liveness evidence or release authority.
Ed25519 signatures from verifier-enrolled, distinct authorities carry the
authority in this module.
"""
from __future__ import annotations
import re
import time
from collections.abc import Callable, Mapping, Sequence
from dataclasses import dataclass
from datetime import UTC, datetime, timedelta
from types import MappingProxyType
from typing import Any
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
from aureon.harmonic.rainbow_reference import rainbow_json, verify_rainbow
from .crypto import domain_hash, ed25519_public_key_hex, sha256_hex, sign_ed25519, verify_ed25519
from .receipts import RECEIPT_SCHEMA, ReceiptKind, ReceiptVerdict, SignedReceipt
from .schema import freeze_mapping, parse_timestamp, thaw_json
PROTOCOL_ID = "AUREON_PLUMBER_V0_2_MAGIC_STAR"
PROFILE_ID = "AUREON_PLUMBER_MAGIC_STAR_POLICY_V0_2"
SOURCE_PROFILE_COMMITMENT = "8a263a1af1067fb997eefeeff4c2beec43a8fad83bab9338a1b5a2cc8c0d9935"
COMPONENT_SCHEMA = "aureon.plumber.magic-star.signed-component.v02"
STAR_SCHEMA = "aureon.plumber.magic-star.v02"
COMPONENT_SIGNING_DOMAIN = "MAGIC-STAR-V0.2"
POINTS: tuple[Mapping[str, Any], ...] = (
MappingProxyType({"index": 0, "lens": "Hexahedron", "element": "Earth", "role": "SOURCE"}),
MappingProxyType({"index": 1, "lens": "Icosahedron", "element": "Water", "role": "OBSERVER"}),
MappingProxyType({"index": 2, "lens": "Octahedron", "element": "Air", "role": "CONSCIENCE"}),
MappingProxyType({"index": 3, "lens": "Dodecahedron", "element": "Ether", "role": "GOVERNANCE"}),
MappingProxyType({"index": 4, "lens": "Tetrahedron", "element": "Fire", "role": "OPERATOR"}),
)
POINT_ROLES: tuple[str, ...] = tuple(str(point["role"]) for point in POINTS)
PENTAGRAM_ROUTE: tuple[tuple[int, int], ...] = ((0, 2), (2, 4), (4, 1), (1, 3), (3, 0))
RAINBOW_FREQUENCIES: tuple[str, ...] = (
"7.83",
"174",
"285",
"396",
"417",
"528",
"639",
"741",
"852",
"963",
)
STAR_AUTHORITY_ROLES = (*POINT_ROLES, "EPAS", "HEART", "STAR_SEAL")
_IDENTIFIER = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._:/-]{0,127}$")
_SHA256 = re.compile(r"^[0-9a-f]{64}$")
_PUBLIC_KEY = re.compile(r"^[0-9a-f]{64}$")
_SIGNATURE = re.compile(r"^[0-9a-f]{128}$")
PROFILE_DESCRIPTOR: Mapping[str, Any] = MappingProxyType({
"protocol_id": PROTOCOL_ID,
"profile_id": PROFILE_ID,
"source_profile_commitment": SOURCE_PROFILE_COMMITMENT,
"points": POINTS,
"pentagram_route": PENTAGRAM_ROUTE,
"rainbow_frequencies": RAINBOW_FREQUENCIES,
"heart_frequency": "528",
"heart_receipt_schema": RECEIPT_SCHEMA,
"heart_receipt_kind": str(ReceiptKind.HEART),
"heart_receipt_bridge_required": True,
"point_verdict_required": "APPROVE",
"cryptographic_carriers": ("AES-256-GCM", "HKDF-SHA256", "Ed25519", "SHA-256"),
"public_context_is_not_entropy": True,
"production_ready": False,
})
IMPLEMENTATION_PROFILE_SHA256 = domain_hash(
"AUREON-PLUMBER-V02-IMPLEMENTATION-PROFILE", PROFILE_DESCRIPTOR
)
RAINBOW_SOURCE_SHA256 = sha256_hex(rainbow_json())
_MAX_COMPONENT_TTL_MS = 5 * 60 * 1000
_UTC_EPOCH = datetime(1970, 1, 1, tzinfo=UTC)
_EPAS_FIELDS = {
"protocol_id",
"profile_id",
"source_profile_commitment",
"release_context_sha256",
"source_lineage_sha256",
"evidence_sha256",
"evidence_class",
"previous_memory_head_sha256",
"memory_epoch",
"verdict",
"outcome",
"issued_at_ms",
"expires_at_ms",
"physical_effects_claimed",
}
_HEART_FIELDS = {
"protocol_id",
"profile_id",
"source_profile_commitment",
"release_context_sha256",
"packet_id",
"packet_commitment",
"session_id",
"purpose",
"source_identity_commitment",
"temporal_commitment",
"observer_commitment",
"policy_commitment",
"runtime_measurement_sha256",
"heart_receipt",
"heart_receipt_commitment",
"verdict",
"issued_at_ms",
"expires_at_ms",
"heart_frequency",
}
_POINT_FIELDS = {
"protocol_id",
"profile_id",
"source_profile_commitment",
"implementation_profile_sha256",
"index",
"lens",
"element",
"role",
"release_context_sha256",
"candidate_center_sha256",
"evidence_sha256",
"share_binding_sha256",
"rainbow_source_sha256",
"verdict",
"issued_at_ms",
"expires_at_ms",
}
_SEAL_FIELDS = {
"protocol_id",
"profile_id",
"source_profile_commitment",
"implementation_profile_sha256",
"release_context_sha256",
"candidate_center_sha256",
"epas_commitment",
"heart_commitment",
"point_commitments",
"edges",
"rainbow_chain",
"formation_sha256",
"all_five_required",
"four_of_five_denied",
"sealed_at_ms",
}
class MagicStarError(ValueError):
"""A stable fail-closed Magic Star validation error."""
def __init__(self, code: str) -> None:
self.code = str(code)
super().__init__(self.code)
def _identifier(value: object, *, code: str) -> str:
if not isinstance(value, str) or _IDENTIFIER.fullmatch(value) is None:
raise MagicStarError(code)
return value
def _sha256(value: object, *, code: str) -> str:
if not isinstance(value, str) or _SHA256.fullmatch(value) is None:
raise MagicStarError(code)
return value
def _uint(value: object, *, code: str) -> int:
if isinstance(value, bool) or not isinstance(value, int) or value < 0:
raise MagicStarError(code)
return value
def _system_now_ms() -> int:
return time.time_ns() // 1_000_000
def _datetime_from_epoch_ms(value: object, *, code: str) -> datetime:
milliseconds = _uint(value, code=code)
try:
return _UTC_EPOCH + timedelta(milliseconds=milliseconds)
except OverflowError as exc:
raise MagicStarError(code) from exc
def _timestamp_to_epoch_ms(value: object, *, code: str) -> int:
try:
parsed = parse_timestamp(value, field=code)
elapsed = parsed - _UTC_EPOCH
except (OverflowError, TypeError, ValueError) as exc:
raise MagicStarError(code) from exc
return (
elapsed.days * 86_400_000
+ elapsed.seconds * 1_000
+ elapsed.microseconds // 1_000
)
def heart_receipt_commitment_v02(receipt: SignedReceipt) -> str:
"""Commit the complete signed v0 Heart receipt, including its signature."""
if not isinstance(receipt, SignedReceipt):
raise MagicStarError("heart_receipt_type_invalid")
return domain_hash("AUREON-PLUMBER-V02-HEART-RECEIPT", receipt.to_dict())
def build_heart_source_identity_commitment_v02(
*,
source_authority: AuthorityBindingV02,
packet_id: str,
packet_commitment: str,
source_signature_commitment: str,
) -> str:
"""Bind the v0 Heart receipt to the exact source-signed v0.2 packet."""
if not isinstance(source_authority, AuthorityBindingV02) or source_authority.role != "SOURCE":
raise MagicStarError("heart_source_authority_invalid")
return domain_hash(
"AUREON-PLUMBER-V02-HEART-SOURCE-IDENTITY",
{
"protocol_id": PROTOCOL_ID,
"profile_id": PROFILE_ID,
"source_profile_commitment": SOURCE_PROFILE_COMMITMENT,
"packet_id": _identifier(packet_id, code="packet_id_invalid"),
"packet_commitment": _sha256(
packet_commitment, code="packet_commitment_invalid"
),
"source_signature_commitment": _sha256(
source_signature_commitment,
code="source_signature_commitment_invalid",
),
"source_authority": source_authority.public_dict(),
},
)
def _profile_public() -> dict[str, Any]:
return {
"protocol_id": PROTOCOL_ID,
"profile_id": PROFILE_ID,
"source_profile_commitment": SOURCE_PROFILE_COMMITMENT,
"points": [dict(point) for point in POINTS],
"pentagram_route": [list(edge) for edge in PENTAGRAM_ROUTE],
"rainbow_frequencies": list(RAINBOW_FREQUENCIES),
"heart_frequency": "528",
"heart_receipt_schema": RECEIPT_SCHEMA,
"heart_receipt_kind": str(ReceiptKind.HEART),
"heart_receipt_bridge_required": True,
"point_verdict_required": "APPROVE",
"cryptographic_carriers": ["AES-256-GCM", "HKDF-SHA256", "Ed25519", "SHA-256"],
"public_context_is_not_entropy": True,
"production_ready": False,
}
def _require_profile_and_shape(payload: Mapping[str, Any], fields: set[str], *, code: str) -> None:
if set(payload) != fields or any(
payload.get(key) != value
for key, value in {
"protocol_id": PROTOCOL_ID,
"profile_id": PROFILE_ID,
"source_profile_commitment": SOURCE_PROFILE_COMMITMENT,
}.items()
):
raise MagicStarError(code)
def _validate_window(payload: Mapping[str, Any], *, now: int, prefix: str) -> None:
issued = _uint(payload.get("issued_at_ms"), code=f"{prefix}_issued_at_invalid")
expires = _uint(payload.get("expires_at_ms"), code=f"{prefix}_expires_at_invalid")
if issued > now or expires <= now or expires <= issued or expires - issued > _MAX_COMPONENT_TTL_MS:
raise MagicStarError(f"{prefix}_time_window_invalid")
@dataclass(frozen=True, slots=True)
class AuthorityBindingV02:
role: str
issuer: str
principal: str
key_id: str
public_key_hex: str
def __post_init__(self) -> None:
if self.role not in STAR_AUTHORITY_ROLES and self.role not in {
"COHERENCE",
"CONTINUITY",
"AUTHORIZATION",
"CUSTODY",
"CAPABILITY_RECEIPT",
"RELEASE_PROOF",
}:
raise MagicStarError("authority_role_invalid")
_identifier(self.issuer, code="authority_issuer_invalid")
_identifier(self.principal, code="authority_principal_invalid")
_identifier(self.key_id, code="authority_key_id_invalid")
if not isinstance(self.public_key_hex, str) or _PUBLIC_KEY.fullmatch(self.public_key_hex) is None:
raise MagicStarError("authority_public_key_invalid")
def public_dict(self) -> dict[str, str]:
return {
"role": self.role,
"issuer": self.issuer,
"principal": self.principal,
"key_id": self.key_id,
"public_key_hex": self.public_key_hex,
}
def build_authority_binding_v02(
*,
role: str,
issuer: str,
principal: str,
key_id: str,
private_key: Ed25519PrivateKey,
) -> AuthorityBindingV02:
return AuthorityBindingV02(
role=role,
issuer=issuer,
principal=principal,
key_id=key_id,
public_key_hex=ed25519_public_key_hex(private_key),
)
def validate_distinct_authorities_v02(
trust: Mapping[str, AuthorityBindingV02],
*,
required_roles: Sequence[str],
) -> None:
if set(trust) != set(required_roles):
raise MagicStarError("authority_role_set_incomplete")
bindings = [trust[role] for role in required_roles]
for role, binding in zip(required_roles, bindings, strict=True):
if not isinstance(binding, AuthorityBindingV02) or binding.role != role:
raise MagicStarError("authority_role_binding_mismatch")
for attribute, code in (
("public_key_hex", "authority_keys_not_distinct"),
("key_id", "authority_key_ids_not_distinct"),
("principal", "authority_principals_not_distinct"),
("issuer", "authority_issuers_not_distinct"),
):
values = [getattr(binding, attribute) for binding in bindings]
if len(set(values)) != len(values):
raise MagicStarError(code)
def _component_unsigned(
*,
component_type: str,
authority: AuthorityBindingV02,
payload: Mapping[str, Any],
) -> dict[str, Any]:
component = _identifier(component_type, code="component_type_invalid")
body = dict(payload)
return {
"schema": COMPONENT_SCHEMA,
"component_type": component,
"authority": authority.public_dict(),
"payload": body,
"payload_sha256": domain_hash(f"AUREON-PLUMBER-V02-{component}", body),
}
def sign_component_v02(
*,
component_type: str,
authority: AuthorityBindingV02,
payload: Mapping[str, Any],
private_key: Ed25519PrivateKey,
) -> dict[str, Any]:
if ed25519_public_key_hex(private_key) != authority.public_key_hex:
raise MagicStarError("component_signer_key_mismatch")
unsigned = _component_unsigned(
component_type=component_type,
authority=authority,
payload=payload,
)
return {
**unsigned,
"signature_hex": sign_ed25519(
private_key,
unsigned,
domain=f"{COMPONENT_SIGNING_DOMAIN}:{component_type}",
),
}
def component_commitment_v02(component: Mapping[str, Any]) -> str:
return domain_hash("AUREON-PLUMBER-V02-SIGNED-COMPONENT", dict(component))
def verify_component_v02(
component: Mapping[str, Any],
*,
expected_type: str,
expected_authority: AuthorityBindingV02,
) -> dict[str, Any]:
exact_fields = {
"schema",
"component_type",
"authority",
"payload",
"payload_sha256",
"signature_hex",
}
if not isinstance(component, Mapping) or set(component) != exact_fields:
raise MagicStarError("signed_component_shape_invalid")
if component.get("schema") != COMPONENT_SCHEMA or component.get("component_type") != expected_type:
raise MagicStarError("signed_component_schema_or_type_mismatch")
if component.get("authority") != expected_authority.public_dict():
raise MagicStarError("signed_component_authority_mismatch")
payload = component.get("payload")
if not isinstance(payload, Mapping):
raise MagicStarError("signed_component_payload_invalid")
unsigned = _component_unsigned(
component_type=expected_type,
authority=expected_authority,
payload=payload,
)
if component.get("payload_sha256") != unsigned["payload_sha256"]:
raise MagicStarError("signed_component_payload_hash_mismatch")
signature = component.get("signature_hex")
if not isinstance(signature, str) or _SIGNATURE.fullmatch(signature) is None:
raise MagicStarError("signed_component_signature_invalid")
if not verify_ed25519(
expected_authority.public_key_hex,
unsigned,
signature,
domain=f"{COMPONENT_SIGNING_DOMAIN}:{expected_type}",
):
raise MagicStarError("signed_component_signature_invalid")
return {key: thaw_json(value) for key, value in payload.items()}
def _validate_heart_receipt_bridge(
payload: Mapping[str, Any],
*,
authority: AuthorityBindingV02,
trusted_now_ms: int,
) -> SignedReceipt:
receipt_value = payload.get("heart_receipt")
if not isinstance(receipt_value, Mapping):
raise MagicStarError("heart_receipt_schema_invalid")
try:
receipt = SignedReceipt.from_dict(receipt_value)
except (TypeError, ValueError) as exc:
raise MagicStarError("heart_receipt_schema_invalid") from exc
if receipt.kind != str(ReceiptKind.HEART):
raise MagicStarError("heart_receipt_kind_invalid")
if receipt.verdict != str(ReceiptVerdict.APPROVED):
raise MagicStarError("heart_receipt_verdict_invalid")
if (
receipt.signer_public_key != authority.public_key_hex
or receipt.signer_id != authority.principal
):
raise MagicStarError("heart_receipt_authority_mismatch")
packet_id = _identifier(payload.get("packet_id"), code="packet_id_invalid")
session_id = _identifier(payload.get("session_id"), code="session_id_invalid")
purpose = _identifier(payload.get("purpose"), code="purpose_invalid")
source_identity = _sha256(
payload.get("source_identity_commitment"),
code="heart_source_identity_commitment_invalid",
)
temporal = _sha256(
payload.get("temporal_commitment"), code="temporal_commitment_invalid"
)
observer = _sha256(
payload.get("observer_commitment"), code="observer_commitment_invalid"
)
policy = _sha256(
payload.get("policy_commitment"), code="heart_policy_commitment_invalid"
)
runtime = _sha256(
payload.get("runtime_measurement_sha256"),
code="runtime_measurement_invalid",
)
expected_receipt_fields = {
"packet_identity": packet_id,
"session_identity": session_id,
"purpose_commitment": domain_hash("aureon.plumber.purpose.v0", purpose),
"source_identity_commitment": source_identity,
"temporal_identity_commitment": temporal,
"observer_transcript_commitment": observer,
"policy_commitment": policy,
"runtime_measurement_commitment": runtime,
}
if any(
getattr(receipt, field) != value
for field, value in expected_receipt_fields.items()
):
raise MagicStarError("heart_receipt_binding_mismatch")
if payload.get("verdict") != "APPROVE" or payload.get("heart_frequency") != "528":
raise MagicStarError("heart_precondition_denied")
if payload.get("heart_receipt_commitment") != heart_receipt_commitment_v02(receipt):
raise MagicStarError("heart_receipt_commitment_mismatch")
receipt_issued_ms = _timestamp_to_epoch_ms(
receipt.issued_at, code="heart_receipt_issued_at_invalid"
)
receipt_expires_ms = _timestamp_to_epoch_ms(
receipt.expires_at, code="heart_receipt_expires_at_invalid"
)
if (
payload.get("issued_at_ms") != receipt_issued_ms
or payload.get("expires_at_ms") != receipt_expires_ms
):
raise MagicStarError("heart_receipt_time_join_mismatch")
validation = receipt.validate(
now=_datetime_from_epoch_ms(
trusted_now_ms, code="heart_receipt_trusted_time_invalid"
),
expected_packet_identity=packet_id,
expected_session_identity=session_id,
expected_purpose_commitment=expected_receipt_fields["purpose_commitment"],
expected_signer_public_key=authority.public_key_hex,
require_approved=True,
)
if not validation.valid:
if any(code in {"future_state", "stale_state"} for code in validation.denial_codes):
raise MagicStarError("heart_receipt_time_window_invalid")
raise MagicStarError("heart_receipt_validation_failed")
return receipt
def build_epas_precondition_v02(
*,
release_context_sha256: str,
source_lineage_sha256: str,
evidence_sha256: str,
evidence_class: str,
previous_memory_head_sha256: str,
memory_epoch: int,
verdict: str,
outcome: str,
issued_at_ms: int,
expires_at_ms: int,
authority: AuthorityBindingV02,
private_key: Ed25519PrivateKey,
) -> dict[str, Any]:
if authority.role != "EPAS":
raise MagicStarError("epas_authority_role_invalid")
payload: dict[str, Any] = {
"protocol_id": PROTOCOL_ID,
"profile_id": PROFILE_ID,
"source_profile_commitment": SOURCE_PROFILE_COMMITMENT,
"release_context_sha256": _sha256(release_context_sha256, code="release_context_invalid"),
"source_lineage_sha256": _sha256(source_lineage_sha256, code="source_lineage_invalid"),
"evidence_sha256": _sha256(evidence_sha256, code="epas_evidence_invalid"),
"evidence_class": _identifier(evidence_class, code="epas_evidence_class_invalid"),
"previous_memory_head_sha256": _sha256(
previous_memory_head_sha256, code="epas_memory_head_invalid"
),
"memory_epoch": _uint(memory_epoch, code="epas_memory_epoch_invalid"),
"verdict": str(verdict),
"outcome": str(outcome),
"issued_at_ms": _uint(issued_at_ms, code="epas_issued_at_invalid"),
"expires_at_ms": _uint(expires_at_ms, code="epas_expires_at_invalid"),
"physical_effects_claimed": False,
}
if payload["expires_at_ms"] <= payload["issued_at_ms"]:
raise MagicStarError("epas_time_window_invalid")
return sign_component_v02(
component_type="EPAS_PRECONDITION",
authority=authority,
payload=payload,
private_key=private_key,
)
def build_heart_precondition_v02(
*,
release_context_sha256: str,
packet_id: str,
packet_commitment: str,
session_id: str,
purpose: str,
temporal_commitment: str,
observer_commitment: str,
runtime_measurement_sha256: str,
heart_receipt: SignedReceipt,
verdict: str,
issued_at_ms: int,
expires_at_ms: int,
authority: AuthorityBindingV02,
private_key: Ed25519PrivateKey,
) -> dict[str, Any]:
if authority.role != "HEART":
raise MagicStarError("heart_authority_role_invalid")
if not isinstance(heart_receipt, SignedReceipt):
raise MagicStarError("heart_receipt_type_invalid")
payload: dict[str, Any] = {
"protocol_id": PROTOCOL_ID,
"profile_id": PROFILE_ID,
"source_profile_commitment": SOURCE_PROFILE_COMMITMENT,
"release_context_sha256": _sha256(release_context_sha256, code="release_context_invalid"),
"packet_id": _identifier(packet_id, code="packet_id_invalid"),
"packet_commitment": _sha256(packet_commitment, code="packet_commitment_invalid"),
"session_id": _identifier(session_id, code="session_id_invalid"),
"purpose": _identifier(purpose, code="purpose_invalid"),
"source_identity_commitment": heart_receipt.source_identity_commitment,
"temporal_commitment": _sha256(temporal_commitment, code="temporal_commitment_invalid"),
"observer_commitment": _sha256(observer_commitment, code="observer_commitment_invalid"),
"policy_commitment": heart_receipt.policy_commitment,
"runtime_measurement_sha256": _sha256(
runtime_measurement_sha256, code="runtime_measurement_invalid"
),
"heart_receipt": heart_receipt.to_dict(),
"heart_receipt_commitment": heart_receipt_commitment_v02(heart_receipt),
"verdict": str(verdict),
"issued_at_ms": _uint(issued_at_ms, code="heart_issued_at_invalid"),
"expires_at_ms": _uint(expires_at_ms, code="heart_expires_at_invalid"),
"heart_frequency": "528",
}
if payload["expires_at_ms"] <= payload["issued_at_ms"]:
raise MagicStarError("heart_time_window_invalid")
_require_profile_and_shape(
payload, _HEART_FIELDS, code="heart_precondition_profile_or_shape_invalid"
)
_validate_window(
payload,
now=_uint(payload["issued_at_ms"], code="heart_issued_at_invalid"),
prefix="heart",
)
_validate_heart_receipt_bridge(
payload,
authority=authority,
trusted_now_ms=_uint(
payload["issued_at_ms"], code="heart_issued_at_invalid"
),
)
return sign_component_v02(
component_type="HEART_PRECONDITION",
authority=authority,
payload=payload,
private_key=private_key,
)
def build_candidate_center_v02(
*,
release_context_sha256: str,
packet_commitment: str,
recipient_proof_commitment: str,
purpose: str,
temporal_commitment: str,
observer_commitment: str,
epas_commitment: str,
heart_commitment: str,
) -> str:
return domain_hash(
"AUREON-PLUMBER-V02-CANDIDATE-CENTER",
{
"protocol_id": PROTOCOL_ID,
"profile_id": PROFILE_ID,
"source_profile_commitment": SOURCE_PROFILE_COMMITMENT,
"release_context_sha256": _sha256(
release_context_sha256, code="release_context_invalid"
),
"packet_commitment": _sha256(packet_commitment, code="packet_commitment_invalid"),
"recipient_proof_commitment": _sha256(
recipient_proof_commitment, code="recipient_proof_commitment_invalid"
),
"purpose": _identifier(purpose, code="purpose_invalid"),
"temporal_commitment": _sha256(
temporal_commitment, code="temporal_commitment_invalid"
),
"observer_commitment": _sha256(
observer_commitment, code="observer_commitment_invalid"
),
"epas_commitment": _sha256(epas_commitment, code="epas_commitment_invalid"),
"heart_commitment": _sha256(heart_commitment, code="heart_commitment_invalid"),
},
)
def build_magic_star_point_v02(
*,
index: int,
release_context_sha256: str,
candidate_center_sha256: str,
evidence_sha256: str,
share_binding_sha256: str,
verdict: str,
issued_at_ms: int,
expires_at_ms: int,
authority: AuthorityBindingV02,
private_key: Ed25519PrivateKey,
) -> dict[str, Any]:
point_index = _uint(index, code="star_point_index_invalid")
if point_index >= len(POINTS):
raise MagicStarError("star_point_index_invalid")
definition = POINTS[point_index]
if authority.role != definition["role"]:
raise MagicStarError("star_point_authority_role_mismatch")
point_verdict = str(verdict)
if point_verdict not in {"APPROVE", "VETO"}:
raise MagicStarError("star_point_verdict_invalid")
payload: dict[str, Any] = {
"protocol_id": PROTOCOL_ID,
"profile_id": PROFILE_ID,
"source_profile_commitment": SOURCE_PROFILE_COMMITMENT,
"implementation_profile_sha256": IMPLEMENTATION_PROFILE_SHA256,
**definition,
"release_context_sha256": _sha256(release_context_sha256, code="release_context_invalid"),
"candidate_center_sha256": _sha256(
candidate_center_sha256, code="candidate_center_invalid"
),
"evidence_sha256": _sha256(evidence_sha256, code="star_point_evidence_invalid"),
"share_binding_sha256": _sha256(
share_binding_sha256, code="star_point_share_binding_invalid"
),
"rainbow_source_sha256": RAINBOW_SOURCE_SHA256,
"verdict": point_verdict,
"issued_at_ms": _uint(issued_at_ms, code="star_point_issued_at_invalid"),
"expires_at_ms": _uint(expires_at_ms, code="star_point_expires_at_invalid"),
}
if payload["expires_at_ms"] <= payload["issued_at_ms"]:
raise MagicStarError("star_point_time_window_invalid")
return sign_component_v02(
component_type="MAGIC_STAR_POINT",
authority=authority,
payload=payload,
private_key=private_key,
)
def _rainbow_chain(release_context_sha256: str, candidate_center_sha256: str) -> dict[str, Any]:
previous = domain_hash(
"AUREON-PLUMBER-V02-RAINBOW-SEED",
{
"release_context_sha256": release_context_sha256,
"candidate_center_sha256": candidate_center_sha256,
"rainbow_source_sha256": RAINBOW_SOURCE_SHA256,
},
)
rungs: list[dict[str, Any]] = []
for index, frequency in enumerate(RAINBOW_FREQUENCIES):
current = domain_hash(
"AUREON-PLUMBER-V02-RAINBOW-RUNG",
{
"index": index,
"frequency_hz": frequency,
"previous_sha256": previous,
"release_context_sha256": release_context_sha256,
"candidate_center_sha256": candidate_center_sha256,
},
)
rungs.append(
{
"index": index,
"frequency_hz": frequency,
"previous_sha256": previous,
"commitment": current,
}
)
previous = current
return {"rungs": rungs, "terminal_sha256": previous}
@dataclass(frozen=True, slots=True)
class MagicStarV02:
schema: str
profile: Mapping[str, Any]
epas_precondition: Mapping[str, Any]
heart_precondition: Mapping[str, Any]
points: tuple[Mapping[str, Any], ...]
seal: Mapping[str, Any]
def __post_init__(self) -> None:
for field_name in ("profile", "epas_precondition", "heart_precondition", "seal"):
object.__setattr__(
self,
field_name,
freeze_mapping(getattr(self, field_name), field=field_name),
)
object.__setattr__(
self,
"points",
tuple(
freeze_mapping(point, field=f"points[{index}]")
for index, point in enumerate(self.points)
),
)
def public_dict(self) -> dict[str, Any]:
return {
"schema": self.schema,
"profile": thaw_json(self.profile),
"epas_precondition": thaw_json(self.epas_precondition),
"heart_precondition": thaw_json(self.heart_precondition),
"points": [thaw_json(point) for point in self.points],
"seal": thaw_json(self.seal),
}
@property
def commitment(self) -> str:
return domain_hash("AUREON-PLUMBER-V02-MAGIC-STAR", self.public_dict())
def assemble_magic_star_v02(
*,
release_context_sha256: str,
candidate_center_sha256: str,
epas_precondition: Mapping[str, Any],
heart_precondition: Mapping[str, Any],
points: Sequence[Mapping[str, Any]],
trust: Mapping[str, AuthorityBindingV02],
seal_authority: AuthorityBindingV02,
seal_private_key: Ed25519PrivateKey,
trusted_now_ms: Callable[[], int] = _system_now_ms,
) -> MagicStarV02:
validate_distinct_authorities_v02(trust, required_roles=STAR_AUTHORITY_ROLES)
if trust["STAR_SEAL"] != seal_authority:
raise MagicStarError("star_seal_authority_mismatch")
context = _sha256(release_context_sha256, code="release_context_invalid")
center = _sha256(candidate_center_sha256, code="candidate_center_invalid")
now = _uint(trusted_now_ms(), code="trusted_time_invalid")
epas_payload = verify_component_v02(
epas_precondition,
expected_type="EPAS_PRECONDITION",
expected_authority=trust["EPAS"],
)
heart_payload = verify_component_v02(
heart_precondition,
expected_type="HEART_PRECONDITION",
expected_authority=trust["HEART"],
)
_require_profile_and_shape(
epas_payload, _EPAS_FIELDS, code="epas_precondition_profile_or_shape_invalid"
)
_require_profile_and_shape(
heart_payload, _HEART_FIELDS, code="heart_precondition_profile_or_shape_invalid"
)
_validate_window(epas_payload, now=now, prefix="epas")
_validate_window(heart_payload, now=now, prefix="heart")
_validate_heart_receipt_bridge(
heart_payload,
authority=trust["HEART"],
trusted_now_ms=now,
)
if (
epas_payload.get("release_context_sha256") != context
or epas_payload.get("verdict") != "CLEAR"
or epas_payload.get("outcome") != "PROCEED"
or epas_payload.get("physical_effects_claimed") is not False
):
raise MagicStarError("epas_precondition_denied")
if heart_payload.get("release_context_sha256") != context or heart_payload.get("verdict") != "APPROVE":
raise MagicStarError("heart_precondition_denied")
if len(points) != len(POINTS):
raise MagicStarError("all_five_star_points_required")
point_components: list[dict[str, Any]] = []
point_payloads: list[dict[str, Any]] = []
for index, supplied in enumerate(points):
payload = verify_component_v02(
supplied,
expected_type="MAGIC_STAR_POINT",
expected_authority=trust[POINTS[index]["role"]],
)
_require_profile_and_shape(
payload, _POINT_FIELDS, code="star_point_profile_or_shape_invalid"
)
_validate_window(payload, now=now, prefix="star_point")
if any(payload.get(key) != value for key, value in POINTS[index].items()):
raise MagicStarError("star_point_definition_mismatch")
if payload.get("verdict") != "APPROVE":
raise MagicStarError("star_point_denied")
if payload.get("release_context_sha256") != context or payload.get(
"candidate_center_sha256"
) != center:
raise MagicStarError("star_point_context_mismatch")
point_components.append(dict(supplied))
point_payloads.append(payload)
point_commitments = [component_commitment_v02(point) for point in point_components]
edges = [
{
"from": start,
"to": end,
"commitment": domain_hash(
"AUREON-PLUMBER-V02-STAR-EDGE",
{
"from": start,
"to": end,
"from_point": point_commitments[start],
"to_point": point_commitments[end],
"candidate_center_sha256": center,
},
),
}
for start, end in PENTAGRAM_ROUTE
]
rainbow = _rainbow_chain(context, center)
formation_sha256 = domain_hash(
"AUREON-PLUMBER-V02-STAR-FORMATION",
{
"point_commitments": point_commitments,
"edges": edges,
"rainbow_terminal_sha256": rainbow["terminal_sha256"],
"epas_commitment": component_commitment_v02(epas_precondition),
"heart_commitment": component_commitment_v02(heart_precondition),
"release_context_sha256": context,
"candidate_center_sha256": center,
},
)
seal_payload = {
"protocol_id": PROTOCOL_ID,
"profile_id": PROFILE_ID,
"source_profile_commitment": SOURCE_PROFILE_COMMITMENT,
"implementation_profile_sha256": IMPLEMENTATION_PROFILE_SHA256,
"release_context_sha256": context,
"candidate_center_sha256": center,
"epas_commitment": component_commitment_v02(epas_precondition),
"heart_commitment": component_commitment_v02(heart_precondition),
"point_commitments": point_commitments,
"edges": edges,
"rainbow_chain": rainbow,
"formation_sha256": formation_sha256,
"all_five_required": True,
"four_of_five_denied": True,
"sealed_at_ms": now,
}
seal = sign_component_v02(
component_type="MAGIC_STAR_SEAL",
authority=seal_authority,
payload=seal_payload,
private_key=seal_private_key,
)
star = MagicStarV02(
schema=STAR_SCHEMA,
profile=_profile_public(),
epas_precondition=dict(epas_precondition),
heart_precondition=dict(heart_precondition),
points=tuple(point_components),
seal=seal,
)
validate_magic_star_v02(
star,
trust=trust,
expected_release_context_sha256=context,
expected_candidate_center_sha256=center,
trusted_now_ms=trusted_now_ms,
)
return star
def validate_magic_star_v02(
star: MagicStarV02,
*,
trust: Mapping[str, AuthorityBindingV02],
expected_release_context_sha256: str,
expected_candidate_center_sha256: str,
trusted_now_ms: Callable[[], int] = _system_now_ms,
) -> dict[str, Any]:
if not isinstance(star, MagicStarV02) or star.schema != STAR_SCHEMA:
raise MagicStarError("magic_star_wire_schema_invalid")
if thaw_json(star.profile) != _profile_public():
raise MagicStarError("magic_star_profile_mismatch")
validate_distinct_authorities_v02(trust, required_roles=STAR_AUTHORITY_ROLES)
context = _sha256(expected_release_context_sha256, code="release_context_invalid")
center = _sha256(expected_candidate_center_sha256, code="candidate_center_invalid")
now = _uint(trusted_now_ms(), code="trusted_time_invalid")
epas_payload = verify_component_v02(
star.epas_precondition,
expected_type="EPAS_PRECONDITION",
expected_authority=trust["EPAS"],
)
heart_payload = verify_component_v02(
star.heart_precondition,
expected_type="HEART_PRECONDITION",
expected_authority=trust["HEART"],
)
_require_profile_and_shape(
epas_payload, _EPAS_FIELDS, code="epas_precondition_profile_or_shape_invalid"
)
_require_profile_and_shape(
heart_payload, _HEART_FIELDS, code="heart_precondition_profile_or_shape_invalid"
)
_validate_window(epas_payload, now=now, prefix="epas")
_validate_window(heart_payload, now=now, prefix="heart")
heart_receipt = _validate_heart_receipt_bridge(
heart_payload,
authority=trust["HEART"],
trusted_now_ms=now,
)
if (
epas_payload.get("release_context_sha256") != context
or epas_payload.get("verdict") != "CLEAR"
or epas_payload.get("outcome") != "PROCEED"
or epas_payload.get("physical_effects_claimed") is not False
):
raise MagicStarError("epas_precondition_invalid")
if (
heart_payload.get("release_context_sha256") != context
or heart_payload.get("verdict") != "APPROVE"
):
raise MagicStarError("heart_precondition_invalid")
if len(star.points) != len(POINTS):
raise MagicStarError("all_five_star_points_required")
point_commitments: list[str] = []
for index, component in enumerate(star.points):
payload = verify_component_v02(
component,
expected_type="MAGIC_STAR_POINT",
expected_authority=trust[POINTS[index]["role"]],
)
_require_profile_and_shape(
payload, _POINT_FIELDS, code="star_point_profile_or_shape_invalid"
)
_validate_window(payload, now=now, prefix="star_point")
if any(payload.get(key) != value for key, value in POINTS[index].items()):
raise MagicStarError("star_point_definition_mismatch")
if payload.get("verdict") != "APPROVE":
raise MagicStarError("star_point_denied")
if payload.get("release_context_sha256") != context or payload.get(
"candidate_center_sha256"
) != center:
raise MagicStarError("star_point_context_mismatch")
point_commitments.append(component_commitment_v02(component))
seal_payload = verify_component_v02(
star.seal,
expected_type="MAGIC_STAR_SEAL",
expected_authority=trust["STAR_SEAL"],
)
_require_profile_and_shape(
seal_payload, _SEAL_FIELDS, code="magic_star_seal_profile_or_shape_invalid"
)
expected_edges = [
{
"from": start,
"to": end,
"commitment": domain_hash(
"AUREON-PLUMBER-V02-STAR-EDGE",
{
"from": start,
"to": end,
"from_point": point_commitments[start],
"to_point": point_commitments[end],
"candidate_center_sha256": center,
},
),
}
for start, end in PENTAGRAM_ROUTE
]
rainbow = _rainbow_chain(context, center)
expected_formation = domain_hash(
"AUREON-PLUMBER-V02-STAR-FORMATION",
{
"point_commitments": point_commitments,
"edges": expected_edges,
"rainbow_terminal_sha256": rainbow["terminal_sha256"],
"epas_commitment": component_commitment_v02(star.epas_precondition),
"heart_commitment": component_commitment_v02(star.heart_precondition),
"release_context_sha256": context,
"candidate_center_sha256": center,
},
)
exact = {
"protocol_id": PROTOCOL_ID,
"profile_id": PROFILE_ID,
"source_profile_commitment": SOURCE_PROFILE_COMMITMENT,
"implementation_profile_sha256": IMPLEMENTATION_PROFILE_SHA256,
"release_context_sha256": context,
"candidate_center_sha256": center,
"epas_commitment": component_commitment_v02(star.epas_precondition),
"heart_commitment": component_commitment_v02(star.heart_precondition),
"point_commitments": point_commitments,
"edges": expected_edges,
"rainbow_chain": rainbow,
"formation_sha256": expected_formation,
"all_five_required": True,
"four_of_five_denied": True,
}
if any(seal_payload.get(key) != value for key, value in exact.items()):
raise MagicStarError("magic_star_seal_join_mismatch")
sealed_at = _uint(seal_payload.get("sealed_at_ms"), code="magic_star_seal_time_invalid")
latest_issued = max(
_uint(epas_payload["issued_at_ms"], code="epas_issued_at_invalid"),
_uint(heart_payload["issued_at_ms"], code="heart_issued_at_invalid"),
*(
_uint(
verify_component_v02(
component,
expected_type="MAGIC_STAR_POINT",
expected_authority=trust[POINTS[index]["role"]],
)["issued_at_ms"],
code="star_point_issued_at_invalid",
)
for index, component in enumerate(star.points)
),
)
if sealed_at < latest_issued or sealed_at > now:
raise MagicStarError("magic_star_seal_time_invalid")
source_rainbow = verify_rainbow()
if source_rainbow.get("consistent") is not True:
raise MagicStarError("canonical_rainbow_source_inconsistent")
return {
"valid": True,
"protocol_id": PROTOCOL_ID,
"profile_id": PROFILE_ID,
"release_context_sha256": context,
"candidate_center_sha256": center,
"formation_sha256": expected_formation,
"star_commitment": star.commitment,
"heart_receipt_commitment": heart_receipt_commitment_v02(heart_receipt),
"point_count": len(point_commitments),
"expires_at_ms": min(
_uint(epas_payload["expires_at_ms"], code="epas_expires_at_invalid"),
_uint(heart_payload["expires_at_ms"], code="heart_expires_at_invalid"),
*(
_uint(
verify_component_v02(
component,
expected_type="MAGIC_STAR_POINT",
expected_authority=trust[POINTS[index]["role"]],
)["expires_at_ms"],
code="star_point_expires_at_invalid",
)
for index, component in enumerate(star.points)
),
),
"production_ready": False,
}
__all__ = [
"AuthorityBindingV02",
"IMPLEMENTATION_PROFILE_SHA256",
"MagicStarError",
"MagicStarV02",
"PENTAGRAM_ROUTE",
"POINTS",
"POINT_ROLES",
"PROFILE_DESCRIPTOR",
"PROFILE_ID",
"PROTOCOL_ID",
"RAINBOW_FREQUENCIES",
"RAINBOW_SOURCE_SHA256",
"SOURCE_PROFILE_COMMITMENT",
"STAR_AUTHORITY_ROLES",
"assemble_magic_star_v02",
"build_authority_binding_v02",
"build_candidate_center_v02",
"build_epas_precondition_v02",
"build_heart_precondition_v02",
"build_heart_source_identity_commitment_v02",
"build_magic_star_point_v02",
"component_commitment_v02",
"heart_receipt_commitment_v02",
"sign_component_v02",
"validate_distinct_authorities_v02",
"validate_magic_star_v02",
"verify_component_v02",
]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236"""Canonical HNC observer transcript commitments for Plumber v0.
Observer values are authenticated public context. This module never treats
them as encryption keys, key shares, or sources of cryptographic entropy.
"""
from __future__ import annotations
from collections.abc import Mapping, Sequence
from dataclasses import dataclass
from typing import Any, Self
from .crypto import domain_hash
from .schema import (
DenialCode,
SchemaError,
freeze_mapping,
require_exact_keys,
require_fixed_decimal,
require_nonblank,
require_sha256,
)
OBSERVER_TRANSCRIPT_SCHEMA = "aureon.plumber.observer-transcript.v0"
_FIELDS = (
"schema",
"packet_identity",
"session_identity",
"purpose_commitment",
"challenge_commitment",
"canonical_hnc_values",
"trajectory_commitments",
"coherence",
"consciousness_proxy",
"symbolic_life",
"hnc_parameters",
"rock_commitments",
"active_mode",
"active_plateau",
"transition_commitment",
"regime",
"divergence_score",
"source_receipt_commitments",
"transcript_commitment",
)
def _numbers(value: Mapping[str, Any], *, field: str) -> dict[str, str]:
if not isinstance(value, Mapping) or not value:
raise SchemaError(DenialCode.INVALID_TYPE, field=field)
parsed: dict[str, str] = {}
for key, item in value.items():
require_nonblank(key, field=f"{field}.key")
parsed[key] = require_fixed_decimal(item, field=f"{field}.{key}")
return parsed
def _commitments(value: Sequence[Any], *, field: str, nonempty: bool = True) -> tuple[str, ...]:
if isinstance(value, (str, bytes, bytearray)) or not isinstance(value, Sequence):
raise SchemaError(DenialCode.INVALID_TYPE, field=field)
result = tuple(value)
if nonempty and not result:
raise SchemaError(DenialCode.INVALID_VALUE, field=field)
for item in result:
require_sha256(item, field=field)
return result
@dataclass(frozen=True, slots=True)
class ObserverTranscriptV0:
schema: str
packet_identity: str
session_identity: str
purpose_commitment: str
challenge_commitment: str
canonical_hnc_values: Mapping[str, str]
trajectory_commitments: tuple[str, ...]
coherence: str
consciousness_proxy: str | None
symbolic_life: bool
hnc_parameters: Mapping[str, str]
rock_commitments: tuple[str, ...]
active_mode: str
active_plateau: str
transition_commitment: str
regime: str
divergence_score: str
source_receipt_commitments: tuple[str, ...]
transcript_commitment: str
def __post_init__(self) -> None:
if self.schema != OBSERVER_TRANSCRIPT_SCHEMA:
raise SchemaError(DenialCode.INVALID_SCHEMA, field="schema")
for field in ("packet_identity", "session_identity", "active_mode", "active_plateau", "regime"):
require_nonblank(getattr(self, field), field=field)
for field in ("purpose_commitment", "challenge_commitment", "transition_commitment", "transcript_commitment"):
require_sha256(getattr(self, field), field=field)
_numbers(self.canonical_hnc_values, field="canonical_hnc_values")
_numbers(self.hnc_parameters, field="hnc_parameters")
object.__setattr__(
self,
"canonical_hnc_values",
freeze_mapping(self.canonical_hnc_values, field="canonical_hnc_values"),
)
object.__setattr__(
self,
"hnc_parameters",
freeze_mapping(self.hnc_parameters, field="hnc_parameters"),
)
object.__setattr__(
self,
"trajectory_commitments",
_commitments(self.trajectory_commitments, field="trajectory_commitments"),
)
object.__setattr__(
self,
"rock_commitments",
_commitments(self.rock_commitments, field="rock_commitments", nonempty=False),
)
object.__setattr__(
self,
"source_receipt_commitments",
_commitments(self.source_receipt_commitments, field="source_receipt_commitments"),
)
require_fixed_decimal(self.coherence, field="coherence")
require_fixed_decimal(self.divergence_score, field="divergence_score")
if self.consciousness_proxy is not None:
require_fixed_decimal(self.consciousness_proxy, field="consciousness_proxy")
if type(self.symbolic_life) is not bool:
raise SchemaError(DenialCode.INVALID_TYPE, field="symbolic_life")
if domain_hash("aureon.plumber.observer-transcript.v0", self.commitment_payload()) != self.transcript_commitment:
raise SchemaError(DenialCode.OBSERVER_TRANSCRIPT_MISMATCH, field="transcript_commitment")
@classmethod
def build(
cls,
*,
packet_identity: str,
session_identity: str,
purpose_commitment: str,
challenge_commitment: str,
canonical_hnc_values: Mapping[str, int | str],
trajectory_commitments: Sequence[str],
coherence: int | str,
consciousness_proxy: int | str | None,
symbolic_life: bool,
hnc_parameters: Mapping[str, int | str],
rock_commitments: Sequence[str],
active_mode: str,
active_plateau: str,
transition_commitment: str,
regime: str,
divergence_score: int | str,
source_receipt_commitments: Sequence[str],
) -> Self:
values: dict[str, Any] = {
"schema": OBSERVER_TRANSCRIPT_SCHEMA,
"packet_identity": packet_identity,
"session_identity": session_identity,
"purpose_commitment": purpose_commitment,
"challenge_commitment": challenge_commitment,
"canonical_hnc_values": _numbers(canonical_hnc_values, field="canonical_hnc_values"),
"trajectory_commitments": _commitments(trajectory_commitments, field="trajectory_commitments"),
"coherence": require_fixed_decimal(coherence, field="coherence"),
"consciousness_proxy": (
None
if consciousness_proxy is None
else require_fixed_decimal(consciousness_proxy, field="consciousness_proxy")
),
"symbolic_life": symbolic_life,
"hnc_parameters": _numbers(hnc_parameters, field="hnc_parameters"),
"rock_commitments": _commitments(rock_commitments, field="rock_commitments", nonempty=False),
"active_mode": active_mode,
"active_plateau": active_plateau,
"transition_commitment": transition_commitment,
"regime": regime,
"divergence_score": require_fixed_decimal(divergence_score, field="divergence_score"),
"source_receipt_commitments": _commitments(
source_receipt_commitments,
field="source_receipt_commitments",
),
}
return cls(
**values,
transcript_commitment=domain_hash("aureon.plumber.observer-transcript.v0", values),
)
@classmethod
def from_dict(cls, value: Mapping[str, Any]) -> Self:
parsed = require_exact_keys(value, _FIELDS, field="observer_transcript")
parsed["canonical_hnc_values"] = _numbers(parsed["canonical_hnc_values"], field="canonical_hnc_values")
parsed["hnc_parameters"] = _numbers(parsed["hnc_parameters"], field="hnc_parameters")
for field, nonempty in (
("trajectory_commitments", True),
("rock_commitments", False),
("source_receipt_commitments", True),
):
parsed[field] = _commitments(parsed[field], field=field, nonempty=nonempty)
return cls(**parsed)
def commitment_payload(self) -> dict[str, Any]:
return {
field: getattr(self, field)
for field in _FIELDS
if field != "transcript_commitment"
}
def to_dict(self) -> dict[str, Any]:
return {
**self.commitment_payload(),
"trajectory_commitments": list(self.trajectory_commitments),
"rock_commitments": list(self.rock_commitments),
"source_receipt_commitments": list(self.source_receipt_commitments),
"transcript_commitment": self.transcript_commitment,
}
def public_summary(self) -> dict[str, Any]:
return {
"schema": self.schema,
"packet_identity": self.packet_identity,
"session_identity": self.session_identity,
"purpose_commitment": self.purpose_commitment,
"challenge_commitment": self.challenge_commitment,
"hnc_values_commitment": domain_hash("aureon.plumber.hnc-values.v0", self.canonical_hnc_values),
"trajectory_count": len(self.trajectory_commitments),
"rock_count": len(self.rock_commitments),
"source_receipt_count": len(self.source_receipt_commitments),
"transcript_commitment": self.transcript_commitment,
}
def build_observer_transcript(**values: Any) -> ObserverTranscriptV0:
return ObserverTranscriptV0.build(**values)
__all__ = ["OBSERVER_TRANSCRIPT_SCHEMA", "ObserverTranscriptV0", "build_observer_transcript"]12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081"""Local-development whole-OS admission and Magic Star hand-off boundary.
This module is an architectural choke point for *untrusted ingress*. It does
not claim that locally wrapping bytes establishes remote truth, and it is not a
production sandbox, HSM, durable replay ledger, or malware detector.
Every call to :meth:`LocalOSProtectionBoundary.admit_external` that reaches the
bounded-content contract returns exactly one of two typed outcomes:
* :class:`AdmittedHNC` -- the bytes were sealed into a validated HNC packet and
retained only behind an opaque, one-use handle; or
* :class:`QuarantinedHNC` -- no application payload was retained. When a valid
key is available, a separate HNC packet contains commitment-only quarantine
metadata. A missing/invalid key still yields a fail-closed metadata record.
The only supported carrier hand-off consumes the opaque handle and calls the
existing local-development Magic Star custody adapter. No public API returns
the HNC carrier, its key, or the original bytes.
"""
from __future__ import annotations
import hashlib
import secrets
import threading
from collections.abc import Callable, Iterator, Mapping, Sequence
from contextlib import AbstractContextManager, contextmanager
from dataclasses import dataclass, field
from datetime import UTC, datetime
from enum import StrEnum
from typing import Any, Final, Protocol, TypeAlias
from aureon.harmonic.hnc_quantum_packet_crypto import (
build_hnc_quantum_packet,
normalize_hnc_key_material,
validate_hnc_packet_contract,
)
from .audit import assert_public_summary_safe
from .crypto import canonical_json_bytes, decode_canonical_json, domain_hash, sha256_hex
from .packet import HNCPayloadBindingV0, bind_hnc_packet
from .quarantine import QuarantineRecord
from .schema import (
SchemaError,
format_timestamp,
parse_timestamp,
require_aware_datetime,
require_nonblank,
require_sha256,
)
from .star_custody_v02 import (
LocalDevelopmentStarCustodyV02,
ProtectedMagicStarPacketV02,
StarCustodyError,
validate_magic_star_inner_carrier_capacity_v02,
)
OS_PROTECTION_SCHEMA: Final = "aureon.plumber.os-protection.v0"
OS_INGRESS_AAD_SCHEMA: Final = "aureon.plumber.os-ingress-aad.v0"
OS_QUARANTINE_EVIDENCE_SCHEMA: Final = "aureon.plumber.os-quarantine-evidence.v0"
OS_QUARANTINE_EVIDENCE_PURPOSE: Final = "aureon.plumber.os.quarantine-evidence.v0"
OS_KEY_PREFLIGHT_SCHEMA: Final = "aureon.plumber.os-key-preflight.v0"
OS_DURABLE_QUARANTINE_EVIDENCE_SCHEMA: Final = (
"aureon.plumber.os-durable-quarantine-evidence.v04"
)
OS_RUNTIME_GUARD_LIFECYCLE_SCHEMA: Final = (
"aureon.plumber.os-runtime-guard-lifecycle.v04"
)
DEFAULT_MAX_INGRESS_BYTES: Final = 16 * 1024 * 1024
MAX_OPERATOR_AAD_BYTES: Final = 64 * 1024
_MAX_BOUNDARY_ID_BYTES: Final = 128
_MAX_SOURCE_ID_BYTES: Final = 512
_MAX_INGRESS_KIND_BYTES: Final = 128
_MAX_PURPOSE_BYTES: Final = 1024
_MAX_OPERATOR_AAD_DEPTH: Final = 16
_MAX_OPERATOR_AAD_NODES: Final = 4096
_MAX_ACTIVE_HANDLES_LIMIT: Final = 4096
_MAX_ACTIVE_INGRESS_BYTES_LIMIT: Final = 256 * 1024 * 1024
_MAX_REPLAY_TOKENS_LIMIT: Final = 1_000_000
_MAX_QUARANTINE_EVIDENCE_LIMIT: Final = 65_536
MasterKeyProvider: TypeAlias = Callable[[], bytes | str | None]
ContentValidator: TypeAlias = Callable[[memoryview], bool]
class QuarantineEvidenceSink(Protocol):
"""Pre-opened durable sink used without returning sealed HNC packets."""
def preflight(self) -> Mapping[str, Any]: ...
def append_violation(
self,
*,
intrusion_id: str,
runtime_metadata: Mapping[str, Any],
quarantine_summary: Mapping[str, Any],
hnc_packet: Mapping[str, Any],
) -> Mapping[str, Any]: ...
def seal_for_runtime_guard(self, owner_token: str) -> Mapping[str, Any]: ...
def validate_runtime_guard_seal(
self,
owner_token: str,
lifecycle_generation: int,
) -> Mapping[str, Any]: ...
def runtime_guard_lifecycle_lease(
self,
owner_token: str,
lifecycle_generation: int,
) -> AbstractContextManager[Mapping[str, Any]]: ...
class OSProtectionError(ValueError):
"""Stable, non-secret local protection boundary error."""
def __init__(self, code: str) -> None:
self.code = str(code)
super().__init__(self.code)
class IngressDisposition(StrEnum):
ADMITTED_HNC = "ADMITTED_HNC"
QUARANTINED_HNC = "QUARANTINED_HNC"
def _system_now() -> datetime:
return datetime.now(UTC).replace(microsecond=0)
def _bounded_text(value: object, *, field_name: str, maximum_bytes: int) -> str:
try:
text = require_nonblank(value, field=field_name, max_length=maximum_bytes)
encoded = text.encode("utf-8", errors="strict")
except (SchemaError, UnicodeEncodeError) as exc:
raise OSProtectionError(f"{field_name}_invalid") from exc
if len(encoded) > maximum_bytes or "\x00" in text:
raise OSProtectionError(f"{field_name}_invalid")
return text
def _purpose_commitment(purpose: str) -> str:
return domain_hash("aureon.plumber.purpose.v0", purpose)
def _handle_commitment(*, boundary_id: str, handle_id: str, token: str) -> str:
return domain_hash(
"aureon.plumber.os-protection-handle.v0",
{"boundary_id": boundary_id, "handle_id": handle_id, "token": token},
)
def _snapshot_operator_aad(
value: Any,
*,
depth: int = 0,
remaining_nodes: list[int] | None = None,
) -> Any:
"""Copy JSON-like AAD under explicit depth, node, and string budgets."""
budget = remaining_nodes if remaining_nodes is not None else [_MAX_OPERATOR_AAD_NODES]
budget[0] -= 1
if budget[0] < 0 or depth > _MAX_OPERATOR_AAD_DEPTH:
raise OSProtectionError("operator_aad_invalid")
if value is None or type(value) in {bool, int}:
return value
if isinstance(value, str):
if len(value.encode("utf-8", errors="strict")) > MAX_OPERATOR_AAD_BYTES:
raise OSProtectionError("operator_aad_invalid")
return value
if isinstance(value, Mapping):
result: dict[str, Any] = {}
for key, item in value.items():
if not isinstance(key, str) or key in result:
raise OSProtectionError("operator_aad_invalid")
if len(key.encode("utf-8", errors="strict")) > MAX_OPERATOR_AAD_BYTES:
raise OSProtectionError("operator_aad_invalid")
result[key] = _snapshot_operator_aad(
item,
depth=depth + 1,
remaining_nodes=budget,
)
return result
if isinstance(value, Sequence) and not isinstance(
value,
(bytes, bytearray, memoryview, str),
):
return [
_snapshot_operator_aad(
item,
depth=depth + 1,
remaining_nodes=budget,
)
for item in value
]
raise OSProtectionError("operator_aad_invalid")
@dataclass(frozen=True, slots=True)
class OpaqueHNCHandle:
"""Unforgeable, one-use reference to an HNC carrier held by the boundary."""
boundary_id: str
handle_id: str
token: str = field(repr=False)
handle_commitment: str
def __post_init__(self) -> None:
_bounded_text(
self.boundary_id,
field_name="boundary_id",
maximum_bytes=_MAX_BOUNDARY_ID_BYTES,
)
_bounded_text(
self.handle_id,
field_name="handle_id",
maximum_bytes=_MAX_BOUNDARY_ID_BYTES,
)
if not isinstance(self.token, str) or not self.token:
raise OSProtectionError("opaque_handle_token_invalid")
require_sha256(self.handle_commitment, field="handle_commitment")
if self.handle_commitment != _handle_commitment(
boundary_id=self.boundary_id,
handle_id=self.handle_id,
token=self.token,
):
raise OSProtectionError("opaque_handle_commitment_invalid")
@classmethod
def issue(cls, *, boundary_id: str, handle_id: str) -> OpaqueHNCHandle:
token = secrets.token_urlsafe(32)
return cls(
boundary_id=boundary_id,
handle_id=handle_id,
token=token,
handle_commitment=_handle_commitment(
boundary_id=boundary_id,
handle_id=handle_id,
token=token,
),
)
def public_summary(self) -> dict[str, str]:
return {
"boundary_id": self.boundary_id,
"handle_id": self.handle_id,
"handle_commitment": self.handle_commitment,
}
def _common_public_values(
*,
disposition: IngressDisposition,
boundary_id: str,
admission_id: str,
source_id: str,
ingress_kind: str,
content_sha256: str,
content_size_bytes: int,
purpose_commitment: str,
operator_aad_sha256: str,
replay_token: str,
recorded_at: str,
) -> dict[str, Any]:
return {
"schema": OS_PROTECTION_SCHEMA,
"disposition": str(disposition),
"boundary_id": boundary_id,
"admission_id": admission_id,
"source_id": source_id,
"ingress_kind": ingress_kind,
"content_sha256": content_sha256,
"content_size_bytes": content_size_bytes,
"purpose_commitment": purpose_commitment,
"operator_aad_sha256": operator_aad_sha256,
"replay_token": replay_token,
"recorded_at": recorded_at,
"local_development_only": True,
"production_ready": False,
}
@dataclass(frozen=True, slots=True)
class AdmittedHNC:
"""Validated HNC admission. It intentionally contains no carrier bytes."""
boundary_id: str
admission_id: str
source_id: str
ingress_kind: str
content_sha256: str
content_size_bytes: int
purpose_commitment: str
operator_aad_sha256: str
replay_token: str
recorded_at: str
handle: OpaqueHNCHandle
hnc_payload_binding: HNCPayloadBindingV0
admission_commitment: str
disposition: IngressDisposition = IngressDisposition.ADMITTED_HNC
local_development_only: bool = True
production_ready: bool = False
def __post_init__(self) -> None:
if self.disposition is not IngressDisposition.ADMITTED_HNC:
raise OSProtectionError("admitted_disposition_invalid")
if self.local_development_only is not True or self.production_ready is not False:
raise OSProtectionError("admitted_scope_invalid")
if self.handle.boundary_id != self.boundary_id or self.handle.handle_id != self.admission_id:
raise OSProtectionError("admitted_handle_join_mismatch")
if not isinstance(self.hnc_payload_binding, HNCPayloadBindingV0):
raise OSProtectionError("hnc_payload_binding_invalid")
_bounded_text(
self.boundary_id,
field_name="boundary_id",
maximum_bytes=_MAX_BOUNDARY_ID_BYTES,
)
_bounded_text(
self.admission_id,
field_name="admission_id",
maximum_bytes=_MAX_BOUNDARY_ID_BYTES,
)
_bounded_text(
self.source_id,
field_name="source_id",
maximum_bytes=_MAX_SOURCE_ID_BYTES,
)
_bounded_text(
self.ingress_kind,
field_name="ingress_kind",
maximum_bytes=_MAX_INGRESS_KIND_BYTES,
)
parse_timestamp(self.recorded_at, field="recorded_at")
for value in (
self.content_sha256,
self.purpose_commitment,
self.operator_aad_sha256,
self.replay_token,
self.admission_commitment,
):
require_sha256(value, field="admitted_commitment")
if self.content_size_bytes < 0:
raise OSProtectionError("content_size_invalid")
if self.hnc_payload_binding.purpose_commitment != self.purpose_commitment:
raise OSProtectionError("admitted_hnc_purpose_join_mismatch")
expected = domain_hash(
"aureon.plumber.os-admission.v0",
self._commitment_payload(),
)
if expected != self.admission_commitment:
raise OSProtectionError("admission_commitment_invalid")
def _commitment_payload(self) -> dict[str, Any]:
return {
**_common_public_values(
disposition=self.disposition,
boundary_id=self.boundary_id,
admission_id=self.admission_id,
source_id=self.source_id,
ingress_kind=self.ingress_kind,
content_sha256=self.content_sha256,
content_size_bytes=self.content_size_bytes,
purpose_commitment=self.purpose_commitment,
operator_aad_sha256=self.operator_aad_sha256,
replay_token=self.replay_token,
recorded_at=self.recorded_at,
),
"handle": self.handle.public_summary(),
"hnc_payload_binding": self.hnc_payload_binding.public_summary(),
}
def public_summary(self) -> dict[str, Any]:
summary = {
**self._commitment_payload(),
"admission_commitment": self.admission_commitment,
}
assert_public_summary_safe(summary)
return summary
@dataclass(frozen=True, slots=True)
class QuarantinedHNC:
"""Commitment-only denial; the application payload is never retained."""
boundary_id: str
admission_id: str
source_id: str
ingress_kind: str
content_sha256: str
content_size_bytes: int
purpose_commitment: str
operator_aad_sha256: str
replay_token: str
recorded_at: str
denial_codes: tuple[str, ...]
quarantine_record: QuarantineRecord
hnc_evidence_binding: HNCPayloadBindingV0 | None
quarantine_commitment: str
disposition: IngressDisposition = IngressDisposition.QUARANTINED_HNC
local_development_only: bool = True
production_ready: bool = False
def __post_init__(self) -> None:
if self.disposition is not IngressDisposition.QUARANTINED_HNC:
raise OSProtectionError("quarantine_disposition_invalid")
if self.local_development_only is not True or self.production_ready is not False:
raise OSProtectionError("quarantine_scope_invalid")
if not self.denial_codes or tuple(sorted(set(self.denial_codes))) != self.denial_codes:
raise OSProtectionError("quarantine_denial_codes_invalid")
if not isinstance(self.quarantine_record, QuarantineRecord):
raise OSProtectionError("quarantine_record_invalid")
if self.hnc_evidence_binding is not None and not isinstance(
self.hnc_evidence_binding,
HNCPayloadBindingV0,
):
raise OSProtectionError("quarantine_hnc_binding_invalid")
_bounded_text(
self.boundary_id,
field_name="boundary_id",
maximum_bytes=_MAX_BOUNDARY_ID_BYTES,
)
_bounded_text(
self.admission_id,
field_name="admission_id",
maximum_bytes=_MAX_BOUNDARY_ID_BYTES,
)
_bounded_text(
self.source_id,
field_name="source_id",
maximum_bytes=_MAX_SOURCE_ID_BYTES,
)
_bounded_text(
self.ingress_kind,
field_name="ingress_kind",
maximum_bytes=_MAX_INGRESS_KIND_BYTES,
)
parse_timestamp(self.recorded_at, field="recorded_at")
for value in (
self.content_sha256,
self.purpose_commitment,
self.operator_aad_sha256,
self.replay_token,
self.quarantine_commitment,
):
require_sha256(value, field="quarantine_commitment")
if self.content_size_bytes < 0:
raise OSProtectionError("content_size_invalid")
record = self.quarantine_record
if (
record.quarantine_id != self.admission_id
or record.packet_identity != self.admission_id
or record.session_identity != self.boundary_id
or record.packet_commitment != self.content_sha256
or record.denial_codes != self.denial_codes
or record.quarantined_at != self.recorded_at
or record.evidence_commitments.get("operator_aad_sha256")
!= self.operator_aad_sha256
or record.evidence_commitments.get("purpose_commitment")
!= self.purpose_commitment
or record.evidence_commitments.get("replay_token") != self.replay_token
):
raise OSProtectionError("quarantine_record_join_mismatch")
if self.hnc_evidence_binding is not None and (
record.evidence_commitments.get("hnc_quarantine_packet_commitment")
!= self.hnc_evidence_binding.hnc_packet_commitment
or record.evidence_commitments.get("hnc_quarantine_binding_commitment")
!= self.hnc_evidence_binding.binding_commitment
or self.hnc_evidence_binding.purpose_commitment
!= _purpose_commitment(OS_QUARANTINE_EVIDENCE_PURPOSE)
):
raise OSProtectionError("quarantine_hnc_join_mismatch")
expected = domain_hash(
"aureon.plumber.os-quarantine.v0",
self._commitment_payload(),
)
if expected != self.quarantine_commitment:
raise OSProtectionError("quarantine_commitment_invalid")
def _commitment_payload(self) -> dict[str, Any]:
return {
**_common_public_values(
disposition=self.disposition,
boundary_id=self.boundary_id,
admission_id=self.admission_id,
source_id=self.source_id,
ingress_kind=self.ingress_kind,
content_sha256=self.content_sha256,
content_size_bytes=self.content_size_bytes,
purpose_commitment=self.purpose_commitment,
operator_aad_sha256=self.operator_aad_sha256,
replay_token=self.replay_token,
recorded_at=self.recorded_at,
),
"denial_codes": list(self.denial_codes),
"quarantine_record": self.quarantine_record.public_summary(),
"hnc_evidence_binding": (
None
if self.hnc_evidence_binding is None
else self.hnc_evidence_binding.public_summary()
),
"raw_material_retained": False,
}
def public_summary(self) -> dict[str, Any]:
summary = {
**self._commitment_payload(),
"quarantine_commitment": self.quarantine_commitment,
}
assert_public_summary_safe(summary)
return summary
AdmissionOutcome: TypeAlias = AdmittedHNC | QuarantinedHNC
@dataclass(slots=True)
class _AdmissionRecord:
packet: dict[str, Any]
master_key: bytearray
purpose: str
handle_commitment: str
content_size_bytes: int
class LocalOSProtectionBoundary:
"""Atomic in-memory ingress boundary for local development only."""
production_ready = False
def __init__(
self,
*,
boundary_id: str,
master_key_provider: MasterKeyProvider,
max_ingress_bytes: int = DEFAULT_MAX_INGRESS_BYTES,
max_active_handles: int = 64,
max_active_ingress_bytes: int = 64 * 1024 * 1024,
max_replay_tokens: int = 8192,
max_quarantine_evidence: int = 2048,
trusted_now: Callable[[], datetime] = _system_now,
quarantine_evidence_sink: QuarantineEvidenceSink | None = None,
) -> None:
self._boundary_id = _bounded_text(
boundary_id,
field_name="boundary_id",
maximum_bytes=_MAX_BOUNDARY_ID_BYTES,
)
if not callable(master_key_provider):
raise OSProtectionError("master_key_provider_invalid")
if not callable(trusted_now):
raise OSProtectionError("trusted_time_provider_invalid")
if quarantine_evidence_sink is not None and (
not callable(getattr(quarantine_evidence_sink, "preflight", None))
or not callable(
getattr(quarantine_evidence_sink, "append_violation", None)
)
or not callable(
getattr(quarantine_evidence_sink, "seal_for_runtime_guard", None)
)
or not callable(
getattr(
quarantine_evidence_sink,
"validate_runtime_guard_seal",
None,
)
)
or not callable(
getattr(
quarantine_evidence_sink,
"runtime_guard_lifecycle_lease",
None,
)
)
):
raise OSProtectionError("quarantine_evidence_sink_invalid")
if (
type(max_ingress_bytes) is not int
or max_ingress_bytes < 1
or max_ingress_bytes > DEFAULT_MAX_INGRESS_BYTES
):
raise OSProtectionError("max_ingress_bytes_invalid")
if (
type(max_active_handles) is not int
or max_active_handles < 1
or max_active_handles > _MAX_ACTIVE_HANDLES_LIMIT
):
raise OSProtectionError("max_active_handles_invalid")
if (
type(max_active_ingress_bytes) is not int
or max_active_ingress_bytes < 1
or max_active_ingress_bytes > _MAX_ACTIVE_INGRESS_BYTES_LIMIT
):
raise OSProtectionError("max_active_ingress_bytes_invalid")
if (
type(max_replay_tokens) is not int
or max_replay_tokens < 1
or max_replay_tokens > _MAX_REPLAY_TOKENS_LIMIT
):
raise OSProtectionError("max_replay_tokens_invalid")
if (
type(max_quarantine_evidence) is not int
or max_quarantine_evidence < 1
or max_quarantine_evidence > _MAX_QUARANTINE_EVIDENCE_LIMIT
):
raise OSProtectionError("max_quarantine_evidence_invalid")
self._master_key_provider = master_key_provider
self._max_ingress_bytes = max_ingress_bytes
self._max_active_handles = max_active_handles
self._max_active_ingress_bytes = max_active_ingress_bytes
self._max_replay_tokens = max_replay_tokens
self._max_quarantine_evidence = max_quarantine_evidence
self._trusted_now = trusted_now
self._quarantine_evidence_sink = quarantine_evidence_sink
self._durable_evidence_terminal = False
self._durable_evidence_failure_code: str | None = None
self._durable_evidence_count = 0
self._durable_evidence_head_commitment = "0" * 64
self._durable_evidence_ledger_id: str | None = None
self._durable_evidence_ledger_instance_commitment: str | None = None
self._durable_evidence_entry_count: int | None = None
self._durable_evidence_violation_count: int | None = None
self._durable_evidence_last_receipt_sequence: int | None = None
self._durable_evidence_packets_persisted = False
# Serializes one complete boundary operation with runtime-guard
# evidence lifecycle transitions. The state lock below remains the
# short critical-section lock for counters and opaque records; this
# lifecycle lock may intentionally span validator/custody calls so a
# terminal transition is linearly ordered before or after the whole
# operation, never through its middle.
self._runtime_guard_lifecycle_lock = threading.RLock()
self._runtime_guard_sealed = False
self._runtime_guard_owner_token: str | None = None
self._runtime_guard_owner_token_sha256: str | None = None
self._runtime_guard_sink_generation: int | None = None
self._runtime_guard_lifecycle_generation = 0
self._seen_replay_tokens: set[str] = set()
self._records: dict[str, _AdmissionRecord] = {}
self._active_ingress_bytes = 0
self._consumed_handle_commitments: set[str] = set()
self._quarantine_packets: dict[str, dict[str, Any]] = {}
self._lock = threading.RLock()
def _mark_durable_evidence_terminal_locked(self, code: str) -> None:
"""Make one sticky terminal transition while ``self._lock`` is held."""
selected = _bounded_text(
code,
field_name="durable_quarantine_failure_code",
maximum_bytes=128,
)
if not self._durable_evidence_terminal:
self._runtime_guard_lifecycle_generation += 1
self._durable_evidence_terminal = True
self._durable_evidence_failure_code = selected
elif self._durable_evidence_failure_code is None: # pragma: no cover
self._durable_evidence_failure_code = selected
def _lifecycle_operation_generation(self) -> int:
"""Snapshot one non-terminal generation for later atomic commit."""
with self._runtime_guard_lifecycle_lock:
self._require_durable_evidence_ready()
with self._lock:
if self._durable_evidence_terminal:
raise OSProtectionError("durable_quarantine_evidence_terminal")
return self._runtime_guard_lifecycle_generation
def _require_lifecycle_generation_locked(self, generation: int) -> None:
"""Reject in-flight work invalidated by a completed transition."""
if (
self._durable_evidence_terminal
or generation != self._runtime_guard_lifecycle_generation
):
raise OSProtectionError("durable_quarantine_evidence_terminal")
@contextmanager
def _lifecycle_commit_lease(self, generation: int) -> Iterator[None]:
"""Linearize one admission/custody return against durable lifecycle."""
with self._runtime_guard_lifecycle_lock:
with self._lock:
self._require_lifecycle_generation_locked(generation)
sink = self._quarantine_evidence_sink
sealed = self._runtime_guard_sealed
owner_token = self._runtime_guard_owner_token
sink_generation = self._runtime_guard_sink_generation
if not sealed or sink is None:
self._require_durable_evidence_ready()
with self._lock:
self._require_lifecycle_generation_locked(generation)
yield
with self._lock:
self._require_lifecycle_generation_locked(generation)
return
lease = getattr(sink, "runtime_guard_lifecycle_lease", None)
if (
not callable(lease)
or owner_token is None
or sink_generation is None
):
with self._lock:
self._mark_durable_evidence_terminal_locked(
"runtime_guard_sink_lease_unsupported"
)
raise OSProtectionError("runtime_guard_sink_lease_unsupported")
body_failed = False
try:
with lease(owner_token, sink_generation) as raw:
state = self._validated_runtime_guard_sink_seal(
raw,
owner_token_sha256=sha256_hex(
owner_token.encode("utf-8", errors="strict")
),
expected_generation=sink_generation,
)
with self._lock:
self._join_durable_sink_state(
{
"ledger_id": state["ledger_id"],
"ledger_instance_commitment": state[
"ledger_instance_commitment"
],
"entry_count": state["entry_count"],
"violation_count": state["violation_count"],
"persisted": state["violation_count"] > 0,
}
)
self._require_lifecycle_generation_locked(generation)
try:
yield
except BaseException:
body_failed = True
raise
with self._lock:
self._require_lifecycle_generation_locked(generation)
except BaseException as exc:
if body_failed:
raise
with self._lock:
failure_code = (
exc.code
if isinstance(exc, OSProtectionError)
else "runtime_guard_sink_lease_failed"
)
self._mark_durable_evidence_terminal_locked(
failure_code
)
if isinstance(exc, OSProtectionError):
raise
raise OSProtectionError("runtime_guard_sink_lease_failed") from exc
def durable_quarantine_evidence_preflight(self) -> dict[str, Any]:
"""Validate the pre-opened sink without exposing packet or key material."""
with self._runtime_guard_lifecycle_lock, self._lock:
sink = self._quarantine_evidence_sink
if sink is None:
result = {
"schema": OS_DURABLE_QUARANTINE_EVIDENCE_SCHEMA,
"configured": False,
"ready": False,
"reason_code": "durable_quarantine_evidence_not_configured",
"remaining_violation_capacity": 0,
"encrypted_hnc_packets_persisted": False,
"external_head_anchor_attested": False,
"magic_star_durable_custody_attested": False,
"production_ready": False,
}
assert_public_summary_safe(result)
return result
if self._durable_evidence_terminal:
result = {
"schema": OS_DURABLE_QUARANTINE_EVIDENCE_SCHEMA,
"configured": True,
"ready": False,
"reason_code": self._durable_evidence_failure_code
or "durable_quarantine_evidence_terminal",
"remaining_violation_capacity": 0,
"encrypted_hnc_packets_persisted": (
self._durable_evidence_packets_persisted
),
"external_head_anchor_attested": False,
"magic_star_durable_custody_attested": False,
"production_ready": False,
}
assert_public_summary_safe(result)
return result
try:
state = self._validated_durable_sink_state(sink.preflight())
self._join_durable_sink_state(state)
result = {
"schema": OS_DURABLE_QUARANTINE_EVIDENCE_SCHEMA,
"configured": True,
"ready": state["ready"],
"reason_code": state["reason_code"],
"remaining_violation_capacity": state["remaining"],
"encrypted_hnc_packets_persisted": state["persisted"],
"external_head_anchor_attested": state[
"external_head_anchor_attested"
],
"magic_star_durable_custody_attested": state[
"magic_star_durable_custody_attested"
],
"production_ready": False,
}
assert_public_summary_safe(result)
if state["ready"] is not True:
raise OSProtectionError("durable_quarantine_evidence_not_ready")
return result
except BaseException as exc:
failure_code = (
exc.code
if isinstance(exc, OSProtectionError)
else "durable_quarantine_evidence_preflight_failed"
)
self._mark_durable_evidence_terminal_locked(failure_code)
raise OSProtectionError(
"durable_quarantine_evidence_preflight_failed"
) from exc
def _validated_durable_sink_state(
self,
raw: Mapping[str, Any] | object,
) -> dict[str, Any]:
if not isinstance(raw, Mapping):
raise OSProtectionError("durable_quarantine_evidence_preflight_invalid")
ready = raw.get("ready")
remaining = raw.get("remaining_violation_capacity")
entry_count = raw.get("entry_count")
violation_count = raw.get("violation_count")
ledger_id = raw.get("ledger_id")
try:
ledger_instance_commitment = require_sha256(
raw.get("ledger_instance_commitment"),
field="durable_ledger_instance_commitment",
)
except (TypeError, ValueError) as exc:
raise OSProtectionError(
"durable_quarantine_evidence_preflight_invalid"
) from exc
persisted = raw.get("encrypted_hnc_packets_persisted")
if (
type(ready) is not bool
or type(remaining) is not int
or remaining < 0
or type(entry_count) is not int
or entry_count < 1
or type(violation_count) is not int
or violation_count < 0
or violation_count > entry_count
or not isinstance(ledger_id, str)
or not ledger_id
or type(persisted) is not bool
):
raise OSProtectionError("durable_quarantine_evidence_preflight_invalid")
reason_code = _bounded_text(
raw.get("reason_code"),
field_name="durable_quarantine_reason_code",
maximum_bytes=128,
)
actual_persistence = persisted and violation_count > 0
return {
"ledger_id": ledger_id,
"ledger_instance_commitment": ledger_instance_commitment,
"ready": ready,
"reason_code": reason_code,
"remaining": remaining,
"entry_count": entry_count,
"violation_count": violation_count,
"persisted": actual_persistence,
"external_head_anchor_attested": (
raw.get("external_head_anchor_attested") is True
),
"magic_star_durable_custody_attested": (
raw.get("magic_star_durable_custody_attested") is True
),
}
def _join_durable_sink_state(self, state: Mapping[str, Any]) -> None:
ledger_id = str(state["ledger_id"])
ledger_instance_commitment = str(state["ledger_instance_commitment"])
entry_count = int(state["entry_count"])
violation_count = int(state["violation_count"])
if self._durable_evidence_ledger_id is None:
self._durable_evidence_ledger_id = ledger_id
self._durable_evidence_ledger_instance_commitment = (
ledger_instance_commitment
)
self._durable_evidence_entry_count = entry_count
self._durable_evidence_violation_count = violation_count
elif (
ledger_id != self._durable_evidence_ledger_id
or ledger_instance_commitment
!= self._durable_evidence_ledger_instance_commitment
or entry_count != self._durable_evidence_entry_count
or violation_count != self._durable_evidence_violation_count
):
raise OSProtectionError("durable_quarantine_evidence_state_join_invalid")
if self._durable_evidence_packets_persisted and state["persisted"] is not True:
raise OSProtectionError("durable_quarantine_evidence_persistence_regressed")
self._durable_evidence_packets_persisted = (
self._durable_evidence_packets_persisted or state["persisted"] is True
)
def _require_durable_evidence_ready(self) -> None:
with self._lock:
configured = self._quarantine_evidence_sink is not None
if not configured:
return
preflight = self.durable_quarantine_evidence_preflight()
if preflight.get("ready") is not True:
raise OSProtectionError("durable_quarantine_evidence_terminal")
def _validated_runtime_guard_sink_seal(
self,
raw: Mapping[str, Any] | object,
*,
owner_token_sha256: str,
expected_generation: int | None,
) -> dict[str, Any]:
if not isinstance(raw, Mapping):
raise OSProtectionError("runtime_guard_sink_seal_invalid")
generation = raw.get("lifecycle_generation")
if (
raw.get("sealed") is not True
or raw.get("owner_token_sha256") != owner_token_sha256
or type(generation) is not int
or generation < 1
or (
expected_generation is not None
and generation != expected_generation
)
or raw.get("close_rejected_while_sealed") is not True
or raw.get("ready") is not True
or raw.get("production_ready") is not False
):
raise OSProtectionError("runtime_guard_sink_seal_invalid")
ledger_id = _bounded_text(
raw.get("ledger_id"),
field_name="runtime_guard_sink_ledger_id",
maximum_bytes=128,
)
try:
ledger_instance_commitment = require_sha256(
raw.get("ledger_instance_commitment"),
field="runtime_guard_sink_ledger_instance_commitment",
)
except (TypeError, ValueError) as exc:
raise OSProtectionError("runtime_guard_sink_seal_invalid") from exc
entry_count = raw.get("entry_count")
violation_count = raw.get("violation_count")
remaining = raw.get("remaining_violation_capacity")
if (
type(entry_count) is not int
or entry_count < 1
or type(violation_count) is not int
or violation_count < 0
or violation_count > entry_count
or type(remaining) is not int
or remaining < 0
):
raise OSProtectionError("runtime_guard_sink_seal_invalid")
return {
"ledger_id": ledger_id,
"ledger_instance_commitment": ledger_instance_commitment,
"generation": generation,
"entry_count": entry_count,
"violation_count": violation_count,
"remaining": remaining,
}
def seal_for_runtime_guard(self, owner_token: str) -> dict[str, Any]:
"""Irreversibly pin the configured durable sink before hook install."""
token = _bounded_text(
owner_token,
field_name="runtime_guard_owner_token",
maximum_bytes=128,
)
owner_sha256 = sha256_hex(token.encode("utf-8", errors="strict"))
with self._runtime_guard_lifecycle_lock:
with self._lock:
if self._durable_evidence_terminal:
raise OSProtectionError("durable_quarantine_evidence_terminal")
if self._runtime_guard_sealed:
if not secrets.compare_digest(
owner_sha256,
self._runtime_guard_owner_token_sha256 or "",
):
raise OSProtectionError("runtime_guard_owner_mismatch")
return self.validate_runtime_guard_seal(
token,
self._runtime_guard_lifecycle_generation,
)
sink = self._quarantine_evidence_sink
sink_generation: int
ledger_id: str | None = None
try:
if sink is None:
sink_generation = 1
else:
seal = getattr(sink, "seal_for_runtime_guard", None)
if not callable(seal):
raise OSProtectionError(
"runtime_guard_sink_seal_unsupported"
)
state = self._validated_runtime_guard_sink_seal(
seal(token),
owner_token_sha256=owner_sha256,
expected_generation=None,
)
sink_generation = int(state["generation"])
ledger_id = str(state["ledger_id"])
with self._lock:
self._join_durable_sink_state(
{
"ledger_id": ledger_id,
"ledger_instance_commitment": state[
"ledger_instance_commitment"
],
"entry_count": state["entry_count"],
"violation_count": state["violation_count"],
"persisted": state["violation_count"] > 0,
}
)
except BaseException as exc:
with self._lock:
failure_code = (
exc.code
if isinstance(exc, OSProtectionError)
else "runtime_guard_sink_seal_failed"
)
self._mark_durable_evidence_terminal_locked(failure_code)
raise OSProtectionError("runtime_guard_sink_seal_failed") from exc
with self._lock:
self._runtime_guard_sealed = True
self._runtime_guard_owner_token = token
self._runtime_guard_owner_token_sha256 = owner_sha256
self._runtime_guard_sink_generation = sink_generation
self._runtime_guard_lifecycle_generation += 1
result = {
"schema": OS_RUNTIME_GUARD_LIFECYCLE_SCHEMA,
"boundary_id": self._boundary_id,
"sealed": True,
"owner_token_sha256": owner_sha256,
"lifecycle_generation": (
self._runtime_guard_lifecycle_generation
),
"sink_lifecycle_generation": sink_generation,
"durable_sink_configured": sink is not None,
"durable_ledger_id": ledger_id,
"close_rejected_while_sealed": sink is not None,
"terminal": False,
"production_ready": False,
}
assert_public_summary_safe(result)
return result
def validate_runtime_guard_seal(
self,
owner_token: str,
lifecycle_generation: int,
) -> dict[str, Any]:
"""Revalidate the exact irreversible sink pin under the lifecycle lock."""
token = _bounded_text(
owner_token,
field_name="runtime_guard_owner_token",
maximum_bytes=128,
)
owner_sha256 = sha256_hex(token.encode("utf-8", errors="strict"))
if type(lifecycle_generation) is not int or lifecycle_generation < 1:
raise OSProtectionError("runtime_guard_lifecycle_generation_invalid")
with self._runtime_guard_lifecycle_lock:
with self._lock:
if (
not self._runtime_guard_sealed
or not secrets.compare_digest(
owner_sha256,
self._runtime_guard_owner_token_sha256 or "",
)
or lifecycle_generation
!= self._runtime_guard_lifecycle_generation
or self._durable_evidence_terminal
):
raise OSProtectionError("runtime_guard_lifecycle_invalid")
sink = self._quarantine_evidence_sink
sink_generation = self._runtime_guard_sink_generation
try:
if sink is not None:
validate = getattr(
sink,
"validate_runtime_guard_seal",
None,
)
if not callable(validate) or sink_generation is None:
raise OSProtectionError(
"runtime_guard_sink_seal_unsupported"
)
state = self._validated_runtime_guard_sink_seal(
validate(token, sink_generation),
owner_token_sha256=owner_sha256,
expected_generation=sink_generation,
)
with self._lock:
self._join_durable_sink_state(
{
"ledger_id": state["ledger_id"],
"ledger_instance_commitment": state[
"ledger_instance_commitment"
],
"entry_count": state["entry_count"],
"violation_count": state["violation_count"],
"persisted": state["violation_count"] > 0,
}
)
result = {
"schema": OS_RUNTIME_GUARD_LIFECYCLE_SCHEMA,
"boundary_id": self._boundary_id,
"sealed": True,
"owner_token_sha256": owner_sha256,
"lifecycle_generation": lifecycle_generation,
"sink_lifecycle_generation": sink_generation,
"durable_sink_configured": sink is not None,
"close_rejected_while_sealed": sink is not None,
"terminal": False,
"production_ready": False,
}
assert_public_summary_safe(result)
return result
except BaseException as exc:
with self._lock:
failure_code = (
exc.code
if isinstance(exc, OSProtectionError)
else "runtime_guard_sink_seal_validation_failed"
)
self._mark_durable_evidence_terminal_locked(failure_code)
raise OSProtectionError(
"runtime_guard_sink_seal_validation_failed"
) from exc
@contextmanager
def runtime_guard_lifecycle_lease(
self,
owner_token: str,
lifecycle_generation: int,
) -> Iterator[dict[str, Any]]:
"""Hold one non-mutating lifecycle decision stable; never append inside."""
with self._runtime_guard_lifecycle_lock:
before = self.validate_runtime_guard_seal(
owner_token,
lifecycle_generation,
)
with self._lock:
sink = self._quarantine_evidence_sink
sink_generation = self._runtime_guard_sink_generation
if sink is None:
yield before
self.validate_runtime_guard_seal(
owner_token,
lifecycle_generation,
)
return
lease = getattr(sink, "runtime_guard_lifecycle_lease", None)
if not callable(lease) or sink_generation is None:
with self._lock:
self._mark_durable_evidence_terminal_locked(
"runtime_guard_sink_lease_unsupported"
)
raise OSProtectionError("runtime_guard_sink_lease_unsupported")
body_failed = False
try:
with lease(owner_token, sink_generation) as raw:
self._validated_runtime_guard_sink_seal(
raw,
owner_token_sha256=sha256_hex(
owner_token.encode("utf-8", errors="strict")
),
expected_generation=sink_generation,
)
try:
yield before
except BaseException:
body_failed = True
raise
# The sink context performs its own post-body validation
# inside the still-open SQLite transaction. Re-entering
# its public validate method here would attempt a nested
# BEGIN IMMEDIATE on the same pre-opened connection.
with self._lock:
if (
not self._runtime_guard_sealed
or lifecycle_generation
!= self._runtime_guard_lifecycle_generation
or self._durable_evidence_terminal
):
raise OSProtectionError(
"runtime_guard_lifecycle_invalid"
)
except BaseException as exc:
if body_failed or isinstance(
exc,
(GeneratorExit, KeyboardInterrupt, SystemExit),
):
raise
# Sink/validation exceptions make the boundary terminal before
# propagating. Body exceptions above retain their own stable
# type and code.
with self._lock:
failure_code = (
exc.code
if isinstance(exc, OSProtectionError)
else "runtime_guard_sink_lease_failed"
)
self._mark_durable_evidence_terminal_locked(
failure_code
)
if isinstance(exc, OSProtectionError):
raise
raise OSProtectionError("runtime_guard_sink_lease_failed") from exc
def _persist_quarantine_evidence(
self,
*,
outcome: QuarantinedHNC,
evidence_packet: Mapping[str, Any],
) -> None:
binding = outcome.hnc_evidence_binding
if binding is None:
raise OSProtectionError("durable_quarantine_hnc_evidence_required")
metadata = {
"schema": OS_DURABLE_QUARANTINE_EVIDENCE_SCHEMA,
"intrusion_id": outcome.admission_id,
"content_sha256": outcome.content_sha256,
"source_id_sha256": sha256_hex(outcome.source_id.encode("utf-8")),
"ingress_kind_sha256": sha256_hex(outcome.ingress_kind.encode("utf-8")),
"denial_code_count": len(outcome.denial_codes),
"raw_arguments_retained": False,
"plaintext_retained": False,
"action_eligible": False,
"economic_eligible": False,
"production_ready": False,
}
try:
with self._lock:
sink = self._quarantine_evidence_sink
if sink is None:
return
if self._durable_evidence_terminal:
raise OSProtectionError("durable_quarantine_evidence_terminal")
before = self._validated_durable_sink_state(sink.preflight())
self._join_durable_sink_state(before)
if before["ready"] is not True:
raise OSProtectionError("durable_quarantine_evidence_not_ready")
expected_sequence = int(before["entry_count"]) + 1
expected_violation_count = int(before["violation_count"]) + 1
receipt = sink.append_violation(
intrusion_id=outcome.admission_id,
runtime_metadata=metadata,
quarantine_summary=outcome.public_summary(),
hnc_packet=evidence_packet,
)
if not isinstance(receipt, Mapping):
raise OSProtectionError(
"durable_quarantine_evidence_readback_invalid"
)
sequence = receipt.get("sequence")
terminal_after_append = receipt.get("terminal_after_append")
previous_entry_commitment = require_sha256(
receipt.get("previous_entry_commitment"),
field="durable_quarantine_previous_entry_commitment",
)
entry_commitment = require_sha256(
receipt.get("entry_commitment"),
field="durable_quarantine_entry_commitment",
)
if (
type(sequence) is not int
or sequence != expected_sequence
or type(terminal_after_append) is not bool
or receipt.get("ledger_id") != before["ledger_id"]
or receipt.get("ledger_instance_commitment")
!= before["ledger_instance_commitment"]
or receipt.get("intrusion_id") != outcome.admission_id
or receipt.get("quarantine_commitment")
!= outcome.quarantine_commitment
or receipt.get("quarantine_record_commitment")
!= outcome.quarantine_record.record_commitment
or receipt.get("hnc_packet_commitment")
!= binding.hnc_packet_commitment
or receipt.get("hnc_binding_commitment")
!= binding.binding_commitment
or receipt.get("durability_readback") is not True
or receipt.get("encrypted_hnc_packet_persisted") is not True
or (
self._durable_evidence_last_receipt_sequence is not None
and (
sequence
!= self._durable_evidence_last_receipt_sequence + 1
or previous_entry_commitment
!= self._durable_evidence_head_commitment
)
)
):
raise OSProtectionError(
"durable_quarantine_evidence_readback_invalid"
)
after = self._validated_durable_sink_state(sink.preflight())
expected_entry_count = expected_sequence + int(terminal_after_append)
if (
after["ledger_id"] != before["ledger_id"]
or after["ledger_instance_commitment"]
!= before["ledger_instance_commitment"]
or after["entry_count"] != expected_entry_count
or after["violation_count"] != expected_violation_count
or after["remaining"] != max(0, int(before["remaining"]) - 1)
or after["persisted"] is not True
or (terminal_after_append and after["ready"] is not False)
or (not terminal_after_append and after["ready"] is not True)
):
raise OSProtectionError(
"durable_quarantine_evidence_post_append_join_invalid"
)
self._durable_evidence_entry_count = expected_entry_count
self._durable_evidence_violation_count = expected_violation_count
self._durable_evidence_packets_persisted = True
self._durable_evidence_count += 1
self._durable_evidence_head_commitment = entry_commitment
self._durable_evidence_last_receipt_sequence = sequence
if terminal_after_append:
self._mark_durable_evidence_terminal_locked(
"runtime_intrusion_ledger_capacity_exhausted"
)
except BaseException as exc:
with self._lock:
failure_code = (
exc.code
if isinstance(exc, OSProtectionError)
else "durable_quarantine_evidence_append_failed"
)
self._mark_durable_evidence_terminal_locked(failure_code)
raise OSProtectionError("durable_quarantine_evidence_append_failed") from exc
def _recorded_at(self) -> tuple[datetime, str | None]:
try:
current = require_aware_datetime(self._trusted_now(), field="trusted_now")
if current.microsecond:
return current.replace(microsecond=0), "trusted_time_precision_invalid"
return current, None
except BaseException:
# Evidence still needs a bounded timestamp when the trusted clock is
# unavailable. This fallback never authorizes admission.
return _system_now(), "trusted_time_unavailable"
def _key_material(self) -> tuple[bytes | None, str | None]:
try:
supplied = self._master_key_provider()
if supplied is None:
return None, "master_key_unavailable"
return normalize_hnc_key_material(supplied), None
except BaseException:
return None, "master_key_invalid"
def key_preflight(self) -> dict[str, Any]:
"""Verify key availability without returning key material or granting admission.
This preflight is intentionally metadata-only. Callers that will process
sensitive plaintext use it to fail before model inference; admission still
performs its own independent key validation to avoid treating this receipt
as an authorization token.
"""
material, error = self._key_material()
ready = material is not None and error is None
if material is not None:
# Best-effort destruction of the temporary normalized copy. The key
# provider and Python runtime may retain other copies, so no stronger
# memory-erasure claim is made.
scratch = bytearray(material)
for index in range(len(scratch)):
scratch[index] = 0
del scratch
del material
return {
"schema": OS_KEY_PREFLIGHT_SCHEMA,
"boundary_id": self._boundary_id,
"ready": ready,
"reason_code": "ready" if ready else str(error or "master_key_unavailable"),
"key_material_returned": False,
"admission_authorized": False,
"action_eligible": False,
"economic_eligible": False,
"local_development_only": True,
"production_ready": False,
}
def admit_external(
self,
raw: bytes | bytearray | memoryview,
*,
source_id: str,
ingress_kind: str,
purpose: str,
operator_aad: Mapping[str, Any] | None = None,
content_validator: ContentValidator | None = None,
) -> AdmissionOutcome:
"""Admit only if its starting lifecycle generation remains current."""
lifecycle_generation = self._lifecycle_operation_generation()
return self._admit_external_under_lifecycle(
raw,
source_id=source_id,
ingress_kind=ingress_kind,
purpose=purpose,
operator_aad=operator_aad,
content_validator=content_validator,
lifecycle_generation=lifecycle_generation,
)
def _admit_external_under_lifecycle(
self,
raw: bytes | bytearray | memoryview,
*,
source_id: str,
ingress_kind: str,
purpose: str,
operator_aad: Mapping[str, Any] | None = None,
content_validator: ContentValidator | None = None,
lifecycle_generation: int,
) -> AdmissionOutcome:
"""Seal one bounded ingress or produce commitment-only quarantine.
The optional validator is a pure schema/content predicate. It receives
a read-only view and cannot authorize effects. False, an exception, or
a non-boolean result quarantines the material without exposing details.
"""
source = _bounded_text(
source_id,
field_name="source_id",
maximum_bytes=_MAX_SOURCE_ID_BYTES,
)
kind = _bounded_text(
ingress_kind,
field_name="ingress_kind",
maximum_bytes=_MAX_INGRESS_KIND_BYTES,
)
bounded_purpose = _bounded_text(
purpose,
field_name="purpose",
maximum_bytes=_MAX_PURPOSE_BYTES,
)
if operator_aad is not None and not isinstance(operator_aad, Mapping):
raise OSProtectionError("operator_aad_invalid")
if content_validator is not None and not callable(content_validator):
raise OSProtectionError("content_validator_invalid")
denial_codes: set[str] = set()
try:
caller_aad_snapshot = _snapshot_operator_aad(dict(operator_aad or {}))
caller_aad_bytes = canonical_json_bytes(caller_aad_snapshot)
if len(caller_aad_bytes) > MAX_OPERATOR_AAD_BYTES:
raise OSProtectionError("operator_aad_invalid")
decoded_caller_aad = decode_canonical_json(
caller_aad_bytes,
require_mapping=True,
max_bytes=MAX_OPERATOR_AAD_BYTES,
)
if not isinstance(decoded_caller_aad, dict): # pragma: no cover
raise OSProtectionError("operator_aad_invalid")
caller_aad = decoded_caller_aad
except BaseException:
caller_aad = {}
denial_codes.add("operator_aad_invalid")
payload: bytes | None = None
try:
view = memoryview(raw)
content_size = view.nbytes
if content_size <= self._max_ingress_bytes:
# Snapshot once so a caller-owned bytearray cannot change
# between commitment, validation, and encryption.
payload = view.tobytes()
content_sha256 = hashlib.sha256(payload).hexdigest()
else:
# Do not make a second, potentially huge copy merely to deny
# an already oversized ingress.
content_sha256 = hashlib.sha256(view).hexdigest()
except BaseException:
view = memoryview(b"")
content_size = 0
content_sha256 = domain_hash(
"aureon.plumber.invalid-ingress-type.v0",
{"type": type(raw).__name__},
)
denial_codes.add("ingress_bytes_invalid")
if content_size == 0:
denial_codes.add("ingress_empty")
if content_size > self._max_ingress_bytes:
denial_codes.add("ingress_too_large")
purpose_hash = _purpose_commitment(bounded_purpose)
ingress_aad: dict[str, Any] = {
"schema": OS_INGRESS_AAD_SCHEMA,
"boundary_id": self._boundary_id,
"source_id": source,
"ingress_kind": kind,
"content_sha256": content_sha256,
"content_size_bytes": content_size,
"purpose": bounded_purpose,
"purpose_commitment": purpose_hash,
"caller_aad": caller_aad,
"source_truth_established_by_local_wrapping": False,
}
with self._lock:
ledger_instance_commitment = (
self._durable_evidence_ledger_instance_commitment
)
durable_sink_configured = self._quarantine_evidence_sink is not None
if durable_sink_configured and ledger_instance_commitment is None:
raise OSProtectionError(
"durable_quarantine_ledger_instance_unavailable"
)
if ledger_instance_commitment is not None:
ingress_aad["ledger_instance_commitment"] = ledger_instance_commitment
try:
operator_aad_sha256 = sha256_hex(canonical_json_bytes(ingress_aad))
except BaseException:
operator_aad_sha256 = domain_hash(
"aureon.plumber.invalid-os-ingress-aad.v0",
{
"boundary_id": self._boundary_id,
"source_id": source,
"ingress_kind": kind,
"content_sha256": content_sha256,
"content_size_bytes": content_size,
"purpose_commitment": purpose_hash,
},
)
denial_codes.add("operator_aad_invalid")
replay_token = domain_hash(
"aureon.plumber.os-ingress-replay.v0",
{
"boundary_id": self._boundary_id,
"source_id": source,
"ingress_kind": kind,
"content_sha256": content_sha256,
"content_size_bytes": content_size,
"purpose_commitment": purpose_hash,
"operator_aad_sha256": operator_aad_sha256,
},
)
admission_id = f"os-ingress-{secrets.token_hex(16)}"
recorded_at, time_error = self._recorded_at()
if time_error is not None:
denial_codes.add(time_error)
with self._lock:
if replay_token in self._seen_replay_tokens:
denial_codes.add("ingress_replay_detected")
elif len(self._seen_replay_tokens) >= self._max_replay_tokens:
denial_codes.add("replay_ledger_capacity_exhausted")
else:
self._seen_replay_tokens.add(replay_token)
if not denial_codes and content_validator is not None:
try:
if payload is None: # pragma: no cover - guarded by denial codes
raise OSProtectionError("ingress_payload_snapshot_missing")
valid = content_validator(memoryview(payload).toreadonly())
except BaseException:
valid = False
if valid is not True:
denial_codes.add("ingress_content_invalid")
key_material, key_error = self._key_material()
if key_error is not None:
denial_codes.add(key_error)
if not denial_codes and key_material is not None:
try:
if payload is None: # pragma: no cover - guarded by denial codes
raise OSProtectionError("ingress_payload_snapshot_missing")
packet = build_hnc_quantum_packet(
payload,
key_material,
purpose=bounded_purpose,
operator_aad=ingress_aad,
hnc_context={
"os_protection_schema": OS_PROTECTION_SCHEMA,
"admission_id": admission_id,
"source_truth_established_by_local_wrapping": False,
},
)
validation = validate_hnc_packet_contract(packet)
if validation.get("valid") is not True:
raise OSProtectionError("hnc_packet_contract_invalid")
if packet.get("operator_aad") != ingress_aad:
raise OSProtectionError("hnc_operator_aad_join_mismatch")
binding = bind_hnc_packet(packet)
validate_magic_star_inner_carrier_capacity_v02(
packet_id=admission_id,
purpose=bounded_purpose,
legacy_carrier=packet,
legacy_master_key=key_material,
)
except StarCustodyError as exc:
denial_codes.add(
"magic_star_inner_capacity_exceeded"
if exc.code == "inner_carrier_too_large"
else "magic_star_inner_preflight_failed"
)
except BaseException:
denial_codes.add("hnc_packet_seal_failed")
else:
handle = OpaqueHNCHandle.issue(
boundary_id=self._boundary_id,
handle_id=admission_id,
)
recorded_at_text = format_timestamp(recorded_at)
values = _common_public_values(
disposition=IngressDisposition.ADMITTED_HNC,
boundary_id=self._boundary_id,
admission_id=admission_id,
source_id=source,
ingress_kind=kind,
content_sha256=content_sha256,
content_size_bytes=content_size,
purpose_commitment=purpose_hash,
operator_aad_sha256=operator_aad_sha256,
replay_token=replay_token,
recorded_at=recorded_at_text,
)
values.update(
{
"handle": handle.public_summary(),
"hnc_payload_binding": binding.public_summary(),
}
)
outcome = AdmittedHNC(
boundary_id=self._boundary_id,
admission_id=admission_id,
source_id=source,
ingress_kind=kind,
content_sha256=content_sha256,
content_size_bytes=content_size,
purpose_commitment=purpose_hash,
operator_aad_sha256=operator_aad_sha256,
replay_token=replay_token,
recorded_at=recorded_at_text,
handle=handle,
hnc_payload_binding=binding,
admission_commitment=domain_hash(
"aureon.plumber.os-admission.v0",
values,
),
)
# This is the admission linearization point. A terminal or
# seal transition completed while the caller validator/crypto
# work was in flight invalidates the result before custody is
# stored or an opaque handle can escape.
stored_record: _AdmissionRecord | None = None
try:
with self._lifecycle_commit_lease(
lifecycle_generation
), self._lock:
capacity_available = (
len(self._records) < self._max_active_handles
and self._active_ingress_bytes + content_size
<= self._max_active_ingress_bytes
)
if capacity_available:
stored_record = _AdmissionRecord(
packet=dict(packet),
master_key=bytearray(key_material),
purpose=bounded_purpose,
handle_commitment=handle.handle_commitment,
content_size_bytes=content_size,
)
self._records[admission_id] = stored_record
self._active_ingress_bytes += content_size
else:
denial_codes.add(
"active_admission_capacity_exhausted"
)
except BaseException:
if stored_record is not None:
with self._lock:
if self._records.get(admission_id) is stored_record:
self._records.pop(admission_id, None)
self._active_ingress_bytes = max(
0,
self._active_ingress_bytes - content_size,
)
stored_record.master_key[:] = bytes(
len(stored_record.master_key)
)
raise
if capacity_available:
return outcome
return self._quarantine(
admission_id=admission_id,
source_id=source,
ingress_kind=kind,
content_sha256=content_sha256,
content_size_bytes=content_size,
purpose_commitment=purpose_hash,
operator_aad_sha256=operator_aad_sha256,
replay_token=replay_token,
ingress_aad=ingress_aad,
denial_codes=denial_codes,
recorded_at=recorded_at,
key_material=key_material,
)
return self._quarantine(
admission_id=admission_id,
source_id=source,
ingress_kind=kind,
content_sha256=content_sha256,
content_size_bytes=content_size,
purpose_commitment=purpose_hash,
operator_aad_sha256=operator_aad_sha256,
replay_token=replay_token,
ingress_aad=ingress_aad,
denial_codes=denial_codes,
recorded_at=recorded_at,
key_material=key_material,
)
def _quarantine(
self,
*,
admission_id: str,
source_id: str,
ingress_kind: str,
content_sha256: str,
content_size_bytes: int,
purpose_commitment: str,
operator_aad_sha256: str,
replay_token: str,
ingress_aad: Mapping[str, Any],
denial_codes: set[str],
recorded_at: datetime,
key_material: bytes | None,
) -> QuarantinedHNC:
codes = set(denial_codes or {"ingress_denied"})
evidence_binding: HNCPayloadBindingV0 | None = None
evidence_packet: dict[str, Any] | None = None
if key_material is not None:
evidence_payload = {
"schema": OS_QUARANTINE_EVIDENCE_SCHEMA,
"admission_id": admission_id,
"boundary_id": self._boundary_id,
"source_id": source_id,
"ingress_kind": ingress_kind,
"content_sha256": content_sha256,
"content_size_bytes": content_size_bytes,
"purpose_commitment": purpose_commitment,
"operator_aad_sha256": operator_aad_sha256,
"replay_token": replay_token,
"denial_codes": sorted(codes),
"raw_material_retained": False,
"source_truth_established_by_local_wrapping": False,
}
quarantine_aad = {
**dict(ingress_aad),
"quarantine": True,
"quarantine_evidence_schema": OS_QUARANTINE_EVIDENCE_SCHEMA,
"denial_codes": sorted(codes),
}
with self._lock:
if len(self._quarantine_packets) >= self._max_quarantine_evidence:
codes.add("quarantine_evidence_capacity_exhausted")
else:
try:
evidence_packet = build_hnc_quantum_packet(
canonical_json_bytes(evidence_payload),
key_material,
purpose=OS_QUARANTINE_EVIDENCE_PURPOSE,
operator_aad=quarantine_aad,
hnc_context={
"original_purpose_commitment": purpose_commitment,
"metadata_only_quarantine": True,
},
)
validation = validate_hnc_packet_contract(evidence_packet)
if validation.get("valid") is not True:
raise OSProtectionError("quarantine_hnc_contract_invalid")
evidence_binding = bind_hnc_packet(evidence_packet)
except BaseException:
codes.add("quarantine_hnc_evidence_unavailable")
evidence_binding = None
evidence_packet = None
else:
self._quarantine_packets[admission_id] = dict(evidence_packet)
normalized_codes = tuple(sorted(codes))
evidence_commitments = {
"operator_aad_sha256": operator_aad_sha256,
"purpose_commitment": purpose_commitment,
"replay_token": replay_token,
}
if evidence_binding is not None:
evidence_commitments.update(
{
"hnc_quarantine_packet_commitment": evidence_binding.hnc_packet_commitment,
"hnc_quarantine_binding_commitment": evidence_binding.binding_commitment,
}
)
record = QuarantineRecord.build(
quarantine_id=admission_id,
packet_identity=admission_id,
session_identity=self._boundary_id,
packet_commitment=content_sha256,
denial_codes=normalized_codes,
evidence_commitments=evidence_commitments,
quarantined_at=recorded_at,
)
recorded_at_text = format_timestamp(recorded_at)
values = {
**_common_public_values(
disposition=IngressDisposition.QUARANTINED_HNC,
boundary_id=self._boundary_id,
admission_id=admission_id,
source_id=source_id,
ingress_kind=ingress_kind,
content_sha256=content_sha256,
content_size_bytes=content_size_bytes,
purpose_commitment=purpose_commitment,
operator_aad_sha256=operator_aad_sha256,
replay_token=replay_token,
recorded_at=recorded_at_text,
),
"denial_codes": list(normalized_codes),
"quarantine_record": record.public_summary(),
"hnc_evidence_binding": (
None if evidence_binding is None else evidence_binding.public_summary()
),
"raw_material_retained": False,
}
outcome = QuarantinedHNC(
boundary_id=self._boundary_id,
admission_id=admission_id,
source_id=source_id,
ingress_kind=ingress_kind,
content_sha256=content_sha256,
content_size_bytes=content_size_bytes,
purpose_commitment=purpose_commitment,
operator_aad_sha256=operator_aad_sha256,
replay_token=replay_token,
recorded_at=recorded_at_text,
denial_codes=normalized_codes,
quarantine_record=record,
hnc_evidence_binding=evidence_binding,
quarantine_commitment=domain_hash(
"aureon.plumber.os-quarantine.v0",
values,
),
)
if evidence_packet is not None:
self._persist_quarantine_evidence(
outcome=outcome,
evidence_packet=evidence_packet,
)
return outcome
def protect_for_magic_star(
self,
handle: OpaqueHNCHandle,
*,
custody: LocalDevelopmentStarCustodyV02,
release_context_sha256: str,
) -> ProtectedMagicStarPacketV02:
"""Reject custody results invalidated by a terminal transition."""
lifecycle_generation = self._lifecycle_operation_generation()
return self._protect_for_magic_star_under_lifecycle(
handle,
custody=custody,
release_context_sha256=release_context_sha256,
lifecycle_generation=lifecycle_generation,
)
def _protect_for_magic_star_under_lifecycle(
self,
handle: OpaqueHNCHandle,
*,
custody: LocalDevelopmentStarCustodyV02,
release_context_sha256: str,
lifecycle_generation: int,
) -> ProtectedMagicStarPacketV02:
"""Consume one opaque admission and hand its carrier directly to custody."""
if not isinstance(custody, LocalDevelopmentStarCustodyV02):
raise OSProtectionError("local_magic_star_custody_required")
require_sha256(release_context_sha256, field="release_context_sha256")
record = self._consume_admitted_record(handle)
key = bytes(record.master_key)
try:
protected = custody.protect_carrier(
packet_id=handle.handle_id,
purpose=record.purpose,
release_context_sha256=release_context_sha256,
legacy_carrier=record.packet,
legacy_master_key=key,
)
except BaseException:
raise OSProtectionError("magic_star_protection_failed") from None
finally:
record.master_key[:] = bytes(len(record.master_key))
if not isinstance(protected, ProtectedMagicStarPacketV02):
raise OSProtectionError("magic_star_protected_packet_invalid")
with self._lifecycle_commit_lease(lifecycle_generation):
pass
return protected
def _consume_admitted_record(self, handle: OpaqueHNCHandle) -> _AdmissionRecord:
"""Atomically burn one valid handle before any caller-controlled work."""
if not isinstance(handle, OpaqueHNCHandle):
raise OSProtectionError("opaque_hnc_handle_required")
if handle.boundary_id != self._boundary_id:
raise OSProtectionError("opaque_hnc_handle_boundary_mismatch")
with self._lock:
record = self._records.get(handle.handle_id)
if (
record is None
or record.handle_commitment != handle.handle_commitment
or handle.handle_commitment in self._consumed_handle_commitments
or not secrets.compare_digest(
handle.handle_commitment,
_handle_commitment(
boundary_id=handle.boundary_id,
handle_id=handle.handle_id,
token=handle.token,
),
)
):
raise OSProtectionError("opaque_hnc_handle_unavailable_or_replayed")
# Burn before the downstream call. Any failure is fail-closed and
# cannot expose a retry path for the same admitted carrier.
self._records.pop(handle.handle_id, None)
self._active_ingress_bytes = max(
0,
self._active_ingress_bytes - record.content_size_bytes,
)
self._consumed_handle_commitments.add(handle.handle_commitment)
return record
def discard_admitted(
self,
handle: OpaqueHNCHandle,
*,
reason_code: str,
) -> dict[str, Any]:
"""Linearly order destruction of a held admission with lifecycle state."""
with self._runtime_guard_lifecycle_lock:
return self._discard_admitted_under_lifecycle(
handle,
reason_code=reason_code,
)
def _discard_admitted_under_lifecycle(
self,
handle: OpaqueHNCHandle,
*,
reason_code: str,
) -> dict[str, Any]:
"""Burn a held admission without decoding or handing off its carrier."""
reason = _bounded_text(
reason_code,
field_name="discard_reason_code",
maximum_bytes=128,
)
record = self._consume_admitted_record(handle)
try:
summary = {
"schema": OS_PROTECTION_SCHEMA,
"disposition": "DISCARDED_HNC",
"boundary_id": self._boundary_id,
"admission_id": handle.handle_id,
"handle_commitment": handle.handle_commitment,
"reason_code": reason,
"carrier_released": False,
"plaintext_decoded": False,
"local_development_only": True,
"production_ready": False,
}
assert_public_summary_safe(summary)
return summary
finally:
record.master_key[:] = bytes(len(record.master_key))
def public_summary(self) -> dict[str, Any]:
with self._runtime_guard_lifecycle_lock, self._lock:
summary = {
"schema": OS_PROTECTION_SCHEMA,
"boundary_id": self._boundary_id,
"scope": "in_memory_local_development_only",
"max_ingress_bytes": self._max_ingress_bytes,
"max_active_handles": self._max_active_handles,
"max_active_ingress_bytes": self._max_active_ingress_bytes,
"max_replay_tokens": self._max_replay_tokens,
"max_quarantine_evidence": self._max_quarantine_evidence,
"seen_replay_count": len(self._seen_replay_tokens),
"active_opaque_handle_count": len(self._records),
"active_ingress_bytes": self._active_ingress_bytes,
"consumed_opaque_handle_count": len(self._consumed_handle_commitments),
"quarantine_evidence_count": len(self._quarantine_packets),
"durable_quarantine_evidence_configured": (
self._quarantine_evidence_sink is not None
),
"durable_quarantine_evidence_count": self._durable_evidence_count,
"durable_quarantine_evidence_head_commitment": (
self._durable_evidence_head_commitment
),
"durable_quarantine_evidence_last_receipt_sequence": (
self._durable_evidence_last_receipt_sequence
),
"durable_quarantine_evidence_ledger_entry_count": (
self._durable_evidence_entry_count
),
"durable_quarantine_evidence_ledger_violation_count": (
self._durable_evidence_violation_count
),
"durable_quarantine_evidence_packets_persisted": (
self._durable_evidence_packets_persisted
),
"durable_quarantine_evidence_terminal": (
self._durable_evidence_terminal
),
"durable_quarantine_evidence_failure_code": (
self._durable_evidence_failure_code
),
"runtime_guard_lifecycle_sealed": self._runtime_guard_sealed,
"runtime_guard_lifecycle_generation": (
self._runtime_guard_lifecycle_generation
),
"runtime_guard_sink_generation": (
self._runtime_guard_sink_generation
),
"external_head_anchor_attested": False,
"magic_star_durable_custody_attested": False,
"raw_material_returned": False,
"persistent": False,
"local_development_only": True,
"production_ready": False,
}
assert_public_summary_safe(summary)
return summary
__all__ = [
"DEFAULT_MAX_INGRESS_BYTES",
"MAX_OPERATOR_AAD_BYTES",
"OS_INGRESS_AAD_SCHEMA",
"OS_KEY_PREFLIGHT_SCHEMA",
"OS_DURABLE_QUARANTINE_EVIDENCE_SCHEMA",
"OS_PROTECTION_SCHEMA",
"OS_QUARANTINE_EVIDENCE_PURPOSE",
"OS_QUARANTINE_EVIDENCE_SCHEMA",
"OS_RUNTIME_GUARD_LIFECYCLE_SCHEMA",
"AdmissionOutcome",
"AdmittedHNC",
"ContentValidator",
"IngressDisposition",
"LocalOSProtectionBoundary",
"MasterKeyProvider",
"OSProtectionError",
"OpaqueHNCHandle",
"QuarantinedHNC",
"QuarantineEvidenceSink",
]12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184"""Pinned-trust semantic validation for Aureon Plumber v0 packets.
The established HNC validator remains authoritative for its encrypted carrier.
Without an explicit :class:`PacketTrustPolicy`, quorum policy pin, observer
transcript, and replay guard, inspection is structural-only and returns HOLD.
Embedded self-signatures never establish trust.
"""
from __future__ import annotations
import threading
from collections.abc import Mapping, Sequence
from dataclasses import dataclass
from datetime import datetime
from enum import StrEnum
from typing import Any, Self, cast
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
from .crypto import (
b64url_decode,
canonical_json_bytes,
decode_canonical_json,
domain_hash,
ed25519_public_key_hex,
load_ed25519_private_key,
load_ed25519_public_key,
sha256_hex,
sign_ed25519,
verify_ed25519,
)
from .immune_gate import GateClass
from .observer_transcript import ObserverTranscriptV0
from .quorum import AuthorityPermit, QuorumPolicyV0, evaluate_quorum
from .receipts import ReceiptKind, SignedReceipt
from .schema import (
DenialCode,
PlumberPacketV0,
SchemaError,
format_timestamp,
freeze_mapping,
parse_timestamp,
require_aware_datetime,
require_exact_keys,
require_int,
require_nonblank,
require_sha256,
)
from .source_identity import SourceIdentityV0
from .spore_transport import SporeManifest
from .sympathetic_identity import SympatheticIdentityV0
from .temporal_identity import TemporalIdentityV0
from .twin_rune_seal import TwinRuneSealV0
HNC_PAYLOAD_BINDING_SCHEMA = "aureon.plumber.hnc-payload-binding.v0"
_PACKET_SIGNATURE_DOMAIN = "aureon.plumber.packet-signature.v0"
_REQUIRED_RECEIPT_KINDS = (
str(ReceiptKind.FIELD),
str(ReceiptKind.HEART),
str(ReceiptKind.CONSCIENCE),
str(ReceiptKind.GOVERNANCE),
)
_REFRESHABLE_CODES = {
str(DenialCode.FUTURE_STATE),
str(DenialCode.QUORUM_INCOMPLETE),
str(DenialCode.STALE_STATE),
}
def _plain_mapping(value: Mapping[str, Any]) -> dict[str, Any]:
"""Thaw schema-frozen tuples/mappings through strict canonical JSON."""
parsed = decode_canonical_json(canonical_json_bytes(value), require_mapping=True)
if not isinstance(parsed, dict): # pragma: no cover - guaranteed by the decoder
raise SchemaError(DenialCode.INVALID_TYPE, field="mapping")
return parsed
class PacketContractError(ValueError):
def __init__(self, code: str) -> None:
self.code = code
super().__init__(code)
class PacketDisposition(StrEnum):
VALID = "valid"
HOLD = "hold"
DENY = "deny"
class PacketCode(StrEnum):
HNC_CONTRACT_INVALID = "hnc_contract_invalid"
HNC_BINDING_MISMATCH = "hnc_binding_mismatch"
SOURCE_BINDING_INVALID = "source_binding_invalid"
TEMPORAL_BINDING_INVALID = "temporal_binding_invalid"
TEMPORAL_ANCHOR_REQUIRED = "temporal_anchor_required"
OBSERVER_TRANSCRIPT_INVALID = "observer_transcript_invalid"
SYMPATHETIC_IDENTITY_INVALID = "sympathetic_identity_invalid"
TWIN_RUNE_INVALID = "twin_rune_invalid"
SPORE_BINDING_INVALID = "spore_binding_invalid"
RECEIPT_INVALID = "receipt_invalid"
RECEIPT_STALE = "receipt_stale"
QUORUM_POLICY_INVALID = "quorum_policy_invalid"
QUORUM_POLICY_PIN_REQUIRED = "quorum_policy_pin_required"
QUORUM_INVALID = "quorum_invalid"
QUORUM_AUTHORITY_UNTRUSTED = "quorum_authority_untrusted"
TRUST_POLICY_REQUIRED = "trust_policy_required"
REPLAY_GUARD_REQUIRED = "replay_guard_required"
REPLAY_DETECTED = "replay_detected"
PACKET_SIGNATURE_MISSING = "packet_signature_missing"
PACKET_SIGNATURE_INVALID = "packet_signature_invalid"
PACKET_SIGNER_UNTRUSTED = "packet_signer_untrusted"
RECEIPT_SIGNER_UNTRUSTED = "receipt_signer_untrusted"
_BINDING_FIELDS = (
"schema",
"hnc_magic",
"hnc_schema_version",
"hnc_packet_commitment",
"hnc_alignment_commitment",
"ciphertext_commitment",
"purpose_commitment",
"binding_commitment",
)
@dataclass(frozen=True, slots=True)
class HNCPayloadBindingV0:
schema: str
hnc_magic: str
hnc_schema_version: int
hnc_packet_commitment: str
hnc_alignment_commitment: str
ciphertext_commitment: str
purpose_commitment: str
binding_commitment: str
def __post_init__(self) -> None:
if self.schema != HNC_PAYLOAD_BINDING_SCHEMA:
raise SchemaError(DenialCode.INVALID_SCHEMA, field="schema")
require_nonblank(self.hnc_magic, field="hnc_magic")
require_int(self.hnc_schema_version, field="hnc_schema_version", minimum=0)
for field in _BINDING_FIELDS[3:]:
require_sha256(getattr(self, field), field=field)
if domain_hash("aureon.plumber.hnc-payload-binding.v0", self.commitment_payload()) != self.binding_commitment:
raise SchemaError(DenialCode.PACKET_COMMITMENT_MISMATCH, field="binding_commitment")
@classmethod
def build(
cls,
*,
hnc_magic: str,
hnc_schema_version: int,
hnc_packet_commitment: str,
hnc_alignment_commitment: str,
ciphertext_commitment: str,
purpose_commitment: str,
) -> Self:
values: dict[str, Any] = {
"schema": HNC_PAYLOAD_BINDING_SCHEMA,
"hnc_magic": hnc_magic,
"hnc_schema_version": hnc_schema_version,
"hnc_packet_commitment": hnc_packet_commitment,
"hnc_alignment_commitment": hnc_alignment_commitment,
"ciphertext_commitment": ciphertext_commitment,
"purpose_commitment": purpose_commitment,
}
return cls(
**values,
binding_commitment=domain_hash("aureon.plumber.hnc-payload-binding.v0", values),
)
@classmethod
def from_dict(cls, value: Mapping[str, Any]) -> Self:
return cls(**require_exact_keys(value, _BINDING_FIELDS, field="hnc_payload_binding"))
def commitment_payload(self) -> dict[str, Any]:
return {field: getattr(self, field) for field in _BINDING_FIELDS if field != "binding_commitment"}
def to_dict(self) -> dict[str, Any]:
return {**self.commitment_payload(), "binding_commitment": self.binding_commitment}
def public_summary(self) -> dict[str, Any]:
return self.to_dict()
def bind_hnc_packet(hnc_packet: Mapping[str, Any]) -> HNCPayloadBindingV0:
"""Validate and bind one existing HNC packet without decoding it."""
if not isinstance(hnc_packet, Mapping):
raise PacketContractError(str(PacketCode.HNC_CONTRACT_INVALID))
try:
from aureon.harmonic.hnc_quantum_packet_crypto import validate_hnc_packet_contract
validation = validate_hnc_packet_contract(hnc_packet)
if not validation.get("valid"):
raise PacketContractError(str(PacketCode.HNC_CONTRACT_INVALID))
purpose = require_nonblank(validation.get("purpose"), field="hnc_packet.purpose", max_length=1024)
b64url_decode(
require_nonblank(
hnc_packet.get("nonce_b64"),
field="hnc_packet.nonce_b64",
max_length=64,
),
expected_bytes=12,
)
ciphertext = b64url_decode(
require_nonblank(
hnc_packet.get("ciphertext_b64"),
field="hnc_packet.ciphertext_b64",
max_length=32 * 1024 * 1024,
)
)
return HNCPayloadBindingV0.build(
hnc_magic=require_nonblank(hnc_packet.get("magic"), field="hnc_packet.magic"),
hnc_schema_version=require_int(
hnc_packet.get("schema_version"),
field="hnc_packet.schema_version",
minimum=0,
),
hnc_packet_commitment=require_sha256(
validation.get("packet_sha256"),
field="hnc_packet.packet_sha256",
),
hnc_alignment_commitment=require_sha256(
validation.get("hnc_alignment_sha256"),
field="hnc_packet.hnc_alignment_sha256",
),
ciphertext_commitment=sha256_hex(ciphertext),
purpose_commitment=domain_hash("aureon.plumber.purpose.v0", purpose),
)
except PacketContractError:
raise
except (KeyError, TypeError, ValueError) as exc:
raise PacketContractError(str(PacketCode.HNC_CONTRACT_INVALID)) from exc
def _validate_authority_map(
value: Mapping[str, Any],
*,
field: str,
required_keys: set[str] | None = None,
require_distinct: bool = False,
) -> Mapping[str, Any]:
frozen = freeze_mapping(value, field=field)
if required_keys is not None and set(frozen) != required_keys:
raise SchemaError(DenialCode.INVALID_VALUE, field=field)
authority_ids: set[str] = set()
public_keys: set[str] = set()
for role, authority in frozen.items():
require_nonblank(role, field=f"{field}.role")
parsed = require_exact_keys(authority, {"authority_id", "public_key"}, field=f"{field}.{role}")
authority_id = require_nonblank(parsed["authority_id"], field=f"{field}.{role}.authority_id")
public_key = ed25519_public_key_hex(load_ed25519_public_key(parsed["public_key"]))
if require_distinct and (authority_id in authority_ids or public_key in public_keys):
raise SchemaError(DenialCode.INVALID_VALUE, field=field)
authority_ids.add(authority_id)
public_keys.add(public_key)
return frozen
@dataclass(frozen=True, slots=True)
class PacketTrustPolicy:
"""Pinned authorities; packet-embedded keys are never trust anchors."""
packet_signer_public_keys: tuple[str, ...]
receipt_authorities: Mapping[str, Mapping[str, str]]
quorum_authorities: Mapping[str, Mapping[str, str]]
expected_hardware_identity_commitment: str
expected_operator_identity_commitment: str
trust_policy_commitment: str
def __post_init__(self) -> None:
if not self.packet_signer_public_keys or tuple(sorted(set(self.packet_signer_public_keys))) != (
self.packet_signer_public_keys
):
raise SchemaError(DenialCode.INVALID_VALUE, field="packet_signer_public_keys")
for key in self.packet_signer_public_keys:
load_ed25519_public_key(key)
object.__setattr__(
self,
"receipt_authorities",
_validate_authority_map(
self.receipt_authorities,
field="receipt_authorities",
required_keys=set(_REQUIRED_RECEIPT_KINDS),
require_distinct=True,
),
)
object.__setattr__(
self,
"quorum_authorities",
_validate_authority_map(self.quorum_authorities, field="quorum_authorities"),
)
require_sha256(
self.expected_hardware_identity_commitment,
field="expected_hardware_identity_commitment",
)
require_sha256(
self.expected_operator_identity_commitment,
field="expected_operator_identity_commitment",
)
require_sha256(self.trust_policy_commitment, field="trust_policy_commitment")
if domain_hash("aureon.plumber.packet-trust-policy.v0", self.commitment_payload()) != (
self.trust_policy_commitment
):
raise SchemaError(DenialCode.INVALID_VALUE, field="trust_policy_commitment")
@classmethod
def build(
cls,
*,
packet_signer_public_keys: Sequence[str],
receipt_authorities: Mapping[str, Mapping[str, str]],
quorum_authorities: Mapping[str, Mapping[str, str]],
expected_hardware_identity_commitment: str,
expected_operator_identity_commitment: str,
) -> PacketTrustPolicy:
keys = tuple(sorted(set(packet_signer_public_keys)))
values = {
"packet_signer_public_keys": list(keys),
"receipt_authorities": dict(receipt_authorities),
"quorum_authorities": dict(quorum_authorities),
"expected_hardware_identity_commitment": expected_hardware_identity_commitment,
"expected_operator_identity_commitment": expected_operator_identity_commitment,
}
return cls(
packet_signer_public_keys=keys,
receipt_authorities=receipt_authorities,
quorum_authorities=quorum_authorities,
expected_hardware_identity_commitment=expected_hardware_identity_commitment,
expected_operator_identity_commitment=expected_operator_identity_commitment,
trust_policy_commitment=domain_hash("aureon.plumber.packet-trust-policy.v0", values),
)
def commitment_payload(self) -> dict[str, Any]:
return {
"packet_signer_public_keys": list(self.packet_signer_public_keys),
"receipt_authorities": {
role: dict(authority) for role, authority in self.receipt_authorities.items()
},
"quorum_authorities": {
role: dict(authority) for role, authority in self.quorum_authorities.items()
},
"expected_hardware_identity_commitment": self.expected_hardware_identity_commitment,
"expected_operator_identity_commitment": self.expected_operator_identity_commitment,
}
def public_summary(self) -> dict[str, Any]:
return {
"packet_signer_count": len(self.packet_signer_public_keys),
"receipt_authority_count": len(self.receipt_authorities),
"quorum_authority_count": len(self.quorum_authorities),
"trust_policy_commitment": self.trust_policy_commitment,
}
@dataclass(slots=True)
class _TemporalAnchor:
expected_previous_state_commitment: str
minimum_counter: int
expected_field_receipt_commitment: str
expected_runtime_measurement_commitment: str
@dataclass(frozen=True, slots=True)
class _TemporalReservation:
session_identity: str
temporal_commitment: str
nonce_commitment: str
counter: int
class PacketReplayGuard:
"""Atomic, anchored in-memory replay guard for local-development execution."""
def __init__(self) -> None:
self._lock = threading.Lock()
self._consumed: set[str] = set()
self._anchors: dict[str, _TemporalAnchor] = {}
self._reservations: dict[str, _TemporalReservation] = {}
self._execution_claims: dict[str, _TemporalReservation] = {}
self._reserved_sessions: set[str] = set()
self._seen_temporal_commitments: set[str] = set()
self._seen_nonce_commitments: set[str] = set()
def register_temporal_anchor(
self,
session_identity: str,
*,
expected_previous_state_commitment: str,
minimum_counter: int,
expected_field_receipt_commitment: str,
expected_runtime_measurement_commitment: str,
) -> bool:
"""Register one immutable external anchor for a session."""
session = require_nonblank(session_identity, field="session_identity")
require_sha256(
expected_previous_state_commitment,
field="expected_previous_state_commitment",
)
require_int(minimum_counter, field="minimum_counter", minimum=0)
require_sha256(
expected_field_receipt_commitment,
field="expected_field_receipt_commitment",
)
require_sha256(
expected_runtime_measurement_commitment,
field="expected_runtime_measurement_commitment",
)
anchor = _TemporalAnchor(
expected_previous_state_commitment=expected_previous_state_commitment,
minimum_counter=minimum_counter,
expected_field_receipt_commitment=expected_field_receipt_commitment,
expected_runtime_measurement_commitment=expected_runtime_measurement_commitment,
)
with self._lock:
if session in self._anchors:
return False
self._anchors[session] = anchor
return True
def has_temporal_anchor(self, session_identity: str) -> bool:
session = require_nonblank(session_identity, field="session_identity")
with self._lock:
return session in self._anchors
def has_seen(self, replay_token: str) -> bool:
require_sha256(replay_token, field="replay_token")
with self._lock:
return (
replay_token in self._consumed
or replay_token in self._reservations
or replay_token in self._execution_claims
)
def reserve_temporal(
self,
temporal: TemporalIdentityV0,
replay_token: str,
*,
now: datetime,
) -> bool:
"""Atomically validate external continuity and reserve one temporal identity."""
if not isinstance(temporal, TemporalIdentityV0):
raise SchemaError(DenialCode.INVALID_TYPE, field="temporal_identity")
require_sha256(replay_token, field="replay_token")
current = require_aware_datetime(now, field="now")
with self._lock:
anchor = self._anchors.get(temporal.session_identity)
if (
anchor is None
or replay_token in self._consumed
or replay_token in self._reservations
or replay_token in self._execution_claims
or temporal.session_identity in self._reserved_sessions
):
return False
reserved_temporal = {
reservation.temporal_commitment
for reservation in (
*self._reservations.values(),
*self._execution_claims.values(),
)
}
reserved_nonces = {
reservation.nonce_commitment
for reservation in (
*self._reservations.values(),
*self._execution_claims.values(),
)
}
validation = temporal.validate(
now=current,
expected_previous_state_commitment=anchor.expected_previous_state_commitment,
minimum_counter=anchor.minimum_counter,
seen_temporal_commitments=self._seen_temporal_commitments | reserved_temporal,
seen_nonce_commitments=self._seen_nonce_commitments | reserved_nonces,
)
external_anchors_match = (
temporal.field_receipt_commitment
== anchor.expected_field_receipt_commitment
and temporal.runtime_measurement_commitment
== anchor.expected_runtime_measurement_commitment
)
if not validation.valid or not external_anchors_match:
return False
self._reservations[replay_token] = _TemporalReservation(
session_identity=temporal.session_identity,
temporal_commitment=temporal.temporal_commitment,
nonce_commitment=temporal.nonce_commitment,
counter=temporal.counter,
)
self._reserved_sessions.add(temporal.session_identity)
return True
def claim_for_execution(self, replay_token: str) -> bool:
"""Atomically claim a reservation while pre-capability work runs."""
require_sha256(replay_token, field="replay_token")
with self._lock:
if replay_token in self._consumed or replay_token in self._execution_claims:
return False
reservation = self._reservations.pop(replay_token, None)
if reservation is None:
return False
self._execution_claims[replay_token] = reservation
return True
def rollback_execution_claim(self, replay_token: str) -> bool:
"""Return an uncommitted claim to its original reservation."""
require_sha256(replay_token, field="replay_token")
with self._lock:
if replay_token in self._consumed or replay_token in self._reservations:
return False
reservation = self._execution_claims.pop(replay_token, None)
if reservation is None:
return False
self._reservations[replay_token] = reservation
return True
def commit_execution_claim(self, replay_token: str) -> bool:
"""Irreversibly consume a claim immediately before capability dispatch."""
require_sha256(replay_token, field="replay_token")
with self._lock:
reservation = self._execution_claims.pop(replay_token, None)
if reservation is None:
return False
return self._commit_reservation(replay_token, reservation)
def consume(self, replay_token: str) -> bool:
require_sha256(replay_token, field="replay_token")
with self._lock:
reservation = self._reservations.pop(replay_token, None)
if reservation is None:
return False
return self._commit_reservation(replay_token, reservation)
def _commit_reservation(
self,
replay_token: str,
reservation: _TemporalReservation,
) -> bool:
"""Commit one reservation while ``self._lock`` is held."""
anchor = self._anchors.get(reservation.session_identity)
if anchor is None: # pragma: no cover - anchors are never removed
return False
self._reserved_sessions.remove(reservation.session_identity)
self._consumed.add(replay_token)
self._seen_temporal_commitments.add(reservation.temporal_commitment)
self._seen_nonce_commitments.add(reservation.nonce_commitment)
anchor.expected_previous_state_commitment = reservation.temporal_commitment
anchor.minimum_counter = reservation.counter
return True
def public_summary(self) -> dict[str, Any]:
with self._lock:
summary = {
"anchor_count": len(self._anchors),
"reservation_count": len(self._reservations),
"execution_claim_count": len(self._execution_claims),
"consumed_count": len(self._consumed),
"seen_temporal_count": len(self._seen_temporal_commitments),
"seen_nonce_count": len(self._seen_nonce_commitments),
}
return {
"scope": "in_memory_local_development_only",
**summary,
"persistent": False,
}
def add_packet_signature(
packet: PlumberPacketV0,
private_key: Ed25519PrivateKey | bytes | str,
) -> PlumberPacketV0:
if not isinstance(packet, PlumberPacketV0):
raise SchemaError(DenialCode.INVALID_TYPE, field="packet")
key = load_ed25519_private_key(private_key)
signer = ed25519_public_key_hex(key)
signature = sign_ed25519(
key,
{"packet_commitment": packet.packet_commitment},
domain=_PACKET_SIGNATURE_DOMAIN,
)
values = packet.to_dict()
values["signatures"] = {**values["signatures"], signer: signature}
return PlumberPacketV0.from_dict(values)
@dataclass(frozen=True, slots=True)
class PacketInspection:
disposition: PacketDisposition
trusted: bool
packet_identity: str
session_identity: str
temporal_counter: int
inspected_at: str
evidence_not_before: str
evidence_expires_at: str
gate_evidence_commitments: Mapping[str, str]
packet_commitment: str
purpose_commitment: str
hnc_packet_commitment: str
trust_policy_commitment: str
quorum_policy_commitment: str
quorum_commitment: str
quorum_validated: bool
replay_token: str
denial_codes: tuple[str, ...]
evidence_commitment: str
inspection_commitment: str
def __post_init__(self) -> None:
try:
disposition = PacketDisposition(self.disposition)
except ValueError as exc:
raise SchemaError(DenialCode.INVALID_VALUE, field="disposition") from exc
object.__setattr__(self, "disposition", disposition)
if type(self.trusted) is not bool or type(self.quorum_validated) is not bool:
raise SchemaError(DenialCode.INVALID_TYPE, field="inspection_flags")
require_nonblank(self.packet_identity, field="packet_identity")
require_nonblank(self.session_identity, field="session_identity")
require_int(self.temporal_counter, field="temporal_counter", minimum=0)
inspected_at = parse_timestamp(self.inspected_at, field="inspected_at")
evidence_not_before = parse_timestamp(
self.evidence_not_before,
field="evidence_not_before",
)
evidence_expires_at = parse_timestamp(
self.evidence_expires_at,
field="evidence_expires_at",
)
expected_gate_classes = {str(gate_class) for gate_class in GateClass}
gate_commitments = freeze_mapping(
self.gate_evidence_commitments,
field="gate_evidence_commitments",
)
if set(gate_commitments) != expected_gate_classes:
raise SchemaError(DenialCode.INVALID_VALUE, field="gate_evidence_commitments")
for commitment in gate_commitments.values():
require_sha256(commitment, field="gate_evidence_commitments")
object.__setattr__(self, "gate_evidence_commitments", gate_commitments)
for field in (
"packet_commitment",
"purpose_commitment",
"hnc_packet_commitment",
"trust_policy_commitment",
"quorum_policy_commitment",
"quorum_commitment",
"replay_token",
"evidence_commitment",
"inspection_commitment",
):
require_sha256(getattr(self, field), field=field)
if tuple(sorted(set(self.denial_codes))) != self.denial_codes:
raise SchemaError(DenialCode.INVALID_VALUE, field="denial_codes")
if (disposition is PacketDisposition.VALID) != (not self.denial_codes):
raise SchemaError(DenialCode.INVALID_VALUE, field="disposition")
if disposition is PacketDisposition.VALID and (not self.trusted or not self.quorum_validated):
raise SchemaError(DenialCode.INVALID_VALUE, field="trusted")
if disposition is PacketDisposition.VALID and not (
evidence_not_before <= inspected_at < evidence_expires_at
):
raise SchemaError(DenialCode.INVALID_VALUE, field="evidence_window")
if domain_hash("aureon.plumber.packet-inspection.v0", self.commitment_payload()) != self.inspection_commitment:
raise SchemaError(DenialCode.PACKET_COMMITMENT_MISMATCH, field="inspection_commitment")
@classmethod
def build(cls, **values: Any) -> PacketInspection:
payload = {
**values,
"disposition": str(values["disposition"]),
"denial_codes": list(values["denial_codes"]),
}
return cls(
**values,
inspection_commitment=domain_hash("aureon.plumber.packet-inspection.v0", payload),
)
def commitment_payload(self) -> dict[str, Any]:
return {
"disposition": str(self.disposition),
"trusted": self.trusted,
"packet_identity": self.packet_identity,
"session_identity": self.session_identity,
"temporal_counter": self.temporal_counter,
"inspected_at": self.inspected_at,
"evidence_not_before": self.evidence_not_before,
"evidence_expires_at": self.evidence_expires_at,
"gate_evidence_commitments": dict(self.gate_evidence_commitments),
"packet_commitment": self.packet_commitment,
"purpose_commitment": self.purpose_commitment,
"hnc_packet_commitment": self.hnc_packet_commitment,
"trust_policy_commitment": self.trust_policy_commitment,
"quorum_policy_commitment": self.quorum_policy_commitment,
"quorum_commitment": self.quorum_commitment,
"quorum_validated": self.quorum_validated,
"replay_token": self.replay_token,
"denial_codes": list(self.denial_codes),
"evidence_commitment": self.evidence_commitment,
}
def public_summary(self) -> dict[str, Any]:
return {**self.commitment_payload(), "inspection_commitment": self.inspection_commitment}
def _signature_denials(packet: PlumberPacketV0, trust_policy: PacketTrustPolicy | None) -> tuple[set[str], set[str]]:
hard: set[str] = set()
holds: set[str] = set()
if not packet.signatures:
holds.add(str(PacketCode.PACKET_SIGNATURE_MISSING))
return hard, holds
valid_signers = {
signer
for signer, signature in packet.signatures.items()
if verify_ed25519(
signer,
{"packet_commitment": packet.packet_commitment},
signature,
domain=_PACKET_SIGNATURE_DOMAIN,
)
}
if len(valid_signers) != len(packet.signatures):
hard.add(str(PacketCode.PACKET_SIGNATURE_INVALID))
if trust_policy is not None:
if not valid_signers & set(trust_policy.packet_signer_public_keys):
hard.add(str(PacketCode.PACKET_SIGNER_UNTRUSTED))
if set(packet.signatures) - set(trust_policy.packet_signer_public_keys):
hard.add(str(PacketCode.PACKET_SIGNER_UNTRUSTED))
return hard, holds
def inspect_plumber_packet(
packet: PlumberPacketV0,
hnc_packet: Mapping[str, Any],
*,
now: datetime,
observer_transcript: ObserverTranscriptV0 | Mapping[str, Any] | None = None,
sympathetic_identity: SympatheticIdentityV0 | Mapping[str, Any] | None = None,
quorum_permits: Sequence[AuthorityPermit] = (),
trust_policy: PacketTrustPolicy | None = None,
required_quorum_policy_commitment: str | None = None,
replay_guard: PacketReplayGuard | None = None,
) -> PacketInspection:
"""Inspect structurally, or establish trust only with every explicit pin."""
if not isinstance(packet, PlumberPacketV0):
raise SchemaError(DenialCode.INVALID_TYPE, field="packet")
current = require_aware_datetime(now, field="now")
inspected_at = format_timestamp(current.replace(microsecond=0))
purpose_commitment = domain_hash("aureon.plumber.purpose.v0", packet.requested_purpose)
hard: set[str] = set()
holds: set[str] = set()
evidence_not_before_values: list[datetime] = []
evidence_expires_at_values: list[datetime] = []
gate_evidence_commitments = {
str(gate_class): domain_hash(
"aureon.plumber.unavailable-gate-evidence.v0",
{
"packet_commitment": packet.packet_commitment,
"gate_class": str(gate_class),
},
)
for gate_class in GateClass
}
if trust_policy is None:
holds.add(str(PacketCode.TRUST_POLICY_REQUIRED))
trust_commitment = domain_hash("aureon.plumber.no-trust-policy.v0", {"packet": packet.packet_commitment})
else:
trust_commitment = trust_policy.trust_policy_commitment
if trust_policy is not None and required_quorum_policy_commitment is None:
holds.add(str(PacketCode.QUORUM_POLICY_PIN_REQUIRED))
if required_quorum_policy_commitment is not None:
require_sha256(required_quorum_policy_commitment, field="required_quorum_policy_commitment")
if trust_policy is not None and replay_guard is None:
holds.add(str(PacketCode.REPLAY_GUARD_REQUIRED))
fallback_hnc = domain_hash("aureon.plumber.unavailable-hnc-binding.v0", packet.packet_commitment)
live_binding: HNCPayloadBindingV0 | None = None
live_ciphertext_size: int | None = None
try:
live_binding = bind_hnc_packet(hnc_packet)
fallback_hnc = live_binding.hnc_packet_commitment
live_ciphertext_size = len(
b64url_decode(
require_nonblank(
hnc_packet.get("ciphertext_b64"),
field="hnc_packet.ciphertext_b64",
max_length=32 * 1024 * 1024,
)
)
)
except PacketContractError:
hard.add(str(PacketCode.HNC_CONTRACT_INVALID))
try:
packet_binding = HNCPayloadBindingV0.from_dict(_plain_mapping(packet.encrypted_payload))
fallback_hnc = packet_binding.hnc_packet_commitment
if live_binding is None or packet_binding != live_binding:
hard.add(str(PacketCode.HNC_BINDING_MISMATCH))
if packet_binding.purpose_commitment != purpose_commitment:
hard.add(str(DenialCode.PURPOSE_MISMATCH))
except (SchemaError, TypeError, ValueError):
hard.add(str(PacketCode.HNC_BINDING_MISMATCH))
packet_binding = None
try:
source = SourceIdentityV0.from_dict(_plain_mapping(packet.source_identity))
if packet_binding is None or source.source_content_commitment != packet_binding.hnc_packet_commitment:
hard.add(str(PacketCode.SOURCE_BINDING_INVALID))
except (SchemaError, TypeError, ValueError):
hard.add(str(PacketCode.SOURCE_BINDING_INVALID))
source = None
try:
temporal = TemporalIdentityV0.from_dict(_plain_mapping(packet.temporal_identity))
if temporal.packet_identity != packet.packet_identity:
hard.add(str(PacketCode.TEMPORAL_BINDING_INVALID))
temporal_issued_at = parse_timestamp(temporal.issued_at, field="issued_at")
temporal_expires_at = parse_timestamp(temporal.expires_at, field="expires_at")
evidence_not_before_values.append(temporal_issued_at)
evidence_expires_at_values.append(temporal_expires_at)
if current < temporal_issued_at or current >= temporal_expires_at:
holds.add(str(PacketCode.RECEIPT_STALE))
session_identity = temporal.session_identity
temporal_counter = temporal.counter
gate_evidence_commitments[str(GateClass.TEMPORAL)] = temporal.temporal_commitment
replay_token = domain_hash(
"aureon.plumber.packet-replay-token.v0",
{
"packet_commitment": packet.packet_commitment,
"session_identity": temporal.session_identity,
"counter": temporal.counter,
"nonce_commitment": temporal.nonce_commitment,
},
)
except (SchemaError, TypeError, ValueError):
hard.add(str(PacketCode.TEMPORAL_BINDING_INVALID))
temporal = None
session_identity = "invalid-session"
temporal_counter = 0
replay_token = domain_hash("aureon.plumber.invalid-replay-token.v0", packet.packet_commitment)
if replay_guard is not None and replay_guard.has_seen(replay_token):
hard.add(str(PacketCode.REPLAY_DETECTED))
parsed_observer: ObserverTranscriptV0 | None = None
if observer_transcript is not None:
try:
parsed_observer = (
observer_transcript
if isinstance(observer_transcript, ObserverTranscriptV0)
else ObserverTranscriptV0.from_dict(observer_transcript)
)
expected = (
packet.packet_identity,
session_identity,
purpose_commitment,
packet.hnc_observer_challenge,
packet.observer_transcript_commitment,
)
actual = (
parsed_observer.packet_identity,
parsed_observer.session_identity,
parsed_observer.purpose_commitment,
parsed_observer.challenge_commitment,
parsed_observer.transcript_commitment,
)
if actual != expected:
hard.add(str(PacketCode.OBSERVER_TRANSCRIPT_INVALID))
if source is not None and source.provenance_receipt_commitment not in (
parsed_observer.source_receipt_commitments
):
hard.add(str(PacketCode.OBSERVER_TRANSCRIPT_INVALID))
if (
temporal is None
or temporal.observer_receipt_commitment
!= parsed_observer.transcript_commitment
):
hard.add(str(PacketCode.TEMPORAL_BINDING_INVALID))
except (SchemaError, TypeError, ValueError):
hard.add(str(PacketCode.OBSERVER_TRANSCRIPT_INVALID))
elif trust_policy is not None:
hard.add(str(PacketCode.OBSERVER_TRANSCRIPT_INVALID))
try:
rune = TwinRuneSealV0.from_dict(_plain_mapping(packet.twin_rune_seal))
expected_rune = (
None if source is None else source.identity_commitment,
packet.observer_transcript_commitment,
None if temporal is None else temporal.temporal_commitment,
purpose_commitment,
packet.hnc_observer_challenge,
)
actual_rune = (
rune.source_identity_commitment,
rune.observer_transcript_commitment,
rune.temporal_identity_commitment,
rune.purpose_commitment,
rune.challenge_commitment,
)
if actual_rune != expected_rune:
hard.add(str(PacketCode.TWIN_RUNE_INVALID))
except (SchemaError, TypeError, ValueError):
hard.add(str(PacketCode.TWIN_RUNE_INVALID))
try:
policy = QuorumPolicyV0.from_dict(_plain_mapping(packet.quorum_policy))
policy_commitment = policy.policy_commitment
if required_quorum_policy_commitment is not None and policy_commitment != required_quorum_policy_commitment:
hard.add(str(PacketCode.QUORUM_POLICY_INVALID))
except (SchemaError, TypeError, ValueError):
hard.add(str(PacketCode.QUORUM_POLICY_INVALID))
policy = None
policy_commitment = domain_hash("aureon.plumber.invalid-quorum-policy.v0", packet.packet_commitment)
parsed_sympathetic: SympatheticIdentityV0 | None = None
if sympathetic_identity is not None:
try:
parsed_sympathetic = (
sympathetic_identity
if isinstance(sympathetic_identity, SympatheticIdentityV0)
else SympatheticIdentityV0.from_dict(sympathetic_identity)
)
expected_sympathetic = (
None if source is None else source.identity_commitment,
None if temporal is None else temporal.temporal_commitment,
None if parsed_observer is None else parsed_observer.transcript_commitment,
purpose_commitment,
None if policy is None else policy.policy_commitment,
packet.sympathetic_identity_commitment,
)
actual_sympathetic = (
parsed_sympathetic.source_identity_commitment,
parsed_sympathetic.temporal_identity_commitment,
parsed_sympathetic.observer_identity_commitment,
parsed_sympathetic.purpose_commitment,
parsed_sympathetic.policy_commitment,
parsed_sympathetic.identity_commitment,
)
if actual_sympathetic != expected_sympathetic:
hard.add(str(PacketCode.SYMPATHETIC_IDENTITY_INVALID))
if trust_policy is not None and (
parsed_sympathetic.hardware_identity_commitment
!= trust_policy.expected_hardware_identity_commitment
or parsed_sympathetic.operator_identity_commitment
!= trust_policy.expected_operator_identity_commitment
):
hard.add(str(PacketCode.SYMPATHETIC_IDENTITY_INVALID))
gate_evidence_commitments[str(GateClass.IDENTITY)] = (
parsed_sympathetic.identity_commitment
)
except (SchemaError, TypeError, ValueError):
hard.add(str(PacketCode.SYMPATHETIC_IDENTITY_INVALID))
parsed_sympathetic = None
elif trust_policy is not None:
hard.add(str(PacketCode.SYMPATHETIC_IDENTITY_INVALID))
try:
manifest = SporeManifest.from_dict(_plain_mapping(packet.spore_manifest))
if (
packet_binding is None
or temporal is None
or manifest.ciphertext_commitment != packet_binding.ciphertext_commitment
or manifest.packet_identity != packet.packet_identity
or manifest.temporal_epoch != temporal.counter
or manifest.challenge_commitment != packet.hnc_observer_challenge
or live_ciphertext_size is None
or manifest.ciphertext_size != live_ciphertext_size
):
hard.add(str(PacketCode.SPORE_BINDING_INVALID))
manifest_expires_at = parse_timestamp(manifest.expires_at, field="expires_at")
evidence_expires_at_values.append(manifest_expires_at)
if current >= manifest_expires_at:
holds.add(str(PacketCode.RECEIPT_STALE))
except (SchemaError, TypeError, ValueError):
hard.add(str(PacketCode.SPORE_BINDING_INVALID))
receipt_fields = (
("canonical_field_receipt", ReceiptKind.FIELD, GateClass.FIELD),
("heart_receipt", ReceiptKind.HEART, GateClass.HEART),
("conscience_receipt", ReceiptKind.CONSCIENCE, GateClass.CONSCIENCE),
("governance_receipt", ReceiptKind.GOVERNANCE, GateClass.GOVERNANCE),
)
for field, kind, gate_class in receipt_fields:
try:
receipt = SignedReceipt.from_dict(_plain_mapping(getattr(packet, field)))
gate_evidence_commitments[str(gate_class)] = receipt.receipt_hash
evidence_not_before_values.append(
parse_timestamp(receipt.issued_at, field="issued_at")
)
evidence_expires_at_values.append(
parse_timestamp(receipt.expires_at, field="expires_at")
)
expected_key = None
if trust_policy is not None:
authority = trust_policy.receipt_authorities[str(kind)]
expected_key = authority["public_key"]
if receipt.signer_id != authority["authority_id"]:
hard.add(str(PacketCode.RECEIPT_SIGNER_UNTRUSTED))
validation = receipt.validate(
now=current,
expected_packet_identity=packet.packet_identity,
expected_session_identity=session_identity,
expected_purpose_commitment=purpose_commitment,
expected_signer_public_key=expected_key,
)
if receipt.kind != kind:
hard.add(str(PacketCode.RECEIPT_INVALID))
for code in validation.denial_codes:
if code in _REFRESHABLE_CODES:
holds.add(str(PacketCode.RECEIPT_STALE))
elif code == str(DenialCode.SIGNER_MISMATCH):
hard.add(str(PacketCode.RECEIPT_SIGNER_UNTRUSTED))
else:
hard.add(str(PacketCode.RECEIPT_INVALID))
if source is not None and receipt.source_identity_commitment != source.identity_commitment:
hard.add(str(PacketCode.RECEIPT_INVALID))
if temporal is not None and receipt.temporal_identity_commitment != temporal.temporal_commitment:
hard.add(str(PacketCode.RECEIPT_INVALID))
if (
temporal is None
or receipt.runtime_measurement_commitment
!= temporal.runtime_measurement_commitment
):
hard.add(str(PacketCode.RECEIPT_INVALID))
if receipt.observer_transcript_commitment != packet.observer_transcript_commitment:
hard.add(str(PacketCode.RECEIPT_INVALID))
if policy is not None and receipt.policy_commitment != policy.policy_commitment:
hard.add(str(PacketCode.RECEIPT_INVALID))
except (KeyError, SchemaError, TypeError, ValueError):
hard.add(str(PacketCode.RECEIPT_INVALID))
signature_hard, signature_holds = _signature_denials(packet, trust_policy)
hard.update(signature_hard)
holds.update(signature_holds)
quorum_commitment = domain_hash("aureon.plumber.no-quorum-validation.v0", policy_commitment)
quorum_validated = False
if policy is not None and temporal is not None:
try:
for permit in quorum_permits:
if not isinstance(permit, AuthorityPermit):
raise SchemaError(DenialCode.INVALID_TYPE, field="quorum_permits")
evidence_not_before_values.append(
parse_timestamp(permit.issued_at, field="issued_at")
)
evidence_expires_at_values.append(
parse_timestamp(permit.expires_at, field="expires_at")
)
quorum_validation = evaluate_quorum(
policy,
quorum_permits,
now=current,
packet_identity=packet.packet_identity,
session_identity=temporal.session_identity,
purpose_commitment=purpose_commitment,
)
quorum_commitment = quorum_validation.permit_set_commitment
for code in quorum_validation.denial_codes:
if code in _REFRESHABLE_CODES:
holds.add(str(PacketCode.QUORUM_INVALID))
else:
hard.add(str(PacketCode.QUORUM_INVALID))
pinned = trust_policy is not None
if trust_policy is not None:
if set(policy.required_roles) != set(trust_policy.quorum_authorities):
hard.add(str(PacketCode.QUORUM_AUTHORITY_UNTRUSTED))
pinned = False
for permit in quorum_permits:
quorum_authority = trust_policy.quorum_authorities.get(permit.role)
if quorum_authority is None or (
permit.authority_id != quorum_authority["authority_id"]
or permit.signer_public_key != quorum_authority["public_key"]
):
hard.add(str(PacketCode.QUORUM_AUTHORITY_UNTRUSTED))
pinned = False
quorum_validated = quorum_validation.valid and pinned
except (KeyError, SchemaError, TypeError, ValueError):
hard.add(str(PacketCode.QUORUM_INVALID))
ready_for_temporal_reservation = (
trust_policy is not None
and required_quorum_policy_commitment is not None
and replay_guard is not None
and parsed_observer is not None
and parsed_sympathetic is not None
and temporal is not None
and quorum_validated
and not hard
and not holds
)
temporal_reserved = False
if ready_for_temporal_reservation:
trusted_replay_guard = cast(PacketReplayGuard, replay_guard)
trusted_temporal = cast(TemporalIdentityV0, temporal)
if not trusted_replay_guard.has_temporal_anchor(
trusted_temporal.session_identity
):
hard.add(str(PacketCode.TEMPORAL_ANCHOR_REQUIRED))
elif not trusted_replay_guard.reserve_temporal(
trusted_temporal,
replay_token,
now=current,
):
hard.add(str(PacketCode.TEMPORAL_BINDING_INVALID))
hard.add(str(PacketCode.REPLAY_DETECTED))
else:
temporal_reserved = True
trusted = ready_for_temporal_reservation and temporal_reserved and not hard and not holds
if hard:
disposition = PacketDisposition.DENY
codes = tuple(sorted(hard | holds))
elif holds or not trusted:
disposition = PacketDisposition.HOLD
codes = tuple(sorted(holds or {str(PacketCode.TRUST_POLICY_REQUIRED)}))
else:
disposition = PacketDisposition.VALID
codes = ()
evidence_not_before = format_timestamp(
max(evidence_not_before_values)
if evidence_not_before_values
else current.replace(microsecond=0)
)
evidence_expires_at = format_timestamp(
min(evidence_expires_at_values)
if evidence_expires_at_values
else current.replace(microsecond=0)
)
evidence = {
"packet_commitment": packet.packet_commitment,
"hnc_packet_commitment": fallback_hnc,
"purpose_commitment": purpose_commitment,
"trust_policy_commitment": trust_commitment,
"quorum_policy_commitment": policy_commitment,
"quorum_commitment": quorum_commitment,
"replay_token": replay_token,
"inspected_at": inspected_at,
"evidence_not_before": evidence_not_before,
"evidence_expires_at": evidence_expires_at,
"gate_evidence_commitments": gate_evidence_commitments,
}
return PacketInspection.build(
disposition=disposition,
trusted=trusted,
packet_identity=packet.packet_identity,
session_identity=session_identity,
temporal_counter=temporal_counter,
inspected_at=inspected_at,
evidence_not_before=evidence_not_before,
evidence_expires_at=evidence_expires_at,
gate_evidence_commitments=gate_evidence_commitments,
packet_commitment=packet.packet_commitment,
purpose_commitment=purpose_commitment,
hnc_packet_commitment=fallback_hnc,
trust_policy_commitment=trust_commitment,
quorum_policy_commitment=policy_commitment,
quorum_commitment=quorum_commitment,
quorum_validated=quorum_validated,
replay_token=replay_token,
denial_codes=codes,
evidence_commitment=domain_hash("aureon.plumber.packet-evidence.v0", evidence),
)
__all__ = [
"HNC_PAYLOAD_BINDING_SCHEMA",
"HNCPayloadBindingV0",
"PacketCode",
"PacketContractError",
"PacketDisposition",
"PacketInspection",
"PacketReplayGuard",
"PacketTrustPolicy",
"add_packet_signature",
"bind_hnc_packet",
"inspect_plumber_packet",
]12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126"""Fail-closed v0.3 contract for an out-of-process Magic Star broker.
This module defines and verifies the metadata crossing a production release
boundary. It deliberately contains no decryptor, capability callback, network
client, HSM key, or provider mutation. A production composition must implement
the canonical-wire protocols below and use four pinned, distinct review,
dispatch, executor, and receipt authorities.
``SQLiteTerminalLedgerV03`` is a durable reference implementation for local
integration and crash tests. It is not an independently administered
production ledger, but it does prove the required one-use/idempotency semantics
across process restarts. An expired, uncertain claim is never made retryable
or falsely terminal: it remains unresolved until independently reconciled with
authentic executor/provider evidence.
"""
from __future__ import annotations
import re
import secrets
import sqlite3
import time
from collections.abc import Callable, Mapping
from dataclasses import dataclass
from enum import StrEnum
from pathlib import Path
from typing import Any, Final, Protocol, TypeAlias, cast, runtime_checkable
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
from .audit import assert_public_summary_safe
from .crypto import (
canonical_json_bytes,
decode_canonical_json,
domain_hash,
sign_ed25519,
verify_ed25519,
)
COMMAND_SCHEMA: Final = "aureon.plumber.production-release-command.v03"
DISPATCH_SCHEMA: Final = "aureon.plumber.production-dispatch-claim.v03"
REVIEW_SCHEMA: Final = "aureon.plumber.production-review-authorization.v03"
EXECUTOR_EVIDENCE_SCHEMA: Final = "aureon.plumber.production-executor-evidence.v03"
RELEASE_RECEIPT_SCHEMA: Final = "aureon.plumber.production-release-receipt.v03"
DENIED_RECEIPT_SCHEMA: Final = "aureon.plumber.production-denied-receipt.v03"
LEDGER_SCHEMA: Final = "aureon.plumber.production-terminal-ledger.v03"
REVIEW_SIGNATURE_DOMAIN: Final = "AUREON-PLUMBER-V03-REVIEW-AUTHORIZATION"
DISPATCH_SIGNATURE_DOMAIN: Final = "AUREON-PLUMBER-V03-DISPATCH-CLAIM"
EXECUTOR_SIGNATURE_DOMAIN: Final = "AUREON-PLUMBER-V03-EXECUTOR-EVIDENCE"
RECEIPT_SIGNATURE_DOMAIN: Final = "AUREON-PLUMBER-V03-TERMINAL-RECEIPT"
_IDENTIFIER = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._:/-]{0,127}$")
_SHA256 = re.compile(r"^[0-9a-f]{64}$")
_SIGNATURE = re.compile(r"^[0-9a-f]{128}$")
_MAX_COMMAND_LIFETIME_MS = 15 * 60 * 1000
_MAX_CLOCK_SKEW_MS = 5_000
_MAX_WIRE_BYTES = 64 * 1024
_MAX_SAFE_INTEGER = (1 << 53) - 1
_ZERO_SHA256 = "0" * 64
class ProductionReleaseBrokerError(ValueError):
"""Stable, non-secret contract or durable-state failure."""
def __init__(self, code: str) -> None:
self.code = str(code)
super().__init__(self.code)
def _identifier(value: object, *, code: str) -> str:
if not isinstance(value, str) or _IDENTIFIER.fullmatch(value) is None:
raise ProductionReleaseBrokerError(code)
return value
def _opaque_id(value: object, *, code: str) -> str:
"""Require a fixed-width opaque identifier, never caller-chosen plaintext."""
return _sha256(value, code=code)
def _sha256(value: object, *, code: str) -> str:
if not isinstance(value, str) or _SHA256.fullmatch(value) is None:
raise ProductionReleaseBrokerError(code)
return value
def _uint(value: object, *, code: str) -> int:
if (
isinstance(value, bool)
or not isinstance(value, int)
or value < 0
or value > _MAX_SAFE_INTEGER
):
raise ProductionReleaseBrokerError(code)
return value
def _signature(value: object, *, code: str) -> str:
if not isinstance(value, str) or _SIGNATURE.fullmatch(value) is None:
raise ProductionReleaseBrokerError(code)
return value
def _exact_mapping(value: object, keys: set[str], *, code: str) -> dict[str, Any]:
if not isinstance(value, Mapping) or set(value) != keys:
raise ProductionReleaseBrokerError(code)
return dict(value)
def _system_now_ms() -> int:
return time.time_ns() // 1_000_000
def _decode_wire_mapping(data: bytes | str, *, code: str) -> dict[str, Any]:
try:
decoded = decode_canonical_json(
data,
require_mapping=True,
max_bytes=_MAX_WIRE_BYTES,
)
except BaseException:
raise ProductionReleaseBrokerError(code) from None
if not isinstance(decoded, dict): # pragma: no cover - require_mapping
raise ProductionReleaseBrokerError(code)
return decoded
def _decode_stored_receipt(value: object) -> dict[str, Any]:
if isinstance(value, bytes):
raw = value
elif isinstance(value, bytearray | memoryview):
raw = bytes(value)
else:
raise ProductionReleaseBrokerError("stored_receipt_invalid")
return _decode_wire_mapping(raw, code="stored_receipt_invalid")
@dataclass(frozen=True, slots=True)
class AuthorityBindingV03:
"""One pinned public authority identity; never private key custody."""
role: str
authority_id: str
key_id: str
public_key_hex: str
def __post_init__(self) -> None:
_identifier(self.role, code="authority_role_invalid")
_identifier(self.authority_id, code="authority_id_invalid")
_identifier(self.key_id, code="authority_key_id_invalid")
if (
not isinstance(self.public_key_hex, str)
or re.fullmatch(r"[0-9a-f]{64}", self.public_key_hex) is None
):
raise ProductionReleaseBrokerError("authority_public_key_invalid")
def public_dict(self) -> dict[str, str]:
return {
"role": self.role,
"authority_id": self.authority_id,
"key_id": self.key_id,
"public_key_hex": self.public_key_hex,
}
def _require_distinct_authorities(
review: AuthorityBindingV03,
dispatch: AuthorityBindingV03,
executor: AuthorityBindingV03,
receipt: AuthorityBindingV03,
) -> None:
expected = (
(review, "REVIEW"),
(dispatch, "DISPATCH"),
(executor, "EXECUTOR"),
(receipt, "RECEIPT"),
)
if any(binding.role != role for binding, role in expected):
raise ProductionReleaseBrokerError("authority_role_binding_invalid")
bindings = (review, dispatch, executor, receipt)
for field, code in (
("authority_id", "authority_ids_not_distinct"),
("key_id", "authority_key_ids_not_distinct"),
("public_key_hex", "authority_public_keys_not_distinct"),
):
values = {getattr(binding, field) for binding in bindings}
if len(values) != 4:
raise ProductionReleaseBrokerError(code)
@dataclass(frozen=True, slots=True)
class ReleaseCommandV03:
command_id: str
packet_commitment: str
admission_commitment: str
effect_id: str
capability_id: str
capability_measurement_sha256: str
runtime_measurement_sha256: str
authorization_context_sha256: str
request_nonce: str
issued_at_ms: int
expires_at_ms: int
schema: str = COMMAND_SCHEMA
def __post_init__(self) -> None:
if self.schema != COMMAND_SCHEMA:
raise ProductionReleaseBrokerError("release_command_schema_invalid")
for value, code in (
(self.command_id, "command_id_invalid"),
(self.effect_id, "effect_id_invalid"),
(self.capability_id, "capability_id_invalid"),
(self.request_nonce, "request_nonce_invalid"),
):
_opaque_id(value, code=code)
for value, code in (
(self.packet_commitment, "packet_commitment_invalid"),
(self.admission_commitment, "admission_commitment_invalid"),
(self.capability_measurement_sha256, "capability_measurement_invalid"),
(self.runtime_measurement_sha256, "runtime_measurement_invalid"),
(self.authorization_context_sha256, "authorization_context_invalid"),
):
_sha256(value, code=code)
issued = _uint(self.issued_at_ms, code="command_issued_at_invalid")
expires = _uint(self.expires_at_ms, code="command_expires_at_invalid")
if expires <= issued or expires - issued > _MAX_COMMAND_LIFETIME_MS:
raise ProductionReleaseBrokerError("command_lifetime_invalid")
def public_dict(self) -> dict[str, Any]:
result = {
"schema": self.schema,
"command_id": self.command_id,
"packet_commitment": self.packet_commitment,
"admission_commitment": self.admission_commitment,
"effect_id": self.effect_id,
"capability_id": self.capability_id,
"capability_measurement_sha256": self.capability_measurement_sha256,
"runtime_measurement_sha256": self.runtime_measurement_sha256,
"authorization_context_sha256": self.authorization_context_sha256,
"request_nonce": self.request_nonce,
"issued_at_ms": self.issued_at_ms,
"expires_at_ms": self.expires_at_ms,
"production_ready": False,
}
assert_public_summary_safe(result)
return result
@property
def commitment(self) -> str:
return domain_hash("AUREON-PLUMBER-V03-RELEASE-COMMAND", self.public_dict())
def wire_dict(self) -> dict[str, Any]:
return {
key: value
for key, value in self.public_dict().items()
if key != "production_ready"
}
@classmethod
def from_wire(cls, value: Mapping[str, Any]) -> ReleaseCommandV03:
payload = _exact_mapping(
value,
{
"schema", "command_id", "packet_commitment", "admission_commitment",
"effect_id", "capability_id", "capability_measurement_sha256",
"runtime_measurement_sha256", "authorization_context_sha256",
"request_nonce", "issued_at_ms", "expires_at_ms",
},
code="release_command_shape_invalid",
)
try:
return cls(**payload)
except TypeError as exc:
raise ProductionReleaseBrokerError("release_command_shape_invalid") from exc
@dataclass(frozen=True, slots=True)
class ReviewAuthorizationV03:
review_id: str
command_commitment: str
decision: str
issued_at_ms: int
expires_at_ms: int
authority_id: str
key_id: str
signature_hex: str
schema: str = REVIEW_SCHEMA
def __post_init__(self) -> None:
if self.schema != REVIEW_SCHEMA or self.decision != "ALLOW":
raise ProductionReleaseBrokerError("review_authorization_invalid")
_opaque_id(self.review_id, code="review_id_invalid")
_sha256(self.command_commitment, code="review_command_commitment_invalid")
_identifier(self.authority_id, code="review_authority_id_invalid")
_identifier(self.key_id, code="review_key_id_invalid")
_signature(self.signature_hex, code="review_signature_invalid")
issued = _uint(self.issued_at_ms, code="review_issued_at_invalid")
expires = _uint(self.expires_at_ms, code="review_expires_at_invalid")
if expires <= issued or expires - issued > _MAX_COMMAND_LIFETIME_MS:
raise ProductionReleaseBrokerError("review_lifetime_invalid")
def unsigned_dict(self) -> dict[str, Any]:
return {
"schema": self.schema,
"review_id": self.review_id,
"command_commitment": self.command_commitment,
"decision": self.decision,
"issued_at_ms": self.issued_at_ms,
"expires_at_ms": self.expires_at_ms,
"authority_id": self.authority_id,
"key_id": self.key_id,
}
def wire_dict(self) -> dict[str, Any]:
return {**self.unsigned_dict(), "signature_hex": self.signature_hex}
@property
def commitment(self) -> str:
return domain_hash("AUREON-PLUMBER-V03-REVIEW", self.wire_dict())
@dataclass(frozen=True, slots=True)
class DispatchClaimV03:
"""Durable, unpredictable claim that the executor must sign back."""
command_commitment: str
review_commitment: str
effect_id: str
request_nonce: str
dispatch_nonce: str
claimed_at_ms: int
claim_expires_at_ms: int
authority_id: str
key_id: str
signature_hex: str
schema: str = DISPATCH_SCHEMA
def __post_init__(self) -> None:
if self.schema != DISPATCH_SCHEMA:
raise ProductionReleaseBrokerError("dispatch_claim_schema_invalid")
for value, code in (
(self.command_commitment, "dispatch_command_commitment_invalid"),
(self.review_commitment, "dispatch_review_commitment_invalid"),
(self.effect_id, "dispatch_effect_id_invalid"),
(self.request_nonce, "dispatch_request_nonce_invalid"),
(self.dispatch_nonce, "dispatch_nonce_invalid"),
):
_sha256(value, code=code)
claimed = _uint(self.claimed_at_ms, code="dispatch_claimed_at_invalid")
expires = _uint(self.claim_expires_at_ms, code="dispatch_expires_at_invalid")
if expires <= claimed or expires - claimed > _MAX_COMMAND_LIFETIME_MS:
raise ProductionReleaseBrokerError("dispatch_lifetime_invalid")
_identifier(self.authority_id, code="dispatch_authority_id_invalid")
_identifier(self.key_id, code="dispatch_key_id_invalid")
_signature(self.signature_hex, code="dispatch_signature_invalid")
def unsigned_dict(self) -> dict[str, Any]:
return {
"schema": self.schema,
"command_commitment": self.command_commitment,
"review_commitment": self.review_commitment,
"effect_id": self.effect_id,
"request_nonce": self.request_nonce,
"dispatch_nonce": self.dispatch_nonce,
"claimed_at_ms": self.claimed_at_ms,
"claim_expires_at_ms": self.claim_expires_at_ms,
"authority_id": self.authority_id,
"key_id": self.key_id,
}
def wire_dict(self) -> dict[str, Any]:
return {**self.unsigned_dict(), "signature_hex": self.signature_hex}
@property
def commitment(self) -> str:
return domain_hash("AUREON-PLUMBER-V03-DISPATCH-CLAIM", self.wire_dict())
@classmethod
def from_wire(cls, value: Mapping[str, Any]) -> DispatchClaimV03:
payload = _exact_mapping(
value,
{
"schema", "command_commitment", "review_commitment", "effect_id",
"request_nonce", "dispatch_nonce", "claimed_at_ms",
"claim_expires_at_ms", "authority_id", "key_id", "signature_hex",
},
code="dispatch_claim_shape_invalid",
)
try:
return cls(**payload)
except TypeError as exc:
raise ProductionReleaseBrokerError("dispatch_claim_shape_invalid") from exc
class ExecutorOutcome(StrEnum):
CONSUMED = "CONSUMED"
DENIED = "DENIED"
@dataclass(frozen=True, slots=True)
class ExecutorTerminalEvidenceV03:
evidence_id: str
command_commitment: str
review_commitment: str
dispatch_commitment: str
effect_id: str
capability_id: str
runtime_measurement_sha256: str
request_nonce: str
outcome: ExecutorOutcome
result_sha256: str
provider_readback_sha256: str
reason_code: str
terminal_at_ms: int
authority_id: str
key_id: str
signature_hex: str
schema: str = EXECUTOR_EVIDENCE_SCHEMA
def __post_init__(self) -> None:
if self.schema != EXECUTOR_EVIDENCE_SCHEMA:
raise ProductionReleaseBrokerError("executor_evidence_schema_invalid")
if not isinstance(self.outcome, ExecutorOutcome):
raise ProductionReleaseBrokerError("executor_outcome_invalid")
for value, code in (
(self.evidence_id, "executor_evidence_id_invalid"),
(self.effect_id, "executor_effect_id_invalid"),
(self.capability_id, "executor_capability_id_invalid"),
(self.request_nonce, "executor_request_nonce_invalid"),
):
_opaque_id(value, code=code)
for value, code in (
(self.reason_code, "executor_reason_code_invalid"),
(self.authority_id, "executor_authority_id_invalid"),
(self.key_id, "executor_key_id_invalid"),
):
_identifier(value, code=code)
for value, code in (
(self.command_commitment, "executor_command_commitment_invalid"),
(self.review_commitment, "executor_review_commitment_invalid"),
(self.dispatch_commitment, "executor_dispatch_commitment_invalid"),
(self.runtime_measurement_sha256, "executor_runtime_measurement_invalid"),
(self.result_sha256, "executor_result_sha256_invalid"),
(self.provider_readback_sha256, "executor_readback_sha256_invalid"),
):
_sha256(value, code=code)
_uint(self.terminal_at_ms, code="executor_terminal_at_invalid")
_signature(self.signature_hex, code="executor_signature_invalid")
if self.outcome is ExecutorOutcome.CONSUMED and (
self.result_sha256 == _ZERO_SHA256
or self.provider_readback_sha256 == _ZERO_SHA256
or self.reason_code != "effect_consumed_with_provider_readback"
):
raise ProductionReleaseBrokerError("consumed_executor_evidence_invalid")
if self.outcome is ExecutorOutcome.DENIED and (
self.result_sha256 != _ZERO_SHA256
or self.provider_readback_sha256 == _ZERO_SHA256
or self.reason_code != "effect_denied_with_provider_readback"
):
raise ProductionReleaseBrokerError("denied_executor_evidence_invalid")
def unsigned_dict(self) -> dict[str, Any]:
return {
"schema": self.schema,
"evidence_id": self.evidence_id,
"command_commitment": self.command_commitment,
"review_commitment": self.review_commitment,
"dispatch_commitment": self.dispatch_commitment,
"effect_id": self.effect_id,
"capability_id": self.capability_id,
"runtime_measurement_sha256": self.runtime_measurement_sha256,
"request_nonce": self.request_nonce,
"outcome": self.outcome.value,
"result_sha256": self.result_sha256,
"provider_readback_sha256": self.provider_readback_sha256,
"reason_code": self.reason_code,
"terminal_at_ms": self.terminal_at_ms,
"authority_id": self.authority_id,
"key_id": self.key_id,
}
def wire_dict(self) -> dict[str, Any]:
return {**self.unsigned_dict(), "signature_hex": self.signature_hex}
@property
def commitment(self) -> str:
return domain_hash("AUREON-PLUMBER-V03-EXECUTOR-EVIDENCE", self.wire_dict())
class ReceiptDisposition(StrEnum):
RELEASED = "RELEASED"
DENIED = "DENIED"
@dataclass(frozen=True, slots=True)
class _TerminalReceiptV03:
receipt_id: str
command_commitment: str
review_commitment: str
executor_evidence_commitment: str
effect_id: str
request_nonce: str
disposition: ReceiptDisposition
reason_code: str
terminal_at_ms: int
authority_id: str
key_id: str
signature_hex: str
effect_retry_authorized: bool = False
production_ready: bool = False
def _validate(self, *, expected_schema: str) -> None:
if getattr(self, "schema", None) != expected_schema:
raise ProductionReleaseBrokerError("terminal_receipt_schema_invalid")
for value, code in (
(self.receipt_id, "terminal_receipt_id_invalid"),
(self.effect_id, "terminal_effect_id_invalid"),
(self.request_nonce, "terminal_request_nonce_invalid"),
):
_opaque_id(value, code=code)
for value, code in (
(self.reason_code, "terminal_reason_code_invalid"),
(self.authority_id, "terminal_authority_id_invalid"),
(self.key_id, "terminal_key_id_invalid"),
):
_identifier(value, code=code)
for value, code in (
(self.command_commitment, "terminal_command_commitment_invalid"),
(self.review_commitment, "terminal_review_commitment_invalid"),
(self.executor_evidence_commitment, "terminal_executor_evidence_invalid"),
):
_sha256(value, code=code)
_uint(self.terminal_at_ms, code="terminal_at_invalid")
_signature(self.signature_hex, code="terminal_signature_invalid")
if self.effect_retry_authorized is not False or self.production_ready is not False:
raise ProductionReleaseBrokerError("terminal_scope_invalid")
def unsigned_dict(self) -> dict[str, Any]:
return {
"schema": self.schema, # type: ignore[attr-defined]
"receipt_id": self.receipt_id,
"command_commitment": self.command_commitment,
"review_commitment": self.review_commitment,
"executor_evidence_commitment": self.executor_evidence_commitment,
"effect_id": self.effect_id,
"request_nonce": self.request_nonce,
"disposition": self.disposition.value,
"reason_code": self.reason_code,
"terminal_at_ms": self.terminal_at_ms,
"authority_id": self.authority_id,
"key_id": self.key_id,
"effect_retry_authorized": self.effect_retry_authorized,
"production_ready": self.production_ready,
}
def wire_dict(self) -> dict[str, Any]:
result = {**self.unsigned_dict(), "signature_hex": self.signature_hex}
assert_public_summary_safe(result)
return result
@property
def commitment(self) -> str:
return domain_hash("AUREON-PLUMBER-V03-TERMINAL-RECEIPT", self.wire_dict())
@dataclass(frozen=True, slots=True)
class ReleaseReceiptV03(_TerminalReceiptV03):
schema: str = RELEASE_RECEIPT_SCHEMA
def __post_init__(self) -> None:
self._validate(expected_schema=RELEASE_RECEIPT_SCHEMA)
if (
self.disposition is not ReceiptDisposition.RELEASED
or self.reason_code != "effect_consumed_with_provider_readback"
or self.executor_evidence_commitment == _ZERO_SHA256
):
raise ProductionReleaseBrokerError("release_receipt_invalid")
@dataclass(frozen=True, slots=True)
class DeniedReceiptV03(_TerminalReceiptV03):
schema: str = DENIED_RECEIPT_SCHEMA
def __post_init__(self) -> None:
self._validate(expected_schema=DENIED_RECEIPT_SCHEMA)
if self.disposition is not ReceiptDisposition.DENIED:
raise ProductionReleaseBrokerError("denied_receipt_invalid")
if (
self.reason_code != "effect_denied_with_provider_readback"
or self.executor_evidence_commitment == _ZERO_SHA256
):
raise ProductionReleaseBrokerError("denied_receipt_invalid")
TerminalReceiptV03: TypeAlias = ReleaseReceiptV03 | DeniedReceiptV03
def decode_release_command_v03(data: bytes | str) -> ReleaseCommandV03:
"""Decode one bounded canonical command with an exact key set."""
return ReleaseCommandV03.from_wire(
_decode_wire_mapping(data, code="release_command_wire_invalid")
)
def decode_dispatch_claim_v03(data: bytes | str) -> DispatchClaimV03:
"""Decode one bounded canonical durable dispatch claim."""
return DispatchClaimV03.from_wire(
_decode_wire_mapping(data, code="dispatch_claim_wire_invalid")
)
def decode_review_authorization_v03(data: bytes | str) -> ReviewAuthorizationV03:
payload = _exact_mapping(
_decode_wire_mapping(data, code="review_authorization_wire_invalid"),
{
"schema", "review_id", "command_commitment", "decision",
"issued_at_ms", "expires_at_ms", "authority_id", "key_id",
"signature_hex",
},
code="review_authorization_shape_invalid",
)
try:
return ReviewAuthorizationV03(**payload)
except (TypeError, ValueError) as exc:
if isinstance(exc, ProductionReleaseBrokerError):
raise
raise ProductionReleaseBrokerError("review_authorization_shape_invalid") from exc
def decode_executor_evidence_v03(data: bytes | str) -> ExecutorTerminalEvidenceV03:
payload = _exact_mapping(
_decode_wire_mapping(data, code="executor_evidence_wire_invalid"),
{
"schema", "evidence_id", "command_commitment", "review_commitment",
"dispatch_commitment", "effect_id",
"capability_id", "runtime_measurement_sha256", "request_nonce",
"outcome", "result_sha256", "provider_readback_sha256",
"reason_code", "terminal_at_ms", "authority_id", "key_id",
"signature_hex",
},
code="executor_evidence_shape_invalid",
)
try:
payload["outcome"] = ExecutorOutcome(payload["outcome"])
return ExecutorTerminalEvidenceV03(**payload)
except (TypeError, ValueError) as exc:
if isinstance(exc, ProductionReleaseBrokerError):
raise
raise ProductionReleaseBrokerError("executor_evidence_shape_invalid") from exc
def decode_terminal_receipt_v03(data: bytes | str) -> TerminalReceiptV03:
payload = _exact_mapping(
_decode_wire_mapping(data, code="terminal_receipt_wire_invalid"),
{
"schema", "receipt_id", "command_commitment", "review_commitment",
"executor_evidence_commitment", "effect_id", "request_nonce",
"disposition", "reason_code", "terminal_at_ms", "authority_id",
"key_id", "effect_retry_authorized", "production_ready",
"signature_hex",
},
code="terminal_receipt_shape_invalid",
)
try:
payload["disposition"] = ReceiptDisposition(payload["disposition"])
schema = payload.get("schema")
if schema == RELEASE_RECEIPT_SCHEMA:
return ReleaseReceiptV03(**payload)
if schema == DENIED_RECEIPT_SCHEMA:
return DeniedReceiptV03(**payload)
raise ProductionReleaseBrokerError("terminal_receipt_schema_invalid")
except (TypeError, ValueError) as exc:
if isinstance(exc, ProductionReleaseBrokerError):
raise
raise ProductionReleaseBrokerError("terminal_receipt_shape_invalid") from exc
@runtime_checkable
class DispatchClaimSignerV03(Protocol):
"""Canonical-wire adapter for an independently held dispatch key."""
signer_id: str
key_id: str
def sign_dispatch(
self,
unsigned_dispatch_wire: bytes,
*,
deadline_at_ms: int,
) -> bytes: ...
@runtime_checkable
class OutOfProcessReleaseExecutorV03(Protocol):
"""Canonical-wire adapter for a separately isolated executor service.
A Python protocol cannot itself prove process or administrative isolation;
the checked-in broker therefore remains non-production until its concrete
transport and remote service are independently attested.
"""
executor_id: str
def execute(
self,
command_wire: bytes,
review_wire: bytes,
dispatch_wire: bytes,
) -> bytes: ...
@runtime_checkable
class TerminalReceiptSignerV03(Protocol):
"""Canonical-wire adapter for an independent remote receipt authority.
Production implementations must durably deduplicate by the executor
evidence commitment and return that same signed receipt through readback.
"""
signer_id: str
def sign_terminal(
self,
command_wire: bytes,
review_wire: bytes,
evidence_wire: bytes,
*,
idempotency_key: str,
) -> bytes: ...
def read_terminal(self, *, idempotency_key: str) -> bytes | None: ...
def terminal_receipt_id_v03(executor_evidence_commitment: str) -> str:
"""Derive the sole permitted receipt identity for terminal evidence."""
_sha256(
executor_evidence_commitment,
code="terminal_executor_evidence_invalid",
)
return domain_hash(
"AUREON-PLUMBER-V03-TERMINAL-RECEIPT-ID",
{"executor_evidence_commitment": executor_evidence_commitment},
)
class ProductionReleaseVerifierV03:
"""Verify exact joins and four independent pinned signatures."""
production_ready = False
def __init__(
self,
*,
review_authority: AuthorityBindingV03,
dispatch_authority: AuthorityBindingV03,
executor_authority: AuthorityBindingV03,
receipt_authority: AuthorityBindingV03,
trusted_now_ms: Callable[[], int] = _system_now_ms,
max_clock_skew_ms: int = _MAX_CLOCK_SKEW_MS,
) -> None:
_require_distinct_authorities(
review_authority,
dispatch_authority,
executor_authority,
receipt_authority,
)
if not callable(trusted_now_ms):
raise ProductionReleaseBrokerError("trusted_clock_invalid")
skew = _uint(max_clock_skew_ms, code="clock_skew_policy_invalid")
if skew > 60_000:
raise ProductionReleaseBrokerError("clock_skew_policy_invalid")
self._review = review_authority
self._dispatch = dispatch_authority
self._executor = executor_authority
self._receipt = receipt_authority
self._trusted_now_ms = trusted_now_ms
self._max_clock_skew_ms = skew
@property
def authority_ids(self) -> dict[str, str]:
"""Return only pinned public identities for composition checks."""
return {
"review": self._review.authority_id,
"dispatch": self._dispatch.authority_id,
"executor": self._executor.authority_id,
"receipt": self._receipt.authority_id,
}
def _now(self) -> int:
return _uint(self._trusted_now_ms(), code="trusted_time_invalid")
def verify_review(
self,
command: ReleaseCommandV03,
review: ReviewAuthorizationV03,
*,
require_current: bool = True,
) -> None:
now = self._now()
if (
type(command) is not ReleaseCommandV03
or type(review) is not ReviewAuthorizationV03
or review.command_commitment != command.commitment
or review.authority_id != self._review.authority_id
or review.key_id != self._review.key_id
or review.expires_at_ms > command.expires_at_ms
or review.issued_at_ms < command.issued_at_ms - self._max_clock_skew_ms
or (
require_current
and (
now < review.issued_at_ms - self._max_clock_skew_ms
or now >= review.expires_at_ms
or now >= command.expires_at_ms
)
)
):
raise ProductionReleaseBrokerError("review_authorization_join_or_time_invalid")
if not verify_ed25519(
self._review.public_key_hex,
review.unsigned_dict(),
review.signature_hex,
domain=REVIEW_SIGNATURE_DOMAIN,
):
raise ProductionReleaseBrokerError("review_signature_invalid")
def verify_dispatch(
self,
command: ReleaseCommandV03,
review: ReviewAuthorizationV03,
dispatch: DispatchClaimV03,
*,
require_current: bool = False,
) -> None:
"""Authenticate the ledger-issued dispatch and its exact joins."""
self.verify_review(command, review, require_current=require_current)
now = self._now()
if (
type(dispatch) is not DispatchClaimV03
or dispatch.command_commitment != command.commitment
or dispatch.review_commitment != review.commitment
or dispatch.effect_id != command.effect_id
or dispatch.request_nonce != command.request_nonce
or dispatch.claimed_at_ms < review.issued_at_ms
or dispatch.claimed_at_ms > now + self._max_clock_skew_ms
or dispatch.claim_expires_at_ms > command.expires_at_ms
or dispatch.claim_expires_at_ms > review.expires_at_ms
or dispatch.authority_id != self._dispatch.authority_id
or dispatch.key_id != self._dispatch.key_id
or (
require_current
and (
now < dispatch.claimed_at_ms - self._max_clock_skew_ms
or now >= dispatch.claim_expires_at_ms
)
)
):
raise ProductionReleaseBrokerError("dispatch_claim_join_or_time_invalid")
if not verify_ed25519(
self._dispatch.public_key_hex,
dispatch.unsigned_dict(),
dispatch.signature_hex,
domain=DISPATCH_SIGNATURE_DOMAIN,
):
raise ProductionReleaseBrokerError("dispatch_signature_invalid")
def verify_executor_evidence(
self,
command: ReleaseCommandV03,
review: ReviewAuthorizationV03,
dispatch: DispatchClaimV03,
evidence: ExecutorTerminalEvidenceV03,
) -> None:
self.verify_dispatch(command, review, dispatch)
now = self._now()
if (
type(evidence) is not ExecutorTerminalEvidenceV03
or evidence.command_commitment != command.commitment
or evidence.review_commitment != review.commitment
or evidence.dispatch_commitment != dispatch.commitment
or evidence.effect_id != command.effect_id
or evidence.capability_id != command.capability_id
or evidence.runtime_measurement_sha256 != command.runtime_measurement_sha256
or evidence.request_nonce != command.request_nonce
or evidence.authority_id != self._executor.authority_id
or evidence.key_id != self._executor.key_id
or evidence.terminal_at_ms < dispatch.claimed_at_ms
or evidence.terminal_at_ms >= dispatch.claim_expires_at_ms
or evidence.terminal_at_ms >= review.expires_at_ms
or evidence.terminal_at_ms >= command.expires_at_ms
or evidence.terminal_at_ms > now + self._max_clock_skew_ms
):
raise ProductionReleaseBrokerError("executor_evidence_join_or_time_invalid")
if not verify_ed25519(
self._executor.public_key_hex,
evidence.unsigned_dict(),
evidence.signature_hex,
domain=EXECUTOR_SIGNATURE_DOMAIN,
):
raise ProductionReleaseBrokerError("executor_signature_invalid")
def verify_dispatch_current(
self,
command: ReleaseCommandV03,
review: ReviewAuthorizationV03,
dispatch: DispatchClaimV03,
) -> None:
"""Require an exact durable dispatch lease immediately before transport."""
self.verify_dispatch(command, review, dispatch, require_current=True)
def verify_terminal(
self,
command: ReleaseCommandV03,
review: ReviewAuthorizationV03,
dispatch: DispatchClaimV03,
receipt: TerminalReceiptV03,
evidence: ExecutorTerminalEvidenceV03,
) -> None:
self.verify_terminal_receipt_signature(command, review, receipt)
if type(evidence) is not ExecutorTerminalEvidenceV03:
raise ProductionReleaseBrokerError("terminal_executor_evidence_required")
self.verify_executor_evidence(command, review, dispatch, evidence)
if receipt.executor_evidence_commitment != evidence.commitment:
raise ProductionReleaseBrokerError("terminal_executor_evidence_join_invalid")
if (
receipt.terminal_at_ms < evidence.terminal_at_ms
or receipt.terminal_at_ms
> command.expires_at_ms + self._max_clock_skew_ms
):
raise ProductionReleaseBrokerError("terminal_receipt_time_join_invalid")
if (
receipt.receipt_id != terminal_receipt_id_v03(evidence.commitment)
or receipt.reason_code != evidence.reason_code
or receipt.terminal_at_ms != evidence.terminal_at_ms
):
raise ProductionReleaseBrokerError("terminal_receipt_canonical_join_invalid")
if (receipt.disposition is ReceiptDisposition.RELEASED) != (
evidence.outcome is ExecutorOutcome.CONSUMED
):
raise ProductionReleaseBrokerError("terminal_outcome_join_invalid")
def verify_terminal_receipt_signature(
self,
command: ReleaseCommandV03,
review: ReviewAuthorizationV03,
receipt: TerminalReceiptV03,
) -> None:
"""Authenticate durable replay without re-executing an effect."""
# Terminal evidence is a durable historical fact. The review must
# have been valid inside the command window, while an authentic
# executor-backed terminal chain remains verifiable after that window.
self.verify_review(command, review, require_current=False)
now = self._now()
if type(receipt) not in {ReleaseReceiptV03, DeniedReceiptV03}:
raise ProductionReleaseBrokerError("terminal_receipt_type_invalid")
if (
receipt.command_commitment != command.commitment
or receipt.review_commitment != review.commitment
or receipt.effect_id != command.effect_id
or receipt.request_nonce != command.request_nonce
or receipt.authority_id != self._receipt.authority_id
or receipt.key_id != self._receipt.key_id
or receipt.terminal_at_ms < review.issued_at_ms
or receipt.terminal_at_ms > now + self._max_clock_skew_ms
):
raise ProductionReleaseBrokerError("terminal_receipt_join_invalid")
if not verify_ed25519(
self._receipt.public_key_hex,
receipt.unsigned_dict(),
receipt.signature_hex,
domain=RECEIPT_SIGNATURE_DOMAIN,
):
raise ProductionReleaseBrokerError("terminal_signature_invalid")
def sign_review_authorization_v03(
private_key: Ed25519PrivateKey,
**values: Any,
) -> ReviewAuthorizationV03:
"""Test/integration builder; production review keys remain remote."""
unsigned = dict(values)
unsigned.setdefault("schema", REVIEW_SCHEMA)
signature = sign_ed25519(private_key, unsigned, domain=REVIEW_SIGNATURE_DOMAIN)
return ReviewAuthorizationV03(**unsigned, signature_hex=signature)
def sign_dispatch_claim_v03(
private_key: Ed25519PrivateKey,
**values: Any,
) -> DispatchClaimV03:
"""Test/integration builder; production dispatch keys remain remote."""
unsigned = dict(values)
unsigned.setdefault("schema", DISPATCH_SCHEMA)
signature = sign_ed25519(private_key, unsigned, domain=DISPATCH_SIGNATURE_DOMAIN)
return DispatchClaimV03(**unsigned, signature_hex=signature)
def sign_executor_evidence_v03(
private_key: Ed25519PrivateKey,
**values: Any,
) -> ExecutorTerminalEvidenceV03:
"""Test/integration builder; production executor keys remain remote."""
unsigned = dict(values)
unsigned.setdefault("schema", EXECUTOR_EVIDENCE_SCHEMA)
outcome = unsigned.get("outcome")
if isinstance(outcome, str):
unsigned["outcome"] = ExecutorOutcome(outcome)
signable = {
**unsigned,
"outcome": (
unsigned["outcome"].value
if isinstance(unsigned.get("outcome"), ExecutorOutcome)
else unsigned.get("outcome")
),
}
signature = sign_ed25519(private_key, signable, domain=EXECUTOR_SIGNATURE_DOMAIN)
return ExecutorTerminalEvidenceV03(**unsigned, signature_hex=signature)
def sign_terminal_receipt_v03(
private_key: Ed25519PrivateKey,
*,
denied: bool,
**values: Any,
) -> TerminalReceiptV03:
"""Test/integration builder; production receipt keys remain remote."""
unsigned = dict(values)
unsigned.setdefault("schema", DENIED_RECEIPT_SCHEMA if denied else RELEASE_RECEIPT_SCHEMA)
unsigned.setdefault("effect_retry_authorized", False)
unsigned.setdefault("production_ready", False)
disposition = unsigned.get("disposition")
if isinstance(disposition, str):
unsigned["disposition"] = ReceiptDisposition(disposition)
signable = {
**unsigned,
"disposition": (
unsigned["disposition"].value
if isinstance(unsigned.get("disposition"), ReceiptDisposition)
else unsigned.get("disposition")
),
}
signature = sign_ed25519(private_key, signable, domain=RECEIPT_SIGNATURE_DOMAIN)
cls = DeniedReceiptV03 if denied else ReleaseReceiptV03
return cls(**unsigned, signature_hex=signature)
class LedgerClaimDisposition(StrEnum):
CLAIMED = "CLAIMED"
IN_FLIGHT = "IN_FLIGHT"
STALE_UNCERTAIN = "STALE_UNCERTAIN"
EVIDENCE_READY = "EVIDENCE_READY"
TERMINAL_REPLAY = "TERMINAL_REPLAY"
@dataclass(frozen=True, slots=True)
class LedgerClaimV03:
disposition: LedgerClaimDisposition
command_commitment: str
effect_id: str
request_nonce: str
dispatch: Mapping[str, Any]
receipt: Mapping[str, Any] | None = None
executor_evidence: Mapping[str, Any] | None = None
def public_dict(self) -> dict[str, Any]:
result = {
"schema": LEDGER_SCHEMA,
"disposition": self.disposition.value,
"command_commitment": self.command_commitment,
"effect_id": self.effect_id,
"request_nonce": self.request_nonce,
"dispatch": dict(self.dispatch),
"receipt": None if self.receipt is None else dict(self.receipt),
"executor_evidence": (
None if self.executor_evidence is None else dict(self.executor_evidence)
),
"effect_retry_authorized": False,
"production_ready": False,
}
assert_public_summary_safe(result)
return result
@runtime_checkable
class DurableTerminalLedgerV03(Protocol):
"""Durable ledger boundary supported by the non-production coordinator."""
production_ready: bool
def inspect(
self,
command: ReleaseCommandV03,
review: ReviewAuthorizationV03,
*,
verifier: ProductionReleaseVerifierV03,
) -> LedgerClaimV03 | None: ...
def claim(
self,
command: ReleaseCommandV03,
review: ReviewAuthorizationV03,
*,
verifier: ProductionReleaseVerifierV03,
claim_timeout_ms: int = 60_000,
) -> LedgerClaimV03: ...
def record_terminal(
self,
command: ReleaseCommandV03,
review: ReviewAuthorizationV03,
receipt: TerminalReceiptV03,
evidence: ExecutorTerminalEvidenceV03,
*,
verifier: ProductionReleaseVerifierV03,
) -> dict[str, Any]: ...
def record_executor_evidence(
self,
command: ReleaseCommandV03,
review: ReviewAuthorizationV03,
evidence: ExecutorTerminalEvidenceV03,
*,
verifier: ProductionReleaseVerifierV03,
) -> dict[str, Any]: ...
_LEDGER_TABLE_SQL: Final = """
CREATE TABLE release_terminal_v03 (
command_commitment TEXT PRIMARY KEY,
effect_id TEXT NOT NULL,
request_nonce TEXT NOT NULL,
dispatch_nonce TEXT NOT NULL,
command_json BLOB NOT NULL,
review_json BLOB NOT NULL,
dispatch_unsigned_json BLOB NOT NULL,
dispatch_json BLOB,
state TEXT NOT NULL CHECK(state IN ('PENDING_DISPATCH','CLAIMED','EVIDENCED','TERMINAL')),
claimed_at_ms INTEGER NOT NULL,
claim_expires_at_ms INTEGER NOT NULL,
receipt_json BLOB,
receipt_commitment TEXT,
executor_evidence_json BLOB,
executor_evidence_commitment TEXT
) STRICT
""".strip()
_LEDGER_EFFECT_INDEX_SQL: Final = (
"CREATE UNIQUE INDEX release_terminal_v03_effect_id_uq "
"ON release_terminal_v03(effect_id)"
)
_LEDGER_NONCE_INDEX_SQL: Final = (
"CREATE UNIQUE INDEX release_terminal_v03_request_nonce_uq "
"ON release_terminal_v03(request_nonce)"
)
_LEDGER_DISPATCH_INDEX_SQL: Final = (
"CREATE UNIQUE INDEX release_terminal_v03_dispatch_nonce_uq "
"ON release_terminal_v03(dispatch_nonce)"
)
def _normalized_sql(value: object) -> str:
if not isinstance(value, str):
return ""
return re.sub(r"\s+", " ", value.strip()).casefold()
class SQLiteTerminalLedgerV03:
"""Durable local reference ledger with atomic one-use effect claims."""
production_ready = False
def __init__(
self,
path: Path,
*,
dispatch_signer: DispatchClaimSignerV03,
trusted_now_ms: Callable[[], int] = _system_now_ms,
) -> None:
if not isinstance(path, Path) or not path.is_absolute() or str(path) == ":memory:":
raise ProductionReleaseBrokerError("durable_sqlite_path_required")
resolved = path.resolve()
if not resolved.parent.exists() or not resolved.parent.is_dir():
raise ProductionReleaseBrokerError("durable_sqlite_parent_required")
if not callable(trusted_now_ms):
raise ProductionReleaseBrokerError("trusted_clock_invalid")
if not isinstance(dispatch_signer, DispatchClaimSignerV03):
raise ProductionReleaseBrokerError("dispatch_claim_signer_required")
_identifier(dispatch_signer.signer_id, code="dispatch_signer_id_invalid")
_identifier(dispatch_signer.key_id, code="dispatch_signer_key_id_invalid")
self._path = resolved
self._trusted_now_ms = trusted_now_ms
self._dispatch_signer = dispatch_signer
self._initialize()
def _connect(self, *, validate_schema: bool = True) -> sqlite3.Connection:
connection = sqlite3.connect(str(self._path), timeout=30.0, isolation_level=None)
try:
journal_mode = connection.execute("PRAGMA journal_mode=WAL").fetchone()
connection.execute("PRAGMA synchronous=FULL")
connection.execute("PRAGMA foreign_keys=ON")
connection.execute("PRAGMA busy_timeout=30000")
synchronous = connection.execute("PRAGMA synchronous").fetchone()
foreign_keys = connection.execute("PRAGMA foreign_keys").fetchone()
busy_timeout = connection.execute("PRAGMA busy_timeout").fetchone()
if (
journal_mode is None
or str(journal_mode[0]).casefold() != "wal"
or synchronous != (2,)
or foreign_keys != (1,)
or busy_timeout != (30_000,)
):
raise ProductionReleaseBrokerError("terminal_ledger_durability_pragmas_invalid")
if validate_schema:
self._validate_schema(connection)
return connection
except BaseException:
connection.close()
raise
def _initialize(self) -> None:
connection = self._connect(validate_schema=False)
try:
connection.execute(_LEDGER_TABLE_SQL.replace("CREATE TABLE ", "CREATE TABLE IF NOT EXISTS ", 1))
table_row = connection.execute(
"SELECT sql FROM sqlite_master "
"WHERE type='table' AND name='release_terminal_v03'"
).fetchone()
if (
table_row is None
or _normalized_sql(table_row[0]) != _normalized_sql(_LEDGER_TABLE_SQL)
):
raise ProductionReleaseBrokerError("terminal_ledger_schema_invalid")
connection.execute(
_LEDGER_EFFECT_INDEX_SQL.replace(
"CREATE UNIQUE INDEX ", "CREATE UNIQUE INDEX IF NOT EXISTS ", 1
)
)
connection.execute(
_LEDGER_NONCE_INDEX_SQL.replace(
"CREATE UNIQUE INDEX ", "CREATE UNIQUE INDEX IF NOT EXISTS ", 1
)
)
connection.execute(
_LEDGER_DISPATCH_INDEX_SQL.replace(
"CREATE UNIQUE INDEX ", "CREATE UNIQUE INDEX IF NOT EXISTS ", 1
)
)
self._validate_schema(connection)
finally:
connection.close()
@staticmethod
def _validate_schema(connection: sqlite3.Connection) -> None:
table_row = connection.execute(
"SELECT sql FROM sqlite_master WHERE type='table' AND name='release_terminal_v03'"
).fetchone()
expected_indexes = {
"release_terminal_v03_effect_id_uq": _normalized_sql(_LEDGER_EFFECT_INDEX_SQL),
"release_terminal_v03_request_nonce_uq": _normalized_sql(_LEDGER_NONCE_INDEX_SQL),
"release_terminal_v03_dispatch_nonce_uq": _normalized_sql(
_LEDGER_DISPATCH_INDEX_SQL
),
}
actual_indexes = {
str(name): _normalized_sql(sql)
for name, sql in connection.execute(
"SELECT name, sql FROM sqlite_master "
"WHERE type='index' AND tbl_name='release_terminal_v03' AND sql IS NOT NULL"
).fetchall()
}
triggers = connection.execute(
"SELECT name FROM sqlite_master "
"WHERE type='trigger' AND tbl_name='release_terminal_v03'"
).fetchall()
quick_check = connection.execute("PRAGMA quick_check").fetchone()
if (
table_row is None
or _normalized_sql(table_row[0]) != _normalized_sql(_LEDGER_TABLE_SQL)
or actual_indexes != expected_indexes
or triggers
or quick_check != ("ok",)
):
raise ProductionReleaseBrokerError("terminal_ledger_schema_invalid")
def _now(self) -> int:
return _uint(self._trusted_now_ms(), code="trusted_time_invalid")
@staticmethod
def _command_bytes(command: ReleaseCommandV03) -> bytes:
if type(command) is not ReleaseCommandV03:
raise ProductionReleaseBrokerError("release_command_type_invalid")
return canonical_json_bytes(command.wire_dict())
@staticmethod
def _review_bytes(review: ReviewAuthorizationV03) -> bytes:
if type(review) is not ReviewAuthorizationV03:
raise ProductionReleaseBrokerError("review_authorization_type_invalid")
return canonical_json_bytes(review.wire_dict())
@staticmethod
def _stored_mapping(value: object, *, code: str) -> dict[str, Any]:
return _decode_wire_mapping(
SQLiteTerminalLedgerV03._blob_bytes(value, code=code),
code=code,
)
@staticmethod
def _blob_bytes(value: object, *, code: str) -> bytes:
if isinstance(value, bytes):
return value
if isinstance(value, bytearray | memoryview):
return bytes(value)
raise ProductionReleaseBrokerError(code)
@classmethod
def _unsigned_dispatch_from_blob(cls, value: object) -> dict[str, Any]:
payload = _exact_mapping(
_decode_wire_mapping(
cls._blob_bytes(value, code="stored_unsigned_dispatch_invalid"),
code="stored_unsigned_dispatch_invalid",
),
{
"schema", "command_commitment", "review_commitment", "effect_id",
"request_nonce", "dispatch_nonce", "claimed_at_ms",
"claim_expires_at_ms", "authority_id", "key_id",
},
code="stored_unsigned_dispatch_invalid",
)
return payload
def _claim_from_row(
self,
row: tuple[Any, ...],
command: ReleaseCommandV03,
review: ReviewAuthorizationV03,
*,
verifier: ProductionReleaseVerifierV03,
now: int,
) -> LedgerClaimV03:
(
effect_id,
nonce,
stored_dispatch_nonce,
stored_command,
stored_review,
state,
stored_claimed_at,
stored_expiry,
dispatch_json,
receipt_json,
evidence_json,
stored_receipt_commitment,
stored_evidence_commitment,
unsigned_dispatch_json,
) = row
if (
effect_id != command.effect_id
or nonce != command.request_nonce
or self._blob_bytes(stored_command, code="stored_command_invalid")
!= self._command_bytes(command)
or self._blob_bytes(stored_review, code="stored_review_invalid")
!= self._review_bytes(review)
):
raise ProductionReleaseBrokerError("stored_command_or_review_join_mismatch")
dispatch = decode_dispatch_claim_v03(
self._blob_bytes(dispatch_json, code="stored_dispatch_invalid")
)
if (
dispatch.command_commitment != command.commitment
or dispatch.review_commitment != review.commitment
or dispatch.effect_id != command.effect_id
or dispatch.request_nonce != command.request_nonce
or stored_dispatch_nonce != dispatch.dispatch_nonce
or _uint(stored_claimed_at, code="stored_claimed_at_invalid")
!= dispatch.claimed_at_ms
or _uint(stored_expiry, code="stored_claim_expiry_invalid")
!= dispatch.claim_expires_at_ms
):
raise ProductionReleaseBrokerError("stored_dispatch_join_mismatch")
verifier.verify_dispatch(command, review, dispatch)
if self._unsigned_dispatch_from_blob(unsigned_dispatch_json) != dispatch.unsigned_dict():
raise ProductionReleaseBrokerError("stored_unsigned_dispatch_join_invalid")
receipt_mapping: Mapping[str, Any] | None = None
evidence_mapping: Mapping[str, Any] | None = None
if state == "TERMINAL":
receipt_mapping = self._stored_mapping(
receipt_json, code="stored_receipt_invalid"
)
evidence_mapping = self._stored_mapping(
evidence_json, code="stored_executor_evidence_invalid"
)
receipt = decode_terminal_receipt_v03(
canonical_json_bytes(receipt_mapping)
)
evidence = decode_executor_evidence_v03(
canonical_json_bytes(evidence_mapping)
)
if (
stored_receipt_commitment != receipt.commitment
or stored_evidence_commitment != evidence.commitment
):
raise ProductionReleaseBrokerError("stored_terminal_commitment_mismatch")
verifier.verify_terminal(command, review, dispatch, receipt, evidence)
disposition = LedgerClaimDisposition.TERMINAL_REPLAY
elif state == "EVIDENCED":
if receipt_json is not None:
raise ProductionReleaseBrokerError("stored_evidenced_state_invalid")
evidence_mapping = self._stored_mapping(
evidence_json, code="stored_executor_evidence_invalid"
)
evidence = decode_executor_evidence_v03(
canonical_json_bytes(evidence_mapping)
)
if (
stored_receipt_commitment is not None
or stored_evidence_commitment != evidence.commitment
):
raise ProductionReleaseBrokerError("stored_evidence_commitment_mismatch")
verifier.verify_executor_evidence(command, review, dispatch, evidence)
disposition = LedgerClaimDisposition.EVIDENCE_READY
elif state == "CLAIMED" and now >= dispatch.claim_expires_at_ms:
if (
receipt_json is not None
or evidence_json is not None
or stored_receipt_commitment is not None
or stored_evidence_commitment is not None
):
raise ProductionReleaseBrokerError("stored_claimed_state_invalid")
disposition = LedgerClaimDisposition.STALE_UNCERTAIN
elif state == "CLAIMED":
if (
receipt_json is not None
or evidence_json is not None
or stored_receipt_commitment is not None
or stored_evidence_commitment is not None
):
raise ProductionReleaseBrokerError("stored_claimed_state_invalid")
disposition = LedgerClaimDisposition.IN_FLIGHT
else:
raise ProductionReleaseBrokerError("stored_claim_state_invalid")
return LedgerClaimV03(
disposition=disposition,
command_commitment=command.commitment,
effect_id=command.effect_id,
request_nonce=command.request_nonce,
dispatch=dispatch.wire_dict(),
receipt=receipt_mapping,
executor_evidence=evidence_mapping,
)
def inspect(
self,
command: ReleaseCommandV03,
review: ReviewAuthorizationV03,
*,
verifier: ProductionReleaseVerifierV03,
) -> LedgerClaimV03 | None:
"""Return only schema-checked and signature-authenticated state."""
if type(verifier) is not ProductionReleaseVerifierV03:
raise ProductionReleaseBrokerError("production_release_verifier_required")
verifier.verify_review(command, review, require_current=False)
connection = self._connect()
try:
row = connection.execute(
"SELECT effect_id, request_nonce, dispatch_nonce, command_json, "
"review_json, state, claimed_at_ms, claim_expires_at_ms, "
"dispatch_json, receipt_json, executor_evidence_json, "
"receipt_commitment, executor_evidence_commitment, "
"dispatch_unsigned_json "
"FROM release_terminal_v03 WHERE command_commitment = ?",
(command.commitment,),
).fetchone()
finally:
connection.close()
if row is None:
return None
if row[5] == "PENDING_DISPATCH":
if any(value is not None for value in row[8:13]):
raise ProductionReleaseBrokerError("stored_pending_dispatch_state_invalid")
return None
return self._claim_from_row(
row, command, review, verifier=verifier, now=self._now()
)
def claim(
self,
command: ReleaseCommandV03,
review: ReviewAuthorizationV03,
*,
verifier: ProductionReleaseVerifierV03,
claim_timeout_ms: int = 60_000,
) -> LedgerClaimV03:
if type(verifier) is not ProductionReleaseVerifierV03:
raise ProductionReleaseBrokerError("production_release_verifier_required")
timeout = _uint(claim_timeout_ms, code="claim_timeout_invalid")
if timeout == 0 or timeout > _MAX_COMMAND_LIFETIME_MS:
raise ProductionReleaseBrokerError("claim_timeout_invalid")
encoded_command = self._command_bytes(command)
encoded_review = self._review_bytes(review)
connection = self._connect()
try:
connection.execute("BEGIN IMMEDIATE")
now = self._now()
row = connection.execute(
"SELECT effect_id, request_nonce, dispatch_nonce, command_json, "
"review_json, state, claimed_at_ms, claim_expires_at_ms, "
"dispatch_json, receipt_json, executor_evidence_json, "
"receipt_commitment, executor_evidence_commitment, "
"dispatch_unsigned_json "
"FROM release_terminal_v03 WHERE command_commitment = ?",
(command.commitment,),
).fetchone()
if row is None:
# Both clocks and the signed review are rechecked only after
# the write lock is held, closing the lock-wait expiry race.
verifier.verify_review(command, review)
now = self._now()
if (
now < max(command.issued_at_ms, review.issued_at_ms) - _MAX_CLOCK_SKEW_MS
or now >= command.expires_at_ms
or now >= review.expires_at_ms
):
raise ProductionReleaseBrokerError("command_or_review_not_current")
claim_expiry = min(
command.expires_at_ms,
review.expires_at_ms,
now + timeout,
)
unsigned_dispatch = {
"schema": DISPATCH_SCHEMA,
"command_commitment": command.commitment,
"review_commitment": review.commitment,
"effect_id": command.effect_id,
"request_nonce": command.request_nonce,
"dispatch_nonce": secrets.token_hex(32),
"claimed_at_ms": now,
"claim_expires_at_ms": claim_expiry,
"authority_id": self._dispatch_signer.signer_id,
"key_id": self._dispatch_signer.key_id,
}
encoded_unsigned_dispatch = canonical_json_bytes(unsigned_dispatch)
try:
connection.execute(
"INSERT INTO release_terminal_v03 ("
"command_commitment,effect_id,request_nonce,dispatch_nonce,"
"command_json,review_json,dispatch_unsigned_json,dispatch_json,"
"state,claimed_at_ms,"
"claim_expires_at_ms,receipt_json,receipt_commitment,"
"executor_evidence_json,executor_evidence_commitment"
") VALUES (?, ?, ?, ?, ?, ?, ?, NULL, 'PENDING_DISPATCH', "
"?, ?, NULL, NULL, NULL, NULL)",
(
command.commitment,
command.effect_id,
command.request_nonce,
unsigned_dispatch["dispatch_nonce"],
encoded_command,
encoded_review,
encoded_unsigned_dispatch,
now,
claim_expiry,
),
)
except sqlite3.IntegrityError as exc:
raise ProductionReleaseBrokerError(
"effect_nonce_or_dispatch_reused"
) from exc
connection.execute("COMMIT")
elif row[5] == "PENDING_DISPATCH":
if (
row[0] != command.effect_id
or row[1] != command.request_nonce
or self._blob_bytes(row[3], code="stored_command_invalid")
!= encoded_command
or self._blob_bytes(row[4], code="stored_review_invalid")
!= encoded_review
or any(value is not None for value in row[8:13])
):
raise ProductionReleaseBrokerError("stored_pending_dispatch_state_invalid")
verifier.verify_review(command, review)
now = self._now()
unsigned_dispatch = self._unsigned_dispatch_from_blob(row[13])
if (
row[2] != unsigned_dispatch["dispatch_nonce"]
or _uint(row[6], code="stored_claimed_at_invalid")
!= unsigned_dispatch["claimed_at_ms"]
or _uint(row[7], code="stored_claim_expiry_invalid")
!= unsigned_dispatch["claim_expires_at_ms"]
or unsigned_dispatch["command_commitment"] != command.commitment
or unsigned_dispatch["review_commitment"] != review.commitment
or unsigned_dispatch["effect_id"] != command.effect_id
or unsigned_dispatch["request_nonce"] != command.request_nonce
):
raise ProductionReleaseBrokerError("stored_unsigned_dispatch_join_invalid")
if now >= unsigned_dispatch["claim_expires_at_ms"]:
# A PENDING reservation has never produced a signed dispatch,
# so executor transport was impossible. Renew it atomically
# with a new nonce. A late signer response for the old bytes is
# fenced by the exact dispatch_unsigned_json comparison used
# during finalization.
claim_expiry = min(
command.expires_at_ms,
review.expires_at_ms,
now + timeout,
)
unsigned_dispatch = {
"schema": DISPATCH_SCHEMA,
"command_commitment": command.commitment,
"review_commitment": review.commitment,
"effect_id": command.effect_id,
"request_nonce": command.request_nonce,
"dispatch_nonce": secrets.token_hex(32),
"claimed_at_ms": now,
"claim_expires_at_ms": claim_expiry,
"authority_id": self._dispatch_signer.signer_id,
"key_id": self._dispatch_signer.key_id,
}
encoded_unsigned_dispatch = canonical_json_bytes(unsigned_dispatch)
updated = connection.execute(
"UPDATE release_terminal_v03 SET dispatch_nonce=?, "
"dispatch_unsigned_json=?, claimed_at_ms=?, claim_expires_at_ms=? "
"WHERE command_commitment=? AND state='PENDING_DISPATCH' "
"AND dispatch_unsigned_json=?",
(
unsigned_dispatch["dispatch_nonce"],
encoded_unsigned_dispatch,
now,
claim_expiry,
command.commitment,
self._blob_bytes(
row[13], code="stored_unsigned_dispatch_invalid"
),
),
)
if updated.rowcount != 1:
raise ProductionReleaseBrokerError(
"pending_dispatch_renewal_race"
)
else:
encoded_unsigned_dispatch = canonical_json_bytes(unsigned_dispatch)
connection.execute("COMMIT")
else:
verifier.verify_review(command, review, require_current=False)
claim = self._claim_from_row(
row, command, review, verifier=verifier, now=now
)
connection.execute("COMMIT")
return claim
except BaseException:
if connection.in_transaction:
connection.execute("ROLLBACK")
raise
finally:
connection.close()
# The potentially remote signer is called only after the SQLite write
# transaction is closed. The PENDING_DISPATCH reservation is durable
# and retryable without ever authorizing executor dispatch.
try:
signed_dispatch_wire = self._dispatch_signer.sign_dispatch(
encoded_unsigned_dispatch,
deadline_at_ms=_uint(
unsigned_dispatch["claim_expires_at_ms"],
code="dispatch_signer_deadline_invalid",
),
)
if type(signed_dispatch_wire) is not bytes:
raise ProductionReleaseBrokerError("dispatch_signer_wire_type_invalid")
dispatch = decode_dispatch_claim_v03(signed_dispatch_wire)
except BaseException:
raise ProductionReleaseBrokerError(
"dispatch_signer_unavailable_claim_reserved"
) from None
if dispatch.unsigned_dict() != unsigned_dispatch:
raise ProductionReleaseBrokerError("dispatch_signer_join_invalid")
verifier.verify_dispatch_current(command, review, dispatch)
encoded_dispatch = canonical_json_bytes(dispatch.wire_dict())
connection = self._connect()
try:
connection.execute("BEGIN IMMEDIATE")
row = connection.execute(
"SELECT state, dispatch_unsigned_json, dispatch_json FROM "
"release_terminal_v03 WHERE command_commitment=?",
(command.commitment,),
).fetchone()
if row is None or self._blob_bytes(
row[1], code="stored_unsigned_dispatch_invalid"
) != encoded_unsigned_dispatch:
raise ProductionReleaseBrokerError("dispatch_reservation_missing")
if row[0] == "PENDING_DISPATCH":
updated = connection.execute(
"UPDATE release_terminal_v03 SET state='CLAIMED', dispatch_json=? "
"WHERE command_commitment=? AND state='PENDING_DISPATCH'",
(encoded_dispatch, command.commitment),
)
if updated.rowcount != 1:
raise ProductionReleaseBrokerError("dispatch_finalize_race")
connection.execute("COMMIT")
return LedgerClaimV03(
disposition=LedgerClaimDisposition.CLAIMED,
command_commitment=command.commitment,
effect_id=command.effect_id,
request_nonce=command.request_nonce,
dispatch=dispatch.wire_dict(),
)
if self._blob_bytes(
row[2], code="stored_dispatch_invalid"
) != encoded_dispatch:
raise ProductionReleaseBrokerError("dispatch_finalize_conflict")
connection.execute("COMMIT")
except BaseException:
if connection.in_transaction:
connection.execute("ROLLBACK")
raise
finally:
connection.close()
existing = self.inspect(command, review, verifier=verifier)
if existing is None:
raise ProductionReleaseBrokerError("dispatch_finalize_state_invalid")
return existing
def record_executor_evidence(
self,
command: ReleaseCommandV03,
review: ReviewAuthorizationV03,
evidence: ExecutorTerminalEvidenceV03,
*,
verifier: ProductionReleaseVerifierV03,
) -> dict[str, Any]:
"""Persist authentic executor evidence before any receipt-signing call."""
if type(verifier) is not ProductionReleaseVerifierV03:
raise ProductionReleaseBrokerError("production_release_verifier_required")
if type(evidence) is not ExecutorTerminalEvidenceV03:
raise ProductionReleaseBrokerError("exact_executor_evidence_required")
evidence_bytes = canonical_json_bytes(evidence.wire_dict())
command_bytes = self._command_bytes(command)
review_bytes = self._review_bytes(review)
connection = self._connect()
try:
connection.execute("BEGIN IMMEDIATE")
row = connection.execute(
"SELECT command_json, review_json, dispatch_json, state, "
"executor_evidence_json, executor_evidence_commitment "
"FROM release_terminal_v03 WHERE command_commitment = ?",
(command.commitment,),
).fetchone()
if (
row is None
or self._blob_bytes(row[0], code="stored_command_invalid")
!= command_bytes
or self._blob_bytes(row[1], code="stored_review_invalid")
!= review_bytes
):
raise ProductionReleaseBrokerError("release_claim_required")
dispatch = decode_dispatch_claim_v03(
self._blob_bytes(row[2], code="stored_dispatch_invalid")
)
verifier.verify_executor_evidence(command, review, dispatch, evidence)
if row[3] in {"EVIDENCED", "TERMINAL"}:
if (
self._blob_bytes(
row[4], code="stored_executor_evidence_invalid"
)
!= evidence_bytes
or row[5] != evidence.commitment
):
raise ProductionReleaseBrokerError("executor_evidence_conflict")
connection.execute("COMMIT")
return evidence.wire_dict()
if row[3] != "CLAIMED":
raise ProductionReleaseBrokerError("release_claim_state_invalid")
updated = connection.execute(
"UPDATE release_terminal_v03 SET state='EVIDENCED', "
"executor_evidence_json=?, executor_evidence_commitment=? "
"WHERE command_commitment=? AND state='CLAIMED'",
(evidence_bytes, evidence.commitment, command.commitment),
)
if updated.rowcount != 1:
raise ProductionReleaseBrokerError("executor_evidence_record_race")
connection.execute("COMMIT")
return evidence.wire_dict()
except BaseException:
if connection.in_transaction:
connection.execute("ROLLBACK")
raise
finally:
connection.close()
def record_terminal(
self,
command: ReleaseCommandV03,
review: ReviewAuthorizationV03,
receipt: TerminalReceiptV03,
evidence: ExecutorTerminalEvidenceV03,
*,
verifier: ProductionReleaseVerifierV03,
) -> dict[str, Any]:
if type(verifier) is not ProductionReleaseVerifierV03:
raise ProductionReleaseBrokerError("production_release_verifier_required")
if (
type(receipt) not in {ReleaseReceiptV03, DeniedReceiptV03}
or type(evidence) is not ExecutorTerminalEvidenceV03
):
raise ProductionReleaseBrokerError("exact_terminal_chain_required")
receipt_bytes = canonical_json_bytes(receipt.wire_dict())
evidence_bytes = canonical_json_bytes(evidence.wire_dict())
command_bytes = self._command_bytes(command)
review_bytes = self._review_bytes(review)
connection = self._connect()
try:
connection.execute("BEGIN IMMEDIATE")
row = connection.execute(
"SELECT command_json, review_json, dispatch_json, state, receipt_json, "
"receipt_commitment, executor_evidence_json, executor_evidence_commitment "
"FROM release_terminal_v03 WHERE command_commitment = ?",
(command.commitment,),
).fetchone()
if (
row is None
or self._blob_bytes(row[0], code="stored_command_invalid")
!= command_bytes
or self._blob_bytes(row[1], code="stored_review_invalid")
!= review_bytes
):
raise ProductionReleaseBrokerError("release_claim_required")
dispatch = decode_dispatch_claim_v03(
self._blob_bytes(row[2], code="stored_dispatch_invalid")
)
verifier.verify_terminal(command, review, dispatch, receipt, evidence)
if row[3] == "TERMINAL":
if (
self._blob_bytes(row[4], code="stored_receipt_invalid")
!= receipt_bytes
or row[5] != receipt.commitment
or self._blob_bytes(
row[6], code="stored_executor_evidence_invalid"
)
!= evidence_bytes
or row[7] != evidence.commitment
):
raise ProductionReleaseBrokerError("terminal_receipt_conflict")
connection.execute("COMMIT")
return receipt.wire_dict()
if (
row[3] != "EVIDENCED"
or self._blob_bytes(
row[6], code="stored_executor_evidence_invalid"
)
!= evidence_bytes
or row[7] != evidence.commitment
):
raise ProductionReleaseBrokerError("recorded_executor_evidence_required")
updated = connection.execute(
"UPDATE release_terminal_v03 SET state='TERMINAL', receipt_json=?, "
"receipt_commitment=? "
"WHERE command_commitment=? AND state='EVIDENCED'",
(
receipt_bytes,
receipt.commitment,
command.commitment,
),
)
if updated.rowcount != 1:
raise ProductionReleaseBrokerError("terminal_receipt_record_race")
connection.execute("COMMIT")
return receipt.wire_dict()
except BaseException:
if connection.in_transaction:
connection.execute("ROLLBACK")
raise
finally:
connection.close()
def read_terminal(
self,
command: ReleaseCommandV03,
review: ReviewAuthorizationV03,
*,
verifier: ProductionReleaseVerifierV03,
) -> dict[str, Any] | None:
claim = self.inspect(command, review, verifier=verifier)
if claim is None or claim.disposition is not LedgerClaimDisposition.TERMINAL_REPLAY:
return None
if claim.receipt is None or claim.executor_evidence is None:
raise ProductionReleaseBrokerError("stored_terminal_chain_invalid")
decoded = dict(claim.receipt)
assert_public_summary_safe(decoded)
return decoded
class ProductionReleaseBrokerV03:
"""Reference coordinator for signed out-of-process execution.
The coordinator exchanges only bounded canonical metadata bytes with its
executor and receipt-signer adapters. A real deployment must prove those
adapters are remote and independently administered; this Python contract
cannot establish that property by structural typing alone.
The checked-in coordinator and SQLite ledger therefore remain explicitly
non-production until that live composition is attested.
"""
production_ready = False
def __init__(
self,
*,
verifier: ProductionReleaseVerifierV03,
ledger: DurableTerminalLedgerV03,
executor: OutOfProcessReleaseExecutorV03,
receipt_signer: TerminalReceiptSignerV03,
claim_timeout_ms: int = 60_000,
) -> None:
if type(verifier) is not ProductionReleaseVerifierV03:
raise ProductionReleaseBrokerError("production_release_verifier_required")
if not isinstance(ledger, DurableTerminalLedgerV03):
raise ProductionReleaseBrokerError("durable_terminal_ledger_required")
if not isinstance(executor, OutOfProcessReleaseExecutorV03):
raise ProductionReleaseBrokerError("out_of_process_executor_required")
if not isinstance(receipt_signer, TerminalReceiptSignerV03):
raise ProductionReleaseBrokerError("terminal_receipt_signer_required")
identities = verifier.authority_ids
if (
executor.executor_id != identities["executor"]
or receipt_signer.signer_id != identities["receipt"]
or cast(object, executor) is cast(object, receipt_signer)
):
raise ProductionReleaseBrokerError("broker_adapter_authority_join_invalid")
timeout = _uint(claim_timeout_ms, code="claim_timeout_invalid")
if timeout == 0 or timeout > _MAX_COMMAND_LIFETIME_MS:
raise ProductionReleaseBrokerError("claim_timeout_invalid")
self._verifier = verifier
self._ledger = ledger
self._executor = executor
self._receipt_signer = receipt_signer
self._claim_timeout_ms = timeout
def execute_release(
self,
command: ReleaseCommandV03,
review: ReviewAuthorizationV03,
) -> dict[str, Any]:
"""Execute or recover exactly one metadata-bound effect claim."""
if type(command) is not ReleaseCommandV03 or type(review) is not ReviewAuthorizationV03:
raise ProductionReleaseBrokerError("exact_release_command_and_review_required")
existing = self._ledger.inspect(
command,
review,
verifier=self._verifier,
)
if existing is None:
# Authorization is validated before the first durable claim so an
# unauthenticated caller cannot burn an effect id or nonce.
self._verifier.verify_review(command, review)
claim = self._ledger.claim(
command,
review,
verifier=self._verifier,
claim_timeout_ms=self._claim_timeout_ms,
)
else:
claim = existing
if type(claim) is not LedgerClaimV03:
raise ProductionReleaseBrokerError("exact_ledger_claim_required")
if claim.disposition is LedgerClaimDisposition.TERMINAL_REPLAY:
if claim.receipt is None or claim.executor_evidence is None:
raise ProductionReleaseBrokerError("stored_terminal_chain_invalid")
result = dict(claim.receipt)
receipt = decode_terminal_receipt_v03(canonical_json_bytes(result))
evidence = decode_executor_evidence_v03(
canonical_json_bytes(claim.executor_evidence)
)
dispatch = DispatchClaimV03.from_wire(claim.dispatch)
self._verifier.verify_terminal(
command, review, dispatch, receipt, evidence
)
assert_public_summary_safe(result)
return result
if claim.disposition is LedgerClaimDisposition.IN_FLIGHT:
raise ProductionReleaseBrokerError("release_claim_in_flight")
if claim.disposition is LedgerClaimDisposition.STALE_UNCERTAIN:
self._verifier.verify_review(command, review, require_current=False)
# An expired lease is not proof that the remote effect failed. It
# remains durably unresolved and can never authorize a retry or a
# fabricated terminal denial.
raise ProductionReleaseBrokerError(
"release_claim_stale_uncertain_reconciliation_required"
)
dispatch = DispatchClaimV03.from_wire(claim.dispatch)
command_wire = canonical_json_bytes(command.wire_dict())
review_wire = canonical_json_bytes(review.wire_dict())
if claim.disposition is LedgerClaimDisposition.EVIDENCE_READY:
if claim.executor_evidence is None:
raise ProductionReleaseBrokerError("stored_executor_evidence_invalid")
evidence = decode_executor_evidence_v03(
canonical_json_bytes(claim.executor_evidence)
)
self._verifier.verify_executor_evidence(
command, review, dispatch, evidence
)
elif claim.disposition is LedgerClaimDisposition.CLAIMED:
# Recheck authorization immediately before crossing the transport.
self._verifier.verify_dispatch_current(command, review, dispatch)
dispatch_wire = canonical_json_bytes(dispatch.wire_dict())
try:
evidence_wire = self._executor.execute(
command_wire,
review_wire,
dispatch_wire,
)
if type(evidence_wire) is not bytes:
raise ProductionReleaseBrokerError("executor_wire_type_invalid")
evidence = decode_executor_evidence_v03(evidence_wire)
except BaseException:
# The durable CLAIMED row is intentionally retained. Retrying an
# effect after an uncertain remote failure is forbidden.
raise ProductionReleaseBrokerError(
"executor_unavailable_or_uncertain_claim_retained"
) from None
self._verifier.verify_executor_evidence(
command, review, dispatch, evidence
)
self._ledger.record_executor_evidence(
command,
review,
evidence,
verifier=self._verifier,
)
else:
raise ProductionReleaseBrokerError("release_claim_state_invalid")
signed_receipt_wire: bytes | None = None
try:
candidate = self._receipt_signer.sign_terminal(
command_wire,
review_wire,
canonical_json_bytes(evidence.wire_dict()),
idempotency_key=evidence.commitment,
)
if type(candidate) is not bytes:
raise ProductionReleaseBrokerError("terminal_receipt_wire_type_invalid")
signed_receipt_wire = candidate
except BaseException:
# The signing service may have committed before its response was
# lost. The mandatory idempotent readback below is authoritative.
signed_receipt_wire = None
try:
receipt_wire = self._receipt_signer.read_terminal(
idempotency_key=evidence.commitment
)
if type(receipt_wire) is not bytes:
raise ProductionReleaseBrokerError("terminal_receipt_readback_missing")
if signed_receipt_wire is not None and signed_receipt_wire != receipt_wire:
raise ProductionReleaseBrokerError("terminal_receipt_readback_mismatch")
receipt = decode_terminal_receipt_v03(receipt_wire)
except BaseException:
raise ProductionReleaseBrokerError(
"terminal_signer_unavailable_evidence_retained"
) from None
if type(receipt) not in {ReleaseReceiptV03, DeniedReceiptV03}:
raise ProductionReleaseBrokerError("terminal_receipt_type_invalid")
self._verifier.verify_terminal(
command, review, dispatch, receipt, evidence
)
return self._ledger.record_terminal(
command,
review,
receipt,
evidence,
verifier=self._verifier,
)
__all__ = [
"COMMAND_SCHEMA",
"DENIED_RECEIPT_SCHEMA",
"DISPATCH_SCHEMA",
"EXECUTOR_EVIDENCE_SCHEMA",
"LEDGER_SCHEMA",
"RELEASE_RECEIPT_SCHEMA",
"REVIEW_SCHEMA",
"AuthorityBindingV03",
"DeniedReceiptV03",
"DispatchClaimV03",
"DispatchClaimSignerV03",
"DurableTerminalLedgerV03",
"ExecutorOutcome",
"ExecutorTerminalEvidenceV03",
"LedgerClaimDisposition",
"LedgerClaimV03",
"OutOfProcessReleaseExecutorV03",
"ProductionReleaseBrokerError",
"ProductionReleaseBrokerV03",
"ProductionReleaseVerifierV03",
"ReceiptDisposition",
"ReleaseCommandV03",
"ReleaseReceiptV03",
"ReviewAuthorizationV03",
"SQLiteTerminalLedgerV03",
"TerminalReceiptSignerV03",
"TerminalReceiptV03",
"decode_executor_evidence_v03",
"decode_dispatch_claim_v03",
"decode_release_command_v03",
"decode_review_authorization_v03",
"decode_terminal_receipt_v03",
"sign_executor_evidence_v03",
"sign_dispatch_claim_v03",
"sign_review_authorization_v03",
"sign_terminal_receipt_v03",
"terminal_receipt_id_v03",
]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973"""Proposal-only self-coder forge for local development.
The forge has no filesystem, subprocess, import, compile, execution, or patch
application path. It seals an exact source request and unified-diff candidate
through :class:`LocalOSProtectionBoundary`, retaining the admitted HNC carrier
only behind an opaque handle. Rejected material follows the boundary's
metadata-only quarantine path.
Promotion is permanently HOLD in this local implementation. The checked-in
Magic Star and custody components are non-production, so neither they nor an
injected applier are called. A future production release implementation must
define a separately reviewed trust and transaction boundary; it cannot be
unlocked by a self-attested local receipt.
This is explicitly an in-memory, local-development design. It is not a
durable proposal ledger, production HSM/sandbox, independent review service,
or proof that caller-supplied adviser metadata is externally authentic.
"""
from __future__ import annotations
import re
import secrets
import threading
from collections.abc import Mapping
from dataclasses import dataclass, field
from datetime import datetime
from enum import StrEnum
from typing import Any, Final, Protocol, TypeAlias
from .audit import assert_public_summary_safe
from .crypto import canonical_json_bytes, decode_canonical_json, domain_hash, sha256_hex
from .os_protection import (
AdmittedHNC,
LocalOSProtectionBoundary,
OpaqueHNCHandle,
OSProtectionError,
QuarantinedHNC,
)
from .schema import (
SchemaError,
format_timestamp,
freeze_mapping,
parse_timestamp,
require_exact_keys,
require_int,
require_nonblank,
require_sha256,
thaw_json,
)
from .star_custody_v02 import (
LocalDevelopmentStarCustodyV02,
)
PROPOSAL_FORGE_SCHEMA: Final = "aureon.plumber.proposal-forge.v0"
PROPOSAL_FORGE_PREFLIGHT_SCHEMA: Final = "aureon.plumber.proposal-forge-preflight.v0"
PROPOSAL_PURPOSE: Final = "aureon.plumber.self-coder.proposal.v0"
AUTHORSHIP_STATEMENT: Final = (
"Aureon proposal generation with OpenAI adviser/reviewer assistance; "
"this record makes no ownership claim."
)
_PROPOSAL_PAYLOAD_SCHEMA: Final = "aureon.plumber.proposal-payload.v0"
_PROPOSAL_AAD_SCHEMA: Final = "aureon.plumber.proposal-aad.v0"
_PROPOSAL_SOURCE_ID: Final = "aureon.autonomous.internal-self-coder"
_PROPOSAL_INGRESS_KIND: Final = "application/vnd.aureon.unified-diff-proposal+json"
_PROPOSAL_GENERATOR: Final = "Aureon"
_OPENAI_ORGANIZATION: Final = "OpenAI"
_OPENAI_ROLE: Final = "adviser_and_reviewer"
_OWNERSHIP_CLAIM: Final = "none"
_METADATA_VERIFICATION: Final = "caller_supplied_receipt_commitment_not_independently_verified"
_MAX_DIFF_BYTES: Final = 128 * 1024
_MAX_REQUEST_BYTES: Final = 8 * 1024
_MAX_PROVENANCE_BYTES: Final = 128 * 1024
_MAX_ID_BYTES: Final = 512
_MAX_DIFF_FILES: Final = 8
_MAX_DIFF_HUNKS: Final = 128
_MAX_DIFF_LINE_BYTES: Final = 16 * 1024
_GIT_COMMIT_RE: Final = re.compile(r"^(?:[0-9a-f]{40}|[0-9a-f]{64})$")
_DESCRIPTOR_FIELDS: Final = {
"schema",
"forge_id",
"proposal_id",
"source_request_sha256",
"source_request_size_bytes",
"model_id",
"adviser_organization",
"adviser_id",
"reviewer_id",
"adviser_evidence_sha256",
"provenance_sha256",
"base_commit",
"diff_sha256",
"diff_size_bytes",
"proposal_generator",
"openai_role",
"ownership_claim",
"authorship_statement",
"metadata_verification",
"proposal_commitment",
}
class ProposalForgeError(ValueError):
"""Stable proposal-forge contract error with no rejected value in text."""
def __init__(self, code: str) -> None:
self.code = str(code)
super().__init__(self.code)
class PromotionDisposition(StrEnum):
HOLD = "HOLD"
def _bounded_text(value: object, *, field_name: str, maximum_bytes: int) -> str:
try:
text = require_nonblank(value, field=field_name, max_length=maximum_bytes)
encoded = text.encode("utf-8", errors="strict")
except (SchemaError, UnicodeEncodeError) as exc:
raise ProposalForgeError(f"{field_name}_invalid") from exc
if len(encoded) > maximum_bytes:
raise ProposalForgeError(f"{field_name}_invalid")
return text
def _base_commit(value: object) -> str:
if not isinstance(value, str) or _GIT_COMMIT_RE.fullmatch(value) is None:
raise ProposalForgeError("base_commit_invalid")
return value
def _canonical_mapping(
value: object,
*,
field_name: str,
maximum_bytes: int,
) -> tuple[dict[str, Any], bytes]:
if not isinstance(value, Mapping):
raise ProposalForgeError(f"{field_name}_invalid")
try:
encoded = canonical_json_bytes(dict(value))
if len(encoded) > maximum_bytes:
raise ProposalForgeError(f"{field_name}_invalid")
decoded = decode_canonical_json(encoded, require_mapping=True, max_bytes=maximum_bytes)
except BaseException as exc:
if isinstance(exc, ProposalForgeError):
raise
raise ProposalForgeError(f"{field_name}_invalid") from exc
if not isinstance(decoded, dict): # pragma: no cover - required by decoder
raise ProposalForgeError(f"{field_name}_invalid")
return decoded, encoded
def _safe_diff_path(value: str, *, expected_prefix: str) -> str | None:
raw = value.split("\t", 1)[0].strip()
if raw == "/dev/null":
return raw
if (
not raw.startswith(expected_prefix)
or "\\" in raw
or any(character.isspace() or ord(character) < 32 or ord(character) == 127 for character in raw)
):
return None
relative = raw[len(expected_prefix) :]
parts = relative.split("/")
if (
not relative
or len(relative.encode("utf-8", errors="strict")) > _MAX_ID_BYTES
or any(part in {"", ".", ".."} for part in parts)
or any(":" in part for part in parts)
):
return None
return relative
def _diff_contract_valid(diff: str, diff_bytes: bytes) -> bool:
if (
not diff_bytes
or len(diff_bytes) > _MAX_DIFF_BYTES
or "\x00" in diff
or "GIT binary patch" in diff
):
return False
lines = diff.splitlines()
try:
if any(len(line.encode("utf-8", errors="strict")) > _MAX_DIFF_LINE_BYTES for line in lines):
return False
except UnicodeEncodeError:
return False
if any(
line.startswith(("rename from ", "rename to ", "copy from ", "copy to "))
for line in lines
):
return False
old_headers = [line[4:] for line in lines if line.startswith("--- ")]
new_headers = [line[4:] for line in lines if line.startswith("+++ ")]
hunk_count = sum(line.startswith("@@") for line in lines)
if (
not old_headers
or len(old_headers) != len(new_headers)
or len(old_headers) > _MAX_DIFF_FILES
or not 1 <= hunk_count <= _MAX_DIFF_HUNKS
):
return False
for old_header, new_header in zip(old_headers, new_headers, strict=True):
old_path = _safe_diff_path(old_header, expected_prefix="a/")
new_path = _safe_diff_path(new_header, expected_prefix="b/")
if old_path is None or new_path is None:
return False
if old_path == "/dev/null" and new_path == "/dev/null":
return False
if old_path != "/dev/null" and new_path != "/dev/null" and old_path != new_path:
return False
for line in lines:
if not line.startswith("diff --git "):
continue
fields = line.split()
if len(fields) != 4:
return False
old_path = _safe_diff_path(fields[2], expected_prefix="a/")
new_path = _safe_diff_path(fields[3], expected_prefix="b/")
if old_path is None or new_path is None or old_path != new_path:
return False
return True
def _descriptor_core(descriptor: Mapping[str, Any]) -> dict[str, Any]:
return {
key: descriptor[key]
for key in _DESCRIPTOR_FIELDS
if key not in {"proposal_id", "proposal_commitment"}
}
def _validate_descriptor(value: Mapping[str, Any]) -> dict[str, Any]:
parsed = require_exact_keys(value, _DESCRIPTOR_FIELDS, field="proposal_descriptor")
if parsed["schema"] != PROPOSAL_FORGE_SCHEMA:
raise ProposalForgeError("proposal_descriptor_schema_invalid")
for name in ("forge_id", "proposal_id", "model_id", "adviser_id", "reviewer_id"):
_bounded_text(parsed[name], field_name=name, maximum_bytes=_MAX_ID_BYTES)
if (
parsed["adviser_organization"] != _OPENAI_ORGANIZATION
or parsed["proposal_generator"] != _PROPOSAL_GENERATOR
or parsed["openai_role"] != _OPENAI_ROLE
or parsed["ownership_claim"] != _OWNERSHIP_CLAIM
or parsed["authorship_statement"] != AUTHORSHIP_STATEMENT
or parsed["metadata_verification"] != _METADATA_VERIFICATION
):
raise ProposalForgeError("proposal_authorship_invalid")
if not str(parsed["model_id"]).startswith(("aureon-local:", "ollama:")):
raise ProposalForgeError("aureon_generator_model_id_invalid")
_base_commit(parsed["base_commit"])
for name in (
"source_request_sha256",
"adviser_evidence_sha256",
"provenance_sha256",
"diff_sha256",
"proposal_commitment",
):
require_sha256(parsed[name], field=name)
require_int(parsed["source_request_size_bytes"], field="source_request_size_bytes", minimum=1)
require_int(parsed["diff_size_bytes"], field="diff_size_bytes", minimum=1)
expected = domain_hash("aureon.plumber.proposal.v0", _descriptor_core(parsed))
if parsed["proposal_commitment"] != expected:
raise ProposalForgeError("proposal_commitment_invalid")
expected_id = f"proposal-{expected[:32]}"
if parsed["proposal_id"] != expected_id:
raise ProposalForgeError("proposal_id_invalid")
return parsed
def _proposal_handle_commitment(
*,
forge_id: str,
proposal_id: str,
proposal_commitment: str,
os_handle_commitment: str,
token: str,
) -> str:
return domain_hash(
"aureon.plumber.opaque-proposal-handle.v0",
{
"forge_id": forge_id,
"proposal_id": proposal_id,
"proposal_commitment": proposal_commitment,
"os_handle_commitment": os_handle_commitment,
"token": token,
},
)
@dataclass(frozen=True, slots=True)
class OpaqueProposalHandle:
"""One-use proposal reference; no request, diff, HNC carrier, or key."""
descriptor: Mapping[str, Any]
os_handle_commitment: str
token: str = field(repr=False)
handle_commitment: str
def __post_init__(self) -> None:
parsed = _validate_descriptor(self.descriptor)
object.__setattr__(
self,
"descriptor",
freeze_mapping(parsed, field="proposal_descriptor"),
)
require_sha256(self.os_handle_commitment, field="os_handle_commitment")
require_sha256(self.handle_commitment, field="handle_commitment")
if not isinstance(self.token, str) or not self.token:
raise ProposalForgeError("proposal_handle_token_invalid")
expected = _proposal_handle_commitment(
forge_id=self.forge_id,
proposal_id=self.proposal_id,
proposal_commitment=self.proposal_commitment,
os_handle_commitment=self.os_handle_commitment,
token=self.token,
)
if self.handle_commitment != expected:
raise ProposalForgeError("proposal_handle_commitment_invalid")
@classmethod
def issue(
cls,
*,
descriptor: Mapping[str, Any],
os_handle: OpaqueHNCHandle,
) -> OpaqueProposalHandle:
parsed = _validate_descriptor(descriptor)
token = secrets.token_urlsafe(32)
return cls(
descriptor=parsed,
os_handle_commitment=os_handle.handle_commitment,
token=token,
handle_commitment=_proposal_handle_commitment(
forge_id=parsed["forge_id"],
proposal_id=parsed["proposal_id"],
proposal_commitment=parsed["proposal_commitment"],
os_handle_commitment=os_handle.handle_commitment,
token=token,
),
)
@property
def forge_id(self) -> str:
return str(self.descriptor["forge_id"])
@property
def proposal_id(self) -> str:
return str(self.descriptor["proposal_id"])
@property
def proposal_commitment(self) -> str:
return str(self.descriptor["proposal_commitment"])
def public_summary(self) -> dict[str, Any]:
summary = {
"schema": PROPOSAL_FORGE_SCHEMA,
"descriptor": thaw_json(self.descriptor),
"os_handle_commitment": self.os_handle_commitment,
"handle_commitment": self.handle_commitment,
"promotion_disposition": str(PromotionDisposition.HOLD),
"promotion_authority": "none_until_reviewed_magic_star_final_applier",
"raw_request_returned": False,
"raw_diff_returned": False,
"local_development_only": True,
"production_ready": False,
}
assert_public_summary_safe(summary)
return summary
@dataclass(frozen=True, slots=True)
class QuarantinedProposal:
descriptor: Mapping[str, Any]
quarantine: QuarantinedHNC
def __post_init__(self) -> None:
parsed = _validate_descriptor(self.descriptor)
object.__setattr__(
self,
"descriptor",
freeze_mapping(parsed, field="proposal_descriptor"),
)
if not isinstance(self.quarantine, QuarantinedHNC):
raise ProposalForgeError("proposal_quarantine_invalid")
def public_summary(self) -> dict[str, Any]:
summary = {
"schema": PROPOSAL_FORGE_SCHEMA,
"descriptor": thaw_json(self.descriptor),
"outcome": "QUARANTINED_PROPOSAL",
"promotion_disposition": str(PromotionDisposition.HOLD),
"quarantine": self.quarantine.public_summary(),
"raw_request_returned": False,
"raw_diff_returned": False,
"local_development_only": True,
"production_ready": False,
}
assert_public_summary_safe(summary)
return summary
ProposalForgeOutcome: TypeAlias = OpaqueProposalHandle | QuarantinedProposal
@dataclass(frozen=True, slots=True)
class ProposalReview:
proposal_commitment: str
base_commit: str
diff_sha256: str
decision: str
reviewer_organization: str
reviewer_id: str
reviewer_role: str
review_receipt_sha256: str
reviewed_at: str
review_commitment: str
def __post_init__(self) -> None:
for name in (
"proposal_commitment",
"diff_sha256",
"review_receipt_sha256",
"review_commitment",
):
require_sha256(getattr(self, name), field=name)
_base_commit(self.base_commit)
if self.decision not in {"APPROVE", "HOLD", "REJECT"}:
raise ProposalForgeError("review_decision_invalid")
for name in ("reviewer_organization", "reviewer_id", "reviewer_role"):
_bounded_text(getattr(self, name), field_name=name, maximum_bytes=_MAX_ID_BYTES)
parse_timestamp(self.reviewed_at, field="reviewed_at")
if self.review_commitment != domain_hash(
"aureon.plumber.proposal-review.v0",
self.commitment_payload(),
):
raise ProposalForgeError("review_commitment_invalid")
@classmethod
def build(
cls,
*,
proposal_commitment: str,
base_commit: str,
diff_sha256: str,
decision: str,
reviewer_organization: str,
reviewer_id: str,
reviewer_role: str,
review_receipt_sha256: str,
reviewed_at: datetime,
) -> ProposalReview:
values = {
"proposal_commitment": proposal_commitment,
"base_commit": base_commit,
"diff_sha256": diff_sha256,
"decision": decision,
"reviewer_organization": reviewer_organization,
"reviewer_id": reviewer_id,
"reviewer_role": reviewer_role,
"review_receipt_sha256": review_receipt_sha256,
"reviewed_at": format_timestamp(reviewed_at),
}
return cls(
**values,
review_commitment=domain_hash(
"aureon.plumber.proposal-review.v0",
values,
),
)
def commitment_payload(self) -> dict[str, Any]:
return {
"proposal_commitment": self.proposal_commitment,
"base_commit": self.base_commit,
"diff_sha256": self.diff_sha256,
"decision": self.decision,
"reviewer_organization": self.reviewer_organization,
"reviewer_id": self.reviewer_id,
"reviewer_role": self.reviewer_role,
"review_receipt_sha256": self.review_receipt_sha256,
"reviewed_at": self.reviewed_at,
}
def public_summary(self) -> dict[str, Any]:
summary = {**self.commitment_payload(), "review_commitment": self.review_commitment}
assert_public_summary_safe(summary)
return summary
class ReviewedFinalApplier(Protocol):
"""Reserved production-applier shape; the local forge never invokes it."""
applier_id: str
measurement_sha256: str
def apply_reviewed_proposal(
self,
*,
protected_proposal: object,
proposal_summary: Mapping[str, Any],
review: ProposalReview,
) -> Mapping[str, Any]: ...
@dataclass(frozen=True, slots=True)
class ProposalPromotionResult:
proposal_id: str
proposal_commitment: str
review_commitment: str
disposition: PromotionDisposition
denial_codes: tuple[str, ...]
proposal_handle_consumed: bool
production_magic_star_release_available: bool
final_applier_invoked: bool
promotion_commitment: str
local_development_only: bool = True
production_ready: bool = False
def __post_init__(self) -> None:
_bounded_text(self.proposal_id, field_name="proposal_id", maximum_bytes=_MAX_ID_BYTES)
require_sha256(self.proposal_commitment, field="proposal_commitment")
require_sha256(self.review_commitment, field="review_commitment")
require_sha256(self.promotion_commitment, field="promotion_commitment")
if not isinstance(self.disposition, PromotionDisposition):
raise ProposalForgeError("promotion_disposition_invalid")
if (
type(self.proposal_handle_consumed) is not bool
or type(self.production_magic_star_release_available) is not bool
or type(self.final_applier_invoked) is not bool
):
raise ProposalForgeError("promotion_boolean_invalid")
if (
any(not isinstance(code, str) or not code for code in self.denial_codes)
or tuple(sorted(set(self.denial_codes))) != self.denial_codes
):
raise ProposalForgeError("promotion_denial_codes_invalid")
if self.local_development_only is not True or self.production_ready is not False:
raise ProposalForgeError("promotion_scope_invalid")
if not self.denial_codes:
raise ProposalForgeError("promotion_hold_denial_required")
if (
self.disposition is not PromotionDisposition.HOLD
or self.proposal_handle_consumed
or self.production_magic_star_release_available
or self.final_applier_invoked
):
raise ProposalForgeError("nonproduction_promotion_must_hold")
if self.promotion_commitment != domain_hash(
"aureon.plumber.proposal-promotion.v0",
self.commitment_payload(),
):
raise ProposalForgeError("promotion_commitment_invalid")
def commitment_payload(self) -> dict[str, Any]:
return {
"proposal_id": self.proposal_id,
"proposal_commitment": self.proposal_commitment,
"review_commitment": self.review_commitment,
"disposition": str(self.disposition),
"denial_codes": list(self.denial_codes),
"proposal_handle_consumed": self.proposal_handle_consumed,
"production_magic_star_release_available": self.production_magic_star_release_available,
"final_applier_invoked": self.final_applier_invoked,
"local_development_only": True,
"production_ready": False,
}
def public_summary(self) -> dict[str, Any]:
summary = {
**self.commitment_payload(),
"promotion_commitment": self.promotion_commitment,
}
assert_public_summary_safe(summary)
return summary
@dataclass(slots=True)
class _ProposalRecord:
os_handle: OpaqueHNCHandle
descriptor: dict[str, Any]
proposal_handle_commitment: str
class LocalProposalForge:
"""In-memory proposal-only bridge from self-coder output to Magic Star."""
production_ready = False
def __init__(
self,
*,
forge_id: str,
os_boundary: LocalOSProtectionBoundary,
) -> None:
self._forge_id = _bounded_text(
forge_id,
field_name="forge_id",
maximum_bytes=_MAX_ID_BYTES,
)
if not isinstance(os_boundary, LocalOSProtectionBoundary):
raise ProposalForgeError("local_os_protection_boundary_required")
self._os_boundary = os_boundary
self._records: dict[str, _ProposalRecord] = {}
self._consumed_handle_commitments: set[str] = set()
self._lock = threading.RLock()
def preflight(self) -> dict[str, Any]:
"""Return a metadata-only readiness check before sensitive authoring."""
key = self._os_boundary.key_preflight()
ready = key.get("ready") is True
summary = {
"schema": PROPOSAL_FORGE_PREFLIGHT_SCHEMA,
"forge_id": self._forge_id,
"ready": ready,
"reason_code": "ready" if ready else str(key.get("reason_code") or "hold"),
"os_key_preflight_schema": str(key.get("schema") or ""),
"key_material_returned": False,
"proposal_admission_authorized": False,
"action_eligible": False,
"economic_eligible": False,
"local_development_only": True,
"production_ready": False,
}
assert_public_summary_safe(summary)
return summary
def forge_proposal(
self,
*,
source_request: str,
unified_diff: str,
model_id: str,
adviser_id: str,
reviewer_id: str,
adviser_evidence_sha256: str,
provenance: Mapping[str, Any],
base_commit: str,
) -> ProposalForgeOutcome:
"""Seal one exact candidate; never write, apply, import, or execute it."""
request = _bounded_text(
source_request,
field_name="source_request",
maximum_bytes=_MAX_REQUEST_BYTES,
)
if not isinstance(unified_diff, str):
raise ProposalForgeError("unified_diff_invalid")
try:
diff_bytes = unified_diff.encode("utf-8", errors="strict")
except UnicodeEncodeError as exc:
raise ProposalForgeError("unified_diff_invalid") from exc
bounded_model = _bounded_text(
model_id,
field_name="model_id",
maximum_bytes=_MAX_ID_BYTES,
)
bounded_adviser = _bounded_text(
adviser_id,
field_name="adviser_id",
maximum_bytes=_MAX_ID_BYTES,
)
bounded_reviewer = _bounded_text(
reviewer_id,
field_name="reviewer_id",
maximum_bytes=_MAX_ID_BYTES,
)
require_sha256(adviser_evidence_sha256, field="adviser_evidence_sha256")
commit = _base_commit(base_commit)
normalized_provenance, provenance_bytes = _canonical_mapping(
provenance,
field_name="provenance",
maximum_bytes=_MAX_PROVENANCE_BYTES,
)
request_bytes = request.encode("utf-8")
core: dict[str, Any] = {
"schema": PROPOSAL_FORGE_SCHEMA,
"forge_id": self._forge_id,
"source_request_sha256": sha256_hex(request_bytes),
"source_request_size_bytes": len(request_bytes),
"model_id": bounded_model,
"adviser_organization": _OPENAI_ORGANIZATION,
"adviser_id": bounded_adviser,
"reviewer_id": bounded_reviewer,
"adviser_evidence_sha256": adviser_evidence_sha256,
"provenance_sha256": sha256_hex(provenance_bytes),
"base_commit": commit,
"diff_sha256": sha256_hex(diff_bytes),
"diff_size_bytes": len(diff_bytes),
"proposal_generator": _PROPOSAL_GENERATOR,
"openai_role": _OPENAI_ROLE,
"ownership_claim": _OWNERSHIP_CLAIM,
"authorship_statement": AUTHORSHIP_STATEMENT,
"metadata_verification": _METADATA_VERIFICATION,
}
provisional = {**core, "proposal_id": ""}
# The proposal ID is derived from a core that excludes the ID itself,
# preventing random identifiers from defeating OS replay detection.
commitment_core = {key: value for key, value in provisional.items() if key != "proposal_id"}
proposal_commitment = domain_hash("aureon.plumber.proposal.v0", commitment_core)
descriptor = {
**core,
"proposal_id": f"proposal-{proposal_commitment[:32]}",
"proposal_commitment": proposal_commitment,
}
_validate_descriptor(descriptor)
payload = {
"schema": _PROPOSAL_PAYLOAD_SCHEMA,
"descriptor": descriptor,
"source_request": request,
"unified_diff": unified_diff,
"provenance": normalized_provenance,
}
payload_bytes = canonical_json_bytes(payload)
operator_aad = {
"schema": _PROPOSAL_AAD_SCHEMA,
"descriptor": descriptor,
"payload_sha256": sha256_hex(payload_bytes),
"promotion_initial_disposition": str(PromotionDisposition.HOLD),
"repository_mutation_authorized": False,
"generated_code_execution_authorized": False,
}
def validate_payload(view: memoryview) -> bool:
try:
decoded = decode_canonical_json(view.tobytes(), require_mapping=True)
if not isinstance(decoded, dict) or set(decoded) != set(payload):
return False
return (
decoded == payload
and _diff_contract_valid(unified_diff, diff_bytes)
and sha256_hex(payload_bytes) == operator_aad["payload_sha256"]
)
except BaseException:
return False
outcome = self._os_boundary.admit_external(
payload_bytes,
source_id=_PROPOSAL_SOURCE_ID,
ingress_kind=_PROPOSAL_INGRESS_KIND,
purpose=PROPOSAL_PURPOSE,
operator_aad=operator_aad,
content_validator=validate_payload,
)
if isinstance(outcome, QuarantinedHNC):
return QuarantinedProposal(descriptor=descriptor, quarantine=outcome)
if not isinstance(outcome, AdmittedHNC): # pragma: no cover - total OS outcome
raise ProposalForgeError("os_admission_outcome_invalid")
handle = OpaqueProposalHandle.issue(
descriptor=descriptor,
os_handle=outcome.handle,
)
record = _ProposalRecord(
os_handle=outcome.handle,
descriptor=dict(descriptor),
proposal_handle_commitment=handle.handle_commitment,
)
with self._lock:
if handle.proposal_id in self._records:
raise ProposalForgeError("proposal_record_collision")
self._records[handle.proposal_id] = record
return handle
def _promotion_result(
self,
*,
handle: OpaqueProposalHandle,
review: ProposalReview,
denial_codes: tuple[str, ...],
) -> ProposalPromotionResult:
normalized_codes = tuple(sorted(set(denial_codes)))
values = {
"proposal_id": handle.proposal_id,
"proposal_commitment": handle.proposal_commitment,
"review_commitment": review.review_commitment,
"disposition": str(PromotionDisposition.HOLD),
"denial_codes": list(normalized_codes),
"proposal_handle_consumed": False,
"production_magic_star_release_available": False,
"final_applier_invoked": False,
"local_development_only": True,
"production_ready": False,
}
return ProposalPromotionResult(
proposal_id=handle.proposal_id,
proposal_commitment=handle.proposal_commitment,
review_commitment=review.review_commitment,
disposition=PromotionDisposition.HOLD,
denial_codes=normalized_codes,
proposal_handle_consumed=False,
production_magic_star_release_available=False,
final_applier_invoked=False,
promotion_commitment=domain_hash(
"aureon.plumber.proposal-promotion.v0",
values,
),
)
def discard_proposal(
self,
handle: OpaqueProposalHandle,
*,
reason_code: str,
) -> dict[str, Any]:
"""Atomically burn one transient proposal and its OS admission.
This is the terminal path for a proposal that cannot enter a durable,
authenticated review vault. It never decodes or releases the carrier.
"""
if not isinstance(handle, OpaqueProposalHandle):
raise ProposalForgeError("opaque_proposal_handle_required")
reason = _bounded_text(
reason_code,
field_name="discard_reason_code",
maximum_bytes=128,
)
with self._lock:
record = self._records.get(handle.proposal_id)
available = (
record is not None
and handle.forge_id == self._forge_id
and record.proposal_handle_commitment == handle.handle_commitment
and handle.handle_commitment not in self._consumed_handle_commitments
and secrets.compare_digest(
handle.handle_commitment,
_proposal_handle_commitment(
forge_id=handle.forge_id,
proposal_id=handle.proposal_id,
proposal_commitment=handle.proposal_commitment,
os_handle_commitment=handle.os_handle_commitment,
token=handle.token,
),
)
)
if not available or record is None:
raise ProposalForgeError("proposal_handle_unavailable_or_replayed")
try:
os_discard = self._os_boundary.discard_admitted(
record.os_handle,
reason_code=reason,
)
except OSProtectionError as exc:
raise ProposalForgeError("proposal_os_discard_failed") from exc
self._records.pop(handle.proposal_id, None)
self._consumed_handle_commitments.add(handle.handle_commitment)
summary = {
"schema": PROPOSAL_FORGE_SCHEMA,
"proposal_id": handle.proposal_id,
"proposal_commitment": handle.proposal_commitment,
"disposition": "DISCARDED_HNC",
"reason_code": reason,
"proposal_handle_consumed": True,
"carrier_released": False,
"plaintext_decoded": False,
"os_discard_handle_commitment": str(
os_discard.get("handle_commitment") or ""
),
"local_development_only": True,
"production_ready": False,
}
assert_public_summary_safe(summary)
return summary
def promote_reviewed(
self,
handle: OpaqueProposalHandle,
*,
review: ProposalReview,
custody: LocalDevelopmentStarCustodyV02,
release_context_sha256: str,
final_applier: ReviewedFinalApplier,
) -> ProposalPromotionResult:
"""Return HOLD without touching non-production custody or an applier.
The checked-in OS boundary, Magic Star custody, and release boundary
are local-development components with ``production_ready=False``.
Consequently no injected object can create release authority here.
"""
if not isinstance(handle, OpaqueProposalHandle):
raise ProposalForgeError("opaque_proposal_handle_required")
if not isinstance(review, ProposalReview):
raise ProposalForgeError("proposal_review_required")
require_sha256(release_context_sha256, field="release_context_sha256")
with self._lock:
record = self._records.get(handle.proposal_id)
available = (
record is not None
and record.proposal_handle_commitment == handle.handle_commitment
and handle.handle_commitment not in self._consumed_handle_commitments
and secrets.compare_digest(
handle.handle_commitment,
_proposal_handle_commitment(
forge_id=handle.forge_id,
proposal_id=handle.proposal_id,
proposal_commitment=handle.proposal_commitment,
os_handle_commitment=handle.os_handle_commitment,
token=handle.token,
),
)
)
if not available or record is None:
raise ProposalForgeError("proposal_handle_unavailable_or_replayed")
descriptor = record.descriptor
if (
review.proposal_commitment != descriptor["proposal_commitment"]
or review.base_commit != descriptor["base_commit"]
or review.diff_sha256 != descriptor["diff_sha256"]
or review.reviewer_organization != descriptor["adviser_organization"]
or review.reviewer_id != descriptor["reviewer_id"]
):
return self._promotion_result(
handle=handle,
review=review,
denial_codes=("review_binding_mismatch",),
)
if review.decision != "APPROVE":
return self._promotion_result(
handle=handle,
review=review,
denial_codes=("review_not_approved",),
)
# Deliberately do not inspect either object: hostile properties and
# self-attested receipts must not become a code-execution escape hatch.
_ = custody
_ = final_applier
return self._promotion_result(
handle=handle,
review=review,
denial_codes=("production_magic_star_release_unavailable",),
)
def public_summary(self) -> dict[str, Any]:
with self._lock:
summary = {
"schema": PROPOSAL_FORGE_SCHEMA,
"forge_id": self._forge_id,
"active_opaque_proposal_count": len(self._records),
"consumed_opaque_proposal_count": len(self._consumed_handle_commitments),
"proposal_only": True,
"repository_mutation_implemented": False,
"generated_code_execution_implemented": False,
"production_magic_star_release_available": False,
"reviewed_final_applier_invocation_implemented": False,
"persistent": False,
"local_development_only": True,
"production_ready": False,
}
assert_public_summary_safe(summary)
return summary
__all__ = [
"AUTHORSHIP_STATEMENT",
"PROPOSAL_FORGE_SCHEMA",
"PROPOSAL_FORGE_PREFLIGHT_SCHEMA",
"PROPOSAL_PURPOSE",
"LocalProposalForge",
"OpaqueProposalHandle",
"PromotionDisposition",
"ProposalForgeError",
"ProposalForgeOutcome",
"ProposalPromotionResult",
"ProposalReview",
"QuarantinedProposal",
"ReviewedFinalApplier",
]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586"""Fixed-target, fail-closed bootstrap boundary for Aureon runtimes.
This module is deliberately import-inert: importing it never installs an audit
hook, imports a registered target, starts a process, or writes a receipt. An
evaluation may call its supplied evidence probes; the default source-scope
probe invokes Git. No bootstrap-process-absence claim is therefore made. The
v0.5 reference makes the current system-level gap executable and unambiguous:
every official runtime target must pass one exact source-bound OS protection
decision before target import. While the target-byte, argument-policy, root,
v0.4 Python guard, and durable HNC evidence gaps remain, every target stays on
HOLD.
"""
from __future__ import annotations
import argparse
import hashlib
import json
import re
import sys
import time
from collections.abc import Callable, Mapping, Sequence
from dataclasses import dataclass
from pathlib import Path
from types import MappingProxyType
from typing import Any, Final
from aureon.autonomous.aureon_full_live_release import (
compute_source_scope_digest,
run_os_protection_audit,
validate_os_protection_summary,
)
from .runtime_guard_v04 import HNCRuntimeViolationRecorderV04, RuntimeAuditGuardV04
BOOTSTRAP_SCHEMA: Final = "aureon.plumber.protected-bootstrap.v05"
BOOTSTRAP_TARGET_SCHEMA: Final = "aureon.plumber.protected-bootstrap-target.v05"
_TARGET_ID_RE: Final = re.compile(r"^[a-z][a-z0-9-]{0,63}$")
_MAX_TARGET_ARGUMENTS: Final = 64
_MAX_TARGET_ARGUMENT_BYTES: Final = 4096
_MAX_TARGET_ARGUMENT_AGGREGATE_BYTES: Final = 64 * 1024
_ZERO_SHA256: Final = "0" * 64
_MODULE_ROOT: Final = Path(__file__).resolve().parents[2]
def _target_id(value: object) -> str:
if type(value) is not str or _TARGET_ID_RE.fullmatch(value) is None:
raise ValueError("exact_bootstrap_target_id_required")
return value
@dataclass(frozen=True, slots=True)
class ProtectedBootstrapTargetV05:
target_id: str
runtime_kind: str
entrypoint: str
def __post_init__(self) -> None:
_target_id(self.target_id)
if self.runtime_kind not in {"python", "node", "powershell", "native", "shell"}:
raise ValueError("recognized_bootstrap_runtime_kind_required")
if (
type(self.entrypoint) is not str
or not self.entrypoint
or len(self.entrypoint.encode("utf-8")) > 512
or "\x00" in self.entrypoint
):
raise ValueError("bounded_bootstrap_entrypoint_required")
@property
def commitment(self) -> str:
return _sha256(
{
"schema": BOOTSTRAP_TARGET_SCHEMA,
"target_id": self.target_id,
"runtime_kind": self.runtime_kind,
"entrypoint": self.entrypoint,
}
)
def _target(target_id: str, runtime_kind: str, entrypoint: str) -> ProtectedBootstrapTargetV05:
return ProtectedBootstrapTargetV05(target_id, runtime_kind, entrypoint)
# The registry is intentionally fixed in source. CLI input can select an ID;
# it can never supply a module, path, callable, interpreter, or shell command.
PROTECTED_BOOTSTRAP_TARGETS_V05: Final[Mapping[str, ProtectedBootstrapTargetV05]] = (
MappingProxyType(
{
item.target_id: item
for item in (
_target("full-live-release", "python", "aureon.autonomous.aureon_full_live_release"),
_target(
"cloud-autonomous-worker",
"python",
"aureon.autonomous.aureon_autonomous_worker",
),
_target(
"cloud-command-center",
"python",
"aureon.command_centers.aureon_command_center_ui",
),
_target(
"cloud-kraken-cache",
"python",
"aureon.exchanges.kraken_cache_feeder",
),
_target(
"cloud-market-cache",
"python",
"aureon.data_feeds.unified_market_cache",
),
_target("cloud-orca", "python", "aureon.bots.orca_complete_kill_cycle"),
_target(
"cloud-pro-dashboard",
"python",
"aureon.monitors.aureon_pro_dashboard",
),
_target(
"cloud-queen-redistribution",
"python",
"aureon.queen.queen_power_redistribution",
),
_target("capability-demo", "python", "aureon.saas.capability_demo"),
_target(
"canonical-cloud-organism",
"python",
"scripts.operations.run_canonical_cloud_organism",
),
_target(
"druidic-live-calibration",
"python",
"scripts.operations.run_live_druidic_calibration",
),
_target("ws-market-data-feeder", "python", "aureon.data_feeds.ws_market_data_feeder"),
_target("ignition", "python", "scripts/aureon_ignition.py"),
_target("unified-market-status", "python", "aureon.exchanges.unified_market_status_server"),
_target("unified-market-trader", "python", "aureon.exchanges.unified_market_trader"),
_target("parallel-strategy-unity", "python", "aureon.trading.parallel_strategy_unity"),
_target(
"parallel-strategy-audit",
"python",
"aureon.autonomous.aureon_parallel_strategy_unity_stress_audit",
),
_target("mind-hub", "python", "aureon.autonomous.aureon_mind_thought_action_hub"),
_target("self-questioning", "python", "aureon.autonomous.aureon_self_questioning_ai"),
_target("scorm-benchmark", "python", "aureon.operator.scorm_cloud_runner"),
_target(
"organism-observer",
"python",
"aureon.autonomous.aureon_organism_runtime_observer",
),
_target(
"autonomous-self-run",
"python",
"aureon.autonomous.aureon_autonomous_self_run_loop",
),
_target("saas-system-inventory", "python", "aureon.autonomous.aureon_saas_system_inventory"),
_target(
"frontend-unification-plan",
"python",
"aureon.autonomous.aureon_frontend_unification_plan",
),
_target(
"frontend-evolution-queue",
"python",
"aureon.autonomous.aureon_frontend_evolution_queue",
),
_target(
"autonomous-capability-switchboard",
"python",
"aureon.autonomous.aureon_autonomous_capability_switchboard",
),
_target("unified-ui-builder", "python", "aureon.autonomous.aureon_unified_ui_builder"),
_target(
"trading-intelligence-checklist",
"python",
"aureon.autonomous.aureon_trading_intelligence_checklist",
),
_target(
"exchange-monitoring-checklist",
"python",
"aureon.autonomous.aureon_exchange_monitoring_checklist",
),
_target(
"exchange-data-capability-matrix",
"python",
"aureon.autonomous.aureon_exchange_data_capability_matrix",
),
_target(
"global-financial-coverage-map",
"python",
"aureon.autonomous.aureon_global_financial_coverage_map",
),
_target("data-ocean", "python", "aureon.autonomous.aureon_data_ocean"),
_target("kraken-asset-registry", "python", "aureon.exchanges.kraken_asset_registry"),
_target("capital-asset-registry", "python", "aureon.exchanges.capital_asset_registry"),
_target("ingest-global-memory", "python", "scripts/python/ingest_global_memory.py"),
_target("operator", "python", "aureon.operator.operator_server"),
_target("operator-wsgi", "python", "aureon.operator.wsgi"),
_target("organism", "python", "aureon.core.organism_daemon"),
_target("hnc", "python", "aureon.core.hnc_live_daemon"),
_target("local-gui", "python", "aureon.operator.local_gui_organism"),
_target("website", "python", "aureon.operator.website_operator"),
_target("docker-runtime", "native", "Dockerfile"),
_target("ephemeris-pipeline", "native", "Dockerfile.ephemeris"),
_target("linux-supervisor", "native", "deploy/supervisord.linux.conf"),
_target(
"master-launcher",
"python",
"aureon.autonomous.aureon_master_launcher",
),
_target(
"queen-eternal-machine",
"python",
"aureon.queen.queen_eternal_machine",
),
_target(
"queen-web-dashboard",
"python",
"aureon.queen.queen_web_dashboard",
),
_target(
"power-redistribution-engine",
"python",
"aureon.utils.aureon_power_redistribution_engine",
),
_target("frontend-vite", "node", "frontend:vite"),
_target("flameborn-runtime", "node", "flameborn:runtime"),
_target("windows-wake", "powershell", "scripts/launchers/AUREON_WAKE_UP_FULL_AUTONOMOUS.ps1"),
_target("cloud-supervisor", "native", "deploy/supervisord.conf"),
_target("production-supervisor", "native", "production/supervisord.conf"),
)
}
)
)
@dataclass(frozen=True, slots=True)
class ProtectedBootstrapRequestV05:
target_id: str
target_arguments: tuple[str, ...] = ()
def __post_init__(self) -> None:
_target_id(self.target_id)
if type(self.target_arguments) is not tuple or len(self.target_arguments) > _MAX_TARGET_ARGUMENTS:
raise ValueError("bounded_bootstrap_target_arguments_required")
aggregate = 0
for argument in self.target_arguments:
if type(argument) is not str or "\x00" in argument:
raise ValueError("exact_bootstrap_target_argument_required")
size = len(argument.encode("utf-8"))
if size > _MAX_TARGET_ARGUMENT_BYTES:
raise ValueError("bounded_bootstrap_target_argument_required")
aggregate += size
if aggregate > _MAX_TARGET_ARGUMENT_AGGREGATE_BYTES:
raise ValueError("bounded_bootstrap_target_argument_aggregate_required")
@dataclass(frozen=True, slots=True)
class ProtectedBootstrapResultV05:
decision: str
receipt: Mapping[str, Any]
SourceScopeDigestFn = Callable[[Path], str]
OSProtectionAuditFn = Callable[[Path], Mapping[str, Any]]
def _canonical_bytes(value: Mapping[str, Any]) -> bytes:
return json.dumps(
value,
sort_keys=True,
separators=(",", ":"),
ensure_ascii=True,
allow_nan=False,
).encode("utf-8")
def _sha256(value: Mapping[str, Any] | Sequence[str] | str) -> str:
if isinstance(value, Mapping):
raw = _canonical_bytes(value)
elif isinstance(value, str):
raw = value.encode("utf-8")
else:
raw = json.dumps(
list(value),
sort_keys=False,
separators=(",", ":"),
ensure_ascii=True,
).encode("utf-8")
return hashlib.sha256(raw).hexdigest()
def _digest(value: object, code: str) -> str:
if (
type(value) is not str
or len(value) != 64
or any(character not in "0123456789abcdef" for character in value)
):
raise ValueError(code)
return value
def _failed_os_summary(reason: str) -> dict[str, Any]:
return {
"ok": False,
"reason": reason,
"schema": "aureon.os-protection-boundary-census.v1",
"source_files_scanned": 0,
"detected_count": 0,
"classified_count": 0,
"blocker_count": 0,
"protected_count": 0,
"explicit_hold_count": 0,
"parse_error_count": 1,
"inventory_sha256": _ZERO_SHA256,
"certified_full_os_protection": False,
}
def _runtime_guard_facts() -> dict[str, Any]:
return {
"guard_type": "RuntimeAuditGuardV04",
"guard_production_ready": RuntimeAuditGuardV04.production_ready is True,
"hnc_recorder_production_ready": HNCRuntimeViolationRecorderV04.production_ready is True,
"target_import_after_install_attested": False,
"native_outer_boundary_attested": False,
"node_boundary_attested": False,
"powershell_boundary_attested": False,
"durable_hnc_evidence_attested": False,
"restart_replay_attested": False,
"external_head_anchor_attested": False,
}
def _invalid_request_receipt(*, checked_at: float) -> dict[str, Any]:
causal = {
"schema": BOOTSTRAP_SCHEMA,
"decision": "HOLD",
"reason": "exact_protected_bootstrap_request_required",
"failed_checks": ["bootstrap_request"],
"target_id": "",
"target_registered": False,
"target_runtime_kind": "",
"target_entrypoint_commitment": _ZERO_SHA256,
"target_source_sha256": _ZERO_SHA256,
"target_source_bytes_attested": False,
"target_argument_count": 0,
"target_arguments_sha256": _sha256(()),
"target_argument_bounds_validated": False,
"target_argument_policy_attested": False,
"measurement_root_module_bound": False,
"target_import_root_bound": False,
"source_scope_before": _ZERO_SHA256,
"source_scope_after": _ZERO_SHA256,
"source_scope_stable": False,
"full_os_protection": _failed_os_summary("os_protection_not_evaluated"),
"runtime_guard": _runtime_guard_facts(),
"target_imported": False,
"target_called": False,
"target_subprocess_started": False,
"bootstrap_subprocess_absence_attested": False,
"hnc_denial_recorded": False,
"durable_hnc_denial_recorded": False,
"process_start_authorized": False,
"action_eligible": False,
"economic_eligible": False,
"operational_eligible": False,
"production_ready": False,
"checked_at": checked_at,
}
return {**causal, "receipt_id": f"bootstrap:v05:{_sha256(causal)}"}
def evaluate_protected_bootstrap_v05(
*,
root: Path,
request: ProtectedBootstrapRequestV05,
source_scope_digest_fn: SourceScopeDigestFn = compute_source_scope_digest,
os_protection_audit_fn: OSProtectionAuditFn = run_os_protection_audit,
now: float | None = None,
) -> ProtectedBootstrapResultV05:
"""Evaluate one fixed target without importing or starting it."""
if type(request) is not ProtectedBootstrapRequestV05:
raise ValueError("exact_protected_bootstrap_request_required")
resolved = root.resolve()
checked_at = float(time.time() if now is None else now)
failures: list[str] = []
target = PROTECTED_BOOTSTRAP_TARGETS_V05.get(request.target_id)
if target is None:
failures.append("fixed_bootstrap_target")
measurement_root_module_bound = resolved == _MODULE_ROOT
if not measurement_root_module_bound:
failures.append("module_bound_measurement_root")
# The registry currently binds an entrypoint descriptor, not the bytes that
# an eventual import/exec would load. Arbitrary bounded argv is likewise
# committed but has no per-target policy. Both remain explicit HOLDs.
failures.extend(
(
"bootstrap_subprocess_absence",
"target_argument_policy",
"target_import_root_binding",
"target_source_attestation",
)
)
try:
source_before = _digest(
source_scope_digest_fn(resolved),
"bootstrap_source_scope_digest_required",
)
except Exception: # noqa: BLE001 - source boundary becomes a fixed HOLD
source_before = _ZERO_SHA256
failures.append("source_scope")
try:
os_protection = validate_os_protection_summary(
os_protection_audit_fn(resolved)
)
except Exception: # noqa: BLE001 - audit boundary becomes a fixed HOLD
os_protection = _failed_os_summary("os_protection_audit_failed")
if os_protection.get("ok") is not True:
failures.append("full_os_protection")
try:
source_after = _digest(
source_scope_digest_fn(resolved),
"bootstrap_source_scope_digest_required",
)
except Exception: # noqa: BLE001 - source boundary becomes a fixed HOLD
source_after = _ZERO_SHA256
failures.append("source_scope")
source_stable = source_before != _ZERO_SHA256 and source_before == source_after
if not source_stable:
failures.append("source_scope_stability")
guard = _runtime_guard_facts()
if guard["guard_production_ready"] is not True:
failures.append("runtime_guard_production_readiness")
if guard["hnc_recorder_production_ready"] is not True:
failures.append("hnc_evidence_production_readiness")
if guard["target_import_after_install_attested"] is not True:
failures.append("sealed_target_import")
if guard["durable_hnc_evidence_attested"] is not True:
failures.append("durable_hnc_evidence")
if target is not None and target.runtime_kind != "python":
failures.append(f"{target.runtime_kind}_outer_boundary")
failed_checks = sorted(set(failures))
target_id = target.target_id if target is not None else request.target_id
causal = {
"schema": BOOTSTRAP_SCHEMA,
"decision": "HOLD",
"reason": "complete_protected_bootstrap_evidence_required",
"failed_checks": failed_checks,
"target_id": target_id,
"target_registered": target is not None,
"target_runtime_kind": "" if target is None else target.runtime_kind,
"target_entrypoint_commitment": _ZERO_SHA256 if target is None else target.commitment,
"target_source_sha256": _ZERO_SHA256,
"target_source_bytes_attested": False,
"target_argument_count": len(request.target_arguments),
"target_arguments_sha256": _sha256(request.target_arguments),
"target_argument_bounds_validated": True,
"target_argument_policy_attested": False,
"measurement_root_module_bound": measurement_root_module_bound,
"target_import_root_bound": False,
"source_scope_before": source_before,
"source_scope_after": source_after,
"source_scope_stable": source_stable,
"full_os_protection": os_protection,
"runtime_guard": guard,
"target_imported": False,
"target_called": False,
"target_subprocess_started": False,
"bootstrap_subprocess_absence_attested": False,
"hnc_denial_recorded": False,
"durable_hnc_denial_recorded": False,
"process_start_authorized": False,
"action_eligible": False,
"economic_eligible": False,
"operational_eligible": False,
"production_ready": False,
"checked_at": checked_at,
}
receipt = {**causal, "receipt_id": f"bootstrap:v05:{_sha256(causal)}"}
return ProtectedBootstrapResultV05(decision="HOLD", receipt=receipt)
def _parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--target-id", required=True)
parser.add_argument("--pretty", action="store_true")
parser.add_argument("target_arguments", nargs=argparse.REMAINDER)
return parser
def _cli_os_protection_unattested(_root: Path) -> dict[str, Any]:
"""Decline the whole-tree census on the CLI path.
The census cannot override HOLD, and walking every source file blocks the
receipt. The structural gaps already keep the target unimported.
"""
raise RuntimeError("bootstrap_cli_declines_unbounded_os_protection_census")
def main(argv: list[str] | None = None) -> int:
args = _parser().parse_args(argv)
target_arguments = tuple(args.target_arguments)
if target_arguments[:1] == ("--",):
target_arguments = target_arguments[1:]
try:
request = ProtectedBootstrapRequestV05(
target_id=args.target_id,
target_arguments=target_arguments,
)
result = evaluate_protected_bootstrap_v05(
root=_MODULE_ROOT,
request=request,
os_protection_audit_fn=_cli_os_protection_unattested,
)
receipt = result.receipt
exit_code = 1
except (OSError, TypeError, ValueError):
receipt = _invalid_request_receipt(checked_at=time.time())
exit_code = 2
print(
json.dumps(
receipt,
sort_keys=True,
indent=2 if args.pretty else None,
separators=None if args.pretty else (",", ":"),
)
)
return exit_code
def _console_target_main(target_id: str) -> int:
return main(["--target-id", target_id, "--", *sys.argv[1:]])
def operator_main() -> int:
return _console_target_main("operator")
def organism_main() -> int:
return _console_target_main("organism")
def hnc_main() -> int:
return _console_target_main("hnc")
def local_gui_main() -> int:
return _console_target_main("local-gui")
def website_main() -> int:
return _console_target_main("website")
if __name__ == "__main__":
raise SystemExit(main())
__all__ = [
"BOOTSTRAP_SCHEMA",
"BOOTSTRAP_TARGET_SCHEMA",
"PROTECTED_BOOTSTRAP_TARGETS_V05",
"ProtectedBootstrapRequestV05",
"ProtectedBootstrapResultV05",
"ProtectedBootstrapTargetV05",
"evaluate_protected_bootstrap_v05",
"hnc_main",
"local_gui_main",
"main",
"operator_main",
"organism_main",
"website_main",
]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135"""Metadata-only quarantine records for denied Plumber material."""
from __future__ import annotations
from collections.abc import Mapping, Sequence
from dataclasses import dataclass
from datetime import datetime
from typing import Any, Self
from .crypto import domain_hash
from .schema import (
DenialCode,
SchemaError,
format_timestamp,
freeze_mapping,
parse_timestamp,
require_exact_keys,
require_nonblank,
require_sha256,
)
QUARANTINE_SCHEMA = "aureon.plumber.quarantine-record.v0"
_FIELDS = (
"schema",
"quarantine_id",
"packet_identity",
"session_identity",
"packet_commitment",
"denial_codes",
"evidence_commitments",
"quarantined_at",
"record_commitment",
)
@dataclass(frozen=True, slots=True)
class QuarantineRecord:
schema: str
quarantine_id: str
packet_identity: str
session_identity: str
packet_commitment: str
denial_codes: tuple[str, ...]
evidence_commitments: Mapping[str, str]
quarantined_at: str
record_commitment: str
def __post_init__(self) -> None:
if self.schema != QUARANTINE_SCHEMA:
raise SchemaError(DenialCode.INVALID_SCHEMA, field="schema")
for field in ("quarantine_id", "packet_identity", "session_identity"):
require_nonblank(getattr(self, field), field=field)
for field in ("packet_commitment", "record_commitment"):
require_sha256(getattr(self, field), field=field)
if not self.denial_codes or tuple(sorted(set(self.denial_codes))) != self.denial_codes:
raise SchemaError(DenialCode.INVALID_VALUE, field="denial_codes")
if not isinstance(self.evidence_commitments, Mapping):
raise SchemaError(DenialCode.INVALID_TYPE, field="evidence_commitments")
for name, commitment in self.evidence_commitments.items():
require_nonblank(name, field="evidence_commitments.key")
require_sha256(commitment, field="evidence_commitments.value")
object.__setattr__(
self,
"evidence_commitments",
freeze_mapping(self.evidence_commitments, field="evidence_commitments", nonempty=False),
)
parse_timestamp(self.quarantined_at, field="quarantined_at")
if domain_hash("aureon.plumber.quarantine-record.v0", self.commitment_payload()) != self.record_commitment:
raise SchemaError(DenialCode.INVALID_VALUE, field="record_commitment")
@classmethod
def build(
cls,
*,
quarantine_id: str,
packet_identity: str,
session_identity: str,
packet_commitment: str,
denial_codes: Sequence[DenialCode | str],
evidence_commitments: Mapping[str, str],
quarantined_at: datetime,
) -> Self:
normalized_codes = tuple(sorted({str(code) for code in denial_codes}))
normalized_evidence = dict(evidence_commitments)
quarantined_at_text = format_timestamp(quarantined_at)
values = {
"schema": QUARANTINE_SCHEMA,
"quarantine_id": quarantine_id,
"packet_identity": packet_identity,
"session_identity": session_identity,
"packet_commitment": packet_commitment,
"denial_codes": normalized_codes,
"evidence_commitments": normalized_evidence,
"quarantined_at": quarantined_at_text,
}
return cls(
schema=QUARANTINE_SCHEMA,
quarantine_id=quarantine_id,
packet_identity=packet_identity,
session_identity=session_identity,
packet_commitment=packet_commitment,
denial_codes=normalized_codes,
evidence_commitments=normalized_evidence,
quarantined_at=quarantined_at_text,
record_commitment=domain_hash("aureon.plumber.quarantine-record.v0", values),
)
@classmethod
def from_dict(cls, value: Mapping[str, Any]) -> Self:
parsed = require_exact_keys(value, _FIELDS, field="quarantine_record")
if not isinstance(parsed["denial_codes"], list):
raise SchemaError(DenialCode.INVALID_TYPE, field="denial_codes")
parsed["denial_codes"] = tuple(parsed["denial_codes"])
return cls(**parsed)
def commitment_payload(self) -> dict[str, Any]:
return {
"schema": self.schema,
"quarantine_id": self.quarantine_id,
"packet_identity": self.packet_identity,
"session_identity": self.session_identity,
"packet_commitment": self.packet_commitment,
"denial_codes": list(self.denial_codes),
"evidence_commitments": dict(self.evidence_commitments),
"quarantined_at": self.quarantined_at,
}
def to_dict(self) -> dict[str, Any]:
return {**self.commitment_payload(), "record_commitment": self.record_commitment}
def public_summary(self) -> dict[str, Any]:
return self.to_dict()
__all__ = ["QUARANTINE_SCHEMA", "QuarantineRecord"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316"""Typed-authority quorum permits for Aureon Plumber v0.
Permits carry only wrapped-share commitments. This module never accepts or
returns a raw key share and does not reconstruct a session key.
"""
from __future__ import annotations
from collections.abc import Mapping, Sequence
from dataclasses import dataclass
from datetime import datetime
from enum import StrEnum
from typing import Any, Self
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
from .crypto import (
domain_hash,
ed25519_public_key_hex,
load_ed25519_private_key,
sign_ed25519,
verify_ed25519,
)
from .schema import (
DenialCode,
SchemaError,
format_timestamp,
parse_timestamp,
require_aware_datetime,
require_ed25519_public_key,
require_ed25519_signature,
require_exact_keys,
require_nonblank,
require_sha256,
)
QUORUM_POLICY_SCHEMA = "aureon.plumber.quorum-policy.v0"
AUTHORITY_PERMIT_SCHEMA = "aureon.plumber.authority-permit.v0"
_SIGNATURE_DOMAIN = "aureon.plumber.authority-permit.signature.v0"
class AuthorityRole(StrEnum):
SOURCE = "source"
OBSERVER = "observer"
CONSCIENCE = "conscience"
GOVERNANCE = "governance"
OPERATOR = "operator"
_POLICY_FIELDS = ("schema", "required_roles", "operator_required", "policy_commitment")
@dataclass(frozen=True, slots=True)
class QuorumPolicyV0:
schema: str
required_roles: tuple[str, ...]
operator_required: bool
policy_commitment: str
def __post_init__(self) -> None:
if self.schema != QUORUM_POLICY_SCHEMA:
raise SchemaError(DenialCode.INVALID_SCHEMA, field="schema")
if type(self.operator_required) is not bool:
raise SchemaError(DenialCode.INVALID_TYPE, field="operator_required")
if not isinstance(self.required_roles, tuple) or not self.required_roles:
raise SchemaError(DenialCode.INVALID_TYPE, field="required_roles")
try:
parsed = tuple(str(AuthorityRole(role)) for role in self.required_roles)
except ValueError as exc:
raise SchemaError(DenialCode.INVALID_VALUE, field="required_roles") from exc
if tuple(sorted(set(parsed))) != parsed:
raise SchemaError(DenialCode.INVALID_VALUE, field="required_roles")
if self.operator_required != (str(AuthorityRole.OPERATOR) in parsed):
raise SchemaError(DenialCode.INVALID_VALUE, field="operator_required")
require_sha256(self.policy_commitment, field="policy_commitment")
if domain_hash("aureon.plumber.quorum-policy.v0", self.commitment_payload()) != self.policy_commitment:
raise SchemaError(DenialCode.INVALID_VALUE, field="policy_commitment")
@classmethod
def build(
cls,
*,
required_roles: Sequence[AuthorityRole | str] = (
AuthorityRole.SOURCE,
AuthorityRole.OBSERVER,
AuthorityRole.CONSCIENCE,
AuthorityRole.GOVERNANCE,
),
operator_required: bool = False,
) -> Self:
roles = {str(AuthorityRole(role)) for role in required_roles}
if operator_required:
roles.add(str(AuthorityRole.OPERATOR))
else:
roles.discard(str(AuthorityRole.OPERATOR))
required_roles_value = tuple(sorted(roles))
values = {
"schema": QUORUM_POLICY_SCHEMA,
"required_roles": required_roles_value,
"operator_required": operator_required,
}
return cls(
schema=QUORUM_POLICY_SCHEMA,
required_roles=required_roles_value,
operator_required=operator_required,
policy_commitment=domain_hash("aureon.plumber.quorum-policy.v0", values),
)
@classmethod
def from_dict(cls, value: Mapping[str, Any]) -> Self:
parsed = require_exact_keys(value, _POLICY_FIELDS, field="quorum_policy")
if not isinstance(parsed["required_roles"], list):
raise SchemaError(DenialCode.INVALID_TYPE, field="required_roles")
parsed["required_roles"] = tuple(parsed["required_roles"])
return cls(**parsed)
def commitment_payload(self) -> dict[str, Any]:
return {
"schema": self.schema,
"required_roles": list(self.required_roles),
"operator_required": self.operator_required,
}
def to_dict(self) -> dict[str, Any]:
return {**self.commitment_payload(), "policy_commitment": self.policy_commitment}
_PERMIT_FIELDS = (
"schema",
"role",
"authority_id",
"packet_identity",
"session_identity",
"purpose_commitment",
"policy_commitment",
"wrapped_share_commitment",
"issued_at",
"expires_at",
"signer_public_key",
"permit_hash",
"signature",
)
@dataclass(frozen=True, slots=True)
class AuthorityPermit:
schema: str
role: str
authority_id: str
packet_identity: str
session_identity: str
purpose_commitment: str
policy_commitment: str
wrapped_share_commitment: str
issued_at: str
expires_at: str
signer_public_key: str
permit_hash: str
signature: str
def __post_init__(self) -> None:
if self.schema != AUTHORITY_PERMIT_SCHEMA:
raise SchemaError(DenialCode.INVALID_SCHEMA, field="schema")
try:
AuthorityRole(self.role)
except ValueError as exc:
raise SchemaError(DenialCode.INVALID_VALUE, field="role") from exc
for field in ("authority_id", "packet_identity", "session_identity"):
require_nonblank(getattr(self, field), field=field)
for field in (
"purpose_commitment",
"policy_commitment",
"wrapped_share_commitment",
"permit_hash",
):
require_sha256(getattr(self, field), field=field)
require_ed25519_public_key(self.signer_public_key, field="signer_public_key")
require_ed25519_signature(self.signature, field="signature")
issued = parse_timestamp(self.issued_at, field="issued_at")
expires = parse_timestamp(self.expires_at, field="expires_at")
if expires <= issued:
raise SchemaError(DenialCode.INVALID_VALUE, field="expires_at")
@classmethod
def issue(
cls,
*,
role: AuthorityRole | str,
authority_id: str,
packet_identity: str,
session_identity: str,
purpose_commitment: str,
policy_commitment: str,
wrapped_share_commitment: str,
issued_at: datetime,
expires_at: datetime,
private_key: Ed25519PrivateKey | bytes | str,
) -> Self:
key = load_ed25519_private_key(private_key)
values = {
"schema": AUTHORITY_PERMIT_SCHEMA,
"role": str(AuthorityRole(role)),
"authority_id": authority_id,
"packet_identity": packet_identity,
"session_identity": session_identity,
"purpose_commitment": purpose_commitment,
"policy_commitment": policy_commitment,
"wrapped_share_commitment": wrapped_share_commitment,
"issued_at": format_timestamp(issued_at),
"expires_at": format_timestamp(expires_at),
"signer_public_key": ed25519_public_key_hex(key),
}
permit_hash = domain_hash("aureon.plumber.authority-permit.v0", values)
signature = sign_ed25519(key, {"permit_hash": permit_hash}, domain=_SIGNATURE_DOMAIN)
return cls(**values, permit_hash=permit_hash, signature=signature)
@classmethod
def from_dict(cls, value: Mapping[str, Any]) -> Self:
return cls(**require_exact_keys(value, _PERMIT_FIELDS, field="authority_permit"))
def unsigned_payload(self) -> dict[str, str]:
return {
field: getattr(self, field)
for field in _PERMIT_FIELDS
if field not in {"permit_hash", "signature"}
}
def to_dict(self) -> dict[str, str]:
return {field: getattr(self, field) for field in _PERMIT_FIELDS}
def signature_valid(self) -> bool:
return (
domain_hash("aureon.plumber.authority-permit.v0", self.unsigned_payload()) == self.permit_hash
and verify_ed25519(
self.signer_public_key,
{"permit_hash": self.permit_hash},
self.signature,
domain=_SIGNATURE_DOMAIN,
)
)
def public_summary(self) -> dict[str, str]:
return {field: getattr(self, field) for field in _PERMIT_FIELDS if field != "signature"}
@dataclass(frozen=True, slots=True)
class QuorumValidation:
valid: bool
denial_codes: tuple[str, ...]
accepted_roles: tuple[str, ...]
permit_set_commitment: str
def evaluate_quorum(
policy: QuorumPolicyV0,
permits: Sequence[AuthorityPermit],
*,
now: datetime,
packet_identity: str,
session_identity: str,
purpose_commitment: str,
) -> QuorumValidation:
if not isinstance(policy, QuorumPolicyV0):
raise SchemaError(DenialCode.INVALID_TYPE, field="policy")
if isinstance(permits, (str, bytes, bytearray)) or not isinstance(permits, Sequence):
raise SchemaError(DenialCode.INVALID_TYPE, field="permits")
denials: set[str] = set()
by_role: dict[str, AuthorityPermit] = {}
authority_ids: set[str] = set()
public_keys: set[str] = set()
current = require_aware_datetime(now, field="now")
for permit in permits:
if not isinstance(permit, AuthorityPermit):
raise SchemaError(DenialCode.INVALID_TYPE, field="permits")
if permit.role in by_role or permit.authority_id in authority_ids or permit.signer_public_key in public_keys:
denials.add(str(DenialCode.QUORUM_DUPLICATE_AUTHORITY))
by_role.setdefault(permit.role, permit)
authority_ids.add(permit.authority_id)
public_keys.add(permit.signer_public_key)
if permit.role not in policy.required_roles:
denials.add(str(DenialCode.POLICY_RECEIPT_INVALID))
if not permit.signature_valid():
denials.add(str(DenialCode.INVALID_SIGNATURE))
if permit.packet_identity != packet_identity or permit.session_identity != session_identity:
if permit.packet_identity != packet_identity:
denials.add(str(DenialCode.PACKET_IDENTITY_MISMATCH))
if permit.session_identity != session_identity:
denials.add(str(DenialCode.SESSION_IDENTITY_MISMATCH))
if permit.purpose_commitment != purpose_commitment:
denials.add(str(DenialCode.PURPOSE_MISMATCH))
if permit.policy_commitment != policy.policy_commitment:
denials.add(str(DenialCode.POLICY_RECEIPT_INVALID))
if current < parse_timestamp(permit.issued_at, field="issued_at"):
denials.add(str(DenialCode.FUTURE_STATE))
if current >= parse_timestamp(permit.expires_at, field="expires_at"):
denials.add(str(DenialCode.STALE_STATE))
if set(policy.required_roles) - set(by_role):
denials.add(str(DenialCode.QUORUM_INCOMPLETE))
summaries = [by_role[role].public_summary() for role in sorted(by_role)]
return QuorumValidation(
valid=not denials,
denial_codes=tuple(sorted(denials)),
accepted_roles=tuple(sorted(set(by_role) & set(policy.required_roles))),
permit_set_commitment=domain_hash("aureon.plumber.permit-set.v0", summaries),
)
__all__ = [
"AUTHORITY_PERMIT_SCHEMA",
"QUORUM_POLICY_SCHEMA",
"AuthorityPermit",
"AuthorityRole",
"QuorumPolicyV0",
"QuorumValidation",
"evaluate_quorum",
]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251"""Signed, purpose-bound receipts for the foundational Plumber protocol."""
from __future__ import annotations
from collections.abc import Mapping
from dataclasses import dataclass
from datetime import datetime
from enum import StrEnum
from typing import Any, Self
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
from .crypto import (
domain_hash,
ed25519_public_key_hex,
load_ed25519_private_key,
sign_ed25519,
verify_ed25519,
)
from .schema import (
DenialCode,
SchemaError,
format_timestamp,
parse_timestamp,
require_aware_datetime,
require_ed25519_public_key,
require_ed25519_signature,
require_exact_keys,
require_nonblank,
require_sha256,
)
RECEIPT_SCHEMA = "aureon.plumber.receipt.v0"
_RECEIPT_SIGNATURE_DOMAIN = "aureon.plumber.receipt.signature.v0"
class ReceiptKind(StrEnum):
FIELD = "field"
OBSERVER = "observer"
HEART = "heart"
CONSCIENCE = "conscience"
GOVERNANCE = "governance"
SOURCE = "source"
OPERATOR = "operator"
class ReceiptVerdict(StrEnum):
APPROVED = "approved"
DENIED = "denied"
_RECEIPT_FIELDS = (
"schema",
"kind",
"packet_identity",
"session_identity",
"purpose_commitment",
"source_identity_commitment",
"temporal_identity_commitment",
"observer_transcript_commitment",
"policy_commitment",
"runtime_measurement_commitment",
"verdict",
"issued_at",
"expires_at",
"signer_id",
"signer_public_key",
"receipt_hash",
"signature",
)
@dataclass(frozen=True, slots=True)
class ReceiptValidation:
valid: bool
denial_codes: tuple[str, ...]
@dataclass(frozen=True, slots=True)
class SignedReceipt:
schema: str
kind: str
packet_identity: str
session_identity: str
purpose_commitment: str
source_identity_commitment: str
temporal_identity_commitment: str
observer_transcript_commitment: str
policy_commitment: str
runtime_measurement_commitment: str
verdict: str
issued_at: str
expires_at: str
signer_id: str
signer_public_key: str
receipt_hash: str
signature: str
def __post_init__(self) -> None:
if self.schema != RECEIPT_SCHEMA:
raise SchemaError(DenialCode.INVALID_SCHEMA, field="schema")
try:
ReceiptKind(self.kind)
ReceiptVerdict(self.verdict)
except ValueError as exc:
raise SchemaError(DenialCode.INVALID_VALUE, field="receipt_enum") from exc
for field in ("packet_identity", "session_identity", "signer_id"):
require_nonblank(getattr(self, field), field=field)
for field in (
"purpose_commitment",
"source_identity_commitment",
"temporal_identity_commitment",
"observer_transcript_commitment",
"policy_commitment",
"runtime_measurement_commitment",
"receipt_hash",
):
require_sha256(getattr(self, field), field=field)
require_ed25519_public_key(self.signer_public_key, field="signer_public_key")
require_ed25519_signature(self.signature, field="signature")
issued = parse_timestamp(self.issued_at, field="issued_at")
expires = parse_timestamp(self.expires_at, field="expires_at")
if expires <= issued:
raise SchemaError(DenialCode.INVALID_VALUE, field="expires_at")
@classmethod
def issue(
cls,
*,
kind: ReceiptKind | str,
packet_identity: str,
session_identity: str,
purpose_commitment: str,
source_identity_commitment: str,
temporal_identity_commitment: str,
observer_transcript_commitment: str,
policy_commitment: str,
runtime_measurement_commitment: str,
verdict: ReceiptVerdict | str,
issued_at: datetime,
expires_at: datetime,
signer_id: str,
private_key: Ed25519PrivateKey | bytes | str,
) -> Self:
key = load_ed25519_private_key(private_key)
values: dict[str, Any] = {
"schema": RECEIPT_SCHEMA,
"kind": str(ReceiptKind(kind)),
"packet_identity": packet_identity,
"session_identity": session_identity,
"purpose_commitment": purpose_commitment,
"source_identity_commitment": source_identity_commitment,
"temporal_identity_commitment": temporal_identity_commitment,
"observer_transcript_commitment": observer_transcript_commitment,
"policy_commitment": policy_commitment,
"runtime_measurement_commitment": runtime_measurement_commitment,
"verdict": str(ReceiptVerdict(verdict)),
"issued_at": format_timestamp(issued_at),
"expires_at": format_timestamp(expires_at),
"signer_id": signer_id,
"signer_public_key": ed25519_public_key_hex(key),
}
receipt_hash = domain_hash("aureon.plumber.receipt.v0", values)
signature = sign_ed25519(key, {"receipt_hash": receipt_hash}, domain=_RECEIPT_SIGNATURE_DOMAIN)
return cls(**values, receipt_hash=receipt_hash, signature=signature)
@classmethod
def from_dict(cls, value: Mapping[str, Any]) -> Self:
return cls(**require_exact_keys(value, _RECEIPT_FIELDS, field="receipt"))
def unsigned_payload(self) -> dict[str, Any]:
return {
field: getattr(self, field)
for field in _RECEIPT_FIELDS
if field not in {"receipt_hash", "signature"}
}
def to_dict(self) -> dict[str, Any]:
return {field: getattr(self, field) for field in _RECEIPT_FIELDS}
def validate(
self,
*,
now: datetime,
expected_packet_identity: str | None = None,
expected_session_identity: str | None = None,
expected_purpose_commitment: str | None = None,
expected_signer_public_key: str | None = None,
require_approved: bool = True,
) -> ReceiptValidation:
denials: set[str] = set()
if domain_hash("aureon.plumber.receipt.v0", self.unsigned_payload()) != self.receipt_hash:
denials.add(str(DenialCode.INVALID_SIGNATURE))
if not verify_ed25519(
self.signer_public_key,
{"receipt_hash": self.receipt_hash},
self.signature,
domain=_RECEIPT_SIGNATURE_DOMAIN,
):
denials.add(str(DenialCode.INVALID_SIGNATURE))
if expected_packet_identity is not None and self.packet_identity != expected_packet_identity:
denials.add(str(DenialCode.PACKET_IDENTITY_MISMATCH))
if expected_session_identity is not None and self.session_identity != expected_session_identity:
denials.add(str(DenialCode.SESSION_IDENTITY_MISMATCH))
if expected_purpose_commitment is not None and self.purpose_commitment != expected_purpose_commitment:
denials.add(str(DenialCode.PURPOSE_MISMATCH))
if expected_signer_public_key is not None and self.signer_public_key != expected_signer_public_key:
denials.add(str(DenialCode.SIGNER_MISMATCH))
current = require_aware_datetime(now, field="now")
if current < parse_timestamp(self.issued_at, field="issued_at"):
denials.add(str(DenialCode.FUTURE_STATE))
if current >= parse_timestamp(self.expires_at, field="expires_at"):
denials.add(str(DenialCode.STALE_STATE))
if require_approved and self.verdict != ReceiptVerdict.APPROVED:
denials.add(str(DenialCode.POLICY_RECEIPT_INVALID))
return ReceiptValidation(valid=not denials, denial_codes=tuple(sorted(denials)))
def public_summary(self) -> dict[str, Any]:
return {
"schema": self.schema,
"kind": self.kind,
"packet_identity": self.packet_identity,
"session_identity": self.session_identity,
"purpose_commitment": self.purpose_commitment,
"verdict": self.verdict,
"expires_at": self.expires_at,
"signer_id": self.signer_id,
"signer_public_key": self.signer_public_key,
"receipt_hash": self.receipt_hash,
}
def sign_receipt(**values: Any) -> SignedReceipt:
"""Compatibility-friendly function form of :meth:`SignedReceipt.issue`."""
return SignedReceipt.issue(**values)
def validate_receipt(receipt: SignedReceipt, **expectations: Any) -> ReceiptValidation:
return receipt.validate(**expectations)
__all__ = [
"RECEIPT_SCHEMA",
"ReceiptKind",
"ReceiptValidation",
"ReceiptVerdict",
"SignedReceipt",
"sign_receipt",
"validate_receipt",
]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395"""Verifier-owned recipient challenge and possession proof for Magic Star v0.2."""
from __future__ import annotations
import re
import secrets
import threading
import time
from collections.abc import Callable, Mapping
from dataclasses import dataclass
from typing import Any
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
from .crypto import (
b64url_encode,
domain_hash,
ed25519_public_key_hex,
sign_ed25519,
verify_ed25519,
)
CHALLENGE_SCHEMA = "aureon.plumber.magic-star.recipient-challenge.v02"
PROOF_SCHEMA = "aureon.plumber.magic-star.recipient-proof.v02"
_SIGNING_DOMAIN = "AUREON-PLUMBER-V02-RECIPIENT-PROOF"
_IDENTIFIER = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._:/-]{0,127}$")
_SHA256 = re.compile(r"^[0-9a-f]{64}$")
_PUBLIC_KEY = re.compile(r"^[0-9a-f]{64}$")
_SIGNATURE = re.compile(r"^[0-9a-f]{128}$")
_MAX_CHALLENGE_TTL_MS = 5 * 60 * 1000
class RecipientProofError(ValueError):
def __init__(self, code: str) -> None:
self.code = str(code)
super().__init__(self.code)
def _identifier(value: object, *, code: str) -> str:
if not isinstance(value, str) or _IDENTIFIER.fullmatch(value) is None:
raise RecipientProofError(code)
return value
def _sha256(value: object, *, code: str) -> str:
if not isinstance(value, str) or _SHA256.fullmatch(value) is None:
raise RecipientProofError(code)
return value
def _uint(value: object, *, code: str) -> int:
if isinstance(value, bool) or not isinstance(value, int) or value < 0:
raise RecipientProofError(code)
return value
def _system_now_ms() -> int:
return time.time_ns() // 1_000_000
@dataclass(frozen=True, slots=True)
class RecipientEnrollmentV02:
recipient_id: str
principal: str
key_id: str
public_key_hex: str
allowed_channel_bindings: tuple[str, ...]
allowed_purposes: tuple[str, ...]
def __post_init__(self) -> None:
if not isinstance(self.allowed_channel_bindings, list | tuple):
raise RecipientProofError("recipient_channel_policy_invalid")
if not isinstance(self.allowed_purposes, list | tuple):
raise RecipientProofError("recipient_purpose_policy_invalid")
object.__setattr__(
self,
"allowed_channel_bindings",
tuple(self.allowed_channel_bindings),
)
object.__setattr__(self, "allowed_purposes", tuple(self.allowed_purposes))
_identifier(self.recipient_id, code="recipient_id_invalid")
_identifier(self.principal, code="recipient_principal_invalid")
_identifier(self.key_id, code="recipient_key_id_invalid")
if not isinstance(self.public_key_hex, str) or _PUBLIC_KEY.fullmatch(self.public_key_hex) is None:
raise RecipientProofError("recipient_public_key_invalid")
if not self.allowed_channel_bindings or len(set(self.allowed_channel_bindings)) != len(
self.allowed_channel_bindings
):
raise RecipientProofError("recipient_channel_policy_invalid")
for value in self.allowed_channel_bindings:
_sha256(value, code="recipient_channel_policy_invalid")
if not self.allowed_purposes or len(set(self.allowed_purposes)) != len(self.allowed_purposes):
raise RecipientProofError("recipient_purpose_policy_invalid")
for value in self.allowed_purposes:
_identifier(value, code="recipient_purpose_policy_invalid")
@dataclass(frozen=True, slots=True)
class RecipientChallengeV02:
schema: str
challenge_id: str
session_id: str
packet_commitment: str
purpose: str
channel_binding_sha256: str
nonce: str
issued_at_ms: int
expires_at_ms: int
def payload(self) -> dict[str, Any]:
return {
"schema": self.schema,
"challenge_id": self.challenge_id,
"session_id": self.session_id,
"packet_commitment": self.packet_commitment,
"purpose": self.purpose,
"channel_binding_sha256": self.channel_binding_sha256,
"nonce": self.nonce,
"issued_at_ms": self.issued_at_ms,
"expires_at_ms": self.expires_at_ms,
}
@property
def commitment(self) -> str:
return domain_hash("AUREON-PLUMBER-V02-RECIPIENT-CHALLENGE", self.payload())
@dataclass(frozen=True, slots=True)
class RecipientProofV02:
schema: str
challenge_commitment: str
recipient_id: str
principal: str
key_id: str
session_id: str
packet_commitment: str
purpose: str
channel_binding_sha256: str
signed_at_ms: int
signature_hex: str
def signed_payload(self) -> dict[str, Any]:
return {
"schema": self.schema,
"challenge_commitment": self.challenge_commitment,
"recipient_id": self.recipient_id,
"principal": self.principal,
"key_id": self.key_id,
"session_id": self.session_id,
"packet_commitment": self.packet_commitment,
"purpose": self.purpose,
"channel_binding_sha256": self.channel_binding_sha256,
"signed_at_ms": self.signed_at_ms,
}
def public_dict(self) -> dict[str, Any]:
return {**self.signed_payload(), "signature_hex": self.signature_hex}
@property
def commitment(self) -> str:
return domain_hash("AUREON-PLUMBER-V02-RECIPIENT-PROOF-RECEIPT", self.public_dict())
def build_recipient_challenge_v02(
*,
session_id: str,
packet_commitment: str,
purpose: str,
channel_binding_sha256: str,
ttl_ms: int = 60_000,
trusted_now_ms: Callable[[], int] = _system_now_ms,
) -> RecipientChallengeV02:
now = _uint(trusted_now_ms(), code="trusted_time_invalid")
ttl = _uint(ttl_ms, code="challenge_ttl_invalid")
if ttl == 0 or ttl > _MAX_CHALLENGE_TTL_MS:
raise RecipientProofError("challenge_ttl_invalid")
return RecipientChallengeV02(
schema=CHALLENGE_SCHEMA,
challenge_id=f"challenge-{b64url_encode(secrets.token_bytes(18))}",
session_id=_identifier(session_id, code="session_id_invalid"),
packet_commitment=_sha256(packet_commitment, code="packet_commitment_invalid"),
purpose=_identifier(purpose, code="purpose_invalid"),
channel_binding_sha256=_sha256(channel_binding_sha256, code="channel_binding_invalid"),
nonce=b64url_encode(secrets.token_bytes(32)),
issued_at_ms=now,
expires_at_ms=now + ttl,
)
def build_recipient_proof_v02(
challenge: RecipientChallengeV02,
*,
enrollment: RecipientEnrollmentV02,
private_key: Ed25519PrivateKey,
trusted_now_ms: Callable[[], int] = _system_now_ms,
) -> RecipientProofV02:
if not isinstance(challenge, RecipientChallengeV02):
raise RecipientProofError("challenge_type_invalid")
now = _uint(trusted_now_ms(), code="trusted_time_invalid")
if now < challenge.issued_at_ms or now >= challenge.expires_at_ms:
raise RecipientProofError("challenge_not_current")
if ed25519_public_key_hex(private_key) != enrollment.public_key_hex:
raise RecipientProofError("recipient_private_key_not_enrolled")
if challenge.channel_binding_sha256 not in enrollment.allowed_channel_bindings:
raise RecipientProofError("recipient_channel_not_enrolled")
if challenge.purpose not in enrollment.allowed_purposes:
raise RecipientProofError("recipient_purpose_not_enrolled")
unsigned = RecipientProofV02(
schema=PROOF_SCHEMA,
challenge_commitment=challenge.commitment,
recipient_id=enrollment.recipient_id,
principal=enrollment.principal,
key_id=enrollment.key_id,
session_id=challenge.session_id,
packet_commitment=challenge.packet_commitment,
purpose=challenge.purpose,
channel_binding_sha256=challenge.channel_binding_sha256,
signed_at_ms=now,
signature_hex="",
)
return RecipientProofV02(
**unsigned.signed_payload(),
signature_hex=sign_ed25519(private_key, unsigned.signed_payload(), domain=_SIGNING_DOMAIN),
)
def verify_recipient_proof_v02(
proof: RecipientProofV02,
challenge: RecipientChallengeV02,
*,
enrollment: RecipientEnrollmentV02,
expected_packet_commitment: str,
expected_purpose: str,
expected_channel_binding_sha256: str,
trusted_now_ms: Callable[[], int] = _system_now_ms,
) -> dict[str, Any]:
if not isinstance(proof, RecipientProofV02) or not isinstance(challenge, RecipientChallengeV02):
raise RecipientProofError("recipient_proof_type_invalid")
expected_packet = _sha256(expected_packet_commitment, code="packet_commitment_invalid")
expected_channel = _sha256(expected_channel_binding_sha256, code="channel_binding_invalid")
purpose = _identifier(expected_purpose, code="purpose_invalid")
now = _uint(trusted_now_ms(), code="trusted_time_invalid")
if challenge.schema != CHALLENGE_SCHEMA or proof.schema != PROOF_SCHEMA:
raise RecipientProofError("recipient_wire_downgrade_or_schema_mismatch")
if now < challenge.issued_at_ms or now >= challenge.expires_at_ms:
raise RecipientProofError("challenge_not_current")
if (
proof.signed_at_ms < challenge.issued_at_ms
or proof.signed_at_ms > now
or proof.signed_at_ms >= challenge.expires_at_ms
):
raise RecipientProofError("recipient_proof_timestamp_invalid")
if proof.challenge_commitment != challenge.commitment:
raise RecipientProofError("recipient_challenge_commitment_mismatch")
exact = {
"session_id": challenge.session_id,
"packet_commitment": expected_packet,
"purpose": purpose,
"channel_binding_sha256": expected_channel,
}
if any(getattr(challenge, key) != value or getattr(proof, key) != value for key, value in exact.items()):
raise RecipientProofError("recipient_context_mismatch")
if (
proof.recipient_id != enrollment.recipient_id
or proof.principal != enrollment.principal
or proof.key_id != enrollment.key_id
):
raise RecipientProofError("recipient_enrollment_mismatch")
if expected_channel not in enrollment.allowed_channel_bindings or purpose not in enrollment.allowed_purposes:
raise RecipientProofError("recipient_enrollment_policy_denied")
if not isinstance(proof.signature_hex, str) or _SIGNATURE.fullmatch(proof.signature_hex) is None:
raise RecipientProofError("recipient_signature_invalid")
if not verify_ed25519(
enrollment.public_key_hex,
proof.signed_payload(),
proof.signature_hex,
domain=_SIGNING_DOMAIN,
):
raise RecipientProofError("recipient_signature_invalid")
return {
"valid": True,
"recipient_id": proof.recipient_id,
"session_id": proof.session_id,
"packet_commitment": proof.packet_commitment,
"purpose": proof.purpose,
"channel_binding_sha256": proof.channel_binding_sha256,
"proof_commitment": proof.commitment,
}
class RecipientProofVerifierV02:
"""Verifier-owned enrollment, challenge issuance, and one-use registry."""
production_ready = False
def __init__(
self,
*,
enrollments: Mapping[str, RecipientEnrollmentV02],
trusted_now_ms: Callable[[], int] = _system_now_ms,
) -> None:
if not enrollments or not callable(trusted_now_ms):
raise RecipientProofError("recipient_verifier_configuration_invalid")
normalized: dict[str, RecipientEnrollmentV02] = {}
for recipient_id, enrollment in enrollments.items():
if (
not isinstance(enrollment, RecipientEnrollmentV02)
or recipient_id != enrollment.recipient_id
or recipient_id in normalized
):
raise RecipientProofError("recipient_enrollment_registry_invalid")
normalized[recipient_id] = enrollment
self._enrollments = normalized
self._trusted_now_ms = trusted_now_ms
self._issued: dict[str, RecipientChallengeV02] = {}
self._consumed: set[str] = set()
self._sessions: set[str] = set()
self._lock = threading.RLock()
def enrollment_for(self, recipient_id: str) -> RecipientEnrollmentV02:
identity = _identifier(recipient_id, code="recipient_id_invalid")
enrollment = self._enrollments.get(identity)
if enrollment is None:
raise RecipientProofError("recipient_not_enrolled")
return enrollment
def issue_challenge(
self,
*,
session_id: str,
packet_commitment: str,
purpose: str,
channel_binding_sha256: str,
ttl_ms: int = 60_000,
) -> RecipientChallengeV02:
with self._lock:
session = _identifier(session_id, code="session_id_invalid")
if session in self._sessions:
raise RecipientProofError("recipient_challenge_session_reused")
challenge = build_recipient_challenge_v02(
session_id=session,
packet_commitment=packet_commitment,
purpose=purpose,
channel_binding_sha256=channel_binding_sha256,
ttl_ms=ttl_ms,
trusted_now_ms=self._trusted_now_ms,
)
self._issued[challenge.commitment] = challenge
self._sessions.add(session)
return challenge
def verify_and_consume(
self,
proof: RecipientProofV02,
challenge: RecipientChallengeV02,
*,
expected_packet_commitment: str,
expected_purpose: str,
expected_channel_binding_sha256: str,
) -> dict[str, Any]:
if not isinstance(proof, RecipientProofV02):
raise RecipientProofError("recipient_proof_type_invalid")
with self._lock:
commitment = challenge.commitment
issued = self._issued.get(commitment)
if issued != challenge:
raise RecipientProofError("recipient_challenge_not_verifier_issued")
if commitment in self._consumed:
raise RecipientProofError("recipient_challenge_replayed")
enrollment = self.enrollment_for(proof.recipient_id)
summary = verify_recipient_proof_v02(
proof,
challenge,
enrollment=enrollment,
expected_packet_commitment=expected_packet_commitment,
expected_purpose=expected_purpose,
expected_channel_binding_sha256=expected_channel_binding_sha256,
trusted_now_ms=self._trusted_now_ms,
)
self._consumed.add(commitment)
return summary
__all__ = [
"CHALLENGE_SCHEMA",
"PROOF_SCHEMA",
"RecipientChallengeV02",
"RecipientEnrollmentV02",
"RecipientProofError",
"RecipientProofV02",
"RecipientProofVerifierV02",
"build_recipient_challenge_v02",
"build_recipient_proof_v02",
"verify_recipient_proof_v02",
]12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199"""Pinned, fail-closed orchestration for the Magic Star v0.2 local lab.
Every trust root, evidence probe, recipient verifier, and capability policy is
pinned when the boundary is constructed. The implementation is intentionally
process-local: it is useful for deterministic integration and attack testing,
but it is not an HSM, sandbox, durable replay ledger, or production release
service.
"""
from __future__ import annotations
import re
import threading
import time
from collections.abc import Callable, Mapping, Sequence
from dataclasses import dataclass
from typing import Any
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
from .authorization_chain_v02 import (
AUTHORIZATION_ROLES,
AuthorizationChainError,
AuthorizationChainV02,
validate_authorization_chain_v02,
)
from .crypto import canonical_json_bytes, domain_hash, ed25519_public_key_hex
from .magic_star_v02 import (
POINT_ROLES,
PROFILE_ID,
PROTOCOL_ID,
SOURCE_PROFILE_COMMITMENT,
AuthorityBindingV02,
MagicStarError,
MagicStarV02,
build_candidate_center_v02,
build_heart_source_identity_commitment_v02,
component_commitment_v02,
sign_component_v02,
validate_magic_star_v02,
verify_component_v02,
)
from .recipient_proof_v02 import (
RecipientChallengeV02,
RecipientEnrollmentV02,
RecipientProofError,
RecipientProofV02,
RecipientProofVerifierV02,
)
from .release_evidence_v02 import (
ORGAN_ROLES,
RELEASE_EVIDENCE_ROLES,
ReleaseEvidenceError,
ReleaseEvidenceV02,
validate_release_evidence_v02,
)
from .release_state_v02 import (
EPAS_STATE_SCHEMA,
STATE_SCHEMA,
EPASChainSnapshot,
InMemoryEPASChainStoreV02,
InMemoryReleaseStateStoreV02,
OpaqueEPASReservation,
ReleasePhase,
ReleaseStateError,
ReleaseStateSnapshot,
)
from .schema import freeze_mapping, thaw_json
from .star_custody_v02 import (
LocalDevelopmentStarCustodyV02,
ProtectedMagicStarPacketV02,
StarCustodyError,
validate_magic_star_hnc_packet_v02,
)
RELEASE_BOUNDARY_SCHEMA = "aureon.plumber.magic-star.release-boundary.v02"
CAPABILITY_POLICY_SCHEMA = "aureon.plumber.magic-star.capability-policy.v02"
CAPABILITY_RECEIPT_SCHEMA = "aureon.plumber.magic-star.capability-receipt.v02"
_IDENTIFIER = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._:/-]{0,127}$")
_SHA256 = re.compile(r"^[0-9a-f]{64}$")
_FORBIDDEN_RESULT_KEY = re.compile(
r"(?:plain(?:text)?|payload|secret|private|master.?key|raw.?key|key.?share|"
r"share.?bytes|carrier|ciphertext|nonce|lease.?token)",
re.IGNORECASE,
)
_MAX_LIVE_AGE_MS = 5_000
_MAX_RESULT_BYTES = 64 * 1024
_RECEIPT_PAYLOAD_FIELDS = {
"schema",
"protocol_id",
"profile_id",
"source_profile_commitment",
"packet_id",
"packet_commitment",
"session_id",
"purpose",
"release_context_sha256",
"recipient_proof_commitment",
"star_commitment",
"epas_commitment",
"live_binding_sha256",
"runtime_measurement_sha256",
"policy_measurement_sha256",
"release_proof_commitment",
"authorization_chain_commitment",
"custody_authorization_commitment",
"capability_id",
"capability_measurement_sha256",
"capability_policy_commitment",
"capability_result_sha256",
"result_bytes",
"state_transition",
"epas_previous_epoch",
"epas_previous_head_sha256",
"epas_next_epoch",
"epas_next_head_sha256",
"issued_at_ms",
"plaintext_returned",
"keys_returned",
"shares_returned",
"carrier_returned",
"production_ready",
}
class ReleaseBoundaryError(ValueError):
"""Stable, non-secret denial from the v0.2 release boundary."""
def __init__(self, code: str) -> None:
candidate = str(code)
self.code = (
candidate
if _IDENTIFIER.fullmatch(candidate) is not None
else "release_boundary_denied"
)
super().__init__(self.code)
def _identifier(value: object, *, code: str) -> str:
if not isinstance(value, str) or _IDENTIFIER.fullmatch(value) is None:
raise ReleaseBoundaryError(code)
return value
def _sha256(value: object, *, code: str) -> str:
if not isinstance(value, str) or _SHA256.fullmatch(value) is None:
raise ReleaseBoundaryError(code)
return value
def _uint(value: object, *, code: str) -> int:
if isinstance(value, bool) or not isinstance(value, int) or value < 0:
raise ReleaseBoundaryError(code)
return value
def _system_now_ms() -> int:
return time.time_ns() // 1_000_000
def build_release_context_v02(
*,
packet_id: str,
session_id: str,
purpose: str,
channel_binding_sha256: str,
temporal_commitment: str,
observer_commitment: str,
live_binding_sha256: str,
runtime_measurement_sha256: str,
policy_measurement_sha256: str,
) -> str:
"""Build the non-circular context committed before packet protection."""
return domain_hash(
"AUREON-PLUMBER-V02-RELEASE-CONTEXT",
{
"protocol_id": PROTOCOL_ID,
"profile_id": PROFILE_ID,
"source_profile_commitment": SOURCE_PROFILE_COMMITMENT,
"packet_id": _identifier(packet_id, code="packet_id_invalid"),
"session_id": _identifier(session_id, code="session_id_invalid"),
"purpose": _identifier(purpose, code="purpose_invalid"),
"channel_binding_sha256": _sha256(
channel_binding_sha256, code="channel_binding_invalid"
),
"temporal_commitment": _sha256(
temporal_commitment, code="temporal_commitment_invalid"
),
"observer_commitment": _sha256(
observer_commitment, code="observer_commitment_invalid"
),
"live_binding_sha256": _sha256(
live_binding_sha256, code="live_binding_invalid"
),
"runtime_measurement_sha256": _sha256(
runtime_measurement_sha256, code="runtime_measurement_invalid"
),
"policy_measurement_sha256": _sha256(
policy_measurement_sha256, code="policy_measurement_invalid"
),
},
)
@dataclass(frozen=True, slots=True)
class LiveBindingEvidenceV02:
live_binding_sha256: str
runtime_measurement_sha256: str
policy_measurement_sha256: str
observed_at_ms: int
valid: bool
def validate(self, *, trusted_now_ms: int, max_age_ms: int) -> None:
now = _uint(trusted_now_ms, code="trusted_time_invalid")
observed = _uint(self.observed_at_ms, code="live_observed_at_invalid")
age_limit = _uint(max_age_ms, code="live_age_policy_invalid")
if self.valid is not True:
raise ReleaseBoundaryError("live_binding_not_valid")
_sha256(self.live_binding_sha256, code="live_binding_invalid")
_sha256(self.runtime_measurement_sha256, code="runtime_measurement_invalid")
_sha256(self.policy_measurement_sha256, code="policy_measurement_invalid")
if observed > now or now - observed > age_limit:
raise ReleaseBoundaryError("live_binding_stale_or_future")
def public_dict(self) -> dict[str, Any]:
return {
"live_binding_sha256": self.live_binding_sha256,
"runtime_measurement_sha256": self.runtime_measurement_sha256,
"policy_measurement_sha256": self.policy_measurement_sha256,
"observed_at_ms": self.observed_at_ms,
"valid": self.valid,
}
@dataclass(frozen=True, slots=True)
class ContinuityStateEvidenceV02:
previous_decision_head_sha256: str
revocation_epoch: int
observed_at_ms: int
valid: bool
def validate(self, *, trusted_now_ms: int, max_age_ms: int) -> None:
now = _uint(trusted_now_ms, code="trusted_time_invalid")
observed = _uint(self.observed_at_ms, code="continuity_observed_at_invalid")
_sha256(self.previous_decision_head_sha256, code="continuity_head_invalid")
_uint(self.revocation_epoch, code="revocation_epoch_invalid")
if self.valid is not True or observed > now or now - observed > max_age_ms:
raise ReleaseBoundaryError("continuity_state_stale_or_invalid")
@dataclass(frozen=True, slots=True)
class EvidenceExpectationsV02:
organ_evidence_sha256_by_role: Mapping[str, str]
star_point_evidence_sha256_by_role: Mapping[str, str]
epas_source_lineage_sha256: str
epas_evidence_sha256: str
epas_evidence_class: str
def __post_init__(self) -> None:
organ_evidence = freeze_mapping(
self.organ_evidence_sha256_by_role,
field="organ_evidence_sha256_by_role",
)
star_point_evidence = freeze_mapping(
self.star_point_evidence_sha256_by_role,
field="star_point_evidence_sha256_by_role",
)
object.__setattr__(
self,
"organ_evidence_sha256_by_role",
organ_evidence,
)
object.__setattr__(
self,
"star_point_evidence_sha256_by_role",
star_point_evidence,
)
self.validate()
def validate(self) -> None:
if set(self.organ_evidence_sha256_by_role) != set(ORGAN_ROLES):
raise ReleaseBoundaryError("expected_organ_evidence_set_invalid")
if set(self.star_point_evidence_sha256_by_role) != set(POINT_ROLES):
raise ReleaseBoundaryError("expected_star_evidence_set_invalid")
for value in self.organ_evidence_sha256_by_role.values():
_sha256(value, code="expected_organ_evidence_invalid")
for value in self.star_point_evidence_sha256_by_role.values():
_sha256(value, code="expected_star_evidence_invalid")
_sha256(self.epas_source_lineage_sha256, code="epas_source_lineage_invalid")
_sha256(self.epas_evidence_sha256, code="epas_evidence_invalid")
_identifier(self.epas_evidence_class, code="epas_evidence_class_invalid")
def _walk_result_keys(value: Any) -> None:
if isinstance(value, Mapping):
for key, item in value.items():
if not isinstance(key, str) or _FORBIDDEN_RESULT_KEY.search(key):
raise ReleaseBoundaryError("capability_result_forbidden_field")
_walk_result_keys(item)
elif isinstance(value, Sequence) and not isinstance(value, str | bytes | bytearray):
for item in value:
_walk_result_keys(item)
@dataclass(frozen=True, slots=True)
class CapabilityPolicyV02:
capability_id: str
capability_measurement_sha256: str
allowed_output_keys: tuple[str, ...]
output_types_by_key: Mapping[str, str]
required_output_keys: tuple[str, ...] = ()
max_result_bytes: int = 16 * 1024
def __post_init__(self) -> None:
if not isinstance(self.allowed_output_keys, list | tuple):
raise ReleaseBoundaryError("capability_allowed_output_invalid")
if not isinstance(self.required_output_keys, list | tuple):
raise ReleaseBoundaryError("capability_required_output_invalid")
if not isinstance(self.output_types_by_key, Mapping):
raise ReleaseBoundaryError("capability_output_types_invalid")
object.__setattr__(self, "allowed_output_keys", tuple(self.allowed_output_keys))
object.__setattr__(self, "required_output_keys", tuple(self.required_output_keys))
normalized_types = dict(self.output_types_by_key)
object.__setattr__(
self,
"output_types_by_key",
freeze_mapping(normalized_types, field="capability_output_types"),
)
_identifier(self.capability_id, code="capability_id_invalid")
_sha256(
self.capability_measurement_sha256,
code="capability_measurement_invalid",
)
if not self.allowed_output_keys or len(set(self.allowed_output_keys)) != len(
self.allowed_output_keys
):
raise ReleaseBoundaryError("capability_allowed_output_invalid")
if len(set(self.required_output_keys)) != len(
self.required_output_keys
) or not set(self.required_output_keys).issubset(self.allowed_output_keys):
raise ReleaseBoundaryError("capability_required_output_invalid")
if set(normalized_types) != set(self.allowed_output_keys) or any(
value_type != "bool" for value_type in normalized_types.values()
):
raise ReleaseBoundaryError("capability_output_types_invalid")
for key in (*self.allowed_output_keys, *self.required_output_keys):
_identifier(key, code="capability_output_key_invalid")
if _FORBIDDEN_RESULT_KEY.search(key):
raise ReleaseBoundaryError("capability_output_key_forbidden")
maximum = _uint(self.max_result_bytes, code="capability_result_limit_invalid")
if maximum == 0 or maximum > _MAX_RESULT_BYTES:
raise ReleaseBoundaryError("capability_result_limit_invalid")
@property
def commitment(self) -> str:
return domain_hash(
"AUREON-PLUMBER-V02-CAPABILITY-POLICY",
{
"schema": CAPABILITY_POLICY_SCHEMA,
"capability_id": self.capability_id,
"capability_measurement_sha256": self.capability_measurement_sha256,
"allowed_output_keys": list(self.allowed_output_keys),
"output_types_by_key": dict(self.output_types_by_key),
"required_output_keys": list(self.required_output_keys),
"max_result_bytes": self.max_result_bytes,
},
)
def validate_result(self, result: Mapping[str, Any]) -> tuple[dict[str, Any], str]:
if not isinstance(result, Mapping):
raise ReleaseBoundaryError("capability_result_must_be_mapping")
public_result = dict(result)
keys = set(public_result)
if not keys.issubset(self.allowed_output_keys) or not set(
self.required_output_keys
).issubset(keys):
raise ReleaseBoundaryError("capability_result_schema_denied")
_walk_result_keys(public_result)
if any(
self.output_types_by_key.get(key) != "bool" or type(value) is not bool
for key, value in public_result.items()
):
raise ReleaseBoundaryError("capability_result_type_denied")
try:
encoded = canonical_json_bytes(public_result)
except (TypeError, ValueError) as exc:
raise ReleaseBoundaryError("capability_result_not_canonical") from exc
if len(encoded) > self.max_result_bytes:
raise ReleaseBoundaryError("capability_result_too_large")
return public_result, domain_hash(
"AUREON-PLUMBER-V02-CAPABILITY-RESULT", public_result
)
@dataclass(frozen=True, slots=True)
class CapabilityReleaseResultV02:
result: Mapping[str, Any]
receipt: Mapping[str, Any]
release_state: ReleaseStateSnapshot
epas_state: EPASChainSnapshot
def __post_init__(self) -> None:
object.__setattr__(self, "result", freeze_mapping(self.result, field="result"))
object.__setattr__(self, "receipt", freeze_mapping(self.receipt, field="receipt"))
def public_dict(self) -> dict[str, Any]:
return {
"schema": RELEASE_BOUNDARY_SCHEMA,
"result": thaw_json(self.result),
"receipt": thaw_json(self.receipt),
"release_state": self.release_state.public_dict(),
"epas_state": self.epas_state.public_dict(),
"production_ready": False,
}
def _validate_trust_constellation(
*,
star_trust: Mapping[str, AuthorityBindingV02],
evidence_trust: Mapping[str, AuthorityBindingV02],
authorization_trust: Mapping[str, AuthorityBindingV02],
receipt_authority: AuthorityBindingV02,
enrollment: RecipientEnrollmentV02 | None = None,
) -> None:
combined: dict[str, AuthorityBindingV02] = {}
required_sets = (
(star_trust, set(POINT_ROLES) | {"EPAS", "HEART", "STAR_SEAL"}),
(evidence_trust, set(RELEASE_EVIDENCE_ROLES)),
(authorization_trust, set(AUTHORIZATION_ROLES)),
)
for trust, required in required_sets:
if set(trust) != required:
raise ReleaseBoundaryError("trust_constellation_role_set_invalid")
for role, binding in trust.items():
if not isinstance(binding, AuthorityBindingV02) or binding.role != role:
raise ReleaseBoundaryError("trust_constellation_binding_invalid")
existing = combined.get(role)
if existing is not None and existing != binding:
raise ReleaseBoundaryError("shared_authority_binding_mismatch")
combined[role] = binding
if receipt_authority.role != "CAPABILITY_RECEIPT":
raise ReleaseBoundaryError("capability_receipt_authority_invalid")
combined["CAPABILITY_RECEIPT"] = receipt_authority
bindings = list(combined.values())
for attribute, code in (
("public_key_hex", "constellation_keys_not_distinct"),
("key_id", "constellation_key_ids_not_distinct"),
("principal", "constellation_principals_not_distinct"),
("issuer", "constellation_issuers_not_distinct"),
):
values = [getattr(binding, attribute) for binding in bindings]
if len(values) != len(set(values)):
raise ReleaseBoundaryError(code)
if enrollment is not None and (
enrollment.public_key_hex in {item.public_key_hex for item in bindings}
or enrollment.key_id in {item.key_id for item in bindings}
or enrollment.principal in {item.principal for item in bindings}
):
raise ReleaseBoundaryError("recipient_authority_not_distinct")
def _require_exact_join(summary: Mapping[str, Any], expected: Mapping[str, Any]) -> None:
for key, value in expected.items():
if summary.get(key) != value:
raise ReleaseBoundaryError(f"release_join_mismatch_{key}")
def _predicted_epas_head(
*,
previous: EPASChainSnapshot,
terminal_star_sha256: str,
session_id: str,
authorization_sha256: str,
outcome: str,
) -> str:
return domain_hash(
"AUREON-PLUMBER-V02-EPAS-MEMORY",
{
"previous_epoch": previous.epoch,
"previous_head_sha256": previous.head_sha256,
"terminal_star_sha256": terminal_star_sha256,
"session_id": session_id,
"authorization_sha256": authorization_sha256,
"outcome": outcome,
"next_epoch": previous.epoch + 1,
},
)
def validate_capability_release_result_v02(
result: CapabilityReleaseResultV02,
*,
receipt_authority: AuthorityBindingV02,
expected_join: Mapping[str, Any] | None = None,
) -> dict[str, Any]:
"""Validate signed result-object consistency without a durable provider query."""
if not isinstance(result, CapabilityReleaseResultV02):
raise ReleaseBoundaryError("capability_release_result_type_invalid")
if (
result.release_state.schema != STATE_SCHEMA
or result.release_state.phase is not ReleasePhase.CONSUMED
or result.release_state.terminal_reason is not None
or result.epas_state.schema != EPAS_STATE_SCHEMA
):
raise ReleaseBoundaryError("capability_release_state_not_consumed")
try:
payload = verify_component_v02(
result.receipt,
expected_type="CAPABILITY_RELEASE_RECEIPT",
expected_authority=receipt_authority,
)
except MagicStarError as exc:
raise ReleaseBoundaryError(exc.code) from exc
if set(payload) != _RECEIPT_PAYLOAD_FIELDS:
raise ReleaseBoundaryError("capability_receipt_shape_invalid")
fixed = {
"schema": CAPABILITY_RECEIPT_SCHEMA,
"protocol_id": PROTOCOL_ID,
"profile_id": PROFILE_ID,
"source_profile_commitment": SOURCE_PROFILE_COMMITMENT,
"state_transition": "CUSTODY_TO_CONSUMED",
"plaintext_returned": False,
"keys_returned": False,
"shares_returned": False,
"carrier_returned": False,
"production_ready": False,
}
if any(payload.get(key) != value for key, value in fixed.items()):
raise ReleaseBoundaryError("capability_receipt_contract_invalid")
for key in (
"packet_commitment",
"release_context_sha256",
"recipient_proof_commitment",
"star_commitment",
"epas_commitment",
"live_binding_sha256",
"runtime_measurement_sha256",
"policy_measurement_sha256",
"release_proof_commitment",
"authorization_chain_commitment",
"custody_authorization_commitment",
"capability_measurement_sha256",
"capability_policy_commitment",
"capability_result_sha256",
"epas_previous_head_sha256",
"epas_next_head_sha256",
):
_sha256(payload.get(key), code=f"capability_receipt_{key}_invalid")
for key in ("packet_id", "session_id", "purpose", "capability_id"):
_identifier(payload.get(key), code=f"capability_receipt_{key}_invalid")
for key in (
"result_bytes",
"epas_previous_epoch",
"epas_next_epoch",
"issued_at_ms",
):
_uint(payload.get(key), code=f"capability_receipt_{key}_invalid")
_identifier(result.release_state.session_id, code="release_state_session_id_invalid")
_identifier(result.release_state.packet_id, code="release_state_packet_id_invalid")
_identifier(result.release_state.purpose, code="release_state_purpose_invalid")
_sha256(
result.release_state.live_binding_sha256,
code="release_state_live_binding_invalid",
)
_uint(result.release_state.expires_at_ms, code="release_state_expiry_invalid")
_uint(result.release_state.version, code="release_state_version_invalid")
epas_epoch = _uint(result.epas_state.epoch, code="epas_state_epoch_invalid")
epas_head = _sha256(result.epas_state.head_sha256, code="epas_state_head_invalid")
previous_epoch = _uint(
payload["epas_previous_epoch"], code="capability_receipt_epas_previous_epoch_invalid"
)
next_epoch = _uint(
payload["epas_next_epoch"], code="capability_receipt_epas_next_epoch_invalid"
)
previous_head = _sha256(
payload["epas_previous_head_sha256"],
code="capability_receipt_epas_previous_head_invalid",
)
expected_epas_head = _predicted_epas_head(
previous=EPASChainSnapshot(
schema=EPAS_STATE_SCHEMA,
epoch=previous_epoch,
head_sha256=previous_head,
),
terminal_star_sha256=payload["star_commitment"],
session_id=payload["session_id"],
authorization_sha256=payload["authorization_chain_commitment"],
outcome="CONSUMED",
)
result_hash = domain_hash(
"AUREON-PLUMBER-V02-CAPABILITY-RESULT", dict(result.result)
)
if (
payload.get("capability_result_sha256") != result_hash
or payload.get("result_bytes") != len(canonical_json_bytes(result.result))
or payload.get("session_id") != result.release_state.session_id
or payload.get("packet_id") != result.release_state.packet_id
or payload.get("purpose") != result.release_state.purpose
or payload.get("live_binding_sha256")
!= result.release_state.live_binding_sha256
or next_epoch != previous_epoch + 1
or epas_epoch != next_epoch
or epas_head != expected_epas_head
or payload.get("epas_next_head_sha256") != expected_epas_head
):
raise ReleaseBoundaryError("capability_result_readback_mismatch")
if expected_join is not None:
_require_exact_join(payload, expected_join)
return {
"valid": True,
"session_id": payload["session_id"],
"packet_commitment": payload["packet_commitment"],
"capability_id": payload["capability_id"],
"capability_result_sha256": result_hash,
"epas_next_head_sha256": result.epas_state.head_sha256,
"production_ready": False,
}
class LocalDevelopmentReleaseBoundaryV02:
"""Laboratory same-process release coordinator with pinned local trust."""
production_ready = False
def __init__(
self,
*,
allow_insecure_same_process: bool,
state_store: InMemoryReleaseStateStoreV02,
epas_store: InMemoryEPASChainStoreV02,
custody: LocalDevelopmentStarCustodyV02,
recipient_verifier: RecipientProofVerifierV02,
star_trust: Mapping[str, AuthorityBindingV02],
release_evidence_trust: Mapping[str, AuthorityBindingV02],
authorization_trust: Mapping[str, AuthorityBindingV02],
receipt_authority: AuthorityBindingV02,
receipt_private_key: Ed25519PrivateKey,
capability_policies: Mapping[str, CapabilityPolicyV02],
live_binding_probe: Callable[[], LiveBindingEvidenceV02],
continuity_state_probe: Callable[[str, str], ContinuityStateEvidenceV02],
evidence_expectations_probe: Callable[[str, str], EvidenceExpectationsV02],
trusted_now_ms: Callable[[], int] = _system_now_ms,
max_live_age_ms: int = _MAX_LIVE_AGE_MS,
) -> None:
if allow_insecure_same_process is not True:
raise ReleaseBoundaryError("explicit_insecure_same_process_opt_in_required")
if not isinstance(state_store, InMemoryReleaseStateStoreV02):
raise ReleaseBoundaryError("release_state_store_invalid")
if not isinstance(epas_store, InMemoryEPASChainStoreV02):
raise ReleaseBoundaryError("epas_state_store_invalid")
if not isinstance(custody, LocalDevelopmentStarCustodyV02):
raise ReleaseBoundaryError("star_custody_invalid")
if not isinstance(recipient_verifier, RecipientProofVerifierV02):
raise ReleaseBoundaryError("recipient_verifier_invalid")
_validate_trust_constellation(
star_trust=star_trust,
evidence_trust=release_evidence_trust,
authorization_trust=authorization_trust,
receipt_authority=receipt_authority,
)
if ed25519_public_key_hex(receipt_private_key) != receipt_authority.public_key_hex:
raise ReleaseBoundaryError("capability_receipt_signer_key_mismatch")
if not capability_policies:
raise ReleaseBoundaryError("capability_policy_registry_invalid")
policies: dict[str, CapabilityPolicyV02] = {}
for capability_id, policy in capability_policies.items():
if (
not isinstance(policy, CapabilityPolicyV02)
or capability_id != policy.capability_id
or capability_id in policies
or custody.capability_measurement(capability_id)
!= policy.capability_measurement_sha256
or custody.capability_policy_measurement(capability_id)
!= policy.commitment
or custody.capability_result_schema(capability_id)
!= dict(policy.output_types_by_key)
):
raise ReleaseBoundaryError("capability_policy_registry_invalid")
policies[capability_id] = policy
if not all(
callable(probe)
for probe in (
live_binding_probe,
continuity_state_probe,
evidence_expectations_probe,
trusted_now_ms,
)
):
raise ReleaseBoundaryError("release_runtime_probe_invalid")
maximum_age = _uint(max_live_age_ms, code="live_age_policy_invalid")
if maximum_age == 0 or maximum_age > 60_000:
raise ReleaseBoundaryError("live_age_policy_invalid")
self._state_store = state_store
self._epas_store = epas_store
self._custody = custody
self._recipient_verifier = recipient_verifier
self._star_trust = dict(star_trust)
self._release_evidence_trust = dict(release_evidence_trust)
self._authorization_trust = dict(authorization_trust)
self._receipt_authority = receipt_authority
self._receipt_private_key = receipt_private_key
self._capability_policies = policies
self._live_binding_probe = live_binding_probe
self._continuity_state_probe = continuity_state_probe
self._evidence_expectations_probe = evidence_expectations_probe
self._trusted_now_ms = trusted_now_ms
self._max_live_age_ms = maximum_age
self._lock = threading.RLock()
def release(
self,
packet: ProtectedMagicStarPacketV02,
*,
session_id: str,
challenge: RecipientChallengeV02,
recipient_proof: RecipientProofV02,
temporal_commitment: str,
observer_commitment: str,
expected_channel_binding_sha256: str,
expected_live_binding_sha256: str,
expected_runtime_measurement_sha256: str,
star: MagicStarV02,
release_evidence: ReleaseEvidenceV02,
authorization_chain: AuthorizationChainV02,
capability_id: str,
) -> CapabilityReleaseResultV02:
"""Validate all joins, execute one registered capability, and consume."""
created = False
consumed = False
epas_advanced = False
epas_reservation: OpaqueEPASReservation | None = None
original_epas: EPASChainSnapshot | None = None
authorization_commitment = "0" * 64
denial_code = "release_boundary_denied"
session = _identifier(session_id, code="session_id_invalid")
with self._lock:
try:
selected_id = _identifier(capability_id, code="capability_id_invalid")
capability_policy = self._capability_policies.get(selected_id)
if capability_policy is None:
raise ReleaseBoundaryError("capability_not_authorized")
enrollment = self._recipient_verifier.enrollment_for(
recipient_proof.recipient_id
)
_validate_trust_constellation(
star_trust=self._star_trust,
evidence_trust=self._release_evidence_trust,
authorization_trust=self._authorization_trust,
receipt_authority=self._receipt_authority,
enrollment=enrollment,
)
packet_preflight = validate_magic_star_hnc_packet_v02(
packet,
source_authority=self._star_trust["SOURCE"],
)
heart_source_identity = build_heart_source_identity_commitment_v02(
source_authority=self._star_trust["SOURCE"],
packet_id=packet.packet_id,
packet_commitment=packet.packet_commitment,
source_signature_commitment=packet_preflight[
"source_signature_commitment"
],
)
channel = _sha256(
expected_channel_binding_sha256, code="channel_binding_invalid"
)
live = _sha256(expected_live_binding_sha256, code="live_binding_invalid")
runtime = _sha256(
expected_runtime_measurement_sha256,
code="runtime_measurement_invalid",
)
temporal = _sha256(
temporal_commitment, code="temporal_commitment_invalid"
)
observer = _sha256(
observer_commitment, code="observer_commitment_invalid"
)
policy = capability_policy.commitment
expected_context = build_release_context_v02(
packet_id=packet.packet_id,
session_id=session,
purpose=packet.purpose,
channel_binding_sha256=channel,
temporal_commitment=temporal,
observer_commitment=observer,
live_binding_sha256=live,
runtime_measurement_sha256=runtime,
policy_measurement_sha256=policy,
)
if packet.release_context_sha256 != expected_context:
raise ReleaseBoundaryError("protected_packet_release_context_mismatch")
self._recipient_verifier.verify_and_consume(
recipient_proof,
challenge,
expected_packet_commitment=packet.packet_commitment,
expected_purpose=packet.purpose,
expected_channel_binding_sha256=channel,
)
expectations = self._evidence_expectations_probe(
packet.packet_id, session
)
if not isinstance(expectations, EvidenceExpectationsV02):
raise ReleaseBoundaryError("evidence_expectations_probe_invalid")
expectations.validate()
epas_commitment = component_commitment_v02(star.epas_precondition)
heart_commitment = component_commitment_v02(star.heart_precondition)
candidate_center = build_candidate_center_v02(
release_context_sha256=expected_context,
packet_commitment=packet.packet_commitment,
recipient_proof_commitment=recipient_proof.commitment,
purpose=packet.purpose,
temporal_commitment=temporal,
observer_commitment=observer,
epas_commitment=epas_commitment,
heart_commitment=heart_commitment,
)
star_summary = validate_magic_star_v02(
star,
trust=self._star_trust,
expected_release_context_sha256=expected_context,
expected_candidate_center_sha256=candidate_center,
trusted_now_ms=self._trusted_now_ms,
)
original_epas = self._epas_store.snapshot()
epas_payload = verify_component_v02(
star.epas_precondition,
expected_type="EPAS_PRECONDITION",
expected_authority=self._star_trust["EPAS"],
)
_require_exact_join(
epas_payload,
{
"release_context_sha256": expected_context,
"source_lineage_sha256": expectations.epas_source_lineage_sha256,
"evidence_sha256": expectations.epas_evidence_sha256,
"evidence_class": expectations.epas_evidence_class,
"previous_memory_head_sha256": original_epas.head_sha256,
"memory_epoch": original_epas.epoch,
"verdict": "CLEAR",
"outcome": "PROCEED",
"physical_effects_claimed": False,
},
)
heart_payload = verify_component_v02(
star.heart_precondition,
expected_type="HEART_PRECONDITION",
expected_authority=self._star_trust["HEART"],
)
_require_exact_join(
heart_payload,
{
"release_context_sha256": expected_context,
"packet_id": packet.packet_id,
"packet_commitment": packet.packet_commitment,
"session_id": session,
"purpose": packet.purpose,
"source_identity_commitment": heart_source_identity,
"temporal_commitment": temporal,
"observer_commitment": observer,
"policy_commitment": policy,
"runtime_measurement_sha256": runtime,
"verdict": "APPROVE",
"heart_frequency": "528",
},
)
star_share_bindings: list[str] = []
for role, component in zip(POINT_ROLES, star.points, strict=True):
point_payload = verify_component_v02(
component,
expected_type="MAGIC_STAR_POINT",
expected_authority=self._star_trust[role],
)
if point_payload.get("evidence_sha256") != expectations.star_point_evidence_sha256_by_role[
role
]:
raise ReleaseBoundaryError("star_point_evidence_substitution_detected")
star_share_bindings.append(
_sha256(
point_payload.get("share_binding_sha256"),
code="star_share_binding_invalid",
)
)
packet_share_bindings = [
item["binding_sha256"] for item in packet.share_bindings
]
if star_share_bindings != packet_share_bindings:
raise ReleaseBoundaryError("five_share_binding_join_mismatch")
evidence_summary = validate_release_evidence_v02(
release_evidence,
trust=self._release_evidence_trust,
expected_evidence_sha256_by_role=expectations.organ_evidence_sha256_by_role,
trusted_now_ms=self._trusted_now_ms,
)
shared = {
"packet_commitment": packet.packet_commitment,
"session_id": session,
"purpose": packet.purpose,
"release_context_sha256": expected_context,
"recipient_proof_commitment": recipient_proof.commitment,
"star_commitment": star.commitment,
"epas_commitment": epas_commitment,
"live_binding_sha256": live,
"runtime_measurement_sha256": runtime,
"policy_measurement_sha256": policy,
}
_require_exact_join(evidence_summary, shared)
continuity = self._continuity_state_probe(packet.packet_id, session)
if not isinstance(continuity, ContinuityStateEvidenceV02):
raise ReleaseBoundaryError("continuity_state_probe_invalid")
continuity.validate(
trusted_now_ms=_uint(
self._trusted_now_ms(), code="trusted_time_invalid"
),
max_age_ms=self._max_live_age_ms,
)
authorization_expected = {
**shared,
"release_proof_commitment": evidence_summary[
"release_proof_commitment"
],
}
authorization_summary = validate_authorization_chain_v02(
authorization_chain,
trust=self._authorization_trust,
expected_previous_decision_head_sha256=continuity.previous_decision_head_sha256,
expected_revocation_epoch=continuity.revocation_epoch,
expected_join=authorization_expected,
trusted_now_ms=self._trusted_now_ms,
)
if authorization_summary.get("share_bindings") != packet_share_bindings:
raise ReleaseBoundaryError("five_share_binding_join_mismatch")
authorization_commitment = authorization_chain.commitment
expiry = min(
challenge.expires_at_ms,
_uint(star_summary["expires_at_ms"], code="star_expiry_invalid"),
_uint(
evidence_summary["expires_at_ms"],
code="release_evidence_expiry_invalid",
),
_uint(
authorization_summary["expires_at_ms"],
code="authorization_expiry_invalid",
),
)
self._state_store.create(
session_id=session,
packet_id=packet.packet_id,
purpose=packet.purpose,
live_binding_sha256=live,
expires_at_ms=expiry,
)
created = True
epas_reservation = self._epas_store.reserve(
expected_epoch=original_epas.epoch,
expected_head_sha256=original_epas.head_sha256,
)
sampled = self._live_binding_probe()
if not isinstance(sampled, LiveBindingEvidenceV02):
raise ReleaseBoundaryError("live_binding_probe_type_invalid")
sampled.validate(
trusted_now_ms=_uint(
self._trusted_now_ms(), code="trusted_time_invalid"
),
max_age_ms=self._max_live_age_ms,
)
_require_exact_join(
sampled.public_dict(),
{
"live_binding_sha256": live,
"runtime_measurement_sha256": runtime,
"policy_measurement_sha256": policy,
"valid": True,
},
)
latest_continuity = self._continuity_state_probe(
packet.packet_id, session
)
if not isinstance(latest_continuity, ContinuityStateEvidenceV02):
raise ReleaseBoundaryError("continuity_state_probe_invalid")
latest_continuity.validate(
trusted_now_ms=_uint(
self._trusted_now_ms(), code="trusted_time_invalid"
),
max_age_ms=self._max_live_age_ms,
)
if (
latest_continuity.previous_decision_head_sha256
!= continuity.previous_decision_head_sha256
or latest_continuity.revocation_epoch
!= continuity.revocation_epoch
or latest_continuity.valid is not True
):
raise ReleaseBoundaryError("continuity_state_changed_at_boundary")
now = _uint(self._trusted_now_ms(), code="trusted_time_invalid")
if now >= expiry:
raise ReleaseBoundaryError("release_session_expired_before_custody")
# Revalidate every expiring signed component at the last boundary.
validate_magic_star_v02(
star,
trust=self._star_trust,
expected_release_context_sha256=expected_context,
expected_candidate_center_sha256=candidate_center,
trusted_now_ms=self._trusted_now_ms,
)
validate_release_evidence_v02(
release_evidence,
trust=self._release_evidence_trust,
expected_evidence_sha256_by_role=expectations.organ_evidence_sha256_by_role,
trusted_now_ms=self._trusted_now_ms,
)
validate_authorization_chain_v02(
authorization_chain,
trust=self._authorization_trust,
expected_previous_decision_head_sha256=continuity.previous_decision_head_sha256,
expected_revocation_epoch=continuity.revocation_epoch,
expected_join=authorization_expected,
trusted_now_ms=self._trusted_now_ms,
)
self._state_store.reserve(
session_id=session,
expected_live_binding_sha256=sampled.live_binding_sha256,
)
lease = self._state_store.claim_custody(session_id=session)
raw_result, custody_metadata = self._custody.release_to_capability(
packet,
lease=lease,
authorization_chain=authorization_chain,
capability_id=selected_id,
)
result, result_sha256 = capability_policy.validate_result(raw_result)
_require_exact_join(
custody_metadata,
{
"capability_result_sha256": result_sha256,
"capability_id": selected_id,
"capability_measurement_sha256": capability_policy.capability_measurement_sha256,
"capability_policy_commitment": capability_policy.commitment,
},
)
receipt_issued_at_ms = _uint(
self._trusted_now_ms(), code="trusted_time_invalid"
)
if receipt_issued_at_ms >= expiry:
raise ReleaseBoundaryError("release_session_expired_during_capability")
predicted_head = _predicted_epas_head(
previous=original_epas,
terminal_star_sha256=star.commitment,
session_id=session,
authorization_sha256=authorization_commitment,
outcome="CONSUMED",
)
receipt_payload: dict[str, Any] = {
"schema": CAPABILITY_RECEIPT_SCHEMA,
"protocol_id": PROTOCOL_ID,
"profile_id": PROFILE_ID,
"source_profile_commitment": SOURCE_PROFILE_COMMITMENT,
"packet_id": packet.packet_id,
**shared,
"release_proof_commitment": evidence_summary[
"release_proof_commitment"
],
"authorization_chain_commitment": authorization_commitment,
"custody_authorization_commitment": authorization_summary[
"custody_authorization_commitment"
],
"capability_id": selected_id,
"capability_measurement_sha256": capability_policy.capability_measurement_sha256,
"capability_policy_commitment": capability_policy.commitment,
"capability_result_sha256": result_sha256,
"result_bytes": len(canonical_json_bytes(result)),
"state_transition": "CUSTODY_TO_CONSUMED",
"epas_previous_epoch": original_epas.epoch,
"epas_previous_head_sha256": original_epas.head_sha256,
"epas_next_epoch": original_epas.epoch + 1,
"epas_next_head_sha256": predicted_head,
"issued_at_ms": receipt_issued_at_ms,
"plaintext_returned": False,
"keys_returned": False,
"shares_returned": False,
"carrier_returned": False,
"production_ready": False,
}
receipt = sign_component_v02(
component_type="CAPABILITY_RELEASE_RECEIPT",
authority=self._receipt_authority,
payload=receipt_payload,
private_key=self._receipt_private_key,
)
try:
verified_receipt_payload = verify_component_v02(
receipt,
expected_type="CAPABILITY_RELEASE_RECEIPT",
expected_authority=self._receipt_authority,
)
except MagicStarError as exc:
raise ReleaseBoundaryError(exc.code) from exc
if (
set(verified_receipt_payload) != _RECEIPT_PAYLOAD_FIELDS
or verified_receipt_payload != receipt_payload
):
raise ReleaseBoundaryError("capability_receipt_precommit_mismatch")
state_snapshot = self._state_store.consume(lease)
consumed = True
if state_snapshot.phase is not ReleasePhase.CONSUMED:
raise ReleaseBoundaryError("release_state_not_consumed")
epas_snapshot = self._epas_store.finalize(
epas_reservation,
terminal_star_sha256=star.commitment,
session_id=session,
authorization_sha256=authorization_commitment,
outcome="CONSUMED",
)
epas_advanced = True
if epas_snapshot.head_sha256 != predicted_head:
raise ReleaseBoundaryError("epas_terminal_readback_mismatch")
release_result = CapabilityReleaseResultV02(
result=result,
receipt=receipt,
release_state=state_snapshot,
epas_state=epas_snapshot,
)
validate_capability_release_result_v02(
release_result,
receipt_authority=self._receipt_authority,
expected_join={
"packet_commitment": packet.packet_commitment,
"session_id": session,
"capability_id": selected_id,
},
)
return release_result
except Exception as exc:
code = str(getattr(exc, "code", "release_boundary_denied"))
if created and not consumed:
try:
self._state_store.deny(session_id=session, reason=code)
except Exception:
pass
if (
epas_reservation is not None
and not epas_advanced
and original_epas is not None
):
try:
self._epas_store.finalize(
epas_reservation,
terminal_star_sha256=star.commitment,
session_id=session,
authorization_sha256=authorization_commitment,
outcome="DENIED",
)
except Exception:
pass
if isinstance(exc, ReleaseBoundaryError):
denial_code = exc.code
elif isinstance(
exc,
(
AuthorizationChainError,
MagicStarError,
RecipientProofError,
ReleaseEvidenceError,
ReleaseStateError,
StarCustodyError,
),
):
denial_code = code
raise ReleaseBoundaryError(denial_code) from None
# Long-form compatibility name retained for callers that include the protocol
# family in the local laboratory boundary type. Both names identify the same
# explicitly insecure, same-process implementation.
LocalDevelopmentMagicStarReleaseBoundaryV02 = LocalDevelopmentReleaseBoundaryV02
__all__ = [
"CAPABILITY_POLICY_SCHEMA",
"CAPABILITY_RECEIPT_SCHEMA",
"RELEASE_BOUNDARY_SCHEMA",
"CapabilityPolicyV02",
"CapabilityReleaseResultV02",
"ContinuityStateEvidenceV02",
"EvidenceExpectationsV02",
"LiveBindingEvidenceV02",
"LocalDevelopmentMagicStarReleaseBoundaryV02",
"LocalDevelopmentReleaseBoundaryV02",
"ReleaseBoundaryError",
"build_release_context_v02",
"validate_capability_release_result_v02",
]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648"""Pinned, one-shot, local-development release orchestration for Plumber v0.
The engine constructor pins trust, quorum policy, enclave, and replay state.
Only inspections issued by that engine instance may execute. There is no
production release path and no raw decrypted result in any return value.
"""
from __future__ import annotations
import threading
from collections.abc import Callable, Mapping, Sequence
from dataclasses import dataclass
from datetime import datetime
from enum import StrEnum
from typing import Any
from .crypto import domain_hash
from .enclave import (
EnclaveDisposition,
LocalComputationResult,
LocalDevelopmentEnclave,
LocalEnclaveAttestation,
LocalEnclaveExecutionReceipt,
)
from .immune_gate import (
GateClass,
GateDecision,
GateEvidence,
GateVerdict,
build_gate_context_commitment,
evaluate_immune_gate,
)
from .observer_transcript import ObserverTranscriptV0
from .packet import (
PacketDisposition,
PacketInspection,
PacketReplayGuard,
PacketTrustPolicy,
bind_hnc_packet,
inspect_plumber_packet,
)
from .quorum import AuthorityPermit
from .schema import (
DenialCode,
PlumberPacketV0,
SchemaError,
parse_timestamp,
require_aware_datetime,
require_sha256,
)
from .sympathetic_identity import SympatheticIdentityV0
class ReleaseDisposition(StrEnum):
ALLOW_LOCAL_DEVELOPMENT = "allow_local_development"
COMPLETED_LOCAL = "completed_local"
HOLD = "hold"
DENY = "deny"
class ReleaseCode(StrEnum):
PACKET_HOLD = "packet_hold"
PACKET_DENIED = "packet_denied"
PACKET_NOT_TRUSTED = "packet_not_trusted"
IMMUNE_GATE_HOLD = "immune_gate_hold"
IMMUNE_GATE_DENIED = "immune_gate_denied"
IMMUNE_GATE_CONTEXT_MISMATCH = "immune_gate_context_mismatch"
IMMUNE_GATE_BINDING_MISMATCH = "immune_gate_binding_mismatch"
IMMUNE_GATE_NOT_ISSUED = "immune_gate_not_issued"
QUORUM_NOT_VALIDATED = "quorum_not_validated"
TRUST_POLICY_MISMATCH = "trust_policy_mismatch"
QUORUM_POLICY_MISMATCH = "quorum_policy_mismatch"
ENCLAVE_ATTESTATION_INVALID = "enclave_attestation_invalid"
PURPOSE_MISMATCH = "purpose_mismatch"
INSPECTION_NOT_ISSUED = "inspection_not_issued"
INSPECTION_TIME_ROLLBACK = "inspection_time_rollback"
INSPECTION_EVIDENCE_EXPIRED = "inspection_evidence_expired"
REPLAY_DETECTED = "replay_detected"
ENCLAVE_HOLD = "enclave_hold"
ENCLAVE_DENIED = "enclave_denied"
ENCLAVE_RECEIPT_MISMATCH = "enclave_receipt_mismatch"
_REFRESHABLE_GATE_CODES = {
str(DenialCode.FUTURE_STATE),
str(DenialCode.POLICY_RECEIPT_MISSING),
str(DenialCode.STALE_STATE),
}
def _gate_for_inspection(packet: PacketInspection) -> GateDecision:
"""Build the only gate decision acceptable for one trusted inspection."""
context = build_gate_context_commitment(
packet_identity=packet.packet_identity,
session_identity=packet.session_identity,
purpose_commitment=packet.purpose_commitment,
)
evidence = tuple(
GateEvidence(
gate_class=gate_class,
receipt_commitment=packet.gate_evidence_commitments[str(gate_class)],
valid=True,
context_commitment=context,
)
for gate_class in GateClass
)
return evaluate_immune_gate(
evidence,
packet_inspection_commitment=packet.inspection_commitment,
evaluated_at=parse_timestamp(packet.inspected_at, field="inspected_at"),
expires_at=parse_timestamp(
packet.evidence_expires_at,
field="evidence_expires_at",
),
)
@dataclass(frozen=True, slots=True)
class ReleaseDecision:
disposition: ReleaseDisposition
packet_commitment: str
purpose_commitment: str
packet_inspection_commitment: str
gate_decision_commitment: str
quorum_commitment: str
trust_policy_commitment: str
quorum_policy_commitment: str
enclave_attestation_commitment: str
denial_codes: tuple[str, ...]
production_release: bool
decision_commitment: str
def __post_init__(self) -> None:
try:
disposition = ReleaseDisposition(self.disposition)
except ValueError as exc:
raise SchemaError(DenialCode.INVALID_VALUE, field="disposition") from exc
object.__setattr__(self, "disposition", disposition)
if disposition is ReleaseDisposition.COMPLETED_LOCAL:
raise SchemaError(DenialCode.INVALID_VALUE, field="disposition")
for field in (
"packet_commitment",
"purpose_commitment",
"packet_inspection_commitment",
"gate_decision_commitment",
"quorum_commitment",
"trust_policy_commitment",
"quorum_policy_commitment",
"enclave_attestation_commitment",
"decision_commitment",
):
require_sha256(getattr(self, field), field=field)
if tuple(sorted(set(self.denial_codes))) != self.denial_codes:
raise SchemaError(DenialCode.INVALID_VALUE, field="denial_codes")
if (disposition is ReleaseDisposition.ALLOW_LOCAL_DEVELOPMENT) != (not self.denial_codes):
raise SchemaError(DenialCode.INVALID_VALUE, field="disposition")
if self.production_release is not False:
raise SchemaError(DenialCode.INVALID_VALUE, field="production_release")
if domain_hash("aureon.plumber.local-release-decision.v0", self.commitment_payload()) != (
self.decision_commitment
):
raise SchemaError(DenialCode.INVALID_VALUE, field="decision_commitment")
@classmethod
def build(
cls,
*,
disposition: ReleaseDisposition,
packet: PacketInspection,
gate: GateDecision,
attestation: LocalEnclaveAttestation,
denial_codes: Sequence[ReleaseCode | str] = (),
) -> ReleaseDecision:
codes = tuple(sorted({str(code) for code in denial_codes}))
values = {
"disposition": str(disposition),
"packet_commitment": packet.packet_commitment,
"purpose_commitment": packet.purpose_commitment,
"packet_inspection_commitment": packet.inspection_commitment,
"gate_decision_commitment": gate.decision_commitment,
"quorum_commitment": packet.quorum_commitment,
"trust_policy_commitment": packet.trust_policy_commitment,
"quorum_policy_commitment": packet.quorum_policy_commitment,
"enclave_attestation_commitment": attestation.attestation_commitment,
"denial_codes": list(codes),
"production_release": False,
}
return cls(
disposition=disposition,
packet_commitment=packet.packet_commitment,
purpose_commitment=packet.purpose_commitment,
packet_inspection_commitment=packet.inspection_commitment,
gate_decision_commitment=gate.decision_commitment,
quorum_commitment=packet.quorum_commitment,
trust_policy_commitment=packet.trust_policy_commitment,
quorum_policy_commitment=packet.quorum_policy_commitment,
enclave_attestation_commitment=attestation.attestation_commitment,
denial_codes=codes,
production_release=False,
decision_commitment=domain_hash("aureon.plumber.local-release-decision.v0", values),
)
def commitment_payload(self) -> dict[str, Any]:
return {
"disposition": str(self.disposition),
"packet_commitment": self.packet_commitment,
"purpose_commitment": self.purpose_commitment,
"packet_inspection_commitment": self.packet_inspection_commitment,
"gate_decision_commitment": self.gate_decision_commitment,
"quorum_commitment": self.quorum_commitment,
"trust_policy_commitment": self.trust_policy_commitment,
"quorum_policy_commitment": self.quorum_policy_commitment,
"enclave_attestation_commitment": self.enclave_attestation_commitment,
"denial_codes": list(self.denial_codes),
"production_release": self.production_release,
}
def public_summary(self) -> dict[str, Any]:
return {**self.commitment_payload(), "decision_commitment": self.decision_commitment}
def evaluate_local_release(
packet: PacketInspection,
gate: GateDecision,
attestation: LocalEnclaveAttestation,
*,
required_trust_policy_commitment: str,
required_quorum_policy_commitment: str,
) -> ReleaseDecision:
"""Pure decision function with explicit trust and policy pins."""
if not isinstance(packet, PacketInspection):
raise SchemaError(DenialCode.INVALID_TYPE, field="packet_inspection")
if not isinstance(gate, GateDecision):
raise SchemaError(DenialCode.INVALID_TYPE, field="gate_decision")
if not isinstance(attestation, LocalEnclaveAttestation):
raise SchemaError(DenialCode.INVALID_TYPE, field="enclave_attestation")
require_sha256(required_trust_policy_commitment, field="required_trust_policy_commitment")
require_sha256(required_quorum_policy_commitment, field="required_quorum_policy_commitment")
hard: set[str] = set()
holds: set[str] = set()
if packet.disposition is PacketDisposition.DENY:
hard.add(str(ReleaseCode.PACKET_DENIED))
elif packet.disposition is PacketDisposition.HOLD:
holds.add(str(ReleaseCode.PACKET_HOLD))
if not packet.trusted:
hard.add(str(ReleaseCode.PACKET_NOT_TRUSTED))
if not packet.quorum_validated:
hard.add(str(ReleaseCode.QUORUM_NOT_VALIDATED))
expected_gate_context = build_gate_context_commitment(
packet_identity=packet.packet_identity,
session_identity=packet.session_identity,
purpose_commitment=packet.purpose_commitment,
)
if gate.context_commitment != expected_gate_context:
hard.add(str(ReleaseCode.IMMUNE_GATE_CONTEXT_MISMATCH))
expected_gate = _gate_for_inspection(packet)
if gate.decision_commitment != expected_gate.decision_commitment:
hard.add(str(ReleaseCode.IMMUNE_GATE_BINDING_MISMATCH))
if packet.trust_policy_commitment != required_trust_policy_commitment:
hard.add(str(ReleaseCode.TRUST_POLICY_MISMATCH))
if packet.quorum_policy_commitment != required_quorum_policy_commitment:
hard.add(str(ReleaseCode.QUORUM_POLICY_MISMATCH))
if gate.verdict is GateVerdict.DENIED:
if gate.denial_codes and set(gate.denial_codes) <= _REFRESHABLE_GATE_CODES:
holds.add(str(ReleaseCode.IMMUNE_GATE_HOLD))
else:
hard.add(str(ReleaseCode.IMMUNE_GATE_DENIED))
if not attestation.enabled or not attestation.local_development_only or attestation.production_capable:
hard.add(str(ReleaseCode.ENCLAVE_ATTESTATION_INVALID))
if packet.purpose_commitment not in attestation.allowed_purpose_commitments:
hard.add(str(ReleaseCode.PURPOSE_MISMATCH))
if hard:
disposition = ReleaseDisposition.DENY
codes = tuple(sorted(hard | holds))
elif holds:
disposition = ReleaseDisposition.HOLD
codes = tuple(sorted(holds))
else:
disposition = ReleaseDisposition.ALLOW_LOCAL_DEVELOPMENT
codes = ()
return ReleaseDecision.build(
disposition=disposition,
packet=packet,
gate=gate,
attestation=attestation,
denial_codes=codes,
)
@dataclass(frozen=True, slots=True)
class ReleaseExecutionReceipt:
disposition: ReleaseDisposition
packet_commitment: str
purpose_commitment: str
decision_commitment: str
enclave_receipt_commitment: str
denial_codes: tuple[str, ...]
production_release: bool
execution_commitment: str
def __post_init__(self) -> None:
try:
disposition = ReleaseDisposition(self.disposition)
except ValueError as exc:
raise SchemaError(DenialCode.INVALID_VALUE, field="disposition") from exc
object.__setattr__(self, "disposition", disposition)
if disposition is ReleaseDisposition.ALLOW_LOCAL_DEVELOPMENT:
raise SchemaError(DenialCode.INVALID_VALUE, field="disposition")
for field in (
"packet_commitment",
"purpose_commitment",
"decision_commitment",
"enclave_receipt_commitment",
"execution_commitment",
):
require_sha256(getattr(self, field), field=field)
if tuple(sorted(set(self.denial_codes))) != self.denial_codes:
raise SchemaError(DenialCode.INVALID_VALUE, field="denial_codes")
if (disposition is ReleaseDisposition.COMPLETED_LOCAL) != (not self.denial_codes):
raise SchemaError(DenialCode.INVALID_VALUE, field="disposition")
if self.production_release is not False:
raise SchemaError(DenialCode.INVALID_VALUE, field="production_release")
if domain_hash("aureon.plumber.local-release-execution.v0", self.commitment_payload()) != (
self.execution_commitment
):
raise SchemaError(DenialCode.INVALID_VALUE, field="execution_commitment")
@classmethod
def build(
cls,
*,
disposition: ReleaseDisposition,
decision: ReleaseDecision,
enclave_receipt_commitment: str,
denial_codes: Sequence[ReleaseCode | str] = (),
) -> ReleaseExecutionReceipt:
codes = tuple(sorted({str(code) for code in denial_codes}))
values = {
"disposition": str(disposition),
"packet_commitment": decision.packet_commitment,
"purpose_commitment": decision.purpose_commitment,
"decision_commitment": decision.decision_commitment,
"enclave_receipt_commitment": enclave_receipt_commitment,
"denial_codes": list(codes),
"production_release": False,
}
return cls(
disposition=disposition,
packet_commitment=decision.packet_commitment,
purpose_commitment=decision.purpose_commitment,
decision_commitment=decision.decision_commitment,
enclave_receipt_commitment=enclave_receipt_commitment,
denial_codes=codes,
production_release=False,
execution_commitment=domain_hash("aureon.plumber.local-release-execution.v0", values),
)
def commitment_payload(self) -> dict[str, Any]:
return {
"disposition": str(self.disposition),
"packet_commitment": self.packet_commitment,
"purpose_commitment": self.purpose_commitment,
"decision_commitment": self.decision_commitment,
"enclave_receipt_commitment": self.enclave_receipt_commitment,
"denial_codes": list(self.denial_codes),
"production_release": self.production_release,
}
def public_summary(self) -> dict[str, Any]:
return {**self.commitment_payload(), "execution_commitment": self.execution_commitment}
class LocalReleaseEngine:
"""One-shot engine with constructor-pinned trust, policy, and replay state."""
def __init__(
self,
*,
trust_policy: PacketTrustPolicy,
required_quorum_policy_commitment: str,
replay_guard: PacketReplayGuard,
enclave: LocalDevelopmentEnclave,
) -> None:
if not isinstance(trust_policy, PacketTrustPolicy):
raise SchemaError(DenialCode.INVALID_TYPE, field="trust_policy")
require_sha256(required_quorum_policy_commitment, field="required_quorum_policy_commitment")
if not isinstance(replay_guard, PacketReplayGuard):
raise SchemaError(DenialCode.INVALID_TYPE, field="replay_guard")
if not isinstance(enclave, LocalDevelopmentEnclave):
raise SchemaError(DenialCode.INVALID_TYPE, field="enclave")
self._trust_policy = trust_policy
self._required_quorum_policy_commitment = required_quorum_policy_commitment
self._replay_guard = replay_guard
self._enclave = enclave
self._lock = threading.Lock()
self._issued_inspections: set[str] = set()
self._issued_gates: dict[str, str] = {}
def inspect_packet(
self,
packet: PlumberPacketV0,
hnc_packet: Mapping[str, Any],
*,
observer_transcript: ObserverTranscriptV0,
sympathetic_identity: SympatheticIdentityV0,
quorum_permits: Sequence[AuthorityPermit],
now: datetime,
) -> PacketInspection:
inspection = inspect_plumber_packet(
packet,
hnc_packet,
now=now,
observer_transcript=observer_transcript,
sympathetic_identity=sympathetic_identity,
quorum_permits=quorum_permits,
trust_policy=self._trust_policy,
required_quorum_policy_commitment=self._required_quorum_policy_commitment,
replay_guard=self._replay_guard,
)
if inspection.disposition is PacketDisposition.VALID:
with self._lock:
self._issued_inspections.add(inspection.inspection_commitment)
return inspection
def issue_gate(self, packet: PacketInspection) -> GateDecision:
"""Issue the exact, one-use immune decision for an inspection from this engine."""
if not isinstance(packet, PacketInspection):
raise SchemaError(DenialCode.INVALID_TYPE, field="packet_inspection")
with self._lock:
issued = packet.inspection_commitment in self._issued_inspections
if not issued or packet.disposition is not PacketDisposition.VALID:
raise SchemaError(DenialCode.INVALID_VALUE, field="packet_inspection")
gate = _gate_for_inspection(packet)
with self._lock:
if packet.inspection_commitment not in self._issued_inspections:
raise SchemaError(DenialCode.INVALID_VALUE, field="packet_inspection")
self._issued_gates[gate.decision_commitment] = packet.inspection_commitment
return gate
def evaluate(self, packet: PacketInspection, gate: GateDecision) -> ReleaseDecision:
decision = evaluate_local_release(
packet,
gate,
self._enclave.attestation(),
required_trust_policy_commitment=self._trust_policy.trust_policy_commitment,
required_quorum_policy_commitment=self._required_quorum_policy_commitment,
)
if decision.disposition is not ReleaseDisposition.ALLOW_LOCAL_DEVELOPMENT:
return decision
with self._lock:
inspection_issued = packet.inspection_commitment in self._issued_inspections
gate_issued = (
self._issued_gates.get(gate.decision_commitment)
== packet.inspection_commitment
)
if not inspection_issued:
return ReleaseDecision.build(
disposition=ReleaseDisposition.DENY,
packet=packet,
gate=gate,
attestation=self._enclave.attestation(),
denial_codes=(ReleaseCode.INSPECTION_NOT_ISSUED,),
)
if not gate_issued:
return ReleaseDecision.build(
disposition=ReleaseDisposition.DENY,
packet=packet,
gate=gate,
attestation=self._enclave.attestation(),
denial_codes=(ReleaseCode.IMMUNE_GATE_NOT_ISSUED,),
)
return decision
def execute(
self,
packet: PacketInspection,
gate: GateDecision,
hnc_packet: Mapping[str, Any],
*,
master_key: bytes | str,
expected_purpose: str,
processor_id: str,
processor: Callable[[memoryview], LocalComputationResult],
now: datetime,
) -> tuple[ReleaseExecutionReceipt, LocalEnclaveExecutionReceipt | None]:
current = require_aware_datetime(now, field="now")
if not callable(processor):
raise SchemaError(DenialCode.INVALID_TYPE, field="processor")
decision = self.evaluate(packet, gate)
no_receipt = domain_hash(
"aureon.plumber.no-enclave-receipt.v0",
{"decision_commitment": decision.decision_commitment},
)
if decision.disposition is not ReleaseDisposition.ALLOW_LOCAL_DEVELOPMENT:
return (
ReleaseExecutionReceipt.build(
disposition=decision.disposition,
decision=decision,
enclave_receipt_commitment=no_receipt,
denial_codes=decision.denial_codes,
),
None,
)
with self._lock:
issued = decision.packet_inspection_commitment in self._issued_inspections
gate_issued = (
self._issued_gates.get(gate.decision_commitment)
== decision.packet_inspection_commitment
)
if issued and gate_issued:
self._issued_inspections.remove(decision.packet_inspection_commitment)
self._issued_gates.pop(gate.decision_commitment, None)
if not issued:
return self._blocked_execution(decision, no_receipt, ReleaseCode.INSPECTION_NOT_ISSUED)
if not gate_issued:
return self._blocked_execution(decision, no_receipt, ReleaseCode.IMMUNE_GATE_NOT_ISSUED)
inspected_at = parse_timestamp(packet.inspected_at, field="inspected_at")
evidence_not_before = parse_timestamp(
packet.evidence_not_before,
field="evidence_not_before",
)
evidence_expires_at = parse_timestamp(
packet.evidence_expires_at,
field="evidence_expires_at",
)
if current < inspected_at or current < evidence_not_before:
return self._blocked_execution(
decision,
no_receipt,
ReleaseCode.INSPECTION_TIME_ROLLBACK,
)
if current >= evidence_expires_at:
return self._blocked_execution(
decision,
no_receipt,
ReleaseCode.INSPECTION_EVIDENCE_EXPIRED,
)
if domain_hash("aureon.plumber.purpose.v0", expected_purpose) != decision.purpose_commitment:
return self._blocked_execution(decision, no_receipt, ReleaseCode.PURPOSE_MISMATCH)
try:
live_binding = bind_hnc_packet(hnc_packet)
except (SchemaError, TypeError, ValueError):
return self._blocked_execution(
decision, no_receipt, ReleaseCode.ENCLAVE_RECEIPT_MISMATCH
)
if (
live_binding.hnc_packet_commitment != packet.hnc_packet_commitment
or live_binding.purpose_commitment != packet.purpose_commitment
):
return self._blocked_execution(
decision, no_receipt, ReleaseCode.ENCLAVE_RECEIPT_MISMATCH
)
if not self._replay_guard.claim_for_execution(packet.replay_token):
return self._blocked_execution(decision, no_receipt, ReleaseCode.REPLAY_DETECTED)
try:
def one_shot_processor(view: memoryview) -> LocalComputationResult:
# Authentication and structural checks have completed when the
# enclave invokes this wrapper. Commit replay state before the
# caller's processor can produce effects, including effects that
# precede an exception or invalid result.
if not self._replay_guard.commit_execution_claim(packet.replay_token):
raise RuntimeError("replay_execution_claim_unavailable")
return processor(view)
enclave_receipt = self._enclave.execute_hnc_packet(
hnc_packet,
master_key=master_key,
expected_purpose=expected_purpose,
processor_id=processor_id,
processor=one_shot_processor,
now=current,
)
finally:
# If the processor wrapper was never reached, the claim still exists
# and is safe to roll back. A committed claim cannot be rolled back.
if self._replay_guard.rollback_execution_claim(packet.replay_token):
with self._lock:
if gate.decision_commitment not in self._issued_gates:
self._issued_inspections.add(
decision.packet_inspection_commitment
)
self._issued_gates[gate.decision_commitment] = (
decision.packet_inspection_commitment
)
mismatched = (
enclave_receipt.packet_commitment != packet.hnc_packet_commitment
or enclave_receipt.purpose_commitment != packet.purpose_commitment
)
if mismatched:
disposition = ReleaseDisposition.DENY
codes: tuple[ReleaseCode | str, ...] = (ReleaseCode.ENCLAVE_RECEIPT_MISMATCH,)
elif enclave_receipt.disposition is EnclaveDisposition.COMPLETED_LOCAL:
disposition = ReleaseDisposition.COMPLETED_LOCAL
codes = ()
elif enclave_receipt.disposition is EnclaveDisposition.HOLD:
disposition = ReleaseDisposition.HOLD
codes = (ReleaseCode.ENCLAVE_HOLD, *enclave_receipt.denial_codes)
else:
disposition = ReleaseDisposition.DENY
codes = (ReleaseCode.ENCLAVE_DENIED, *enclave_receipt.denial_codes)
return (
ReleaseExecutionReceipt.build(
disposition=disposition,
decision=decision,
enclave_receipt_commitment=enclave_receipt.receipt_commitment,
denial_codes=codes,
),
enclave_receipt,
)
@staticmethod
def _blocked_execution(
decision: ReleaseDecision,
no_receipt: str,
code: ReleaseCode,
) -> tuple[ReleaseExecutionReceipt, None]:
return (
ReleaseExecutionReceipt.build(
disposition=ReleaseDisposition.DENY,
decision=decision,
enclave_receipt_commitment=no_receipt,
denial_codes=(code,),
),
None,
)
def public_summary(self) -> dict[str, Any]:
return {
"scope": "local_development_only",
"trust_policy_commitment": self._trust_policy.trust_policy_commitment,
"quorum_policy_commitment": self._required_quorum_policy_commitment,
"enclave_attestation_commitment": self._enclave.attestation().attestation_commitment,
"production_release": False,
"replay_guard": self._replay_guard.public_summary(),
}
__all__ = [
"LocalReleaseEngine",
"ReleaseCode",
"ReleaseDecision",
"ReleaseDisposition",
"ReleaseExecutionReceipt",
"evaluate_local_release",
]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437"""Seven-organ post-Star evidence and release proof for Plumber v0.2."""
from __future__ import annotations
import time
from collections.abc import Callable, Mapping, Sequence
from dataclasses import dataclass
from typing import Any
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
from .magic_star_v02 import (
PROFILE_ID,
PROTOCOL_ID,
SOURCE_PROFILE_COMMITMENT,
AuthorityBindingV02,
MagicStarError,
component_commitment_v02,
sign_component_v02,
verify_component_v02,
)
from .schema import freeze_mapping, thaw_json
RELEASE_EVIDENCE_SCHEMA = "aureon.plumber.magic-star.release-evidence.v02"
ORGAN_ROLES = (
"SOURCE",
"OBSERVER",
"HEART",
"COHERENCE",
"CONSCIENCE",
"GOVERNANCE",
"OPERATOR",
)
RELEASE_EVIDENCE_ROLES = (*ORGAN_ROLES, "RELEASE_PROOF")
_MAX_COMPONENT_TTL_MS = 5 * 60 * 1000
_ORGAN_PAYLOAD_FIELDS = {
"protocol_id",
"profile_id",
"source_profile_commitment",
"role",
"packet_commitment",
"session_id",
"purpose",
"release_context_sha256",
"recipient_proof_commitment",
"star_commitment",
"epas_commitment",
"live_binding_sha256",
"runtime_measurement_sha256",
"policy_measurement_sha256",
"evidence_sha256",
"verdict",
"issued_at_ms",
"expires_at_ms",
}
_RELEASE_PROOF_PAYLOAD_FIELDS = {
"protocol_id",
"profile_id",
"source_profile_commitment",
"packet_commitment",
"session_id",
"purpose",
"release_context_sha256",
"recipient_proof_commitment",
"star_commitment",
"epas_commitment",
"live_binding_sha256",
"runtime_measurement_sha256",
"policy_measurement_sha256",
"organ_roles",
"organ_commitments",
"all_seven_required",
"proof_issued_at_ms",
"proof_expires_at_ms",
}
class ReleaseEvidenceError(ValueError):
def __init__(self, code: str) -> None:
self.code = str(code)
super().__init__(self.code)
def _sha256(value: object, *, code: str) -> str:
if not isinstance(value, str) or len(value) != 64 or any(c not in "0123456789abcdef" for c in value):
raise ReleaseEvidenceError(code)
return value
def _identifier(value: object, *, code: str) -> str:
if (
not isinstance(value, str)
or not value
or len(value) > 128
or any(not (c.isascii() and (c.isalnum() or c in "._:/-")) for c in value)
):
raise ReleaseEvidenceError(code)
return value
def _uint(value: object, *, code: str) -> int:
if isinstance(value, bool) or not isinstance(value, int) or value < 0:
raise ReleaseEvidenceError(code)
return value
def _system_now_ms() -> int:
return time.time_ns() // 1_000_000
def _validate_component_window(payload: Mapping[str, Any], *, now: int) -> None:
issued = _uint(payload.get("issued_at_ms"), code="organ_issued_at_invalid")
expires = _uint(payload.get("expires_at_ms"), code="organ_expires_at_invalid")
if issued > now or expires <= now or expires <= issued or expires - issued > _MAX_COMPONENT_TTL_MS:
raise ReleaseEvidenceError("organ_time_window_invalid")
def validate_release_evidence_trust_v02(
trust: Mapping[str, AuthorityBindingV02],
) -> None:
if set(trust) != set(RELEASE_EVIDENCE_ROLES):
raise ReleaseEvidenceError("release_evidence_authority_set_incomplete")
bindings = [trust[role] for role in RELEASE_EVIDENCE_ROLES]
for role, binding in zip(RELEASE_EVIDENCE_ROLES, bindings, strict=True):
if not isinstance(binding, AuthorityBindingV02) or binding.role != role:
raise ReleaseEvidenceError("release_evidence_authority_binding_mismatch")
for attribute, code in (
("public_key_hex", "release_evidence_keys_not_distinct"),
("key_id", "release_evidence_key_ids_not_distinct"),
("principal", "release_evidence_principals_not_distinct"),
("issuer", "release_evidence_issuers_not_distinct"),
):
values = [getattr(binding, attribute) for binding in bindings]
if len(set(values)) != len(values):
raise ReleaseEvidenceError(code)
def build_organ_receipt_v02(
*,
role: str,
packet_commitment: str,
session_id: str,
purpose: str,
release_context_sha256: str,
recipient_proof_commitment: str,
star_commitment: str,
epas_commitment: str,
live_binding_sha256: str,
runtime_measurement_sha256: str,
policy_measurement_sha256: str,
evidence_sha256: str,
verdict: str,
issued_at_ms: int,
expires_at_ms: int,
authority: AuthorityBindingV02,
private_key: Ed25519PrivateKey,
) -> dict[str, Any]:
if role not in ORGAN_ROLES or authority.role != role:
raise ReleaseEvidenceError("organ_role_invalid")
payload: dict[str, Any] = {
"protocol_id": PROTOCOL_ID,
"profile_id": PROFILE_ID,
"source_profile_commitment": SOURCE_PROFILE_COMMITMENT,
"role": role,
"packet_commitment": _sha256(packet_commitment, code="packet_commitment_invalid"),
"session_id": _identifier(session_id, code="session_id_invalid"),
"purpose": _identifier(purpose, code="purpose_invalid"),
"release_context_sha256": _sha256(release_context_sha256, code="release_context_invalid"),
"recipient_proof_commitment": _sha256(
recipient_proof_commitment, code="recipient_proof_commitment_invalid"
),
"star_commitment": _sha256(star_commitment, code="star_commitment_invalid"),
"epas_commitment": _sha256(epas_commitment, code="epas_commitment_invalid"),
"live_binding_sha256": _sha256(live_binding_sha256, code="live_binding_invalid"),
"runtime_measurement_sha256": _sha256(
runtime_measurement_sha256, code="runtime_measurement_invalid"
),
"policy_measurement_sha256": _sha256(
policy_measurement_sha256, code="policy_measurement_invalid"
),
"evidence_sha256": _sha256(evidence_sha256, code="organ_evidence_invalid"),
"verdict": str(verdict),
"issued_at_ms": _uint(issued_at_ms, code="organ_issued_at_invalid"),
"expires_at_ms": _uint(expires_at_ms, code="organ_expires_at_invalid"),
}
if payload["expires_at_ms"] <= payload["issued_at_ms"]:
raise ReleaseEvidenceError("organ_time_window_invalid")
try:
return sign_component_v02(
component_type="POST_STAR_ORGAN_RECEIPT",
authority=authority,
payload=payload,
private_key=private_key,
)
except MagicStarError as exc:
raise ReleaseEvidenceError(exc.code) from exc
@dataclass(frozen=True, slots=True)
class ReleaseEvidenceV02:
schema: str
organ_receipts: tuple[Mapping[str, Any], ...]
release_proof: Mapping[str, Any]
def __post_init__(self) -> None:
object.__setattr__(
self,
"organ_receipts",
tuple(
freeze_mapping(receipt, field=f"organ_receipts[{index}]")
for index, receipt in enumerate(self.organ_receipts)
),
)
object.__setattr__(
self,
"release_proof",
freeze_mapping(self.release_proof, field="release_proof"),
)
def public_dict(self) -> dict[str, Any]:
return {
"schema": self.schema,
"organ_receipts": [thaw_json(receipt) for receipt in self.organ_receipts],
"release_proof": thaw_json(self.release_proof),
}
@property
def commitment(self) -> str:
from .crypto import domain_hash
return domain_hash("AUREON-PLUMBER-V02-RELEASE-EVIDENCE", self.public_dict())
def assemble_release_evidence_v02(
*,
organ_receipts: Sequence[Mapping[str, Any]],
trust: Mapping[str, AuthorityBindingV02],
release_proof_authority: AuthorityBindingV02,
release_proof_private_key: Ed25519PrivateKey,
trusted_now_ms: Callable[[], int] = _system_now_ms,
) -> ReleaseEvidenceV02:
validate_release_evidence_trust_v02(trust)
if trust["RELEASE_PROOF"] != release_proof_authority:
raise ReleaseEvidenceError("release_proof_authority_mismatch")
if len(organ_receipts) != len(ORGAN_ROLES):
raise ReleaseEvidenceError("all_seven_organ_receipts_required")
now = _uint(trusted_now_ms(), code="trusted_time_invalid")
payloads: list[dict[str, Any]] = []
components: list[dict[str, Any]] = []
for role, receipt in zip(ORGAN_ROLES, organ_receipts, strict=True):
try:
payload = verify_component_v02(
receipt,
expected_type="POST_STAR_ORGAN_RECEIPT",
expected_authority=trust[role],
)
except MagicStarError as exc:
raise ReleaseEvidenceError(exc.code) from exc
if payload.get("role") != role:
raise ReleaseEvidenceError("organ_receipt_order_or_role_mismatch")
if set(payload) != _ORGAN_PAYLOAD_FIELDS or any(
payload.get(key) != value
for key, value in {
"protocol_id": PROTOCOL_ID,
"profile_id": PROFILE_ID,
"source_profile_commitment": SOURCE_PROFILE_COMMITMENT,
}.items()
):
raise ReleaseEvidenceError("organ_receipt_profile_or_shape_invalid")
if payload.get("verdict") != "APPROVE":
raise ReleaseEvidenceError("organ_receipt_denied")
_validate_component_window(payload, now=now)
payloads.append(payload)
components.append(dict(receipt))
join_fields = (
"packet_commitment",
"session_id",
"purpose",
"release_context_sha256",
"recipient_proof_commitment",
"star_commitment",
"epas_commitment",
"live_binding_sha256",
"runtime_measurement_sha256",
"policy_measurement_sha256",
)
for field in join_fields:
if len({payload[field] for payload in payloads}) != 1:
raise ReleaseEvidenceError(f"organ_join_mismatch_{field}")
proof_payload = {
"protocol_id": PROTOCOL_ID,
"profile_id": PROFILE_ID,
"source_profile_commitment": SOURCE_PROFILE_COMMITMENT,
**{field: payloads[0][field] for field in join_fields},
"organ_roles": list(ORGAN_ROLES),
"organ_commitments": [component_commitment_v02(component) for component in components],
"all_seven_required": True,
"proof_issued_at_ms": now,
"proof_expires_at_ms": min(
_uint(payload["expires_at_ms"], code="organ_expires_at_invalid") for payload in payloads
),
}
try:
release_proof = sign_component_v02(
component_type="RELEASE_PROOF",
authority=release_proof_authority,
payload=proof_payload,
private_key=release_proof_private_key,
)
except MagicStarError as exc:
raise ReleaseEvidenceError(exc.code) from exc
evidence = ReleaseEvidenceV02(
schema=RELEASE_EVIDENCE_SCHEMA,
organ_receipts=tuple(components),
release_proof=release_proof,
)
validate_release_evidence_v02(evidence, trust=trust, trusted_now_ms=trusted_now_ms)
return evidence
def validate_release_evidence_v02(
evidence: ReleaseEvidenceV02,
*,
trust: Mapping[str, AuthorityBindingV02],
expected_evidence_sha256_by_role: Mapping[str, str] | None = None,
trusted_now_ms: Callable[[], int] = _system_now_ms,
) -> dict[str, Any]:
if not isinstance(evidence, ReleaseEvidenceV02) or evidence.schema != RELEASE_EVIDENCE_SCHEMA:
raise ReleaseEvidenceError("release_evidence_schema_invalid")
validate_release_evidence_trust_v02(trust)
if len(evidence.organ_receipts) != len(ORGAN_ROLES):
raise ReleaseEvidenceError("all_seven_organ_receipts_required")
now = _uint(trusted_now_ms(), code="trusted_time_invalid")
payloads: list[dict[str, Any]] = []
commitments: list[str] = []
for role, receipt in zip(ORGAN_ROLES, evidence.organ_receipts, strict=True):
try:
payload = verify_component_v02(
receipt,
expected_type="POST_STAR_ORGAN_RECEIPT",
expected_authority=trust[role],
)
except MagicStarError as exc:
raise ReleaseEvidenceError(exc.code) from exc
if payload.get("role") != role:
raise ReleaseEvidenceError("organ_receipt_order_or_role_mismatch")
if set(payload) != _ORGAN_PAYLOAD_FIELDS or any(
payload.get(key) != value
for key, value in {
"protocol_id": PROTOCOL_ID,
"profile_id": PROFILE_ID,
"source_profile_commitment": SOURCE_PROFILE_COMMITMENT,
}.items()
):
raise ReleaseEvidenceError("organ_receipt_profile_or_shape_invalid")
if payload.get("verdict") != "APPROVE":
raise ReleaseEvidenceError("organ_receipt_denied")
_validate_component_window(payload, now=now)
if expected_evidence_sha256_by_role is not None:
if set(expected_evidence_sha256_by_role) != set(ORGAN_ROLES):
raise ReleaseEvidenceError("expected_organ_evidence_set_invalid")
expected_evidence = _sha256(
expected_evidence_sha256_by_role[role],
code="expected_organ_evidence_invalid",
)
if payload.get("evidence_sha256") != expected_evidence:
raise ReleaseEvidenceError("organ_evidence_substitution_detected")
payloads.append(payload)
commitments.append(component_commitment_v02(receipt))
try:
proof = verify_component_v02(
evidence.release_proof,
expected_type="RELEASE_PROOF",
expected_authority=trust["RELEASE_PROOF"],
)
except MagicStarError as exc:
raise ReleaseEvidenceError(exc.code) from exc
if set(proof) != _RELEASE_PROOF_PAYLOAD_FIELDS or any(
proof.get(key) != value
for key, value in {
"protocol_id": PROTOCOL_ID,
"profile_id": PROFILE_ID,
"source_profile_commitment": SOURCE_PROFILE_COMMITMENT,
}.items()
):
raise ReleaseEvidenceError("release_proof_profile_or_shape_invalid")
join_fields = (
"packet_commitment",
"session_id",
"purpose",
"release_context_sha256",
"recipient_proof_commitment",
"star_commitment",
"epas_commitment",
"live_binding_sha256",
"runtime_measurement_sha256",
"policy_measurement_sha256",
)
for field in join_fields:
expected = payloads[0].get(field)
if any(payload.get(field) != expected for payload in payloads) or proof.get(field) != expected:
raise ReleaseEvidenceError(f"release_proof_join_mismatch_{field}")
if (
proof.get("organ_roles") != list(ORGAN_ROLES)
or proof.get("organ_commitments") != commitments
or proof.get("all_seven_required") is not True
):
raise ReleaseEvidenceError("release_proof_organ_join_mismatch")
proof_issued = _uint(proof.get("proof_issued_at_ms"), code="release_proof_issued_at_invalid")
proof_expires = _uint(proof.get("proof_expires_at_ms"), code="release_proof_expiry_invalid")
expected_expiry = min(
_uint(payload["expires_at_ms"], code="organ_expires_at_invalid")
for payload in payloads
)
if proof_issued > now or proof_expires <= now or proof_expires != expected_expiry:
raise ReleaseEvidenceError("release_proof_expired")
return {
"valid": True,
**{field: proof[field] for field in join_fields},
"release_proof_commitment": component_commitment_v02(evidence.release_proof),
"release_evidence_commitment": evidence.commitment,
"organ_count": len(ORGAN_ROLES),
"expires_at_ms": proof_expires,
}
__all__ = [
"ORGAN_ROLES",
"RELEASE_EVIDENCE_ROLES",
"RELEASE_EVIDENCE_SCHEMA",
"ReleaseEvidenceError",
"ReleaseEvidenceV02",
"assemble_release_evidence_v02",
"build_organ_receipt_v02",
"validate_release_evidence_trust_v02",
"validate_release_evidence_v02",
]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453"""Atomic in-memory state model for the Plumber Magic Star v0.2 lab path.
The stores in this module model one-use and EPAS compare-and-set semantics. They
are deliberately process-local and rollbackable, so they are never production
evidence. Production requires a durable, monotonic, independently administered
state service.
"""
from __future__ import annotations
import re
import secrets
import threading
import time
from collections.abc import Callable
from dataclasses import dataclass, field, replace
from enum import StrEnum
from typing import Any
from .crypto import b64url_encode, domain_hash
STATE_SCHEMA = "aureon.plumber.magic-star.release-state.v02"
EPAS_STATE_SCHEMA = "aureon.plumber.magic-star.epas-state.v02"
_IDENTIFIER = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._:/-]{0,127}$")
_SHA256 = re.compile(r"^[0-9a-f]{64}$")
_MAX_SESSION_LIFETIME_MS = 15 * 60 * 1000
class ReleaseStateError(ValueError):
"""A stable fail-closed release-state error."""
def __init__(self, code: str) -> None:
self.code = str(code)
super().__init__(self.code)
class ReleasePhase(StrEnum):
CREATED = "CREATED"
RESERVED = "RESERVED"
CUSTODY = "CUSTODY"
CONSUMED = "CONSUMED"
DENIED = "DENIED"
@dataclass(frozen=True, slots=True)
class ReleaseStateSnapshot:
schema: str
session_id: str
packet_id: str
purpose: str
live_binding_sha256: str
expires_at_ms: int
phase: ReleasePhase
version: int
terminal_reason: str | None = None
def public_dict(self) -> dict[str, Any]:
return {
"schema": self.schema,
"session_id": self.session_id,
"packet_id": self.packet_id,
"purpose": self.purpose,
"live_binding_sha256": self.live_binding_sha256,
"expires_at_ms": self.expires_at_ms,
"phase": self.phase.value,
"version": self.version,
"terminal_reason": self.terminal_reason,
}
@dataclass(frozen=True, slots=True)
class OpaqueCustodyLease:
"""One-use lease. The secret token is omitted from repr and public views."""
session_id: str
packet_id: str
lease_token: str = field(repr=False)
@dataclass(slots=True)
class _MutableState:
snapshot: ReleaseStateSnapshot
lease_digest: str | None = None
def _identifier(value: object, *, code: str) -> str:
if not isinstance(value, str) or _IDENTIFIER.fullmatch(value) is None:
raise ReleaseStateError(code)
return value
def _sha256(value: object, *, code: str) -> str:
if not isinstance(value, str) or _SHA256.fullmatch(value) is None:
raise ReleaseStateError(code)
return value
def _uint(value: object, *, code: str) -> int:
if isinstance(value, bool) or not isinstance(value, int) or value < 0:
raise ReleaseStateError(code)
return value
def _system_now_ms() -> int:
return time.time_ns() // 1_000_000
class InMemoryReleaseStateStoreV02:
"""Thread-safe one-use state store for tests and local development only."""
production_ready = False
def __init__(self, *, trusted_now_ms: Callable[[], int] = _system_now_ms) -> None:
self._trusted_now_ms = trusted_now_ms
self._states: dict[str, _MutableState] = {}
self._lock = threading.RLock()
def _now(self) -> int:
return _uint(self._trusted_now_ms(), code="trusted_time_invalid")
def _active(self, session_id: str) -> _MutableState:
key = _identifier(session_id, code="session_id_invalid")
state = self._states.get(key)
if state is None:
raise ReleaseStateError("release_session_unknown")
return state
def _require_not_expired(self, state: _MutableState) -> None:
if self._now() >= state.snapshot.expires_at_ms:
state.snapshot = replace(
state.snapshot,
phase=ReleasePhase.DENIED,
version=state.snapshot.version + 1,
terminal_reason="release_session_expired",
)
state.lease_digest = None
raise ReleaseStateError("release_session_expired")
def create(
self,
*,
session_id: str,
packet_id: str,
purpose: str,
live_binding_sha256: str,
expires_at_ms: int,
) -> ReleaseStateSnapshot:
session = _identifier(session_id, code="session_id_invalid")
packet = _identifier(packet_id, code="packet_id_invalid")
bounded_purpose = _identifier(purpose, code="purpose_invalid")
live_binding = _sha256(live_binding_sha256, code="live_binding_invalid")
expiry = _uint(expires_at_ms, code="expiry_invalid")
with self._lock:
now = self._now()
if expiry <= now or expiry - now > _MAX_SESSION_LIFETIME_MS:
raise ReleaseStateError("expiry_outside_local_policy")
if session in self._states:
raise ReleaseStateError("release_session_reused")
snapshot = ReleaseStateSnapshot(
schema=STATE_SCHEMA,
session_id=session,
packet_id=packet,
purpose=bounded_purpose,
live_binding_sha256=live_binding,
expires_at_ms=expiry,
phase=ReleasePhase.CREATED,
version=0,
)
self._states[session] = _MutableState(snapshot=snapshot)
return snapshot
def reserve(self, *, session_id: str, expected_live_binding_sha256: str) -> ReleaseStateSnapshot:
expected = _sha256(expected_live_binding_sha256, code="live_binding_invalid")
with self._lock:
state = self._active(session_id)
self._require_not_expired(state)
if state.snapshot.phase is not ReleasePhase.CREATED:
raise ReleaseStateError("release_session_not_reservable")
if state.snapshot.live_binding_sha256 != expected:
self._deny_locked(state, "live_binding_changed")
raise ReleaseStateError("live_binding_changed")
state.snapshot = replace(
state.snapshot,
phase=ReleasePhase.RESERVED,
version=state.snapshot.version + 1,
)
return state.snapshot
def claim_custody(self, *, session_id: str) -> OpaqueCustodyLease:
with self._lock:
state = self._active(session_id)
self._require_not_expired(state)
if state.snapshot.phase is not ReleasePhase.RESERVED:
raise ReleaseStateError("release_session_not_claimable")
token = b64url_encode(secrets.token_bytes(32))
state.lease_digest = domain_hash(
"AUREON-PLUMBER-V02-CUSTODY-LEASE",
{"session_id": state.snapshot.session_id, "lease_token": token},
)
state.snapshot = replace(
state.snapshot,
phase=ReleasePhase.CUSTODY,
version=state.snapshot.version + 1,
)
return OpaqueCustodyLease(
session_id=state.snapshot.session_id,
packet_id=state.snapshot.packet_id,
lease_token=token,
)
def consume(self, lease: OpaqueCustodyLease) -> ReleaseStateSnapshot:
if not isinstance(lease, OpaqueCustodyLease):
raise ReleaseStateError("custody_lease_invalid")
with self._lock:
state = self._active(lease.session_id)
self._require_not_expired(state)
if state.snapshot.phase is not ReleasePhase.CUSTODY:
raise ReleaseStateError("release_session_not_consumable")
if state.snapshot.packet_id != lease.packet_id:
self._deny_locked(state, "custody_lease_packet_mismatch")
raise ReleaseStateError("custody_lease_packet_mismatch")
expected = domain_hash(
"AUREON-PLUMBER-V02-CUSTODY-LEASE",
{"session_id": state.snapshot.session_id, "lease_token": lease.lease_token},
)
if not secrets.compare_digest(state.lease_digest or "", expected):
self._deny_locked(state, "custody_lease_mismatch")
raise ReleaseStateError("custody_lease_mismatch")
state.lease_digest = None
state.snapshot = replace(
state.snapshot,
phase=ReleasePhase.CONSUMED,
version=state.snapshot.version + 1,
)
return state.snapshot
def validate_lease(self, lease: OpaqueCustodyLease) -> bool:
"""Re-sample time and authenticate an opaque lease without consuming it."""
if not isinstance(lease, OpaqueCustodyLease):
raise ReleaseStateError("custody_lease_invalid")
with self._lock:
state = self._active(lease.session_id)
self._require_not_expired(state)
if state.snapshot.phase is not ReleasePhase.CUSTODY:
raise ReleaseStateError("release_session_not_in_custody")
if state.snapshot.packet_id != lease.packet_id:
self._deny_locked(state, "custody_lease_packet_mismatch")
raise ReleaseStateError("custody_lease_packet_mismatch")
expected = domain_hash(
"AUREON-PLUMBER-V02-CUSTODY-LEASE",
{"session_id": state.snapshot.session_id, "lease_token": lease.lease_token},
)
if not secrets.compare_digest(state.lease_digest or "", expected):
self._deny_locked(state, "custody_lease_mismatch")
raise ReleaseStateError("custody_lease_mismatch")
return True
def _deny_locked(self, state: _MutableState, reason: str) -> ReleaseStateSnapshot:
if state.snapshot.phase in {ReleasePhase.CONSUMED, ReleasePhase.DENIED}:
return state.snapshot
state.lease_digest = None
state.snapshot = replace(
state.snapshot,
phase=ReleasePhase.DENIED,
version=state.snapshot.version + 1,
terminal_reason=_identifier(reason, code="terminal_reason_invalid"),
)
return state.snapshot
def deny(self, *, session_id: str, reason: str) -> ReleaseStateSnapshot:
with self._lock:
return self._deny_locked(self._active(session_id), reason)
def snapshot(self, session_id: str) -> ReleaseStateSnapshot:
with self._lock:
return self._active(session_id).snapshot
@dataclass(frozen=True, slots=True)
class EPASChainSnapshot:
schema: str
epoch: int
head_sha256: str
def public_dict(self) -> dict[str, Any]:
return {"schema": self.schema, "epoch": self.epoch, "head_sha256": self.head_sha256}
@dataclass(frozen=True, slots=True)
class OpaqueEPASReservation:
epoch: int
head_sha256: str
reservation_token: str = field(repr=False)
class InMemoryEPASChainStoreV02:
"""Exact-predecessor EPAS chain model. It is not durable ancestry proof."""
production_ready = False
def __init__(self, *, epoch: int, head_sha256: str) -> None:
self._snapshot = EPASChainSnapshot(
schema=EPAS_STATE_SCHEMA,
epoch=_uint(epoch, code="epas_epoch_invalid"),
head_sha256=_sha256(head_sha256, code="epas_head_invalid"),
)
self._reservation_digest: str | None = None
self._lock = threading.RLock()
def snapshot(self) -> EPASChainSnapshot:
with self._lock:
return self._snapshot
def compare_and_set(
self,
*,
expected_epoch: int,
expected_head_sha256: str,
terminal_star_sha256: str,
session_id: str,
authorization_sha256: str,
outcome: str,
) -> EPASChainSnapshot:
epoch = _uint(expected_epoch, code="epas_epoch_invalid")
head = _sha256(expected_head_sha256, code="epas_head_invalid")
star = _sha256(terminal_star_sha256, code="terminal_star_invalid")
session = _identifier(session_id, code="session_id_invalid")
authorization = _sha256(authorization_sha256, code="authorization_invalid")
terminal_outcome = str(outcome or "")
if terminal_outcome not in {"CONSUMED", "DENIED"}:
raise ReleaseStateError("epas_outcome_invalid")
with self._lock:
if self._reservation_digest is not None:
raise ReleaseStateError("epas_chain_reserved")
current = self._snapshot
if current.epoch != epoch or current.head_sha256 != head:
raise ReleaseStateError("epas_predecessor_mismatch")
next_epoch = current.epoch + 1
next_head = domain_hash(
"AUREON-PLUMBER-V02-EPAS-MEMORY",
{
"previous_epoch": current.epoch,
"previous_head_sha256": current.head_sha256,
"terminal_star_sha256": star,
"session_id": session,
"authorization_sha256": authorization,
"outcome": terminal_outcome,
"next_epoch": next_epoch,
},
)
self._snapshot = EPASChainSnapshot(
schema=EPAS_STATE_SCHEMA,
epoch=next_epoch,
head_sha256=next_head,
)
return self._snapshot
def reserve(
self,
*,
expected_epoch: int,
expected_head_sha256: str,
) -> OpaqueEPASReservation:
epoch = _uint(expected_epoch, code="epas_epoch_invalid")
head = _sha256(expected_head_sha256, code="epas_head_invalid")
with self._lock:
if self._reservation_digest is not None:
raise ReleaseStateError("epas_chain_reserved")
if self._snapshot.epoch != epoch or self._snapshot.head_sha256 != head:
raise ReleaseStateError("epas_predecessor_mismatch")
token = b64url_encode(secrets.token_bytes(32))
self._reservation_digest = domain_hash(
"AUREON-PLUMBER-V02-EPAS-RESERVATION",
{"epoch": epoch, "head_sha256": head, "reservation_token": token},
)
return OpaqueEPASReservation(
epoch=epoch,
head_sha256=head,
reservation_token=token,
)
def finalize(
self,
reservation: OpaqueEPASReservation,
*,
terminal_star_sha256: str,
session_id: str,
authorization_sha256: str,
outcome: str,
) -> EPASChainSnapshot:
if not isinstance(reservation, OpaqueEPASReservation):
raise ReleaseStateError("epas_reservation_invalid")
star = _sha256(terminal_star_sha256, code="terminal_star_invalid")
session = _identifier(session_id, code="session_id_invalid")
authorization = _sha256(authorization_sha256, code="authorization_invalid")
terminal_outcome = str(outcome or "")
if terminal_outcome not in {"CONSUMED", "DENIED"}:
raise ReleaseStateError("epas_outcome_invalid")
with self._lock:
expected_digest = domain_hash(
"AUREON-PLUMBER-V02-EPAS-RESERVATION",
{
"epoch": reservation.epoch,
"head_sha256": reservation.head_sha256,
"reservation_token": reservation.reservation_token,
},
)
if not secrets.compare_digest(
self._reservation_digest or "", expected_digest
):
raise ReleaseStateError("epas_reservation_mismatch")
current = self._snapshot
if (
current.epoch != reservation.epoch
or current.head_sha256 != reservation.head_sha256
):
self._reservation_digest = None
raise ReleaseStateError("epas_predecessor_mismatch")
next_epoch = current.epoch + 1
next_head = domain_hash(
"AUREON-PLUMBER-V02-EPAS-MEMORY",
{
"previous_epoch": current.epoch,
"previous_head_sha256": current.head_sha256,
"terminal_star_sha256": star,
"session_id": session,
"authorization_sha256": authorization,
"outcome": terminal_outcome,
"next_epoch": next_epoch,
},
)
self._snapshot = EPASChainSnapshot(
schema=EPAS_STATE_SCHEMA,
epoch=next_epoch,
head_sha256=next_head,
)
self._reservation_digest = None
return self._snapshot
__all__ = [
"EPASChainSnapshot",
"EPAS_STATE_SCHEMA",
"InMemoryEPASChainStoreV02",
"InMemoryReleaseStateStoreV02",
"OpaqueCustodyLease",
"OpaqueEPASReservation",
"ReleasePhase",
"ReleaseStateError",
"ReleaseStateSnapshot",
"STATE_SCHEMA",
]12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952"""Fail-closed Python runtime effect guard for the Aureon Plumber.
This module is a local reference boundary, not a process sandbox. Once
explicitly installed it uses CPython audit events to deny covered mutations
and post-install file opens unless the current synchronous handler was selected
by an exact, current v0.3
dispatch and its signed command commits to an exact v0.4 effect manifest.
Denied attempts are represented only by bounded metadata commitments. An
exact :class:`LocalOSProtectionBoundary` turns that metadata into HNC
quarantine evidence; raw audit arguments are never retained or returned.
Python objects remain introspectable and privileged/native code can bypass
Python audit hooks. JavaScript, child runtimes, remote authority isolation,
durable replay state, OS policy, pre-opened descriptors/sockets, memory maps,
and inbound socket payloads are outside this module. Earlier audit hooks see
an event before this hook and therefore remain part of the trusted bootstrap.
Consequently all types here remain ``production_ready = False``.
"""
from __future__ import annotations
import hashlib
import os
import re
import secrets
import sys
import threading
from collections.abc import Callable, Iterator, Mapping
from contextlib import contextmanager
from dataclasses import dataclass
from typing import Any, Final
from .audit import assert_public_summary_safe
from .crypto import canonical_json_bytes, decode_canonical_json, domain_hash
from .os_protection import LocalOSProtectionBoundary, QuarantinedHNC
from .production_release_broker_v03 import (
DispatchClaimV03,
ProductionReleaseVerifierV03,
ReleaseCommandV03,
ReviewAuthorizationV03,
decode_dispatch_claim_v03,
decode_release_command_v03,
decode_review_authorization_v03,
)
from .schema import SchemaError, require_sha256
RUNTIME_EFFECT_MANIFEST_SCHEMA: Final = "aureon.plumber.runtime-effect-manifest.v04"
RUNTIME_EFFECT_RULE_SCHEMA: Final = "aureon.plumber.runtime-effect-rule.v04"
RUNTIME_GUARD_EXECUTION_SCHEMA: Final = "aureon.plumber.runtime-guard-execution.v04"
RUNTIME_GUARD_PREFLIGHT_SCHEMA: Final = "aureon.plumber.runtime-guard-preflight.v04"
RUNTIME_GUARD_LIFECYCLE_SCHEMA: Final = "aureon.plumber.runtime-guard-lifecycle.v04"
RUNTIME_INTRUSION_SCHEMA: Final = "aureon.plumber.runtime-intrusion.v04"
RUNTIME_INTRUSION_PURPOSE: Final = "aureon.plumber.runtime-intrusion-quarantine.v04"
_MAX_RULES: Final = 128
_MAX_RULE_USES: Final = 1024
_MAX_TOTAL_RULE_USES: Final = 4096
_MAX_AUDIT_VALUE_DEPTH: Final = 12
_MAX_AUDIT_VALUE_NODES: Final = 4096
_MAX_AUDIT_TEXT_BYTES: Final = 64 * 1024
_MAX_AUDIT_AGGREGATE_BYTES: Final = 256 * 1024
_MAX_VIOLATION_RECEIPTS: Final = 4096
_MAX_CONSUMED_RELEASES: Final = 4096
_SAFE_INTEGER_MAX: Final = (1 << 53) - 1
_IDENTIFIER_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$")
_AUDIT_EVENT_RE = re.compile(r"^[A-Za-z0-9_][A-Za-z0-9._:/-]{0,127}$")
_INSTALL_PROBE_EVENT: Final = "aureon.runtime_guard_v04.install_probe"
_ALWAYS_PROTECTED_EVENTS: Final = frozenset(
{
"_thread.start_joinable_thread",
"_thread.start_new_thread",
"code.__new__",
"compile",
"cpython.PyInterpreterState_New",
"ctypes.PyObj_FromPtr",
"ctypes.addressof",
"ctypes.call_function",
"ctypes.cdata",
"ctypes.cdata/buffer",
"ctypes.create_string_buffer",
"ctypes.create_unicode_buffer",
"ctypes.dlopen",
"ctypes.dlsym",
"ctypes.dlsym/handle",
"ctypes.set_errno",
"ctypes.set_exception",
"ctypes.set_last_error",
"ctypes.string_at",
"ctypes.wstring_at",
"exec",
"ftplib.connect",
"ftplib.sendcmd",
"function.__new__",
"http.client.connect",
"http.client.send",
"import",
"imaplib.open",
"imaplib.send",
"marshal.load",
"marshal.loads",
"mmap.__new__",
"nntplib.connect",
"nntplib.putline",
"os.add_dll_directory",
"os.chdir",
"os.chflags",
"os.chmod",
"os.chown",
"os.exec",
"os.fork",
"os.forkpty",
"os.kill",
"os.killpg",
"os.link",
"os.lockf",
"os.mkdir",
"os.posix_spawn",
"os.putenv",
"os.remove",
"os.removexattr",
"os.rename",
"os.rmdir",
"os.startfile",
"os.startfile/2",
"os.spawn",
"os.setxattr",
"os.symlink",
"os.system",
"os.truncate",
"os.unsetenv",
"os.utime",
"pickle.find_class",
"poplib.connect",
"poplib.putline",
"shutil.copyfile",
"shutil.chown",
"shutil.copymode",
"shutil.copystat",
"shutil.copytree",
"shutil.make_archive",
"shutil.move",
"shutil.rmtree",
"shutil.unpack_archive",
"smtplib.connect",
"smtplib.send",
"socket.__new__",
"socket.bind",
"socket.connect",
"socket.getaddrinfo",
"socket.gethostbyaddr",
"socket.gethostbyname",
"socket.gethostname",
"socket.getnameinfo",
"socket.getservbyname",
"socket.getservbyport",
"socket.sendmsg",
"socket.sendto",
"socket.sethostname",
"sqlite3.connect",
"sqlite3.connect/handle",
"sqlite3.enable_load_extension",
"sqlite3.load_extension",
"subprocess.Popen",
"sys.addaudithook",
"sys.setprofile",
"sys.settrace",
"telnetlib.Telnet.open",
"telnetlib.Telnet.write",
"urllib.Request",
"webbrowser.open",
"winreg.ConnectRegistry",
"winreg.CreateKey",
"winreg.DeleteKey",
"winreg.DeleteValue",
"winreg.DisableReflectionKey",
"winreg.EnableReflectionKey",
"winreg.LoadKey",
"winreg.SaveKey",
"winreg.SetValue",
}
)
_DENY_ONLY_EVENT_MINIMUM: Final = frozenset(
{
"_thread.start_joinable_thread",
"_thread.start_new_thread",
"open",
"code.__new__",
"compile",
"cpython.PyInterpreterState_New",
"ctypes.PyObj_FromPtr",
"ctypes.addressof",
"ctypes.call_function",
"ctypes.cdata",
"ctypes.cdata/buffer",
"ctypes.create_string_buffer",
"ctypes.create_unicode_buffer",
"ctypes.dlopen",
"ctypes.dlsym",
"ctypes.dlsym/handle",
"ctypes.set_errno",
"ctypes.set_exception",
"ctypes.set_last_error",
"ctypes.string_at",
"ctypes.wstring_at",
"exec",
"function.__new__",
"http.client.connect",
"http.client.send",
"import",
"marshal.load",
"marshal.loads",
"mmap.__new__",
"os.add_dll_directory",
"os.chdir",
"os.exec",
"os.fork",
"os.forkpty",
"os.kill",
"os.killpg",
"os.lockf",
"os.posix_spawn",
"os.startfile",
"os.startfile/2",
"os.spawn",
"os.system",
"pickle.find_class",
"socket.__new__",
"socket.bind",
"socket.connect",
"socket.getaddrinfo",
"socket.gethostbyaddr",
"socket.gethostbyname",
"socket.gethostname",
"socket.getnameinfo",
"socket.getservbyname",
"socket.getservbyport",
"socket.sendmsg",
"socket.sendto",
"socket.sethostname",
"sqlite3.connect",
"sqlite3.connect/handle",
"sqlite3.enable_load_extension",
"sqlite3.load_extension",
"subprocess.Popen",
"sys.addaudithook",
"sys.setprofile",
"sys.settrace",
"urllib.Request",
"winreg.ConnectRegistry",
"winreg.DisableReflectionKey",
"winreg.EnableReflectionKey",
"winreg.LoadKey",
"winreg.SaveKey",
}
)
_SUPPORTED_RULE_EVENTS: Final = frozenset({"open", *_ALWAYS_PROTECTED_EVENTS})
_AUTHORIZABLE_EVENTS: Final = frozenset({"os.mkdir"})
_NON_AUTHORIZABLE_EVENTS: Final = (
_SUPPORTED_RULE_EVENTS - _AUTHORIZABLE_EVENTS
)
if not _DENY_ONLY_EVENT_MINIMUM <= _NON_AUTHORIZABLE_EVENTS:
raise RuntimeError("runtime_guard_deny_only_event_invariant_failed")
_SOCKET_INSTANCE_EVENTS: Final = frozenset(
{"socket.bind", "socket.connect", "socket.sendto"}
)
class RuntimeGuardError(ValueError):
"""Stable, non-secret runtime guard contract failure."""
def __init__(self, code: str) -> None:
self.code = str(code)
super().__init__(self.code)
class RuntimeGuardViolation(PermissionError):
"""A covered runtime effect was denied before the operation."""
def __init__(self, code: str) -> None:
self.code = str(code)
super().__init__(self.code)
def _identifier(value: object, *, code: str) -> str:
if type(value) is not str or _IDENTIFIER_RE.fullmatch(value) is None:
raise RuntimeGuardError(code)
return value
def _audit_event_identifier(value: object, *, code: str) -> str:
if type(value) is not str or _AUDIT_EVENT_RE.fullmatch(value) is None:
raise RuntimeGuardError(code)
return value
def _sha256(value: object, *, code: str) -> str:
if type(value) is not str:
raise RuntimeGuardError(code)
try:
return require_sha256(value, field=code)
except SchemaError as exc:
raise RuntimeGuardError(code) from exc
def _uint(value: object, *, code: str) -> int:
if type(value) is not int or value < 0 or value > _SAFE_INTEGER_MAX:
raise RuntimeGuardError(code)
return value
def _safe_integer(value: object, *, code: str) -> int:
if (
type(value) is not int
or value < -_SAFE_INTEGER_MAX
or value > _SAFE_INTEGER_MAX
):
raise RuntimeGuardError(code)
return value
def _exact_mapping(
value: object,
keys: set[str],
*,
code: str,
) -> dict[str, Any]:
if not isinstance(value, Mapping) or set(value) != keys:
raise RuntimeGuardError(code)
return dict(value)
def _decode_mapping(data: bytes | str, *, code: str) -> dict[str, Any]:
try:
value = decode_canonical_json(
data,
require_mapping=True,
max_bytes=_MAX_AUDIT_TEXT_BYTES,
)
except BaseException as exc:
raise RuntimeGuardError(code) from exc
if not isinstance(value, dict): # pragma: no cover - decoder contract
raise RuntimeGuardError(code)
return value
def _hash_bytes(value: bytes) -> dict[str, Any]:
if type(value) is not bytes:
raise RuntimeGuardError("audit_argument_bytes_invalid")
if len(value) > _MAX_AUDIT_TEXT_BYTES:
raise RuntimeGuardError("audit_argument_bytes_invalid")
return {
"kind": "bytes",
"size_bytes": len(value),
"sha256": hashlib.sha256(value).hexdigest(),
}
def _hash_text(value: str) -> dict[str, Any]:
if type(value) is not str:
raise RuntimeGuardError("audit_argument_text_invalid")
if len(value) > _MAX_AUDIT_TEXT_BYTES or "\x00" in value:
raise RuntimeGuardError("audit_argument_text_invalid")
try:
encoded = str.encode(value, "utf-8", errors="strict")
except UnicodeEncodeError as exc:
raise RuntimeGuardError("audit_argument_text_invalid") from exc
if len(encoded) > _MAX_AUDIT_TEXT_BYTES:
raise RuntimeGuardError("audit_argument_text_invalid")
return {
"kind": "text",
"size_bytes": len(encoded),
"sha256": hashlib.sha256(encoded).hexdigest(),
}
def _snapshot_audit_value(
value: object,
*,
depth: int = 0,
remaining_nodes: list[int] | None = None,
remaining_bytes: list[int] | None = None,
) -> Any:
budget = remaining_nodes if remaining_nodes is not None else [_MAX_AUDIT_VALUE_NODES]
byte_budget = (
remaining_bytes
if remaining_bytes is not None
else [_MAX_AUDIT_AGGREGATE_BYTES]
)
budget[0] -= 1
if budget[0] < 0 or depth > _MAX_AUDIT_VALUE_DEPTH:
raise RuntimeGuardError("audit_argument_budget_exceeded")
if value is None or type(value) is bool:
return value
if type(value) is int:
return {
"kind": "integer",
"value": _safe_integer(value, code="audit_integer_invalid"),
}
if type(value) is str:
snapshot = _hash_text(value)
byte_budget[0] -= int(snapshot["size_bytes"])
if byte_budget[0] < 0:
raise RuntimeGuardError("audit_argument_budget_exceeded")
return snapshot
if type(value) is bytes:
if len(value) > _MAX_AUDIT_TEXT_BYTES:
raise RuntimeGuardError("audit_argument_bytes_invalid")
byte_budget[0] -= len(value)
if byte_budget[0] < 0:
raise RuntimeGuardError("audit_argument_budget_exceeded")
return _hash_bytes(value)
if type(value) is dict:
entries: list[dict[str, Any]] = []
for key, item in value.items():
if type(key) is not str:
raise RuntimeGuardError("audit_mapping_key_invalid")
key_snapshot = _hash_text(key)
byte_budget[0] -= int(key_snapshot["size_bytes"])
if byte_budget[0] < 0:
raise RuntimeGuardError("audit_argument_budget_exceeded")
entries.append(
{
"key": key_snapshot,
"value": _snapshot_audit_value(
item,
depth=depth + 1,
remaining_nodes=budget,
remaining_bytes=byte_budget,
),
}
)
entries.sort(key=lambda entry: canonical_json_bytes(entry["key"]))
return {"kind": "mapping", "entries": entries}
if isinstance(value, (list, tuple)):
if type(value) not in (list, tuple):
raise RuntimeGuardError("audit_argument_type_unsupported")
return {
"kind": "sequence",
"items": [
_snapshot_audit_value(
item,
depth=depth + 1,
remaining_nodes=budget,
remaining_bytes=byte_budget,
)
for item in value
],
}
raise RuntimeGuardError("audit_argument_type_unsupported")
def _open_is_mutating(arguments: tuple[Any, ...]) -> bool:
if len(arguments) < 3:
return True
mode = arguments[1]
flags = arguments[2]
if type(mode) is str and any(
str.__contains__(mode, marker) for marker in "wax+"
):
return True
if type(flags) is int:
write_flags = (
os.O_WRONLY
| os.O_RDWR
| os.O_CREAT
| os.O_TRUNC
| os.O_APPEND
)
return bool(flags & write_flags)
return mode is None or type(mode) is not str
def _open_access(arguments: tuple[Any, ...]) -> dict[str, bool]:
mode = arguments[1] if len(arguments) > 1 else None
flags = arguments[2] if len(arguments) > 2 else None
if type(mode) is str:
return {
"append": str.__contains__(mode, "a"),
"create": any(
str.__contains__(mode, marker) for marker in "wax"
),
"exclusive": str.__contains__(mode, "x"),
"truncate": str.__contains__(mode, "w"),
"update": str.__contains__(mode, "+"),
}
if type(flags) is int:
return {
"append": bool(flags & os.O_APPEND),
"create": bool(flags & os.O_CREAT),
"exclusive": bool(flags & os.O_EXCL),
"truncate": bool(flags & os.O_TRUNC),
"update": bool(flags & os.O_RDWR),
}
raise RuntimeGuardError("audit_open_access_invalid")
def _requires_protection(event_name: str, arguments: tuple[Any, ...]) -> bool:
if event_name == "open":
return True
return event_name in _ALWAYS_PROTECTED_EVENTS
def _event_resource(event_name: str, arguments: tuple[Any, ...]) -> dict[str, Any]:
_audit_event_identifier(event_name, code="audit_event_name_invalid")
if event_name not in _SUPPORTED_RULE_EVENTS:
raise RuntimeGuardError("audit_event_not_guarded")
if event_name == "open":
if not arguments:
raise RuntimeGuardError("audit_open_arguments_invalid")
target = arguments[0]
if type(target) is str:
target_text = target
else:
raise RuntimeGuardError("audit_open_target_not_absolute_text")
if not os.path.isabs(target_text):
raise RuntimeGuardError("audit_open_target_not_absolute_text")
return {
"event_name": event_name,
"target": _snapshot_audit_value(target_text),
"access": _open_access(arguments),
}
if event_name == "os.mkdir" and (
len(arguments) != 3
or type(arguments[0]) is not str
or not os.path.isabs(arguments[0])
or type(arguments[1]) is not int
or arguments[1] < 0
or arguments[1] > 0o7777
or type(arguments[2]) is not int
or arguments[2] != -1
):
raise RuntimeGuardError("audit_mkdir_arguments_invalid")
selected = arguments[1:] if event_name in _SOCKET_INSTANCE_EVENTS else arguments
return {
"event_name": event_name,
"arguments": _snapshot_audit_value(selected),
}
def audit_event_resource_commitment_v04(
event_name: str,
arguments: tuple[Any, ...],
) -> str:
"""Return an opaque resource commitment for one CPython audit event.
For ``open`` the commitment binds the exact target and normalized mutation
semantics. Raw ``open`` remains non-authorizable because later handle
writes are not audited. Socket-instance commitments ignore the
process-local socket object and bind the remaining audited arguments.
Network, native-loader, thread, and child-process events are observable but
never manifest-authorizable in this Python reference layer.
"""
if type(arguments) is not tuple:
raise RuntimeGuardError("audit_arguments_tuple_required")
return domain_hash(
"AUREON-PLUMBER-V04-AUDIT-RESOURCE",
_event_resource(event_name, arguments),
)
@dataclass(frozen=True, slots=True)
class AuditEffectRuleV04:
event_name: str
resource_commitment: str
max_uses: int
schema: str = RUNTIME_EFFECT_RULE_SCHEMA
def __post_init__(self) -> None:
if self.schema != RUNTIME_EFFECT_RULE_SCHEMA:
raise RuntimeGuardError("runtime_effect_rule_schema_invalid")
_audit_event_identifier(
self.event_name,
code="runtime_effect_event_invalid",
)
if (
self.event_name not in _SUPPORTED_RULE_EVENTS
or self.event_name not in _AUTHORIZABLE_EVENTS
):
raise RuntimeGuardError("runtime_effect_event_not_authorizable")
_sha256(self.resource_commitment, code="runtime_effect_resource_invalid")
uses = _uint(self.max_uses, code="runtime_effect_max_uses_invalid")
if uses < 1 or uses > _MAX_RULE_USES:
raise RuntimeGuardError("runtime_effect_max_uses_invalid")
def wire_dict(self) -> dict[str, Any]:
return {
"schema": self.schema,
"event_name": self.event_name,
"resource_commitment": self.resource_commitment,
"max_uses": self.max_uses,
}
@dataclass(frozen=True, slots=True)
class RuntimeEffectManifestV04:
effect_id: str
capability_id: str
runtime_measurement_sha256: str
operations: tuple[AuditEffectRuleV04, ...]
schema: str = RUNTIME_EFFECT_MANIFEST_SCHEMA
def __post_init__(self) -> None:
if self.schema != RUNTIME_EFFECT_MANIFEST_SCHEMA:
raise RuntimeGuardError("runtime_effect_manifest_schema_invalid")
_sha256(self.effect_id, code="runtime_effect_id_invalid")
_sha256(self.capability_id, code="runtime_capability_id_invalid")
_sha256(
self.runtime_measurement_sha256,
code="runtime_measurement_invalid",
)
if (
type(self.operations) is not tuple
or not self.operations
or len(self.operations) > _MAX_RULES
or any(type(item) is not AuditEffectRuleV04 for item in self.operations)
):
raise RuntimeGuardError("runtime_effect_operations_invalid")
keys = [
(item.event_name, item.resource_commitment)
for item in self.operations
]
if keys != sorted(keys) or len(keys) != len(set(keys)):
raise RuntimeGuardError("runtime_effect_operations_not_canonical")
if sum(item.max_uses for item in self.operations) > _MAX_TOTAL_RULE_USES:
raise RuntimeGuardError("runtime_effect_total_uses_invalid")
def wire_dict(self) -> dict[str, Any]:
return {
"schema": self.schema,
"effect_id": self.effect_id,
"capability_id": self.capability_id,
"runtime_measurement_sha256": self.runtime_measurement_sha256,
"operations": [item.wire_dict() for item in self.operations],
}
@property
def commitment(self) -> str:
return domain_hash(
"AUREON-PLUMBER-V04-RUNTIME-EFFECT-MANIFEST",
self.wire_dict(),
)
def decode_runtime_effect_manifest_v04(data: bytes | str) -> RuntimeEffectManifestV04:
payload = _exact_mapping(
_decode_mapping(data, code="runtime_effect_manifest_wire_invalid"),
{
"schema",
"effect_id",
"capability_id",
"runtime_measurement_sha256",
"operations",
},
code="runtime_effect_manifest_shape_invalid",
)
raw_operations = payload["operations"]
if not isinstance(raw_operations, list) or len(raw_operations) > _MAX_RULES:
raise RuntimeGuardError("runtime_effect_operations_invalid")
operations: list[AuditEffectRuleV04] = []
for value in raw_operations:
rule = _exact_mapping(
value,
{"schema", "event_name", "resource_commitment", "max_uses"},
code="runtime_effect_rule_shape_invalid",
)
try:
operations.append(AuditEffectRuleV04(**rule))
except (TypeError, ValueError) as exc:
if isinstance(exc, RuntimeGuardError):
raise
raise RuntimeGuardError("runtime_effect_rule_shape_invalid") from exc
payload["operations"] = tuple(operations)
try:
return RuntimeEffectManifestV04(**payload)
except (TypeError, ValueError) as exc:
if isinstance(exc, RuntimeGuardError):
raise
raise RuntimeGuardError("runtime_effect_manifest_shape_invalid") from exc
@dataclass(frozen=True, slots=True)
class GuardedRuntimeCapabilityV04:
capability_id: str
capability_measurement_sha256: str
handler: Callable[[], object]
def __post_init__(self) -> None:
_sha256(self.capability_id, code="runtime_capability_id_invalid")
_sha256(
self.capability_measurement_sha256,
code="runtime_capability_measurement_invalid",
)
if not callable(self.handler):
raise RuntimeGuardError("runtime_capability_handler_invalid")
def _reject_content(_view: memoryview) -> bool:
return False
class HNCRuntimeViolationRecorderV04:
"""Bounded, in-memory HNC quarantine evidence for denied audit events."""
production_ready = False
def __init__(
self,
*,
boundary: LocalOSProtectionBoundary,
max_receipts: int = 1024,
require_durable_evidence: bool = False,
) -> None:
if type(boundary) is not LocalOSProtectionBoundary:
raise RuntimeGuardError("exact_local_os_protection_boundary_required")
limit = _uint(max_receipts, code="runtime_violation_capacity_invalid")
if limit < 1 or limit > _MAX_VIOLATION_RECEIPTS:
raise RuntimeGuardError("runtime_violation_capacity_invalid")
if type(require_durable_evidence) is not bool:
raise RuntimeGuardError("runtime_durable_evidence_policy_invalid")
self._boundary = boundary
self._max_receipts = limit
self._require_durable_evidence = require_durable_evidence
self._receipts: list[dict[str, Any]] = []
self._reserved_receipts = 0
self._sequence = 0
self._preflight: dict[str, Any] | None = None
self._terminal_failure_code: str | None = None
self._runtime_guard_sealed = False
self._runtime_guard_owner_token: str | None = None
self._runtime_guard_boundary_generation: int | None = None
self._runtime_guard_lifecycle_generation = 0
self._runtime_lifecycle_lock = threading.RLock()
self._lock = threading.RLock()
def _mark_terminal_locked(self, code: str) -> None:
selected = _identifier(code, code="runtime_intrusion_terminal_code_invalid")
if self._terminal_failure_code is None:
self._runtime_guard_lifecycle_generation += 1
self._terminal_failure_code = selected
def preflight(self) -> dict[str, Any]:
"""Warm and prove the commitment-only HNC quarantine path."""
with self._runtime_lifecycle_lock, self._lock:
if self._preflight is not None:
cached = dict(self._preflight)
if self._terminal_failure_code is not None:
cached["ready"] = False
cached["reason_code"] = self._terminal_failure_code
return cached
remaining_required = max(
0,
self._max_receipts
- len(self._receipts)
- self._reserved_receipts,
)
key = self._boundary.key_preflight()
boundary_summary = self._boundary.public_summary()
maximum = boundary_summary.get("max_quarantine_evidence")
used = boundary_summary.get("quarantine_evidence_count")
local_available = (
max(0, maximum - used)
if type(maximum) is int and type(used) is int
else 0
)
cached["hnc_key_ready"] = key.get("ready") is True
cached["hnc_quarantine_capacity_after_probe"] = local_available
cached["hnc_quarantine_capacity_backed"] = (
local_available >= remaining_required
)
if key.get("ready") is not True:
self._mark_terminal_locked("runtime_hnc_key_unavailable")
elif local_available < remaining_required:
self._mark_terminal_locked(
"runtime_hnc_quarantine_capacity_insufficient"
)
durable_configured = (
boundary_summary.get(
"durable_quarantine_evidence_configured"
)
is True
)
if (
self._terminal_failure_code is None
and (self._require_durable_evidence or durable_configured)
):
try:
durable = (
self._boundary.durable_quarantine_evidence_preflight()
)
available = durable.get("remaining_violation_capacity")
durable_ready = durable.get("ready") is True
capacity_backed = (
type(available) is int
and available >= remaining_required
)
cached["durable_hnc_evidence_ready"] = durable_ready
cached["durable_hnc_capacity_backed"] = capacity_backed
cached["durable_hnc_capacity_after_probe"] = (
available if type(available) is int else 0
)
if not durable_ready or not capacity_backed:
failure_code = (
str(
durable.get("reason_code")
or "runtime_durable_hnc_evidence_not_ready"
)
if not durable_ready
else "runtime_durable_hnc_capacity_insufficient"
)
self._mark_terminal_locked(failure_code)
except BaseException:
boundary_summary = self._boundary.public_summary()
self._mark_terminal_locked(
str(
boundary_summary.get(
"durable_quarantine_evidence_failure_code"
)
or "runtime_durable_hnc_evidence_preflight_failed"
)
)
if self._terminal_failure_code is not None:
cached["ready"] = False
cached["reason_code"] = self._terminal_failure_code
return cached
key = self._boundary.key_preflight()
ready = key.get("ready") is True
hnc_evidence_ready = False
capacity_backed = False
durable_evidence_ready = False
durable_capacity_backed = False
durable_available_before = 0
durable_available_after = 0
available_before = 0
available_after = 0
reason_code = str(key.get("reason_code") or "runtime_hnc_key_unavailable")
if self._require_durable_evidence:
try:
durable_before = self._boundary.durable_quarantine_evidence_preflight()
durable_evidence_ready = durable_before.get("ready") is True
available = durable_before.get("remaining_violation_capacity")
if type(available) is int:
durable_available_before = max(0, available)
durable_capacity_backed = (
durable_evidence_ready
and durable_available_before >= self._max_receipts + 1
)
if not durable_evidence_ready:
reason_code = "runtime_durable_hnc_evidence_not_ready"
elif not durable_capacity_backed:
reason_code = "runtime_durable_hnc_capacity_insufficient"
except BaseException:
durable_evidence_ready = False
durable_capacity_backed = False
reason_code = "runtime_durable_hnc_evidence_preflight_failed"
else:
durable_evidence_ready = False
durable_capacity_backed = True
if ready:
boundary_before = self._boundary.public_summary()
maximum = boundary_before.get("max_quarantine_evidence")
used = boundary_before.get("quarantine_evidence_count")
if type(maximum) is int and type(used) is int:
available_before = max(0, maximum - used)
capacity_backed = (
available_before >= self._max_receipts + 1
and durable_capacity_backed
)
if not capacity_backed:
reason_code = (
"runtime_durable_hnc_capacity_insufficient"
if self._require_durable_evidence
and not durable_capacity_backed
else "runtime_hnc_quarantine_capacity_insufficient"
)
if ready and capacity_backed:
probe = canonical_json_bytes(
{
"schema": RUNTIME_GUARD_PREFLIGHT_SCHEMA,
"probe": "commitment-only-hnc-quarantine",
"production_ready": False,
}
)
try:
outcome = self._boundary.admit_external(
probe,
source_id="aureon:runtime-guard-v04",
ingress_kind="runtime-guard-preflight",
purpose=RUNTIME_INTRUSION_PURPOSE,
operator_aad={"preflight": True},
content_validator=_reject_content,
)
hnc_evidence_ready = (
type(outcome) is QuarantinedHNC
and outcome.hnc_evidence_binding is not None
)
boundary_after = self._boundary.public_summary()
maximum_after = boundary_after.get("max_quarantine_evidence")
used_after = boundary_after.get("quarantine_evidence_count")
if type(maximum_after) is int and type(used_after) is int:
available_after = max(0, maximum_after - used_after)
capacity_backed = available_after >= self._max_receipts
if self._require_durable_evidence:
try:
durable_after = (
self._boundary.durable_quarantine_evidence_preflight()
)
durable_evidence_ready = durable_after.get("ready") is True
durable_available = durable_after.get(
"remaining_violation_capacity"
)
if type(durable_available) is int:
durable_available_after = max(0, durable_available)
durable_capacity_backed = (
durable_evidence_ready
and durable_available_after >= self._max_receipts
)
except BaseException:
durable_evidence_ready = False
durable_capacity_backed = False
capacity_backed = capacity_backed and durable_capacity_backed
hnc_evidence_ready = hnc_evidence_ready and capacity_backed
except BaseException:
hnc_evidence_ready = False
capacity_backed = False
reason_code = (
"ready"
if hnc_evidence_ready
else (
"runtime_durable_hnc_evidence_preflight_failed"
if self._require_durable_evidence
and not durable_evidence_ready
else (
"runtime_durable_hnc_capacity_insufficient"
if self._require_durable_evidence
and not durable_capacity_backed
else (
"runtime_hnc_quarantine_capacity_insufficient"
if not capacity_backed
else "runtime_hnc_quarantine_preflight_failed"
)
)
)
)
result = {
"schema": RUNTIME_GUARD_PREFLIGHT_SCHEMA,
"ready": ready and hnc_evidence_ready,
"reason_code": reason_code,
"hnc_key_ready": ready,
"hnc_quarantine_evidence_ready": hnc_evidence_ready,
"hnc_quarantine_capacity_backed": capacity_backed,
"hnc_quarantine_capacity_before_probe": available_before,
"hnc_quarantine_capacity_after_probe": available_after,
"required_violation_receipt_capacity": self._max_receipts,
"durable_evidence_required": self._require_durable_evidence,
"durable_hnc_evidence_ready": durable_evidence_ready,
"durable_hnc_capacity_backed": durable_capacity_backed,
"durable_hnc_capacity_before_probe": durable_available_before,
"durable_hnc_capacity_after_probe": durable_available_after,
"exclusive_boundary_custody_attested": False,
"external_head_anchor_attested": False,
"magic_star_durable_custody_attested": False,
"raw_arguments_retained": False,
"action_eligible": False,
"economic_eligible": False,
"production_ready": False,
}
assert_public_summary_safe(result)
self._preflight = dict(result)
return result
def record(
self,
*,
event_name: str,
resource_commitment: str,
reason_code: str,
) -> dict[str, Any]:
"""Record one violation while excluding guard lifecycle transitions."""
with self._runtime_lifecycle_lock:
return self._record_under_lifecycle(
event_name=event_name,
resource_commitment=resource_commitment,
reason_code=reason_code,
)
def _record_under_lifecycle(
self,
*,
event_name: str,
resource_commitment: str,
reason_code: str,
) -> dict[str, Any]:
event = _audit_event_identifier(
event_name,
code="runtime_intrusion_event_invalid",
)
resource = _sha256(
resource_commitment,
code="runtime_intrusion_resource_invalid",
)
reason = _identifier(reason_code, code="runtime_intrusion_reason_invalid")
with self._lock:
if self._terminal_failure_code is not None:
raise RuntimeGuardError(self._terminal_failure_code)
if (
len(self._receipts) + self._reserved_receipts
>= self._max_receipts
):
self._mark_terminal_locked("runtime_violation_capacity_exhausted")
raise RuntimeGuardError(
self._terminal_failure_code
or "runtime_violation_capacity_exhausted"
)
self._reserved_receipts += 1
self._sequence += 1
sequence = self._sequence
reservation_active = True
try:
metadata = {
"schema": RUNTIME_INTRUSION_SCHEMA,
"sequence": sequence,
"event_name": event,
"resource_commitment": resource,
"reason_code": reason,
"raw_arguments_retained": False,
"audit_event_origin_attested": False,
"effect_attempt_attested": False,
"resource_commitment_confidentiality_attested": False,
"resource_commitments_keyed": False,
"action_eligible": False,
"economic_eligible": False,
"production_ready": False,
}
outcome = self._boundary.admit_external(
canonical_json_bytes(metadata),
source_id="aureon:runtime-guard-v04",
ingress_kind="runtime-effect-violation",
purpose=RUNTIME_INTRUSION_PURPOSE,
operator_aad={
"event_name": event,
"resource_commitment": resource,
"reason_code": reason,
},
content_validator=_reject_content,
)
if (
type(outcome) is not QuarantinedHNC
or outcome.hnc_evidence_binding is None
):
raise RuntimeGuardError("runtime_intrusion_hnc_evidence_unavailable")
receipt = {
**metadata,
"hnc_quarantine_commitment": outcome.quarantine_commitment,
"hnc_evidence_binding": outcome.hnc_evidence_binding.public_summary(),
}
assert_public_summary_safe(receipt)
stored_receipt = _decode_mapping(
canonical_json_bytes(receipt),
code="runtime_intrusion_receipt_clone_failed",
)
with self._lock:
self._reserved_receipts -= 1
reservation_active = False
self._receipts.append(stored_receipt)
self._receipts.sort(key=lambda item: int(item["sequence"]))
boundary_summary = self._boundary.public_summary()
if boundary_summary.get("durable_quarantine_evidence_terminal") is True:
self._mark_terminal_locked(
str(
boundary_summary.get(
"durable_quarantine_evidence_failure_code"
)
or "runtime_intrusion_evidence_terminal"
)
)
elif (
len(self._receipts) + self._reserved_receipts
>= self._max_receipts
):
self._mark_terminal_locked(
"runtime_violation_capacity_exhausted"
)
return _decode_mapping(
canonical_json_bytes(receipt),
code="runtime_intrusion_receipt_clone_failed",
)
except BaseException as exc:
with self._lock:
if self._terminal_failure_code is None:
self._mark_terminal_locked(
exc.code
if isinstance(exc, RuntimeGuardError)
else "runtime_intrusion_evidence_recording_failed"
)
raise
finally:
if reservation_active:
with self._lock:
self._reserved_receipts -= 1
def seal_for_runtime_guard_install(self) -> dict[str, Any]:
"""Pin the boundary/sink before an irreversible CPython hook install."""
with self._runtime_lifecycle_lock:
with self._lock:
if self._terminal_failure_code is not None:
raise RuntimeGuardError(self._terminal_failure_code)
if self._runtime_guard_sealed:
return self.validate_runtime_guard_seal(
self._runtime_guard_owner_token or "",
self._runtime_guard_lifecycle_generation,
)
preflight = self.preflight()
if preflight.get("ready") is not True:
raise RuntimeGuardError("runtime_hnc_violation_recorder_not_ready")
owner_token = secrets.token_hex(32)
try:
boundary_seal = self._boundary.seal_for_runtime_guard(owner_token)
owner_sha256 = hashlib.sha256(
owner_token.encode("utf-8", errors="strict")
).hexdigest()
boundary_generation = boundary_seal.get("lifecycle_generation")
if (
boundary_seal.get("sealed") is not True
or boundary_seal.get("owner_token_sha256") != owner_sha256
or type(boundary_generation) is not int
or boundary_generation < 1
or boundary_seal.get("terminal") is not False
or boundary_seal.get("production_ready") is not False
):
raise RuntimeGuardError("runtime_guard_boundary_seal_invalid")
confirmed = self.preflight()
if confirmed.get("ready") is not True:
raise RuntimeGuardError(
"runtime_hnc_violation_recorder_not_ready"
)
except BaseException as exc:
with self._lock:
self._mark_terminal_locked(
exc.code
if isinstance(exc, RuntimeGuardError)
else "runtime_guard_lifecycle_seal_failed"
)
raise RuntimeGuardError("runtime_guard_lifecycle_seal_failed") from exc
with self._lock:
self._runtime_guard_sealed = True
self._runtime_guard_owner_token = owner_token
self._runtime_guard_boundary_generation = boundary_generation
self._runtime_guard_lifecycle_generation += 1
result = {
"schema": RUNTIME_GUARD_LIFECYCLE_SCHEMA,
"sealed": True,
"owner_token_sha256": owner_sha256,
"lifecycle_generation": (
self._runtime_guard_lifecycle_generation
),
"boundary_lifecycle_generation": boundary_generation,
"durable_evidence_required": self._require_durable_evidence,
"terminal": False,
"production_ready": False,
}
assert_public_summary_safe(result)
return result
def validate_runtime_guard_seal(
self,
owner_token: str,
lifecycle_generation: int,
) -> dict[str, Any]:
"""Validate the recorder and boundary lifecycle generations exactly."""
with self._runtime_lifecycle_lock:
with self._lock:
if (
not self._runtime_guard_sealed
or owner_token != self._runtime_guard_owner_token
or lifecycle_generation
!= self._runtime_guard_lifecycle_generation
or self._terminal_failure_code is not None
or self._runtime_guard_boundary_generation is None
):
raise RuntimeGuardError("runtime_guard_lifecycle_invalid")
boundary_generation = self._runtime_guard_boundary_generation
try:
boundary = self._boundary.validate_runtime_guard_seal(
owner_token,
boundary_generation,
)
except BaseException as exc:
with self._lock:
self._mark_terminal_locked(
"runtime_guard_boundary_seal_validation_failed"
)
raise RuntimeGuardError(
"runtime_guard_boundary_seal_validation_failed"
) from exc
result = {
"schema": RUNTIME_GUARD_LIFECYCLE_SCHEMA,
"sealed": True,
"owner_token_sha256": hashlib.sha256(
owner_token.encode("utf-8", errors="strict")
).hexdigest(),
"lifecycle_generation": lifecycle_generation,
"boundary_lifecycle_generation": boundary_generation,
"boundary_seal_valid": boundary.get("sealed") is True,
"terminal": False,
"production_ready": False,
}
assert_public_summary_safe(result)
return result
def _runtime_guard_lease_identity(self) -> tuple[str, int]:
"""Return private lease material only to the exact in-process guard."""
with self._runtime_lifecycle_lock, self._lock:
if (
not self._runtime_guard_sealed
or self._runtime_guard_owner_token is None
or self._runtime_guard_lifecycle_generation < 1
or self._terminal_failure_code is not None
):
raise RuntimeGuardError("runtime_guard_lifecycle_invalid")
return (
self._runtime_guard_owner_token,
self._runtime_guard_lifecycle_generation,
)
@contextmanager
def runtime_guard_decision_lease(
self,
owner_token: str,
lifecycle_generation: int,
) -> Iterator[dict[str, Any]]:
"""Hold one exact non-appending lifecycle decision across all layers."""
with self._runtime_lifecycle_lock:
before = self.validate_runtime_guard_seal(
owner_token,
lifecycle_generation,
)
boundary_generation = self._runtime_guard_boundary_generation
if boundary_generation is None: # pragma: no cover - validated above
raise RuntimeGuardError("runtime_guard_lifecycle_invalid")
with self._boundary.runtime_guard_lifecycle_lease(
owner_token,
boundary_generation,
):
yield before
self.validate_runtime_guard_seal(
owner_token,
lifecycle_generation,
)
def terminal_failure_code(self) -> str | None:
with self._runtime_lifecycle_lock, self._lock:
return self._terminal_failure_code
def receipts(self) -> tuple[dict[str, Any], ...]:
with self._runtime_lifecycle_lock, self._lock:
return tuple(
_decode_mapping(
canonical_json_bytes(item),
code="runtime_intrusion_receipt_clone_failed",
)
for item in self._receipts
)
@dataclass(slots=True)
class _ActivePermit:
dispatch_commitment: str
owner_thread_id: int
remaining: dict[tuple[str, str], int]
violation_generation_at_start: int
violations: int = 0
revoked: bool = False
_GLOBAL_GUARD_LOCK = threading.RLock()
_GLOBAL_GUARD: RuntimeAuditGuardV04 | None = None
class _DirectEnvironData(dict):
"""Mirror string-key writes onto the POSIX bytes map without ``os.putenv``.
``os.getenv`` reads encoded keys. A direct ``_data`` assignment is outside
the signed ``os.putenv`` effect, and the installed guard must keep that
read pin true without recording a violation.
"""
def __setitem__(self, key: object, value: object) -> None:
if isinstance(key, str):
encoded_key = key.encode("utf-8", "surrogateescape")
encoded_value = (
value.encode("utf-8", "surrogateescape")
if isinstance(value, str)
else value
)
super().__setitem__(encoded_key, encoded_value)
super().__setitem__(key, value)
def __delitem__(self, key: object) -> None:
if isinstance(key, str):
encoded_key = key.encode("utf-8", "surrogateescape")
removed = False
if encoded_key in self:
super().__delitem__(encoded_key)
removed = True
if key in self:
super().__delitem__(key)
removed = True
if not removed:
raise KeyError(key)
return
super().__delitem__(key)
def _bridge_posix_environ_direct_reads() -> None:
data = getattr(os.environ, "_data", None)
if not isinstance(data, dict) or isinstance(data, _DirectEnvironData):
return
if data:
if not isinstance(next(iter(data)), bytes):
return
elif os.name != "posix":
return
os.environ._data = _DirectEnvironData(data)
class RuntimeAuditGuardV04:
"""Permanent, default-deny CPython audit hook for covered effects."""
production_ready = False
def __init__(
self,
*,
verifier: ProductionReleaseVerifierV03,
recorder: HNCRuntimeViolationRecorderV04,
runtime_measurement_sha256: str,
capabilities: Mapping[str, GuardedRuntimeCapabilityV04],
) -> None:
if type(verifier) is not ProductionReleaseVerifierV03:
raise RuntimeGuardError("production_release_verifier_required")
if type(recorder) is not HNCRuntimeViolationRecorderV04:
raise RuntimeGuardError("exact_runtime_violation_recorder_required")
runtime_measurement = _sha256(
runtime_measurement_sha256,
code="runtime_measurement_invalid",
)
if not isinstance(capabilities, Mapping) or not capabilities:
raise RuntimeGuardError("runtime_capability_registry_required")
normalized: dict[str, GuardedRuntimeCapabilityV04] = {}
for capability_id, capability in capabilities.items():
if (
type(capability) is not GuardedRuntimeCapabilityV04
or capability_id != capability.capability_id
or capability_id in normalized
):
raise RuntimeGuardError("runtime_capability_registry_invalid")
normalized[capability_id] = capability
self._verifier = verifier
self._recorder = recorder
self._runtime_measurement_sha256 = runtime_measurement
self._capabilities = normalized
# Thread-local state deliberately does not propagate through copied
# contextvars/async tasks. A permit exists only for the synchronous
# registered handler stack on the installing process thread.
self._thread_state = threading.local()
self._consumed_dispatches: set[str] = set()
self._consumed_release_identities: set[tuple[str, str]] = set()
self._violation_count = 0
self._evidence_failure_count = 0
self._evidence_terminal = False
self._evidence_terminal_reason_code: str | None = None
self._installed = False
self._installation_failed_terminal = False
self._install_probe: object | None = None
self._install_probe_seen = False
self._recorder_owner_token: str | None = None
self._recorder_lifecycle_generation: int | None = None
self._runtime_lifecycle_lock = threading.RLock()
self._lock = threading.RLock()
self._execution_lock = threading.Lock()
self._active_execution_count = 0
def install(self) -> dict[str, Any]:
"""Install one irreversible hook after proving HNC evidence readiness."""
preflight = self._recorder.preflight()
if preflight.get("ready") is not True:
raise RuntimeGuardError("runtime_hnc_violation_recorder_not_ready")
global _GLOBAL_GUARD
with _GLOBAL_GUARD_LOCK:
if _GLOBAL_GUARD is not None:
if _GLOBAL_GUARD is self and self._installed:
return self.public_summary()
if _GLOBAL_GUARD is self and self._installation_failed_terminal:
raise RuntimeGuardError(
"runtime_audit_guard_installation_terminal"
)
raise RuntimeGuardError("runtime_audit_guard_already_installed")
with self._runtime_lifecycle_lock:
# Sealing is the installation credential. The recorder pins
# the durable sink under its own lock; from this point close is
# rejected and the seal is revalidated for every capability.
seal = self._recorder.seal_for_runtime_guard_install()
if seal.get("sealed") is not True:
raise RuntimeGuardError("runtime_guard_lifecycle_seal_failed")
owner_token, lifecycle_generation = (
self._recorder._runtime_guard_lease_identity()
)
self._recorder.validate_runtime_guard_seal(
owner_token,
lifecycle_generation,
)
self._recorder_owner_token = owner_token
self._recorder_lifecycle_generation = lifecycle_generation
# Hold the exact recorder/boundary/sink decision lease until
# the irreversible hook is installed and proven. A failed or
# vetoed attempt remains process-terminal and leaves the sink
# sealed; no close/DDL/terminal transition can occupy the old
# preflight-to-install gap.
with self._recorder.runtime_guard_decision_lease(
owner_token,
lifecycle_generation,
):
_GLOBAL_GUARD = self
self._install_probe = object()
self._install_probe_seen = False
try:
sys.addaudithook(self._audit_hook)
sys.audit(_INSTALL_PROBE_EVENT, self._install_probe)
except BaseException as exc:
self._install_probe = None
self._installation_failed_terminal = True
raise RuntimeGuardError(
"runtime_audit_guard_installation_unproven"
) from exc
if not self._install_probe_seen:
# CPython permits an earlier audit hook to veto hook
# installation without returning an error.
self._install_probe = None
self._installation_failed_terminal = True
raise RuntimeGuardError(
"runtime_audit_guard_installation_unproven"
)
self._install_probe = None
self._installed = True
_bridge_posix_environ_direct_reads()
return self.public_summary()
@contextmanager
def _runtime_guard_decision_lease(self) -> Iterator[dict[str, Any]]:
"""Hold the exact lifecycle only for one non-mutating decision."""
with self._runtime_lifecycle_lock:
owner_token = self._recorder_owner_token
lifecycle_generation = self._recorder_lifecycle_generation
if owner_token is None or lifecycle_generation is None:
raise RuntimeGuardError("runtime_guard_lifecycle_invalid")
body_failed = False
try:
with self._recorder.runtime_guard_decision_lease(
owner_token,
lifecycle_generation,
) as snapshot:
try:
yield snapshot
except BaseException:
body_failed = True
raise
except BaseException as exc:
if body_failed:
raise
with self._lock:
self._evidence_terminal = True
self._evidence_terminal_reason_code = (
self._recorder.terminal_failure_code()
or "runtime_guard_lifecycle_invalid"
)
raise RuntimeGuardError(
"runtime_intrusion_evidence_terminal"
) from exc
def _record_violation(
self,
*,
event_name: str,
resource_commitment: str,
permit: _ActivePermit | None,
) -> None:
with self._runtime_lifecycle_lock:
self._record_violation_under_lifecycle(
event_name=event_name,
resource_commitment=resource_commitment,
permit=permit,
)
def _record_violation_under_lifecycle(
self,
*,
event_name: str,
resource_commitment: str,
permit: _ActivePermit | None,
) -> None:
with self._lock:
self._violation_count += 1
if permit is not None:
permit.violations += 1
previous_recording = getattr(self._thread_state, "recording", False)
self._thread_state.recording = True
try:
self._recorder.record(
event_name=event_name,
resource_commitment=resource_commitment,
reason_code="runtime_effect_not_magic_star_released",
)
terminal_code = self._recorder.terminal_failure_code()
if terminal_code is not None:
with self._lock:
self._evidence_terminal = True
self._evidence_terminal_reason_code = terminal_code
except BaseException:
with self._lock:
self._evidence_failure_count += 1
self._evidence_terminal = True
self._evidence_terminal_reason_code = (
self._recorder.terminal_failure_code()
or "runtime_intrusion_evidence_recording_failed"
)
finally:
self._thread_state.recording = previous_recording
def _audit_hook(self, event_name: str, arguments: tuple[Any, ...]) -> None:
# Each audit decision, not the arbitrary caller handler, is serialized
# with recorder/boundary/sink lifecycle state. The authorization
# decision is therefore linearizable without deadlocking handlers that
# join worker threads.
with self._runtime_lifecycle_lock:
self._audit_hook_under_lifecycle(event_name, arguments)
def _audit_authorization_decision(
self,
*,
event_name: str,
resource_commitment: str,
fingerprinted: bool,
permit: _ActivePermit | None,
) -> tuple[bool, str | None]:
"""Atomically consume or reject one permit use under a lifecycle lease."""
key = (event_name, resource_commitment)
terminal_code = self._recorder.terminal_failure_code()
with self._lock:
if terminal_code is not None:
self._evidence_terminal = True
self._evidence_terminal_reason_code = terminal_code
evidence_terminal = self._evidence_terminal
generation_changed = (
permit is not None
and self._violation_count
!= permit.violation_generation_at_start
)
if permit is not None and (
evidence_terminal or generation_changed or permit.revoked
):
permit.revoked = True
return (
False,
"runtime_intrusion_evidence_terminal"
if evidence_terminal
else "runtime_active_permit_revoked",
)
if (
fingerprinted
and event_name in _AUTHORIZABLE_EVENTS
and permit is not None
and permit.owner_thread_id == threading.get_ident()
and permit.remaining.get(key, 0) > 0
):
permit.remaining[key] -= 1
return True, None
return False, None
def _audit_hook_under_lifecycle(
self,
event_name: str,
arguments: tuple[Any, ...],
) -> None:
if (
event_name == _INSTALL_PROBE_EVENT
and len(arguments) == 1
and arguments[0] is self._install_probe
):
self._install_probe_seen = True
return
if not _requires_protection(event_name, arguments):
return
if getattr(self._thread_state, "recording", False):
raise RuntimeGuardViolation("runtime_intrusion_recorder_effect_forbidden")
fingerprinted = True
try:
resource_commitment = audit_event_resource_commitment_v04(
event_name,
arguments,
)
except BaseException:
fingerprinted = False
resource_commitment = domain_hash(
"AUREON-PLUMBER-V04-UNFINGERPRINTABLE-AUDIT-RESOURCE",
{"event_name": event_name},
)
permit = getattr(self._thread_state, "active_permit", None)
owner_token = self._recorder_owner_token
lifecycle_generation = self._recorder_lifecycle_generation
if owner_token is not None and lifecycle_generation is not None:
try:
# Decision-only: recording/appending happens after this exact
# durable transaction has exited.
with self._runtime_guard_decision_lease():
authorized, rejection_code = (
self._audit_authorization_decision(
event_name=event_name,
resource_commitment=resource_commitment,
fingerprinted=fingerprinted,
permit=permit,
)
)
except BaseException:
with self._lock:
self._evidence_terminal = True
self._evidence_terminal_reason_code = (
self._recorder.terminal_failure_code()
or "runtime_guard_lifecycle_invalid"
)
if permit is not None:
permit.revoked = True
raise RuntimeGuardViolation(
"runtime_intrusion_evidence_terminal"
) from None
else:
# Pre-install direct tests still exercise the local decision state;
# a process hook never reaches this branch after installation.
authorized, rejection_code = self._audit_authorization_decision(
event_name=event_name,
resource_commitment=resource_commitment,
fingerprinted=fingerprinted,
permit=permit,
)
if rejection_code is not None:
raise RuntimeGuardViolation(rejection_code)
if authorized:
return
# Never append while the ledger decision transaction is open.
self._record_violation_under_lifecycle(
event_name=event_name,
resource_commitment=resource_commitment,
permit=permit,
)
raise RuntimeGuardViolation("runtime_effect_not_magic_star_released")
def execute_released(
self,
command_wire: bytes,
review_wire: bytes,
dispatch_wire: bytes,
manifest_wire: bytes,
) -> dict[str, Any]:
"""Serialize and execute one exact registered runtime capability."""
terminal_code = self._recorder.terminal_failure_code()
with self._lock:
if terminal_code is not None:
self._evidence_terminal = True
self._evidence_terminal_reason_code = terminal_code
if self._evidence_terminal:
raise RuntimeGuardError("runtime_intrusion_evidence_terminal")
if getattr(self._thread_state, "active_permit", None) is not None:
raise RuntimeGuardError("nested_runtime_effect_forbidden")
if not self._execution_lock.acquire(blocking=False):
raise RuntimeGuardError("concurrent_runtime_effect_forbidden")
with self._lock:
self._active_execution_count += 1
try:
return self._execute_released_serial(
command_wire,
review_wire,
dispatch_wire,
manifest_wire,
)
finally:
with self._lock:
self._active_execution_count -= 1
self._execution_lock.release()
def _execute_released_serial(
self,
command_wire: bytes,
review_wire: bytes,
dispatch_wire: bytes,
manifest_wire: bytes,
) -> dict[str, Any]:
with self._runtime_lifecycle_lock, self._lock:
if not self._installed:
raise RuntimeGuardError("runtime_audit_guard_not_installed")
owner_token = self._recorder_owner_token
lifecycle_generation = self._recorder_lifecycle_generation
if owner_token is None or lifecycle_generation is None:
raise RuntimeGuardError("runtime_guard_lifecycle_invalid")
return self._execute_released_serial_under_lifecycle(
command_wire,
review_wire,
dispatch_wire,
manifest_wire,
)
def _execute_released_serial_under_lifecycle(
self,
command_wire: bytes,
review_wire: bytes,
dispatch_wire: bytes,
manifest_wire: bytes,
) -> dict[str, Any]:
"""Run one exact handler while the process execution lock is held."""
if any(type(item) is not bytes for item in (
command_wire,
review_wire,
dispatch_wire,
manifest_wire,
)):
raise RuntimeGuardError("runtime_guard_canonical_wire_required")
command: ReleaseCommandV03 = decode_release_command_v03(command_wire)
review: ReviewAuthorizationV03 = decode_review_authorization_v03(review_wire)
dispatch: DispatchClaimV03 = decode_dispatch_claim_v03(dispatch_wire)
manifest = decode_runtime_effect_manifest_v04(manifest_wire)
self._verifier.verify_dispatch_current(command, review, dispatch)
capability = self._capabilities.get(command.capability_id)
if capability is None:
raise RuntimeGuardError("runtime_capability_not_registered")
if (
manifest.effect_id != command.effect_id
or manifest.capability_id != command.capability_id
or manifest.runtime_measurement_sha256
!= command.runtime_measurement_sha256
or command.runtime_measurement_sha256
!= self._runtime_measurement_sha256
or command.capability_measurement_sha256
!= capability.capability_measurement_sha256
or command.authorization_context_sha256 != manifest.commitment
):
raise RuntimeGuardError("runtime_manifest_command_join_invalid")
if getattr(self._thread_state, "active_permit", None) is not None:
raise RuntimeGuardError("nested_runtime_effect_forbidden")
dispatch_commitment = dispatch.commitment
release_identities = {
("command", command.commitment),
("command_id", command.command_id),
("effect_id", command.effect_id),
("request_nonce", command.request_nonce),
}
remaining = {
(item.event_name, item.resource_commitment): item.max_uses
for item in manifest.operations
}
# Consume the release and establish its permit in one exact lifecycle
# decision. This context performs no evidence append.
with self._runtime_guard_decision_lease():
terminal_code = self._recorder.terminal_failure_code()
with self._lock:
if terminal_code is not None:
self._evidence_terminal = True
self._evidence_terminal_reason_code = terminal_code
if self._evidence_terminal:
raise RuntimeGuardError(
"runtime_intrusion_evidence_terminal"
)
if dispatch_commitment in self._consumed_dispatches:
raise RuntimeGuardError("runtime_dispatch_replayed")
if not release_identities.isdisjoint(
self._consumed_release_identities
):
raise RuntimeGuardError("runtime_release_identity_replayed")
if len(self._consumed_dispatches) >= _MAX_CONSUMED_RELEASES:
raise RuntimeGuardError(
"runtime_release_replay_capacity_exhausted"
)
# Consume before caller-controlled work. Failure is unresolved
# and never grants a retry through this local reference guard.
self._consumed_dispatches.add(dispatch_commitment)
self._consumed_release_identities.update(release_identities)
permit = _ActivePermit(
dispatch_commitment=dispatch_commitment,
owner_thread_id=threading.get_ident(),
remaining=remaining,
violation_generation_at_start=self._violation_count,
)
self._thread_state.active_permit = permit
try:
try:
result = capability.handler()
if result is not None:
raise RuntimeGuardError(
"runtime_capability_result_channel_forbidden"
)
except RuntimeGuardViolation:
raise
except BaseException:
raise RuntimeGuardError(
"runtime_capability_failed_claim_consumed"
) from None
# Final-return linearization point. A completed terminal
# transition or guard violation during the handler prevents any
# successful execution receipt from escaping.
with self._runtime_guard_decision_lease():
terminal_code = self._recorder.terminal_failure_code()
with self._lock:
if terminal_code is not None:
self._evidence_terminal = True
self._evidence_terminal_reason_code = terminal_code
if self._evidence_terminal:
permit.revoked = True
raise RuntimeGuardError(
"runtime_intrusion_evidence_terminal"
)
violation_generation_changed = (
self._violation_count
!= permit.violation_generation_at_start
)
if (
permit.violations
or permit.revoked
or violation_generation_changed
):
raise RuntimeGuardError(
"runtime_capability_violation_claim_consumed"
)
if any(count != 0 for count in permit.remaining.values()):
raise RuntimeGuardError(
"runtime_effect_manifest_not_fully_consumed"
)
finally:
self._thread_state.active_permit = None
receipt = {
"schema": RUNTIME_GUARD_EXECUTION_SCHEMA,
"effect_id": command.effect_id,
"capability_id": command.capability_id,
"command_commitment": command.commitment,
"review_commitment": review.commitment,
"dispatch_commitment": dispatch_commitment,
"manifest_commitment": manifest.commitment,
"operation_count": len(manifest.operations),
"operation_use_count": sum(
item.max_uses for item in manifest.operations
),
"all_manifest_operations_consumed": True,
"audit_event_authorizations_consumed": True,
"audit_event_origin_attested": False,
"capability_measurement_attested": False,
"effect_retry_authorized": False,
"external_effect_success_attested": False,
"handler_identity_attested": False,
"provider_readback_verified": False,
"result_channel_returned": False,
"runtime_measurement_attested": False,
"production_ready": False,
}
assert_public_summary_safe(receipt)
return receipt
def public_summary(self) -> dict[str, Any]:
with self._runtime_lifecycle_lock, self._lock:
result = {
"schema": RUNTIME_GUARD_PREFLIGHT_SCHEMA,
"installed": self._installed,
"runtime_measurement_sha256": self._runtime_measurement_sha256,
"registered_capability_count": len(self._capabilities),
"declared_guard_event_count": len(_SUPPORTED_RULE_EVENTS),
"authorizable_event_count": len(_AUTHORIZABLE_EVENTS),
"deny_only_event_count": len(_NON_AUTHORIZABLE_EVENTS),
"consumed_dispatch_count": len(self._consumed_dispatches),
"max_consumed_release_count": _MAX_CONSUMED_RELEASES,
"consumed_release_identity_count": len(
self._consumed_release_identities
),
"violation_count": self._violation_count,
"evidence_failure_count": self._evidence_failure_count,
"evidence_terminal": self._evidence_terminal,
"evidence_terminal_reason_code": (
self._evidence_terminal_reason_code
),
"active_execution_count": self._active_execution_count,
"active_permit": self._active_execution_count > 0,
"runtime_guard_lifecycle_sealed": (
self._recorder_owner_token is not None
and self._recorder_lifecycle_generation is not None
),
"runtime_guard_lifecycle_generation": (
self._recorder_lifecycle_generation
),
"capability_measurement_attested": False,
"installation_failed_terminal": (
self._installation_failed_terminal
),
"native_code_isolation_attested": False,
"javascript_isolation_attested": False,
"durable_replay_state": False,
"audit_event_origin_attested": False,
"file_handle_lifetime_isolation_attested": False,
"handler_identity_attested": False,
"inbound_payload_admission_attested": False,
"native_environment_integrity_attested": False,
"preopened_descriptor_isolation_attested": False,
"provider_readback_verified": False,
"python_object_integrity_attested": False,
"resource_commitment_confidentiality_attested": False,
"resource_commitments_keyed": False,
"runtime_event_coverage_attested": False,
"runtime_measurement_attested": False,
"symlink_race_isolation_attested": False,
"action_eligible": False,
"economic_eligible": False,
"production_ready": False,
}
assert_public_summary_safe(result)
return result
__all__ = [
"RUNTIME_EFFECT_MANIFEST_SCHEMA",
"RUNTIME_EFFECT_RULE_SCHEMA",
"RUNTIME_GUARD_EXECUTION_SCHEMA",
"RUNTIME_GUARD_LIFECYCLE_SCHEMA",
"RUNTIME_GUARD_PREFLIGHT_SCHEMA",
"RUNTIME_INTRUSION_PURPOSE",
"RUNTIME_INTRUSION_SCHEMA",
"AuditEffectRuleV04",
"GuardedRuntimeCapabilityV04",
"HNCRuntimeViolationRecorderV04",
"RuntimeAuditGuardV04",
"RuntimeEffectManifestV04",
"RuntimeGuardError",
"RuntimeGuardViolation",
"audit_event_resource_commitment_v04",
"decode_runtime_effect_manifest_v04",
]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373"""Strict, fail-closed schema primitives for Aureon Plumber v0.
The v0 packet is an authenticated metadata envelope. It deliberately makes
no claim that encrypted material has been released, executed, or accepted by
any production system.
"""
from __future__ import annotations
import json
import re
from collections.abc import Iterable, Mapping
from dataclasses import dataclass
from datetime import UTC, datetime
from enum import StrEnum
from types import MappingProxyType
from typing import Any, Self, cast
from .crypto import canonical_json_bytes, domain_hash
PLUMBER_MAGIC = "AUREON-HNC-PLUMBER"
PLUMBER_SCHEMA_VERSION = 0
PLUMBER_PACKET_SCHEMA = "aureon.plumber.packet.v0"
_SHA256_RE = re.compile(r"^[0-9a-f]{64}$")
_ED25519_SIGNATURE_RE = re.compile(r"^[0-9a-f]{128}$")
_CONTROL_RE = re.compile(r"[\x00-\x1f\x7f]")
_FIXED_DECIMAL_RE = re.compile(r"^(?:0|[1-9][0-9]*|-[1-9][0-9]*)(?:\.[0-9]*[1-9])?$")
class DenialCode(StrEnum):
"""Stable machine-readable failure codes shared by the v0 modules."""
INVALID_SCHEMA = "invalid_schema"
UNKNOWN_FIELD = "unknown_field"
MISSING_FIELD = "missing_field"
INVALID_TYPE = "invalid_type"
INVALID_VALUE = "invalid_value"
INVALID_SIGNATURE = "invalid_signature"
SIGNER_MISMATCH = "signer_mismatch"
PACKET_IDENTITY_MISMATCH = "packet_identity_mismatch"
SESSION_IDENTITY_MISMATCH = "session_identity_mismatch"
PACKET_COMMITMENT_MISMATCH = "packet_commitment_mismatch"
SOURCE_IDENTITY_MISMATCH = "source_identity_mismatch"
TEMPORAL_IDENTITY_MISMATCH = "temporal_identity_mismatch"
OBSERVER_TRANSCRIPT_MISMATCH = "observer_transcript_mismatch"
TWIN_RUNE_MISMATCH = "twin_rune_mismatch"
SYMPATHETIC_IDENTITY_MISMATCH = "sympathetic_identity_mismatch"
POLICY_RECEIPT_MISSING = "policy_receipt_missing"
POLICY_RECEIPT_INVALID = "policy_receipt_invalid"
QUORUM_INCOMPLETE = "quorum_incomplete"
QUORUM_DUPLICATE_AUTHORITY = "quorum_duplicate_authority"
FRAGMENT_SET_INCOMPLETE = "fragment_set_incomplete"
FRAGMENT_INVALID = "fragment_invalid"
FRAGMENT_EXPIRED = "fragment_expired"
REPLAY_DETECTED = "replay_detected"
STALE_STATE = "stale_state"
FUTURE_STATE = "future_state"
COUNTER_ROLLBACK = "counter_rollback"
PREVIOUS_STATE_MISMATCH = "previous_state_mismatch"
PURPOSE_MISMATCH = "purpose_mismatch"
QUARANTINED = "quarantined"
INTERNAL_ERROR = "internal_error"
class SchemaError(ValueError):
"""A validation failure that never interpolates rejected values."""
def __init__(self, code: DenialCode | str, *, field: str | None = None) -> None:
self.code = str(code)
self.field = field
message = self.code if field is None else f"{self.code}:{field}"
super().__init__(message)
def require_exact_keys(
value: Mapping[str, Any],
expected: Iterable[str],
*,
field: str,
) -> dict[str, Any]:
if not isinstance(value, Mapping):
raise SchemaError(DenialCode.INVALID_TYPE, field=field)
if any(not isinstance(key, str) for key in value):
raise SchemaError(DenialCode.INVALID_TYPE, field=field)
expected_keys = frozenset(expected)
actual_keys = frozenset(value)
missing = sorted(expected_keys - actual_keys)
if missing:
raise SchemaError(DenialCode.MISSING_FIELD, field=f"{field}.{missing[0]}")
unknown = sorted(actual_keys - expected_keys)
if unknown:
raise SchemaError(DenialCode.UNKNOWN_FIELD, field=f"{field}.{unknown[0]}")
return dict(value)
def require_mapping(value: Any, *, field: str, nonempty: bool = True) -> dict[str, Any]:
if not isinstance(value, Mapping) or any(not isinstance(key, str) for key in value):
raise SchemaError(DenialCode.INVALID_TYPE, field=field)
result = dict(value)
if nonempty and not result:
raise SchemaError(DenialCode.INVALID_VALUE, field=field)
try:
canonical_json_bytes(result)
except ValueError as exc:
raise SchemaError(DenialCode.INVALID_VALUE, field=field) from exc
return result
def _freeze_json(value: Any) -> Any:
if isinstance(value, Mapping):
return MappingProxyType({key: _freeze_json(item) for key, item in value.items()})
if isinstance(value, list | tuple):
return tuple(_freeze_json(item) for item in value)
return value
def freeze_mapping(value: Any, *, field: str, nonempty: bool = True) -> Mapping[str, Any]:
"""Validate and defensively freeze a JSON mapping."""
return cast(
Mapping[str, Any],
_freeze_json(require_mapping(value, field=field, nonempty=nonempty)),
)
def thaw_json(value: Any) -> Any:
"""Return a recursively mutable, JSON-serializable public copy."""
if isinstance(value, Mapping):
return {key: thaw_json(item) for key, item in value.items()}
if isinstance(value, list | tuple):
return [thaw_json(item) for item in value]
return value
def require_nonblank(value: Any, *, field: str, max_length: int = 512) -> str:
if not isinstance(value, str):
raise SchemaError(DenialCode.INVALID_TYPE, field=field)
if not value or value != value.strip() or len(value) > max_length or _CONTROL_RE.search(value):
raise SchemaError(DenialCode.INVALID_VALUE, field=field)
return value
def require_sha256(value: Any, *, field: str) -> str:
if not isinstance(value, str) or _SHA256_RE.fullmatch(value) is None:
raise SchemaError(DenialCode.INVALID_VALUE, field=field)
return value
def require_ed25519_public_key(value: Any, *, field: str) -> str:
return require_sha256(value, field=field)
def require_ed25519_signature(value: Any, *, field: str) -> str:
if not isinstance(value, str) or _ED25519_SIGNATURE_RE.fullmatch(value) is None:
raise SchemaError(DenialCode.INVALID_VALUE, field=field)
return value
def require_int(value: Any, *, field: str, minimum: int = 0) -> int:
if type(value) is not int or value < minimum:
raise SchemaError(DenialCode.INVALID_VALUE, field=field)
return value
def require_fixed_decimal(value: Any, *, field: str) -> str:
"""Return the v0 canonical number representation.
Python floats are intentionally rejected. Integers normalize to decimal
strings and callers with measured fractional values must supply a fixed
decimal string without redundant leading or trailing zeroes.
"""
if type(value) is int:
value = str(value)
if not isinstance(value, str):
raise SchemaError(DenialCode.INVALID_TYPE, field=field)
if _FIXED_DECIMAL_RE.fullmatch(value) is None:
raise SchemaError(DenialCode.INVALID_VALUE, field=field)
return value
def format_timestamp(value: datetime) -> str:
normalized = require_aware_datetime(value, field="timestamp")
if normalized.microsecond:
raise SchemaError(DenialCode.INVALID_VALUE, field="timestamp")
return normalized.strftime("%Y-%m-%dT%H:%M:%SZ")
def parse_timestamp(value: Any, *, field: str) -> datetime:
if not isinstance(value, str) or not value.endswith("Z"):
raise SchemaError(DenialCode.INVALID_VALUE, field=field)
try:
parsed = datetime.fromisoformat(f"{value[:-1]}+00:00")
except ValueError as exc:
raise SchemaError(DenialCode.INVALID_VALUE, field=field) from exc
if parsed.microsecond or format_timestamp(parsed) != value:
raise SchemaError(DenialCode.INVALID_VALUE, field=field)
return parsed
def require_aware_datetime(value: Any, *, field: str) -> datetime:
if not isinstance(value, datetime) or value.tzinfo is None or value.utcoffset() is None:
raise SchemaError(DenialCode.INVALID_VALUE, field=field)
return value.astimezone(UTC)
def utc_now() -> datetime:
return datetime.now(UTC).replace(microsecond=0)
_PACKET_FIELDS = (
"magic",
"schema",
"schema_version",
"packet_identity",
"source_identity",
"temporal_identity",
"requested_purpose",
"hnc_observer_challenge",
"canonical_field_receipt",
"observer_transcript_commitment",
"twin_rune_seal",
"sympathetic_identity_commitment",
"heart_receipt",
"conscience_receipt",
"governance_receipt",
"quorum_policy",
"encrypted_payload",
"spore_manifest",
"packet_commitment",
"signatures",
)
def _copy_json(value: Mapping[str, Any]) -> dict[str, Any]:
return cast(dict[str, Any], json.loads(canonical_json_bytes(value)))
def _packet_commitment_payload(values: Mapping[str, Any]) -> dict[str, Any]:
return {key: values[key] for key in _PACKET_FIELDS if key not in {"packet_commitment", "signatures"}}
@dataclass(frozen=True, slots=True)
class PlumberPacketV0:
magic: str
schema: str
schema_version: int
packet_identity: str
source_identity: Mapping[str, Any]
temporal_identity: Mapping[str, Any]
requested_purpose: str
hnc_observer_challenge: str
canonical_field_receipt: Mapping[str, Any]
observer_transcript_commitment: str
twin_rune_seal: Mapping[str, Any]
sympathetic_identity_commitment: str
heart_receipt: Mapping[str, Any]
conscience_receipt: Mapping[str, Any]
governance_receipt: Mapping[str, Any]
quorum_policy: Mapping[str, Any]
encrypted_payload: Mapping[str, Any]
spore_manifest: Mapping[str, Any]
packet_commitment: str
signatures: Mapping[str, str]
def __post_init__(self) -> None:
if self.magic != PLUMBER_MAGIC or self.schema != PLUMBER_PACKET_SCHEMA:
raise SchemaError(DenialCode.INVALID_SCHEMA, field="packet")
if type(self.schema_version) is not int or self.schema_version != PLUMBER_SCHEMA_VERSION:
raise SchemaError(DenialCode.INVALID_SCHEMA, field="schema_version")
require_nonblank(self.packet_identity, field="packet_identity")
require_nonblank(self.requested_purpose, field="requested_purpose", max_length=1024)
require_sha256(self.hnc_observer_challenge, field="hnc_observer_challenge")
require_sha256(self.observer_transcript_commitment, field="observer_transcript_commitment")
require_sha256(self.sympathetic_identity_commitment, field="sympathetic_identity_commitment")
require_sha256(self.packet_commitment, field="packet_commitment")
for name in (
"source_identity",
"temporal_identity",
"canonical_field_receipt",
"twin_rune_seal",
"heart_receipt",
"conscience_receipt",
"governance_receipt",
"quorum_policy",
"encrypted_payload",
"spore_manifest",
):
object.__setattr__(self, name, freeze_mapping(getattr(self, name), field=name))
if not isinstance(self.signatures, Mapping):
raise SchemaError(DenialCode.INVALID_TYPE, field="signatures")
for signer, signature in self.signatures.items():
require_nonblank(signer, field="signatures.signer")
require_ed25519_signature(signature, field="signatures.signature")
object.__setattr__(self, "signatures", freeze_mapping(self.signatures, field="signatures", nonempty=False))
if self.computed_commitment() != self.packet_commitment:
raise SchemaError(DenialCode.PACKET_COMMITMENT_MISMATCH, field="packet_commitment")
@classmethod
def build(cls, **values: Any) -> Self:
allowed = set(_PACKET_FIELDS) - {"packet_commitment"}
unknown = sorted(set(values) - allowed)
if unknown:
raise SchemaError(DenialCode.UNKNOWN_FIELD, field=f"packet.{unknown[0]}")
required = allowed - {"magic", "schema", "schema_version", "signatures"}
missing = sorted(required - set(values))
if missing:
raise SchemaError(DenialCode.MISSING_FIELD, field=f"packet.{missing[0]}")
parsed = {
"magic": values.get("magic", PLUMBER_MAGIC),
"schema": values.get("schema", PLUMBER_PACKET_SCHEMA),
"schema_version": values.get("schema_version", PLUMBER_SCHEMA_VERSION),
**{key: value for key, value in values.items() if key not in {"magic", "schema", "schema_version"}},
}
parsed.setdefault("signatures", {})
parsed["packet_commitment"] = domain_hash(
"aureon.plumber.packet.v0",
_packet_commitment_payload(parsed),
)
return cls.from_dict(parsed)
@classmethod
def from_dict(cls, value: Mapping[str, Any]) -> Self:
parsed = require_exact_keys(value, _PACKET_FIELDS, field="packet")
return cls(**parsed)
def to_dict(self) -> dict[str, Any]:
return _copy_json({name: getattr(self, name) for name in _PACKET_FIELDS})
def computed_commitment(self) -> str:
return domain_hash("aureon.plumber.packet.v0", _packet_commitment_payload(self.to_dict()))
def public_summary(self) -> dict[str, Any]:
"""Return commitments and counts only; omit payload, purpose, and signatures."""
return {
"magic": self.magic,
"schema": self.schema,
"schema_version": self.schema_version,
"packet_identity": self.packet_identity,
"purpose_commitment": domain_hash("aureon.plumber.purpose.v0", self.requested_purpose),
"observer_transcript_commitment": self.observer_transcript_commitment,
"sympathetic_identity_commitment": self.sympathetic_identity_commitment,
"packet_commitment": self.packet_commitment,
"signature_count": len(self.signatures),
"release_state": "not_released",
}
__all__ = [
"DenialCode",
"PLUMBER_MAGIC",
"PLUMBER_PACKET_SCHEMA",
"PLUMBER_SCHEMA_VERSION",
"PlumberPacketV0",
"SchemaError",
"format_timestamp",
"freeze_mapping",
"thaw_json",
"parse_timestamp",
"require_aware_datetime",
"require_ed25519_public_key",
"require_ed25519_signature",
"require_exact_keys",
"require_int",
"require_fixed_decimal",
"require_mapping",
"require_nonblank",
"require_sha256",
"utc_now",
]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143"""Commitment-only source identity for Aureon Plumber v0."""
from __future__ import annotations
from collections.abc import Mapping
from dataclasses import dataclass
from typing import Any, Self
from .crypto import domain_hash
from .schema import (
DenialCode,
SchemaError,
require_exact_keys,
require_nonblank,
require_sha256,
)
SOURCE_IDENTITY_SCHEMA = "aureon.plumber.source-identity.v0"
_FIELDS = (
"schema",
"source_type",
"source_locator_commitment",
"source_content_commitment",
"provenance_receipt_commitment",
"identity_commitment",
)
@dataclass(frozen=True, slots=True)
class SourceIdentityV0:
schema: str
source_type: str
source_locator_commitment: str
source_content_commitment: str
provenance_receipt_commitment: str
identity_commitment: str
def __post_init__(self) -> None:
if self.schema != SOURCE_IDENTITY_SCHEMA:
raise SchemaError(DenialCode.INVALID_SCHEMA, field="schema")
require_nonblank(self.source_type, field="source_type")
for field in (
"source_locator_commitment",
"source_content_commitment",
"provenance_receipt_commitment",
"identity_commitment",
):
require_sha256(getattr(self, field), field=field)
if domain_hash("aureon.plumber.source-identity.v0", self.commitment_payload()) != self.identity_commitment:
raise SchemaError(DenialCode.SOURCE_IDENTITY_MISMATCH, field="identity_commitment")
@classmethod
def build(
cls,
*,
source_type: str,
source_locator_commitment: str,
source_content_commitment: str,
provenance_receipt_commitment: str,
) -> Self:
values = {
"schema": SOURCE_IDENTITY_SCHEMA,
"source_type": source_type,
"source_locator_commitment": source_locator_commitment,
"source_content_commitment": source_content_commitment,
"provenance_receipt_commitment": provenance_receipt_commitment,
}
return cls(
**values,
identity_commitment=domain_hash("aureon.plumber.source-identity.v0", values),
)
@classmethod
def from_dict(cls, value: Mapping[str, Any]) -> Self:
return cls(**require_exact_keys(value, _FIELDS, field="source_identity"))
def commitment_payload(self) -> dict[str, str]:
return {field: getattr(self, field) for field in _FIELDS if field != "identity_commitment"}
def to_dict(self) -> dict[str, str]:
return {field: getattr(self, field) for field in _FIELDS}
def public_summary(self) -> dict[str, str]:
return self.to_dict()
def build_source_identity(**values: Any) -> SourceIdentityV0:
return SourceIdentityV0.build(**values)
def build_source_identity_from_hnc_packet(packet: Mapping[str, Any]) -> SourceIdentityV0:
"""Bind an existing, valid HNC quantum packet without decoding it.
The established HNC validator remains authoritative for its packet
contract. Plumber consumes only its validated packet and alignment hashes;
ciphertext, nonce, purpose, and plaintext never enter the public identity.
"""
if not isinstance(packet, Mapping):
raise SchemaError(DenialCode.INVALID_TYPE, field="hnc_packet")
from aureon.harmonic.hnc_quantum_packet_crypto import validate_hnc_packet_contract
validation = validate_hnc_packet_contract(packet)
if not validation.get("valid"):
raise SchemaError(DenialCode.SOURCE_IDENTITY_MISMATCH, field="hnc_packet")
packet_commitment = require_sha256(
validation.get("packet_sha256"),
field="hnc_packet.packet_sha256",
)
alignment_commitment = require_sha256(
validation.get("hnc_alignment_sha256"),
field="hnc_packet.hnc_alignment_sha256",
)
locator_commitment = domain_hash(
"aureon.plumber.hnc-source-locator.v0",
{
"magic": packet.get("magic"),
"schema_version": packet.get("schema_version"),
},
)
return SourceIdentityV0.build(
source_type="hnc-quantum-packet-v1",
source_locator_commitment=locator_commitment,
source_content_commitment=packet_commitment,
provenance_receipt_commitment=alignment_commitment,
)
def verify_source_identity(value: SourceIdentityV0 | Mapping[str, Any]) -> bool:
try:
identity = value if isinstance(value, SourceIdentityV0) else SourceIdentityV0.from_dict(value)
return domain_hash("aureon.plumber.source-identity.v0", identity.commitment_payload()) == identity.identity_commitment
except (SchemaError, TypeError, ValueError):
return False
__all__ = [
"SOURCE_IDENTITY_SCHEMA",
"SourceIdentityV0",
"build_source_identity",
"build_source_identity_from_hnc_packet",
"verify_source_identity",
]aureon/operator/website_design_capabilities/motion_interaction.pyAdded+88
aureon/operator/website_design_capabilities/performance_core_web_vitals.pyAdded+99
aureon/operator/website_design_capabilities/research_object_rendering.pyAdded+78
aureon/operator/website_design_capabilities/visual_identity_tokens.pyAdded+71
aureon/operator/website_design_capability_set.pyAdded+678
aureon/operator/website_operator.defaults.jsonAdded+417
aureon/operator/website_operator.pyAdded
aureon/operator/website_operator.schema.jsonAdded+227
aureon/operator/website_operator_receipts.schema.jsonAdded+87
aureon/operator/website_runtime_measurement_provenance.pyAdded+938
aureon/operator/website_runtime_optimisation.pyAdded+1743
aureon/operator/website_source_rationalisation.pyAdded+1915
aureon/operator/wsgi.pyAdded+19
aureon/organism/__init__.pyAdded+1
aureon/organism/repository_layers.pyAdded+254
aureon/plumber/__init__.pyAdded+682
aureon/plumber/audit.pyAdded+165
aureon/plumber/authorization_chain_v02.pyAdded+652
aureon/plumber/breaker.pyAdded+160
aureon/plumber/crypto.pyAdded+307
aureon/plumber/enclave.pyAdded+428
aureon/plumber/immune_gate.pyAdded+271
aureon/plumber/magic_star_v02.pyAdded+1171
aureon/plumber/observer_transcript.pyAdded+236
aureon/plumber/os_protection.pyAdded+2081
aureon/plumber/packet.pyAdded+1184
aureon/plumber/production_release_broker_v03.pyAdded+2126
aureon/plumber/proposal_forge.pyAdded+973
aureon/plumber/protected_bootstrap_v05.pyAdded+586
aureon/plumber/quarantine.pyAdded+135
aureon/plumber/quorum.pyAdded+316
aureon/plumber/receipts.pyAdded+251
aureon/plumber/recipient_proof_v02.pyAdded+395
aureon/plumber/release_boundary_v02.pyAdded+1199
aureon/plumber/release_engine.pyAdded+648
aureon/plumber/release_evidence_v02.pyAdded+437
aureon/plumber/release_state_v02.pyAdded+453
aureon/plumber/runtime_guard_v04.pyAdded+1952
aureon/plumber/runtime_intrusion_ledger_v04.pyAdded
aureon/plumber/schema.pyAdded+373
aureon/plumber/source_identity.pyAdded+143
aureon/plumber/spore_transport.pyAdded
aureon/plumber/star_custody_v02.pyAdded
aureon/plumber/sympathetic_identity.pyAdded
aureon/plumber/temporal_identity.pyAdded
aureon/plumber/twin_rune_seal.pyAdded
aureon/portals/__init__.pyAdded
aureon/portals/actions.pyAdded
aureon/portals/ifs.pyAdded
aureon/portals/reconcile.pyAdded