diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index e2a7c47..a918067 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -67,7 +67,7 @@ VM (Ubuntu 24.04; XFCE desktop unless --headless) | `backends/index.mjs` | agent machine and host | What each backend declares: supported and tested boxery-host platforms, runtimes, prerequisites and capabilities, as data (no probes). `host/capabilities.mjs` checks against it, `boxery-host backends`/`capabilities` print it, and `vm_info` lists it; it imports nothing. A backend without a declaration (one added as a `.sh` file) runs unchecked ([backends](docs/backends.md)) | | `help/index.mjs` | agent machine and host | Renders CLI help from a command table (`PROG help [--all]`, `COMMAND --help`, a family's and an action's help derived from the command each action runs, usage errors, the docs reference) for `controller/cli.mjs` and `host/help.mjs`; it imports nothing | | `guests/linux.mjs`, `guests/index.mjs` | agent machine and host | What's inside a VM, per guest OS: the agent's home and project, boxery's config and grants directories. `core/` and `host/` both import it instead of keeping their own copies; it imports nothing. Only `linux` exists ([plan](docs/plans/2026-11-03-guest-os-seam.md)) | -| `mcp/boxery-mcp.mjs` | agent machine (stdio) or host (HTTP) | MCP server. stdio, or Streamable HTTP at `/mcp` (bearer token required, optional Tailscale user allowlist, Origin check; meant for `tailscale serve`, never funnel). Sessions keep their own host and VM. `vm_view` + `mcp/desktop-view.html` give MCP Apps clients a live desktop | +| `mcp/boxery-mcp.mjs` | agent machine (stdio) or host (HTTP) | MCP server. stdio, or Streamable HTTP at `/mcp` (bearer token required: unscoped, or [scoped](docs/mcp.md#scoped-tokens) to tools, hosts and VMs by `core/mcp-tokens.mjs` and checked where boxery acts by `core/mcp-auth.mjs`; optional Tailscale user allowlist, Origin check; meant for `tailscale serve`, never funnel). Sessions keep their own host and VM. `vm_view` + `mcp/desktop-view.html` give MCP Apps clients a live desktop | | `extension/index.ts` | agent machine | pi extension: explicit `vm_*` tools next to pi's built-ins (which stay local), `--vm NAME/new/pool`, `--vm-host`, `/vm` commands, throwaway VMs and leases tied to the pi session | | `controller/boxery` + `controller/*.mjs` | agent machine | The CLI. `controller/boxery` is a small Bash shim (it finds Node and passes arguments on byte for byte, like `host/boxery-host`); `controller/cli.mjs` parses commands and runs the same core code MCP and pi do. Its `COMMANDS` table is the one definition of routing and help (and of which long commands report their progress to the terminal, as OSC 7501 on stderr when it is a terminal: a `status` on the entry, run by `controller/status.mjs`): a command has a `run` handler, and a command family (`host`, `snapshot`, `agent`, `job`, `access`, `lease`; `pool` and `runners` parse their own actions) has `actions`, each naming an existing command whose handler it runs, so `boxery job ls` and `boxery jobs` are one code path and the older spellings need no second table. Commands carry an optional `contract` beside their handlers: selected-host or controller scope, help/payload boundaries, optional host selection, all-host listings, SSH-qualified targets and terminal needs. Ordinary commands use selected-host/legacy-help defaults; aliases and family actions inherit their handler's contract. Approval is conditional when granting (`new`, `fork`, `grant`, `agent-forward`); only `attach` unconditionally needs a terminal on stdin, after argument validation. Family actions are resolved before any host or profile is read; `host` registry actions (`add`, `ls`, `show`, `use`, `rm`) explicitly declare `scope: "registry"` and run before host selection. Registry scope is not an offline guarantee: `host add DEST` contacts DEST. Host maintenance uses the ordinary selected-host path. Read-only host-wide text listings use `controller/all-hosts.mjs`, sharing host ordering, same-host deduplication and headings with `controller/ls.mjs`; JSON and explicit `--host` remain single-host, and mutating actions stay selected-host. The code behind the commands: `core/lifecycle.mjs` (new/fork/rm/start/stop/resize/snap/revert/pin/pool/patch, listings), `core/leases.mjs`, `core/grants.mjs`, `vm_copy` (`cp`), `core/versions.mjs`. What only the CLI has: argument parsing and output formats (unchanged, [cli.md](docs/cli.md)), `/dev/tty` grant approval (`controller/grants.mjs`), terminal commands (`ssh`, `attach`, `desktop`, `forward`, `run`, jobs in `controller/jobs.mjs`, `runners once` with your `gh` login), and the host registry's CLI (`controller/hosts.mjs`: `setup`, `host add/ls/show/use/rm`, over `core/registry.mjs`, which `vm_manage host_add/host_rm` use too). Profiles: `core/profile.mjs` (config, `hostRun` to boxery-host, ssh_config, shared connections) and `core/ssh-config.mjs` (quoting and the ssh_config text). A profile `config` that only assigns the controller's settings (`HOST`, `HOST_BIN`, `HOST_PROFILE`, `IDENTITY`, `GRANT_CONFIRM`, as `setup` writes them) is parsed; any other config is sourced by bash (`set -eu`, with `$CONF_DIR` and the defaults set), and its exported environment reaches host commands. `test/ssh-config.test.mjs` holds the ssh_config text and quoting to the Bash controller's (`test/fixtures/bash-profile.sh`), word for word. Each profile's `ssh_config`: `*.boxery` → `ProxyCommand ssh HOST boxery-host connect %h %p`, ControlMaster, per-lease identities, per-VM `ForwardAgent` | | `host/boxery-host` + `host/*.mjs` | control plane | Backend-agnostic VM manager. Bash entry point; `connect` stays in Bash so the ProxyCommand never pays Node startup; everything else is Node. Ownership per module: [host-modules.md](docs/host-modules.md) | @@ -201,7 +201,7 @@ Nothing in boxery's own state limits that: lock transactions are short, the prox ## Roadmap -1. **Hardening** of what exists: Lima on Linux and Lima guests' reach to the Mac's non-loopback addresses ([#67](https://github.com/modem-dev/boxery/issues/67)), confining HTTP-MCP `local:` copies ([#68](https://github.com/modem-dev/boxery/issues/68)), proxy header and token hardening ([#73](https://github.com/modem-dev/boxery/issues/73)), HTTP MCP bounds and argument validation ([#21](https://github.com/modem-dev/boxery/issues/21), [#72](https://github.com/modem-dev/boxery/issues/72)), scoped MCP tokens ([#3](https://github.com/modem-dev/boxery/issues/3)), default-deny egress ([#4](https://github.com/modem-dev/boxery/issues/4)), per-VM proxy budgets. +1. **Hardening** of what exists: Lima on Linux and Lima guests' reach to the Mac's non-loopback addresses ([#67](https://github.com/modem-dev/boxery/issues/67)), confining HTTP-MCP `local:` copies ([#68](https://github.com/modem-dev/boxery/issues/68)), proxy header and token hardening ([#73](https://github.com/modem-dev/boxery/issues/73)), HTTP MCP bounds and argument validation ([#21](https://github.com/modem-dev/boxery/issues/21), [#72](https://github.com/modem-dev/boxery/issues/72)), default-deny egress ([#4](https://github.com/modem-dev/boxery/issues/4)), per-VM proxy budgets. 2. **Lease enforcement:** the restricted host gateway and authenticated holders ([#71](https://github.com/modem-dev/boxery/issues/71)). First decide the pool's shape ([#75](https://github.com/modem-dev/boxery/issues/75)). 3. **Profiles** (app-agnostic setup on top of images), `--keep`, detach/resume semantics for pi, versioned templates, builder VMs for build-time tokens: [plan](docs/plans/2026-11-01-profiles-and-lease-extensions.md). 4. **Simplification:** align the Node requirement ([#77](https://github.com/modem-dev/boxery/issues/77)). (The controller moved into Node: [#74](https://github.com/modem-dev/boxery/issues/74).) @@ -217,6 +217,7 @@ Nothing in boxery's own state limits that: lock transactions are short, the prox - **Grant operations in Node, approval in front-ends.** As with `cp`, CLI and tools call one implementation so store edits, validation and application cannot drift. Existing lifecycle/connect paths delegate only reconciliation and do not ask again. The CLI uses its already-selected profile directory rather than re-resolving a changed registry entry. Existing-grant reconciliation tolerates incomplete registry entries but still includes their directory pointers in symlink deny checks; new file-grant validation remains strict. Leases (`core/leases.mjs`), profile/ssh_config plumbing (`core/profile.mjs`, `core/ssh-config.mjs`) and lifecycle (`core/lifecycle.mjs`) are Node; the registry (`core/registry.mjs`) and the desktop tunnel (`core/desktop.mjs`) too; core never runs the CLI ([#74](https://github.com/modem-dev/boxery/issues/74)). `vm_manage new` does not pass grants. - **Node for logic, Bash at the edges.** Where boxery decides something (leases, locks, recovery, grants, profiles, the CLI's commands), it is Node: modules with injected dependencies, tested directly, one implementation for the CLI, MCP and pi ([#18](https://github.com/modem-dev/boxery/issues/18), [#74](https://github.com/modem-dev/boxery/issues/74)). Bash is left where it is the better tool or the only one: entry shims (`controller/boxery`, `host/boxery-host`; `connect`, the ssh ProxyCommand of every VM connection, never starts Node), backends that wrap a hypervisor's command line (`host/backends/*.sh`: libvirt, Lima, cloud-hypervisor; exe.dev's CLI over ssh), and what runs in the guest (`image/layers/*.sh`, the job runner, the grant applier: Node may not be there yet, and they are sent each time). Data both sides need is data, not a copy in each language: the host.env settings are one list (`host/host-env.list`) that `host/backend.sh` and `host/config.mjs` read. A backend whose work is an HTTP API is a Node module behind a Bash contract file (`openshell.sh` → `lib/openshell.mjs`; `boat.sh` → `lib/boat.mjs` for boat.dev's REST API, with ssh and tunnels in Bash). - **Unsigned fake JWT as the Codex token.** The Codex client derives an account id from a JWT, so a VM gets an `alg: none` JWT whose payload carries `name:secret`. The proxy never treats it as a signed credential. +- **Scoped MCP tokens on the controller, checked where boxery acts.** `boxery-mcp --http` runs on the controller and can drive several hosts, so its tokens live there (`~/.boxery/mcp-tokens.json`, hashed), not on a host, which can't import the core. A tool's arguments name VMs many ways (`vm`, `VM@SNAP`, `HOST/VM:path`, fork targets, generated names), so the scope is checked again where a name finally reaches ssh or a host command (`core/mcp-auth.mjs`), with the grant carried in async context; the HTTP server refuses any operation that lost it. A VM a token created is its own only while its ssh host key matches, so a reused name isn't ([#3](https://github.com/modem-dev/boxery/issues/3)). ## Review log diff --git a/controller/cli.mjs b/controller/cli.mjs index a25a182..9ec1135 100644 --- a/controller/cli.mjs +++ b/controller/cli.mjs @@ -391,6 +391,21 @@ export const COMMANDS = { capabilities: { command: "capabilities" }, }, }, + "mcp-token": { + contract: { scope: "controller", noHost: "mcp-token takes --host NAME after new LABEL, to scope a token to that host" }, + local: async (args) => (await import("./mcp-tokens.mjs")).mcpTokenCommand(args), + help: { + group: "more", summary: "scoped tokens for the HTTP MCP server (boxery-mcp --http)", list: "mcp-token new|ls|rm", + usage: ["mcp-token new LABEL [--vm PATTERN]... [--host NAME]... [--tools TOOL[:ACTION],... | --read-only] [--admin] [--ttl 30d|12h|never]", "mcp-token ls [--json]", "mcp-token rm LABEL"], + details: [ + "A token reaches only its tools, its hosts (default: the server's --host) and its VMs: those matching --vm (* matches any characters) and those created with it. Admin work (build-base, adding hosts, pool leases) needs --admin.", + "new prints the token once; the server stores only its hash, in ~/.boxery/mcp-tokens.json. rm and expiry take effect at the next request, without a restart.", + ], + flags: [["--vm PATTERN", "VMs the token may use besides the ones it creates (repeatable; * matches any characters)"], ["--host NAME", "A registered host it may use (repeatable; default: the server's --host)"], ["--tools LIST", "Only these tools, or TOOL:ACTION (e.g. vm_bash,vm_manage:new)"], ["--read-only", "Only vm_read, vm_screenshot and vm_info"], ["--admin", "Also build-base, host_add, host_rm and pool leases"], ["--ttl T", "Lifetime: 90m, 12h, 30d (default) or never"], JSON_FLAG], + examples: [["An agent that may create and use its own VMs, for a week", "boxery mcp-token new ci-agent --ttl 7d"], ["Look at the demo VMs, change nothing", "boxery mcp-token new viewer --vm 'demo-*' --read-only"]], + seeAlso: ["setup"], docs: "mcp.md#scoped-tokens", + }, + }, "build-base": { help: { group: "legacy", summary: "build the host's desktop base image (one time, ~3 min)", usage: ["build-base"], details: ["Headless VMs (new --headless) don't need it."], docs: "cli.md#lifecycle" }, status: {}, diff --git a/controller/mcp-tokens.mjs b/controller/mcp-tokens.mjs new file mode 100644 index 0000000..a2332ff --- /dev/null +++ b/controller/mcp-tokens.mjs @@ -0,0 +1,64 @@ +// boxery mcp-token new|ls|rm: scoped tokens for the HTTP MCP server (core/mcp-tokens.mjs, docs/mcp.md). +// Only a person mints them: no agent tool does (test/parity.test.mjs says why). +import { resolveHost } from "../core/boxery-core.mjs"; +import { toolCatalog } from "../core/boxery-tools.mjs"; +import { createToken, describeScope, hostNames, parseTtl, readStore, removeToken, toolsScope, vmPatterns } from "../core/mcp-tokens.mjs"; +import { die, say, usage } from "./lib.mjs"; + +/** @param {number | null} t */ +const when = (t) => (t == null ? "never" : new Date(t * 1000).toISOString().replace(/\.\d+Z$/, "Z")); + +/** @param {string[]} args */ +export async function mcpTokenCommand(args) { + const [action, ...rest] = args; + switch (action) { + case "new": { + const label = rest.shift(); + if (!label || label.startsWith("-")) usage("mcp-token"); + /** @type {string[]} */ + const vms = [], hosts = []; + let tools = /** @type {string | null} */ (null), readOnly = false, admin = false, ttl = "30d"; + while (rest.length) { + const a = /** @type {string} */ (rest.shift()); + const value = () => rest.shift() ?? die(`${a} needs a value`); + if (a === "--vm") vms.push(value()); + else if (a === "--host") hosts.push(value()); + else if (a === "--tools") tools = value(); + else if (a === "--read-only") readOnly = true; + else if (a === "--admin") admin = true; + else if (a === "--ttl") ttl = value(); + else usage("mcp-token"); + } + for (const h of hosts) { + try { resolveHost(h); } catch (e) { die(`--host ${h}: ${/** @type {Error} */ (e).message} (boxery host ls lists the hosts)`); } + } + const scope = { tools: toolsScope(toolCatalog(), { tools, readOnly }), hosts: hostNames(hosts), vms: vmPatterns(vms), admin }; + const { secret, entry } = createToken(/** @type {string} */ (label), scope, { ttl: parseTtl(ttl) }); + say(secret); + process.stderr.write(`boxery: token ${entry.label}: ${describeScope(scope, "the server's --host")}; expires ${when(entry.expires)}.\n` + + "boxery: shown once. Give it to the MCP client as: Authorization: Bearer \n"); + return; + } + case "ls": { + const json = rest[0] === "--json"; + if (rest.length > (json ? 1 : 0)) usage("mcp-token"); + const entries = readStore().map(({ hash: _h, ...e }) => e); + if (json) return say(JSON.stringify(entries, null, 2)); + if (!entries.length) return say("no MCP tokens (create one: boxery mcp-token new LABEL)"); + for (const e of entries) { + say(`${e.label}\texpires ${when(e.expires)}${e.expires != null && e.expires <= Date.now() / 1000 ? " (expired)" : ""}`); + say(` ${describeScope(e.scope, "the server's --host")}`); + for (const o of e.owned) say(` created ${o.host}/${o.vm}${o.key ? "" : " (identified by name only: its backend manages host keys)"}`); + } + return; + } + case "rm": { + if (rest.length !== 1) usage("mcp-token"); + if (!removeToken(rest[0])) die(`no MCP token labelled ${rest[0]}`); + say(`removed MCP token ${rest[0]}; a server using it refuses it from the next request`); + return; + } + default: + usage("mcp-token"); + } +} diff --git a/core/boxery-core.mjs b/core/boxery-core.mjs index fd3a1db..2762f05 100644 --- a/core/boxery-core.mjs +++ b/core/boxery-core.mjs @@ -13,6 +13,7 @@ import { q } from "./shell.mjs"; import { streamCopy } from "./copy-stream.mjs"; import { DEFAULT_HOST_BIN, VALID_DEST, localHostBin, parseConfig, shellWord } from "./ssh-config.mjs"; import { acquireLease, findLease, releaseLease, renewLease } from "./leases.mjs"; +import { authorizeAdmin, authorizeVm } from "./mcp-auth.mjs"; import * as lifecycle from "./lifecycle.mjs"; import { versions as versionInfo } from "./versions.mjs"; import { parseGrantRequest, grantPrompt, grantCommand, listGrants, addGrants } from "./grants.mjs"; @@ -255,6 +256,7 @@ export function describeHosts() { */ export async function addHost({ name, dest, backend, profile }, { progress } = {}) { assertHost(name); + authorizeAdmin(`adding host ${name}`); if (typeof dest !== "string" || !VALID_DEST.test(dest)) throw new Error(`invalid destination "${dest ?? ""}" (local, or an ssh destination such as user@host)`); if (backend != null && !VALID_HOST.test(backend)) throw new Error(`invalid backend "${backend}"`); if (profile != null && !VALID_HOST.test(profile)) throw new Error(`invalid host profile "${profile}"`); @@ -269,6 +271,7 @@ export async function addHost({ name, dest, backend, profile }, { progress } = { * grants stay). @param {string} name @returns {Promise} */ export async function removeHost(name) { assertHost(name); + authorizeAdmin(`removing host ${name}`); const registry = await import("./registry.mjs"); const { io, text } = registry.textIO(); try { await registry.withRegistryLock(async () => registry.removeHostLocked(name, io)); } @@ -345,10 +348,11 @@ export function parseLoc(spec, current) { * (vmProblem), unless a fresh connection works: then the 255 was the script's own and resolves. * @param {string} vm @param {string} script @param {SshRunOpts} [opts] @returns {Promise} */ -export function sshRun(vm, script, opts = {}) { +export async function sshRun(vm, script, opts = {}) { + if (!VALID_NAME.test(vm ?? "")) throw new Error(`invalid VM name "${vm}"`); + const host = currentHost(); + await authorizeVm(host, vm); // scoped MCP tokens (core/mcp-auth.mjs) return new Promise((resolve, reject) => { - if (!VALID_NAME.test(vm ?? "")) return reject(new Error(`invalid VM name "${vm}"`)); - const host = currentHost(); const { sshConf } = host; if (!existsSync(sshConf)) return reject(new Error(`boxery not set up (${sshConf} missing); run: boxery setup user@host`)); // stdin is a pipe whenever it is used (opts.input != null). @@ -449,6 +453,7 @@ export const noSuchVm = (vm) => `no such vm: ${vm} on host ${currentHost().name} */ export async function vmProblem(vm, { env, signal } = {}) { assertName(vm); + await authorizeVm(currentHost(), vm); const probe = await new Promise((/** @type {(r: { code: number | null, stderr: string }) => void} */ resolve) => { const child = spawn("ssh", ["-F", currentHost().sshConf, "-o", "BatchMode=yes", "-o", "ControlMaster=no", "-o", "ControlPath=none", `${vm}.boxery`, "true"], { stdio: ["ignore", "ignore", "pipe"], ...(env ? { env } : {}) }); @@ -966,6 +971,8 @@ export async function copyTool({ from, to }, { current, localCwd = process.cwd() }; const source = endpoint(src); const destination = endpoint(dst, path.posix.basename(source.path)); + // The copy's own ssh (core/copy-stream.mjs) carries no host context: check each VM endpoint here, on its host. + for (const loc of [src, dst]) if (loc.vm) await authorizeVm(loc.host, loc.vm); // (Each endpoint on its own host: HOST/NAME:path may name another.) const unreachable = (/** @type {CopyEndpoint} */ e) => withHost(e === source ? src.host : dst.host, () => vmProblem(/** @type {string} */ (e.vm), { signal })); const bytes = await streamCopy(source, destination, { signal, unreachable }); diff --git a/core/boxery-tools.mjs b/core/boxery-tools.mjs index 8caaabd..1c47505 100644 --- a/core/boxery-tools.mjs +++ b/core/boxery-tools.mjs @@ -17,6 +17,7 @@ import * as core from "./boxery-core.mjs"; import { BACKENDS as BACKEND_DECLARATIONS } from "../backends/index.mjs"; import { SYNC_OUTPUT, syncTool } from "./sync.mjs"; +import { authorizeAdmin, authorizeHostName, authorizeTool, authorizeVm, visibleHost, visibleVm } from "./mcp-auth.mjs"; /** @import { Approve, HostProfile, LocalConfinement, ManageArgs, Progress, ToolResult } from "./boxery-core.mjs" */ /** A JSON Schema fragment. @typedef {{ type?: string | string[], description?: string, enum?: readonly string[], properties?: Record, items?: JsonSchema, required?: string[], anyOf?: JsonSchema[], minimum?: number, maximum?: number }} JsonSchema */ /** A tool's input schema: always an object with named properties. @typedef {JsonSchema & { type: "object", properties: Record, required: string[] }} ObjectSchema */ @@ -407,16 +408,25 @@ export function callTarget(tool, args, s) { /** * Run a TOOLS entry (or a front-end's own tool of the same shape): resolve its target (callTarget), then run it on that host. - * @param {Pick} tool @param {Record} args @param {Session} s @param {ToolContext} [ctx] @returns {Promise} + * @param {Pick & { name?: string }} tool @param {Record} args @param {Session} s @param {ToolContext} [ctx] @returns {Promise} */ export async function runTool(tool, args, s, ctx = {}) { const { host, current, vm, args: a } = callTarget(tool, args, s); + // Scoped MCP tokens (core/mcp-auth.mjs): the tool and action first, for a clear refusal. VMs and hosts are + // checked again where boxery acts on them (ssh, host commands), whatever argument named them. + authorizeTool(tool.name ?? "", typeof args.action === "string" ? args.action : null); + authorizeHostName(host.name); + if (vm) await authorizeVm(host, vm); + if (tool.name === "vm_manage" && args.action === "host_rm") authorizeAdmin(`removing host ${args.name ?? ""}`); return core.withHost(host, () => tool.run(/** @type {string} */ (vm), a, { ...ctx, session: s, host, current })); } +/** Tool → its actions (the `action` enum) or null: what a token's --tools may name (core/mcp-tokens.mjs). @returns {Record} */ +export const toolCatalog = () => Object.fromEntries(TOOLS.map((t) => [t.name, t.parameters.properties.action?.enum ?? null])); + /** vm_info hosts: the registered hosts, `host` marked current. @param {HostProfile} host @returns {ToolResult} */ export function hostsResult(host) { - const hosts = core.describeHosts().map(({ name, destination, backend, default: def, same_as, dir }) => + const hosts = core.describeHosts().filter((h) => visibleHost(h.name)).map(({ name, destination, backend, default: def, same_as, dir }) => ({ name, destination, backend, current: name === host.name, default: def, same_as, dir })); const row = (/** @type {(typeof hosts)[number]} */ h) => [`${h.name}${h.current ? " *" : ""}`, h.destination ?? "-", h.backend ?? "-", [h.default && "default", h.same_as.length && `same host as ${h.same_as.join(", ")}`].filter(Boolean).join("; ") || "-", h.dir].join("\t"); @@ -437,7 +447,7 @@ export async function infoAction(a, { host, current }) { }; switch (a.action) { case "list": { - const vms = await core.listVms(); + const vms = (await core.listVms()).filter((/** @type {{ name: string }} */ v) => visibleVm(host.name, v.name)); return { text: `${core.formatVms(vms)}\ncurrent: ${current ?? "(none)"} (host: ${host.name})`, structured: { vms, current: current ?? null, host: host.name } }; } case "shapes": { @@ -455,7 +465,7 @@ export async function infoAction(a, { host, current }) { return { text: core.formatSnaps(vm, snapshots), structured: { vm, snapshots } }; } case "images": { - const images = await core.listImages(); + const images = (await core.listImages()).filter((/** @type {{ image: string }} */ i) => visibleVm(host.name, String(i.image).split("@")[0])); return { text: core.formatImages(images), structured: { images } }; } case "version": { diff --git a/core/desktop.mjs b/core/desktop.mjs index 370caef..f7acef0 100644 --- a/core/desktop.mjs +++ b/core/desktop.mjs @@ -8,6 +8,7 @@ import { spawn } from "node:child_process"; import net from "node:net"; import { assertName, cliHint, currentHost, sshRun } from "./boxery-core.mjs"; import { profileConfig } from "./profile.mjs"; +import { authorizeVm } from "./mcp-auth.mjs"; const SETUP = 'if test -e /etc/boxery/headless; then echo headless\nelif command -v boxery-vnc-password >/dev/null; then p=$(boxery-vnc-password --new) && echo "password $p"\nelse echo nopassword; fi'; @@ -62,6 +63,7 @@ export function openUrl(url) { export async function openDesktop(name, { open = true } = {}) { const { url, port, warning } = await prepareDesktop(name); const { env } = await profileConfig(); + await authorizeVm(currentHost(), name); // scoped MCP tokens (core/mcp-auth.mjs) const child = spawn("ssh", tunnelArgs(name, port, { batch: true }), { stdio: "ignore", env }); const ended = new Promise((resolve) => { child.once("error", () => resolve(127)); child.once("exit", (code) => resolve(code ?? 1)); }); // Up once the port answers and our ssh is still there (another program taking the port first makes ssh diff --git a/core/grant-operations.mjs b/core/grant-operations.mjs index 02a0822..bdaced1 100644 --- a/core/grant-operations.mjs +++ b/core/grant-operations.mjs @@ -8,6 +8,7 @@ import { parseGrantSpec } from "./grants.mjs"; import { q } from "./shell.mjs"; import { writeAtomic } from "./fsutil.mjs"; import { closeMaster, hostRun, writeSshConfig } from "./profile.mjs"; +import { authorizeVm } from "./mcp-auth.mjs"; /** @import { Grant, GrantSpec } from "./boxery-core.mjs" */ /** CLI env-command helpers may use the original stdin and show prompts on stderr. Agent calls remain headless. * @typedef {{ signal?: AbortSignal, interactiveCommands?: boolean, commandStdin?: number }} GrantOptions @@ -189,6 +190,7 @@ export async function applyGrants(vm, opts = {}) { // Include HTTP URL setup even if a credential command failed, as the previous reconciler did. for (const g of grants) if (g.kind === "http") values.push(`put_edge ${q(g.host ?? "")}`); const script = guestTemplate.replace("# BOXERY_GRANT_VALUES", () => values.join("\n")); + await authorizeVm(currentHost(), assertName(vm)); // scoped MCP tokens (core/mcp-auth.mjs) const output = await new Promise((resolve, reject) => { const child = execFile("ssh", ["-F", currentHost().sshConf, `${assertName(vm)}.boxery`, "bash -s"], { timeout: 120_000, maxBuffer: 2 * 1024 * 1024, signal: opts.signal }, (e, stdout, stderr) => e ? reject(new Error(`could not apply grants to ${vm}: ${stderr || e.message}`)) : resolve(`${stdout}${stderr}`.trim())); child.stdin?.on("error", () => {}); child.stdin?.end(script); diff --git a/core/mcp-auth.mjs b/core/mcp-auth.mjs new file mode 100644 index 0000000..d0194e6 --- /dev/null +++ b/core/mcp-auth.mjs @@ -0,0 +1,206 @@ +// Who an operation acts for, checked where boxery acts: before every ssh to a VM and every host command +// (core/profile.mjs hostRun), not only when a tool starts. A tool's arguments name VMs in many ways +// (vm, VM@SNAP, HOST/VM:path, fork targets, generated names); checking where the name finally reaches ssh or +// the host means a new way of naming one can't slip past (OWASP: deny by default, check every request). +// +// The grant rides in an AsyncLocalStorage beside the current host (core/boxery-core.mjs), so it follows a +// call into timers and child-process callbacks. The HTTP MCP server runs every session's work inside its grant +// and calls enforce(): from then on an operation with no grant at all is refused (a code path that lost its +// context fails closed). stdio MCP, pi and the CLI never call enforce() and are unaffected. +// (Imports boxery-core and profile, which import this module: fine while nothing here runs at load.) +import { AsyncLocalStorage } from "node:async_hooks"; +import { hostBackend } from "./boxery-core.mjs"; +import { describeScope, editStore, keyHash, matches, recordOwned, tokenById, toolAllowed } from "./mcp-tokens.mjs"; +import { hostRun } from "./profile.mjs"; +/** @import { HostProfile } from "./boxery-core.mjs" */ +/** @import { Owned, TokenEntry } from "./mcp-tokens.mjs" */ + +/** A session's grant: everything (the legacy token, --no-auth, stdio), or token ID's scope. defaultHost: the + * server's startup host, the only one a token without --host reaches. leased: VMs the session holds a lease on. + * @typedef {{ kind: "unscoped" } | { kind: "token", id: string, label: string, defaultHost: string, leased?: (host: string, vm: string) => boolean }} Grant */ + +export const UNSCOPED = /** @type {Grant} */ (Object.freeze({ kind: "unscoped" })); +/** Backends that manage VM host keys themselves (backend_platform_host_key in host/backends/*.sh): a key there + * changes legitimately, so a VM created through a token is identified by its name alone. */ +export const PLATFORM_KEY_BACKENDS = ["boat", "openshell"]; + +const context = /** @type {AsyncLocalStorage} */ (new AsyncLocalStorage()); +let enforcing = false; +/** From now on (this process), an operation outside any grant is refused. */ +export const enforce = () => { enforcing = true; }; +/** @template T @param {Grant} grant @param {() => T} fn @returns {T} */ +export const withGrant = (grant, fn) => context.run(grant, fn); + +/** A refusal the agent can act on. The same words whether or not the VM exists, so it reveals nothing. */ +export class OutOfScope extends Error {} +/** @param {Grant & { kind: "token" }} g @param {string} what */ +const refuse = (g, what) => new OutOfScope(`${what} is outside this token's scope (token '${g.label}'); ask the user for a token that covers it`); + +/** @returns {Grant} */ +function grantNow() { + const g = context.getStore(); + if (g) return g; + if (enforcing) throw new Error("boxery: refused: this operation has no MCP authorization context (please report this as a bug)"); + return UNSCOPED; +} +/** The token's entry as the store has it now: a removed or expired token stops working mid-session too. + * @param {Grant & { kind: "token" }} g @returns {TokenEntry} */ +function entryOf(g) { + const e = tokenById(g.id); + if (!e) throw new OutOfScope(`token '${g.label}' was removed; ask the user for a new one`); + if (e.expires != null && e.expires <= Date.now() / 1000) throw new OutOfScope(`token '${g.label}' expired; ask the user for a new one`); + return e; +} +/** @param {TokenEntry} e @param {Grant & { kind: "token" }} g */ +const hostsOf = (e, g) => e.scope.hosts ?? [g.defaultHost]; + +// ---------------------------------------------------------------- VM identity + +/** Host key hashes by host/vm, for a few seconds: a check per ssh would otherwise cost a host call each. */ +const keys = new Map(); +const KEY_TTL_MS = 10_000; +/** VM's current ssh host key hash on HOST (null: none, or the host can't say). @param {HostProfile} host @param {string} vm @param {boolean} [fresh] */ +async function currentKey(host, vm, fresh = false) { + const k = `${host.name}/${host.dir}/${vm}`; + const hit = keys.get(k); + if (!fresh && hit && Date.now() - hit.at < KEY_TTL_MS) return hit.key; + const line = await hostRun(["known-hosts", vm], { host, timeout: 20_000 }).catch(() => ""); + const key = line.trim() ? keyHash(line.split("\n")[0]) : null; + keys.set(k, { at: Date.now(), key }); + return key; +} + +/** Is VM on HOST in token entry E's scope? Patterns, the session's leases, then VMs created through the token, + * if still the same VM (its host key unchanged). @param {Grant & { kind: "token" }} g @param {TokenEntry} e @param {HostProfile} host @param {string} vm */ +async function vmInScope(g, e, host, vm) { + if (e.scope.vms.some((p) => matches(p, vm))) return true; + if (g.leased?.(host.name, vm)) return true; + const o = e.owned.find((x) => x.host === host.name && x.vm === vm); + if (!o) return false; + return o.key == null || (await currentKey(host, vm)) === o.key; +} + +// ---------------------------------------------------------------- checks at the point of action + +/** Before ssh to VM on HOST. @param {HostProfile} host @param {string} vm */ +export async function authorizeVm(host, vm) { + const g = grantNow(); + if (g.kind === "unscoped") return; + const e = entryOf(g); + if (!hostsOf(e, g).includes(host.name)) throw refuse(g, `host ${host.name}`); + if (!(await vmInScope(g, e, host, vm))) throw refuse(g, `VM '${vm}' on host ${host.name}`); +} + +/** Before work that changes the host for everyone (adding or removing a host registration). @param {string} what */ +export function authorizeAdmin(what) { + const g = grantNow(); + if (g.kind === "unscoped" || entryOf(g).scope.admin) return; + throw refuse(g, what); +} + +/** + * The boxery-host commands the core sends, by what they touch. `read`: host-wide listings (tools filter what + * they show by scope). `vm`: VM argv[1]. `new`: creates argv[1] (from --from VM@SNAP, a VM to read). + * `fork`: reads argv[1], creates the names after it. Anything else (build-base, pool leases, setup) is admin. + */ +export const HOST_COMMANDS = /** @type {const} */ ({ + ls: "read", images: "read", shapes: "read", capabilities: "read", version: "read", help: "read", backend: "read", "known-hosts": "read", + rm: "vm", start: "vm", stop: "vm", resize: "vm", snap: "vm", "snap-rm": "vm", revert: "vm", snaps: "vm", "edge-set": "vm", + new: "new", fork: "fork", +}); +/** fork's new VMs: the names after the source, up to the first flag. @param {string[]} args */ +const forkTargets = (args) => { const out = []; for (const a of args.slice(2)) { if (a.startsWith("-")) break; out.push(a); } return out; }; + +/** Before boxery-host ARGS on HOST. @param {HostProfile} host @param {string[]} args */ +export async function authorizeHostCommand(host, args) { + const g = grantNow(); + if (g.kind === "unscoped") return; + const e = entryOf(g); + const [cmd] = args; + const kind = Object.hasOwn(HOST_COMMANDS, cmd) ? HOST_COMMANDS[/** @type {keyof typeof HOST_COMMANDS} */ (cmd)] : "admin"; + if (kind === "admin") { + if (!e.scope.admin) throw refuse(g, `host command '${cmd}'`); + return; + } + if (!hostsOf(e, g).includes(host.name)) throw refuse(g, `host ${host.name}`); + const vm = async (/** @type {string | undefined} */ name) => { + if (!name || !(await vmInScope(g, e, host, name))) throw refuse(g, `VM '${name ?? ""}' on host ${host.name}`); + }; + if (kind === "vm" || kind === "fork") await vm(args[1]); + if (kind === "new") { + const i = args.indexOf("--from"); + if (i >= 0) await vm(String(args[i + 1] ?? "").split("@")[0]); + } +} + +/** After boxery-host ARGS succeeded on HOST: VMs a token created become its own (with their host keys), and a + * VM it removed stops being. @param {HostProfile} host @param {string[]} args */ +export async function afterHostCommand(host, args) { + const g = grantNow(); + const [cmd] = args; + const names = cmd === "new" ? [args[1]] : cmd === "fork" ? forkTargets(args) : cmd === "rm" ? [args[1]] : []; + for (const n of names) keys.delete(`${host.name}/${host.dir}/${n}`); + if (g.kind === "unscoped" || !names.length) return; + if (cmd === "rm") { + // So a VM later made under that name isn't the token's. + editStore((entries) => { + const e = entries.find((t) => t.id === g.id); + if (e) e.owned = e.owned.filter((o) => !(o.host === host.name && o.vm === args[1])); + }); + return; + } + const platform = PLATFORM_KEY_BACKENDS.includes(hostBackend(host) ?? ""); + /** @type {Owned[]} */ + const owned = []; + for (const vm of names) owned.push({ host: host.name, vm, key: platform ? null : await currentKey(host, vm, true) }); + recordOwned(g.id, owned); +} + +// ---------------------------------------------------------------- for the tool layer + +/** May the current grant use TOOL (ACTION)? Throws the refusal the agent sees. @param {string} tool @param {string | null | undefined} action */ +export function authorizeTool(tool, action) { + const g = grantNow(); + if (g.kind === "unscoped") return; + const e = entryOf(g); + if (!toolAllowed(e.scope, tool, action)) throw refuse(g, action ? `${tool} ${action}` : tool); +} + +/** May the current grant use host NAME at all? (vm_manage host, the host argument.) @param {string} name */ +export function authorizeHostName(name) { + const g = grantNow(); + if (g.kind === "unscoped") return; + if (!hostsOf(entryOf(g), g).includes(name)) throw refuse(g, `host ${name}`); +} + +/** For listings: does VM on host HOST belong in what the current grant sees? (Patterns, leases and owned + * names; a name it can see but no longer owns is refused when used.) @param {string} host @param {string} vm */ +export function visibleVm(host, vm) { + const g = grantNow(); + if (g.kind === "unscoped") return true; + let e; + try { e = entryOf(g); } catch { return false; } + return hostsOf(e, g).includes(host) && (e.scope.vms.some((p) => matches(p, vm)) || !!g.leased?.(host, vm) || e.owned.some((o) => o.host === host && o.vm === vm)); +} +/** @param {string} host */ +export function visibleHost(host) { + const g = grantNow(); + if (g.kind === "unscoped") return true; + try { return hostsOf(entryOf(g), g).includes(host); } catch { return false; } +} + +/** The current grant's tool filter: (tool, actions) → whether any action of it is allowed. */ +export function toolFilter() { + const g = grantNow(); + if (g.kind === "unscoped") return () => true; + const e = tokenById(g.id); + return (/** @type {string} */ tool, /** @type {readonly string[] | null} */ actions) => !!e && (actions ? actions.some((a) => toolAllowed(e.scope, tool, a)) : toolAllowed(e.scope, tool, null)); +} + +/** One line for the agent's instructions: what this connection may do (empty when unscoped). */ +export function describeGrant() { + const g = grantNow(); + if (g.kind === "unscoped") return ""; + const e = tokenById(g.id); + return e ? `This connection uses token '${g.label}', which allows only: ${describeScope(e.scope, g.defaultHost)}. Other tools, VMs and hosts are refused; don't work around that, ask the user.` : ""; +} diff --git a/core/mcp-tokens.mjs b/core/mcp-tokens.mjs new file mode 100644 index 0000000..b95c132 --- /dev/null +++ b/core/mcp-tokens.mjs @@ -0,0 +1,205 @@ +// Scoped bearer tokens for the HTTP MCP server (#3): the store and what a scope allows. The store is +// $BOXERY_HOME/mcp-tokens.json (0600) on the machine running the server, beside the host registry it reads; +// a host never sees it. Each entry keeps a SHA-256 of its secret (32 random bytes, so no key stretching is +// needed), a label, an optional expiry, its scope, and the VMs created through it ("owned", each with the +// ssh host key it had then, so a VM later made under the same name by someone else isn't owned). +// Read as the proxy reads tokens.json: a stat per call, parsed again only when the file changes, so +// `boxery mcp-token rm` and expiry count from the next request. Written under a lock file, then renamed. +// No imports beyond node: builtins and fsutil: the CLI, the MCP server and core/mcp-auth.mjs share it. +import { createHash, randomBytes } from "node:crypto"; +import { closeSync, mkdirSync, openSync, readFileSync, rmSync, statSync } from "node:fs"; +import { homedir } from "node:os"; +import path from "node:path"; +import { writeAtomic } from "./fsutil.mjs"; + +/** Tool → its actions (tools with an `action` enum), or null (no actions). From core/boxery-tools.mjs TOOLS. + * @typedef {Record} Catalog */ +/** tools: tool → true (every action) or the actions allowed. hosts: host names (null: the server's own host). + * vms: name patterns (`*` matches any run of characters). admin: host-wide work (build-base, adding and + * removing hosts, pool leases, any host command not listed in core/mcp-auth.mjs). + * @typedef {{ tools: Record, hosts: string[] | null, vms: string[], admin: boolean }} Scope */ +/** A VM created through a token: its host, name, and ssh host key line hash then (null: the backend + * manages host keys itself, or the host predates pinned keys, so the name alone identifies it). + * @typedef {{ host: string, vm: string, key: string | null }} Owned */ +/** @typedef {{ id: string, label: string, hash: string, created: number, expires: number | null, scope: Scope, owned: Owned[] }} TokenEntry */ + +export const TOKEN_PREFIX = "bxm_"; +export const VALID_LABEL = /^[a-z0-9][a-z0-9._-]{0,63}$/; +const VALID_PATTERN = /^[a-z*][a-z0-9*-]{0,30}$/; +const VALID_HOST_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/; + +/** Host-wide actions only an admin token may take: they change the host for everyone, or hold pool VMs. */ +export const ADMIN_ACTIONS = { vm_manage: ["build-base", "host_add", "host_rm"], vm_lease: ["acquire", "renew", "release", "list"] }; +/** Tools that only look (their MCP annotation readOnlyHint). */ +export const READ_ONLY_TOOLS = ["vm_read", "vm_screenshot", "vm_info"]; + +export const storeFile = () => path.join(path.resolve(process.env.BOXERY_HOME ?? path.join(homedir(), ".boxery")), "mcp-tokens.json"); +const sha = (/** @type {string} */ s) => createHash("sha256").update(s).digest("hex"); +/** sha256 of an ssh host key line, as Owned.key keeps it (whitespace-normalized). @param {string} line */ +export const keyHash = (line) => sha(line.trim().split(/\s+/).slice(-2).join(" ")); + +// ---------------------------------------------------------------- scope + +/** `*` as "any run of characters", the rest literal. @param {string} pattern @param {string} name */ +export const matches = (pattern, name) => new RegExp(`^${pattern.split("*").map((s) => s.replace(/[.+?^${}()|[\]\\-]/g, "\\$&")).join(".*")}$`).test(name); + +/** Is TOOL's ACTION (null for tools without actions) allowed? Anything not listed is refused. + * @param {Scope} scope @param {string} tool @param {string | null | undefined} action */ +export function toolAllowed(scope, tool, action) { + const t = Object.hasOwn(scope.tools, tool) ? scope.tools[tool] : undefined; + if (t === undefined) return false; + if (action != null && !scope.admin && /** @type {Record} */ (ADMIN_ACTIONS)[tool]?.includes(action)) return false; + if (t === true) return true; + return action != null && t.includes(action); +} + +/** + * The tools part of a scope from --tools / --read-only (else every tool; admin actions still need --admin). + * spec: "vm_bash,vm_manage:new,vm_manage:snap". Unknown tools or actions are errors, not ignored. + * @param {Catalog} catalog @param {{ tools?: string | null, readOnly?: boolean }} opts @returns {Scope["tools"]} + */ +export function toolsScope(catalog, { tools, readOnly = false } = {}) { + if (tools != null && readOnly) throw new Error("use either --tools or --read-only"); + /** @type {Scope["tools"]} */ + const out = {}; + if (readOnly) { + for (const t of READ_ONLY_TOOLS) if (Object.hasOwn(catalog, t)) out[t] = true; + return out; + } + if (tools == null) { + for (const t of Object.keys(catalog)) out[t] = true; + return out; + } + for (const item of tools.split(",").map((s) => s.trim()).filter(Boolean)) { + const [tool, action, ...rest] = item.split(":"); + if (rest.length || !Object.hasOwn(catalog, tool)) throw new Error(`unknown tool in --tools: ${item} (tools: ${Object.keys(catalog).join(", ")})`); + const actions = catalog[tool]; + if (action === undefined) { out[tool] = true; continue; } + if (!actions?.includes(action)) throw new Error(`${tool} has no action ${action}${actions ? ` (actions: ${actions.join(", ")})` : ""}`); + const cur = out[tool]; + if (cur !== true) out[tool] = [...(cur ?? []), action]; + } + if (!Object.keys(out).length) throw new Error("--tools allows nothing"); + return out; +} + +/** --vm patterns, checked. @param {string[]} patterns */ +export function vmPatterns(patterns) { + for (const p of patterns) if (!VALID_PATTERN.test(p)) throw new Error(`invalid --vm pattern: ${p} (a VM name, * for any characters)`); + return [...new Set(patterns)]; +} + +/** --host names, checked (whether they're registered is the caller's to check). @param {string[]} hosts */ +export function hostNames(hosts) { + for (const h of hosts) if (!VALID_HOST_NAME.test(h)) throw new Error(`invalid --host: ${h}`); + return hosts.length ? [...new Set(hosts)] : null; +} + +/** "30d", "12h", "90m", "never" → seconds, or null for never. @param {string} ttl */ +export function parseTtl(ttl) { + if (ttl === "never") return null; + const m = /^([1-9][0-9]{0,5})([mhd])$/.exec(ttl); + if (!m) throw new Error(`invalid --ttl: ${ttl} (like 90m, 12h, 30d, or never)`); + return Number(m[1]) * { m: 60, h: 3600, d: 86_400 }[/** @type {"m" | "h" | "d"} */ (m[2])]; +} + +/** One line for a person or the agent: what a scope allows. @param {Scope} s @param {string} defaultHost */ +export function describeScope(s, defaultHost) { + const tools = Object.entries(s.tools).map(([t, a]) => (a === true ? t : `${t} (${a.join(", ")})`)).join(", "); + const vms = [...s.vms.map((p) => `${p}`), "the VMs created with this token"].join(", "); + return `tools: ${tools}; VMs: ${vms}; hosts: ${(s.hosts ?? [defaultHost]).join(", ")}${s.admin ? "; admin" : ""}`; +} + +// ---------------------------------------------------------------- store + +/** @type {{ key: string, entries: TokenEntry[] } | null} */ +let cache = null; +/** Every entry, as the file is now ([] when there is none). Throws on a file that isn't a token store. @returns {TokenEntry[]} */ +export function readStore(file = storeFile()) { + let st; + try { st = statSync(file, { bigint: true }); } catch { cache = null; return []; } + const key = `${file}:${st.dev}:${st.ino}:${st.size}:${st.mtimeNs}:${st.ctimeNs}`; + if (cache?.key !== key) { + const j = JSON.parse(readFileSync(file, "utf8")); + if (!Array.isArray(j?.tokens)) throw new Error(`${file} is not a boxery MCP token store`); + cache = { key, entries: j.tokens }; + } + return cache.entries; +} + +/** Change the store under its lock (one writer at a time; readers see the old or the new file whole). + * @template T @param {(entries: TokenEntry[]) => T} change @returns {T} */ +export function editStore(change, file = storeFile()) { + mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 }); + const lock = `${file}.lock`; + let fd; + for (let i = 0; ; i++) { + try { fd = openSync(lock, "wx", 0o600); break; } + catch (e) { + if (/** @type {NodeJS.ErrnoException} */ (e).code !== "EEXIST") throw e; + // A lock older than 30 s belongs to a process that died holding it. + try { if (Date.now() - statSync(lock).mtimeMs > 30_000) rmSync(lock, { force: true }); } catch { /* gone */ } + if (i >= 200) throw new Error(`${lock} is held; retry`); + Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 25); + } + } + try { + const entries = structuredClone(readStore(file)); + const out = change(entries); + writeAtomic(file, `${JSON.stringify({ tokens: entries }, null, 1)}\n`, { mode: 0o600 }); + return out; + } finally { + closeSync(fd); + rmSync(lock, { force: true }); + } +} + +/** + * A new token LABEL with SCOPE. Returns the secret (shown once; only its hash is kept). + * @param {string} label @param {Scope} scope @param {{ ttl?: number | null, now?: number }} [opts] @returns {{ secret: string, entry: TokenEntry }} + */ +export function createToken(label, scope, { ttl = 30 * 86_400, now = Math.floor(Date.now() / 1000) } = {}, file = storeFile()) { + if (!VALID_LABEL.test(label)) throw new Error(`invalid label: ${label} (lowercase letters, digits, . _ -)`); + const secret = `${TOKEN_PREFIX}${randomBytes(32).toString("base64url")}`; + const entry = { id: randomBytes(8).toString("hex"), label, hash: sha(secret), created: now, expires: ttl == null ? null : now + ttl, scope, owned: [] }; + editStore((entries) => { + if (entries.some((e) => e.label === label)) throw new Error(`a token labelled ${label} exists; remove it first (boxery mcp-token rm ${label})`); + entries.push(entry); + }, file); + return { secret, entry }; +} + +/** Remove token LABEL. Returns whether it existed. @param {string} label */ +export const removeToken = (label, file = storeFile()) => editStore((entries) => { + const i = entries.findIndex((e) => e.label === label); + if (i >= 0) entries.splice(i, 1); + return i >= 0; +}, file); + +/** + * The entry SECRET belongs to: {entry} if it's valid now, {expired: label} if it was, null otherwise. + * Looked up by hash: comparing hashes of a 256-bit secret leaks nothing useful through timing. + * @param {unknown} secret @returns {{ entry: TokenEntry } | { expired: string } | null} + */ +export function verifyToken(secret, { now = Math.floor(Date.now() / 1000) } = {}, file = storeFile()) { + if (typeof secret !== "string" || !secret.startsWith(TOKEN_PREFIX)) return null; + const h = sha(secret); + let entries; + try { entries = readStore(file); } catch { return null; } // a broken store refuses everyone + const entry = entries.find((e) => e.hash === h); + if (!entry) return null; + return entry.expires != null && entry.expires <= now ? { expired: entry.label } : { entry }; +} + +/** The current entry with ID (null once removed). @param {string} id */ +export function tokenById(id, file = storeFile()) { + try { return readStore(file).find((e) => e.id === id) ?? null; } catch { return null; } +} + +/** Record VMs created through token ID (replacing older records of the same host and name). + * @param {string} id @param {Owned[]} vms */ +export const recordOwned = (id, vms, file = storeFile()) => editStore((entries) => { + const e = entries.find((t) => t.id === id); + if (!e) return; + e.owned = [...e.owned.filter((o) => !vms.some((v) => v.host === o.host && v.vm === o.vm)), ...vms]; +}, file); diff --git a/core/profile.mjs b/core/profile.mjs index 0c61e79..be22893 100644 --- a/core/profile.mjs +++ b/core/profile.mjs @@ -8,6 +8,7 @@ import os, { homedir } from "node:os"; import path from "node:path"; import { BOXERY_HOME, currentHost, defaultHost } from "./boxery-core.mjs"; import { writeAtomic } from "./fsutil.mjs"; +import { afterHostCommand, authorizeHostCommand } from "./mcp-auth.mjs"; import { DEFAULT_HOST_BIN, checkTarget, localHostBin, parseConfig, remoteCommand, renderSshConfig } from "./ssh-config.mjs"; /** @import { HostProfile } from "./boxery-core.mjs" */ /** @import { Target } from "./ssh-config.mjs" */ @@ -104,9 +105,11 @@ export function hostCommand(host, c, args) { * @param {string[]} args @param {HostRunOpts} [opts] @returns {Promise} */ export async function hostRun(args, { input, signal, host = currentHost(), timeout = 120_000, stdin = "pipe", stdout = "pipe", stderr = "pipe", raw = false, config, onData } = {}) { + // Scoped MCP tokens (core/mcp-auth.mjs): every host command is checked here, where it is finally sent. + await authorizeHostCommand(host, args); const c = config ?? await profileConfig(host, { signal }); const [cmd, argv] = hostCommand(host, c, args); - return new Promise((resolve, reject) => { + const result = await new Promise((/** @type {(out: string) => void} */ resolve, reject) => { const child = spawn(cmd, argv, { stdio: [stdin, stdout, stderr], signal, env: c.env }); running.add(child); child.once("close", () => running.delete(child)); child.once("error", () => running.delete(child)); // Our own timer, not spawn's: that one is never cleared when the command can't start (ENOENT), and @@ -147,6 +150,9 @@ export async function hostRun(args, { input, signal, host = currentHost(), timeo child.stdin?.on("error", () => {}); // EPIPE if the command exits before reading child.stdin?.end(input); }); + // (The command succeeded either way: a VM whose ownership couldn't be recorded is just not the token's.) + await afterHostCommand(host, args).catch(() => {}); + return result; } /** Does the host support something its `help` shows (PATTERN)? Remembered in the profile as MARKER once it diff --git a/core/sync.mjs b/core/sync.mjs index f1d5417..c4cf8f0 100644 --- a/core/sync.mjs +++ b/core/sync.mjs @@ -10,6 +10,7 @@ import { homedir, tmpdir } from "node:os"; import path from "node:path"; import { q } from "./shell.mjs"; import { PROJECT, assertName, confineLocal, currentHost, deniedDirs, isWithin, sshRun, vmPath } from "./boxery-core.mjs"; +import { authorizeVm } from "./mcp-auth.mjs"; /** @import { LocalConfinement, ToolResult } from "./boxery-core.mjs" */ /** @typedef {{ from?: string, to?: string }} SyncParams */ /** @typedef {{ localCwd?: string, local?: LocalConfinement | false, signal?: AbortSignal }} SyncOpts */ @@ -329,6 +330,7 @@ export async function syncTool(vm, { from, to } = {}, { localCwd = process.cwd() const created = probe.state !== "repo"; if (created) await guest(vm, { MODE: "init", DIR: dest, FORMAT: s.format }); try { + await authorizeVm(host, vm); // git's own ssh carries no context: scoped MCP tokens (core/mcp-auth.mjs) objects = (await push(bare, vm, host.sshConf, dest, ref, signal)) ?? 0; } catch (e) { if (created) await guest(vm, { MODE: "uninit", DIR: dest }).catch(() => {}); diff --git a/docs/cli.md b/docs/cli.md index c4ff801..de10583 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -396,6 +396,7 @@ Generated from the help `boxery help --all` shows (`controller/cli.mjs`); edit i | Command | What it does | |---|---| +| `boxery mcp-token new LABEL [--vm PATTERN]... [--host NAME]... [--tools TOOL[:ACTION],... \| --read-only] [--admin] [--ttl 30d\|12h\|never]`
`boxery mcp-token ls [--json]`
`boxery mcp-token rm LABEL` | Scoped tokens for the HTTP MCP server (boxery-mcp --http) [→](mcp.md#scoped-tokens) | | `boxery pin NAME [--from-guest]` | Re-pin a VM's ssh host key (VMs made before keys were pinned) [→](security.md#vm-host-keys) | | `boxery shapes [--json]` | VM sizes on every host (* = default; --host NAME: one) [→](shapes.md) | | `boxery version [--json]` | Controller and every host's version; warns per host | diff --git a/docs/mcp.md b/docs/mcp.md index ab11713..3da6417 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -79,6 +79,29 @@ With `--copy-root DIR`, `local:` paths are confined to `DIR`: The `initialize` instructions and the `vm_copy` and `vm_sync` descriptions tell the agent which of the two applies. stdio mode is unchanged: there `local:` is your own machine. `--copy-root` confines it there too, if you want that. +### Scoped tokens + +`BOXERY_MCP_TOKEN` (or `--token-file`) is one unscoped token: whoever holds it can use every tool on every VM and host the server reaches, and the server logs a warning when it has one. To give a client less, mint a scoped token on the machine running the server, and give it that instead: + +```bash +boxery mcp-token new ci-agent --ttl 7d # its own VMs only, on the server's --host +boxery mcp-token new viewer --vm 'demo-*' --read-only # look at the demo VMs, change nothing +boxery mcp-token new ops --host hornet --tools vm_bash,vm_info --vm 'web-*' +boxery mcp-token ls +boxery mcp-token rm viewer # refused from its next request +``` + +The server starts with scoped tokens alone (no `BOXERY_MCP_TOKEN` needed), and accepts both kinds when it has both. A scoped token reaches: + +- **Tools:** all of them by default, or `--tools vm_bash,vm_manage:new,…` (a tool, or one action of it), or `--read-only` (`vm_read`, `vm_screenshot`, `vm_info`). The client's tool list shows only these, and the `initialize` instructions say what the token allows. +- **Hosts:** the server's `--host` by default, or each `--host NAME`. +- **VMs:** those matching a `--vm` pattern (`*` matches any characters: any VM of that name, whoever made it), and those it created itself (`new`, `fork`, `use` of a missing VM). A created VM is recorded with its ssh host key: if it is removed and someone else makes a VM of the same name, that one isn't the token's. On backends that manage host keys themselves (boat, OpenShell), the name alone identifies it, and `mcp-token ls` says so. +- **Admin work** only with `--admin`: `build-base`, `host_add`, `host_rm`, pool leases (`vm_lease`), and any other host-wide command. + +Anything else is refused with a message that names the token and tells the agent to ask the user; it reads the same whether or not the VM exists. The check runs where boxery acts (every ssh to a VM and every host command), not only when a tool starts, so no way of naming a VM (`HOST/VM:path`, `VM@SNAP`, fork targets, generated names) gets around it. `vm_info list`, `images` and `hosts` show only what the token reaches; other output (a name that's taken, an error from the host) can still reveal that a VM exists, but not let the token use it. + +Tokens are stored hashed in `~/.boxery/mcp-tokens.json` (mode 0600), which `vm_copy` and `vm_grant` refuse to read. They expire after `--ttl` (default 30 days; `never` for none). A session belongs to the token, and tailnet user, that opened it: another can't use or end it. `rm`, expiry and changes to the token file take effect at the next request, without a restart. + ## Protocol features The server speaks MCP `2024-11-05` through `2025-11-25` and sends newer fields only to clients that negotiated them, so older clients see the same responses as before. @@ -178,7 +201,7 @@ commit outcome**, not rollback: reread before retrying. | `--host NAME` | Registered startup host (otherwise the controller default). Each HTTP session keeps its own host and VM. | | `--vm NAME` | Default VM. Without it, the model picks one with `vm_manage {action:"use"}`, and tools fail closed when no `vm` is given. | | `--http ADDR:PORT` | Serve Streamable HTTP at `/mcp` instead of stdio. Each MCP session keeps its own current VM. | -| `--token-file PATH` | Bearer token from a file instead of `$BOXERY_MCP_TOKEN` | +| `--token-file PATH` | The unscoped bearer token from a file instead of `$BOXERY_MCP_TOKEN` (or neither: [scoped tokens](#scoped-tokens) only). The file is read again when it changes, so writing a new token there revokes the old one at the next request, without a restart. While the file is missing or empty, every request is refused. | | `--copy-root DIR` | Allow `vm_copy` `local:` paths and `vm_sync` checkouts, confined to `DIR` (see [B](#b-streamable-http-on-the-host-over-tailscale)). Over HTTP, both are refused without it. | | `--allow-user LOGIN` | Also require this `Tailscale-User-Login` header (set by `tailscale serve`). Loopback binds only. Can be repeated. | | `--allow-origin ORIGIN` | Accept requests with this `Origin`. Foreign origins are rejected by default. | diff --git a/docs/security.md b/docs/security.md index a327bf5..b555cf5 100644 --- a/docs/security.md +++ b/docs/security.md @@ -87,7 +87,7 @@ VM: pi/opencode ──► 127.0.0.1:8088 ──vsock──► host: boxery-proxy - A host-side HTTP proxy or DNS resolver on `127.0.0.1` is out of reach for Lima guests too. Confined qemu instances use slirp's DNS forwarder (`192.168.5.3`) instead of Lima's host resolver, which listens on loopback. - **Proxy spend.** A guest with root can read its own token and spend through every provider it's been granted. That's the same blast radius as handing it an API key, except the token is revocable per VM and logged. Per-VM budgets are planned. - **Grant front-ends require confirmation by default.** `vm_grant` adds a grant only after you approve a boxery-generated client elicitation or pi dialog. The CLI asks on `/dev/tty` (not stdin), defaults to No, and refuses without a controlling terminal. This covers `grant`, `agent-forward on`, creation-time grants and `fork --grants`; re-applying existing grants and revocation never prompt. Both front-ends call shared operations; tool approval does not invoke the CLI or use a prompt-bypass flag. It can't ask for `http:` grants with a `--cmd`, files in `~/.ssh`, `~/.gnupg`, `~/.pi` or boxery's own config (the same set `vm_copy --copy-root` refuses), or `env:BOXERY_*` variables such as the HTTP MCP token ([Agents can ask](grants.md#agents-can-ask)). A requested file is stored by its real path, and an apply skips any granted file that has since been re-pointed through a symlink into one of those directories. The CLI enforces the same deny-directory and `BOXERY_*` rules. A client hook or setting that auto-accepts MCP elicitations would also auto-accept these. Headless automation may explicitly put `GRANT_CONFIRM=off` in a host profile's `config`: **this turns off CLI grant confirmation protection for that profile**, not MCP/pi dialogs or validation. No flag or environment variable skips CLI confirmation. **This is friction, not a security boundary:** an agent running as the user can fake a terminal (`script`, `expect`, tmux), change the profile or call internal operations directly. -- **HTTP MCP runs on the control plane.** `boxery-mcp --http` runs next to the credentials it protects, so its `vm_copy` refuses `local:` endpoints unless you start it with `--copy-root DIR`, which confines them to `DIR` and still refuses boxery's config, `~/.ssh`, `~/.gnupg` and `~/.pi` ([details](mcp.md#b-streamable-http-on-the-host-over-tailscale)). Anyone with the bearer token can drive every VM on that host; keep it on the tailnet behind `--allow-user`. +- **HTTP MCP runs on the control plane.** `boxery-mcp --http` runs next to the credentials it protects, so its `vm_copy` refuses `local:` endpoints unless you start it with `--copy-root DIR`, which confines them to `DIR` and still refuses boxery's config, `~/.ssh`, `~/.gnupg` and `~/.pi` ([details](mcp.md#b-streamable-http-on-the-host-over-tailscale)). Anyone with its unscoped token (`BOXERY_MCP_TOKEN`) can drive every VM on every host it reaches; give clients [scoped tokens](mcp.md#scoped-tokens) (`boxery mcp-token new`) instead, limited to some tools, hosts and VMs, expiring and revocable one by one. Each is checked where boxery acts (every ssh to a VM and host command), and a session belongs to the token that opened it. Keep the server on the tailnet behind `--allow-user` either way: a scoped token still reaches everything inside its scope. - **Pushed grants are readable.** `env:`/`file:` values (and the ssh-agent while connected) can be used or read by whatever runs in the VM. Grant dev-scoped credentials only, and prefer `http:` grants, whose values stay on the host. - **Desktops from older bases have no VNC password.** The password is part of the desktop base image. VMs made from a base built before it have an open VNC server, and so do their snapshots and images: while a `boxery desktop` tunnel is open, any local process or web page can drive that desktop, including its logged-in browser. `boxery desktop` warns when it opens one. Rebuild the base (`boxery build-base`) and create those VMs again ([details](cli.md#desktop-and-ports)). - **Desktop password limits.** VncAuth is old (a DES challenge-response, 8 characters at most). It stops processes and pages on your machine that would guess, but not anything that can read your browser's history: the URL is saved there, and its password works until the next `boxery desktop` or a reboot of the VM replaces it. TigerVNC blocks an address for a while after 5 failed logins. Every login through the tunnel comes from `127.0.0.1`, so a local process that keeps guessing can also lock you out for a while. diff --git a/mcp/boxery-mcp.mjs b/mcp/boxery-mcp.mjs index 0a195a2..aeecfe2 100755 --- a/mcp/boxery-mcp.mjs +++ b/mcp/boxery-mcp.mjs @@ -12,17 +12,22 @@ // "local" (vm_copy) and grant sources are the machine this server runs on. Over HTTP that is the // control plane, so vm_copy local: endpoints and vm_sync are refused unless --copy-root confines them. import { createHash, randomUUID, timingSafeEqual } from "node:crypto"; -import { readFileSync } from "node:fs"; +import { readFileSync, statSync } from "node:fs"; import http from "node:http"; import * as core from "../core/boxery-core.mjs"; import { HOST_PARAM, runTool, sameHost, TOOLS as SHARED_TOOLS, VM_PARAM } from "../core/boxery-tools.mjs"; +import { UNSCOPED, describeGrant, enforce, toolFilter, withGrant } from "../core/mcp-auth.mjs"; +import { readStore, verifyToken } from "../core/mcp-tokens.mjs"; /** @import { Lease } from "../core/boxery-core.mjs" */ +/** @import { Grant } from "../core/mcp-auth.mjs" */ /** @import { JsonSchema, ObjectSchema, Session as ToolSession, Tool, ToolContext } from "../core/boxery-tools.mjs" */ /** Sends one JSON-RPC message to the client. @typedef {(message: object) => unknown} Notify */ /** * One MCP client session: the shared tool session (current VM, host, leases; core/boxery-tools.mjs) plus protocol state. * pending: our requests to the client (elicitation) by id; approve: vm_grant's prompt (see elicitApprover). - * @typedef {ToolSession & { id: string, inflight: Map, protocolVersion: string, + * grant: what the session may do (core/mcp-auth.mjs); principal: who opened it (token and tailnet user), which + * every later request on it must match. + * @typedef {ToolSession & { id: string, grant: Grant, principal: string, inflight: Map, protocolVersion: string, * lastActive: number, pending: Map void>, requestSeq: number, ui?: boolean, elicit?: boolean, * approve?: (req: { message: string, send: Notify, signal: AbortSignal }) => Promise }} Session */ @@ -154,9 +159,10 @@ const TOOL_MAP = new Map([...TOOLS, ...VIEW_TOOLS].map((t) => [t.name, t])); /** @type {Set} */ const allSessions = new Set(); -function newSession() { +/** @param {Grant} [grant] @param {string} [principal] */ +function newSession(grant = UNSCOPED, principal = "") { const session = /** @type {Session} */ ({ - id: randomUUID(), host: DEFAULT_HOST, current: DEFAULT_VM, currentHost: DEFAULT_VM ? DEFAULT_HOST : null, inflight: new Map(), protocolVersion: PROTOCOL_VERSIONS.at(-1), lastActive: Date.now(), + id: randomUUID(), grant, principal, host: DEFAULT_HOST, current: DEFAULT_VM, currentHost: DEFAULT_VM ? DEFAULT_HOST : null, inflight: new Map(), protocolVersion: PROTOCOL_VERSIONS.at(-1), lastActive: Date.now(), // Session hooks for the shared vm_manage / vm_lease (core/boxery-tools.mjs). adopt(name, host) { session.current = name; session.host = session.currentHost = host; }, clear() { session.current = null; session.currentHost = null; }, @@ -175,14 +181,18 @@ function newSession() { if (session.current === l.name && sameHost(session.currentHost, l.host)) session.current = session.currentHost = null; }, }); + // A token's own leases are in its scope while the session holds them. + if (grant.kind === "token") session.grant = { ...grant, leased: (h, vm) => !!session.keeper.find(vm) && session.host.name === h }; allSessions.add(session); return session; } /** tools/list for this session: title/outputSchema only for clients on 2025-06-18 or later; vm_view only for MCP Apps clients. */ -const listTools = (/** @type {Session} */ session) => - [...TOOLS, ...(session.ui ? VIEW_TOOLS : [])].map(({ run: _r, noVm: _n, title, outputSchema, ...t }) => +const listTools = (/** @type {Session} */ session) => { + const allowed = withGrant(session.grant, toolFilter); + return [...TOOLS, ...(session.ui ? VIEW_TOOLS : [])].filter((t) => allowed(t.name, t.inputSchema.properties.action?.enum ?? null)).map(({ run: _r, noVm: _n, title, outputSchema, ...t }) => since(session, "2025-06-18") ? { ...t, title, ...(outputSchema ? { outputSchema } : {}) } : t); +}; /** * Progress reporter for one tools/call, or undefined when the client sent no progressToken. @@ -219,7 +229,7 @@ function progressReporter(token, notify, tool) { /** @param {Session} session */ async function endSession(session) { allSessions.delete(session); - await session.keeper.releaseAll(); + await withGrant(session.grant, () => session.keeper.releaseAll()); } /** Before the server exits: sessions' leases go back, and a host registration in progress gives the @@ -236,7 +246,8 @@ const instructions = (/** @type {Session} */ s) => host: s.host.name, localToolsNote: "Your other tools (shell, files) act on this machine, not a VM; use them only when you mean to work here.", - }) + (LOCAL_COPY_NOTE ? `\nvm_copy: ${LOCAL_COPY_NOTE}` : "") + (LOCAL_SYNC_NOTE ? `\nvm_sync: ${LOCAL_SYNC_NOTE}` : ""); + }) + (LOCAL_COPY_NOTE ? `\nvm_copy: ${LOCAL_COPY_NOTE}` : "") + (LOCAL_SYNC_NOTE ? `\nvm_sync: ${LOCAL_SYNC_NOTE}` : "") + + withGrant(s.grant, () => { const d = describeGrant(); return d ? `\n${d}` : ""; }); /** Send the client a request on this call's channel and resolve with its result. Abort sends notifications/cancelled. * @param {Session} session @param {Notify} send @param {string} method @param {object} params @param {AbortSignal} [signal] @returns {Promise} */ @@ -298,7 +309,11 @@ async function callTool(session, params, signal, progress, send) { * notify(message) sends a server notification tied to this request (progress), when the transport can. * @param {Session} session @param {any} msg @param {Notify} [notify] @returns {Promise} */ -async function handle(session, msg, notify) { +function handle(session, msg, notify) { + return withGrant(session.grant, () => dispatch(session, msg, notify)); +} +/** handle()'s body, inside the session's grant. @param {Session} session @param {any} msg @param {Notify} [notify] @returns {Promise} */ +async function dispatch(session, msg, notify) { const { id, method, params } = msg ?? {}; const isRequest = id !== undefined && id !== null; session.lastActive = Date.now(); @@ -403,15 +418,58 @@ const sha256 = (/** @type {string} */ s) => createHash("sha256").update(s).diges /** Constant-time string compare: equal-length digests, so neither the length nor the content leaks through timing. */ const secretEquals = (/** @type {unknown} */ got, /** @type {unknown} */ want) => typeof got === "string" && typeof want === "string" && timingSafeEqual(sha256(got), sha256(want)); +/** + * The current bearer token: $BOXERY_MCP_TOKEN, or --token-file read again whenever the file changes (a stat + * per request, as the proxy does for tokens.json), so rotating it revokes the old token without a restart. + * A missing or empty file gives no token, and every request is refused until it is fixed. + * @returns {() => string | undefined} + */ +function tokenSource() { + const file = TOKEN_FILE; + if (!file) { + const token = process.env.BOXERY_MCP_TOKEN; + return () => token; + } + /** @type {{ key: string, token: string | undefined } | null} */ + let cache = null; + return () => { + try { + const st = statSync(file, { bigint: true }); + const key = `${st.dev}:${st.ino}:${st.size}:${st.mtimeNs}:${st.ctimeNs}`; + if (cache?.key !== key) cache = { key, token: readFileSync(file, "utf8").trim() || undefined }; + return cache.token; + } catch { + cache = null; + return undefined; + } + }; +} + /** @param {string} listen */ function serveHttp(listen) { const [hostPart, portPart] = listen.includes(":") ? [listen.slice(0, listen.lastIndexOf(":")), listen.slice(listen.lastIndexOf(":") + 1)] : ["127.0.0.1", listen]; - const token = TOKEN_FILE ? readFileSync(TOKEN_FILE, "utf8").trim() : process.env.BOXERY_MCP_TOKEN; + const token = tokenSource(); const noAuth = has("--no-auth"); - if (!token && !noAuth) { - log("refusing to start: set BOXERY_MCP_TOKEN or --token-file (or --no-auth for local testing)"); + const hasScoped = () => { try { return readStore().length > 0; } catch { return false; } }; + if (!token() && !noAuth && !hasScoped()) { + log(`refusing to start: no token. Create a scoped one with \`boxery mcp-token new LABEL\`, or ${TOKEN_FILE ? `fix --token-file ${TOKEN_FILE} (missing or empty)` : "set BOXERY_MCP_TOKEN or --token-file"} (or --no-auth for local testing)`); process.exit(2); } + if (token()) log("warning: the BOXERY_MCP_TOKEN / --token-file token is unscoped (every tool, VM and host); prefer scoped tokens: boxery mcp-token new"); + // Every session's work runs inside its grant from here on; anything that loses it is refused. + enforce(); + /** Who a request is: the session grant and principal (token, then tailnet user), or why it is refused. + * @param {http.IncomingMessage} req @returns {{ grant: Grant, principal: string } | { error: string }} */ + const authenticate = (req) => { + if (noAuth) return { grant: UNSCOPED, principal: "none" }; + const authz = req.headers.authorization; + const legacy = token(); + if (legacy && secretEquals(authz, `Bearer ${legacy}`)) return { grant: UNSCOPED, principal: "legacy" }; + const m = typeof authz === "string" ? /^Bearer (\S+)$/.exec(authz) : null; + const v = m ? verifyToken(m[1]) : null; + if (v && "entry" in v) return { grant: { kind: "token", id: v.entry.id, label: v.entry.label, defaultHost: DEFAULT_HOST.name }, principal: `token:${v.entry.id}` }; + return { error: v && "expired" in v ? `token '${v.expired}' expired; ask the user for a new one (boxery mcp-token new)` : "unauthorized" }; + }; if (noAuth && !LOOPBACK.includes(hostPart)) { log("refusing to start: --no-auth serves every VM tool unauthenticated, so it only listens on loopback"); process.exit(2); @@ -438,17 +496,22 @@ function serveHttp(listen) { // DNS-rebinding guard: browsers send Origin; reject unknown ones. const origin = req.headers.origin; if (origin && !allowOrigins.includes(origin)) return send(403, { error: `origin not allowed: ${origin}` }); - if (!noAuth && !secretEquals(req.headers.authorization, `Bearer ${token}`)) return send(401, { error: "unauthorized" }, { "www-authenticate": "Bearer" }); + const auth = authenticate(req); + if ("error" in auth) return send(401, { error: auth.error }, { "www-authenticate": req.headers.authorization ? 'Bearer error="invalid_token"' : "Bearer" }); + let principal = auth.principal; if (allowUsers.length) { // Set by `tailscale serve` for requests from tailnet users (absent for tagged devices). const who = req.headers["tailscale-user-login"]; if (!who || !allowUsers.includes(String(who))) return send(403, { error: `tailnet user not allowed: ${who ?? "(none)"}` }); + principal += `|${who}`; } + // A session belongs to whoever opened it: another token (or tailnet user) can't use or end it. + const own = (/** @type {Session | undefined | "" } */ x) => (x && x.principal === principal ? x : undefined); const sid = /** @type {string | undefined} */ (req.headers["mcp-session-id"]); // node joins a repeated header if (req.method === "DELETE") { - const ended = sid && sessions.get(sid); + const ended = own(sid && sessions.get(sid)); if (ended) { - sessions.delete(sid); + sessions.delete(ended.id); await endSession(ended); } return send(204, null); @@ -474,10 +537,10 @@ function serveHttp(listen) { const msgs = Array.isArray(msg) ? msg : [msg]; let session; if (msgs.some((m) => m?.method === "initialize")) { - session = newSession(); + session = newSession(auth.grant, principal); sessions.set(session.id, session); } else { - session = sid && sessions.get(sid); + session = own(sid && sessions.get(sid)); if (!session) return send(404, { jsonrpc: "2.0", id: null, error: { code: -32001, message: "unknown or missing Mcp-Session-Id; re-initialize" } }); } res.on("close", () => { diff --git a/test/cli-contracts.test.mjs b/test/cli-contracts.test.mjs index 7a48545..9479d23 100644 --- a/test/cli-contracts.test.mjs +++ b/test/cli-contracts.test.mjs @@ -95,9 +95,9 @@ test("root flag aliases never resolve inherited object properties", () => { } }); -test("PRE_HOST is the controller-scope commands: help and setup", () => { +test("PRE_HOST is the controller-scope commands: help, mcp-token (this machine's MCP tokens) and setup", () => { assert.deepEqual([...PRE_HOST].sort(), commands.filter(([, , c]) => c.scope === "controller").map(([n]) => n).sort()); - assert.deepEqual([...PRE_HOST].sort(), ["help", "setup"]); + assert.deepEqual([...PRE_HOST].sort(), ["help", "mcp-token", "setup"]); }); test("every host-scope command is dispatched to a host: --host ghost reaches the host lookup, whatever the words", () => { diff --git a/test/fixtures/boxery-help-all.txt b/test/fixtures/boxery-help-all.txt index 60fd2d7..e93b970 100644 --- a/test/fixtures/boxery-help-all.txt +++ b/test/fixtures/boxery-help-all.txt @@ -81,6 +81,7 @@ boxery lease — borrow a VM from the shared pool: lease ls Your leases on every host (--host NAME: one) More: + mcp-token new|ls|rm Scoped tokens for the HTTP MCP server (boxery-mcp --http) pin NAME Re-pin a VM's ssh host key (VMs made before keys were pinned) shapes VM sizes on every host (* = default; --host NAME: one) version Controller and every host's version; warns per host diff --git a/test/fixtures/boxery-help.txt b/test/fixtures/boxery-help.txt index 646179d..28ad43e 100644 --- a/test/fixtures/boxery-help.txt +++ b/test/fixtures/boxery-help.txt @@ -38,6 +38,7 @@ Command families (boxery FAMILY --help): runners once|status|... GitHub Actions runners on pool VMs More: + mcp-token new|ls|rm Scoped tokens for the HTTP MCP server (boxery-mcp --http) pin NAME Re-pin a VM's ssh host key (VMs made before keys were pinned) shapes VM sizes on every host (* = default; --host NAME: one) version Controller and every host's version; warns per host diff --git a/test/help-drift.test.mjs b/test/help-drift.test.mjs index d9e42fd..a7cbd9b 100644 --- a/test/help-drift.test.mjs +++ b/test/help-drift.test.mjs @@ -26,6 +26,7 @@ const PARSED_IN = { grant: [["core/grant-approval.mjs", "parseGrantArgs"]], runners: [["controller/runners-once.mjs", "runnersOnce"]], version: [["controller/cli.mjs", "cmdVersion"]], + "mcp-token": [["controller/mcp-tokens.mjs", "mcpTokenCommand"]], }; // Flags in a handler that aren't its own options: arguments it gives ssh, gh or the VM helper. const NOT_OPTIONS = { diff --git a/test/mcp-tokens.test.mjs b/test/mcp-tokens.test.mjs new file mode 100644 index 0000000..07edd3e --- /dev/null +++ b/test/mcp-tokens.test.mjs @@ -0,0 +1,168 @@ +// Scoped MCP tokens (#3): the store and scope rules (core/mcp-tokens.mjs), and the guards that keep every +// place boxery acts behind core/mcp-auth.mjs. The HTTP server's use of them is in test/mcp.test.mjs. +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import { mkdtempSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { after, test } from "node:test"; +import { INFO_ACTIONS, LEASE_ACTIONS, MANAGE_ACTIONS, TOOLS, toolCatalog } from "../core/boxery-tools.mjs"; +import { HOST_COMMANDS as GUARDED, PLATFORM_KEY_BACKENDS } from "../core/mcp-auth.mjs"; +import { ADMIN_ACTIONS, createToken, keyHash, matches, parseTtl, readStore, recordOwned, removeToken, toolAllowed, toolsScope, verifyToken, vmPatterns } from "../core/mcp-tokens.mjs"; +import { HOST_COMMANDS } from "../host/help.mjs"; + +const ROOT = path.resolve(import.meta.dirname, ".."); +const dir = mkdtempSync(path.join(tmpdir(), "boxery-mcp-tokens-")); +after(() => rmSync(dir, { recursive: true, force: true })); +const store = path.join(dir, "mcp-tokens.json"); +const all = toolsScope(toolCatalog()); +/** @param {Partial} s */ +const scope = (s = {}) => ({ tools: all, hosts: null, vms: [], admin: false, ...s }); + +test("a token is shown once and stored hashed, 0600; verify finds it, refuses others, reports expiry", () => { + const { secret, entry } = createToken("ci", scope(), {}, store); + assert.match(secret, /^bxm_[A-Za-z0-9_-]{43}$/); + const text = readFileSync(store, "utf8"); + assert.ok(!text.includes(secret.slice(4)), "the secret itself is never written"); + assert.equal(statSync(store).mode & 0o777, 0o600); + assert.equal(/** @type {any} */ (verifyToken(secret, {}, store)).entry.id, entry.id); + for (const bad of [`${secret}x`, secret.slice(0, -1), "bxm_", "", null, 42, secret.replace("bxm_", "")]) assert.equal(verifyToken(bad, {}, store), null, String(bad)); + const old = createToken("old", scope(), { ttl: 60, now: 1000 }, store); + assert.deepEqual(verifyToken(old.secret, {}, store), { expired: "old" }); + assert.equal(createToken("never", scope(), { ttl: null }, store).entry.expires, null); + assert.throws(() => createToken("ci", scope(), {}, store), /a token labelled ci exists/); + assert.throws(() => createToken("Bad Label", scope(), {}, store), /invalid label/); +}); + +test("rm takes effect at the next verify (the store is re-read when it changes)", () => { + const { secret } = createToken("gone", scope(), {}, store); + assert.ok(verifyToken(secret, {}, store)); + assert.equal(removeToken("gone", store), true); + assert.equal(verifyToken(secret, {}, store), null); + assert.equal(removeToken("gone", store), false); +}); + +test("a store that isn't one refuses everyone instead of failing open", () => { + const broken = path.join(dir, "broken.json"); + writeFileSync(broken, '{"tokens": "nope"}'); + assert.throws(() => readStore(broken), /not a boxery MCP token store/); + assert.equal(verifyToken("bxm_x", {}, broken), null); +}); + +test("owned VMs: recorded per host and name, replacing an older record of the same VM", () => { + const { entry } = createToken("owner", scope(), {}, store); + recordOwned(entry.id, [{ host: "h", vm: "a", key: "k1" }], store); + recordOwned(entry.id, [{ host: "h", vm: "a", key: "k2" }, { host: "h2", vm: "a", key: null }], store); + assert.deepEqual(readStore(store).find((e) => e.id === entry.id)?.owned, [{ host: "h", vm: "a", key: "k2" }, { host: "h2", vm: "a", key: null }]); + assert.equal(keyHash("demo.boxery ssh-ed25519 AAAAC3 \n"), keyHash("ssh-ed25519 AAAAC3"), "the key, not the host label or spacing"); +}); + +test("tools are denied by default; admin actions need --admin even when the tool is allowed", () => { + const s = scope({ tools: toolsScope(toolCatalog(), { tools: "vm_bash,vm_manage:new,vm_manage:build-base,vm_lease" }) }); + assert.equal(toolAllowed(s, "vm_bash", null), true); + assert.equal(toolAllowed(s, "vm_read", null), false); + assert.equal(toolAllowed(s, "vm_manage", "new"), true); + assert.equal(toolAllowed(s, "vm_manage", "rm"), false); + assert.equal(toolAllowed(s, "vm_manage", "build-base"), false, "admin action without --admin"); + assert.equal(toolAllowed(s, "vm_lease", "acquire"), false); + assert.equal(toolAllowed({ ...s, admin: true }, "vm_manage", "build-base"), true); + assert.equal(toolAllowed({ ...s, admin: true }, "vm_lease", "acquire"), true); + const ro = toolsScope(toolCatalog(), { readOnly: true }); + assert.deepEqual(Object.keys(ro).sort(), ["vm_info", "vm_read", "vm_screenshot"]); + for (const t of Object.keys(ro)) assert.equal(TOOLS.find((x) => x.name === t)?.annotations.readOnlyHint, true, `${t} is annotated read-only`); + assert.throws(() => toolsScope(toolCatalog(), { tools: "vm_nope" }), /unknown tool/); + assert.throws(() => toolsScope(toolCatalog(), { tools: "vm_bash:x" }), /vm_bash has no action x/); + assert.throws(() => toolsScope(toolCatalog(), { tools: "vm_bash", readOnly: true }), /either --tools or --read-only/); +}); + +test("every admin action is a real action, and every action of every tool is either allowed or admin", () => { + for (const [tool, actions] of Object.entries(ADMIN_ACTIONS)) for (const a of actions) assert.ok(toolCatalog()[tool]?.includes(a), `${tool} ${a}`); + assert.deepEqual(toolCatalog().vm_manage, MANAGE_ACTIONS); + assert.deepEqual(toolCatalog().vm_info, INFO_ACTIONS); + assert.deepEqual(toolCatalog().vm_lease, LEASE_ACTIONS); +}); + +test("VM patterns: * is any run of characters, everything else literal", () => { + assert.ok(matches("demo-*", "demo-1") && matches("demo-*", "demo-") && matches("*", "x") && matches("a", "a")); + assert.ok(!matches("demo-*", "xdemo-1") && !matches("demo", "demo-1") && !matches("a-b", "axb")); + assert.throws(() => vmPatterns(["../x"]), /invalid --vm pattern/); + assert.throws(() => vmPatterns(["Demo"]), /invalid --vm pattern/); + assert.equal(parseTtl("never"), null); + assert.equal(parseTtl("90m"), 5400); + assert.equal(parseTtl("2d"), 172_800); + for (const bad of ["", "0d", "1y", "-1d", "1.5h"]) assert.throws(() => parseTtl(bad), /invalid --ttl/, bad); +}); + +test("the guarded host commands are real boxery-host commands", () => { + for (const c of Object.keys(GUARDED)) assert.ok(Object.hasOwn(HOST_COMMANDS, c), `core/mcp-auth.mjs guards ${c}, which boxery-host doesn't have`); +}); + +test("the backends identified by name alone are exactly those that manage host keys themselves", () => { + const declaring = readdirSync(path.join(ROOT, "host/backends")).filter((f) => f.endsWith(".sh") && /^\s*backend_platform_host_key\b|backend_platform_host_key\(\)/m.test(readFileSync(path.join(ROOT, "host/backends", f), "utf8"))).map((f) => f.slice(0, -3)).sort(); + assert.deepEqual([...PLATFORM_KEY_BACKENDS].sort(), declaring); +}); + +// Every place the core starts ssh to a VM or a host command, and what guards it. A new one fails here until it +// is checked by core/mcp-auth.mjs (or said here why it needs no check). +const SSH_SITES = { + "core/boxery-core.mjs": { count: 2, guard: /await authorizeVm\(/g, why: "sshRun and vmProblem" }, + "core/grant-operations.mjs": { count: 1, guard: /await authorizeVm\(/g, why: "applyGrants" }, + "core/desktop.mjs": { count: 1, guard: /await authorizeVm\(/g, why: "the desktop tunnel" }, + "core/profile.mjs": { count: 2, guard: /await authorizeHostCommand\(/g, why: "hostRun (every host command); the other is ssh -O exit, which only closes a shared connection" }, + "core/copy-stream.mjs": { count: 0, guard: null, why: "its ssh carries no host context: copyTool checks both endpoints before streamCopy" }, + "core/sync.mjs": { count: 1, guard: /await authorizeVm\(/g, why: "git push over ssh" }, +}; +test("every ssh to a VM and every host command goes through core/mcp-auth.mjs", () => { + for (const f of readdirSync(path.join(ROOT, "core")).filter((f) => f.endsWith(".mjs"))) { + const text = readFileSync(path.join(ROOT, "core", f), "utf8"); + const n = (text.match(/(?:spawn|execFile)\("ssh"|spawn\(cmd, argv|GIT_SSH_COMMAND/g) ?? []).length; + const site = /** @type {Record} */ (SSH_SITES)[`core/${f}`]; + if (!site) { assert.equal(n, 0, `core/${f} starts ssh or a host command: guard it (core/mcp-auth.mjs) and list it in SSH_SITES`); continue; } + assert.equal(n, site.count, `core/${f}: ssh/host command sites changed; check each is guarded and update SSH_SITES`); + if (site.guard) assert.ok((text.match(site.guard) ?? []).length >= 1, `core/${f} has no ${site.guard} guard`); + } + const core = readFileSync(path.join(ROOT, "core/boxery-core.mjs"), "utf8"); + assert.match(core, /for \(const loc of \[src, dst\]\) if \(loc\.vm\) await authorizeVm\(loc\.host, loc\.vm\);\n[^\n]*\n?[^]*?streamCopy\(/, "copyTool checks both endpoints before streamCopy"); +}); + +test("once enforced, an operation outside any grant is refused (fail closed); a scoped grant can't reach other VMs", () => { + const home = mkdtempSync(path.join(tmpdir(), "boxery-mcp-auth-")); + try { + const { entry } = createToken("t", scope({ vms: ["mine-*"] }), {}, path.join(home, "mcp-tokens.json")); + const script = ` + const auth = await import(${JSON.stringify(path.join(ROOT, "core/mcp-auth.mjs"))}); + const host = { name: "h", dir: "/nonexistent" }; + const out = []; + const tryIt = async (label, fn) => { try { await fn(); out.push(label + ": ok"); } catch (e) { out.push(label + ": " + e.message); } }; + await tryIt("unscoped before enforce", () => auth.authorizeVm(host, "any")); + auth.enforce(); + await tryIt("no grant", () => auth.authorizeVm(host, "any")); + await tryIt("no grant, host command", () => auth.authorizeHostCommand(host, ["rm", "any"])); + const g = { kind: "token", id: ${JSON.stringify(entry.id)}, label: "t", defaultHost: "h" }; + await auth.withGrant(g, async () => { + await tryIt("pattern", () => auth.authorizeVm(host, "mine-1")); + await tryIt("other VM", () => auth.authorizeVm(host, "theirs")); + await tryIt("other host", () => auth.authorizeVm({ name: "h2", dir: "/x" }, "mine-1")); + await tryIt("fork from other", () => auth.authorizeHostCommand(host, ["fork", "theirs", "mine-2"])); + await tryIt("new from other's image", () => auth.authorizeHostCommand(host, ["new", "mine-3", "--from", "theirs@s1"])); + await tryIt("new", () => auth.authorizeHostCommand(host, ["new", "mine-3"])); + await tryIt("admin", () => auth.authorizeHostCommand(host, ["build-base"])); + await tryIt("unknown command", () => auth.authorizeHostCommand(host, ["pool", "add", "mine-1"])); + await tryIt("listing", () => auth.authorizeHostCommand(host, ["ls", "--json"])); + out.push("visible: " + ["mine-1", "theirs"].filter((v) => auth.visibleVm("h", v)).join(",")); + }); + await auth.withGrant(auth.UNSCOPED, () => tryIt("legacy", () => auth.authorizeVm(host, "theirs"))); + console.log(out.join("\\n"));`; + const out = execFileSync(process.execPath, ["--input-type=module", "-e", script], { env: { ...process.env, BOXERY_HOME: home }, encoding: "utf8" }); + const refused = (/** @type {string} */ what) => new RegExp(`^${what}: .* is outside this token's scope \\(token 't'\\); ask the user`, "m"); + assert.match(out, /^unscoped before enforce: ok$/m, "stdio/pi/CLI: nothing changes until the HTTP server enforces"); + assert.match(out, /^no grant: boxery: refused: this operation has no MCP authorization context/m); + assert.match(out, /^no grant, host command: boxery: refused/m); + assert.match(out, /^pattern: ok$/m); + for (const r of ["other VM", "other host", "fork from other", "new from other's image", "admin", "unknown command"]) assert.match(out, refused(r)); + assert.match(out, /^new: ok$/m); + assert.match(out, /^listing: ok$/m); + assert.match(out, /^visible: mine-1$/m); + assert.match(out, /^legacy: ok$/m); + } finally { rmSync(home, { recursive: true, force: true }); } +}); diff --git a/test/mcp.test.mjs b/test/mcp.test.mjs index 6e7c95b..7fb0a6d 100644 --- a/test/mcp.test.mjs +++ b/test/mcp.test.mjs @@ -2,7 +2,7 @@ // (in a temp "VM home"), and a stub boxery-host answers controller operations. import assert from "node:assert/strict"; import { execFileSync, spawn, spawnSync } from "node:child_process"; -import { chmodSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; +import { chmodSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; import http from "node:http"; import { tmpdir } from "node:os"; import path from "node:path"; @@ -848,6 +848,43 @@ describe("http", () => { } }); + test("--token-file is read again when it changes: rotating it revokes the old token without a restart", async () => { + const tdir = mkdtempSync(path.join(tmpdir(), "boxery-mcp-token-")); + const file = path.join(tdir, "token"); + // Rotate the way an operator would: write a new file and rename it into place. + const rotate = (/** @type {string} */ value) => { + writeFileSync(`${file}.new`, value, { mode: 0o600 }); + renameSync(`${file}.new`, file); + }; + rotate("first-token\n"); + const tport = 20000 + Math.floor(Math.random() * 20000); + const q = spawn(process.execPath, [SERVER, "--http", `127.0.0.1:${tport}`, "--vm", "fakevm", "--token-file", file], { env: { ...env, BOXERY_MCP_TOKEN: "" }, stdio: "ignore" }); + const status = async (/** @type {string} */ t) => + (await fetch(`http://127.0.0.1:${tport}/mcp`, { method: "POST", headers: { ...H, authorization: `Bearer ${t}` }, body: JSON.stringify(init) })).status; + try { + let up = false; + for (let i = 0; i < 50 && !up; i++) { + up = await fetch(`http://127.0.0.1:${tport}/healthz`).then((r) => r.ok, () => false); + if (!up) await new Promise((r) => setTimeout(r, 100)); + } + assert.ok(up, "http server did not start"); + assert.equal(await status("first-token"), 200); + rotate("second-token\n"); + assert.equal(await status("first-token"), 401, "the old token stops working at once"); + assert.equal(await status("second-token"), 200, "the new token works without a restart"); + rmSync(file); + assert.equal(await status("second-token"), 401, "a missing token file refuses everything"); + assert.equal(await status("undefined"), 401, "including a guess at an unset token"); + writeFileSync(file, "\n"); + assert.equal(await status("second-token"), 401, "so does an empty one"); + } finally { + q.kill(); + rmSync(tdir, { recursive: true, force: true }); + } + const missing = spawn(process.execPath, [SERVER, "--http", "127.0.0.1:1", "--token-file", path.join(tdir, "nope")], { env: { ...env, BOXERY_MCP_TOKEN: "" }, stdio: "ignore" }); + assert.equal(await new Promise((r) => missing.on("exit", r)), 2, "refuses to start without a readable token file"); + }); + test("auth: token required, Tailscale user allowlist, Origin check", async () => { assert.equal((await post(init)).status, 401); for (const bad of ["Bearer nope", "Bearer t0ke", `Bearer ${token}x`, `Bearer ${token}${"x".repeat(4096)}`, token, `bearer ${token}`, "Bearer "]) { @@ -968,6 +1005,128 @@ describe("http", () => { }); }); +// Scoped tokens (#3, docs/mcp.md#scoped-tokens): a server with no unscoped token. Each refusal must happen +// before anything reaches the host (the stub's host.calls) or the VM (a marker file in the fake VM). +describe("http scoped tokens", () => { + let p, port, store; + const H = { "content-type": "application/json", accept: "application/json, text/event-stream" }; + const init = { jsonrpc: "2.0", id: 1, method: "initialize", params: { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "t", version: "0" } } }; + const post = (body, headers = {}) => fetch(`http://127.0.0.1:${port}/mcp`, { method: "POST", headers: { ...H, ...headers }, body: JSON.stringify(body) }); + /** A session for SECRET: { sid, call(tool, args) → result, list() → tool names, instructions }. */ + const open = async (/** @type {string} */ secret) => { + const auth = { authorization: `Bearer ${secret}` }; + const r = await post(init, auth); + assert.equal(r.status, 200, "initialize"); + const sid = /** @type {string} */ (r.headers.get("mcp-session-id")); + const { result } = await r.json(); + let id = 10; + const call = async (/** @type {string} */ name, /** @type {object} */ args) => (await (await post({ jsonrpc: "2.0", id: ++id, method: "tools/call", params: { name, arguments: args } }, { ...auth, "mcp-session-id": sid })).json()).result; + const list = async () => (await (await post({ jsonrpc: "2.0", id: ++id, method: "tools/list" }, { ...auth, "mcp-session-id": sid })).json()).result.tools.map((/** @type {{ name: string }} */ t) => t.name); + return { sid, call, list, instructions: /** @type {string} */ (result.instructions), auth }; + }; + const refused = (/** @type {any} */ r, /** @type {RegExp} */ what) => { + assert.equal(r.isError, true, JSON.stringify(r)); + assert.match(r.content[0].text, what); + assert.match(r.content[0].text, /outside this token's scope \(token '[a-z-]+'\); ask the user for a token that covers it/); + }; + let mcpTokens, catalog; + + before(async () => { + mcpTokens = await import("../core/mcp-tokens.mjs"); + catalog = (await import("../core/boxery-tools.mjs")).toolCatalog(); + store = path.join(dir, "home/mcp-tokens.json"); + registerHost(path.join(dir, "home"), "other", path.join(dir, "home")); // a second name for a host in no token's scope + port = 20000 + Math.floor(Math.random() * 20000); + p = spawn(process.execPath, [SERVER, "--http", `127.0.0.1:${port}`], { env: { ...env, BOXERY_MCP_TOKEN: "" }, stdio: "ignore" }); + // Starts with scoped tokens alone: the store needs one before the server looks. + mcpTokens.createToken("boot", { tools: { vm_info: true }, hosts: null, vms: [], admin: false }, {}, store); + for (let i = 0; i < 50; i++) { + try { if ((await fetch(`http://127.0.0.1:${port}/healthz`)).ok) return; } catch {} + await new Promise((r) => setTimeout(r, 100)); + } + throw new Error("http server did not start with scoped tokens only"); + }); + after(() => { p?.kill(); rmSync(path.join(dir, "home/host-registry/other"), { force: true }); rmSync(store, { force: true }); }); + const mint = (/** @type {string} */ label, /** @type {object} */ s = {}, /** @type {object} */ opts = {}) => + mcpTokens.createToken(label, { tools: mcpTokens.toolsScope(catalog), hosts: null, vms: [], admin: false, ...s }, opts, store).secret; + + test("a token for its own VMs: every way of naming another VM is refused before it reaches the host or the VM", async () => { + const c = await open(mint("own")); + assert.match(c.instructions, /token 'own', which allows only: .*VMs: the VMs created with this token; hosts: local/); + const marker = path.join(env.VMROOT, "pwned-by-scope"); + const before = hostArgs(dir).length; + refused(await c.call("vm_bash", { vm: "fakevm", command: "touch ~/pwned-by-scope" }), /VM 'fakevm' on host local/); + refused(await c.call("vm_manage", { action: "use", vm: "fakevm" }), /VM 'fakevm'/); + refused(await c.call("vm_read", { vm: "fakevm", path: "/etc/hostname" }), /fakevm/); + refused(await c.call("vm_jobs", { vm: "fakevm", action: "list" }), /fakevm/); + refused(await c.call("vm_grant", { vm: "fakevm", spec: "llm:openai", reason: "x" }), /fakevm/); + refused(await c.call("vm_copy", { from: "fakevm:/etc/hostname", to: "mine-x:/tmp/x" }), /fakevm/); + refused(await c.call("vm_copy", { from: "local/fakevm:/etc/hostname", to: "fakevm:/tmp/y" }), /fakevm/); + for (const a of [{ action: "rm", vm: "fakevm" }, { action: "snap", vm: "fakevm" }, { action: "revert", vm: "fakevm", snapshot: "s1" }, { action: "stop", vm: "fakevm" }, + { action: "fork", vm: "fakevm", to: ["mine-copy"] }, { action: "new", vm: "mine-img", from: "fakevm@s1" }]) refused(await c.call("vm_manage", a), /fakevm/); + refused(await c.call("vm_manage", { action: "build-base" }), /vm_manage build-base/); + refused(await c.call("vm_lease", { action: "acquire" }), /vm_lease acquire/); + refused(await c.call("vm_manage", { action: "host", host: "other" }), /host other/); + refused(await c.call("vm_info", { action: "list", host: "other" }), /host other/); + refused(await c.call("vm_manage", { action: "host_rm", name: "other" }), /vm_manage host_rm/); + assert.equal(existsSync(marker), false, "nothing ran in the VM"); + const reached = hostArgs(dir).slice(before); + for (const c2 of reached) assert.match(c2, /^(ls --json|known-hosts .*)$/, `only listings reached the host, not: ${c2}`); + assert.equal((await c.call("vm_info", { action: "list" })).structuredContent.vms.length, 0, "list shows only what the token reaches"); + assert.equal((await c.call("vm_info", { action: "images" })).structuredContent.images.length, 0); + assert.deepEqual((await c.call("vm_info", { action: "hosts" })).structuredContent.hosts.map((/** @type {{ name: string }} */ h) => h.name), ["local"]); + }); + + test("a VM the token creates is its own (bound to its host key); a VM reusing the name later isn't", async () => { + const c = await open(mint("maker")); + const made = await c.call("vm_manage", { action: "new", vm: "mine" }); + assert.equal(made.isError, false, JSON.stringify(made)); + assert.ok(hostArgs(dir).includes("new mine")); + const rec = mcpTokens.readStore(store).find((e) => e.label === "maker"); + assert.deepEqual(rec.owned.map((o) => [o.host, o.vm, typeof o.key]), [["local", "mine", "string"]], "recorded with its host key"); + assert.equal((await c.call("vm_manage", { action: "stop", vm: "mine" })).isError, false); + assert.deepEqual((await c.call("vm_info", { action: "list" })).structuredContent.vms.map((v) => v.name), [], "(the stub host lists only fakevm)"); + // The VM is removed and someone else makes one named "mine": its host key differs. + mcpTokens.editStore((entries) => { entries.find((e) => e.label === "maker").owned[0].key = "0".repeat(64); }, store); + await new Promise((r) => setTimeout(r, 10_100)); // past the key cache + refused(await c.call("vm_manage", { action: "stop", vm: "mine" }), /VM 'mine'/); + // rm through the token forgets it. + mcpTokens.editStore((entries) => { entries.find((e) => e.label === "maker").owned[0].key = null; }, store); + assert.equal((await c.call("vm_manage", { action: "rm", vm: "mine" })).isError, false); + assert.deepEqual(mcpTokens.readStore(store).find((e) => e.label === "maker").owned, []); + }); + + test("--vm patterns, --read-only and --tools: the tool list shows only what the token may use", async () => { + const w = await open(mint("worker", { vms: ["fake*"] })); + assert.match((await w.call("vm_bash", { vm: "fakevm", command: "echo in-scope" })).content[0].text, /in-scope/); + const ro = await open(mint("viewer", { vms: ["fakevm"], tools: mcpTokens.toolsScope(catalog, { readOnly: true }) })); + assert.deepEqual((await ro.list()).sort(), ["vm_info", "vm_read", "vm_screenshot"]); + refused(await ro.call("vm_write", { vm: "fakevm", path: "x", content: "y" }), /vm_write/); + const narrow = await open(mint("narrow", { vms: ["fakevm"], tools: mcpTokens.toolsScope(catalog, { tools: "vm_manage:snap" }) })); + assert.deepEqual(await narrow.list(), ["vm_manage"]); + refused(await narrow.call("vm_manage", { action: "rm", vm: "fakevm" }), /vm_manage rm/); + assert.equal((await narrow.call("vm_manage", { action: "snap", vm: "fakevm" })).isError, false); + }); + + test("sessions belong to the token that opened them; rm and expiry refuse from the next request", async () => { + const a = await open(mint("alice", { vms: ["fakevm"] })); + const bSecret = mint("bob", { vms: ["fakevm"] }); + const asBob = { authorization: `Bearer ${bSecret}`, "mcp-session-id": a.sid }; + assert.equal((await post({ jsonrpc: "2.0", id: 2, method: "tools/list" }, asBob)).status, 404, "another token can't use the session"); + assert.equal((await fetch(`http://127.0.0.1:${port}/mcp`, { method: "DELETE", headers: asBob })).status, 204); + assert.equal((await a.list()).length > 0, true, "nor end it"); + mcpTokens.removeToken("alice", store); + const r = await post({ jsonrpc: "2.0", id: 3, method: "tools/list" }, { ...a.auth, "mcp-session-id": a.sid }); + assert.equal(r.status, 401); + assert.equal(r.headers.get("www-authenticate"), 'Bearer error="invalid_token"'); + const old = mint("old", {}, { ttl: 60, now: 1000 }); + const e = await post(init, { authorization: `Bearer ${old}` }); + assert.equal(e.status, 401); + assert.match((await e.json()).error, /token 'old' expired; ask the user for a new one/); + assert.equal((await post(init)).headers.get("www-authenticate"), "Bearer", "no credentials: a plain challenge"); + }); +}); + /** A ustar archive from {name, type ("0" file, "1" hard link, "2" symlink, "5" dir), body, link}. For hostile-VM tests. */ function tarball(entries) { const blocks = entries.flatMap(({ name, type = "0", body = "", link = "" }) => { diff --git a/test/parity.test.mjs b/test/parity.test.mjs index 3bce5c4..d384589 100644 --- a/test/parity.test.mjs +++ b/test/parity.test.mjs @@ -59,6 +59,7 @@ const CLI_ONLY = { runners: "host admin: GitHub Actions runners on the pool, with a GitHub token that stays on the host", pin: "which ssh host key a VM is trusted with is the user's decision (--from-guest trusts the network once)", patch: "rewrites a VM's software and may restart it under running agents; the user's to run (vm_info list shows outdated VMs)", + "mcp-token": "minting MCP access is the user's decision; an agent never mints or widens its own token", }; // controller/cli.mjs's command table: every command, including those handled before a host is selected @@ -139,7 +140,7 @@ const NO_STATUS = { prompt: "starts a background job and returns; the job isn't this process", ssh: INTERACTIVE, attach: INTERACTIVE, forward: INTERACTIVE, desktop: INTERACTIVE, host: FAMILY, snapshot: FAMILY, agent: FAMILY, job: FAMILY, access: FAMILY, lease: FAMILY, - setup: BEFORE_HOST, help: BEFORE_HOST, + setup: BEFORE_HOST, help: BEFORE_HOST, "mcp-token": BEFORE_HOST, }; test("every CLI command declares a terminal status, or says why it has none", () => {