feat(server): add one-shot sensitive artifacts and retention (#4)
This commit is contained in:
@@ -4,10 +4,14 @@ export interface ServerConfig {
|
||||
workspaceDir: string;
|
||||
dataDir: string;
|
||||
sshKeyPath: string;
|
||||
artifactTtlHours: number;
|
||||
}
|
||||
|
||||
export function loadConfig(overrides: Partial<ServerConfig> = {}): ServerConfig {
|
||||
const artifactTtlHours = Number(overrides.artifactTtlHours ?? process.env.SHELLBOOK_ARTIFACT_TTL_HOURS ?? 24);
|
||||
if (!Number.isFinite(artifactTtlHours) || artifactTtlHours <= 0) throw new Error("Artifact TTL must be a positive number of hours");
|
||||
return {
|
||||
artifactTtlHours,
|
||||
workspaceDir: path.resolve(overrides.workspaceDir ?? process.env.SHELLBOOK_WORKSPACE ?? "workspace"),
|
||||
dataDir: path.resolve(overrides.dataDir ?? process.env.SHELLBOOK_DATA_DIR ?? "data"),
|
||||
sshKeyPath: path.resolve(overrides.sshKeyPath ?? process.env.SHELLBOOK_SSH_KEY ?? "data/id_ed25519"),
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
import { mkdir, open, readFile, writeFile, stat, readdir, rm } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { createHash } from "node:crypto";
|
||||
import type { ServerConfig } from "../config";
|
||||
import { httpError, safeFile, safeRelative } from "../workspace";
|
||||
|
||||
const RUN_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
||||
export function runRoot(config: ServerConfig, id: string) {
|
||||
if (!RUN_ID.test(id)) throw httpError(400, "Invalid run ID");
|
||||
return path.join(config.dataDir, "runs", id);
|
||||
}
|
||||
export interface Artifact { name: string; sensitive: boolean }
|
||||
/** Inspect only a bounded prefix, independent of the artifact size. */
|
||||
export async function isSensitive(file: string): Promise<boolean> {
|
||||
const handle = await open(file, "r");
|
||||
try {
|
||||
const prefix = Buffer.alloc(512);
|
||||
const { bytesRead } = await handle.read(prefix, 0, prefix.length, 0);
|
||||
return /^\s*-----BEGIN (?:[A-Z0-9]+ )*PRIVATE KEY-----/.test(prefix.toString("ascii", 0, bytesRead));
|
||||
} finally { await handle.close(); }
|
||||
}
|
||||
/** Shared by collection and portable fixtures; metadata contains no file contents. */
|
||||
export async function persistArtifacts(config: ServerConfig, id: string, names: string[]): Promise<Artifact[]> {
|
||||
const root = runRoot(config, id);
|
||||
const artifacts = await Promise.all(names.map(async name => ({ name, sensitive: await isSensitive(await safeFile(path.join(root, "artifacts"), name)) })));
|
||||
await writeFile(path.join(root, "artifacts.json"), JSON.stringify(artifacts), { mode: 0o600 });
|
||||
return artifacts;
|
||||
}
|
||||
export async function artifactFile(config: ServerConfig, id: string, name: string) {
|
||||
safeRelative(name);
|
||||
const root = runRoot(config, id);
|
||||
try {
|
||||
if (Date.now() - (await stat(root)).mtimeMs >= config.artifactTtlHours * 3600000) throw httpError(410, "Artifact expired");
|
||||
const entries: (Artifact | string)[] = JSON.parse(await readFile(path.join(root, "artifacts.json"), "utf8"));
|
||||
const entry = entries.find(entry => (typeof entry === "string" ? entry : entry.name) === name);
|
||||
if (!entry) throw httpError(404, "Artifact not found");
|
||||
const file = await safeFile(path.join(root, "artifacts"), name);
|
||||
if (!(await stat(file)).isFile()) throw httpError(410, "Artifact unavailable");
|
||||
return { file, sensitive: typeof entry === "string" ? await isSensitive(file) : entry.sensitive };
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code === "ENOENT" || (error as { statusCode?: number }).statusCode === 404 && (error as Error).message === "File not found") throw httpError(410, "Artifact not found or expired");
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
/** Exclusive on-disk claim prevents simultaneous sensitive downloads, including across app instances. */
|
||||
export async function claimArtifact(file: string) {
|
||||
const locks = path.join(path.dirname(file), ".downloads");
|
||||
await mkdir(locks, { recursive: true, mode: 0o700 });
|
||||
const identity = process.platform === "win32" ? path.basename(file).toLowerCase() : path.basename(file);
|
||||
const lock = path.join(locks, createHash("sha256").update(identity).digest("hex"));
|
||||
try { const handle = await open(lock, "wx", 0o600); await handle.close(); }
|
||||
catch (error) { if ((error as NodeJS.ErrnoException).code === "EEXIST") throw httpError(410, "Sensitive artifact already claimed"); throw error; }
|
||||
// A preceding download may have deleted the file while this request awaited metadata.
|
||||
try { await stat(file); }
|
||||
catch (error) {
|
||||
await rm(lock, { force: true });
|
||||
if ((error as NodeJS.ErrnoException).code === "ENOENT") throw httpError(410, "Artifact not found or expired");
|
||||
throw error;
|
||||
}
|
||||
return async (success: boolean) => {
|
||||
// Keep the claim if deletion fails: fail closed rather than serve the key again.
|
||||
if (success) await rm(file, { force: true });
|
||||
await rm(lock, { force: true });
|
||||
};
|
||||
}
|
||||
export async function sweepRuns(config: ServerConfig, active: ReadonlySet<string>, now = Date.now()) {
|
||||
const base = path.join(config.dataDir, "runs");
|
||||
await mkdir(base, { recursive: true, mode: 0o700 });
|
||||
for (const entry of await readdir(base, { withFileTypes: true })) {
|
||||
if (!entry.isDirectory() || !RUN_ID.test(entry.name) || active.has(entry.name)) continue;
|
||||
const root = runRoot(config, entry.name);
|
||||
const info = await stat(root).catch((error: NodeJS.ErrnoException) => { if (error.code === "ENOENT") return undefined; throw error; });
|
||||
if (info && now - info.mtimeMs >= config.artifactTtlHours * 3600000 && !active.has(entry.name)) await rm(root, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { appendFile, mkdir, readFile, writeFile, copyFile, stat } from "node:fs/promises";
|
||||
import { appendFile, mkdir, copyFile, stat, rm } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { createReadStream } from "node:fs";
|
||||
import { parseNotebook, resolveParams, renderStep, secretEnv, shellQuote, type Block, type Step, type Notebook, type RenderedStep, type StartRunRequest, type HostInfo } from "@shellbook/core";
|
||||
@@ -9,6 +9,7 @@ import type { ServerConfig } from "../config";
|
||||
import { readHosts, readNotebook, safeFile, safeRelative, httpError, SerialQueue } from "../workspace";
|
||||
import { connect, exec, localExec, scriptInput, sftp, sftpRequest, transfer, HostKeyError, type Output } from "../ssh";
|
||||
import { EventsHub } from "./events";
|
||||
import { runRoot, artifactFile, persistArtifacts, isSensitive, claimArtifact, sweepRuns } from "./artifacts";
|
||||
export { EventsHub } from "./events";
|
||||
|
||||
export function findStep(blocks: Block[], id: string): Step | undefined {
|
||||
@@ -52,20 +53,6 @@ export function redactor(secrets: string[], output: (data: string) => void) {
|
||||
return { write(data: string) { pending += data; flush(false); }, end() { flush(true); } };
|
||||
}
|
||||
|
||||
function runRoot(config: ServerConfig, id: string) {
|
||||
if (!/^[0-9a-f-]{36}$/.test(id)) throw httpError(400, "Invalid run ID");
|
||||
return path.join(config.dataDir, "runs", id);
|
||||
}
|
||||
async function artifactFile(config: ServerConfig, id: string, name: string) {
|
||||
safeRelative(name);
|
||||
const root = runRoot(config, id);
|
||||
const names: string[] = JSON.parse(await readFile(path.join(root, "artifacts.json"), "utf8"));
|
||||
if (!names.includes(name)) throw httpError(404, "Artifact not found");
|
||||
const file = await safeFile(path.join(root, "artifacts"), name);
|
||||
if (!(await stat(file)).isFile()) throw httpError(404, "Artifact not a file");
|
||||
return file;
|
||||
}
|
||||
|
||||
export interface ExecuteRun {
|
||||
config: ServerConfig; hub: EventsHub; runId: string; request: StartRunRequest;
|
||||
step: Step; rendered: RenderedStep; host?: HostInfo; env: Record<string, string>;
|
||||
@@ -84,6 +71,8 @@ export async function executeRun({ config, hub, runId, request, step, rendered,
|
||||
let client: Client | undefined;
|
||||
let remoteDir: string | undefined;
|
||||
const artifacts: string[] = [];
|
||||
let sensitiveArtifacts: string[] = [];
|
||||
let failureReason = "Cannot prepare run storage";
|
||||
const streams = {
|
||||
stdout: redactor(secrets, data => {
|
||||
if (step.attrs.capture) {
|
||||
@@ -101,7 +90,9 @@ export async function executeRun({ config, hub, runId, request, step, rendered,
|
||||
hub.publish({ type: "run.started", runId, notebookPath: request.notebookPath, stepId: rendered.stepId, host: rendered.host, script: clean(rendered.script) });
|
||||
const timeout = step.attrs.timeoutSec * 1000;
|
||||
if (!rendered.local) {
|
||||
failureReason = `Cannot connect to ${host!.address}:${host!.port}`;
|
||||
client = await connect(config, host!, request.acceptHostKey);
|
||||
failureReason = "Cannot create remote workdir";
|
||||
let directory = "";
|
||||
const code = await exec(client, "mktemp -d", "", timeout, (stream, data) => { if (stream === "stdout") directory += data; });
|
||||
remoteDir = directory.trim();
|
||||
@@ -109,8 +100,10 @@ export async function executeRun({ config, hub, runId, request, step, rendered,
|
||||
}
|
||||
for (const upload of rendered.uploads) {
|
||||
const sourceId = request.artifactSources[upload.src];
|
||||
if (!sourceId) throw new Error("Missing upload source");
|
||||
const source = await artifactFile(config, sourceId, upload.src);
|
||||
failureReason = `Upload source artifact '${upload.src}' not found or expired`;
|
||||
if (!sourceId) throw new Error(failureReason);
|
||||
const { file: source } = await artifactFile(config, sourceId, upload.src);
|
||||
failureReason = `Upload of artifact '${upload.src}' failed`;
|
||||
if (rendered.local) {
|
||||
// Local upload destinations must remain inside this run's workdir.
|
||||
safeRelative(upload.dst);
|
||||
@@ -124,12 +117,15 @@ export async function executeRun({ config, hub, runId, request, step, rendered,
|
||||
finally { session.end(); }
|
||||
}
|
||||
}
|
||||
failureReason = "Execution failed";
|
||||
if (rendered.local) exitCode = await localExec(workdir, rendered.script, env, step.attrs.sudo, timeout, output);
|
||||
else exitCode = await exec(client!, `cd ${shellQuote(remoteDir!)} && ${step.attrs.sudo ? "sudo -n " : ""}bash -euo pipefail -s`, scriptInput(rendered.script, env), timeout, output);
|
||||
streams.stdout.end(); streams.stderr.end();
|
||||
if (exitCode !== 0) hub.publish({ type: "run.error", runId, message: clean(`Script exited with code ${exitCode}`) });
|
||||
if (captureTooLarge) throw new Error("Captured output exceeds 1 MiB");
|
||||
if (exitCode === 0) {
|
||||
for (const name of rendered.artifacts) {
|
||||
failureReason = `Artifact '${name}' not found on host`;
|
||||
safeRelative(name);
|
||||
if (secrets.some(secret => name.includes(secret))) throw new Error("Secret in artifact name");
|
||||
const target = path.join(artifactDir, name);
|
||||
@@ -138,6 +134,7 @@ export async function executeRun({ config, hub, runId, request, step, rendered,
|
||||
const source = await safeFile(workdir, name);
|
||||
if (!(await stat(source)).isFile()) throw new Error("Artifact is not a regular file");
|
||||
await copyFile(source, target);
|
||||
if (await isSensitive(target)) await rm(source);
|
||||
} else {
|
||||
const session = await sftp(client!);
|
||||
try {
|
||||
@@ -152,11 +149,12 @@ export async function executeRun({ config, hub, runId, request, step, rendered,
|
||||
artifacts.push(name);
|
||||
}
|
||||
}
|
||||
await writeFile(path.join(root, "artifacts.json"), JSON.stringify(artifacts), { mode: 0o600 });
|
||||
failureReason = "Cannot persist artifact metadata";
|
||||
sensitiveArtifacts = (await persistArtifacts(config, runId, artifacts)).filter(a => a.sensitive).map(a => a.name);
|
||||
} catch (error) {
|
||||
exitCode = -1;
|
||||
if (error instanceof HostKeyError) hub.publish({ type: "run.hostKeyUnknown", runId, host: rendered.host!, fingerprint: error.fingerprint, changed: error.changed });
|
||||
else hub.publish({ type: "run.error", runId, message: "Run failed (connection, execution, or file transfer error)" });
|
||||
else hub.publish({ type: "run.error", runId, message: clean(runFailure(error, failureReason, step.attrs.timeoutSec)) });
|
||||
} finally {
|
||||
streams.stdout.end(); streams.stderr.end();
|
||||
if (client && remoteDir) {
|
||||
@@ -169,9 +167,9 @@ export async function executeRun({ config, hub, runId, request, step, rendered,
|
||||
await appendFile(path.join(config.dataDir, "audit.jsonl"), JSON.stringify({ time: new Date(start).toISOString(), notebookPath: request.notebookPath, stepId: rendered.stepId, host: rendered.host ?? "local", script: clean(rendered.script), exitCode, durationMs }) + "\n", { mode: 0o600 });
|
||||
} catch {
|
||||
exitCode = -1;
|
||||
hub.publish({ type: "run.error", runId, message: "Run audit could not be persisted" });
|
||||
hub.publish({ type: "run.error", runId, message: clean("Run audit could not be persisted") });
|
||||
}
|
||||
hub.publish({ type: "run.finished", runId, exitCode, durationMs, artifacts: exitCode === 0 ? artifacts : [], ...(exitCode === 0 && step.attrs.capture ? { captured: { name: step.attrs.capture, value: stdout.trim() } } : {}) });
|
||||
hub.publish({ type: "run.finished", runId, exitCode, durationMs, artifacts: exitCode === 0 ? artifacts : [], sensitiveArtifacts: exitCode === 0 ? sensitiveArtifacts : [], ...(exitCode === 0 && step.attrs.capture ? { captured: { name: step.attrs.capture, value: stdout.trim() } } : {}) });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -180,6 +178,14 @@ function stringMap(value: unknown): value is Record<string, string> {
|
||||
}
|
||||
export async function runsPlugin(app: FastifyInstance, { config, hub }: { config: ServerConfig; hub: EventsHub }) {
|
||||
const queue = new SerialQueue();
|
||||
const active = new Set<string>();
|
||||
const downloads = new Set<Promise<void>>();
|
||||
await sweepRuns(config, active);
|
||||
let sweeping = Promise.resolve();
|
||||
const timer = setInterval(() => {
|
||||
sweeping = sweeping.then(() => sweepRuns(config, active)).catch(() => { app.log.warn("Artifact retention sweep failed"); });
|
||||
}, 3600000);
|
||||
timer.unref();
|
||||
app.get("/api/events", { websocket: true }, socket => {
|
||||
const unsubscribe = hub.subscribe(event => { if (socket.readyState === 1) socket.send(JSON.stringify(event)); });
|
||||
socket.on("close", unsubscribe);
|
||||
@@ -191,16 +197,40 @@ export async function runsPlugin(app: FastifyInstance, { config, hub }: { config
|
||||
const { source } = await readNotebook(config, body.notebookPath);
|
||||
const prepared = prepareRun(parseNotebook(source), body, await readHosts(config));
|
||||
const runId = randomUUID();
|
||||
active.add(runId);
|
||||
// Queue immediately; defer the work to allow the HTTP response to reach the subscriber.
|
||||
void queue.run(prepared.host ? `${prepared.host.address}:${prepared.host.port}` : "local", async () => {
|
||||
await new Promise<void>(resolve => setImmediate(resolve));
|
||||
await executeRun({ config, hub, runId, request: body, ...prepared });
|
||||
}).catch(() => hub.publish({ type: "run.error", runId, message: "Run persistence failed" }));
|
||||
}).catch(() => hub.publish({ type: "run.error", runId, message: "Run persistence failed" })).finally(() => active.delete(runId));
|
||||
return reply.code(202).send({ runId });
|
||||
});
|
||||
app.get<{ Params: { runId: string; name: string } }>("/api/runs/:runId/artifacts/:name", async (req, reply) => {
|
||||
const file = await artifactFile(config, req.params.runId, req.params.name);
|
||||
return reply.type("application/octet-stream").header("Content-Disposition", "attachment").send(createReadStream(file));
|
||||
const { file, sensitive } = await artifactFile(config, req.params.runId, req.params.name);
|
||||
const release = sensitive ? await claimArtifact(file) : undefined;
|
||||
if (release) {
|
||||
let settled = false;
|
||||
const finish = (success: boolean) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
const cleanup = release(success).catch(() => { app.log.warn("Sensitive artifact cleanup failed"); });
|
||||
downloads.add(cleanup);
|
||||
void cleanup.finally(() => downloads.delete(cleanup));
|
||||
};
|
||||
reply.raw.once("finish", () => finish(true));
|
||||
reply.raw.once("close", () => finish(reply.raw.writableFinished));
|
||||
}
|
||||
return reply.type("application/octet-stream").header("Content-Disposition", "attachment").header("Cache-Control", "no-store").send(createReadStream(file));
|
||||
});
|
||||
app.addHook("onClose", async () => { await queue.idle(); });
|
||||
app.addHook("onClose", async () => { clearInterval(timer); await sweeping; await queue.idle(); await Promise.all(downloads); });
|
||||
}
|
||||
|
||||
/** Allowlisted reasons only: raw transport errors may contain credentials or paths. */
|
||||
function runFailure(error: unknown, fallback: string, timeoutSec: number): string {
|
||||
const e = error as { message?: string; level?: string; code?: string };
|
||||
if (e.message === "Execution timed out") return `Execution timed out after ${timeoutSec} s`;
|
||||
if (e.level === "client-authentication") return "SSH authentication failed";
|
||||
if (e.message === "Captured output exceeds 1 MiB") return e.message;
|
||||
if (e.message?.startsWith("SFTP ") && e.message.endsWith(" timed out")) return "File transfer timed out";
|
||||
return fallback;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user