From 7ba8aabb37575570e2d47d820e875dfeef0d1379 Mon Sep 17 00:00:00 2001 From: Florian Schmidt Date: Mon, 16 Nov 2026 00:19:26 +0100 Subject: [PATCH] feat(server): add one-shot sensitive artifacts and retention (#4) --- apps/server/README.md | 46 ++++++- apps/server/src/config.ts | 4 + apps/server/src/runs/artifacts.ts | 75 +++++++++++ apps/server/src/runs/index.ts | 80 ++++++++---- apps/server/test/m2.test.ts | 66 +--------- apps/server/test/m3.test.ts | 209 ++++++++++++++++++++++++++++++ apps/server/test/ssh-fixture.ts | 67 ++++++++++ 7 files changed, 453 insertions(+), 94 deletions(-) create mode 100644 apps/server/src/runs/artifacts.ts create mode 100644 apps/server/test/m3.test.ts create mode 100644 apps/server/test/ssh-fixture.ts diff --git a/apps/server/README.md b/apps/server/README.md index dbc37c3..81ff6c2 100644 --- a/apps/server/README.md +++ b/apps/server/README.md @@ -1,4 +1,4 @@ -# Server execution (M2, issue #3) +# Server execution and artifacts (M2/M3, issues #3/#4) `buildApp({ config: { workspaceDir, dataDir, sshKeyPath }, events })` accepts overrides for tests and embedding. Defaults come from `SHELLBOOK_WORKSPACE` @@ -38,7 +38,8 @@ chunk boundaries; encoded or transformed secret output cannot be detected. Audit records store only the rendered script, with defensive secret redaction. Local working files are in `data/runs//work/`. Declared successful artifacts -are copied to a separate `artifacts/` tree and listed in `artifacts.json`; only +are copied to a separate `artifacts/` tree and listed as `{name, sensitive}` entries +in `artifacts.json`; only listed files can be downloaded or used as upload sources, including after a restart. Local upload destinations must be relative to the fresh workdir. Remote uploads may use absolute destinations (the notebook format intentionally permits @@ -49,12 +50,47 @@ or forced timeout can leave remote temporary files behind. Execution timeouts close the channel and connection; Unix local runs kill the process group. Windows process-tree termination depends on the installed bash implementation. SFTP establishment and transfers have a 30-second limit. Capture -is limited to 1 MiB. Authentication, retention/24-hour artifact expiration and -sensitive one-download artifacts are separate integration work; this module -does not add those policies. The service has root-equivalent access and must be +is limited to 1 MiB. Failures emit short, specific `run.error` reasons (timeout, +authentication, connection, missing upload/artifact, or nonzero script exit), +with secret redaction and no raw transport errors or stack traces. +The service has root-equivalent access and must be deployed with the authentication plugin and trusted workspace permissions. Dependencies: `ssh2` supplies SSH/SFTP and strict host verification, `yaml` parses the inventory. `@types/ssh2` and `@types/ws` are compile-time declarations only. Tests use an in-process SSH/SFTP server that never invokes a real shell. Local bash tests skip only when bash cannot successfully execute a probe. + +## Sensitive artifacts and retention + +Collection inspects only the first 512 bytes for PEM private-key headers, including +OpenSSH, RSA, EC, DSA, encrypted and generic private keys. Sensitivity is persisted +without file contents and reported in `run.finished.sensitiveArtifacts`. A local +sensitive file is removed from `work/` after collection so it has no spare copy. +Public files remain repeatable downloads and upload sources. Legacy name-only +metadata remains readable; sensitivity is detected from the file on access. + +A sensitive download takes an exclusive filesystem claim before streaming. Parallel +requests cannot both succeed. Only after the HTTP response finishes does cleanup +delete the artifact; an interrupted response releases the claim for retry. Downloads +use `Cache-Control: no-store`. Once deleted, subsequent downloads return 410 and +upload attempts fail with a specific `run.error`. An undeclared name in an existing +run returns 404; a valid unknown run, expired run, or missing declared file returns +410. Invalid run IDs/paths return 400. A crash during a claimed download leaves a +fail-closed claim until retention removes the run; it does not allow a second copy. + +`ServerConfig.artifactTtlHours` / `SHELLBOOK_ARTIFACT_TTL_HOURS` sets a positive, +finite TTL in hours (default **24**, fractional hours supported). Whole run directories +under `data/runs/` expire based on their directory modification time (normally last +collection/metadata write). Expiration is enforced at download/upload lookup; physical +cleanup runs on startup and hourly. Queued/executing runs are protected from the +sweep. The interval is unref'd, cleared on app close, and outstanding sweeps finish +before shutdown. The service owns this data directory; do not share it between +independent server processes with different run queues. + +The HTTP tests in `test/m3.test.ts` use real core parsing/rendering and an in-process +SSH/SFTP server. A portable seeded-artifact flow covers sensitivity, downloads, +uploads, and capture/runtime rendering without bash. The full shipped `ssh-key.md` +flow generates real keys and skips cleanly when bash or ssh-keygen is unavailable; +it runs in CI/Linux, and also on Windows when a working bash with ssh-keygen is +installed. No real target host is modified by these tests. diff --git a/apps/server/src/config.ts b/apps/server/src/config.ts index cf13726..f7e8cc2 100644 --- a/apps/server/src/config.ts +++ b/apps/server/src/config.ts @@ -4,10 +4,14 @@ export interface ServerConfig { workspaceDir: string; dataDir: string; sshKeyPath: string; + artifactTtlHours: number; } export function loadConfig(overrides: Partial = {}): ServerConfig { + const artifactTtlHours = Number(overrides.artifactTtlHours ?? process.env.SHELLBOOK_ARTIFACT_TTL_HOURS ?? 24); + if (!Number.isFinite(artifactTtlHours) || artifactTtlHours <= 0) throw new Error("Artifact TTL must be a positive number of hours"); return { + artifactTtlHours, workspaceDir: path.resolve(overrides.workspaceDir ?? process.env.SHELLBOOK_WORKSPACE ?? "workspace"), dataDir: path.resolve(overrides.dataDir ?? process.env.SHELLBOOK_DATA_DIR ?? "data"), sshKeyPath: path.resolve(overrides.sshKeyPath ?? process.env.SHELLBOOK_SSH_KEY ?? "data/id_ed25519"), diff --git a/apps/server/src/runs/artifacts.ts b/apps/server/src/runs/artifacts.ts new file mode 100644 index 0000000..d2d6b68 --- /dev/null +++ b/apps/server/src/runs/artifacts.ts @@ -0,0 +1,75 @@ +import { mkdir, open, readFile, writeFile, stat, readdir, rm } from "node:fs/promises"; +import path from "node:path"; +import { createHash } from "node:crypto"; +import type { ServerConfig } from "../config"; +import { httpError, safeFile, safeRelative } from "../workspace"; + +const RUN_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; +export function runRoot(config: ServerConfig, id: string) { + if (!RUN_ID.test(id)) throw httpError(400, "Invalid run ID"); + return path.join(config.dataDir, "runs", id); +} +export interface Artifact { name: string; sensitive: boolean } +/** Inspect only a bounded prefix, independent of the artifact size. */ +export async function isSensitive(file: string): Promise { + const handle = await open(file, "r"); + try { + const prefix = Buffer.alloc(512); + const { bytesRead } = await handle.read(prefix, 0, prefix.length, 0); + return /^\s*-----BEGIN (?:[A-Z0-9]+ )*PRIVATE KEY-----/.test(prefix.toString("ascii", 0, bytesRead)); + } finally { await handle.close(); } +} +/** Shared by collection and portable fixtures; metadata contains no file contents. */ +export async function persistArtifacts(config: ServerConfig, id: string, names: string[]): Promise { + const root = runRoot(config, id); + const artifacts = await Promise.all(names.map(async name => ({ name, sensitive: await isSensitive(await safeFile(path.join(root, "artifacts"), name)) }))); + await writeFile(path.join(root, "artifacts.json"), JSON.stringify(artifacts), { mode: 0o600 }); + return artifacts; +} +export async function artifactFile(config: ServerConfig, id: string, name: string) { + safeRelative(name); + const root = runRoot(config, id); + try { + if (Date.now() - (await stat(root)).mtimeMs >= config.artifactTtlHours * 3600000) throw httpError(410, "Artifact expired"); + const entries: (Artifact | string)[] = JSON.parse(await readFile(path.join(root, "artifacts.json"), "utf8")); + const entry = entries.find(entry => (typeof entry === "string" ? entry : entry.name) === name); + if (!entry) throw httpError(404, "Artifact not found"); + const file = await safeFile(path.join(root, "artifacts"), name); + if (!(await stat(file)).isFile()) throw httpError(410, "Artifact unavailable"); + return { file, sensitive: typeof entry === "string" ? await isSensitive(file) : entry.sensitive }; + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT" || (error as { statusCode?: number }).statusCode === 404 && (error as Error).message === "File not found") throw httpError(410, "Artifact not found or expired"); + throw error; + } +} +/** Exclusive on-disk claim prevents simultaneous sensitive downloads, including across app instances. */ +export async function claimArtifact(file: string) { + const locks = path.join(path.dirname(file), ".downloads"); + await mkdir(locks, { recursive: true, mode: 0o700 }); + const identity = process.platform === "win32" ? path.basename(file).toLowerCase() : path.basename(file); + const lock = path.join(locks, createHash("sha256").update(identity).digest("hex")); + try { const handle = await open(lock, "wx", 0o600); await handle.close(); } + catch (error) { if ((error as NodeJS.ErrnoException).code === "EEXIST") throw httpError(410, "Sensitive artifact already claimed"); throw error; } + // A preceding download may have deleted the file while this request awaited metadata. + try { await stat(file); } + catch (error) { + await rm(lock, { force: true }); + if ((error as NodeJS.ErrnoException).code === "ENOENT") throw httpError(410, "Artifact not found or expired"); + throw error; + } + return async (success: boolean) => { + // Keep the claim if deletion fails: fail closed rather than serve the key again. + if (success) await rm(file, { force: true }); + await rm(lock, { force: true }); + }; +} +export async function sweepRuns(config: ServerConfig, active: ReadonlySet, now = Date.now()) { + const base = path.join(config.dataDir, "runs"); + await mkdir(base, { recursive: true, mode: 0o700 }); + for (const entry of await readdir(base, { withFileTypes: true })) { + if (!entry.isDirectory() || !RUN_ID.test(entry.name) || active.has(entry.name)) continue; + const root = runRoot(config, entry.name); + const info = await stat(root).catch((error: NodeJS.ErrnoException) => { if (error.code === "ENOENT") return undefined; throw error; }); + if (info && now - info.mtimeMs >= config.artifactTtlHours * 3600000 && !active.has(entry.name)) await rm(root, { recursive: true, force: true }); + } +} diff --git a/apps/server/src/runs/index.ts b/apps/server/src/runs/index.ts index 1032594..ec424da 100644 --- a/apps/server/src/runs/index.ts +++ b/apps/server/src/runs/index.ts @@ -1,5 +1,5 @@ import { randomUUID } from "node:crypto"; -import { appendFile, mkdir, readFile, writeFile, copyFile, stat } from "node:fs/promises"; +import { appendFile, mkdir, copyFile, stat, rm } from "node:fs/promises"; import path from "node:path"; import { createReadStream } from "node:fs"; import { parseNotebook, resolveParams, renderStep, secretEnv, shellQuote, type Block, type Step, type Notebook, type RenderedStep, type StartRunRequest, type HostInfo } from "@shellbook/core"; @@ -9,6 +9,7 @@ import type { ServerConfig } from "../config"; import { readHosts, readNotebook, safeFile, safeRelative, httpError, SerialQueue } from "../workspace"; import { connect, exec, localExec, scriptInput, sftp, sftpRequest, transfer, HostKeyError, type Output } from "../ssh"; import { EventsHub } from "./events"; +import { runRoot, artifactFile, persistArtifacts, isSensitive, claimArtifact, sweepRuns } from "./artifacts"; export { EventsHub } from "./events"; export function findStep(blocks: Block[], id: string): Step | undefined { @@ -52,20 +53,6 @@ export function redactor(secrets: string[], output: (data: string) => void) { return { write(data: string) { pending += data; flush(false); }, end() { flush(true); } }; } -function runRoot(config: ServerConfig, id: string) { - if (!/^[0-9a-f-]{36}$/.test(id)) throw httpError(400, "Invalid run ID"); - return path.join(config.dataDir, "runs", id); -} -async function artifactFile(config: ServerConfig, id: string, name: string) { - safeRelative(name); - const root = runRoot(config, id); - const names: string[] = JSON.parse(await readFile(path.join(root, "artifacts.json"), "utf8")); - if (!names.includes(name)) throw httpError(404, "Artifact not found"); - const file = await safeFile(path.join(root, "artifacts"), name); - if (!(await stat(file)).isFile()) throw httpError(404, "Artifact not a file"); - return file; -} - export interface ExecuteRun { config: ServerConfig; hub: EventsHub; runId: string; request: StartRunRequest; step: Step; rendered: RenderedStep; host?: HostInfo; env: Record; @@ -84,6 +71,8 @@ export async function executeRun({ config, hub, runId, request, step, rendered, let client: Client | undefined; let remoteDir: string | undefined; const artifacts: string[] = []; + let sensitiveArtifacts: string[] = []; + let failureReason = "Cannot prepare run storage"; const streams = { stdout: redactor(secrets, data => { if (step.attrs.capture) { @@ -101,7 +90,9 @@ export async function executeRun({ config, hub, runId, request, step, rendered, hub.publish({ type: "run.started", runId, notebookPath: request.notebookPath, stepId: rendered.stepId, host: rendered.host, script: clean(rendered.script) }); const timeout = step.attrs.timeoutSec * 1000; if (!rendered.local) { + failureReason = `Cannot connect to ${host!.address}:${host!.port}`; client = await connect(config, host!, request.acceptHostKey); + failureReason = "Cannot create remote workdir"; let directory = ""; const code = await exec(client, "mktemp -d", "", timeout, (stream, data) => { if (stream === "stdout") directory += data; }); remoteDir = directory.trim(); @@ -109,8 +100,10 @@ export async function executeRun({ config, hub, runId, request, step, rendered, } for (const upload of rendered.uploads) { const sourceId = request.artifactSources[upload.src]; - if (!sourceId) throw new Error("Missing upload source"); - const source = await artifactFile(config, sourceId, upload.src); + failureReason = `Upload source artifact '${upload.src}' not found or expired`; + if (!sourceId) throw new Error(failureReason); + const { file: source } = await artifactFile(config, sourceId, upload.src); + failureReason = `Upload of artifact '${upload.src}' failed`; if (rendered.local) { // Local upload destinations must remain inside this run's workdir. safeRelative(upload.dst); @@ -124,12 +117,15 @@ export async function executeRun({ config, hub, runId, request, step, rendered, finally { session.end(); } } } + failureReason = "Execution failed"; if (rendered.local) exitCode = await localExec(workdir, rendered.script, env, step.attrs.sudo, timeout, output); else exitCode = await exec(client!, `cd ${shellQuote(remoteDir!)} && ${step.attrs.sudo ? "sudo -n " : ""}bash -euo pipefail -s`, scriptInput(rendered.script, env), timeout, output); streams.stdout.end(); streams.stderr.end(); + if (exitCode !== 0) hub.publish({ type: "run.error", runId, message: clean(`Script exited with code ${exitCode}`) }); if (captureTooLarge) throw new Error("Captured output exceeds 1 MiB"); if (exitCode === 0) { for (const name of rendered.artifacts) { + failureReason = `Artifact '${name}' not found on host`; safeRelative(name); if (secrets.some(secret => name.includes(secret))) throw new Error("Secret in artifact name"); const target = path.join(artifactDir, name); @@ -138,6 +134,7 @@ export async function executeRun({ config, hub, runId, request, step, rendered, const source = await safeFile(workdir, name); if (!(await stat(source)).isFile()) throw new Error("Artifact is not a regular file"); await copyFile(source, target); + if (await isSensitive(target)) await rm(source); } else { const session = await sftp(client!); try { @@ -152,11 +149,12 @@ export async function executeRun({ config, hub, runId, request, step, rendered, artifacts.push(name); } } - await writeFile(path.join(root, "artifacts.json"), JSON.stringify(artifacts), { mode: 0o600 }); + failureReason = "Cannot persist artifact metadata"; + sensitiveArtifacts = (await persistArtifacts(config, runId, artifacts)).filter(a => a.sensitive).map(a => a.name); } catch (error) { exitCode = -1; if (error instanceof HostKeyError) hub.publish({ type: "run.hostKeyUnknown", runId, host: rendered.host!, fingerprint: error.fingerprint, changed: error.changed }); - else hub.publish({ type: "run.error", runId, message: "Run failed (connection, execution, or file transfer error)" }); + else hub.publish({ type: "run.error", runId, message: clean(runFailure(error, failureReason, step.attrs.timeoutSec)) }); } finally { streams.stdout.end(); streams.stderr.end(); if (client && remoteDir) { @@ -169,9 +167,9 @@ export async function executeRun({ config, hub, runId, request, step, rendered, await appendFile(path.join(config.dataDir, "audit.jsonl"), JSON.stringify({ time: new Date(start).toISOString(), notebookPath: request.notebookPath, stepId: rendered.stepId, host: rendered.host ?? "local", script: clean(rendered.script), exitCode, durationMs }) + "\n", { mode: 0o600 }); } catch { exitCode = -1; - hub.publish({ type: "run.error", runId, message: "Run audit could not be persisted" }); + hub.publish({ type: "run.error", runId, message: clean("Run audit could not be persisted") }); } - hub.publish({ type: "run.finished", runId, exitCode, durationMs, artifacts: exitCode === 0 ? artifacts : [], ...(exitCode === 0 && step.attrs.capture ? { captured: { name: step.attrs.capture, value: stdout.trim() } } : {}) }); + hub.publish({ type: "run.finished", runId, exitCode, durationMs, artifacts: exitCode === 0 ? artifacts : [], sensitiveArtifacts: exitCode === 0 ? sensitiveArtifacts : [], ...(exitCode === 0 && step.attrs.capture ? { captured: { name: step.attrs.capture, value: stdout.trim() } } : {}) }); } } @@ -180,6 +178,14 @@ function stringMap(value: unknown): value is Record { } export async function runsPlugin(app: FastifyInstance, { config, hub }: { config: ServerConfig; hub: EventsHub }) { const queue = new SerialQueue(); + const active = new Set(); + const downloads = new Set>(); + await sweepRuns(config, active); + let sweeping = Promise.resolve(); + const timer = setInterval(() => { + sweeping = sweeping.then(() => sweepRuns(config, active)).catch(() => { app.log.warn("Artifact retention sweep failed"); }); + }, 3600000); + timer.unref(); app.get("/api/events", { websocket: true }, socket => { const unsubscribe = hub.subscribe(event => { if (socket.readyState === 1) socket.send(JSON.stringify(event)); }); socket.on("close", unsubscribe); @@ -191,16 +197,40 @@ export async function runsPlugin(app: FastifyInstance, { config, hub }: { config const { source } = await readNotebook(config, body.notebookPath); const prepared = prepareRun(parseNotebook(source), body, await readHosts(config)); const runId = randomUUID(); + active.add(runId); // Queue immediately; defer the work to allow the HTTP response to reach the subscriber. void queue.run(prepared.host ? `${prepared.host.address}:${prepared.host.port}` : "local", async () => { await new Promise(resolve => setImmediate(resolve)); await executeRun({ config, hub, runId, request: body, ...prepared }); - }).catch(() => hub.publish({ type: "run.error", runId, message: "Run persistence failed" })); + }).catch(() => hub.publish({ type: "run.error", runId, message: "Run persistence failed" })).finally(() => active.delete(runId)); return reply.code(202).send({ runId }); }); app.get<{ Params: { runId: string; name: string } }>("/api/runs/:runId/artifacts/:name", async (req, reply) => { - const file = await artifactFile(config, req.params.runId, req.params.name); - return reply.type("application/octet-stream").header("Content-Disposition", "attachment").send(createReadStream(file)); + const { file, sensitive } = await artifactFile(config, req.params.runId, req.params.name); + const release = sensitive ? await claimArtifact(file) : undefined; + if (release) { + let settled = false; + const finish = (success: boolean) => { + if (settled) return; + settled = true; + const cleanup = release(success).catch(() => { app.log.warn("Sensitive artifact cleanup failed"); }); + downloads.add(cleanup); + void cleanup.finally(() => downloads.delete(cleanup)); + }; + reply.raw.once("finish", () => finish(true)); + reply.raw.once("close", () => finish(reply.raw.writableFinished)); + } + return reply.type("application/octet-stream").header("Content-Disposition", "attachment").header("Cache-Control", "no-store").send(createReadStream(file)); }); - app.addHook("onClose", async () => { await queue.idle(); }); + app.addHook("onClose", async () => { clearInterval(timer); await sweeping; await queue.idle(); await Promise.all(downloads); }); +} + +/** Allowlisted reasons only: raw transport errors may contain credentials or paths. */ +function runFailure(error: unknown, fallback: string, timeoutSec: number): string { + const e = error as { message?: string; level?: string; code?: string }; + if (e.message === "Execution timed out") return `Execution timed out after ${timeoutSec} s`; + if (e.level === "client-authentication") return "SSH authentication failed"; + if (e.message === "Captured output exceeds 1 MiB") return e.message; + if (e.message?.startsWith("SFTP ") && e.message.endsWith(" timed out")) return "File transfer timed out"; + return fallback; } diff --git a/apps/server/test/m2.test.ts b/apps/server/test/m2.test.ts index 4ba7d26..cd5d411 100644 --- a/apps/server/test/m2.test.ts +++ b/apps/server/test/m2.test.ts @@ -4,7 +4,7 @@ import os from "node:os"; import path from "node:path"; import { generateKeyPairSync, randomUUID } from "node:crypto"; import { spawnSync } from "node:child_process"; -import { Server, utils, type Connection } from "ssh2"; +import { createSshFixture } from "./ssh-fixture"; import type { HostInfo, Notebook, Step, RenderedStep, StartRunRequest, ServerEvent } from "@shellbook/core"; import { parseNotebook, resolveParams, renderStep } from "@shellbook/core"; import { buildApp } from "../src/app"; @@ -39,69 +39,7 @@ function step(): Step { } function rendered(): RenderedStep { return { stepId: "test", kind: "run", host: "test", local: false, script: "echo ok\n", artifacts: [], uploads: [], missing: [], invalid: {} }; } function request(): StartRunRequest { return { notebookPath: "nested/test.md", stepId: "test", params: {}, runtime: {}, artifactSources: {} }; } -async function sshFixture() { - const config = await fixture(); - const key = generateKeyPairSync("rsa", { modulusLength: 2048 }).privateKey.export({ type: "pkcs1", format: "pem" }).toString(); - const parsed = utils.parseKey(key); - if (parsed instanceof Error) throw parsed; - const fp = fingerprint(parsed.getPublicSSH()); - const clients = new Set(); - const received: { command: string; input: string }[] = []; - const files = new Map([["/tmp/shellbook-test/out.txt", Buffer.from("artifact bytes")]]); - const server = new Server({ hostKeys: [key] }, client => { - clients.add(client); - client.on("error", () => {}); - client.on("close", () => clients.delete(client)); - client.on("authentication", ctx => ctx.accept()); - client.on("ready", () => client.on("session", accept => { - const session = accept(); - session.on("exec", (acceptExec, _reject, info) => { - const stream = acceptExec(); - const record = { command: info.command, input: "" }; - received.push(record); - stream.on("data", (data: Buffer) => { record.input += data.toString(); }); - stream.on("end", () => { - if (record.input.includes("HANG")) return; - if (info.command === "mktemp -d") stream.write("/tmp/shellbook-test\n"); - else if (info.command.startsWith("rm -rf")) { /* deterministic cleanup */ } - else { stream.write("hello "); stream.stderr.write("warning\n"); stream.write("world\n"); } - stream.exit(record.input.includes("FAIL") ? 7 : 0); - stream.end(); - }); - }); - session.on("sftp", acceptSftp => { - const session = acceptSftp(); - const { OK, EOF, NO_SUCH_FILE } = utils.sftp.STATUS_CODE; - const attrs = (name: string) => ({ mode: 0o100600, uid: 0, gid: 0, size: files.get(name)?.length ?? 0, atime: 0, mtime: 0 }); - session.on("REALPATH", (id, name) => session.name(id, [{ filename: name, longname: name, attrs: attrs(name) }])); - session.on("STAT", (id, name) => files.has(name) ? session.attrs(id, attrs(name)) : session.status(id, NO_SUCH_FILE)); - session.on("OPEN", (id, name, flags) => { - if (flags & 8) files.set(name, Buffer.alloc(0)); - if (!files.has(name)) return session.status(id, NO_SUCH_FILE); - session.handle(id, Buffer.from(name)); - }); - session.on("FSTAT", (id, handle) => session.attrs(id, attrs(handle.toString()))); - session.on("READ", (id, handle, offset, length) => { - const data = files.get(handle.toString())!; - if (offset >= data.length) session.status(id, EOF); - else session.data(id, data.subarray(offset, offset + length)); - }); - session.on("WRITE", (id, handle, offset, data) => { - const name = handle.toString(); const old = files.get(name)!; - const next = Buffer.alloc(Math.max(old.length, offset + data.length)); old.copy(next); data.copy(next, offset); files.set(name, next); - session.status(id, OK); - }); - session.on("CLOSE", id => session.status(id, OK)); - }); - })); - }); - await new Promise(resolve => server.listen(0, "127.0.0.1", resolve)); - cleanup.push(async () => { for (const client of clients) client.end(); await new Promise(resolve => server.close(() => resolve())); }); - const address = server.address(); - if (typeof address === "string" || !address) throw new Error("Missing test address"); - const host: HostInfo = { name: "test", address: "127.0.0.1", port: address.port, user: "admin", tags: [] }; - return { config, host, fp, received, files }; -} +async function sshFixture() { return createSshFixture(await fixture(), cleanup); } describe("workspace", () => { it("reads nested notebooks, lists them, hashes versions, rejects stale concurrent saves", async () => { diff --git a/apps/server/test/m3.test.ts b/apps/server/test/m3.test.ts new file mode 100644 index 0000000..2be119e --- /dev/null +++ b/apps/server/test/m3.test.ts @@ -0,0 +1,209 @@ +import { afterEach, expect, it, vi } from "vitest"; +import { mkdtemp, mkdir, writeFile, rm, copyFile, readFile, stat, utimes } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { randomUUID, generateKeyPairSync } from "node:crypto"; +import { get } from "node:http"; +import { claimArtifact } from "../src/runs/artifacts"; +import { spawnSync } from "node:child_process"; +import type { ServerEvent, StartRunRequest } from "@shellbook/core"; +import { EventsHub } from "../src/runs"; +import { persistArtifacts, sweepRuns } from "../src/runs/artifacts"; +import { createSshFixture } from "./ssh-fixture"; +import { buildApp } from "../src/app"; +import { loadConfig } from "../src/config"; + +const cleanup: (() => Promise)[] = []; +afterEach(async () => { try { for (const fn of cleanup.splice(0).reverse()) await fn(); } finally { vi.useRealTimers(); } }); +async function fixture() { + const dir = await mkdtemp(path.join(os.tmpdir(), "shellbook-m3-")); + cleanup.push(() => rm(dir, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 })); + const config = loadConfig({ workspaceDir: path.join(dir, "workspace"), dataDir: path.join(dir, "data") }); + await mkdir(path.join(config.workspaceDir, "notebooks"), { recursive: true }); + const events: ServerEvent[] = []; const hub = new EventsHub(); hub.subscribe(e => events.push(e)); + const app = await buildApp({ config, events: hub, auth: false }); cleanup.push(() => app.close()); + return { config, app, events }; +} +it("returns 410 for unknown valid runs and missing declared artifacts", async () => { + const { config, app } = await fixture(); const id = randomUUID(); + expect((await app.inject(`/api/runs/${id}/artifacts/key`)).statusCode).toBe(410); + await mkdir(path.join(config.dataDir, "runs", id), { recursive: true }); + await writeFile(path.join(config.dataDir, "runs", id, "artifacts.json"), JSON.stringify(["key"])); + expect((await app.inject(`/api/runs/${id}/artifacts/key`)).statusCode).toBe(410); + expect((await app.inject('/api/runs/invalid/artifacts/key')).statusCode).toBe(400); +}); +async function seeded(config: ReturnType, names: Record) { + const id = randomUUID(); const dir = path.join(config.dataDir, "runs", id, "artifacts"); + await mkdir(dir, { recursive: true }); + for (const [name, value] of Object.entries(names)) await writeFile(path.join(dir, name), value); + await persistArtifacts(config, id, Object.keys(names)); return id; +} +const privateKey = "-----BEGIN OPENSSH PRIVATE KEY-----\nprivate payload\n-----END OPENSSH PRIVATE KEY-----\n"; +it("persists sensitivity, serves public files repeatedly, and consumes one of two concurrent private downloads", async () => { + const { config, app } = await fixture(); + const id = await seeded(config, { key: privateKey, 'key.pub': 'ssh-ed25519 public' }); + expect(JSON.parse(await readFile(path.join(config.dataDir, 'runs', id, 'artifacts.json'), 'utf8'))).toEqual([ + { name: 'key', sensitive: true }, { name: 'key.pub', sensitive: false }, + ]); + const url = `/api/runs/${id}/artifacts/`; + for (let i = 0; i < 2; i++) expect((await app.inject(url + 'key.pub')).body).toBe('ssh-ed25519 public'); + const results = await Promise.all([app.inject(url + 'key'), app.inject(url + 'key')]); + expect(results.map(r => r.statusCode).sort()).toEqual([200, 410]); + expect(results.find(r => r.statusCode === 200)?.body).toBe(privateKey); + await expect.poll(async () => stat(path.join(config.dataDir, 'runs', id, 'artifacts/key')).then(() => true, () => false)).toBe(false); + expect((await app.inject(url + 'key')).statusCode).toBe(410); +}); +it.each(['PRIVATE KEY', 'OPENSSH PRIVATE KEY', 'RSA PRIVATE KEY', 'EC PRIVATE KEY', 'DSA PRIVATE KEY', 'ENCRYPTED PRIVATE KEY'])("detects %s by content", async header => { + const { config } = await fixture(); const id = await seeded(config, { arbitrary: `-----BEGIN ${header}-----\nbody` }); + expect(JSON.parse(await readFile(path.join(config.dataDir, 'runs', id, 'artifacts.json'), 'utf8'))[0].sensitive).toBe(true); +}); +it("expires artifacts at access and sweeps old runs, preserving active runs and unrelated directories", async () => { + const { config, app } = await fixture(); + const expired = await seeded(config, { key: 'public' }); const active = await seeded(config, { key: privateKey }); + const fresh = await seeded(config, { key: 'new' }); const old = new Date(Date.now() - 25 * 3600000); + for (const id of [expired, active]) await utimes(path.join(config.dataDir, 'runs', id), old, old); + await mkdir(path.join(config.dataDir, 'runs', 'unrelated')); + expect((await app.inject(`/api/runs/${expired}/artifacts/key`)).statusCode).toBe(410); + await sweepRuns(config, new Set([active])); + await expect(stat(path.join(config.dataDir, 'runs', expired))).rejects.toMatchObject({ code: 'ENOENT' }); + for (const id of [active, fresh, 'unrelated']) expect((await stat(path.join(config.dataDir, 'runs', id))).isDirectory()).toBe(true); + const restarted = await buildApp({ config, auth: false }); cleanup.push(() => restarted.close()); + await expect(stat(path.join(config.dataDir, 'runs', active))).rejects.toMatchObject({ code: 'ENOENT' }); +}); +it("validates TTL configuration", () => { + expect(loadConfig().artifactTtlHours).toBe(24); + expect(loadConfig({ artifactTtlHours: 0.5 }).artifactTtlHours).toBe(0.5); + for (const value of [0, -1, NaN, Infinity]) expect(() => loadConfig({ artifactTtlHours: value })).toThrow('TTL'); +}); +async function httpFixture(authenticate = true) { + const f = await fixture(); + await writeFile(f.config.sshKeyPath, generateKeyPairSync('rsa', { modulusLength: 2048 }).privateKey.export({ type: 'pkcs1', format: 'pem' })); + const ssh = await createSshFixture(f.config, cleanup, authenticate); + await writeFile(path.join(f.config.workspaceDir, 'hosts.yaml'), JSON.stringify([ssh.host])); + await copyFile(path.resolve('../../templates/workspace/notebooks/ssh-key.md'), path.join(f.config.workspaceDir, 'notebooks/ssh-key.md')); + // Close the app before its SSH transport during teardown. + cleanup.push(() => f.app.close()); + return { ...f, ...ssh }; +} +async function run(f: Awaited>, stepId: string, overrides: Partial = {}) { + const response = await f.app.inject({ method: 'POST', url: '/api/runs', payload: { + notebookPath: 'ssh-key.md', stepId, params: { host: 'test', user: 'admin', keyname: 'id_test' }, runtime: {}, artifactSources: {}, acceptHostKey: f.fp, ...overrides, + } }); + expect(response.statusCode, response.body).toBe(202); const id: string = response.json().runId; + await expect.poll(() => f.events.find(e => e.type === 'run.finished' && e.runId === id), { timeout: 10000 }).toBeDefined(); + const finished = f.events.find(e => e.type === 'run.finished' && e.runId === id)!; + if (finished.type !== 'run.finished') throw new Error('Missing result'); + return { id, finished }; +} +async function authorize(f: Awaited>, id: string, publicKey: string) { + const result = await run(f, 'authorize', { artifactSources: { 'id_test.pub': id } }); + expect(result.finished.exitCode).toBe(0); + expect(f.files.get('/tmp/shellbook-new-key.pub')?.toString()).toBe(publicKey); + const started = f.events.find(e => e.type === 'run.started' && e.runId === result.id); + if (started?.type !== 'run.started') throw new Error('Missing started'); + expect(f.received.find(r => r.command.includes('sudo -n bash'))?.input).toBe(started.script); + expect(started.script).toContain('getent passwd admin'); +} +it("uploads a seeded public key over HTTP/SFTP and refuses a consumed private upload source (portable)", async () => { + const f = await httpFixture(); const pub = 'ssh-ed25519 public-key admin@test\n'; + const id = await seeded(f.config, { id_test: privateKey, 'id_test.pub': pub }); + expect((await f.app.inject(`/api/runs/${id}/artifacts/id_test`)).statusCode).toBe(200); + expect((await f.app.inject(`/api/runs/${id}/artifacts/id_test`)).statusCode).toBe(410); + await authorize(f, id, pub); + await writeFile(path.join(f.config.workspaceDir, 'notebooks/private.md'), '```sh {run host="{{host}}" id=upload upload="id_test:/tmp/key"}\necho ok\n```\n'.replace('host="{{host}}"', 'host=test')); + const result = await run(f, 'upload', { notebookPath: 'private.md', params: {}, artifactSources: { id_test: id } }); + expect(result.finished.exitCode).toBe(-1); + expect(f.events).toContainEqual({ type: 'run.error', runId: result.id, message: "Upload source artifact 'id_test' not found or expired" }); +}); +const localTools = spawnSync('bash', ['-c', 'command -v ssh-keygen >/dev/null'], { timeout: 5000 }).status === 0; +it.skipIf(!localTools)("generates the template SSH keys, downloads once, and authorizes over HTTP", async () => { + const f = await httpFixture(); const { id, finished } = await run(f, 'keygen'); + expect(finished).toMatchObject({ exitCode: 0, artifacts: ['id_test', 'id_test.pub'], sensitiveArtifacts: ['id_test'] }); + const base = `/api/runs/${id}/artifacts/`; + const pub = await f.app.inject(base + 'id_test.pub'); expect(pub.statusCode).toBe(200); + expect((await f.app.inject(base + 'id_test.pub')).body).toBe(pub.body); + const key = await f.app.inject(base + 'id_test'); expect(key.statusCode).toBe(200); expect(key.body).toContain('PRIVATE KEY'); + expect((await f.app.inject(base + 'id_test')).statusCode).toBe(410); + await expect(stat(path.join(f.config.dataDir, 'runs', id, 'work/id_test'))).rejects.toMatchObject({ code: 'ENOENT' }); + await authorize(f, id, pub.body); +}); +it("passes a captured value into a later HTTP run using real core rendering", async () => { + const f = await httpFixture(); + await writeFile(path.join(f.config.workspaceDir, 'notebooks/capture.md'), '```sh {check host=test id=first capture=result}\nprintf result\n```\n\n```sh {run host=test id=second}\nprintf %s {{result}}\n```\n'); + const first = await run(f, 'first', { notebookPath: 'capture.md', params: {} }); + expect(first.finished.captured).toEqual({ name: 'result', value: 'hello world' }); + const second = await run(f, 'second', { notebookPath: 'capture.md', params: {}, runtime: { result: first.finished.captured!.value } }); + expect(second.finished.exitCode).toBe(0); + const started = f.events.find(e => e.type === 'run.started' && e.runId === second.id); + expect(started).toMatchObject({ script: "printf %s 'hello world'\n" }); + expect(f.received.some(r => r.input === "printf %s 'hello world'\n")).toBe(true); +}); +it("reports specific timeouts and missing artifacts without raw errors or secret values", async () => { + const f = await httpFixture(); + await writeFile(path.join(f.config.workspaceDir, 'notebooks/error.md'), '---\nparams:\n TOKEN: { type: secret }\n---\n```sh {run host=test id=timeout timeout=0.05}\nHANG\n```\n\n```sh {run host=test id=missing artifacts="absent"}\necho ok\n```\n'); + const timed = await run(f, 'timeout', { notebookPath: 'error.md', params: { TOKEN: 'private-secret' } }); + expect(f.events).toContainEqual({ type: 'run.error', runId: timed.id, message: 'Execution timed out after 0.05 s' }); + const missing = await run(f, 'missing', { notebookPath: 'error.md', params: { TOKEN: 'private-secret' } }); + expect(f.events).toContainEqual({ type: 'run.error', runId: missing.id, message: "Artifact 'absent' not found on host" }); + expect(JSON.stringify(f.events)).not.toContain('private-secret'); +}); +it("sweeps hourly, protects executing and queued runs, and clears its timer on close", async () => { + vi.useFakeTimers({ toFake: ['setInterval', 'clearInterval'] }); + const intervals = vi.spyOn(globalThis, 'setInterval'); + const clears = vi.spyOn(globalThis, 'clearInterval'); + const f = await httpFixture(); + const retentionIndex = intervals.mock.calls.findIndex(call => call[1] === 3600000); + const retentionTimer = intervals.mock.results[retentionIndex]!.value as NodeJS.Timeout; + expect(retentionTimer.hasRef()).toBe(false); + const expired = await seeded(f.config, { out: 'old' }); const old = new Date(Date.now() - 25 * 3600000); + await utimes(path.join(f.config.dataDir, 'runs', expired), old, old); + await writeFile(path.join(f.config.workspaceDir, 'notebooks/queued.md'), '```sh {run host=test id=hang timeout=1}\nHANG\n```\n'); + const ids: string[] = []; + for (let i = 0; i < 2; i++) { + const res = await f.app.inject({ method: 'POST', url: '/api/runs', payload: { notebookPath: 'queued.md', stepId: 'hang', params: {}, runtime: {}, artifactSources: {}, acceptHostKey: f.fp } }); + expect(res.statusCode).toBe(202); ids.push(res.json().runId); + } + await expect.poll(() => f.received.some(r => r.input === 'HANG\n')).toBe(true); + for (const id of ids) { + // Queued runs normally have no directory yet; seed one to exercise the protection. + const root = path.join(f.config.dataDir, 'runs', id); await mkdir(root, { recursive: true }); await utimes(root, old, old); + } + await vi.advanceTimersByTimeAsync(3600000); + await expect.poll(() => stat(path.join(f.config.dataDir, 'runs', expired)).then(() => true, () => false)).toBe(false); + for (const id of ids) expect((await stat(path.join(f.config.dataDir, 'runs', id))).isDirectory()).toBe(true); + await f.app.close(); expect(clears).toHaveBeenCalledWith(retentionTimer); + intervals.mockRestore(); clears.mockRestore(); +}); +it("retains a private artifact after an interrupted download and permits a successful retry", async () => { + const { config, app } = await fixture(); + const contents = privateKey + 'x'.repeat(8 * 1024 * 1024); + const id = await seeded(config, { key: contents }); + const address = await app.listen({ host: '127.0.0.1', port: 0 }); + await new Promise((resolve, reject) => { + const request = get(`${address}/api/runs/${id}/artifacts/key`, response => { + response.once('data', () => { response.destroy(); resolve(); }); + }); + request.once('error', reject); + }); + const file = path.join(config.dataDir, 'runs', id, 'artifacts/key'); + await expect.poll(async () => { + try { const release = await claimArtifact(file); await release(false); return true; } catch { return false; } + }).toBe(true); + expect((await stat(file)).isFile()).toBe(true); + const response = await app.inject(`/api/runs/${id}/artifacts/key`); + expect(response.statusCode).toBe(200); expect(response.body).toBe(contents); + expect((await app.inject(`/api/runs/${id}/artifacts/key`)).statusCode).toBe(410); +}); +it("redacts secrets in specific run.error reasons", async () => { + const f = await httpFixture(); + await writeFile(path.join(f.config.workspaceDir, 'notebooks/redact.md'), '---\nparams:\n TOKEN: { type: secret }\n---\n```sh {run host=test id=missing artifacts="private-secret"}\necho ok\n```\n'); + const result = await run(f, 'missing', { notebookPath: 'redact.md', params: { TOKEN: 'private-secret' } }); + expect(f.events).toContainEqual({ type: 'run.error', runId: result.id, message: "Artifact '[REDACTED]' not found on host" }); + expect(JSON.stringify(f.events) + await readFile(path.join(f.config.dataDir, 'audit.jsonl'), 'utf8')).not.toContain('private-secret'); +}); +it("reports SSH authentication failure without raw transport details", async () => { + const f = await httpFixture(false); + const result = await run(f, 'authorize'); + expect(result.finished.exitCode).toBe(-1); + expect(f.events).toContainEqual({ type: 'run.error', runId: result.id, message: 'SSH authentication failed' }); +}); diff --git a/apps/server/test/ssh-fixture.ts b/apps/server/test/ssh-fixture.ts new file mode 100644 index 0000000..00f6571 --- /dev/null +++ b/apps/server/test/ssh-fixture.ts @@ -0,0 +1,67 @@ +import { generateKeyPairSync } from "node:crypto"; +import { Server, utils, type Connection } from "ssh2"; +import type { HostInfo } from "@shellbook/core"; +import type { ServerConfig } from "../src/config"; +import { fingerprint } from "../src/ssh"; +export async function createSshFixture(config: ServerConfig, cleanup: (() => Promise)[], authenticate = true) { + const key = generateKeyPairSync("rsa", { modulusLength: 2048 }).privateKey.export({ type: "pkcs1", format: "pem" }).toString(); + const parsed = utils.parseKey(key); + if (parsed instanceof Error) throw parsed; + const fp = fingerprint(parsed.getPublicSSH()); + const clients = new Set(); + const received: { command: string; input: string }[] = []; + const files = new Map([["/tmp/shellbook-test/out.txt", Buffer.from("artifact bytes")]]); + const server = new Server({ hostKeys: [key] }, client => { + clients.add(client); + client.on("error", () => {}); + client.on("close", () => clients.delete(client)); + client.on("authentication", ctx => authenticate ? ctx.accept() : ctx.reject()); + client.on("ready", () => client.on("session", accept => { + const session = accept(); + session.on("exec", (acceptExec, _reject, info) => { + const stream = acceptExec(); + const record = { command: info.command, input: "" }; + received.push(record); + stream.on("data", (data: Buffer) => { record.input += data.toString(); }); + stream.on("end", () => { + if (record.input.includes("HANG")) return; + if (info.command === "mktemp -d") stream.write("/tmp/shellbook-test\n"); + else if (info.command.startsWith("rm -rf")) { /* deterministic cleanup */ } + else { stream.write("hello "); stream.stderr.write("warning\n"); stream.write("world\n"); } + stream.exit(record.input.includes("FAIL") ? 7 : 0); + stream.end(); + }); + }); + session.on("sftp", acceptSftp => { + const session = acceptSftp(); + const { OK, EOF, NO_SUCH_FILE } = utils.sftp.STATUS_CODE; + const attrs = (name: string) => ({ mode: 0o100600, uid: 0, gid: 0, size: files.get(name)?.length ?? 0, atime: 0, mtime: 0 }); + session.on("REALPATH", (id, name) => session.name(id, [{ filename: name, longname: name, attrs: attrs(name) }])); + session.on("STAT", (id, name) => files.has(name) ? session.attrs(id, attrs(name)) : session.status(id, NO_SUCH_FILE)); + session.on("OPEN", (id, name, flags) => { + if (flags & 8) files.set(name, Buffer.alloc(0)); + if (!files.has(name)) return session.status(id, NO_SUCH_FILE); + session.handle(id, Buffer.from(name)); + }); + session.on("FSTAT", (id, handle) => session.attrs(id, attrs(handle.toString()))); + session.on("READ", (id, handle, offset, length) => { + const data = files.get(handle.toString())!; + if (offset >= data.length) session.status(id, EOF); + else session.data(id, data.subarray(offset, offset + length)); + }); + session.on("WRITE", (id, handle, offset, data) => { + const name = handle.toString(); const old = files.get(name)!; + const next = Buffer.alloc(Math.max(old.length, offset + data.length)); old.copy(next); data.copy(next, offset); files.set(name, next); + session.status(id, OK); + }); + session.on("CLOSE", id => session.status(id, OK)); + }); + })); + }); + await new Promise(resolve => server.listen(0, "127.0.0.1", resolve)); + cleanup.push(async () => { for (const client of clients) client.end(); await new Promise(resolve => server.close(() => resolve())); }); + const address = server.address(); + if (typeof address === "string" || !address) throw new Error("Missing test address"); + const host: HostInfo = { name: "test", address: "127.0.0.1", port: address.port, user: "admin", tags: [] }; + return { config, host, fp, received, files }; +}