Merge branch 't3/implement-auth-deploy'
Integrate auth, config, watcher and terminal wiring in buildApp: auth guards every API route by default, notebook watcher events feed the /api/events hub, the terminal runs in the configured workspace, and SHELLBOOK_DATA_DIR is the single data directory variable. The systemd unit uses KillMode=process so tmux sessions survive service restarts.
This commit is contained in:
@@ -0,0 +1,134 @@
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import type { FastifyInstance } from "fastify";
|
||||
import { buildApp, type AppOptions } from "../src/app";
|
||||
import type { AuthOptions } from "../src/auth";
|
||||
import { hashPassword, setPassword, verifyPassword } from "../src/auth/credentials";
|
||||
import { loadSessionSecret, signSession, verifySession } from "../src/auth/session";
|
||||
|
||||
const dirs: string[] = [];
|
||||
const apps: FastifyInstance[] = [];
|
||||
async function directory() { const dir = await mkdtemp(join(tmpdir(), "shellbook-auth-")); dirs.push(dir); return dir; }
|
||||
async function setup(options: AppOptions & { auth?: Partial<AuthOptions> } = {}) {
|
||||
const dataDir = options.auth?.dataDir ?? await directory();
|
||||
await setPassword(dataDir, "test password");
|
||||
const app = await buildApp({ ...options, auth: { dataDir, ...options.auth } });
|
||||
apps.push(app);
|
||||
app.get("/api/private", async () => ({ ok: true }));
|
||||
app.get("/api/ws", { websocket: true }, socket => { socket.send("authenticated"); });
|
||||
return { app, dataDir };
|
||||
}
|
||||
async function login(app: FastifyInstance, headers = {}) {
|
||||
return app.inject({ method: "POST", url: "/api/auth/login", payload: { password: "test password" }, headers });
|
||||
}
|
||||
afterEach(async () => {
|
||||
for (const app of apps.splice(0)) await app.close();
|
||||
for (const dir of dirs.splice(0)) await rm(dir, { recursive: true, force: true });
|
||||
});
|
||||
describe("passwords and sessions", () => {
|
||||
it("salts scrypt hashes and compares passwords safely", async () => {
|
||||
const hash = await hashPassword("secret");
|
||||
expect(await hashPassword("secret")).not.toBe(hash);
|
||||
expect(await verifyPassword("secret", hash)).toBe(true);
|
||||
expect(await verifyPassword("wrong", hash)).toBe(false);
|
||||
expect(await verifyPassword("secret", "malformed")).toBe(false);
|
||||
expect(await verifyPassword("x".repeat(4097), hash)).toBe(false);
|
||||
await expect(hashPassword("")).rejects.toThrow();
|
||||
});
|
||||
it("rejects tampering, wrong keys, invalid input and expired cookies", () => {
|
||||
const key = Buffer.alloc(32, 1);
|
||||
const token = signSession(key, 2000);
|
||||
expect(verifySession(key, token, 1000)).toBe(true);
|
||||
expect(verifySession(key, token, 2000)).toBe(false);
|
||||
expect(verifySession(key, token.replace("2000", "3000"), 1000)).toBe(false);
|
||||
expect(verifySession(Buffer.alloc(32, 2), token, 1000)).toBe(false);
|
||||
for (const bad of ["", "x.y", "99999999999999999.a", token + "x"]) expect(verifySession(key, bad, 1000)).toBe(false);
|
||||
});
|
||||
it("persists a private signing secret and rejects corrupt state", async () => {
|
||||
const dir = await directory();
|
||||
expect(loadSessionSecret(dir)).toEqual(loadSessionSecret(dir));
|
||||
if (process.platform !== "win32") expect((await stat(join(dir, "session-secret"))).mode & 0o777).toBe(0o600);
|
||||
await writeFile(join(dir, "session-secret"), "bad");
|
||||
expect(() => loadSessionSecret(dir)).toThrow("Invalid session-secret");
|
||||
});
|
||||
});
|
||||
describe("authentication boundary", () => {
|
||||
it("protects all API paths, including websocket handshakes, and permits health/login", async () => {
|
||||
const { app } = await setup();
|
||||
for (const url of ["/api", "/api/private", "/api/auth/me", "/api/auth/logout", "/api/unknown", "/api/health/", "/api/ws"]) {
|
||||
const response = await app.inject({ method: url.endsWith("logout") ? "POST" : "GET", url, headers: { connection: "Upgrade", upgrade: "websocket" } });
|
||||
expect(response.statusCode, url).toBe(401);
|
||||
}
|
||||
expect((await app.inject("/api/health?check=1")).statusCode).toBe(200);
|
||||
await expect(app.injectWS("/api/ws")).rejects.toThrow("401");
|
||||
expect((await app.inject({ method: "POST", url: "/api/auth/login", payload: { password: "wrong" } })).statusCode).toBe(401);
|
||||
const response = await login(app);
|
||||
expect(response.statusCode).toBe(204);
|
||||
expect(response.headers["set-cookie"]).toContain("HttpOnly; SameSite=Strict; Max-Age=2592000");
|
||||
const cookie = String(response.headers["set-cookie"]).split(";")[0]!;
|
||||
expect((await app.inject({ url: "/api/auth/me", headers: { cookie } })).json()).toEqual({ authenticated: true });
|
||||
const ws = await app.injectWS("/api/ws", { headers: { cookie } });
|
||||
ws.close();
|
||||
const logout = await app.inject({ method: "POST", url: "/api/auth/logout", headers: { cookie } });
|
||||
expect(logout.statusCode).toBe(204);
|
||||
expect(logout.headers["set-cookie"]).toContain("Max-Age=0");
|
||||
});
|
||||
it("survives app restart using the same data directory", async () => {
|
||||
const { app, dataDir } = await setup();
|
||||
const cookie = String((await login(app)).headers["set-cookie"]).split(";")[0]!;
|
||||
await app.close();
|
||||
apps.splice(apps.indexOf(app), 1);
|
||||
const second = await buildApp({ auth: { dataDir } }); apps.push(second);
|
||||
expect((await second.inject({ url: "/api/auth/me", headers: { cookie } })).statusCode).toBe(200);
|
||||
expect(await readFile(join(dataDir, "auth.json"), "utf8")).not.toContain("test password");
|
||||
});
|
||||
it("fails closed without configured password and rejects cross-origin requests", async () => {
|
||||
const app = await buildApp({ auth: { dataDir: await directory() } }); apps.push(app);
|
||||
expect((await login(app)).statusCode).toBe(401);
|
||||
expect((await login(app, { origin: "https://evil.test", host: "shellbook.test" })).statusCode).toBe(403);
|
||||
});
|
||||
it("only trusts HTTPS forwarding from configured proxies", async () => {
|
||||
const { app } = await setup();
|
||||
expect((await login(app, { "x-forwarded-proto": "https" })).headers["set-cookie"]).not.toContain("Secure");
|
||||
const { app: trusted } = await setup({ trustProxy: ["127.0.0.1"] });
|
||||
expect((await login(trusted, { "x-forwarded-proto": "https" })).headers["set-cookie"]).toContain("Secure");
|
||||
const { app: other } = await setup({ trustProxy: ["192.0.2.1"] });
|
||||
expect((await login(other, { "x-forwarded-proto": "https" })).headers["set-cookie"]).not.toContain("Secure");
|
||||
});
|
||||
it("limits parallel failures per IP and permits retry after the window", async () => {
|
||||
const { app } = await setup({ auth: { dataDir: await directory(), maxAttempts: 2, rateWindowMs: 100 } });
|
||||
const attempt = () => app.inject({ method: "POST", url: "/api/auth/login", payload: { password: "wrong" } });
|
||||
const results = await Promise.all([attempt(), attempt(), attempt()]);
|
||||
expect(results.map(r => r.statusCode).sort()).toEqual([401, 401, 429]);
|
||||
await new Promise(resolve => setTimeout(resolve, 120));
|
||||
expect((await login(app)).statusCode).toBe(204);
|
||||
});
|
||||
it("accepts identity headers only from configured direct peers, never X-Forwarded-For", async () => {
|
||||
const dir = await directory();
|
||||
const { app } = await setup({ auth: { dataDir: dir, forwardAuth: { header: "Remote-User", trustedProxyIps: ["127.0.0.1"] } } });
|
||||
expect((await app.inject({ url: "/api/auth/me", headers: { "remote-user": "admin" } })).statusCode).toBe(200);
|
||||
expect((await app.inject({ url: "/api/auth/me", headers: { "remote-user": " " } })).statusCode).toBe(401);
|
||||
const { app: untrusted } = await setup({ auth: { dataDir: await directory(), forwardAuth: { header: "Remote-User", trustedProxyIps: ["192.0.2.1"] } } });
|
||||
expect((await untrusted.inject({ url: "/api/auth/me", headers: { "remote-user": "admin", "x-forwarded-for": "192.0.2.1" } })).statusCode).toBe(401);
|
||||
const { app: disabled } = await setup();
|
||||
expect((await disabled.inject({ url: "/api/auth/me", headers: { "remote-user": "admin" } })).statusCode).toBe(401);
|
||||
});
|
||||
it("rejects expired sessions and honors configured lifetime", async () => {
|
||||
const { app, dataDir } = await setup({ auth: { dataDir: await directory(), sessionMaxAgeSeconds: 60 } });
|
||||
expect((await login(app)).headers["set-cookie"]).toContain("Max-Age=60");
|
||||
const cookie = `shellbook_session=${signSession(loadSessionSecret(dataDir), Date.now() - 1)}`;
|
||||
expect((await app.inject({ url: "/api/auth/me", headers: { cookie } })).statusCode).toBe(401);
|
||||
});
|
||||
it("serves static assets and SPA routes without swallowing API misses", async () => {
|
||||
const root = await directory();
|
||||
await writeFile(join(root, "index.html"), "<h1>ShellBook</h1>");
|
||||
await writeFile(join(root, "asset.js"), "/* asset */");
|
||||
const { app } = await setup({ staticDir: root });
|
||||
expect((await app.inject("/notebooks/example")).body).toBe("<h1>ShellBook</h1>");
|
||||
expect((await app.inject("/asset.js")).body).toBe("/* asset */");
|
||||
const cookie = String((await login(app)).headers["set-cookie"]).split(";")[0]!;
|
||||
expect((await app.inject({ url: "/api/missing", headers: { cookie } })).statusCode).toBe(404);
|
||||
});
|
||||
});
|
||||
@@ -3,7 +3,7 @@ import { buildApp } from "../src/app";
|
||||
|
||||
describe("health", () => {
|
||||
it("answers on /api/health", async () => {
|
||||
const app = await buildApp();
|
||||
const app = await buildApp({ auth: false });
|
||||
const res = await app.inject({ method: "GET", url: "/api/health" });
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.json()).toEqual({ ok: true });
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
import { mkdtemp, mkdir, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import type { FastifyInstance } from "fastify";
|
||||
import type { ServerEvent } from "@shellbook/core";
|
||||
import { buildApp } from "../src/app";
|
||||
import { EventsHub } from "../src/runs";
|
||||
import { setPassword } from "../src/auth/credentials";
|
||||
|
||||
const cleanup: Array<() => Promise<unknown>> = [];
|
||||
afterEach(async () => { for (const fn of cleanup.splice(0).reverse()) await fn(); });
|
||||
|
||||
async function workspace() {
|
||||
const root = await mkdtemp(join(tmpdir(), "shellbook-int-"));
|
||||
cleanup.push(() => rm(root, { recursive: true, force: true }));
|
||||
const workspaceDir = join(root, "workspace");
|
||||
const dataDir = join(root, "data");
|
||||
await mkdir(join(workspaceDir, "notebooks"), { recursive: true });
|
||||
await writeFile(join(workspaceDir, "hosts.yaml"), "[]\n");
|
||||
await writeFile(join(workspaceDir, "notebooks", "a.md"), "# A\n");
|
||||
return { workspaceDir, dataDir, sshKeyPath: join(dataDir, "id_ed25519") };
|
||||
}
|
||||
async function app(options: Parameters<typeof buildApp>[0]): Promise<FastifyInstance> {
|
||||
const instance = await buildApp(options);
|
||||
cleanup.push(() => instance.close());
|
||||
return instance;
|
||||
}
|
||||
|
||||
describe("app wiring", () => {
|
||||
it("publishes notebook watcher events into the /api/events hub", async () => {
|
||||
const config = await workspace();
|
||||
const hub = new EventsHub();
|
||||
const events: ServerEvent[] = [];
|
||||
hub.subscribe(event => events.push(event));
|
||||
await app({ config, events: hub, auth: false, watchNotebooks: true });
|
||||
await writeFile(join(config.workspaceDir, "notebooks", "a.md"), "# A changed\n");
|
||||
await vi.waitFor(() => expect(events).toContainEqual({ type: "file.changed", path: "a.md" }), { timeout: 5000 });
|
||||
});
|
||||
|
||||
it("guards every API route from the run, workspace and terminal plugins by default", async () => {
|
||||
const config = await workspace();
|
||||
await setPassword(config.dataDir, "pw");
|
||||
const instance = await app({ config, terminal: { ptyFactory: () => { throw new Error("no pty in this test"); } } });
|
||||
const routes: Array<[string, string]> = [
|
||||
["GET", "/api/notebooks"], ["GET", "/api/notebooks/a.md"], ["PUT", "/api/notebooks/a.md"],
|
||||
["GET", "/api/hosts"], ["POST", "/api/runs"], ["GET", "/api/events"],
|
||||
["GET", "/api/terminal?session=main"], ["GET", "/api/auth/me"],
|
||||
["GET", `/api/runs/${"0".repeat(8)}-0000-0000-0000-${"0".repeat(12)}/artifacts/x`],
|
||||
];
|
||||
for (const [method, url] of routes) {
|
||||
const res = await instance.inject({ method: method as "GET", url, payload: method === "GET" ? undefined : {} });
|
||||
expect(res.statusCode, `${method} ${url}`).toBe(401);
|
||||
}
|
||||
expect((await instance.inject("/api/health")).statusCode).toBe(200);
|
||||
const login = await instance.inject({ method: "POST", url: "/api/auth/login", payload: { password: "pw" } });
|
||||
expect(login.statusCode).toBe(204);
|
||||
const cookie = String(login.headers["set-cookie"]).split(";")[0]!;
|
||||
expect((await instance.inject({ url: "/api/notebooks", headers: { cookie } })).json().notebooks).toEqual([{ path: "a.md", title: "A" }]);
|
||||
});
|
||||
});
|
||||
@@ -105,7 +105,7 @@ async function sshFixture() {
|
||||
|
||||
describe("workspace", () => {
|
||||
it("reads nested notebooks, lists them, hashes versions, rejects stale concurrent saves", async () => {
|
||||
const app = await buildApp({ config: await fixture() }); cleanup.push(() => app.close());
|
||||
const app = await buildApp({ config: await fixture(), auth: false }); cleanup.push(() => app.close());
|
||||
const url = "/api/notebooks/nested%2Ftest.md";
|
||||
const res = await app.inject(url);
|
||||
expect(res.statusCode).toBe(200);
|
||||
@@ -117,7 +117,7 @@ describe("workspace", () => {
|
||||
expect((await app.inject(url)).json().version).not.toBe(payload.baseVersion);
|
||||
});
|
||||
it("validates inventory and applies defaults", async () => {
|
||||
const config = await fixture(); const app = await buildApp({ config }); cleanup.push(() => app.close());
|
||||
const config = await fixture(); const app = await buildApp({ config, auth: false }); cleanup.push(() => app.close());
|
||||
expect((await app.inject("/api/hosts")).json().hosts[0]).toEqual({ name: "test", address: "localhost", user: "admin", port: 22, tags: [] });
|
||||
await writeFile(path.join(config.workspaceDir, "hosts.yaml"), "- name: bad\n address: localhost\n");
|
||||
expect((await app.inject("/api/hosts")).statusCode).toBe(400);
|
||||
@@ -128,7 +128,7 @@ describe("workspace", () => {
|
||||
it("rejects symlink notebooks and non-md paths", async () => {
|
||||
const config = await fixture();
|
||||
await symlink(path.join(config.workspaceDir, "notebooks", "nested"), path.join(config.workspaceDir, "notebooks", "link"), "junction");
|
||||
const app = await buildApp({ config }); cleanup.push(() => app.close());
|
||||
const app = await buildApp({ config, auth: false }); cleanup.push(() => app.close());
|
||||
expect((await app.inject("/api/notebooks/link%2Ftest.md")).statusCode).toBe(400);
|
||||
expect((await app.inject("/api/notebooks/hosts.yaml")).statusCode).toBe(400);
|
||||
});
|
||||
@@ -194,7 +194,7 @@ describe("SSH with a deterministic in-process server", () => {
|
||||
const req = request(); req.acceptHostKey = fp;
|
||||
await executeRun({ config, hub, runId: first, request: req, step: step(), rendered: r, host, env: {} });
|
||||
expect(events.at(-1)).toMatchObject({ exitCode: 0, artifacts: ["out.txt"] });
|
||||
const app = await buildApp({ config }); cleanup.push(() => app.close());
|
||||
const app = await buildApp({ config, auth: false }); cleanup.push(() => app.close());
|
||||
const download = await app.inject(`/api/runs/${first}/artifacts/out.txt`);
|
||||
expect(download.statusCode).toBe(200); expect(download.body).toBe("artifact bytes");
|
||||
expect((await app.inject(`/api/runs/${first}/artifacts/undeclared.txt`)).statusCode).toBe(404);
|
||||
@@ -211,7 +211,7 @@ describe("pipeline helpers", () => {
|
||||
await writeFile(path.join(config.workspaceDir, "hosts.yaml"), JSON.stringify([host]));
|
||||
vi.mocked(parseNotebook).mockReturnValueOnce({ title: "Test", params: [], blocks: [{ type: "step", step: step() }], diagnostics: [] });
|
||||
const hub = new EventsHub();
|
||||
const app = await buildApp({ config, events: hub }); cleanup.push(() => app.close());
|
||||
const app = await buildApp({ config, events: hub, auth: false }); cleanup.push(() => app.close());
|
||||
await app.ready();
|
||||
const socket = await app.injectWS("/api/events"); cleanup.push(async () => socket.close());
|
||||
const events: ServerEvent[] = [];
|
||||
|
||||
@@ -36,7 +36,7 @@ describe("terminal validation", () => {
|
||||
|
||||
describe("terminal plugin", () => {
|
||||
it("is registered by buildApp and rejects invalid sessions", async () => {
|
||||
const app = await buildApp();
|
||||
const app = await buildApp({ auth: false });
|
||||
try {
|
||||
expect(app.hasRoute({ method: "GET", url: "/api/terminal" })).toBe(true);
|
||||
expect((await app.inject("/api/terminal?session=BAD")).statusCode).toBe(400);
|
||||
@@ -65,7 +65,7 @@ describe("terminal plugin", () => {
|
||||
// injectWS uses in-memory Duplexify streams whose close handshake does not
|
||||
// finish like a TCP socket. Terminate the server peer to model a lost tab.
|
||||
const peers = [...app.websocketServer.clients];
|
||||
peers[0].terminate();
|
||||
peers[0]!.terminate();
|
||||
await vi.waitFor(() => expect(first.pty.kill).toHaveBeenCalledTimes(1));
|
||||
expect(second.pty.kill).not.toHaveBeenCalled();
|
||||
expect(first.dataDispose).toHaveBeenCalledOnce();
|
||||
|
||||
Reference in New Issue
Block a user