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.
160 lines
9.2 KiB
TypeScript
160 lines
9.2 KiB
TypeScript
import { afterEach, describe, expect, it } from "vitest";
|
|
import { cp, mkdtemp, mkdir, writeFile, rm } from "node:fs/promises";
|
|
import os from "node:os";
|
|
import path from "node:path";
|
|
import { generateKeyPairSync } from "node:crypto";
|
|
import type { HostInfo, NotebookResponse, StartRunRequest } from "@shellbook/core";
|
|
import { findStep } from "@shellbook/core";
|
|
import { buildApp } from "../src/app";
|
|
import { loadConfig, type ServerConfig } from "../src/config";
|
|
import { prepareRun } from "../src/runs";
|
|
import { loadNotebook } from "../src/workspace";
|
|
|
|
const lxc = `---
|
|
title: LXC container
|
|
params:
|
|
proxmox: {type: host, required: true}
|
|
hostname: {type: name, required: true}
|
|
ROOTPW: {type: secret}
|
|
---
|
|
\`\`\`sh {run host="{{proxmox}}" id=create capture=address}
|
|
pct create --hostname {{hostname}} --key {{shellbook.public_key}} --pw "$ROOTPW"
|
|
\`\`\`
|
|
|
|
::host{name="{{hostname}}" address="{{address}}" capture=host}
|
|
`;
|
|
const service = `---
|
|
title: Web server
|
|
params:
|
|
target: {type: choice, options: [existing, lxc], default: lxc}
|
|
host: {type: host, required: true, default: "{{ct.host}}"}
|
|
TOKEN: {type: secret}
|
|
---
|
|
:::when{target=lxc}
|
|
::use{notebook="infra/lxc.md" as=ct with="hostname=web-ct"}
|
|
:::
|
|
|
|
\`\`\`sh {run host="{{host}}" id=install}
|
|
apt-get install -y nginx
|
|
\`\`\`
|
|
`;
|
|
const hosts: HostInfo[] = ["pve", "web-ct", "existing"].map(name => ({ name, address: "127.0.0.1", user: "root", port: 22, tags: [] }));
|
|
|
|
const cleanup: (() => Promise<unknown>)[] = [];
|
|
afterEach(async () => { for (const fn of cleanup.splice(0).reverse()) await fn(); });
|
|
async function fixture(files: Record<string, string> = { "infra/lxc.md": lxc, "services/web.md": service }) {
|
|
const dir = await mkdtemp(path.join(os.tmpdir(), "shellbook-chain-"));
|
|
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"), { recursive: true });
|
|
for (const [name, source] of Object.entries(files)) {
|
|
await mkdir(path.dirname(path.join(config.workspaceDir, "notebooks", name)), { recursive: true });
|
|
await writeFile(path.join(config.workspaceDir, "notebooks", name), source);
|
|
}
|
|
await writeFile(path.join(config.workspaceDir, "hosts.yaml"), "- name: pve\n address: 127.0.0.1\n user: root\n");
|
|
await writeFile(config.sshKeyPath, generateKeyPairSync("rsa", { modulusLength: 2048 }).privateKey.export({ type: "pkcs1", format: "pem" }).toString());
|
|
return config;
|
|
}
|
|
async function app(config: ServerConfig) {
|
|
const instance = await buildApp({ config, auth: false });
|
|
cleanup.push(() => instance.close());
|
|
return instance;
|
|
}
|
|
const request = (stepId: string, params: Record<string, string>, runtime: Record<string, string> = {}): StartRunRequest =>
|
|
({ notebookPath: "services/web.md", stepId, params, runtime, artifactSources: {} });
|
|
|
|
describe("chained notebooks on the server", () => {
|
|
it("returns the composed notebook with its includes and builtins", async () => {
|
|
const config = await fixture();
|
|
const res = await (await app(config)).inject("/api/notebooks/services%2Fweb.md");
|
|
expect(res.statusCode).toBe(200);
|
|
const body = res.json() as NotebookResponse;
|
|
expect(body.source).toBe(service);
|
|
expect(body.includes).toEqual(["infra/lxc.md"]);
|
|
expect(body.builtins["shellbook.public_key"]).toMatch(/^ssh-rsa AAAA/);
|
|
expect(body.notebook.diagnostics).toEqual([]);
|
|
expect(body.notebook.params.map(p => p.name)).toContain("ct.hostname");
|
|
expect(findStep(body.notebook.blocks, "ct.create")?.attrs.scope).toBe("ct");
|
|
});
|
|
|
|
it("reports a missing or unreadable include on the use line and refuses runs", async () => {
|
|
const config = await fixture({ "web.md": '::use{notebook="../escape.md" as=x}\n::use{notebook="gone.md" as=y}\n' });
|
|
const { notebook, includes } = await loadNotebook(config, "web.md");
|
|
expect(includes).toEqual(["gone.md"]);
|
|
expect(notebook.diagnostics.map(d => [d.line, d.message])).toEqual([
|
|
[1, 'use requires notebook="dir/name.md" (relative to notebooks/)'],
|
|
[2, "Included notebook not found: gone.md"],
|
|
]);
|
|
const res = await (await app(config)).inject({ method: "POST", url: "/api/runs", payload: { ...request("x", {}), notebookPath: "web.md" } });
|
|
expect(res.statusCode).toBe(400);
|
|
expect(res.json().message).toBe("Notebook has errors");
|
|
});
|
|
|
|
it("gates by scope, refuses inactive when sections and injects server builtins only", async () => {
|
|
const config = await fixture();
|
|
const { notebook } = await loadNotebook(config, "services/web.md");
|
|
const builtins = { "shellbook.public_key": "ssh-ed25519 SERVER" };
|
|
const values = { target: "lxc", "ct.proxmox": "pve", "ct.ROOTPW": "root-pw", TOKEN: "token" };
|
|
// The parent's host is still pending (captured later), which must not block the container step.
|
|
const prepared = prepareRun(notebook, request("ct.create", values, { "shellbook.public_key": "ssh-ed25519 CLIENT" }), hosts, builtins);
|
|
expect(prepared.rendered.script).toBe("pct create --hostname web-ct --key 'ssh-ed25519 SERVER' --pw \"$ROOTPW\"\n");
|
|
expect(prepared.host?.name).toBe("pve");
|
|
expect(prepared.env).toEqual({ ROOTPW: "root-pw" });
|
|
expect(() => prepareRun(notebook, request("install", values), hosts, builtins)).toThrow("Parameters are missing or invalid");
|
|
const parent = prepareRun(notebook, request("install", values, { "ct.host": "web-ct" }), hosts, builtins);
|
|
expect(parent.host?.name).toBe("web-ct");
|
|
expect(parent.env).toEqual({ TOKEN: "token" });
|
|
// Container steps are refused when "existing host" is selected; the included form gates its own steps.
|
|
expect(() => prepareRun(notebook, request("ct.create", { ...values, target: "existing" }), hosts, builtins)).toThrow("Step is not part of the selected options");
|
|
expect(() => prepareRun(notebook, request("ct.create", { target: "lxc" }), hosts, builtins)).toThrow("Parameters are missing or invalid");
|
|
// Without a server key the builtin stays missing even if a client sends one.
|
|
expect(() => prepareRun(notebook, request("ct.create", values, { "shellbook.public_key": "ssh-ed25519 CLIENT" }), hosts, {})).toThrow("Step parameters are missing or invalid");
|
|
});
|
|
|
|
it("lets an optional parameter wait for a capture without blocking the step that captures it", async () => {
|
|
const config = await fixture({ "next.md": `---
|
|
params:
|
|
proxmox: {type: host, required: true}
|
|
ctid: {type: name, default: "{{nextid}}"}
|
|
---
|
|
\`\`\`sh {check host="{{proxmox}}" id=next capture=nextid}
|
|
pvesh get /cluster/nextid
|
|
\`\`\`
|
|
|
|
\`\`\`sh {run host="{{proxmox}}" id=create}
|
|
pct create {{ctid}}
|
|
\`\`\`
|
|
` });
|
|
const { notebook } = await loadNotebook(config, "next.md");
|
|
const run = (stepId: string, runtime: Record<string, string> = {}) =>
|
|
prepareRun(notebook, { notebookPath: "next.md", stepId, params: { proxmox: "pve" }, runtime, artifactSources: {} }, hosts);
|
|
expect(run("next").rendered.script).toBe("pvesh get /cluster/nextid\n");
|
|
expect(() => run("create")).toThrow("Step parameters are missing or invalid");
|
|
expect(run("create", { nextid: "105" }).rendered.script).toBe("pct create 105\n");
|
|
});
|
|
|
|
it("ships template notebooks that compose without diagnostics", async () => {
|
|
const config = await fixture({});
|
|
await cp(path.resolve(__dirname, "../../../templates/workspace/notebooks"), path.join(config.workspaceDir, "notebooks"), { recursive: true });
|
|
const names = ["base-hardening-checks.md", "install-package.md", "ssh-key.md", "infra/lxc-container.md", "services/web-server.md"];
|
|
for (const name of names) expect((await loadNotebook(config, name)).notebook.diagnostics, name).toEqual([]);
|
|
const { notebook, includes } = await loadNotebook(config, "services/web-server.md");
|
|
expect(includes).toEqual(["infra/lxc-container.md"]);
|
|
const values = { target: "lxc", server_name: "web", "ct.proxmox": "pve", "ct.net": "ip=10.0.30.160/24,gw=10.0.30.1" };
|
|
const runtime = { "ct.nextid": "105", "ct.template": "local:vztmpl/debian-12-standard_12.7-1_amd64.tar.zst" };
|
|
const prepared = prepareRun(notebook, request("ct.create", values, runtime), hosts, { "shellbook.public_key": "ssh-ed25519 AAAAKEY shellbook" });
|
|
expect(prepared.rendered.script).toContain("printf '%s\\n' 'ssh-ed25519 AAAAKEY shellbook' > \"$keys\"");
|
|
expect(prepared.rendered.script).toContain("pct create 105 local:vztmpl/debian-12-standard_12.7-1_amd64.tar.zst \\\n --hostname web \\");
|
|
expect(prepared.rendered.script).toContain("--net0 name=eth0,bridge=vmbr0,'ip=10.0.30.160/24,gw=10.0.30.1'");
|
|
expect(() => prepareRun(notebook, request("install", { ...values, target: "existing" }), hosts, {})).toThrow("Parameters are missing or invalid");
|
|
expect(prepareRun(notebook, request("install", { target: "existing", host: "existing" }), hosts, {}).host?.name).toBe("existing");
|
|
});
|
|
|
|
it("refuses an inactive step over HTTP", async () => {
|
|
const config = await fixture();
|
|
const res = await (await app(config)).inject({ method: "POST", url: "/api/runs", payload: request("ct.create", { target: "existing", "ct.proxmox": "pve" }) });
|
|
expect(res.statusCode).toBe(400);
|
|
expect(res.json().message).toBe("Step is not part of the selected options");
|
|
});
|
|
});
|