diff --git a/.github/workflows/pm-console-android.yml b/.github/workflows/pm-console-android.yml index b99151f374..aeb2f582e5 100644 --- a/.github/workflows/pm-console-android.yml +++ b/.github/workflows/pm-console-android.yml @@ -3,11 +3,16 @@ name: pm-console android # Builds the PM console's Android app (pm-stack/console/android): a # Trusted Web Activity over https://pm.security.cab. Manual only: it is # run when the app changes, which is rarely, since the app is the site. +# +# With the signing secrets set, the APK is signed here and attached to +# the release. Without them the build is unsigned and kept as an +# artifact, to be signed by pm-stack/console/android/sign.sh on the +# machine that holds the key. on: workflow_dispatch: inputs: publish: - description: "Attach the signed APK to the release pm-console-android" + description: "Attach the APK to the release pm-console-android (signed builds only)" type: boolean default: true @@ -16,30 +21,33 @@ permissions: jobs: build: - name: "build: signed APK" + name: "build: APK" runs-on: ubuntu-latest timeout-minutes: 25 permissions: contents: write steps: - uses: actions/checkout@v7 - - name: Build, sign and check the signing certificate + - name: Build, and sign when the signing secrets are set + id: build env: KEYSTORE_B64: ${{ secrets.PM_CONSOLE_ANDROID_KEYSTORE_B64 }} PM_ANDROID_KEYSTORE_PASSWORD: ${{ secrets.PM_CONSOLE_ANDROID_KEYSTORE_PASSWORD }} run: | - if [ -z "$KEYSTORE_B64" ] || [ -z "$PM_ANDROID_KEYSTORE_PASSWORD" ]; then - echo "::error::The signing secrets PM_CONSOLE_ANDROID_KEYSTORE_B64 and PM_CONSOLE_ANDROID_KEYSTORE_PASSWORD are not set." - exit 1 - fi bash pm-stack/console/android/build.sh + if [ -f pm-stack/console/android/app/build/outputs/apk/release/pm-console.apk ]; then + echo "signed=true" >>"$GITHUB_OUTPUT" + else + echo "signed=false" >>"$GITHUB_OUTPUT" + echo "::notice::Built unsigned: the signing secrets are not set. Sign the artifact with pm-stack/console/android/sign.sh on the machine that holds the key." + fi - uses: actions/upload-artifact@v7 with: - name: pm-console-apk - path: pm-stack/console/android/app/build/outputs/apk/release/pm-console.apk + name: ${{ steps.build.outputs.signed == 'true' && 'pm-console-apk' || 'pm-console-apk-unsigned' }} + path: pm-stack/console/android/app/build/outputs/apk/release/*.apk if-no-files-found: error - name: Attach to the release - if: inputs.publish + if: inputs.publish && steps.build.outputs.signed == 'true' env: GH_TOKEN: ${{ github.token }} run: | diff --git a/pm-stack/PORTS.md b/pm-stack/PORTS.md index f2f369e86a..876d6c6c31 100644 --- a/pm-stack/PORTS.md +++ b/pm-stack/PORTS.md @@ -39,18 +39,18 @@ fleet-config default (see the CONNECT-UDP rows). ## pm-stack -| Port | Service | Bind | Source of truth | Status | -| ---- | ---------------------------------------- | -------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------- | -| 4870 | pm-aggregator (dashboard HTTP) | loopback + tailnet | `pm-stack/aggregator/src/config.ts` (`PM_AGG_PORT` default 4870); `nixos/services/pm-stack/default.nix` | live | -| 4871 | pm-aggregator freshness IPC (`/publish`) | loopback | `pm-stack/aggregator/src/config.ts:148` (`PM_AGG_FRESHNESS_PORT` default 4871); `nixos/services/pm-stack/default.nix:163` | live | -| 4872 | pm-console (operations) | loopback | `pm-stack/console/src/config.ts` (`PM_CONSOLE_PORT` default 4872); `pm-stack/systemd/pm-console.service`; public as `pm.security.cab/console` through the tunnel | -| 4879 | pm-dispatch (intake) | loopback + tailnet | `pm-stack/dispatch/src/config.ts:73` (`DISPATCH_PORT` default 4879); `pkgs/fleet/crates/fleet-config/src/lib.rs` `PORT_DISPATCH` | live | -| 5173 | Kaneo (Docker, `pm-stack-kaneo-1`) | loopback | `pm-stack/compose.yml:35` | live | -| 5432 | Kaneo Postgres (Docker) | container-internal only (no host bind) | `pm-stack/compose.yml`; `pm-stack/aggregator/src/topology.ts` | live (internal) | -| 6056 | ready-for-agent (UI + GraphQL) | loopback + tailnet via socket proxy | `pm-stack/aggregator/src/config.ts:209` (`PM_AGG_RFA_URL` default); `nixos/services/pm-apps/default.nix:148-166` | live | -| 7777 | Pad (Docker, `pm-pad`, v0.18.1) | loopback + tailnet | `pm-stack/pad/compose.yml:26-31` (`PAD_PORT 7777`); `nixos/services/pm-apps/default.nix:103-108` | live | -| 7801 | pm-projector (+ link registry) | loopback | `pm-stack/projector/src/config.ts:1` (`DEFAULT_PORT 7801`); `nixos/services/pm-stack/default.nix:100` | live | -| 8484 | Grist (Docker, `pm-grist`) | loopback + tailnet | `pm-stack/grist/compose.yml:30-31`; `nixos/services/pm-apps/default.nix:92-93` | live | +| Port | Service | Bind | Source of truth | Status | +| ---- | ---------------------------------------- | -------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------- | +| 4870 | pm-aggregator (dashboard HTTP) | loopback + tailnet | `pm-stack/aggregator/src/config.ts` (`PM_AGG_PORT` default 4870); `nixos/services/pm-stack/default.nix` | live | +| 4871 | pm-aggregator freshness IPC (`/publish`) | loopback | `pm-stack/aggregator/src/config.ts:148` (`PM_AGG_FRESHNESS_PORT` default 4871); `nixos/services/pm-stack/default.nix:163` | live | +| 4872 | pm-console (operations) | loopback | `pm-stack/console/src/config.ts` (`PM_CONSOLE_PORT` default 4872); `pm-stack/systemd/pm-console.service`; the tunnel sends all of `pm.security.cab` here, and it passes the dashboard's paths to 4870 for a signed-in owner | +| 4879 | pm-dispatch (intake) | loopback + tailnet | `pm-stack/dispatch/src/config.ts:73` (`DISPATCH_PORT` default 4879); `pkgs/fleet/crates/fleet-config/src/lib.rs` `PORT_DISPATCH` | live | +| 5173 | Kaneo (Docker, `pm-stack-kaneo-1`) | loopback | `pm-stack/compose.yml:35` | live | +| 5432 | Kaneo Postgres (Docker) | container-internal only (no host bind) | `pm-stack/compose.yml`; `pm-stack/aggregator/src/topology.ts` | live (internal) | +| 6056 | ready-for-agent (UI + GraphQL) | loopback + tailnet via socket proxy | `pm-stack/aggregator/src/config.ts:209` (`PM_AGG_RFA_URL` default); `nixos/services/pm-apps/default.nix:148-166` | live | +| 7777 | Pad (Docker, `pm-pad`, v0.18.1) | loopback + tailnet | `pm-stack/pad/compose.yml:26-31` (`PAD_PORT 7777`); `nixos/services/pm-apps/default.nix:103-108` | live | +| 7801 | pm-projector (+ link registry) | loopback | `pm-stack/projector/src/config.ts:1` (`DEFAULT_PORT 7801`); `nixos/services/pm-stack/default.nix:100` | live | +| 8484 | Grist (Docker, `pm-grist`) | loopback + tailnet | `pm-stack/grist/compose.yml:30-31`; `nixos/services/pm-apps/default.nix:92-93` | live | ## Fleet (brokers, laptop-agent, CONNECT-UDP) diff --git a/pm-stack/README.md b/pm-stack/README.md index de905767ef..532d532cbd 100644 --- a/pm-stack/README.md +++ b/pm-stack/README.md @@ -17,14 +17,14 @@ Phase 2 (2026-10-24) added three layers, each in its own subdirectory with the same deploy shape (SOPS → mode-600 env → compose/unit → health gate): -| Layer | Piece | Version / pin | Reach | Deployment definition | -| --------- | --------------- | ---------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | --------------------- | -| Dispatch | ready-for-agent | npm `ready-for-agent@1.1.0` (no container image exists upstream) | UI + GraphQL on `6056`, loopback + tailnet (app loopback-only; tailnet via socket proxy, #1181) | `ready-for-agent/` | -| Planning | Pad | `ghcr.io/perpetualsoftware/pad:0.18.1`, pinned by digest | `127.0.0.1:7777` + host tailnet address (`PM_STACK_TAILNET_IP`):7777; no tunnel hostname | `pad/` | -| Tables | Grist | `gristlabs/grist-oss:v1.7.21`, pinned by digest | `127.0.0.1:8484` + host tailnet address (`PM_STACK_TAILNET_IP`):8484; no tunnel hostname | `grist/` | -| Dashboard | Aggregator | this repo (Bun app, user unit `pm-aggregator`) | `127.0.0.1:4870` + tailnet `amd-6.raptor-pumpkinseed.ts.net:4870`; no public route | `aggregator/` | -| Intake | pm-dispatch | this repo (Bun app, user unit `pm-dispatch`) | `127.0.0.1:4879` + tailnet; public via tunnel as `dispatch.security.cab` | `dispatch/` | -| Console | pm-console | this repo (Bun app, user unit `pm-console`) | `127.0.0.1:4872`; public behind sign-in as `pm.security.cab/console` (dashboard at `/`) | `console/` | +| Layer | Piece | Version / pin | Reach | Deployment definition | +| --------- | --------------- | ---------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------- | --------------------- | +| Dispatch | ready-for-agent | npm `ready-for-agent@1.1.0` (no container image exists upstream) | UI + GraphQL on `6056`, loopback + tailnet (app loopback-only; tailnet via socket proxy, #1181) | `ready-for-agent/` | +| Planning | Pad | `ghcr.io/perpetualsoftware/pad:0.18.1`, pinned by digest | `127.0.0.1:7777` + host tailnet address (`PM_STACK_TAILNET_IP`):7777; no tunnel hostname | `pad/` | +| Tables | Grist | `gristlabs/grist-oss:v1.7.21`, pinned by digest | `127.0.0.1:8484` + host tailnet address (`PM_STACK_TAILNET_IP`):8484; no tunnel hostname | `grist/` | +| Dashboard | Aggregator | this repo (Bun app, user unit `pm-aggregator`) | `127.0.0.1:4870` + tailnet `amd-6.raptor-pumpkinseed.ts.net:4870`; no public route | `aggregator/` | +| Intake | pm-dispatch | this repo (Bun app, user unit `pm-dispatch`) | `127.0.0.1:4879` + tailnet; public via tunnel as `dispatch.security.cab` | `dispatch/` | +| Console | pm-console | this repo (Bun app, user unit `pm-console`) | `127.0.0.1:4872`; public behind sign-in as `pm.security.cab` (console at `/console`, dashboard at `/` through the console's gate) | `console/` | ready-for-agent runs as a systemd **user unit** (like `pm-tunnel`) because upstream ships only an npm package; Pad and Grist run as diff --git a/pm-stack/console/README.md b/pm-stack/console/README.md index b5854da07f..c996761f03 100644 --- a/pm-stack/console/README.md +++ b/pm-stack/console/README.md @@ -1,8 +1,17 @@ # pm-console -The write side of the PM stack. The dashboard (`pm-aggregator`) shows the -fleet; the console acts on it, from a phone or a browser, at -`https://pm.security.cab/console/`. +The write side of the PM stack, and the gate in front of it. The +dashboard (`pm-aggregator`) shows the fleet; the console acts on it, from +a phone or a browser, at `https://pm.security.cab/console/`. + +The whole public hostname is routed here. `/console` is this service. +Every other path is the dashboard's, and the console passes it through +only for a verified owner: the dashboard has no sign-in of its own, so +the check is made at this origin as well as at the edge, and does not +depend on how the edge reads a path. Writes from another site are +refused. Five files a phone fetches before anyone has signed in are +public, matched exactly: `/manifest.webmanifest` and the four icons under +`/icons/`. | Section | What you can do | What runs | | ------------- | ----------------------------------------------------------------------------------- | --------------------------------------- | @@ -56,15 +65,16 @@ itself comes from this machine and it crossed no proxy (loopback Host, no forwarding headers). The connection's address is the test, since headers are the caller's to write; for the same reason the console only listens on loopback and refuses to start on any other address. Everything else -needs a token. Two paths answer without one: `/console/health` and -`/.well-known/assetlinks.json` (the Android app's link to this origin). +needs a token. Outside the install files above, two paths answer without +one: `/console/health` and `/.well-known/assetlinks.json` (the Android +app's link to this origin). ## Run ```bash bash pm-stack/console/install.sh # user unit pm-console, port 4872, loopback only python3 pm-stack/console/scripts/expose.py --check # what public exposure would change -python3 pm-stack/console/scripts/expose.py # tunnel routes, DNS, Access, console env +python3 pm-stack/console/scripts/expose.py # Access, console env, tunnel route, DNS cd pm-stack/console && bun test ``` @@ -82,12 +92,14 @@ the route if the console does not come up with its sign-in settings. | `PM_CONSOLE_ACCESS_TEAM_DOMAIN`, `PM_CONSOLE_ACCESS_AUD` | unset | The Access issuer; set together | | `PM_CONSOLE_ISSUERS_FILE` | unset | JSON list of further issuers | | `PM_CONSOLE_CERT_NAMES` | none | Certificate common names that are the owner | +| `PM_CONSOLE_DASHBOARD_URL` | `http://127.0.0.1:4870` | The dashboard behind the gate; loopback, or empty | | `PM_CONSOLE_UNITS`, `PM_CONSOLE_PROTECTED_UNITS` | the stack's units | Units the console manages; units it will not stop | | `PM_CONSOLE_ANDROID_PACKAGE`, `PM_CONSOLE_ANDROID_SHA256` | `today.developing.pmconsole`, none | The Android app's identity in the asset-links file | | `PM_CONSOLE_REPO`, `PM_CONSOLE_QUEUE` | `developing-today/code`, `repo-health-code-pilot` | What it operates on | -A malformed port, a listen address that is not loopback, or a malformed -issuer stops the process at boot and names the variable. +A malformed port, a listen address or dashboard address that is not +loopback, or a malformed issuer stops the process at boot and names the +variable. ## Android diff --git a/pm-stack/console/android/README.md b/pm-stack/console/android/README.md index 503df8fa3f..dd35f6877b 100644 --- a/pm-stack/console/android/README.md +++ b/pm-stack/console/android/README.md @@ -19,17 +19,29 @@ If the two disagree the app still works, with a browser bar at the top. ## Build ```bash -gh workflow run pm-console-android.yml # signed APK, attached to the release pm-console-android +gh workflow run pm-console-android.yml # builds the APK in CI bash pm-stack/console/android/build.sh # locally: needs JAVA_HOME (17 or 21) and ANDROID_HOME +bash pm-stack/console/android/sign.sh app-release-unsigned.apk # sign a CI build with the key on this machine ``` -The workflow signs with the repository secrets -`PM_CONSOLE_ANDROID_KEYSTORE_B64` and -`PM_CONSOLE_ANDROID_KEYSTORE_PASSWORD`, and fails unless the APK's -certificate matches `signing-fingerprint.txt`. The keystore itself is on -the pm-stack host at `~/.local/state/pm-console/android/release.p12`. -Losing it means a new key, a new fingerprint and a reinstall; nothing -else depends on it. +The signing key is on the pm-stack host at +`~/.local/state/pm-console/android/release.p12`, and it stays there. The +workflow builds an unsigned APK and keeps it as the artifact +`pm-console-apk-unsigned`; `sign.sh` on the host signs it, checks the +certificate against `signing-fingerprint.txt`, and the signed +`pm-console.apk` is uploaded to the release: + +```bash +gh run download -n pm-console-apk-unsigned -D /tmp/pm-apk +nix shell nixpkgs#apksigner -c bash pm-stack/console/android/sign.sh /tmp/pm-apk/app-release-unsigned.apk +gh release upload pm-console-android /tmp/pm-apk/pm-console.apk --clobber +``` + +If the repository secrets `PM_CONSOLE_ANDROID_KEYSTORE_B64` and +`PM_CONSOLE_ANDROID_KEYSTORE_PASSWORD` are ever set, the workflow signs +and publishes by itself instead, and fails unless the certificate +matches. Losing the key means a new key, a new fingerprint and a +reinstall; nothing else depends on it. ## Install diff --git a/pm-stack/console/android/sign.sh b/pm-stack/console/android/sign.sh new file mode 100644 index 0000000000..eaf120ea80 --- /dev/null +++ b/pm-stack/console/android/sign.sh @@ -0,0 +1,51 @@ +#!/usr/bin/env bash +# sign.sh — sign an unsigned build of the PM console APK with the key on +# this machine, and check the result carries the certificate the site +# lists. For when the build ran somewhere that does not hold the key. +# +# Usage: bash sign.sh [] +# +# Inputs (environment): +# PM_ANDROID_KEYSTORE PKCS#12 keystore, key alias pmconsole +# (default ~/.local/state/pm-console/android/release.p12) +# PM_ANDROID_KEYSTORE_PASSWORD_FILE file holding its password +# (default: keystore-password beside the keystore) +# Needs apksigner on PATH (on NixOS: nix shell nixpkgs#apksigner). +# +# The password is read by apksigner from the file. It is never an +# argument, an environment value or output. +set -euo pipefail + +if [ "$#" -lt 1 ] || [ "$#" -gt 2 ]; then + echo "usage: bash sign.sh []" >&2 + exit 2 +fi +here="$(cd "$(dirname "$0")" && pwd)" +in="$1" +out="${2:-$(dirname "$in")/pm-console.apk}" +keystore="${PM_ANDROID_KEYSTORE:-$HOME/.local/state/pm-console/android/release.p12}" +password_file="${PM_ANDROID_KEYSTORE_PASSWORD_FILE:-$(dirname "$keystore")/keystore-password}" + +for f in "$in" "$keystore" "$password_file"; do + if [ ! -f "$f" ]; then + echo "sign.sh: not found: $f" >&2 + exit 1 + fi +done +if ! command -v apksigner >/dev/null 2>&1; then + echo "sign.sh: apksigner is not on PATH (on NixOS: nix shell nixpkgs#apksigner)" >&2 + exit 1 +fi + +apksigner sign --ks "$keystore" --ks-type pkcs12 --ks-key-alias pmconsole \ + --ks-pass "file:$password_file" --key-pass "file:$password_file" \ + --out "$out" "$in" + +got="$(apksigner verify --print-certs "$out" | sed -n 's/^Signer #1 certificate SHA-256 digest: //p' | tr 'a-f' 'A-F' | sed 's/../&:/g; s/:$//')" +want="$(tr -d '[:space:]' <"$here/signing-fingerprint.txt")" +if [ "$got" != "$want" ]; then + rm -f "$out" + echo "sign.sh: signed by $got, not by the certificate the site lists ($want)" >&2 + exit 1 +fi +echo "sign.sh: $out signed by $got" diff --git a/pm-stack/console/scripts/expose.py b/pm-stack/console/scripts/expose.py index 97f186ea41..468b4e08ce 100755 --- a/pm-stack/console/scripts/expose.py +++ b/pm-stack/console/scripts/expose.py @@ -2,20 +2,25 @@ """Put the PM stack on a public hostname behind sign-in, or check that it is. One hostname carries the dashboard (pm-aggregator) and the console -(pm-console). This script makes each of these true, changing only what -is not already so, and prints what it did: +(pm-console). All of it is routed to the console, which serves /console +and passes every other path to the dashboard only for a verified owner. +The dashboard has no sign-in of its own, so sign-in is checked twice: by +Cloudflare Access at the edge, and by the console at the origin. + +This script makes each of these true, changing only what is not already +so, and prints what it did: 1. A Cloudflare Access application covers the hostname, with one policy: the owner's address. Sign-in methods are the one-time PIN, plus Google when the secrets `google.access-sso.client-id` and `google.access-sso.client-secret` exist. -2. Three public paths bypass sign-in, because a phone fetches them before - anyone has signed in: the asset-links file, the install manifest and - its icons. None of them says anything about the fleet. +2. Three public paths bypass sign-in at the edge, because a phone + fetches them before anyone has signed in: the asset-links file, the + install manifest and its icons. The console serves exactly those + files to an unsigned caller and nothing else. 3. The console's environment file names the Access issuer and the owner, and the console is running with it. -4. The tunnel routes the hostname: /console and the Android asset-links - file to the console, every other path to the dashboard. +4. The tunnel routes the hostname to the console. 5. DNS points the hostname at the tunnel. The gate comes first and the route last, so the origin is never @@ -44,8 +49,12 @@ TUNNEL = "amd-6-pm-stack" CONSOLE = "http://localhost:4872" UNIT = "pm-console.service" -DASHBOARD = "http://localhost:4870" -CONSOLE_PATHS = r"^/(console($|/)|\.well-known/assetlinks\.json$)" +# The sign-in cookie is not sent on another site's requests, and page +# scripts cannot read it. +APP_SETTINGS = { + "same_site_cookie_attribute": "lax", + "http_only_cookie_attribute": True, +} PUBLIC_PATHS = ("/.well-known/assetlinks.json", "/manifest.webmanifest", "/icons") GOOGLE_ID = "google.access-sso.client-id" GOOGLE_SECRET = "google.access-sso.client-secret" @@ -109,20 +118,18 @@ def ensure_routes( cf: Cloudflare, account: str, host: str, tunnel: str, config: dict, console: str ) -> None: ingress = config.get("ingress") or [] - wanted = [ - # A rule with a path must come before the same hostname's rule without one. - {"hostname": host, "path": CONSOLE_PATHS, "service": console}, - {"hostname": host, "service": DASHBOARD}, - ] + # One rule, no path: every path on the hostname goes to the console, + # which is the only thing that decides what reaches the dashboard. + wanted = [{"hostname": host, "service": console}] def plain(rule: dict) -> dict: return {k: rule[k] for k in ("hostname", "path", "service") if k in rule} - # cloudflared takes the first rule that matches. This host's rules go + # cloudflared takes the first rule that matches. This host's rule goes # ahead of every other rule, so a wildcard such as *.security.cab can - # never take the host's traffic and send it somewhere with no /console. - if [plain(r) for r in ingress[:2]] == wanted and all( - r.get("hostname") != host for r in ingress[2:] + # never take the host's traffic and send it somewhere with no gate. + if [plain(r) for r in ingress[:1]] == wanted and all( + r.get("hostname") != host for r in ingress[1:] ): return rest = [r for r in ingress if r.get("hostname") != host] @@ -130,7 +137,7 @@ def plain(rule: dict) -> dict: rest.append({"service": "http_status:404"}) config["ingress"] = wanted + rest cf.change( - f"tunnel {TUNNEL}: route {host} (/console -> console, the rest -> dashboard)", + f"tunnel {TUNNEL}: route {host} to the console", "PUT", f"/accounts/{account}/cfd_tunnel/{tunnel}/configurations", {"config": config}, @@ -231,6 +238,7 @@ def ensure_app( decision: str, include: list, idps: list[str] | None, + settings: dict | None = None, ) -> str | None: app = next( ( @@ -250,6 +258,7 @@ def ensure_app( } if idps: body["allowed_idps"] = idps + body.update(settings or {}) app = cf.change( f"access: application for {domain}", "POST", @@ -258,14 +267,20 @@ def ensure_app( ) if app is None: return None - elif idps and sorted(app.get("allowed_idps") or []) != sorted(idps): - app["allowed_idps"] = idps - cf.change( - f"access: sign-in methods for {domain}", - "PUT", - f"/accounts/{account}/access/apps/{app['id']}", - app, - ) + else: + stale = [k for k, v in (settings or {}).items() if app.get(k) != v] + if idps and sorted(app.get("allowed_idps") or []) != sorted(idps): + stale.append("allowed_idps") + if stale: + app.update(settings or {}) + if idps: + app["allowed_idps"] = idps + cf.change( + f"access: settings for {domain} ({', '.join(sorted(stale))})", + "PUT", + f"/accounts/{account}/access/apps/{app['id']}", + app, + ) policies = cf.get(f"/accounts/{account}/access/apps/{app['id']}/policies") # Exclude and require rules change who a policy lets in, so a policy # carrying either is not the one this script writes. @@ -433,6 +448,7 @@ def main() -> int: "allow", [{"email": {"email": args.owner}}], idps, + APP_SETTINGS, ) if aud: ensure_console( diff --git a/pm-stack/console/scripts/test_expose.py b/pm-stack/console/scripts/test_expose.py index c1d7cb80a2..5ebf315bf7 100755 --- a/pm-stack/console/scripts/test_expose.py +++ b/pm-stack/console/scripts/test_expose.py @@ -51,6 +51,10 @@ def call(self, method, path, body=None): if method == "POST": self.idps.append({"id": f"idp-{body['type']}", **body}) result = self.idps[-1] if method == "POST" else self.idps + elif "/access/apps/" in path and method == "PUT": + app = next(a for a in self.apps if a["id"] == path.split("/")[-1]) + app.update(body) + result = app elif path.endswith("/access/apps"): if method == "POST": self.apps.append( @@ -160,17 +164,18 @@ def test_the_gate_exists_before_the_route(self): ], ) self.assertEqual(main["allowed_idps"], ["idp-onetimepin"]) + self.assertEqual(main["same_site_cookie_attribute"], "lax") + self.assertIs(main["http_only_cookie_attribute"], True) for path in expose.PUBLIC_PATHS: app = next(a for a in account.apps if a["domain"] == HOST + path) self.assertEqual( [p["decision"] for p in account.policies[app["id"]]], ["bypass"] ) - # /console before the rest of the host; other hosts and the final rule kept. + # The whole host goes to the console: no path of it is routed past the gate. self.assertEqual( [(r.get("hostname"), r.get("path"), r["service"]) for r in account.ingress], [ - (HOST, expose.CONSOLE_PATHS, expose.CONSOLE), - (HOST, None, expose.DASHBOARD), + (HOST, None, expose.CONSOLE), ("kaneo.security.cab", None, "http://localhost:5173"), (None, None, "http_status:404"), ], @@ -266,6 +271,16 @@ def test_foreign_records_and_policies_are_left_alone(self): account.policies[main["id"]][0].update(extra) with self.assertRaisesRegex(SystemExit, "did not write"): run(account, self.home) + # Cookie settings changed by hand are put back. + account = Account() + run(account, self.home) + main = next(a for a in account.apps if a["domain"] == HOST) + main["same_site_cookie_attribute"] = "none" + self.assertEqual(run(account, self.home), 0) + self.assertEqual(len(account.changes), 1) + self.assertEqual(main["same_site_cookie_attribute"], "lax") + self.assertEqual(run(account, self.home), 0) + self.assertEqual(account.changes, []) # Empty lists, as the API returns them, are still this script's rule. account = Account() run(account, self.home) @@ -312,7 +327,6 @@ def test_the_route_follows_the_console_port_and_sits_ahead_of_wildcards(self): [(r.get("hostname"), r["service"]) for r in account.ingress], [ (HOST, "http://localhost:4999"), - (HOST, expose.DASHBOARD), ("*.security.cab", "http://localhost:1"), ("kaneo.security.cab", "http://localhost:5173"), (None, "http_status:404"), @@ -329,6 +343,18 @@ def test_the_route_follows_the_console_port_and_sits_ahead_of_wildcards(self): self.assertEqual(len(account.changes), 1) self.assertEqual(run(account, self.home), 0) self.assertEqual(account.changes, []) + # Rules from an earlier layout that sent part of the host straight to + # the dashboard are replaced: nothing on the host skips the console. + account.ingress = [ + {"hostname": HOST, "path": "^/console", "service": "http://localhost:4999"}, + {"hostname": HOST, "service": "http://localhost:4870"}, + {"service": "http_status:404"}, + ] + self.assertEqual(run(account, self.home), 0) + self.assertEqual( + [(r.get("hostname"), r.get("path"), r["service"]) for r in account.ingress], + [(HOST, None, "http://localhost:4999"), (None, None, "http_status:404")], + ) # A tunnel whose last rule is not a catch-all gets one. account.ingress = [{"hostname": "kaneo.security.cab", "service": "x"}] run(account, self.home) diff --git a/pm-stack/console/src/config.ts b/pm-stack/console/src/config.ts index ede68f4b93..182782781d 100644 --- a/pm-stack/console/src/config.ts +++ b/pm-stack/console/src/config.ts @@ -43,6 +43,9 @@ export interface Config { * either one cuts off the interface that would start it again. */ protectedUnits: string[]; auditFile: string; + /** The dashboard (pm-aggregator) this service fronts on the public + * hostname, or null to serve /console alone. Loopback only. */ + dashboardUrl: string | null; /** Android app identity served at /.well-known/assetlinks.json. */ androidPackage: string; androidFingerprints: string[]; @@ -151,6 +154,35 @@ export function readConfig( throw new ConfigError(`PM_CONSOLE_BIND: only a loopback address is supported, not ${JSON.stringify(bind)}`); } + // The dashboard has no sign-in of its own. The console passes requests + // to it only for a verified owner, so the address has to be one that + // nothing but this machine can reach or answer. + let dashboardUrl: string | null = env.PM_CONSOLE_DASHBOARD_URL ?? "http://127.0.0.1:4870"; + if (dashboardUrl === "") dashboardUrl = null; + if (dashboardUrl !== null) { + let parsed: URL | null = null; + try { + parsed = new URL(dashboardUrl); + } catch { + // reported below + } + const host = parsed?.hostname ?? ""; + if ( + !parsed || + parsed.protocol !== "http:" || + !(host === "127.0.0.1" || host === "localhost" || host === "[::1]") || + parsed.pathname !== "/" || + parsed.search !== "" || + parsed.username !== "" || + parsed.password !== "" + ) { + throw new ConfigError( + `PM_CONSOLE_DASHBOARD_URL: expected http://127.0.0.1: (loopback, no path), got ${JSON.stringify(dashboardUrl)}`, + ); + } + dashboardUrl = parsed.origin; + } + return { port: port(env, "PM_CONSOLE_PORT", 4872), bind, @@ -172,6 +204,7 @@ export function readConfig( ]), protectedUnits: list(env, "PM_CONSOLE_PROTECTED_UNITS", ["pm-tunnel.service", "pm-console.service"]), auditFile: env.PM_CONSOLE_AUDIT_FILE ?? `${home}/.local/state/pm-console/audit.jsonl`, + dashboardUrl, androidPackage: env.PM_CONSOLE_ANDROID_PACKAGE ?? "today.developing.pmconsole", androidFingerprints: fingerprints, }; diff --git a/pm-stack/console/src/server.ts b/pm-stack/console/src/server.ts index 7e838cc240..5ae4403cda 100644 --- a/pm-stack/console/src/server.ts +++ b/pm-stack/console/src/server.ts @@ -1,9 +1,12 @@ // pm-console: the write side of the PM stack. The dashboard // (pm-aggregator) shows the fleet; this service acts on it. // -// Everything lives under /console so one public hostname can carry both: -// the tunnel sends /console and the Android asset-links file here and -// every other path to the dashboard. +// One public hostname carries both, and all of it arrives here. /console +// is this service. Every other path is the dashboard's, passed through +// only for a verified owner: the dashboard has no sign-in of its own, so +// the check happens at this origin and does not rest on how the edge +// reads a path. Three files a phone fetches before anyone has signed in +// (the install manifest, its icons, the Android asset links) are public. import { mkdirSync, readFileSync } from "node:fs"; import { appendFile } from "node:fs/promises"; import { dirname, join } from "node:path"; @@ -24,6 +27,25 @@ const SECURITY = { "X-Content-Type-Options": "nosniff", "Referrer-Policy": "same-origin", }; +/** The dashboard's files that are public, matched against the parsed + * path in full. They say nothing about the fleet. */ +const PUBLIC_DASHBOARD = + /^\/(manifest\.webmanifest|icons\/(icon-192|icon-512|icon-maskable-512|apple-touch-icon)\.png)$/; +/** Headers that belong to one connection, not to the request or response. */ +const HOP_BY_HOP = new Set([ + "connection", + "keep-alive", + "proxy-authenticate", + "proxy-authorization", + "proxy-connection", + "te", + "trailer", + "transfer-encoding", + "upgrade", +]); +const UPSTREAM_HEADER_TIMEOUT_MS = 60_000; +const UPSTREAM_BODY_LIMIT = 16 * 1024 * 1024; + /** Longest a request may run with nothing written: above the longest * operation (a 60 second systemctl call), or the connection would drop * while the action carried on. Bun's limit is 255. */ @@ -70,6 +92,69 @@ export interface Deps { /** `peer` is the connection's remote address as the server saw it. */ identify: (req: Request, peer: string | null) => Promise; audit: (entry: Record) => Promise; + /** Reaches the dashboard. Injected so tests can stand in for it. */ + upstream?: (url: string, init: RequestInit) => Promise; +} + +/** A write must come from this site. A browser sends Origin on every + * cross-site write and Sec-Fetch-Site on every request, and the sign-in + * cookie alone must not be enough for another site to act as the owner. */ +function crossSiteWrite(req: Request): boolean { + if (req.method === "GET" || req.method === "HEAD") return false; + if (req.headers.get("sec-fetch-site") === "cross-site") return true; + const origin = req.headers.get("origin"); + if (origin === null) return false; + try { + return new URL(origin).host !== (req.headers.get("host") ?? ""); + } catch { + return true; + } +} + +/** Pass one request to the dashboard and its answer back. `open` is for + * the public files: nothing the caller sent goes with it. */ +async function toDashboard(req: Request, url: URL, deps: Deps, open: boolean): Promise { + const headers = new Headers(); + if (!open) { + for (const [name, value] of req.headers) { + if (!HOP_BY_HOP.has(name) && name !== "content-length" && name !== "accept-encoding") headers.set(name, value); + } + } + // The dashboard builds links and checks origins against the public + // name; and an uncompressed answer keeps its headers true as it passes. + headers.set("host", req.headers.get("host") ?? url.host); + headers.set("accept-encoding", "identity"); + let body: ArrayBuffer | undefined; + if (!open && req.method !== "GET" && req.method !== "HEAD") { + body = await req.arrayBuffer(); + if (body.byteLength > UPSTREAM_BODY_LIMIT) return json({ error: "request body too large" }, 413); + } + const abort = new AbortController(); + const stop = () => abort.abort(); + req.signal.addEventListener("abort", stop, { once: true }); + const timer = setTimeout(stop, UPSTREAM_HEADER_TIMEOUT_MS); + let res: Response; + try { + // The parsed path is what was checked, so it is what is sent: the + // dashboard never sees a spelling of the path the check did not. + res = await (deps.upstream ?? fetch)(`${deps.cfg.dashboardUrl}${url.pathname}${url.search}`, { + method: open ? "GET" : req.method, + headers, + body, + redirect: "manual", + signal: abort.signal, + }); + } catch (error) { + console.error(`pm-console: dashboard: ${(error as Error).message}`); + return json({ error: "the dashboard did not answer" }, 502); + } finally { + clearTimeout(timer); + } + const out = new Headers(); + for (const [name, value] of res.headers) { + if (!HOP_BY_HOP.has(name) && name !== "content-length" && name !== "content-encoding") out.append(name, value); + } + return new Response(req.method === "HEAD" ? null : res.body, { status: res.status, headers: out }); } /** A state-changing request must be one this page made: a custom header @@ -93,7 +178,12 @@ export async function handle(req: Request, deps: Deps, peer: string | null = nul // Public, unauthenticated: nothing here says anything about the fleet. if (path === "/.well-known/assetlinks.json" && method === "GET") return json(assetLinks(deps.cfg)); if (path === `${BASE}/health` && method === "GET") return json({ ok: true }); - if (path !== BASE && !path.startsWith(`${BASE}/`)) return json({ error: "not found" }, 404); + const ours = path === BASE || path.startsWith(`${BASE}/`); + if (!ours) { + if (deps.cfg.dashboardUrl === null) return json({ error: "not found" }, 404); + if ((method === "GET" || method === "HEAD") && PUBLIC_DASHBOARD.test(path)) + return toDashboard(req, url, deps, true); + } let who: Identity; try { @@ -102,6 +192,10 @@ export async function handle(req: Request, deps: Deps, peer: string | null = nul if (error instanceof AuthError) return json({ error: error.message }, error.status); throw error; } + if (!ours) { + if (crossSiteWrite(req)) return json({ error: "this request did not come from this site" }, 403); + return toDashboard(req, url, deps, false); + } const rest = path.slice(BASE.length).replace(/^\/+/, ""); if (method === "GET" && rest === "") { @@ -253,6 +347,6 @@ if (import.meta.main) { fetch: (req, srv) => handle(req, deps, srv.requestIP(req)?.address ?? null), }); console.log( - `pm-console listening on http://${server.hostname}:${server.port}${BASE}/ — owners: ${cfg.owners.length}, issuers: ${cfg.issuers.map((i) => i.name).join(", ") || "none (edge requests are refused)"}`, + `pm-console listening on http://${server.hostname}:${server.port}${BASE}/ — owners: ${cfg.owners.length}, issuers: ${cfg.issuers.map((i) => i.name).join(", ") || "none (edge requests are refused)"}, dashboard: ${cfg.dashboardUrl ?? "not fronted"}`, ); } diff --git a/pm-stack/console/test/console.test.ts b/pm-stack/console/test/console.test.ts index 9bc6401608..1996b12229 100644 --- a/pm-stack/console/test/console.test.ts +++ b/pm-stack/console/test/console.test.ts @@ -9,6 +9,9 @@ // unit name outside the allowlist reaches systemctl; the unit parser // reads back what a formatter wrote). A request is local only by the // connection's own address, which the tests pass in as the server does. +// The dashboard behind the gate is a recorder too: what it was sent is +// compared with literal URLs, so no spelling of a path can pass as one +// of the public files unless the dashboard is asked for exactly that file. import { beforeEach, describe, expect, test } from "bun:test"; import { readFileSync } from "node:fs"; import { @@ -361,6 +364,22 @@ describe("configuration", () => { for (const bind of ["127.0.0.1", "::1", "localhost"]) { expect(readConfig({ PM_CONSOLE_BIND: bind }).bind).toBe(bind); } + // The dashboard has no sign-in of its own: only an address on this machine can stand behind the gate. + expect(readConfig({}).dashboardUrl).toBe("http://127.0.0.1:4870"); + expect(readConfig({ PM_CONSOLE_DASHBOARD_URL: "http://localhost:9/" }).dashboardUrl).toBe("http://localhost:9"); + expect(readConfig({ PM_CONSOLE_DASHBOARD_URL: "" }).dashboardUrl).toBeNull(); + for (const url of [ + "http://100.99.113.103:4870", + "https://127.0.0.1:4870", + "http://127.0.0.1:4870/admin", + "http://127.0.0.1:4870/?x=1", + "http://user:pw@127.0.0.1:4870", + "http://127.0.0.1.evil.example:4870", + "http://evil.example", + "4870", + ]) { + expect(() => readConfig({ PM_CONSOLE_DASHBOARD_URL: url })).toThrow(/PM_CONSOLE_DASHBOARD_URL/); + } }); }); @@ -810,9 +829,26 @@ describe("operations", () => { }); describe("HTTP surface", () => { - function deps(who: "owner" | 401 | 403, r = recorder()): Deps & { audited: Record[] } { + type Sent = { url: string; method: string; headers: Record; body: string | null; redirect?: string }; + function deps( + who: "owner" | 401 | 403, + r = recorder(), + answer: (url: string) => Response = () => new Response("dash", { headers: { "content-type": "text/html" } }), + ): Deps & { audited: Record[]; sent: Sent[] } { const audited: Record[] = []; + const sent: Sent[] = []; return { + sent, + upstream: async (url, init) => { + sent.push({ + url, + method: String(init.method), + headers: Object.fromEntries(new Headers(init.headers)), + body: init.body ? new TextDecoder().decode(init.body as ArrayBuffer) : null, + redirect: init.redirect, + }); + return answer(url); + }, cfg: CFG, ops: new Ops(CFG, r.run), identify: async () => { @@ -855,7 +891,11 @@ describe("HTTP surface", () => { expect((await handle(get(path), d)).status).toBe(401); } expect((await handle(get("/console/api/me"), deps(403))).status).toBe(403); - expect((await handle(get("/elsewhere"), d)).status).toBe(404); + expect((await handle(get("/elsewhere"), d)).status).toBe(401); + expect(d.sent).toEqual([]); + // With no dashboard configured there is nothing outside /console. + const alone = { ...deps("owner"), cfg: readConfig({ HOME: "/h", PM_CONSOLE_DASHBOARD_URL: "" }) }; + expect((await handle(get("/elsewhere"), alone)).status).toBe(404); }); test("the page and its files are served to the owner with a strict policy", async () => { @@ -866,7 +906,9 @@ describe("HTTP surface", () => { expect(await page.text()).toContain('src="/console/app.js"'); expect((await handle(get("/console/app.css"), d)).headers.get("content-type")).toContain("text/css"); expect((await handle(get("/console"), d)).status).toBe(308); - expect((await handle(get("/console/../src/server.ts"), d)).status).toBe(404); + // A path that climbs out of /console is the dashboard's to answer, never a file of this service. + expect(await (await handle(get("/console/../src/server.ts"), d)).text()).toBe("dash"); + expect(d.sent.map((c) => c.url)).toEqual(["http://127.0.0.1:4870/src/server.ts"]); expect((await handle(get("/console/config.ts"), d)).status).toBe(404); // Names every object has are not files, and a path that does not decode is a bad request. for (const name of ["constructor", "__proto__", "toString", "hasOwnProperty"]) { @@ -932,6 +974,196 @@ describe("HTTP surface", () => { ).toBe(405); }); + const PUBLIC = [ + "/manifest.webmanifest", + "/icons/icon-192.png", + "/icons/icon-512.png", + "/icons/icon-maskable-512.png", + "/icons/apple-touch-icon.png", + ]; + + test("the dashboard is reached only by the owner, apart from its install files", async () => { + const out = deps(401); + for (const path of [ + "/", + "/attention", + "/api/board", + "/sw.js", + "/icons/", + "/icons/evil.png", + "/icons/../attention", + "/icons/%2e%2e/attention", + "/icons/..%2fattention", + "/icons/icon-192.png/../../attention", + "/icons/icon-192.png/", + "/icons/icon-192.png%00", + "/ICONS/icon-192.png", + "//icons/icon-192.png", + "/manifest.webmanifest/x", + "/manifest.webmanifest;x", + "/x/manifest.webmanifest", + "/.well-known/assetlinks.json/x", + ]) { + expect([path, (await handle(get(path), out)).status]).toEqual([path, 401]); + } + expect(out.sent).toEqual([]); + expect((await handle(get("/attention"), deps(403))).status).toBe(403); + + // The install files: asked for exactly, read-only, and nothing the caller sent goes along. + for (const path of PUBLIC) { + const res = await handle( + new Request(`https://pm.security.cab${path}?v=2`, { + headers: { host: "pm.security.cab", cookie: "CF_Authorization=x", authorization: "Bearer y" }, + }), + out, + ); + expect(await res.text()).toBe("dash"); + } + expect(out.sent.map((c) => c.url)).toEqual(PUBLIC.map((p) => `http://127.0.0.1:4870${p}?v=2`)); + for (const call of out.sent) { + expect(call.method).toBe("GET"); + expect(call.headers).toEqual({ host: "pm.security.cab", "accept-encoding": "identity" }); + } + expect((await handle(post("/manifest.webmanifest", {}), out)).status).toBe(401); + expect(out.sent.length).toBe(PUBLIC.length); + }); + + test("property: no spelling of a path reaches the dashboard without sign-in unless it is an install file", async () => { + const next = rng(4870); + const pieces = [ + "/", + "icons", + "icon-192.png", + "manifest.webmanifest", + "attention", + "..", + ".", + "%2e%2e", + "%2E", + "%2f", + "%5c", + "\\", + "%00", + ";", + "?", + "#", + "ICONS", + "api", + ".well-known", + "assetlinks.json", + "console", + " ", + "%20", + ]; + const out = deps(401); + const allowed = new Set(PUBLIC.map((p) => `http://127.0.0.1:4870${p}`)); + let reached = 0; + for (let i = 0; i < 4000; i++) { + const path = `/${Array.from({ length: 1 + Math.floor(next() * 7) }, () => pieces[Math.floor(next() * pieces.length)]).join(next() < 0.7 ? "/" : "")}`; + let req: Request; + try { + req = get(path); + } catch { + continue; // not a request a client could send + } + const before = out.sent.length; + const res = await handle(req, out); + if (out.sent.length > before) { + reached++; + expect(allowed.has(out.sent[before].url.split("?")[0])).toBe(true); + } else if (!new URL(req.url).pathname.startsWith("/.well-known/assetlinks.json")) { + expect([path, res.status === 401 || res.status === 200 || res.status === 308]).toEqual([path, true]); + } + } + expect(reached).toBeGreaterThan(0); // the generator does produce the public files + for (const call of out.sent) expect(allowed.has(call.url.split("?")[0])).toBe(true); + }); + + test("the owner's request passes to the dashboard as it was checked, and the answer comes back", async () => { + const d = deps("owner", recorder(), (url) => + url.endsWith("/moved") + ? new Response(null, { status: 302, headers: { location: "/attention" } }) + : new Response("

board

", { + status: 207, + headers: { + "content-type": "text/html", + "content-encoding": "gzip", + "content-length": "999", + connection: "close", + "set-cookie": "a=1", + "x-board": "yes", + }, + }), + ); + const res = await handle( + new Request("https://pm.security.cab/attention/../board?lane=id&x=%2F", { + headers: { + host: "pm.security.cab", + cookie: "CF_Authorization=t", + "cf-access-jwt-assertion": "t", + connection: "keep-alive, upgrade", + upgrade: "websocket", + "accept-encoding": "br", + "x-forwarded-for": "203.0.113.9", + }, + }), + d, + ); + expect(res.status).toBe(207); + expect(await res.text()).toBe("

board

"); + expect(res.headers.get("x-board")).toBe("yes"); + expect(res.headers.get("set-cookie")).toBe("a=1"); + expect(res.headers.get("content-encoding")).toBeNull(); + expect(res.headers.get("connection")).toBeNull(); + expect(d.sent).toEqual([ + { + url: "http://127.0.0.1:4870/board?lane=id&x=%2F", + method: "GET", + headers: { + host: "pm.security.cab", + cookie: "CF_Authorization=t", + "cf-access-jwt-assertion": "t", + "accept-encoding": "identity", + "x-forwarded-for": "203.0.113.9", + }, + body: null, + redirect: "manual", + }, + ]); + + // A redirect is the browser's to follow, not the console's. + const moved = await handle(get("/moved"), d); + expect([moved.status, moved.headers.get("location")]).toEqual([302, "/attention"]); + + // Writes: this site's own pass with their body; another site's do not reach the dashboard. + const before = d.sent.length; + const own = await handle(post("/api/cards/7/move", { to: "done" }), d); + expect(own.status).toBe(207); + expect(d.sent[before]).toMatchObject({ + url: "http://127.0.0.1:4870/api/cards/7/move", + method: "POST", + body: '{"to":"done"}', + }); + expect(d.sent[before].headers["content-length"]).toBeUndefined(); + for (const headers of [ + { origin: "https://evil.example" }, + { origin: "null" }, + { origin: "https://pm.security.cab", "sec-fetch-site": "cross-site" }, + ]) { + expect((await handle(post("/api/cards/7/move", { to: "done" }, headers), d)).status).toBe(403); + } + expect(d.sent.length).toBe(before + 1); + // An agent on the host, with no browser headers at all, still writes. + expect((await handle(post("/api/cards/7/move", {}, {}), d)).status).toBe(207); + + const down = deps("owner"); + down.upstream = async () => { + throw new Error("connection refused"); + }; + const failed = await handle(get("/attention"), down); + expect([failed.status, await failed.json()]).toEqual([502, { error: "the dashboard did not answer" }]); + }); + test("an action that cannot be recorded is not taken; one already taken is reported as it went", async () => { const r = recorder(); const order: string[] = [];