import { afterEach, expect, it } from "vitest"; import { mkdtemp, mkdir, writeFile, readFile, rm, readdir, stat, } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; import { generateKeyPairSync, randomUUID, createPrivateKey } from "node:crypto"; import { utils } from "ssh2"; import { buildApp } from "../src/app"; import { loadConfig } from "../src/config"; import { validateHost } from "../src/hosts/validation"; import { CredentialStore } from "../src/hosts/credentials"; import { installKeyScript } from "../src/hosts"; import { connect, exec, forgetHostKey, sftp, transfer } from "../src/ssh"; import { createSshFixture } from "./ssh-fixture"; import { executeRun, EventsHub } from "../src/runs"; import { shellQuote, type ServerEvent } from "@shellbook/core"; const cleanup: (() => Promise)[] = []; afterEach(async () => { for (const fn of cleanup.splice(0).reverse()) await fn(); }); const host = { name: "demo", address: "example.org", user: "ops", port: 22, tags: ["prod"], }; async function fixture(auth = false) { const dir = await mkdtemp(path.join(os.tmpdir(), "shellbook-hosts-")); 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(config.workspaceDir); await mkdir(path.join(config.workspaceDir, "notebooks")); await writeFile( path.join(config.workspaceDir, "hosts.yaml"), "# Inventory\nhosts:\n # Production\n - name: demo # stable name\n address: example.org # endpoint\n user: ops\n", ); const key = generateKeyPairSync("rsa", { modulusLength: 2048 }) .privateKey.export({ format: "pem", type: "pkcs1" }) .toString(); await writeFile(config.sshKeyPath, key); const app = await buildApp({ config, auth: auth ? {} : false }); cleanup.push(() => app.close()); return { config, app, key, store: new CredentialStore(config.dataDir) }; } it.each([ { name: "../bad" }, { name: "" }, { address: "a b" }, { address: "a/b" }, { address: "999.1.1.1" }, { address: "-host" }, { address: "host:22" }, { user: "-x" }, { user: "a;id" }, { port: 0 }, { port: 65536 }, { port: 1.5 }, { tags: [2] }, ])("rejects invalid host fields %j", (value) => { expect(() => validateHost({ ...host, ...value })).toThrow(); }); it.each([ "localhost", "example.org", "host-1.example.org.", "127.0.0.1", "::1", "2001:db8::1", ])("accepts address %s", (address) => { expect(validateHost({ ...host, address }).address).toBe(address); }); it("round-trips YAML comments/order, validates uniqueness, renames and rejects stale saves", async () => { const { app, config, store } = await fixture(); const first = (await app.inject("/api/host-management")).json(); const url = "/api/host-management/demo"; await store.set("demo", { type: "password", password: "kept-on-rename" }); const payload = { host: { ...host, name: "renamed" }, baseVersion: first.version, }; const results = await Promise.all([ app.inject({ method: "PUT", url, payload }), app.inject({ method: "PUT", url, payload }), ]); expect(results.map((r) => r.statusCode).sort()).toEqual([200, 409]); const source = await readFile( path.join(config.workspaceDir, "hosts.yaml"), "utf8", ); for (const comment of [ "# Inventory", "# Production", "# stable name", "# endpoint", ]) expect(source).toContain(comment); expect((await store.get("renamed"))?.input).toEqual({ type: "password", password: "kept-on-rename", }); expect(await store.get("demo")).toBeUndefined(); const current = (await app.inject("/api/host-management")).json(); expect( ( await app.inject({ method: "POST", url: "/api/host-management", payload: { host: { ...host, name: "renamed" }, baseVersion: current.version, }, }) ).statusCode, ).toBe(409); expect( ( await app.inject({ method: "DELETE", url: "/api/host-management/renamed", payload: { baseVersion: current.version }, }) ).statusCode, ).toBe(200); expect(await store.get("renamed")).toBeUndefined(); }); it("encrypts credentials, rejects tampering and stores no secrets in workspace", async () => { const { config, store, key } = await fixture(); await store.set("demo", { type: "password", password: "very-secret-value" }); expect((await store.get("demo"))?.input).toEqual({ type: "password", password: "very-secret-value", }); const dir = path.join(config.dataDir, "ssh-credentials"); const file = path.join(dir, (await readdir(dir))[0]!); const bytes = await readFile(file); expect(bytes.toString()).not.toContain("very-secret-value"); if (process.platform !== "win32") for (const f of [file, path.join(config.dataDir, "ssh-credentials.key")]) expect((await stat(f)).mode & 0o777).toBe(0o600); bytes[30] = bytes[30]! ^ 1; await writeFile(file, bytes); await expect(store.get("demo")).rejects.toThrow("Cannot decrypt"); expect( (await store.set("demo", { type: "privateKey", privateKey: key })) .fingerprint, ).toMatch(/^SHA256:/); expect((await store.get("demo"))?.input).toEqual({ type: "privateKey", privateKey: key, }); await expect( store.set("demo", { type: "privateKey", privateKey: "bad secret" }), ).rejects.toThrow("Invalid private key"); expect( await readFile(path.join(config.workspaceDir, "hosts.yaml"), "utf8"), ).not.toContain("very-secret-value"); }); it("keeps the API write-only and removes credentials when selecting the default", async () => { const { app } = await fixture(); const url = "/api/host-management/demo/credential"; const response = await app.inject({ method: "PUT", url, payload: { type: "password", password: "browser-never-gets-this" }, }); expect(response.statusCode).toBe(200); expect(response.json()).toMatchObject({ type: "password", setAt: expect.any(String), }); const inventory = await app.inject("/api/host-management"); expect(inventory.body + response.body).not.toContain( "browser-never-gets-this", ); expect(inventory.headers["cache-control"]).toBe("no-store"); expect((await app.inject(url)).statusCode).toBe(404); expect( ( await app.inject({ method: "PUT", url, payload: { type: "certificate", privateKey: "secret" }, }) ).statusCode, ).toBe(400); await app.inject({ method: "DELETE", url }); expect( (await app.inject("/api/host-management")).json().hosts[0].credential, ).toEqual({ type: "shellbook" }); }); it.each([ ["GET", ""], ["POST", ""], ["PUT", "/demo"], ["DELETE", "/demo"], ["PUT", "/demo/credential"], ["DELETE", "/demo/credential"], ["GET", "/demo/install-key"], ["POST", "/demo/action"], ["DELETE", "/demo/known-key"], ] as const)( "guards %s host management%s with session and origin checks", async (method, suffix) => { const { app } = await fixture(true); expect( (await app.inject({ method, url: "/api/host-management" + suffix })) .statusCode, ).toBe(401); expect( ( await app.inject({ method, url: "/api/host-management" + suffix, headers: { origin: "https://evil.invalid" }, }) ).statusCode, ).toBe(403); }, ); it.each(["password", "keyboard", "privateKey", "encryptedKey"])( "uses stored %s authentication with strict TOFU", async (mode) => { const { config, store, key } = await fixture(); const parsed = utils.parseKey(key); if (parsed instanceof Error || Array.isArray(parsed)) throw new Error("key"); let accepted = false; const ssh = await createSshFixture(config, cleanup, (ctx) => { if ( mode === "password" && ctx.method === "password" && ctx.password === "ssh-password" ) { accepted = true; ctx.accept(); } else if (mode === "keyboard" && ctx.method === "keyboard-interactive") ctx.prompt([{ prompt: "Password: ", echo: false }], (answers) => { if (answers[0] === "ssh-password") { accepted = true; ctx.accept(); } else ctx.reject(); }); else if ( (mode === "privateKey" || mode === "encryptedKey") && ctx.method === "publickey" && ctx.key.data.equals(parsed.getPublicSSH()) && (!ctx.signature || parsed.verify(ctx.blob!, ctx.signature, ctx.hashAlgo) === true) ) { accepted = true; ctx.accept(); } else ctx.reject( mode === "keyboard" ? ["keyboard-interactive"] : mode === "password" ? ["password"] : ["publickey"], ); }); await store.set( ssh.host.name, mode === "privateKey" || mode === "encryptedKey" ? { type: "privateKey", privateKey: mode === "encryptedKey" ? createPrivateKey(key) .export({ type: "pkcs1", format: "pem", cipher: "aes-256-cbc", passphrase: "key-passphrase", }) .toString() : key, ...(mode === "encryptedKey" ? { passphrase: "key-passphrase" } : {}), } : { type: "password", password: "ssh-password" }, ); await expect(connect(config, ssh.host)).rejects.toMatchObject({ fingerprint: ssh.fp, }); const client = await connect(config, ssh.host, ssh.fp); expect(await exec(client, "true", "", 2000, () => {})).toBe(0); const session = await sftp(client); const output = path.join(config.dataDir, "download.txt"); await transfer(session, "fastGet", "/tmp/shellbook-test/out.txt", output); await transfer(session, "fastPut", output, "/tmp/uploaded.txt"); expect(ssh.files.get("/tmp/uploaded.txt")?.toString()).toBe( "artifact bytes", ); session.end(); client.end(); expect(accepted).toBe(true); await forgetHostKey(config, ssh.host); await expect(connect(config, ssh.host)).rejects.toMatchObject({ fingerprint: ssh.fp, }); }, ); it("renders the exact install command using core quoting and checks the preview before execution", async () => { const publicKey = "ssh-ed25519 AAAA a'comment"; const script = installKeyScript(publicKey); expect(script).toContain(`grep -qxF -- ${shellQuote(publicKey)}`); expect(script).toContain(`printf '\\n%s\\n' ${shellQuote(publicKey)}`); const { app, config, store } = await fixture(); const ssh = await createSshFixture(config, cleanup); await writeFile( path.join(config.workspaceDir, "hosts.yaml"), JSON.stringify([ssh.host]), ); await store.set(ssh.host.name, { type: "password", password: "ssh-secret" }); const root = `/api/host-management/${ssh.host.name}`; const preview = (await app.inject(root + "/install-key")).json().script; expect( ( await app.inject({ method: "POST", url: root + "/action", payload: { action: "install-key", script: "other" }, }) ).statusCode, ).toBe(409); const untrusted = ( await app.inject({ method: "POST", url: root + "/action", payload: { action: "test" }, }) ).json(); expect(untrusted.hostKey).toMatchObject({ fingerprint: ssh.fp, changed: false, }); const result = await app.inject({ method: "POST", url: root + "/action", payload: { action: "install-key", script: preview, acceptHostKey: ssh.fp }, }); expect(result.json()).toEqual({ exitCode: 0 }); expect(ssh.received.at(-1)?.input).toBe(preview); }); it("redacts credential values in streamed run output and audit", async () => { const { config, store } = await fixture(); const ssh = await createSshFixture(config, cleanup); await store.set(ssh.host.name, { type: "password", password: "hello" }); const events: ServerEvent[] = []; const hub = new EventsHub(); hub.subscribe((e) => events.push(e)); await executeRun({ config, hub, host: ssh.host, runId: randomUUID(), env: {}, request: { notebookPath: "a.md", stepId: "x", params: {}, runtime: {}, artifactSources: {}, acceptHostKey: ssh.fp, }, step: { kind: "check", lang: "sh", script: "true", range: { startLine: 1, endLine: 3 }, attrs: { id: "x", local: false, sudo: false, confirm: false, artifacts: [], uploads: [], timeoutSec: 5, }, }, rendered: { stepId: "x", kind: "check", host: ssh.host.name, local: false, script: "true", artifacts: [], uploads: [], missing: [], invalid: {}, }, }); expect(JSON.stringify(events)).not.toContain("hello"); expect(JSON.stringify(events)).toContain("[REDACTED]"); expect(events.at(-1)).toMatchObject({ type: "run.finished", exitCode: 0 }); }); it("creates one encryption key under concurrent writes", async () => { const { config } = await fixture(); await Promise.all( Array.from({ length: 20 }, (_, i) => new CredentialStore(config.dataDir).set(String(i), { type: "password", password: `password-${i}`, }), ), ); for (let i = 0; i < 20; i++) expect( (await new CredentialStore(config.dataDir).get(String(i)))?.input, ).toEqual({ type: "password", password: `password-${i}` }); }); it("separates appended public keys from an existing unterminated line", () => { expect(installKeyScript("ssh-ed25519 AAA")).toContain("printf '\\n%s\\n'"); }); it("pins an explicit ShellBook authentication snapshot instead of rereading a changed credential", async () => { const { config, store } = await fixture(); const ssh = await createSshFixture(config, cleanup, (ctx) => ctx.method === "publickey" ? ctx.accept() : ctx.reject(["publickey"]), ); await store.set(ssh.host.name, { type: "password", password: "wrong-method", }); const client = await connect(config, ssh.host, ssh.fp, null); client.end(); }); it("refuses to write credential secrets inside the git workspace", async () => { const { config } = await fixture(); const dir = path.join(config.workspaceDir, "data"); await expect( new CredentialStore(dir, config.workspaceDir).set("demo", { type: "password", password: "must-not-write", }), ).rejects.toThrow("outside the workspace"); expect(await readdir(dir)).not.toContain("ssh-credentials.key"); });