import { afterEach, describe, expect, it, vi } from "vitest"; import { mkdtemp, mkdir, writeFile, readFile, symlink, rm } from "node:fs/promises"; 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 type { HostInfo, Notebook, Step, RenderedStep, StartRunRequest, ServerEvent } from "@shellbook/core"; import { parseNotebook, resolveParams, renderStep } from "@shellbook/core"; import { buildApp } from "../src/app"; import { loadConfig, type ServerConfig } from "../src/config"; import { SerialQueue, safeRelative } from "../src/workspace"; import { connect, exec, fingerprint, HostKeyError, localExec, scriptInput } from "../src/ssh"; import { executeRun, EventsHub, prepareRun, redactor } from "../src/runs"; vi.mock("@shellbook/core", () => ({ parseNotebook: vi.fn((source: string) => ({ title: source.split("\n")[0], params: [], blocks: [], diagnostics: [] })), shellQuote: (value: string) => /^[A-Za-z0-9._/@:=+-]+$/.test(value) ? value : "'" + value.replaceAll("'", "'\\''") + "'", resolveParams: vi.fn((_notebook: Notebook, values: Record) => ({ values, errors: {} })), renderStep: vi.fn(() => rendered()), secretEnv: vi.fn(() => ({})), })); const cleanup: (() => Promise)[] = []; afterEach(async () => { for (const fn of cleanup.splice(0).reverse()) await fn(); vi.clearAllMocks(); }); async function fixture() { const dir = await mkdtemp(path.join(os.tmpdir(), "shellbook-")); 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"), sshKeyPath: path.join(dir, "key") }); await mkdir(path.join(config.workspaceDir, "notebooks", "nested"), { recursive: true }); await writeFile(path.join(config.workspaceDir, "notebooks", "nested", "test.md"), "# Test\necho ok"); await writeFile(path.join(config.workspaceDir, "hosts.yaml"), "- name: test\n address: localhost\n user: admin\n"); const privateKey = generateKeyPairSync("rsa", { modulusLength: 2048 }).privateKey.export({ type: "pkcs1", format: "pem" }).toString(); await writeFile(config.sshKeyPath, privateKey); return config; } function step(): Step { return { kind: "run", lang: "sh", script: "echo ok\n", range: { startLine: 1, endLine: 3 }, attrs: { id: "test", local: false, sudo: false, confirm: false, artifacts: [], uploads: [], timeoutSec: 1 } }; } 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 }; } describe("workspace", () => { it("reads nested notebooks, lists them, hashes versions, rejects stale concurrent saves", async () => { const app = await buildApp({ config: await fixture(), auth: false }); cleanup.push(() => app.close()); const url = "/api/notebooks/nested%2Ftest.md"; const res = await app.inject(url); expect(res.statusCode).toBe(200); expect(res.json().notebook.title).toBe("# Test"); expect((await app.inject("/api/notebooks")).json().notebooks).toEqual([{ path: "nested/test.md", title: "# Test" }]); const payload = { source: "# Updated", baseVersion: res.json().version }; const saves = await Promise.all([app.inject({ method: "PUT", url, payload }), app.inject({ method: "PUT", url, payload })]); expect(saves.map(r => r.statusCode).sort()).toEqual([200, 409]); expect((await app.inject(url)).json().version).not.toBe(payload.baseVersion); }); it("validates inventory and applies defaults", async () => { const config = await fixture(); const app = await buildApp({ config, auth: false }); cleanup.push(() => app.close()); expect((await app.inject("/api/hosts")).json().hosts[0]).toEqual({ name: "test", address: "localhost", user: "admin", port: 22, tags: [] }); await writeFile(path.join(config.workspaceDir, "hosts.yaml"), "- name: bad\n address: localhost\n"); expect((await app.inject("/api/hosts")).statusCode).toBe(400); }); it.each(["../secret.md", "/absolute.md", "C:/secret.md", "a\\b.md", "a/../b.md", "a//b.md", "a\0.md"])("rejects unsafe path %s", name => { expect(() => safeRelative(name)).toThrow(); }); it("rejects symlink notebooks and non-md paths", async () => { const config = await fixture(); await symlink(path.join(config.workspaceDir, "notebooks", "nested"), path.join(config.workspaceDir, "notebooks", "link"), "junction"); const app = await buildApp({ config, auth: false }); cleanup.push(() => app.close()); expect((await app.inject("/api/notebooks/link%2Ftest.md")).statusCode).toBe(400); expect((await app.inject("/api/notebooks/hosts.yaml")).statusCode).toBe(400); }); }); describe("SSH with a deterministic in-process server", () => { it("aborts unknown keys, rejects incorrect acceptance, pins accepted key and reconnects", async () => { const { config, host, fp, received } = await sshFixture(); await expect(connect(config, host)).rejects.toMatchObject({ fingerprint: fp, changed: false }); await expect(connect(config, host, "SHA256:wrong")).rejects.toBeInstanceOf(HostKeyError); expect(received).toEqual([]); const client = await connect(config, host, fp); client.end(); expect(await readFile(path.join(config.workspaceDir, "known_hosts"), "utf8")).toContain(`[127.0.0.1]:${host.port} ssh-rsa `); const second = await connect(config, host); second.end(); }); it("flags changed keys and only replaces after matching acceptance", async () => { const { config, host, fp } = await sshFixture(); await writeFile(path.join(config.workspaceDir, "known_hosts"), `[127.0.0.1]:${host.port} ssh-rsa wrong\n`); await expect(connect(config, host)).rejects.toMatchObject({ changed: true, fingerprint: fp }); const client = await connect(config, host, fp); client.end(); const second = await connect(config, host); second.end(); }); it("streams both channels and preserves exit codes without running a shell", async () => { const { config, host, fp, received } = await sshFixture(); const client = await connect(config, host, fp); const output: [string, string][] = []; expect(await exec(client, "bash -euo pipefail -s", "FAIL\n", 2000, (stream, data) => output.push([stream, data]))).toBe(7); client.end(); expect(output.filter(([s]) => s === "stdout").map(([,d]) => d).join("")).toBe("hello world\n"); expect(output.filter(([s]) => s === "stderr").map(([,d]) => d).join("")).toBe("warning\n"); expect(received[0]).toEqual({ command: "bash -euo pipefail -s", input: "FAIL\n" }); }); it("kills a channel that exceeds its timeout", async () => { const { config, host, fp } = await sshFixture(); const client = await connect(config, host, fp); await expect(exec(client, "bash -euo pipefail -s", "HANG", 50, () => {})).rejects.toThrow("timed out"); }); it("executes the run pipeline, captures stdout, audits and cleans remote directory", async () => { const { config, host, fp, received } = await sshFixture(); const hub = new EventsHub(); const events: ServerEvent[] = []; hub.subscribe(e => events.push(e)); const s = step(); s.attrs.capture = "result"; s.attrs.sudo = true; const req = request(); req.acceptHostKey = fp; const r = rendered(); await executeRun({ config, hub, runId: randomUUID(), request: req, host, rendered: r, step: s, env: { TOKEN: "secret'word" } }); expect(received[1]?.command).toBe("cd /tmp/shellbook-test && sudo -n bash -euo pipefail -s"); expect(received[1]?.input).toBe(scriptInput(r.script, { TOKEN: "secret'word" })); expect(received[2]?.command).toBe("rm -rf -- /tmp/shellbook-test"); expect(events.at(-1)).toMatchObject({ type: "run.finished", exitCode: 0, captured: { name: "result", value: "hello world" } }); const audit = await readFile(path.join(config.dataDir, "audit.jsonl"), "utf8"); expect(JSON.parse(audit).script).toBe(r.script); expect(audit + JSON.stringify(events)).not.toContain("secret'word"); }); it("emits TOFU events and a failed audited result", async () => { const { config, host, fp } = await sshFixture(); const hub = new EventsHub(); const events: ServerEvent[] = []; hub.subscribe(e => events.push(e)); await executeRun({ config, hub, runId: randomUUID(), request: request(), step: step(), rendered: rendered(), host, env: {} }); expect(events).toContainEqual(expect.objectContaining({ type: "run.hostKeyUnknown", fingerprint: fp, changed: false })); expect(events.at(-1)).toMatchObject({ type: "run.finished", exitCode: -1 }); }); it("collects remote artifacts, serves downloads, and uploads a prior artifact via SFTP", async () => { const { config, host, fp, files } = await sshFixture(); const hub = new EventsHub(); const events: ServerEvent[] = []; hub.subscribe(e => events.push(e)); const first = randomUUID(); const r = rendered(); r.artifacts = ["out.txt"]; const req = request(); req.acceptHostKey = fp; await executeRun({ config, hub, runId: first, request: req, step: step(), rendered: r, host, env: {} }); expect(events.at(-1)).toMatchObject({ exitCode: 0, artifacts: ["out.txt"] }); const app = await buildApp({ config, auth: false }); cleanup.push(() => app.close()); const download = await app.inject(`/api/runs/${first}/artifacts/out.txt`); expect(download.statusCode).toBe(200); expect(download.body).toBe("artifact bytes"); expect((await app.inject(`/api/runs/${first}/artifacts/undeclared.txt`)).statusCode).toBe(404); const next = rendered(); next.uploads = [{ src: "out.txt", dst: "/tmp/uploaded.txt" }]; await executeRun({ config, hub, runId: randomUUID(), request: { ...request(), artifactSources: { "out.txt": first } }, step: step(), rendered: next, host, env: {} }); expect(events.at(-1)).toMatchObject({ exitCode: 0 }); expect(files.get("/tmp/uploaded.txt")?.toString()).toBe("artifact bytes"); }); }); describe("pipeline helpers", () => { it("accepts HTTP runs and broadcasts protocol events over WebSocket", async () => { const { config, host } = await sshFixture(); await writeFile(path.join(config.workspaceDir, "hosts.yaml"), JSON.stringify([host])); vi.mocked(parseNotebook).mockReturnValueOnce({ title: "Test", params: [], blocks: [{ type: "step", step: step() }], diagnostics: [] }); const hub = new EventsHub(); const app = await buildApp({ config, events: hub, auth: false }); cleanup.push(() => app.close()); await app.ready(); const socket = await app.injectWS("/api/events"); cleanup.push(async () => socket.close()); const events: ServerEvent[] = []; const finished = new Promise(resolve => socket.on("message", data => { const event = JSON.parse(data.toString()) as ServerEvent; events.push(event); if (event.type === "run.finished") resolve(); })); hub.publish({ type: "file.changed", path: "nested/test.md" }); const res = await app.inject({ method: "POST", url: "/api/runs", payload: request() }); expect(res.statusCode).toBe(202); await finished; expect(events).toContainEqual({ type: "file.changed", path: "nested/test.md" }); expect(events).toContainEqual(expect.objectContaining({ type: "run.hostKeyUnknown", runId: res.json().runId })); expect(events.at(-1)).toMatchObject({ type: "run.finished", exitCode: -1 }); }); it("refuses missing or invalid parameters before execution", () => { const notebook: Notebook = { title: "Test", params: [], blocks: [{ type: "step", step: step() }], diagnostics: [] }; vi.mocked(resolveParams).mockReturnValueOnce({ values: {}, errors: { required: "missing" } }); expect(() => prepareRun(notebook, request(), [])).toThrow("Parameters are missing or invalid"); vi.mocked(renderStep).mockReturnValueOnce({ ...rendered(), missing: ["required"] }); expect(() => prepareRun(notebook, request(), [])).toThrow("Step parameters are missing or invalid"); }); it("serializes a host FIFO, allows another host, and recovers after errors", async () => { const queue = new SerialQueue(); const order: string[] = []; let release!: () => void; const gate = new Promise(resolve => { release = resolve; }); const a = queue.run("a", async () => { order.push("a1"); await gate; throw new Error("failed"); }); const failed = expect(a).rejects.toThrow("failed"); const a2 = queue.run("a", async () => { order.push("a2"); }); await queue.run("b", async () => { order.push("b"); }); expect(order).toEqual(["a1", "b"]); release(); await failed; await a2; expect(order).toEqual(["a1", "b", "a2"]); }); it("redacts secrets split across chunks", () => { let text = ""; const redact = redactor(["secret", "secret-long"], data => { text += data; }); redact.write("before sec"); redact.write("ret-long after sec"); redact.write("ret!"); redact.end(); expect(text).toBe("before [REDACTED] after [REDACTED]!"); }); it("rejects invalid secret env names", () => { expect(() => scriptInput("echo hi", { "bad;name": "x" })).toThrow(); }); it("refuses broken notebooks and unknown steps before running", () => { const notebook: Notebook = { title: "Test", params: [], blocks: [{ type: "step", step: step() }], diagnostics: [{ severity: "error", message: "bad" }] }; expect(() => prepareRun(notebook, request(), [])).toThrow("Notebook has errors"); notebook.diagnostics = []; expect(() => prepareRun(notebook, { ...request(), stepId: "absent" }, [])).toThrow("Step not found"); expect(() => prepareRun(notebook, request(), [])).toThrow("Unknown target host"); }); const bashAvailable = spawnSync("bash", ["-c", "exit 0"], { timeout: 5000 }).status === 0; it.skipIf(!bashAvailable)("runs local bash with env and correct exit code", async () => { const config = await fixture(); let text = ""; const code = await localExec(path.join(config.dataDir, "local"), "printf '%s' \"$TOKEN\"; exit 4", { TOKEN: "abc" }, false, 2000, (_, data) => { text += data; }); expect(code).toBe(4); expect(text).toBe("abc"); }); it.skipIf(!bashAvailable)("collects only declared local files after success", async () => { const config = await fixture(); const hub = new EventsHub(); const events: ServerEvent[] = []; hub.subscribe(e => events.push(e)); const r = rendered(); r.local = true; r.script = "printf artifact > result.txt"; r.artifacts = ["result.txt"]; const id = randomUUID(); await executeRun({ config, hub, runId: id, request: request(), step: step(), rendered: r, env: {} }); expect(events.at(-1)).toMatchObject({ type: "run.finished", exitCode: 0, artifacts: ["result.txt"] }); expect(await readFile(path.join(config.dataDir, "runs", id, "artifacts", "result.txt"), "utf8")).toBe("artifact"); }); });