diff --git a/.github/ci-policy.md b/.github/ci-policy.md index 27ba14656d..805aa2b4e4 100644 --- a/.github/ci-policy.md +++ b/.github/ci-policy.md @@ -98,6 +98,7 @@ never a state that persists by default. | Workflow | Automatic venue | Manual | | ------------------------- | --------------------- | ------ | | workflow-lint | none | yes | +| pm-console-android | none | yes | | proxy-port-fallbacks | none | yes | | fleet-search-parity-guard | none | yes | | fleet-rust-tests | nightly schedule | yes | diff --git a/.github/test-suite-registry.json b/.github/test-suite-registry.json index 116c72f7dd..4e668c6177 100644 --- a/.github/test-suite-registry.json +++ b/.github/test-suite-registry.json @@ -763,6 +763,18 @@ }, "status": "mapped" }, + { + "id": "pm-stack.console", + "paths": ["pm-stack/console/test/*.test.ts", "pm-stack/console/scripts/test_expose.py"], + "invocation": "cd pm-stack/console && bun test && python3 -I -m unittest discover -s scripts -p 'test_*.py'", + "venue": { + "workflow": ".github/workflows/pm-stack-tests.yml", + "job_step": "Test console", + "state": "active", + "dispatchable": true + }, + "status": "mapped" + }, { "id": "pm-stack.dispatch", "paths": ["pm-stack/dispatch/test/*.test.ts"], diff --git a/.github/workflows/pm-console-android.yml b/.github/workflows/pm-console-android.yml new file mode 100644 index 0000000000..b99151f374 --- /dev/null +++ b/.github/workflows/pm-console-android.yml @@ -0,0 +1,52 @@ +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. +on: + workflow_dispatch: + inputs: + publish: + description: "Attach the signed APK to the release pm-console-android" + type: boolean + default: true + +permissions: + contents: read + +jobs: + build: + name: "build: signed APK" + runs-on: ubuntu-latest + timeout-minutes: 25 + permissions: + contents: write + steps: + - uses: actions/checkout@v7 + - name: Build, sign and check the signing certificate + 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 + - uses: actions/upload-artifact@v7 + with: + name: pm-console-apk + path: pm-stack/console/android/app/build/outputs/apk/release/pm-console.apk + if-no-files-found: error + - name: Attach to the release + if: inputs.publish + env: + GH_TOKEN: ${{ github.token }} + run: | + apk=pm-stack/console/android/app/build/outputs/apk/release/pm-console.apk + if ! gh release view pm-console-android >/dev/null 2>&1; then + gh release create pm-console-android --latest=false \ + --title "PM console for Android" \ + --notes "The PM stack's console as an Android app. It opens https://pm.security.cab/console/ and signs in the way the site does. Install pm-console.apk; later builds install over it." + fi + gh release upload pm-console-android "$apk" --clobber diff --git a/.github/workflows/pm-stack-tests.yml b/.github/workflows/pm-stack-tests.yml index 406eb16ec4..cbc3ac03a0 100644 --- a/.github/workflows/pm-stack-tests.yml +++ b/.github/workflows/pm-stack-tests.yml @@ -71,6 +71,16 @@ jobs: fi bun test + - name: Test console + working-directory: pm-stack/console + run: | + if [ ! -d test ] || ! ls test/*.test.ts >/dev/null 2>&1; then + echo "::error::Missing console test suite — pm-stack/console/test has no *.test.ts files." + exit 1 + fi + bun test + python3 -I -m unittest discover -s scripts -p 'test_*.py' + - name: Test seed and deploy/install scripts run: | bash pm-stack/scripts/seed-smoke.test.sh diff --git a/pm-stack/PORTS.md b/pm-stack/PORTS.md index a5ba42e923..f2f369e86a 100644 --- a/pm-stack/PORTS.md +++ b/pm-stack/PORTS.md @@ -39,17 +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 | -| 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`; 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 | ## Fleet (brokers, laptop-agent, CONNECT-UDP) diff --git a/pm-stack/README.md b/pm-stack/README.md index b9640f6746..de905767ef 100644 --- a/pm-stack/README.md +++ b/pm-stack/README.md @@ -24,6 +24,7 @@ health gate): | 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/` | 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 new file mode 100644 index 0000000000..b5854da07f --- /dev/null +++ b/pm-stack/console/README.md @@ -0,0 +1,97 @@ +# 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/`. + +| Section | What you can do | What runs | +| ------------- | ----------------------------------------------------------------------------------- | --------------------------------------- | +| Overview | Queue counts, ready pull requests, agents, failed units | the calls below, together | +| Queue | List queued, claimed, blocked and parked tasks; unblock or cancel one with a reason | the queue store (read), `fleet queue` | +| Priorities | Ranked issues, most urgent first; change a rank; comment; file new work | `fleet gh` | +| Agents | Send an idea, message or command to one agent, a group or everyone; recent messages | `fleet bridge` | +| Services | State of the stack's units; start, stop, restart; read logs | `systemctl --user`, `journalctl --user` | +| Pull requests | Open pull requests; check one; merge it | `fleet gh` | + +Every operation is an argument vector, never a shell line, and text you +type travels on stdin or as one argument. + +Each write leaves two lines in `~/.local/state/pm-console/audit.jsonl` +(who, what, when; message text is not copied): one before the action +runs, one with how it went. If the first cannot be written the action is +not taken. If the second cannot be written the action's own result still +comes back, so a merge that happened is never reported as failed. + +Work filed from Priorities is created as an issue and enqueued as a +triage task in the same pass, so a worker picks it up without waiting for +the coverage reconciliation. The rank sets the task's place in the queue. +If the enqueue fails, the issue still exists and the page says it is not +queued. + +## Sign-in + +The console runs no sign-in of its own. A caller arrives with a signed +token from an issuer the deployment trusts; the console checks the +signature, issuer, audience and times, then asks whether the identity is +the owner (`PM_CONSOLE_OWNER_EMAILS`). + +- **Today:** Cloudflare Access at the public edge runs the interactive + sign-in and issues the token. The sign-in methods are set on the Access + application, not here. +- **Google:** an Access sign-in method. It turns on when + `scripts/expose.py` finds the secrets `google.access-sso.client-id` and + `google.access-sso.client-secret` (an OAuth client whose redirect URI is + `https://.cloudflareaccess.com/cdn-cgi/access/callback`). +- **The central OIDC provider (#9077):** either an Access sign-in method + (generic OIDC), or trusted directly: add + `{name, issuer, jwksUri, audience}` to the file named by + `PM_CONSOLE_ISSUERS_FILE` and its ID tokens are accepted as + `Authorization: Bearer`. RS256 and ES256. +- **Certificates from the central CA (#9155):** upload the CA to Access + mTLS; the token then carries the certificate's common name, and names + listed in `PM_CONSOLE_CERT_NAMES` are the owner. + +A request is local, and treated as the owner, only when the connection +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). + +## 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 +cd pm-stack/console && bun test +``` + +`expose.py` is safe to run again: it changes only what is not already so +and refuses to touch DNS records or Access policies it did not write. It +puts the sign-in gate in place first and the route last, and stops before +the route if the console does not come up with its sign-in settings. + +## Configuration + +| Variable | Default | Meaning | +| --------------------------------------------------------- | ------------------------------------------------- | -------------------------------------------------- | +| `PM_CONSOLE_PORT`, `PM_CONSOLE_BIND` | `4872`, `127.0.0.1` | Listener; the address must be loopback | +| `PM_CONSOLE_OWNER_EMAILS` | none (nobody) | Comma-separated owner addresses | +| `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_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. + +## Android + +`pm-stack/console/android/` is a Trusted Web Activity: the same site in +Chrome without browser chrome, so sign-in is Chrome's own and nothing is +reimplemented. The signed APK is built by the `pm-console-android` +workflow and attached to the release of the same name. See its README. diff --git a/pm-stack/console/android/.gitignore b/pm-stack/console/android/.gitignore new file mode 100644 index 0000000000..ff4118e66e --- /dev/null +++ b/pm-stack/console/android/.gitignore @@ -0,0 +1,5 @@ +build/ +.gradle/ +*.p12 +*.apk +/gradle-dist/ diff --git a/pm-stack/console/android/README.md b/pm-stack/console/android/README.md new file mode 100644 index 0000000000..503df8fa3f --- /dev/null +++ b/pm-stack/console/android/README.md @@ -0,0 +1,38 @@ +# PM console for Android + +A Trusted Web Activity: the app opens `https://pm.security.cab/console/` +in Chrome without browser chrome. It is the site, so it does everything +the site does, signs in the way the site does (Chrome's own session), and +never needs a release when the console changes. There is no code in the +module; the launcher activity comes from `androidbrowserhelper`. + +## How the app and the site trust each other + +- The app names the site in its manifest (`asset_statements`). +- The site names the app in `/.well-known/assetlinks.json`: package + `today.developing.pmconsole`, signed by the certificate in + [`signing-fingerprint.txt`](signing-fingerprint.txt). `pm-console` + serves that file from `PM_CONSOLE_ANDROID_SHA256`. + +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 +bash pm-stack/console/android/build.sh # locally: needs JAVA_HOME (17 or 21) and ANDROID_HOME +``` + +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. + +## Install + +Download `pm-console.apk` from the +[release](https://github.com/developing-today/code/releases/tag/pm-console-android) +on the phone and open it. Later builds install over it. diff --git a/pm-stack/console/android/app/build.gradle b/pm-stack/console/android/app/build.gradle new file mode 100644 index 0000000000..8b85ff4136 --- /dev/null +++ b/pm-stack/console/android/app/build.gradle @@ -0,0 +1,62 @@ +// The PM console for Android: a Trusted Web Activity. The app is the +// site itself, shown by Chrome without browser chrome, so sign-in is +// Chrome's and nothing is reimplemented here. There is no code in this +// module: the launcher activity comes from androidbrowserhelper. +plugins { + id 'com.android.application' +} + +def site = 'https://pm.security.cab' +def keystore = System.getenv('PM_ANDROID_KEYSTORE') + +android { + namespace 'today.developing.pmconsole' + compileSdk 34 + + defaultConfig { + applicationId 'today.developing.pmconsole' + minSdk 23 + targetSdk 34 + versionCode 1 + versionName '0.1.0' + manifestPlaceholders = [hostName: 'pm.security.cab', defaultUrl: "${site}/console/"] + // The app's half of the link to the site. The site's half is + // /.well-known/assetlinks.json, served by pm-console. + resValue 'string', 'asset_statements', "[{\\\"relation\\\": [\\\"delegate_permission/common.handle_all_urls\\\"], \\\"target\\\": {\\\"namespace\\\": \\\"web\\\", \\\"site\\\": \\\"${site}\\\"}}]" + } + + // The sources live in src/twa, not src/main: the repository ignores + // every directory named "main". + sourceSets { + main { + manifest.srcFile 'src/twa/AndroidManifest.xml' + res.srcDirs = ['src/twa/res'] + java.srcDirs = [] + } + } + + signingConfigs { + release { + if (keystore) { + storeFile file(keystore) + storeType 'pkcs12' + storePassword System.getenv('PM_ANDROID_KEYSTORE_PASSWORD') + keyAlias 'pmconsole' + keyPassword System.getenv('PM_ANDROID_KEYSTORE_PASSWORD') + } + } + } + + buildTypes { + release { + minifyEnabled false + if (keystore) { + signingConfig signingConfigs.release + } + } + } +} + +dependencies { + implementation 'com.google.androidbrowserhelper:androidbrowserhelper:2.5.0' +} diff --git a/pm-stack/console/android/app/src/twa/AndroidManifest.xml b/pm-stack/console/android/app/src/twa/AndroidManifest.xml new file mode 100644 index 0000000000..3ad0c32515 --- /dev/null +++ b/pm-stack/console/android/app/src/twa/AndroidManifest.xml @@ -0,0 +1,59 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/pm-stack/console/android/app/src/twa/res/mipmap-xxxhdpi/ic_launcher.png b/pm-stack/console/android/app/src/twa/res/mipmap-xxxhdpi/ic_launcher.png new file mode 100644 index 0000000000..28ada84e52 Binary files /dev/null and b/pm-stack/console/android/app/src/twa/res/mipmap-xxxhdpi/ic_launcher.png differ diff --git a/pm-stack/console/android/app/src/twa/res/values/colors.xml b/pm-stack/console/android/app/src/twa/res/values/colors.xml new file mode 100644 index 0000000000..70e5510db1 --- /dev/null +++ b/pm-stack/console/android/app/src/twa/res/values/colors.xml @@ -0,0 +1,4 @@ + + + #12151A + diff --git a/pm-stack/console/android/app/src/twa/res/values/strings.xml b/pm-stack/console/android/app/src/twa/res/values/strings.xml new file mode 100644 index 0000000000..82bd6ffdc1 --- /dev/null +++ b/pm-stack/console/android/app/src/twa/res/values/strings.xml @@ -0,0 +1,4 @@ + + + PM Console + diff --git a/pm-stack/console/android/build.gradle b/pm-stack/console/android/build.gradle new file mode 100644 index 0000000000..48978475f3 --- /dev/null +++ b/pm-stack/console/android/build.gradle @@ -0,0 +1,3 @@ +plugins { + id 'com.android.application' version '8.5.2' apply false +} diff --git a/pm-stack/console/android/build.sh b/pm-stack/console/android/build.sh new file mode 100755 index 0000000000..f5d00fb447 --- /dev/null +++ b/pm-stack/console/android/build.sh @@ -0,0 +1,60 @@ +#!/usr/bin/env bash +# build.sh — build the PM console APK, signed when a keystore is given. +# +# Inputs (environment): +# KEYSTORE_B64 base64 of the PKCS#12 signing keystore (key alias pmconsole) +# PM_ANDROID_KEYSTORE_PASSWORD its password +# GRADLE_VERSION Gradle to fetch (default 8.9; AGP 8.5 needs 8.7 or later) +# Needs: a JDK 17 or 21, an Android SDK at ANDROID_HOME, curl, unzip. +# +# With both keystore variables set the result is app/build/outputs/apk/release/pm-console.apk, +# and the build fails unless its signing certificate is the one in +# signing-fingerprint.txt: the site lists that fingerprint in its +# asset-links file, and an APK signed by anything else would open with a +# browser bar. Without them the result is an unsigned APK, for a check +# that the project builds. +set -euo pipefail + +cd "$(dirname "$0")" +GRADLE_VERSION="${GRADLE_VERSION:-8.9}" +OUT=app/build/outputs/apk/release + +export JAVA_HOME="${JAVA_HOME_17_X64:-${JAVA_HOME_21_X64:-${JAVA_HOME:-}}}" +if [ -z "$JAVA_HOME" ] || [ -z "${ANDROID_HOME:-}" ]; then + echo "build.sh: JAVA_HOME and ANDROID_HOME must be set" >&2 + exit 2 +fi + +if [ ! -x "gradle-dist/gradle-$GRADLE_VERSION/bin/gradle" ]; then + mkdir -p gradle-dist + zip="gradle-dist/gradle-$GRADLE_VERSION-bin.zip" + curl -fsSL -o "$zip" "https://services.gradle.org/distributions/gradle-$GRADLE_VERSION-bin.zip" + want="$(curl -fsSL "https://services.gradle.org/distributions/gradle-$GRADLE_VERSION-bin.zip.sha256")" + echo "$want $zip" | sha256sum -c - >/dev/null + unzip -q -o "$zip" -d gradle-dist +fi +GRADLE="gradle-dist/gradle-$GRADLE_VERSION/bin/gradle" + +if [ -n "${KEYSTORE_B64:-}" ] && [ -n "${PM_ANDROID_KEYSTORE_PASSWORD:-}" ]; then + keystore="$(mktemp --suffix=.p12)" + trap 'rm -f "$keystore"' EXIT + printf '%s' "$KEYSTORE_B64" | base64 -d >"$keystore" + export PM_ANDROID_KEYSTORE="$keystore" +fi + +"$GRADLE" --no-daemon --console=plain assembleRelease + +if [ -z "${PM_ANDROID_KEYSTORE:-}" ]; then + echo "build.sh: built unsigned: $(ls $OUT/*.apk)" + exit 0 +fi + +mv "$OUT/app-release.apk" "$OUT/pm-console.apk" +apksigner="$(find "$ANDROID_HOME/build-tools" -name apksigner -type f | sort -V | tail -1)" +got="$("$apksigner" verify --print-certs "$OUT/pm-console.apk" | sed -n 's/^Signer #1 certificate SHA-256 digest: //p' | tr 'a-f' 'A-F' | sed 's/../&:/g; s/:$//')" +want="$(tr -d '[:space:]' &2 + exit 1 +fi +echo "build.sh: $OUT/pm-console.apk signed by $got" diff --git a/pm-stack/console/android/gradle.properties b/pm-stack/console/android/gradle.properties new file mode 100644 index 0000000000..c335529575 --- /dev/null +++ b/pm-stack/console/android/gradle.properties @@ -0,0 +1,2 @@ +android.useAndroidX=true +org.gradle.jvmargs=-Xmx2g diff --git a/pm-stack/console/android/settings.gradle b/pm-stack/console/android/settings.gradle new file mode 100644 index 0000000000..5fced4106b --- /dev/null +++ b/pm-stack/console/android/settings.gradle @@ -0,0 +1,16 @@ +pluginManagement { + repositories { + google() + mavenCentral() + gradlePluginPortal() + } +} +dependencyResolutionManagement { + repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) + repositories { + google() + mavenCentral() + } +} +rootProject.name = 'pm-console' +include ':app' diff --git a/pm-stack/console/android/signing-fingerprint.txt b/pm-stack/console/android/signing-fingerprint.txt new file mode 100644 index 0000000000..7e7842dbe8 --- /dev/null +++ b/pm-stack/console/android/signing-fingerprint.txt @@ -0,0 +1 @@ +8B:82:C4:70:18:15:C1:5C:92:C3:51:1D:2F:32:51:B3:FC:27:3D:F2:1D:1E:44:2C:F0:CF:41:74:78:35:FC:12 diff --git a/pm-stack/console/install.sh b/pm-stack/console/install.sh new file mode 100755 index 0000000000..dd5991d361 --- /dev/null +++ b/pm-stack/console/install.sh @@ -0,0 +1,58 @@ +#!/usr/bin/env bash +# install.sh — install or refresh the pm-console user unit on the host +# that runs the pm stack. Safe to run again: it never overwrites an +# existing environment file. +# +# Usage: bash install.sh +set -euo pipefail + +if [ "$#" -ne 0 ]; then + echo "usage: bash install.sh (it takes no arguments)" >&2 + exit 2 +fi + +cd "$(dirname "$0")" +SRC="$PWD" +EXPECTED="$HOME/git/code/pm-stack/console" +if [ "$SRC" != "$EXPECTED" ]; then + echo "install.sh: run from the primary checkout at $EXPECTED (the unit runs that checkout)" >&2 + exit 1 +fi +STATE="$HOME/.local/state/pm-console" +UNIT_SRC="$(dirname "$SRC")/systemd/pm-console.service" +UNIT_DST="$HOME/.config/systemd/user/pm-console.service" + +mkdir -p "$STATE" "$(dirname "$UNIT_DST")" +chmod 700 "$STATE" +if [ ! -f "$STATE/.env" ]; then + # No issuer yet: requests from the edge are refused until + # scripts/expose.py writes the sign-in settings. + umask 077 + printf 'PM_CONSOLE_PORT=4872\nPM_CONSOLE_OWNER_EMAILS=\n' >"$STATE/.env" +fi +install -m 644 "$UNIT_SRC" "$UNIT_DST" +systemctl --user daemon-reload +systemctl --user enable pm-console.service >/dev/null +systemctl --user restart pm-console.service + +# systemd strips one pair of quotes from an EnvironmentFile value, so +# PM_CONSOLE_PORT="4872" is a valid line: read it the same way. +PORT="$(sed -n 's/^[[:space:]]*PM_CONSOLE_PORT=//p' "$STATE/.env" | tail -1 | tr -d '[:space:]')" +PORT="${PORT#[\"\']}" +PORT="${PORT%[\"\']}" +PORT="${PORT:-4872}" +case "$PORT" in + *[!0-9]*) + echo "install.sh: PM_CONSOLE_PORT in $STATE/.env is not a number: $PORT" >&2 + exit 1 + ;; +esac +for _ in 1 2 3 4 5 6 7 8 9 10; do + if curl -fsS "http://127.0.0.1:$PORT/console/health" >/dev/null 2>&1; then + echo "pm-console: running on http://127.0.0.1:$PORT/console/" + exit 0 + fi + sleep 1 +done +echo "pm-console: did not answer its health check; see: journalctl --user -u pm-console -n 50" >&2 +exit 1 diff --git a/pm-stack/console/package.json b/pm-stack/console/package.json new file mode 100644 index 0000000000..673e0e4424 --- /dev/null +++ b/pm-stack/console/package.json @@ -0,0 +1,11 @@ +{ + "name": "pm-console", + "version": "0.1.0", + "private": true, + "type": "module", + "description": "The PM stack's console: queue, priorities, agents, services and pull requests, acted on from one page behind edge sign-in.", + "scripts": { + "start": "bun run src/server.ts", + "test": "bun test" + } +} diff --git a/pm-stack/console/public/app.css b/pm-stack/console/public/app.css new file mode 100644 index 0000000000..0486aba26a --- /dev/null +++ b/pm-stack/console/public/app.css @@ -0,0 +1,269 @@ +:root { + color-scheme: light dark; + --bg: #f6f7f9; + --panel: #ffffff; + --ink: #171a1f; + --muted: #5b6472; + --line: #d9dde3; + --accent: #1f6feb; + --accent-ink: #ffffff; + --good: #1a7f37; + --warn: #9a6700; + --bad: #cf222e; + --radius: 10px; + font: + 16px / 1.45 system-ui, + -apple-system, + "Segoe UI", + Roboto, + sans-serif; +} +@media (prefers-color-scheme: dark) { + :root { + --bg: #12151a; + --panel: #1b2027; + --ink: #e8ebf0; + --muted: #9aa4b2; + --line: #2d343e; + --accent: #4c8dff; + --accent-ink: #0b0d10; + --good: #3fb950; + --warn: #d29922; + --bad: #f85149; + } +} +* { + box-sizing: border-box; +} +body { + margin: 0; + background: var(--bg); + color: var(--ink); + padding-bottom: env(safe-area-inset-bottom); +} +a { + color: var(--accent); +} +h2 { + font-size: 1.05rem; + margin: 0 0 0.5rem; +} +h3 { + font-size: 0.95rem; + margin: 0; + overflow-wrap: anywhere; +} +p { + margin: 0.25rem 0; +} +.bar { + display: flex; + gap: 0.9rem; + align-items: center; + padding: 0.7rem 1rem; + padding-top: calc(0.7rem + env(safe-area-inset-top)); + background: var(--panel); + border-bottom: 1px solid var(--line); +} +.brand { + font-weight: 700; + color: var(--ink); + text-decoration: none; +} +.grow { + flex: 1; +} +.quiet { + color: var(--muted); + font-size: 0.875rem; +} +.tabs { + display: flex; + gap: 0.25rem; + overflow-x: auto; + padding: 0.5rem 0.75rem; + background: var(--panel); + border-bottom: 1px solid var(--line); + position: sticky; + top: 0; + z-index: 2; +} +.tabs button { + background: none; + color: var(--muted); + border: 0; + border-radius: 999px; + padding: 0.45rem 0.9rem; + font: inherit; + white-space: nowrap; + min-height: 2.5rem; +} +.tabs button[aria-current="page"] { + background: var(--accent); + color: var(--accent-ink); + font-weight: 600; +} +main { + max-width: 62rem; + margin: 0 auto; + padding: 1rem; + display: grid; + gap: 0.75rem; + outline: none; +} +.card { + background: var(--panel); + border: 1px solid var(--line); + border-radius: var(--radius); + padding: 0.85rem 1rem; + display: grid; + gap: 0.4rem; +} +.grid { + display: grid; + gap: 0.75rem; + grid-template-columns: repeat(auto-fit, minmax(9.5rem, 1fr)); +} +.stat b { + display: block; + font-size: 1.7rem; + line-height: 1.1; + font-variant-numeric: tabular-nums; +} +.row { + display: flex; + gap: 0.5rem; + align-items: center; + flex-wrap: wrap; +} +.row.end { + justify-content: flex-end; +} +.meta { + color: var(--muted); + font-size: 0.85rem; + overflow-wrap: anywhere; +} +.why { + font-size: 0.9rem; + overflow-wrap: anywhere; +} +button, +select, +input, +textarea { + font: inherit; + color: inherit; +} +button { + background: var(--accent); + color: var(--accent-ink); + border: 1px solid transparent; + border-radius: 8px; + padding: 0.45rem 0.85rem; + min-height: 2.5rem; + cursor: pointer; +} +button.ghost { + background: transparent; + color: var(--ink); + border-color: var(--line); +} +button.danger { + background: var(--bad); + color: #fff; +} +button:disabled { + opacity: 0.55; + cursor: progress; +} +input, +select, +textarea { + background: var(--bg); + border: 1px solid var(--line); + border-radius: 8px; + padding: 0.5rem 0.6rem; + width: 100%; + min-height: 2.5rem; +} +select.narrow { + width: auto; +} +label { + font-size: 0.85rem; + color: var(--muted); + display: grid; + gap: 0.25rem; +} +.badge { + font-size: 0.75rem; + border: 1px solid var(--line); + border-radius: 999px; + padding: 0.1rem 0.55rem; + white-space: nowrap; +} +.badge.good { + color: var(--good); + border-color: var(--good); +} +.badge.warn { + color: var(--warn); + border-color: var(--warn); +} +.badge.bad { + color: var(--bad); + border-color: var(--bad); +} +pre { + margin: 0; + padding: 0.75rem; + background: var(--bg); + border: 1px solid var(--line); + border-radius: 8px; + overflow: auto; + max-height: 55vh; + font-size: 0.78rem; + white-space: pre-wrap; + overflow-wrap: anywhere; +} +.toast { + position: fixed; + left: 50%; + bottom: calc(1rem + env(safe-area-inset-bottom)); + transform: translateX(-50%); + background: var(--ink); + color: var(--bg); + padding: 0.6rem 1rem; + border-radius: 999px; + max-width: 92vw; + z-index: 5; + font-size: 0.9rem; +} +.toast.bad { + background: var(--bad); + color: #fff; +} +dialog { + border: 1px solid var(--line); + border-radius: var(--radius); + background: var(--panel); + color: var(--ink); + width: min(32rem, 92vw); + padding: 1rem; +} +dialog::backdrop { + background: rgb(0 0 0 / 0.5); +} +dialog form { + display: grid; + gap: 0.6rem; +} +.empty { + color: var(--muted); + text-align: center; + padding: 1.5rem 0; +} +[hidden] { + display: none !important; +} diff --git a/pm-stack/console/public/app.js b/pm-stack/console/public/app.js new file mode 100644 index 0000000000..d6409fb276 --- /dev/null +++ b/pm-stack/console/public/app.js @@ -0,0 +1,236 @@ +// Console front end. No framework and no markup strings: every node is +// built with h(), and text from the fleet only ever becomes text. +const API = "/console/api/"; +const view = document.getElementById("view"); +const tabs = document.getElementById("tabs"); +const toastEl = document.getElementById("toast"); + +function h(tag, attrs, ...children) { + const el = document.createElement(tag); + for (const [k, v] of Object.entries(attrs || {})) { + if (v === false || v === null || v === undefined) continue; + if (k === "class") el.className = v; + else if (k.startsWith("on")) el.addEventListener(k.slice(2), v); + else if (k === "value") el.value = v; + else el.setAttribute(k, v === true ? "" : v); + } + for (const c of children.flat()) if (c !== null && c !== undefined && c !== false) el.append(c); + return el; +} + +async function api(path, body) { + const init = body === undefined ? {} : { method: "POST", headers: { "Content-Type": "application/json", "X-PM-Console": "1" }, body: JSON.stringify(body) }; + const res = await fetch(API + path, init); + let data = null; + try { + data = await res.json(); + } catch { + // A sign-in page instead of JSON means the edge session ended. + if (res.redirected || res.status === 401 || res.status === 403) location.reload(); + } + if (!res.ok) throw new Error((data && data.error) || `http ${res.status}`); + return data; +} + +let toastTimer; +function toast(message, bad) { + toastEl.textContent = message; + toastEl.className = bad ? "toast bad" : "toast"; + toastEl.hidden = false; + clearTimeout(toastTimer); + toastTimer = setTimeout(() => (toastEl.hidden = true), bad ? 7000 : 3500); +} + +/** Ask before acting. Resolves to the typed text ("" when none is asked + * for), or null when the person backs out. */ +function ask({ title, text, label, okLabel, danger, required }) { + const dialog = document.getElementById("ask"); + const input = document.getElementById("ask-input"); + const ok = document.getElementById("ask-ok"); + document.getElementById("ask-title").textContent = title; + document.getElementById("ask-text").textContent = text || ""; + document.getElementById("ask-label").textContent = label || ""; + input.hidden = !label; + input.value = ""; + input.required = Boolean(required); + ok.textContent = okLabel || "Confirm"; + ok.className = danger ? "danger" : ""; + return new Promise((resolve) => { + dialog.addEventListener("close", () => resolve(dialog.returnValue === "ok" ? input.value.trim() : null), { once: true }); + dialog.returnValue = ""; + dialog.showModal(); + if (label) input.focus(); + }); +} + +/** Run one action from a button: disable it, report, then redraw. + * `done` is the message, or a function from the result to the message. */ +async function act(button, path, body, done) { + button.disabled = true; + try { + const { result } = await api(path, body); + toast(typeof done === "function" ? done(result) : done); + await show(current); + } catch (error) { + toast(error.message, true); + button.disabled = false; + } +} + +const badge = (text, kind) => h("span", { class: `badge ${kind || ""}` }, text); +const empty = (text) => h("p", { class: "empty" }, text); +const card = (...children) => h("section", { class: "card" }, ...children); + +// ---- views --------------------------------------------------------------- + +async function overview() { + const o = await api("overview"); + const stat = (label, value, tab) => h("button", { class: "card stat ghost", onclick: () => show(tab) }, h("b", {}, String(value)), h("span", { class: "meta" }, label)); + const q = o.queue.error ? {} : o.queue; + const out = [ + h("div", { class: "grid" }, + stat("queued", q.queued ?? "–", "queue"), stat("claimed", q.claimed ?? "–", "queue"), stat("blocked", q.blocked ?? "–", "queue"), stat("parked", q.parked ?? "–", "queue"), + stat("PRs ready", o.prs.error ? "–" : o.prs.ready, "prs"), stat("agents", o.agents.error ? "–" : o.agents.registered, "agents"), + stat("units failed", o.services.error ? "–" : o.services.failed.length, "services")), + ]; + for (const [name, part] of Object.entries(o)) if (part.error) out.push(card(h("h3", {}, `${name}: unavailable`), h("p", { class: "why" }, part.error))); + if (!o.services.error && o.services.failed.length) out.push(card(h("h3", {}, "Failed units"), h("p", { class: "why" }, o.services.failed.join(", ")))); + return out; +} + +let queueStatus = "blocked"; +let queueSearch = ""; +async function queue() { + const data = await api(`queue?status=${queueStatus}&limit=100&q=${encodeURIComponent(queueSearch)}`); + const pick = h("select", { class: "narrow", "aria-label": "Status", onchange: (e) => { queueStatus = e.target.value; show("queue"); } }, + ["queued", "claimed", "blocked", "parked"].map((s) => h("option", { value: s, selected: s === queueStatus }, `${s} (${data.counts[s] ?? 0})`))); + const search = h("input", { type: "search", placeholder: "Filter by title", value: queueSearch, "aria-label": "Filter by title", onchange: (e) => { queueSearch = e.target.value; show("queue"); } }); + const rows = data.tasks.map((t) => card( + h("h3", {}, `${t.id} · ${t.title}`), + h("p", { class: "meta" }, `priority ${t.priority ?? "–"} · updated ${t.updated ?? "–"} · ${t.dedupe_key ?? ""}`), + t.why ? h("p", { class: "why" }, t.why) : null, + h("div", { class: "row end" }, + t.status === "blocked" ? h("button", { onclick: async (e) => { + const reason = await ask({ title: `Unblock task ${t.id}`, text: t.title, label: "Why it can proceed", okLabel: "Unblock", required: true }); + if (reason) act(e.target, `queue/${t.id}/unblock`, { reason }, `Task ${t.id} unblocked`); + } }, "Unblock") : null, + h("button", { class: "ghost", onclick: async (e) => { + const reason = await ask({ title: `Cancel task ${t.id}`, text: t.title, label: "Why it is cancelled", okLabel: "Cancel task", danger: true, required: true }); + if (reason) act(e.target, `queue/${t.id}/cancel`, { reason }, `Task ${t.id} cancelled`); + } }, "Cancel")))); + return [card(h("div", { class: "row" }, pick, h("span", { class: "grow" }), search)), ...(rows.length ? rows : [empty("No tasks in this state.")])]; +} + +const RANKS = ["expedite", "priority/critical", "now", "priority/high", "next", "none"]; +async function priorities() { + const { issues: list, truncated } = await api("priorities"); + const title = h("input", { placeholder: "A new idea or piece of work", "aria-label": "Title" }); + const body = h("textarea", { rows: 3, placeholder: "What you want, in your words (optional)", "aria-label": "Details" }); + const rank = h("select", { class: "narrow", "aria-label": "Rank" }, RANKS.map((r) => h("option", { value: r, selected: r === "next" }, r))); + const file = card(h("h2", {}, "File work"), title, body, h("div", { class: "row end" }, rank, + h("button", { onclick: (e) => title.value.trim() ? act(e.target, "ideas", { title: title.value, body: body.value, rank: rank.value }, (r) => (r.queued ? `Filed #${r.issue} and queued it` : `Filed #${r.issue}. ${r.note || "It is not queued yet."}`)) : toast("Give it a title", true) }, "File issue"))); + const rows = list.map((i) => card( + h("h3", {}, h("a", { href: i.url, target: "_blank", rel: "noopener" }, `#${i.number}`), ` ${i.title}`), + h("p", { class: "meta" }, `updated ${i.updated} · ${i.comments} comments · ${i.labels.filter((l) => !RANKS.includes(l)).slice(0, 6).join(", ")}`), + h("div", { class: "row end" }, + h("select", { class: "narrow", "aria-label": `Rank for #${i.number}`, onchange: (e) => act(e.target, `priorities/${i.number}/rank`, { rank: e.target.value }, `#${i.number} is now ${e.target.value}`) }, + RANKS.map((r) => h("option", { value: r, selected: r === i.rank }, r))), + h("button", { class: "ghost", onclick: async (e) => { + const text = await ask({ title: `Comment on #${i.number}`, text: i.title, label: "Comment", okLabel: "Post", required: true }); + if (text) act(e.target, `issues/${i.number}/comment`, { body: text }, "Comment posted"); + } }, "Comment")))); + const more = truncated ? [empty("There are more ranked issues than this list reads. The most urgent may not all be here.")] : []; + return [file, ...more, ...(rows.length ? rows : [empty("No ranked issues.")])]; +} + +async function agents() { + const [list, log] = await Promise.all([api("agents"), api("messages?limit=20")]); + const groups = [...new Set(list.flatMap((a) => a.groups || []))].sort(); + const target = h("select", { "aria-label": "Send to" }, + h("option", { value: "all" }, "everyone"), + groups.map((g) => h("option", { value: `group:${g}` }, `group: ${g}`)), + list.map((a) => h("option", { value: `agent:${a.name}` }, a.name))); + const kind = h("select", { class: "narrow", "aria-label": "Kind" }, h("option", { value: "message" }, "idea / message"), h("option", { value: "command" }, "command")); + const body = h("textarea", { rows: 4, placeholder: "The idea, in your words", "aria-label": "Text" }); + const send = card(h("h2", {}, "Send to agents"), target, body, h("div", { class: "row end" }, kind, + h("button", { onclick: (e) => body.value.trim() ? act(e.target, "messages", { to: [target.value], text: body.value, command: kind.value === "command" }, "Sent") : toast("Write something to send", true) }, "Send"))); + const roster = card(h("h2", {}, `Agents (${list.length})`), ...list.map((a) => h("div", { class: "row" }, + h("strong", {}, a.name), h("span", { class: "meta" }, (a.groups || []).join(", ")), h("span", { class: "grow" }), + a.unread_commands ? badge(`${a.unread_commands} unread commands`, "warn") : null, a.unread_messages ? badge(`${a.unread_messages} unread`, "warn") : null, + h("span", { class: "meta" }, (a.last_seen || "").slice(0, 16))))); + const recent = card(h("h2", {}, "Recent messages"), ...(log.length ? log.map((m) => h("div", {}, + h("p", { class: "meta" }, `${(m.ts || "").slice(0, 16)} · ${m.direction} · ${m.agent} · ${m.kind}`), h("p", { class: "why" }, (m.body || "").slice(0, 400)))) : [empty("Nothing sent yet.")])); + return [send, roster, recent]; +} + +async function services() { + const list = await api("services"); + const state = (u) => badge(`${u.active} · ${u.sub}`, u.active === "failed" ? "bad" : u.active === "active" ? "good" : "warn"); + return list.map((u) => { + const logs = h("pre", { hidden: true }); + const run = (action, danger) => h("button", { class: danger ? "danger" : "ghost", onclick: async (e) => { + const yes = await ask({ title: `${action} ${u.unit}`, text: u.description, okLabel: action, danger }); + if (yes !== null) act(e.target, `services/${encodeURIComponent(u.unit)}/${action}`, {}, `${u.unit}: ${action} requested`); + } }, action); + return card(h("div", { class: "row" }, h("h3", {}, u.unit), h("span", { class: "grow" }), state(u)), h("p", { class: "meta" }, u.description), + h("div", { class: "row end" }, + h("button", { class: "ghost", onclick: async () => { + if (!logs.hidden) return (logs.hidden = true); + try { logs.textContent = (await api(`services/${encodeURIComponent(u.unit)}/logs?lines=120`)).log || "(no output)"; logs.hidden = false; } catch (error) { toast(error.message, true); } + } }, "Logs"), + run("restart"), u.active === "active" ? run("stop", true) : run("start")), logs); + }); +} + +async function prs() { + const list = await api("prs"); + if (!list.length) return [empty("No open pull requests.")]; + return list.map((p) => { + const detail = h("div", { class: "meta" }); + const merge = h("button", { disabled: true, onclick: async (e) => { + const yes = await ask({ title: `Merge #${p.number}`, text: p.title, okLabel: "Merge" }); + if (yes !== null) act(e.target, `prs/${p.number}/merge`, {}, `#${p.number} merged`); + } }, "Merge"); + const check = h("button", { class: "ghost", onclick: async (e) => { + e.target.disabled = true; + try { + const d = await api(`prs/${p.number}`); + detail.textContent = `+${d.additions} −${d.deletions} in ${d.changed_files} files · ${d.review_comments} review comments · ${d.mergeable === true ? "mergeable" : d.mergeable === false ? "conflicts" : "mergeability pending"} (${d.mergeable_state})`; + merge.disabled = d.mergeable !== true || d.draft; + } catch (error) { toast(error.message, true); } + e.target.disabled = false; + } }, "Check"); + return card(h("h3", {}, h("a", { href: p.url, target: "_blank", rel: "noopener" }, `#${p.number}`), ` ${p.title}`), + h("p", { class: "meta" }, `${p.author} · ${p.branch} · opened ${p.created}`), detail, + h("div", { class: "row end" }, p.draft ? badge("draft", "warn") : null, check, merge)); + }); +} + +// ---- shell ----------------------------------------------------------------- + +const VIEWS = { overview: ["Overview", overview], queue: ["Queue", queue], priorities: ["Priorities", priorities], agents: ["Agents", agents], services: ["Services", services], prs: ["Pull requests", prs] }; +let current = "overview"; +let showSeq = 0; + +async function show(name) { + // Views load at different speeds. Only the latest call may draw, or a + // slow earlier view would land on top of the one now selected. + const seq = ++showSeq; + current = VIEWS[name] ? name : "overview"; + history.replaceState(null, "", `#${current}`); + for (const b of tabs.children) b.toggleAttribute("aria-current", false); + const active = tabs.querySelector(`[data-view="${current}"]`); + if (active) active.setAttribute("aria-current", "page"); + view.replaceChildren(empty("Loading…")); + try { + const drawn = await VIEWS[current][1](); + if (seq === showSeq) view.replaceChildren(...drawn); + } catch (error) { + if (seq !== showSeq) return; + view.replaceChildren(card(h("h3", {}, "This section could not load"), h("p", { class: "why" }, error.message), h("div", { class: "row end" }, h("button", { onclick: () => show(current) }, "Try again")))); + } +} + +for (const [name, [label]] of Object.entries(VIEWS)) tabs.append(h("button", { "data-view": name, onclick: () => show(name) }, label)); +api("me").then((me) => (document.getElementById("who").textContent = me.email || me.certName || me.via)).catch(() => {}); +show(location.hash.slice(1)); diff --git a/pm-stack/console/public/icon.svg b/pm-stack/console/public/icon.svg new file mode 100644 index 0000000000..91633c5c4d --- /dev/null +++ b/pm-stack/console/public/icon.svg @@ -0,0 +1 @@ + diff --git a/pm-stack/console/public/index.html b/pm-stack/console/public/index.html new file mode 100644 index 0000000000..ede8ee7d4b --- /dev/null +++ b/pm-stack/console/public/index.html @@ -0,0 +1,41 @@ + + + + + + + Console · PM stack + + + + + +
+ Console + Dashboard + + +
+ +
+ + +
+

+

+ + +
+ + +
+
+
+ + + diff --git a/pm-stack/console/scripts/expose.py b/pm-stack/console/scripts/expose.py new file mode 100755 index 0000000000..97f186ea41 --- /dev/null +++ b/pm-stack/console/scripts/expose.py @@ -0,0 +1,467 @@ +#!/usr/bin/env python3 +"""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: + +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. +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. +5. DNS points the hostname at the tunnel. + +The gate comes first and the route last, so the origin is never +reachable without sign-in in front of it. If the console does not come +up with its sign-in settings, the run stops before the route. + +Every secret is read by name through `fleet secrets get` and stays in +memory. Nothing printed is a secret. + +Usage: expose.py [--check] [--host pm.security.cab] [--owner EMAIL] + --check report what would change and exit 1 if anything would. +""" + +from __future__ import annotations + +import argparse +import json +import pathlib +import subprocess +import sys +import time +import urllib.error +import urllib.request + +API = "https://api.cloudflare.com/client/v4" +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$)" +PUBLIC_PATHS = ("/.well-known/assetlinks.json", "/manifest.webmanifest", "/icons") +GOOGLE_ID = "google.access-sso.client-id" +GOOGLE_SECRET = "google.access-sso.client-secret" + + +def secret(name: str) -> str: + return subprocess.run( + ["fleet", "secrets", "get", name], capture_output=True, text=True, check=False + ).stdout.strip() + + +class Cloudflare: + def __init__(self, token: str, check: bool) -> None: + self.token = token + self.check = check + self.changes: list[str] = [] + + def call(self, method: str, path: str, body: object | None = None) -> dict: + req = urllib.request.Request( + API + path, + method=method, + data=None if body is None else json.dumps(body).encode(), + headers={ + "Authorization": f"Bearer {self.token}", + "Content-Type": "application/json", + }, + ) + try: + with urllib.request.urlopen(req, timeout=30) as res: + out = json.load(res) + except urllib.error.HTTPError as error: + out = json.load(error) + if not out.get("success"): + raise SystemExit( + f"cloudflare {method} {path.split('?')[0]}: {json.dumps(out.get('errors'))[:300]}" + ) + return out + + def get(self, path: str) -> list | dict: + return self.call("GET", path)["result"] + + def change(self, what: str, method: str, path: str, body: object) -> dict | None: + """Record a change and, unless checking, make it.""" + self.changes.append(what) + if self.check: + return None + return self.call(method, path, body)["result"] + + +def find_tunnel(cf: Cloudflare, account: str) -> tuple[str, dict]: + tunnels = cf.get(f"/accounts/{account}/cfd_tunnel?name={TUNNEL}&is_deleted=false") + if len(tunnels) != 1: + raise SystemExit(f"expected one tunnel named {TUNNEL}, found {len(tunnels)}") + tunnel = tunnels[0]["id"] + return tunnel, cf.get(f"/accounts/{account}/cfd_tunnel/{tunnel}/configurations")[ + "config" + ] + + +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}, + ] + + 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 + # 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:] + ): + return + rest = [r for r in ingress if r.get("hostname") != host] + if not rest or rest[-1].get("hostname") or rest[-1].get("path"): + rest.append({"service": "http_status:404"}) + config["ingress"] = wanted + rest + cf.change( + f"tunnel {TUNNEL}: route {host} (/console -> console, the rest -> dashboard)", + "PUT", + f"/accounts/{account}/cfd_tunnel/{tunnel}/configurations", + {"config": config}, + ) + + +def find_zone(cf: Cloudflare, host: str) -> str: + """The zone that holds the host: the longest suffix of the name that + is a zone in this account. The last two labels are not always it + (example.co.uk, or a delegated dev.example.com).""" + labels = host.split(".") + for start in range(len(labels) - 1): + name = ".".join(labels[start:]) + zones = cf.get(f"/zones?name={name}") + if len(zones) == 1: + return zones[0]["id"] + raise SystemExit(f"dns: no zone in this account holds {host}") + + +def dns_plan(cf: Cloudflare, host: str, tunnel: str) -> tuple[str, bool]: + """Read DNS for the host. Returns the zone and whether a record is + needed; refuses if the host already points anywhere else.""" + zone = find_zone(cf, host) + records = cf.get(f"/zones/{zone}/dns_records?name={host}") + target = f"{tunnel}.cfargotunnel.com" + if records and ( + len(records) != 1 + or records[0]["type"] != "CNAME" + or records[0]["content"] != target + or not records[0]["proxied"] + ): + raise SystemExit( + f"dns: {host} already has records that are not this tunnel; not touching them" + ) + return zone, not records + + +def ensure_dns(cf: Cloudflare, host: str, tunnel: str, zone: str, needed: bool) -> None: + if needed: + cf.change( + f"dns: {host} -> tunnel", + "POST", + f"/zones/{zone}/dns_records", + { + "type": "CNAME", + "name": host, + "content": f"{tunnel}.cfargotunnel.com", + "proxied": True, + "comment": f"pm stack via tunnel {TUNNEL}", + }, + ) + + +def ensure_idps(cf: Cloudflare, account: str) -> list[str]: + idps = cf.get(f"/accounts/{account}/access/identity_providers") + by_type = {i["type"]: i for i in idps} + ids = [] + if "onetimepin" not in by_type: + made = cf.change( + "access: enable the one-time PIN sign-in", + "POST", + f"/accounts/{account}/access/identity_providers", + {"name": "One-time PIN", "type": "onetimepin", "config": {}}, + ) + if made: + ids.append(made["id"]) + else: + ids.append(by_type["onetimepin"]["id"]) + client_id, client_secret = secret(GOOGLE_ID), secret(GOOGLE_SECRET) + if "google" in by_type: + ids.append(by_type["google"]["id"]) + elif client_id and client_secret: + made = cf.change( + "access: add Google sign-in", + "POST", + f"/accounts/{account}/access/identity_providers", + { + "name": "Google", + "type": "google", + "config": {"client_id": client_id, "client_secret": client_secret}, + }, + ) + if made: + ids.append(made["id"]) + else: + print( + f"note: Google sign-in is not on yet: secrets {GOOGLE_ID} and {GOOGLE_SECRET} do not exist" + ) + return ids + + +def ensure_app( + cf: Cloudflare, + account: str, + apps: list, + domain: str, + name: str, + decision: str, + include: list, + idps: list[str] | None, +) -> str | None: + app = next( + ( + a + for a in apps + if a.get("domain") == domain and a.get("type") == "self_hosted" + ), + None, + ) + if app is None: + body: dict = { + "name": name, + "domain": domain, + "type": "self_hosted", + "session_duration": "24h", + "app_launcher_visible": decision == "allow", + } + if idps: + body["allowed_idps"] = idps + app = cf.change( + f"access: application for {domain}", + "POST", + f"/accounts/{account}/access/apps", + body, + ) + 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, + ) + 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. + mine = [ + p + for p in policies + if p.get("decision") == decision + and p.get("include") == include + and not p.get("exclude") + and not p.get("require") + ] + if len(mine) != len(policies): + raise SystemExit( + f"access: {domain} carries {len(policies) - len(mine)} policy(ies) this script did not write; review them before going on" + ) + if not mine: + cf.change( + f"access: {decision} policy on {domain}", + "POST", + f"/accounts/{account}/access/apps/{app['id']}/policies", + { + "name": f"{decision}: {name}", + "decision": decision, + "include": include, + "precedence": 1, + }, + ) + return app.get("aud") + + +def env_values(path: pathlib.Path) -> dict[str, str]: + """Read a systemd EnvironmentFile: KEY=value lines, comments, and one + optional pair of quotes around a value.""" + values: dict[str, str] = {} + if not path.exists(): + return values + for raw in path.read_text().splitlines(): + line = raw.strip() + if not line or line[0] in "#;" or "=" not in line: + continue + key, value = line.split("=", 1) + value = value.strip() + if len(value) >= 2 and value[0] == value[-1] and value[0] in "\"'": + value = value[1:-1] + values[key.strip()] = value + return values + + +def console_origin(env: pathlib.Path) -> str: + """Where the console listens, from its own environment file, so the + tunnel never routes to a port the console is not on.""" + port = env_values(env).get("PM_CONSOLE_PORT") or CONSOLE.rsplit(":", 1)[1] + if not port.isdigit() or not 0 < int(port) < 65536: + raise SystemExit(f"{env}: PM_CONSOLE_PORT is not a port: {port!r}") + return f"http://localhost:{port}" + + +def console_up(origin: str, seconds: int = 20) -> bool: + """True once the console answers its health check.""" + for _ in range(seconds): + try: + with urllib.request.urlopen(f"{origin}/console/health", timeout=3) as res: + if res.status == 200: + return True + except OSError: + pass + time.sleep(1) + return False + + +def ensure_console( + path: pathlib.Path, + wanted: dict[str, str], + origin: str, + check: bool, + changes: list[str], +) -> None: + """The console runs with the sign-in settings. Raises, so nothing is + routed, if it cannot be brought up with them.""" + have = env_values(path) + stale = [k for k, v in wanted.items() if have.get(k) != v] + if stale: + changes.append(f"console environment: {', '.join(stale)}") + running = ( + subprocess.run( + ["systemctl", "--user", "is-active", "--quiet", UNIT], check=False + ).returncode + == 0 + ) + if not stale and not running: + changes.append(f"console service: {UNIT} is not running, start it") + if check or (not stale and running): + return + if stale: + lines = path.read_text().splitlines() if path.exists() else [] + kept = [line for line in lines if line.split("=", 1)[0].strip() not in wanted] + path.parent.mkdir(parents=True, exist_ok=True, mode=0o700) + path.write_text( + "\n".join(kept + [f"{k}={v}" for k, v in wanted.items()]) + "\n" + ) + path.chmod(0o600) + done = subprocess.run( + ["systemctl", "--user", "restart", UNIT], + check=False, + capture_output=True, + text=True, + ) + if done.returncode != 0: + raise SystemExit( + f"{UNIT} did not restart ({(done.stderr or '').strip()[:200]}); the hostname is not routed" + ) + if not console_up(origin): + raise SystemExit( + f"{UNIT} restarted but does not answer at {origin}/console/health; the hostname is not routed" + ) + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + parser.add_argument("--check", action="store_true") + parser.add_argument("--host", default="pm.security.cab") + parser.add_argument("--owner", default="drewrypope@gmail.com") + args = parser.parse_args() + + token = secret("cloudflare.api-token-account-wide") + if not token: + raise SystemExit( + "secret cloudflare.api-token-account-wide is not readable here" + ) + cf = Cloudflare(token, args.check) + accounts = cf.get("/accounts?per_page=5") + if len(accounts) != 1: + raise SystemExit(f"expected one account, found {len(accounts)}") + account = accounts[0]["id"] + team = cf.get(f"/accounts/{account}/access/organizations")["auth_domain"] + + # Look before changing anything: a hostname that already points + # somewhere else stops the run with nothing written. + tunnel, tunnel_config = find_tunnel(cf, account) + zone, dns_needed = dns_plan(cf, args.host, tunnel) + env = pathlib.Path.home() / ".local/state/pm-console/.env" + console = console_origin(env) + + # Order matters. The sign-in gate is put in place first and the route + # last, so the origin is never reachable without the gate in front. + idps = ensure_idps(cf, account) + apps = cf.get(f"/accounts/{account}/access/apps?per_page=200") + for path in PUBLIC_PATHS: + ensure_app( + cf, + account, + apps, + args.host + path, + f"PM stack public file {path}", + "bypass", + [{"everyone": {}}], + None, + ) + aud = ensure_app( + cf, + account, + apps, + args.host, + "PM stack", + "allow", + [{"email": {"email": args.owner}}], + idps, + ) + if aud: + ensure_console( + env, + { + "PM_CONSOLE_ACCESS_TEAM_DOMAIN": team, + "PM_CONSOLE_ACCESS_AUD": aud, + "PM_CONSOLE_OWNER_EMAILS": args.owner, + }, + console, + args.check, + cf.changes, + ) + if aud or args.check: + ensure_routes(cf, account, args.host, tunnel, tunnel_config, console) + ensure_dns(cf, args.host, tunnel, zone, dns_needed) + else: + raise SystemExit( + "the Access application has no audience tag; not routing the hostname" + ) + + for change in cf.changes: + print(("would change: " if args.check else "changed: ") + change) + if not cf.changes: + print( + f"https://{args.host}/ is set up: dashboard at /, console at /console/, owner {args.owner}" + ) + return 1 if args.check and cf.changes else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/pm-stack/console/scripts/test_expose.py b/pm-stack/console/scripts/test_expose.py new file mode 100755 index 0000000000..c1d7cb80a2 --- /dev/null +++ b/pm-stack/console/scripts/test_expose.py @@ -0,0 +1,363 @@ +#!/usr/bin/env python3 +"""expose.py against a model of the Cloudflare account. + +The model holds what the real account holds (sign-in methods, Access +applications and policies, tunnel routes, zones and DNS records) and +applies each change the script makes; a second model stands in for the +machine's console service. Checked: the sign-in gate exists before the +route does, a second run changes nothing, --check changes nothing, +records or policies the script did not write are left alone, a console +that does not come up stops the run before the route, the host's rules +sit ahead of any wildcard, and the DNS record goes in the zone that +really holds the name. +""" + +import copy +import pathlib +import sys +import tempfile +import unittest +from unittest import mock + +sys.path.insert(0, str(pathlib.Path(__file__).parent)) +import expose + +HOST = "pm.security.cab" + + +class Account(expose.Cloudflare): + def __init__(self, check=False): + super().__init__("token", check) + self.idps = [{"id": "idp-cf", "type": "cloudflare", "name": ""}] + self.apps = [] + self.policies = {} + self.ingress = [ + {"hostname": "kaneo.security.cab", "service": "http://localhost:5173"}, + {"service": "http_status:404"}, + ] + self.dns = [] + self.zones = {"security.cab": "zone"} + self.order = [] + + def call(self, method, path, body=None): + path, _, query = path.partition("?") + if method != "GET": + self.order.append(f"{method} {path}") + if path == "/accounts": + result = [{"id": "acc"}] + elif path.endswith("/access/organizations"): + result = {"auth_domain": "team.cloudflareaccess.com"} + elif path.endswith("/access/identity_providers"): + if method == "POST": + self.idps.append({"id": f"idp-{body['type']}", **body}) + result = self.idps[-1] if method == "POST" else self.idps + elif path.endswith("/access/apps"): + if method == "POST": + self.apps.append( + { + "id": f"app-{len(self.apps)}", + "aud": f"aud-{len(self.apps)}", + **body, + } + ) + self.policies[self.apps[-1]["id"]] = [] + result = self.apps[-1] if method == "POST" else self.apps + elif path.endswith("/policies"): + app = path.split("/")[-2] + if method == "POST": + self.policies[app].append(body) + result = self.policies[app] + elif path.endswith("/cfd_tunnel"): + result = [{"id": "tun", "name": expose.TUNNEL}] + elif path.endswith("/configurations"): + if method == "PUT": + self.ingress = body["config"]["ingress"] + result = { + "config": { + "ingress": copy.deepcopy(self.ingress), + "warp-routing": {"enabled": False}, + } + } + elif path == "/zones": + name = query.partition("name=")[2] + result = [{"id": self.zones[name]}] if name in self.zones else [] + elif path.endswith("/dns_records"): + if method == "POST": + self.dns.append({**body, "zone": path.split("/")[2]}) + name = query.partition("name=")[2] + result = [r for r in self.dns if r["name"] == name] + else: + raise AssertionError(f"unexpected call {method} {path}") + return {"success": True, "result": result} + + +class Machine: + """The console's user unit: systemctl and the health check.""" + + def __init__(self, running=True, restarts=True, comes_up=True): + self.running = running + self.restarts = restarts + self.comes_up = comes_up + self.commands = [] + + def systemctl(self, argv, **_): + self.commands.append(argv[2]) + code = 0 + if argv[2] == "is-active": + code = 0 if self.running else 3 + elif argv[2] == "restart": + self.running = self.restarts and self.comes_up + code = 0 if self.restarts else 1 + return mock.Mock(returncode=code, stdout="", stderr="unit failed") + + def up(self, origin, seconds=20): + return self.running + + +def run(account, home, *args, machine=None): + argv = ["expose.py", *args] + machine = machine or Machine() + with ( + mock.patch.object(expose, "Cloudflare", lambda token, check: account), + mock.patch.object( + expose, + "secret", + lambda name: "token" if name.startswith("cloudflare.") else "", + ), + mock.patch.object(expose.pathlib.Path, "home", lambda: pathlib.Path(home)), + mock.patch.object(expose.subprocess, "run", machine.systemctl), + mock.patch.object(expose, "console_up", machine.up), + mock.patch.object(sys, "argv", argv), + mock.patch("builtins.print"), + ): + account.check = "--check" in args + account.changes = [] + return expose.main() + + +class Expose(unittest.TestCase): + def setUp(self): + self.home = tempfile.mkdtemp() + + def test_the_gate_exists_before_the_route(self): + account = Account() + self.assertEqual(run(account, self.home), 0) + route = account.order.index("PUT /accounts/acc/cfd_tunnel/tun/configurations") + dns = account.order.index("POST /zones/zone/dns_records") + gate = max(i for i, c in enumerate(account.order) if "/access/" in c) + self.assertLess(gate, route) + self.assertLess(route, dns) + main = next(a for a in account.apps if a["domain"] == HOST) + self.assertEqual( + account.policies[main["id"]], + [ + { + "name": "allow: PM stack", + "decision": "allow", + "include": [{"email": {"email": "drewrypope@gmail.com"}}], + "precedence": 1, + } + ], + ) + self.assertEqual(main["allowed_idps"], ["idp-onetimepin"]) + 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. + 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), + ("kaneo.security.cab", None, "http://localhost:5173"), + (None, None, "http_status:404"), + ], + ) + self.assertEqual( + account.dns, + [ + { + "type": "CNAME", + "name": HOST, + "content": "tun.cfargotunnel.com", + "proxied": True, + "comment": f"pm stack via tunnel {expose.TUNNEL}", + "zone": "zone", + } + ], + ) + env = (pathlib.Path(self.home) / ".local/state/pm-console/.env").read_text() + self.assertIn("PM_CONSOLE_ACCESS_AUD=" + main["aud"], env) + self.assertIn("PM_CONSOLE_OWNER_EMAILS=drewrypope@gmail.com", env) + + def test_a_second_run_changes_nothing(self): + account = Account() + run(account, self.home) + before = ( + copy.deepcopy(account.apps), + copy.deepcopy(account.policies), + copy.deepcopy(account.ingress), + copy.deepcopy(account.dns), + len(account.order), + ) + self.assertEqual(run(account, self.home), 0) + self.assertEqual(account.changes, []) + self.assertEqual( + ( + account.apps, + account.policies, + account.ingress, + account.dns, + len(account.order), + ), + before, + ) + self.assertEqual(run(account, self.home, "--check"), 0) + + def test_check_reports_and_changes_nothing(self): + account = Account() + self.assertEqual(run(account, self.home, "--check"), 1) + self.assertEqual(account.order, []) + self.assertEqual(len(account.changes), 7) + self.assertFalse( + (pathlib.Path(self.home) / ".local/state/pm-console/.env").exists() + ) + + def test_foreign_records_and_policies_are_left_alone(self): + account = Account() + account.dns = [ + {"type": "A", "name": HOST, "content": "203.0.113.5", "proxied": False} + ] + with self.assertRaisesRegex(SystemExit, "not this tunnel"): + run(account, self.home) + self.assertEqual(len(account.dns), 1) + self.assertEqual(account.order, []) # refused before anything was written + + account = Account() + account.apps = [ + { + "id": "app-x", + "aud": "aud-x", + "domain": HOST, + "type": "self_hosted", + "allowed_idps": ["idp-onetimepin"], + } + ] + account.policies = { + "app-x": [{"decision": "allow", "include": [{"everyone": {}}]}] + } + with self.assertRaisesRegex(SystemExit, "did not write"): + run(account, self.home) + # Nothing was routed, and no policy added, while the gate was in doubt. + self.assertNotIn(HOST, [r.get("hostname") for r in account.ingress]) + self.assertEqual(len(account.policies["app-x"]), 1) + + # The owner's own rule with a condition added is not this script's rule. + owner = [{"email": {"email": "drewrypope@gmail.com"}}] + for extra in ( + {"exclude": owner}, + {"require": [{"geo": {"country_code": "XX"}}]}, + ): + account = Account() + run(account, self.home) + main = next(a for a in account.apps if a["domain"] == HOST) + account.policies[main["id"]][0].update(extra) + with self.assertRaisesRegex(SystemExit, "did not write"): + run(account, self.home) + # Empty lists, as the API returns them, are still this script's rule. + account = Account() + run(account, self.home) + main = next(a for a in account.apps if a["domain"] == HOST) + account.policies[main["id"]][0].update({"exclude": [], "require": []}) + self.assertEqual(run(account, self.home), 0) + self.assertEqual(account.changes, []) + + def test_a_console_that_does_not_come_up_stops_the_run_before_the_route(self): + for machine, why in ( + (Machine(restarts=False), "did not restart"), + (Machine(comes_up=False), "does not answer"), + ): + account = Account() + with self.assertRaisesRegex(SystemExit, why): + run(account, self.home, machine=machine) + self.assertNotIn(HOST, [r.get("hostname") for r in account.ingress]) + self.assertEqual(account.dns, []) + pathlib.Path(self.home, ".local/state/pm-console/.env").unlink() + + # Settings already right but the service down: it is started, and + # --check says so instead of calling the setup complete. + account = Account() + run(account, self.home) + down = Machine(running=False) + self.assertEqual(run(account, self.home, "--check", machine=down), 1) + self.assertEqual(down.commands, ["is-active"]) + self.assertEqual(run(account, self.home, machine=down), 0) + self.assertEqual(down.commands, ["is-active", "is-active", "restart"]) + self.assertTrue(down.running) + up = Machine() + self.assertEqual(run(account, self.home, machine=up), 0) + self.assertEqual(up.commands, ["is-active"]) + + def test_the_route_follows_the_console_port_and_sits_ahead_of_wildcards(self): + env = pathlib.Path(self.home, ".local/state/pm-console/.env") + env.parent.mkdir(parents=True) + env.write_text('# settings\nPM_CONSOLE_PORT="4999"\nOTHER=kept\n') + account = Account() + wildcard = {"hostname": "*.security.cab", "service": "http://localhost:1"} + account.ingress.insert(0, wildcard) + self.assertEqual(run(account, self.home), 0) + self.assertEqual( + [(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"), + ], + ) + self.assertIn("OTHER=kept", env.read_text()) + self.assertIn('PM_CONSOLE_PORT="4999"', env.read_text()) + # The host's rules behind a wildcard are moved ahead of it, once. + account.ingress = [wildcard] + [ + r for r in account.ingress if r is not wildcard and r != wildcard + ] + self.assertEqual(run(account, self.home), 0) + self.assertEqual(account.ingress[0]["hostname"], HOST) + self.assertEqual(len(account.changes), 1) + self.assertEqual(run(account, self.home), 0) + self.assertEqual(account.changes, []) + # A tunnel whose last rule is not a catch-all gets one. + account.ingress = [{"hostname": "kaneo.security.cab", "service": "x"}] + run(account, self.home) + self.assertEqual(account.ingress[-1], {"service": "http_status:404"}) + + env.write_text("PM_CONSOLE_PORT=console\n") + account = Account() + with self.assertRaisesRegex(SystemExit, "PM_CONSOLE_PORT"): + run(account, self.home) + self.assertEqual(account.order, []) # refused before anything was written + + def test_the_record_goes_in_the_zone_that_holds_the_name(self): + host = "pm.dev.example.co.uk" + account = Account() + account.zones = {"example.co.uk": "outer", "dev.example.co.uk": "inner"} + self.assertEqual(run(account, self.home, "--host", host), 0) + self.assertEqual( + [(r["name"], r["zone"]) for r in account.dns], [(host, "inner")] + ) + account = Account() + account.zones = {"example.co.uk": "outer"} + self.assertEqual(run(account, self.home, "--host", host), 0) + self.assertEqual([r["zone"] for r in account.dns], ["outer"]) + account = Account() + account.zones = {"co.uk.example": "wrong"} + with self.assertRaisesRegex(SystemExit, "no zone"): + run(account, self.home, "--host", host) + self.assertEqual(account.order, []) + + +if __name__ == "__main__": + unittest.main() diff --git a/pm-stack/console/src/auth.ts b/pm-stack/console/src/auth.ts new file mode 100644 index 0000000000..cd1be519b7 --- /dev/null +++ b/pm-stack/console/src/auth.ts @@ -0,0 +1,245 @@ +// Who is calling. +// +// The console never runs a sign-in itself. A caller arrives with a +// signed token from an issuer the deployment trusts, and the console +// checks the signature, the issuer, the audience and the times, then +// asks one question: is this identity the owner? +// +// Today the issuer is Cloudflare Access at the public edge, which runs +// the interactive sign-in (Google, and any OIDC provider or client +// certificate authority added to it later). Any other OIDC issuer's +// token is accepted the same way once it is listed in the issuers file, +// so the central provider needs configuration, not code. +// +// A request that did not come through the edge at all (loopback host, +// no edge headers) is a process on this machine and is the owner: such +// a process already has the owner's shell. +import type { Config, Issuer } from "./config.ts"; + +export interface Identity { + /** Issuer name, or "loopback". */ + via: string; + email?: string; + certName?: string; + sub?: string; +} + +export class AuthError extends Error { + constructor( + public status: 401 | 403, + message: string, + ) { + super(message); + } +} + +type Jwk = JsonWebKey & { kid?: string }; +type FetchLike = ( + url: string, + init?: { signal?: AbortSignal }, +) => Promise<{ ok: boolean; status: number; json(): Promise }>; + +const JWKS_TTL_MS = 10 * 60_000; +const JWKS_REFRESH_COOLDOWN_MS = 30_000; +const JWKS_FETCH_TIMEOUT_MS = 5_000; +const SKEW_MS = 60_000; +const jwksCache = new Map(); +const jwksInFlight = new Map>(); + +export function clearJwksCache(): void { + jwksCache.clear(); + jwksInFlight.clear(); +} + +/** + * The issuer's keys. `force` asks for a fresh copy because a token named + * a key the cache does not hold. Anyone can send such a token, so a + * forced refresh happens at most once per cooldown, concurrent callers + * share one request, and the request has a deadline. + */ +async function jwks(uri: string, fetchImpl: FetchLike, now: number, force = false): Promise { + const hit = jwksCache.get(uri); + if (hit && now - hit.at < (force ? JWKS_REFRESH_COOLDOWN_MS : JWKS_TTL_MS)) return hit.keys; + const pending = jwksInFlight.get(uri); + if (pending) return pending; + const request = (async () => { + const res = await fetchImpl(uri, { signal: AbortSignal.timeout(JWKS_FETCH_TIMEOUT_MS) }); + if (!res.ok) throw new Error(`key set fetch failed: http ${res.status}`); + const body = (await res.json()) as { keys?: unknown }; + if (!Array.isArray(body.keys)) throw new Error("key set has no keys"); + const keys = body.keys as Jwk[]; + jwksCache.set(uri, { at: now, keys }); + return keys; + })(); + jwksInFlight.set(uri, request); + try { + return await request; + } finally { + jwksInFlight.delete(uri); + } +} + +function b64url(text: string): Uint8Array { + if (!/^[A-Za-z0-9_-]*$/.test(text)) throw new Error("not base64url"); + const pad = text.length % 4 === 0 ? "" : "=".repeat(4 - (text.length % 4)); + const bin = atob(text.replace(/-/g, "+").replace(/_/g, "/") + pad); + return Uint8Array.from(bin, (c) => c.charCodeAt(0)); +} + +const ALGS: Record< + string, + { kty: string; importAlg: RsaHashedImportParams | EcKeyImportParams; verifyAlg: AlgorithmIdentifier | EcdsaParams } +> = { + RS256: { kty: "RSA", importAlg: { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" }, verifyAlg: "RSASSA-PKCS1-v1_5" }, + ES256: { + kty: "EC", + importAlg: { name: "ECDSA", namedCurve: "P-256" }, + verifyAlg: { name: "ECDSA", hash: "SHA-256" }, + }, +}; + +/** Verify a compact JWT against one issuer. Returns its claims. */ +export async function verifyJwt( + token: string, + issuer: Issuer, + fetchImpl: FetchLike = fetch as unknown as FetchLike, + now: number = Date.now(), +): Promise> { + const parts = token.split("."); + if (parts.length !== 3) throw new Error("malformed token"); + let header: Record; + let claims: Record; + try { + header = JSON.parse(new TextDecoder().decode(b64url(parts[0]))); + claims = JSON.parse(new TextDecoder().decode(b64url(parts[1]))); + } catch { + throw new Error("malformed token"); + } + if (header === null || typeof header !== "object" || claims === null || typeof claims !== "object") { + throw new Error("malformed token"); + } + // The algorithm comes from a fixed list, never from the key or from + // whatever the token asks for ("none", HS256 with a public key, ...). + const alg = typeof header.alg === "string" ? ALGS[header.alg] : undefined; + if (!alg) throw new Error("unsupported token algorithm"); + if (typeof header.kid !== "string" || header.kid === "") throw new Error("token names no key"); + const match = (keys: Jwk[]) => keys.find((k) => k.kid === header.kid && k.kty === alg.kty); + let jwk = match(await jwks(issuer.jwksUri, fetchImpl, now)); + // An issuer may rotate keys inside the cache window: one forced refresh. + if (!jwk) jwk = match(await jwks(issuer.jwksUri, fetchImpl, now, true)); + if (!jwk) throw new Error("no key matches the token"); + const { kty, n, e, crv, x, y } = jwk; + const key = await crypto.subtle.importKey("jwk", { kty, n, e, crv, x, y }, alg.importAlg, false, ["verify"]); + const ok = await crypto.subtle.verify( + alg.verifyAlg, + key, + b64url(parts[2]), + new TextEncoder().encode(`${parts[0]}.${parts[1]}`), + ); + if (!ok) throw new Error("token signature invalid"); + + if (claims.iss !== issuer.issuer) throw new Error("token issuer mismatch"); + const aud = claims.aud; + const audOk = typeof aud === "string" ? aud === issuer.audience : Array.isArray(aud) && aud.includes(issuer.audience); + if (!audOk) throw new Error("token audience mismatch"); + if (typeof claims.exp !== "number" || claims.exp * 1000 < now - SKEW_MS) throw new Error("token expired"); + if (claims.nbf !== undefined && (typeof claims.nbf !== "number" || claims.nbf * 1000 > now + SKEW_MS)) { + throw new Error("token not yet valid"); + } + if (claims.iat !== undefined && (typeof claims.iat !== "number" || claims.iat * 1000 > now + SKEW_MS)) { + throw new Error("token issued in the future"); + } + return claims; +} + +const EDGE_HEADERS = [ + "cf-ray", + "cf-connecting-ip", + "cdn-loop", + "cf-visitor", + "cf-access-jwt-assertion", + "x-forwarded-for", +]; + +export function isLoopbackHost(host: string | null): boolean { + if (!host) return false; + const name = host.toLowerCase().replace(/:\d+$/, ""); + return name === "127.0.0.1" || name === "localhost" || name === "[::1]"; +} + +/** True when the request shows any sign of having crossed a proxy. */ +export function cameThroughEdge(req: Request): boolean { + return !isLoopbackHost(req.headers.get("host")) || EDGE_HEADERS.some((h) => req.headers.has(h)); +} + +function cookie(req: Request, name: string): string | null { + for (const part of (req.headers.get("cookie") ?? "").split(";")) { + const i = part.indexOf("="); + if (i > 0 && part.slice(0, i).trim() === name) return part.slice(i + 1).trim(); + } + return null; +} + +function presented(req: Request, source: Issuer["source"]): string | null { + if (source === "access") return req.headers.get("cf-access-jwt-assertion") ?? cookie(req, "CF_Authorization"); + const m = /^Bearer\s+(\S+)$/i.exec(req.headers.get("authorization") ?? ""); + return m ? m[1] : null; +} + +/** Map verified claims to the owner, or refuse. */ +export function authorize( + claims: Record, + via: string, + cfg: Pick, +): Identity { + const sub = typeof claims.sub === "string" ? claims.sub : undefined; + const email = typeof claims.email === "string" ? claims.email.toLowerCase() : ""; + // An issuer that says the address is unverified has not identified anyone. + if (email !== "" && claims.email_verified !== false && cfg.owners.includes(email)) return { via, email, sub }; + const certName = typeof claims.common_name === "string" ? claims.common_name : ""; + if (certName !== "" && cfg.certNames.includes(certName)) return { via, certName, sub }; + throw new AuthError(403, "this identity is not the owner"); +} + +/** True for an address on this machine's loopback interface. */ +export function isLoopbackAddress(address: string | null | undefined): boolean { + if (!address) return false; + const a = address.toLowerCase().replace(/^::ffff:/, ""); + return a === "::1" || /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(a); +} + +export interface IdentifyOptions { + /** The connection's remote address, from the server, never from a header. */ + peer?: string | null; + fetchImpl?: FetchLike; + now?: number; +} + +/** Identify the caller of a request, or throw AuthError. */ +export async function identify( + req: Request, + cfg: Pick, + opts: IdentifyOptions = {}, +): Promise { + const fetchImpl = opts.fetchImpl ?? (fetch as unknown as FetchLike); + const now = opts.now ?? Date.now(); + let sawToken = false; + for (const issuer of cfg.issuers) { + const token = presented(req, issuer.source); + if (!token) continue; + sawToken = true; + let claims: Record; + try { + claims = await verifyJwt(token, issuer, fetchImpl, now); + } catch { + continue; // another issuer may own this token + } + return authorize(claims, issuer.name, cfg); + } + if (sawToken) throw new AuthError(401, "the presented token was not accepted"); + // Local means the connection itself came from this machine. The Host + // and forwarding headers are the caller's to write, so they can only + // take the local identity away, never grant it. + if (!isLoopbackAddress(opts.peer) || cameThroughEdge(req)) throw new AuthError(401, "sign-in required"); + return { via: "loopback", email: "local" }; +} diff --git a/pm-stack/console/src/config.ts b/pm-stack/console/src/config.ts new file mode 100644 index 0000000000..ede68f4b93 --- /dev/null +++ b/pm-stack/console/src/config.ts @@ -0,0 +1,178 @@ +// pm-console configuration. Numeric variables follow the pm-stack +// environment contract (pm-stack/README.md, "Environment numbers"): +// decimal digits only, range-checked, and a bad value stops the process +// at boot naming the variable. +import { readFileSync } from "node:fs"; + +/** A token issuer whose signed tokens identify a caller. */ +export interface Issuer { + /** Short name shown in the audit log and on /api/me. */ + name: string; + /** Exact `iss` claim. */ + issuer: string; + /** Where the issuer publishes its signing keys. */ + jwksUri: string; + /** Required `aud` value. */ + audience: string; + /** + * Where the token arrives. "access" is Cloudflare Access: the + * Cf-Access-Jwt-Assertion header, or the CF_Authorization cookie. + * "bearer" is `Authorization: Bearer `, the form any other + * OIDC issuer's ID token takes. + */ + source: "access" | "bearer"; +} + +export interface Config { + port: number; + bind: string; + /** Email addresses that are the owner, lower-cased. */ + owners: string[]; + /** Certificate common names that are the owner (client certificates + * checked at the edge and reported in the token's `common_name`). */ + certNames: string[]; + issuers: Issuer[]; + repo: string; + queue: string; + queueDbUrl: string; + queueTokenName: string; + fleetBin: string; + /** Glob patterns of the systemd user units the console may manage. */ + unitPatterns: string[]; + /** Units that may be restarted but never stopped from here: stopping + * either one cuts off the interface that would start it again. */ + protectedUnits: string[]; + auditFile: string; + /** Android app identity served at /.well-known/assetlinks.json. */ + androidPackage: string; + androidFingerprints: string[]; +} + +export class ConfigError extends Error {} + +type Env = Record; + +function port(env: Env, name: string, fallback: number): number { + const raw = env[name]; + if (raw === undefined) return fallback; + if (!/^[0-9]+$/.test(raw)) throw new ConfigError(`${name}: not a decimal port: ${JSON.stringify(raw)}`); + const n = Number(raw); + if (n < 1 || n > 65535) throw new ConfigError(`${name}: port out of range 1-65535: ${raw}`); + return n; +} + +function list(env: Env, name: string, fallback: string[] = []): string[] { + const raw = env[name]; + if (raw === undefined) return fallback; + return raw + .split(",") + .map((s) => s.trim()) + .filter((s) => s !== ""); +} + +function issuerFrom(value: unknown, where: string): Issuer { + const v = value as Record; + for (const key of ["name", "issuer", "jwksUri", "audience"]) { + if (typeof v?.[key] !== "string" || v[key] === "") throw new ConfigError(`${where}: missing "${key}"`); + } + const source = v.source === undefined ? "bearer" : v.source; + if (source !== "access" && source !== "bearer") + throw new ConfigError(`${where}: source must be "access" or "bearer"`); + for (const key of ["issuer", "jwksUri"]) { + if (!/^https:\/\//.test(v[key] as string)) throw new ConfigError(`${where}: "${key}" must be an https URL`); + } + return { + name: v.name as string, + issuer: v.issuer as string, + jwksUri: v.jwksUri as string, + audience: v.audience as string, + source, + }; +} + +export function readConfig( + env: Env = process.env, + readFile: (p: string) => string = (p) => readFileSync(p, "utf8"), +): Config { + const home = env.HOME ?? ""; + const issuers: Issuer[] = []; + + // Cloudflare Access, the edge sign-in. Both variables or neither. + const team = env.PM_CONSOLE_ACCESS_TEAM_DOMAIN; + const aud = env.PM_CONSOLE_ACCESS_AUD; + if ((team === undefined) !== (aud === undefined)) { + throw new ConfigError("PM_CONSOLE_ACCESS_TEAM_DOMAIN and PM_CONSOLE_ACCESS_AUD must be set together"); + } + if (team !== undefined && aud !== undefined) { + if (!/^[a-z0-9-]+\.cloudflareaccess\.com$/.test(team)) { + throw new ConfigError( + `PM_CONSOLE_ACCESS_TEAM_DOMAIN: not a cloudflareaccess.com team domain: ${JSON.stringify(team)}`, + ); + } + if (aud === "") throw new ConfigError("PM_CONSOLE_ACCESS_AUD: empty"); + issuers.push({ + name: "cloudflare-access", + issuer: `https://${team}`, + jwksUri: `https://${team}/cdn-cgi/access/certs`, + audience: aud, + source: "access", + }); + } + + // Any further issuer (the central OIDC provider, Google directly) is + // one entry in a JSON file: [{name, issuer, jwksUri, audience, source}]. + const file = env.PM_CONSOLE_ISSUERS_FILE; + if (file !== undefined && file !== "") { + let parsed: unknown; + try { + parsed = JSON.parse(readFile(file)); + } catch (error) { + throw new ConfigError(`PM_CONSOLE_ISSUERS_FILE: cannot read ${file}: ${(error as Error).message}`); + } + if (!Array.isArray(parsed)) throw new ConfigError("PM_CONSOLE_ISSUERS_FILE: expected a JSON array"); + parsed.forEach((entry, i) => issuers.push(issuerFrom(entry, `PM_CONSOLE_ISSUERS_FILE[${i}]`))); + } + const names = issuers.map((i) => i.name); + if (new Set(names).size !== names.length) throw new ConfigError("issuer names must be unique"); + + const fingerprints = list(env, "PM_CONSOLE_ANDROID_SHA256"); + for (const f of fingerprints) { + if (!/^([0-9A-F]{2}:){31}[0-9A-F]{2}$/.test(f)) { + throw new ConfigError( + `PM_CONSOLE_ANDROID_SHA256: not a colon-separated SHA-256 fingerprint: ${JSON.stringify(f)}`, + ); + } + } + + // Loopback only. A request with no token is trusted when it comes from + // this machine, so the listener must not be reachable from another one. + const bind = env.PM_CONSOLE_BIND ?? "127.0.0.1"; + if (bind !== "127.0.0.1" && bind !== "::1" && bind !== "localhost") { + throw new ConfigError(`PM_CONSOLE_BIND: only a loopback address is supported, not ${JSON.stringify(bind)}`); + } + + return { + port: port(env, "PM_CONSOLE_PORT", 4872), + bind, + owners: list(env, "PM_CONSOLE_OWNER_EMAILS").map((e) => e.toLowerCase()), + certNames: list(env, "PM_CONSOLE_CERT_NAMES"), + issuers, + repo: env.PM_CONSOLE_REPO ?? "developing-today/code", + queue: env.PM_CONSOLE_QUEUE ?? "repo-health-code-pilot", + queueDbUrl: env.PM_CONSOLE_QUEUE_DB_URL ?? "https://fleet-queue-dezren39.aws-us-east-1.turso.io", + queueTokenName: env.PM_CONSOLE_QUEUE_TOKEN_NAME ?? "turso.fleet-queue-rw-token", + fleetBin: env.PM_CONSOLE_FLEET_BIN ?? "fleet", + unitPatterns: list(env, "PM_CONSOLE_UNITS", [ + "pm-*", + "opencode*", + "openchamber*", + "queue-broker*", + "secrets-broker*", + "fleet-*", + ]), + 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`, + androidPackage: env.PM_CONSOLE_ANDROID_PACKAGE ?? "today.developing.pmconsole", + androidFingerprints: fingerprints, + }; +} diff --git a/pm-stack/console/src/ops.ts b/pm-stack/console/src/ops.ts new file mode 100644 index 0000000000..29a2a06607 --- /dev/null +++ b/pm-stack/console/src/ops.ts @@ -0,0 +1,557 @@ +// What the console can do. Every operation is one of the verbs the +// fleet already has: the queue through `fleet queue` and its store, +// messages through `fleet bridge`, GitHub through `fleet gh`, and +// services through `systemctl --user`. Nothing here builds a shell +// command line: each call is an argument vector, and text a person +// typed travels on stdin or as a single argument. +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import type { Config } from "./config.ts"; + +export interface RunResult { + code: number; + stdout: string; + stderr: string; +} +export type Run = (argv: string[], opts?: { stdin?: string; timeoutMs?: number }) => Promise; +export type Fetch = ( + url: string, + init: { method: string; headers: Record; body: string }, +) => Promise<{ ok: boolean; status: number; json(): Promise }>; + +export class OpError extends Error { + constructor( + public status: 400 | 404 | 409 | 502, + message: string, + ) { + super(message); + } +} + +export const realRun: Run = async (argv, opts = {}) => { + const proc = Bun.spawn(argv, { + stdin: opts.stdin === undefined ? "ignore" : new Blob([opts.stdin]), + stdout: "pipe", + stderr: "pipe", + }); + const timer = setTimeout(() => proc.kill(), opts.timeoutMs ?? 30_000); + try { + const [stdout, stderr, code] = await Promise.all([ + new Response(proc.stdout).text(), + new Response(proc.stderr).text(), + proc.exited, + ]); + return { code, stdout, stderr }; + } finally { + clearTimeout(timer); + } +}; + +/** Rank labels, most urgent first: the order the intake ladder reads. */ +export const RANKS = ["expedite", "priority/critical", "now", "priority/high", "next"] as const; +export type Rank = (typeof RANKS)[number] | "none"; +/** Pages of ranked issues read before giving up (100 issues a page). */ +const PRIORITY_PAGES = 10; +export const QUEUE_STATUSES = ["queued", "claimed", "blocked", "parked"] as const; +const UNIT_NAME = /^[A-Za-z0-9@._-]+\.(service|timer)$/; +const UNIT_ACTIONS = ["start", "stop", "restart"] as const; +export type UnitAction = (typeof UNIT_ACTIONS)[number]; + +function globToRegExp(glob: string): RegExp { + return new RegExp("^" + glob.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, "[A-Za-z0-9@._-]*") + "$"); +} + +/** A unit the console may touch: a plain unit name matching a pattern. */ +export function manageable(unit: string, patterns: string[]): boolean { + return UNIT_NAME.test(unit) && patterns.some((p) => globToRegExp(p).test(unit)); +} + +export interface Unit { + unit: string; + load: string; + active: string; + sub: string; + description: string; +} + +/** Parse `systemctl list-units --plain --no-legend` output. */ +export function parseUnits(text: string): Unit[] { + const units: Unit[] = []; + for (const line of text.split("\n")) { + const m = /^\s*(?:●\s+)?(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s*(.*)$/.exec(line); + if (!m || !UNIT_NAME.test(m[1])) continue; + units.push({ unit: m[1], load: m[2], active: m[3], sub: m[4], description: m[5].trim() }); + } + return units; +} + +/** Queue priority for owner-filed work, on the queue's design scale + * (10, 20, 30, ...): lower is sooner and 30 is the bulk band. */ +const RANK_PRIORITY: Record = { + expedite: 10, + "priority/critical": 10, + now: 20, + "priority/high": 20, + next: 30, + none: 30, +}; + +/** The triage task for an issue the owner filed from the console. Same + * shape as the coverage reconciliation's, so the two never disagree. */ +export function triagePacket( + repo: string, + queue: string, + number: number, + title: string, + rank: Rank, + checkedAt: string, +) { + const url = `https://github.com/${repo}/issues/${number}`; + return { + title: `Triage ${repo}#${number}: ${title}`.slice(0, 180), + body: `Filed by the owner from the PM console: ${url}`, + priority: RANK_PRIORITY[rank], + dedupe_key: `repo-health:v1:triage:${repo}:issue:${number}`, + payload: { + schema: "repo-task/v1", + kind: "triage", + repo, + queue, + issue: { number, url, title, state_checked_at: checkedAt }, + problem: + "The owner filed this from the PM console. It is new work with no task yet: triage it and either do it or return it to the queue sized for real work.", + evidence: [`Filed from the PM console at ${checkedAt}, rank ${rank}`, url], + acceptance: [ + "Issue triaged per the standing triage doctrine: annotate, validate, and either fix it in a small edit (merge with a closing keyword) or return it to the queue for real work", + ], + tests: ["Triage verdict recorded on the issue; if a small fix, the merged PR carries a closing keyword"], + scope: { include: [`Triage of ${repo}#${number}`], exclude: ["Secrets, credentials or purchases"] }, + risk: { level: "low", flags: ["owner-filed"] }, + priority_reason: `Owner-filed from the console with rank ${rank}: priority ${RANK_PRIORITY[rank]}.`, + timebox_minutes: 45, + max_attempts: 1000, + context_refs: [url], + dedupe: { + checked_at: checkedAt, + basis: "The issue was created in the same pass as this task, so no other task can hold it.", + }, + }, + }; +} + +/** Parse `systemctl list-unit-files --plain --no-legend` output: + * unit, state, and sometimes a preset. Templates (name@.service) are + * skipped: they cannot be started without an instance name. */ +export function parseUnitFiles(text: string): { unit: string; state: string }[] { + const files: { unit: string; state: string }[] = []; + for (const line of text.split("\n")) { + const m = /^\s*(\S+)\s+(\S+)/.exec(line); + if (!m || !UNIT_NAME.test(m[1]) || m[1].includes("@.")) continue; + files.push({ unit: m[1], state: m[2] }); + } + return files; +} + +function text(value: unknown, name: string, max: number, min = 1): string { + if (typeof value !== "string") throw new OpError(400, `${name}: expected text`); + const trimmed = value.trim(); + if (trimmed.length < min) throw new OpError(400, `${name}: required`); + if (trimmed.length > max) throw new OpError(400, `${name}: longer than ${max} characters`); + return trimmed; +} + +function id(value: unknown, name: string): number { + const s = String(value); + if (!/^[1-9][0-9]{0,9}$/.test(s)) throw new OpError(400, `${name}: not a positive number`); + return Number(s); +} + +export class Ops { + private queueToken: string | null = null; + + constructor( + private cfg: Config, + private run: Run = realRun, + private fetchImpl: Fetch = fetch as unknown as Fetch, + ) {} + + private async must(argv: string[], opts?: { stdin?: string; timeoutMs?: number }): Promise { + const r = await this.run(argv, opts); + if (r.code !== 0) { + const detail = (r.stderr || r.stdout).trim().split("\n").slice(-3).join(" ").slice(0, 400); + throw new OpError(502, `${argv[0]} ${argv[1] ?? ""} failed (exit ${r.code}): ${detail}`); + } + return r.stdout; + } + + private async gh(args: string[], body?: unknown): Promise { + const argv = [this.cfg.fleetBin, "gh", "api", ...args]; + const out = await this.must( + body === undefined ? argv : [...argv, "--input", "-"], + body === undefined ? undefined : { stdin: JSON.stringify(body) }, + ); + return out.trim() === "" ? null : JSON.parse(out); + } + + // ---- queue ----------------------------------------------------------- + + private async sql(statement: string, args: (string | number)[]): Promise[]> { + if (!/^\s*select\b/i.test(statement)) throw new Error("the console only reads the queue store"); + const body = { + requests: [ + { + type: "execute", + stmt: { + sql: statement, + args: args.map((a) => + typeof a === "number" ? { type: "integer", value: String(a) } : { type: "text", value: a }, + ), + }, + }, + { type: "close" }, + ], + }; + const ask = async () => { + if (this.queueToken === null) { + this.queueToken = (await this.must([this.cfg.fleetBin, "secrets", "get", this.cfg.queueTokenName])).trim(); + } + return this.fetchImpl(`${this.cfg.queueDbUrl}/v2/pipeline`, { + method: "POST", + headers: { Authorization: `Bearer ${this.queueToken}`, "Content-Type": "application/json" }, + body: JSON.stringify(body), + }); + }; + let res = await ask(); + if (res.status === 401 || res.status === 403) { + // The token was rotated: fetch it again, once. + this.queueToken = null; + res = await ask(); + } + if (!res.ok) throw new OpError(502, `queue store answered http ${res.status}`); + const first = ( + (await res.json()) as { + results?: { + type?: string; + response?: { result?: { cols: { name: string }[]; rows: { value?: string | number | null }[][] } }; + }[]; + } + ).results?.[0]; + const result = first?.type === "ok" ? first.response?.result : undefined; + if (!result) throw new OpError(502, "queue store refused the query"); + return result.rows.map((row) => Object.fromEntries(result.cols.map((c, i) => [c.name, row[i]?.value ?? null]))); + } + + async queueCounts(): Promise> { + const rows = await this.sql( + "SELECT status, count(*) AS n FROM tasks WHERE queue = ? AND status NOT IN ('done','cancelled','failed') GROUP BY status", + [this.cfg.queue], + ); + return Object.fromEntries(rows.map((r) => [String(r.status), Number(r.n)])); + } + + async queueList(status: unknown, search: unknown, limit: unknown) { + if (!QUEUE_STATUSES.includes(status as (typeof QUEUE_STATUSES)[number])) + throw new OpError(400, `status: one of ${QUEUE_STATUSES.join(", ")}`); + const n = limit === undefined || limit === null || limit === "" ? 50 : id(limit, "limit"); + const q = typeof search === "string" ? search.trim().slice(0, 100) : ""; + const like = `%${q.replace(/[\\%_]/g, "\\$&")}%`; + return this.sql( + "SELECT id, status, priority, title, dedupe_key, substr(updated_at,1,16) AS updated, substr(coalesce(json_extract(progress,'$.reason'), json_extract(progress,'$.blocker'), ready_condition, ''),1,300) AS why FROM tasks WHERE queue = ? AND status = ? AND title LIKE ? ESCAPE '\\' ORDER BY (priority IS NULL), priority ASC, created_at ASC, id ASC LIMIT ?", + [this.cfg.queue, status as string, like, Math.min(n, 200)], + ); + } + + async queueAct(action: unknown, task: unknown, reason: unknown) { + if (action !== "unblock" && action !== "cancel") throw new OpError(400, "action: unblock or cancel"); + const taskId = id(task, "task"); + const why = text(reason, "reason", 500); + await this.must([this.cfg.fleetBin, "queue", action, String(taskId), "--worker", "pm-console", "--reason", why]); + return { task: taskId, action }; + } + + // ---- priorities and ideas --------------------------------------------- + + async priorities() { + const q = `repo:${this.cfg.repo} is:issue is:open label:${RANKS.map((r) => `"${r}"`).join(",")}`; + type Item = { + number: number; + title: string; + html_url: string; + updated_at: string; + comments: number; + labels: { name: string }[]; + }; + const items: Item[] = []; + let truncated = false; + // Search order is not rank order, so every page is read before sorting. + for (let page = 1; ; page++) { + const found = (await this.gh([ + "-X", + "GET", + "search/issues", + "-f", + `q=${q}`, + "-f", + "per_page=100", + "-f", + `page=${page}`, + ])) as { items: Item[] }; + items.push(...found.items); + if (found.items.length < 100) break; + if (page === PRIORITY_PAGES) { + truncated = true; + break; + } + } + const issues = items + .map((i) => { + const labels = i.labels.map((l) => l.name); + const rank = RANKS.findIndex((r) => labels.includes(r)); + return { + number: i.number, + title: i.title, + url: i.html_url, + updated: i.updated_at.slice(0, 16), + comments: i.comments, + labels, + rank: RANKS[rank] ?? "none", + order: rank < 0 ? RANKS.length : rank, + }; + }) + .sort((a, b) => a.order - b.order || a.number - b.number); + return { issues, truncated }; + } + + async setRank(issue: unknown, rank: unknown) { + const n = id(issue, "issue"); + if (rank !== "none" && !RANKS.includes(rank as (typeof RANKS)[number])) { + throw new OpError(400, `rank: one of ${RANKS.join(", ")}, none`); + } + const current = ( + (await this.gh([`repos/${this.cfg.repo}/issues/${n}`])) as { labels: { name: string }[] } + ).labels.map((l) => l.name); + // Add first: if a later call fails the issue keeps a rank, and stays + // on the list it would otherwise vanish from. + if (rank !== "none" && !current.includes(rank as string)) { + await this.gh(["-X", "POST", `repos/${this.cfg.repo}/issues/${n}/labels`], { labels: [rank] }); + } + for (const label of RANKS) { + if (label !== rank && current.includes(label)) { + await this.gh(["-X", "DELETE", `repos/${this.cfg.repo}/issues/${n}/labels/${encodeURIComponent(label)}`]); + } + } + return { issue: n, rank }; + } + + async comment(issue: unknown, body: unknown) { + const n = id(issue, "issue"); + const made = (await this.gh(["-X", "POST", `repos/${this.cfg.repo}/issues/${n}/comments`], { + body: text(body, "comment", 20_000), + })) as { html_url: string }; + return { issue: n, url: made.html_url }; + } + + /** + * File an idea as an issue and enqueue its triage task in the same + * pass (doc/agents/one-queue-claiming-work.md): an issue with no queue + * task is invisible to every worker. If the enqueue fails the issue + * still exists, the result says it is not queued, and the coverage + * reconciliation picks it up. + */ + async fileIdea(title: unknown, body: unknown, rank: unknown) { + if (rank !== "none" && !RANKS.includes(rank as (typeof RANKS)[number])) { + throw new OpError(400, `rank: one of ${RANKS.join(", ")}, none`); + } + const made = (await this.gh(["-X", "POST", `repos/${this.cfg.repo}/issues`], { + title: text(title, "title", 200), + body: typeof body === "string" ? body.slice(0, 60_000) : "", + labels: rank === "none" ? [] : [rank], + })) as { number: number; html_url: string; title: string }; + const packet = triagePacket( + this.cfg.repo, + this.cfg.queue, + made.number, + made.title, + rank as Rank, + new Date().toISOString(), + ); + // `fleet queue enqueue` reads a packet file, not stdin. + const dir = mkdtempSync(join(tmpdir(), "pm-console-")); + const file = join(dir, "packet.json"); + let queued: RunResult; + try { + writeFileSync(file, JSON.stringify(packet), { mode: 0o600 }); + queued = await this.run([this.cfg.fleetBin, "queue", "enqueue", file, "--queue", this.cfg.queue]); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + return { + issue: made.number, + url: made.html_url, + queued: queued.code === 0, + ...(queued.code === 0 + ? {} + : { note: `filed, not queued: ${(queued.stderr || queued.stdout).trim().split("\n").pop()?.slice(0, 200)}` }), + }; + } + + // ---- agents ------------------------------------------------------------ + + async agents() { + return (JSON.parse(await this.must([this.cfg.fleetBin, "bridge", "agents"])) as { agents: unknown[] }).agents; + } + + async messages(limit: unknown) { + const n = limit === undefined || limit === null || limit === "" ? 30 : Math.min(id(limit, "limit"), 200); + return ( + JSON.parse(await this.must([this.cfg.fleetBin, "bridge", "log", "--limit", String(n), "--order", "desc"])) as { + messages: unknown[]; + } + ).messages; + } + + /** Send a message or a command to agents, groups, or everyone. */ + async send(to: unknown, body: unknown, command: unknown) { + if (!Array.isArray(to) || to.length === 0 || to.length > 50) throw new OpError(400, "to: one to fifty targets"); + const targets = to.map((t) => { + if (typeof t !== "string" || !/^(all|(agent:|group:)?[A-Za-z0-9][A-Za-z0-9._-]{0,63})$/.test(t)) + throw new OpError(400, `to: not a target: ${JSON.stringify(t).slice(0, 80)}`); + return t; + }); + const argv = [this.cfg.fleetBin, "bridge", "send", "--to", targets.join(",")]; + if (command === true) argv.push("--command"); + // The text goes on stdin, so nothing in it is read as an option. + argv.push("-"); + await this.must(argv, { stdin: text(body, "text", 16_000) }); + return { to: targets, command: command === true }; + } + + // ---- services ---------------------------------------------------------- + + async services(): Promise { + const select = ["--plain", "--no-legend", "--type=service", "--type=timer", ...this.cfg.unitPatterns]; + const [loaded, files] = await Promise.all([ + this.must(["systemctl", "--user", "list-units", "--all", ...select]), + // A stopped unit nothing refers to leaves memory and drops off + // list-units; without this it could never be started from here. + this.run(["systemctl", "--user", "list-unit-files", ...select]), + ]); + const units = parseUnits(loaded); + const seen = new Set(units.map((u) => u.unit)); + for (const f of files.code === 0 ? parseUnitFiles(files.stdout) : []) { + if (!seen.has(f.unit)) + units.push({ + unit: f.unit, + load: "not-loaded", + active: "inactive", + sub: "dead", + description: `not loaded (${f.state})`, + }); + } + return units.filter((u) => manageable(u.unit, this.cfg.unitPatterns)).sort((a, b) => a.unit.localeCompare(b.unit)); + } + + async serviceAct(unit: unknown, action: unknown) { + if (typeof unit !== "string" || !manageable(unit, this.cfg.unitPatterns)) + throw new OpError(404, "not a unit this console manages"); + if (!UNIT_ACTIONS.includes(action as UnitAction)) + throw new OpError(400, `action: one of ${UNIT_ACTIONS.join(", ")}`); + if (action === "stop" && this.cfg.protectedUnits.includes(unit)) { + throw new OpError(409, `${unit} carries this interface: it can be restarted from here, not stopped`); + } + await this.must(["systemctl", "--user", action as string, unit], { timeoutMs: 60_000 }); + return { unit, action }; + } + + async serviceLogs(unit: unknown, lines: unknown) { + if (typeof unit !== "string" || !manageable(unit, this.cfg.unitPatterns)) + throw new OpError(404, "not a unit this console manages"); + const n = lines === undefined || lines === null || lines === "" ? 80 : Math.min(id(lines, "lines"), 400); + return { + unit, + log: await this.must(["journalctl", "--user", "-u", unit, "-n", String(n), "--no-pager", "-o", "short-iso"]), + }; + } + + // ---- pull requests ----------------------------------------------------- + + async prs() { + const list = (await this.gh([`repos/${this.cfg.repo}/pulls?state=open&per_page=60`])) as { + number: number; + title: string; + draft: boolean; + html_url: string; + created_at: string; + user: { login: string }; + head: { ref: string }; + }[]; + return list.map((p) => ({ + number: p.number, + title: p.title, + draft: p.draft, + url: p.html_url, + created: p.created_at.slice(0, 16), + author: p.user.login, + branch: p.head.ref, + })); + } + + async pr(number: unknown) { + const n = id(number, "pull request"); + const p = (await this.gh([`repos/${this.cfg.repo}/pulls/${n}`])) as Record; + return { + number: n, + title: p.title, + state: p.state, + draft: p.draft, + merged: p.merged, + mergeable: p.mergeable, + mergeable_state: p.mergeable_state, + additions: p.additions, + deletions: p.deletions, + changed_files: p.changed_files, + review_comments: p.review_comments, + comments: p.comments, + url: p.html_url, + body: typeof p.body === "string" ? p.body.slice(0, 4000) : "", + }; + } + + async mergePr(number: unknown) { + const n = id(number, "pull request"); + const done = (await this.gh([ + "-X", + "PUT", + `repos/${this.cfg.repo}/pulls/${n}/merge`, + "-f", + "merge_method=merge", + ])) as { merged: boolean; sha: string }; + return { number: n, merged: done.merged, sha: done.sha }; + } + + // ---- one screen -------------------------------------------------------- + + async overview() { + const part = async (p: Promise): Promise => + p.catch((e: Error) => ({ error: e.message })); + const [queue, units, prs, agents] = await Promise.all([ + part(this.queueCounts()), + part(this.services()), + part(this.prs()), + part(this.agents()), + ]); + return { + queue, + services: Array.isArray(units) + ? { + total: units.length, + failed: units.filter((u) => u.active === "failed").map((u) => u.unit), + inactive: units.filter((u) => u.unit.endsWith(".service") && u.active === "inactive").length, + } + : units, + prs: Array.isArray(prs) ? { open: prs.length, ready: prs.filter((p) => !p.draft).length } : prs, + agents: Array.isArray(agents) ? { registered: agents.length } : agents, + }; + } +} diff --git a/pm-stack/console/src/server.ts b/pm-stack/console/src/server.ts new file mode 100644 index 0000000000..7e838cc240 --- /dev/null +++ b/pm-stack/console/src/server.ts @@ -0,0 +1,258 @@ +// 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. +import { mkdirSync, readFileSync } from "node:fs"; +import { appendFile } from "node:fs/promises"; +import { dirname, join } from "node:path"; +import { AuthError, type Identity, identify } from "./auth.ts"; +import { type Config, readConfig } from "./config.ts"; +import { OpError, Ops } from "./ops.ts"; + +const BASE = "/console"; +const PUBLIC_DIR = join(import.meta.dir, "..", "public"); +const STATIC = new Map([ + ["app.js", "text/javascript; charset=utf-8"], + ["app.css", "text/css; charset=utf-8"], + ["icon.svg", "image/svg+xml"], +]); +const SECURITY = { + "Content-Security-Policy": + "default-src 'self'; img-src 'self' data:; frame-ancestors 'none'; base-uri 'none'; form-action 'self'", + "X-Content-Type-Options": "nosniff", + "Referrer-Policy": "same-origin", +}; +/** 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. */ +const IDLE_TIMEOUT_SECONDS = 120; + +function json(body: unknown, status = 200): Response { + return new Response(JSON.stringify(body), { + status, + headers: { "Content-Type": "application/json; charset=utf-8", "Cache-Control": "no-store", ...SECURITY }, + }); +} + +// The page's four files, read once: nothing on the request path touches +// the disk synchronously after the first hit. +const fileCache = new Map(); +function file(name: string, type: string): Response { + let bytes = fileCache.get(name); + if (!bytes) { + bytes = readFileSync(join(PUBLIC_DIR, name)); + fileCache.set(name, bytes); + } + return new Response(bytes, { headers: { "Content-Type": type, "Cache-Control": "no-cache", ...SECURITY } }); +} + +/** The Digital Asset Links statement that lets the Android app open + * this origin full screen. Public by design: Android fetches it. */ +export function assetLinks(cfg: Pick): unknown[] { + if (cfg.androidFingerprints.length === 0) return []; + return [ + { + relation: ["delegate_permission/common.handle_all_urls"], + target: { + namespace: "android_app", + package_name: cfg.androidPackage, + sha256_cert_fingerprints: cfg.androidFingerprints, + }, + }, + ]; +} + +export interface Deps { + cfg: Config; + ops: Ops; + /** `peer` is the connection's remote address as the server saw it. */ + identify: (req: Request, peer: string | null) => Promise; + audit: (entry: Record) => Promise; +} + +/** A state-changing request must be one this page made: a custom header + * a cross-site form cannot set, and an Origin that is this host. */ +function sameSiteWrite(req: Request): boolean { + if (req.headers.get("x-pm-console") !== "1") return false; + const origin = req.headers.get("origin"); + if (origin === null) return true; + try { + return new URL(origin).host === (req.headers.get("host") ?? ""); + } catch { + return false; + } +} + +export async function handle(req: Request, deps: Deps, peer: string | null = null): Promise { + const url = new URL(req.url); + const path = url.pathname; + const method = req.method; + + // 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); + + let who: Identity; + try { + who = await deps.identify(req, peer); + } catch (error) { + if (error instanceof AuthError) return json({ error: error.message }, error.status); + throw error; + } + + const rest = path.slice(BASE.length).replace(/^\/+/, ""); + if (method === "GET" && rest === "") { + if (path === BASE) return Response.redirect(`${BASE}/`, 308); + return file("index.html", "text/html; charset=utf-8"); + } + const type = method === "GET" ? STATIC.get(rest) : undefined; + if (type !== undefined) return file(rest, type); + if (!rest.startsWith("api/")) return json({ error: "not found" }, 404); + + let seg: string[]; + try { + seg = rest.slice(4).split("/").map(decodeURIComponent); + } catch { + return json({ error: "bad path" }, 400); + } + const ops = deps.ops; + const query = url.searchParams; + try { + if (method === "GET") { + if (seg.length === 1) { + switch (seg[0]) { + case "me": + return json({ ...who, repo: deps.cfg.repo, queue: deps.cfg.queue }); + case "overview": + return json(await ops.overview()); + case "queue": + return json({ + counts: await ops.queueCounts(), + tasks: await ops.queueList(query.get("status") ?? "queued", query.get("q"), query.get("limit")), + }); + case "priorities": + return json(await ops.priorities()); + case "agents": + return json(await ops.agents()); + case "messages": + return json(await ops.messages(query.get("limit"))); + case "services": + return json(await ops.services()); + case "prs": + return json(await ops.prs()); + } + } + if (seg.length === 2 && seg[0] === "prs") return json(await ops.pr(seg[1])); + if (seg.length === 3 && seg[0] === "services" && seg[2] === "logs") { + return json(await ops.serviceLogs(seg[1], query.get("lines"))); + } + return json({ error: "not found" }, 404); + } + + if (method !== "POST") return json({ error: "method not allowed" }, 405); + if (!sameSiteWrite(req)) return json({ error: "this request did not come from the console" }, 403); + let body: Record = {}; + try { + const parsed = await req.json(); + if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error("not an object"); + body = parsed as Record; + } catch { + return json({ error: "body: expected a JSON object" }, 400); + } + + // Two audit records per action. The first is written before anything + // runs and must succeed: an action that cannot be recorded is not + // taken, and one that kills this process (restarting the console) is + // still on record. The second records the outcome; if it cannot be + // written the action's own result still goes back to the caller, so a + // finished merge is never reported as failed and tried again. + const act = async ( + name: string, + args: Record, + work: () => Promise, + ): Promise => { + const base = { + at: new Date().toISOString(), + who: who.email ?? who.certName ?? who.sub ?? who.via, + via: who.via, + action: name, + args, + }; + try { + await deps.audit({ ...base, phase: "start" }); + } catch (error) { + console.error(`pm-console: audit: ${(error as Error).message}`); + return json({ error: "the action could not be recorded, so it was not taken" }, 502); + } + const done = (entry: Record) => + deps + .audit({ ...base, phase: "done", ...entry }) + .catch((error) => console.error(`pm-console: audit: ${(error as Error).message}`)); + try { + const result = await work(); + await done({ ok: true }); + return json({ ok: true, result }); + } catch (error) { + await done({ ok: false, error: (error as Error).message }); + throw error; + } + }; + + if (seg.length === 3 && seg[0] === "queue") { + return await act(`queue.${seg[2]}`, { task: seg[1], reason: body.reason }, () => + ops.queueAct(seg[2], seg[1], body.reason), + ); + } + if (seg.length === 3 && seg[0] === "priorities" && seg[2] === "rank") { + return await act("priority.rank", { issue: seg[1], rank: body.rank }, () => ops.setRank(seg[1], body.rank)); + } + if (seg.length === 3 && seg[0] === "issues" && seg[2] === "comment") { + return await act("issue.comment", { issue: seg[1] }, () => ops.comment(seg[1], body.body)); + } + if (seg.length === 1 && seg[0] === "ideas") { + return await act("idea.file", { title: body.title, rank: body.rank }, () => + ops.fileIdea(body.title, body.body, body.rank ?? "none"), + ); + } + if (seg.length === 1 && seg[0] === "messages") { + return await act("message.send", { to: body.to, command: body.command === true }, () => + ops.send(body.to, body.text, body.command), + ); + } + if (seg.length === 3 && seg[0] === "services") { + return await act(`service.${seg[2]}`, { unit: seg[1] }, () => ops.serviceAct(seg[1], seg[2])); + } + if (seg.length === 3 && seg[0] === "prs" && seg[2] === "merge") { + return await act("pr.merge", { pr: seg[1] }, () => ops.mergePr(seg[1])); + } + return json({ error: "not found" }, 404); + } catch (error) { + if (error instanceof OpError) return json({ error: error.message }, error.status); + console.error(`pm-console: ${method} ${path}: ${(error as Error).stack ?? error}`); + return json({ error: "the console could not complete that" }, 502); + } +} + +if (import.meta.main) { + const cfg = readConfig(); + const ops = new Ops(cfg); + mkdirSync(dirname(cfg.auditFile), { recursive: true, mode: 0o700 }); + const deps: Deps = { + cfg, + ops, + identify: (req, peer) => identify(req, cfg, { peer }), + audit: (entry) => appendFile(cfg.auditFile, `${JSON.stringify(entry)}\n`, { mode: 0o600 }), + }; + const server = Bun.serve({ + hostname: cfg.bind, + port: cfg.port, + idleTimeout: IDLE_TIMEOUT_SECONDS, + 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)"}`, + ); +} diff --git a/pm-stack/console/test/console.test.ts b/pm-stack/console/test/console.test.ts new file mode 100644 index 0000000000..9bc6401608 --- /dev/null +++ b/pm-stack/console/test/console.test.ts @@ -0,0 +1,1011 @@ +// pm-console: who gets in, what each operation runs, and what the HTTP +// surface refuses. +// +// Oracles: tokens are signed here with keys generated here, so "valid" +// is defined by the test and not by the code under test; every +// operation runs against a recording runner, so what would reach the +// machine is compared as an exact argument vector; and seeded generators +// drive the properties (any changed token byte is refused; no generated +// 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. +import { beforeEach, describe, expect, test } from "bun:test"; +import { readFileSync } from "node:fs"; +import { + AuthError, + authorize, + cameThroughEdge, + clearJwksCache, + identify, + isLoopbackAddress, + verifyJwt, +} from "../src/auth.ts"; +import { type Config, ConfigError, type Issuer, readConfig } from "../src/config.ts"; +import { manageable, OpError, Ops, parseUnitFiles, parseUnits, type Run, triagePacket } from "../src/ops.ts"; +import { assetLinks, type Deps, handle } from "../src/server.ts"; + +const NOW = 1_800_000_000_000; +const ACCESS: Issuer = { + name: "cloudflare-access", + issuer: "https://team.cloudflareaccess.com", + jwksUri: "https://team.cloudflareaccess.com/cdn-cgi/access/certs", + audience: "aud-tag", + source: "access", +}; +const CENTRAL: Issuer = { + name: "central", + issuer: "https://id.example", + jwksUri: "https://id.example/jwks", + audience: "pm-console", + source: "bearer", +}; +const OWNER = "drewrypope@gmail.com"; + +function b64u(bytes: Uint8Array | string): string { + const raw = typeof bytes === "string" ? new TextEncoder().encode(bytes) : bytes; + return btoa(String.fromCharCode(...raw)) + .replace(/\+/g, "-") + .replace(/\//g, "_") + .replace(/=+$/, ""); +} + +interface Signer { + jwk: JsonWebKey & { kid: string }; + sign(claims: Record, header?: Record): Promise; +} + +async function signer(alg: "RS256" | "ES256", kid: string): Promise { + const params = + alg === "RS256" + ? { name: "RSASSA-PKCS1-v1_5", modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 1]), hash: "SHA-256" } + : { name: "ECDSA", namedCurve: "P-256" }; + const pair = (await crypto.subtle.generateKey(params, true, ["sign", "verify"])) as CryptoKeyPair; + const jwk = { ...(await crypto.subtle.exportKey("jwk", pair.publicKey)), kid }; + return { + jwk, + async sign(claims, header = {}) { + const head = b64u(JSON.stringify({ alg, kid, typ: "JWT", ...header })); + const body = b64u(JSON.stringify(claims)); + const sig = await crypto.subtle.sign( + alg === "RS256" ? "RSASSA-PKCS1-v1_5" : { name: "ECDSA", hash: "SHA-256" }, + pair.privateKey, + new TextEncoder().encode(`${head}.${body}`), + ); + return `${head}.${body}.${b64u(new Uint8Array(sig))}`; + }, + }; +} + +function keyServer(sets: Record, gate?: Promise) { + const calls: string[] = []; + const signals: (AbortSignal | undefined)[] = []; + const fetchImpl = async (url: string, init?: { signal?: AbortSignal }) => { + calls.push(url); + signals.push(init?.signal); + await gate; + return { ok: url in sets, status: url in sets ? 200 : 404, json: async () => ({ keys: sets[url] ?? [] }) }; + }; + return { fetchImpl, calls, signals }; +} + +const good = (issuer: Issuer, extra: Record = {}) => ({ + iss: issuer.issuer, + aud: [issuer.audience], + exp: NOW / 1000 + 600, + iat: NOW / 1000 - 5, + sub: "user-1", + email: OWNER, + ...extra, +}); + +function rng(seed: number) { + let s = seed >>> 0; + return () => (s = (Math.imul(s, 1664525) + 1013904223) >>> 0) / 2 ** 32; +} + +let rsa: Signer; +let ec: Signer; +let other: Signer; +beforeEach(async () => { + clearJwksCache(); + rsa ??= await signer("RS256", "k1"); + ec ??= await signer("ES256", "k2"); + other ??= await signer("RS256", "k1"); // same key id, different key +}); + +describe("token verification", () => { + test("accepts a token its issuer signed, RS256 and ES256", async () => { + const keys = keyServer({ [ACCESS.jwksUri]: [rsa.jwk], [CENTRAL.jwksUri]: [ec.jwk] }); + expect((await verifyJwt(await rsa.sign(good(ACCESS)), ACCESS, keys.fetchImpl, NOW)).email).toBe(OWNER); + expect( + (await verifyJwt(await ec.sign(good(CENTRAL, { aud: CENTRAL.audience })), CENTRAL, keys.fetchImpl, NOW)).sub, + ).toBe("user-1"); + }); + + test("refuses each way a token can be wrong", async () => { + const keys = keyServer({ [ACCESS.jwksUri]: [rsa.jwk] }); + const refuse = async (token: string, why: RegExp) => { + await expect(verifyJwt(token, ACCESS, keys.fetchImpl, NOW)).rejects.toThrow(why); + }; + await refuse(await rsa.sign(good(ACCESS, { iss: "https://evil.cloudflareaccess.com" })), /issuer/); + await refuse(await rsa.sign(good(ACCESS, { aud: ["another-app"] })), /audience/); + await refuse(await rsa.sign(good(ACCESS, { exp: NOW / 1000 - 120 })), /expired/); + await refuse(await rsa.sign({ ...good(ACCESS), exp: undefined }), /expired/); + await refuse(await rsa.sign(good(ACCESS, { nbf: NOW / 1000 + 600 })), /not yet valid/); + await refuse(await rsa.sign(good(ACCESS, { iat: NOW / 1000 + 600 })), /future/); + await refuse(await other.sign(good(ACCESS)), /signature/); + await refuse(await rsa.sign(good(ACCESS), { kid: "unknown" }), /no key/); + await refuse(await rsa.sign(good(ACCESS), { alg: "none" }), /algorithm/); + await refuse(await rsa.sign(good(ACCESS), { alg: "HS256" }), /algorithm/); + await refuse("a.b", /malformed/); + await refuse("!!.??.**", /malformed/); + // A token asking for ES256 against an RSA key of the same id. + await refuse(await rsa.sign(good(ACCESS), { alg: "ES256" }), /no key/); + }); + + test("property: changing any one character of a valid token refuses it", async () => { + const keys = keyServer({ [ACCESS.jwksUri]: [rsa.jwk] }); + const token = await rsa.sign(good(ACCESS)); + const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; + const next = rng(12268); + for (let i = 0; i < 300; i++) { + const at = Math.floor(next() * token.length); + if (token[at] === ".") continue; + let c = alphabet[Math.floor(next() * alphabet.length)]; + if (c === token[at]) c = c === "A" ? "B" : "A"; + const changed = token.slice(0, at) + c + token.slice(at + 1); + // base64url's last character of a segment can carry unused bits: + // a change there may decode to the same bytes, which is the same token. + const same = changed.split(".").every((part, n) => atob(pad(part)) === atob(pad(token.split(".")[n]))); + if (same) continue; + await expect(verifyJwt(changed, ACCESS, keys.fetchImpl, NOW)).rejects.toThrow(); + } + function pad(s: string) { + return s.replace(/-/g, "+").replace(/_/g, "/") + "=".repeat((4 - (s.length % 4)) % 4); + } + }); + + test("caches the key set, and fetches a rotated key at most once per cooldown", async () => { + const rotated = await signer("RS256", "k9"); + const sets: Record = { [ACCESS.jwksUri]: [rsa.jwk] }; + const keys = keyServer(sets); + await verifyJwt(await rsa.sign(good(ACCESS)), ACCESS, keys.fetchImpl, NOW); + await verifyJwt(await rsa.sign(good(ACCESS)), ACCESS, keys.fetchImpl, NOW + 1000); + expect(keys.calls.length).toBe(1); + expect(keys.signals[0]).toBeInstanceOf(AbortSignal); // the fetch has a deadline + sets[ACCESS.jwksUri] = [rsa.jwk, rotated.jwk]; + // Tokens naming an unknown key cost nothing while the last fetch is + // fresh: anyone can send them, so they must not each reach the issuer. + const unknown = await rotated.sign(good(ACCESS)); + for (let i = 0; i < 20; i++) { + await expect(verifyJwt(unknown, ACCESS, keys.fetchImpl, NOW + 2000 + i)).rejects.toThrow(/no key matches/); + } + expect(keys.calls.length).toBe(1); + // Once the cooldown has passed, the rotated key is picked up. + await verifyJwt(unknown, ACCESS, keys.fetchImpl, NOW + 31_000); + expect(keys.calls.length).toBe(2); + await verifyJwt(unknown, ACCESS, keys.fetchImpl, NOW + 32_000); + expect(keys.calls.length).toBe(2); + }); + + test("requests arriving together share one key fetch", async () => { + let open = () => {}; + const gate = new Promise((resolve) => { + open = resolve; + }); + const keys = keyServer({ [ACCESS.jwksUri]: [rsa.jwk] }, gate); + const token = await rsa.sign(good(ACCESS)); + const all = Promise.all(Array.from({ length: 25 }, () => verifyJwt(token, ACCESS, keys.fetchImpl, NOW))); + await new Promise((resolve) => setTimeout(resolve, 20)); // let every verification reach the key lookup + open(); + expect((await all).length).toBe(25); + expect(keys.calls.length).toBe(1); + // A failed fetch is not remembered: the next request tries again. + clearJwksCache(); + const down = keyServer({}); + await expect(verifyJwt(token, ACCESS, down.fetchImpl, NOW)).rejects.toThrow(/key set/); + await verifyJwt(token, ACCESS, keys.fetchImpl, NOW); + }); +}); + +describe("who is the owner", () => { + const cfg = { owners: [OWNER], certNames: ["laptop.devices.central"], issuers: [ACCESS, CENTRAL] }; + const edge = (headers: Record = {}) => + new Request("https://pm.security.cab/console/api/me", { + headers: { host: "pm.security.cab", "cf-ray": "1", ...headers }, + }); + // The tunnel connects from this machine, so an edge request's peer is loopback too. + const at = (keys: { fetchImpl: ReturnType["fetchImpl"] }) => ({ + fetchImpl: keys.fetchImpl, + now: NOW, + peer: "127.0.0.1", + }); + + test("the owner's verified address gets in through either issuer", async () => { + const keys = keyServer({ [ACCESS.jwksUri]: [rsa.jwk], [CENTRAL.jwksUri]: [ec.jwk] }); + expect(await identify(edge({ "cf-access-jwt-assertion": await rsa.sign(good(ACCESS)) }), cfg, at(keys))).toEqual({ + via: "cloudflare-access", + email: OWNER, + sub: "user-1", + }); + expect( + await identify( + edge({ cookie: `x=1; CF_Authorization=${await rsa.sign(good(ACCESS, { email: "DrewryPope@Gmail.com" }))}` }), + cfg, + at(keys), + ), + ).toMatchObject({ email: OWNER }); + expect( + await identify(edge({ authorization: `Bearer ${await ec.sign(good(CENTRAL))}` }), cfg, at(keys)), + ).toMatchObject({ via: "central", email: OWNER }); + }); + + test("anyone else is refused, by status", async () => { + const keys = keyServer({ [ACCESS.jwksUri]: [rsa.jwk], [CENTRAL.jwksUri]: [ec.jwk] }); + const status = async (req: Request) => + identify(req, cfg, at(keys)).then( + () => 200, + (e: AuthError) => e.status, + ); + expect(await status(edge())).toBe(401); + expect(await status(edge({ "cf-access-jwt-assertion": "garbage" }))).toBe(401); + expect(await status(edge({ "cf-access-jwt-assertion": await other.sign(good(ACCESS)) }))).toBe(401); + expect( + await status(edge({ "cf-access-jwt-assertion": await rsa.sign(good(ACCESS, { email: "someone@gmail.com" })) })), + ).toBe(403); + expect( + await status(edge({ "cf-access-jwt-assertion": await rsa.sign(good(ACCESS, { email_verified: false })) })), + ).toBe(403); + // A token for one issuer is not accepted in another issuer's place. + expect(await status(edge({ authorization: `Bearer ${await rsa.sign(good(ACCESS))}` }))).toBe(401); + // With no owners configured, a valid token still opens nothing. + const closed = { ...cfg, owners: [], certNames: [] }; + await expect( + identify(edge({ "cf-access-jwt-assertion": await rsa.sign(good(ACCESS)) }), closed, at(keys)), + ).rejects.toThrow(AuthError); + }); + + test("a client certificate the edge checked is the owner by its name", () => { + expect(authorize({ common_name: "laptop.devices.central", sub: "" }, "cloudflare-access", cfg)).toEqual({ + via: "cloudflare-access", + certName: "laptop.devices.central", + sub: "", + }); + expect(() => authorize({ common_name: "other.devices.central" }, "cloudflare-access", cfg)).toThrow(AuthError); + }); + + test("only a connection from this machine that crossed no proxy is local", async () => { + const local = (headers: Record) => new Request("http://127.0.0.1:4872/console/api/me", { headers }); + const here = { peer: "127.0.0.1" }; + for (const peer of ["127.0.0.1", "127.8.9.10", "::1", "::ffff:127.0.0.1"]) { + expect(await identify(local({ host: "127.0.0.1:4872" }), cfg, { peer })).toEqual({ + via: "loopback", + email: "local", + }); + } + expect(cameThroughEdge(local({ host: "localhost:4872" }))).toBe(false); + // The Host header is the caller's to write. A connection from another + // machine that names loopback in it is not local, whatever it says. + for (const peer of ["100.99.113.103", "203.0.113.9", "::ffff:203.0.113.9", "fe80::1", "", null, undefined]) { + await expect(identify(local({ host: "127.0.0.1:4872" }), cfg, { peer })).rejects.toThrow(/sign-in required/); + } + await expect(identify(local({ host: "127.0.0.1:4872" }), cfg)).rejects.toThrow(/sign-in required/); + for (const address of [ + "127.0.0.1.evil.example", + "1127.0.0.1", + "127.0.0.1:80", + "localhost", + "0.0.0.0", + "::", + "::ffff:", + ]) { + expect(isLoopbackAddress(address)).toBe(false); + } + for (const headers of [ + { host: "pm.security.cab" }, + { host: "evil.example:4872" }, // a rebound name resolving to loopback + { host: "127.0.0.1:4872", "cf-connecting-ip": "203.0.113.9" }, + { host: "127.0.0.1:4872", "x-forwarded-for": "203.0.113.9" }, + { host: "127.0.0.1:4872", "cdn-loop": "cloudflare" }, + ]) { + await expect(identify(local(headers), cfg, here)).rejects.toThrow(/sign-in required/); + } + }); +}); + +describe("configuration", () => { + test("defaults, the Access issuer and the issuers file", () => { + const file = JSON.stringify([ + { name: "central", issuer: "https://id.example", jwksUri: "https://id.example/jwks", audience: "pm-console" }, + ]); + const cfg = readConfig( + { + HOME: "/h", + PM_CONSOLE_OWNER_EMAILS: " DrewryPope@gmail.com ,", + PM_CONSOLE_ACCESS_TEAM_DOMAIN: "team.cloudflareaccess.com", + PM_CONSOLE_ACCESS_AUD: "aud-tag", + PM_CONSOLE_ISSUERS_FILE: "/x", + }, + () => file, + ); + expect(cfg.port).toBe(4872); + expect(cfg.bind).toBe("127.0.0.1"); + expect(cfg.owners).toEqual([OWNER]); + expect(cfg.issuers).toEqual([ACCESS, CENTRAL]); + expect(cfg.auditFile).toBe("/h/.local/state/pm-console/audit.jsonl"); + }); + + test("a bad value stops the boot and names the variable", () => { + for (const [env, why] of [ + [{ PM_CONSOLE_PORT: "80abc" }, /PM_CONSOLE_PORT/], + [{ PM_CONSOLE_PORT: "0" }, /PM_CONSOLE_PORT/], + [{ PM_CONSOLE_PORT: "70000" }, /PM_CONSOLE_PORT/], + [{ PM_CONSOLE_ACCESS_AUD: "x" }, /set together/], + [{ PM_CONSOLE_ACCESS_TEAM_DOMAIN: "evil.example", PM_CONSOLE_ACCESS_AUD: "x" }, /team domain/], + [{ PM_CONSOLE_ANDROID_SHA256: "AB:CD" }, /fingerprint/], + // A request with no token is trusted when it comes from this + // machine, so the listener must not be reachable from another. + [{ PM_CONSOLE_BIND: "0.0.0.0" }, /PM_CONSOLE_BIND/], + [{ PM_CONSOLE_BIND: "100.99.113.103" }, /PM_CONSOLE_BIND/], + [{ PM_CONSOLE_BIND: "::" }, /PM_CONSOLE_BIND/], + ] as const) { + expect(() => readConfig(env)).toThrow(why); + } + expect(() => + readConfig( + { PM_CONSOLE_ISSUERS_FILE: "/x" }, + () => '[{"name":"c","issuer":"http://id.example","jwksUri":"https://id.example/jwks","audience":"a"}]', + ), + ).toThrow(/https/); + expect(() => readConfig({ PM_CONSOLE_ISSUERS_FILE: "/x" }, () => "{}")).toThrow(ConfigError); + for (const bind of ["127.0.0.1", "::1", "localhost"]) { + expect(readConfig({ PM_CONSOLE_BIND: bind }).bind).toBe(bind); + } + }); +}); + +function recorder(answers: (argv: string[]) => string | { code: number; stderr: string } = () => "") { + const calls: { argv: string[]; stdin?: string }[] = []; + const run: Run = async (argv, opts) => { + calls.push({ argv, stdin: opts?.stdin }); + const a = answers(argv); + return typeof a === "string" ? { code: 0, stdout: a, stderr: "" } : { code: a.code, stdout: "", stderr: a.stderr }; + }; + return { run, calls }; +} + +const CFG: Config = readConfig({ + HOME: "/h", + PM_CONSOLE_OWNER_EMAILS: OWNER, + PM_CONSOLE_ANDROID_SHA256: Array(32).fill("AB").join(":"), +}); + +describe("operations", () => { + test("queue actions run the fleet verb with the reason as one argument", async () => { + const r = recorder(); + const ops = new Ops(CFG, r.run); + await ops.queueAct("unblock", "20306", "--force; rm -rf ~ it can proceed"); + expect(r.calls).toEqual([ + { + argv: [ + "fleet", + "queue", + "unblock", + "20306", + "--worker", + "pm-console", + "--reason", + "--force; rm -rf ~ it can proceed", + ], + stdin: undefined, + }, + ]); + for (const [action, task, reason] of [ + ["delete", "1", "x"], + ["unblock", "1; id", "x"], + ["unblock", "-1", "x"], + ["unblock", "0", "x"], + ["cancel", "5", " "], + ["cancel", "5", 7], + ]) { + await expect(ops.queueAct(action, task, reason)).rejects.toThrow(OpError); + } + expect(r.calls.length).toBe(1); + }); + + test("the queue is read with bound parameters and never written", async () => { + const r = recorder(() => "secret-token\n"); + const sent: { url: string; body: { requests: { stmt?: { sql: string; args: unknown[] } }[] }; auth: string }[] = []; + const ops = new Ops(CFG, r.run, async (url, init) => { + sent.push({ url, body: JSON.parse(init.body), auth: init.headers.Authorization }); + return { + ok: true, + status: 200, + json: async () => ({ + results: [ + { + type: "ok", + response: { + result: { cols: [{ name: "id" }, { name: "title" }], rows: [[{ value: "7" }, { value: "t" }]] }, + }, + }, + ], + }), + }; + }); + expect(await ops.queueList("blocked", "50%_off'; DROP TABLE tasks;--", "10")).toEqual([{ id: "7", title: "t" }]); + const stmt = sent[0].body.requests[0].stmt!; + expect(stmt.sql.startsWith("SELECT")).toBe(true); + expect(stmt.sql).not.toContain("DROP"); + expect(stmt.args).toEqual([ + { type: "text", value: "repo-health-code-pilot" }, + { type: "text", value: "blocked" }, + { type: "text", value: "%50\\%\\_off'; DROP TABLE tasks;--%" }, + { type: "integer", value: "10" }, + ]); + expect(sent[0].auth).toBe("Bearer secret-token"); + await ops.queueCounts(); + expect(r.calls.length).toBe(1); // the token is fetched once + await expect(ops.queueList("done", "", "")).rejects.toThrow(/status/); + }); + + test("a rotated queue token is fetched again, once", async () => { + let issued = 0; + const r = recorder(() => `token-${++issued}\n`); + const seen: string[] = []; + const answer = (status: number) => ({ + ok: status === 200, + status, + json: async () => ({ + results: [{ type: "ok", response: { result: { cols: [{ name: "status" }, { name: "n" }], rows: [] } } }], + }), + }); + let valid = "token-2"; + const ops = new Ops(CFG, r.run, async (_url, init) => { + seen.push(init.headers.Authorization); + return answer(init.headers.Authorization === `Bearer ${valid}` ? 200 : 401); + }); + await ops.queueCounts(); // token-1 is refused, token-2 works + expect(seen).toEqual(["Bearer token-1", "Bearer token-2"]); + await ops.queueCounts(); + expect(seen.length).toBe(3); + expect(issued).toBe(2); + // A store that keeps refusing gets one retry, not a loop. + valid = "none"; + await expect(ops.queueCounts()).rejects.toThrow(/http 401/); + expect(seen.length).toBe(5); + expect(issued).toBe(3); + }); + + test("a message's text travels on stdin and targets are checked", async () => { + const r = recorder(); + const ops = new Ops(CFG, r.run); + await ops.send(["group:opencode", "agent:conductor"], "--command do the thing\n$(reboot)", true); + expect(r.calls[0]).toEqual({ + argv: ["fleet", "bridge", "send", "--to", "group:opencode,agent:conductor", "--command", "-"], + stdin: "--command do the thing\n$(reboot)", + }); + await ops.send(["all"], "an idea", false); + expect(r.calls[1].argv).toEqual(["fleet", "bridge", "send", "--to", "all", "-"]); + for (const to of [[], ["--to"], ["a,b"], ["agent:"], [""], "all", ["x y"]]) { + await expect(ops.send(to, "text", false)).rejects.toThrow(OpError); + } + await expect(ops.send(["all"], "", false)).rejects.toThrow(/required/); + expect(r.calls.length).toBe(2); + }); + + test("ranking an issue adds the new rank before it removes the others", async () => { + const r = recorder((argv) => + argv.includes("repos/developing-today/code/issues/12279") + ? JSON.stringify({ labels: [{ name: "now" }, { name: "app/id" }, { name: "priority/high" }] }) + : "{}", + ); + const ops = new Ops(CFG, r.run); + await ops.setRank("12279", "next"); + expect(r.calls.map((c) => c.argv.slice(3))).toEqual([ + ["repos/developing-today/code/issues/12279"], + ["-X", "POST", "repos/developing-today/code/issues/12279/labels", "--input", "-"], + ["-X", "DELETE", "repos/developing-today/code/issues/12279/labels/now"], + ["-X", "DELETE", "repos/developing-today/code/issues/12279/labels/priority%2Fhigh"], + ]); + expect(r.calls[1].stdin).toBe('{"labels":["next"]}'); + // If removing fails part way, the issue still carries the new rank. + const failing = recorder((argv) => + argv.includes("DELETE") + ? { code: 1, stderr: "gh: Server Error (HTTP 502)" } + : JSON.stringify({ labels: [{ name: "now" }] }), + ); + await expect(new Ops(CFG, failing.run).setRank("12279", "next")).rejects.toThrow(/502/); + expect(failing.calls.map((c) => c.argv[4])).toEqual([undefined, "POST", "DELETE"]); + // A rank the issue already has is not added again; "none" only removes. + const same = recorder(() => JSON.stringify({ labels: [{ name: "now" }, { name: "next" }] })); + await new Ops(CFG, same.run).setRank("12279", "now"); + expect(same.calls.map((c) => c.argv[4])).toEqual([undefined, "DELETE"]); + const none = recorder(() => JSON.stringify({ labels: [{ name: "now" }] })); + await new Ops(CFG, none.run).setRank("12279", "none"); + expect(none.calls.map((c) => c.argv[4])).toEqual([undefined, "DELETE"]); + await expect(ops.setRank("12279", "urgent")).rejects.toThrow(/rank/); + await expect(ops.setRank("12279/labels", "now")).rejects.toThrow(OpError); + }); + + test("ranked issues come back most urgent first", async () => { + const item = (number: number, ...labels: string[]) => ({ + number, + title: `t${number}`, + html_url: `u${number}`, + updated_at: "2026-11-22T01:02:03Z", + comments: 0, + labels: labels.map((name) => ({ name })), + }); + const r = recorder(() => + JSON.stringify({ + items: [ + item(5, "next"), + item(9, "now", "priority/high"), + item(2, "priority/high"), + item(7, "expedite"), + item(1, "now"), + ], + }), + ); + const listed = await new Ops(CFG, r.run).priorities(); + expect(listed.truncated).toBe(false); + expect(listed.issues.map((i) => [i.number, i.rank])).toEqual([ + [7, "expedite"], + [1, "now"], + [9, "now"], + [2, "priority/high"], + [5, "next"], + ]); + expect(r.calls.length).toBe(1); + + // Search order is not rank order: the one expedite issue can be on any + // page, so every page is read before sorting. + const pageOf = (argv: string[]) => Number(argv.find((a) => a.startsWith("page="))?.slice(5)); + const paged = (pages: number) => + recorder((argv) => { + const page = pageOf(argv); + const full = page < pages; + return JSON.stringify({ + items: Array.from({ length: full ? 100 : 3 }, (_, n) => + item(page * 1000 + n, !full && n === 2 ? "expedite" : "next"), + ), + }); + }); + const three = paged(3); + const all = await new Ops(CFG, three.run).priorities(); + expect(three.calls.map((c) => pageOf(c.argv))).toEqual([1, 2, 3]); + expect(all.issues.length).toBe(203); + expect(all.issues[0]).toMatchObject({ number: 3002, rank: "expedite" }); + expect(all.truncated).toBe(false); + // Past the cap the list says it is incomplete instead of looking whole. + const endless = paged(Number.POSITIVE_INFINITY); + const capped = await new Ops(CFG, endless.run).priorities(); + expect(endless.calls.length).toBe(10); + expect(capped.issues.length).toBe(1000); + expect(capped.truncated).toBe(true); + // Exactly one full page: the second, empty page ends the read. + const exact = recorder((argv) => + JSON.stringify({ items: pageOf(argv) === 1 ? Array.from({ length: 100 }, (_, n) => item(n + 1, "next")) : [] }), + ); + expect(await new Ops(CFG, exact.run).priorities()).toMatchObject({ truncated: false }); + expect(exact.calls.length).toBe(2); + }); + + test("an idea is filed and queued in the same pass", async () => { + const packets: unknown[] = []; + const answers = (enqueue: string | { code: number; stderr: string }) => (argv: string[]) => { + if (argv[1] === "gh") + return JSON.stringify({ number: 12400, html_url: "https://x/12400", title: "Join at admission" }); + packets.push(JSON.parse(readFileSync(argv[3], "utf8"))); + return enqueue; + }; + const r = recorder(answers("{}")); + const ops = new Ops(CFG, r.run); + expect(await ops.fileIdea(" Join at admission ", "details", "now")).toEqual({ + issue: 12400, + url: "https://x/12400", + queued: true, + }); + expect(r.calls[0].argv.slice(3)).toEqual(["-X", "POST", "repos/developing-today/code/issues", "--input", "-"]); + expect(JSON.parse(r.calls[0].stdin!)).toEqual({ title: "Join at admission", body: "details", labels: ["now"] }); + expect(r.calls[1].argv.slice(0, 3)).toEqual(["fleet", "queue", "enqueue"]); + expect(r.calls[1].argv.slice(4)).toEqual(["--queue", "repo-health-code-pilot"]); + expect(() => readFileSync(r.calls[1].argv[3])).toThrow(); // the packet file does not outlive the call + expect(packets[0]).toMatchObject({ + title: "Triage developing-today/code#12400: Join at admission", + priority: 20, + dedupe_key: "repo-health:v1:triage:developing-today/code:issue:12400", + payload: { + schema: "repo-task/v1", + kind: "triage", + repo: "developing-today/code", + queue: "repo-health-code-pilot", + issue: { number: 12400, url: "https://github.com/developing-today/code/issues/12400" }, + max_attempts: 1000, + }, + }); + // The queue only takes priorities on its scale, and a more urgent + // rank never gets a later place than a less urgent one. + const scale = [10, 20, 30, 40, 50, 70, 90]; + const order = (["expedite", "priority/critical", "now", "priority/high", "next", "none"] as const).map( + (rank) => triagePacket("o/r", "q", 1, "t", rank, "2026-11-22T00:00:00Z").priority, + ); + expect(order.every((p) => scale.includes(p))).toBe(true); + expect(order).toEqual([...order].sort((a, b) => a - b)); + expect(triagePacket("o/r", "q", 1, "x".repeat(400), "none", "t").title.length).toBe(180); + + // The issue exists either way: a failed enqueue is reported, not hidden and not thrown. + const failing = recorder(answers({ code: 1, stderr: "error: store unreachable\nrepo-queue: enqueue failed" })); + expect(await new Ops(CFG, failing.run).fileIdea("t", "", "none")).toEqual({ + issue: 12400, + url: "https://x/12400", + queued: false, + note: "filed, not queued: repo-queue: enqueue failed", + }); + expect(JSON.parse(failing.calls[0].stdin!).labels).toEqual([]); + const refused = recorder(); + await expect(new Ops(CFG, refused.run).fileIdea("t", "", "urgent")).rejects.toThrow(/rank/); + await expect(new Ops(CFG, refused.run).fileIdea(" ", "", "none")).rejects.toThrow(OpError); + expect(refused.calls.length).toBe(0); + }); + + test("a stopped unit that systemd has unloaded is still listed", async () => { + const r = recorder((argv) => + argv[2] === "list-units" + ? " pm-aggregator.service loaded active running PM dashboard\n● pm-old.service not-found inactive dead pm-old.service\n" + : [ + "pm-aggregator.service enabled enabled", + "pm-console.service disabled enabled", + "pm-git-sync.timer enabled enabled", + "fleet-worker@.service static -", + "sshd.service enabled enabled", + "", + "5 unit files listed.", + ].join("\n"), + ); + const units = await new Ops(CFG, r.run).services(); + expect(units.map((u) => [u.unit, u.active, u.load])).toEqual([ + ["pm-aggregator.service", "active", "loaded"], + ["pm-console.service", "inactive", "not-loaded"], + ["pm-git-sync.timer", "inactive", "not-loaded"], + ["pm-old.service", "inactive", "not-found"], + ]); + expect(r.calls.map((c) => c.argv.slice(0, 3))).toEqual([ + ["systemctl", "--user", "list-units"], + ["systemctl", "--user", "list-unit-files"], + ]); + expect(parseUnitFiles("a b\n\nx.service\n pm-a.service masked\n")).toEqual([ + { unit: "pm-a.service", state: "masked" }, + ]); + // The loaded list is the one that must work; the file list only adds to it. + const partial = recorder((argv) => + argv[2] === "list-units" ? "pm-a.service loaded active running A\n" : { code: 1, stderr: "failed" }, + ); + expect((await new Ops(CFG, partial.run).services()).map((u) => u.unit)).toEqual(["pm-a.service"]); + }); + + test("services: only allowlisted units, and the interface's own units cannot be stopped", async () => { + const r = recorder(); + const ops = new Ops(CFG, r.run); + await ops.serviceAct("pm-aggregator.service", "restart"); + await ops.serviceAct("pm-tunnel.service", "restart"); + expect(r.calls.map((c) => c.argv)).toEqual([ + ["systemctl", "--user", "restart", "pm-aggregator.service"], + ["systemctl", "--user", "restart", "pm-tunnel.service"], + ]); + await expect(ops.serviceAct("pm-tunnel.service", "stop")).rejects.toThrow(/not stopped/); + await expect(ops.serviceAct("pm-console.service", "stop")).rejects.toThrow(/not stopped/); + for (const [unit, action] of [ + ["sshd.service", "restart"], + ["pm-x.service; reboot", "restart"], + ["pm-x.service", "kill"], + ["pm-x.service", "daemon-reload"], + ["pm-x", "restart"], + ["../pm-x.service", "restart"], + ["--now", "stop"], + [7, "stop"], + ]) { + await expect(ops.serviceAct(unit, action)).rejects.toThrow(OpError); + } + await expect(ops.serviceLogs("dbus.service", "10")).rejects.toThrow(OpError); + await ops.serviceLogs("opencode.service", "9999"); + expect(r.calls.length).toBe(3); + expect(r.calls[2].argv).toEqual([ + "journalctl", + "--user", + "-u", + "opencode.service", + "-n", + "400", + "--no-pager", + "-o", + "short-iso", + ]); + }); + + test("property: no generated unit name outside the allowlist is manageable", () => { + const next = rng(4872); + const pieces = [ + "pm-", + "opencode", + "fleet-", + "sshd", + "dbus", + "x", + ".service", + ".timer", + ".socket", + ";", + " ", + "/", + "..", + "$(", + "*", + "-", + "@", + "\n", + "queue-broker", + ]; + for (let i = 0; i < 3000; i++) { + const name = Array.from( + { length: 1 + Math.floor(next() * 4) }, + () => pieces[Math.floor(next() * pieces.length)], + ).join(""); + const allowed = manageable(name, CFG.unitPatterns); + const plain = /^[A-Za-z0-9@._-]+\.(service|timer)$/.test(name); + const prefixed = ["pm-", "opencode", "openchamber", "queue-broker", "secrets-broker", "fleet-"].some((p) => + name.startsWith(p), + ); + expect(allowed).toBe(plain && prefixed); + } + }); + + test("property: the unit parser reads back what systemctl prints", () => { + const next = rng(20261122); + const word = () => + ["active", "inactive", "failed", "running", "dead", "waiting", "exited", "loaded", "not-found"][ + Math.floor(next() * 9) + ]; + for (let i = 0; i < 300; i++) { + const units = Array.from({ length: Math.floor(next() * 6) }, (_, n) => ({ + unit: `pm-u${i}-${n}.${next() < 0.5 ? "service" : "timer"}`, + load: word(), + active: word(), + sub: word(), + description: next() < 0.3 ? "" : `Some unit — number ${n}`, + })); + const printed = units + .map( + (u) => + `${next() < 0.2 ? "● " : " "}${u.unit}${" ".repeat(1 + Math.floor(next() * 9))}${u.load} ${u.active} ${u.sub} ${u.description}`, + ) + .join("\n"); + expect(parseUnits(`${printed}\n\n`)).toEqual(units); + } + expect(parseUnits("0 loaded units listed.\n")).toEqual([]); + }); + + test("merging and a failing command", async () => { + const r = recorder((argv) => + argv.includes("-X") + ? JSON.stringify({ merged: true, sha: "abc" }) + : { code: 1, stderr: "gh: Not Found (HTTP 404)" }, + ); + const ops = new Ops(CFG, r.run); + expect(await ops.mergePr("12240")).toEqual({ number: 12240, merged: true, sha: "abc" }); + expect(r.calls[0].argv).toEqual([ + "fleet", + "gh", + "api", + "-X", + "PUT", + "repos/developing-today/code/pulls/12240/merge", + "-f", + "merge_method=merge", + ]); + await expect(ops.pr("12240")).rejects.toThrow(/failed \(exit 1\).*Not Found/); + await expect(ops.mergePr("12240/merge")).rejects.toThrow(OpError); + }); +}); + +describe("HTTP surface", () => { + function deps(who: "owner" | 401 | 403, r = recorder()): Deps & { audited: Record[] } { + const audited: Record[] = []; + return { + cfg: CFG, + ops: new Ops(CFG, r.run), + identify: async () => { + if (who === "owner") return { via: "cloudflare-access", email: OWNER }; + throw new AuthError(who, who === 401 ? "sign-in required" : "this identity is not the owner"); + }, + audit: async (e) => { + audited.push(e); + }, + audited, + }; + } + const get = (path: string) => new Request(`https://pm.security.cab${path}`, { headers: { host: "pm.security.cab" } }); + const post = ( + path: string, + body: unknown, + headers: Record = { "x-pm-console": "1", origin: "https://pm.security.cab" }, + ) => + new Request(`https://pm.security.cab${path}`, { + method: "POST", + body: JSON.stringify(body), + headers: { host: "pm.security.cab", "content-type": "application/json", ...headers }, + }); + + test("only the asset links and the health check answer without sign-in", async () => { + const d = deps(401); + const links = await handle(get("/.well-known/assetlinks.json"), d); + expect(links.status).toBe(200); + expect(await links.json()).toEqual(assetLinks(CFG)); + expect(assetLinks(CFG)[0]).toMatchObject({ target: { package_name: "today.developing.pmconsole" } }); + expect(assetLinks({ androidPackage: "p", androidFingerprints: [] })).toEqual([]); + expect(await (await handle(get("/console/health"), d)).json()).toEqual({ ok: true }); + for (const path of [ + "/console/", + "/console/app.js", + "/console/api/me", + "/console/api/services", + "/console/api/queue", + ]) { + 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); + }); + + test("the page and its files are served to the owner with a strict policy", async () => { + const d = deps("owner"); + const page = await handle(get("/console/"), d); + expect(page.headers.get("content-type")).toContain("text/html"); + expect(page.headers.get("content-security-policy")).toContain("default-src 'self'"); + 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); + 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"]) { + expect((await handle(get(`/console/${name}`), d)).status).toBe(404); + } + expect((await handle(get("/console/api/prs/%E0%A4%A"), d)).status).toBe(400); + expect((await handle(post("/console/api/queue/%ZZ/unblock", { reason: "x" }), d)).status).toBe(400); + expect(await (await handle(get("/console/api/me"), d)).json()).toMatchObject({ + email: OWNER, + via: "cloudflare-access", + repo: "developing-today/code", + }); + }); + + test("a write needs the console's header and its own origin, and is audited", async () => { + const r = recorder(); + const d = deps("owner", r); + expect((await handle(post("/console/api/services/pm-aggregator.service/restart", {}, {}), d)).status).toBe(403); + expect( + ( + await handle( + post( + "/console/api/services/pm-aggregator.service/restart", + {}, + { "x-pm-console": "1", origin: "https://evil.example" }, + ), + d, + ) + ).status, + ).toBe(403); + expect(r.calls.length).toBe(0); + const ok = await handle(post("/console/api/services/pm-aggregator.service/restart", {}), d); + expect(await ok.json()).toEqual({ ok: true, result: { unit: "pm-aggregator.service", action: "restart" } }); + expect(r.calls.map((c) => c.argv)).toEqual([["systemctl", "--user", "restart", "pm-aggregator.service"]]); + const refused = await handle(post("/console/api/services/pm-tunnel.service/stop", {}), d); + expect(refused.status).toBe(409); + const bad = await handle( + new Request("https://pm.security.cab/console/api/messages", { + method: "POST", + body: "[1]", + headers: { host: "pm.security.cab", "x-pm-console": "1" }, + }), + d, + ); + expect(bad.status).toBe(400); + // Each action is recorded before it runs and again with its outcome. + expect(d.audited.map((e) => [e.action, e.phase, e.ok, e.who])).toEqual([ + ["service.restart", "start", undefined, OWNER], + ["service.restart", "done", true, OWNER], + ["service.stop", "start", undefined, OWNER], + ["service.stop", "done", false, OWNER], + ]); + expect( + ( + await handle( + new Request("https://pm.security.cab/console/api/me", { + method: "DELETE", + headers: { host: "pm.security.cab" }, + }), + d, + ) + ).status, + ).toBe(405); + }); + + 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[] = []; + const d = deps("owner", r); + const run = r.run; + d.ops = new Ops(CFG, async (argv, opts) => { + order.push("run"); + return run(argv, opts); + }); + d.audit = async (e) => { + order.push(`audit:${e.phase}`); + }; + expect((await handle(post("/console/api/services/pm-aggregator.service/restart", {}), d)).status).toBe(200); + expect(order).toEqual(["audit:start", "run", "audit:done"]); + + // The record cannot be written: nothing runs. + d.audit = async () => { + throw new Error("disk full"); + }; + const refused = await handle(post("/console/api/prs/12240/merge", {}), d); + expect(refused.status).toBe(502); + expect((await refused.json()).error).toContain("not taken"); + expect(r.calls.length).toBe(1); + + // The record of the outcome cannot be written: the merge happened, and + // the answer says so, or the owner would press Merge again. + let writes = 0; + d.audit = async () => { + if (++writes > 1) throw new Error("disk full"); + }; + d.ops = new Ops(CFG, async () => ({ code: 0, stdout: JSON.stringify({ merged: true, sha: "abc" }), stderr: "" })); + const merged = await handle(post("/console/api/prs/12240/merge", {}), d); + expect(merged.status).toBe(200); + expect(await merged.json()).toEqual({ ok: true, result: { number: 12240, merged: true, sha: "abc" } }); + expect(writes).toBe(2); + }); + + test("the server hands the connection's address to sign-in", async () => { + const d = deps("owner"); + const seen: (string | null)[] = []; + d.identify = async (_req, peer) => { + seen.push(peer); + return { via: "loopback", email: "local" }; + }; + await handle(get("/console/api/me"), d, "203.0.113.9"); + await handle(get("/console/api/me"), d); + expect(seen).toEqual(["203.0.113.9", null]); + }); + + test("each write route reaches its operation", async () => { + const r = recorder((argv) => + argv[1] === "gh" ? JSON.stringify({ number: 1, html_url: "u", merged: true, sha: "s", labels: [] }) : "", + ); + const d = deps("owner", r); + const run = async (path: string, body: unknown) => (await handle(post(path, body), d)).status; + expect(await run("/console/api/queue/20306/unblock", { reason: "blocker closed" })).toBe(200); + expect(await run("/console/api/queue/20306/cancel", { reason: "duplicate" })).toBe(200); + expect(await run("/console/api/priorities/12279/rank", { rank: "now" })).toBe(200); + expect(await run("/console/api/issues/12279/comment", { body: "go" })).toBe(200); + expect(await run("/console/api/ideas", { title: "an idea", body: "", rank: "next" })).toBe(200); + expect(await run("/console/api/messages", { to: ["all"], text: "hello", command: false })).toBe(200); + expect(await run("/console/api/prs/12240/merge", {})).toBe(200); + expect(await run("/console/api/queue/20306/claim", { reason: "x" })).toBe(400); + expect(await run("/console/api/nothing", {})).toBe(404); + expect(d.audited.filter((e) => e.phase === "start").length).toBe(8); // the refused queue action was recorded too + expect(d.audited.filter((e) => e.ok).map((e) => e.action)).toEqual([ + "queue.unblock", + "queue.cancel", + "priority.rank", + "issue.comment", + "idea.file", + "message.send", + "pr.merge", + ]); + expect(JSON.stringify(d.audited)).not.toContain("hello"); // message text is not copied into the audit log + }); +}); diff --git a/pm-stack/systemd/pm-console.service b/pm-stack/systemd/pm-console.service new file mode 100644 index 0000000000..c62922d647 --- /dev/null +++ b/pm-stack/systemd/pm-console.service @@ -0,0 +1,16 @@ +[Unit] +Description=PM console — queue, priorities, agents, services and pull requests (pm-stack) +After=network-online.target + +[Service] +Type=simple +WorkingDirectory=%h/git/code/pm-stack/console +ExecStart=/run/current-system/sw/bin/bun run src/server.ts +EnvironmentFile=%h/.local/state/pm-console/.env +# The console shells out to fleet, gh (through fleet), systemctl and journalctl. +Environment=PATH=%h/.local/bin:/etc/profiles/per-user/%u/bin:/run/current-system/sw/bin:/usr/bin:/bin +Restart=on-failure +RestartSec=5 + +[Install] +WantedBy=default.target