diff --git a/docs/OPERATOR_AUTHORIZATION.md b/docs/OPERATOR_AUTHORIZATION.md new file mode 100644 index 00000000..2e0866f6 --- /dev/null +++ b/docs/OPERATOR_AUTHORIZATION.md @@ -0,0 +1,49 @@ +# Operator authorization boundary + +The PhiShell and GhostWalk HTTP surfaces expose observation and proposal +interfaces. POSTs to authorization-console `decisions`, `bindings`, and `leases` +return **403 operator_channel_required**, before parsing or calling a service. +A loopback address, a browser origin, or a PhiVessel session does not identify +an operator. Other HTTP writes require the exact loopback Host, JSON content +type, and a matching Origin when present; cross-site fetches are rejected. +These checks reduce browser request forgery; they do not authenticate agents. + +Install the Python package to obtain `phi-operator`, or run +`python -m phios.ghostwalk_operator` from the source checkout. Use the same +protected state root and policy environment as the host: + +```sh +phi-operator --state-root ~/.phios --target inspect +phi-operator --state-root ~/.phios --target decide APPROVE +phi-operator --state-root ~/.phios --target decide HOLD +phi-operator --state-root ~/.phios --target decide DENY +phi-operator --state-root ~/.phios --target bind +phi-operator --state-root ~/.phios --target lease +``` + +Each mutation displays the current normalized evidence as escaped JSON and +requires typing the action and full snapshot digest. There is no `--yes` or +unattended option. Cancellation does not mutate authority. Changed evidence +requires a new review, and the existing services still check their exact +request, previous decision, mapping, policy, enforcement and epoch hashes. +Approval does not create a binding or lease. The command never executes an +effect or mounts an executor. Refresh PhiShell after terminal operations. + +Without a valid trusted execution manifest, only inspection and decisions +are available. Binding and lease issuance currently require the supported +Windows desktop host. Linux previews must report this capability unavailable. +The CLI requires its manifest inside the protected state root, rejects +symlinked state, and on POSIX rejects state owned by another user or writable +by group/others. It does not silently repair existing permissions. + +## Trust and remaining release gates + +A TTY is an explicit interaction requirement, **not proof of human identity**. +A malicious process sharing the operator's OS account can create a pseudo-TTY, +import Python services, or edit that account's files. Run untrusted agents as +separate OS principals without access to operator state, terminal or desktop. +On Windows, protect the state with an owner-only ACL; this CLI does not attest +Windows ACLs. The Linux OS release remains held until principal separation, +broker authentication, concurrent writer safety and durable state recovery +have independent evidence. Do not describe this patch as universal human +authentication or whole-OS sandboxing. diff --git a/docs/os/IMPLEMENTATION_STATUS.md b/docs/os/IMPLEMENTATION_STATUS.md new file mode 100644 index 00000000..41132e88 --- /dev/null +++ b/docs/os/IMPLEMENTATION_STATUS.md @@ -0,0 +1,37 @@ +# Linux OS implementation register + +Controlling input: the operator-approved *PhiOS OS Release Audit and Plan*, +2026-09-30, SHA-256 `aba53c05f18ac2f874236a1b6566b74096eabff9422e9e0fee0b5da54b54a676`, audited source `dad7a7d7cd53874926ad366f19d3fc0fa6b99a49`. +This register tracks candidate implementation, not permission to publish or +proof that PhiOS is a completed OS. Preserve the repository AGENTS.md rules. + +| Requirement | Candidate change | Evidence / remaining gate | +| --- | --- | --- | +| R1: HTTP callers cannot mint operator authority | Decision, binding and lease POSTs held; explicit terminal review | HTTP rejection, cancellation and stale-review tests; same-user isolation and Windows ACL evidence remain required | +| R2: Freeze a truthful Linux release contract | Pending | x86_64 UEFI, Arch, Wayfire, PhiShell, distinct OS version | +| R3: Install current Python and UI packages | Pending | Locked inputs, pacman inventory, installed smoke checks | +| R4: Real non-root graphical login and supervised services | Pending | Session start, stop, reboot and no elevated browser | +| R5: Produce and UEFI boot exact live ISO | Pending | Archiso build and QEMU evidence, graphical qualification | +| R6: Recover durable private state | Pending | Concurrent writes, crash recovery, backup/restore, migrations | +| R7: Explicit blank-disk installation | Pending | Disposable VM install, boot without ISO, persistence | +| R8: Whole-OS update and recovery | Pending | Signed artifacts, failed update recovery; app rollback is insufficient | +| R9: Qualify hardware and one Linux governed workflow | Pending | Named hardware matrix and observed effect verification | +| R10: Sign and publish the exact qualified artifact | Held | Proven preceding gates, hashes, SBOM, signatures, source/license notices and maintainer release decision | + +## First builder handoff + +The approval boundary is a bounded candidate repair. Core normalized +contracts, adapter selection, advisory rollout behavior and private PhiKernel +internals remain untouched. Existing terminal services perform each stage +separately; no capability payload or lease lifetime is selected by the CLI. + +Focused security tests and Python lint/type checks are required before review. +The full existing suite must also run in GitHub CI: the local execution host +restricts AF_UNIX, network enumeration and bubblewrap preflight. Environment +failures must be preserved and reported separately, never silently skipped to +claim a pass. Reviewers should rerun the boundary tests and assess the stated +same-user trust limitation before merging. Later milestones must update this +register with actual artifact identities and evidence, rather than readiness +percentages or forecast dates. + +Validation: 73 focused Python tests passed; Ruff and mypy (301 source files) passed. PhiShell production build and 12 targeted HTTP boundary/proposal tests passed. Full PhiShell TypeScript suite passed; three existing Node integration tests fail on this host due to restricted network enumeration and absent systemd, as recorded in the audit. GitHub CI remains the required full-platform check. diff --git a/phios/ghostwalk_operator.py b/phios/ghostwalk_operator.py new file mode 100644 index 00000000..0ac897f6 --- /dev/null +++ b/phios/ghostwalk_operator.py @@ -0,0 +1,209 @@ +"""Explicit terminal review of the existing decision -> binding -> lease chain. + +This process never installs or calls an executor. A terminal is an intentional +operator interface, not proof of a human or isolation from a malicious process +running as the same OS user. Such processes must use a separate OS principal. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import stat +import sys +from datetime import UTC, datetime +from pathlib import Path +from typing import TextIO + +from phios.macro_accepted_intent import GhostWalkAcceptedIntentRegistry +from phios.macro_action_lease_service import GhostWalkActionLeaseService, GhostWalkLeasePolicyRegistry +from phios.macro_authority_request import GhostWalkAuthorityRequestService +from phios.macro_authorization_console import ( + GhostWalkAuthorizationConsoleError, + GhostWalkAuthorizationConsoleService, + GhostWalkAuthorizationConsoleSnapshot, +) +from phios.macro_authorization_decision import ( + GhostWalkAuthorizationDecisionKind, + GhostWalkAuthorizationDecisionService, +) +from phios.macro_capability_binding import ( + GhostWalkCapabilityBindingService, + GhostWalkCapabilityMappingRegistry, +) +from phios.macro_ghostwalk_control_server import DEFAULT_OPERATOR_AUTHOR_ID, default_state_root +from phios.macro_ghostwalk_operator_editor import GhostWalkOperatorEditor +from phios.macro_policy_admission import GhostWalkPolicyAdmissionService, GhostWalkPolicyProfile +from phios.phivessel_local_execution import ( + ManifestAuthorityEpochProvider, + PhiVesselLocalExecutionManifest, + execution_manifest_path, +) +from phios.spine.ledger import RealityLedger + + +def _check_owned_path(path: Path) -> None: + """Reject symlinks and shared-writable state before constructing services.""" + info = path.lstat() + if stat.S_ISLNK(info.st_mode): + raise ValueError(f"operator state must not be a symlink: {path}") + if os.name == "posix": + if info.st_uid != os.getuid() or info.st_mode & 0o022: + raise ValueError(f"operator state must be owned by you and not shared-writable: {path}") + + +def build_operator_console(state_root: Path) -> GhostWalkAuthorizationConsoleService: + root = state_root.expanduser().absolute() + # Existing state is never silently repaired or permission-changed. + root.mkdir(parents=True, exist_ok=True, mode=0o700) + _check_owned_path(root) + for path in root.rglob("*"): + _check_owned_path(path) + ledger_dir = root / "ledger" + ledger_dir.mkdir(exist_ok=True, mode=0o700) + ledger = RealityLedger(ledger_dir / "receipts.jsonl") + editor = GhostWalkOperatorEditor(ledger=ledger, author_id=DEFAULT_OPERATOR_AUTHOR_ID) + intents = GhostWalkAcceptedIntentRegistry(ledger=ledger, accepted_by=DEFAULT_OPERATOR_AUTHOR_ID) + admission = GhostWalkPolicyAdmissionService( + ledger=ledger, accepted_intents=intents, operator_editor=editor, + profile=GhostWalkPolicyProfile.from_environment(os.environ), + ) + requests = GhostWalkAuthorityRequestService( + ledger=ledger, policy_admission=admission, requester_id=DEFAULT_OPERATOR_AUTHOR_ID, + ) + decisions = GhostWalkAuthorizationDecisionService( + ledger=ledger, authority_requests=requests, authorizer_id=DEFAULT_OPERATOR_AUTHOR_ID, + ) + manifest_path = execution_manifest_path(state_root=root) + if not manifest_path.absolute().is_relative_to(root): + raise ValueError("operator execution manifest must be inside the protected state root") + if not manifest_path.exists(): + return GhostWalkAuthorizationConsoleService(authorization_decisions=decisions) + _check_owned_path(manifest_path) + manifest = PhiVesselLocalExecutionManifest.read(manifest_path) + if not manifest.enabled: + return GhostWalkAuthorizationConsoleService(authorization_decisions=decisions) + # The installed desktop executor currently only supports Windows. Linux + # previews must not mint a lease for an unavailable effect implementation. + if sys.platform != "win32" or not manifest.desktop_executor_enabled: + raise ValueError("desktop binding and lease issuance require the supported Windows host") + bindings = GhostWalkCapabilityBindingService( + ledger=ledger, authorization_decisions=decisions, + registry=GhostWalkCapabilityMappingRegistry(manifest.mappings), + ) + leases = GhostWalkActionLeaseService( + ledger=ledger, capability_bindings=bindings, + policies=GhostWalkLeasePolicyRegistry(manifest.lease_policies), + authority_epochs=ManifestAuthorityEpochProvider( + path=manifest_path, expected_static_config_sha256=manifest.static_config_sha256, + ), + ) + return GhostWalkAuthorizationConsoleService( + authorization_decisions=decisions, capability_bindings=bindings, action_leases=leases, + ) + + +def _perform( + console: GhostWalkAuthorizationConsoleService, + snapshot: GhostWalkAuthorizationConsoleSnapshot, + action: str, + decision: str | None, + note: str | None, +) -> dict[str, object]: + target = snapshot.target_inference_receipt_sha256 + if action == "decide": + auth = snapshot.authorization_readiness + if not auth.ready or auth.authority_request_sha256 is None or decision is None: + raise ValueError(f"decision held: {auth.reason.value}") + return console.record_decision( + target_inference_receipt_sha256=target, + expected_authority_request_sha256=auth.authority_request_sha256, + expected_previous_decision_sha256=auth.latest_decision_sha256, + decision=GhostWalkAuthorizationDecisionKind(decision), decision_note=note, + ).to_dict() + if action == "bind": + binding = snapshot.binding_readiness + if (binding is None or not binding.ready or binding.authorization_decision_sha256 is None + or binding.selected_mapping_sha256 is None): + raise ValueError("binding held: current trusted mapping and approval required") + return console.create_binding( + target_inference_receipt_sha256=target, + expected_authorization_decision_sha256=binding.authorization_decision_sha256, + expected_mapping_sha256=binding.selected_mapping_sha256, + expected_mapping_set_sha256=binding.mapping_set_sha256, + bound_at=datetime.now(UTC).isoformat(), + ).to_dict() + lease = snapshot.lease_readiness + if (lease is None or not lease.ready or lease.executable_binding_sha256 is None + or lease.policy_sha256 is None or lease.enforcement_profile_sha256 is None + or lease.authority_epoch_sha256 is None): + raise ValueError("lease held: current binding, policy, enforcement and authority required") + return console.issue_lease( + target_inference_receipt_sha256=target, + expected_executable_binding_sha256=lease.executable_binding_sha256, + expected_policy_sha256=lease.policy_sha256, + expected_policy_set_sha256=lease.policy_set_sha256, + expected_enforcement_profile_sha256=lease.enforcement_profile_sha256, + expected_authority_epoch_sha256=lease.authority_epoch_sha256, + ).to_dict() + + +def review( + console: GhostWalkAuthorizationConsoleService, *, target: str, action: str, + decision: str | None = None, note: str | None = None, + input_stream: TextIO, output_stream: TextIO, +) -> int: + if action not in {"inspect", "decide", "bind", "lease"}: + raise ValueError("unsupported operator action") + if action != "inspect" and not (input_stream.isatty() and output_stream.isatty()): + raise ValueError("operator mutations require an interactive terminal; no unattended flag exists") + snapshot = console.snapshot(target_inference_receipt_sha256=target) + # JSON escaping prevents proposal text from injecting terminal control codes. + print(json.dumps(snapshot.to_dict(), indent=2, ensure_ascii=True), file=output_stream) + if action == "inspect": + return 0 + confirmation = f"{decision if action == 'decide' else action.upper()} {snapshot.snapshot_sha256}" + print(f"Type exactly {confirmation} to confirm, or anything else to cancel:", + file=output_stream, flush=True) + if input_stream.readline().strip() != confirmation: + print("Cancelled; no decision, binding, or lease was created.", file=output_stream) + return 2 + current = console.snapshot(target_inference_receipt_sha256=target) + if current.snapshot_sha256 != snapshot.snapshot_sha256: + raise ValueError("evidence changed during review; inspect and confirm again") + result = _perform(console, snapshot, action, decision, note) + print(json.dumps({"operator_action": action, "result": result, + "execution_authority": False, "effect_performed": False}, indent=2), + file=output_stream) + return 0 + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--state-root", type=Path, default=default_state_root()) + parser.add_argument("--target", required=True) + actions = parser.add_subparsers(dest="action", required=True) + actions.add_parser("inspect") + decide = actions.add_parser("decide") + decide.add_argument("decision", choices=("APPROVE", "HOLD", "DENY")) + decide.add_argument("--note") + actions.add_parser("bind") + actions.add_parser("lease") + args = parser.parse_args(argv) + try: + if re.fullmatch(r"[0-9a-f]{64}", args.target) is None: + raise ValueError("target must be a lowercase SHA-256 digest") + if args.action != "inspect" and not (sys.stdin.isatty() and sys.stdout.isatty()): + raise ValueError("operator mutations require an interactive terminal") + return review(build_operator_console(args.state_root), target=args.target, action=args.action, + decision=getattr(args, "decision", None), note=getattr(args, "note", None), + input_stream=sys.stdin, output_stream=sys.stdout) + except (ValueError, OSError, GhostWalkAuthorizationConsoleError) as exc: + print(f"Operator action held: {exc}", file=sys.stderr) + return 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/phios/macro_ghostwalk_control_server.py b/phios/macro_ghostwalk_control_server.py index 65d8ea0f..5c6464a9 100644 --- a/phios/macro_ghostwalk_control_server.py +++ b/phios/macro_ghostwalk_control_server.py @@ -1905,217 +1905,29 @@ 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) + if parsed.path in { + "/api/v1/ghostwalk/authorization-console/decisions", + "/api/v1/ghostwalk/authorization-console/bindings", + "/api/v1/ghostwalk/authorization-console/leases", + }: + # Loopback connectivity and agent sessions are not operator approval. + self._authorization_console_error( + HTTPStatus.FORBIDDEN, "operator_channel_required" + ) return - if parsed.path == ( - "/api/v1/ghostwalk/authorization-console/leases" + expected_host = f"{LOOPBACK_HOST}:{self.server.server_address[1]}" + origin = self.headers.get("Origin") + fetch_site = self.headers.get("Sec-Fetch-Site") + mime = self.headers.get("Content-Type", "") + if ( + self.headers.get("Host") != expected_host + or parsed.netloc not in {"", expected_host} + or (origin is not None and origin != f"http://{expected_host}") + or (fetch_site is not None and fetch_site not in {"same-origin", "none"}) + or re.fullmatch(r"application/json(?:\s*;\s*charset=utf-8)?", mime, re.I) is None ): - 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) + self._authorization_console_error(HTTPStatus.FORBIDDEN, "invalid_local_write_origin") return if parsed.path == "/api/v1/phivessel/handshake": diff --git a/phishell/host/ghostWalkAuthorizationConsoleLocalTransport.test.mjs b/phishell/host/ghostWalkAuthorizationConsoleLocalTransport.test.mjs index ea9e81f8..16535b3c 100644 --- a/phishell/host/ghostWalkAuthorizationConsoleLocalTransport.test.mjs +++ b/phishell/host/ghostWalkAuthorizationConsoleLocalTransport.test.mjs @@ -1,75 +1,49 @@ 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(); +for (const endpoint of ["decisions", "bindings", "leases"]) { + for (const [label, headers] of [ + ["local agent", { "content-type": "application/json" }], + ["foreign webpage", { "origin": "https://attacker.invalid", "content-type": "text/plain", "sec-fetch-site": "cross-site" }], + ["foreign Host and agent session", { "host": "attacker.invalid", "authorization": "Bearer agent-session", "content-type": "application/json" }], + ]) { + test(`${label} cannot use HTTP ${endpoint}`, async () => { + const transport = createLocalObservationServer({ port: 0, serveShell: false }); + const address = await transport.listen(); + try { + const response = await fetch(`http://${address.host}:${address.port}/api/v1/ghostwalk/authorization-console/${endpoint}`, { + method: "POST", headers, + body: JSON.stringify({ + target_inference_receipt_sha256: "a".repeat(64), + expected_authority_request_sha256: "b".repeat(64), + expected_previous_decision_sha256: null, + decision: "APPROVE", decision_note: "forged human approval", + }), + }); + assert.equal(response.status, 403); + const result = await response.json(); + assert.equal(result.error, "operator_channel_required"); + assert.equal(result.actionAuthority, false); + assert.equal(result.executionAuthority, false); + assert.equal(result.effectPerformed, false); + } 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" }; - }, +test("foreign browser write is refused before proposal dispatch", async () => { + let dispatched = false; + const transport = createLocalObservationServer({ port: 0, serveShell: false, + ghostWalkAuthorityRequestCreator: async () => { dispatched = true; 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(); - } + const response = await fetch(`http://${address.host}:${address.port}/api/v1/ghostwalk/authority-request/requests`, { + method: "POST", headers: { origin: "https://attacker.invalid", "content-type": "text/plain" }, + body: JSON.stringify({target_inference_receipt_sha256: "a".repeat(64), expected_admission_receipt_sha256: "b".repeat(64)}), + }); + assert.equal(response.status, 403); + assert.equal(dispatched, false); + } finally { await transport.close(); } }); diff --git a/phishell/host/localTransport.mjs b/phishell/host/localTransport.mjs index 668dec83..d85f9dcf 100644 --- a/phishell/host/localTransport.mjs +++ b/phishell/host/localTransport.mjs @@ -42,15 +42,7 @@ import { fetchGhostWalkAuthorityRequestStatus, validateGhostWalkAuthorityRequestCreatePayload, } from "./ghostWalkAuthorityRequestProxy.mjs"; -import { - createGhostWalkExecutableBinding, - fetchGhostWalkAuthorizationConsole, - issueGhostWalkActionLease, - recordGhostWalkAuthorizationDecision, - validateAuthorizationDecisionPayload, - validateBindingCreatePayload, - validateLeaseIssuePayload, -} from "./ghostWalkAuthorizationConsoleProxy.mjs"; +import { fetchGhostWalkAuthorizationConsole } from "./ghostWalkAuthorizationConsoleProxy.mjs"; import { createPersistRequest, fetchBrokerHealth, @@ -157,11 +149,6 @@ export function createLocalObservationServer({ 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"); @@ -171,172 +158,49 @@ 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); + // Observation/agent HTTP callers never become the operator channel. + if (request.method === "POST" && [ + "/api/v1/ghostwalk/authorization-console/decisions", + "/api/v1/ghostwalk/authorization-console/bindings", + "/api/v1/ghostwalk/authorization-console/leases", + ].includes(url.pathname)) { + jsonResponse(response, 403, { + error: "operator_channel_required", + operatorChannel: "local-terminal", + policyAuthority: false, + operationalAuthority: false, + actionAuthority: false, + executionAuthority: false, + effectPerformed: false, + }); 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); + const expectedHost = `${LOOPBACK_HOST}:${request.socket.localPort}`; + const expectedOrigin = `http://${expectedHost}`; + if (request.headers.host !== expectedHost || + (url.origin !== `http://${LOOPBACK_HOST}` && url.origin !== expectedOrigin)) { + jsonResponse(response, 403, { error: "invalid_local_host", effectPerformed: false }); 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, - }); + if (request.method === "POST" && [ + "/api/v1/ghostwalk/authority-request/requests", + "/api/v1/ghostwalk/policy-admission/evaluations", + "/api/v1/ghostwalk/accepted-intent/revisions", + "/api/v1/ghostwalk/operator-log/revisions", + "/api/v1/ghostwalk/actions", + "/api/v1/curiosity/persist-requests", + "/api/v1/curiosity/artifacts", + ].includes(url.pathname)) { + const origin = request.headers.origin; + const fetchSite = request.headers["sec-fetch-site"]; + const mime = request.headers["content-type"] ?? ""; + if ((origin !== undefined && origin !== expectedOrigin) || + (fetchSite !== undefined && !["same-origin", "none"].includes(fetchSite)) || + !/^application\/json(?:\s*;\s*charset=utf-8)?$/i.test(mime)) { + jsonResponse(response, 403, { error: "invalid_local_write_origin", effectPerformed: false }); return; } - jsonResponse(response, 200, result.envelope); - return; } if ( diff --git a/phishell/src/components/GhostWalkAuthorizationConsoleCard.tsx b/phishell/src/components/GhostWalkAuthorizationConsoleCard.tsx index 3f2348d7..c992e461 100644 --- a/phishell/src/components/GhostWalkAuthorizationConsoleCard.tsx +++ b/phishell/src/components/GhostWalkAuthorizationConsoleCard.tsx @@ -1,7 +1,6 @@ import { useCallback, useEffect, useState } from "react"; import { ghostWalkAuthorizationConsoleClient, - type AuthorizationDecisionKind, type GhostWalkAuthorizationConsoleSnapshot, } from "../ghostwalk/authorizationConsole"; @@ -18,10 +17,6 @@ export function GhostWalkAuthorizationConsoleCard({ }) { 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 () => { @@ -43,141 +38,6 @@ export function GhostWalkAuthorizationConsoleCard({ 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 (
@@ -235,39 +95,9 @@ export function GhostWalkAuthorizationConsoleCard({ )} - {auth.ready && ( - <> -