From 4db52987a0d1843991d38503dd15db7db7265614 Mon Sep 17 00:00:00 2001 From: darklordVirtual Date: Thu, 6 Aug 2026 08:50:39 +0200 Subject: [PATCH 1/2] =?UTF-8?q?feat(console):=20AAE=20Assurance=20Console?= =?UTF-8?q?=20=E2=80=94=20four=20surfaces,=20no=20framework,=20still=20rea?= =?UTF-8?q?d-only?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Built on 3057808's security contract, which is treated as an invariant: one viewer token, no mutating route, no REMORA package in the image. All fifteen container tests kept and extended rather than replaced. ## The regression that started it Stripping REMORA out of the console image took `core-artifact-lock.json` with it, and the verified engine version, commit and release silently became empty — a console looking fine while telling you less than it should. The lock is 30 lines of JSON the console READS; copying it back reintroduces no dependency. A test now fails if any of the three is unreported. ## Architecture FastAPI serving typed JSON and three static files. No Node, no npm, no framework, no build step, no external request. console/ app.py fetch, validate, serve, report failure, set headers static/ index.html the shell and four surfaces aae.css one graphite theme, light and dark aae.js rendering, no dependencies `app.py` does five things and no more. Every response has an explicit Pydantic model; nothing returns a raw database row. ## Security headers Content-Security-Policy: default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; object-src 'none'; frame-ancestors 'none'; base-uri 'none'; form-action 'none' X-Content-Type-Options: nosniff Referrer-Policy: no-referrer Cache-Control: no-store `form-action 'none'` means no markup here can post anywhere at all. `no-store` because a cached copy of governance state on a shared machine outlives the session entitled to see it. A test asserts no static file references an external host — it fails earlier and more legibly than a CSP violation, which surfaces as a silently missing asset. ## Four surfaces **Overview** answers whether enforcement is operational in one line, then lists only ACTUAL deviations. A list that always has entries is a list nobody reads, which is how a real finding gets missed. With the control plane stopped it names the outage, counts it, and still renders — a test stops the container to prove it. **Decisions** is a proposal LOOKUP, deliberately not a feed. The core returns a proposal by identifier and cannot list them, and the business event log carries no proposal id because the dispatcher passes none to the tool. Assembling a "recent decisions" list from what is available would mean showing a reconstruction as though it were the record. The contract that would fix it is written down in docs/limitations.md as an upstream requirement. **Business records** shows work orders and their change history in human-readable form. `{"from": "normal", "to": "high"}` renders as `normal → high`; the raw JSON lives in the evidence drawer. **System assurance** collects the technical evidence: verified engine and commit, release, tool policy protection, audit integrity, record count, console access, database credential. ## Language Plain language first, the engine's canonical value second and monospaced, so "Approval required" reads as English and VERIFY reads as a machine token. Neither replaces the other — the audit record is unchanged. Every status carries a glyph and a word, never colour alone; a console that encodes "failed" as red fails the people most likely to be reading it. A test asserts each of the four state kinds has a ::before glyph. `/` focuses the lookup, Escape closes the drawer and restores focus, polling pauses while the tab is hidden, and "last checked" is always visible. ## Hardening the client The security hook flagged innerHTML. Audited every interpolation: all pass through `esc()`, so there was no live XSS path — but two spots were fragile. `state()` interpolated its `kind` into a class attribute, where escaping does not protect; it is constrained to four known values now. `esc()` also covers single quotes. ## What is NOT done No screenshot or visual-regression job. That needs a headless browser in CI, and the trade-off is worth a decision rather than an assumption: layout and contrast are currently reviewed by eye. Recorded in docs/limitations.md. 220 tests pass (71 contract, 149 end-to-end), 6/6 scenarios. --- README.md | 6 +- console/app.py | 580 +++++++++++++++++++++-------------- console/static/aae.css | 316 +++++++++++++++++++ console/static/aae.js | 399 ++++++++++++++++++++++++ console/static/index.html | 151 +++++++++ docker/console.Dockerfile | 15 +- docs/architecture.md | 14 +- docs/limitations.md | 31 +- docs/security-model.md | 3 + tests/e2e/test_console.py | 30 +- tests/e2e/test_console_ui.py | 284 +++++++++++++++++ 11 files changed, 1570 insertions(+), 259 deletions(-) create mode 100644 console/static/aae.css create mode 100644 console/static/aae.js create mode 100644 console/static/index.html create mode 100644 tests/e2e/test_console_ui.py diff --git a/README.md b/README.md index 3d3e014..f010c44 100644 --- a/README.md +++ b/README.md @@ -81,9 +81,9 @@ python run.py scenarios 3. signs the ToolPack; 4. builds the containers; 5. applies the database migrations; -6. starts the control plane and dashboard. +6. starts the control plane and the assurance console. -The API and dashboard URLs are printed when startup completes. +The API and console URLs are printed when startup completes. ## Reference scenarios @@ -133,7 +133,7 @@ Every artifact is verified before installation and use. src/aae/ CLI, configuration, evidence and verification toolpacks/work_order/ Reference ToolPack db/workorders/ Example system-of-record schema -console/ Local demonstration dashboard +console/ Read-only assurance console docker/ Container definitions product/ Pinned REMORA artifacts and metadata tests/compatibility/ Core compatibility tests diff --git a/console/app.py b/console/app.py index 7049e9a..a3c8b6d 100644 --- a/console/app.py +++ b/console/app.py @@ -1,55 +1,112 @@ # Author: Stian Skogbrott # SPDX-License-Identifier: BUSL-1.1 -"""Operator console for Assured Agent Execution. - -Deliberately a separate, tiny service that **never imports remora**. It talks -to the control plane over HTTP exactly as any other client would, so nothing -about the demonstration surface can change the behaviour of the system being -demonstrated. It holds no policy and makes no decisions. - -It is **read-only**, and holds exactly one credential: the `viewer` token, -whose role grants `read` and nothing else. It cannot propose, approve or -execute, and there is no endpoint here that writes anything. - -That was not true of the first version. It held all five tokens — including -`domain_expert` and `senior_authority` — and exposed an unauthenticated POST -that ran the scenarios, which perform real writes under those roles. A -presentation surface with an approver credential is a high-value target -wearing a low-value label. - -Running the scenarios is a CLI action (`python run.py scenarios`), which is -where a privileged credential belongs. - -What it shows, and why each panel is on it: - - Posture which core is pinned, which surfaces are served, whether - ToolSpec enforcement is on, whether the audit chain verifies. - A console that only showed activity would let a deployment - look healthy while running unpinned and unenforced. - Decisions the four, each runnable, each showing the reasons the engine - gave rather than a green tick. - System of the work orders themselves, read on the READ-ONLY credential. - record Seeing the effect in the actual table is the difference - between believing the audit trail and checking it. +"""AAE Assurance Console — a read-only view of what the deployment enforced. + +A separate, small service that **never imports remora**. It talks to the +control plane over HTTP exactly as any other client would, so nothing about +the console can change the behaviour of the system it displays. + +It is read-only and holds exactly one credential: the `viewer` token, whose +role grants `read` and nothing else. No route here writes. + +That was not true of the first version. It held all five bearer tokens — +including `domain_expert` and `senior_authority` — and exposed an +unauthenticated POST that ran the scenarios, which perform real writes under +those roles. A presentation surface carrying an approver credential is a +high-value target wearing a low-value label. Running the scenarios is a CLI +action now, which is where a privileged credential belongs. + +Four surfaces: + + Overview is enforcement operational, does the audit verify, what + needs attention. A console showing only activity would + let a deployment look healthy while running unpinned. + Decisions look up a proposal: what was decided, why, who had to + approve it, and whether the effect was confirmed. + Business records the work orders, on the SELECT-only credential. Seeing + the change in the actual table is the difference between + believing the audit trail and checking it. + System assurance the technical evidence: verified engine, tool policy + protection, audit integrity, credential scope. + +This module does five things and no more: fetch, validate, serve static files, +report failure legibly, and set security headers. """ from __future__ import annotations import json import os +import uuid +from datetime import UTC, datetime +from pathlib import Path from typing import Any import httpx -from fastapi import FastAPI -from fastapi.responses import HTMLResponse, JSONResponse +from fastapi import FastAPI, Request +from fastapi.responses import FileResponse, JSONResponse +from fastapi.staticfiles import StaticFiles +from pydantic import BaseModel API = os.environ.get("AAE_API_URL", "http://control-plane:8000") + #: One credential, read-only. Anything this console cannot do with `viewer` #: is something it should not be doing. VIEWER_TOKEN = os.environ.get("AAE_TOKEN_VIEWER", "") READER_DSN = os.environ.get("AAE_WORKORDER_READER_DSN", "") -app = FastAPI(title="AAE Operator Console", docs_url=None, redoc_url=None) +STATIC = Path(__file__).parent / "static" +LOCK_FILE = Path(__file__).parent / "core-artifact-lock.json" + +app = FastAPI(title="AAE Assurance Console", docs_url=None, redoc_url=None) + + +# ── Security headers ─────────────────────────────────────────────────────── + +#: Everything is served from this origin: no CDN, no inline script, no inline +#: style, no frame, no form target. A console for a governance product should +#: not be able to load a third party's JavaScript even by accident. +_CSP = ("default-src 'self'; script-src 'self'; style-src 'self'; " + "img-src 'self' data:; object-src 'none'; frame-ancestors 'none'; " + "base-uri 'none'; form-action 'none'") + + +@app.middleware("http") +async def security_headers(request: Request, call_next): + response = await call_next(request) + response.headers["Content-Security-Policy"] = _CSP + response.headers["X-Content-Type-Options"] = "nosniff" + response.headers["Referrer-Policy"] = "no-referrer" + # This page shows governance state. A cached copy on a shared machine + # outlives the session that was entitled to see it. + response.headers["Cache-Control"] = "no-store" + return response + + +# ── Failure, reported rather than leaked ─────────────────────────────────── +class Problem(BaseModel): + """A failure a person can act on, and an id they can quote. + + Exception text goes to the log, never to the browser: it names internal + hosts, credentials and file paths, and a console is the wrong place to + disclose any of them. + """ + + error: str + correlation_id: str + + +def _problem(message: str, exc: Exception | None = None, + status: int = 503) -> JSONResponse: + correlation = uuid.uuid4().hex[:12] + if exc is not None: + print(f"[{correlation}] {type(exc).__name__}: {exc}", flush=True) + return JSONResponse( + Problem(error=message, correlation_id=correlation).model_dump(), + status_code=status) + + +# ── Upstream ─────────────────────────────────────────────────────────────── def _get(path: str) -> tuple[int, Any]: try: @@ -58,216 +115,267 @@ def _get(path: str) -> tuple[int, Any]: headers={"Authorization": f"Bearer {VIEWER_TOKEN}"}) return response.status_code, response.json() except Exception as exc: # noqa: BLE001 - return 0, {"error": f"{type(exc).__name__}: {exc}"} + print(f"upstream {path}: {type(exc).__name__}: {exc}", flush=True) + return 0, None + + +def _lock() -> dict[str, Any]: + try: + return json.loads(LOCK_FILE.read_text(encoding="utf-8")) + except OSError: + # Reported as unknown rather than absent. A console that silently + # showed nothing where the verified engine belongs looks fine while + # telling you less than it should — which is exactly what happened + # when this file stopped being copied into the image. + return {} + + +def _reader(): + import psycopg + from psycopg.rows import dict_row + + # autocommit: a reader has nothing to keep a transaction for, and one held + # open blocks pg_dump — which is how a scheduled backup hangs in silence. + return psycopg.connect(READER_DSN, row_factory=dict_row, + connect_timeout=5, autocommit=True) + + +def _clean(row: dict) -> dict: + return {k: (v.isoformat() if hasattr(v, "isoformat") else v) + for k, v in row.items()} + + +# ── Models ───────────────────────────────────────────────────────────────── + +class CoreIdentity(BaseModel): + version: str | None = None + commit: str | None = None + release: str | None = None + status: str | None = None + + +class AuditIntegrity(BaseModel): + checked: bool + verified: bool | None = None + records: int | None = None + + +class Assurance(BaseModel): + """Everything that decides whether the activity elsewhere means anything.""" + + reachable: bool + runtime_mode: str | None = None + capabilities: list[str] = [] + health: str | None = None + core: CoreIdentity = CoreIdentity() + tool_policy_enforced: bool = False + tool_policy_pinned: bool = False + audit: AuditIntegrity = AuditIntegrity(checked=False) + console_access: str = "read-only" + database_credential: str = "read-only" + checked_at: str + + +class Overview(BaseModel): + headline: str + all_clear: bool + attention: list[str] + assurance: Assurance + records: dict[str, int] -@app.get("/api/posture") -def posture() -> JSONResponse: - """Everything that decides whether the activity below means anything.""" +class WorkOrder(BaseModel): + wo_id: str + title: str + asset_id: str + status: str + priority: str + closed_reason: str | None = None + updated_by: str + updated_at: str + + +class RecordEvent(BaseModel): + wo_id: str + tool_name: str + actor: str + occurred_at: str + detail: dict[str, Any] = {} + + +class Records(BaseModel): + work_orders: list[WorkOrder] + events: list[RecordEvent] + open_count: int + closed_count: int + + +# ── Assurance ────────────────────────────────────────────────────────────── + +def _assurance() -> Assurance: status, root = _get("/") _, health = _get("/v1/health") chain_status, chain = _get("/v1/execution/audit/verify") - - lock: dict[str, Any] = {} + lock = _lock() + + return Assurance( + reachable=status == 200, + runtime_mode=(root or {}).get("runtime_mode"), + capabilities=(root or {}).get("surfaces", []), + health=(health or {}).get("status"), + core=CoreIdentity( + version=lock.get("remora_core_version"), + commit=(lock.get("remora_core_commit") or "")[:8] or None, + release=lock.get("release_tag"), + status=lock.get("release_status"), + ), + tool_policy_enforced=bool(os.environ.get("AAE_TOOLSPEC_CONFIGURED")), + tool_policy_pinned=bool(os.environ.get("AAE_TOOLSPEC_PINNED")), + audit=AuditIntegrity( + checked=chain_status == 200, + verified=(chain or {}).get("valid") if chain_status == 200 else None, + records=((chain or {}).get("records_checked") + if chain_status == 200 else None), + ), + checked_at=datetime.now(UTC).isoformat(timespec="seconds"), + ) + + +@app.get("/api/assurance", response_model=Assurance) +def assurance() -> Assurance: + return _assurance() + + +@app.get("/api/overview", response_model=Overview) +def overview() -> Any: + state = _assurance() + + # Only actual deviations. A list that always has entries is a list nobody + # reads. + attention: list[str] = [] + if not state.reachable: + attention.append("The control plane is not reachable.") + if state.runtime_mode and state.runtime_mode != "production": + attention.append(f"Running in {state.runtime_mode} mode: the " + f"fail-closed prerequisites are not binding.") + if not state.tool_policy_enforced: + attention.append("Tool policy protection is off: tool definitions are " + "not signature-checked.") + elif not state.tool_policy_pinned: + attention.append("Tool policy is signed but not pinned: a correctly " + "signed older definition would be accepted.") + if state.audit.checked and state.audit.verified is False: + attention.append("Audit integrity check FAILED.") + if not state.audit.checked: + attention.append("Audit integrity could not be checked.") + + counts = {"open": 0, "closed": 0, "cancelled": 0, "total": 0} try: - with open("/console/core-artifact-lock.json", encoding="utf-8") as fh: - lock = json.load(fh) - except OSError: - pass - - toolspec = {"configured": bool(os.environ.get("AAE_TOOLSPEC_CONFIGURED")), - "pinned": bool(os.environ.get("AAE_TOOLSPEC_PINNED"))} - - return JSONResponse({ - "reachable": status == 200, - "runtime_mode": root.get("runtime_mode"), - "surfaces": root.get("surfaces", []), - "health": health.get("status"), - "core": { - "version": lock.get("remora_core_version"), - "commit": (lock.get("remora_core_commit") or "")[:8], - "release": lock.get("release_tag"), - "status": lock.get("release_status"), - }, - "toolspec": toolspec, - "audit_chain": { - "checked": chain_status == 200, - "valid": chain.get("valid") if chain_status == 200 else None, - "records": chain.get("records_checked") if chain_status == 200 else None, - }, - }) - - -@app.get("/api/work-orders") -def work_orders() -> JSONResponse: - """The system of record, on the credential that cannot write it.""" + with _reader() as conn, conn.cursor() as cur: + cur.execute("SELECT status, count(*) AS n FROM work_orders " + "GROUP BY status") + for row in cur.fetchall(): + counts[row["status"]] = row["n"] + counts["total"] += row["n"] + except Exception as exc: # noqa: BLE001 + print(f"records: {type(exc).__name__}: {exc}", flush=True) + attention.append("Business records are not reachable.") + + all_clear = not attention + return Overview( + headline=("All enforcement controls are operational" if all_clear + else f"{len(attention)} control(s) need attention"), + all_clear=all_clear, + attention=attention, + assurance=state, + records=counts, + ) + + +# ── Business records ─────────────────────────────────────────────────────── + +@app.get("/api/records", response_model=Records) +def records() -> Any: if not READER_DSN: - return JSONResponse({"error": "no reader DSN configured"}, status_code=503) + return _problem("No database credential is configured for this console.") try: - import psycopg - from psycopg.rows import dict_row - - with psycopg.connect(READER_DSN, row_factory=dict_row, - connect_timeout=5, autocommit=True) as conn: - conn.read_only = True - with conn.cursor() as cur: - cur.execute( - "SELECT wo_id, title, asset_id, status, priority," - " closed_reason, updated_by, updated_at" - " FROM work_orders ORDER BY wo_id") - rows = cur.fetchall() - cur.execute( - "SELECT wo_id, tool_name, detail, occurred_at" - " FROM work_order_events ORDER BY event_id DESC LIMIT 20") - events = cur.fetchall() + with _reader() as conn, conn.cursor() as cur: + cur.execute( + "SELECT wo_id, title, asset_id, status, priority," + " closed_reason, updated_by, updated_at" + " FROM work_orders ORDER BY wo_id") + orders = [_clean(r) for r in cur.fetchall()] + cur.execute( + "SELECT wo_id, tool_name, actor, detail, occurred_at" + " FROM work_order_events ORDER BY event_id DESC LIMIT 50") + events = [_clean(r) for r in cur.fetchall()] except Exception as exc: # noqa: BLE001 - return JSONResponse({"error": f"{type(exc).__name__}: {exc}"}, - status_code=503) - - def clean(row: dict) -> dict: - return {k: (v.isoformat() if hasattr(v, "isoformat") else v) - for k, v in row.items()} - - return JSONResponse({"work_orders": [clean(r) for r in rows], - "events": [clean(r) for r in events]}) - - -_PAGE = """ -Assured Agent Execution — Operator Console - - -

Assured Agent Execution

-

Operator console. Holds no policy, makes no decisions, and imports -no REMORA module — it reads this deployment over HTTP like any other client.

- -

Posture

-
loading…
- -

These are the facts that decide whether anything below means -anything. A deployment can be busy and still be running unpinned, unenforced, -or with a chain that no longer verifies.

- -

The four decisions

-

Run them from a shell. This console is read-only and holds no -credential that could approve or execute — running the scenarios needs both.

-
python run.py scenarios
-

Then reload this page: the system of record below shows what -the run actually changed.

- -

System of record

-

Read on the read-only credential — the same one -the postcondition reader holds. Seeing the effect in the actual table is the -difference between believing the audit trail and checking it.

-
loading…
- -

Recent governed writes

-
loading…
- -

Read-only. This console holds one credential — the -viewer role, which grants read and nothing else — and -exposes no endpoint that writes. A real deployment puts an identity provider in -front of it; this local profile does not, which is why it binds to loopback.

- - -""" + return _problem("Business records are not reachable.", exc) + + return Records( + work_orders=[WorkOrder(**o) for o in orders], + events=[RecordEvent(**e) for e in events], + open_count=sum(1 for o in orders if o["status"] == "open"), + closed_count=sum(1 for o in orders if o["status"] == "closed"), + ) + + +# ── Decisions: look up a proposal ────────────────────────────────────────── +# +# A lookup, not a feed. The core returns a proposal when its id is known and +# cannot yet LIST proposals, and the business event log carries no proposal id +# because the dispatcher does not pass one to the tool. Assembling a "recent +# decisions" list from what is available would mean showing a reconstruction +# as though it were the record. See docs/limitations.md. + +def _proxy(path: str, missing: str) -> Any: + status, body = _get(path) + if status == 404: + return _problem(missing, status=404) + if status != 200: + return _problem("The control plane did not answer.") + return JSONResponse(body) + + +@app.get("/api/proposals/{proposal_id}") +def proposal(proposal_id: str) -> Any: + return _proxy(f"/v1/execution/proposals/{proposal_id}", + f"No proposal {proposal_id}.") + + +@app.get("/api/proposals/{proposal_id}/lifecycle") +def lifecycle(proposal_id: str) -> Any: + return _proxy(f"/v1/execution/proposals/{proposal_id}/lifecycle", + f"No lifecycle for {proposal_id}.") + + +@app.get("/api/proposals/{proposal_id}/evidence") +def evidence(proposal_id: str) -> Any: + return _proxy(f"/v1/execution/proposals/{proposal_id}/evidence", + f"No evidence bundle for {proposal_id}.") + + +# ── The old paths ────────────────────────────────────────────────────────── +# Kept so an existing bookmark or check resolves. They carry the CURRENT +# payload, not the old shape — a path answering with the old fields would be +# a compatibility promise this product is not making, and the terminology +# changed on purpose. + +@app.get("/api/posture", response_model=Assurance) +def posture() -> Assurance: + return _assurance() + + +@app.get("/api/work-orders", response_model=Records) +def work_orders() -> Any: + return records() + + +# ── Static ───────────────────────────────────────────────────────────────── + +app.mount("/assets", StaticFiles(directory=STATIC), name="assets") -@app.get("/", response_class=HTMLResponse) -def index() -> HTMLResponse: - return HTMLResponse(_PAGE) +@app.get("/") +def index() -> FileResponse: + return FileResponse(STATIC / "index.html", media_type="text/html") diff --git a/console/static/aae.css b/console/static/aae.css new file mode 100644 index 0000000..614bb52 --- /dev/null +++ b/console/static/aae.css @@ -0,0 +1,316 @@ +/* AAE Assurance Console + * + * A graphite enterprise shell: flat surfaces, thin borders, one accent. + * No gradients, no glow, no animated figures. Colour is never the only + * carrier of meaning — every status also has a glyph and a word, because a + * console that encodes "failed" as red alone fails for the people most likely + * to be reading it at 03:00. + * + * System fonts only. Monospace is reserved for identifiers, hashes and the + * engine's own canonical values, so that "VERIFY" reads as a machine token + * and "Approval required" reads as English. + * + * Contrast targets WCAG AA (4.5:1 for body text) on both themes. + */ + +:root { + color-scheme: dark light; + + --bg: #0e0f11; + --bg-raised: #16181b; + --bg-sunken: #0a0b0c; + --line: #26292e; + --line-strong: #3a3f46; + + --fg: #e8eaed; + --fg-dim: #a3a9b3; /* 7.1:1 on --bg */ + --fg-faint: #7b828d; /* 4.6:1 on --bg */ + + --accent: #6ea8fe; + --ok: #56d68a; + --warn: #e8b339; + --bad: #ff7b72; + + --radius: 6px; + --gap: 1rem; + --mono: ui-monospace, "SFMono-Regular", "Cascadia Mono", Menlo, Consolas, monospace; +} + +@media (prefers-color-scheme: light) { + :root { + --bg: #f7f8f9; + --bg-raised: #ffffff; + --bg-sunken: #eceef1; + --line: #d9dde2; + --line-strong: #b6bcc4; + --fg: #16181b; + --fg-dim: #4b525b; + --fg-faint: #6b727c; + --accent: #1f5fd0; + --ok: #12703c; + --warn: #8a5a00; + --bad: #b3261e; + } +} + +* { box-sizing: border-box; } + +body { + margin: 0; + background: var(--bg); + color: var(--fg); + font: 14px/1.55 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; +} + +.sr-only { + position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; + overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; border: 0; +} + +.skip { + position: absolute; left: -9999px; top: 0; z-index: 10; + background: var(--accent); color: #000; padding: .6rem 1rem; +} +.skip:focus { left: 0; } + +:focus-visible { + outline: 2px solid var(--accent); + outline-offset: 2px; +} + +/* ── Shell ─────────────────────────────────────────────────────────── */ + +.shell-head { + display: flex; align-items: center; justify-content: space-between; + gap: var(--gap); + padding: .7rem 1.25rem; + border-bottom: 1px solid var(--line); + background: var(--bg-raised); +} + +.brand { display: flex; align-items: center; gap: .6rem; } +.brand-mark { + width: 10px; height: 10px; border-radius: 2px; + background: var(--accent); flex: none; +} +.brand-name { font-weight: 600; letter-spacing: -.01em; } + +.chip { + font-size: .72rem; font-weight: 600; letter-spacing: .04em; + text-transform: uppercase; + padding: .15rem .45rem; border-radius: 3px; + border: 1px solid var(--line-strong); color: var(--fg-dim); +} +.chip-quiet { background: var(--bg-sunken); } + +.head-meta { font-size: .82rem; } + +.shell { + display: grid; + grid-template-columns: 208px minmax(0, 1fr); + min-height: calc(100vh - 49px); +} + +.nav { + display: flex; flex-direction: column; gap: 2px; + padding: 1rem .6rem; + border-right: 1px solid var(--line); + background: var(--bg-raised); +} + +.nav-item { + appearance: none; text-align: left; + font: inherit; color: var(--fg-dim); + background: none; border: 0; border-radius: var(--radius); + padding: .5rem .7rem; cursor: pointer; +} +.nav-item:hover { background: var(--bg-sunken); color: var(--fg); } +.nav-item.is-active { + background: var(--bg-sunken); color: var(--fg); font-weight: 600; + box-shadow: inset 2px 0 0 var(--accent); +} + +.surface { padding: 1.5rem 1.75rem 4rem; max-width: 1120px; } +.surface:focus { outline: none; } + +h2 { + font-size: .8rem; text-transform: uppercase; letter-spacing: .07em; + color: var(--fg-faint); font-weight: 600; + margin: 2rem 0 .7rem; +} +.panel > h2:first-child { margin-top: 0; } + +.lede { color: var(--fg-dim); margin: 0 0 1.2rem; max-width: 68ch; } +.muted { color: var(--fg-faint); } +.small { font-size: .82rem; } +code { font-family: var(--mono); font-size: .92em; } + +/* ── Status banner ─────────────────────────────────────────────────── */ + +.banner { + display: flex; gap: .85rem; align-items: flex-start; + padding: 1rem 1.15rem; + border: 1px solid var(--line); border-left-width: 3px; + border-radius: var(--radius); + background: var(--bg-raised); +} +.banner-icon { font-size: 1.1rem; line-height: 1.4; flex: none; } +.banner-title { margin: 0; font-size: 1.02rem; font-weight: 600; } +.banner-sub { margin: .2rem 0 0; color: var(--fg-dim); font-size: .88rem; } + +.banner-ok { border-left-color: var(--ok); } +.banner-warn { border-left-color: var(--warn); } +.banner-bad { border-left-color: var(--bad); } +.banner-loading { border-left-color: var(--line-strong); } + +/* ── Attention list ────────────────────────────────────────────────── */ + +.attention { list-style: none; margin: 0; padding: 0; display: grid; gap: .5rem; } +.attention li { + display: flex; gap: .6rem; align-items: baseline; + padding: .65rem .9rem; + border: 1px solid var(--line); border-left: 3px solid var(--warn); + border-radius: var(--radius); background: var(--bg-raised); +} +.attention li::before { content: "!"; color: var(--warn); font-weight: 700; } +.attention.is-clear li { + border-left-color: var(--ok); color: var(--fg-dim); +} +.attention.is-clear li::before { content: "\2713"; color: var(--ok); } + +/* ── Facts ─────────────────────────────────────────────────────────── */ + +.facts { + display: grid; grid-template-columns: repeat(auto-fit, minmax(230px, 1fr)); + gap: 1px; margin: 0; + background: var(--line); border: 1px solid var(--line); + border-radius: var(--radius); overflow: hidden; +} +.facts > div { background: var(--bg-raised); padding: .8rem 1rem; } +.facts dt { + font-size: .74rem; text-transform: uppercase; letter-spacing: .05em; + color: var(--fg-faint); +} +.facts dd { margin: .25rem 0 0; font-size: .98rem; font-weight: 600; } +.facts-wide { grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); } + +.state { display: inline-flex; align-items: baseline; gap: .4rem; } +.state::before { font-weight: 700; } +.state-ok::before { content: "\2713"; color: var(--ok); } +.state-warn::before { content: "!"; color: var(--warn); } +.state-bad::before { content: "\00d7"; color: var(--bad); } +.state-unknown::before { content: "?"; color: var(--fg-faint); } + +.canon { + display: block; font-family: var(--mono); font-size: .74rem; + color: var(--fg-faint); font-weight: 400; margin-top: .15rem; +} + +/* ── Tables ────────────────────────────────────────────────────────── */ + +.scroll-x { overflow-x: auto; border-radius: var(--radius); } +table { + width: 100%; border-collapse: collapse; font-size: .88rem; + background: var(--bg-raised); + border: 1px solid var(--line); border-radius: var(--radius); +} +th, td { + text-align: left; padding: .55rem .8rem; + border-bottom: 1px solid var(--line); + vertical-align: top; +} +th { + font-size: .72rem; text-transform: uppercase; letter-spacing: .05em; + color: var(--fg-faint); font-weight: 600; + background: var(--bg-sunken); +} +tbody tr:last-child td { border-bottom: 0; } +td.id, td.when { font-family: var(--mono); font-size: .82rem; white-space: nowrap; } +.empty td { color: var(--fg-faint); font-style: italic; } + +/* ── Lookup ────────────────────────────────────────────────────────── */ + +.lookup { display: flex; gap: .5rem; max-width: 620px; margin-bottom: .5rem; } +.lookup input { + flex: 1; font: inherit; font-family: var(--mono); font-size: .88rem; + padding: .55rem .7rem; + background: var(--bg-sunken); color: var(--fg); + border: 1px solid var(--line-strong); border-radius: var(--radius); +} +.lookup input::placeholder { font-family: system-ui, sans-serif; color: var(--fg-faint); } + +button { + font: inherit; font-weight: 600; + padding: .55rem 1.1rem; border-radius: var(--radius); + border: 1px solid var(--line-strong); + background: var(--bg-sunken); color: var(--fg); + cursor: pointer; +} +button:hover { border-color: var(--accent); } +.ghost { background: none; } + +/* ── Decision result ───────────────────────────────────────────────── */ + +.result { margin-top: 1.4rem; display: grid; gap: 1.1rem; } + +.decision-head { + border: 1px solid var(--line); border-left: 3px solid var(--line-strong); + border-radius: var(--radius); background: var(--bg-raised); + padding: 1rem 1.15rem; +} +.decision-head.d-allowed { border-left-color: var(--ok); } +.decision-head.d-approval { border-left-color: var(--warn); } +.decision-head.d-blocked { border-left-color: var(--fg-faint); } +.decision-head.d-authority { border-left-color: var(--bad); } + +.decision-title { margin: 0; font-size: 1.05rem; font-weight: 600; } +.decision-sub { margin: .3rem 0 0; color: var(--fg-dim); font-size: .9rem; } + +.timeline { list-style: none; margin: 0; padding: 0; display: grid; gap: 0; } +.timeline li { + display: grid; grid-template-columns: 84px minmax(0, 1fr); + gap: .8rem; padding: .6rem .9rem; + border: 1px solid var(--line); border-top: 0; background: var(--bg-raised); +} +.timeline li:first-child { border-top: 1px solid var(--line); border-radius: var(--radius) var(--radius) 0 0; } +.timeline li:last-child { border-radius: 0 0 var(--radius) var(--radius); } +.timeline .seq { font-family: var(--mono); font-size: .78rem; color: var(--fg-faint); } +.timeline .what { font-weight: 600; } +.timeline .why { color: var(--fg-dim); font-size: .86rem; } + +.problem { + border: 1px solid var(--line); border-left: 3px solid var(--bad); + border-radius: var(--radius); background: var(--bg-raised); + padding: .9rem 1.1rem; +} +.problem code { color: var(--fg-faint); } + +/* ── Drawer ────────────────────────────────────────────────────────── */ + +.drawer { + position: fixed; inset: 0 0 0 auto; width: min(560px, 100%); + background: var(--bg-raised); border-left: 1px solid var(--line-strong); + display: flex; flex-direction: column; z-index: 20; +} +.drawer-head { + display: flex; align-items: center; justify-content: space-between; + padding: .9rem 1.15rem; border-bottom: 1px solid var(--line); +} +.drawer-head h2 { margin: 0; } +.drawer-body { overflow: auto; padding: 1.15rem; } +.drawer-body pre { + background: var(--bg-sunken); border: 1px solid var(--line); + border-radius: var(--radius); padding: .9rem; + font-family: var(--mono); font-size: .78rem; line-height: 1.5; + overflow-x: auto; margin: 0 0 1rem; +} + +/* ── Narrow ────────────────────────────────────────────────────────── */ + +@media (max-width: 860px) { + .shell { grid-template-columns: 1fr; } + .nav { flex-direction: row; overflow-x: auto; border-right: 0; + border-bottom: 1px solid var(--line); } + .nav-item.is-active { box-shadow: inset 0 -2px 0 var(--accent); } + .surface { padding: 1.1rem; } +} diff --git a/console/static/aae.js b/console/static/aae.js new file mode 100644 index 0000000..b777db2 --- /dev/null +++ b/console/static/aae.js @@ -0,0 +1,399 @@ +/* AAE Assurance Console — read-only client. + * + * No framework, no build step, no external request. Every fetch below is a + * GET against this origin; the console has no route that writes, so there is + * nothing here that could be tricked into performing one. + * + * Two rules the rendering follows: + * + * Plain language first, the engine's own token second. "Approval required" + * is what a person needs; VERIFY is what the audit record says. Both are + * shown, and the canonical value is monospaced so it reads as a machine + * value rather than a sentence. + * + * Raw JSON is never the primary presentation. It lives in the drawer under + * "Technical evidence", one keystroke away and not in the way. + */ +"use strict"; + +const $ = (sel) => document.querySelector(sel); +const $$ = (sel) => Array.from(document.querySelectorAll(sel)); + +/* Plain language for the engine's canonical decisions. The canonical value is + * always shown alongside; this replaces nothing in the audit record. */ +const DECISION = { + accept: { label: "Allowed", cls: "d-allowed" }, + verify: { label: "Approval required", cls: "d-approval" }, + abstain: { label: "Blocked — insufficient evidence", cls: "d-blocked" }, + escalate: { label: "Higher authority required", cls: "d-authority" }, +}; + +const EFFECT = { + EFFECT_VERIFIED: { label: "Effect confirmed in the business record", state: "ok" }, + EFFECT_MISMATCH: { label: "Effect DID NOT match what was approved", state: "bad" }, + EFFECT_UNOBSERVABLE: { label: "Could not observe the effect", state: "unknown" }, + EFFECT_VERIFIER_FAILED: { label: "The verifier itself failed", state: "unknown" }, + EFFECT_UNSUPPORTED: { label: "No verification is declared for this tool", state: "unknown" }, +}; + +/* Every value that reaches innerHTML below passes through here. That is the + * invariant this file rests on: escape at the interpolation, not at the + * source, so a new field cannot be added without meeting it. Attributes are + * the exception — see KINDS. */ +const esc = (v) => String(v ?? "").replace(/[&<>"']/g, (c) => + ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c])); + +const when = (iso) => !iso ? "—" : String(iso).replace("T", " ").slice(0, 19); + +const shortId = (v) => { + const s = String(v ?? ""); + return /^[0-9a-f]{32,}$/i.test(s) ? s.slice(0, 8) + "…" : s; +}; + +/* The only four status kinds. Constrained rather than interpolated freely: + * `kind` lands inside a class attribute, and an attribute is the one place + * esc() does not protect on its own. Every caller passes a literal today — + * this keeps that true when one of them stops. */ +const KINDS = new Set(["ok", "warn", "bad", "unknown"]); + +function state(kind, text, canonical) { + const safeKind = KINDS.has(kind) ? kind : "unknown"; + return `${esc(text)}` + + (canonical ? `${esc(canonical)}` : ""); +} + +async function getJSON(path) { + const response = await fetch(path, { headers: { "Accept": "application/json" } }); + const body = await response.json().catch(() => null); + if (!response.ok) { + const message = body && body.error ? body.error : `Request failed (${response.status})`; + const ref = body && body.correlation_id ? body.correlation_id : null; + throw Object.assign(new Error(message), { correlationId: ref }); + } + return body; +} + +/* ── Navigation ───────────────────────────────────────────────────── */ + +function show(name) { + $$(".panel").forEach((p) => { p.hidden = p.id !== `s-${name}`; }); + $$(".nav-item").forEach((b) => { + const active = b.dataset.surface === name; + b.classList.toggle("is-active", active); + if (active) { b.setAttribute("aria-current", "page"); } + else { b.removeAttribute("aria-current"); } + }); + location.hash = name; + if (name === "records") { loadRecords(); } +} + +$$(".nav-item").forEach((b) => + b.addEventListener("click", () => show(b.dataset.surface))); + +/* ── Overview ─────────────────────────────────────────────────────── */ + +function renderBanner(data) { + const banner = $("#status-banner"); + const kind = !data ? "loading" : data.all_clear ? "ok" + : data.assurance && !data.assurance.reachable ? "bad" : "warn"; + banner.className = `banner banner-${kind}`; + banner.querySelector(".banner-icon").textContent = + { ok: "✓", warn: "!", bad: "×", loading: "…" }[kind]; + banner.querySelector(".banner-title").textContent = + data ? data.headline : "Checking enforcement controls"; + + if (!data) { $("#status-sub").textContent = ""; return; } + const a = data.assurance; + const bits = [ + a.audit.verified === true ? "Audit integrity verified" + : a.audit.verified === false ? "AUDIT INTEGRITY FAILED" + : "Audit integrity unknown", + a.tool_policy_pinned ? "Tool policies active and pinned" + : a.tool_policy_enforced ? "Tool policies active, not pinned" + : "Tool policies not enforced", + "Read-only console", + ]; + $("#status-sub").textContent = bits.join(" · "); +} + +function renderAttention(items) { + const list = $("#attention"); + list.classList.toggle("is-clear", items.length === 0); + list.innerHTML = items.length + ? items.map((t) => `
  • ${esc(t)}
  • `).join("") + : `
  • No deviations. Every control this console can check is in its expected state.
  • `; +} + +function renderBusiness(counts) { + $("#business-facts").innerHTML = ` +
    Open work orders
    ${counts.open ?? 0}
    +
    Closed
    ${counts.closed ?? 0}
    +
    Total records
    ${counts.total ?? 0}
    `; +} + +async function loadOverview() { + try { + const data = await getJSON("/api/overview"); + renderBanner(data); + renderAttention(data.attention); + renderBusiness(data.records); + renderAssurance(data.assurance); + $("#updated").textContent = `Last checked ${when(data.assurance.checked_at)}`; + return data; + } catch (err) { + renderBanner(null); + $("#status-banner").className = "banner banner-bad"; + $("#status-banner").querySelector(".banner-icon").textContent = "×"; + $("#status-banner").querySelector(".banner-title").textContent = + "This console cannot reach the control plane"; + $("#status-sub").textContent = err.message + + (err.correlationId ? ` (reference ${err.correlationId})` : ""); + $("#updated").textContent = "Not updated"; + } +} + +async function loadActivity() { + const body = $("#activity tbody"); + try { + const data = await getJSON("/api/records"); + const rows = data.events.slice(0, 8); + body.innerHTML = rows.length ? rows.map((e) => ` + ${esc(when(e.occurred_at))} + ${esc(e.wo_id)} + ${esc(actionLabel(e.tool_name))}${esc(e.tool_name)} + ${esc(e.actor)}`).join("") + : `No governed write has been recorded yet.`; + } catch (err) { + body.innerHTML = `${esc(err.message)}`; + } +} + +const ACTION = { + close_work_order: "Closed a work order", + create_work_order: "Opened a work order", + set_work_order_priority: "Changed priority", + read_work_order: "Read a work order", + purge_work_order_history: "Purged history", +}; +const actionLabel = (tool) => ACTION[tool] || tool; + +/* ── Business records ─────────────────────────────────────────────── */ + +function describeChange(detail) { + if (!detail || typeof detail !== "object") { return "—"; } + if ("from" in detail && "to" in detail) { return `${detail.from} → ${detail.to}`; } + if ("reason" in detail) { return String(detail.reason); } + if ("title" in detail) { return String(detail.title); } + const keys = Object.keys(detail); + return keys.length ? keys.map((k) => `${k}: ${detail[k]}`).join(", ") : "—"; +} + +async function loadRecords() { + const orders = $("#records tbody"); + const history = $("#history tbody"); + try { + const data = await getJSON("/api/records"); + orders.innerHTML = data.work_orders.length ? data.work_orders.map((w) => ` + ${esc(w.wo_id)} + ${esc(w.title)} + ${esc(w.asset_id)} + ${state(w.status === "closed" ? "ok" : "unknown", w.status)} + ${esc(w.priority)} + ${esc(w.updated_by)} + ${esc(when(w.updated_at))}`).join("") + : `No work orders.`; + + history.innerHTML = data.events.length ? data.events.map((e) => ` + ${esc(when(e.occurred_at))} + ${esc(e.wo_id)} + ${esc(actionLabel(e.tool_name))}${esc(e.tool_name)} + ${esc(describeChange(e.detail))}`).join("") + : `Nothing has been changed through a governed path yet.`; + } catch (err) { + const cell = `${esc(err.message)}`; + orders.innerHTML = cell; + history.innerHTML = cell; + } +} + +/* ── System assurance ─────────────────────────────────────────────── */ + +function renderAssurance(a) { + if (!a) { return; } + const core = a.core || {}; + const audit = a.audit || {}; + $("#assurance-facts").innerHTML = ` +
    Control plane
    ${a.reachable + ? state("ok", a.health === "ok" ? "Operational" : String(a.health || "Reachable")) + : state("bad", "Not reachable")}
    + +
    Runtime mode
    ${a.runtime_mode === "production" + ? state("ok", "Production") + : state("warn", a.runtime_mode || "Unknown")}
    + +
    Enabled capability
    ${state( + (a.capabilities || []).includes("assess") ? "warn" : "ok", + (a.capabilities || []).join(", ") || "Unknown", + "REMORA_ENABLED_SURFACES")}
    + +
    Verified engine
    ${core.version + ? state("ok", `REMORA ${core.version}`, `commit ${core.commit}`) + : state("unknown", "Not reported")}
    + +
    Engine release
    ${core.release + ? state(core.status === "stable" ? "ok" : "warn", + core.release, core.status || "") + : state("unknown", "Not reported")}
    + +
    Tool policy protection
    ${ + a.tool_policy_pinned ? state("ok", "Signed and pinned") + : a.tool_policy_enforced ? state("warn", "Signed, not pinned") + : state("bad", "Not enforced")}
    + +
    Audit integrity
    ${ + audit.verified === true ? state("ok", "Verified") + : audit.verified === false ? state("bad", "Verification FAILED") + : state("unknown", "Not checked")}
    + +
    Verified audit records
    ${ + audit.records != null ? esc(audit.records) : state("unknown", "Unknown")}
    + +
    Console access
    ${state("ok", "Read-only", "viewer")}
    + +
    Database credential
    ${state("ok", "Read-only", "aae_reader")}
    `; +} + +/* ── Decisions ────────────────────────────────────────────────────── */ + +function problem(message, ref) { + return `

    ${esc(message)}

    ` + + (ref ? `

    Reference ${esc(ref)}

    ` : "") + + `
    `; +} + +function renderDecision(id, proposal, lifecycle) { + const canonical = String(proposal.decision || "").toLowerCase(); + const meaning = DECISION[canonical] || { label: canonical || "Unknown", cls: "" }; + const effect = proposal.effect && proposal.effect.status + ? EFFECT[proposal.effect.status] : null; + + const reasons = (proposal.reasons || []).length + ? `

    Because: ${esc((proposal.reasons || []).join(", "))}

    ` : ""; + + const head = ` +
    +

    ${esc(meaning.label)}

    +

    + ${esc(proposal.tool_name || "unknown tool")} + · proposal ${esc(shortId(id))} + · state ${esc(proposal.current_state || "?")} +

    + ${reasons} +

    ${esc(canonical.toUpperCase())}

    +
    `; + + const effectBlock = effect ? ` +
    +
    Effect verification
    +
    ${state(effect.state, effect.label, proposal.effect.status)}
    +
    ` : ""; + + const events = (lifecycle && lifecycle.events) || []; + const timeline = events.length ? `` : `

    No lifecycle events recorded.

    `; + + return `${head}${effectBlock} +

    What happened, in order

    ${timeline} +

    `; +} + +async function lookup(id) { + const target = $("#decision-result"); + target.innerHTML = `

    Looking up ${esc(shortId(id))}…

    `; + try { + const proposal = await getJSON(`/api/proposals/${encodeURIComponent(id)}`); + let lifecycle = null; + try { lifecycle = await getJSON(`/api/proposals/${encodeURIComponent(id)}/lifecycle`); } + catch { /* a proposal without a readable trail still renders */ } + target.innerHTML = renderDecision(id, proposal, lifecycle); + const button = $("#show-evidence"); + if (button) { button.addEventListener("click", () => openEvidence(id)); } + } catch (err) { + target.innerHTML = problem(err.message, err.correlationId); + } +} + +$("#lookup").addEventListener("submit", (event) => { + event.preventDefault(); + const id = $("#pid").value.trim(); + if (id) { lookup(id); } +}); + +/* ── Drawer ───────────────────────────────────────────────────────── */ + +let lastFocus = null; + +async function openEvidence(id) { + lastFocus = document.activeElement; + const drawer = $("#drawer"); + $("#drawer-body").innerHTML = `

    Loading…

    `; + drawer.hidden = false; + $("#drawer-close").focus(); + try { + const bundle = await getJSON(`/api/proposals/${encodeURIComponent(id)}/evidence`); + $("#drawer-body").innerHTML = + `
    ${esc(JSON.stringify(bundle, null, 2))}
    `; + } catch (err) { + $("#drawer-body").innerHTML = problem(err.message, err.correlationId); + } +} + +function closeDrawer() { + $("#drawer").hidden = true; + if (lastFocus) { lastFocus.focus(); } +} + +$("#drawer-close").addEventListener("click", closeDrawer); + +document.addEventListener("keydown", (event) => { + if (event.key === "Escape" && !$("#drawer").hidden) { closeDrawer(); return; } + if (event.key === "/" && document.activeElement.tagName !== "INPUT") { + event.preventDefault(); + show("decisions"); + $("#pid").focus(); + } +}); + +/* ── Refresh ──────────────────────────────────────────────────────── */ + +async function refresh() { + await loadOverview(); + await loadActivity(); + if (!$("#s-records").hidden) { loadRecords(); } +} + +/* Paused while the tab is hidden: a console polling a governance API from a + * forgotten background tab is noise in someone's audit log. */ +let timer = null; +function startPolling() { + stopPolling(); + timer = setInterval(refresh, 15000); +} +function stopPolling() { + if (timer) { clearInterval(timer); timer = null; } +} +document.addEventListener("visibilitychange", () => { + if (document.hidden) { stopPolling(); } else { refresh(); startPolling(); } +}); + +const initial = (location.hash || "#overview").slice(1); +show(["overview", "decisions", "records", "assurance"].includes(initial) + ? initial : "overview"); +refresh(); +startPolling(); diff --git a/console/static/index.html b/console/static/index.html new file mode 100644 index 0000000..675aa2b --- /dev/null +++ b/console/static/index.html @@ -0,0 +1,151 @@ + + + + + + +AAE Assurance Console + + + + + + +
    +
    + + Assured Agent Execution + Read-only +
    +
    + Loading… +
    +
    + +
    + + +
    + + +
    + + +
    +

    Needs attention

    +
      +
      + +
      +

      Business state

      +
      +
      + +
      +

      Recent verified actions

      +
      + + + + + + + +
      Most recent governed writes to the system of record
      WhenRecordActionBy
      +
      +
      +
      + + + + + + + + + + +
      +
      + + + + + + diff --git a/docker/console.Dockerfile b/docker/console.Dockerfile index f4128a9..a923338 100644 --- a/docker/console.Dockerfile +++ b/docker/console.Dockerfile @@ -1,4 +1,4 @@ -# Operator console for Assured Agent Execution. +# AAE Assurance Console — read-only. # # A separate, deliberately small image: fastapi, httpx, psycopg. No REMORA # wheel, no product package. @@ -13,8 +13,8 @@ FROM python:3.12-slim -LABEL org.opencontainers.image.title="Assured Agent Execution — Operator Console" \ - org.opencontainers.image.description="Read-mostly operator surface: deployment posture, the four decisions, and the system of record on a read-only credential. Holds no policy and makes no decisions." \ +LABEL org.opencontainers.image.title="AAE Assurance Console" \ + org.opencontainers.image.description="Read-only assurance console: enforcement status, governed decisions and business records, on a viewer token and a SELECT-only database credential. Holds no policy, makes no decisions, and exposes no route that writes." \ org.opencontainers.image.source="https://github.com/darklordVirtual/assured-agent-execution" \ org.opencontainers.image.licenses="BUSL-1.1" \ org.opencontainers.image.vendor="Stian Skogbrott" @@ -30,7 +30,16 @@ RUN pip install --upgrade pip \ && pip install "fastapi>=0.115" "uvicorn[standard]>=0.30" "httpx>=0.27" \ "psycopg[binary]>=3.1" +# The artifact lock, and nothing else from product/. It is 30 lines of JSON +# naming which core release this deployment verified — the console reports it +# on the assurance surface, and reported it EMPTY once the wheel was removed +# from this image and the file went with it. +# +# Copying it back does not reintroduce the REMORA dependency: it is data the +# console reads, not a package it imports. +COPY product/core-artifact-lock.json /console/core-artifact-lock.json COPY console/app.py /console/app.py +COPY console/static /console/static RUN useradd --create-home --uid 10001 console && chown -R console:console /console USER console diff --git a/docs/architecture.md b/docs/architecture.md index 84a5628..905a3e5 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -50,8 +50,18 @@ assumed — see [limitations.md](limitations.md#parallel-declarations). act on. Separate so the effect reader can hold a credential that cannot write it. See [adr/0002-separate-reader-credential.md](adr/0002-separate-reader-credential.md). -**Postcondition reader** — runs in the CLI or the dashboard, not in the -control plane. Declares the expected delta from the approved arguments, reads +**Assurance console** — a read-only surface over four questions: is +enforcement operational, what was decided about a given proposal, what the +business records say, and what technical evidence backs any of it. FastAPI +serving typed JSON and three static files; no framework, no build step, and +every asset from this origin under a strict Content-Security-Policy. + +It holds one credential — `viewer` — and exposes no route that writes. +Decisions is a *lookup*, not a feed, because the core cannot list proposals +and the event log carries no proposal id; see +[limitations.md](limitations.md). + +**Postcondition reader** — runs in the CLI, not in the control plane. Declares the expected delta from the approved arguments, reads the target, compares only the declared fields. ## Data flow diff --git a/docs/limitations.md b/docs/limitations.md index 5a51c44..cbd05f8 100644 --- a/docs/limitations.md +++ b/docs/limitations.md @@ -26,6 +26,24 @@ and nothing calls it at dispatch. types from `remora.toolcall.*`. Pinned symbol-by-symbol so an upstream change fails in CI rather than in a deployment. +**No way to list proposals.** The core returns a proposal when its identifier +is known and offers no paginated listing, so the console's Decisions surface is +a lookup rather than a feed. It cannot be reconstructed locally either: the +business event log carries no proposal id, because the dispatcher passes none +to the tool. Assembling a "recent decisions" list from what is available would +mean showing a reconstruction as though it were the record. + +The contract this needs: + +``` +GET /v1/execution/proposals?limit=50&cursor=…&decision=verify&state=review_pending +``` + +Read access, tenant-isolated, cursor-paginated, projected from the audit chain +rather than a second source of truth, frozen in OpenAPI and exposed as +`list_proposals()` in the SDK. Once that is pinned in a core release, Decisions +can show recent activity, pending attention and filtering. + **No versioned migrations for the core schema.** REMORA's tables are created lazily at first use, so they cannot be pre-provisioned or reviewed before an upgrade. Only the *product's* schema is migrated here. @@ -54,14 +72,19 @@ REMORA wheel is byte-pinned; base images are tags, not digests, and the Python dependencies are floors rather than a lockfile. `python run.py sbom` records what a given build actually contained, which is a record, not reproducibility. -**The dashboard is a demonstration surface.** It is read-only and holds only -the `viewer` token — it cannot propose, approve or execute — but it has no -login, no CSRF protection, no rate limit and no per-user audit trail. It binds -to loopback and is not an operator console. +**The assurance console has no user identity.** It is read-only and holds only +the `viewer` token — it cannot propose, approve or execute, and exposes no +route that writes — but there is no login, no per-user audit trail and no +authorization beyond the deployment's own network boundary. It binds to +loopback. Anyone who can reach the port sees everything it shows. An earlier version held all five tokens and exposed an unauthenticated POST that ran the scenarios under approver roles. Running them is a CLI action now. +**No screenshot or visual regression testing.** The console's contracts are +asserted over HTTP and against the static files; nothing renders a browser, so +layout and contrast are reviewed by eye rather than by CI. + **No signed image, no build provenance, no external security review.** The pinned core is a deliberate prerelease. diff --git a/docs/security-model.md b/docs/security-model.md index 83e1fe6..72be6cc 100644 --- a/docs/security-model.md +++ b/docs/security-model.md @@ -19,6 +19,9 @@ checks is a comment; a declaration presented as a control is worse. | Containers hold no capabilities, no writable root, bounded memory and PIDs | compose | `test_hardening.py`, against `docker inspect` | | Nothing is published beyond loopback | `127.0.0.1` port bindings | `test_published_ports_bind_loopback_only` | | The pinned core is what it claims | seven SHA-256 digests | `verify_core_pin.py`, refuses on mismatch | +| The console cannot act | one `viewer` token, no mutating route, no REMORA package in its image | `test_console.py` | +| The console page loads nothing third-party | `Content-Security-Policy: default-src 'self'`, and every asset self-hosted | `test_console_ui.py` | +| Console failures disclose no internals | a sentence and a correlation id; exception text goes to the log | `test_a_failure_never_returns_exception_text` | ## Declared, not enforced diff --git a/tests/e2e/test_console.py b/tests/e2e/test_console.py index 9056a5c..1ef48c4 100644 --- a/tests/e2e/test_console.py +++ b/tests/e2e/test_console.py @@ -114,24 +114,32 @@ def test_the_dashboard_exposes_no_mutating_route(live, method: str) -> None: # ── It still does its job ────────────────────────────────────────────────── -def test_the_posture_panel_still_reports(live) -> None: - """Dropping four tokens must not have cost the dashboard its purpose.""" +def test_the_assurance_panel_still_reports(live) -> None: + """Dropping four tokens must not have cost the dashboard its purpose. + + `/api/posture` is the old path kept so an existing bookmark resolves; it + now carries the current payload, which uses product terminology rather + than the engine's internal names. A path that answered with the OLD shape + would be a compatibility promise this product is not making. + """ import httpx - posture = httpx.get(f"{_console_url(live)}/api/posture", timeout=15).json() - assert posture["reachable"] is True - assert posture["runtime_mode"] == "production" - assert posture["surfaces"] == ["execution"] - assert posture["audit_chain"]["valid"] is True - assert posture["toolspec"]["pinned"] is True + for path in ("/api/assurance", "/api/posture"): + body = httpx.get(f"{_console_url(live)}{path}", timeout=15).json() + assert body["reachable"] is True, path + assert body["runtime_mode"] == "production", path + assert body["capabilities"] == ["execution"], path + assert body["audit"]["verified"] is True, path + assert body["tool_policy_pinned"] is True, path def test_the_records_panel_still_reports(live) -> None: import httpx - body = httpx.get(f"{_console_url(live)}/api/work-orders", timeout=15).json() - assert len(body["work_orders"]) >= 4 - assert "events" in body + for path in ("/api/records", "/api/work-orders"): + body = httpx.get(f"{_console_url(live)}{path}", timeout=15).json() + assert len(body["work_orders"]) >= 4, path + assert "events" in body, path # ── The image itself ─────────────────────────────────────────────────────── diff --git a/tests/e2e/test_console_ui.py b/tests/e2e/test_console_ui.py new file mode 100644 index 0000000..c4d56bf --- /dev/null +++ b/tests/e2e/test_console_ui.py @@ -0,0 +1,284 @@ +# Author: Stian Skogbrott +# SPDX-License-Identifier: BUSL-1.1 +"""The console's presentation and API contracts. + +``test_console.py`` holds the security invariants — one token, no writes, no +REMORA in the image. This file covers what the redesign added: security +headers, self-hosted assets, the read-only API shape, and the failure states. + +The theme running through it: a console for a governance product must not +show something it cannot substantiate, and must not hide a failure behind an +empty panel. +""" +from __future__ import annotations + +import os +import re +from pathlib import Path + +import pytest + +pytestmark = pytest.mark.usefixtures("live") + +ROOT = Path(__file__).resolve().parents[2] +STATIC = ROOT / "console" / "static" + + +def _base() -> str: + return f"http://127.0.0.1:{os.getenv('AAE_CONSOLE_PORT', '8089')}" + + +def _get(path: str, **kwargs): + import httpx + + return httpx.get(f"{_base()}{path}", timeout=20, **kwargs) + + +# ── Security headers ─────────────────────────────────────────────────────── + +@pytest.mark.parametrize("header, expected", [ + ("x-content-type-options", "nosniff"), + ("referrer-policy", "no-referrer"), + ("cache-control", "no-store"), +]) +def test_security_headers_are_present(header: str, expected: str) -> None: + assert _get("/").headers.get(header, "").lower() == expected + + +@pytest.mark.parametrize("directive", [ + "default-src 'self'", "script-src 'self'", "style-src 'self'", + "object-src 'none'", "frame-ancestors 'none'", "base-uri 'none'", + "form-action 'none'", +]) +def test_the_content_security_policy_confines_the_page(directive: str) -> None: + """No CDN, no inline script, no frame, no form target. + + A console for a governance product should not be able to load a third + party's JavaScript even by accident, and `form-action 'none'` means no + markup here can post anywhere at all. + """ + assert directive in _get("/").headers.get("content-security-policy", "") + + +def test_cache_control_keeps_governance_state_off_disk() -> None: + """A cached copy on a shared machine outlives the session entitled to it.""" + for path in ("/", "/api/overview", "/api/records"): + assert _get(path).headers.get("cache-control") == "no-store", path + + +# ── Assets are ours ──────────────────────────────────────────────────────── + +@pytest.mark.parametrize("asset", ["/assets/aae.css", "/assets/aae.js"]) +def test_the_assets_are_served_from_this_origin(asset: str) -> None: + assert _get(asset).status_code == 200 + + +def test_no_static_file_references_an_external_host() -> None: + """The CSP would block it — this fails earlier, with a better message. + + A stylesheet importing a font from a CDN turns a page that renders into a + page that renders inconsistently and phones home, and the CSP failure + would surface as a silently missing font rather than as this. + """ + external = re.compile(r"""https?://(?!localhost|127\.0\.0\.1)""") + for path in STATIC.iterdir(): + if path.is_file(): + hits = external.findall(path.read_text(encoding="utf-8")) + assert not hits, f"{path.name} references an external host" + + +def test_the_page_loads_only_its_own_assets() -> None: + html = _get("/").text + for reference in re.findall(r'(?:href|src)="([^"]+)"', html): + assert reference.startswith("/assets/") or reference.startswith("#"), ( + f"the page loads {reference}, which is not one of its own assets") + + +# ── The read-only API ────────────────────────────────────────────────────── + +def test_assurance_reports_the_verified_engine() -> None: + """The regression this redesign started from. + + Stripping REMORA out of the console image took the artifact lock with it, + and the verified engine version silently became empty — a console looking + fine while telling you less than it should. + """ + core = _get("/api/assurance").json()["core"] + assert core["version"], "the verified engine version is not reported" + assert core["commit"], "the verified engine commit is not reported" + assert core["release"], "the engine release is not reported" + + +def test_assurance_states_that_this_console_cannot_act() -> None: + body = _get("/api/assurance").json() + assert body["console_access"] == "read-only" + assert body["database_credential"] == "read-only" + + +def test_overview_reports_no_attention_items_on_a_healthy_deployment() -> None: + """The attention list must contain only actual deviations. + + A list that always has entries is a list nobody reads, which is how a real + finding gets missed. + """ + body = _get("/api/overview").json() + assert body["attention"] == [], body["attention"] + assert body["all_clear"] is True + assert "operational" in body["headline"].lower() + + +def test_overview_counts_the_business_records() -> None: + counts = _get("/api/overview").json()["records"] + assert counts["total"] >= 4 + assert counts["total"] == counts["open"] + counts["closed"] + counts["cancelled"] + + +def test_records_returns_typed_rows_not_raw_database_output() -> None: + body = _get("/api/records").json() + assert body["work_orders"], "no work orders returned" + first = body["work_orders"][0] + assert set(first) == { + "wo_id", "title", "asset_id", "status", "priority", + "closed_reason", "updated_by", "updated_at", + } + assert body["open_count"] + body["closed_count"] <= len(body["work_orders"]) + + +# ── Proposal lookup ──────────────────────────────────────────────────────── + +@pytest.fixture() +def a_proposal(agent) -> str: + from remora.sdk import ToolCall + + result = agent.assess(ToolCall( + tool_name="read_work_order", arguments={"wo_id": "WO-1201"}, + target_environment="staging", intent_ref="WO-1201")) + return result.proposal_id + + +@pytest.mark.slow +@pytest.mark.parametrize("suffix", ["", "/lifecycle", "/evidence"]) +def test_a_known_proposal_can_be_inspected(a_proposal: str, suffix: str) -> None: + response = _get(f"/api/proposals/{a_proposal}{suffix}") + assert response.status_code == 200, response.text + assert response.json() + + +def test_an_unknown_proposal_answers_404_with_a_usable_message() -> None: + response = _get("/api/proposals/does-not-exist") + assert response.status_code == 404 + body = response.json() + assert "does-not-exist" in body["error"] + assert body["correlation_id"] + + +def test_a_failure_never_returns_exception_text(monkeypatch) -> None: + """Exception text names internal hosts, credentials and file paths. + + The browser gets a sentence and an id; the detail goes to the log, where + an operator can find it by that id. + """ + body = _get("/api/proposals/definitely-not-here").json() + for leak in ("Traceback", "psycopg", "httpx", "control-plane:8000", + "postgresql://"): + assert leak not in body["error"], f"{leak!r} leaked to the browser" + + +# ── Presentation contracts ───────────────────────────────────────────────── + +def test_the_page_names_the_four_surfaces() -> None: + html = _get("/").text + for surface in ("Overview", "Decisions", "Business records", + "System assurance"): + assert surface in html, f"{surface} is missing from the shell" + + +def test_the_page_offers_no_control_that_could_act() -> None: + """No approve, execute or run BUTTON on a console holding `viewer`. + + Checks interactive elements, not prose: the Decisions surface legitimately + explains "who had to approve it", and a word-match would forbid describing + the very thing the console exists to display. What must not exist is a + control inviting a click that can only end in a permission error. + """ + html = _get("/").text + controls = re.findall(r"]*>(.*?)", html, re.S | re.I) + for label in controls: + text = re.sub(r"<[^>]+>", "", label).strip().lower() + assert not any(verb in text for verb in + ("approve", "execute", "reject", "run ", "delete")), ( + f"the page offers a control labelled {text!r}") + + # And no form that posts anywhere: the CSP forbids it, this names it. + assert not re.search(r']+method\s*=\s*"?post', html, re.I) + for action in re.findall(r']+action="([^"]*)"', html, re.I): + assert not action, f"a form targets {action!r}" + + +def test_the_client_states_plain_language_before_canonical_values() -> None: + """`VERIFY` is what the audit record says; "Approval required" is what a + person needs. Both are shown, and neither replaces the other.""" + script = (STATIC / "aae.js").read_text(encoding="utf-8") + for canonical, plain in ( + ("accept", "Allowed"), + ("verify", "Approval required"), + ("abstain", "Blocked"), + ("escalate", "Higher authority required"), + ): + assert canonical in script and plain in script + + +def test_every_status_carries_a_glyph_and_not_only_colour() -> None: + """A console that encodes "failed" as red alone fails the people most + likely to be reading it.""" + css = (STATIC / "aae.css").read_text(encoding="utf-8") + for kind in ("ok", "warn", "bad", "unknown"): + assert re.search(rf"\.state-{kind}::before\s*{{[^}}]*content:", css), ( + f"state-{kind} has no glyph") + + +# ── Degraded ─────────────────────────────────────────────────────────────── + +@pytest.mark.slow +def test_a_control_plane_outage_is_stated_not_hidden() -> None: + """The failure mode that matters most on an assurance surface. + + A console that renders an empty panel when the thing it assures is down + looks calm and says nothing. This one names the outage, counts it, and + still answers 200 so the page can render the rest. + """ + import subprocess + + subprocess.run(["docker", "compose", "stop", "control-plane"], + cwd=ROOT, capture_output=True, timeout=120) + try: + response = _get("/api/overview") + assert response.status_code == 200, "the page could not render at all" + body = response.json() + assert body["all_clear"] is False + assert any("not reachable" in item for item in body["attention"]), ( + body["attention"]) + assert "attention" in body["headline"].lower() + assert body["assurance"]["reachable"] is False + finally: + subprocess.run(["docker", "compose", "start", "control-plane"], + cwd=ROOT, capture_output=True, timeout=180) + import time + + for _ in range(45): + probe = subprocess.run( + ["docker", "compose", "ps", "--format", "{{.Health}}", + "control-plane"], cwd=ROOT, capture_output=True, text=True) + if probe.stdout.strip().splitlines()[:1] == ["healthy"]: + break + time.sleep(2) + + +def test_records_stay_readable_when_the_control_plane_is_gone() -> None: + """They come from a different process on a different credential. + + One being down must not blank the other; an operator during an incident + needs whichever half still answers. + """ + body = _get("/api/records").json() + assert body["work_orders"] From 15fd93db92ebc788189daa38f59e2a40c2899259 Mon Sep 17 00:00:00 2001 From: darklordVirtual Date: Thu, 6 Aug 2026 13:13:48 +0200 Subject: [PATCH 2/2] docs: add SECURITY.md before the repository goes public MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A public repository about governing agent actions needs a stated place to send findings, and a stated scope. The scope section is the part worth writing carefully. In scope is bypassing any control docs/security-model.md says is ENFORCED — and that document already separates enforced from merely declared, so the two documents agree by construction rather than by maintenance. Out of scope is the pinned core itself, which has its own repository, and anything already in docs/limitations.md — though a demonstration that a listed gap is worse than described is very much a finding. It also states plainly that there are no credentials in this repository, and that a committed credential would itself be a finding. Verified before publishing: `.env` has never been committed, and a scan of every commit for key-shaped strings returns nothing but the generator and test fixtures. --- README.md | 7 ++++++ SECURITY.md | 68 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 75 insertions(+) create mode 100644 SECURITY.md diff --git a/README.md b/README.md index f010c44..a8d25e8 100644 --- a/README.md +++ b/README.md @@ -166,6 +166,13 @@ python run.py reset # Stop and remove all volumes * [Attack the demo](docs/tutorials/attack-the-demo.md) — try to get past the controls * [Decision records](docs/adr/) — why the architecture is the way it is +## Security + +Report suspected vulnerabilities to support@luftfiber.no rather than in a +public issue. [SECURITY.md](SECURITY.md) states the scope; +[docs/security-model.md](docs/security-model.md) states control by control +what is enforced and what is only declared. + ## Non-claims AAE does not claim that agents are always correct, that all tools can be diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..6f7fe21 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,68 @@ +# Security + +## Reporting a vulnerability + +Email **support@luftfiber.no**. Please do not open a public issue for a +suspected vulnerability. + +Include what you did, what happened, and what you expected. A proposal id, a +correlation id from the console, or the output of `python run.py doctor` is +usually enough to reproduce. + +This is a pre-1.0 reference vertical maintained by one person. There is no +paid bounty and no guaranteed response window; findings are still welcome and +will be credited unless you prefer otherwise. + +## What this project claims + +Assured Agent Execution governs AI-agent tool calls through a pinned REMORA +core. [docs/security-model.md](docs/security-model.md) states, control by +control, what is **enforced** and by what — and separately, what is only +**declared**. If you find a control that is weaker than the document says, that +is a finding, and it is the kind we most want to hear about. + +[docs/limitations.md](docs/limitations.md) lists what is known to be missing. +Anything there is a documented gap, not a vulnerability report — though a +demonstration that a listed gap is worse than described certainly is. + +## What this project does not claim + +No external security review has been performed. AAE does not claim that agents +are always correct, that all tools can be effect-verified, that safety is +guaranteed, or that bypass is impossible when an agent retains direct tool +credentials. + +The local deployment profile is a **reference vertical**. It binds to +loopback, generates its own credentials, and is not hardened for exposure to a +network. Do not run it where untrusted parties can reach it. + +## Scope + +In scope: + +- Bypassing a control the security model says is enforced — payload binding, + role separation, single-use grants, the read-only verifier credential, + ToolSpec signature or digest pinning, the import boundary. +- Getting the console to write anything, or to disclose a credential. +- Making the pin verification accept an artifact it should refuse. +- Anything that lets a governed action execute without leaving an audit + record, or leave one that misstates what happened. + +Out of scope: + +- The pinned REMORA core itself — report those to + [REMORA-research](https://github.com/darklordVirtual/REMORA-research). +- The reference work-order ToolPack treated as production software. It is an + example integration with deliberately small, readable tools. +- Denial of service against a loopback-bound local deployment. +- Anything already listed in [docs/limitations.md](docs/limitations.md). + +## Credentials in this repository + +There are none. `python run.py up` generates this installation's signing keys, +database passwords and bearer tokens into `.env`, which is gitignored and has +never been committed. The signed ToolSpec bundle is generated per install and +is not tracked either. + +If you believe a credential has been committed, that is itself a finding — +please report it.