Public: anyone can read this; the crew can change it.
Crew runs can SSH to a device the repository names: an owner-granted host:22 plus a key from the repo's secrets (the arm's Pi) #3679
scout/forge:scout/3470-crew-runs-can-ssh-to-a-device-the-reposi → main 3 commits fork 7 threads · 7 unresolved
docs/APPS.md +28
| @@ -301,6 +301,34 @@ destination forge.json does not name is refused, and each change is an | ||
| 301 | 301 | `app.egress.granted` or `app.egress.revoked` event with who and when. There is |
| 302 | 302 | not yet a terminal command (#3469). |
| 303 | 303 | |
| 304 | ### Devices the crew may reach (#3470) | |
| 305 | ||
| 306 | A crew run's shell reaches the forge and the registry only, unless the | |
| 307 | repository has a granted device. A repository admin lists one with | |
| 308 | `POST /api/v1/repos/:owner/:name/crew-devices` and | |
| 309 | `{ "device": "[email protected]:22", "secret": "ARM_PI_SSH_KEY" }` (exact | |
| 310 | `user@host:port`, no range; the key is a secret set at the repository's own | |
| 311 | scope, never the forge's or an org's). A site admin grants it with | |
| 312 | `POST …/crew-devices/grant` and `{ "device": "…" }`; the forge reads the host | |
| 313 | key the device shows right then and pins it (or the admin sends `host_key`). | |
| 314 | `DELETE` unlists it; changing the secret drops the grant. A run then has | |
| 315 | exactly that `host:port` in its sandbox, a 0600 key file, a pinned | |
| 316 | `known_hosts` and a `ssh <alias>` config in its own temp directory (all gone | |
| 317 | when the run ends), and an `ssh` first on its PATH that notes each call. That note is the run's own | |
| 318 | self-reported record, kept where the run can write: it can be edited or | |
| 319 | bypassed, so it is not an audit, and the device's own logs are the audit. | |
| 320 | The key is also held by the push-time leak guard: a tree or commit holding it | |
| 321 | is scrubbed or refused. The | |
| 322 | brief names the device and the rules. `GET …/crew-devices` shows, to anyone | |
| 323 | who administers the repository, the devices and the sessions (`crew.device.session` | |
| 324 | events: who, when, the arguments the run reported). The rules for the | |
| 325 | device itself (restart only what sudo allows) are enforced on the device. | |
| 326 | The forge reads the run's note as hostile (no symlink, 64 KiB, 50 sessions, | |
| 327 | control characters stripped), and a hostname is resolved at grant and refused | |
| 328 | if any address is never-grantable. Until the settings row (#3684) and the MCP | |
| 329 | tools and terminal command (#3685) land, the JSON API is the only way to manage | |
| 330 | devices; this feature is not done until they do. | |
| 331 | ||
| 304 | 332 | A release that turns egress on must not break an app whose writers have |
| 305 | 333 | not declared what it uses yet, so the operator can start it reported: |
| 306 | 334 | `FORGE_CELLS_EGRESS=report` lets an undeclared public host through (on 80 |
src/actions/crew_devices.ts added +179
| @@ -0,0 +1,179 @@ | ||
| 1 | /** | |
| 2 | * The devices a repository's crew may SSH to (#3470). A repository admin | |
| 3 | * lists a device and the repo secret holding its key; a site admin grants it, | |
| 4 | * which pins the host key it shows right then. Every change is an event, and | |
| 5 | * so is every ssh session a run made, so who, when and which commands are on | |
| 6 | * the repository for its owner. | |
| 7 | */ | |
| 8 | ||
| 9 | import { lookup } from "node:dns/promises"; | |
| 10 | import { isIP } from "node:net"; | |
| 11 | import type { App } from "../app.ts"; | |
| 12 | import { | |
| 13 | addDevice, | |
| 14 | grantDevice, | |
| 15 | isHostKey, | |
| 16 | listDevices, | |
| 17 | parseDevice, | |
| 18 | removeDevice, | |
| 19 | type Device, | |
| 20 | } from "../core/crew_devices.ts"; | |
| 21 | import { neverGrantable } from "../core/egress_grants.ts"; | |
| 22 | import { listEvents } from "../core/events.ts"; | |
| 23 | import type { Repo } from "../core/repos.ts"; | |
| 24 | import { getUserById, type User } from "../core/users.ts"; | |
| 25 | import { scanHostKey, type HostKeyScan } from "../crew/hostkey.ts"; | |
| 26 | import { err, ok, type Result } from "../kernel/result.ts"; | |
| 27 | import { requireRepoAdmin } from "./access.ts"; | |
| 28 | ||
| 29 | export type DeviceError = "not_found" | "forbidden" | "invalid" | "no_host_key" | "no_such_device"; | |
| 30 | ||
| 31 | export interface DeviceRow { | |
| 32 | readonly entry: string; | |
| 33 | readonly secret: string; | |
| 34 | readonly granted: boolean; | |
| 35 | readonly grantedBy: string | null; | |
| 36 | readonly grantedAt: string | null; | |
| 37 | readonly hostKey: string | null; | |
| 38 | } | |
| 39 | ||
| 40 | export interface DeviceSession { | |
| 41 | readonly run: string; | |
| 42 | readonly by: string; | |
| 43 | readonly device: string; | |
| 44 | readonly at: string; | |
| 45 | readonly command: string; | |
| 46 | } | |
| 47 | ||
| 48 | const SESSIONS_SHOWN = 50; | |
| 49 | ||
| 50 | const nameOf = (app: App, id: string | null): string | null => | |
| 51 | id === null ? null : (getUserById(app.db, id)?.username ?? "someone"); | |
| 52 | ||
| 53 | const row = (app: App, d: Device): DeviceRow => ({ | |
| 54 | entry: d.entry, | |
| 55 | secret: d.secretName, | |
| 56 | granted: d.grantedBy !== null && d.hostKey !== null, | |
| 57 | grantedBy: nameOf(app, d.grantedBy), | |
| 58 | grantedAt: d.grantedAt, | |
| 59 | hostKey: d.hostKey, | |
| 60 | }); | |
| 61 | ||
| 62 | function admin(app: App, actor: User | undefined, repo: Repo): Result<User, "not_found"> { | |
| 63 | const checked = requireRepoAdmin(app, actor, repo); | |
| 64 | return checked.ok ? ok(checked.value) : err("not_found"); | |
| 65 | } | |
| 66 | ||
| 67 | /** The listed devices and the sessions the crew made on them; admin only. */ | |
| 68 | export function devicesView( | |
| 69 | app: App, | |
| 70 | actor: User | undefined, | |
| 71 | repo: Repo, | |
| 72 | ): Result<{ devices: DeviceRow[]; sessions: DeviceSession[]; canGrant: boolean }, "not_found"> { | |
| 73 | const who = admin(app, actor, repo); | |
| 74 | if (!who.ok) return who; | |
| 75 | const sessions = listEvents(app.db, { | |
| 76 | repoId: repo.id, | |
| 77 | kind: "crew.device.session", | |
| 78 | limit: SESSIONS_SHOWN, | |
| 79 | }).map((e) => ({ | |
| 80 | run: String(e.payload["run"] ?? ""), | |
| 81 | by: nameOf(app, e.actorId) ?? "someone", | |
| 82 | device: String(e.payload["device"] ?? ""), | |
| 83 | at: String(e.payload["at"] ?? e.createdAt), | |
| 84 | command: String(e.payload["args"] ?? ""), | |
| 85 | })); | |
| 86 | return ok({ | |
| 87 | devices: listDevices(app.db, repo.id).map((d) => row(app, d)), | |
| 88 | sessions, | |
| 89 | canGrant: who.value.isAdmin && who.value.kind !== "agent", | |
| 90 | }); | |
| 91 | } | |
| 92 | ||
| 93 | /** List a device and its key's secret name (not yet granted). */ | |
| 94 | export function addCrewDevice( | |
| 95 | app: App, | |
| 96 | actor: User | undefined, | |
| 97 | repo: Repo, | |
| 98 | entry: string, | |
| 99 | secret: string, | |
| 100 | ): Result<DeviceRow, DeviceError> { | |
| 101 | const who = admin(app, actor, repo); | |
| 102 | if (!who.ok) return who; | |
| 103 | if (who.value.kind === "agent") return err("forbidden"); | |
| 104 | const added = addDevice(app.db, repo.id, entry, secret.trim(), who.value); | |
| 105 | if (!added.ok) return err("invalid"); | |
| 106 | app.bus.append({ | |
| 107 | kind: "crew.device.listed", | |
| 108 | repoId: repo.id, | |
| 109 | actorId: who.value.id, | |
| 110 | payload: { device: added.value.entry, secret: added.value.secretName }, | |
| 111 | }); | |
| 112 | return ok(row(app, added.value)); | |
| 113 | } | |
| 114 | ||
| 115 | /** A site admin's grant: pins `hostKey` when given, else the key the device shows now. */ | |
| 116 | async function resolveHost(host: string): Promise<string[]> { | |
| 117 | try { | |
| 118 | return (await lookup(host, { all: true })).map((a) => a.address); | |
| 119 | } catch { | |
| 120 | return []; | |
| 121 | } | |
| 122 | } | |
| 123 | ||
| 124 | export async function grantCrewDevice( | |
| 125 | app: App, | |
| 126 | actor: User | undefined, | |
| 127 | repo: Repo, | |
| 128 | entry: string, | |
| 129 | hostKey: string, | |
| 130 | scan: HostKeyScan = scanHostKey, | |
| 131 | resolve: (host: string) => Promise<string[]> = resolveHost, | |
| 132 | ): Promise<Result<DeviceRow, DeviceError>> { | |
| 133 | const who = admin(app, actor, repo); | |
| 134 | if (!who.ok) return who; | |
| 135 | if (!who.value.isAdmin || who.value.kind === "agent") return err("forbidden"); | |
| 136 | const parsed = parseDevice(entry.trim()); | |
| 137 | if (!parsed.ok) return err("invalid"); | |
| 138 | if (!listDevices(app.db, repo.id).some((d) => d.entry === parsed.value.entry)) | |
| 139 | return err("no_such_device"); | |
| 140 | // A name that points at loopback or the cluster is refused like the literal. | |
| 141 | if (isIP(parsed.value.host) === 0) { | |
| 142 | const addresses = await resolve(parsed.value.host); | |
| 143 | if (addresses.length === 0 || addresses.some((a) => isIP(a) === 4 && neverGrantable(a))) | |
| 144 | return err("invalid"); | |
| 145 | } | |
| 146 | const key = hostKey.trim() !== "" ? hostKey.trim() : await scan(parsed.value.host, parsed.value.port); | |
| 147 | if (key === undefined || !isHostKey(key)) return err("no_host_key"); | |
| 148 | const granted = grantDevice(app.db, repo.id, parsed.value.entry, key, who.value); | |
| 149 | if (!granted.ok) return err("invalid"); | |
| 150 | app.bus.append({ | |
| 151 | kind: "crew.device.granted", | |
| 152 | repoId: repo.id, | |
| 153 | actorId: who.value.id, | |
| 154 | payload: { device: granted.value.entry, hostKey: key }, | |
| 155 | }); | |
| 156 | return ok(row(app, granted.value)); | |
| 157 | } | |
| 158 | ||
| 159 | /** Unlist a device, which takes its grant with it. */ | |
| 160 | export function removeCrewDevice( | |
| 161 | app: App, | |
| 162 | actor: User | undefined, | |
| 163 | repo: Repo, | |
| 164 | entry: string, | |
| 165 | ): Result<string, DeviceError> { | |
| 166 | const who = admin(app, actor, repo); | |
| 167 | if (!who.ok) return who; | |
| 168 | if (who.value.kind === "agent") return err("forbidden"); | |
| 169 | const parsed = parseDevice(entry.trim()); | |
| 170 | if (!parsed.ok) return err("invalid"); | |
| 171 | if (!removeDevice(app.db, repo.id, parsed.value.entry)) return err("no_such_device"); | |
| 172 | app.bus.append({ | |
| 173 | kind: "crew.device.removed", | |
| 174 | repoId: repo.id, | |
| 175 | actorId: who.value.id, | |
| 176 | payload: { device: parsed.value.entry }, | |
| 177 | }); | |
| 178 | return ok(parsed.value.entry); | |
| 179 | } |
src/core/crew_devices.ts added +152
| @@ -0,0 +1,152 @@ | ||
| 1 | /** | |
| 2 | * Devices a repository's crew may SSH to (#3470): `user@host:port`, exact, and | |
| 3 | * the name of the repository secret holding the key. A repository admin lists | |
| 4 | * a device; only a site admin's grant (which pins the host key) lets a run | |
| 5 | * reach it. Same exactness and never-grantable ranges as app egress. | |
| 6 | */ | |
| 7 | ||
| 8 | import type { Database } from "bun:sqlite"; | |
| 9 | import { isIP } from "node:net"; | |
| 10 | import { err, ok, type Result } from "../kernel/result.ts"; | |
| 11 | import { neverGrantable, parseDestination } from "./egress_grants.ts"; | |
| 12 | import { isSecretName } from "./secret_store.ts"; | |
| 13 | ||
| 14 | export interface Device { | |
| 15 | readonly repoId: string; | |
| 16 | /** `user@host:port`, lowercased host. */ | |
| 17 | readonly entry: string; | |
| 18 | readonly user: string; | |
| 19 | readonly host: string; | |
| 20 | readonly port: number; | |
| 21 | readonly secretName: string; | |
| 22 | readonly addedBy: string; | |
| 23 | readonly grantedBy: string | null; | |
| 24 | readonly grantedAt: string | null; | |
| 25 | /** The pinned key as a known_hosts key part: `ssh-ed25519 AAAA…`. */ | |
| 26 | readonly hostKey: string | null; | |
| 27 | } | |
| 28 | ||
| 29 | const USER_RE = /^[a-z_][a-z0-9_-]{0,31}$/; | |
| 30 | const MAX_PER_REPO = 8; | |
| 31 | /** A host key line's key part: type and base64 blob, nothing more. */ | |
| 32 | const HOST_KEY_RE = /^(ssh-ed25519|ssh-rsa|ecdsa-sha2-nistp(?:256|384|521)) [A-Za-z0-9+/]{20,2000}={0,2}$/; | |
| 33 | ||
| 34 | export const isHostKey = (text: string): boolean => HOST_KEY_RE.test(text); | |
| 35 | ||
| 36 | /** `user@host:port` exactly, or why not. */ | |
| 37 | export function parseDevice( | |
| 38 | text: string, | |
| 39 | ): Result<{ user: string; host: string; port: number; entry: string }, string> { | |
| 40 | const at = text.indexOf("@"); | |
| 41 | const user = text.slice(0, at); | |
| 42 | if (at < 1 || !USER_RE.test(user)) | |
| 43 | return err("a device is user@host:port, like [email protected]:22"); | |
| 44 | const dest = parseDestination(text.slice(at + 1)); | |
| 45 | if (!dest.ok) return dest; | |
| 46 | const { host, port } = dest.value; | |
| 47 | if (isIP(host) === 4 && neverGrantable(host)) | |
| 48 | return err(`${host} can never be granted`); | |
| 49 | return ok({ user, host, port, entry: `${user}@${host}:${port}` }); | |
| 50 | } | |
| 51 | ||
| 52 | interface Row { | |
| 53 | repo_id: string; | |
| 54 | entry: string; | |
| 55 | secret_name: string; | |
| 56 | added_by: string; | |
| 57 | granted_by: string | null; | |
| 58 | granted_at: string | null; | |
| 59 | host_key: string | null; | |
| 60 | } | |
| 61 | ||
| 62 | function toDevice(r: Row): Device | undefined { | |
| 63 | const parsed = parseDevice(r.entry); | |
| 64 | if (!parsed.ok) return undefined; | |
| 65 | return { | |
| 66 | repoId: r.repo_id, | |
| 67 | entry: parsed.value.entry, | |
| 68 | user: parsed.value.user, | |
| 69 | host: parsed.value.host, | |
| 70 | port: parsed.value.port, | |
| 71 | secretName: r.secret_name, | |
| 72 | addedBy: r.added_by, | |
| 73 | grantedBy: r.granted_by, | |
| 74 | grantedAt: r.granted_at, | |
| 75 | hostKey: r.host_key, | |
| 76 | }; | |
| 77 | } | |
| 78 | ||
| 79 | export function listDevices(db: Database, repoId: string): Device[] { | |
| 80 | return db | |
| 81 | .query<Row, [string]>("SELECT * FROM crew_device WHERE repo_id = ?1 ORDER BY entry") | |
| 82 | .all(repoId) | |
| 83 | .flatMap((r) => toDevice(r) ?? []); | |
| 84 | } | |
| 85 | ||
| 86 | /** The devices a run may use: granted, with a pinned key. */ | |
| 87 | export const grantedDevices = (db: Database, repoId: string): Device[] => | |
| 88 | listDevices(db, repoId).filter((d) => d.grantedBy !== null && d.hostKey !== null); | |
| 89 | ||
| 90 | /** List a device (or change its secret); a changed secret loses its grant. */ | |
| 91 | export function addDevice( | |
| 92 | db: Database, | |
| 93 | repoId: string, | |
| 94 | entry: string, | |
| 95 | secretName: string, | |
| 96 | by: { id: string }, | |
| 97 | ): Result<Device, string> { | |
| 98 | const parsed = parseDevice(entry.trim()); | |
| 99 | if (!parsed.ok) return parsed; | |
| 100 | if (!isSecretName(secretName)) return err("the key's secret name is not a usable name"); | |
| 101 | const count = listDevices(db, repoId).filter((d) => d.entry !== parsed.value.entry).length; | |
| 102 | if (count >= MAX_PER_REPO) return err(`at most ${MAX_PER_REPO} devices per repository`); | |
| 103 | db.query( | |
| 104 | `INSERT INTO crew_device (repo_id, entry, secret_name, added_by) VALUES (?1, ?2, ?3, ?4) | |
| 105 | ON CONFLICT(repo_id, entry) DO UPDATE SET secret_name = ?3, added_by = ?4, | |
| 106 | granted_by = CASE WHEN secret_name = ?3 THEN granted_by END, | |
| 107 | granted_at = CASE WHEN secret_name = ?3 THEN granted_at END, | |
| 108 | host_key = CASE WHEN secret_name = ?3 THEN host_key END`, | |
| 109 | ).run(repoId, parsed.value.entry, secretName, by.id); | |
| 110 | return found(db, repoId, parsed.value.entry); | |
| 111 | } | |
| 112 | ||
| 113 | function found(db: Database, repoId: string, entry: string): Result<Device, string> { | |
| 114 | const row = db | |
| 115 | .query<Row, [string, string]>("SELECT * FROM crew_device WHERE repo_id = ?1 AND entry = ?2") | |
| 116 | .get(repoId, entry); | |
| 117 | const device = row === null ? undefined : toDevice(row); | |
| 118 | return device === undefined ? err("no such device") : ok(device); | |
| 119 | } | |
| 120 | ||
| 121 | /** A site admin's yes, with the host key to pin. */ | |
| 122 | export function grantDevice( | |
| 123 | db: Database, | |
| 124 | repoId: string, | |
| 125 | entry: string, | |
| 126 | hostKey: string, | |
| 127 | admin: { id: string; isAdmin: boolean }, | |
| 128 | ): Result<Device, string> { | |
| 129 | if (!admin.isAdmin) return err("only a site admin grants a device"); | |
| 130 | const parsed = parseDevice(entry.trim()); | |
| 131 | if (!parsed.ok) return parsed; | |
| 132 | if (!isHostKey(hostKey)) return err("not a host key"); | |
| 133 | const changed = db | |
| 134 | .query( | |
| 135 | `UPDATE crew_device SET granted_by = ?3, host_key = ?4, | |
| 136 | granted_at = strftime('%Y-%m-%dT%H:%M:%fZ','now') | |
| 137 | WHERE repo_id = ?1 AND entry = ?2`, | |
| 138 | ) | |
| 139 | .run(repoId, parsed.value.entry, admin.id, hostKey).changes; | |
| 140 | return changed === 0 ? err("no such device") : found(db, repoId, parsed.value.entry); | |
| 141 | } | |
| 142 | ||
| 143 | /** Unlist a device (and so revoke it); true when there was one. */ | |
| 144 | export function removeDevice(db: Database, repoId: string, entry: string): boolean { | |
| 145 | const parsed = parseDevice(entry.trim()); | |
| 146 | if (!parsed.ok) return false; | |
| 147 | return ( | |
| 148 | db | |
| 149 | .query("DELETE FROM crew_device WHERE repo_id = ?1 AND entry = ?2") | |
| 150 | .run(repoId, parsed.value.entry).changes > 0 | |
| 151 | ); | |
| 152 | } |
src/core/migrations/20261021120000-crew-devices.ts added +16
| @@ -0,0 +1,16 @@ | ||
| 1 | // A device a repository's crew may SSH to (#3470): `user@host:port`, the repo | |
| 2 | // secret that holds its key, and, once a site admin grants it, who did and the | |
| 3 | // host key pinned at that moment. Additive; a row with no granted_by opens | |
| 4 | // nothing. | |
| 5 | export default ` | |
| 6 | CREATE TABLE crew_device ( | |
| 7 | repo_id TEXT NOT NULL REFERENCES repo(id) ON DELETE CASCADE, | |
| 8 | entry TEXT NOT NULL, | |
| 9 | secret_name TEXT NOT NULL, | |
| 10 | added_by TEXT NOT NULL REFERENCES user(id), | |
| 11 | granted_by TEXT REFERENCES user(id), | |
| 12 | granted_at TEXT, | |
| 13 | host_key TEXT, | |
| 14 | PRIMARY KEY (repo_id, entry) | |
| 15 | ); | |
| 16 | `; |
src/crew/brief.ts +4
| @@ -14,6 +14,7 @@ import type { Pull } from "../core/pulls.ts"; | ||
| 14 | 14 | import { OUTSIDE_LABEL, OUTSIDE_TITLE, saysOutside } from "../core/reports.ts"; |
| 15 | 15 | import type { Repo } from "../core/repos.ts"; |
| 16 | 16 | import { READER } from "./direct.ts"; |
| 17 | import { deviceLines } from "./devices.ts"; | |
| 17 | 18 | import { newsSince } from "./news.ts"; |
| 18 | 19 | import type { Reserve } from "./reserve.ts"; |
| 19 | 20 | import { |
| @@ -51,6 +52,8 @@ export interface BriefInput { | ||
| 51 | 52 | * it writes obey the cells and the cells it does not touch stay decided. |
| 52 | 53 | */ |
| 53 | 54 | readonly policy?: PolicyBrief | undefined; |
| 55 | /** Device aliases the run may `ssh` to (`crew/devices.ts`), alias → entry. */ | |
| 56 | readonly devices?: Readonly<Record<string, string>> | undefined; | |
| 54 | 57 | } |
| 55 | 58 | |
| 56 | 59 | export interface PolicyBrief { |
| @@ -154,6 +157,7 @@ export function systemPrompt(input: BriefInput): string { | ||
| 154 | 157 | lines.push( |
| 155 | 158 | "", |
| 156 | 159 | ...SANDBOX_LINES, |
| 160 | ...deviceLines(input.devices ?? {}), | |
| 157 | 161 | "", |
| 158 | 162 | "Work carefully and finish. If the task is unclear, impossible, or not something you should do, do not guess: make your last message start with `DECLINED:` followed by exactly why. Nothing is pushed then, and a person reads it.", |
| 159 | 163 | "If the issue is already done on the base branch, decline with `DECLINED: already done on main in <commit>` naming the full or abbreviated id of each commit that did it (at most five); the forge checks they are on the base, and a person closes the issue.", |
src/crew/devices.ts added +211
| @@ -0,0 +1,211 @@ | ||
| 1 | /** | |
| 2 | * The devices a crew run may SSH to (#3470). For a run on a repository with | |
| 3 | * granted devices, `deviceKit` materializes in the run's temp directory a key | |
| 4 | * file per device (0600), a pinned known_hosts, an ssh config with an alias | |
| 5 | * per device, and an `ssh` wrapper first on the run's PATH that notes each | |
| 6 | * invocation. That note is the run's own self-reported record, not an audit: | |
| 7 | * it lives where the run can write. The key reaches no argv, environment or log; the kit removes it | |
| 8 | * (`release`) and the sandbox is told exactly the host:port pairs. | |
| 9 | */ | |
| 10 | ||
| 11 | import type { Database } from "bun:sqlite"; | |
| 12 | import { | |
| 13 | chmodSync, | |
| 14 | closeSync, | |
| 15 | constants, | |
| 16 | fstatSync, | |
| 17 | lstatSync, | |
| 18 | mkdirSync, | |
| 19 | openSync, | |
| 20 | readSync, | |
| 21 | rmSync, | |
| 22 | writeFileSync, | |
| 23 | } from "node:fs"; | |
| 24 | import { join } from "node:path"; | |
| 25 | import { grantedDevices, type Device } from "../core/crew_devices.ts"; | |
| 26 | import type { EventBus } from "../core/events.ts"; | |
| 27 | import { resolveScoped } from "../core/secret_store.ts"; | |
| 28 | import { holdValues, releaseValues } from "../kernel/log.ts"; | |
| 29 | import { knownHostsLine } from "./hostkey.ts"; | |
| 30 | ||
| 31 | export interface DeviceKit { | |
| 32 | /** `host:port` pairs the sandbox may reach. */ | |
| 33 | readonly hosts: readonly string[]; | |
| 34 | /** The directory to put first on the run's PATH. */ | |
| 35 | readonly binDir: string; | |
| 36 | /** Alias → entry, for the brief and the log. */ | |
| 37 | readonly aliases: Readonly<Record<string, string>>; | |
| 38 | /** Devices granted whose key is not a repository secret, by entry. */ | |
| 39 | readonly missing: readonly string[]; | |
| 40 | /** The ssh invocations made so far: when and with what arguments. */ | |
| 41 | readonly sessions: () => Sessions; | |
| 42 | /** Every form of the private keys held: the push-time leak guard refuses these. */ | |
| 43 | readonly values: readonly string[]; | |
| 44 | /** Remove the key files and forget the value. Safe to call twice. */ | |
| 45 | readonly release: () => void; | |
| 46 | } | |
| 47 | ||
| 48 | export interface Sessions { | |
| 49 | readonly entries: { at: string; alias: string; args: string }[]; | |
| 50 | /** Lines or bytes beyond the caps, not reported. */ | |
| 51 | readonly dropped: number; | |
| 52 | } | |
| 53 | ||
| 54 | const MAX_LOG_BYTES = 64 * 1024; | |
| 55 | const MAX_SESSIONS = 50; | |
| 56 | ||
| 57 | /** | |
| 58 | * The run writes this file, so the forge reads it as hostile: the directory | |
| 59 | * and the file must be real (no symlink) and ours, at most 64 KiB are read, | |
| 60 | * at most 50 sessions are kept, and control characters are stripped. | |
| 61 | */ | |
| 62 | function readSessions(root: string, log: string): Sessions { | |
| 63 | const none: Sessions = { entries: [], dropped: 0 }; | |
| 64 | const me = process.getuid?.(); | |
| 65 | let fd: number | undefined; | |
| 66 | try { | |
| 67 | const dir = lstatSync(root); | |
| 68 | if (!dir.isDirectory() || (me !== undefined && dir.uid !== me)) return none; | |
| 69 | const st = lstatSync(log); | |
| 70 | if (!st.isFile() || (me !== undefined && st.uid !== me)) return none; | |
| 71 | fd = openSync(log, constants.O_RDONLY | constants.O_NOFOLLOW); | |
| 72 | const fst = fstatSync(fd); | |
| 73 | if (!fst.isFile() || fst.ino !== st.ino) return none; | |
| 74 | const buf = Buffer.alloc(Math.min(fst.size, MAX_LOG_BYTES)); | |
| 75 | const n = readSync(fd, buf, 0, buf.length, 0); | |
| 76 | const lines = buf.subarray(0, n).toString("utf8").split("\n").filter((l) => l !== ""); | |
| 77 | const truncated = fst.size > MAX_LOG_BYTES; | |
| 78 | // Control characters (newlines, escapes) never reach a log line or event. | |
| 79 | const clean = (v: string) => v.replace(/[\x00-\x1f\x7f-\x9f]/g, " "); | |
| 80 | const entries = lines.slice(0, MAX_SESSIONS).map((l) => { | |
| 81 | const [at = "", alias = "", ...rest] = l.split("\t"); | |
| 82 | return { | |
| 83 | at: clean(at).slice(0, 40), | |
| 84 | alias: clean(alias).slice(0, 64), | |
| 85 | args: clean(rest.join(" ")).slice(0, 2000), | |
| 86 | }; | |
| 87 | }); | |
| 88 | return { | |
| 89 | entries, | |
| 90 | dropped: Math.max(0, lines.length - MAX_SESSIONS) + (truncated ? 1 : 0), | |
| 91 | }; | |
| 92 | } catch { | |
| 93 | return none; | |
| 94 | } finally { | |
| 95 | if (fd !== undefined) closeSync(fd); | |
| 96 | } | |
| 97 | } | |
| 98 | ||
| 99 | /** `pi`, `pi-2`: the alias is the host's first label, deduplicated. */ | |
| 100 | function aliasFor(d: Device, taken: Set<string>): string { | |
| 101 | const base = d.host.split(".")[0]!.replace(/[^a-z0-9-]/g, "") || "device"; | |
| 102 | let alias = /^\d+$/.test(base) ? `device-${base}` : base; | |
| 103 | for (let n = 2; taken.has(alias); n++) alias = `${base}-${n}`; | |
| 104 | taken.add(alias); | |
| 105 | return alias; | |
| 106 | } | |
| 107 | ||
| 108 | const SAFE_PATH = /^[A-Za-z0-9_./-]+$/; | |
| 109 | ||
| 110 | export function deviceKit( | |
| 111 | db: Database, | |
| 112 | dataDir: string, | |
| 113 | bus: EventBus, | |
| 114 | run: { id: string; repoId: string; ownerId: string; actorId: string }, | |
| 115 | tmpDir: string, | |
| 116 | ssh: string | null = Bun.which("ssh"), | |
| 117 | ): DeviceKit | undefined { | |
outdated
Medium: the wrapper and |
||
| 118 | const devices = grantedDevices(db, run.repoId); | |
| 119 | if (devices.length === 0 || ssh === null || !SAFE_PATH.test(tmpDir) || !SAFE_PATH.test(ssh)) | |
| 120 | return undefined; | |
| 121 | // Repository scope only: a device cannot name the forge's or an org's secret. | |
| 122 | const secrets = resolveScoped( | |
| 123 | db, | |
| 124 | dataDir, | |
| 125 | bus, | |
| 126 | devices.map((d) => d.secretName), | |
| 127 | { repo: run.repoId, run: run.id, actor: run.actorId }, | |
| 128 | ); | |
| 129 | const root = join(tmpDir, "ssh"); | |
| 130 | const binDir = join(root, "bin"); | |
| 131 | mkdirSync(binDir, { recursive: true, mode: 0o700 }); | |
| 132 | const taken = new Set<string>(); | |
outdated
High: this path is in the run's writable temp dir. |
||
| 133 | const aliases: Record<string, string> = {}; | |
| 134 | const missing: string[] = []; | |
| 135 | const values: string[] = []; | |
| 136 | const config: string[] = []; | |
| 137 | const known: string[] = []; | |
| 138 | for (const d of devices) { | |
| 139 | const secret = secrets[d.secretName]; | |
| 140 | if (secret === undefined || secret.scope !== "repo") { | |
| 141 | missing.push(d.entry); | |
| 142 | continue; | |
| 143 | } | |
| 144 | const alias = aliasFor(d, taken); | |
| 145 | aliases[alias] = d.entry; | |
| 146 | const keyFile = join(root, `key-${alias}`); | |
| 147 | const value = secret.value.endsWith("\n") ? secret.value : `${secret.value}\n`; | |
| 148 | writeFileSync(keyFile, value, { mode: 0o600 }); | |
| 149 | chmodSync(keyFile, 0o600); | |
| 150 | values.push(secret.value, secret.value.trim()); | |
| 151 | known.push(knownHostsLine(d)); | |
| 152 | config.push( | |
| 153 | `Host ${alias}`, | |
| 154 | ` HostName ${d.host}`, | |
| 155 | ` Port ${d.port}`, | |
outdated
This promise does not hold while the log sits in the run's own writable directory (see above). Make it true or reword it, here and in docs/APPS.md. |
||
| 156 | ` User ${d.user}`, | |
| 157 | ` IdentityFile ${keyFile}`, | |
| 158 | " IdentitiesOnly yes", | |
| 159 | " StrictHostKeyChecking yes", | |
| 160 | ` UserKnownHostsFile ${join(root, "known_hosts")}`, | |
| 161 | " GlobalKnownHostsFile /dev/null", | |
| 162 | " ForwardAgent no", | |
| 163 | " ForwardX11 no", | |
| 164 | " ClearAllForwardings yes", | |
| 165 | " BatchMode yes", | |
| 166 | ` ProxyCommand ${join(binDir, "proxy")} %h %p`, | |
| 167 | "", | |
| 168 | ); | |
| 169 | } | |
| 170 | if (values.length > 0) holdValues(`device:${run.id}`, values); | |
| 171 | const log = join(root, "sessions.log"); | |
| 172 | writeFileSync(join(root, "known_hosts"), known.join(""), { mode: 0o600 }); | |
| 173 | writeFileSync(join(root, "config"), config.join("\n"), { mode: 0o600 }); | |
| 174 | writeFileSync(log, "", { mode: 0o600 }); | |
| 175 | // Through the sandbox's SOCKS proxy when there is one (ALL_PROXY), else direct. | |
| 176 | writeFileSync( | |
| 177 | join(binDir, "proxy"), | |
| 178 | `#!/bin/sh\nif [ -n "$ALL_PROXY" ]; then exec nc -X 5 -x "\${ALL_PROXY#*://}" "$1" "$2"; fi\nexec nc "$1" "$2"\n`, | |
| 179 | { mode: 0o700 }, | |
| 180 | ); | |
| 181 | writeFileSync( | |
| 182 | join(binDir, "ssh"), | |
| 183 | `#!/bin/sh\nprintf '%s\\t%s\\t%s\\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$1" "$*" >> '${log}'\nexec '${ssh}' -F '${join(root, "config")}' "$@"\n`, | |
| 184 | { mode: 0o700 }, | |
| 185 | ); | |
| 186 | return { | |
| 187 | hosts: devices.filter((d) => !missing.includes(d.entry)).map((d) => `${d.host}:${d.port}`), | |
| 188 | binDir, | |
| 189 | aliases, | |
| 190 | missing, | |
| 191 | values, | |
| 192 | sessions: () => readSessions(root, log), | |
| 193 | release: () => { | |
| 194 | releaseValues(`device:${run.id}`); | |
| 195 | rmSync(root, { recursive: true, force: true }); | |
| 196 | }, | |
| 197 | }; | |
| 198 | } | |
| 199 | ||
| 200 | /** What the brief tells the crew about the devices it may reach. */ | |
| 201 | export function deviceLines(aliases: Readonly<Record<string, string>>): string[] { | |
| 202 | const names = Object.entries(aliases); | |
| 203 | if (names.length === 0) return []; | |
| 204 | return [ | |
| 205 | "", | |
| 206 | "Devices you may reach over SSH (the owner granted them to this repository):", | |
| 207 | ...names.map(([alias, entry]) => `- \`ssh ${alias}\` is ${entry}; run a command with \`ssh ${alias} <command>\`.`), | |
| 208 | "- Read and test freely. Restart only the services its sudo allows (`sudo systemctl restart|status` on the units the owner named). Never change the device's users, keys, authorized keys or network, and never copy its key anywhere.", | |
| 209 | "- The `ssh` wrapper notes each call you make for the owner to read; that note is your own record, not a tamper-proof audit, so keep to `ssh <alias>` and never bypass it.", | |
| 210 | ]; | |
| 211 | } |
src/crew/hostkey.ts added +31
| @@ -0,0 +1,31 @@ | ||
| 1 | /** | |
| 2 | * The host key a device shows, read once when a site admin grants it (#3470) | |
| 3 | * and pinned from then on; a changed key afterwards refuses the connection. | |
| 4 | */ | |
| 5 | ||
| 6 | import { isHostKey, type Device } from "../core/crew_devices.ts"; | |
| 7 | ||
| 8 | export type HostKeyScan = (host: string, port: number) => Promise<string | undefined>; | |
| 9 | ||
| 10 | /** `ssh-keyscan` for an ed25519 key; host and port are validated by the caller. */ | |
| 11 | export const scanHostKey: HostKeyScan = async (host, port) => { | |
| 12 | const bin = Bun.which("ssh-keyscan"); | |
| 13 | if (bin === null) return undefined; | |
| 14 | const proc = Bun.spawn( | |
| 15 | [bin, "-T", "5", "-t", "ed25519,ecdsa,rsa", "-p", String(port), host], | |
| 16 | { stdin: "ignore", stdout: "pipe", stderr: "ignore" }, | |
| 17 | ); | |
| 18 | const timer = setTimeout(() => proc.kill("SIGKILL"), 10_000); | |
| 19 | const out = await new Response(proc.stdout).text(); | |
| 20 | clearTimeout(timer); | |
| 21 | await proc.exited; | |
| 22 | for (const line of out.split("\n")) { | |
| 23 | const key = line.split(" ").slice(1).join(" ").trim(); | |
| 24 | if (!line.startsWith("#") && isHostKey(key)) return key; | |
| 25 | } | |
| 26 | return undefined; | |
| 27 | }; | |
| 28 | ||
| 29 | /** The known_hosts line that pins a device. */ | |
| 30 | export const knownHostsLine = (d: Device): string => | |
| 31 | `${d.port === 22 ? d.host : `[${d.host}]:${d.port}`} ${d.hostKey ?? ""}\n`; |
src/crew/leak.ts +7 −1
| @@ -52,7 +52,13 @@ export async function historyHolds( | ||
| 52 | 52 | values: readonly string[], |
| 53 | 53 | env: Record<string, string>, |
| 54 | 54 | ): Promise<boolean> { |
| 55 | const forms = [...new Set(values.flatMap(formsOf))]; | |
| 55 | // A patch prefixes every line, so a multi-line value (a private key) never | |
| 56 | // appears whole in it: its long lines are searched one by one. | |
| 57 | const whole = [...new Set(values.flatMap(formsOf))]; | |
| 58 | const forms = [ | |
| 59 | ...whole, | |
| 60 | ...whole.flatMap((f) => (f.includes("\n") ? f.split("\n").filter((l) => l.length >= 24) : [])), | |
| 61 | ]; | |
| 56 | 62 | if (forms.length === 0) return false; |
| 57 | 63 | const out = await runGitCapture(["log", "-p", "--no-color", range], { |
| 58 | 64 | cwd: dir, |
src/crew/runner.ts +41 −2
| @@ -137,6 +137,7 @@ import { | ||
| 137 | 137 | import { trackAgentRun, untrackAgentRun } from "./running.ts"; |
| 138 | 138 | import { sandboxPolicy } from "./sandbox.ts"; |
| 139 | 139 | import { grantSecrets, parseDeclaration, type Grant } from "./grant.ts"; |
| 140 | import { deviceKit, type DeviceKit } from "./devices.ts"; | |
| 140 | 141 | import { historyHolds, scrubTree } from "./leak.ts"; |
| 141 | 142 | import { removeClone, workdirFor } from "./workdir.ts"; |
| 142 | 143 | import { readersAmong, voiceOf } from "./direct.ts"; |
| @@ -844,6 +845,7 @@ async function work( | ||
| 844 | 845 | |
| 845 | 846 | let grant: Grant | undefined; |
| 846 | 847 | let runTmp: string | undefined; |
| 848 | let devices: DeviceKit | undefined; | |
| 847 | 849 | let early: EarlyPull | undefined; |
| 848 | 850 | // A paused run resumes: its pull keeps saying "In progress". |
| 849 | 851 | let pausing = false; |
| @@ -1174,6 +1176,7 @@ async function work( | ||
| 1174 | 1176 | extraHosts: [ |
| 1175 | 1177 | ...(options.allowHosts ?? []), |
| 1176 | 1178 | ...hosts, |
| 1179 | ...(devices?.hosts ?? []), | |
| 1177 | 1180 | ...(gatewayHost === undefined ? [] : [gatewayHost]), |
| 1178 | 1181 | ], |
| 1179 | 1182 | enforced: options.sandboxEnforced, |
| @@ -1189,6 +1192,23 @@ async function work( | ||
| 1189 | 1192 | mkdirSync(runTmp, { recursive: true }); |
| 1190 | 1193 | env["CLAUDE_CODE_TMPDIR"] = runTmp; |
| 1191 | 1194 | env["TMPDIR"] = runTmp; |
| 1195 | // The devices the owner granted this repository: a key file, a pinned | |
| 1196 | // known_hosts and an `ssh` wrapper that logs, all inside the run's own | |
| 1197 | // temp directory, which goes with the run. | |
| 1198 | devices = deviceKit( | |
The kit is built here, but its key values never reach the |
||
| 1199 | app.db, | |
| 1200 | app.config.dataDir, | |
| 1201 | app.bus, | |
| 1202 | { id: run.id, repoId: repo.id, ownerId: repo.ownerId, actorId: agent.user.id }, | |
| 1203 | runTmp, | |
| 1204 | ); | |
| 1205 | if (devices !== undefined) { | |
| 1206 | env["PATH"] = `${devices.binDir}:${process.env["PATH"] ?? "/usr/local/bin:/usr/bin:/bin"}`; | |
| 1207 | for (const [alias, entry] of Object.entries(devices.aliases)) | |
| 1208 | write(`device: ssh ${alias} is ${entry}`); | |
| 1209 | for (const entry of devices.missing) | |
| 1210 | write(`device not reachable: ${entry} (its key is not a repository secret)`); | |
| 1211 | } | |
| 1192 | 1212 | } |
| 1193 | 1213 | // The sandbox refuses a unix socket's bind; the forge's own servers take |
| 1194 | 1214 | // a loopback port instead (`git/hook-address.ts`), so `bun test` runs. |
| @@ -1206,7 +1226,7 @@ async function work( | ||
| 1206 | 1226 | binary: options.binary, |
| 1207 | 1227 | cwd: dir, |
| 1208 | 1228 | prompt, |
| 1209 | appendSystemPrompt: systemPrompt(brief), | |
| 1229 | appendSystemPrompt: systemPrompt({ ...brief, devices: devices?.aliases }), | |
| 1210 | 1230 | model: agent.model || undefined, |
| 1211 | 1231 | budgetUsd, |
| 1212 | 1232 | resume, |
| @@ -1553,7 +1573,7 @@ async function work( | ||
| 1553 | 1573 | ? undefined |
| 1554 | 1574 | : `Budget reached at $${stoppedAt.toFixed(2)}; this is where it stopped.`, |
| 1555 | 1575 | write, |
| 1556 | Object.values(grant.env), | |
| 1576 | [...Object.values(grant.env), ...(devices?.values ?? [])], | |
| 1557 | 1577 | run.variantGroup, |
| 1558 | 1578 | ); |
| 1559 | 1579 | // An outage that outlasted every pause is named as one, not as a push |
| @@ -1573,6 +1593,25 @@ async function work( | ||
| 1573 | 1593 | await early?.stop(); |
| 1574 | 1594 | if (!pausing) early?.settle(ending); |
| 1575 | 1595 | grant?.release(); |
| 1596 | if (devices !== undefined) { | |
| 1597 | const { entries, dropped } = devices.sessions(); | |
outdated
High: every line of a file the run controls becomes a run-log line and a repository event, with no limit on the count. Cap the sessions (e.g. 50, plus a single 'N more dropped' line) and strip control characters from args before write() or bus.append(). |
||
| 1598 | if (dropped > 0) write(`ssh: ${dropped} more session notes dropped (cap reached)`); | |
| 1599 | for (const session of entries) { | |
| 1600 | write(`ssh ${session.alias}: ${session.args}`); | |
| 1601 | app.bus.append({ | |
| 1602 | kind: "crew.device.session", | |
| 1603 | repoId: repo.id, | |
| 1604 | actorId: agent.user.id, | |
| 1605 | payload: { | |
| 1606 | run: run.id, | |
| 1607 | device: devices.aliases[session.alias] ?? session.alias, | |
| 1608 | at: session.at, | |
| 1609 | args: session.args, | |
| 1610 | }, | |
| 1611 | }); | |
| 1612 | } | |
| 1613 | devices.release(); | |
| 1614 | } | |
| 1576 | 1615 | deleteToken(app.db, agent.user.id, token.id); |
| 1577 | 1616 | if (runTmp !== undefined) rmSync(runTmp, { recursive: true, force: true }); |
| 1578 | 1617 | } |
src/http/api.ts +56
| @@ -277,6 +277,12 @@ import { | ||
| 277 | 277 | grantAppEgress, |
| 278 | 278 | revokeAppEgress, |
| 279 | 279 | } from "../actions/egress_grants.ts"; |
| 280 | import { | |
| 281 | addCrewDevice, | |
| 282 | devicesView, | |
| 283 | grantCrewDevice, | |
| 284 | removeCrewDevice, | |
| 285 | } from "../actions/crew_devices.ts"; | |
| 280 | 286 | import { |
| 281 | 287 | addPromptSource, |
| 282 | 288 | listPromptSources, |
| @@ -5304,6 +5310,56 @@ export function apiRoutes(router: Router<Handler>): void { | ||
| 5304 | 5310 | return json({}, 200); |
| 5305 | 5311 | }); |
| 5306 | 5312 | |
| 5313 | // Devices the crew may SSH to (#3470): a repository admin lists one with | |
| 5314 | // the repo secret holding its key, a site admin grants it (pinning the host | |
| 5315 | // key), anyone with admin over the repository reads the sessions. | |
| 5316 | const devicesRoute = "/api/v1/repos/:owner/:name/crew-devices"; | |
API only. The direction's 'done' means reachable on the page and through MCP as well: add a settings line and an MCP tool (or split them into linked issues and name them in the pull). |
||
| 5317 | router.add("GET", devicesRoute, (ctx) => { | |
| 5318 | const denied = requireScope(ctx, "admin"); | |
| 5319 | if (denied) return denied; | |
| 5320 | const repo = loadRepo(ctx); | |
| 5321 | if (!repo) return notFound(); | |
| 5322 | const view = devicesView(ctx.app, ctx.auth.user, repo); | |
| 5323 | if (!view.ok) return respondAccess(view.error, 422); | |
| 5324 | return json({ items: view.value.devices, sessions: view.value.sessions, next_cursor: null }); | |
| 5325 | }); | |
| 5326 | router.add("POST", devicesRoute, async (ctx) => { | |
| 5327 | const denied = requireScope(ctx, "admin"); | |
| 5328 | if (denied) return denied; | |
| 5329 | const repo = loadRepo(ctx); | |
| 5330 | if (!repo) return notFound(); | |
| 5331 | const input = await body(ctx.request); | |
| 5332 | const added = addCrewDevice(ctx.app, ctx.auth.user, repo, str(input.device), str(input.secret)); | |
| 5333 | if (!added.ok) return respondAccess(added.error, 422); | |
| 5334 | return json(added.value, 201); | |
| 5335 | }); | |
| 5336 | router.add("POST", `${devicesRoute}/grant`, async (ctx) => { | |
| 5337 | const denied = requireScope(ctx, "admin"); | |
| 5338 | if (denied) return denied; | |
| 5339 | const repo = loadRepo(ctx); | |
| 5340 | if (!repo) return notFound(); | |
| 5341 | const input = await body(ctx.request); | |
| 5342 | const granted = await grantCrewDevice( | |
| 5343 | ctx.app, | |
| 5344 | ctx.auth.user, | |
| 5345 | repo, | |
| 5346 | str(input.device), | |
| 5347 | str(input.host_key), | |
| 5348 | ); | |
| 5349 | if (!granted.ok) return respondAccess(granted.error, 422); | |
| 5350 | return json(granted.value, 200); | |
| 5351 | }); | |
| 5352 | router.add("DELETE", devicesRoute, async (ctx) => { | |
| 5353 | const denied = requireScope(ctx, "admin"); | |
| 5354 | if (denied) return denied; | |
| 5355 | const repo = loadRepo(ctx); | |
| 5356 | if (!repo) return notFound(); | |
| 5357 | const input = await body(ctx.request); | |
| 5358 | const removed = removeCrewDevice(ctx.app, ctx.auth.user, repo, str(input.device)); | |
| 5359 | if (!removed.ok) return respondAccess(removed.error, 422); | |
| 5360 | return json({}, 200); | |
| 5361 | }); | |
| 5362 | ||
| 5307 | 5363 | // Where the crew's next tell comes from when nobody is typing |
| 5308 | 5364 | // (docs/APPS.md, "Prompts from Instagram"). Admin scope and admin over |
| 5309 | 5365 | // the repository; the token goes in once and never comes back out. |
test/crew-devices.test.ts added +276
| @@ -0,0 +1,276 @@ | ||
| 1 | /** | |
| 2 | * Devices the crew may SSH to (#3470): a repository admin lists one, only a | |
| 3 | * site admin grants it (pinning the host key), a run on that repository gets | |
| 4 | * a key file, a pinned known_hosts and a logging `ssh`, exactly that | |
| 5 | * host:port in its sandbox, and the key never reaches a log; an ungranted | |
| 6 | * device is nowhere. | |
| 7 | */ | |
| 8 | ||
| 9 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 10 | import { chmodSync, existsSync, readFileSync, rmSync, statSync, symlinkSync, writeFileSync } from "node:fs"; | |
| 11 | import { mkdtemp, rm, writeFile } from "node:fs/promises"; | |
| 12 | import { tmpdir } from "node:os"; | |
| 13 | import { join } from "node:path"; | |
| 14 | import { createApp, type App } from "../src/app.ts"; | |
| 15 | import { createRepo } from "../src/actions/repos.ts"; | |
| 16 | import { | |
| 17 | addCrewDevice, | |
| 18 | devicesView, | |
| 19 | grantCrewDevice, | |
| 20 | removeCrewDevice, | |
| 21 | } from "../src/actions/crew_devices.ts"; | |
| 22 | import { parseDevice } from "../src/core/crew_devices.ts"; | |
| 23 | import { setSecret } from "../src/core/secret_store.ts"; | |
| 24 | import { createToken } from "../src/core/tokens.ts"; | |
| 25 | import { createUser, type User } from "../src/core/users.ts"; | |
| 26 | import type { Repo } from "../src/core/repos.ts"; | |
| 27 | import { historyHolds, scrubTree } from "../src/crew/leak.ts"; | |
| 28 | import { runGit } from "../src/git/env.ts"; | |
| 29 | import { deviceKit, deviceLines } from "../src/crew/devices.ts"; | |
| 30 | import { systemPrompt, type BriefInput } from "../src/crew/brief.ts"; | |
| 31 | import { redactHeld } from "../src/kernel/log.ts"; | |
| 32 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 33 | import { quietLogs } from "./helpers/globals.ts"; | |
| 34 | import { promote } from "./helpers/members.ts"; | |
| 35 | ||
| 36 | quietLogs(); | |
| 37 | ||
| 38 | const PI = "[email protected]:22"; | |
| 39 | const OTHER = "[email protected]:22"; | |
| 40 | const HOST_KEY = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIFakeHostKeyFakeHostKeyFakeHostKey1234"; | |
| 41 | const KEY = "-----BEGIN OPENSSH PRIVATE KEY-----\nsecretsecretsecretsecretsecret\n-----END OPENSSH PRIVATE KEY-----"; | |
| 42 | ||
| 43 | let dataDir: string; | |
| 44 | let app: App; | |
| 45 | let servers: Servers; | |
| 46 | let ada: User; // site admin | |
| 47 | let cy: User; // owns the repository, no site admin | |
| 48 | let bot: User; // an agent | |
| 49 | let repo: Repo; | |
| 50 | let cyToken = ""; | |
| 51 | let bobToken = ""; | |
| 52 | ||
| 53 | const scan = async () => HOST_KEY; | |
| 54 | const run = () => ({ id: "run1", repoId: repo.id, ownerId: repo.ownerId, actorId: bot.id }); | |
| 55 | ||
| 56 | beforeAll(async () => { | |
| 57 | dataDir = await mkdtemp(join(tmpdir(), "forge-crew-devices-")); | |
| 58 | app = createApp({ dataDir, port: 0, host: "forge.test" }); | |
| 59 | servers = await serve(app); | |
| 60 | const make = async (username: string, extra: { adminIfFirst?: boolean } = {}) => { | |
| 61 | const made = await createUser(app.db, { | |
| 62 | origin: "seed", | |
| 63 | trusted: true, | |
| 64 | username, | |
| 65 | email: `${username}@forge.local`, | |
| 66 | password: "a-good-passphrase", | |
| 67 | ...extra, | |
| 68 | }); | |
| 69 | if (!made.ok) throw new Error(made.error); | |
| 70 | return made.value; | |
| 71 | }; | |
| 72 | ada = await make("ada", { adminIfFirst: true }); | |
| 73 | cy = await make("cy"); | |
| 74 | promote(app.db, cy); | |
| 75 | const bob = await make("bob"); | |
| 76 | bot = await make("robin"); | |
| 77 | app.db.query("UPDATE user SET is_agent = 1 WHERE id = ?1").run(bot.id); | |
| 78 | bot = { ...bot, kind: "agent" }; | |
| 79 | const made = await createRepo(app, cy, { name: "arm", visibility: "public", description: "" }); | |
| 80 | if (!made.ok) throw new Error(String(made.error)); | |
| 81 | repo = made.value; | |
| 82 | cyToken = createToken(app.db, cy.id, "admin", "admin").token; | |
| 83 | bobToken = createToken(app.db, bob.id, "admin", "admin").token; | |
| 84 | }, 60_000); | |
| 85 | ||
| 86 | afterAll(async () => { | |
| 87 | await servers.stop(); | |
| 88 | await rm(dataDir, { recursive: true, force: true }); | |
| 89 | }); | |
| 90 | ||
| 91 | describe("a device is exact", () => { | |
| 92 | test("user@host:port only: no range, wildcard, missing port or local address", () => { | |
| 93 | expect(parseDevice(PI).ok).toBe(true); | |
| 94 | for (const bad of ["100.89.95.68:22", "[email protected]/24:22", "crew@*.example.com:22", "crew@host", "-oProxy@host:22", "[email protected]:22", "[email protected]:22"]) | |
| 95 | expect(parseDevice(bad).ok).toBe(false); | |
| 96 | }); | |
| 97 | }); | |
| 98 | ||
| 99 | describe("listing and granting", () => { | |
| 100 | test("the owner lists, only a site admin grants, an agent does neither", () => { | |
| 101 | expect(addCrewDevice(app, cy, repo, PI, "ARM_PI_SSH_KEY").ok).toBe(true); | |
| 102 | expect(addCrewDevice(app, cy, repo, "[email protected]/8:22", "ARM_PI_SSH_KEY").ok).toBe(false); | |
| 103 | expect(addCrewDevice(app, bot, repo, OTHER, "K").ok).toBe(false); | |
| 104 | }); | |
| 105 | ||
| 106 | test("a grant needs a site admin and a host key, and pins the key", async () => { | |
| 107 | const byOwner = await grantCrewDevice(app, cy, repo, PI, "", scan); | |
| 108 | expect(byOwner.ok ? "" : byOwner.error).toBe("forbidden"); | |
| 109 | const unknown = await grantCrewDevice(app, ada, repo, OTHER, "", scan); | |
| 110 | expect(unknown.ok ? "" : unknown.error).toBe("no_such_device"); | |
| 111 | const unreadable = await grantCrewDevice(app, ada, repo, PI, "", async () => undefined); | |
| 112 | expect(unreadable.ok ? "" : unreadable.error).toBe("no_host_key"); | |
| 113 | const garbage = await grantCrewDevice(app, ada, repo, PI, "not a key", scan); | |
| 114 | expect(garbage.ok ? "" : garbage.error).toBe("no_host_key"); | |
| 115 | expect(devicesView(app, ada, repo).ok && devicesView(app, ada, repo)).toBeTruthy(); | |
| 116 | const granted = await grantCrewDevice(app, ada, repo, PI, "", scan); | |
| 117 | expect(granted.ok && granted.value.hostKey).toBe(HOST_KEY); | |
| 118 | expect(granted.ok && granted.value.grantedBy).toBe("ada"); | |
| 119 | }); | |
| 120 | ||
| 121 | test("the routes agree: a stranger is refused, the owner reads", async () => { | |
| 122 | const url = `${servers.url}/api/v1/repos/cy/arm/crew-devices`; | |
| 123 | const auth = (token: string) => ({ authorization: `Bearer ${token}` }); | |
| 124 | expect((await fetch(url, { headers: auth(bobToken) })).status).toBe(404); | |
| 125 | const read = await fetch(url, { headers: auth(cyToken) }); | |
| 126 | expect(read.status).toBe(200); | |
| 127 | const body = (await read.json()) as { items: { entry: string; granted: boolean }[] }; | |
| 128 | expect(body.items).toEqual([expect.objectContaining({ entry: PI, granted: true })]); | |
| 129 | const grant = await fetch(`${url}/grant`, { | |
| 130 | method: "POST", | |
| 131 | headers: { ...auth(cyToken), "content-type": "application/json" }, | |
| 132 | body: JSON.stringify({ device: PI, host_key: HOST_KEY }), | |
| 133 | }); | |
| 134 | expect(grant.status).toBe(403); | |
| 135 | }); | |
| 136 | ||
| 137 | test("a hostname that resolves to loopback is not granted", async () => { | |
| 138 | addCrewDevice(app, ada, repo, "[email protected]:22", "ARM_PI_SSH_KEY"); | |
| 139 | const r = await grantCrewDevice(app, ada, repo, "[email protected]:22", "", scan, async () => ["127.0.0.1"]); | |
| 140 | expect(r.ok).toBe(false); | |
| 141 | const fine = await grantCrewDevice(app, ada, repo, "[email protected]:22", "", scan, async () => ["100.89.95.70"]); | |
| 142 | expect(fine.ok).toBe(true); | |
| 143 | removeCrewDevice(app, ada, repo, "[email protected]:22"); | |
| 144 | }); | |
| 145 | ||
| 146 | test("changing the key's secret drops the grant", () => { | |
| 147 | addCrewDevice(app, cy, repo, PI, "OTHER_KEY"); | |
| 148 | expect(devicesView(app, cy, repo).ok && devicesView(app, cy, repo)).toBeTruthy(); | |
| 149 | const v = devicesView(app, cy, repo); | |
| 150 | expect(v.ok && v.value.devices[0]?.granted).toBe(false); | |
| 151 | }); | |
| 152 | }); | |
| 153 | ||
| 154 | describe("a run on the repository", () => { | |
| 155 | let fakeSsh: string; | |
| 156 | beforeAll(async () => { | |
| 157 | await grantCrewDevice(app, ada, repo, PI, "", scan); | |
| 158 | // Re-point the grant at the secret that exists. | |
| 159 | addCrewDevice(app, cy, repo, PI, "ARM_PI_SSH_KEY"); | |
| 160 | await grantCrewDevice(app, ada, repo, PI, "", scan); | |
| 161 | // A listed but ungranted device. | |
| 162 | addCrewDevice(app, cy, repo, OTHER, "ARM_PI_SSH_KEY"); | |
| 163 | fakeSsh = join(dataDir, "fakessh"); | |
| 164 | writeFileSync(fakeSsh, '#!/bin/sh\necho "fake ssh: $*"\n'); | |
| 165 | chmodSync(fakeSsh, 0o755); | |
| 166 | }); | |
| 167 | ||
| 168 | test("a granted device without a repository secret is not reachable", async () => { | |
| 169 | setSecret(app.db, dataDir, "forge", "", "ARM_PI_SSH_KEY", KEY); | |
| 170 | const tmp = await mkdtemp(join(tmpdir(), "forge-kit-")); | |
| 171 | const kit = deviceKit(app.db, dataDir, app.bus, run(), tmp, fakeSsh); | |
| 172 | expect(kit?.hosts).toEqual([]); | |
| 173 | expect(kit?.missing).toEqual([PI]); | |
| 174 | kit?.release(); | |
| 175 | await rm(tmp, { recursive: true, force: true }); | |
| 176 | }); | |
| 177 | ||
| 178 | test("gets exactly the granted host:port, a 0600 key, a pinned host, and a logged ssh", async () => { | |
| 179 | setSecret(app.db, dataDir, "repo", repo.id, "ARM_PI_SSH_KEY", KEY); | |
| 180 | const tmp = await mkdtemp(join(tmpdir(), "forge-kit-")); | |
| 181 | const kit = deviceKit(app.db, dataDir, app.bus, run(), tmp, fakeSsh)!; | |
| 182 | expect(kit.hosts).toEqual(["100.89.95.68:22"]); | |
| 183 | expect(Object.values(kit.aliases)).toEqual([PI]); | |
| 184 | const root = join(tmp, "ssh"); | |
| 185 | const keyFile = join(root, `key-${Object.keys(kit.aliases)[0]}`); | |
| 186 | expect(statSync(keyFile).mode & 0o777).toBe(0o600); | |
| 187 | expect(readFileSync(keyFile, "utf8")).toContain("secretsecret"); | |
| 188 | expect(readFileSync(join(root, "known_hosts"), "utf8")).toBe(`100.89.95.68 ${HOST_KEY}\n`); | |
| 189 | const config = readFileSync(join(root, "config"), "utf8"); | |
| 190 | expect(config).toContain("StrictHostKeyChecking yes"); | |
| 191 | expect(config).toContain("User crew"); | |
| 192 | expect(config).not.toContain("secretsecret"); | |
| 193 | expect(config).not.toContain("100.89.95.70"); | |
| 194 | ||
| 195 | const ssh = Bun.spawnSync([join(kit.binDir, "ssh"), "100", "uptime"], { stdout: "pipe", stderr: "ignore" }); | |
| 196 | const printed = ssh.stdout.toString(); | |
| 197 | expect(printed).toContain(`-F ${join(root, "config")} 100 uptime`); | |
| 198 | expect(printed).not.toContain("secretsecret"); | |
| 199 | const sessions = kit.sessions().entries; | |
| 200 | expect(sessions).toHaveLength(1); | |
| 201 | expect(sessions[0]?.args).toBe("100 uptime"); | |
| 202 | // The key is redacted from any log line while the run holds it. | |
| 203 | expect(redactHeld(`oops ${KEY}`)).not.toContain("secretsecret"); | |
| 204 | ||
| 205 | kit.release(); | |
| 206 | expect(existsSync(keyFile)).toBe(false); | |
| 207 | await rm(tmp, { recursive: true, force: true }); | |
| 208 | }); | |
| 209 | ||
| 210 | test("the session note is read as hostile: a symlink yields nothing, a big log is capped, controls are stripped", async () => { | |
| 211 | setSecret(app.db, dataDir, "repo", repo.id, "ARM_PI_SSH_KEY", KEY); | |
| 212 | const tmp = await mkdtemp(join(tmpdir(), "forge-kit-")); | |
| 213 | const kit = deviceKit(app.db, dataDir, app.bus, run(), tmp, fakeSsh)!; | |
| 214 | const log = join(tmp, "ssh", "sessions.log"); | |
| 215 | writeFileSync(join(tmp, "target"), "now\tpi\tstolen secret\n"); | |
| 216 | rmSync(log); | |
| 217 | symlinkSync(join(tmp, "target"), log); | |
| 218 | expect(kit.sessions()).toEqual({ entries: [], dropped: 0 }); | |
| 219 | rmSync(log); | |
| 220 | writeFileSync(log, "t\tpi\tline\u001b[31m\rforged\n".repeat(5000)); | |
| 221 | const big = kit.sessions(); | |
| 222 | expect(big.entries.length).toBe(50); | |
| 223 | expect(big.dropped).toBeGreaterThan(0); | |
| 224 | expect(big.entries[0]!.args).not.toMatch(/[\x00-\x1f]/); | |
| 225 | kit.release(); | |
| 226 | await rm(tmp, { recursive: true, force: true }); | |
| 227 | }); | |
| 228 | ||
| 229 | test("the key is exposed to the push-time leak guard: a copy in the tree is scrubbed, in a commit refused", async () => { | |
| 230 | setSecret(app.db, dataDir, "repo", repo.id, "ARM_PI_SSH_KEY", KEY); | |
| 231 | const tmp = await mkdtemp(join(tmpdir(), "forge-kit-")); | |
| 232 | const kit = deviceKit(app.db, dataDir, app.bus, run(), tmp, fakeSsh)!; | |
| 233 | expect(kit.values.length).toBeGreaterThan(0); | |
| 234 | const repoDir = await mkdtemp(join(tmpdir(), "forge-leak-")); | |
| 235 | for (const args of [ | |
| 236 | ["init", "-q"], | |
| 237 | ["-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "--allow-empty", "-m", "base"], | |
| 238 | ]) | |
| 239 | await runGit(args, { cwd: repoDir }); | |
| 240 | await writeFile(join(repoDir, "deploy_key"), readFileSync(join(tmp, "ssh", `key-${Object.keys(kit.aliases)[0]}`))); | |
| 241 | expect(await scrubTree(repoDir, kit.values, {})).toEqual(["deploy_key"]); | |
| 242 | expect(readFileSync(join(repoDir, "deploy_key"), "utf8")).not.toContain("secretsecret"); | |
| 243 | await writeFile(join(repoDir, "again"), KEY); | |
| 244 | await runGit(["add", "-A"], { cwd: repoDir }); | |
| 245 | await runGit(["-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "-m", "oops"], { cwd: repoDir }); | |
| 246 | expect(await historyHolds(repoDir, "HEAD~1..HEAD", kit.values, {})).toBe(true); | |
| 247 | kit.release(); | |
| 248 | await rm(tmp, { recursive: true, force: true }); | |
| 249 | await rm(repoDir, { recursive: true, force: true }); | |
| 250 | }); | |
| 251 | ||
| 252 | test("a revoked device gives the run nothing", async () => { | |
| 253 | expect(removeCrewDevice(app, cy, repo, PI).ok).toBe(true); | |
| 254 | const tmp = await mkdtemp(join(tmpdir(), "forge-kit-")); | |
| 255 | expect(deviceKit(app.db, dataDir, app.bus, run(), tmp, fakeSsh)).toBeUndefined(); | |
| 256 | await rm(tmp, { recursive: true, force: true }); | |
| 257 | }); | |
| 258 | }); | |
| 259 | ||
| 260 | describe("the brief", () => { | |
| 261 | test("names the device and the rules; says nothing when there is none", () => { | |
| 262 | const base = { | |
| 263 | agent: { user: { username: "bot", displayName: "" }, brief: "" }, | |
| 264 | repo: { ownerName: "cy", name: "arm", defaultBranch: "main" }, | |
| 265 | issue: { number: 1 }, | |
| 266 | branch: "bot/1", | |
| 267 | forgeUrl: "http://forge.test", | |
| 268 | isApp: false, | |
| 269 | }; | |
| 270 | const with_ = systemPrompt({ ...base, devices: { pi: PI } } as unknown as BriefInput); | |
| 271 | expect(with_).toContain(`\`ssh pi\` is ${PI}`); | |
| 272 | expect(with_).toContain("Never change the device's users, keys"); | |
| 273 | expect(systemPrompt(base as unknown as BriefInput)).not.toContain("over SSH"); | |
| 274 | expect(deviceLines({})).toEqual([]); | |
| 275 | }); | |
| 276 | }); |
test/spawn-pipes.test.ts +1
| @@ -18,6 +18,7 @@ const PIPING: Record<string, { sites: string[]; reason: string }> = { | ||
| 18 | 18 | "src/apps/process.ts": { sites: ["stdout+stderr", "stdout+stderr"], reason: "pump() reads stdout and stderr of the app until exit" }, |
| 19 | 19 | "src/chaos/faults.ts": { sites: ["stdout"], reason: "stdout is read until the kill closes it, then cancelled; stderr is ignored" }, |
| 20 | 20 | "src/crew/claude.ts": { sites: ["stdout+stderr", "stdout"], reason: "session pumps stdout and stderr; --version awaits stdout, stderr ignored" }, |
| 21 | "src/crew/hostkey.ts": { sites: ["stdout"], reason: "stdout is read to its end with Response.text() before the exit is awaited; stderr ignored" }, | |
| 21 | 22 | "src/crew/plan.ts": { sites: ["stdout"], reason: "stdout awaited with the exit; stderr ignored" }, |
| 22 | 23 | "src/crew/runner.ts": { sites: ["stdout"], reason: "lsof stdout awaited; stderr ignored" }, |
| 23 | 24 | "src/crew/sandbox.ts": { sites: ["stderr"], reason: "stderr awaited with the exit; stdout ignored" }, |
High: these values go only to
holdValues(log redaction).landWork's scrub andhistoryHoldsnever see them, so a key copied into the clone and committed gets pushed. Expose them on the kit and pass them intolandWork'sgrantedlist.