Files
ShellBook/apps/server/test/m3.test.ts
T
Florian Schmidt 324ad4b39a fix: show why SSH connection tests and runs fail (#7)
Test connection, key installation and runs now tell authentication
failures apart from unreachable hosts (refused, timeout, DNS, ...)
instead of a generic "SSH connection failed".

The web client keeps the server's deliberate error messages (4xx,
502, 503) and shows them in the hosts page; unexpected 500 errors
still show only the status. The reload hint appears only on 409
conflicts.
2026-11-16 10:31:11 +01:00

210 lines
15 KiB
TypeScript

import { afterEach, expect, it, vi } from "vitest";
import { mkdtemp, mkdir, writeFile, rm, copyFile, readFile, stat, utimes } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { randomUUID, generateKeyPairSync } from "node:crypto";
import { get } from "node:http";
import { claimArtifact } from "../src/runs/artifacts";
import { spawnSync } from "node:child_process";
import type { ServerEvent, StartRunRequest } from "@shellbook/core";
import { EventsHub } from "../src/runs";
import { persistArtifacts, sweepRuns } from "../src/runs/artifacts";
import { createSshFixture } from "./ssh-fixture";
import { buildApp } from "../src/app";
import { loadConfig } from "../src/config";
const cleanup: (() => Promise<unknown>)[] = [];
afterEach(async () => { try { for (const fn of cleanup.splice(0).reverse()) await fn(); } finally { vi.useRealTimers(); } });
async function fixture() {
const dir = await mkdtemp(path.join(os.tmpdir(), "shellbook-m3-"));
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") });
await mkdir(path.join(config.workspaceDir, "notebooks"), { recursive: true });
const events: ServerEvent[] = []; const hub = new EventsHub(); hub.subscribe(e => events.push(e));
const app = await buildApp({ config, events: hub, auth: false }); cleanup.push(() => app.close());
return { config, app, events };
}
it("returns 410 for unknown valid runs and missing declared artifacts", async () => {
const { config, app } = await fixture(); const id = randomUUID();
expect((await app.inject(`/api/runs/${id}/artifacts/key`)).statusCode).toBe(410);
await mkdir(path.join(config.dataDir, "runs", id), { recursive: true });
await writeFile(path.join(config.dataDir, "runs", id, "artifacts.json"), JSON.stringify(["key"]));
expect((await app.inject(`/api/runs/${id}/artifacts/key`)).statusCode).toBe(410);
expect((await app.inject('/api/runs/invalid/artifacts/key')).statusCode).toBe(400);
});
async function seeded(config: ReturnType<typeof loadConfig>, names: Record<string, string>) {
const id = randomUUID(); const dir = path.join(config.dataDir, "runs", id, "artifacts");
await mkdir(dir, { recursive: true });
for (const [name, value] of Object.entries(names)) await writeFile(path.join(dir, name), value);
await persistArtifacts(config, id, Object.keys(names)); return id;
}
const privateKey = "-----BEGIN OPENSSH PRIVATE KEY-----\nprivate payload\n-----END OPENSSH PRIVATE KEY-----\n";
it("persists sensitivity, serves public files repeatedly, and consumes one of two concurrent private downloads", async () => {
const { config, app } = await fixture();
const id = await seeded(config, { key: privateKey, 'key.pub': 'ssh-ed25519 public' });
expect(JSON.parse(await readFile(path.join(config.dataDir, 'runs', id, 'artifacts.json'), 'utf8'))).toEqual([
{ name: 'key', sensitive: true }, { name: 'key.pub', sensitive: false },
]);
const url = `/api/runs/${id}/artifacts/`;
for (let i = 0; i < 2; i++) expect((await app.inject(url + 'key.pub')).body).toBe('ssh-ed25519 public');
const results = await Promise.all([app.inject(url + 'key'), app.inject(url + 'key')]);
expect(results.map(r => r.statusCode).sort()).toEqual([200, 410]);
expect(results.find(r => r.statusCode === 200)?.body).toBe(privateKey);
await expect.poll(async () => stat(path.join(config.dataDir, 'runs', id, 'artifacts/key')).then(() => true, () => false)).toBe(false);
expect((await app.inject(url + 'key')).statusCode).toBe(410);
});
it.each(['PRIVATE KEY', 'OPENSSH PRIVATE KEY', 'RSA PRIVATE KEY', 'EC PRIVATE KEY', 'DSA PRIVATE KEY', 'ENCRYPTED PRIVATE KEY'])("detects %s by content", async header => {
const { config } = await fixture(); const id = await seeded(config, { arbitrary: `-----BEGIN ${header}-----\nbody` });
expect(JSON.parse(await readFile(path.join(config.dataDir, 'runs', id, 'artifacts.json'), 'utf8'))[0].sensitive).toBe(true);
});
it("expires artifacts at access and sweeps old runs, preserving active runs and unrelated directories", async () => {
const { config, app } = await fixture();
const expired = await seeded(config, { key: 'public' }); const active = await seeded(config, { key: privateKey });
const fresh = await seeded(config, { key: 'new' }); const old = new Date(Date.now() - 25 * 3600000);
for (const id of [expired, active]) await utimes(path.join(config.dataDir, 'runs', id), old, old);
await mkdir(path.join(config.dataDir, 'runs', 'unrelated'));
expect((await app.inject(`/api/runs/${expired}/artifacts/key`)).statusCode).toBe(410);
await sweepRuns(config, new Set([active]));
await expect(stat(path.join(config.dataDir, 'runs', expired))).rejects.toMatchObject({ code: 'ENOENT' });
for (const id of [active, fresh, 'unrelated']) expect((await stat(path.join(config.dataDir, 'runs', id))).isDirectory()).toBe(true);
const restarted = await buildApp({ config, auth: false }); cleanup.push(() => restarted.close());
await expect(stat(path.join(config.dataDir, 'runs', active))).rejects.toMatchObject({ code: 'ENOENT' });
});
it("validates TTL configuration", () => {
expect(loadConfig().artifactTtlHours).toBe(24);
expect(loadConfig({ artifactTtlHours: 0.5 }).artifactTtlHours).toBe(0.5);
for (const value of [0, -1, NaN, Infinity]) expect(() => loadConfig({ artifactTtlHours: value })).toThrow('TTL');
});
async function httpFixture(authenticate = true) {
const f = await fixture();
await writeFile(f.config.sshKeyPath, generateKeyPairSync('rsa', { modulusLength: 2048 }).privateKey.export({ type: 'pkcs1', format: 'pem' }));
const ssh = await createSshFixture(f.config, cleanup, authenticate);
await writeFile(path.join(f.config.workspaceDir, 'hosts.yaml'), JSON.stringify([ssh.host]));
await copyFile(path.resolve('../../templates/workspace/notebooks/ssh-key.md'), path.join(f.config.workspaceDir, 'notebooks/ssh-key.md'));
// Close the app before its SSH transport during teardown.
cleanup.push(() => f.app.close());
return { ...f, ...ssh };
}
async function run(f: Awaited<ReturnType<typeof httpFixture>>, stepId: string, overrides: Partial<StartRunRequest> = {}) {
const response = await f.app.inject({ method: 'POST', url: '/api/runs', payload: {
notebookPath: 'ssh-key.md', stepId, params: { host: 'test', user: 'admin', keyname: 'id_test' }, runtime: {}, artifactSources: {}, acceptHostKey: f.fp, ...overrides,
} });
expect(response.statusCode, response.body).toBe(202); const id: string = response.json().runId;
await expect.poll(() => f.events.find(e => e.type === 'run.finished' && e.runId === id), { timeout: 10000 }).toBeDefined();
const finished = f.events.find(e => e.type === 'run.finished' && e.runId === id)!;
if (finished.type !== 'run.finished') throw new Error('Missing result');
return { id, finished };
}
async function authorize(f: Awaited<ReturnType<typeof httpFixture>>, id: string, publicKey: string) {
const result = await run(f, 'authorize', { artifactSources: { 'id_test.pub': id } });
expect(result.finished.exitCode).toBe(0);
expect(f.files.get('/tmp/shellbook-new-key.pub')?.toString()).toBe(publicKey);
const started = f.events.find(e => e.type === 'run.started' && e.runId === result.id);
if (started?.type !== 'run.started') throw new Error('Missing started');
expect(f.received.find(r => r.command.includes('sudo -n bash'))?.input).toBe(started.script);
expect(started.script).toContain('getent passwd admin');
}
it("uploads a seeded public key over HTTP/SFTP and refuses a consumed private upload source (portable)", async () => {
const f = await httpFixture(); const pub = 'ssh-ed25519 public-key admin@test\n';
const id = await seeded(f.config, { id_test: privateKey, 'id_test.pub': pub });
expect((await f.app.inject(`/api/runs/${id}/artifacts/id_test`)).statusCode).toBe(200);
expect((await f.app.inject(`/api/runs/${id}/artifacts/id_test`)).statusCode).toBe(410);
await authorize(f, id, pub);
await writeFile(path.join(f.config.workspaceDir, 'notebooks/private.md'), '```sh {run host="{{host}}" id=upload upload="id_test:/tmp/key"}\necho ok\n```\n'.replace('host="{{host}}"', 'host=test'));
const result = await run(f, 'upload', { notebookPath: 'private.md', params: {}, artifactSources: { id_test: id } });
expect(result.finished.exitCode).toBe(-1);
expect(f.events).toContainEqual({ type: 'run.error', runId: result.id, message: "Upload source artifact 'id_test' not found or expired" });
});
const localTools = spawnSync('bash', ['-c', 'command -v ssh-keygen >/dev/null'], { timeout: 5000 }).status === 0;
it.skipIf(!localTools)("generates the template SSH keys, downloads once, and authorizes over HTTP", async () => {
const f = await httpFixture(); const { id, finished } = await run(f, 'keygen');
expect(finished).toMatchObject({ exitCode: 0, artifacts: ['id_test', 'id_test.pub'], sensitiveArtifacts: ['id_test'] });
const base = `/api/runs/${id}/artifacts/`;
const pub = await f.app.inject(base + 'id_test.pub'); expect(pub.statusCode).toBe(200);
expect((await f.app.inject(base + 'id_test.pub')).body).toBe(pub.body);
const key = await f.app.inject(base + 'id_test'); expect(key.statusCode).toBe(200); expect(key.body).toContain('PRIVATE KEY');
expect((await f.app.inject(base + 'id_test')).statusCode).toBe(410);
await expect(stat(path.join(f.config.dataDir, 'runs', id, 'work/id_test'))).rejects.toMatchObject({ code: 'ENOENT' });
await authorize(f, id, pub.body);
});
it("passes a captured value into a later HTTP run using real core rendering", async () => {
const f = await httpFixture();
await writeFile(path.join(f.config.workspaceDir, 'notebooks/capture.md'), '```sh {check host=test id=first capture=result}\nprintf result\n```\n\n```sh {run host=test id=second}\nprintf %s {{result}}\n```\n');
const first = await run(f, 'first', { notebookPath: 'capture.md', params: {} });
expect(first.finished.captured).toEqual({ name: 'result', value: 'hello world' });
const second = await run(f, 'second', { notebookPath: 'capture.md', params: {}, runtime: { result: first.finished.captured!.value } });
expect(second.finished.exitCode).toBe(0);
const started = f.events.find(e => e.type === 'run.started' && e.runId === second.id);
expect(started).toMatchObject({ script: "printf %s 'hello world'\n" });
expect(f.received.some(r => r.input === "printf %s 'hello world'\n")).toBe(true);
});
it("reports specific timeouts and missing artifacts without raw errors or secret values", async () => {
const f = await httpFixture();
await writeFile(path.join(f.config.workspaceDir, 'notebooks/error.md'), '---\nparams:\n TOKEN: { type: secret }\n---\n```sh {run host=test id=timeout timeout=0.05}\nHANG\n```\n\n```sh {run host=test id=missing artifacts="absent"}\necho ok\n```\n');
const timed = await run(f, 'timeout', { notebookPath: 'error.md', params: { TOKEN: 'private-secret' } });
expect(f.events).toContainEqual({ type: 'run.error', runId: timed.id, message: 'Execution timed out after 0.05 s' });
const missing = await run(f, 'missing', { notebookPath: 'error.md', params: { TOKEN: 'private-secret' } });
expect(f.events).toContainEqual({ type: 'run.error', runId: missing.id, message: "Artifact 'absent' not found on host" });
expect(JSON.stringify(f.events)).not.toContain('private-secret');
});
it("sweeps hourly, protects executing and queued runs, and clears its timer on close", async () => {
vi.useFakeTimers({ toFake: ['setInterval', 'clearInterval'] });
const intervals = vi.spyOn(globalThis, 'setInterval');
const clears = vi.spyOn(globalThis, 'clearInterval');
const f = await httpFixture();
const retentionIndex = intervals.mock.calls.findIndex(call => call[1] === 3600000);
const retentionTimer = intervals.mock.results[retentionIndex]!.value as NodeJS.Timeout;
expect(retentionTimer.hasRef()).toBe(false);
const expired = await seeded(f.config, { out: 'old' }); const old = new Date(Date.now() - 25 * 3600000);
await utimes(path.join(f.config.dataDir, 'runs', expired), old, old);
await writeFile(path.join(f.config.workspaceDir, 'notebooks/queued.md'), '```sh {run host=test id=hang timeout=1}\nHANG\n```\n');
const ids: string[] = [];
for (let i = 0; i < 2; i++) {
const res = await f.app.inject({ method: 'POST', url: '/api/runs', payload: { notebookPath: 'queued.md', stepId: 'hang', params: {}, runtime: {}, artifactSources: {}, acceptHostKey: f.fp } });
expect(res.statusCode).toBe(202); ids.push(res.json().runId);
}
await expect.poll(() => f.received.some(r => r.input === 'HANG\n')).toBe(true);
for (const id of ids) {
// Queued runs normally have no directory yet; seed one to exercise the protection.
const root = path.join(f.config.dataDir, 'runs', id); await mkdir(root, { recursive: true }); await utimes(root, old, old);
}
await vi.advanceTimersByTimeAsync(3600000);
await expect.poll(() => stat(path.join(f.config.dataDir, 'runs', expired)).then(() => true, () => false)).toBe(false);
for (const id of ids) expect((await stat(path.join(f.config.dataDir, 'runs', id))).isDirectory()).toBe(true);
await f.app.close(); expect(clears).toHaveBeenCalledWith(retentionTimer);
intervals.mockRestore(); clears.mockRestore();
});
it("retains a private artifact after an interrupted download and permits a successful retry", async () => {
const { config, app } = await fixture();
const contents = privateKey + 'x'.repeat(8 * 1024 * 1024);
const id = await seeded(config, { key: contents });
const address = await app.listen({ host: '127.0.0.1', port: 0 });
await new Promise<void>((resolve, reject) => {
const request = get(`${address}/api/runs/${id}/artifacts/key`, response => {
response.once('data', () => { response.destroy(); resolve(); });
});
request.once('error', reject);
});
const file = path.join(config.dataDir, 'runs', id, 'artifacts/key');
await expect.poll(async () => {
try { const release = await claimArtifact(file); await release(false); return true; } catch { return false; }
}).toBe(true);
expect((await stat(file)).isFile()).toBe(true);
const response = await app.inject(`/api/runs/${id}/artifacts/key`);
expect(response.statusCode).toBe(200); expect(response.body).toBe(contents);
expect((await app.inject(`/api/runs/${id}/artifacts/key`)).statusCode).toBe(410);
});
it("redacts secrets in specific run.error reasons", async () => {
const f = await httpFixture();
await writeFile(path.join(f.config.workspaceDir, 'notebooks/redact.md'), '---\nparams:\n TOKEN: { type: secret }\n---\n```sh {run host=test id=missing artifacts="private-secret"}\necho ok\n```\n');
const result = await run(f, 'missing', { notebookPath: 'redact.md', params: { TOKEN: 'private-secret' } });
expect(f.events).toContainEqual({ type: 'run.error', runId: result.id, message: "Artifact '[REDACTED]' not found on host" });
expect(JSON.stringify(f.events) + await readFile(path.join(f.config.dataDir, 'audit.jsonl'), 'utf8')).not.toContain('private-secret');
});
it("reports SSH authentication failure without raw transport details", async () => {
const f = await httpFixture(false);
const result = await run(f, 'authorize');
expect(result.finished.exitCode).toBe(-1);
expect(f.events).toContainEqual({ type: 'run.error', runId: result.id, message: 'SSH authentication failed: check the user and the saved password or key' });
});