diff --git a/docs/MACRO_RUNTIME_V0.30.md b/docs/MACRO_RUNTIME_V0.30.md new file mode 100644 index 00000000..e8a36978 --- /dev/null +++ b/docs/MACRO_RUNTIME_V0.30.md @@ -0,0 +1,335 @@ +# Macro Runtime v0.30 — Ghost-Walk Policy Admission + +v0.30 introduces a distinct fail-closed policy-admission layer between typed +accepted intent and any future authority request. + +Core rule: + +```text +ACCEPTED INTENT +!= +POLICY ADMISSION +!= +AUTHORITY REQUEST +!= +ACTIONLEASE +!= +EXECUTION +``` + +## Purpose + +v0.29 can prove what the human says a demonstration means. + +v0.30 answers a different question: + +> Under the currently loaded server-side policy, is this exact accepted intent +> eligible to proceed to a later authority-request step? + +It does not create authority. + +## Decisions + +Policy admission has exactly three decisions: + +```text +ALLOW_REQUEST +HOLD +DENY +``` + +Semantics: + +- `ALLOW_REQUEST`: eligible to create a later authority request +- `HOLD`: insufficient/currently stale/unmapped evidence +- `DENY`: policy explicitly denies this intent code + +`ALLOW_REQUEST` is intentionally named narrowly. + +It does not mean: + +```text +AUTHORIZED +LEASED +EXECUTABLE +EXECUTED +``` + +## Server-owned policy + +The browser cannot edit policy. + +The Ghost-Walk sidecar loads policy from server/runtime configuration: + +```text +PHIOS_GHOSTWALK_POLICY_ALLOW_REQUEST +PHIOS_GHOSTWALK_POLICY_DENY +``` + +Both values are optional comma-separated canonical intent codes. + +Example: + +```powershell +$env:PHIOS_GHOSTWALK_POLICY_ALLOW_REQUEST="OPEN_NETWORK_ADAPTER_PROPERTIES,OPEN_NETWORK_SETTINGS" +$env:PHIOS_GHOSTWALK_POLICY_DENY="TOGGLE_AIRPLANE_MODE" +``` + +The default for any unmapped intent is always: + +```text +HOLD +``` + +An empty policy therefore permits no authority requests. + +## Policy profile + +`GhostWalkPolicyProfile` binds: + +- profile identity +- sorted unique allow-request intent-code set +- sorted unique deny intent-code set +- default HOLD decision +- zero authority flags + +The allow and deny sets may not overlap. + +Its canonical identity is: + +```text +profile_sha256 +``` + +Policy configuration therefore becomes explicit evidence rather than invisible +application state. + +## Admission evidence + +The read-only projection binds: + +- transition-inference receipt SHA-256 +- current accepted-intent revision SHA-256 +- accepted intent family/code/status +- exact OperatorLog revision originally used for acceptance +- exact current OperatorLog revision +- whether the OperatorLog binding is current +- exact policy profile SHA-256 +- decision +- reason +- authority-request eligibility + +Its identity is: + +```text +projection_sha256 +``` + +The projection always asserts: + +```text +effect_performed = false +policy_authority = false +operational_authority = false +action_authority = false +execution_authority = false +``` + +## Decision precedence + +v0.30 evaluates in this order: + +```text +accepted intent REVOKED + -> HOLD + +current OperatorLog RETRACTED + -> HOLD + +accepted intent bound to older OperatorLog revision + -> HOLD + +intent explicitly denied + -> DENY + +intent explicitly allow-request listed + -> ALLOW_REQUEST + +otherwise + -> HOLD +``` + +This means an allow-listed code cannot bypass stale or retracted human evidence. + +## Recorded admission receipt + +PhiShell can explicitly record the current admission result. + +The request binds: + +```text +target_inference_receipt_sha256 +expected_accepted_intent_revision_sha256 +expected_policy_profile_sha256 +``` + +Before persistence, the runtime recomputes the projection and rejects changes to +the accepted intent or policy profile. + +The persisted receipt records: + +- projection SHA-256 +- exact accepted-intent revision SHA-256 +- exact policy profile SHA-256 +- decision +- reason +- request-authority eligibility +- evaluation time +- receipt SHA-256 + +Recording the receipt is a real ledger effect: + +```text +effect_performed = true +``` + +but it explicitly asserts: + +```text +desktop_effect_performed = false +authority_request_created = false +action_lease_created = false + +policy_authority = false +operational_authority = false +action_authority = false +execution_authority = false +``` + +## Transport + +Read current projection: + +```http +GET /api/v1/ghostwalk/policy-admission?target= +``` + +Record current admission evidence: + +```http +POST /api/v1/ghostwalk/policy-admission/evaluations +``` + +Body: + +```json +{ + "target_inference_receipt_sha256": "...", + "expected_accepted_intent_revision_sha256": "...", + "expected_policy_profile_sha256": "..." +} +``` + +The browser cannot supply: + +- decision +- reason +- policy contents +- policy authority +- action authority +- execution authority +- authority-request payloads +- ActionLease data + +## PhiShell + +The Accepted Intent editor now contains a Policy Admission card. + +It displays: + +- ALLOW_REQUEST / HOLD / DENY +- exact reason +- request-authority eligibility +- current/stale OperatorLog binding +- policy profile digest +- allow/deny rule counts +- default HOLD behavior + +The only mutation available is: + +```text +RECORD ADMISSION EVIDENCE +``` + +There is deliberately no: + +```text +REQUEST AUTHORITY +CREATE ACTIONLEASE +EXECUTE +``` + +button in v0.30. + +## Existing ActionLease boundary + +PhiOS already defines `ActionLease` as the first primitive in the wider +architecture that carries affirmative bounded action authority. + +v0.30 does not call or construct it. + +The intended future chain is: + +```text +Ghost-Walk accepted intent + ↓ +v0.30 policy admission + ↓ +future authority request + ↓ +explicit authorization decision + ↓ +existing EffectIntent / EnforcementProfile / AuthorityEpoch gates + ↓ +ActionLease + ↓ +existing governed execution handoff +``` + +## Acceptance rules + +Tests cover: + +- unmapped intent defaults to HOLD +- explicit allow produces ALLOW_REQUEST only +- explicit deny produces DENY +- stale OperatorLog binding HOLDs before allow rules +- persisted admission creates no authority request +- persisted admission creates no ActionLease +- stale accepted-intent expectation conflicts +- policy profile defaults fail closed +- overlapping allow/deny configuration fails closed +- browser cannot inject authority into admission requests +- Node and browser contracts independently verify zero-authority envelopes +- PhiShell transport preserves projection and recorded receipt semantics + +## Next rung + +v0.31 should create an immutable **AuthorityRequest** artifact from an +`ALLOW_REQUEST` admission receipt. + +That artifact should still carry zero action authority: + +```text +policy admission + ↓ +AuthorityRequest + ↓ +explicit authorization decision + ↓ +ActionLease +``` + +A request is evidence that authority was asked for. + +It is not evidence that authority was granted. diff --git a/phios/macro_ghostwalk_control_server.py b/phios/macro_ghostwalk_control_server.py index c6a77a35..35b24643 100644 --- a/phios/macro_ghostwalk_control_server.py +++ b/phios/macro_ghostwalk_control_server.py @@ -39,6 +39,13 @@ GhostWalkOperatorNoteView, ) from phios.macro_operator_log import OperatorNoteStatus +from phios.macro_policy_admission import ( + GhostWalkPolicyAdmissionError, + GhostWalkPolicyAdmissionProjection, + GhostWalkPolicyAdmissionReceipt, + GhostWalkPolicyAdmissionService, + GhostWalkPolicyProfile, +) from phios.spine.ledger import RealityLedger LOOPBACK_HOST = "127.0.0.1" @@ -54,6 +61,10 @@ "phios.ghostwalk-accepted-intent-transport.v0.29" ) ACCEPTED_INTENT_TRANSPORT_IDENTITY = "phios-ghostwalk-accepted-intent" +POLICY_ADMISSION_TRANSPORT_SCHEMA_VERSION = ( + "phios.ghostwalk-policy-admission-transport.v0.30" +) +POLICY_ADMISSION_TRANSPORT_IDENTITY = "phios-ghostwalk-policy-admission" DEFAULT_HOST_ID = "ghostwalk-host:local" DEFAULT_BASELINE_SERVICE_ID = "ghostwalk-baseline:local" DEFAULT_COORDINATOR_ID = "ghostwalk-coordinator:local" @@ -122,6 +133,26 @@ def revoke( ) -> GhostWalkAcceptedIntentRevision: ... +class GhostWalkPolicyAdmissionPort(Protocol): + profile: GhostWalkPolicyProfile + + def project( + self, + *, + target_inference_receipt_sha256: str, + ) -> GhostWalkPolicyAdmissionProjection: ... + + def record( + self, + *, + target_inference_receipt_sha256: str, + expected_accepted_intent_revision_sha256: str, + expected_policy_profile_sha256: str, + evaluated_at: str | None = None, + ) -> GhostWalkPolicyAdmissionReceipt: ... + + + def _utc_now() -> str: return datetime.now(UTC).isoformat() @@ -427,6 +458,124 @@ def parse_accepted_intent_payload( ) +def _policy_admission_transport_base( + *, + effect_performed: bool, +) -> dict[str, object]: + return { + "transportSchemaVersion": ( + POLICY_ADMISSION_TRANSPORT_SCHEMA_VERSION + ), + "transport": "loopback-http", + "transportIdentity": POLICY_ADMISSION_TRANSPORT_IDENTITY, + "localOnly": True, + "admissionRecorded": effect_performed, + "desktopEffectPerformed": False, + "authorityRequestCreated": False, + "actionLeaseCreated": False, + "policyAuthority": False, + "operationalAuthority": False, + "actionAuthority": False, + "executionAuthority": False, + "effectPerformed": effect_performed, + } + + +def policy_admission_projection_envelope( + service: GhostWalkPolicyAdmissionPort, + *, + target_inference_receipt_sha256: str, +) -> dict[str, object]: + projection = service.project( + target_inference_receipt_sha256=( + target_inference_receipt_sha256 + ) + ) + payload = _policy_admission_transport_base( + effect_performed=False + ) + payload.update( + { + "servedAt": _utc_now(), + "profile": service.profile.to_dict(), + "projection": projection.to_dict(), + } + ) + return payload + + +def policy_admission_record_envelope( + service: GhostWalkPolicyAdmissionPort, + *, + target_inference_receipt_sha256: str, + expected_accepted_intent_revision_sha256: str, + expected_policy_profile_sha256: str, +) -> dict[str, object]: + receipt = service.record( + target_inference_receipt_sha256=( + target_inference_receipt_sha256 + ), + expected_accepted_intent_revision_sha256=( + expected_accepted_intent_revision_sha256 + ), + expected_policy_profile_sha256=( + expected_policy_profile_sha256 + ), + ) + payload = _policy_admission_transport_base( + effect_performed=True + ) + payload.update( + { + "servedAt": _utc_now(), + "profile": service.profile.to_dict(), + "receipt": receipt.to_dict(), + } + ) + return payload + + +def parse_policy_admission_record_payload( + payload: object, +) -> tuple[str, str, str]: + if not isinstance(payload, Mapping): + raise GhostWalkControlBridgeError( + "policy-admission record body must be an object" + ) + expected_keys = { + "target_inference_receipt_sha256", + "expected_accepted_intent_revision_sha256", + "expected_policy_profile_sha256", + } + if set(payload) != expected_keys: + raise GhostWalkControlBridgeError( + "policy-admission record fields do not match contract" + ) + target = payload.get("target_inference_receipt_sha256") + expected_intent = payload.get( + "expected_accepted_intent_revision_sha256" + ) + expected_profile = payload.get( + "expected_policy_profile_sha256" + ) + for value, field in ( + (target, "target inference receipt"), + (expected_intent, "expected accepted intent revision"), + (expected_profile, "expected policy profile"), + ): + if ( + not isinstance(value, str) + or re.fullmatch(r"[0-9a-f]{64}", value) is None + ): + raise GhostWalkControlBridgeError( + f"{field} must be a SHA-256 digest" + ) + assert isinstance(target, str) + assert isinstance(expected_intent, str) + assert isinstance(expected_profile, str) + return target, expected_intent, expected_profile + + def status_envelope(surface: GhostWalkSurface) -> dict[str, object]: payload = _transport_base() payload.update( @@ -573,6 +722,17 @@ def _accepted_intent_error( body.update({"error": code, "servedAt": _utc_now()}) self._json(status, body) + def _policy_admission_error( + self, + status: HTTPStatus, + code: str, + ) -> None: + body = _policy_admission_transport_base( + effect_performed=False + ) + body.update({"error": code, "servedAt": _utc_now()}) + self._json(status, body) + def _read_json( self, *, @@ -608,6 +768,58 @@ def _read_json( def do_GET(self) -> None: parsed = urlsplit(self.path) + if parsed.path == "/api/v1/ghostwalk/policy-admission": + if self.server.policy_admission is None: + self._policy_admission_error( + HTTPStatus.SERVICE_UNAVAILABLE, + "ghostwalk_policy_admission_unavailable", + ) + return + try: + query = parse_qs( + parsed.query, + keep_blank_values=True, + strict_parsing=True, + ) + except ValueError: + self._policy_admission_error( + HTTPStatus.BAD_REQUEST, + "invalid_ghostwalk_policy_admission_request", + ) + return + targets = query.get("target") + if ( + set(query) != {"target"} + or targets is None + or len(targets) != 1 + or re.fullmatch(r"[0-9a-f]{64}", targets[0]) is None + ): + self._policy_admission_error( + HTTPStatus.BAD_REQUEST, + "invalid_ghostwalk_policy_admission_request", + ) + return + try: + envelope = policy_admission_projection_envelope( + self.server.policy_admission, + target_inference_receipt_sha256=targets[0], + ) + except GhostWalkPolicyAdmissionError as exc: + code = ( + "ghostwalk_policy_admission_not_ready" + if "does not exist" in str(exc) + else "ghostwalk_policy_admission_invalid_evidence" + ) + self._policy_admission_error( + HTTPStatus.NOT_FOUND + if code.endswith("not_ready") + else HTTPStatus.CONFLICT, + code, + ) + return + self._json(HTTPStatus.OK, envelope) + return + if parsed.path == "/api/v1/ghostwalk/accepted-intent": if self.server.accepted_intents is None: self._accepted_intent_error( @@ -640,7 +852,7 @@ def do_GET(self) -> None: ) return try: - envelope = accepted_intent_envelope( + intent_envelope = accepted_intent_envelope( self.server.accepted_intents, target_inference_receipt_sha256=targets[0], ) @@ -650,13 +862,13 @@ def do_GET(self) -> None: "ghostwalk_accepted_intent_invalid_history", ) return - if envelope is None: + if intent_envelope is None: self._accepted_intent_error( HTTPStatus.NOT_FOUND, "ghostwalk_accepted_intent_not_found", ) return - self._json(HTTPStatus.OK, envelope) + self._json(HTTPStatus.OK, intent_envelope) return if parsed.path == "/api/v1/ghostwalk/operator-log": @@ -719,6 +931,56 @@ def do_GET(self) -> None: def do_POST(self) -> None: parsed = urlsplit(self.path) + if parsed.path == "/api/v1/ghostwalk/policy-admission/evaluations": + if parsed.query or parsed.fragment: + self._policy_admission_error( + HTTPStatus.BAD_REQUEST, + "invalid_ghostwalk_policy_admission_record", + ) + return + if self.server.policy_admission is None: + self._policy_admission_error( + HTTPStatus.SERVICE_UNAVAILABLE, + "ghostwalk_policy_admission_unavailable", + ) + return + try: + target, expected_intent, expected_profile = ( + parse_policy_admission_record_payload( + self._read_json() + ) + ) + except GhostWalkControlBridgeError: + self._policy_admission_error( + HTTPStatus.BAD_REQUEST, + "invalid_ghostwalk_policy_admission_record", + ) + return + try: + envelope = policy_admission_record_envelope( + self.server.policy_admission, + target_inference_receipt_sha256=target, + expected_accepted_intent_revision_sha256=( + expected_intent + ), + expected_policy_profile_sha256=expected_profile, + ) + except GhostWalkPolicyAdmissionError as exc: + conflict = "changed before" in str(exc) + self._policy_admission_error( + HTTPStatus.CONFLICT + if conflict + else HTTPStatus.BAD_REQUEST, + ( + "ghostwalk_policy_admission_conflict" + if conflict + else "ghostwalk_policy_admission_rejected" + ), + ) + return + self._json(HTTPStatus.OK, envelope) + return + if parsed.path == "/api/v1/ghostwalk/accepted-intent/revisions": if parsed.query or parsed.fragment: self._accepted_intent_error( @@ -888,6 +1150,7 @@ def __init__( surface: GhostWalkSurface, editor: GhostWalkOperatorEditorPort | None = None, accepted_intents: GhostWalkAcceptedIntentPort | None = None, + policy_admission: GhostWalkPolicyAdmissionPort | None = None, stop_callback: Callable[[], object] | None = None, ) -> None: if address[0] != LOOPBACK_HOST: @@ -897,6 +1160,7 @@ def __init__( self.surface = surface self.editor = editor self.accepted_intents = accepted_intents + self.policy_admission = policy_admission self._stop_callback = stop_callback super().__init__(address, GhostWalkControlHandler) @@ -995,11 +1259,22 @@ def main() -> None: ), accepted_by=DEFAULT_OPERATOR_AUTHOR_ID, ) + policy_admission = GhostWalkPolicyAdmissionService( + ledger=RealityLedger( + args.state_root.expanduser() + / "ledger" + / "receipts.jsonl" + ), + accepted_intents=accepted_intents, + operator_editor=editor, + profile=GhostWalkPolicyProfile.from_environment(os.environ), + ) server = GhostWalkControlServer( (LOOPBACK_HOST, args.port), surface=surface, editor=editor, accepted_intents=accepted_intents, + policy_admission=policy_admission, stop_callback=host.stop, ) diff --git a/phios/macro_policy_admission.py b/phios/macro_policy_admission.py new file mode 100644 index 00000000..1a9c340f --- /dev/null +++ b/phios/macro_policy_admission.py @@ -0,0 +1,652 @@ +"""Fail-closed Ghost-Walk policy admission for Macro Runtime v0.30. + +Policy admission answers one narrow question: whether the current accepted intent +is eligible to proceed to a *later* authority-request step. + +Admission never creates an EffectIntent, AuthorityEpoch, ActionLease, execution +handoff, or desktop effect. +""" + +from __future__ import annotations + +import hashlib +import json +import re +from dataclasses import dataclass +from datetime import UTC, datetime +from enum import StrEnum +from typing import Mapping + +from phios.macro_accepted_intent import ( + GhostWalkAcceptedIntentError, + GhostWalkAcceptedIntentRegistry, + GhostWalkAcceptedIntentRevision, + GhostWalkAcceptedIntentStatus, +) +from phios.macro_ghostwalk_operator_editor import ( + GhostWalkOperatorEditor, + GhostWalkOperatorEditorError, +) +from phios.macro_operator_log import OperatorNoteStatus +from phios.spine.ledger import RealityLedger + +GHOSTWALK_POLICY_PROFILE_SCHEMA_VERSION = ( + "phios.ghostwalk_policy_profile.v0.30" +) +GHOSTWALK_POLICY_ADMISSION_PROJECTION_SCHEMA_VERSION = ( + "phios.ghostwalk_policy_admission_projection.v0.30" +) +GHOSTWALK_POLICY_ADMISSION_RECEIPT_SCHEMA_VERSION = ( + "phios.ghostwalk_policy_admission_receipt.v0.30" +) +_SHA256_RE = re.compile(r"^[0-9a-f]{64}$") +_INTENT_CODE_RE = re.compile(r"^[A-Z][A-Z0-9_]{2,127}$") + + +class GhostWalkPolicyAdmissionError(ValueError): + """Raised when policy admission evidence or configuration is invalid.""" + + +class GhostWalkPolicyDecision(StrEnum): + ALLOW_REQUEST = "ALLOW_REQUEST" + HOLD = "HOLD" + DENY = "DENY" + + +class GhostWalkPolicyReason(StrEnum): + INTENT_EXPLICITLY_ALLOWED = "INTENT_EXPLICITLY_ALLOWED" + INTENT_EXPLICITLY_DENIED = "INTENT_EXPLICITLY_DENIED" + INTENT_UNMAPPED = "INTENT_UNMAPPED" + ACCEPTED_INTENT_REVOKED = "ACCEPTED_INTENT_REVOKED" + OPERATOR_NOTE_RETRACTED = "OPERATOR_NOTE_RETRACTED" + STALE_OPERATOR_BINDING = "STALE_OPERATOR_BINDING" + + +def _require_text( + value: object, + field: str, + *, + maximum: int = 4096, +) -> str: + if not isinstance(value, str) or not value: + raise GhostWalkPolicyAdmissionError( + f"{field} must be a non-empty string" + ) + if len(value) > maximum: + raise GhostWalkPolicyAdmissionError( + f"{field} exceeds {maximum} characters" + ) + if any(ord(char) < 32 for char in value): + raise GhostWalkPolicyAdmissionError( + f"{field} contains control characters" + ) + return value + + +def _require_sha256(value: object, field: str) -> str: + text = _require_text(value, field, maximum=64) + if not _SHA256_RE.fullmatch(text): + raise GhostWalkPolicyAdmissionError( + f"{field} must be a lowercase SHA-256 digest" + ) + return text + + +def _require_timestamp(value: object, field: str) -> str: + text = _require_text(value, field, maximum=64) + try: + parsed = datetime.fromisoformat(text.replace("Z", "+00:00")) + except ValueError as exc: + raise GhostWalkPolicyAdmissionError( + f"{field} must be an ISO-8601 timestamp" + ) from exc + if parsed.tzinfo is None: + raise GhostWalkPolicyAdmissionError( + f"{field} must include a timezone" + ) + return text + + +def _canonical_json(value: object) -> str: + try: + return json.dumps( + value, + sort_keys=True, + separators=(",", ":"), + ensure_ascii=False, + allow_nan=False, + ) + except (TypeError, ValueError) as exc: + raise GhostWalkPolicyAdmissionError( + "policy-admission payload must be canonical JSON" + ) from exc + + +def _canonical_sha256(value: object) -> str: + return hashlib.sha256(_canonical_json(value).encode("utf-8")).hexdigest() + + +def _utc_now() -> str: + return datetime.now(UTC).isoformat() + + +def _canonical_codes( + values: tuple[str, ...], + field: str, +) -> tuple[str, ...]: + normalized: list[str] = [] + for value in values: + code = _require_text(value, f"{field} item", maximum=128) + if not _INTENT_CODE_RE.fullmatch(code): + raise GhostWalkPolicyAdmissionError( + f"{field} items must be uppercase symbolic intent codes" + ) + normalized.append(code) + canonical = tuple(sorted(set(normalized))) + if canonical != values: + raise GhostWalkPolicyAdmissionError( + f"{field} must be sorted and unique" + ) + return canonical + + +def _parse_csv_codes(raw: str | None) -> tuple[str, ...]: + if raw is None or raw.strip() == "": + return () + values = tuple( + sorted( + { + item.strip().upper() + for item in raw.split(",") + if item.strip() + } + ) + ) + return _canonical_codes(values, "policy codes") + + +@dataclass(frozen=True, slots=True) +class GhostWalkPolicyProfile: + profile_id: str + allow_request_intent_codes: tuple[str, ...] + deny_intent_codes: tuple[str, ...] + default_decision: GhostWalkPolicyDecision = GhostWalkPolicyDecision.HOLD + policy_authority: bool = False + operational_authority: bool = False + action_authority: bool = False + execution_authority: bool = False + schema_version: str = GHOSTWALK_POLICY_PROFILE_SCHEMA_VERSION + + def __post_init__(self) -> None: + if self.schema_version != GHOSTWALK_POLICY_PROFILE_SCHEMA_VERSION: + raise GhostWalkPolicyAdmissionError( + "unsupported Ghost-Walk policy profile schema" + ) + _require_text(self.profile_id, "profile_id", maximum=512) + _canonical_codes( + self.allow_request_intent_codes, + "allow_request_intent_codes", + ) + _canonical_codes(self.deny_intent_codes, "deny_intent_codes") + if set(self.allow_request_intent_codes).intersection( + self.deny_intent_codes + ): + raise GhostWalkPolicyAdmissionError( + "policy allow and deny intent sets must not overlap" + ) + if self.default_decision is not GhostWalkPolicyDecision.HOLD: + raise GhostWalkPolicyAdmissionError( + "v0.30 policy default must fail closed as HOLD" + ) + if ( + self.policy_authority + or self.operational_authority + or self.action_authority + or self.execution_authority + ): + raise GhostWalkPolicyAdmissionError( + "policy profile cannot carry authority" + ) + + def body_dict(self) -> dict[str, object]: + return { + "schema_version": self.schema_version, + "profile_id": self.profile_id, + "allow_request_intent_codes": list( + self.allow_request_intent_codes + ), + "deny_intent_codes": list(self.deny_intent_codes), + "default_decision": self.default_decision.value, + "policy_authority": self.policy_authority, + "operational_authority": self.operational_authority, + "action_authority": self.action_authority, + "execution_authority": self.execution_authority, + } + + @property + def profile_sha256(self) -> str: + return _canonical_sha256(self.body_dict()) + + def to_dict(self) -> dict[str, object]: + payload = self.body_dict() + payload["profile_sha256"] = self.profile_sha256 + return payload + + @classmethod + def from_environment( + cls, + env: Mapping[str, str], + *, + profile_id: str = "ghostwalk-policy:local", + ) -> "GhostWalkPolicyProfile": + return cls( + profile_id=profile_id, + allow_request_intent_codes=_parse_csv_codes( + env.get("PHIOS_GHOSTWALK_POLICY_ALLOW_REQUEST") + ), + deny_intent_codes=_parse_csv_codes( + env.get("PHIOS_GHOSTWALK_POLICY_DENY") + ), + ) + + +@dataclass(frozen=True, slots=True) +class GhostWalkPolicyAdmissionProjection: + target_inference_receipt_sha256: str + accepted_intent_revision_sha256: str + source_operator_note_revision_sha256: str + current_operator_note_revision_sha256: str + policy_profile_sha256: str + intent_family: str + intent_code: str + accepted_intent_status: str + operator_binding_current: bool + decision: GhostWalkPolicyDecision + reason: GhostWalkPolicyReason + request_authority_eligible: bool + effect_performed: bool = False + policy_authority: bool = False + operational_authority: bool = False + action_authority: bool = False + execution_authority: bool = False + schema_version: str = ( + GHOSTWALK_POLICY_ADMISSION_PROJECTION_SCHEMA_VERSION + ) + + def __post_init__(self) -> None: + if ( + self.schema_version + != GHOSTWALK_POLICY_ADMISSION_PROJECTION_SCHEMA_VERSION + ): + raise GhostWalkPolicyAdmissionError( + "unsupported policy admission projection schema" + ) + for field, digest in ( + ( + "target_inference_receipt_sha256", + self.target_inference_receipt_sha256, + ), + ( + "accepted_intent_revision_sha256", + self.accepted_intent_revision_sha256, + ), + ( + "source_operator_note_revision_sha256", + self.source_operator_note_revision_sha256, + ), + ( + "current_operator_note_revision_sha256", + self.current_operator_note_revision_sha256, + ), + ("policy_profile_sha256", self.policy_profile_sha256), + ): + _require_sha256(digest, field) + _require_text(self.intent_family, "intent_family", maximum=64) + code = _require_text(self.intent_code, "intent_code", maximum=128) + if not _INTENT_CODE_RE.fullmatch(code): + raise GhostWalkPolicyAdmissionError( + "intent_code must be an uppercase symbolic identifier" + ) + _require_text( + self.accepted_intent_status, + "accepted_intent_status", + maximum=64, + ) + if self.request_authority_eligible is not ( + self.decision is GhostWalkPolicyDecision.ALLOW_REQUEST + ): + raise GhostWalkPolicyAdmissionError( + "request_authority_eligible must match ALLOW_REQUEST decision" + ) + if ( + self.effect_performed + or self.policy_authority + or self.operational_authority + or self.action_authority + or self.execution_authority + ): + raise GhostWalkPolicyAdmissionError( + "policy admission projection cannot carry authority or effects" + ) + + def body_dict(self) -> dict[str, object]: + return { + "schema_version": self.schema_version, + "target_inference_receipt_sha256": ( + self.target_inference_receipt_sha256 + ), + "accepted_intent_revision_sha256": ( + self.accepted_intent_revision_sha256 + ), + "source_operator_note_revision_sha256": ( + self.source_operator_note_revision_sha256 + ), + "current_operator_note_revision_sha256": ( + self.current_operator_note_revision_sha256 + ), + "policy_profile_sha256": self.policy_profile_sha256, + "intent_family": self.intent_family, + "intent_code": self.intent_code, + "accepted_intent_status": self.accepted_intent_status, + "operator_binding_current": self.operator_binding_current, + "decision": self.decision.value, + "reason": self.reason.value, + "request_authority_eligible": ( + self.request_authority_eligible + ), + "effect_performed": self.effect_performed, + "policy_authority": self.policy_authority, + "operational_authority": self.operational_authority, + "action_authority": self.action_authority, + "execution_authority": self.execution_authority, + } + + @property + def projection_sha256(self) -> str: + return _canonical_sha256(self.body_dict()) + + def to_dict(self) -> dict[str, object]: + payload = self.body_dict() + payload["projection_sha256"] = self.projection_sha256 + return payload + + +@dataclass(frozen=True, slots=True) +class GhostWalkPolicyAdmissionReceipt: + projection_sha256: str + target_inference_receipt_sha256: str + accepted_intent_revision_sha256: str + policy_profile_sha256: str + decision: GhostWalkPolicyDecision + reason: GhostWalkPolicyReason + request_authority_eligible: bool + evaluated_at: str + effect_performed: bool = True + desktop_effect_performed: bool = False + authority_request_created: bool = False + action_lease_created: bool = False + policy_authority: bool = False + operational_authority: bool = False + action_authority: bool = False + execution_authority: bool = False + schema_version: str = ( + GHOSTWALK_POLICY_ADMISSION_RECEIPT_SCHEMA_VERSION + ) + + def __post_init__(self) -> None: + if ( + self.schema_version + != GHOSTWALK_POLICY_ADMISSION_RECEIPT_SCHEMA_VERSION + ): + raise GhostWalkPolicyAdmissionError( + "unsupported policy admission receipt schema" + ) + for field, digest in ( + ("projection_sha256", self.projection_sha256), + ( + "target_inference_receipt_sha256", + self.target_inference_receipt_sha256, + ), + ( + "accepted_intent_revision_sha256", + self.accepted_intent_revision_sha256, + ), + ("policy_profile_sha256", self.policy_profile_sha256), + ): + _require_sha256(digest, field) + _require_timestamp(self.evaluated_at, "evaluated_at") + if self.request_authority_eligible is not ( + self.decision is GhostWalkPolicyDecision.ALLOW_REQUEST + ): + raise GhostWalkPolicyAdmissionError( + "receipt request eligibility must match decision" + ) + if self.effect_performed is not True: + raise GhostWalkPolicyAdmissionError( + "recorded admission receipt must acknowledge persistence effect" + ) + if ( + self.desktop_effect_performed + or self.authority_request_created + or self.action_lease_created + or self.policy_authority + or self.operational_authority + or self.action_authority + or self.execution_authority + ): + raise GhostWalkPolicyAdmissionError( + "policy admission receipt cannot create authority or desktop effects" + ) + + def body_dict(self) -> dict[str, object]: + return { + "schema_version": self.schema_version, + "projection_sha256": self.projection_sha256, + "target_inference_receipt_sha256": ( + self.target_inference_receipt_sha256 + ), + "accepted_intent_revision_sha256": ( + self.accepted_intent_revision_sha256 + ), + "policy_profile_sha256": self.policy_profile_sha256, + "decision": self.decision.value, + "reason": self.reason.value, + "request_authority_eligible": ( + self.request_authority_eligible + ), + "evaluated_at": self.evaluated_at, + "effect_performed": self.effect_performed, + "desktop_effect_performed": self.desktop_effect_performed, + "authority_request_created": self.authority_request_created, + "action_lease_created": self.action_lease_created, + "policy_authority": self.policy_authority, + "operational_authority": self.operational_authority, + "action_authority": self.action_authority, + "execution_authority": self.execution_authority, + } + + @property + def admission_receipt_sha256(self) -> str: + return _canonical_sha256(self.body_dict()) + + def to_dict(self) -> dict[str, object]: + payload = self.body_dict() + payload["admission_receipt_sha256"] = ( + self.admission_receipt_sha256 + ) + return payload + + +class GhostWalkPolicyAdmissionService: + """Evaluate accepted intent against server-owned, fail-closed policy.""" + + def __init__( + self, + *, + ledger: RealityLedger, + accepted_intents: GhostWalkAcceptedIntentRegistry, + operator_editor: GhostWalkOperatorEditor, + profile: GhostWalkPolicyProfile, + ) -> None: + if not isinstance(ledger, RealityLedger): + raise GhostWalkPolicyAdmissionError( + "ledger must be a RealityLedger" + ) + self._ledger = ledger + self._accepted_intents = accepted_intents + self._operator_editor = operator_editor + self.profile = profile + + def project( + self, + *, + target_inference_receipt_sha256: str, + ) -> GhostWalkPolicyAdmissionProjection: + target = _require_sha256( + target_inference_receipt_sha256, + "target_inference_receipt_sha256", + ) + try: + accepted = self._accepted_intents.current( + target_inference_receipt_sha256=target + ) + except GhostWalkAcceptedIntentError as exc: + raise GhostWalkPolicyAdmissionError(str(exc)) from exc + if accepted is None: + raise GhostWalkPolicyAdmissionError( + "accepted intent does not exist" + ) + + try: + note = self._operator_editor.view( + target_inference_receipt_sha256=target + ) + except GhostWalkOperatorEditorError as exc: + raise GhostWalkPolicyAdmissionError(str(exc)) from exc + + binding_current = ( + note.revision_sha256 + == accepted.source_operator_note_revision_sha256 + ) + decision, reason = self._decide( + accepted=accepted, + operator_note_active=( + note.status is OperatorNoteStatus.ACTIVE + ), + binding_current=binding_current, + ) + return GhostWalkPolicyAdmissionProjection( + target_inference_receipt_sha256=target, + accepted_intent_revision_sha256=( + accepted.revision_sha256 + ), + source_operator_note_revision_sha256=( + accepted.source_operator_note_revision_sha256 + ), + current_operator_note_revision_sha256=( + note.revision_sha256 + ), + policy_profile_sha256=self.profile.profile_sha256, + intent_family=accepted.intent_family.value, + intent_code=accepted.intent_code, + accepted_intent_status=accepted.status.value, + operator_binding_current=binding_current, + decision=decision, + reason=reason, + request_authority_eligible=( + decision is GhostWalkPolicyDecision.ALLOW_REQUEST + ), + ) + + def record( + self, + *, + target_inference_receipt_sha256: str, + expected_accepted_intent_revision_sha256: str, + expected_policy_profile_sha256: str, + evaluated_at: str | None = None, + ) -> GhostWalkPolicyAdmissionReceipt: + expected_intent = _require_sha256( + expected_accepted_intent_revision_sha256, + "expected_accepted_intent_revision_sha256", + ) + expected_profile = _require_sha256( + expected_policy_profile_sha256, + "expected_policy_profile_sha256", + ) + if expected_profile != self.profile.profile_sha256: + raise GhostWalkPolicyAdmissionError( + "policy profile changed before admission record" + ) + + projection = self.project( + target_inference_receipt_sha256=( + target_inference_receipt_sha256 + ) + ) + if projection.accepted_intent_revision_sha256 != expected_intent: + raise GhostWalkPolicyAdmissionError( + "accepted intent changed before admission record" + ) + + receipt = GhostWalkPolicyAdmissionReceipt( + projection_sha256=projection.projection_sha256, + target_inference_receipt_sha256=( + projection.target_inference_receipt_sha256 + ), + accepted_intent_revision_sha256=( + projection.accepted_intent_revision_sha256 + ), + policy_profile_sha256=projection.policy_profile_sha256, + decision=projection.decision, + reason=projection.reason, + request_authority_eligible=( + projection.request_authority_eligible + ), + evaluated_at=_require_timestamp( + _utc_now() if evaluated_at is None else evaluated_at, + "evaluated_at", + ), + ) + self._ledger.append_ghostwalk_policy_admission_receipt(receipt) + return receipt + + def _decide( + self, + *, + accepted: GhostWalkAcceptedIntentRevision, + operator_note_active: bool, + binding_current: bool, + ) -> tuple[GhostWalkPolicyDecision, GhostWalkPolicyReason]: + if accepted.status is GhostWalkAcceptedIntentStatus.REVOKED: + return ( + GhostWalkPolicyDecision.HOLD, + GhostWalkPolicyReason.ACCEPTED_INTENT_REVOKED, + ) + if not operator_note_active: + return ( + GhostWalkPolicyDecision.HOLD, + GhostWalkPolicyReason.OPERATOR_NOTE_RETRACTED, + ) + if not binding_current: + return ( + GhostWalkPolicyDecision.HOLD, + GhostWalkPolicyReason.STALE_OPERATOR_BINDING, + ) + if accepted.intent_code in self.profile.deny_intent_codes: + return ( + GhostWalkPolicyDecision.DENY, + GhostWalkPolicyReason.INTENT_EXPLICITLY_DENIED, + ) + if ( + accepted.intent_code + in self.profile.allow_request_intent_codes + ): + return ( + GhostWalkPolicyDecision.ALLOW_REQUEST, + GhostWalkPolicyReason.INTENT_EXPLICITLY_ALLOWED, + ) + return ( + self.profile.default_decision, + GhostWalkPolicyReason.INTENT_UNMAPPED, + ) diff --git a/phios/spine/ledger.py b/phios/spine/ledger.py index 5f6d6fb2..e3a7fb5c 100644 --- a/phios/spine/ledger.py +++ b/phios/spine/ledger.py @@ -31,6 +31,7 @@ from phios.macro_journal import MacroRunJournalEntry, MacroRunResumeReceipt from phios.macro_operator_log import OperatorLogRevision from phios.macro_accepted_intent import GhostWalkAcceptedIntentRevision + from phios.macro_policy_admission import GhostWalkPolicyAdmissionReceipt from phios.macro_post_action_verification import ( PostActionVerificationReceipt, ) @@ -522,6 +523,48 @@ def ghostwalk_accepted_intent_revisions( == target_inference_receipt_sha256 ] + def append_ghostwalk_policy_admission_receipt( + self, + receipt: "GhostWalkPolicyAdmissionReceipt", + ) -> None: + """Append one immutable Ghost-Walk policy-admission receipt.""" + + path = ( + self.path.parent + / "ghostwalk-policy-admission-receipts.jsonl" + ) + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("a", encoding="utf-8") as handle: + handle.write( + json.dumps(receipt.to_dict(), sort_keys=True) + "\n" + ) + + def ghostwalk_policy_admission_receipts( + self, + *, + target_inference_receipt_sha256: str | None = None, + ) -> list[dict[str, object]]: + """Return append-order Ghost-Walk policy-admission receipts.""" + + path = ( + self.path.parent + / "ghostwalk-policy-admission-receipts.jsonl" + ) + if not path.exists(): + return [] + rows = [ + json.loads(line) + for line in path.read_text(encoding="utf-8").splitlines() + ] + if target_inference_receipt_sha256 is None: + return rows + return [ + row + for row in rows + if row.get("target_inference_receipt_sha256") + == target_inference_receipt_sha256 + ] + def append_interaction_guard_receipt( self, receipt: "InteractionGuardReceipt", diff --git a/phishell/host/ghostWalkPolicyAdmissionLocalTransport.test.mjs b/phishell/host/ghostWalkPolicyAdmissionLocalTransport.test.mjs new file mode 100644 index 00000000..0bdc390d --- /dev/null +++ b/phishell/host/ghostWalkPolicyAdmissionLocalTransport.test.mjs @@ -0,0 +1,137 @@ +import test from "node:test"; +import assert from "node:assert/strict"; + +import { createLocalObservationServer } from "./localTransport.mjs"; + +const profile = { + schema_version: "phios.ghostwalk_policy_profile.v0.30", + profile_id: "ghostwalk-policy:test", + allow_request_intent_codes: ["OPEN_NETWORK_ADAPTER_PROPERTIES"], + deny_intent_codes: [], + default_decision: "HOLD", + policy_authority: false, + operational_authority: false, + action_authority: false, + execution_authority: false, + profile_sha256: "a".repeat(64), +}; +const projection = { + schema_version: "phios.ghostwalk_policy_admission_projection.v0.30", + target_inference_receipt_sha256: "b".repeat(64), + accepted_intent_revision_sha256: "c".repeat(64), + source_operator_note_revision_sha256: "d".repeat(64), + current_operator_note_revision_sha256: "d".repeat(64), + policy_profile_sha256: "a".repeat(64), + intent_family: "OPEN", + intent_code: "OPEN_NETWORK_ADAPTER_PROPERTIES", + accepted_intent_status: "ACTIVE", + operator_binding_current: true, + decision: "ALLOW_REQUEST", + reason: "INTENT_EXPLICITLY_ALLOWED", + request_authority_eligible: true, + effect_performed: false, + policy_authority: false, + operational_authority: false, + action_authority: false, + execution_authority: false, + projection_sha256: "e".repeat(64), +}; +const base = { + transportSchemaVersion: "phios.ghostwalk-policy-admission-transport.v0.30", + transport: "loopback-http", + transportIdentity: "phios-ghostwalk-policy-admission", + localOnly: true, + admissionRecorded: false, + desktopEffectPerformed: false, + authorityRequestCreated: false, + actionLeaseCreated: false, + policyAuthority: false, + operationalAuthority: false, + actionAuthority: false, + executionAuthority: false, + effectPerformed: false, + servedAt: "2026-09-27T07:15:00.000Z", +}; +const readEnvelope = { ...base, profile, projection }; +const receiptEnvelope = { + ...base, + admissionRecorded: true, + effectPerformed: true, + profile, + receipt: { + schema_version: "phios.ghostwalk_policy_admission_receipt.v0.30", + projection_sha256: "e".repeat(64), + target_inference_receipt_sha256: "b".repeat(64), + accepted_intent_revision_sha256: "c".repeat(64), + policy_profile_sha256: "a".repeat(64), + decision: "ALLOW_REQUEST", + reason: "INTENT_EXPLICITLY_ALLOWED", + request_authority_eligible: true, + evaluated_at: "2026-09-27T07:15:00.000Z", + effect_performed: true, + desktop_effect_performed: false, + authority_request_created: false, + action_lease_created: false, + policy_authority: false, + operational_authority: false, + action_authority: false, + execution_authority: false, + admission_receipt_sha256: "f".repeat(64), + }, +}; + +test("local transport proxies zero-authority policy projection", async () => { + const transport = createLocalObservationServer({ + port: 0, + serveShell: false, + ghostWalkPolicyAdmissionFetcher: async () => ({ + kind: "found", + envelope: readEnvelope, + }), + }); + const address = await transport.listen(); + try { + const response = await fetch( + `http://${address.host}:${address.port}/api/v1/ghostwalk/policy-admission?target=${"b".repeat(64)}`, + ); + assert.equal(response.status, 200); + const payload = await response.json(); + assert.equal(payload.projection.decision, "ALLOW_REQUEST"); + assert.equal(payload.actionLeaseCreated, false); + } finally { + await transport.close(); + } +}); + +test("local transport records admission without authority request", async () => { + const transport = createLocalObservationServer({ + port: 0, + serveShell: false, + ghostWalkPolicyAdmissionRecorder: async () => ({ + kind: "recorded", + envelope: receiptEnvelope, + }), + }); + const address = await transport.listen(); + try { + const response = await fetch( + `http://${address.host}:${address.port}/api/v1/ghostwalk/policy-admission/evaluations`, + { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ + target_inference_receipt_sha256: "b".repeat(64), + expected_accepted_intent_revision_sha256: "c".repeat(64), + expected_policy_profile_sha256: "a".repeat(64), + }), + }, + ); + assert.equal(response.status, 200); + const payload = await response.json(); + assert.equal(payload.effectPerformed, true); + assert.equal(payload.authorityRequestCreated, false); + assert.equal(payload.actionLeaseCreated, false); + } finally { + await transport.close(); + } +}); diff --git a/phishell/host/ghostWalkPolicyAdmissionProxy.mjs b/phishell/host/ghostWalkPolicyAdmissionProxy.mjs new file mode 100644 index 00000000..9752b597 --- /dev/null +++ b/phishell/host/ghostWalkPolicyAdmissionProxy.mjs @@ -0,0 +1,250 @@ +import { ghostWalkSidecarPort, GHOSTWALK_HOST } from "./ghostWalkControlProxy.mjs"; + +const SHA256 = /^[0-9a-f]{64}$/; +const INTENT_CODE = /^[A-Z][A-Z0-9_]{2,127}$/; +const DECISIONS = new Set(["ALLOW_REQUEST", "HOLD", "DENY"]); +const REASONS = new Set([ + "INTENT_EXPLICITLY_ALLOWED", + "INTENT_EXPLICITLY_DENIED", + "INTENT_UNMAPPED", + "ACCEPTED_INTENT_REVOKED", + "OPERATOR_NOTE_RETRACTED", + "STALE_OPERATOR_BINDING", +]); + +function record(value) { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +function sha(value) { + return typeof value === "string" && SHA256.test(value); +} + +function timestamp(value) { + return typeof value === "string" && value.length <= 64 && !Number.isNaN(Date.parse(value)); +} + +function boundedString(value, maximum = 512) { + return typeof value === "string" && value.length > 0 && value.length <= maximum; +} + +function canonicalCodes(value) { + if ( + !Array.isArray(value) || + value.length > 256 || + !value.every((item) => typeof item === "string" && INTENT_CODE.test(item)) + ) { + return false; + } + const canonical = [...new Set(value)].sort(); + return canonical.length === value.length && + canonical.every((item, index) => item === value[index]); +} + +function zeroSnakeAuthority(value) { + return ( + record(value) && + value.policy_authority === false && + value.operational_authority === false && + value.action_authority === false && + value.execution_authority === false + ); +} + +function zeroTransportAuthority(value) { + return ( + record(value) && + value.policyAuthority === false && + value.operationalAuthority === false && + value.actionAuthority === false && + value.executionAuthority === false + ); +} + +export function validateGhostWalkPolicyProfile(value) { + return ( + zeroSnakeAuthority(value) && + value.schema_version === "phios.ghostwalk_policy_profile.v0.30" && + boundedString(value.profile_id) && + canonicalCodes(value.allow_request_intent_codes) && + canonicalCodes(value.deny_intent_codes) && + value.default_decision === "HOLD" && + sha(value.profile_sha256) && + !value.allow_request_intent_codes.some((code) => + value.deny_intent_codes.includes(code) + ) + ); +} + +export function validateGhostWalkPolicyAdmissionProjection(value) { + if (!zeroSnakeAuthority(value)) return false; + if ( + value.schema_version !== "phios.ghostwalk_policy_admission_projection.v0.30" || + !sha(value.target_inference_receipt_sha256) || + !sha(value.accepted_intent_revision_sha256) || + !sha(value.source_operator_note_revision_sha256) || + !sha(value.current_operator_note_revision_sha256) || + !sha(value.policy_profile_sha256) || + !boundedString(value.intent_family, 64) || + typeof value.intent_code !== "string" || + !INTENT_CODE.test(value.intent_code) || + !["ACTIVE", "REVOKED"].includes(value.accepted_intent_status) || + typeof value.operator_binding_current !== "boolean" || + !DECISIONS.has(value.decision) || + !REASONS.has(value.reason) || + typeof value.request_authority_eligible !== "boolean" || + value.effect_performed !== false || + !sha(value.projection_sha256) + ) { + return false; + } + return value.request_authority_eligible === (value.decision === "ALLOW_REQUEST"); +} + +export function validateGhostWalkPolicyAdmissionReceipt(value) { + if (!zeroSnakeAuthority(value)) return false; + if ( + value.schema_version !== "phios.ghostwalk_policy_admission_receipt.v0.30" || + !sha(value.projection_sha256) || + !sha(value.target_inference_receipt_sha256) || + !sha(value.accepted_intent_revision_sha256) || + !sha(value.policy_profile_sha256) || + !DECISIONS.has(value.decision) || + !REASONS.has(value.reason) || + typeof value.request_authority_eligible !== "boolean" || + !timestamp(value.evaluated_at) || + value.effect_performed !== true || + value.desktop_effect_performed !== false || + value.authority_request_created !== false || + value.action_lease_created !== false || + !sha(value.admission_receipt_sha256) + ) { + return false; + } + return value.request_authority_eligible === (value.decision === "ALLOW_REQUEST"); +} + +function validBase(value, recorded) { + return ( + zeroTransportAuthority(value) && + value.transportSchemaVersion === "phios.ghostwalk-policy-admission-transport.v0.30" && + value.transport === "loopback-http" && + value.transportIdentity === "phios-ghostwalk-policy-admission" && + value.localOnly === true && + value.admissionRecorded === recorded && + value.desktopEffectPerformed === false && + value.authorityRequestCreated === false && + value.actionLeaseCreated === false && + value.effectPerformed === recorded && + timestamp(value.servedAt) + ); +} + +export function validateGhostWalkPolicyProjectionEnvelope(value) { + return ( + validBase(value, false) && + validateGhostWalkPolicyProfile(value.profile) && + validateGhostWalkPolicyAdmissionProjection(value.projection) && + value.profile.profile_sha256 === value.projection.policy_profile_sha256 + ); +} + +export function validateGhostWalkPolicyReceiptEnvelope(value) { + return ( + validBase(value, true) && + validateGhostWalkPolicyProfile(value.profile) && + validateGhostWalkPolicyAdmissionReceipt(value.receipt) && + value.profile.profile_sha256 === value.receipt.policy_profile_sha256 + ); +} + +export function validateGhostWalkPolicyRecordPayload(value) { + if (!record(value)) return false; + const keys = Object.keys(value).sort(); + const expected = [ + "expected_accepted_intent_revision_sha256", + "expected_policy_profile_sha256", + "target_inference_receipt_sha256", + ]; + return ( + keys.length === expected.length && + keys.every((key, index) => key === expected[index]) && + sha(value.target_inference_receipt_sha256) && + sha(value.expected_accepted_intent_revision_sha256) && + sha(value.expected_policy_profile_sha256) + ); +} + +async function request(url, init, fetcher, timeoutMs) { + const controller = new AbortController(); + const timeout = setTimeout(() => controller.abort(), timeoutMs); + try { + return await fetcher(url, { ...init, signal: controller.signal }); + } catch { + return null; + } finally { + clearTimeout(timeout); + } +} + +export async function fetchGhostWalkPolicyAdmission(targetSha256, { + fetcher = globalThis.fetch.bind(globalThis), + port = ghostWalkSidecarPort(), + timeoutMs = 1500, +} = {}) { + if (!sha(targetSha256)) return null; + const response = await request( + `http://${GHOSTWALK_HOST}:${port}/api/v1/ghostwalk/policy-admission?target=${targetSha256}`, + { + method: "GET", + cache: "no-store", + headers: { accept: "application/json" }, + }, + fetcher, + timeoutMs, + ); + if (!response) return null; + if (response.status === 404) return { kind: "not_ready" }; + if (!response.ok) return null; + try { + const payload = await response.json(); + return validateGhostWalkPolicyProjectionEnvelope(payload) + ? { kind: "found", envelope: payload } + : null; + } catch { + return null; + } +} + +export async function recordGhostWalkPolicyAdmission(payload, { + fetcher = globalThis.fetch.bind(globalThis), + port = ghostWalkSidecarPort(), + timeoutMs = 2500, +} = {}) { + if (!validateGhostWalkPolicyRecordPayload(payload)) return null; + const response = await request( + `http://${GHOSTWALK_HOST}:${port}/api/v1/ghostwalk/policy-admission/evaluations`, + { + method: "POST", + cache: "no-store", + headers: { + accept: "application/json", + "content-type": "application/json", + }, + body: JSON.stringify(payload), + }, + fetcher, + timeoutMs, + ); + if (!response) return null; + if (response.status === 409) return { kind: "conflict" }; + if (!response.ok) return null; + try { + const result = await response.json(); + return validateGhostWalkPolicyReceiptEnvelope(result) + ? { kind: "recorded", envelope: result } + : null; + } catch { + return null; + } +} diff --git a/phishell/host/ghostWalkPolicyAdmissionProxy.test.mjs b/phishell/host/ghostWalkPolicyAdmissionProxy.test.mjs new file mode 100644 index 00000000..37440aba --- /dev/null +++ b/phishell/host/ghostWalkPolicyAdmissionProxy.test.mjs @@ -0,0 +1,172 @@ +import test from "node:test"; +import assert from "node:assert/strict"; + +import { + fetchGhostWalkPolicyAdmission, + recordGhostWalkPolicyAdmission, + validateGhostWalkPolicyProjectionEnvelope, + validateGhostWalkPolicyRecordPayload, + validateGhostWalkPolicyReceiptEnvelope, +} from "./ghostWalkPolicyAdmissionProxy.mjs"; + +const profile = { + schema_version: "phios.ghostwalk_policy_profile.v0.30", + profile_id: "ghostwalk-policy:test", + allow_request_intent_codes: ["OPEN_NETWORK_ADAPTER_PROPERTIES"], + deny_intent_codes: [], + default_decision: "HOLD", + policy_authority: false, + operational_authority: false, + action_authority: false, + execution_authority: false, + profile_sha256: "a".repeat(64), +}; + +const projection = { + schema_version: "phios.ghostwalk_policy_admission_projection.v0.30", + target_inference_receipt_sha256: "b".repeat(64), + accepted_intent_revision_sha256: "c".repeat(64), + source_operator_note_revision_sha256: "d".repeat(64), + current_operator_note_revision_sha256: "d".repeat(64), + policy_profile_sha256: "a".repeat(64), + intent_family: "OPEN", + intent_code: "OPEN_NETWORK_ADAPTER_PROPERTIES", + accepted_intent_status: "ACTIVE", + operator_binding_current: true, + decision: "ALLOW_REQUEST", + reason: "INTENT_EXPLICITLY_ALLOWED", + request_authority_eligible: true, + effect_performed: false, + policy_authority: false, + operational_authority: false, + action_authority: false, + execution_authority: false, + projection_sha256: "e".repeat(64), +}; + +const base = { + transportSchemaVersion: "phios.ghostwalk-policy-admission-transport.v0.30", + transport: "loopback-http", + transportIdentity: "phios-ghostwalk-policy-admission", + localOnly: true, + admissionRecorded: false, + desktopEffectPerformed: false, + authorityRequestCreated: false, + actionLeaseCreated: false, + policyAuthority: false, + operationalAuthority: false, + actionAuthority: false, + executionAuthority: false, + effectPerformed: false, + servedAt: "2026-09-27T07:15:00.000Z", +}; + +const projectionEnvelope = { ...base, profile, projection }; +const receipt = { + schema_version: "phios.ghostwalk_policy_admission_receipt.v0.30", + projection_sha256: "e".repeat(64), + target_inference_receipt_sha256: "b".repeat(64), + accepted_intent_revision_sha256: "c".repeat(64), + policy_profile_sha256: "a".repeat(64), + decision: "ALLOW_REQUEST", + reason: "INTENT_EXPLICITLY_ALLOWED", + request_authority_eligible: true, + evaluated_at: "2026-09-27T07:15:00.000Z", + effect_performed: true, + desktop_effect_performed: false, + authority_request_created: false, + action_lease_created: false, + policy_authority: false, + operational_authority: false, + action_authority: false, + execution_authority: false, + admission_receipt_sha256: "f".repeat(64), +}; +const receiptEnvelope = { + ...base, + admissionRecorded: true, + effectPerformed: true, + profile, + receipt, +}; + +test("validates policy projection as zero authority", () => { + assert.equal(validateGhostWalkPolicyProjectionEnvelope(projectionEnvelope), true); + assert.equal( + validateGhostWalkPolicyProjectionEnvelope({ + ...projectionEnvelope, + actionLeaseCreated: true, + }), + false, + ); +}); + +test("validates recorded admission without authority request", () => { + assert.equal(validateGhostWalkPolicyReceiptEnvelope(receiptEnvelope), true); + assert.equal( + validateGhostWalkPolicyReceiptEnvelope({ + ...receiptEnvelope, + authorityRequestCreated: true, + }), + false, + ); +}); + +test("record payload is exact and authority-free", () => { + const payload = { + target_inference_receipt_sha256: "b".repeat(64), + expected_accepted_intent_revision_sha256: "c".repeat(64), + expected_policy_profile_sha256: "a".repeat(64), + }; + assert.equal(validateGhostWalkPolicyRecordPayload(payload), true); + assert.equal( + validateGhostWalkPolicyRecordPayload({ + ...payload, + actionAuthority: true, + }), + false, + ); +}); + +test("fetch distinguishes not-ready from invalid transport", async () => { + const fetcher = async () => ({ status: 404, ok: false }); + assert.deepEqual( + await fetchGhostWalkPolicyAdmission("b".repeat(64), { + fetcher, + port: 3973, + }), + { kind: "not_ready" }, + ); +}); + +test("record preserves conflict and validates success", async () => { + const conflictFetcher = async () => ({ status: 409, ok: false }); + assert.deepEqual( + await recordGhostWalkPolicyAdmission( + { + target_inference_receipt_sha256: "b".repeat(64), + expected_accepted_intent_revision_sha256: "c".repeat(64), + expected_policy_profile_sha256: "a".repeat(64), + }, + { fetcher: conflictFetcher, port: 3973 }, + ), + { kind: "conflict" }, + ); + + const successFetcher = async () => ({ + status: 200, + ok: true, + async json() { + return receiptEnvelope; + }, + }); + const result = await recordGhostWalkPolicyAdmission( + { + target_inference_receipt_sha256: "b".repeat(64), + expected_accepted_intent_revision_sha256: "c".repeat(64), + expected_policy_profile_sha256: "a".repeat(64), + }, + { fetcher: successFetcher, port: 3973 }, + ); + assert.equal(result?.kind, "recorded"); +}); diff --git a/phishell/host/localTransport.mjs b/phishell/host/localTransport.mjs index 309f5e03..efb1c7d8 100644 --- a/phishell/host/localTransport.mjs +++ b/phishell/host/localTransport.mjs @@ -32,6 +32,11 @@ import { fetchGhostWalkAcceptedIntent, validateGhostWalkAcceptedIntentMutationPayload, } from "./ghostWalkAcceptedIntentProxy.mjs"; +import { + fetchGhostWalkPolicyAdmission, + recordGhostWalkPolicyAdmission, + validateGhostWalkPolicyRecordPayload, +} from "./ghostWalkPolicyAdmissionProxy.mjs"; import { createPersistRequest, fetchBrokerHealth, @@ -132,6 +137,8 @@ export function createLocalObservationServer({ ghostWalkOperatorEditApplier = applyGhostWalkOperatorEdit, ghostWalkAcceptedIntentFetcher = fetchGhostWalkAcceptedIntent, ghostWalkAcceptedIntentMutator = applyGhostWalkAcceptedIntentMutation, + ghostWalkPolicyAdmissionFetcher = fetchGhostWalkPolicyAdmission, + ghostWalkPolicyAdmissionRecorder = recordGhostWalkPolicyAdmission, } = {}) { if (!Number.isInteger(port) || port < 0 || port > 65535) { throw new Error("local observation port must be an integer between 0 and 65535"); @@ -141,6 +148,65 @@ export function createLocalObservationServer({ try { const url = new URL(request.url ?? "/", `http://${LOOPBACK_HOST}`); + if ( + request.method === "POST" && + url.pathname === "/api/v1/ghostwalk/policy-admission/evaluations" + ) { + let payload; + try { + payload = await readBoundedJsonObject(request, { maxBytes: 8192 }); + } catch { + jsonResponse(response, 400, { + error: "invalid_ghostwalk_policy_admission_body", + policyAuthority: false, + operationalAuthority: false, + actionAuthority: false, + executionAuthority: false, + effectPerformed: false, + }); + return; + } + + if (!validateGhostWalkPolicyRecordPayload(payload)) { + jsonResponse(response, 400, { + error: "invalid_ghostwalk_policy_admission_request", + policyAuthority: false, + operationalAuthority: false, + actionAuthority: false, + executionAuthority: false, + effectPerformed: false, + }); + return; + } + + const result = await ghostWalkPolicyAdmissionRecorder(payload); + if (result?.kind === "conflict") { + jsonResponse(response, 409, { + error: "ghostwalk_policy_admission_conflict", + policyAuthority: false, + operationalAuthority: false, + actionAuthority: false, + executionAuthority: false, + effectPerformed: false, + }); + return; + } + if (!result || result.kind !== "recorded") { + jsonResponse(response, 503, { + error: "ghostwalk_policy_admission_unavailable", + policyAuthority: false, + operationalAuthority: false, + actionAuthority: false, + executionAuthority: false, + effectPerformed: false, + }); + return; + } + + jsonResponse(response, 200, result.envelope); + return; + } + if ( request.method === "POST" && url.pathname === "/api/v1/ghostwalk/accepted-intent/revisions" @@ -386,6 +452,54 @@ export function createLocalObservationServer({ return; } + if (url.pathname === "/api/v1/ghostwalk/policy-admission") { + const keys = [...url.searchParams.keys()]; + const target = url.searchParams.get("target"); + if ( + keys.length !== 1 || + keys[0] !== "target" || + typeof target !== "string" || + !/^[0-9a-f]{64}$/.test(target) + ) { + jsonResponse(response, 400, { + error: "invalid_ghostwalk_policy_admission_request", + policyAuthority: false, + operationalAuthority: false, + actionAuthority: false, + executionAuthority: false, + effectPerformed: false, + }); + return; + } + + const result = await ghostWalkPolicyAdmissionFetcher(target); + if (result?.kind === "not_ready") { + jsonResponse(response, 404, { + error: "ghostwalk_policy_admission_not_ready", + policyAuthority: false, + operationalAuthority: false, + actionAuthority: false, + executionAuthority: false, + effectPerformed: false, + }); + return; + } + if (!result || result.kind !== "found") { + jsonResponse(response, 503, { + error: "ghostwalk_policy_admission_unavailable", + policyAuthority: false, + operationalAuthority: false, + actionAuthority: false, + executionAuthority: false, + effectPerformed: false, + }); + return; + } + + jsonResponse(response, 200, result.envelope); + return; + } + if (url.pathname === "/api/v1/ghostwalk/accepted-intent") { const keys = [...url.searchParams.keys()]; const target = url.searchParams.get("target"); diff --git a/phishell/src/components/GhostWalkAcceptedIntentEditor.tsx b/phishell/src/components/GhostWalkAcceptedIntentEditor.tsx index a343d6c1..29985728 100644 --- a/phishell/src/components/GhostWalkAcceptedIntentEditor.tsx +++ b/phishell/src/components/GhostWalkAcceptedIntentEditor.tsx @@ -1,4 +1,5 @@ import { useCallback, useEffect, useState } from "react"; +import { GhostWalkPolicyAdmissionCard } from "./GhostWalkPolicyAdmissionCard"; import { GHOSTWALK_INTENT_FAMILIES, ghostWalkAcceptedIntentClient, @@ -219,6 +220,15 @@ export function GhostWalkAcceptedIntentEditor({
MACHINE CANDIDATE != HUMAN ANNOTATION != ACCEPTED INTENT != EXECUTION POLICY
+ + + {current && ( + + )} )} diff --git a/phishell/src/components/GhostWalkPolicyAdmissionCard.tsx b/phishell/src/components/GhostWalkPolicyAdmissionCard.tsx new file mode 100644 index 00000000..c9d379e3 --- /dev/null +++ b/phishell/src/components/GhostWalkPolicyAdmissionCard.tsx @@ -0,0 +1,126 @@ +import { useCallback, useEffect, useState } from "react"; +import { + ghostWalkPolicyAdmissionClient, + type GhostWalkPolicyProfile, + type GhostWalkPolicyProjection, + type GhostWalkPolicyReceipt, +} from "../ghostwalk/policyAdmission"; + +function shortHash(value: string) { + return `${value.slice(0, 10)}…`; +} + +export function GhostWalkPolicyAdmissionCard({ + targetSha256, + acceptedIntentRevisionSha256, + operatorNoteRevisionSha256, +}: { + targetSha256: string; + acceptedIntentRevisionSha256: string; + operatorNoteRevisionSha256: string; +}) { + const [profile, setProfile] = useState(null); + const [projection, setProjection] = useState(null); + const [receipt, setReceipt] = useState(null); + const [busy, setBusy] = useState(false); + const [message, setMessage] = useState(null); + + const load = useCallback(async () => { + const result = await ghostWalkPolicyAdmissionClient.read(targetSha256); + if (result.kind === "found") { + setProfile(result.profile); + setProjection(result.projection); + setMessage(null); + return; + } + setProfile(null); + setProjection(null); + setMessage( + result.kind === "not_ready" + ? "Policy admission is not ready because no valid accepted intent is available." + : "Policy admission is unavailable or returned invalid evidence.", + ); + }, [targetSha256, acceptedIntentRevisionSha256, operatorNoteRevisionSha256]); + + useEffect(() => { + void load(); + }, [load]); + + const recordAdmission = useCallback(async () => { + if (!profile || !projection) return; + setBusy(true); + setMessage(null); + try { + const result = await ghostWalkPolicyAdmissionClient.record({ + targetSha256, + expectedAcceptedIntentRevisionSha256: + projection.accepted_intent_revision_sha256, + expectedPolicyProfileSha256: profile.profile_sha256, + }); + if (result.kind === "conflict") { + setMessage( + "Admission conflict: accepted intent or policy changed before the receipt was recorded. Reload first.", + ); + return; + } + if (result.kind === "unavailable") { + setMessage("Policy admission receipt was rejected or could not be validated."); + return; + } + setReceipt(result.receipt); + setMessage( + `Recorded ${result.receipt.decision} admission evidence. No authority request or ActionLease was created.`, + ); + } finally { + setBusy(false); + } + }, [profile, projection, targetSha256]); + + return ( +
+
+
+ POLICY ADMISSION + {projection?.decision ?? "NOT READY"} +
+ AUTHORITY 0 +
+ + {projection && profile && ( + <> +
+ reason {projection.reason} + eligible {projection.request_authority_eligible ? "YES" : "NO"} + binding {projection.operator_binding_current ? "CURRENT" : "STALE"} + policy {shortHash(profile.profile_sha256)} +
+ +
+ allow-request {profile.allow_request_intent_codes.length} + deny {profile.deny_intent_codes.length} + default HOLD +
+ + + + )} + + {receipt && ( +
+ receipt {shortHash(receipt.admission_receipt_sha256)} · {receipt.decision} +
+ )} + {message &&
{message}
} + +
+ ALLOW_REQUEST != AUTHORITY REQUEST · POLICY ADMISSION != ACTIONLEASE · NO EXECUTION +
+
+ ); +} diff --git a/phishell/src/ghostwalk/policyAdmission.test.ts b/phishell/src/ghostwalk/policyAdmission.test.ts new file mode 100644 index 00000000..8b602bc5 --- /dev/null +++ b/phishell/src/ghostwalk/policyAdmission.test.ts @@ -0,0 +1,37 @@ +import { describe, expect, it, vi } from "vitest"; +import { createGhostWalkPolicyAdmissionClient } from "./policyAdmission"; + +describe("Ghost-Walk policy admission browser client", () => { + it("distinguishes not-ready from unavailable", async () => { + const fetcher = vi.fn(async () => new Response("", { status: 404 })); + const client = createGhostWalkPolicyAdmissionClient({ + fetcher: fetcher as typeof fetch, + }); + await expect(client.read("a".repeat(64))).resolves.toEqual({ + kind: "not_ready", + }); + }); + + it("record request contains only expected evidence hashes", async () => { + const fetcher = vi.fn(async (_url: RequestInfo | URL, init?: RequestInit) => { + const body = JSON.parse(String(init?.body)); + expect(body).toEqual({ + target_inference_receipt_sha256: "a".repeat(64), + expected_accepted_intent_revision_sha256: "b".repeat(64), + expected_policy_profile_sha256: "c".repeat(64), + }); + expect("actionAuthority" in body).toBe(false); + return new Response("", { status: 409 }); + }); + const client = createGhostWalkPolicyAdmissionClient({ + fetcher: fetcher as typeof fetch, + }); + await expect( + client.record({ + targetSha256: "a".repeat(64), + expectedAcceptedIntentRevisionSha256: "b".repeat(64), + expectedPolicyProfileSha256: "c".repeat(64), + }), + ).resolves.toEqual({ kind: "conflict" }); + }); +}); diff --git a/phishell/src/ghostwalk/policyAdmission.ts b/phishell/src/ghostwalk/policyAdmission.ts new file mode 100644 index 00000000..725be35b --- /dev/null +++ b/phishell/src/ghostwalk/policyAdmission.ts @@ -0,0 +1,280 @@ +export type GhostWalkPolicyDecision = "ALLOW_REQUEST" | "HOLD" | "DENY"; + +export interface GhostWalkPolicyProfile { + schema_version: "phios.ghostwalk_policy_profile.v0.30"; + profile_id: string; + allow_request_intent_codes: string[]; + deny_intent_codes: string[]; + default_decision: "HOLD"; + policy_authority: false; + operational_authority: false; + action_authority: false; + execution_authority: false; + profile_sha256: string; +} + +export interface GhostWalkPolicyProjection { + schema_version: "phios.ghostwalk_policy_admission_projection.v0.30"; + target_inference_receipt_sha256: string; + accepted_intent_revision_sha256: string; + source_operator_note_revision_sha256: string; + current_operator_note_revision_sha256: string; + policy_profile_sha256: string; + intent_family: string; + intent_code: string; + accepted_intent_status: string; + operator_binding_current: boolean; + decision: GhostWalkPolicyDecision; + reason: string; + request_authority_eligible: boolean; + effect_performed: false; + policy_authority: false; + operational_authority: false; + action_authority: false; + execution_authority: false; + projection_sha256: string; +} + +export interface GhostWalkPolicyReceipt { + schema_version: "phios.ghostwalk_policy_admission_receipt.v0.30"; + projection_sha256: string; + target_inference_receipt_sha256: string; + accepted_intent_revision_sha256: string; + policy_profile_sha256: string; + decision: GhostWalkPolicyDecision; + reason: string; + request_authority_eligible: boolean; + evaluated_at: string; + effect_performed: true; + desktop_effect_performed: false; + authority_request_created: false; + action_lease_created: false; + policy_authority: false; + operational_authority: false; + action_authority: false; + execution_authority: false; + admission_receipt_sha256: string; +} + +export type GhostWalkPolicyReadResult = + | { kind: "found"; profile: GhostWalkPolicyProfile; projection: GhostWalkPolicyProjection } + | { kind: "not_ready" } + | { kind: "unavailable" }; + +export type GhostWalkPolicyRecordResult = + | { kind: "recorded"; receipt: GhostWalkPolicyReceipt } + | { kind: "conflict" } + | { kind: "unavailable" }; + +function recordValue(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +function sha(value: unknown): value is string { + return typeof value === "string" && /^[0-9a-f]{64}$/.test(value); +} + +function timestamp(value: unknown): value is string { + return typeof value === "string" && value.length <= 64 && !Number.isNaN(Date.parse(value)); +} + +function stringArray(value: unknown): value is string[] { + return Array.isArray(value) && value.every((item) => typeof item === "string"); +} + +function isProfile(value: unknown): value is GhostWalkPolicyProfile { + if (!recordValue(value)) return false; + return ( + value.schema_version === "phios.ghostwalk_policy_profile.v0.30" && + typeof value.profile_id === "string" && + stringArray(value.allow_request_intent_codes) && + stringArray(value.deny_intent_codes) && + value.default_decision === "HOLD" && + value.policy_authority === false && + value.operational_authority === false && + value.action_authority === false && + value.execution_authority === false && + sha(value.profile_sha256) + ); +} + +function isProjection(value: unknown): value is GhostWalkPolicyProjection { + if (!recordValue(value)) return false; + const decision = value.decision; + return ( + value.schema_version === "phios.ghostwalk_policy_admission_projection.v0.30" && + sha(value.target_inference_receipt_sha256) && + sha(value.accepted_intent_revision_sha256) && + sha(value.source_operator_note_revision_sha256) && + sha(value.current_operator_note_revision_sha256) && + sha(value.policy_profile_sha256) && + typeof value.intent_family === "string" && + typeof value.intent_code === "string" && + typeof value.accepted_intent_status === "string" && + typeof value.operator_binding_current === "boolean" && + (decision === "ALLOW_REQUEST" || decision === "HOLD" || decision === "DENY") && + typeof value.reason === "string" && + typeof value.request_authority_eligible === "boolean" && + value.request_authority_eligible === (decision === "ALLOW_REQUEST") && + value.effect_performed === false && + value.policy_authority === false && + value.operational_authority === false && + value.action_authority === false && + value.execution_authority === false && + sha(value.projection_sha256) + ); +} + +function isReceipt(value: unknown): value is GhostWalkPolicyReceipt { + if (!recordValue(value)) return false; + const decision = value.decision; + return ( + value.schema_version === "phios.ghostwalk_policy_admission_receipt.v0.30" && + sha(value.projection_sha256) && + sha(value.target_inference_receipt_sha256) && + sha(value.accepted_intent_revision_sha256) && + sha(value.policy_profile_sha256) && + (decision === "ALLOW_REQUEST" || decision === "HOLD" || decision === "DENY") && + typeof value.reason === "string" && + typeof value.request_authority_eligible === "boolean" && + value.request_authority_eligible === (decision === "ALLOW_REQUEST") && + timestamp(value.evaluated_at) && + value.effect_performed === true && + value.desktop_effect_performed === false && + value.authority_request_created === false && + value.action_lease_created === false && + value.policy_authority === false && + value.operational_authority === false && + value.action_authority === false && + value.execution_authority === false && + sha(value.admission_receipt_sha256) + ); +} + +function validBase(value: unknown, recorded: boolean): value is Record { + if (!recordValue(value)) return false; + return ( + value.transportSchemaVersion === "phios.ghostwalk-policy-admission-transport.v0.30" && + value.transport === "loopback-http" && + value.transportIdentity === "phios-ghostwalk-policy-admission" && + value.localOnly === true && + value.admissionRecorded === recorded && + value.desktopEffectPerformed === false && + value.authorityRequestCreated === false && + value.actionLeaseCreated === false && + value.policyAuthority === false && + value.operationalAuthority === false && + value.actionAuthority === false && + value.executionAuthority === false && + value.effectPerformed === recorded && + timestamp(value.servedAt) + ); +} + +export function createGhostWalkPolicyAdmissionClient({ + fetcher = globalThis.fetch.bind(globalThis), + timeoutMs = 2_500, +}: { + fetcher?: typeof fetch; + timeoutMs?: number; +} = {}) { + return { + async read(targetSha256: string): Promise { + if (!sha(targetSha256)) return { kind: "unavailable" }; + const controller = new AbortController(); + const timeout = globalThis.setTimeout(() => controller.abort(), timeoutMs); + try { + const response = await fetcher( + `/api/v1/ghostwalk/policy-admission?target=${targetSha256}`, + { + method: "GET", + cache: "no-store", + credentials: "same-origin", + headers: { accept: "application/json" }, + signal: controller.signal, + }, + ); + if (response.status === 404) return { kind: "not_ready" }; + if (!response.ok) return { kind: "unavailable" }; + const payload: unknown = await response.json(); + if ( + !validBase(payload, false) || + !isProfile(payload.profile) || + !isProjection(payload.projection) || + payload.profile.profile_sha256 !== payload.projection.policy_profile_sha256 + ) { + return { kind: "unavailable" }; + } + return { + kind: "found", + profile: payload.profile, + projection: payload.projection, + }; + } catch { + return { kind: "unavailable" }; + } finally { + globalThis.clearTimeout(timeout); + } + }, + + async record({ + targetSha256, + expectedAcceptedIntentRevisionSha256, + expectedPolicyProfileSha256, + }: { + targetSha256: string; + expectedAcceptedIntentRevisionSha256: string; + expectedPolicyProfileSha256: string; + }): Promise { + if ( + !sha(targetSha256) || + !sha(expectedAcceptedIntentRevisionSha256) || + !sha(expectedPolicyProfileSha256) + ) { + return { kind: "unavailable" }; + } + const controller = new AbortController(); + const timeout = globalThis.setTimeout(() => controller.abort(), timeoutMs); + try { + const response = await fetcher( + "/api/v1/ghostwalk/policy-admission/evaluations", + { + method: "POST", + cache: "no-store", + credentials: "same-origin", + headers: { + accept: "application/json", + "content-type": "application/json", + }, + body: JSON.stringify({ + target_inference_receipt_sha256: targetSha256, + expected_accepted_intent_revision_sha256: + expectedAcceptedIntentRevisionSha256, + expected_policy_profile_sha256: expectedPolicyProfileSha256, + }), + signal: controller.signal, + }, + ); + if (response.status === 409) return { kind: "conflict" }; + if (!response.ok) return { kind: "unavailable" }; + const payload: unknown = await response.json(); + if ( + !validBase(payload, true) || + !isProfile(payload.profile) || + !isReceipt(payload.receipt) || + payload.profile.profile_sha256 !== payload.receipt.policy_profile_sha256 + ) { + return { kind: "unavailable" }; + } + return { kind: "recorded", receipt: payload.receipt }; + } catch { + return { kind: "unavailable" }; + } finally { + globalThis.clearTimeout(timeout); + } + }, + }; +} + +export const ghostWalkPolicyAdmissionClient = + createGhostWalkPolicyAdmissionClient(); diff --git a/phishell/src/styles.css b/phishell/src/styles.css index 160b0f3c..4e0cef20 100644 --- a/phishell/src/styles.css +++ b/phishell/src/styles.css @@ -328,3 +328,14 @@ linear-gradient(135deg,rgba(13,32,42,.92),rgba(5,13,17,.96));box-shadow:inset 0 .ghostwalk-intent-message,.ghostwalk-intent-warning{padding:7px 8px;border-radius:6px;font-size:7px;line-height:1.45}.ghostwalk-intent-message{border:1px solid rgba(32,229,192,.18);background:rgba(32,229,192,.02);color:var(--teal)}.ghostwalk-intent-warning{border:1px solid rgba(243,182,75,.28);background:rgba(243,182,75,.03);color:#d7c18f} .ghostwalk-intent-boundary{padding:7px 8px;border:1px solid rgba(39,223,255,.18);border-radius:6px;background:rgba(39,223,255,.02);color:var(--cyan);font:6px ui-monospace,monospace;letter-spacing:.04em;line-height:1.45} @media(max-width:780px){.ghostwalk-intent-form{grid-template-columns:1fr}} + + +/* Macro Runtime v0.30 policy admission */ +.ghostwalk-policy{display:grid;gap:8px;margin-top:4px;padding:10px;border:1px solid rgba(184,151,255,.25);border-radius:8px;background:linear-gradient(155deg,rgba(21,14,35,.55),rgba(5,15,20,.92))} +.ghostwalk-policy-head{display:flex;align-items:center;justify-content:space-between;gap:8px}.ghostwalk-policy-head small{display:block;color:#c8adff;font-size:7px;letter-spacing:.13em}.ghostwalk-policy-head b{display:block;margin-top:4px;color:var(--secondary);font:8px ui-monospace,monospace}.ghostwalk-policy-head>span{padding:4px 6px;border:1px solid rgba(184,151,255,.24);border-radius:4px;color:#c8adff;font:6px ui-monospace,monospace;letter-spacing:.05em} +.ghostwalk-policy-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:5px}.ghostwalk-policy-grid span{display:grid;gap:2px;padding:6px;border:1px solid rgba(184,151,255,.14);border-radius:5px;color:var(--muted);font:6px ui-monospace,monospace}.ghostwalk-policy-grid b{color:var(--secondary);font-size:7px;overflow-wrap:anywhere} +.ghostwalk-policy-rules{display:flex;flex-wrap:wrap;gap:5px}.ghostwalk-policy-rules span{padding:4px 6px;border:1px solid rgba(23,67,84,.45);border-radius:4px;color:var(--muted);font:6px ui-monospace,monospace} +.ghostwalk-policy-record{height:30px;border:1px solid rgba(184,151,255,.34);border-radius:6px;background:rgba(184,151,255,.04);color:#c8adff;font-size:6px;letter-spacing:.05em;cursor:pointer}.ghostwalk-policy-record:disabled{opacity:.4;cursor:not-allowed} +.ghostwalk-policy-receipt,.ghostwalk-policy-message{padding:7px 8px;border-radius:6px;font-size:7px;line-height:1.45}.ghostwalk-policy-receipt{border:1px solid rgba(32,229,192,.18);background:rgba(32,229,192,.02);color:var(--teal)}.ghostwalk-policy-message{border:1px solid rgba(243,182,75,.22);background:rgba(243,182,75,.025);color:#d7c18f} +.ghostwalk-policy-boundary{padding:7px 8px;border:1px solid rgba(184,151,255,.2);border-radius:6px;background:rgba(184,151,255,.02);color:#c8adff;font:6px ui-monospace,monospace;letter-spacing:.04em;line-height:1.45} +@media(max-width:780px){.ghostwalk-policy-grid{grid-template-columns:1fr}} diff --git a/tests/test_macro_policy_admission.py b/tests/test_macro_policy_admission.py new file mode 100644 index 00000000..ca4ad1e0 --- /dev/null +++ b/tests/test_macro_policy_admission.py @@ -0,0 +1,244 @@ +from __future__ import annotations + +import hashlib +import json +from pathlib import Path + +import pytest + +from phios.macro_accepted_intent import ( + GhostWalkAcceptedIntentRegistry, + GhostWalkIntentFamily, +) +from phios.macro_ghostwalk_operator_editor import GhostWalkOperatorEditor +from phios.macro_operator_log import OperatorLog +from phios.macro_policy_admission import ( + GhostWalkPolicyAdmissionError, + GhostWalkPolicyAdmissionService, + GhostWalkPolicyDecision, + GhostWalkPolicyProfile, + GhostWalkPolicyReason, +) +from phios.spine.ledger import RealityLedger + +ACTION = "b" * 64 +_INFERENCE_BODY = { + "status": "CANDIDATES", + "session_id": "demo", + "action_observation_sha256": ACTION, +} +TARGET = hashlib.sha256( + json.dumps( + _INFERENCE_BODY, + sort_keys=True, + separators=(",", ":"), + ensure_ascii=False, + allow_nan=False, + ).encode("utf-8") +).hexdigest() + + +def _ledger(tmp_path: Path) -> RealityLedger: + return RealityLedger(tmp_path / "ledger" / "receipts.jsonl") + + +def _seed( + ledger: RealityLedger, + *, + intent_code: str = "OPEN_NETWORK_ADAPTER_PROPERTIES", +) -> tuple[str, str]: + ledger.path.parent.mkdir(parents=True, exist_ok=True) + inference_path = ( + ledger.path.parent / "transition-inference-receipts.jsonl" + ) + inference_path.write_text( + json.dumps( + { + **_INFERENCE_BODY, + "receipt_sha256": TARGET, + }, + sort_keys=True, + ) + + "\n", + encoding="utf-8", + ) + note = OperatorLog(ledger).create( + note_id=f"ghostwalk-transition:{ACTION}", + target_sha256=TARGET, + author_id="operator:local", + body="Correction: opened network adapter properties.", + created_at="2026-09-27T07:10:00+00:00", + tags=( + "ghostwalk", + "operator-interpretation", + "transition-inference", + ), + ) + registry = GhostWalkAcceptedIntentRegistry( + ledger=ledger, + accepted_by="operator:local", + ) + accepted = registry.accept( + target_inference_receipt_sha256=TARGET, + source_operator_note_revision_sha256=note.revision_sha256, + intent_family=GhostWalkIntentFamily.OPEN, + intent_code=intent_code, + expected_current_revision_sha256=None, + accepted_at="2026-09-27T07:11:00+00:00", + ) + return note.revision_sha256, accepted.revision_sha256 + + +def _service( + ledger: RealityLedger, + *, + allow: tuple[str, ...] = (), + deny: tuple[str, ...] = (), +) -> GhostWalkPolicyAdmissionService: + return GhostWalkPolicyAdmissionService( + ledger=ledger, + accepted_intents=GhostWalkAcceptedIntentRegistry( + ledger=ledger, + accepted_by="operator:local", + ), + operator_editor=GhostWalkOperatorEditor( + ledger=ledger, + author_id="operator:local", + ), + profile=GhostWalkPolicyProfile( + profile_id="ghostwalk-policy:test", + allow_request_intent_codes=allow, + deny_intent_codes=deny, + ), + ) + + +def test_unmapped_intent_holds_by_default(tmp_path: Path) -> None: + ledger = _ledger(tmp_path) + _seed(ledger) + projection = _service(ledger).project( + target_inference_receipt_sha256=TARGET + ) + assert projection.decision is GhostWalkPolicyDecision.HOLD + assert projection.reason is GhostWalkPolicyReason.INTENT_UNMAPPED + assert projection.request_authority_eligible is False + assert projection.action_authority is False + + +def test_explicit_allow_makes_request_eligible_without_authority( + tmp_path: Path, +) -> None: + ledger = _ledger(tmp_path) + _seed(ledger) + projection = _service( + ledger, + allow=("OPEN_NETWORK_ADAPTER_PROPERTIES",), + ).project(target_inference_receipt_sha256=TARGET) + + assert projection.decision is GhostWalkPolicyDecision.ALLOW_REQUEST + assert projection.request_authority_eligible is True + assert projection.policy_authority is False + assert projection.action_authority is False + assert projection.execution_authority is False + + +def test_explicit_deny_wins_as_policy_decision(tmp_path: Path) -> None: + ledger = _ledger(tmp_path) + _seed(ledger) + projection = _service( + ledger, + deny=("OPEN_NETWORK_ADAPTER_PROPERTIES",), + ).project(target_inference_receipt_sha256=TARGET) + assert projection.decision is GhostWalkPolicyDecision.DENY + assert ( + projection.reason + is GhostWalkPolicyReason.INTENT_EXPLICITLY_DENIED + ) + + +def test_stale_operator_binding_holds_even_if_code_allowed( + tmp_path: Path, +) -> None: + ledger = _ledger(tmp_path) + note_sha, _ = _seed(ledger) + current = OperatorLog(ledger).current( + note_id=f"ghostwalk-transition:{ACTION}" + ) + assert current.revision_sha256 == note_sha + OperatorLog(ledger).edit( + note_id=current.note_id, + expected_current_revision_sha256=note_sha, + author_id="operator:local", + body="Newer human interpretation.", + created_at="2026-09-27T07:12:00+00:00", + tags=current.tags, + ) + + projection = _service( + ledger, + allow=("OPEN_NETWORK_ADAPTER_PROPERTIES",), + ).project(target_inference_receipt_sha256=TARGET) + assert projection.decision is GhostWalkPolicyDecision.HOLD + assert ( + projection.reason + is GhostWalkPolicyReason.STALE_OPERATOR_BINDING + ) + + +def test_record_binds_exact_intent_and_policy_without_authority( + tmp_path: Path, +) -> None: + ledger = _ledger(tmp_path) + _, intent_sha = _seed(ledger) + service = _service( + ledger, + allow=("OPEN_NETWORK_ADAPTER_PROPERTIES",), + ) + + receipt = service.record( + target_inference_receipt_sha256=TARGET, + expected_accepted_intent_revision_sha256=intent_sha, + expected_policy_profile_sha256=service.profile.profile_sha256, + evaluated_at="2026-09-27T07:13:00+00:00", + ) + + assert receipt.request_authority_eligible is True + assert receipt.authority_request_created is False + assert receipt.action_lease_created is False + assert receipt.execution_authority is False + assert receipt.effect_performed is True + assert len(ledger.ghostwalk_policy_admission_receipts()) == 1 + + +def test_record_rejects_stale_expected_intent(tmp_path: Path) -> None: + ledger = _ledger(tmp_path) + _seed(ledger) + service = _service(ledger) + + with pytest.raises( + GhostWalkPolicyAdmissionError, + match="accepted intent changed", + ): + service.record( + target_inference_receipt_sha256=TARGET, + expected_accepted_intent_revision_sha256="f" * 64, + expected_policy_profile_sha256=service.profile.profile_sha256, + ) + + +def test_policy_env_is_fail_closed_and_rejects_overlap() -> None: + empty = GhostWalkPolicyProfile.from_environment({}) + assert empty.allow_request_intent_codes == () + assert empty.deny_intent_codes == () + assert empty.default_decision is GhostWalkPolicyDecision.HOLD + + with pytest.raises( + GhostWalkPolicyAdmissionError, + match="must not overlap", + ): + GhostWalkPolicyProfile.from_environment( + { + "PHIOS_GHOSTWALK_POLICY_ALLOW_REQUEST": "OPEN_SETTINGS", + "PHIOS_GHOSTWALK_POLICY_DENY": "OPEN_SETTINGS", + } + ) diff --git a/tests/test_macro_policy_admission_server.py b/tests/test_macro_policy_admission_server.py new file mode 100644 index 00000000..586c6c82 --- /dev/null +++ b/tests/test_macro_policy_admission_server.py @@ -0,0 +1,208 @@ +from __future__ import annotations + +import json +import threading +from http.client import HTTPConnection + +from phios.macro_ghostwalk_control_server import ( + LOOPBACK_HOST, + GhostWalkControlServer, +) +from phios.macro_policy_admission import ( + GhostWalkPolicyAdmissionProjection, + GhostWalkPolicyAdmissionReceipt, + GhostWalkPolicyDecision, + GhostWalkPolicyProfile, + GhostWalkPolicyReason, +) + +TARGET = "a" * 64 +INTENT = "b" * 64 +NOTE = "c" * 64 + + +class FakeSurface: + def snapshot(self) -> object: + raise AssertionError("status endpoint not used") + + +class FakePolicyAdmission: + def __init__(self) -> None: + self.profile = GhostWalkPolicyProfile( + profile_id="ghostwalk-policy:test", + allow_request_intent_codes=( + "OPEN_NETWORK_ADAPTER_PROPERTIES", + ), + deny_intent_codes=(), + ) + self.record_calls: list[dict[str, str]] = [] + + def project( + self, + *, + target_inference_receipt_sha256: str, + ) -> GhostWalkPolicyAdmissionProjection: + assert target_inference_receipt_sha256 == TARGET + return GhostWalkPolicyAdmissionProjection( + target_inference_receipt_sha256=TARGET, + accepted_intent_revision_sha256=INTENT, + source_operator_note_revision_sha256=NOTE, + current_operator_note_revision_sha256=NOTE, + policy_profile_sha256=self.profile.profile_sha256, + intent_family="OPEN", + intent_code="OPEN_NETWORK_ADAPTER_PROPERTIES", + accepted_intent_status="ACTIVE", + operator_binding_current=True, + decision=GhostWalkPolicyDecision.ALLOW_REQUEST, + reason=GhostWalkPolicyReason.INTENT_EXPLICITLY_ALLOWED, + request_authority_eligible=True, + ) + + def record( + self, + *, + target_inference_receipt_sha256: str, + expected_accepted_intent_revision_sha256: str, + expected_policy_profile_sha256: str, + evaluated_at: str | None = None, + ) -> GhostWalkPolicyAdmissionReceipt: + self.record_calls.append( + { + "target": target_inference_receipt_sha256, + "intent": expected_accepted_intent_revision_sha256, + "profile": expected_policy_profile_sha256, + } + ) + projection = self.project( + target_inference_receipt_sha256=( + target_inference_receipt_sha256 + ) + ) + return GhostWalkPolicyAdmissionReceipt( + projection_sha256=projection.projection_sha256, + target_inference_receipt_sha256=TARGET, + accepted_intent_revision_sha256=INTENT, + policy_profile_sha256=self.profile.profile_sha256, + decision=GhostWalkPolicyDecision.ALLOW_REQUEST, + reason=GhostWalkPolicyReason.INTENT_EXPLICITLY_ALLOWED, + request_authority_eligible=True, + evaluated_at="2026-09-27T07:15:00+00:00", + ) + + +def _server( + service: FakePolicyAdmission, +) -> tuple[GhostWalkControlServer, threading.Thread]: + server = GhostWalkControlServer( + (LOOPBACK_HOST, 0), + surface=FakeSurface(), # type: ignore[arg-type] + policy_admission=service, # type: ignore[arg-type] + ) + thread = threading.Thread( + target=server.serve_forever, + daemon=True, + ) + thread.start() + return server, thread + + +def _request( + server: GhostWalkControlServer, + method: str, + path: str, + body: dict[str, object] | None = None, +) -> tuple[int, dict[str, object]]: + connection = HTTPConnection( + LOOPBACK_HOST, + server.server_address[1], + timeout=2, + ) + encoded = None + headers: dict[str, str] = {"accept": "application/json"} + if body is not None: + encoded = json.dumps(body).encode("utf-8") + headers["content-type"] = "application/json" + headers["content-length"] = str(len(encoded)) + connection.request(method, path, body=encoded, headers=headers) + response = connection.getresponse() + payload = json.loads(response.read().decode("utf-8")) + connection.close() + return response.status, payload + + +def test_policy_projection_is_read_only_and_zero_authority() -> None: + service = FakePolicyAdmission() + server, thread = _server(service) + try: + status, payload = _request( + server, + "GET", + "/api/v1/ghostwalk/policy-admission?target=" + TARGET, + ) + assert status == 200 + assert payload["effectPerformed"] is False + assert payload["admissionRecorded"] is False + assert payload["authorityRequestCreated"] is False + assert payload["actionLeaseCreated"] is False + assert payload["actionAuthority"] is False + assert payload["projection"]["decision"] == "ALLOW_REQUEST" + finally: + server.shutdown() + server.server_close() + thread.join(timeout=2) + + +def test_recorded_admission_is_ledger_effect_not_authority() -> None: + service = FakePolicyAdmission() + server, thread = _server(service) + try: + status, payload = _request( + server, + "POST", + "/api/v1/ghostwalk/policy-admission/evaluations", + { + "target_inference_receipt_sha256": TARGET, + "expected_accepted_intent_revision_sha256": INTENT, + "expected_policy_profile_sha256": ( + service.profile.profile_sha256 + ), + }, + ) + assert status == 200 + assert payload["effectPerformed"] is True + assert payload["admissionRecorded"] is True + assert payload["desktopEffectPerformed"] is False + assert payload["authorityRequestCreated"] is False + assert payload["actionLeaseCreated"] is False + assert payload["executionAuthority"] is False + assert payload["receipt"]["request_authority_eligible"] is True + assert len(service.record_calls) == 1 + finally: + server.shutdown() + server.server_close() + thread.join(timeout=2) + + +def test_browser_cannot_inject_authority_into_policy_record() -> None: + service = FakePolicyAdmission() + server, thread = _server(service) + try: + status, _ = _request( + server, + "POST", + "/api/v1/ghostwalk/policy-admission/evaluations", + { + "target_inference_receipt_sha256": TARGET, + "expected_accepted_intent_revision_sha256": INTENT, + "expected_policy_profile_sha256": ( + service.profile.profile_sha256 + ), + "actionAuthority": True, + }, + ) + assert status == 400 + assert service.record_calls == [] + finally: + server.shutdown() + server.server_close() + thread.join(timeout=2)