A notebook can include another one and continue with what it produced:
- core: parse :::when{param=a,b}, ::use{notebook= as= with=} and
::host{name= address= user= port= capture=}; composeNotebook namespaces
an included notebook's params, steps, captures and templates by alias
(cycles, missing files, depth > 4 and child errors are reported on the
use line). Defaults may reference captures and builtins
({{shellbook.public_key}}); required params and secrets gate only steps
of their own scope; secretEnv passes a scope's secrets under local names.
- protocol: NotebookResponse gains includes and builtins.
- server: compose includes on load, inject builtins (client values are
ignored), refuse steps in inactive when sections.
- web: render when/use/host blocks, group included params in the form,
add a created machine to Hosts and capture its name, reload when an
included notebook changes, run all checks only for active steps,
authoring snippets for when, use and host.
227 lines
16 KiB
TypeScript
227 lines
16 KiB
TypeScript
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 { 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";
|
|
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", async importOriginal => ({
|
|
// Composition helpers stay real; parsing and rendering are stubbed per test.
|
|
...pick(await importOriginal<typeof import("@shellbook/core")>(), "composeNotebook", "notebookIncludes", "findStep", "blockActive", "isBuiltin"),
|
|
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<string, string>) => ({ values, errors: {} })),
|
|
renderStep: vi.fn(() => rendered()),
|
|
secretEnv: vi.fn(() => ({})),
|
|
}));
|
|
|
|
function pick<T extends object, K extends keyof T>(object: T, ...keys: K[]) {
|
|
return Object.fromEntries(keys.map(key => [key, object[key]])) as Pick<T, K>;
|
|
}
|
|
const cleanup: (() => Promise<unknown>)[] = [];
|
|
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() { return createSshFixture(await fixture(), cleanup); }
|
|
|
|
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("reports a failing script only through run.finished, not as a run.error", async () => {
|
|
// A failing check is a normal result (❌), not a transport/execution error.
|
|
const { config, host, fp } = await sshFixture();
|
|
const hub = new EventsHub(); const events: ServerEvent[] = []; hub.subscribe(e => events.push(e));
|
|
const r = rendered(); r.script = "FAIL";
|
|
await executeRun({ config, hub, runId: randomUUID(), request: { ...request(), acceptHostKey: fp }, step: step(), rendered: r, host, env: {} });
|
|
expect(events.at(-1)).toMatchObject({ type: "run.finished", exitCode: 7 });
|
|
expect(events.some(e => e.type === "run.error")).toBe(false);
|
|
});
|
|
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<void>(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: [{ name: "required", type: "string", required: true }], 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<void>(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");
|
|
});
|
|
});
|