SPB Git

Repository Public

studio-auth.test.ts 16.1 KB 237 lines typescript

1import { DatabaseSync } from "node:sqlite";2import { afterAll, beforeEach, describe, expect, it } from "vitest";3import { listAudit } from "@/server/audit";4import {5  IDLE_MINUTES, SESSION_HOURS, authenticationOptions, bindingOf, can, createEditor, credentialCount, enrollTokenInfo, issueEnrollToken, issueSession, listEditors, listSessions,6  registrationOptions, revokePasskey, revokeSession, revokeSessions, sessionFromToken, updateEditor, verifyAuthentication, verifyRegistration,7} from "@/server/auth";8import { sha256 } from "@/server/crypto";9import { MIGRATIONS, all, closeDb, db, dbPath, get, migrate, run } from "@/server/db";10import { ApiError, assertSameOrigin, rateLimit, resetRateLimits } from "@/server/http";11import { REDACTED, log, redact, setLogSink } from "@/server/log";12import { cleanup, freshDataDir } from "./studio-helpers";1314const code = async (fn: () => unknown) => { try { await fn(); return "ok"; } catch (e) { return e instanceof ApiError ? e.code : `other:${String(e)}`; } };15beforeEach(async () => { await freshDataDir(); });16afterAll(cleanup);1718describe("migrations", () => {19  it("build the whole schema from an empty database, and change nothing when run again", () => {20    const d = new DatabaseSync(":memory:");21    expect(migrate(d)).toEqual(MIGRATIONS.map((m) => m.name));22    const tables = () => (d.prepare("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name").all() as { name: string }[]).map((t) => t.name);23    const first = tables();24    for (const t of ["audit", "auth_sessions", "blobs", "capsules", "challenges", "course", "course_sessions", "credentials", "editors", "enroll_tokens", "imports", "jobs", "masters", "meta", "publications", "resource_versions", "resources", "schema_migrations", "sections", "upload_chunks", "uploads"]) expect(first, t).toContain(t);25    expect(migrate(d)).toEqual([]); // idempotent26    expect(tables()).toEqual(first);27    expect((d.prepare("SELECT count(*) AS n FROM schema_migrations").get() as { n: number }).n).toBe(MIGRATIONS.length);28    d.close();29  });3031  it("apply only what is missing (forward-only), each in its own transaction", () => {32    const d = new DatabaseSync(":memory:");33    expect(migrate(d, MIGRATIONS.slice(0, 1))).toEqual([MIGRATIONS[0]!.name]);34    d.prepare("INSERT INTO meta (key, value) VALUES ('témoin', 'conservé')").run();35    expect(migrate(d)).toEqual(MIGRATIONS.slice(1).map((m) => m.name));36    expect((d.prepare("SELECT value FROM meta WHERE key = 'témoin'").get() as { value: string }).value).toBe("conservé"); // data survives an upgrade37    // A failing migration leaves no trace: nothing half-applied, nothing recorded.38    const broken = [...MIGRATIONS, { name: "999_broken", sql: "CREATE TABLE half (id INTEGER); CREATE TABLE syntax error here;" }];39    expect(() => migrate(d, broken)).toThrow();40    expect(d.prepare("SELECT name FROM sqlite_master WHERE name = 'half'").get()).toBeUndefined();41    expect((d.prepare("SELECT count(*) AS n FROM schema_migrations").get() as { n: number }).n).toBe(MIGRATIONS.length);42    d.close();43  });4445  it("refuse a database that does not match the code", () => {46    const d = new DatabaseSync(":memory:");47    migrate(d);48    expect(() => migrate(d, MIGRATIONS.slice(0, 2))).toThrow(/plus récente que le code/);49    expect(() => migrate(d, [{ ...MIGRATIONS[0]!, name: "001_autre" }, ...MIGRATIONS.slice(1)])).toThrow(/incompatible/);50    d.close();51  });5253  it("opens the file database in WAL mode with foreign keys on", () => {54    expect((db().prepare("PRAGMA journal_mode").get() as { journal_mode: string }).journal_mode).toBe("wal");55    expect((db().prepare("PRAGMA foreign_keys").get() as { foreign_keys: number }).foreign_keys).toBe(1);56    expect(dbPath().endsWith("atlas.db")).toBe(true);57  });58});5960describe("editors and roles", () => {61  it("grants least privilege: author < publisher < owner", () => {62    expect([can("author", "edit"), can("author", "publish"), can("author", "admin")]).toEqual([true, false, false]);63    expect([can("publisher", "edit"), can("publisher", "publish"), can("publisher", "admin")]).toEqual([true, true, false]);64    expect([can("owner", "edit"), can("owner", "publish"), can("owner", "admin")]).toEqual([true, true, true]);65  });6667  it("refuses bad names and roles, and audits creation", async () => {68    expect(await code(() => createEditor(" ", "owner", "cli"))).toBe("bad_name");69    expect(await code(() => createEditor("Quelqu'un", "root" as never, "cli"))).toBe("bad_role");70    const e = createEditor("  Simon-Pierre   Boucher ", "owner", "cli");71    expect(e.name).toBe("Simon-Pierre Boucher");72    expect(listAudit({ action: "editor.created" })[0]).toMatchObject({ actor: "cli", target: `editor:${e.id}` });73  });74});7576describe("enrolment tokens", () => {77  it("are stored hashed, single-use by design, short-lived, one live token per editor", () => {78    const e = createEditor("Propriétaire", "owner", "cli");79    const first = issueEnrollToken(e.id, "setup", "cli");80    expect(JSON.stringify(all("SELECT * FROM enroll_tokens"))).not.toContain(first.raw); // only the SHA-256 is kept81    expect(get<{ token_hash: string }>("SELECT token_hash FROM enroll_tokens")!.token_hash).toBe(sha256(first.raw));82    expect(enrollTokenInfo(first.raw)).toMatchObject({ purpose: "setup", name: "Propriétaire", role: "owner" });83    const second = issueEnrollToken(e.id, "recovery", "cli");84    expect(enrollTokenInfo(first.raw)).toBeNull(); // issuing a new one kills the previous85    expect(enrollTokenInfo(second.raw)).toMatchObject({ purpose: "recovery" });86    run("UPDATE enroll_tokens SET expires_at = ? WHERE used_at IS NULL", new Date(Date.now() - 1000).toISOString());87    expect(enrollTokenInfo(second.raw)).toBeNull(); // expired88    for (const junk of [undefined, "", "court", 42, "x".repeat(500)]) expect(enrollTokenInfo(junk)).toBeNull();89    // The audit trail records that a link was issued, never the link.90    expect(JSON.stringify(listAudit())).not.toContain(first.raw);91    expect(JSON.stringify(listAudit())).not.toContain(second.raw);92  });9394  it("caps the lifetime and refuses unknown or disabled editors", async () => {95    const e = createEditor("Propriétaire", "owner", "cli");96    const t = issueEnrollToken(e.id, "setup", "cli", 99_999);97    expect(Date.parse(t.expiresAt) - Date.now()).toBeLessThanOrEqual(1440 * 60_000 + 1000);98    expect(await code(() => issueEnrollToken("ed_inconnu", "setup", "cli"))).toBe("not_found");99    const other = createEditor("Autre", "author", "cli");100    updateEditor(other.id, { disabled: true }, "cli");101    expect(await code(() => issueEnrollToken(other.id, "setup", "cli"))).toBe("not_found");102  });103104  it("opens no registration ceremony without a valid token, and binds the ceremony to the browser that asked", async () => {105    const e = createEditor("Propriétaire", "owner", "cli"), { raw } = issueEnrollToken(e.id, "setup", "cli");106    expect(await code(() => registrationOptions("faux-jeton-0123456789abcdef", bindingOf("a")))).toBe("invalid_enroll_token");107    const { challengeId, options } = await registrationOptions(raw, bindingOf("navigateur-A"));108    expect(options.rp.id).toBe("atlas.spboucher.ai");109    expect(options.authenticatorSelection).toMatchObject({ residentKey: "required", userVerification: "required" });110    // Another browser cannot finish it; and the attempt burnt the challenge for everyone.111    expect(await code(() => verifyRegistration({ challengeId, token: raw, response: {} }, bindingOf("navigateur-B"), "ip"))).toBe("challenge_expired");112    expect(await code(() => verifyRegistration({ challengeId, token: raw, response: {} }, bindingOf("navigateur-A"), "ip"))).toBe("challenge_expired");113    const again = await registrationOptions(raw, bindingOf("navigateur-A"));114    expect(await code(() => verifyRegistration({ challengeId: again.challengeId, token: raw, response: { id: "x" } }, bindingOf("navigateur-A"), "ip"))).toBe("registration_failed");115    expect(credentialCount()).toBe(0);116    expect(enrollTokenInfo(raw)).not.toBeNull(); // a failed ceremony does not burn the link117  });118});119120describe("sessions", () => {121  const owner = () => createEditor("Propriétaire", "owner", "cli");122123  it("live on the server: the cookie carries a random token, the database only its hash", () => {124    const e = owner(), { token, expires } = issueSession(e.id, { ip: "198.51.100.7", ua: "essai" });125    expect(token.length).toBeGreaterThanOrEqual(40);126    expect(JSON.stringify(all("SELECT * FROM auth_sessions"))).not.toContain(token);127    const s = sessionFromToken(token)!;128    expect(s.editor.id).toBe(e.id);129    expect(s.csrf.length).toBeGreaterThanOrEqual(30);130    expect(s.csrf).not.toBe(token);131    expect(Math.round((expires.getTime() - Date.now()) / 3_600_000)).toBe(SESSION_HOURS);132    for (const junk of [undefined, null, "", "pas-un-jeton", token.slice(0, -1), `${token}x`]) expect(sessionFromToken(junk)).toBeNull();133  });134135  it("expire absolutely and when idle, and are deleted as they are met", () => {136    const e = owner(), a = issueSession(e.id), b = issueSession(e.id);137    expect(sessionFromToken(a.token, Date.now() + (IDLE_MINUTES + 1) * 60_000)).toBeNull(); // idle138    expect(sessionFromToken(a.token)).toBeNull(); // …and gone for good139    run("UPDATE auth_sessions SET expires_at = ?", new Date(Date.now() - 1).toISOString());140    expect(sessionFromToken(b.token)).toBeNull();141    expect(listSessions()).toEqual([]);142  });143144  it("rotate at sign-in (no fixation) and die at sign-out, on revocation, and when the editor is disabled", () => {145    const e = owner(), other = createEditor("Auteur", "author", "cli");146    const first = issueSession(e.id), second = issueSession(e.id, { previous: first.token });147    expect(sessionFromToken(first.token)).toBeNull();148    expect(sessionFromToken(second.token)).not.toBeNull();149    revokeSession(second.token);150    expect(sessionFromToken(second.token)).toBeNull();151    const x = issueSession(other.id), y = issueSession(other.id);152    expect(listSessions().map((s) => s.id.length)).toEqual([16, 16]); // listed by a prefix of the hash, never by the token153    expect(revokeSessions({ id: sha256(x.token).slice(0, 16) }, e.id)).toBe(1);154    expect(sessionFromToken(x.token)).toBeNull();155    updateEditor(other.id, { disabled: true }, e.id);156    expect(sessionFromToken(y.token)).toBeNull(); // signed out everywhere, at once157    expect(listAudit({ action: "editor.disabled" })).toHaveLength(1);158  });159160  it("protect the last owner able to sign in", async () => {161    const e = owner();162    run("INSERT INTO credentials (id, editor_id, public_key, counter, transports, name, created_at) VALUES ('cred-1', ?, x'00', 0, '[]', 'Mac', ?)", e.id, new Date().toISOString());163    expect(await code(() => updateEditor(e.id, { role: "author" }, e.id))).toBe("last_owner");164    expect(await code(() => updateEditor(e.id, { disabled: true }, e.id))).toBe("last_owner");165    expect(await code(() => revokePasskey("cred-1", e.id))).toBe("last_owner");166    const second = createEditor("Second propriétaire", "owner", e.id);167    run("INSERT INTO credentials (id, editor_id, public_key, counter, transports, name, created_at) VALUES ('cred-2', ?, x'00', 0, '[]', 'iPhone', ?)", second.id, new Date().toISOString());168    const s = issueSession(e.id);169    revokePasskey("cred-1", second.id); // now allowed: another owner can still sign in170    expect(sessionFromToken(s.token)).toBeNull(); // sessions opened with the revoked key's owner are closed171    expect(listEditors().find((x) => x.id === e.id)!.passkeys).toBe(0);172  });173});174175describe("sign-in ceremony", () => {176  it("consumes its challenge at the first answer (no replay) and locks out an address that keeps failing", async () => {177    const bogus = (challengeId: string) => ({ challengeId, response: { id: "inconnu", rawId: "inconnu", type: "public-key", response: {} } });178    const binding = bindingOf("navigateur"), first = await authenticationOptions(binding);179    expect(await code(() => verifyAuthentication(bogus(first.challengeId), binding, "203.0.113.5"))).toBe("login_failed");180    expect(await code(() => verifyAuthentication(bogus(first.challengeId), binding, "203.0.113.5"))).toBe("challenge_expired"); // replay181    const stolen = await authenticationOptions(binding);182    expect(await code(() => verifyAuthentication(bogus(stolen.challengeId), bindingOf("autre"), "203.0.113.5"))).toBe("challenge_expired"); // another browser183    expect(await code(() => verifyAuthentication(bogus(stolen.challengeId), null, "203.0.113.5"))).toBe("challenge_expired");184    for (let i = 0; i < 4; i++) { const o = await authenticationOptions(binding); expect(await code(() => verifyAuthentication(bogus(o.challengeId), binding, "203.0.113.5"))).toBe("login_failed"); }185    const o = await authenticationOptions(binding);186    expect(await code(() => verifyAuthentication(bogus(o.challengeId), binding, "203.0.113.5"))).toBe("locked_out"); // five failures in the hour187    const elsewhere = await authenticationOptions(binding);188    expect(await code(() => verifyAuthentication(bogus(elsewhere.challengeId), binding, "198.51.100.1"))).toBe("login_failed"); // other addresses are not punished189    expect(listAudit({ action: "auth.login.failed" }).length).toBe(6);190    closeDb(); // the lock-out comes from the audit trail: it survives a restart191    const after = await authenticationOptions(binding);192    expect(await code(() => verifyAuthentication(bogus(after.challengeId), binding, "203.0.113.5"))).toBe("locked_out");193  });194});195196describe("request guards", () => {197  const req = (headers: Record<string, string>) => new Request("https://atlas.spboucher.ai/admin/api/x", { method: "POST", headers });198  it("accept only the studio's own origin for state-changing requests", () => {199    expect(() => assertSameOrigin(req({ origin: "https://atlas.spboucher.ai", "sec-fetch-site": "same-origin" }))).not.toThrow();200    for (const h of [{ origin: "https://evil.example" } as Record<string, string>, { origin: "http://atlas.spboucher.ai" }, { origin: "https://atlas.spboucher.ai.evil.example" }, { origin: "null" }, { "sec-fetch-site": "cross-site" }, { "sec-fetch-site": "same-site" }]) expect(() => assertSameOrigin(req(h)), JSON.stringify(h)).toThrow(ApiError);201    process.env.ATLAS_STUDIO_ORIGIN = "http://localhost:8840";202    expect(() => assertSameOrigin(req({ origin: "http://localhost:8840" }))).not.toThrow();203    expect(() => assertSameOrigin(req({ origin: "https://atlas.spboucher.ai" }))).toThrow();204    delete process.env.ATLAS_STUDIO_ORIGIN;205  });206207  it("limit the rate per key and say when to come back", () => {208    resetRateLimits();209    for (let i = 0; i < 5; i++) rateLimit("essai", "a", 5, 60);210    let err: ApiError | null = null;211    try { rateLimit("essai", "a", 5, 60); } catch (e) { err = e as ApiError; }212    expect(err).toMatchObject({ status: 429, code: "rate_limited" });213    expect(err!.extra!.retryAfterSeconds).toBeGreaterThan(0);214    expect(() => rateLimit("essai", "b", 5, 60)).not.toThrow(); // another key has its own budget215  });216});217218describe("structured logs", () => {219  it("redact credentials by field name and by shape, whatever the call site passes", () => {220    const lines: string[] = [];221    setLogSink((l) => lines.push(l));222    process.env.ATLAS_LOG_LEVEL = "info";223    log("info", "essai", {224      token: "abc123", csrf: "def456", cookie: "atlas_studio=SECRETCOOKIE", authorization: "Bearer SECRETBEARER", nested: { sessionToken: "x", challenge: "y", ok: "visible" },225      url: "/admin/enrolement?jeton=JETONSECRET123&autre=1", header: "Cookie: atlas_studio=SECRETCOOKIE2; theme=dark", message: "Authorization: Bearer SECRETBEARER2 refused",226      error: new Error("failed for /x?token=SECRETINERROR"), list: ["Bearer SECRETINLIST00"], count: 3,227    });228    setLogSink(null); process.env.ATLAS_LOG_LEVEL = "silent";229    const line = lines[0]!, parsed = JSON.parse(line) as Record<string, unknown>;230    for (const secret of ["abc123", "def456", "SECRETCOOKIE", "SECRETBEARER", "JETONSECRET123", "SECRETCOOKIE2", "SECRETBEARER2", "SECRETINERROR", "SECRETINLIST00"]) expect(line, secret).not.toContain(secret);231    expect(parsed).toMatchObject({ level: "info", msg: "essai", token: REDACTED, count: 3, nested: { ok: "visible", sessionToken: REDACTED } });232    expect(parsed.url).toBe(`/admin/enrolement?jeton=${REDACTED}&autre=1`);233    expect(typeof parsed.ts).toBe("string");234    expect(redact("rien de secret ici")).toBe("rien de secret ici");235  });236});237
Files main
Menu

Theme