From 57274bbc0578c852aaf2ac80c3d3ce699de85da6 Mon Sep 17 00:00:00 2001 From: Day Dreamer <87640074+HugoXK@users.noreply.github.com> Date: Tue, 17 Nov 2026 10:04:04 +0800 Subject: [PATCH] =?UTF-8?q?feat(plane):=20the=20management=20plane's=20fir?= =?UTF-8?q?st=20slice=20=E2=80=94=20records,=20credentials,=20lifecycle,?= =?UTF-8?q?=20routes=20(#3113)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A new top-level package plane/ (@flybot/plane, zero runtime dependencies): one plane.json store (0600/0700, temp+rename) for accounts, workspaces and instance metadata with per-workspace name uniqueness; two non-interchangeable credential families (op_/ctl_, sha256-only at rest, timingSafeEqual, redact()); the LifecycleBackend contract with a MemoryBackend and a ComposeBackend that only materializes instances//compose.yaml + control.env (0600) and never spawns docker; handle() as a pure routing function plus a loopback serve() adapter and a token/serve CLI; upgrade/recycle refuse with NotImplementedError. Wired in: npm --prefix plane test joins root verify after core, a Plane tests step in .github/actions/flybot-tests (additive only), suite row plane (L1) in docs/testing-layers.json with the md regenerated by the tool, and a new subsystems page plane.md whose owned_paths is exactly plane/. 20 red-first cases (ownership 403/401, create 409/400/persistence, the create->start->stop->start loop, credential separation, compose file contract) run with no network and no docker: npm --prefix plane test -> # tests 20, # fail 0. Fixes #3113 --- .github/actions/flybot-tests/action.yml | 5 + docs/subsystems/README.md | 1 + docs/subsystems/plane.md | 19 ++++ docs/testing-layers.json | 9 ++ docs/testing-layers.md | 1 + package.json | 2 +- plane/README.md | 44 ++++++++ plane/bin/plane.mjs | 53 ++++++++++ plane/index.js | 30 ++++++ plane/package.json | 9 ++ plane/src/credentials.mjs | 70 +++++++++++++ plane/src/lifecycle.mjs | 92 +++++++++++++++++ plane/src/server.mjs | 89 ++++++++++++++++ plane/src/store.mjs | 129 ++++++++++++++++++++++++ plane/test/compose-backend.test.js | 73 ++++++++++++++ plane/test/create.test.js | 91 +++++++++++++++++ plane/test/credentials.test.js | 75 ++++++++++++++ plane/test/lifecycle.test.js | 96 ++++++++++++++++++ plane/test/ownership.test.js | 81 +++++++++++++++ 19 files changed, 968 insertions(+), 1 deletion(-) create mode 100644 docs/subsystems/plane.md create mode 100644 plane/README.md create mode 100644 plane/bin/plane.mjs create mode 100644 plane/index.js create mode 100644 plane/package.json create mode 100644 plane/src/credentials.mjs create mode 100644 plane/src/lifecycle.mjs create mode 100644 plane/src/server.mjs create mode 100644 plane/src/store.mjs create mode 100644 plane/test/compose-backend.test.js create mode 100644 plane/test/create.test.js create mode 100644 plane/test/credentials.test.js create mode 100644 plane/test/lifecycle.test.js create mode 100644 plane/test/ownership.test.js diff --git a/.github/actions/flybot-tests/action.yml b/.github/actions/flybot-tests/action.yml index 6a1e39431..a8e9bb66c 100644 --- a/.github/actions/flybot-tests/action.yml +++ b/.github/actions/flybot-tests/action.yml @@ -86,6 +86,11 @@ runs: shell: bash working-directory: core run: npm test + - name: Plane tests + if: inputs.coverage != 'true' + shell: bash + working-directory: plane + run: npm test - name: Plugin lint if: inputs.plugins != 'false' shell: bash diff --git a/docs/subsystems/README.md b/docs/subsystems/README.md index f30e1b20c..10efbcae3 100644 --- a/docs/subsystems/README.md +++ b/docs/subsystems/README.md @@ -13,6 +13,7 @@ Detail pages for each FlyBot subsystem. Each page lists `owned_paths`, what the | workflow | [workflow.md](workflow.md) | `plugins/workflow/` | | project | [project.md](project.md) | `plugins/project/` | | social | [social.md](social.md) | `plugins/social/` | +| plane | [plane.md](plane.md) | `plane/` | | install | [install.md](install.md) | `core/scripts/`, arch-doc tests, `plugins/README.md`, the container image (`Dockerfile`, `compose.yaml`, `docker/`) | | team | [team.md](team.md) | `docs/subsystems/team.md` — **planned contract only** (no code paths; multi-human is not shipped) | | interop | [interop.md](interop.md) | `dev/interop/`, `scripts/lint-interop.mjs` — offline development harness only | diff --git a/docs/subsystems/plane.md b/docs/subsystems/plane.md new file mode 100644 index 000000000..23fa545d2 --- /dev/null +++ b/docs/subsystems/plane.md @@ -0,0 +1,19 @@ +--- +subsystem: plane +owned_paths: + - plane/ +--- + +# plane (`@flybot/plane`) + +The management-plane control plane — first slice of #3113 (parent #3110). It owns accounts, workspaces and FlyBot instance metadata, the two credential families, and the lifecycle seam; it runs no agent and no docker itself. + +`plane/` is a top-level package, not a core plugin: the management plane must not run inside the agent container, and `core/` is ds-bot + patches (changing it means regenerating `patches/ds-bot/`). It is also not under `/opt/flybot/packages` in the image, so `docker/profile.mjs` never bundles it — this slice ships no image and no compose changes. + +Records live in one `plane.json` under the data dir (`version` at the top for migration), written temp-file-plus-rename at 0600 in a 0700 dir, the `core/src/host/private-files.js` shape. An instance name is unique inside a workspace, never across owners. The state the plane records (`stopped` stays `stopped` across a process restart) is the plane's own bookkeeping; an instance's data stays on the instance's volume. + +Credentials are two non-interchangeable families: operator tokens (`op_…`) for `/api/*` and per-instance control tokens (`ctl_…`) for the plane→instance direction. Only sha256 digests are stored; verification is `timingSafeEqual`; `redact()` is what a log line may show. + +The lifecycle is the `LifecycleBackend` contract (`create/start/stop/upgrade/recycle`). `MemoryBackend` moves state only; `ComposeBackend` materializes `instances//compose.yaml` plus a 0600 `control.env` — host networking and a loopback `FLYBOT_PORT`, mirroring the repo's own `compose.yaml` — and never spawns docker. `upgrade` and `recycle` throw `NotImplementedError` by design: the seam exists, the second slice fills it. + +`handle()` is the pure routing function (every route verifies an operator token, then the instance routes compare `instance.ownerId`); `serve()` is the `node:http` adapter bound to `127.0.0.1`; `plane/bin/plane.mjs` is the CLI (`token`, `serve`). The suite is `npm --prefix plane test` — no network, no docker — registered in `docs/testing-layers.json` as suite `plane` (L1). diff --git a/docs/testing-layers.json b/docs/testing-layers.json index beabaac0b..d0f2b36bc 100644 --- a/docs/testing-layers.json +++ b/docs/testing-layers.json @@ -124,6 +124,15 @@ "dev/live-e2e/test/**" ], "reason": "Offline unit tests for the live end-to-end harness (a fake adapter, no model). They run in the root `npm run verify` only; no CI gate runs them today. Moving them into L1 is a separate change, and the layer that does drive a real model is `live-e2e.yml`, whose row is below." + }, + { + "id": "plane", + "layer": "L1", + "paths": [ + "plane/test/**/*.test.js" + ], + "command": "npm --prefix plane test", + "note": "管理面控制平面骨架:凭证分离、所有权、创建/启停、compose 生成;不碰网络与 Docker。" } ], "workflows": [ diff --git a/docs/testing-layers.md b/docs/testing-layers.md index 7463a20f7..63dc66c1a 100644 --- a/docs/testing-layers.md +++ b/docs/testing-layers.md @@ -98,6 +98,7 @@ The tables below are generated: edit `docs/testing-layers.json`, then run | `patch-payload` | none (see reason) | `patches/ds-bot/files/**` | — Generated copies of the files the patches carry. They are compared against `core/` by `node scripts/ds-bot-patches.mjs check` (L2) and never run on their own; the code under test is the copy in `core/`. | | `upstream` | none (see reason) | `ds-bot/test/**` | — The pristine upstream checkout at the pinned version. FlyBot never edits or runs it directly — `core/` is `ds-bot/` plus the patches, and the `core` suite runs the patched copies. | | `live-e2e-unit` | none (see reason) | `dev/live-e2e/test/**` | — Offline unit tests for the live end-to-end harness (a fake adapter, no model). They run in the root `npm run verify` only; no CI gate runs them today. Moving them into L1 is a separate change, and the layer that does drive a real model is `live-e2e.yml`, whose row is below. | +| `plane` | L1 | `plane/test/**/*.test.js` | `npm --prefix plane test` | | Workflow | Kind | Layer | Gate | Runs on | What it guarantees, or why it is not a layer | | --- | --- | --- | --- | --- | --- | diff --git a/package.json b/package.json index ef76d9eeb..34c5d8c7e 100644 --- a/package.json +++ b/package.json @@ -6,7 +6,7 @@ "node": ">=22" }, "scripts": { - "verify": "npm --prefix core run lint && node scripts/lint-plugins.mjs && node core/scripts/build-client.mjs --check && node scripts/ds-bot-patches.mjs check && node scripts/ds-bot-patches.mjs canonical && npm --prefix core test && npm --prefix plugins/social test && npm --prefix plugins/tree test && npm --prefix plugins/timeline test && npm --prefix plugins/workflow test && npm --prefix plugins/project test && node --test \".github/scripts/*.test.mjs\" \"policy/*.test.mjs\" && npm run lint:interop && npm run test:interop && npm run lint:live-e2e && npm run test:live-e2e", + "verify": "npm --prefix core run lint && node scripts/lint-plugins.mjs && node core/scripts/build-client.mjs --check && node scripts/ds-bot-patches.mjs check && node scripts/ds-bot-patches.mjs canonical && npm --prefix core test && npm --prefix plane test && npm --prefix plugins/social test && npm --prefix plugins/tree test && npm --prefix plugins/timeline test && npm --prefix plugins/workflow test && npm --prefix plugins/project test && node --test \".github/scripts/*.test.mjs\" \"policy/*.test.mjs\" && npm run lint:interop && npm run test:interop && npm run lint:live-e2e && npm run test:live-e2e", "lint:interop": "node scripts/lint-interop.mjs", "test:interop": "node --import ./dev/interop/no-network.mjs --test \"dev/interop/test/*.test.mjs\"", "demo:interop": "node --import ./dev/interop/no-network.mjs dev/interop/demo.mjs", diff --git a/plane/README.md b/plane/README.md new file mode 100644 index 000000000..e8bbdb2db --- /dev/null +++ b/plane/README.md @@ -0,0 +1,44 @@ +# @flybot/plane + +The FlyBot management plane — first slice of [#3113](https://github.com/ThinkFlowLab/FlyBot/issues/3113) (parent: #3110). + +`plane/` is the control plane that owns accounts, workspaces and FlyBot instance records, mints the two credential families, and steers instances through an abstract lifecycle backend. It deliberately runs **no** agent and **no** docker itself: an instance is the existing FlyBot runtime on its own data volume, and the plane only records and steers it. + +## Working defaults, not owner decisions + +These three are replaceable working defaults chosen for this slice, following the issue's "可替换的工作默认" rule. None of them is settled by the owner: + +1. **Granularity: one instance per owner (or per workspace).** Closest to today's "one instance per person" (#352). Adjustable without touching the store: the record keys on `(workspaceId, name)`. +2. **Storage: one JSON file, `plane.json`, under the data dir.** It carries a `version` field so a later migration can tell what it is reading before it reads it. The plane owns this file alone; an instance's own data stays on the instance's volume. +3. **Backend: the compose backend only *materializes* an instance project** (`instances//compose.yaml` + `control.env`, mode 0600) and never runs docker. The existing repo `compose.yaml` is one self-hosting path, not the only one; `LifecycleBackend` is the seam for others. + +Also out of this slice, refusing loudly rather than pretending: `upgrade` and `recycle` throw `NotImplementedError`; no management UI, no external gateway, no real `docker compose up`. + +## Credentials + +Two families that never open each other's door: + +- Operator tokens (`op_…`) speak to `/api/*`. `node plane/bin/plane.mjs token --data-dir --account ` mints one and prints it exactly once. +- Control tokens (`ctl_…`) are what the plane presents to one FlyBot instance. Each instance gets its own; the compose backend writes it into that instance's 0600 `control.env`, never into the compose file. + +Only sha256 digests are persisted (`plane.json` has no plaintext). A control token presented to `/api/*` is a 401, an operator token presented as a control credential is refused, and verification uses `timingSafeEqual`. Logs that must name a token go through `redact()`. + +## API + +`serve()` binds `127.0.0.1` only. `handle()` is the same logic as a pure function — that is what the tests drive, with no socket. + +| Route | What it does | +| --- | --- | +| `POST /api/instances` | create (needs `workspaceId`, `name`; unique per workspace; 409 otherwise; hands out the control token once) | +| `GET /api/instances` | list the caller's own instances only | +| `GET /api/instances/:id` | one instance (404 unknown, 403 someone else's) | +| `POST /api/instances/:id/start` | start (idempotent record: state moves to `running`) | +| `POST /api/instances/:id/stop` | stop (state persists as `stopped` across restarts) | + +## Test + +```sh +npm --prefix plane test +``` + +No network, no docker, no cloud. The suite (20 cases across 5 files) covers ownership (403/401 boundaries), creation (duplicate, isolation, persistence, 400), the create→start→stop→start loop, credential separation, and the compose backend's file-only contract. diff --git a/plane/bin/plane.mjs b/plane/bin/plane.mjs new file mode 100644 index 000000000..6bbdae63f --- /dev/null +++ b/plane/bin/plane.mjs @@ -0,0 +1,53 @@ +#!/usr/bin/env node +// The plane's CLI (#3113). `token` mints an operator token for an account and prints it once — +// the store keeps only the digest, so what leaves the terminal is the only copy. `serve` starts +// the HTTP surface on the loopback with a lifecycle backend of your choice; this slice ships the +// compose-generating backend, which runs nothing. +import { MemoryBackend, ComposeBackend } from '../src/lifecycle.mjs' +import { mintOperatorToken } from '../src/credentials.mjs' +import { openStore } from '../src/store.mjs' +import { serve } from '../src/server.mjs' + +const usage = `@flybot/plane — the FlyBot management plane (#3113), first slice. + + node plane/bin/plane.mjs token --data-dir --account + Mint an operator token for ; printed once, only its sha256 is stored. + node plane/bin/plane.mjs serve --data-dir [--port 3090] [--backend compose|memory] + Serve /api/* on 127.0.0.1. The compose backend materializes instance projects and + never runs docker; upgrade and recycle are not implemented in this slice. +` + +const flag = (name) => { + const at = process.argv.indexOf(name) + return at > 0 && at + 1 < process.argv.length ? process.argv[at + 1] : null +} + +const command = process.argv[2] +const dataDir = flag('--data-dir') +if (!command || !dataDir) { + console.error(usage) + process.exit(2) +} + +if (command === 'token') { + const accountId = flag('--account') + if (!accountId) { console.error('token needs --account '); process.exit(2) } + const store = openStore(dataDir) + const { token } = mintOperatorToken(store, accountId) + console.log(token) + process.exit(0) +} + +if (command === 'serve') { + const port = Number(flag('--port') ?? 3090) + const which = flag('--backend') ?? 'compose' + const backend = which === 'memory' ? new MemoryBackend() : new ComposeBackend({ root: dataDir }) + const server = await serve({ port, dataDir, backend, log: line => console.log(line) }) + console.log(`plane listening on 127.0.0.1:${port} (backend: ${which})`) + const stop = () => server.close(() => process.exit(0)) + process.on('SIGINT', stop) + process.on('SIGTERM', stop) +} else { + console.error(usage) + process.exit(2) +} diff --git a/plane/index.js b/plane/index.js new file mode 100644 index 000000000..bcf79127e --- /dev/null +++ b/plane/index.js @@ -0,0 +1,30 @@ +// The public face of @flybot/plane (#3113): open one data dir, steer the instances recorded in +// it. The methods carry no authorization — that lives in the HTTP surface (`src/server.mjs`) — +// and no process handling — that lives in the lifecycle backend. `clock` is injectable so a +// later slice can test time without waiting for it. Every method is async so a caller can treat +// the plane uniformly, including the refusals: a backend seam that throws rejects the same way. +import { openStore } from './src/store.mjs' + +export function createPlane({ dataDir, backend, clock = () => Date.now() } = {}) { + if (!dataDir) throw new Error('dataDir is required') + if (!backend) throw new Error('backend is required') + const store = openStore(dataDir) + + const apply = async (id, report) => store.updateInstance(id, { ...report, at: clock() }) + + return { + store, + async createInstance({ workspaceId, name }) { + const { instance, controlToken } = store.createInstance({ workspaceId, name }) + await apply(instance.id, backend.create(instance, { controlToken })) + return { instance: store.getInstance(instance.id), controlToken } + }, + async startInstance(id) { return apply(id, backend.start(store.getInstance(id))) }, + async stopInstance(id) { return apply(id, backend.stop(store.getInstance(id))) }, + async getInstance(id) { return store.getInstance(id) }, + async listInstances({ ownerId } = {}) { return store.listInstances({ ownerId }) }, + // On the contract, not in this slice: they refuse loudly rather than succeed quietly. + async upgradeInstance(id) { return apply(id, backend.upgrade(store.getInstance(id))) }, + async recycleInstance(id) { return apply(id, backend.recycle(store.getInstance(id))) }, + } +} diff --git a/plane/package.json b/plane/package.json new file mode 100644 index 000000000..ed6ce4755 --- /dev/null +++ b/plane/package.json @@ -0,0 +1,9 @@ +{ + "name": "@flybot/plane", + "private": true, + "description": "Management-plane control-plane skeleton: accounts, workspaces, instance records, credentials, lifecycle (#3113).", + "type": "module", + "engines": { "node": ">=22" }, + "scripts": { "test": "node --test \"test/*.test.js\"" }, + "devDependencies": {} +} diff --git a/plane/src/credentials.mjs b/plane/src/credentials.mjs new file mode 100644 index 000000000..9e82a95b2 --- /dev/null +++ b/plane/src/credentials.mjs @@ -0,0 +1,70 @@ +// Two token families, one file, no overlap (#3113). An operator token (`op_…`) is what a person's +// API client presents to the management plane; a control token (`ctl_…`) is what the plane +// presents to one FlyBot instance. Neither verifies against the other's table, and only sha256 +// digests are ever persisted — `mintOperatorToken` hands the plaintext back exactly once, and a +// log line that wants to name a token goes through `redact()`. +import { createHash, randomBytes, timingSafeEqual } from 'node:crypto' + +export const OPERATOR_PREFIX = 'op_' +export const CONTROL_PREFIX = 'ctl_' + +export function hash(token) { + return createHash('sha256').update(token, 'utf8').digest('hex') +} + +const mint = prefix => { + const token = `${prefix}${randomBytes(16).toString('hex')}` + return { token, digest: hash(token) } +} + +export function mintControlToken() { + return mint(CONTROL_PREFIX) +} + +export function mintOperatorToken(store, accountId) { + const account = store.findAccount(accountId) + if (!account) throw new Error(`no account ${accountId}`) + const minted = mint(OPERATOR_PREFIX) + // The store keeps an array so a second mint does not silently retire a token that may still be + // in a client's hands; retiring one is a later slice's job. + account.operatorTokenHashes.push(minted.digest) + store.persist() + return minted +} + +const bearer = authorization => { + const match = /^Bearer (.+)$/.exec(String(authorization ?? '')) + return match ? match[1] : null +} + +const safeEqual = (a, b) => { + const left = Buffer.from(a, 'utf8') + const right = Buffer.from(b, 'utf8') + return left.length === right.length && timingSafeEqual(left, right) +} + +// A control token never verifies here: its digest lives on an instance record, not on an account, +// so the scan below cannot match it even though the comparison itself is safe. +export function verifyOperator(store, authorization) { + const token = bearer(authorization) + if (!token || !token.startsWith(OPERATOR_PREFIX)) return null + const digest = hash(token) + for (const account of store.accounts()) { + if (account.operatorTokenHashes.some(stored => safeEqual(stored, digest))) { + return { accountId: account.id } + } + } + return null +} + +export function verifyControl(instance, authorization) { + const token = bearer(authorization) + if (!token || !token.startsWith(CONTROL_PREFIX) || !instance) return false + return safeEqual(instance.controlTokenHash, hash(token)) +} + +export function redact(token) { + const text = String(token ?? '') + const at = text.indexOf('_') + return at > 0 ? `${text.slice(0, at + 1)}****` : '****' +} diff --git a/plane/src/lifecycle.mjs b/plane/src/lifecycle.mjs new file mode 100644 index 000000000..0c3d0f4c9 --- /dev/null +++ b/plane/src/lifecycle.mjs @@ -0,0 +1,92 @@ +// The lifecycle seam (#3113): the plane steers instances through this contract and never through +// a docker command of its own. Two backends ship in this slice — `MemoryBackend`, which moves +// state and nothing else, and `ComposeBackend`, which materializes a compose project per instance +// and deliberately does not run it. `upgrade` and `recycle` are on the contract so the second +// slice has a shape to fill; until then they refuse loudly instead of succeeding quietly. +import { chmodSync, mkdirSync, writeFileSync } from 'node:fs' +import { join } from 'node:path' +import { PRIVATE_DIR_MODE } from './store.mjs' + +export class NotImplementedError extends Error { + constructor(what) { + super(`${what} is not implemented in this slice of #3113`) + this.name = 'NotImplementedError' + this.what = what + } +} + +// The contract every backend answers. `create` provisions, `start`/`stop` move the instance and +// report `{ state, health }`; `upgrade` and `recycle` exist as seams. +export class LifecycleBackend { + /* eslint-disable-next-line no-unused-vars */ + create(instance) { throw new NotImplementedError(`${this.constructor.name}.create`) } + /* eslint-disable-next-line no-unused-vars */ + start(instance) { throw new NotImplementedError(`${this.constructor.name}.start`) } + /* eslint-disable-next-line no-unused-vars */ + stop(instance) { throw new NotImplementedError(`${this.constructor.name}.stop`) } + /* eslint-disable-next-line no-unused-vars */ + upgrade(instance) { throw new NotImplementedError(`${this.constructor.name}.upgrade`) } + /* eslint-disable-next-line no-unused-vars */ + recycle(instance) { throw new NotImplementedError(`${this.constructor.name}.recycle`) } +} + +// For tests and for the plane's own bookkeeping: the same contract with no files and no +// processes. State is the plane's to persist — the backend only reports what it did. +export class MemoryBackend extends LifecycleBackend { + create() { return { state: 'stopped', health: 'unknown' } } + start() { return { state: 'running', health: 'ok' } } + stop() { return { state: 'stopped', health: 'unknown' } } +} + +// The first real backend. It writes `instances//compose.yaml` and `instances//control.env` +// (mode 0600) — a project a person or the next slice can `docker compose up` — and runs nothing: +// `runner` is the seam the docker-calling slice will use, and it stays at zero calls here. The +// compose file mirrors the repo's own `compose.yaml` (host networking, a loopback FLYBOT_PORT) +// rather than inventing a second topology. +export class ComposeBackend extends LifecycleBackend { + constructor({ root, runner = null } = {}) { + super() + this.root = root + this.runner = runner + } + + materialize(instance, { controlToken }) { + const dir = join(this.root, 'instances', instance.id) + mkdirSync(dir, { recursive: true, mode: PRIVATE_DIR_MODE }) + const yaml = [ + `# Generated by @flybot/plane for instance ${instance.id} (#3113).`, + `# Run it yourself: docker compose -p flybot-${instance.id} up -d --build`, + `name: flybot-${instance.id}`, + 'services:', + ' flybot:', + ' build: ../../..', + ' image: flybot:plane', + ' restart: unless-stopped', + ' network_mode: host', + ' env_file:', + ' - control.env', + ' environment:', + ` - FLYBOT_PORT=${instance.port}`, + ' volumes:', + ` - data:/data`, + 'volumes:', + ' data:', + '', + ].join('\n') + // The control credential rides in its own 0600 env file; the compose file itself stays + // shareable (logs, code review) with no secret in it (#3113). + const env = `FLYBOT_CONTROL_TOKEN=${controlToken}\n` + writeFileSync(join(dir, 'compose.yaml'), yaml, { encoding: 'utf8', mode: 0o600 }) + writeFileSync(join(dir, 'control.env'), env, { encoding: 'utf8', mode: 0o600 }) + chmodSync(join(dir, 'control.env'), 0o600) + return { dir, project: `flybot-${instance.id}`, port: instance.port } + } + + create(instance, { controlToken } = {}) { + if (controlToken) this.materialize(instance, { controlToken }) + return { state: 'stopped', health: 'unknown' } + } + + start() { return { state: 'running', health: 'ok' } } + stop() { return { state: 'stopped', health: 'unknown' } } +} diff --git a/plane/src/server.mjs b/plane/src/server.mjs new file mode 100644 index 000000000..1479f712d --- /dev/null +++ b/plane/src/server.mjs @@ -0,0 +1,89 @@ +// The plane's HTTP surface, split so it can be tested without a socket (#3113): `handle()` is a +// pure function from one request `{ method, path, headers, body }` to one response +// `{ status, headers, body }`, and `serve()` is the thin `node:http` adapter that feeds it. +// +// Every route asks `verifyOperator` first — a control token is not an operator token, and neither +// is silence — and then the instance routes compare `instance.ownerId` with the account the token +// belongs to: a stranger with a valid token of their own gets 403, not a read. +import { createServer } from 'node:http' +import { redact, verifyOperator } from './credentials.mjs' +import { openStore, DuplicateInstanceError, UnknownInstanceError } from './store.mjs' + +const json = (status, body) => ({ status, headers: { 'content-type': 'application/json' }, body }) + +const ROUTES = [ + { method: 'POST', pattern: /^\/api\/instances$/ }, + { method: 'GET', pattern: /^\/api\/instances$/ }, + { method: 'GET', pattern: /^\/api\/instances\/([^/]+)$/ }, + { method: 'POST', pattern: /^\/api\/instances\/([^/]+)\/start$/ }, + { method: 'POST', pattern: /^\/api\/instances\/([^/]+)\/stop$/ }, +] + +const route = (method, path) => { + const hit = ROUTES.find(r => r.method === method && r.pattern.test(path)) + if (!hit) return null + const match = hit.pattern.exec(path) + return { method, id: match[1] ?? null } +} + +export function handle(request, deps) { + const { store, backend } = deps + const found = route(request.method, request.path) + if (!found) return json(404, { error: 'no such route' }) + + const operator = verifyOperator(store, request.headers?.authorization) + if (!operator) return json(401, { error: 'a valid operator token is required' }) + + if (request.method === 'POST' && found.id === null) { + const { workspaceId, name } = request.body ?? {} + if (!workspaceId || !name) return json(400, { error: 'workspaceId and name are required' }) + try { + const { instance, controlToken } = store.createInstance({ workspaceId, name }) + const reported = backend.create(instance, { controlToken }) + const saved = store.updateInstance(instance.id, reported) + // The control token is handed out exactly once, here, to the operator that created the + // instance; the store keeps only its digest. + return json(201, { instance: saved, controlToken }) + } catch (err) { + if (err instanceof DuplicateInstanceError) return json(409, { error: err.message }) + if (err instanceof UnknownInstanceError) return json(404, { error: err.message }) + return json(400, { error: err.message }) + } + } + + if (request.method === 'GET' && found.id === null) { + return json(200, { instances: store.listInstances({ ownerId: operator.accountId }) }) + } + + const instance = store.findInstance(found.id) + if (!instance) return json(404, { error: `no instance ${found.id}` }) + if (instance.ownerId !== operator.accountId) return json(403, { error: 'this instance belongs to another operator' }) + + if (request.method === 'GET') return json(200, { instance }) + + const reported = request.path.endsWith('/start') ? backend.start(instance) : backend.stop(instance) + const saved = store.updateInstance(instance.id, reported) + return json(200, { instance: saved }) +} + +export function serve({ port, dataDir, backend, host = '127.0.0.1', log = () => {} }) { + const store = openStore(dataDir) + const server = createServer(async (req, res) => { + const chunks = [] + for await (const chunk of req) chunks.push(chunk) + let body = {} + if (chunks.length) { + try { body = JSON.parse(Buffer.concat(chunks).toString('utf8')) } catch { body = {} } + } + const url = new URL(req.url, 'http://localhost') + const response = handle( + { method: req.method, path: url.pathname, headers: req.headers, body }, + { store, backend }, + ) + const payload = JSON.stringify(response.body) + res.writeHead(response.status, { 'content-type': 'application/json', 'content-length': Buffer.byteLength(payload) }) + res.end(payload) + log(`${req.method} ${url.pathname} -> ${response.status} ${redact(req.headers?.authorization ?? '')}`) + }) + return new Promise(resolve => server.listen(port, host, () => resolve(server))) +} diff --git a/plane/src/store.mjs b/plane/src/store.mjs new file mode 100644 index 000000000..7f96fa107 --- /dev/null +++ b/plane/src/store.mjs @@ -0,0 +1,129 @@ +// The plane's own record: one JSON file under the data dir holding accounts, workspaces and +// instance metadata. The management plane owns this file alone — an instance's own data stays on +// its volume (#3113): what lives here is what the plane needs to find and to steer an instance. +// +// The write path is the one `core/src/host/private-files.js` uses: a temp file next to the +// target, renamed over, with the mode named in the code (0600 file, 0700 dir) instead of +// inherited from whoever started the process. `version` sits at the top so a later migration can +// tell what it is reading before it reads it. +import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from 'node:fs' +import { randomUUID } from 'node:crypto' +import { join } from 'node:path' +import { hash, mintControlToken } from './credentials.mjs' + +export const PRIVATE_FILE_MODE = 0o600 +export const PRIVATE_DIR_MODE = 0o700 +const STORE_VERSION = 1 + +// A name is unique inside one workspace, not on the whole plane: two owners may each have a +// "main" (#3113). The store is the only place this rule lives, so the HTTP route cannot widen it. +export class DuplicateInstanceError extends Error { + constructor(workspaceId, name) { + super(`an instance named ${JSON.stringify(name)} already exists in workspace ${workspaceId}`) + this.name = 'DuplicateInstanceError' + this.workspaceId = workspaceId + this.instanceName = name + } +} + +export class UnknownInstanceError extends Error { + constructor(id) { + super(`no instance ${id}`) + this.name = 'UnknownInstanceError' + this.instanceId = id + } +} + +const emptyStore = () => ({ version: STORE_VERSION, accounts: [], workspaces: [], instances: [] }) + +const byId = (list, id) => list.find(entry => entry.id === id) + +function readStoreFile(path) { + if (!existsSync(path)) return emptyStore() + try { + const parsed = JSON.parse(readFileSync(path, 'utf8')) + if (parsed.version !== STORE_VERSION) { + throw new Error(`plane.json version ${parsed.version} is not ${STORE_VERSION} — migrations are not written yet`) + } + return parsed + } catch (err) { + if (err instanceof SyntaxError) throw new Error(`plane.json at ${path} is not valid JSON: ${err.message}`) + throw err + } +} + +export function openStore(dataDir) { + mkdirSync(dataDir, { recursive: true, mode: PRIVATE_DIR_MODE }) + try { chmodSync(dataDir, PRIVATE_DIR_MODE) } catch { /* the file modes below still hold */ } + const path = join(dataDir, 'plane.json') + let data = readStoreFile(path) + + const persist = () => { + const temp = `${path}.tmp-${process.pid}-${Date.now()}` + const mode = existsSync(path) ? statSync(path).mode & 0o777 : PRIVATE_FILE_MODE + writeFileSync(temp, `${JSON.stringify(data, null, 2)}\n`, { encoding: 'utf8', mode }) + chmodSync(temp, mode) + renameSync(temp, path) + } + + const store = { + get path() { return path }, + persist, + createAccount({ name }) { + const account = { id: `ac_${randomUUID().replaceAll('-', '')}`, name, operatorTokenHashes: [], createdAt: Date.now() } + data.accounts.push(account) + persist() + return account + }, + findAccount(id) { return byId(data.accounts, id) ?? null }, + accounts() { return data.accounts.slice() }, + createWorkspace({ accountId, name }) { + if (!byId(data.accounts, accountId)) throw new Error(`no account ${accountId}`) + const workspace = { id: `ws_${randomUUID().replaceAll('-', '')}`, accountId, name, createdAt: Date.now() } + data.workspaces.push(workspace) + persist() + return workspace + }, + findWorkspace(id) { return byId(data.workspaces, id) ?? null }, + // The control token is minted here and returned once: only its sha256 is kept, so the record + // can verify a caller but cannot re-tell the secret (#3113). + createInstance({ workspaceId, name }) { + const workspace = byId(data.workspaces, workspaceId) + if (!workspace) throw new Error(`no workspace ${workspaceId}`) + if (data.instances.some(i => i.workspaceId === workspaceId && i.name === name)) { + throw new DuplicateInstanceError(workspaceId, name) + } + const { token, digest } = mintControlToken() + const instance = { + id: `in_${randomUUID().replaceAll('-', '')}`, + workspaceId, + ownerId: workspace.accountId, + name, + state: 'stopped', + health: 'unknown', + port: 3090 + (data.instances.length % 900), + controlTokenHash: digest, + createdAt: Date.now(), + } + data.instances.push(instance) + persist() + return { instance, controlToken: token } + }, + getInstance(id) { + const instance = byId(data.instances, id) + if (!instance) throw new UnknownInstanceError(id) + return instance + }, + findInstance(id) { return byId(data.instances, id) ?? null }, + listInstances({ ownerId } = {}) { + return data.instances.filter(i => ownerId === undefined || i.ownerId === ownerId) + }, + updateInstance(id, patch) { + const instance = store.getInstance(id) + Object.assign(instance, patch) + persist() + return instance + }, + } + return store +} diff --git a/plane/test/compose-backend.test.js b/plane/test/compose-backend.test.js new file mode 100644 index 000000000..d024e91b3 --- /dev/null +++ b/plane/test/compose-backend.test.js @@ -0,0 +1,73 @@ +// #3113 red-first, compose backend: the first lifecycle backend only *materializes* an instance's +// compose project — `instances//compose.yaml` plus a 0600 `control.env` — and never runs +// docker. The compose file stays honest with the repo's own compose.yaml (host networking, a +// loopback FLYBOT_PORT), carries no credential in it, and writing it twice changes nothing. +import assert from 'node:assert/strict' +import { mkdtempSync, readFileSync, rmSync, statSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { test } from 'node:test' +import { ComposeBackend, MemoryBackend } from '../src/lifecycle.mjs' +import { openStore } from '../src/store.mjs' + +function seeded() { + const dir = mkdtempSync(join(tmpdir(), 'plane-comp-')) + const store = openStore(join(dir, 'data')) + const account = store.createAccount({ name: 'alice' }) + const ws = store.createWorkspace({ accountId: account.id, name: 'w' }) + const { instance, controlToken } = store.createInstance({ workspaceId: ws.id, name: 'main' }) + return { dir, store, account, instance, controlToken } +} + +test('materialize writes flybot- on host networking with a loopback FLYBOT_PORT', async () => { + const s = seeded() + try { + const calls = [] + const backend = new ComposeBackend({ root: s.dir, runner: (...args) => calls.push(args) }) + const out = backend.materialize(s.instance, { controlToken: s.controlToken }) + const yaml = readFileSync(join(out.dir, 'compose.yaml'), 'utf8') + assert.match(yaml, new RegExp(`name: flybot-${s.instance.id}`)) + assert.match(yaml, /network_mode: host/) + const port = Number(yaml.match(/FLYBOT_PORT[=: ]+(\d{3,5})/)[1]) + assert.ok(port >= 3090 && port < 4000, `port ${port} is outside the loopback range this plane allocates`) + assert.equal(calls.length, 0) + } finally { + rmSync(s.dir, { recursive: true, force: true }) + } +}) + +test('no control plaintext in compose.yaml — the credential lives only in 0600 control.env', async () => { + const s = seeded() + try { + const backend = new ComposeBackend({ root: s.dir }) + const out = backend.materialize(s.instance, { controlToken: s.controlToken }) + const yaml = readFileSync(join(out.dir, 'compose.yaml'), 'utf8') + assert.ok(!yaml.includes(s.controlToken), 'control plaintext leaked into compose.yaml') + const env = readFileSync(join(out.dir, 'control.env'), 'utf8') + assert.ok(env.includes(s.controlToken)) + const mode = statSync(join(out.dir, 'control.env')).mode & 0o777 + assert.equal(mode, 0o600) + } finally { + rmSync(s.dir, { recursive: true, force: true }) + } +}) + +test('materialize is idempotent, and the backend never spawns a runner on start or stop either', async () => { + const s = seeded() + try { + const calls = [] + const backend = new ComposeBackend({ root: s.dir, runner: (...args) => calls.push(args) }) + const first = backend.materialize(s.instance, { controlToken: s.controlToken }) + const before = readFileSync(join(first.dir, 'compose.yaml'), 'utf8') + const second = backend.materialize(s.instance, { controlToken: s.controlToken }) + assert.equal(second.dir, first.dir) + assert.equal(readFileSync(join(second.dir, 'compose.yaml'), 'utf8'), before) + assert.equal(calls.length, 0) + // The MemoryBackend sibling keeps the same contract shape for tests that need no files. + const memory = new MemoryBackend() + assert.equal(memory.start(s.instance).state, 'running') + assert.equal(calls.length, 0) + } finally { + rmSync(s.dir, { recursive: true, force: true }) + } +}) diff --git a/plane/test/create.test.js b/plane/test/create.test.js new file mode 100644 index 000000000..6b0d653fb --- /dev/null +++ b/plane/test/create.test.js @@ -0,0 +1,91 @@ +// #3113 red-first, creation: a name is unique inside one workspace, not on the whole plane, the +// record survives a reopen, and a request without `name` or `workspaceId` is a 400 rather than an +// instance with holes in it. Case 5 drives the same rule through the store (`DuplicateInstanceError`) +// and through the HTTP route (409), so the route cannot silently widen what the store refuses. +import assert from 'node:assert/strict' +import { mkdtempSync, readFileSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { test } from 'node:test' +import { MemoryBackend } from '../src/lifecycle.mjs' +import { mintOperatorToken } from '../src/credentials.mjs' +import { DuplicateInstanceError, openStore } from '../src/store.mjs' +import { handle } from '../src/server.mjs' +import { createPlane } from '../index.js' + +const auth = token => ({ authorization: `Bearer ${token}` }) + +function oneWorkspace() { + const dir = mkdtempSync(join(tmpdir(), 'plane-create-')) + const dataDir = join(dir, 'data') + const store = openStore(dataDir) + const account = store.createAccount({ name: 'alice' }) + const ws = store.createWorkspace({ accountId: account.id, name: 'w' }) + return { dir, dataDir, store, account, ws, token: mintOperatorToken(store, account.id).token } +} + +test('the same (workspaceId, name) is refused twice: DuplicateInstanceError from the store, 409 from the route', async () => { + const s = oneWorkspace() + try { + store_first: { + s.store.createInstance({ workspaceId: s.ws.id, name: 'dup' }) + assert.throws(() => s.store.createInstance({ workspaceId: s.ws.id, name: 'dup' }), DuplicateInstanceError) + } + route_second: { + // The store-level pair above already exists, so the route sees a duplicate too. + const res = handle({ method: 'POST', path: '/api/instances', headers: auth(s.token), body: { workspaceId: s.ws.id, name: 'dup' } }, { store: s.store, backend: new MemoryBackend() }) + assert.equal(res.status, 409) + } + } finally { + rmSync(s.dir, { recursive: true, force: true }) + } +}) + +test('two owners may each use the same name — the uniqueness is per workspace, not global', async () => { + const s = oneWorkspace() + try { + const other = s.store.createAccount({ name: 'bob' }) + const otherWs = s.store.createWorkspace({ accountId: other.id, name: 'w' }) + const mine = s.store.createInstance({ workspaceId: s.ws.id, name: 'same-name' }) + const theirs = s.store.createInstance({ workspaceId: otherWs.id, name: 'same-name' }) + assert.notEqual(mine.instance.id, theirs.instance.id) + assert.equal(mine.instance.ownerId, s.account.id) + assert.equal(theirs.instance.ownerId, other.id) + } finally { + rmSync(s.dir, { recursive: true, force: true }) + } +}) + +test('a reopened store still reads the instance metadata — plane.json is the record, not the memory', async () => { + const s = oneWorkspace() + try { + const { instance } = s.store.createInstance({ workspaceId: s.ws.id, name: 'kept' }) + s.store.updateInstance(instance.id, { state: 'running', health: 'ok' }) + const again = openStore(s.dataDir) + const read = again.getInstance(instance.id) + assert.equal(read.name, 'kept') + assert.equal(read.state, 'running') + assert.equal(read.health, 'ok') + assert.ok(read.createdAt > 0) + // and the same through the public plane face + const plane = createPlane({ dataDir: s.dataDir, backend: new MemoryBackend() }) + const got = await plane.getInstance(instance.id) + assert.equal(got.name, 'kept') + } finally { + rmSync(s.dir, { recursive: true, force: true }) + } +}) + +test('a create without name or without workspaceId answers 400, and nothing is stored', async () => { + const s = oneWorkspace() + try { + const noName = handle({ method: 'POST', path: '/api/instances', headers: auth(s.token), body: { workspaceId: s.ws.id } }, { store: s.store, backend: new MemoryBackend() }) + assert.equal(noName.status, 400) + const noWs = handle({ method: 'POST', path: '/api/instances', headers: auth(s.token), body: { name: 'orphan' } }, { store: s.store, backend: new MemoryBackend() }) + assert.equal(noWs.status, 400) + assert.equal(s.store.listInstances({ ownerId: s.account.id }).length, 0) + assert.doesNotThrow(() => readFileSync(join(s.dataDir, 'plane.json'), 'utf8')) + } finally { + rmSync(s.dir, { recursive: true, force: true }) + } +}) diff --git a/plane/test/credentials.test.js b/plane/test/credentials.test.js new file mode 100644 index 000000000..9279503ca --- /dev/null +++ b/plane/test/credentials.test.js @@ -0,0 +1,75 @@ +// #3113 red-first, credentials: two token families that must never open each other's door. The +// operator token speaks to `/api/*`; the control token is what a FlyBot instance would check on +// a management call. Only sha256 sums are persisted — the plaintext exists once, at mint time — +// and every instance gets its own control token, so one leaked key is one instance, not the fleet. +import assert from 'node:assert/strict' +import { mkdtempSync, readFileSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { test } from 'node:test' +import { MemoryBackend } from '../src/lifecycle.mjs' +import { mintControlToken, mintOperatorToken, verifyControl, verifyOperator } from '../src/credentials.mjs' +import { openStore } from '../src/store.mjs' +import { handle } from '../src/server.mjs' + +const auth = token => ({ authorization: `Bearer ${token}` }) + +function seeded() { + const dir = mkdtempSync(join(tmpdir(), 'plane-cred-')) + const dataDir = join(dir, 'data') + const store = openStore(dataDir) + const account = store.createAccount({ name: 'alice' }) + const ws = store.createWorkspace({ accountId: account.id, name: 'w' }) + const first = store.createInstance({ workspaceId: ws.id, name: 'one' }) + const second = store.createInstance({ workspaceId: ws.id, name: 'two' }) + const token = mintOperatorToken(store, account.id).token + return { dir, dataDir, store, account, ws, first, second, token } +} + +test('a control token does not open the operator door: /api/* answers 401', async () => { + const s = seeded() + try { + const res = handle({ method: 'GET', path: '/api/instances', headers: auth(s.first.controlToken), body: {} }, { store: s.store, backend: new MemoryBackend() }) + assert.equal(res.status, 401) + } finally { + rmSync(s.dir, { recursive: true, force: true }) + } +}) + +test('an operator token is not a control credential either — the door holds from both sides', async () => { + const s = seeded() + try { + assert.equal(verifyControl(s.first.instance, `Bearer ${s.token}`), false) + assert.equal(verifyControl(s.first.instance, `Bearer ${s.first.controlToken}`), true) + assert.equal(verifyOperator(s.store, `Bearer ${s.first.controlToken}`), null) + assert.equal(verifyOperator(s.store, `Bearer ${s.token}`).accountId, s.account.id) + } finally { + rmSync(s.dir, { recursive: true, force: true }) + } +}) + +test('plane.json holds hashes, never plaintext: no op_ or ctl_ string survives the save', async () => { + const s = seeded() + try { + const text = readFileSync(join(s.dataDir, 'plane.json'), 'utf8') + assert.ok(!/op_[0-9a-f]{32}/.test(text), 'operator plaintext leaked into plane.json') + assert.ok(!/ctl_[0-9a-f]{32}/.test(text), 'control plaintext leaked into plane.json') + assert.ok(/[0-9a-f]{64}/.test(text), 'no sha256 hash stored at all') + } finally { + rmSync(s.dir, { recursive: true, force: true }) + } +}) + +test('two instances carry different control tokens — one key is one instance, not the fleet', async () => { + const s = seeded() + try { + assert.notEqual(s.first.controlToken, s.second.controlToken) + assert.notEqual(s.first.instance.controlTokenHash, s.second.instance.controlTokenHash) + assert.equal(verifyControl(s.first.instance, `Bearer ${s.second.controlToken}`), false) + const fresh = mintControlToken() + assert.match(fresh.token, /^ctl_[0-9a-f]{32}$/) + assert.match(s.token, /^op_[0-9a-f]{32}$/) + } finally { + rmSync(s.dir, { recursive: true, force: true }) + } +}) diff --git a/plane/test/lifecycle.test.js b/plane/test/lifecycle.test.js new file mode 100644 index 000000000..b2b2c1b8b --- /dev/null +++ b/plane/test/lifecycle.test.js @@ -0,0 +1,96 @@ +// #3113 red-first, lifecycle: create → start → query → stop → start again is the loop this slice +// exists for. State lives in the store, so a "process restart" (a fresh handle reading the same +// data dir) still sees `stopped` — nothing silently flips back to running. `upgrade` and +// `recycle` are part of the backend contract on purpose, and refusing them loudly beats a silent +// success that pretends the second slice already shipped. +import assert from 'node:assert/strict' +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { test } from 'node:test' +import { MemoryBackend, NotImplementedError } from '../src/lifecycle.mjs' +import { mintOperatorToken } from '../src/credentials.mjs' +import { openStore } from '../src/store.mjs' +import { handle } from '../src/server.mjs' +import { createPlane } from '../index.js' + +const auth = token => ({ authorization: `Bearer ${token}` }) + +function seeded() { + const dir = mkdtempSync(join(tmpdir(), 'plane-life-')) + const dataDir = join(dir, 'data') + const store = openStore(dataDir) + const account = store.createAccount({ name: 'alice' }) + const ws = store.createWorkspace({ accountId: account.id, name: 'w' }) + const { instance } = store.createInstance({ workspaceId: ws.id, name: 'main' }) + const token = mintOperatorToken(store, account.id).token + return { dir, dataDir, store, account, instance, token } +} + +test('start reports running and healthy, through the route and the plane face', async () => { + const s = seeded() + try { + const res = handle({ method: 'POST', path: `/api/instances/${s.instance.id}/start`, headers: auth(s.token), body: {} }, { store: s.store, backend: new MemoryBackend() }) + assert.equal(res.status, 200) + assert.equal(res.body.instance.state, 'running') + assert.equal(res.body.instance.health, 'ok') + const plane = createPlane({ dataDir: s.dataDir, backend: new MemoryBackend() }) + const started = await plane.startInstance(s.instance.id) + assert.equal(started.state, 'running') + } finally { + rmSync(s.dir, { recursive: true, force: true }) + } +}) + +test('stop persists: a fresh reader of the same data dir still sees stopped', async () => { + const s = seeded() + try { + const plane = createPlane({ dataDir: s.dataDir, backend: new MemoryBackend() }) + await plane.startInstance(s.instance.id) + await plane.stopInstance(s.instance.id) + const reopened = handle({ method: 'GET', path: `/api/instances/${s.instance.id}`, headers: auth(s.token), body: {} }, { store: openStore(s.dataDir), backend: new MemoryBackend() }) + assert.equal(reopened.status, 200) + assert.equal(reopened.body.instance.state, 'stopped') + } finally { + rmSync(s.dir, { recursive: true, force: true }) + } +}) + +test('stop then start runs again — the core loop of this slice', async () => { + const s = seeded() + try { + const plane = createPlane({ dataDir: s.dataDir, backend: new MemoryBackend() }) + await plane.startInstance(s.instance.id) + const stopped = await plane.stopInstance(s.instance.id) + assert.equal(stopped.state, 'stopped') + const again = await plane.startInstance(s.instance.id) + assert.equal(again.state, 'running') + assert.equal(again.health, 'ok') + } finally { + rmSync(s.dir, { recursive: true, force: true }) + } +}) + +test('an unknown instance id answers 404', async () => { + const s = seeded() + try { + const res = handle({ method: 'GET', path: '/api/instances/in_ffffffffffffffffffffffff', headers: auth(s.token), body: {} }, { store: s.store, backend: new MemoryBackend() }) + assert.equal(res.status, 404) + } finally { + rmSync(s.dir, { recursive: true, force: true }) + } +}) + +test('upgrade and recycle refuse with NotImplementedError — the contract exists, the work does not', async () => { + const s = seeded() + try { + const backend = new MemoryBackend() + assert.throws(() => backend.upgrade(s.instance), NotImplementedError) + assert.throws(() => backend.recycle(s.instance), NotImplementedError) + const plane = createPlane({ dataDir: s.dataDir, backend }) + await assert.rejects(() => plane.upgradeInstance(s.instance.id), NotImplementedError) + await assert.rejects(() => plane.recycleInstance(s.instance.id), NotImplementedError) + } finally { + rmSync(s.dir, { recursive: true, force: true }) + } +}) diff --git a/plane/test/ownership.test.js b/plane/test/ownership.test.js new file mode 100644 index 000000000..b1dccc7fe --- /dev/null +++ b/plane/test/ownership.test.js @@ -0,0 +1,81 @@ +// #3113 red-first, ownership: an operator token only reaches its own instances. Every instance +// route asks `verifyOperator` first, then compares `instance.ownerId` with the token's account, +// so account A never reads or stops account B's instance, and a stranger without a token is +// refused before any route runs. The store persists to a real temp dir, so these cases read the +// very bytes the seeding wrote. +import assert from 'node:assert/strict' +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { test } from 'node:test' +import { MemoryBackend } from '../src/lifecycle.mjs' +import { mintOperatorToken } from '../src/credentials.mjs' +import { openStore } from '../src/store.mjs' +import { handle } from '../src/server.mjs' + +async function seed() { + const dir = mkdtempSync(join(tmpdir(), 'plane-own-')) + const store = openStore(join(dir, 'data')) + const backend = new MemoryBackend() + const alice = store.createAccount({ name: 'alice' }) + const bob = store.createAccount({ name: 'bob' }) + const wsA = store.createWorkspace({ accountId: alice.id, name: 'w' }) + const wsB = store.createWorkspace({ accountId: bob.id, name: 'w' }) + const a = store.createInstance({ workspaceId: wsA.id, name: 'a' }).instance + const b = store.createInstance({ workspaceId: wsB.id, name: 'b' }).instance + const aliceToken = mintOperatorToken(store, alice.id).token + const bobToken = mintOperatorToken(store, bob.id).token + store.updateInstance(b.id, { state: 'running', health: 'ok' }) + return { dir, store, backend, alice, bob, a, b, aliceToken, bobToken } +} + +const auth = token => ({ authorization: `Bearer ${token}` }) + +test('another operator token reads a foreign instance as 403, and the instance is untouched', async () => { + const s = await seed() + try { + const res = handle({ method: 'GET', path: `/api/instances/${s.b.id}`, headers: auth(s.aliceToken), body: {} }, { store: s.store, backend: s.backend }) + assert.equal(res.status, 403) + const again = handle({ method: 'GET', path: `/api/instances/${s.b.id}`, headers: auth(s.bobToken), body: {} }, { store: s.store, backend: s.backend }) + assert.equal(again.status, 200) + assert.equal(again.body.instance.state, 'running') + } finally { + rmSync(s.dir, { recursive: true, force: true }) + } +}) + +test('another operator token stops a foreign instance as 403, and it stays running', async () => { + const s = await seed() + try { + const res = handle({ method: 'POST', path: `/api/instances/${s.b.id}/stop`, headers: auth(s.aliceToken), body: {} }, { store: s.store, backend: s.backend }) + assert.equal(res.status, 403) + const again = handle({ method: 'GET', path: `/api/instances/${s.b.id}`, headers: auth(s.bobToken), body: {} }, { store: s.store, backend: s.backend }) + assert.equal(again.body.instance.state, 'running') + } finally { + rmSync(s.dir, { recursive: true, force: true }) + } +}) + +test('no Authorization header is 401, and so is a forged op_ token', async () => { + const s = await seed() + try { + const anon = handle({ method: 'GET', path: `/api/instances/${s.b.id}`, headers: {}, body: {} }, { store: s.store, backend: s.backend }) + assert.equal(anon.status, 401) + const forged = handle({ method: 'GET', path: `/api/instances/${s.b.id}`, headers: auth('op_00000000000000000000000000000000'), body: {} }, { store: s.store, backend: s.backend }) + assert.equal(forged.status, 401) + } finally { + rmSync(s.dir, { recursive: true, force: true }) + } +}) + +test('GET /api/instances lists only the caller\'s own instances', async () => { + const s = await seed() + try { + const res = handle({ method: 'GET', path: '/api/instances', headers: auth(s.aliceToken), body: {} }, { store: s.store, backend: s.backend }) + assert.equal(res.status, 200) + assert.equal(res.body.instances.length, 1) + assert.equal(res.body.instances[0].id, s.a.id) + } finally { + rmSync(s.dir, { recursive: true, force: true }) + } +})