Files
Florian Schmidt bdbcd2dcd5 feat(core): parameter fields in text, groups and gating by used values (#16)
- `::param{name=x}` places a parameter's input inside the text.
- `:::group{title="…" collapsed}` is a collapsible container for anything;
  groups are presentational and never gate steps. Included notebooks
  namespace field names and group titles.
- `groupInputs` reports a container's input status (missing, filled,
  optional, none) from its fields, the parameters its steps use and, for
  `::use`, the included notebook's parameters.
- A step is gated only by the values it uses: referenced parameters, the
  required secrets its script reads and valid set secrets of its scope.
  Unused required parameters no longer block early steps of a guided
  runbook.
- Spec §3.2/§3.6/§3.7, workspace format guide and a guided admin-user
  example notebook.
2026-11-16 16:49:47 +01:00

195 lines
13 KiB
TypeScript

import { describe, expect, it } from "vitest";
import { readFileSync } from "node:fs";
import { spawnSync } from "node:child_process";
import { parseNotebook, renderStep, renderText, resolveParams, secretEnv, shellQuote } from "../src/index";
import type { Block, Notebook, Step } from "../src/index";
const steps = (blocks: Block[]): Step[] => blocks.flatMap(b => b.type === "step" ? [b.step] : b.type === "after" ? steps(b.blocks) : []);
const book = (params: string, script = "echo {{x}}", attrs = "on=local"): Notebook => parseNotebook(`---\nparams:\n${params}\n---\n\n\`\`\`sh {run ${attrs}}\n${script}\n\`\`\`\n`);
const render = (n: Notebook, values = {}, runtime = {}) => renderStep(n, steps(n.blocks)[0]!, values, runtime, ["server"]);
// Keep an exact copy of the spec's notebook example in a portable fixture.
const example = readFileSync(new URL("./fixtures/ssh-key.md", import.meta.url), "utf8");
describe("spec §3.1", () => {
it("parses params, steps, after sections and inclusive source ranges", () => {
const n = parseNotebook(example);
expect(n.diagnostics).toEqual([]);
expect(n.title).toBe("New server SSH key");
expect(n.params).toEqual([
{ name: "host", type: "host", required: true, label: "Target server" },
{ name: "user", type: "name", required: true, default: "admin", label: "Login user" },
{ name: "keyname", type: "name", required: false, default: "id_ed25519_{{host}}" },
]);
const ss = steps(n.blocks);
expect(ss.map(s => s.attrs.id)).toEqual(["user-exists", "password-login-disabled", "keygen", "authorize"]);
expect(ss.map(s => s.attrs.timeoutSec)).toEqual([30, 30, 300, 300]);
expect(ss[0]!.range).toEqual({ startLine: 13, endLine: 15 });
expect(ss[2]!.attrs).toMatchObject({ local: true, artifacts: ["{{keyname}}", "{{keyname}}.pub"] });
expect(n.blocks.find(b => b.type === "after")).toMatchObject({ stepId: "keygen", onFailure: false });
});
it("renders the exact scripts and resolved metadata", () => {
const n = parseNotebook(example);
const rendered = steps(n.blocks).map(s => renderStep(n, s, { host: "server" }, {}, ["server"]));
expect(rendered.map(s => s.script)).toEqual([
"id admin\n", "sshd -T | grep -qx 'passwordauthentication no'\n",
"ssh-keygen -q -t ed25519 -N '' -C admin@server -f id_ed25519_server\n",
"install -d -m 700 -o admin -g admin ~admin/.ssh\ncat /tmp/new_key.pub >> ~admin/.ssh/authorized_keys\nrm /tmp/new_key.pub\n",
]);
expect(rendered.every(s => !s.missing.length && !Object.keys(s.invalid).length)).toBe(true);
expect(rendered[2]!.artifacts).toEqual(["id_ed25519_server", "id_ed25519_server.pub"]);
expect(rendered[3]!.uploads).toEqual([{ src: "id_ed25519_server.pub", dst: "/tmp/new_key.pub" }]);
});
});
describe("parser", () => {
it("preserves ordinary fences and ignores headings/directives inside them", () => {
const text = "```markdown\n# fake\n:::after{step=no}\n```\n# Real\n```sh\necho hi\n```\n";
const n = parseNotebook(text);
expect(n.title).toBe("Real"); expect(n.diagnostics).toEqual([]);
expect(n.blocks).toEqual([{ type: "markdown", text, range: { startLine: 1, endLine: 8 } }]);
});
it("handles nested after sections and contained steps, including forward references", () => {
const n = parseNotebook(":::after{step=later failed}\ntext\n:::after{step=later}\n~~~bash {check id=later confirm sudo timeout=4}\nid\n~~~\n:::\n:::\n");
expect(n.diagnostics).toEqual([]); expect(n.blocks[0]).toMatchObject({ type: "after", onFailure: true, range: { startLine: 1, endLine: 8 } });
expect(steps(n.blocks)[0]!.attrs).toMatchObject({ confirm: false, sudo: true, timeoutSec: 4 });
});
it("supports repeatable and comma-separated uploads and quoted attributes", () => {
const n = book(" x: {type: string}", "hi", 'on=local title="Say \\"hi\\"" upload="a:/a,b:/b" upload=c:/c capture=result');
expect(n.diagnostics).toEqual([]);
expect(steps(n.blocks)[0]!.attrs).toMatchObject({ title: 'Say "hi"', uploads: [{ src: "a", dst: "/a" }, { src: "b", dst: "/b" }, { src: "c", dst: "/c" }], capture: "result" });
});
it.each([
["---\nparams: [\n---", "YAML"],
["---\nparams: []\n---", "mapping"],
["---\nparams:\n a: {type: bogus}\n---", "Unknown param type"],
["---\nparams:\n a: {type: secret, default: hidden}\n---", "cannot have a default"],
["---\nparams:\n a: {type: choice}\n---", "needs options"],
["---\ntitle: x", "Unclosed frontmatter"],
[":::after{step=no}\n:::", "unknown step"],
[":::after{step=no}", "Unclosed after"],
["```sh {run typo=x}\nx\n```", "Unknown attribute"],
["```sh {run timeout=0}\nx\n```", "timeout"],
["```sh {run on=remote}\nx\n```", "on must"],
["```sh {run host=a on=local}\nx\n```", "cannot be combined"],
["```sh {check upload=a:b artifacts=a}\nx\n```", "Checks cannot"],
["```sh {run upload=broken}\nx\n```", "src:dst"],
["```sh {run id=x id=y}\nx\n```", "Duplicate attribute"],
["```sh {run title=\"broken}\nx\n```", "Unclosed quote"],
["```sh {run}\nx", "Unclosed step"],
["```sh {run id=x}\nx\n```\n```sh {check id=x}\nx\n```", "Duplicate step id"],
])("reports malformed input without throwing: %s", (source, message) => {
expect(parseNotebook(source).diagnostics.some(d => d.message.includes(message))).toBe(true);
});
it("points an unquoted comma in a flow-mapping label at the parameter line with a fix", () => {
const n = parseNotebook("---\ntitle: T\nparams:\n host: { type: host }\n key: { type: secret, label: Auth key (optional, else log in) }\n---\n# T\n");
expect(n.diagnostics).toEqual([{
severity: "error",
line: 5,
message: 'Unknown parameter field "else log in)" for key. A value containing a comma needs quotes, e.g. label: "a, b"',
}]);
});
it("uses title fallback, numeric step ids, CRLF ranges and exact script whitespace", () => {
expect(parseNotebook("").title).toBe("Untitled");
const n = parseNotebook("---\r\ntitle: Front\r\n---\r\n# Heading\r\n```sh {run}\r\n echo x \r\n\r\n```\r\n");
// Scripts are executed by bash: CRLF line endings must not leak a trailing \r into commands.
expect(n.title).toBe("Front"); expect(steps(n.blocks)[0]).toMatchObject({ script: " echo x \n\n", attrs: { id: "step-1" }, range: { startLine: 5, endLine: 8 } });
});
});
describe("parameter resolution", () => {
it("resolves chains, explicit overrides and blank values via defaults", () => {
const n = book(" x: {type: name, default: '{{y}}.pub'}\n y: {type: name, default: '{{z}}'}\n z: {type: name, default: key}");
expect(resolveParams(n, { x: "", z: "custom" }, []).values).toEqual({ x: "custom.pub", y: "custom", z: "custom" });
expect(resolveParams(n, { x: "override" }, []).errors).toEqual({});
});
it.each([
["host", "other", "Unknown host"], ["name", "bad name", "Expected a name"], ["name", "", "missing"],
["path", "a\nb", "newlines"], ["path", "a\0b", "NUL"], ["choice, options: [a, b]", "c", "available choice"],
])("validates %s", (type, value, message) => {
const n = book(` x: {type: ${type}, required: true}`);
expect(resolveParams(n, { x: value }, ["server"]).errors.x).toContain(message);
});
it.each(["string", "path", "name", "host", "choice, options: [server]", "secret"])("accepts valid %s", type => {
expect(resolveParams(book(` x: {type: ${type}}`), { x: "server" }, ["server"]).errors).toEqual({});
});
it("rejects cyclic, unknown, missing and secret dependencies without leaking secrets", () => {
const n = book(" x: {type: string, default: '{{y}}'}\n y: {type: string, default: '{{x}}'}\n z: {type: string, default: '{{unknown}}'}\n a: {type: string, default: '{{TOKEN}}'}\n TOKEN: {type: secret}");
const r = resolveParams(n, { TOKEN: "hidden" }, []);
expect(Object.keys(r.errors).sort()).toEqual(["a", "x", "y", "z"]);
expect(r.values.a).not.toContain("hidden");
expect(resolveParams(book(" x: {type: string, default: '{{y}}'}\n y: {type: string}"), {}, []).errors.x).toContain("Missing default");
});
});
describe("rendering and secrets", () => {
it("uses shellQuote for scripts and raw substitution for metadata, without recursive substitution", () => {
const n = book(" x: {type: string}", "printf %s {{x}} {{captured}}", "host=\"{{target}}\" artifacts=\"{{file}}\" upload=\"{{file}}:{{dst}}\"");
const r = render(n, { x: "$(touch bad)'\n{{other}}" }, { captured: "a b", target: "server", file: "a key", dst: "/tmp/a b" });
expect(r.script).toBe(`printf %s ${shellQuote("$(touch bad)'\n{{other}}")} ${shellQuote("a b")}\n`);
expect(r.artifacts).toEqual(["a key"]); expect(r.uploads[0]!.dst).toBe("/tmp/a b");
expect(r.invalid).toEqual({});
});
it("blocks missing and invalid used params, unknown variables and invalid hosts", () => {
const n = book(" x: {type: name}\n required: {type: string, required: true}\n unused: {type: name}", "{{x}} {{unknown}} {{empty}}", "host=missing");
const r = render(n, { x: "bad value", unused: "bad value" }, { empty: "" });
// An unused required param does not block the step (guided notebooks, spec §3.6).
expect(r.missing).toEqual(["empty"]);
expect(Object.keys(r.invalid).sort()).toEqual(["host", "unknown", "x"]);
expect(r.script).toBe("{{x}} {{unknown}} {{empty}}\n");
});
it("never exposes secret values via templates, defaults, prose or runtime shadowing", () => {
const n = book(" x: {type: secret, required: true}", "echo {{x}} $x", "on=local artifacts={{x}} upload={{x}}:{{x}}");
const r = render(n, { x: "hidden" }, { x: "shadow" });
expect(JSON.stringify(r)).not.toContain("hidden"); expect(JSON.stringify(r)).not.toContain("shadow");
expect(r.invalid.x).toContain("environment");
expect(renderText("{{x}} {{unknown}}", { x: "hidden" }, n)).toBe("•••• {{unknown}}");
expect(secretEnv(n, { x: "hidden", other: "public" })).toEqual({ x: "hidden" });
expect(secretEnv(n, {})).toEqual({});
});
it.each(["../file", "a/b", "a\\b", "a..b", "a\nb", "a\0b"])("rejects unsafe artifact names: %s", value => {
const n = book(" x: {type: string}", "true", "on=local artifacts={{file}} upload={{file}}:/tmp/key");
const r = render(n, {}, { file: value });
expect(Object.keys(r.invalid).length).toBeGreaterThan(0);
});
it("validates filled secrets even when optional because they are passed as env vars", () => {
const n = book(" TOKEN: {type: secret}", "true");
expect(render(n, { TOKEN: "bad\0value" }).invalid.TOKEN).toContain("NUL");
expect(render(n).missing).toEqual([]);
});
it("preserves explicit Untitled frontmatter instead of replacing it with a heading", () => {
expect(parseNotebook("---\ntitle: Untitled\n---\n# Different").title).toBe("Untitled");
});
it("renders prose with raw values and handles inherited names safely", () => {
const n = book(" x: {type: string}");
expect(renderText("{{x}} {{toString}}", { x: "a & b" }, n)).toBe("a & b {{toString}}");
// An unset value stays visible as its template instead of vanishing ("on ****").
expect(renderText("on **{{x}}**", { x: "" }, n)).toBe("on **{{x}}**");
expect(render(n, {}, {}).invalid.x).toBeUndefined();
expect(render(n, {}, {}).missing).toContain("x");
});
});
describe("shellQuote", () => {
it.each(["abc", "A09._/@:=+-", "path/to/file"])("leaves safe values unchanged: %s", value => expect(shellQuote(value)).toBe(value));
it.each([["\r", "'\r'"], ["", "''"], ["a b", "'a b'"], ["'", "''\\'''"], ["$x`id`\n雪", "'$x`id`\n雪'"]])("quotes %s", (value, quoted) => expect(shellQuote(value)).toBe(quoted));
// Git for Windows strips CR and transforms backslashes in -c arguments.
// Feed generated scripts through stdin there; CR has separate pure coverage.
const candidates = process.platform === "win32" ? ["sh", "C:/Program Files/Git/bin/sh.exe"] : ["sh"];
const sh = candidates.find(path => { const r = spawnSync(path, ["-c", "printf shellbook"], { encoding: "utf8" }); return r.status === 0 && r.stdout === "shellbook"; });
it.skipIf(!sh)("round-trips 256 deterministic random strings through POSIX sh", () => {
const alphabet = Array.from("aZ09 '\"\n\t$`\\;|&(){}[]*?!雪😀é/@:=+-");
let seed = 123456789;
const random = () => { seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0; return seed; };
for (let i = 0; i < 256; i++) {
let value = "";
const length = random() % 90;
for (let j = 0; j < length; j++) value += alphabet[random() % alphabet.length];
const script = `printf %s ${shellQuote(value)}`;
const result = process.platform === "win32"
? spawnSync(sh!, ["-c", 'eval "$(cat)"'], { input: script, encoding: "utf8" })
: spawnSync(sh!, ["-c", script], { encoding: "utf8" });
expect(result.status).toBe(0); expect(result.stdout).toBe(value);
}
}, 30000);
});