diff --git a/.github/actions/flybot-tests/action.yml b/.github/actions/flybot-tests/action.yml index 6a1e39431..dff32d559 100644 --- a/.github/actions/flybot-tests/action.yml +++ b/.github/actions/flybot-tests/action.yml @@ -86,6 +86,10 @@ runs: shell: bash working-directory: core run: npm test + - name: Plane tests + 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..63df145aa 100644 --- a/docs/subsystems/README.md +++ b/docs/subsystems/README.md @@ -14,6 +14,7 @@ Detail pages for each FlyBot subsystem. Each page lists `owned_paths`, what the | project | [project.md](project.md) | `plugins/project/` | | social | [social.md](social.md) | `plugins/social/` | | install | [install.md](install.md) | `core/scripts/`, arch-doc tests, `plugins/README.md`, the container image (`Dockerfile`, `compose.yaml`, `docker/`) | +| plane | [plane.md](plane.md) | `plane/` — management-plane skeleton (metadata, split credentials, lifecycle contract, compose materialization; not in the image) | | 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 | | live-e2e | [live-e2e.md](live-e2e.md) | `dev/live-e2e/`, `scripts/lint-live-e2e.mjs` — real-model browser suite (#204) | diff --git a/docs/subsystems/plane.md b/docs/subsystems/plane.md new file mode 100644 index 000000000..28c47174e --- /dev/null +++ b/docs/subsystems/plane.md @@ -0,0 +1,50 @@ +--- +subsystem: plane +owned_paths: + - plane/ +--- + +# plane (management-plane skeleton) + +The first slice of the management server for self-hosted FlyBot (#3113, parent #3110): accounts, +workspaces and instance metadata, the two separated credentials, the create/start/stop/restart +lifecycle, and an abstract lifecycle backend with one compose materializer. It is a skeleton on +purpose: no container is started in this slice. + +## Owns + +- `plane/`: the `@flybot/plane` package — store, credentials, lifecycle contract, HTTP router, + CLI, tests and its README. The three replaceable working defaults (granularity, storage, + backend) are at the top of [plane/README.md](../../plane/README.md). + +## Does not own + +- The FlyBot runtime inside the instance (Agent, sessions, memory, scheduling) — that stays + `core/` and the plugins. +- The shipped image, `Dockerfile`, `compose.yaml`, `docker/` and the pack whitelist — this + package is not in the image and not in `docker/profile.mjs`'s bundles. +- Cross-instance social traffic — Bot Social and `plugins/social`; the plane will configure an + instance's connection later, not carry messages. +- Upgrade, recycle, backup and recovery implementation — present only as `NotImplementedError` + on the lifecycle contract. + +## Invariants + +- The plane never runs an Agent. It records an instance, and a `LifecycleBackend` decides where + it runs; the first backend writes a compose project and starts nothing. +- Two credentials never interchange: `op_` is accepted on `/api/*` only, `ctl_` is what the + plane hands an instance. Only sha256 is persisted, and comparison is timing-safe. +- Every instance route checks the operator token first, then `instance.ownerId === + token.accountId`; a mismatch is `403`, an unknown id is `404`, no token is `401`. +- `(workspaceId, name)` is unique inside an owner's workspace, never globally; a clash is + `DuplicateInstanceError` / HTTP 409. +- `plane.json` is written atomically (temporary file + rename), mode 0600, directory 0700, and + carries `version: 1` for migration. +- `upgrade` and `recycle` fail loudly (`NotImplementedError`) instead of pretending to succeed. + +## Tests and gates + +`npm --prefix plane test` (20 cases) runs in the L1 `plane` suite registered in +[`docs/testing-layers.json`](../testing-layers.json) and in the `Plane tests` step of +[`.github/actions/flybot-tests/action.yml`](../../.github/actions/flybot-tests/action.yml). Root +`npm run verify` includes it. The suite needs no Docker, network, socket or model. diff --git a/docs/testing-layers.json b/docs/testing-layers.json index beabaac0b..29e2406d9 100644 --- a/docs/testing-layers.json +++ b/docs/testing-layers.json @@ -82,6 +82,15 @@ "command": "npm --prefix plugins/workflow test", "note": "Peer plugin; its CI job also runs the plugin lint and fails a skipped test." }, + { + "id": "plane", + "layer": "L1", + "paths": [ + "plane/test/**/*.test.js" + ], + "command": "npm --prefix plane test", + "note": "Management-plane skeleton: credential separation, ownership, create/start/stop, compose materialization; no network and no Docker." + }, { "id": "scripts", "layer": "L1", diff --git a/docs/testing-layers.md b/docs/testing-layers.md index 7463a20f7..e16de1b44 100644 --- a/docs/testing-layers.md +++ b/docs/testing-layers.md @@ -93,6 +93,7 @@ The tables below are generated: edit `docs/testing-layers.json`, then run | `plugins/project` | L1 | `plugins/project/test/**/*.test.js` | `npm --prefix plugins/project test` | | `plugins/timeline` | L1 | `plugins/timeline/test/**/*.test.js` | `npm --prefix plugins/timeline test` | | `plugins/workflow` | L1 | `plugins/workflow/test/**/*.test.js` | `npm --prefix plugins/workflow test` | +| `plane` | L1 | `plane/test/**/*.test.js` | `npm --prefix plane test` | | `scripts` | L1 | `.github/scripts/*.test.mjs`
`policy/*.test.mjs` | `node --test ".github/scripts/*.test.mjs" "policy/*.test.mjs"` | | `interop` | L1 | `dev/interop/**/*.test.mjs` | `npm run test:interop` | | `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/`. | 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..aeb8963b5 --- /dev/null +++ b/plane/README.md @@ -0,0 +1,76 @@ +# @flybot/plane — management-plane skeleton + +**Three working defaults, all replaceable — none of them is an owner decision (#3113):** + +1. **Granularity:** one FlyBot instance per **owner**, not per workspace or per Agent. The + issue's body suggested this as the closest thing to today's "one instance per person"; split + it further once the workspace product exists. +2. **Storage:** a single JSON document (`/plane.json`, `version: 1`) for accounts, + workspaces and instance metadata. It is in the data directory, not the Agent container's + volume, and the `version` field is there so a later slice can migrate it. No cloud database + is bound. +3. **Backend:** compose is only the **first** lifecycle path. `LifecycleBackend` is the + contract; `ComposeBackend` materializes a compose project and starts nothing. A cloud or + other orchestrator is another backend, not a rewrite. + +Everything below follows from those three; if the owner picks a different granularity, storage +or orchestrator, only the default changes. + +## What this first slice does + +- Records accounts, workspaces and instances (`plane/src/store.mjs`), atomically (temporary + file + rename), file mode 0600, directory mode 0700. +- Splits the two credentials (`plane/src/credentials.mjs`): `op_<32 hex>` operator tokens for + the API, `ctl_<32 hex>` instance control tokens. Only sha256 is stored; both are checked with + `timingSafeEqual`; `redact()` is for logs. Neither token type verifies as the other. +- Creates, starts, stops and restarts an instance (`index.js`), with per-owner uniqueness on + `(workspaceId, name)` and `DuplicateInstanceError` on a clash. +- Routes the HTTP surface as a pure function (`plane/src/server.mjs`): `POST/GET + /api/instances`, `GET /api/instances/:id`, `POST /api/instances/:id/{start,stop}`. Every + instance route checks the operator token first, then `instance.ownerId === token.accountId`. +- Materializes an instance's compose project (`plane/src/lifecycle.mjs`): `compose.yaml` plus + `control.env` (0600), loopback port, project `flybot-`. It does **not** run `docker + compose up`; `runner` is an unused injection point for the next slice. +- `upgrade` and `recycle` are on the contract and throw `NotImplementedError`. + +## API + +```js +import { createPlane, ComposeBackend } from '@flybot/plane' + +const plane = createPlane({ dataDir: '/var/lib/flybot/plane', backend: new ComposeBackend({ instancesDir: '/var/lib/flybot/plane/instances' }) }) +const instance = await plane.createInstance({ workspaceId: 'ws-1', name: 'main', ownerId: 'acct-1' }) +await plane.startInstance(instance.id) +await plane.stopInstance(instance.id) +``` + +`createInstance()` returns the instance and, exactly once, `controlToken`. `getInstance()` and +`listInstances()` never include the token or its hash. `createPlane` accepts `{ dataDir, +store, backend, clock }`; `clock` is injectable for deterministic tests. + +## CLI + +```sh +node plane/bin/plane.mjs token --data-dir /var/lib/flybot/plane [--account owner_local] +node plane/bin/plane.mjs serve --data-dir /var/lib/flybot/plane [--port 3090] +``` + +`token` prints the operator token once (only its sha256 is kept). `serve` binds +`127.0.0.1:` and answers `401` to an unauthenticated `GET /api/instances`. + +## Not in this slice + +No container is started, stopped or upgraded for real; no management UI; no public gateway; no +backup/recovery; no Bot Social wiring (the instance's social connection is a later package). The +package does not ship in the FlyBot image and is not registered in `docker/profile.mjs`'s +bundles. + +## Tests + +```sh +npm --prefix plane test +``` + +20 cases: ownership/403, 401, per-owner listing, duplicate creation (409), persistence, 400s, +start/stop/restart, unknown id (404), credential separation and storage, compose materialization, +idempotency and the zero-spawn guarantee. diff --git a/plane/bin/plane.mjs b/plane/bin/plane.mjs new file mode 100644 index 000000000..4243c0c7f --- /dev/null +++ b/plane/bin/plane.mjs @@ -0,0 +1,66 @@ +#!/usr/bin/env node +// Operator CLI. `token` is the one place a plaintext operator token is printed — once. +import { resolve } from 'node:path' +import { join } from 'node:path' +import { openStore } from '../src/store.mjs' +import { mintOperatorToken } from '../src/credentials.mjs' +import { ComposeBackend } from '../src/lifecycle.mjs' +import { createPlane } from '../index.js' +import { serve } from '../src/server.mjs' + +const USAGE = `usage: + node plane/bin/plane.mjs token --data-dir [--account ] + node plane/bin/plane.mjs serve --data-dir [--port 3090] + +token mint an operator token (printed once; only its sha256 is stored) +serve run the management-plane API on 127.0.0.1:` + +function parseFlags(argv) { + const flags = {} + for (let i = 0; i < argv.length; i += 1) { + const arg = argv[i] + if (!arg.startsWith('--')) continue + const [key, inline] = arg.slice(2).split('=') + if (inline !== undefined) flags[key] = inline + else if (argv[i + 1] !== undefined && !argv[i + 1].startsWith('--')) flags[key] = argv[i + 1], (i += 1) + else flags[key] = true + } + return flags +} + +function dataDirFrom(flags) { + if (typeof flags['data-dir'] !== 'string' || flags['data-dir'] === '') { + console.error('plane: --data-dir is required') + process.exit(2) + } + return resolve(flags['data-dir']) +} + +const [command, ...rest] = process.argv.slice(2) +const flags = parseFlags(rest) + +if (command === 'token') { + const dataDir = dataDirFrom(flags) + const account = typeof flags.account === 'string' ? flags.account : 'owner_local' + const store = openStore(dataDir) + const token = mintOperatorToken(store, account) + // stdout only: this is the mint, not a log line. + console.log(`account: ${account}`) + console.log(`token: ${token}`) + console.error('plane: this token is shown once and is not recoverable; store it outside the repository.') +} else if (command === 'serve') { + const dataDir = dataDirFrom(flags) + const port = flags.port === undefined ? 3090 : Number(flags.port) + if (!Number.isInteger(port) || port < 1 || port > 65535) { + console.error('plane: --port must be an integer between 1 and 65535') + process.exit(2) + } + const store = openStore(dataDir) + const backend = new ComposeBackend({ instancesDir: join(dataDir, 'instances') }) + const plane = createPlane({ dataDir, store, backend }) + serve({ port, plane, store }) + console.log(`plane: listening on http://127.0.0.1:${port}`) +} else { + console.error(USAGE) + process.exit(2) +} diff --git a/plane/index.js b/plane/index.js new file mode 100644 index 000000000..4155948cd --- /dev/null +++ b/plane/index.js @@ -0,0 +1,103 @@ +// Public surface of @flybot/plane. +// +// const plane = createPlane({ dataDir, backend }) +// const instance = await plane.createInstance({ workspaceId, name, ownerId }) +// +// The plane owns metadata, ownership and credentials; a LifecycleBackend owns where the +// instance actually runs. This package starts no HTTP server and no container by itself — +// `server.mjs` is a pure router plus an opt-in node:http adapter, and the compose backend +// only writes files. +import { randomBytes } from 'node:crypto' +import { openStore, InstanceNotFoundError } from './src/store.mjs' +import { mintControlToken, hashToken } from './src/credentials.mjs' +import { MemoryBackend } from './src/lifecycle.mjs' + +export { DuplicateInstanceError, InstanceNotFoundError, openStore } from './src/store.mjs' +export { LifecycleBackend, MemoryBackend, ComposeBackend, NotImplementedError, hostPortFor } from './src/lifecycle.mjs' +export { + mintOperatorToken, + mintControlToken, + verifyOperator, + verifyControl, + hashToken, + redact, +} from './src/credentials.mjs' +export { handle, serve } from './src/server.mjs' + +function assertNonEmpty(value, field) { + if (typeof value !== 'string' || value.trim() === '') throw new TypeError(`${field} is required`) +} + +// The record the plane hands out: the control-token hash never leaves the store. +function publicRecord(record) { + if (!record) return null + const { controlTokenHash, ...rest } = record + return rest +} + +export function createPlane({ dataDir, store, backend = new MemoryBackend(), clock = () => Date.now() } = {}) { + const theStore = store ?? (dataDir ? openStore(dataDir) : null) + if (!theStore) throw new TypeError('createPlane needs a dataDir or a store') + const now = () => new Date(clock()).toISOString() + + function applyOutcome(id, outcome) { + const patch = { updatedAt: now() } + if (outcome?.state) patch.state = outcome.state + if (outcome?.health) patch.health = outcome.health + if (outcome?.hostPort !== undefined) patch.hostPort = outcome.hostPort + if (outcome?.composePath !== undefined) patch.composePath = outcome.composePath + return publicRecord(theStore.updateInstance(id, patch)) + } + + async function createInstance({ workspaceId, name, ownerId } = {}) { + assertNonEmpty(workspaceId, 'workspaceId') + assertNonEmpty(name, 'name') + assertNonEmpty(ownerId, 'ownerId') + + const createdAt = now() + theStore.ensureWorkspace({ id: workspaceId, ownerId, createdAt }) + + const controlToken = mintControlToken() + const record = { + id: `inst_${randomBytes(8).toString('hex')}`, + ownerId, + workspaceId, + name, + state: 'stopped', + health: 'unknown', + createdAt, + updatedAt: createdAt, + controlTokenHash: hashToken(controlToken), + } + theStore.insertInstance(record) + + const outcome = await backend.create(publicRecord(record), { controlToken }) + const instance = applyOutcome(record.id, outcome) + // The plaintext control token is returned exactly once, to the caller that created it. + return { ...instance, controlToken } + } + + async function startInstance(id) { + const record = theStore.getInstance(id) + if (!record) throw new InstanceNotFoundError(id) + const outcome = await backend.start(publicRecord(record)) + return applyOutcome(id, outcome) + } + + async function stopInstance(id) { + const record = theStore.getInstance(id) + if (!record) throw new InstanceNotFoundError(id) + const outcome = await backend.stop(publicRecord(record)) + return applyOutcome(id, outcome) + } + + function getInstance(id) { + return publicRecord(theStore.getInstance(id)) + } + + function listInstances(ownerId) { + return theStore.listInstances(ownerId).map(publicRecord) + } + + return { createInstance, startInstance, stopInstance, getInstance, listInstances } +} diff --git a/plane/package.json b/plane/package.json new file mode 100644 index 000000000..6efa14bd9 --- /dev/null +++ b/plane/package.json @@ -0,0 +1,18 @@ +{ + "name": "@flybot/plane", + "version": "0.0.0", + "private": true, + "description": "Management-plane skeleton: instance metadata, split credentials, an abstract lifecycle backend and a compose materializer. No runtime dependencies; does not ship in the FlyBot image.", + "type": "module", + "license": "Apache-2.0", + "main": "index.js", + "bin": { + "plane": "bin/plane.mjs" + }, + "engines": { + "node": ">=22" + }, + "scripts": { + "test": "node --test \"test/*.test.js\"" + } +} diff --git a/plane/src/credentials.mjs b/plane/src/credentials.mjs new file mode 100644 index 000000000..f0dae05be --- /dev/null +++ b/plane/src/credentials.mjs @@ -0,0 +1,72 @@ +// The two credentials of the management plane, and the only place either is minted or checked. +// +// op_<32 hex> operator token — what a person/agent uses against /api/* (account-scoped) +// ctl_<32 hex> instance control token — what the plane hands an instance, never accepted on /api/* +// +// Only the sha256 of either is stored; comparison is timing-safe. `redact()` is what logs use. +import { createHash, randomBytes, timingSafeEqual } from 'node:crypto' + +const OPERATOR_PREFIX = 'op_' +const CONTROL_PREFIX = 'ctl_' +const TOKEN_RE = /^(?:op|ctl)_[0-9a-f]{32}$/ + +export function mintOperatorToken(store, accountId) { + if (!store || typeof store.upsertAccount !== 'function') throw new TypeError('mintOperatorToken needs a store') + if (typeof accountId !== 'string' || accountId === '') throw new TypeError('mintOperatorToken needs an account id') + const token = `${OPERATOR_PREFIX}${randomBytes(16).toString('hex')}` + store.upsertAccount({ + id: accountId, + tokenHash: hashToken(token), + createdAt: new Date().toISOString(), + }) + return token +} + +export function mintControlToken() { + return `${CONTROL_PREFIX}${randomBytes(16).toString('hex')}` +} + +export function hashToken(token) { + return createHash('sha256').update(token).digest('hex') +} + +function digest(token) { + return createHash('sha256').update(token).digest() +} + +// Accepts `Bearer ` (HTTP) or the bare token (tests, internal calls). +export function bearerToken(header) { + if (typeof header !== 'string') return null + const match = header.match(/^\s*Bearer\s+(\S+)\s*$/i) + const token = match ? match[1] : header.trim() + return token === '' ? null : token +} + +export function verifyOperator(store, header) { + const token = bearerToken(header) + if (!token || !token.startsWith(OPERATOR_PREFIX) || !TOKEN_RE.test(token)) return null + const expected = digest(token) + let found = null + for (const account of store.listAccounts()) { + const stored = Buffer.from(account.tokenHash ?? '', 'hex') + if (stored.length === expected.length && timingSafeEqual(stored, expected)) found = account + } + return found +} + +export function verifyControl(instance, header) { + const token = bearerToken(header) + if (!token || !token.startsWith(CONTROL_PREFIX) || !TOKEN_RE.test(token)) return null + if (!instance || typeof instance.controlTokenHash !== 'string') return null + const stored = Buffer.from(instance.controlTokenHash, 'hex') + const expected = digest(token) + if (stored.length !== expected.length) return null + return timingSafeEqual(stored, expected) ? { id: instance.id } : null +} + +export function redact(token) { + if (typeof token !== 'string') return '' + if (token.startsWith(CONTROL_PREFIX)) return `${CONTROL_PREFIX}` + if (token.startsWith(OPERATOR_PREFIX)) return `${OPERATOR_PREFIX}` + return '' +} diff --git a/plane/src/lifecycle.mjs b/plane/src/lifecycle.mjs new file mode 100644 index 000000000..76f87be6b --- /dev/null +++ b/plane/src/lifecycle.mjs @@ -0,0 +1,152 @@ +// The lifecycle contract the plane calls, and the two first-slice backends. +// +// A backend owns *where* an instance runs; the plane owns the record, the owner check and +// the credentials. This slice never starts a real container: MemoryBackend is the test +// stand-in and ComposeBackend only materializes a compose project on disk. `upgrade` and +// `recycle` are part of the contract and fail loudly until a later slice implements them. +import { chmodSync, mkdirSync, writeFileSync } from 'node:fs' +import { join } from 'node:path' +import { createHash } from 'node:crypto' + +export class NotImplementedError extends Error { + constructor(operation) { + super(`${operation} is not implemented in the management-plane skeleton`) + this.name = 'NotImplementedError' + this.code = 'NOT_IMPLEMENTED' + this.operation = operation + } +} + +// `create/start/stop` resolve to `{ state, health }` where state is 'running' or 'stopped'. +export class LifecycleBackend { + async create() { + throw new NotImplementedError('create') + } + + async start() { + throw new NotImplementedError('start') + } + + async stop() { + throw new NotImplementedError('stop') + } + + async upgrade() { + throw new NotImplementedError('upgrade') + } + + async recycle() { + throw new NotImplementedError('recycle') + } +} + +// No process at all: the state machine the HTTP tests exercise. +export class MemoryBackend extends LifecycleBackend { + constructor() { + super() + this.calls = [] + } + + async create() { + this.calls.push('create') + return { state: 'stopped', health: 'unknown' } + } + + async start() { + this.calls.push('start') + return { state: 'running', health: 'ok' } + } + + async stop() { + this.calls.push('stop') + return { state: 'stopped', health: 'unknown' } + } +} + +const DEFAULT_PORT_START = 31000 +const DEFAULT_PORT_SPAN = 900 + +// Deterministic so materializing twice yields the same project. The next slice replaces +// this with real port allocation when a runner exists. +export function hostPortFor(id, { portStart = DEFAULT_PORT_START, portSpan = DEFAULT_PORT_SPAN } = {}) { + const hash = createHash('sha256').update(String(id)).digest() + return portStart + (hash.readUInt32BE(0) % portSpan) +} + +// Writes `instances//compose.yaml` and `instances//control.env` (0600). It does not +// run `docker compose up`: `runner` is the injection point a later slice will use, and this +// slice must never call it. +export class ComposeBackend extends LifecycleBackend { + constructor({ instancesDir, portStart = DEFAULT_PORT_START, portSpan = DEFAULT_PORT_SPAN, runner = null } = {}) { + super() + if (typeof instancesDir !== 'string' || instancesDir === '') { + throw new TypeError('ComposeBackend needs an instancesDir') + } + this.instancesDir = instancesDir + this.portStart = portStart + this.portSpan = portSpan + this.runner = runner + this.calls = [] + } + + async create(instance, { controlToken } = {}) { + this.calls.push('create') + const materialized = this.materialize(instance, { controlToken }) + return { state: 'stopped', health: 'unknown', hostPort: materialized.hostPort, composePath: materialized.composePath } + } + + // Recorded transitions only; no container is started in this slice. + async start() { + this.calls.push('start') + return { state: 'running', health: 'unknown' } + } + + async stop() { + this.calls.push('stop') + return { state: 'stopped', health: 'unknown' } + } + + materialize(instance, { controlToken } = {}) { + if (!instance || typeof instance.id !== 'string' || instance.id === '') { + throw new TypeError('materialize needs an instance with an id') + } + if (typeof controlToken !== 'string' || !/^ctl_[0-9a-f]{32}$/.test(controlToken)) { + throw new TypeError('materialize needs the instance control token') + } + const hostPort = hostPortFor(instance.id, { portStart: this.portStart, portSpan: this.portSpan }) + const dir = join(this.instancesDir, instance.id) + mkdirSync(dir, { recursive: true, mode: 0o700 }) + chmodSync(dir, 0o700) + + const controlPath = join(dir, 'control.env') + writeFileSync( + controlPath, + `FLYBOT_CONTROL_TOKEN=${controlToken}\nFLYBOT_INSTANCE_ID=${instance.id}\n`, + { mode: 0o600 }, + ) + chmodSync(controlPath, 0o600) + + const composePath = join(dir, 'compose.yaml') + const compose = [ + '# Generated by @flybot/plane — re-run materialize instead of editing this file.', + `name: flybot-${instance.id}`, + 'services:', + ' flybot:', + ' image: flybot:local', + ` container_name: flybot-${instance.id}`, + ' network_mode: host', + ' environment:', + ` FLYBOT_PORT: "${hostPort}"`, + ` FLYBOT_INSTANCE_ID: "${instance.id}"`, + ` FLYBOT_CONTROL_URL: "http://127.0.0.1:${hostPort}"`, + ' env_file:', + ' - control.env', + ' volumes:', + ' - ./data:/data', + ' restart: unless-stopped', + '', + ].join('\n') + writeFileSync(composePath, compose, { mode: 0o644 }) + return { composePath, controlPath, hostPort } + } +} diff --git a/plane/src/server.mjs b/plane/src/server.mjs new file mode 100644 index 000000000..1e6ab492a --- /dev/null +++ b/plane/src/server.mjs @@ -0,0 +1,100 @@ +// Pure router + an optional node:http adapter. +// +// `handle()` never listens on a socket, so the whole authorization surface is testable +// without ports. Every /api/* route verifies the operator token first; instance routes +// then compare `instance.ownerId === token.accountId` and answer 403 on mismatch. +import { createServer } from 'node:http' +import { createPlane } from '../index.js' +import { DuplicateInstanceError, openStore } from './store.mjs' +import { verifyOperator } from './credentials.mjs' + +const JSON_HEADERS = { 'content-type': 'application/json; charset=utf-8' } + +function reply(status, body) { + return { status, body, headers: JSON_HEADERS } +} + +function nonEmpty(value) { + return typeof value === 'string' && value.trim() !== '' +} + +function parseBody(body) { + if (body === undefined || body === null || body === '') return null + if (typeof body === 'object') return body + return JSON.parse(body) +} + +export async function handle(request, { plane, store } = {}) { + const method = String(request.method ?? 'GET').toUpperCase() + const path = String(request.path ?? '/').split('?')[0] + const headers = request.headers ?? {} + const authorization = headers.authorization ?? headers.Authorization ?? '' + + const account = verifyOperator(store, authorization) + if (!account) return reply(401, { error: 'unauthorized' }) + + if (path === '/api/instances') { + if (method === 'GET') return reply(200, { instances: plane.listInstances(account.id) }) + if (method !== 'POST') return reply(405, { error: 'method_not_allowed' }) + let body + try { + body = parseBody(request.body) + } catch { + return reply(400, { error: 'invalid_json' }) + } + if (!body || typeof body !== 'object') return reply(400, { error: 'invalid_request' }) + const { workspaceId, name } = body + if (!nonEmpty(workspaceId) || !nonEmpty(name)) return reply(400, { error: 'invalid_request' }) + try { + const created = await plane.createInstance({ workspaceId, name, ownerId: account.id }) + return reply(201, created) + } catch (error) { + if (error instanceof DuplicateInstanceError) return reply(409, { error: 'duplicate_instance' }) + throw error + } + } + + const match = path.match(/^\/api\/instances\/([^/]+)(?:\/(start|stop))?$/) + if (match) { + const id = decodeURIComponent(match[1]) + const action = match[2] + const instance = plane.getInstance(id) + if (!instance) return reply(404, { error: 'not_found' }) + if (instance.ownerId !== account.id) return reply(403, { error: 'forbidden' }) + + if (!action && method === 'GET') return reply(200, { instance }) + if (action === 'start' && method === 'POST') { + return reply(200, { instance: await plane.startInstance(id) }) + } + if (action === 'stop' && method === 'POST') { + return reply(200, { instance: await plane.stopInstance(id) }) + } + return reply(405, { error: 'method_not_allowed' }) + } + + return reply(404, { error: 'not_found' }) +} + +// Convenience for the CLI and tests. Accepts an already-built plane/store so a caller can +// keep one store instance; otherwise builds both from `dataDir`. +export function serve({ port = 3090, dataDir, backend, plane, store, clock } = {}) { + const theStore = store ?? (dataDir ? openStore(dataDir) : null) + const thePlane = plane ?? createPlane({ dataDir, store: theStore, backend, clock }) + if (!theStore) throw new TypeError('serve needs a store or a dataDir') + const server = createServer(async (req, res) => { + const chunks = [] + for await (const chunk of req) chunks.push(chunk) + const body = Buffer.concat(chunks).toString('utf8') + let answer + try { + answer = await handle({ method: req.method, path: req.url, headers: req.headers, body }, { plane: thePlane, store: theStore }) + } catch { + answer = reply(500, { error: 'internal_error' }) + } + res.writeHead(answer.status, answer.headers) + res.end(JSON.stringify(answer.body)) + }) + if (typeof port === 'number') server.listen(port, '127.0.0.1') + return server +} + diff --git a/plane/src/store.mjs b/plane/src/store.mjs new file mode 100644 index 000000000..b7e989703 --- /dev/null +++ b/plane/src/store.mjs @@ -0,0 +1,148 @@ +// Minimal persistent store for the management plane. +// +// One JSON document (`/plane.json`) with a `version` so a later slice can +// migrate it. Writes go through a temporary file in the same directory and a rename, +// so a crash leaves the previous document intact. The file is 0600 and the directory +// 0700 — the same private-file discipline as core/src/host/private-files.js. +import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs' +import { join } from 'node:path' +import { randomBytes } from 'node:crypto' + +export const STORE_VERSION = 1 + +export class DuplicateInstanceError extends Error { + constructor(workspaceId, name) { + super(`instance "${name}" already exists in workspace "${workspaceId}"`) + this.name = 'DuplicateInstanceError' + this.code = 'DUPLICATE_INSTANCE' + this.workspaceId = workspaceId + this.instanceName = name + } +} + +export class InstanceNotFoundError extends Error { + constructor(id) { + super(`no instance ${id}`) + this.name = 'InstanceNotFoundError' + this.code = 'INSTANCE_NOT_FOUND' + this.instanceId = id + } +} + +function emptyData() { + return { version: STORE_VERSION, accounts: [], workspaces: [], instances: [] } +} + +export class Store { + #dataDir + #file + #data + + constructor(dataDir) { + if (typeof dataDir !== 'string' || dataDir === '') throw new TypeError('openStore needs a data directory') + this.#dataDir = dataDir + this.#file = join(dataDir, 'plane.json') + this.#data = this.#read() + } + + get file() { + return this.#file + } + + get dataDir() { + return this.#dataDir + } + + #read() { + if (!existsSync(this.#file)) return emptyData() + const parsed = JSON.parse(readFileSync(this.#file, 'utf8')) + if (parsed.version !== STORE_VERSION) { + throw new Error(`unsupported plane.json version ${parsed.version}; expected ${STORE_VERSION}`) + } + parsed.accounts ??= [] + parsed.workspaces ??= [] + parsed.instances ??= [] + return parsed + } + + save() { + const existed = existsSync(this.#dataDir) + mkdirSync(this.#dataDir, { recursive: true, mode: 0o700 }) + if (!existed) chmodSync(this.#dataDir, 0o700) + const body = `${JSON.stringify(this.#data, null, 2)}\n` + const tmp = `${this.#file}.${process.pid}.${randomBytes(4).toString('hex')}.tmp` + writeFileSync(tmp, body, { mode: 0o600 }) + renameSync(tmp, this.#file) + chmodSync(this.#file, 0o600) + } + + listAccounts() { + return this.#data.accounts + } + + getAccount(id) { + return this.#data.accounts.find((account) => account.id === id) ?? null + } + + upsertAccount(account) { + const index = this.#data.accounts.findIndex((existing) => existing.id === account.id) + if (index >= 0) this.#data.accounts[index] = account + else this.#data.accounts.push(account) + this.save() + return account + } + + ensureWorkspace({ id, ownerId, createdAt }) { + let workspace = this.getWorkspace(id, ownerId) + if (!workspace) { + workspace = { id, ownerId, createdAt } + this.#data.workspaces.push(workspace) + this.save() + } + return workspace + } + + // Workspace ids are owner-scoped: two owners may each name a workspace "ws-1". + getWorkspace(id, ownerId) { + return ( + this.#data.workspaces.find( + (workspace) => workspace.id === id && (ownerId === undefined || workspace.ownerId === ownerId), + ) ?? null + ) + } + + listInstances(ownerId) { + return ownerId ? this.#data.instances.filter((instance) => instance.ownerId === ownerId) : this.#data.instances + } + + getInstance(id) { + return this.#data.instances.find((instance) => instance.id === id) ?? null + } + + insertInstance(instance) { + // Unique within an owner's workspace, not globally: two owners keep their own "main". + const clash = this.#data.instances.some( + (existing) => + existing.ownerId === instance.ownerId && + existing.workspaceId === instance.workspaceId && + existing.name === instance.name, + ) + if (clash) throw new DuplicateInstanceError(instance.workspaceId, instance.name) + this.#data.instances.push(instance) + this.save() + return instance + } + + updateInstance(id, patch) { + const instance = this.getInstance(id) + if (!instance) throw new InstanceNotFoundError(id) + Object.assign(instance, patch) + this.save() + return instance + } +} + +export function openStore(dataDir) { + return new Store(dataDir) +} + diff --git a/plane/test/compose-backend.test.js b/plane/test/compose-backend.test.js new file mode 100644 index 000000000..00ceaf747 --- /dev/null +++ b/plane/test/compose-backend.test.js @@ -0,0 +1,72 @@ +import test from 'node:test' +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 { createPlane } from '../index.js' +import { ComposeBackend } from '../src/lifecycle.mjs' +import { openStore } from '../src/store.mjs' + +function setup() { + const dataDir = mkdtempSync(join(tmpdir(), 'plane-compose-')) + const instancesDir = join(dataDir, 'instances') + const calls = [] + const backend = new ComposeBackend({ instancesDir, runner: (...args) => calls.push(args) }) + const store = openStore(dataDir) + const plane = createPlane({ dataDir, store, backend }) + const cleanup = () => rmSync(dataDir, { recursive: true, force: true }) + return { dataDir, instancesDir, backend, store, plane, calls, cleanup } +} + +test('materialize writes a compose project named flybot- on a loopback port', async () => { + const { instancesDir, plane, cleanup } = setup() + try { + const created = await plane.createInstance({ workspaceId: 'ws-1', name: 'main', ownerId: 'acct-a' }) + const composePath = join(instancesDir, created.id, 'compose.yaml') + const text = readFileSync(composePath, 'utf8') + assert.match(text, new RegExp(`^name: flybot-${created.id}$`, 'm')) + assert.match(text, /network_mode: host/m) + const port = Number(text.match(/FLYBOT_PORT: "(\d+)"/)[1]) + assert.ok(port >= 31000 && port <= 31999, `expected a loopback-range port, got ${port}`) + assert.equal(created.hostPort, port) + } finally { + cleanup() + } +}) + +test('the control token lives only in control.env (0600), never in compose.yaml', async () => { + const { instancesDir, plane, cleanup } = setup() + try { + const created = await plane.createInstance({ workspaceId: 'ws-1', name: 'main', ownerId: 'acct-a' }) + const dir = join(instancesDir, created.id) + const compose = readFileSync(join(dir, 'compose.yaml'), 'utf8') + assert.ok(!compose.includes(created.controlToken)) + assert.match(compose, /env_file:\n\s+- control\.env/) + const control = readFileSync(join(dir, 'control.env'), 'utf8') + assert.ok(control.includes(`FLYBOT_CONTROL_TOKEN=${created.controlToken}`)) + assert.equal(statSync(join(dir, 'control.env')).mode & 0o777, 0o600) + } finally { + cleanup() + } +}) + +test('materialize is idempotent and never spawns a container (runner call count 0)', async () => { + const { instancesDir, backend, plane, calls, cleanup } = setup() + try { + const created = await plane.createInstance({ workspaceId: 'ws-1', name: 'main', ownerId: 'acct-a' }) + const dir = join(instancesDir, created.id) + const record = plane.getInstance(created.id) + const first = backend.materialize(record, { controlToken: created.controlToken }) + const firstCompose = readFileSync(join(dir, 'compose.yaml'), 'utf8') + const second = backend.materialize(record, { controlToken: created.controlToken }) + const secondCompose = readFileSync(join(dir, 'compose.yaml'), 'utf8') + assert.equal(firstCompose, secondCompose) + assert.deepEqual(second, first) + + await plane.startInstance(created.id) + await plane.stopInstance(created.id) + assert.equal(calls.length, 0, 'this slice must not spawn docker compose') + } finally { + cleanup() + } +}) diff --git a/plane/test/create.test.js b/plane/test/create.test.js new file mode 100644 index 000000000..5ddb18ceb --- /dev/null +++ b/plane/test/create.test.js @@ -0,0 +1,89 @@ +import test from 'node:test' +import assert from 'node:assert/strict' +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { createPlane, DuplicateInstanceError } from '../index.js' +import { MemoryBackend } from '../src/lifecycle.mjs' +import { openStore } from '../src/store.mjs' +import { mintOperatorToken } from '../src/credentials.mjs' +import { handle } from '../src/server.mjs' + +function setup() { + const dataDir = mkdtempSync(join(tmpdir(), 'plane-create-')) + const store = openStore(dataDir) + const plane = createPlane({ dataDir, store, backend: new MemoryBackend() }) + const tokenA = mintOperatorToken(store, 'acct-a') + const tokenB = mintOperatorToken(store, 'acct-b') + const deps = { plane, store } + const cleanup = () => rmSync(dataDir, { recursive: true, force: true }) + return { dataDir, store, plane, tokenA, tokenB, deps, cleanup } +} + +test('the same workspace and name twice is a DuplicateInstanceError and HTTP 409', async () => { + const { plane, store, tokenA, cleanup } = setup() + try { + const first = await plane.createInstance({ workspaceId: 'ws-1', name: 'main', ownerId: 'acct-a' }) + assert.equal(first.workspaceId, 'ws-1') + await assert.rejects( + () => plane.createInstance({ workspaceId: 'ws-1', name: 'main', ownerId: 'acct-a' }), + { name: 'DuplicateInstanceError' }, + ) + assert.ok(new DuplicateInstanceError('ws-1', 'main') instanceof Error) + const res = await handle( + { method: 'POST', path: '/api/instances', headers: { authorization: `Bearer ${tokenA}` }, body: JSON.stringify({ workspaceId: 'ws-1', name: 'main' }) }, + { plane, store }, + ) + assert.equal(res.status, 409) + } finally { + cleanup() + } +}) + +test('two owners may each use the same workspace and name (per-owner uniqueness)', async () => { + const { plane, cleanup } = setup() + try { + const a = await plane.createInstance({ workspaceId: 'ws-shared', name: 'main', ownerId: 'acct-a' }) + const b = await plane.createInstance({ workspaceId: 'ws-shared', name: 'main', ownerId: 'acct-b' }) + assert.notEqual(a.id, b.id) + assert.equal(plane.listInstances('acct-a').length, 1) + assert.equal(plane.listInstances('acct-b').length, 1) + } finally { + cleanup() + } +}) + +test('instance metadata survives reopening the store', async () => { + const { dataDir, plane, cleanup } = setup() + try { + const created = await plane.createInstance({ workspaceId: 'ws-1', name: 'durable', ownerId: 'acct-a' }) + const reopened = openStore(dataDir) + const again = reopened.getInstance(created.id) + assert.ok(again) + assert.equal(again.name, 'durable') + assert.equal(again.ownerId, 'acct-a') + assert.equal(again.workspaceId, 'ws-1') + assert.equal(again.state, 'stopped') + assert.equal(reopened.getWorkspace('ws-1').ownerId, 'acct-a') + } finally { + cleanup() + } +}) + +test('creating without a name or a workspaceId is HTTP 400', async () => { + const { plane, store, tokenA, cleanup } = setup() + try { + const noName = await handle( + { method: 'POST', path: '/api/instances', headers: { authorization: `Bearer ${tokenA}` }, body: JSON.stringify({ workspaceId: 'ws-1' }) }, + { plane, store }, + ) + assert.equal(noName.status, 400) + const noWorkspace = await handle( + { method: 'POST', path: '/api/instances', headers: { authorization: `Bearer ${tokenA}` }, body: JSON.stringify({ name: 'main' }) }, + { plane, store }, + ) + assert.equal(noWorkspace.status, 400) + } finally { + cleanup() + } +}) diff --git a/plane/test/credentials.test.js b/plane/test/credentials.test.js new file mode 100644 index 000000000..a2900daed --- /dev/null +++ b/plane/test/credentials.test.js @@ -0,0 +1,76 @@ +import test from 'node:test' +import assert from 'node:assert/strict' +import { mkdtempSync, readFileSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { createPlane } from '../index.js' +import { MemoryBackend } from '../src/lifecycle.mjs' +import { openStore } from '../src/store.mjs' +import { mintOperatorToken, redact, verifyControl, verifyOperator } from '../src/credentials.mjs' +import { handle } from '../src/server.mjs' + +function setup() { + const dataDir = mkdtempSync(join(tmpdir(), 'plane-cred-')) + const store = openStore(dataDir) + const plane = createPlane({ dataDir, store, backend: new MemoryBackend() }) + const tokenA = mintOperatorToken(store, 'acct-a') + const cleanup = () => rmSync(dataDir, { recursive: true, force: true }) + return { dataDir, store, plane, tokenA, cleanup } +} + +test('a control token is not accepted on the operator API (401)', async () => { + const { store, plane, tokenA, cleanup } = setup() + try { + const created = await plane.createInstance({ workspaceId: 'ws-1', name: 'main', ownerId: 'acct-a' }) + assert.match(tokenA, /^op_[0-9a-f]{32}$/) + assert.match(created.controlToken, /^ctl_[0-9a-f]{32}$/) + const res = await handle( + { method: 'GET', path: `/api/instances/${created.id}`, headers: { authorization: `Bearer ${created.controlToken}` }, body: '' }, + { plane, store }, + ) + assert.equal(res.status, 401) + } finally { + cleanup() + } +}) + +test('operator and control credentials do not verify as each other', async () => { + const { store, plane, tokenA, cleanup } = setup() + try { + const created = await plane.createInstance({ workspaceId: 'ws-1', name: 'main', ownerId: 'acct-a' }) + assert.equal(verifyOperator(store, `Bearer ${created.controlToken}`), null) + assert.equal(verifyControl(store.getInstance(created.id), `Bearer ${tokenA}`), null) + assert.equal(verifyOperator(store, `Bearer ${tokenA}`).id, 'acct-a') + assert.equal(verifyControl(store.getInstance(created.id), `Bearer ${created.controlToken}`).id, created.id) + } finally { + cleanup() + } +}) + +test('plane.json stores token hashes, never the plaintext tokens', async () => { + const { dataDir, plane, tokenA, cleanup } = setup() + try { + const created = await plane.createInstance({ workspaceId: 'ws-1', name: 'main', ownerId: 'acct-a' }) + const raw = readFileSync(join(dataDir, 'plane.json'), 'utf8') + assert.ok(!raw.includes(tokenA), 'operator token must not be persisted in plaintext') + assert.ok(!raw.includes(created.controlToken), 'control token must not be persisted in plaintext') + assert.doesNotMatch(raw, /(?:op|ctl)_[0-9a-f]{32}/) + assert.equal(JSON.parse(raw).version, 1) + } finally { + cleanup() + } +}) + +test('two instances get different control tokens and redact() hides them', async () => { + const { plane, cleanup } = setup() + try { + const a = await plane.createInstance({ workspaceId: 'ws-1', name: 'a', ownerId: 'acct-a' }) + const b = await plane.createInstance({ workspaceId: 'ws-1', name: 'b', ownerId: 'acct-a' }) + assert.notEqual(a.controlToken, b.controlToken) + const redacted = redact(a.controlToken) + assert.ok(!redacted.includes(a.controlToken.slice(3))) + assert.match(redacted, /^ctl_/) + } finally { + cleanup() + } +}) diff --git a/plane/test/lifecycle.test.js b/plane/test/lifecycle.test.js new file mode 100644 index 000000000..aad1c21db --- /dev/null +++ b/plane/test/lifecycle.test.js @@ -0,0 +1,90 @@ +import test from 'node:test' +import assert from 'node:assert/strict' +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { createPlane, NotImplementedError } from '../index.js' +import { ComposeBackend, MemoryBackend } from '../src/lifecycle.mjs' +import { openStore } from '../src/store.mjs' +import { mintOperatorToken } from '../src/credentials.mjs' +import { handle } from '../src/server.mjs' + +function setup(backend = new MemoryBackend()) { + const dataDir = mkdtempSync(join(tmpdir(), 'plane-life-')) + const store = openStore(dataDir) + const plane = createPlane({ dataDir, store, backend }) + const token = mintOperatorToken(store, 'acct-a') + const cleanup = () => rmSync(dataDir, { recursive: true, force: true }) + return { dataDir, store, plane, token, backend, cleanup } +} + +test('start makes the instance running and healthy', async () => { + const { plane, cleanup } = setup() + try { + const created = await plane.createInstance({ workspaceId: 'ws-1', name: 'main', ownerId: 'acct-a' }) + assert.equal(created.state, 'stopped') + const started = await plane.startInstance(created.id) + assert.equal(started.state, 'running') + assert.equal(started.health, 'ok') + assert.equal(plane.getInstance(created.id).state, 'running') + } finally { + cleanup() + } +}) + +test('stop records stopped, and a fresh store does not resurrect it as running', async () => { + const { dataDir, plane, cleanup } = setup() + try { + const created = await plane.createInstance({ workspaceId: 'ws-1', name: 'main', ownerId: 'acct-a' }) + await plane.startInstance(created.id) + const stopped = await plane.stopInstance(created.id) + assert.equal(stopped.state, 'stopped') + assert.equal(stopped.health, 'unknown') + + const reopened = openStore(dataDir) + const plane2 = createPlane({ dataDir, store: reopened, backend: new MemoryBackend() }) + assert.equal(plane2.getInstance(created.id).state, 'stopped') + } finally { + cleanup() + } +}) + +test('stop then start again returns to running (the lifecycle loop)', async () => { + const { plane, cleanup } = setup() + try { + const created = await plane.createInstance({ workspaceId: 'ws-1', name: 'main', ownerId: 'acct-a' }) + await plane.startInstance(created.id) + await plane.stopInstance(created.id) + const again = await plane.startInstance(created.id) + assert.equal(again.state, 'running') + assert.equal(again.health, 'ok') + } finally { + cleanup() + } +}) + +test('an unknown instance id is HTTP 404 for a valid operator', async () => { + const { plane, store, token, cleanup } = setup() + try { + const res = await handle( + { method: 'GET', path: '/api/instances/inst_missing', headers: { authorization: `Bearer ${token}` }, body: '' }, + { plane, store }, + ) + assert.equal(res.status, 404) + } finally { + cleanup() + } +}) + +test('upgrade and recycle are explicit NotImplementedError in this slice', async () => { + const composeDir = mkdtempSync(join(tmpdir(), 'plane-compose-')) + try { + for (const backend of [new MemoryBackend(), new ComposeBackend({ instancesDir: composeDir })]) { + await assert.rejects(() => backend.upgrade({ id: 'inst_x' }), { name: 'NotImplementedError' }) + await assert.rejects(() => backend.recycle({ id: 'inst_x' }), { name: 'NotImplementedError' }) + } + assert.ok(new NotImplementedError('upgrade') instanceof Error) + } finally { + rmSync(composeDir, { recursive: true, force: true }) + } +}) diff --git a/plane/test/ownership.test.js b/plane/test/ownership.test.js new file mode 100644 index 000000000..29d593518 --- /dev/null +++ b/plane/test/ownership.test.js @@ -0,0 +1,85 @@ +import test from 'node:test' +import assert from 'node:assert/strict' +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { createPlane } from '../index.js' +import { MemoryBackend } from '../src/lifecycle.mjs' +import { openStore } from '../src/store.mjs' +import { mintOperatorToken } from '../src/credentials.mjs' +import { handle } from '../src/server.mjs' + +async function setup() { + const dataDir = mkdtempSync(join(tmpdir(), 'plane-owner-')) + const store = openStore(dataDir) + const plane = createPlane({ + dataDir, + store, + backend: new MemoryBackend(), + clock: () => Date.parse('2026-11-17T00:00:00.000Z'), + }) + const tokenA = mintOperatorToken(store, 'acct-a') + const tokenB = mintOperatorToken(store, 'acct-b') + const b = await plane.createInstance({ workspaceId: 'ws-b', name: 'b-main', ownerId: 'acct-b' }) + await plane.startInstance(b.id) + const deps = { plane, store } + const cleanup = () => rmSync(dataDir, { recursive: true, force: true }) + return { dataDir, store, plane, tokenA, tokenB, deps, b, cleanup } +} + +function request(method, path, token) { + const headers = token ? { authorization: `Bearer ${token}` } : {} + return { method, path, headers, body: '' } +} + +test('A operator token cannot read B instance: 403 and B state unchanged', async () => { + const { tokenA, deps, b, cleanup } = await setup() + try { + const res = await handle(request('GET', `/api/instances/${b.id}`, tokenA), deps) + assert.equal(res.status, 403) + assert.deepEqual(res.body, { error: 'forbidden' }) + assert.equal(deps.plane.getInstance(b.id).state, 'running') + } finally { + cleanup() + } +}) + +test('A operator token cannot stop B instance: 403 and B stays running', async () => { + const { tokenA, deps, b, cleanup } = await setup() + try { + const res = await handle(request('POST', `/api/instances/${b.id}/stop`, tokenA), deps) + assert.equal(res.status, 403) + assert.equal(deps.plane.getInstance(b.id).state, 'running') + } finally { + cleanup() + } +}) + +test('missing Authorization is 401 and a forged op_ token is 401', async () => { + const { deps, b, cleanup } = await setup() + try { + const noAuth = await handle(request('GET', `/api/instances/${b.id}`), deps) + assert.equal(noAuth.status, 401) + const forged = await handle(request('GET', `/api/instances/${b.id}`, `op_${'0'.repeat(32)}`), deps) + assert.equal(forged.status, 401) + } finally { + cleanup() + } +}) + +test('GET /api/instances lists only the caller own instances', async () => { + const { tokenA, tokenB, deps, plane, cleanup } = await setup() + try { + const a = await plane.createInstance({ workspaceId: 'ws-a', name: 'a-main', ownerId: 'acct-a' }) + const listA = await handle(request('GET', '/api/instances', tokenA), deps) + assert.equal(listA.status, 200) + assert.deepEqual(listA.body.instances.map((i) => i.id), [a.id]) + const listB = await handle(request('GET', '/api/instances', tokenB), deps) + assert.equal(listB.status, 200) + assert.equal(listB.body.instances.length, 1) + assert.equal(listB.body.instances[0].id, deps.plane.listInstances('acct-b')[0].id) + assert.ok(listB.body.instances.every((i) => i.ownerId === 'acct-b')) + } finally { + cleanup() + } +})