Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion docs/subsystems/plane.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,13 +38,22 @@ purpose: no container is started in this slice.
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.
- `workspace.members` is the only source of membership: `owner / admin / member`, and the
creating account becomes the only `owner`. An older `plane.json` is read with its owner
seeded as the only member, never rejected.
- `GET` / `POST /api/workspaces/:id/members` verify the token, then pick the workspace by the
caller's role: two owners' same-named `ws-1` never mix. Non-member `403`, unknown id `404`,
duplicate member `409`, unknown role `400`. A role does not reach the instance routes yet —
those still answer to `instance.ownerId` alone, so an `admin` adds members and nothing more.
A workspace id is still owner-scoped, so one account invited into two owners' `ws-1` resolves
to the first one stored; scoping the workspace key is the next slice.
- `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
`npm --prefix plane test` (25 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.
13 changes: 11 additions & 2 deletions plane/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,11 @@ or orchestrator, only the default changes.
- 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`.
- Keeps workspace membership (`plane/src/workspace-roles.mjs`): `workspace.members` with the
three roles `owner / admin / member`, the creator as the only owner, and an older
`plane.json` read with its owner seeded into the membership instead of rejected.
`GET` / `POST /api/workspaces/:id/members` read the list and add a member; a bare id is
resolved by the caller's role, and a role does not reach the instance routes yet.
- Materializes an instance's compose project (`plane/src/lifecycle.mjs`): `compose.yaml` plus
`control.env` (0600), loopback port, project `flybot-<id>`. It does **not** run `docker
compose up`; `runner` is an unused injection point for the next slice.
Expand All @@ -47,6 +52,10 @@ 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.
`listWorkspaceMembers(workspaceId, actorId)` answers the member list, and
`addWorkspaceMember(workspaceId, actorId, { accountId, role })` adds one, throwing
`WorkspaceRoleError` with `invalid_role` / `member_exists` / `forbidden` / `workspace_not_found` /
`account_not_found`.

## CLI

Expand All @@ -71,6 +80,6 @@ bundles.
npm --prefix plane test
```

20 cases: ownership/403, 401, per-owner listing, duplicate creation (409), persistence, 400s,
25 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.
idempotency, workspace membership and the zero-spawn guarantee.
32 changes: 31 additions & 1 deletion plane/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,10 @@ 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'
import { WorkspaceRoleError, canAddMembers, canRead, withMember } from './src/workspace-roles.mjs'

export { DuplicateInstanceError, InstanceNotFoundError, openStore } from './src/store.mjs'
export { ROLES, WorkspaceRoleError, canAddMembers, canRead, memberOf, roleOf } from './src/workspace-roles.mjs'
export { LifecycleBackend, MemoryBackend, ComposeBackend, NotImplementedError, hostPortFor } from './src/lifecycle.mjs'
export {
mintOperatorToken,
Expand Down Expand Up @@ -49,6 +51,31 @@ export function createPlane({ dataDir, store, backend = new MemoryBackend(), clo
return publicRecord(theStore.updateInstance(id, patch))
}

// A workspace id is owner-scoped, so two owners both have a "ws-1": pick the candidate the
// caller has the role for. No candidate is a missing workspace; candidates it cannot enter are
// forbidden, so a member of somebody else's workspace learns nothing about it.
function workspaceFor(workspaceId, actorId, allowed) {
const candidates = theStore.workspacesWithId(workspaceId)
if (candidates.length === 0) throw new WorkspaceRoleError('workspace_not_found', `no workspace ${workspaceId}`)
const workspace = candidates.find((candidate) => allowed(candidate, actorId))
if (!workspace) throw new WorkspaceRoleError('forbidden', `not a member of workspace ${workspaceId}`)
return workspace
}

// The actor always comes from the verified account, never from the request body.
function listWorkspaceMembers(workspaceId, actorId) {
const workspace = workspaceFor(workspaceId, actorId, canRead)
return workspace.members.map((member) => ({ ...member }))
}

function addWorkspaceMember(workspaceId, actorId, { accountId, role } = {}) {
const workspace = workspaceFor(workspaceId, actorId, canAddMembers)
if (!theStore.getAccount(accountId)) throw new WorkspaceRoleError('account_not_found', `no account ${accountId}`)
const member = withMember(workspace, { accountId, role }, now())
theStore.updateWorkspaceMembers(workspace, workspace.members)
return { ...member }
}

async function createInstance({ workspaceId, name, ownerId } = {}) {
assertNonEmpty(workspaceId, 'workspaceId')
assertNonEmpty(name, 'name')
Expand Down Expand Up @@ -99,5 +126,8 @@ export function createPlane({ dataDir, store, backend = new MemoryBackend(), clo
return theStore.listInstances(ownerId).map(publicRecord)
}

return { createInstance, startInstance, stopInstance, getInstance, listInstances }
return {
createInstance, startInstance, stopInstance, getInstance, listInstances,
listWorkspaceMembers, addWorkspaceMember,
}
}
37 changes: 37 additions & 0 deletions plane/src/server.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { createServer } from 'node:http'
import { createPlane } from '../index.js'
import { DuplicateInstanceError, openStore } from './store.mjs'
import { verifyOperator } from './credentials.mjs'
import { WorkspaceRoleError } from './workspace-roles.mjs'

const JSON_HEADERS = { 'content-type': 'application/json; charset=utf-8' }

Expand All @@ -18,6 +19,15 @@ function nonEmpty(value) {
return typeof value === 'string' && value.trim() !== ''
}

// A membership refusal is a status, not a thrown 500: the role error names it.
const MEMBER_ERROR_STATUS = { invalid_role: 400, forbidden: 403, workspace_not_found: 404, account_not_found: 404, member_exists: 409 }

function memberReply(error) {
const status = error instanceof WorkspaceRoleError ? MEMBER_ERROR_STATUS[error.code] : undefined
if (!status) throw error
return reply(status, { error: error.code })
}

function parseBody(body) {
if (body === undefined || body === null || body === '') return null
if (typeof body === 'object') return body
Expand Down Expand Up @@ -54,6 +64,33 @@ export async function handle(request, { plane, store } = {}) {
}
}

const members = path.match(/^\/api\/workspaces\/([^/]+)\/members$/)
if (members) {
const workspaceId = decodeURIComponent(members[1])
if (method === 'GET') {
try {
return reply(200, { members: plane.listWorkspaceMembers(workspaceId, account.id) })
} catch (error) {
return memberReply(error)
}
}
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' })
if (!nonEmpty(body.accountId)) return reply(400, { error: 'invalid_request' })
try {
const member = plane.addWorkspaceMember(workspaceId, account.id, { accountId: body.accountId, role: body.role })
return reply(201, { member })
} catch (error) {
return memberReply(error)
}
}

const match = path.match(/^\/api\/instances\/([^/]+)(?:\/(start|stop))?$/)
if (match) {
const id = decodeURIComponent(match[1])
Expand Down
20 changes: 19 additions & 1 deletion plane/src/store.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
import { join } from 'node:path'
import { randomBytes } from 'node:crypto'
import { seedMembers } from './workspace-roles.mjs'

export const STORE_VERSION = 1

Expand Down Expand Up @@ -62,6 +63,7 @@ export class Store {
parsed.accounts ??= []
parsed.workspaces ??= []
parsed.instances ??= []
for (const workspace of parsed.workspaces) seedMembers(workspace)
return parsed
}

Expand Down Expand Up @@ -95,7 +97,7 @@ export class Store {
ensureWorkspace({ id, ownerId, createdAt }) {
let workspace = this.getWorkspace(id, ownerId)
if (!workspace) {
workspace = { id, ownerId, createdAt }
workspace = seedMembers({ id, ownerId, createdAt })
this.#data.workspaces.push(workspace)
this.save()
}
Expand All @@ -111,6 +113,22 @@ export class Store {
)
}

// The candidates for a bare workspace id: two owners may each own a "ws-1", so a caller picks
// the one it has a role in instead of taking the first.
workspacesWithId(id) {
return this.#data.workspaces.filter((workspace) => workspace.id === id)
}

updateWorkspaceMembers(workspace, members) {
const stored = this.#data.workspaces.find(
(candidate) => candidate.id === workspace.id && candidate.ownerId === workspace.ownerId,
)
if (!stored) throw new Error(`no workspace ${workspace.id} owned by ${workspace.ownerId}`)
stored.members = members
this.save()
return stored
}

listInstances(ownerId) {
return ownerId ? this.#data.instances.filter((instance) => instance.ownerId === ownerId) : this.#data.instances
}
Expand Down
45 changes: 45 additions & 0 deletions plane/src/workspace-roles.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
// Workspace membership and its three roles (#3117).
//
// `workspace.members` is the only source of membership: `{ accountId, role, addedAt }`. This
// module is the one place that reads a role and the one place that adds a member, so a route
// never re-checks the shape of the array.
export const ROLES = ['owner', 'admin', 'member']

export class WorkspaceRoleError extends Error {
constructor(code, message) {
super(message)
this.name = 'WorkspaceRoleError'
this.code = code
}
}

export function memberOf(workspace, accountId) {
return (workspace?.members ?? []).find((member) => member.accountId === accountId) ?? null
}

export function roleOf(workspace, accountId) {
return memberOf(workspace, accountId)?.role ?? null
}

export function canRead(workspace, accountId) {
return roleOf(workspace, accountId) !== null
}

export function canAddMembers(workspace, accountId) {
return ['owner', 'admin'].includes(roleOf(workspace, accountId))
}

// A workspace written before members existed gets its owner as the only member, never a
// rejection: refusing it would take down a plane that is already running.
export function seedMembers(workspace) {
workspace.members ??= [{ accountId: workspace.ownerId, role: 'owner', addedAt: workspace.createdAt }]
return workspace
}

export function withMember(workspace, { accountId, role } = {}, addedAt) {
if (!ROLES.includes(role)) throw new WorkspaceRoleError('invalid_role', `unknown role ${role}`)
if (memberOf(workspace, accountId)) throw new WorkspaceRoleError('member_exists', `${accountId} is already a member`)
const member = { accountId, role, addedAt }
workspace.members.push(member)
return member
}
86 changes: 86 additions & 0 deletions plane/test/workspace-members.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
import test from 'node:test'
import assert from 'node:assert/strict'
import { mkdtempSync, rmSync, writeFileSync } 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'

const AT = '2026-11-18T00:00:00.000Z'
const PATH = '/api/workspaces/ws-1/members'
const MEMBERS = (res) => res.body.members.map((member) => member.accountId)

function setup(t) {
const dataDir = mkdtempSync(join(tmpdir(), 'plane-members-'))
t.after(() => rmSync(dataDir, { recursive: true, force: true }))
const store = openStore(dataDir)
const plane = createPlane({ dataDir, store, backend: new MemoryBackend(), clock: () => Date.parse(AT) })
const tokens = Object.fromEntries(
['a', 'b', 'c', 'd'].map((name) => [`acct-${name}`, mintOperatorToken(store, `acct-${name}`)]),
)
const req = (method, path, token, body) =>
handle({ method, path, headers: { authorization: `Bearer ${token}` }, body: body === undefined ? '' : JSON.stringify(body) }, { plane, store })
return { plane, tokens, req }
}

test('a workspace member list has its creator as the only owner (#3117)', async (t) => {
const { plane, tokens, req } = setup(t)
await plane.createInstance({ workspaceId: 'ws-1', name: 'main', ownerId: 'acct-a' })
const res = await req('GET', PATH, tokens['acct-a'])
assert.equal(res.status, 200)
assert.deepEqual(res.body.members, [{ accountId: 'acct-a', role: 'owner', addedAt: AT }])
})

test('two owners with the same workspace id never read or write each others members (#3117)', async (t) => {
const { plane, tokens, req } = setup(t)
await plane.createInstance({ workspaceId: 'ws-1', name: 'main', ownerId: 'acct-a' })
await plane.createInstance({ workspaceId: 'ws-1', name: 'main', ownerId: 'acct-b' })
assert.equal((await req('POST', PATH, tokens['acct-a'], { accountId: 'acct-c', role: 'member' })).status, 201)
assert.deepEqual(MEMBERS(await req('GET', PATH, tokens['acct-a'])), ['acct-a', 'acct-c'])
assert.deepEqual(MEMBERS(await req('GET', PATH, tokens['acct-b'])), ['acct-b'])
assert.deepEqual(MEMBERS(await req('GET', PATH, tokens['acct-c'])), ['acct-a', 'acct-c'])
const outsider = await req('GET', PATH, tokens['acct-d'])
assert.deepEqual([outsider.status, outsider.body], [403, { error: 'forbidden' }])
assert.equal((await req('POST', PATH, tokens['acct-b'], { accountId: 'acct-d', role: 'member' })).status, 201)
assert.deepEqual(MEMBERS(await req('GET', PATH, tokens['acct-a'])), ['acct-a', 'acct-c'])
})

test('an owner adds a member, who can then read the list (#3117)', async (t) => {
const { plane, tokens, req } = setup(t)
await plane.createInstance({ workspaceId: 'ws-1', name: 'main', ownerId: 'acct-a' })
const added = await req('POST', PATH, tokens['acct-a'], { accountId: 'acct-b', role: 'member' })
assert.equal(added.status, 201)
assert.deepEqual(added.body.member, { accountId: 'acct-b', role: 'member', addedAt: AT })
assert.deepEqual(MEMBERS(await req('GET', PATH, tokens['acct-b'])), ['acct-a', 'acct-b'])
const again = await req('POST', PATH, tokens['acct-a'], { accountId: 'acct-b', role: 'admin' })
assert.deepEqual([again.status, again.body], [409, { error: 'member_exists' }])
const noRole = await req('POST', PATH, tokens['acct-a'], { accountId: 'acct-c', role: 'root' })
assert.deepEqual([noRole.status, noRole.body], [400, { error: 'invalid_role' }])
const noAccount = await req('POST', PATH, tokens['acct-a'], { accountId: 'acct-zz', role: 'member' })
assert.deepEqual([noAccount.status, noAccount.body], [404, { error: 'account_not_found' }])
const noWorkspace = await req('GET', '/api/workspaces/ws-nope/members', tokens['acct-a'])
assert.deepEqual([noWorkspace.status, noWorkspace.body], [404, { error: 'workspace_not_found' }])
})

test('an admin may add a member; a plain member may not (#3117)', async (t) => {
const { plane, tokens, req } = setup(t)
await plane.createInstance({ workspaceId: 'ws-1', name: 'main', ownerId: 'acct-a' })
assert.equal((await req('POST', PATH, tokens['acct-a'], { accountId: 'acct-b', role: 'admin' })).status, 201)
const asAdmin = await req('POST', PATH, tokens['acct-b'], { accountId: 'acct-c', role: 'member' })
assert.deepEqual([asAdmin.status, asAdmin.body.member?.role], [201, 'member'])
const asMember = await req('POST', PATH, tokens['acct-c'], { accountId: 'acct-d', role: 'member' })
assert.deepEqual([asMember.status, asMember.body], [403, { error: 'forbidden' }])
})

test('a plane.json from before members loads with its owner as the only member (#3117)', (t) => {
const dataDir = mkdtempSync(join(tmpdir(), 'plane-old-'))
t.after(() => rmSync(dataDir, { recursive: true, force: true }))
const old = { version: 1, accounts: [], workspaces: [{ id: 'ws-old', ownerId: 'acct-a', createdAt: AT }], instances: [] }
writeFileSync(join(dataDir, 'plane.json'), JSON.stringify(old))
assert.deepEqual(openStore(dataDir).getWorkspace('ws-old', 'acct-a').members, [
{ accountId: 'acct-a', role: 'owner', addedAt: AT },
])
})
Loading