From 443dac6047930859916367483fc22a47462ddfd7 Mon Sep 17 00:00:00 2001 From: Lachlan Lindsay <4453667+LachlanLindsay@users.noreply.github.com> Date: Sat, 14 Nov 2026 00:33:51 +0000 Subject: [PATCH] feat(apps): serve app web origins over the dashboard connection An app that frames its own backend's pages had to point the frame at the backend's loopback port. The browser resolves that on its own machine, so a dashboard reached through one ssh -L forward showed a blank frame: the port only exists on the gateway's host. An app can now set backend.webOrigin: true. The gateway serves its backend at http://.apps.localhost:, routed by Host on the dashboard's own listener, HTTP and WebSocket. A *.localhost name resolves to the browser's own loopback, so the frame rides whatever carries the dashboard, and it is a different site from the dashboard, so no dashboard cookie or script reaches it. Only direct local requests on a dashboard port are served, and only for an enabled, opted-in, running app. The gateway forwards no credential of its own and signs nothing there, and the response may set only host-only cookies, cannot clear site data, and may be framed only by the dashboard. The dashboard CSP admits the names in frame-src and connect-src; the CSRF allowlist does not. appWebOrigin(name) on the App SDK (seam level 8) gives an app its origin, or null where none is served. --- docs/app-kit/api-reference.md | 8 +- docs/app-kit/manifest-reference.md | 1 + docs/feature-map/README.md | 1 + docs/system-specs/modules/app-kit-platform.md | 93 +++ docs/system-specs/modules/sel.md | 1 + src/kiro_crew/apps/app_web_origin.py | 619 +++++++++++++++ src/kiro_crew/apps/manifest.py | 3 + src/kiro_crew/apps/manifest_sections.py | 7 + .../server_runtime/middleware_chain.py | 16 +- .../server_runtime/security_headers.py | 16 +- test/test_app_web_origin.py | 730 ++++++++++++++++++ test/test_dashboard_security_headers.py | 6 +- ...t_dashboard_server_composition_contract.py | 3 +- ...board_server_composition_contract_reach.py | 4 +- test/test_ssm_loopback_trust_sites.py | 6 +- website/public/vendor/kirocrew-app-sdk.mjs | 2 + website/src/app-sdk/index.ts | 2 + website/src/app-sdk/webOrigin.test.ts | 31 + website/src/app-sdk/webOrigin.ts | 28 + 19 files changed, 1560 insertions(+), 17 deletions(-) create mode 100644 src/kiro_crew/apps/app_web_origin.py create mode 100644 test/test_app_web_origin.py create mode 100644 website/src/app-sdk/webOrigin.test.ts create mode 100644 website/src/app-sdk/webOrigin.ts diff --git a/docs/app-kit/api-reference.md b/docs/app-kit/api-reference.md index 104d14ab0471..4b9de353ddf3 100644 --- a/docs/app-kit/api-reference.md +++ b/docs/app-kit/api-reference.md @@ -137,6 +137,7 @@ resolves through: |---|---|---| | `fmtCurrency(value, currency = 'USD', options?)` | `@kirocrew/app-sdk` | Money in the host's locale. | | `APP_SDK_LEVEL` | `@kirocrew/app-sdk` | The seam level, equal to the gateway's `ctx.sdk_level`. | +| `appWebOrigin(name)` | `@kirocrew/app-sdk` | The app's own site on the dashboard's port, `http://.apps.localhost:`, for a backend with `backend.webOrigin: true`; available when the dashboard uses http on `localhost`, `127.0.0.1` or `kirocrew.localhost`, and `null` on IPv6 or any other dashboard host. Level 8. | | `Select` | `@kirocrew/app-sdk/ui` | A themed inline dropdown: `options`, `optionLabels?`, `value`, `onChange`, `clearLabel?`, `disabled?`, `aria-label?`, `title?`, `className?`. Native list on touch devices. | | `guideCaution` | `@kirocrew/app-sdk/ui` | Spread onto a control that removes something (``), so a dashboard guide shows its caution line before a press there. | @@ -1924,9 +1925,10 @@ and level 7 adds the manifest's `agentReadOnlyDirs` (see `permissions.desktopCapabilities`, the dashboard's [project picker](#project-picker) (`ProjectPicker`) and [`ctx.webhook_source`](#webhook-source-ctxwebhook_source), and level 8 adds -directory entries in `credentialMasks` (`"state/"`) and the dashboard's -[host sessions](#host-sessions) (`useHostSessions`); each level -includes every level below it. Several seams share level 7, and two share level 8, so an app that needs one +directory entries in `credentialMasks` (`"state/"`), the dashboard's +[host sessions](#host-sessions) (`useHostSessions`), and the manifest's +`backend.webOrigin` with the dashboard's `appWebOrigin(name)`; each level +includes every level below it. Several seams share level 7, and three share level 8, so an app that needs one feature-detects it, never the level alone. Read it with `getattr(ctx, "sdk_level", 0)`. When it is lower than your app needs, call `ctx.health.mark_degraded(...)` with the consequence and keep serving what you can. diff --git a/docs/app-kit/manifest-reference.md b/docs/app-kit/manifest-reference.md index 1fe1dc0554c5..fa43a7378c14 100644 --- a/docs/app-kit/manifest-reference.md +++ b/docs/app-kit/manifest-reference.md @@ -1580,6 +1580,7 @@ popover says the app did not respond. | `backend.routes` | string | | Base route path for the backend | | `backend.type` | string | `""` | Backend runtime: `"python"`, `"asgi"`, `"node"`, `"exec"` (execute the entry point file as-is), or `""` (auto-detect from `entryPoint` — a `.sh` file or an extensionless executable with a non-Python shebang is treated as a shell launcher) | | `backend.signedPrincipal` | boolean | `false` | Add a signed `X-KiroCrew-Principal` claim to every request the reverse proxy forwards to this backend. Only the JSON boolean `true` turns it on. The claim says whether the gateway authenticated an `owner-session`, an `app-token`, an `agent-tool` call, or `none`. | +| `backend.webOrigin` | boolean | `false` | Serve this backend on its own site, `http://.apps.localhost:`, so a page the app frames rides the dashboard's own connection. Only the JSON boolean `true` turns it on, and the name must be at most 63 characters. The gateway forwards no credential and signs nothing on that site; the app authenticates its own pages. Read the origin with `appWebOrigin(name)` from `@kirocrew/app-sdk` (level 8). | > **Note:** the shell-launcher auto-detect reads the entry point's shebang > line, so a compiled/binary launcher (e.g. an ELF executable) cannot be diff --git a/docs/feature-map/README.md b/docs/feature-map/README.md index fe6a9e141baa..a3d94699bc6c 100644 --- a/docs/feature-map/README.md +++ b/docs/feature-map/README.md @@ -368,6 +368,7 @@ Third-party and builtin apps that add their own pages, crons and MCP tools. | Rail app menu | Details and Unpin for one installed app, from its sidebar row. Details carries the Library tile's update badge when the registry reports a newer version. When the registry list fails to load, the menu shows the failure with an Ask the agent item. Update, Sync, Disable, and Uninstall stay on the detail page and the Library | Right-click, or the context-menu key, on an app row in the sidebar's Apps list | `shell/nav/appRailMenu.tsx`, `shell/nav/navRail.tsx` | `src/kiro_crew/apps/routes_registry.py` | `GET /api/apps/registry` | | App detail | One app's manifest, config, permissions, uninstall | `/apps/detail/:name` | `pages/AppDetailRoute.tsx` (the route element, keyed by app name so each app gets a fresh page), `pages/AppDetailPage.tsx`, `pages/AppDetailPageArt.tsx` (hero banner, screenshot gallery), `pages/AppDetailLinks.tsx` (the app's own `links` as buttons in the Details card, host shown), `pages/appDetailPageTypes.ts` (view model), `pages/appDetailPageLabels.ts` (origin and lifecycle words), `pages/AppDetailAdoptionNotice.tsx` (a former built-in's pending, blocked or staged move to its registry copy), `pages/appDetailPageLocalSwitch.ts` (a local-only refusal's "Trust the repository and update" step), `pages/AppDetailPageLocalOnlyNotice.tsx` (the refusal's error notice, which offers that step), `pages/AppDetailGrantBoxes.tsx` (the worker auto-approve and user-session reach permission boxes), `pages/appDetailPageStagedGrants.ts` (the declared grants an update widened that wait for the owner's approval) | `src/kiro_crew/apps/routes_listing.py`, `src/kiro_crew/apps/routes_uninstall.py`, `src/kiro_crew/apps/routes_art.py`, `src/kiro_crew/apps/store_links.py` (`links` validation) | `GET /api/apps/{name}`, `GET /api/apps/{name}/manifest`, `GET /api/apps/{name}/config` | | Installed app page | An app's own UI, served by the app | `/apps/:name` | `pages/AppPage.tsx` | app-owned | `POST /api/apps/{name}/token`, `POST /api/apps/{name}/open` | +| App web origin | An app that sets `backend.webOrigin` gets its own site on the dashboard's port, which the gateway relays to the app's backend (HTTP and WebSocket), so a frame of the app's pages loads over the one connection that carries the dashboard | The app's own frame, at the address `appWebOrigin(name)` in `@kirocrew/app-sdk` gives it — no route of its own | `app-sdk/webOrigin.ts` | `src/kiro_crew/apps/app_web_origin.py` (`build_app_web_origin_middleware`, placed by `dashboard/server_runtime/middleware_chain.py`) | any path on `http://.apps.localhost:` | | App agent tools | MCP tools a first-party app declares in its manifest `agentTools` block and serves from its own process: the agent sees each one in `kirocrew-core`, the call is checked against the declared schema, and the gateway hands it to the app's declared route. A built-in adopted onto its own repository keeps its shipped copy's tools; any other installed or registry app's block lists nothing. No page of its own | An agent's tool call in chat, while the declaring app is enabled | — | `handlers/app_agent_tools.py` (`api_app_agent_tool_call`), `src/kiro_crew/apps/app_agent_tools.py` (the first-party reader), `src/kiro_crew/mcp_tools/app_tools.py` (the listing and forwarder), `src/kiro_crew/apps/routes_proxy.py` (`handle_app_api_proxy`) | `POST /api/app-tools/call` (strict internal: mcp-core only; it reaches `POST /apps/{name}/api/{route}` or the app's registered route) | | App migration | Move an app's data after a packaging change | `/apps/migrate/:name` | `pages/MigrationPage.tsx` | `src/kiro_crew/apps/routes_uninstall.py` | `DELETE /api/apps/{name}/migrate-cleanup` | | Builtin app surfaces | Top-level routes builtin apps claim | `/` via the `/:builtinApp/*` catch-all | `apps/builtinRegistry.ts` → per-app page | per-app `backend/routes.py` | `POST /api/apps//...` per app | diff --git a/docs/system-specs/modules/app-kit-platform.md b/docs/system-specs/modules/app-kit-platform.md index c816a519409b..bc85b9def137 100644 --- a/docs/system-specs/modules/app-kit-platform.md +++ b/docs/system-specs/modules/app-kit-platform.md @@ -5853,6 +5853,99 @@ Writers: `website/src/app-sdk/hostSessions.ts`, `website/src/app-sdk/index.ts`, its check read), `website/public/vendor/kirocrew-app-sdk.mjs`, `apps/builtins/agent_worlds/app.json`. +## 18k. An app web origin is the app's own site on the dashboard's port + +An app whose UI frames its own backend's pages (a local reverse proxy in front of +a third-party site is the case this exists for) needs that frame to have a real +origin, with its own cookies and storage, kept apart from the dashboard. Framing +the backend's loopback port gives it one only when the browser runs on the +gateway's machine: a dashboard reached through one `ssh -L` forward resolves that +port on the browser's machine, so the frame goes blank. + +**Opt-in.** `backend.webOrigin: true` (`apps/manifest_sections.py`, parsed like +`signedPrincipal`: only the JSON boolean turns it on). The app name becomes a DNS +label, so `validate()` refuses it on a name longer than 63 characters. + +**Routing.** `apps/app_web_origin.py::app_web_origin_middleware` sits in the +dashboard chain directly inside the deny-audit boundary and outside the host +canonicalization and the `Host` barrier (§ the chain in +`dashboard/server_runtime/middleware_chain.py`). A `Host` under `.apps.localhost` +is decided there and reaches no dashboard layer: + +- served only to a direct local request (`is_direct_local_request`, and not + `is_proxied_request`): a loopback peer with no forwarding header, not relayed. + An `ssh -L` forward is served; a tailnet, relayed or proxied peer gets 421. A + request that arrived on the Session Manager listener's port gets 421 too, + checked by listener (`SsmGate.owns`) because this router runs before that + listener's gate; +- only on a port the dashboard's own loopback origins in `allowed_origins` name + (the bound port and `KIROCREW_ALLOWED_LOOPBACK_PORTS`), else 421. A missing + `Host` port is the HTTP default, 80, and is served only when 80 is one of those + dashboard ports; +- only for `` that is installed, enabled, opted in, gateway-managed and has a + tracked backend port, else 404 with a body that names nothing; a name under the + suffix that is not one DNS label is 404 too; +- relayed to `http://127.0.0.1:` with path, query and body + unchanged, HTTP and WebSocket, streaming, with no total time bound (an idle + bound only), and with `Host` set to the canonical app name and explicit port. + A WebSocket message under 64 MiB is relayed in either direction + (`_MAX_WS_MESSAGE_BYTES`, above aiohttp's 4 MiB default because a live document + sync can send larger frames); a larger one closes the relay with 1009. aiohttp + checks the size once a frame is complete, so the cap bounds a message built + from many frames or a compressed one. When either side ends, both legs close + with the code that side reported: no status (an empty close frame, or 1005) + becomes 1000, a dropped connection (1006) becomes 1001, and a code outside + 1000-4999 becomes 1002, because those codes are never sent. + +Every decision is audited: one SEL `api_access` row per served request +(`outcome=granted`, `resources` the canonical app host and path) and per refusal +(`outcome=denied`, the refusal reason in `error`), both `source=app_web_origin`. + +**Credentials.** Nothing the gateway trusts crosses: `Authorization`, the +internal-auth headers, relay identity headers and every `X-KiroCrew-*` header are +dropped, the dashboard's `mc_token*` / `mc_refresh_*` cookies are removed from +`Cookie`, and the request is not signed. A backend treats `X-KiroCrew-Proxy` as +proof that the API proxy (§24) forwarded a call; a page on the app origin may be +a third party's scripts, so signing there would hand them the backend's +gateway-only API. The app's own credential (for example a launch token traded +for a host-only cookie) is the only one on this origin. + +**Response.** Hop-by-hop headers and `Clear-Site-Data` are dropped, every +`Set-Cookie` loses its `Domain` (host-only, so one app's cookie never reaches +another app's name), and each comma-separated CSP policy the backend sent loses +only its `frame-ancestors` directive. Every other directive and every non-empty +policy stays enforced. One more policy carries `frame-ancestors 'self'` plus the +dashboard's loopback origins (`frame_ancestors_value`). The dashboard's own +security headers are not applied. + +**Dashboard side.** `APP_WEB_ORIGIN_CSP_SOURCE` (`http://*.apps.localhost:*`) is in the +dashboard's `frame-src` and `connect-src` always (the frame, and the no-cors +reachability probe an app runs on it). The CSRF allowlist does not gain it, so a +page on an app origin cannot post to a dashboard API: `check_origin` refuses its +Origin. `.apps.localhost` is two labels below `localhost`, apart from the +single-label Remote Crew pane names and from `kirocrew.localhost`. + +**Discovery.** `appWebOrigin(name)` on `@kirocrew/app-sdk` +(`website/src/app-sdk/webOrigin.ts`), App Kit seam level 8, answers +`http://.apps.localhost:` when the dashboard is on +`localhost`, `127.0.0.1` or `kirocrew.localhost` over http, and `null` otherwise. +That includes an IPv6 dashboard: CSP `frame-ancestors` cannot express its +bracketed host source, so the app origin cannot be framed there. A published +HTTPS host and a Remote Crew pane also have no app origin. An app on an older +host finds no such export and keeps its own loopback frame. + +Not covered: a dashboard reached over a published HTTPS host (it has no wildcard +name or certificate for app hosts), a Remote Crew pane whose forward port differs +from the remote gateway's, and Session Manager forwards. Each keeps what the app +did before. + +Writers: `apps/app_web_origin.py`, `apps/manifest_sections.py`, `apps/manifest.py`, +`dashboard/server_runtime/middleware_chain.py`, +`dashboard/server_runtime/security_headers.py`, `website/src/app-sdk/webOrigin.ts`, +`website/src/app-sdk/index.ts`, `website/public/vendor/kirocrew-app-sdk.mjs`, +`website/src/app-sdk/sdkLevel.ts`, `apps/app_sdk_level.py`. +Tests: `test/test_app_web_origin.py`, `website/src/app-sdk/webOrigin.test.ts`. + ## 19. Spec Builder's backend is composed by lifecycle owner Spec Builder's backend carries more orchestration than a typical app: agent turns diff --git a/docs/system-specs/modules/sel.md b/docs/system-specs/modules/sel.md index 872dd8832e57..e7a838c20d3d 100644 --- a/docs/system-specs/modules/sel.md +++ b/docs/system-specs/modules/sel.md @@ -201,6 +201,7 @@ Two bounds, and the tighter wins: | Refresh tokens | `refresh_token_use`, `refresh_token_logout`, `access_cookie_revoked` (`source=refresh_tokens`) | `dashboard/handlers/auth_refresh.py` | | ACP transport | `tool_interrupted` per-turn cancellation audit (`source=acp`) | `acp/client_turn.py`, `acp/client_tool_events.py` | | Browser sign-in from the vault | One `api_access` row per vault fill (`browser_ask_vault_fill`, `outcome` = the fill's outcome word, or `unusable` when the picked login no longer fits) and per save (`browser_ask_vault_save`, `ok` / `failed`), `source=browser`, `resources` = the ask's origin and the item NAME. Never a username, password or page text | `browser_harness/vault_fill.py` | +| App web origins | One `api_access` row per request the app web origin router decides: `granted` when it relays to the app's backend, `denied` when it refuses (`source=app_web_origin`, `caller=app_web_origin`, `operation= app web origin`) | `apps/app_web_origin.py` | | Installed apps | `api_access` rows an app writes about its own decisions via `ctx.audit` (`source=app`, `caller=app:`, `operation=.`). Attribution is minted from the app name the context was built with, so there is no `caller=` parameter to pass the wrong value into — cooperative, not unforgeable, since in-process hook code can construct another app's SDK or reach `sel()` directly; `record` swallows a write failure, because auditing must not break the operation it only describes; `outcome` is not narrowed to a vocabulary (rewriting it would record something other than what happened), and the SDK adds no scrubbing of its own — `log_api_access` puts `outcome` through `_redact_and_clip` for every caller, because this seam is what turns that slot from an in-tree constant into caller text and the fix belongs at the boundary all fillers cross | `apps/audit_sdk.py` | ## APIs diff --git a/src/kiro_crew/apps/app_web_origin.py b/src/kiro_crew/apps/app_web_origin.py new file mode 100644 index 000000000000..0ed63589575b --- /dev/null +++ b/src/kiro_crew/apps/app_web_origin.py @@ -0,0 +1,619 @@ +"""App web origins: an opted-in app's own site on the dashboard's port. + +An app whose manifest sets ``backend.webOrigin: true`` is served at +``http://.apps.localhost:``. The browser resolves every +``*.localhost`` name to loopback on its own machine without DNS, so a request for +that name reaches whatever listener carries the dashboard there: the gateway +itself, or the one ``ssh -L`` forward that carries the dashboard from another +machine. The gateway tells it apart from a dashboard request by ``Host`` and +relays it, HTTP and WebSocket, to the app's backend. No listener is added. + +The name is a different site from every dashboard name (``localhost`` is not on +the Public Suffix List), so the dashboard's host-only cookies are never sent to +it and a page served there cannot script the dashboard. That is what lets an app +frame a full third-party site, with real cookies and storage, next to the +dashboard instead of inside its origin. + +The trust model is the app backend's own loopback port's, unchanged: + +* Only a request straight from this machine is served (a loopback peer with no + forwarding header, not relayed), so no peer that cannot reach the backend's + port today reaches it this way. A request that arrived on the Session Manager + listener's port is refused, checked by listener because this router runs + before that listener's gate. +* The request reaches no dashboard layer: no route, no session auth, no CSRF and + no dashboard response header. The app's own credential is the only one here. +* The gateway forwards no credential of its own and signs nothing. A backend + trusts ``X-KiroCrew-Proxy`` as proof that the dashboard's API proxy forwarded a + call, and a page on this origin is the app's framed content (possibly a third + party's scripts), so a signature here would let that page call the backend's + gateway-only API. Every ``X-KiroCrew-*`` header, the dashboard's cookies and + ``Authorization`` are dropped. +* The response may set only host-only cookies, cannot clear the dashboard's site + data, and may be framed only by the dashboard's own loopback origins. +""" + +from __future__ import annotations + +import asyncio +import functools +import logging +import re +from collections.abc import Iterable, Sequence +from typing import TYPE_CHECKING, Any + +import aiohttp +import yarl +from aiohttp import web +from multidict import CIMultiDict + +from kiro_crew.sel import sel, sel_is_warm + +if TYPE_CHECKING: + from kiro_crew.dashboard.ssm_gate import GateRef + +logger = logging.getLogger("kiro_crew.apps.app_web_origin") + +#: The suffix every app web origin's host name carries. Two labels below +#: ``localhost`` keep it apart from the single-label ``*.localhost`` names the +#: Remote Crew panes use and from ``kirocrew.localhost``. +APP_WEB_ORIGIN_SUFFIX = ".apps.localhost" + +#: The CSP source the dashboard admits in ``frame-src`` and ``connect-src`` for app +#: web origins. Only names under the suffix match, which a browser resolves to its +#: own loopback; the port is a wildcard because the browser's port is whatever +#: local port carries the dashboard. Kept apart from the dashboard's loopback +#: preview sources, whose client mirror decides Remote Crew pane embedding. +APP_WEB_ORIGIN_CSP_SOURCE = " http://*" + APP_WEB_ORIGIN_SUFFIX + ":*" + +#: One DNS label: what an app name must be to name a host. App names are +#: kebab-case but may run to 128 characters, and a label stops at 63. +_LABEL_RE = re.compile(r"^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$") + +#: The dashboard host names whose origins may frame an app web origin, and whose +#: ports an app web origin may be reached on. IPv6 loopback is excluded because +#: CSP ``frame-ancestors`` cannot express a bracketed IPv6 host source. +_DASHBOARD_LOOPBACK_HOSTS = frozenset({"localhost", "127.0.0.1", "kirocrew.localhost"}) + +#: Connecting to the backend. The backend is on loopback, so this only bounds a +#: backend that accepts nothing. +_CONNECT_TIMEOUT = 30.0 + +#: Longest silence on a relayed response, its first byte included. There is no +#: total: a framed page can wait this long for its first response while the +#: backend's own upstream sign-in runs, and a stream does not end. A backend that +#: stops producing is still cut. +_IDLE_TIMEOUT = 120.0 + +#: Largest WebSocket message relayed, in either direction (aiohttp refuses one of +#: this size or more and closes with 1009). aiohttp's 4 MiB default would close a +#: live document sync on one large frame. aiohttp checks the size once a frame is +#: complete, so this bounds a message built from many frames or a compressed one; +#: a single frame is read whole first, as on every aiohttp WebSocket in the gateway. +_MAX_WS_MESSAGE_BYTES = 64 * 1024 * 1024 + +#: Request headers never forwarded on top of the API proxy's strip list (see +#: :func:`_drop_request_headers`), matched lower-case: the hop-by-hop spellings +#: that list does not name, ``host`` (set below) and the WebSocket handshake +#: headers the client library writes itself. +_EXTRA_DROP_REQUEST_HEADERS = frozenset( + { + "proxy-connection", + "trailer", + "host", + "sec-websocket-key", + "sec-websocket-version", + "sec-websocket-extensions", + "sec-websocket-accept", + "sec-websocket-protocol", + } +) + + +@functools.cache +def _drop_request_headers() -> frozenset[str]: + """Every request header never forwarded, matched lower-case. + + Everything the API proxy strips (hop-by-hop headers, ``cookie``, + ``authorization``, the internal-auth headers and the gateway's own + ``x-kirocrew-*`` names), read from its one list so a credential header added + there is dropped here too, plus :data:`_EXTRA_DROP_REQUEST_HEADERS`. ``cookie`` + is rebuilt, not dropped. Read through the routes facade, lazily, because the + dashboard imports this module on its first response. + """ + from kiro_crew.apps.routes import _PROXY_STRIP_HEADERS + + return _PROXY_STRIP_HEADERS | _EXTRA_DROP_REQUEST_HEADERS + + +#: Header-name prefixes never forwarded: every gateway-authored header, so a page +#: cannot present one as the gateway's. +_DROP_REQUEST_PREFIXES = ("x-kirocrew-",) + +#: Response headers never relayed. ``Clear-Site-Data`` is dropped so a framed +#: page cannot ask the browser to wipe storage on the user's behalf. +_DROP_RESPONSE_HEADERS = frozenset( + { + "connection", + "keep-alive", + "proxy-authenticate", + "proxy-connection", + "te", + "trailer", + "trailers", + "transfer-encoding", + "upgrade", + "clear-site-data", + } +) + +#: The dashboard's own cookie names (``dashboard/refresh_tokens.py``). They are +#: host-only today, so a browser never sends them to an app host; dropping them by +#: name keeps that true if one is ever set with a ``Domain``. +_DASHBOARD_COOKIE_PREFIXES = ("mc_token", "mc_refresh_") + + +def parse_app_host(raw_host: str) -> tuple[str, str] | None | bool: + """Classify a ``Host`` header. + + ``None`` when the name is not under :data:`APP_WEB_ORIGIN_SUFFIX` (the request + is the dashboard's, and goes on unchanged). ``False`` when it is under the + suffix but names no well-formed app, so it is refused here and never reaches + a dashboard layer. Otherwise ``(app name, port)``, both canonical, as the + dashboard's own ``Host`` barrier reads them: the name lower-cased with one + trailing root dot dropped, and a missing port read as the HTTP default, ``80`` + (a browser leaves the default port out of ``Host``). + """ + from kiro_crew.dashboard.origin import _canonical_host, _split_authority + + parts = _split_authority(raw_host) + if parts is None: + lowered = (raw_host or "").lower().rstrip(".") + return False if APP_WEB_ORIGIN_SUFFIX in lowered else None + host = _canonical_host(parts[0]) + if not host.endswith(APP_WEB_ORIGIN_SUFFIX): + return None + label = host[: -len(APP_WEB_ORIGIN_SUFFIX)] + port = parts[1][1:] or "80" + if not _LABEL_RE.match(label): + return False + return label, port + + +def dashboard_loopback_origins(allowed_origins: Iterable[str]) -> list[str]: + """The dashboard's loopback origins: its own names, on every port it serves. + + Read from the live CSRF allowlist, so the gateway's bound port and every port + the operator opted in through ``KIROCREW_ALLOWED_LOOPBACK_PORTS`` count, and + nothing else does. Sorted, so a header built from them is stable. + """ + found: set[str] = set() + for origin in allowed_origins: + url = yarl.URL(origin) if "://" in origin else None + if url is None or url.scheme != "http" or url.explicit_port is None: + continue + authority = url.raw_authority.lower() + host = authority.rsplit(":", 1)[0] + if host in _DASHBOARD_LOOPBACK_HOSTS: + found.add(f"http://{authority}") + return sorted(found) + + +def _served_ports(origins: Iterable[str]) -> set[str]: + return {origin.rsplit(":", 1)[1] for origin in origins} + + +def forwarded_cookie(raw: str) -> str: + """The ``Cookie`` header with every dashboard cookie removed. + + Pairs are kept byte for byte and in order; only a pair whose name is a + dashboard cookie is dropped, so the app's own cookies reach it unchanged. + """ + kept = [] + for pair in raw.split(";"): + name = pair.split("=", 1)[0].strip() + if not name or name.startswith(_DASHBOARD_COOKIE_PREFIXES): + continue + kept.append(pair.strip()) + return "; ".join(kept) + + +def _forwarded_request_headers(request: web.Request, host: str) -> CIMultiDict[str]: + from kiro_crew.dashboard.relay_headers import is_relay_header + + drop = _drop_request_headers() + headers: CIMultiDict[str] = CIMultiDict() + for key, value in request.headers.items(): + lowered = key.lower() + if lowered in drop or lowered.startswith(_DROP_REQUEST_PREFIXES): + continue + if is_relay_header(key): + continue + headers.add(key, value) + cookie = forwarded_cookie("; ".join(request.headers.getall("Cookie", []))) + if cookie: + headers["Cookie"] = cookie + # The backend sees the name the browser used, so its own Host check and the + # absolute URLs it builds keep meaning what they mean to the browser. + headers["Host"] = host + return headers + + +def host_only_set_cookie(value: str) -> str: + """One ``Set-Cookie`` value with its ``Domain`` attribute removed. + + A cookie with a ``Domain`` would be sent to every name under it: on + ``apps.localhost`` that is every other app's site. Without one the browser + keeps it host-only, on this app's name alone. + """ + parts = value.split(";") + kept = [parts[0]] + [p for p in parts[1:] if p.split("=", 1)[0].strip().lower() != "domain"] + return ";".join(kept) + + +def _without_frame_ancestors(policy: str) -> str: + policies: list[str] = [] + for serialized_policy in policy.split(","): + directives = [directive.strip() for directive in serialized_policy.split(";")] + kept = [ + directive + for directive in directives + if directive and directive.split(None, 1)[0].lower() != "frame-ancestors" + ] + if kept: + policies.append("; ".join(kept)) + return ", ".join(policies) + + +def hardened_response_headers( + upstream: Iterable[tuple[str, str]], ancestors: str +) -> CIMultiDict[str]: + """The backend's response headers as the browser may receive them. + + Hop-by-hop headers and ``Clear-Site-Data`` dropped, every ``Set-Cookie`` + host-only, and ``frame-ancestors`` replaced by *ancestors*: the backend's own + directive is removed from each policy it sent, and one policy carrying only + the gateway's directive is added. Policies are enforced together, so the rest + of the backend's CSP still applies. + """ + headers: CIMultiDict[str] = CIMultiDict() + for key, value in upstream: + lowered = key.lower() + if lowered in _DROP_RESPONSE_HEADERS: + continue + if lowered == "set-cookie": + headers.add(key, host_only_set_cookie(value)) + elif lowered == "content-security-policy": + rest = _without_frame_ancestors(value) + if rest: + headers.add(key, rest) + else: + headers.add(key, value) + headers.add("Content-Security-Policy", f"frame-ancestors {ancestors}") + return headers + + +async def _audit( + request: web.Request, *, outcome: str, resources: str, error: str | None = None +) -> None: + """Record one app web origin decision in the SEL, best-effort. + + A trust root too short to sign the chain makes the singleton's construction + raise, and :func:`kiro_crew.sel.warm_sel_singleton` lets the gateway start + anyway. An unguarded write would then turn every decision into a 500: a + refusal would lose its 404 or 421, and a healthy app would stop loading. The + decision always stands; what a failed write loses is the row, and the + warning says the trail has a hole. On a failed warm the next ``sel()`` + retries construction, which reads and writes files, so that case takes a + worker thread instead of the event loop; the healthy path only enqueues. + """ + fields: dict[str, Any] = { + "caller": "app_web_origin", + "operation": f"{request.method} app web origin", + "outcome": outcome, + "source": "app_web_origin", + "resources": resources, + } + if error is not None: + fields["error"] = error + + def _write() -> None: + sel().log_api_access(**fields) + + try: + if sel_is_warm(): + _write() + else: + await asyncio.to_thread(_write) + except Exception: + logger.warning("Failed to log an app web origin %s to SEL", outcome, exc_info=True) + + +async def _refusal(request: web.Request, status: int, reason: str) -> web.Response: + """A refusal, recorded once; the body names nothing about the app.""" + from kiro_crew.dashboard.origin import mark_audit_claimed + + mark_audit_claimed(request) + await _audit( + request, + outcome="denied", + resources=request.headers.get("Host", "") or "", + error=reason, + ) + text = "misdirected request" if status == 421 else "not found" + return web.Response(status=status, text=text) + + +async def _record_grant(request: web.Request, app_host: str) -> None: + """The serve decision, recorded as every refusal is, before the relay starts.""" + await _audit(request, outcome="granted", resources=f"{app_host}{request.path}") + + +async def _backend_port(name: str) -> int | None: + """The tracked port of *name*'s backend when the app may be served, else None. + + Installed, enabled, opted in, gateway-managed and running. Every failing + condition answers the same, so a page cannot tell which apps are installed. + """ + from kiro_crew.apps.backend import get_app_backend_port + from kiro_crew.apps.manager import get_app_manifest, is_app_enabled + + manifest = await asyncio.to_thread(get_app_manifest, name) + if manifest is None or not manifest.backend.webOrigin: + return None + if not await asyncio.to_thread(is_app_enabled, name): + return None + port = get_app_backend_port(name) + return int(port) if port else None + + +def _client_session(request: web.Request) -> tuple[aiohttp.ClientSession, bool]: + session = request.app.get("_proxy_session") + if session is None or session.closed: + return aiohttp.ClientSession(auto_decompress=False), True + return session, False + + +async def _relay_http( + request: web.Request, target: yarl.URL, headers: CIMultiDict[str], ancestors: str +) -> web.StreamResponse: + timeout = aiohttp.ClientTimeout(total=None, connect=_CONNECT_TIMEOUT, sock_read=_IDLE_TIMEOUT) + session, owns = _client_session(request) + resp: web.StreamResponse | None = None + try: + async with session.request( + request.method, + target, + headers=headers, + data=request.content if request.body_exists else None, + timeout=timeout, + allow_redirects=False, + ) as upstream: + resp = web.StreamResponse( + status=upstream.status, + reason=upstream.reason, + headers=hardened_response_headers(upstream.headers.items(), ancestors), + ) + try: + await resp.prepare(request) + async for chunk in upstream.content.iter_any(): + await resp.write(chunk) + await resp.write_eof() + except (ConnectionResetError, ConnectionAbortedError): + pass + return resp + except (aiohttp.ClientError, asyncio.TimeoutError) as exc: + logger.info("app web origin relay to %s failed: %s", target.port, exc) + if resp is not None and resp.prepared: + from kiro_crew.apps.routes import _end_relay_midbody + + return _end_relay_midbody(request, resp) + return web.Response(status=502, text="app backend unreachable") + finally: + if owns: + await session.close() + + +#: Close codes a peer may report but no endpoint may send in a close frame +#: (RFC 6455 section 7.4.1): no status, abnormal closure, TLS failure. +_UNSENDABLE_CLOSE_CODES = frozenset({1005, 1006, 1015}) + + +def _close_code_to_relay(code: int | None) -> int: + """The code to close both legs with, from the side that ended first. + + A code that side's peer chose is passed on as it is. A close with no status + (aiohttp reports an empty close frame as 0) is a normal closure, a connection + that dropped is "going away", and a code outside the sendable 1000-4999 range + is a protocol error. + """ + if not code or code == 1005: + return int(aiohttp.WSCloseCode.OK) + if code in _UNSENDABLE_CLOSE_CODES: + return int(aiohttp.WSCloseCode.GOING_AWAY) + if not 1000 <= code <= 4999: + return int(aiohttp.WSCloseCode.PROTOCOL_ERROR) + return code + + +def _ended_with(pumps: Sequence[asyncio.Future[int | None]]) -> int | None: + """The close code of the first pump, page side first, that finished on its own.""" + for task in pumps: + if task.done() and not task.cancelled(): + return 1006 if task.exception() is not None else task.result() + return None + + +async def _pump(source: Any, sink: Any) -> int | None: + """Copy WebSocket messages from *source* to *sink*; answer the code *source* ended with. + + The code comes from the message that ended it: the peer's close frame, or the + error aiohttp raised (1009 for a message over the cap). Only a socket aiohttp + already reports closing or closed is read through its own ``close_code``. + """ + while True: + msg = await source.receive() + if msg.type == aiohttp.WSMsgType.TEXT: + await sink.send_str(msg.data) + elif msg.type == aiohttp.WSMsgType.BINARY: + await sink.send_bytes(msg.data) + elif msg.type == aiohttp.WSMsgType.CLOSE: + return msg.data if isinstance(msg.data, int) else None + elif msg.type == aiohttp.WSMsgType.ERROR: + code = getattr(msg.data, "code", None) + return code if isinstance(code, int) else 1006 + elif msg.type in (aiohttp.WSMsgType.CLOSING, aiohttp.WSMsgType.CLOSED): + return source.close_code if isinstance(source.close_code, int) else None + + +#: How long the relay waits for the backend's closing handshake. +_WS_CLOSE_TIMEOUT = 10.0 + + +def _ws_connect_timeouts() -> dict[str, Any]: + """``ws_connect`` timeouts: no receive bound, and :data:`_WS_CLOSE_TIMEOUT` to close. + + ``aiohttp.ClientWSTimeout`` exists from aiohttp 3.11, and ``setup.cfg`` allows + 3.9. Before it, the same two bounds are the ``receive_timeout`` and ``timeout`` + keywords, which 3.11 deprecates. + """ + ws_timeout = getattr(aiohttp, "ClientWSTimeout", None) + if ws_timeout is None: + return {"timeout": _WS_CLOSE_TIMEOUT, "receive_timeout": None} + return {"timeout": ws_timeout(ws_receive=None, ws_close=_WS_CLOSE_TIMEOUT)} + + +async def _relay_websocket( + request: web.Request, target: yarl.URL, headers: CIMultiDict[str] +) -> web.StreamResponse: + offered = tuple( + p.strip() for p in request.headers.get("Sec-WebSocket-Protocol", "").split(",") if p.strip() + ) + session, owns = _client_session(request) + try: + try: + upstream = await session.ws_connect( + target.with_scheme("ws"), + headers=headers, + protocols=offered, + **_ws_connect_timeouts(), + max_msg_size=_MAX_WS_MESSAGE_BYTES, + autoclose=False, + ) + except (aiohttp.ClientError, asyncio.TimeoutError) as exc: + logger.info("app web origin WebSocket to %s failed: %s", target.port, exc) + return web.Response(status=502, text="app backend unreachable") + async with upstream: + browser = web.WebSocketResponse( + protocols=(upstream.protocol,) if upstream.protocol else (), + max_msg_size=_MAX_WS_MESSAGE_BYTES, + autoclose=False, + ) + await browser.prepare(request) + pumps = [ + asyncio.ensure_future(_pump(browser, upstream)), + asyncio.ensure_future(_pump(upstream, browser)), + ] + try: + await asyncio.wait(pumps, return_when=asyncio.FIRST_COMPLETED) + finally: + # Read in `finally`, so a handler cancelled during the wait still + # relays the code of a pump that had already ended. + code = _close_code_to_relay(_ended_with(pumps)) + for task in pumps: + task.cancel() + await asyncio.gather(*pumps, return_exceptions=True) + await browser.close(code=code) + await upstream.close(code=code) + return browser + finally: + if owns: + await session.close() + + +def _is_websocket_upgrade(request: web.Request) -> bool: + connection = {t.strip().lower() for t in request.headers.get("Connection", "").split(",")} + return request.headers.get("Upgrade", "").lower() == "websocket" and "upgrade" in connection + + +async def serve_app_web_origin( + request: web.Request, name: str, port: str, ssm_gate: GateRef | None +) -> web.StreamResponse: + """Serve one request for ``.apps.localhost:``, or refuse it. + + *ssm_gate* holds the Session Manager listener's gate, the one token auth is + built with. This runs before that gate has judged the request, so its mark is + not set yet and the listener is read from the socket's local port instead. + """ + from kiro_crew.dashboard.origin import ( + frame_ancestors_value, + is_direct_local_request, + is_proxied_request, + ) + + gate = ssm_gate.gate if ssm_gate is not None else None + if gate is not None and gate.owns(request): + return await _refusal(request, 421, "arrived on the Session Manager listener") + if is_proxied_request(request) or not is_direct_local_request(request): + return await _refusal(request, 421, "not a direct local request") + origins = dashboard_loopback_origins(request.app.get("allowed_origins") or ()) + if port not in _served_ports(origins): + return await _refusal(request, 421, "port is not a dashboard port") + backend_port = await _backend_port(name) + if backend_port is None: + return await _refusal(request, 404, "no app web origin for this name") + target = yarl.URL.build( + scheme="http", + host="127.0.0.1", + port=backend_port, + encoded=True, + path=request.rel_url.raw_path, + query_string=request.rel_url.raw_query_string, + ) + app_host = f"{name}{APP_WEB_ORIGIN_SUFFIX}:{port}" + headers = _forwarded_request_headers(request, app_host) + await _record_grant(request, app_host) + if _is_websocket_upgrade(request): + return await _relay_websocket(request, target, headers) + return await _relay_http(request, target, headers, frame_ancestors_value(origins)) + + +def build_app_web_origin_middleware(ssm_gate: GateRef | None) -> Any: + """The app web origin router, built with the chain's Session Manager gate holder. + + *ssm_gate* is the holder the chain passes to token auth. The gateway fills it + before the Session Manager listener accepts a connection, so this router + refuses that listener's requests from the first one on. + """ + + @web.middleware # type: ignore[misc] + async def app_web_origin_middleware(request: web.Request, handler: Any) -> web.StreamResponse: + """Hand an app web origin's request to its app; every other request goes on. + + Placed ahead of the dashboard's host canonicalization and ``Host`` barrier, + so a name under :data:`APP_WEB_ORIGIN_SUFFIX` is decided here and never by a + dashboard layer: served, or refused. + """ + parsed = parse_app_host(request.headers.get("Host", "")) + if parsed is None: + return await handler(request) # type: ignore[no-any-return] + if parsed is False: + return await _refusal(request, 404, "malformed app web origin host") + assert isinstance(parsed, tuple) + name, port = parsed + return await serve_app_web_origin(request, name, port, ssm_gate) + + return app_web_origin_middleware + + +__all__ = [ + "APP_WEB_ORIGIN_CSP_SOURCE", + "APP_WEB_ORIGIN_SUFFIX", + "build_app_web_origin_middleware", + "dashboard_loopback_origins", + "forwarded_cookie", + "hardened_response_headers", + "host_only_set_cookie", + "parse_app_host", + "serve_app_web_origin", +] diff --git a/src/kiro_crew/apps/manifest.py b/src/kiro_crew/apps/manifest.py index c9ddb699b158..ff26d8eecd86 100644 --- a/src/kiro_crew/apps/manifest.py +++ b/src/kiro_crew/apps/manifest.py @@ -577,6 +577,9 @@ def report_path(refusal: str, message: str) -> None: name_error = app_name_error(self.name) if name_error: errors.append(name_error) + elif self.backend.webOrigin and len(self.name) > 63: + # The name becomes a DNS label in its web origin's host name. + errors.append("backend.webOrigin needs an app name of at most 63 characters") if not self.version: errors.append("missing required field: version") diff --git a/src/kiro_crew/apps/manifest_sections.py b/src/kiro_crew/apps/manifest_sections.py index 8620697ae49f..103b855df0f6 100644 --- a/src/kiro_crew/apps/manifest_sections.py +++ b/src/kiro_crew/apps/manifest_sections.py @@ -505,6 +505,10 @@ class BackendConfig: # Only the literal JSON boolean true enables it: a string or a number keeps # the default off, so a malformed manifest never widens what a backend trusts. signedPrincipal: bool = False # noqa: N815 + # Opt in to an app web origin: the gateway serves this backend at + # ``http://.apps.localhost:`` (apps/app_web_origin.py). + # Same strict parse as signedPrincipal: only the JSON boolean true turns it on. + webOrigin: bool = False # noqa: N815 hooks: HooksConfig = field(default_factory=HooksConfig) def to_dict(self) -> dict[str, Any]: @@ -521,6 +525,8 @@ def to_dict(self) -> dict[str, Any]: d["type"] = self.type if self.signedPrincipal: d["signedPrincipal"] = True + if self.webOrigin: + d["webOrigin"] = True hooks_d = self.hooks.to_dict() if hooks_d: d["hooks"] = hooks_d @@ -537,6 +543,7 @@ def from_dict(cls, data: dict[str, Any]) -> BackendConfig: routes=str(data.get("routes", "")), type=str(data.get("type", "")), signedPrincipal=data.get("signedPrincipal") is True, # noqa: N815 + webOrigin=data.get("webOrigin") is True, # noqa: N815 hooks=hooks, ) diff --git a/src/kiro_crew/dashboard/server_runtime/middleware_chain.py b/src/kiro_crew/dashboard/server_runtime/middleware_chain.py index 0642365dfecb..6a7cab010c49 100644 --- a/src/kiro_crew/dashboard/server_runtime/middleware_chain.py +++ b/src/kiro_crew/dashboard/server_runtime/middleware_chain.py @@ -131,9 +131,10 @@ def _install_dashboard_middlewares( The order is a security contract: route latency outermost, then the relay-path header rule, the client-sent relay-header strip just inside it, the deny-audit - boundary outer to every barrier that can refuse, the host canonicalization, the - ``Host`` barrier, the header policy, CSRF, token auth, the SEL request audit and - the per-slot ownership checkpoint, with the SPA fallback innermost. + boundary outer to every barrier that can refuse, the app web origin router, the + host canonicalization, the ``Host`` barrier, the header policy, CSRF, token + auth, the SEL request audit and the per-slot ownership checkpoint, with the SPA + fallback innermost. ``_register_workflow_lifecycle`` and ``_register_crewmate_prune_gate`` append their gates after it. The barriers are built by the entrypoint from the shared factories; the layers only this chain uses are built here. @@ -217,6 +218,7 @@ async def sel_audit_middleware( raise return await handler(request) # type: ignore[operator] + from kiro_crew.apps.app_web_origin import build_app_web_origin_middleware from kiro_crew.dashboard.card_send import ( card_turn_arrival_middleware, card_turn_delegation_middleware, @@ -252,6 +254,14 @@ async def sel_audit_middleware( # latency middleware and the two relay-header layers only, which keeps the # latency layer's "times the FULL in-gateway handling" contract intact. deny_audit_middleware, + # Inner to the deny-audit boundary and outer to the host canonicalization + # and the ``Host`` barrier: a request for an app web origin + # (``.apps.localhost``) is served or refused here and reaches no + # dashboard layer, so it is never redirected, never answered by a dashboard + # route and never given dashboard credentials (apps/app_web_origin.py). + # It runs before token auth's SSM gate, so it is built with the same + # holder and refuses a request on the SSM listener by its socket. + build_app_web_origin_middleware(ssm_gate), host_canonical_redirect, host_validation_middleware, # Compressed request bodies are refused outright (415): the hardened diff --git a/src/kiro_crew/dashboard/server_runtime/security_headers.py b/src/kiro_crew/dashboard/server_runtime/security_headers.py index f901c9d5fea2..a286fd2bee08 100644 --- a/src/kiro_crew/dashboard/server_runtime/security_headers.py +++ b/src/kiro_crew/dashboard/server_runtime/security_headers.py @@ -219,10 +219,16 @@ def _apply_security_headers( state = app.get("state") instances_mgr = getattr(state, "instances_manager", None) if state else None - # Loopback preview origins are always framable (Web Preview panel); the - # *.localhost tunnel wildcard is added only when instances mode is active. - frame_src_extra = _LOOPBACK_FRAME_SRC + ( - _INSTANCES_FRAME_SRC_EXTRA if instances_mgr is not None else "" + # Loopback preview origins are always framable (Web Preview panel), and so are + # app web origins (apps/app_web_origin.py), which are also connectable for an + # app's no-cors reachability probe on its frame; the *.localhost tunnel + # wildcard is added only when instances mode is active. + from kiro_crew.apps.app_web_origin import APP_WEB_ORIGIN_CSP_SOURCE + + frame_src_extra = ( + _LOOPBACK_FRAME_SRC + + APP_WEB_ORIGIN_CSP_SOURCE + + (_INSTANCES_FRAME_SRC_EXTRA if instances_mgr is not None else "") ) # frame-ancestors: ``'self'`` plus the EXACT parent origin carried in the # request token's embed_parent_port claim (see _extra_frame_ancestors) — never @@ -238,7 +244,7 @@ def _apply_security_headers( resp.headers.setdefault( "Content-Security-Policy", _BASE_CSP.format( - connect_src_extra=_LOOPBACK_FRAME_SRC, + connect_src_extra=_LOOPBACK_FRAME_SRC + APP_WEB_ORIGIN_CSP_SOURCE, frame_src_extra=frame_src_extra, frame_ancestors=frame_ancestors, ), diff --git a/test/test_app_web_origin.py b/test/test_app_web_origin.py new file mode 100644 index 000000000000..8b03daaf5e6a --- /dev/null +++ b/test/test_app_web_origin.py @@ -0,0 +1,730 @@ +"""App web origins: ``.apps.localhost`` on the dashboard's port. + +The router serves an enabled, opted-in app's backend on its own site and refuses +every other name under the suffix before any dashboard layer sees it. These tests +drive the real middleware in front of a real loopback backend. +""" + +from __future__ import annotations + +import asyncio +from collections.abc import AsyncIterator +from pathlib import Path +from typing import Any + +import aiohttp +import pytest +import pytest_asyncio +from aiohttp import web +from aiohttp.test_utils import TestClient, TestServer + +from kiro_crew.apps import app_web_origin as awo +from kiro_crew.apps.manifest import AppManifest +from kiro_crew.dashboard.ssm_gate import GateRef, SsmGate +from kiro_crew.testing.wait import FALLBACK_TIMEOUT_SECS, async_wait_until + +_PORT = "5476" +_ALLOWED = { + f"http://localhost:{_PORT}", + f"http://127.0.0.1:{_PORT}", + f"http://[::1]:{_PORT}", + f"http://kirocrew.localhost:{_PORT}", + "https://crew.example.com", +} +_HOST = f"demo.apps.localhost:{_PORT}" + + +# ── pure helpers ───────────────────────────────────────────────────────────── + + +@pytest.mark.parametrize( + ("raw", "expected"), + [ + (_HOST, ("demo", _PORT)), + (f"DEMO.Apps.LocalHost:{_PORT}", ("demo", _PORT)), + (f"demo.apps.localhost.:{_PORT}", ("demo", _PORT)), + (f"localhost:{_PORT}", None), + (f"kirocrew.localhost:{_PORT}", None), + (f"demo.localhost:{_PORT}", None), + # A rebinding name that merely contains the suffix is not ours; the + # dashboard's own Host barrier refuses it. + (f"demo.apps.localhost.evil.example:{_PORT}", None), + ("", None), + ("demo.apps.localhost", ("demo", "80")), + (f"a.b.apps.localhost:{_PORT}", False), + (f"-x.apps.localhost:{_PORT}", False), + (f"{'a' * 64}.apps.localhost:{_PORT}", False), + (f".apps.localhost:{_PORT}", False), + ("demo.apps.localhost:x", False), + ], +) +def test_parse_app_host(raw: str, expected: object) -> None: + assert awo.parse_app_host(raw) == expected + + +def test_dashboard_loopback_origins_are_the_dashboard_names_only() -> None: + assert awo.dashboard_loopback_origins(_ALLOWED) == sorted( + f"http://{host}:{_PORT}" for host in ("localhost", "127.0.0.1", "kirocrew.localhost") + ) + + +def test_every_header_the_api_proxy_strips_is_dropped_here_too() -> None: + """One credential list: a header the API proxy learns to strip is dropped here too.""" + from kiro_crew.apps.routes import _PROXY_STRIP_HEADERS + + assert _PROXY_STRIP_HEADERS <= awo._drop_request_headers() + + +def test_dashboard_cookies_are_not_forwarded() -> None: + raw = "mc_token_5476=dash; app=1; mc_refresh_5476=r; mc_token=legacy; other=a=b" + assert awo.forwarded_cookie(raw) == "app=1; other=a=b" + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + ("a=1; Domain=apps.localhost; Path=/", "a=1; Path=/"), + ("a=1; domain=.localhost; HttpOnly", "a=1; HttpOnly"), + ("a=1; Path=/; Secure", "a=1; Path=/; Secure"), + ], +) +def test_set_cookie_is_host_only(value: str, expected: str) -> None: + assert awo.host_only_set_cookie(value) == expected + + +def test_response_hardening() -> None: + headers = awo.hardened_response_headers( + [ + ("Content-Security-Policy", "default-src 'self'; frame-ancestors *"), + ( + "Content-Security-Policy", + "frame-ancestors 'none', script-src 'none'; frame-ancestors *", + ), + ("Clear-Site-Data", '"*"'), + ("Set-Cookie", "a=1; Domain=apps.localhost"), + ("Set-Cookie", "b=2"), + ("Transfer-Encoding", "chunked"), + ("Content-Type", "text/html"), + ], + "'self' http://localhost:5476", + ) + assert headers.getall("Content-Security-Policy") == [ + "default-src 'self'", + "script-src 'none'", + "frame-ancestors 'self' http://localhost:5476", + ] + assert headers.getall("Set-Cookie") == ["a=1", "b=2"] + assert "Clear-Site-Data" not in headers + assert "Transfer-Encoding" not in headers + assert headers["Content-Type"] == "text/html" + + +@pytest.mark.parametrize( + ("backend", "name", "error"), + [ + ({"entryPoint": "s.py", "webOrigin": True}, "demo", False), + ({"entryPoint": "s.py", "webOrigin": True}, "a" * 64, True), + ({"entryPoint": "s.py"}, "a" * 64, False), + ], +) +def test_manifest_opt_in(backend: dict[str, Any], name: str, error: bool) -> None: + manifest = AppManifest.from_dict( + { + "name": name, + "version": "1.0.0", + "displayName": "D", + "description": "d", + "backend": backend, + } + ) + assert manifest.backend.webOrigin is bool(backend.get("webOrigin")) + assert ("backend.webOrigin" in " ".join(manifest.validate())) is error + + +@pytest.mark.parametrize("raw", ["true", 1, "yes", None]) +def test_manifest_opt_in_is_the_json_boolean_only(raw: object) -> None: + manifest = AppManifest.from_dict( + { + "name": "demo", + "version": "1.0.0", + "displayName": "D", + "description": "d", + "backend": {"entryPoint": "s.py", "webOrigin": raw}, + } + ) + assert manifest.backend.webOrigin is False + assert "webOrigin" not in manifest.to_dict().get("backend", {}) + + +# ── the router in front of a real backend ──────────────────────────────────── + + +class _Backend: + def __init__(self) -> None: + self.seen: list[dict[str, Any]] = [] + self.ws_texts: list[str] = [] + self.ws_close_codes: list[int | None] = [] + self.port = 0 + self._runner: web.AppRunner | None = None + + async def _capture(self, request: web.Request) -> web.StreamResponse: + if request.headers.get("Upgrade", "").lower() == "websocket": + ws = web.WebSocketResponse(protocols=("chat",)) + await ws.prepare(request) + self.seen.append({"ws": True, "headers": dict(request.headers)}) + while True: + msg = await ws.receive() + if msg.type == aiohttp.WSMsgType.TEXT: + self.ws_texts.append(msg.data) + if msg.data == "bye": + await ws.close(code=4001) + self.ws_close_codes.append(None) + break + await ws.send_str(f"echo:{msg.data}") + elif msg.type == aiohttp.WSMsgType.BINARY: + await ws.send_bytes(msg.data[::-1]) + else: + # The code in the close frame the relay sent, before this + # side's own closing handshake overwrites ws.close_code. + self.ws_close_codes.append( + msg.data if msg.type == aiohttp.WSMsgType.CLOSE else None + ) + break + return ws + body = await request.read() + self.seen.append( + { + "headers": dict(request.headers), + "cookies": request.headers.get("Cookie", ""), + "target": request.raw_path, + "body": body, + "method": request.method, + } + ) + resp = web.Response(text="framed page", content_type="text/html") + resp.headers.add("Set-Cookie", "app=1; Domain=apps.localhost; Path=/") + resp.headers["Content-Security-Policy"] = ( + "frame-ancestors 'none', script-src 'none'; frame-ancestors *" + ) + resp.headers["Clear-Site-Data"] = '"*"' + return resp + + async def start(self) -> None: + app = web.Application() + app.router.add_route("*", "/{path:.*}", self._capture) + self._runner = web.AppRunner(app) + await self._runner.setup() + site = web.TCPSite(self._runner, "127.0.0.1", 0) + await site.start() + self.port = self._runner.addresses[0][1] + + async def stop(self) -> None: + if self._runner is not None: + await self._runner.cleanup() + + +@pytest_asyncio.fixture +async def backend() -> AsyncIterator[_Backend]: + b = _Backend() + await b.start() + try: + yield b + finally: + await b.stop() + + +def _router_app( + backend: _Backend, monkeypatch: pytest.MonkeyPatch, ssm_gate: GateRef | None +) -> web.Application: + """The router outermost, then a stand-in for every dashboard layer.""" + + async def _port(name: str) -> int | None: + return backend.port if name == "demo" else None + + monkeypatch.setattr(awo, "_backend_port", _port) + + async def dashboard(_request: web.Request) -> web.Response: + return web.Response(text="dashboard") + + app = web.Application(middlewares=[awo.build_app_web_origin_middleware(ssm_gate)]) + app["allowed_origins"] = set(_ALLOWED) + app.router.add_route("*", "/{path:.*}", dashboard) + return app + + +@pytest_asyncio.fixture +async def gateway(backend: _Backend, monkeypatch: pytest.MonkeyPatch) -> AsyncIterator[TestClient]: + """The router on a gateway with no Session Manager listener.""" + client = TestClient(TestServer(_router_app(backend, monkeypatch, None), host="127.0.0.1")) + await client.start_server() + try: + yield client + finally: + await client.close() + + +@pytest_asyncio.fixture +async def ssm_gateway( + backend: _Backend, monkeypatch: pytest.MonkeyPatch +) -> AsyncIterator[tuple[TestClient, int]]: + """The router with a Session Manager listener bound beside the dashboard's. + + As ``ssm_gate.start_after_bind`` binds it: a second site on the same runner, so + a request on either port runs the same chain, and the gate holder the chain was + built with names the second site's port. Yields the client and that port. + """ + ref = GateRef() + client = TestClient(TestServer(_router_app(backend, monkeypatch, ref), host="127.0.0.1")) + await client.start_server() + try: + runner = client.server.runner + assert runner is not None + await web.TCPSite(runner, "127.0.0.1", 0).start() + ssm_port = next(addr[1] for addr in runner.addresses if addr[1] != client.port) + ref.gate = SsmGate(port=ssm_port) + yield client, ssm_port + finally: + await client.close() + + +@pytest.mark.asyncio +async def test_serves_the_app_and_never_the_dashboard( + gateway: TestClient, backend: _Backend +) -> None: + for path in ("/", "/api/session", "/__kc_auth?t=x&next=/doc/1"): + resp = await gateway.get(path, headers={"Host": _HOST}) + assert resp.status == 200 + assert await resp.text() == "framed page" + assert [s["target"] for s in backend.seen] == [ + "/", + "/api/session", + "/__kc_auth?t=x&next=/doc/1", + ] + + +@pytest.mark.asyncio +async def test_other_hosts_reach_the_dashboard(gateway: TestClient, backend: _Backend) -> None: + resp = await gateway.get("/", headers={"Host": f"localhost:{_PORT}"}) + assert await resp.text() == "dashboard" + assert backend.seen == [] + + +@pytest.mark.parametrize( + ("host", "extra", "status"), + [ + (f"other.apps.localhost:{_PORT}", {}, 404), + ("demo.apps.localhost:6000", {}, 421), + ("demo.apps.localhost", {}, 421), + (f"a.b.apps.localhost:{_PORT}", {}, 404), + (_HOST, {"X-Forwarded-For": "203.0.113.9"}, 421), + (_HOST, {"Forwarded": "for=203.0.113.9"}, 421), + ], +) +@pytest.mark.asyncio +async def test_refusals( + gateway: TestClient, backend: _Backend, host: str, extra: dict[str, str], status: int +) -> None: + resp = await gateway.get("/api/session", headers={"Host": host, **extra}) + assert resp.status == status + assert await resp.text() in ("not found", "misdirected request") + assert backend.seen == [] + + +@pytest.mark.asyncio +async def test_default_port_host_is_served_only_by_port_80_dashboard( + gateway: TestClient, backend: _Backend +) -> None: + allowed_origins = gateway.app["allowed_origins"] + allowed_origins.clear() + allowed_origins.update({"http://localhost:80", "http://localhost"}) + origins = awo.dashboard_loopback_origins(allowed_origins) + assert awo._served_ports(origins) == {"80"} + + resp = await gateway.get("/", headers={"Host": "demo.apps.localhost"}) + assert resp.status == 200 + headers = {key.lower(): value for key, value in backend.seen[0]["headers"].items()} + assert headers["host"] == "demo.apps.localhost:80" + + allowed_origins.clear() + allowed_origins.update(_ALLOWED) + resp = await gateway.get("/", headers={"Host": "demo.apps.localhost"}) + assert resp.status == 421 + assert len(backend.seen) == 1 + + +@pytest.mark.asyncio +async def test_gateway_credentials_are_never_forwarded( + gateway: TestClient, backend: _Backend +) -> None: + resp = await gateway.post( + "/api/thing?x=%20y", + data=b"payload", + headers={ + "Host": _HOST, + "Cookie": "mc_token_5476=dash; kc_app=yes; mc_refresh_5476=r", + "Authorization": "Bearer dash", + "X-KiroCrew-Proxy": "1:forged", + "X-KiroCrew-Proxy-V2": "forged", + "X-KiroCrew-Principal": "forged", + "X-Internal-Secret": "s", + "X-Kiro-Relay-User": "someone", + "Origin": f"http://{_HOST}", + }, + ) + assert resp.status == 200 + seen = backend.seen[0] + lowered = {k.lower(): v for k, v in seen["headers"].items()} + assert seen["cookies"] == "kc_app=yes" + assert not [k for k in lowered if k.startswith(("x-kirocrew-", "x-kiro-relay-", "x-internal"))] + assert "authorization" not in lowered + assert lowered["host"] == _HOST + assert lowered["origin"] == f"http://{_HOST}" + assert seen["body"] == b"payload" + assert seen["target"] == "/api/thing?x=%20y" + + +@pytest.mark.asyncio +async def test_response_is_hardened(gateway: TestClient) -> None: + resp = await gateway.get("/", headers={"Host": _HOST}) + assert resp.headers.getall("Set-Cookie") == ["app=1; Path=/"] + assert "Clear-Site-Data" not in resp.headers + policies = resp.headers.getall("Content-Security-Policy") + assert policies[0] == "script-src 'none'" + assert policies[1] == ( + f"frame-ancestors 'self' http://127.0.0.1:{_PORT} " + f"http://kirocrew.localhost:{_PORT} http://localhost:{_PORT}" + ) + + +@pytest.mark.asyncio +async def test_websocket_round_trips(gateway: TestClient, backend: _Backend) -> None: + async with asyncio.timeout(FALLBACK_TIMEOUT_SECS): + ws = await gateway.ws_connect( + "/live", + headers={ + "Host": _HOST, + "Cookie": "mc_token_5476=dash; kc_app=yes", + "Origin": f"http://{_HOST}", + "X-KiroCrew-Proxy": "1:forged", + }, + protocols=("chat",), + ) + assert ws.protocol == "chat" + await ws.send_str("hi") + assert (await ws.receive()).data == "echo:hi" + await ws.send_bytes(b"abc") + assert (await ws.receive()).data == b"cba" + await ws.close() + headers = {k.lower(): v for k, v in backend.seen[0]["headers"].items()} + assert headers["cookie"] == "kc_app=yes" + assert headers["host"] == _HOST + assert headers["origin"] == f"http://{_HOST}" + assert "x-kirocrew-proxy" not in headers + + +@pytest.mark.asyncio +async def test_the_session_manager_listener_never_reaches_a_backend( + ssm_gateway: tuple[TestClient, int], backend: _Backend +) -> None: + """A peer with only a Session Manager forward is refused before any backend lookup. + + The router runs before that listener's gate has judged the request, and the + peer is loopback with no forwarding header, so only the socket's local port + tells it apart from this machine's own browser. + """ + client, ssm_port = ssm_gateway + on_ssm = f"http://127.0.0.1:{ssm_port}" + for host in (_HOST, f"DEMO.apps.localhost.:{_PORT}"): + async with client.session.get(f"{on_ssm}/", headers={"Host": host}) as resp: + assert resp.status == 421, host + assert await resp.text() == "misdirected request" + with pytest.raises(aiohttp.WSServerHandshakeError) as refused: + await client.session.ws_connect(f"{on_ssm}/live", headers={"Host": _HOST}) + assert refused.value.status == 421 + assert backend.seen == [] + # The same request on the dashboard's own listener is still served. + resp = await client.get("/", headers={"Host": _HOST}) + assert resp.status == 200 + assert await resp.text() == "framed page" + assert [s["target"] for s in backend.seen] == ["/"] + + +class _Audit: + """Stands in for the security event log, keeping each row it is handed.""" + + def __init__(self) -> None: + self.rows: list[dict[str, Any]] = [] + + def log_api_access(self, **row: Any) -> None: + self.rows.append(row) + + +@pytest.mark.asyncio +async def test_each_serve_and_refusal_is_audited( + gateway: TestClient, backend: _Backend, monkeypatch: pytest.MonkeyPatch +) -> None: + audit = _Audit() + monkeypatch.setattr(awo, "sel", lambda: audit) + served = await gateway.post("/doc/1?x=2", data=b"edit", headers={"Host": _HOST}) + assert served.status == 200 + async with asyncio.timeout(FALLBACK_TIMEOUT_SECS): + ws = await gateway.ws_connect("/live?k=v", headers={"Host": _HOST}, protocols=("chat",)) + await ws.close() + refused = await gateway.get("/", headers={"Host": f"nosuch.apps.localhost:{_PORT}"}) + assert refused.status == 404 + assert [(r["outcome"], r["operation"], r["resources"]) for r in audit.rows] == [ + ("granted", "POST app web origin", f"{_HOST}/doc/1"), + ("granted", "GET app web origin", f"{_HOST}/live"), + ("denied", "GET app web origin", f"nosuch.apps.localhost:{_PORT}"), + ] + assert {r["source"] for r in audit.rows} == {"app_web_origin"} + + +class _BrokenSel: + """The singleton when its trust root cannot sign: every write raises.""" + + def log_api_access(self, **_row: Any) -> None: + raise RuntimeError("trust root too short to sign the chain") + + +@pytest.mark.asyncio +async def test_a_failing_audit_never_changes_the_decision( + gateway: TestClient, backend: _Backend, monkeypatch: pytest.MonkeyPatch +) -> None: + """A broken SEL loses the row; the app still loads and a refusal keeps its status.""" + monkeypatch.setattr(awo, "sel", lambda: _BrokenSel()) + for warm in (True, False): + monkeypatch.setattr(awo, "sel_is_warm", lambda warm=warm: warm) + served = await gateway.get("/", headers={"Host": _HOST}) + assert served.status == 200 + assert await served.text() == "framed page" + refused = await gateway.get("/", headers={"Host": f"nosuch.apps.localhost:{_PORT}"}) + assert refused.status == 404 + wrong_port = await gateway.get("/", headers={"Host": "demo.apps.localhost:6000"}) + assert wrong_port.status == 421 + assert len(backend.seen) == 2 + + +@pytest.mark.asyncio +async def test_a_cold_audit_singleton_is_written_off_the_event_loop( + gateway: TestClient, monkeypatch: pytest.MonkeyPatch +) -> None: + """Only a failed startup warm costs a thread hop; a warm singleton is written in place.""" + import threading + + loop_thread = threading.get_ident() + writers: list[int] = [] + + class _Recording: + def log_api_access(self, **_row: Any) -> None: + writers.append(threading.get_ident()) + + monkeypatch.setattr(awo, "sel", lambda: _Recording()) + monkeypatch.setattr(awo, "sel_is_warm", lambda: False) + await gateway.get("/", headers={"Host": f"nosuch.apps.localhost:{_PORT}"}) + monkeypatch.setattr(awo, "sel_is_warm", lambda: True) + await gateway.get("/", headers={"Host": f"nosuch.apps.localhost:{_PORT}"}) + assert len(writers) == 2 + assert writers[0] != loop_thread + assert writers[1] == loop_thread + + +def test_ws_connect_timeouts_on_every_supported_aiohttp(monkeypatch: pytest.MonkeyPatch) -> None: + """No receive bound and a 10 s close bound, spelled for the installed aiohttp. + + ``setup.cfg`` allows aiohttp 3.9, which has no ``ClientWSTimeout`` (3.11 added it). + """ + current = awo._ws_connect_timeouts() + if hasattr(aiohttp, "ClientWSTimeout"): + assert current == {"timeout": aiohttp.ClientWSTimeout(ws_receive=None, ws_close=10.0)} + monkeypatch.delattr(aiohttp, "ClientWSTimeout", raising=False) + assert awo._ws_connect_timeouts() == {"timeout": 10.0, "receive_timeout": None} + + +def test_the_websocket_message_cap_is_above_the_library_default() -> None: + """A live document sync can send one frame larger than aiohttp's 4 MiB default.""" + assert awo._MAX_WS_MESSAGE_BYTES > 4 * 1024 * 1024 + + +@pytest.mark.asyncio +async def test_an_oversized_message_from_the_page_never_reaches_the_backend( + gateway: TestClient, backend: _Backend, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setattr(awo, "_MAX_WS_MESSAGE_BYTES", 1024) + async with asyncio.timeout(FALLBACK_TIMEOUT_SECS): + ws = await gateway.ws_connect("/live", headers={"Host": _HOST}, protocols=("chat",)) + await ws.send_str("small") + assert (await ws.receive()).data == "echo:small" + await ws.send_str("x" * 2048) + closing = await ws.receive() + assert closing.type in (aiohttp.WSMsgType.CLOSE, aiohttp.WSMsgType.CLOSED) + assert ws.close_code == aiohttp.WSCloseCode.MESSAGE_TOO_BIG + await ws.close() + await async_wait_until(lambda: backend.ws_close_codes, describe=lambda: backend.ws_close_codes) + assert backend.ws_texts == ["small"] + # The backend is told why, with a code an endpoint may send. + assert backend.ws_close_codes == [aiohttp.WSCloseCode.MESSAGE_TOO_BIG] + + +@pytest.mark.asyncio +async def test_an_oversized_message_from_the_backend_closes_the_relay( + gateway: TestClient, backend: _Backend, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setattr(awo, "_MAX_WS_MESSAGE_BYTES", 1024) + # Under the cap on the way in; its echo ("echo:" + 1020 bytes) is over it. + async with asyncio.timeout(FALLBACK_TIMEOUT_SECS): + ws = await gateway.ws_connect("/live", headers={"Host": _HOST}, protocols=("chat",)) + await ws.send_str("z" * 1020) + closing = await ws.receive() + assert closing.type in (aiohttp.WSMsgType.CLOSE, aiohttp.WSMsgType.CLOSED) + assert ws.close_code == aiohttp.WSCloseCode.MESSAGE_TOO_BIG + await ws.close() + assert backend.ws_texts == ["z" * 1020] + + +@pytest.mark.asyncio +async def test_the_page_close_code_reaches_the_backend( + gateway: TestClient, backend: _Backend +) -> None: + async with asyncio.timeout(FALLBACK_TIMEOUT_SECS): + ws = await gateway.ws_connect("/live", headers={"Host": _HOST}, protocols=("chat",)) + await ws.send_str("hi") + assert (await ws.receive()).data == "echo:hi" + await ws.close(code=4000) + await async_wait_until(lambda: backend.ws_close_codes, describe=lambda: backend.ws_close_codes) + assert backend.ws_close_codes == [4000] + + +@pytest.mark.asyncio +async def test_the_backend_close_code_reaches_the_page( + gateway: TestClient, backend: _Backend +) -> None: + async with asyncio.timeout(FALLBACK_TIMEOUT_SECS): + ws = await gateway.ws_connect("/live", headers={"Host": _HOST}, protocols=("chat",)) + await ws.send_str("bye") + closing = await ws.receive() + assert closing.type == aiohttp.WSMsgType.CLOSE + assert closing.data == 4001 + await ws.close() + + +@pytest.mark.asyncio +async def test_a_close_with_no_status_closes_both_legs_normally( + gateway: TestClient, backend: _Backend +) -> None: + """A browser's plain ``ws.close()`` sends an empty close frame; aiohttp reads it as 0.""" + async with asyncio.timeout(FALLBACK_TIMEOUT_SECS): + ws = await gateway.ws_connect("/live", headers={"Host": _HOST}, protocols=("chat",)) + await ws.send_str("hi") + assert (await ws.receive()).data == "echo:hi" + writer = getattr(ws, "_writer", None) + assert writer is not None and hasattr(writer, "send_frame"), "aiohttp writer API moved" + await writer.send_frame(b"", aiohttp.WSMsgType.CLOSE) + closing = await ws.receive() + assert closing.type == aiohttp.WSMsgType.CLOSE + assert closing.data == aiohttp.WSCloseCode.OK + await ws.close() + await async_wait_until(lambda: backend.ws_close_codes, describe=lambda: backend.ws_close_codes) + assert backend.ws_close_codes == [aiohttp.WSCloseCode.OK] + + +@pytest.mark.parametrize( + ("ended_with", "relayed"), + [ + (None, 1000), + (0, 1000), + (1005, 1000), + (1006, 1001), + (1015, 1001), + (999, 1002), + (5000, 1002), + (1000, 1000), + (1009, 1009), + (4000, 4000), + ], +) +def test_only_a_sendable_close_code_is_relayed(ended_with: int | None, relayed: int) -> None: + assert awo._close_code_to_relay(ended_with) == relayed + + +@pytest.mark.asyncio +async def test_unreachable_backend_is_502(gateway: TestClient, backend: _Backend) -> None: + await backend.stop() + resp = await gateway.get("/", headers={"Host": _HOST}) + assert resp.status == 502 + + +# ── who may be served ──────────────────────────────────────────────────────── + + +@pytest.mark.parametrize( + ("backend_cfg", "enabled", "port", "served"), + [ + ({"entryPoint": "s.py", "webOrigin": True}, True, 9107, True), + ({"entryPoint": "s.py", "webOrigin": True}, False, 9107, False), + ({"entryPoint": "s.py"}, True, 9107, False), + ({"entryPoint": "s.py", "webOrigin": True}, True, None, False), + ], +) +@pytest.mark.asyncio +async def test_backend_port_requires_enabled_opted_in_running( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + backend_cfg: dict[str, Any], + enabled: bool, + port: int | None, + served: bool, +) -> None: + import kiro_crew.apps.backend as backend_mod + import kiro_crew.apps.manager as manager + + manifest = AppManifest.from_dict( + { + "name": "demo", + "version": "1.0.0", + "displayName": "D", + "description": "d", + "backend": backend_cfg, + } + ) + monkeypatch.setattr( + manager, "get_app_manifest", lambda name: manifest if name == "demo" else None + ) + monkeypatch.setattr(manager, "is_app_enabled", lambda _name: enabled) + monkeypatch.setattr(backend_mod, "get_app_backend_port", lambda _name: port) + assert (await awo._backend_port("demo")) == (port if served else None) + assert await awo._backend_port("missing") is None + + +def test_dashboard_csrf_refuses_an_app_web_origin() -> None: + """A page on an app web origin cannot post to a dashboard API.""" + from unittest.mock import MagicMock + + from kiro_crew.dashboard.origin import check_origin + + request = MagicMock() + request.app = {"allowed_origins": set(_ALLOWED)} + request.remote = "127.0.0.1" + request.headers = {"Origin": f"http://{_HOST}", "Host": f"localhost:{_PORT}"} + assert check_origin(request) is False + # Same request from the dashboard itself still passes. + request.headers = {"Origin": f"http://localhost:{_PORT}", "Host": f"localhost:{_PORT}"} + assert check_origin(request) is True + + +def test_dashboard_csp_admits_app_web_origins() -> None: + """The dashboard may frame and probe an app web origin, and no wider ``*.`` name.""" + from types import SimpleNamespace + + from kiro_crew.dashboard.server import _apply_security_headers + + app = web.Application() + app["state"] = SimpleNamespace(instances_manager=None) + app["allowed_origins"] = set(_ALLOWED) + resp = web.Response(text="ok") + _apply_security_headers(resp, app) + csp = resp.headers["Content-Security-Policy"] + directives = {d.split()[0]: d.split()[1:] for d in csp.split(";") if d.strip()} + for name in ("frame-src", "connect-src"): + wildcards = [s for s in directives[name] if s.startswith("http://*.")] + assert wildcards == ["http://*.apps.localhost:*"], (name, wildcards) diff --git a/test/test_dashboard_security_headers.py b/test/test_dashboard_security_headers.py index 0288f4a3a10e..438a90bf4aba 100644 --- a/test/test_dashboard_security_headers.py +++ b/test/test_dashboard_security_headers.py @@ -294,12 +294,12 @@ def test_csp_connect_src_allows_loopback_liveness_probe(self) -> None: assert "*.cloudfront.net" not in connect_src def test_csp_connect_src_stays_local_with_public_origin_configured(self) -> None: - """connect-src is a fixed list: 'self', loopback and esm.sh. A - public dashboard origin in the allowed-origin set does not reach it. + """connect-src is a fixed list: 'self', loopback, app web origins and + esm.sh. A public dashboard origin in the allowed-origin set does not reach it. A dashboard behind a reverse proxy is served same-origin, so 'self' already admits its own wss:// socket (docs/guides/remote-and-mobile.md, "Behind a reverse proxy").""" - allowed = {"'self'", "https://esm.sh"} + allowed = {"'self'", "https://esm.sh", "http://*.apps.localhost:*"} for host in ("localhost", "127.0.0.1", "0.0.0.0"): allowed |= {f"{scheme}://{host}:*" for scheme in ("http", "https", "ws")} for with_instances in (False, True): diff --git a/test/test_dashboard_server_composition_contract.py b/test/test_dashboard_server_composition_contract.py index a637b92e77f5..2984dcd6933b 100644 --- a/test/test_dashboard_server_composition_contract.py +++ b/test/test_dashboard_server_composition_contract.py @@ -385,6 +385,7 @@ def test_the_shared_state_keeps_its_identity() -> None: "kiro_crew.apps.builtin_adoption": ( "apply_builtin_adoptions released_builtin_packages stage_builtin_adoptions" ), + "kiro_crew.apps.app_web_origin": "APP_WEB_ORIGIN_CSP_SOURCE build_app_web_origin_middleware", "kiro_crew.apps.builtins": "BUILTIN_NAMES", "kiro_crew.apps.manager": "sweep_interrupted_updates", "kiro_crew.apps.builtin_adoption_gate": "adopted_app_own_mcp_servers", @@ -500,7 +501,7 @@ def test_the_lazy_imports_stay_inside_the_functions_that_need_them() -> None: for alias in node.names: local.setdefault(alias.asname or alias.name, set()).add(alias.name) assert local == {name: {module} for name, module in expected.items()} - assert len(expected) == 154 + assert len(expected) == 156 def test_a_star_import_carries_the_moved_public_names(tmp_path: Path) -> None: diff --git a/test/test_dashboard_server_composition_contract_reach.py b/test/test_dashboard_server_composition_contract_reach.py index 10ea5d096210..4a21ec655311 100644 --- a/test/test_dashboard_server_composition_contract_reach.py +++ b/test/test_dashboard_server_composition_contract_reach.py @@ -660,7 +660,8 @@ def test_the_whole_census_holds_the_known_rebinds_and_an_owner_s_definitions() - #: outermost, the relay-path header rule is next so it reads a verified handover before #: any inner layer, the client-sent relay-header strip sits just inside it so no inner #: layer reads a client-sent relay header, the -#: deny-audit boundary is outer to every barrier that can refuse, the SEL request +#: deny-audit boundary is outer to every barrier that can refuse, the app web origin +#: router is outer to the host canonicalization and the ``Host`` barrier, the SEL request #: audit is inner to them, the per-slot ownership checkpoint is inner to token auth #: and the audit record, and the workflow and crewmate-prune gates, the Shared Crew #: team-config gate and the change-card hook (innermost, after auth has classified @@ -671,6 +672,7 @@ def test_the_whole_census_holds_the_known_rebinds_and_an_owner_s_definitions() - ("_relay_ingress", "relay_ingress_middleware.."), ("relay_header_strip_middleware", "relay_header_strip_middleware"), ("deny_audit_middleware", "_make_deny_audit_middleware.."), + ("app_web_origin_middleware", "build_app_web_origin_middleware.."), ("host_canonical_redirect", "build_host_canonical_redirect.."), ("host_validation_middleware", "_make_host_validation_middleware.."), ("reject_compressed_body_middleware", "reject_compressed_body_middleware"), diff --git a/test/test_ssm_loopback_trust_sites.py b/test/test_ssm_loopback_trust_sites.py index d9ba837bedc9..d0bf370405a2 100644 --- a/test/test_ssm_loopback_trust_sites.py +++ b/test/test_ssm_loopback_trust_sites.py @@ -86,8 +86,12 @@ def test_an_ssm_request_mints_no_bearer_link() -> None: # ── every site that trusts a peer address ── #: ``is_direct_local_request(...)`` call sites per file. Each is covered by the -#: predicate's SSM refusal above. +#: predicate's SSM refusal above, except where its comment says otherwise. PREDICATE_SITES = { + # The app web origin router runs ahead of token auth, so the SSM gate has not + # set its mark yet and the predicate alone would pass an SSM request. The + # router refuses by listener first (``SsmGate.owns``, the socket's local port). + "apps/app_web_origin.py": 1, "dashboard/file_api/desktop.py": 1, "dashboard/handlers/core.py": 2, "dashboard/handlers/external_terminal.py": 1, diff --git a/website/public/vendor/kirocrew-app-sdk.mjs b/website/public/vendor/kirocrew-app-sdk.mjs index b28c4b8f3caa..f39b02c3bc2b 100644 --- a/website/public/vendor/kirocrew-app-sdk.mjs +++ b/website/public/vendor/kirocrew-app-sdk.mjs @@ -8,6 +8,8 @@ export const { fmtNumber, fmtCurrency, fmtDate, fmtTime, fmtDateTime, fmtRelative, compareText, // The App Kit seam level, so an app can feature-detect what this host provides. APP_SDK_LEVEL, + // An app's own site on the dashboard's port (level 8). + appWebOrigin, // Marker protocol. Naming an export the host does not provide is a load-time failure for the // whole app, so this list is checked against the protocol barrel by chatProtocolBoundary.test.ts. parseOptions, deriveFollowUpOptions, extractSteeringAcks, stripPartialOptionMarker, diff --git a/website/src/app-sdk/index.ts b/website/src/app-sdk/index.ts index ffe897e1cee2..70e2d3139d4d 100644 --- a/website/src/app-sdk/index.ts +++ b/website/src/app-sdk/index.ts @@ -638,5 +638,7 @@ export { useImeGuard } from '../hooks/useImeGuard' export { useLanguageGeneration } from '../i18n/useLanguageGeneration' export { activeLocale, fmtNumber, fmtCurrency, fmtDate, fmtTime, fmtDateTime, fmtRelative, compareText } from '../i18n/format' export type { NumberOptions, DateStyleOptions, RelativeStyle } from '../i18n/format' +// An app's own site on the dashboard's port, for a backend that frames its own pages (level 8). +export { appWebOrigin } from './webOrigin' // The App Kit seam level; an app feature-detects the seams above by it. export { APP_SDK_LEVEL } from './sdkLevel' diff --git a/website/src/app-sdk/webOrigin.test.ts b/website/src/app-sdk/webOrigin.test.ts new file mode 100644 index 000000000000..979c28e1391e --- /dev/null +++ b/website/src/app-sdk/webOrigin.test.ts @@ -0,0 +1,31 @@ +import { describe, expect, it } from 'vitest' +import { appWebOrigin } from './webOrigin' + +const at = (hostname: string, port = '5476', protocol = 'http:') => ({ hostname, port, protocol }) + +describe('appWebOrigin', () => { + it.each(['localhost', '127.0.0.1', 'kirocrew.localhost', 'LOCALHOST'])( + 'names the app site on the dashboard port from %s', + (hostname) => { + expect(appWebOrigin('docs', at(hostname))).toBe('http://docs.apps.localhost:5476') + }, + ) + + it('keeps the port the browser used, so a tunnel on another local port still matches', () => { + expect(appWebOrigin('docs', at('localhost', '6000'))).toBe('http://docs.apps.localhost:6000') + expect(appWebOrigin('docs', at('localhost', ''))).toBe('http://docs.apps.localhost:80') + }) + + it.each([ + ['an IPv6 dashboard', at('[::1]')], + ['a Remote Crew pane name', at('box.localhost')], + ['a published host', at('crew.example.com')], + ['https', at('localhost', '5476', 'https:')], + ])('has none on %s', (_label, location) => { + expect(appWebOrigin('docs', location)).toBeNull() + }) + + it.each(['', 'Docs', 'a.b', '-x', 'x-', 'a'.repeat(64), 'a_b'])('refuses the app name %j', (name) => { + expect(appWebOrigin(name, at('localhost'))).toBeNull() + }) +}) diff --git a/website/src/app-sdk/webOrigin.ts b/website/src/app-sdk/webOrigin.ts new file mode 100644 index 000000000000..24d6221b51ae --- /dev/null +++ b/website/src/app-sdk/webOrigin.ts @@ -0,0 +1,28 @@ +/** + * An app's web origin: `http://.apps.localhost:`, which the + * gateway serves for an enabled app whose manifest sets `backend.webOrigin: true` + * (`apps/app_web_origin.py`). The browser resolves every `*.localhost` name to its + * own loopback, so the origin rides whatever connection carries the dashboard, + * including one `ssh -L` forward from another machine. + * + * Only a dashboard opened on one of its own loopback names over plain http has + * one: the gateway serves app web origins only to direct local peers, and a + * tunnel or published HTTPS host has no wildcard name to offer. Everywhere else + * this answers `null`, and the app keeps whatever it did before. App Kit seam + * level 8. + */ + +/** One DNS label, as the gateway requires of the app name. */ +const LABEL_RE = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/ + +/** The dashboard's own loopback names, as `location.hostname` spells them. */ +// CSP frame-ancestors cannot express a bracketed IPv6 host source. +const DASHBOARD_LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', 'kirocrew.localhost']) + +export function appWebOrigin(appName: string, location: Pick = window.location): string | null { + if (!LABEL_RE.test(appName)) return null + if (location.protocol !== 'http:') return null + if (!DASHBOARD_LOOPBACK_HOSTS.has(location.hostname.toLowerCase())) return null + const port = location.port || '80' + return `http://${appName}.apps.localhost:${port}` +}