diff --git a/docs/MACRO_RUNTIME_V0.36.md b/docs/MACRO_RUNTIME_V0.36.md new file mode 100644 index 00000000..a9b960c0 --- /dev/null +++ b/docs/MACRO_RUNTIME_V0.36.md @@ -0,0 +1,293 @@ +# Macro Runtime v0.36 — Human Authorization + Lease Console + +Macro Runtime v0.36 exposes the already-governed v0.32-v0.34 trust chain to +the local human operator. + +It does not add a new executor. + +The completed operator path is: + +```text +AuthorityRequest + ↓ +human APPROVE / HOLD / DENY + ↓ +AuthorizationDecision + ↓ +deterministic capability/effect binding + ↓ +lease-readiness projection + ↓ +single-use ActionLease +``` + +Execution remains a separate v0.35 / PhiVessel bridge concern. + +## Core boundary + +```text +HUMAN DECISION != EXECUTABLE BINDING +EXECUTABLE BINDING != ACTION LEASE +ACTION LEASE != EXECUTION +VESSEL MAY REFERENCE A LEASE +VESSEL MAY NOT MINT A LEASE +``` + +## Human-only authorization surface + +The console is mounted under the existing PhiShell AuthorityRequest card. + +The browser may submit one explicit human decision: + +```text +APPROVE +HOLD +DENY +``` + +The decision request contains only: + +```text +target_inference_receipt_sha256 +expected_authority_request_sha256 +expected_previous_decision_sha256 +decision +decision_note +``` + +Authorizer identity remains server-owned. + +An APPROVE decision records authorization for the exact semantic request but +still carries no action authority and creates no lease. + +HOLD remains non-terminal. + +DENY and APPROVE remain terminal under the v0.32 contract. + +## Binding stage + +After an APPROVE decision, the console can request creation of the existing +v0.33 executable binding. + +The browser may echo only current optimistic-concurrency identities: + +```text +target_inference_receipt_sha256 +expected_authorization_decision_sha256 +expected_mapping_sha256 +expected_mapping_set_sha256 +``` + +The browser cannot supply: + +- capability ID or version; +- action payload; +- target; +- permission set; +- effects; +- mapping contents; +- binding timestamp. + +PhiOS derives those from trusted local mapping configuration and immutable +Ghost-Walk evidence. + +The console displays only a bounded binding summary, including capability, +payload hash, permissions, effects, mapping ID, and binding digest. The full +executable payload is not projected into the operator card. + +## Lease stage + +The console can issue the existing v0.34 ActionLease only when lease readiness +is `READY`. + +The browser may echo only: + +```text +target_inference_receipt_sha256 +expected_executable_binding_sha256 +expected_policy_sha256 +expected_policy_set_sha256 +expected_enforcement_profile_sha256 +expected_authority_epoch_sha256 +``` + +It cannot submit: + +- payload; +- permission names; +- effect names; +- lease duration; +- principal; +- issuer; +- policy rules; +- AuthorityEpoch contents; +- accepted enforcement gaps. + +The server recomputes trusted state under the existing v0.34 lock. + +The resulting lease remains single-use and bounded by the server-owned policy +and current AuthorityEpoch. + +## Console projection authority + +The console snapshot and transport remain zero-authority: + +```text +policy_authority = false +operational_authority = false +action_authority = false +execution_authority = false +effect_performed = false +``` + +A nested lease summary may report: + +```text +lease_action_authority = true +``` + +as a fact about the existing ActionLease. + +That does not transfer the lease's authority to the console transport. + +## Trusted execution manifest behavior + +Human authorization is available whenever the v0.31 AuthorityRequest service +is available. + +The binding and lease stages require the trusted local execution mount. + +Therefore: + +```text +no execution manifest + → human APPROVE / HOLD / DENY still available + → binding unavailable + → lease unavailable + → execution unavailable +``` + +With a valid enabled manifest: + +```text +human decision + ↓ +binding + ↓ +ActionLease + ↓ +Vessie may later call execute(leaseId) +``` + +The local execution mount now reuses the same +`GhostWalkAuthorizationDecisionService` instance as the human console, so +authorization mutation and downstream binding do not depend on separate +process-local decision locks. + +## Transport + +The Python loopback sidecar adds: + +```text +GET /api/v1/ghostwalk/authorization-console +POST /api/v1/ghostwalk/authorization-console/decisions +POST /api/v1/ghostwalk/authorization-console/bindings +POST /api/v1/ghostwalk/authorization-console/leases +``` + +PhiShell's Node local transport independently validates and proxies those +contracts. + +The browser client validates them again before rendering. + +No permissive CORS is added. + +## Mutation semantics + +Decision, binding, and lease creation are local Ledger mutations, so their +transport envelopes report: + +```text +effectPerformed = true +desktopEffectPerformed = false +``` + +The read-only console status reports: + +```text +effectPerformed = false +``` + +No v0.36 endpoint enters the desktop executor. + +## UI stages + +The PhiShell console is intentionally split into three visible stages: + +1. **Human Decision** + - APPROVE + - HOLD + - DENY + - optional human note + +2. **Executable Binding** + - trusted mapping readiness + - capability/version + - payload digest + - permissions/effects + - explicit create action + +3. **Single-Use ActionLease** + - lease-policy digest + - EnforcementProfile digest + - AuthorityEpoch digest + - missing-permission visibility + - explicit issue action + - exact lease identity and validity window + +There is intentionally no Execute button in this console. + +## PhiVessel boundary + +PhiVessel continues to expose only: + +```text +observe(...) +propose(...) +execute(leaseId) +``` + +v0.36 does not add: + +```text +authorize(...) +bind(...) +issueLease(...) +``` + +to Vessie. + +That asymmetry is intentional. + +```text +VESSEL MAY PROPOSE +HUMAN MAY AUTHORIZE +PHIOS MAY LEASE +VESSEL MAY REFERENCE LEASE +PHIOS MAY EXECUTE +REALITY LEDGER RECORDS RESULT +``` + +## Next rung + +After v0.36 is green, the next useful work should be operational rather than +another authority layer: + +1. trusted manifest / AuthorityEpoch operator tooling; +2. native/local Vessie host handshake; +3. one controlled Windows end-to-end Ghost-Walk acceptance scenario; +4. confirmation that the issued lease is consumed exactly once and that + post-action verification lands in the Reality Ledger. + +The authority architecture itself should remain unchanged unless that real +acceptance run reveals a concrete gap. diff --git a/phios/macro_authorization_console.py b/phios/macro_authorization_console.py new file mode 100644 index 00000000..0f1225e6 --- /dev/null +++ b/phios/macro_authorization_console.py @@ -0,0 +1,556 @@ +"""Human authorization and lease console for Macro Runtime v0.36. + +This layer surfaces the already-governed v0.32-v0.34 trust chain to a local +human operator. It does not execute a capability and it does not let the +browser choose capability, payload, effects, permissions, policy, authority +epoch, lease duration, principal, or issuer. +""" + +from __future__ import annotations + +import hashlib +import json +import re +from dataclasses import dataclass +from typing import Protocol + +from phios.macro_action_lease_service import ( + GhostWalkActionLeaseError, + GhostWalkActionLeaseRecord, + GhostWalkLeaseReadiness, +) +from phios.macro_authorization_decision import ( + GhostWalkAuthorizationDecision, + GhostWalkAuthorizationDecisionError, + GhostWalkAuthorizationDecisionKind, + GhostWalkAuthorizationReadiness, +) +from phios.macro_capability_binding import ( + GhostWalkBindingReadiness, + GhostWalkCapabilityBindingError, + GhostWalkExecutableBinding, +) + +GHOSTWALK_AUTHORIZATION_CONSOLE_SCHEMA_VERSION = ( + "phios.ghostwalk_authorization_console_snapshot.v0.36" +) +GHOSTWALK_BINDING_SUMMARY_SCHEMA_VERSION = ( + "phios.ghostwalk_executable_binding_summary.v0.36" +) +GHOSTWALK_LEASE_SUMMARY_SCHEMA_VERSION = ( + "phios.ghostwalk_action_lease_summary.v0.36" +) +_SHA256_RE = re.compile(r"^[0-9a-f]{64}$") + + +class GhostWalkAuthorizationConsoleError(ValueError): + """Raised when the human authorization console cannot trust its state.""" + + +def _require_sha256(value: object, field: str) -> str: + if not isinstance(value, str) or _SHA256_RE.fullmatch(value) is None: + raise GhostWalkAuthorizationConsoleError( + f"{field} must be a lowercase SHA-256 digest" + ) + return value + + +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 GhostWalkAuthorizationConsoleError( + "authorization-console payload must be canonical JSON" + ) from exc + + +def _canonical_sha256(value: object) -> str: + return hashlib.sha256(_canonical_json(value).encode("utf-8")).hexdigest() + + +@dataclass(frozen=True, slots=True) +class GhostWalkExecutableBindingSummary: + executable_binding_sha256: str + authorization_decision_sha256: str + intent_code: str + mapping_id: str + capability_id: str + capability_version: str + payload_sha256: str + permissions_required: tuple[str, ...] + effects_declared: tuple[str, ...] + bound_at: str + effect_performed: bool = False + action_authority: bool = False + execution_authority: bool = False + schema_version: str = GHOSTWALK_BINDING_SUMMARY_SCHEMA_VERSION + + @classmethod + def from_binding( + cls, + binding: GhostWalkExecutableBinding, + ) -> "GhostWalkExecutableBindingSummary": + return cls( + executable_binding_sha256=binding.executable_binding_sha256, + authorization_decision_sha256=( + binding.authorization_decision_sha256 + ), + intent_code=binding.intent_code, + mapping_id=binding.mapping_id, + capability_id=binding.capability_id, + capability_version=binding.capability_version, + payload_sha256=binding.payload_sha256, + permissions_required=binding.permissions_required, + effects_declared=binding.effects_declared, + bound_at=binding.bound_at, + ) + + def to_dict(self) -> dict[str, object]: + return { + "schema_version": self.schema_version, + "executable_binding_sha256": self.executable_binding_sha256, + "authorization_decision_sha256": ( + self.authorization_decision_sha256 + ), + "intent_code": self.intent_code, + "mapping_id": self.mapping_id, + "capability_id": self.capability_id, + "capability_version": self.capability_version, + "payload_sha256": self.payload_sha256, + "permissions_required": list(self.permissions_required), + "effects_declared": list(self.effects_declared), + "bound_at": self.bound_at, + "effect_performed": self.effect_performed, + "action_authority": self.action_authority, + "execution_authority": self.execution_authority, + } + + +@dataclass(frozen=True, slots=True) +class GhostWalkActionLeaseSummary: + action_lease_sha256: str + lease_record_sha256: str + executable_binding_sha256: str + principal_id: str + issuer_id: str + capability_id: str + capability_version: str + payload_sha256: str + effects_declared: tuple[str, ...] + permissions_authorized: tuple[str, ...] + valid_from: str + valid_until: str + max_uses: int + lease_action_authority: bool + effect_performed: bool = False + execution_authority: bool = False + schema_version: str = GHOSTWALK_LEASE_SUMMARY_SCHEMA_VERSION + + @classmethod + def from_record( + cls, + record: GhostWalkActionLeaseRecord, + ) -> "GhostWalkActionLeaseSummary": + lease = record.action_lease + return cls( + action_lease_sha256=lease.action_lease_sha256, + lease_record_sha256=record.lease_record_sha256, + executable_binding_sha256=record.executable_binding_sha256, + principal_id=lease.principal_id, + issuer_id=lease.issuer_id, + capability_id=lease.capability_id, + capability_version=lease.capability_version, + payload_sha256=lease.payload_sha256, + effects_declared=lease.effects_declared, + permissions_authorized=lease.permissions_authorized, + valid_from=lease.valid_from, + valid_until=lease.valid_until, + max_uses=lease.max_uses, + lease_action_authority=lease.action_authority, + ) + + def to_dict(self) -> dict[str, object]: + return { + "schema_version": self.schema_version, + "action_lease_sha256": self.action_lease_sha256, + "lease_record_sha256": self.lease_record_sha256, + "executable_binding_sha256": self.executable_binding_sha256, + "principal_id": self.principal_id, + "issuer_id": self.issuer_id, + "capability_id": self.capability_id, + "capability_version": self.capability_version, + "payload_sha256": self.payload_sha256, + "effects_declared": list(self.effects_declared), + "permissions_authorized": list(self.permissions_authorized), + "valid_from": self.valid_from, + "valid_until": self.valid_until, + "max_uses": self.max_uses, + "lease_action_authority": self.lease_action_authority, + "effect_performed": self.effect_performed, + "execution_authority": self.execution_authority, + } + + +@dataclass(frozen=True, slots=True) +class GhostWalkAuthorizationConsoleSnapshot: + target_inference_receipt_sha256: str + authorization_readiness: GhostWalkAuthorizationReadiness + authorization_decision: GhostWalkAuthorizationDecision | None + binding_available: bool + binding_readiness: GhostWalkBindingReadiness | None + binding: GhostWalkExecutableBindingSummary | None + lease_available: bool + lease_readiness: GhostWalkLeaseReadiness | None + lease: GhostWalkActionLeaseSummary | None + effect_performed: bool = False + policy_authority: bool = False + operational_authority: bool = False + action_authority: bool = False + execution_authority: bool = False + schema_version: str = GHOSTWALK_AUTHORIZATION_CONSOLE_SCHEMA_VERSION + + def __post_init__(self) -> None: + _require_sha256( + self.target_inference_receipt_sha256, + "target_inference_receipt_sha256", + ) + if self.target_inference_receipt_sha256 != ( + self.authorization_readiness.target_inference_receipt_sha256 + ): + raise GhostWalkAuthorizationConsoleError( + "authorization readiness target differs from console target" + ) + if self.authorization_decision is not None and ( + self.authorization_decision.target_inference_receipt_sha256 + != self.target_inference_receipt_sha256 + ): + raise GhostWalkAuthorizationConsoleError( + "authorization decision target differs from console target" + ) + if self.binding_available is not ( + self.binding_readiness is not None + ): + raise GhostWalkAuthorizationConsoleError( + "binding availability differs from readiness presence" + ) + if self.lease_available is not ( + self.lease_readiness is not None + ): + raise GhostWalkAuthorizationConsoleError( + "lease availability differs from readiness presence" + ) + if any( + ( + self.effect_performed, + self.policy_authority, + self.operational_authority, + self.action_authority, + self.execution_authority, + ) + ): + raise GhostWalkAuthorizationConsoleError( + "authorization console snapshot cannot carry effects or authority" + ) + + def body_dict(self) -> dict[str, object]: + return { + "schema_version": self.schema_version, + "target_inference_receipt_sha256": ( + self.target_inference_receipt_sha256 + ), + "authorization_readiness": ( + self.authorization_readiness.to_dict() + ), + "authorization_decision": ( + None + if self.authorization_decision is None + else self.authorization_decision.to_dict() + ), + "binding_available": self.binding_available, + "binding_readiness": ( + None + if self.binding_readiness is None + else self.binding_readiness.to_dict() + ), + "binding": ( + None if self.binding is None else self.binding.to_dict() + ), + "lease_available": self.lease_available, + "lease_readiness": ( + None + if self.lease_readiness is None + else self.lease_readiness.to_dict() + ), + "lease": None if self.lease is None else self.lease.to_dict(), + "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 snapshot_sha256(self) -> str: + return _canonical_sha256(self.body_dict()) + + def to_dict(self) -> dict[str, object]: + payload = self.body_dict() + payload["snapshot_sha256"] = self.snapshot_sha256 + return payload + + +class AuthorizationDecisionPort(Protocol): + def readiness( + self, + *, + target_inference_receipt_sha256: str, + ) -> GhostWalkAuthorizationReadiness: ... + + def latest( + self, + *, + target_inference_receipt_sha256: str, + ) -> GhostWalkAuthorizationDecision | None: ... + + def record( + self, + *, + target_inference_receipt_sha256: str, + expected_authority_request_sha256: str, + expected_previous_decision_sha256: str | None, + decision: GhostWalkAuthorizationDecisionKind, + decision_note: str | None = None, + decided_at: str | None = None, + ) -> GhostWalkAuthorizationDecision: ... + + +class CapabilityBindingPort(Protocol): + def readiness( + self, + *, + target_inference_receipt_sha256: str, + ) -> GhostWalkBindingReadiness: ... + + def latest( + self, + *, + target_inference_receipt_sha256: str, + ) -> GhostWalkExecutableBinding | None: ... + + def create( + self, + *, + target_inference_receipt_sha256: str, + expected_authorization_decision_sha256: str, + expected_mapping_sha256: str, + expected_mapping_set_sha256: str, + bound_at: str, + ) -> GhostWalkExecutableBinding: ... + + +class ActionLeasePort(Protocol): + def readiness( + self, + *, + target_inference_receipt_sha256: str, + ) -> GhostWalkLeaseReadiness: ... + + def latest( + self, + *, + target_inference_receipt_sha256: str, + ) -> GhostWalkActionLeaseRecord | None: ... + + def issue( + self, + *, + target_inference_receipt_sha256: str, + expected_executable_binding_sha256: str, + expected_policy_sha256: str, + expected_policy_set_sha256: str, + expected_enforcement_profile_sha256: str, + expected_authority_epoch_sha256: str, + ) -> GhostWalkActionLeaseRecord: ... + + +class GhostWalkAuthorizationConsoleService: + """Human-facing façade over v0.32-v0.34 governed services.""" + + def __init__( + self, + *, + authorization_decisions: AuthorizationDecisionPort, + capability_bindings: CapabilityBindingPort | None = None, + action_leases: ActionLeasePort | None = None, + ) -> None: + self._authorization_decisions = authorization_decisions + self._capability_bindings = capability_bindings + self._action_leases = action_leases + + def snapshot( + self, + *, + target_inference_receipt_sha256: str, + ) -> GhostWalkAuthorizationConsoleSnapshot: + target = _require_sha256( + target_inference_receipt_sha256, + "target_inference_receipt_sha256", + ) + try: + auth_readiness = self._authorization_decisions.readiness( + target_inference_receipt_sha256=target + ) + decision = self._authorization_decisions.latest( + target_inference_receipt_sha256=target + ) + except GhostWalkAuthorizationDecisionError as exc: + raise GhostWalkAuthorizationConsoleError(str(exc)) from exc + + binding_readiness: GhostWalkBindingReadiness | None = None + binding_summary: GhostWalkExecutableBindingSummary | None = None + if self._capability_bindings is not None: + try: + binding_readiness = self._capability_bindings.readiness( + target_inference_receipt_sha256=target + ) + binding = self._capability_bindings.latest( + target_inference_receipt_sha256=target + ) + except GhostWalkCapabilityBindingError as exc: + raise GhostWalkAuthorizationConsoleError(str(exc)) from exc + if binding is not None: + binding_summary = ( + GhostWalkExecutableBindingSummary.from_binding(binding) + ) + + lease_readiness: GhostWalkLeaseReadiness | None = None + lease_summary: GhostWalkActionLeaseSummary | None = None + if self._action_leases is not None: + try: + lease_readiness = self._action_leases.readiness( + target_inference_receipt_sha256=target + ) + lease = self._action_leases.latest( + target_inference_receipt_sha256=target + ) + except GhostWalkActionLeaseError as exc: + raise GhostWalkAuthorizationConsoleError(str(exc)) from exc + if lease is not None: + lease_summary = GhostWalkActionLeaseSummary.from_record(lease) + + return GhostWalkAuthorizationConsoleSnapshot( + target_inference_receipt_sha256=target, + authorization_readiness=auth_readiness, + authorization_decision=decision, + binding_available=binding_readiness is not None, + binding_readiness=binding_readiness, + binding=binding_summary, + lease_available=lease_readiness is not None, + lease_readiness=lease_readiness, + lease=lease_summary, + ) + + def record_decision( + self, + *, + target_inference_receipt_sha256: str, + expected_authority_request_sha256: str, + expected_previous_decision_sha256: str | None, + decision: GhostWalkAuthorizationDecisionKind, + decision_note: str | None, + ) -> GhostWalkAuthorizationDecision: + try: + return self._authorization_decisions.record( + target_inference_receipt_sha256=( + target_inference_receipt_sha256 + ), + expected_authority_request_sha256=( + expected_authority_request_sha256 + ), + expected_previous_decision_sha256=( + expected_previous_decision_sha256 + ), + decision=decision, + decision_note=decision_note, + ) + except GhostWalkAuthorizationDecisionError as exc: + raise GhostWalkAuthorizationConsoleError(str(exc)) from exc + + def create_binding( + self, + *, + target_inference_receipt_sha256: str, + expected_authorization_decision_sha256: str, + expected_mapping_sha256: str, + expected_mapping_set_sha256: str, + bound_at: str, + ) -> GhostWalkExecutableBindingSummary: + if self._capability_bindings is None: + raise GhostWalkAuthorizationConsoleError( + "trusted capability binding service is not mounted" + ) + try: + binding = self._capability_bindings.create( + target_inference_receipt_sha256=( + target_inference_receipt_sha256 + ), + expected_authorization_decision_sha256=( + expected_authorization_decision_sha256 + ), + expected_mapping_sha256=expected_mapping_sha256, + expected_mapping_set_sha256=expected_mapping_set_sha256, + bound_at=bound_at, + ) + except GhostWalkCapabilityBindingError as exc: + raise GhostWalkAuthorizationConsoleError(str(exc)) from exc + return GhostWalkExecutableBindingSummary.from_binding(binding) + + def issue_lease( + self, + *, + target_inference_receipt_sha256: str, + expected_executable_binding_sha256: str, + expected_policy_sha256: str, + expected_policy_set_sha256: str, + expected_enforcement_profile_sha256: str, + expected_authority_epoch_sha256: str, + ) -> GhostWalkActionLeaseSummary: + if self._action_leases is None: + raise GhostWalkAuthorizationConsoleError( + "trusted ActionLease service is not mounted" + ) + try: + record = self._action_leases.issue( + target_inference_receipt_sha256=( + target_inference_receipt_sha256 + ), + expected_executable_binding_sha256=( + expected_executable_binding_sha256 + ), + expected_policy_sha256=expected_policy_sha256, + expected_policy_set_sha256=expected_policy_set_sha256, + expected_enforcement_profile_sha256=( + expected_enforcement_profile_sha256 + ), + expected_authority_epoch_sha256=( + expected_authority_epoch_sha256 + ), + ) + except GhostWalkActionLeaseError as exc: + raise GhostWalkAuthorizationConsoleError(str(exc)) from exc + return GhostWalkActionLeaseSummary.from_record(record) + + +__all__ = [ + "GhostWalkActionLeaseSummary", + "GhostWalkAuthorizationConsoleError", + "GhostWalkAuthorizationConsoleService", + "GhostWalkAuthorizationConsoleSnapshot", + "GhostWalkExecutableBindingSummary", +] diff --git a/phios/macro_ghostwalk_control_server.py b/phios/macro_ghostwalk_control_server.py index e4d5e385..2552395b 100644 --- a/phios/macro_ghostwalk_control_server.py +++ b/phios/macro_ghostwalk_control_server.py @@ -25,6 +25,14 @@ GhostWalkAuthorityRequestReadiness, GhostWalkAuthorityRequestService, ) +from phios.macro_authorization_decision import ( + GhostWalkAuthorizationDecisionKind, + GhostWalkAuthorizationDecisionService, +) +from phios.macro_authorization_console import ( + GhostWalkAuthorizationConsoleError, + GhostWalkAuthorizationConsoleService, +) from phios.macro_accepted_intent import ( GhostWalkAcceptedIntentError, GhostWalkAcceptedIntentRegistry, @@ -87,6 +95,12 @@ "phios.ghostwalk-authority-request-transport.v0.31" ) AUTHORITY_REQUEST_TRANSPORT_IDENTITY = "phios-ghostwalk-authority-request" +AUTHORIZATION_CONSOLE_TRANSPORT_SCHEMA_VERSION = ( + "phios.ghostwalk-authorization-console-transport.v0.36" +) +AUTHORIZATION_CONSOLE_TRANSPORT_IDENTITY = ( + "phios-ghostwalk-authorization-console" +) PHIVESSEL_BRIDGE_TRANSPORT_SCHEMA_VERSION = ( "phios.phivessel-bridge-transport.v0.1" ) @@ -732,6 +746,302 @@ def parse_authority_request_create_payload( return target, admission +def _authorization_console_transport_base( + *, + mutation_kind: str = "NONE", +) -> dict[str, object]: + if mutation_kind not in {"NONE", "DECISION", "BINDING", "LEASE"}: + raise GhostWalkControlBridgeError( + "authorization-console mutation kind is invalid" + ) + mutated = mutation_kind != "NONE" + return { + "transportSchemaVersion": ( + AUTHORIZATION_CONSOLE_TRANSPORT_SCHEMA_VERSION + ), + "transport": "loopback-http", + "transportIdentity": ( + AUTHORIZATION_CONSOLE_TRANSPORT_IDENTITY + ), + "localOnly": True, + "humanAuthorizationSurface": True, + "mutationKind": mutation_kind, + "decisionRecorded": mutation_kind == "DECISION", + "bindingCreated": mutation_kind == "BINDING", + "actionLeaseCreated": mutation_kind == "LEASE", + "desktopEffectPerformed": False, + "policyAuthority": False, + "operationalAuthority": False, + "actionAuthority": False, + "executionAuthority": False, + "effectPerformed": mutated, + } + + +def authorization_console_status_envelope( + service: GhostWalkAuthorizationConsoleService, + *, + target_inference_receipt_sha256: str, +) -> dict[str, object]: + snapshot = service.snapshot( + target_inference_receipt_sha256=( + target_inference_receipt_sha256 + ) + ) + payload = _authorization_console_transport_base() + payload.update( + { + "servedAt": _utc_now(), + "snapshot": snapshot.to_dict(), + } + ) + return payload + + +def authorization_console_decision_envelope( + service: GhostWalkAuthorizationConsoleService, + *, + target_inference_receipt_sha256: str, + expected_authority_request_sha256: str, + expected_previous_decision_sha256: str | None, + decision: GhostWalkAuthorizationDecisionKind, + decision_note: str | None, +) -> dict[str, object]: + item = service.record_decision( + target_inference_receipt_sha256=( + target_inference_receipt_sha256 + ), + expected_authority_request_sha256=( + expected_authority_request_sha256 + ), + expected_previous_decision_sha256=( + expected_previous_decision_sha256 + ), + decision=decision, + decision_note=decision_note, + ) + snapshot = service.snapshot( + target_inference_receipt_sha256=( + target_inference_receipt_sha256 + ) + ) + payload = _authorization_console_transport_base( + mutation_kind="DECISION" + ) + payload.update( + { + "servedAt": _utc_now(), + "decision": item.to_dict(), + "snapshot": snapshot.to_dict(), + } + ) + return payload + + +def authorization_console_binding_envelope( + service: GhostWalkAuthorizationConsoleService, + *, + target_inference_receipt_sha256: str, + expected_authorization_decision_sha256: str, + expected_mapping_sha256: str, + expected_mapping_set_sha256: str, +) -> dict[str, object]: + binding = service.create_binding( + target_inference_receipt_sha256=( + target_inference_receipt_sha256 + ), + expected_authorization_decision_sha256=( + expected_authorization_decision_sha256 + ), + expected_mapping_sha256=expected_mapping_sha256, + expected_mapping_set_sha256=expected_mapping_set_sha256, + bound_at=_utc_now(), + ) + snapshot = service.snapshot( + target_inference_receipt_sha256=( + target_inference_receipt_sha256 + ) + ) + payload = _authorization_console_transport_base( + mutation_kind="BINDING" + ) + payload.update( + { + "servedAt": _utc_now(), + "binding": binding.to_dict(), + "snapshot": snapshot.to_dict(), + } + ) + return payload + + +def authorization_console_lease_envelope( + service: GhostWalkAuthorizationConsoleService, + *, + target_inference_receipt_sha256: str, + expected_executable_binding_sha256: str, + expected_policy_sha256: str, + expected_policy_set_sha256: str, + expected_enforcement_profile_sha256: str, + expected_authority_epoch_sha256: str, +) -> dict[str, object]: + lease = service.issue_lease( + target_inference_receipt_sha256=( + target_inference_receipt_sha256 + ), + expected_executable_binding_sha256=( + expected_executable_binding_sha256 + ), + expected_policy_sha256=expected_policy_sha256, + expected_policy_set_sha256=expected_policy_set_sha256, + expected_enforcement_profile_sha256=( + expected_enforcement_profile_sha256 + ), + expected_authority_epoch_sha256=( + expected_authority_epoch_sha256 + ), + ) + snapshot = service.snapshot( + target_inference_receipt_sha256=( + target_inference_receipt_sha256 + ) + ) + payload = _authorization_console_transport_base( + mutation_kind="LEASE" + ) + payload.update( + { + "servedAt": _utc_now(), + "lease": lease.to_dict(), + "snapshot": snapshot.to_dict(), + } + ) + return payload + + +def _console_sha(value: object, field: str) -> str: + 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" + ) + return value + + +def parse_authorization_console_decision_payload( + payload: object, +) -> tuple[ + str, + str, + str | None, + GhostWalkAuthorizationDecisionKind, + str | None, +]: + if not isinstance(payload, Mapping): + raise GhostWalkControlBridgeError( + "authorization decision body must be an object" + ) + expected_keys = { + "target_inference_receipt_sha256", + "expected_authority_request_sha256", + "expected_previous_decision_sha256", + "decision", + "decision_note", + } + if set(payload) != expected_keys: + raise GhostWalkControlBridgeError( + "authorization decision fields do not match contract" + ) + target = _console_sha( + payload.get("target_inference_receipt_sha256"), + "target inference receipt", + ) + request = _console_sha( + payload.get("expected_authority_request_sha256"), + "expected AuthorityRequest", + ) + previous_raw = payload.get("expected_previous_decision_sha256") + previous = ( + None + if previous_raw is None + else _console_sha( + previous_raw, + "expected previous AuthorizationDecision", + ) + ) + raw_decision = payload.get("decision") + if not isinstance(raw_decision, str): + raise GhostWalkControlBridgeError( + "authorization decision must be a string" + ) + try: + decision = GhostWalkAuthorizationDecisionKind(raw_decision) + except ValueError as exc: + raise GhostWalkControlBridgeError( + "authorization decision is unsupported" + ) from exc + note = payload.get("decision_note") + if note is not None and ( + not isinstance(note, str) + or len(note) > 2048 + or "\x00" in note + ): + raise GhostWalkControlBridgeError( + "authorization decision note is invalid" + ) + return target, request, previous, decision, note + + +def parse_authorization_console_binding_payload( + payload: object, +) -> tuple[str, str, str, str]: + if not isinstance(payload, Mapping): + raise GhostWalkControlBridgeError( + "capability binding body must be an object" + ) + keys = ( + "target_inference_receipt_sha256", + "expected_authorization_decision_sha256", + "expected_mapping_sha256", + "expected_mapping_set_sha256", + ) + if set(payload) != set(keys): + raise GhostWalkControlBridgeError( + "capability binding fields do not match contract" + ) + return tuple( + _console_sha(payload.get(key), key) + for key in keys + ) # type: ignore[return-value] + + +def parse_authorization_console_lease_payload( + payload: object, +) -> tuple[str, str, str, str, str, str]: + if not isinstance(payload, Mapping): + raise GhostWalkControlBridgeError( + "ActionLease issuance body must be an object" + ) + keys = ( + "target_inference_receipt_sha256", + "expected_executable_binding_sha256", + "expected_policy_sha256", + "expected_policy_set_sha256", + "expected_enforcement_profile_sha256", + "expected_authority_epoch_sha256", + ) + if set(payload) != set(keys): + raise GhostWalkControlBridgeError( + "ActionLease issuance fields do not match contract" + ) + return tuple( + _console_sha(payload.get(key), key) + for key in keys + ) # type: ignore[return-value] + + def _phivessel_transport_base( *, bridge_mutation: bool = False, @@ -1098,6 +1408,15 @@ def _authority_request_error( body.update({"error": code, "servedAt": _utc_now()}) self._json(status, body) + def _authorization_console_error( + self, + status: HTTPStatus, + code: str, + ) -> None: + body = _authorization_console_transport_base() + body.update({"error": code, "servedAt": _utc_now()}) + self._json(status, body) + def _phivessel_error( self, status: HTTPStatus, @@ -1142,6 +1461,48 @@ def _read_json( def do_GET(self) -> None: parsed = urlsplit(self.path) + if parsed.path == "/api/v1/ghostwalk/authorization-console": + if self.server.authorization_console is None: + self._authorization_console_error( + HTTPStatus.SERVICE_UNAVAILABLE, + "ghostwalk_authorization_console_unavailable", + ) + return + try: + query = parse_qs( + parsed.query, + keep_blank_values=True, + strict_parsing=True, + ) + except ValueError: + query = {} + targets = query.get("target") + if ( + parsed.fragment + or set(query) != {"target"} + or targets is None + or len(targets) != 1 + or re.fullmatch(r"[0-9a-f]{64}", targets[0]) is None + ): + self._authorization_console_error( + HTTPStatus.BAD_REQUEST, + "invalid_ghostwalk_authorization_console_request", + ) + return + try: + envelope = authorization_console_status_envelope( + self.server.authorization_console, + target_inference_receipt_sha256=targets[0], + ) + except GhostWalkAuthorizationConsoleError: + self._authorization_console_error( + HTTPStatus.BAD_REQUEST, + "ghostwalk_authorization_console_rejected", + ) + return + self._json(HTTPStatus.OK, envelope) + return + if parsed.path == "/api/v1/phivessel/observe": if self.server.phivessel_bridge is None: self._phivessel_error( @@ -1394,6 +1755,219 @@ def do_GET(self) -> None: def do_POST(self) -> None: parsed = urlsplit(self.path) + if parsed.path == ( + "/api/v1/ghostwalk/authorization-console/decisions" + ): + if parsed.query or parsed.fragment: + self._authorization_console_error( + HTTPStatus.BAD_REQUEST, + "invalid_ghostwalk_authorization_decision_request", + ) + return + if self.server.authorization_console is None: + self._authorization_console_error( + HTTPStatus.SERVICE_UNAVAILABLE, + "ghostwalk_authorization_console_unavailable", + ) + return + try: + ( + target, + request_sha, + previous_sha, + decision, + note, + ) = parse_authorization_console_decision_payload( + self._read_json(max_bytes=8192) + ) + envelope = authorization_console_decision_envelope( + self.server.authorization_console, + target_inference_receipt_sha256=target, + expected_authority_request_sha256=request_sha, + expected_previous_decision_sha256=previous_sha, + decision=decision, + decision_note=note, + ) + except GhostWalkControlBridgeError: + self._authorization_console_error( + HTTPStatus.BAD_REQUEST, + "invalid_ghostwalk_authorization_decision_request", + ) + return + except GhostWalkAuthorizationConsoleError as exc: + message = str(exc) + unavailable = "not mounted" in message + conflict = any( + token in message + for token in ( + "changed before", + "not ready", + "already", + "stale", + ) + ) + self._authorization_console_error( + ( + HTTPStatus.SERVICE_UNAVAILABLE + if unavailable + else HTTPStatus.CONFLICT + if conflict + else HTTPStatus.BAD_REQUEST + ), + ( + "ghostwalk_authorization_console_unavailable" + if unavailable + else "ghostwalk_authorization_decision_conflict" + if conflict + else "ghostwalk_authorization_decision_rejected" + ), + ) + return + self._json(HTTPStatus.OK, envelope) + return + + if parsed.path == ( + "/api/v1/ghostwalk/authorization-console/bindings" + ): + if parsed.query or parsed.fragment: + self._authorization_console_error( + HTTPStatus.BAD_REQUEST, + "invalid_ghostwalk_binding_request", + ) + return + if self.server.authorization_console is None: + self._authorization_console_error( + HTTPStatus.SERVICE_UNAVAILABLE, + "ghostwalk_authorization_console_unavailable", + ) + return + try: + ( + target, + decision_sha, + mapping_sha, + mapping_set_sha, + ) = parse_authorization_console_binding_payload( + self._read_json() + ) + envelope = authorization_console_binding_envelope( + self.server.authorization_console, + target_inference_receipt_sha256=target, + expected_authorization_decision_sha256=decision_sha, + expected_mapping_sha256=mapping_sha, + expected_mapping_set_sha256=mapping_set_sha, + ) + except GhostWalkControlBridgeError: + self._authorization_console_error( + HTTPStatus.BAD_REQUEST, + "invalid_ghostwalk_binding_request", + ) + return + except GhostWalkAuthorizationConsoleError as exc: + message = str(exc) + unavailable = "not mounted" in message + conflict = any( + token in message + for token in ( + "changed before", + "not ready", + "already", + "stale", + ) + ) + self._authorization_console_error( + ( + HTTPStatus.SERVICE_UNAVAILABLE + if unavailable + else HTTPStatus.CONFLICT + if conflict + else HTTPStatus.BAD_REQUEST + ), + ( + "ghostwalk_authorization_console_unavailable" + if unavailable + else "ghostwalk_binding_conflict" + if conflict + else "ghostwalk_binding_rejected" + ), + ) + return + self._json(HTTPStatus.OK, envelope) + return + + if parsed.path == ( + "/api/v1/ghostwalk/authorization-console/leases" + ): + if parsed.query or parsed.fragment: + self._authorization_console_error( + HTTPStatus.BAD_REQUEST, + "invalid_ghostwalk_lease_request", + ) + return + if self.server.authorization_console is None: + self._authorization_console_error( + HTTPStatus.SERVICE_UNAVAILABLE, + "ghostwalk_authorization_console_unavailable", + ) + return + try: + ( + target, + binding_sha, + policy_sha, + policy_set_sha, + profile_sha, + epoch_sha, + ) = parse_authorization_console_lease_payload( + self._read_json() + ) + envelope = authorization_console_lease_envelope( + self.server.authorization_console, + target_inference_receipt_sha256=target, + expected_executable_binding_sha256=binding_sha, + expected_policy_sha256=policy_sha, + expected_policy_set_sha256=policy_set_sha, + expected_enforcement_profile_sha256=profile_sha, + expected_authority_epoch_sha256=epoch_sha, + ) + except GhostWalkControlBridgeError: + self._authorization_console_error( + HTTPStatus.BAD_REQUEST, + "invalid_ghostwalk_lease_request", + ) + return + except GhostWalkAuthorizationConsoleError as exc: + message = str(exc) + unavailable = "not mounted" in message + conflict = any( + token in message + for token in ( + "changed before", + "not ready", + "already", + "stale", + ) + ) + self._authorization_console_error( + ( + HTTPStatus.SERVICE_UNAVAILABLE + if unavailable + else HTTPStatus.CONFLICT + if conflict + else HTTPStatus.BAD_REQUEST + ), + ( + "ghostwalk_authorization_console_unavailable" + if unavailable + else "ghostwalk_lease_conflict" + if conflict + else "ghostwalk_lease_rejected" + ), + ) + return + self._json(HTTPStatus.OK, envelope) + return + if parsed.path == "/api/v1/phivessel/proposals": if parsed.query or parsed.fragment: self._phivessel_error( @@ -1736,6 +2310,9 @@ def __init__( accepted_intents: GhostWalkAcceptedIntentPort | None = None, policy_admission: GhostWalkPolicyAdmissionPort | None = None, authority_requests: GhostWalkAuthorityRequestPort | None = None, + authorization_console: ( + GhostWalkAuthorizationConsoleService | None + ) = None, phivessel_bridge: PhiVesselBridgeService | None = None, stop_callback: Callable[[], object] | None = None, ) -> None: @@ -1748,6 +2325,7 @@ def __init__( self.accepted_intents = accepted_intents self.policy_admission = policy_admission self.authority_requests = authority_requests + self.authorization_console = authorization_console self.phivessel_bridge = phivessel_bridge self._stop_callback = stop_callback super().__init__(address, GhostWalkControlHandler) @@ -1871,6 +2449,11 @@ def main() -> None: / "ledger" / "receipts.jsonl" ) + authorization_decisions = GhostWalkAuthorizationDecisionService( + ledger=shared_ledger, + authority_requests=authority_requests, + authorizer_id=DEFAULT_OPERATOR_AUTHOR_ID, + ) manifest_path = execution_manifest_path( state_root=args.state_root, environ=os.environ, @@ -1882,6 +2465,7 @@ def main() -> None: authority_requests=authority_requests, authorizer_id=DEFAULT_OPERATOR_AUTHOR_ID, manifest_path=manifest_path, + authorization_decisions=authorization_decisions, ) except PhiVesselLocalExecutionError as exc: execution_mount = None @@ -1891,6 +2475,19 @@ def main() -> None: file=sys.stderr, ) + authorization_console = GhostWalkAuthorizationConsoleService( + authorization_decisions=authorization_decisions, + capability_bindings=( + None + if execution_mount is None + else execution_mount.capability_bindings + ), + action_leases=( + None + if execution_mount is None + else execution_mount.action_leases + ), + ) phivessel_bridge = PhiVesselBridgeService( ledger=shared_ledger, ghostwalk_surface=surface, @@ -1907,6 +2504,7 @@ def main() -> None: accepted_intents=accepted_intents, policy_admission=policy_admission, authority_requests=authority_requests, + authorization_console=authorization_console, phivessel_bridge=phivessel_bridge, stop_callback=host.stop, ) diff --git a/phios/phivessel_local_execution.py b/phios/phivessel_local_execution.py index 554df4a9..f2c83488 100644 --- a/phios/phivessel_local_execution.py +++ b/phios/phivessel_local_execution.py @@ -569,6 +569,9 @@ def build_local_execution_mount( authority_requests: GhostWalkAuthorityRequestService, authorizer_id: str, manifest_path: Path, + authorization_decisions: ( + GhostWalkAuthorizationDecisionService | None + ) = None, desktop_executor_factory: ( Callable[[PhiOSSpine], GovernedDesktopClickExecutor] | None ) = None, @@ -601,10 +604,14 @@ def build_local_execution_mount( ), ) - authorization_decisions = GhostWalkAuthorizationDecisionService( - ledger=ledger, - authority_requests=authority_requests, - authorizer_id=authorizer_id, + authorization_decisions = ( + authorization_decisions + if authorization_decisions is not None + else GhostWalkAuthorizationDecisionService( + ledger=ledger, + authority_requests=authority_requests, + authorizer_id=authorizer_id, + ) ) capability_bindings = GhostWalkCapabilityBindingService( ledger=ledger, diff --git a/phishell/host/ghostWalkAuthorizationConsoleLocalTransport.test.mjs b/phishell/host/ghostWalkAuthorizationConsoleLocalTransport.test.mjs new file mode 100644 index 00000000..ea9e81f8 --- /dev/null +++ b/phishell/host/ghostWalkAuthorizationConsoleLocalTransport.test.mjs @@ -0,0 +1,75 @@ +import test from "node:test"; +import assert from "node:assert/strict"; + +import { createLocalObservationServer } from "./localTransport.mjs"; + +const SHA = (char) => char.repeat(64); + +test("local transport forwards human decision without widening it", async () => { + const seen = []; + const transport = createLocalObservationServer({ + port: 0, + serveShell: false, + ghostWalkAuthorizationDecisionRecorder: async (payload) => { + seen.push(payload); + return { kind: "conflict" }; + }, + }); + const address = await transport.listen(); + try { + const body = { + target_inference_receipt_sha256: SHA("a"), + expected_authority_request_sha256: SHA("b"), + expected_previous_decision_sha256: null, + decision: "APPROVE", + decision_note: "human approval", + }; + const response = await fetch( + `http://${address.host}:${address.port}/api/v1/ghostwalk/authorization-console/decisions`, + { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify(body), + }, + ); + assert.equal(response.status, 409); + assert.deepEqual(seen, [body]); + } finally { + await transport.close(); + } +}); + +test("local transport rejects browser-supplied lease duration", async () => { + const seen = []; + const transport = createLocalObservationServer({ + port: 0, + serveShell: false, + ghostWalkActionLeaseIssuer: async (payload) => { + seen.push(payload); + return { kind: "conflict" }; + }, + }); + const address = await transport.listen(); + try { + const response = await fetch( + `http://${address.host}:${address.port}/api/v1/ghostwalk/authorization-console/leases`, + { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ + target_inference_receipt_sha256: SHA("a"), + expected_executable_binding_sha256: SHA("b"), + expected_policy_sha256: SHA("c"), + expected_policy_set_sha256: SHA("d"), + expected_enforcement_profile_sha256: SHA("e"), + expected_authority_epoch_sha256: SHA("f"), + lease_seconds: 300, + }), + }, + ); + assert.equal(response.status, 400); + assert.deepEqual(seen, []); + } finally { + await transport.close(); + } +}); diff --git a/phishell/host/ghostWalkAuthorizationConsoleProxy.mjs b/phishell/host/ghostWalkAuthorizationConsoleProxy.mjs new file mode 100644 index 00000000..d22b3b04 --- /dev/null +++ b/phishell/host/ghostWalkAuthorizationConsoleProxy.mjs @@ -0,0 +1,533 @@ +import { + GHOSTWALK_HOST, + ghostWalkSidecarPort, +} from "./ghostWalkControlProxy.mjs"; + +const SHA256 = /^[0-9a-f]{64}$/; +const INTENT_CODE = /^[A-Z][A-Z0-9_]{2,127}$/; + +function record(value) { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +function sha(value) { + return typeof value === "string" && SHA256.test(value); +} + +function nullableSha(value) { + return value === null || sha(value); +} + +function timestamp(value) { + return ( + typeof value === "string" && + value.length <= 64 && + !Number.isNaN(Date.parse(value)) + ); +} + +function text(value, maximum = 512) { + return ( + typeof value === "string" && + value.length > 0 && + value.length <= maximum + ); +} + +function stringArray(value) { + return ( + Array.isArray(value) && + value.every((item) => text(item, 256)) && + new Set(value).size === value.length + ); +} + +function exactKeys(value, expected) { + if (!record(value)) return false; + const actual = Object.keys(value).sort(); + const wanted = [...expected].sort(); + return ( + actual.length === wanted.length && + actual.every((key, index) => key === wanted[index]) + ); +} + +function zeroSnakeAuthority(value) { + return ( + record(value) && + value.policy_authority === false && + value.operational_authority === false && + value.action_authority === false && + value.execution_authority === false + ); +} + +function validateAuthorizationReadiness(value) { + if (!zeroSnakeAuthority(value)) return false; + const reasons = [ + "READY", + "AUTHORITY_REQUEST_REQUIRED", + "AUTHORITY_REQUEST_STALE", + "DECISION_FINAL", + ]; + return ( + value.schema_version === + "phios.ghostwalk_authorization_readiness.v0.32" && + sha(value.target_inference_receipt_sha256) && + nullableSha(value.authority_request_sha256) && + nullableSha(value.latest_decision_sha256) && + ( + value.latest_decision === null || + ["APPROVE", "DENY", "HOLD"].includes(value.latest_decision) + ) && + typeof value.ready === "boolean" && + reasons.includes(value.reason) && + value.ready === (value.reason === "READY") && + typeof value.authorization_granted === "boolean" && + value.authorization_granted === + (value.latest_decision === "APPROVE") && + value.capability_binding_created === false && + value.action_lease_created === false && + value.effect_performed === false && + sha(value.readiness_sha256) + ); +} + +export function validateGhostWalkAuthorizationDecision(value) { + if (!zeroSnakeAuthority(value)) return false; + if ( + value.schema_version !== + "phios.ghostwalk_authorization_decision.v0.32" || + !sha(value.authority_request_sha256) || + !sha(value.target_inference_receipt_sha256) || + !sha(value.admission_receipt_sha256) || + !sha(value.accepted_intent_revision_sha256) || + !sha(value.policy_profile_sha256) || + !INTENT_CODE.test(value.intent_code) || + !text(value.authorizer_id) || + !["APPROVE", "DENY", "HOLD"].includes(value.decision) || + !Number.isInteger(value.decision_sequence) || + value.decision_sequence < 0 || + !nullableSha(value.previous_decision_sha256) || + !timestamp(value.decided_at) || + !( + value.decision_note === null || + ( + typeof value.decision_note === "string" && + value.decision_note.length <= 2048 + ) + ) || + typeof value.authorization_granted !== "boolean" || + typeof value.request_resolved !== "boolean" || + value.capability_binding_created !== false || + value.action_lease_created !== false || + value.effect_performed !== false || + !sha(value.authorization_decision_sha256) + ) { + return false; + } + if ( + value.authorization_granted !== (value.decision === "APPROVE") || + value.request_resolved !== + (value.decision === "APPROVE" || value.decision === "DENY") + ) { + return false; + } + return ( + (value.decision_sequence === 0) === + (value.previous_decision_sha256 === null) + ); +} + +function validateBindingReadiness(value) { + if (!zeroSnakeAuthority(value)) return false; + const reasons = [ + "READY", + "AUTHORIZATION_DECISION_REQUIRED", + "AUTHORIZATION_NOT_APPROVED", + "AUTHORIZATION_STALE", + "NO_MAPPING", + "AMBIGUOUS_MAPPING", + "ACTION_EVIDENCE_MISSING", + "MAPPING_CONSTRAINT_MISMATCH", + "BINDING_ALREADY_EXISTS", + ]; + return ( + value.schema_version === + "phios.ghostwalk_binding_readiness.v0.33" && + sha(value.target_inference_receipt_sha256) && + nullableSha(value.authorization_decision_sha256) && + sha(value.mapping_set_sha256) && + nullableSha(value.selected_mapping_sha256) && + nullableSha(value.action_observation_sha256) && + nullableSha(value.existing_binding_sha256) && + typeof value.ready === "boolean" && + reasons.includes(value.reason) && + value.ready === (value.reason === "READY") && + value.effect_performed === false && + sha(value.readiness_sha256) + ); +} + +export function validateGhostWalkBindingSummary(value) { + return ( + record(value) && + value.schema_version === + "phios.ghostwalk_executable_binding_summary.v0.36" && + sha(value.executable_binding_sha256) && + sha(value.authorization_decision_sha256) && + INTENT_CODE.test(value.intent_code) && + text(value.mapping_id, 128) && + text(value.capability_id, 256) && + text(value.capability_version, 128) && + sha(value.payload_sha256) && + stringArray(value.permissions_required) && + stringArray(value.effects_declared) && + timestamp(value.bound_at) && + value.effect_performed === false && + value.action_authority === false && + value.execution_authority === false + ); +} + +function validateLeaseReadiness(value) { + if (!record(value)) return false; + const reasons = [ + "READY", + "EXECUTABLE_BINDING_REQUIRED", + "EXECUTABLE_BINDING_STALE", + "LEASE_POLICY_MISSING", + "ENFORCEMENT_PROFILE_INCOMPLETE", + "UNENFORCED_EFFECT_ACK_REQUIRED", + "AUTHORITY_EPOCH_UNAVAILABLE", + "AUTHORITY_EPOCH_STALE", + "AUTHORITY_PRINCIPAL_MISMATCH", + "AUTHORITY_PERMISSION_MISSING", + "LEASE_ALREADY_EXISTS", + ]; + return ( + value.schema_version === + "phios.ghostwalk_lease_readiness.v0.34" && + sha(value.target_inference_receipt_sha256) && + nullableSha(value.executable_binding_sha256) && + nullableSha(value.policy_sha256) && + sha(value.policy_set_sha256) && + nullableSha(value.enforcement_profile_sha256) && + nullableSha(value.authority_epoch_sha256) && + stringArray(value.required_permissions) && + stringArray(value.missing_permissions) && + stringArray(value.unenforced_effects) && + stringArray(value.accepted_unenforced_effects) && + nullableSha(value.existing_action_lease_sha256) && + typeof value.ready === "boolean" && + reasons.includes(value.reason) && + value.ready === (value.reason === "READY") && + value.effect_performed === false && + value.operational_authority === false && + value.action_authority === false && + value.execution_authority === false && + sha(value.readiness_sha256) + ); +} + +export function validateGhostWalkLeaseSummary(value) { + return ( + record(value) && + value.schema_version === + "phios.ghostwalk_action_lease_summary.v0.36" && + sha(value.action_lease_sha256) && + sha(value.lease_record_sha256) && + sha(value.executable_binding_sha256) && + text(value.principal_id, 256) && + text(value.issuer_id, 256) && + text(value.capability_id, 256) && + text(value.capability_version, 128) && + sha(value.payload_sha256) && + stringArray(value.effects_declared) && + stringArray(value.permissions_authorized) && + timestamp(value.valid_from) && + timestamp(value.valid_until) && + value.max_uses === 1 && + value.lease_action_authority === true && + value.effect_performed === false && + value.execution_authority === false + ); +} + +export function validateGhostWalkAuthorizationConsoleSnapshot(value) { + if (!zeroSnakeAuthority(value)) return false; + if ( + value.schema_version !== + "phios.ghostwalk_authorization_console_snapshot.v0.36" || + !sha(value.target_inference_receipt_sha256) || + !validateAuthorizationReadiness(value.authorization_readiness) || + !( + value.authorization_decision === null || + validateGhostWalkAuthorizationDecision( + value.authorization_decision, + ) + ) || + typeof value.binding_available !== "boolean" || + typeof value.lease_available !== "boolean" || + value.effect_performed !== false || + !sha(value.snapshot_sha256) + ) { + return false; + } + if ( + value.binding_available !== (value.binding_readiness !== null) || + value.lease_available !== (value.lease_readiness !== null) + ) { + return false; + } + if ( + value.binding_readiness !== null && + !validateBindingReadiness(value.binding_readiness) + ) { + return false; + } + if ( + value.binding !== null && + !validateGhostWalkBindingSummary(value.binding) + ) { + return false; + } + if ( + value.lease_readiness !== null && + !validateLeaseReadiness(value.lease_readiness) + ) { + return false; + } + if ( + value.lease !== null && + !validateGhostWalkLeaseSummary(value.lease) + ) { + return false; + } + return true; +} + +function validateBase(value, mutationKind) { + if (!record(value)) return false; + const mutated = mutationKind !== "NONE"; + return ( + value.transportSchemaVersion === + "phios.ghostwalk-authorization-console-transport.v0.36" && + value.transport === "loopback-http" && + value.transportIdentity === + "phios-ghostwalk-authorization-console" && + value.localOnly === true && + value.humanAuthorizationSurface === true && + value.mutationKind === mutationKind && + value.decisionRecorded === (mutationKind === "DECISION") && + value.bindingCreated === (mutationKind === "BINDING") && + value.actionLeaseCreated === (mutationKind === "LEASE") && + value.desktopEffectPerformed === false && + value.policyAuthority === false && + value.operationalAuthority === false && + value.actionAuthority === false && + value.executionAuthority === false && + value.effectPerformed === mutated && + timestamp(value.servedAt) + ); +} + +export function validateGhostWalkAuthorizationConsoleStatusEnvelope(value) { + return ( + validateBase(value, "NONE") && + validateGhostWalkAuthorizationConsoleSnapshot(value.snapshot) + ); +} + +export function validateGhostWalkAuthorizationDecisionEnvelope(value) { + return ( + validateBase(value, "DECISION") && + validateGhostWalkAuthorizationDecision(value.decision) && + validateGhostWalkAuthorizationConsoleSnapshot(value.snapshot) + ); +} + +export function validateGhostWalkBindingEnvelope(value) { + return ( + validateBase(value, "BINDING") && + validateGhostWalkBindingSummary(value.binding) && + validateGhostWalkAuthorizationConsoleSnapshot(value.snapshot) + ); +} + +export function validateGhostWalkLeaseEnvelope(value) { + return ( + validateBase(value, "LEASE") && + validateGhostWalkLeaseSummary(value.lease) && + validateGhostWalkAuthorizationConsoleSnapshot(value.snapshot) + ); +} + +export function validateAuthorizationDecisionPayload(value) { + const keys = [ + "decision", + "decision_note", + "expected_authority_request_sha256", + "expected_previous_decision_sha256", + "target_inference_receipt_sha256", + ]; + return ( + exactKeys(value, keys) && + sha(value.target_inference_receipt_sha256) && + sha(value.expected_authority_request_sha256) && + nullableSha(value.expected_previous_decision_sha256) && + ["APPROVE", "DENY", "HOLD"].includes(value.decision) && + ( + value.decision_note === null || + ( + typeof value.decision_note === "string" && + value.decision_note.length <= 2048 && + !value.decision_note.includes("\u0000") + ) + ) + ); +} + +export function validateBindingCreatePayload(value) { + const keys = [ + "expected_authorization_decision_sha256", + "expected_mapping_set_sha256", + "expected_mapping_sha256", + "target_inference_receipt_sha256", + ]; + return ( + exactKeys(value, keys) && + keys.every((key) => sha(value[key])) + ); +} + +export function validateLeaseIssuePayload(value) { + const keys = [ + "expected_authority_epoch_sha256", + "expected_enforcement_profile_sha256", + "expected_executable_binding_sha256", + "expected_policy_set_sha256", + "expected_policy_sha256", + "target_inference_receipt_sha256", + ]; + return ( + exactKeys(value, keys) && + keys.every((key) => sha(value[key])) + ); +} + +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); + } +} + +async function post(path, payload, validator, options) { + const { + fetcher = globalThis.fetch.bind(globalThis), + port = ghostWalkSidecarPort(), + timeoutMs = 2500, + } = options ?? {}; + const response = await request( + `http://${GHOSTWALK_HOST}:${port}${path}`, + { + 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.status === 503) return { kind: "unavailable" }; + if (!response.ok) return null; + try { + const envelope = await response.json(); + return validator(envelope) + ? { kind: "applied", envelope } + : null; + } catch { + return null; + } +} + +export async function fetchGhostWalkAuthorizationConsole( + 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/authorization-console?target=${targetSha256}`, + { + method: "GET", + cache: "no-store", + headers: { accept: "application/json" }, + }, + fetcher, + timeoutMs, + ); + if (!response || !response.ok) return null; + try { + const envelope = await response.json(); + return validateGhostWalkAuthorizationConsoleStatusEnvelope(envelope) + ? { kind: "found", envelope } + : null; + } catch { + return null; + } +} + +export async function recordGhostWalkAuthorizationDecision( + payload, + options = {}, +) { + if (!validateAuthorizationDecisionPayload(payload)) return null; + return post( + "/api/v1/ghostwalk/authorization-console/decisions", + payload, + validateGhostWalkAuthorizationDecisionEnvelope, + options, + ); +} + +export async function createGhostWalkExecutableBinding( + payload, + options = {}, +) { + if (!validateBindingCreatePayload(payload)) return null; + return post( + "/api/v1/ghostwalk/authorization-console/bindings", + payload, + validateGhostWalkBindingEnvelope, + options, + ); +} + +export async function issueGhostWalkActionLease( + payload, + options = {}, +) { + if (!validateLeaseIssuePayload(payload)) return null; + return post( + "/api/v1/ghostwalk/authorization-console/leases", + payload, + validateGhostWalkLeaseEnvelope, + options, + ); +} diff --git a/phishell/host/ghostWalkAuthorizationConsoleProxy.test.mjs b/phishell/host/ghostWalkAuthorizationConsoleProxy.test.mjs new file mode 100644 index 00000000..1d9bba88 --- /dev/null +++ b/phishell/host/ghostWalkAuthorizationConsoleProxy.test.mjs @@ -0,0 +1,106 @@ +import test from "node:test"; +import assert from "node:assert/strict"; + +import { + issueGhostWalkActionLease, + recordGhostWalkAuthorizationDecision, + validateAuthorizationDecisionPayload, + validateLeaseIssuePayload, +} from "./ghostWalkAuthorizationConsoleProxy.mjs"; + +const SHA = (char) => char.repeat(64); + +test("authorization decision payload cannot choose executable fields", () => { + const valid = { + target_inference_receipt_sha256: SHA("a"), + expected_authority_request_sha256: SHA("b"), + expected_previous_decision_sha256: null, + decision: "APPROVE", + decision_note: "approve exact request", + }; + assert.equal(validateAuthorizationDecisionPayload(valid), true); + assert.equal( + validateAuthorizationDecisionPayload({ + ...valid, + capability_id: "desktop.interaction.click", + }), + false, + ); +}); + +test("lease payload is optimistic-concurrency hashes only", () => { + const valid = { + target_inference_receipt_sha256: SHA("a"), + expected_executable_binding_sha256: SHA("b"), + expected_policy_sha256: SHA("c"), + expected_policy_set_sha256: SHA("d"), + expected_enforcement_profile_sha256: SHA("e"), + expected_authority_epoch_sha256: SHA("f"), + }; + assert.equal(validateLeaseIssuePayload(valid), true); + assert.equal( + validateLeaseIssuePayload({ ...valid, lease_seconds: 300 }), + false, + ); + assert.equal( + validateLeaseIssuePayload({ + ...valid, + payload: { x: 1 }, + }), + false, + ); +}); + +test("decision proxy forwards exact payload to loopback sidecar", async () => { + const seen = []; + const fetcher = async (url, init) => { + seen.push({ + url: String(url), + body: JSON.parse(String(init.body)), + }); + return new Response("", { status: 409 }); + }; + const payload = { + target_inference_receipt_sha256: SHA("a"), + expected_authority_request_sha256: SHA("b"), + expected_previous_decision_sha256: null, + decision: "HOLD", + decision_note: null, + }; + const result = await recordGhostWalkAuthorizationDecision(payload, { + fetcher, + port: 3973, + }); + assert.deepEqual(result, { kind: "conflict" }); + assert.equal(seen.length, 1); + assert.match( + seen[0].url, + /\/api\/v1\/ghostwalk\/authorization-console\/decisions$/, + ); + assert.deepEqual(seen[0].body, payload); +}); + +test("lease proxy never adds authority-bearing fields", async () => { + const seen = []; + const fetcher = async (_url, init) => { + seen.push(JSON.parse(String(init.body))); + return new Response("", { status: 409 }); + }; + const payload = { + target_inference_receipt_sha256: SHA("a"), + expected_executable_binding_sha256: SHA("b"), + expected_policy_sha256: SHA("c"), + expected_policy_set_sha256: SHA("d"), + expected_enforcement_profile_sha256: SHA("e"), + expected_authority_epoch_sha256: SHA("f"), + }; + const result = await issueGhostWalkActionLease(payload, { + fetcher, + port: 3973, + }); + assert.deepEqual(result, { kind: "conflict" }); + assert.deepEqual(seen[0], payload); + assert.equal("payload" in seen[0], false); + assert.equal("permissions" in seen[0], false); + assert.equal("lease_seconds" in seen[0], false); +}); diff --git a/phishell/host/localTransport.mjs b/phishell/host/localTransport.mjs index e5e1e4d1..668dec83 100644 --- a/phishell/host/localTransport.mjs +++ b/phishell/host/localTransport.mjs @@ -42,6 +42,15 @@ import { fetchGhostWalkAuthorityRequestStatus, validateGhostWalkAuthorityRequestCreatePayload, } from "./ghostWalkAuthorityRequestProxy.mjs"; +import { + createGhostWalkExecutableBinding, + fetchGhostWalkAuthorizationConsole, + issueGhostWalkActionLease, + recordGhostWalkAuthorizationDecision, + validateAuthorizationDecisionPayload, + validateBindingCreatePayload, + validateLeaseIssuePayload, +} from "./ghostWalkAuthorizationConsoleProxy.mjs"; import { createPersistRequest, fetchBrokerHealth, @@ -146,6 +155,13 @@ export function createLocalObservationServer({ ghostWalkPolicyAdmissionRecorder = recordGhostWalkPolicyAdmission, ghostWalkAuthorityRequestFetcher = fetchGhostWalkAuthorityRequestStatus, ghostWalkAuthorityRequestCreator = createGhostWalkAuthorityRequest, + ghostWalkAuthorizationConsoleFetcher = + fetchGhostWalkAuthorizationConsole, + ghostWalkAuthorizationDecisionRecorder = + recordGhostWalkAuthorizationDecision, + ghostWalkExecutableBindingCreator = + createGhostWalkExecutableBinding, + ghostWalkActionLeaseIssuer = issueGhostWalkActionLease, } = {}) { if (!Number.isInteger(port) || port < 0 || port > 65535) { throw new Error("local observation port must be an integer between 0 and 65535"); @@ -155,6 +171,174 @@ export function createLocalObservationServer({ try { const url = new URL(request.url ?? "/", `http://${LOOPBACK_HOST}`); + if ( + request.method === "POST" && + url.pathname === "/api/v1/ghostwalk/authorization-console/decisions" + ) { + let payload; + try { + payload = await readBoundedJsonObject(request, { maxBytes: 8192 }); + } catch { + jsonResponse(response, 400, { + error: "invalid_ghostwalk_authorization_decision_body", + policyAuthority: false, + operationalAuthority: false, + actionAuthority: false, + executionAuthority: false, + effectPerformed: false, + }); + return; + } + if (!validateAuthorizationDecisionPayload(payload)) { + jsonResponse(response, 400, { + error: "invalid_ghostwalk_authorization_decision_request", + policyAuthority: false, + operationalAuthority: false, + actionAuthority: false, + executionAuthority: false, + effectPerformed: false, + }); + return; + } + const result = await ghostWalkAuthorizationDecisionRecorder(payload); + if (result?.kind === "conflict") { + jsonResponse(response, 409, { + error: "ghostwalk_authorization_decision_conflict", + policyAuthority: false, + operationalAuthority: false, + actionAuthority: false, + executionAuthority: false, + effectPerformed: false, + }); + return; + } + if (!result || result.kind !== "applied") { + jsonResponse(response, 503, { + error: "ghostwalk_authorization_console_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/authorization-console/bindings" + ) { + let payload; + try { + payload = await readBoundedJsonObject(request, { maxBytes: 8192 }); + } catch { + jsonResponse(response, 400, { + error: "invalid_ghostwalk_binding_body", + policyAuthority: false, + operationalAuthority: false, + actionAuthority: false, + executionAuthority: false, + effectPerformed: false, + }); + return; + } + if (!validateBindingCreatePayload(payload)) { + jsonResponse(response, 400, { + error: "invalid_ghostwalk_binding_request", + policyAuthority: false, + operationalAuthority: false, + actionAuthority: false, + executionAuthority: false, + effectPerformed: false, + }); + return; + } + const result = await ghostWalkExecutableBindingCreator(payload); + if (result?.kind === "conflict") { + jsonResponse(response, 409, { + error: "ghostwalk_binding_conflict", + policyAuthority: false, + operationalAuthority: false, + actionAuthority: false, + executionAuthority: false, + effectPerformed: false, + }); + return; + } + if (!result || result.kind !== "applied") { + jsonResponse(response, 503, { + error: "ghostwalk_authorization_console_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/authorization-console/leases" + ) { + let payload; + try { + payload = await readBoundedJsonObject(request, { maxBytes: 8192 }); + } catch { + jsonResponse(response, 400, { + error: "invalid_ghostwalk_lease_body", + policyAuthority: false, + operationalAuthority: false, + actionAuthority: false, + executionAuthority: false, + effectPerformed: false, + }); + return; + } + if (!validateLeaseIssuePayload(payload)) { + jsonResponse(response, 400, { + error: "invalid_ghostwalk_lease_request", + policyAuthority: false, + operationalAuthority: false, + actionAuthority: false, + executionAuthority: false, + effectPerformed: false, + }); + return; + } + const result = await ghostWalkActionLeaseIssuer(payload); + if (result?.kind === "conflict") { + jsonResponse(response, 409, { + error: "ghostwalk_lease_conflict", + policyAuthority: false, + operationalAuthority: false, + actionAuthority: false, + executionAuthority: false, + effectPerformed: false, + }); + return; + } + if (!result || result.kind !== "applied") { + jsonResponse(response, 503, { + error: "ghostwalk_authorization_console_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/authority-request/requests" @@ -518,6 +702,43 @@ export function createLocalObservationServer({ return; } + if ( + url.pathname === "/api/v1/ghostwalk/authorization-console" + ) { + 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_authorization_console_request", + policyAuthority: false, + operationalAuthority: false, + actionAuthority: false, + executionAuthority: false, + effectPerformed: false, + }); + return; + } + const result = await ghostWalkAuthorizationConsoleFetcher(target); + if (!result || result.kind !== "found") { + jsonResponse(response, 503, { + error: "ghostwalk_authorization_console_unavailable", + policyAuthority: false, + operationalAuthority: false, + actionAuthority: false, + executionAuthority: false, + effectPerformed: false, + }); + return; + } + jsonResponse(response, 200, result.envelope); + return; + } + if (url.pathname === "/api/v1/ghostwalk/authority-request") { const keys = [...url.searchParams.keys()]; const target = url.searchParams.get("target"); diff --git a/phishell/src/components/GhostWalkAuthorityRequestCard.tsx b/phishell/src/components/GhostWalkAuthorityRequestCard.tsx index 88c7a229..143fdc39 100644 --- a/phishell/src/components/GhostWalkAuthorityRequestCard.tsx +++ b/phishell/src/components/GhostWalkAuthorityRequestCard.tsx @@ -1,4 +1,5 @@ import { useCallback, useEffect, useState } from "react"; +import { GhostWalkAuthorizationConsoleCard } from "./GhostWalkAuthorizationConsoleCard"; import { ghostWalkAuthorityRequestClient, type GhostWalkAuthorityRequest, @@ -122,6 +123,13 @@ export function GhostWalkAuthorityRequestCard({
REQUEST != AUTHORIZATION · PENDING_AUTHORIZATION != ACTION AUTHORITY · ACTIONLEASE NOT CREATED
+ + {request && ( + + )} ); } diff --git a/phishell/src/components/GhostWalkAuthorizationConsoleCard.tsx b/phishell/src/components/GhostWalkAuthorizationConsoleCard.tsx new file mode 100644 index 00000000..3f2348d7 --- /dev/null +++ b/phishell/src/components/GhostWalkAuthorizationConsoleCard.tsx @@ -0,0 +1,383 @@ +import { useCallback, useEffect, useState } from "react"; +import { + ghostWalkAuthorizationConsoleClient, + type AuthorizationDecisionKind, + type GhostWalkAuthorizationConsoleSnapshot, +} from "../ghostwalk/authorizationConsole"; + +function shortHash(value: string | null) { + return value ? `${value.slice(0, 10)}…` : "NONE"; +} + +export function GhostWalkAuthorizationConsoleCard({ + targetSha256, + refreshToken, +}: { + targetSha256: string; + refreshToken: string; +}) { + const [snapshot, setSnapshot] = + useState(null); + const [note, setNote] = useState(""); + const [busy, setBusy] = useState< + "DECISION" | "BINDING" | "LEASE" | null + >(null); + const [message, setMessage] = useState(null); + + const load = useCallback(async () => { + const result = await ghostWalkAuthorizationConsoleClient.read( + targetSha256, + ); + if (result.kind === "found") { + setSnapshot(result.snapshot); + setMessage(null); + return; + } + setSnapshot(null); + setMessage( + "Human authorization console is unavailable or returned invalid evidence.", + ); + }, [targetSha256, refreshToken]); + + useEffect(() => { + void load(); + }, [load]); + + const recordDecision = useCallback( + async (decision: AuthorizationDecisionKind) => { + if ( + !snapshot?.authorization_readiness.ready || + !snapshot.authorization_readiness.authority_request_sha256 + ) { + return; + } + setBusy("DECISION"); + setMessage(null); + try { + const result = + await ghostWalkAuthorizationConsoleClient.recordDecision({ + targetSha256, + expectedAuthorityRequestSha256: + snapshot.authorization_readiness.authority_request_sha256, + expectedPreviousDecisionSha256: + snapshot.authorization_readiness.latest_decision_sha256, + decision, + decisionNote: note.trim() || null, + }); + if (result.kind === "conflict") { + setMessage( + "Authorization conflict: the request or decision history " + + "changed. Reload before deciding again.", + ); + return; + } + if (result.kind === "unavailable") { + setMessage( + "Authorization decision was rejected or could not be validated.", + ); + return; + } + setSnapshot(result.snapshot); + setNote(""); + setMessage( + `${decision} recorded. This decision did not create an ActionLease or execute an effect.`, + ); + } finally { + setBusy(null); + } + }, + [note, snapshot, targetSha256], + ); + + const createBinding = useCallback(async () => { + const readiness = snapshot?.binding_readiness; + if ( + !readiness?.ready || + !readiness.authorization_decision_sha256 || + !readiness.selected_mapping_sha256 + ) { + return; + } + setBusy("BINDING"); + setMessage(null); + try { + const result = + await ghostWalkAuthorizationConsoleClient.createBinding({ + targetSha256, + expectedAuthorizationDecisionSha256: + readiness.authorization_decision_sha256, + expectedMappingSha256: readiness.selected_mapping_sha256, + expectedMappingSetSha256: readiness.mapping_set_sha256, + }); + if (result.kind === "conflict") { + setMessage( + "Binding conflict: authorization or trusted mapping state changed. Reload first.", + ); + return; + } + if (result.kind === "unavailable") { + setMessage( + "Executable binding is unavailable. Trusted local execution " + + "configuration may be absent or invalid.", + ); + return; + } + setSnapshot(result.snapshot); + setMessage( + "Exact executable binding created. It still carries zero action and execution authority.", + ); + } finally { + setBusy(null); + } + }, [snapshot, targetSha256]); + + const issueLease = useCallback(async () => { + const readiness = snapshot?.lease_readiness; + if ( + !readiness?.ready || + !readiness.executable_binding_sha256 || + !readiness.policy_sha256 || + !readiness.enforcement_profile_sha256 || + !readiness.authority_epoch_sha256 + ) { + return; + } + setBusy("LEASE"); + setMessage(null); + try { + const result = await ghostWalkAuthorizationConsoleClient.issueLease({ + targetSha256, + expectedExecutableBindingSha256: + readiness.executable_binding_sha256, + expectedPolicySha256: readiness.policy_sha256, + expectedPolicySetSha256: readiness.policy_set_sha256, + expectedEnforcementProfileSha256: + readiness.enforcement_profile_sha256, + expectedAuthorityEpochSha256: + readiness.authority_epoch_sha256, + }); + if (result.kind === "conflict") { + setMessage( + "Lease conflict: binding, policy, enforcement, or authority state changed. Reload first.", + ); + return; + } + if (result.kind === "unavailable") { + setMessage( + "ActionLease issuance is unavailable or failed current authority checks.", + ); + return; + } + setSnapshot(result.snapshot); + setMessage( + "Single-use ActionLease issued. The lease carries bounded action " + + "authority; this console still cannot execute it.", + ); + } finally { + setBusy(null); + } + }, [snapshot, targetSha256]); + + if (!snapshot) { + return ( +
+
+
+ HUMAN AUTHORIZATION + LEASE + UNAVAILABLE +
+ EXECUTION 0 +
+ {message && ( +
{message}
+ )} +
+ ); + } + + const auth = snapshot.authorization_readiness; + const binding = snapshot.binding_readiness; + const lease = snapshot.lease_readiness; + + return ( +
+
+
+ HUMAN AUTHORIZATION + LEASE + {snapshot.lease ? "LEASE ISSUED" : auth.reason} +
+ EXECUTION 0 +
+ +
+
+ 1 · HUMAN DECISION + {auth.ready ? "READY" : auth.reason} +
+ + {snapshot.authorization_decision && ( +
+ {snapshot.authorization_decision.decision} + + decision{" "} + {shortHash( + snapshot.authorization_decision + .authorization_decision_sha256, + )} + + + authorization{" "} + {snapshot.authorization_decision.authorization_granted + ? "GRANTED" + : "NOT GRANTED"} + {" · "}action authority 0 + +
+ )} + + {auth.ready && ( + <> +