SPB Git

Repository Public

api.test.ts 19.8 KB 226 lines typescript

1// Security tests against the real server: authn/authz bypass, IDOR, CSRF, enumeration, brute force, replay,2// session handling, headers, malformed input, idempotency, log hygiene.3import test, { after, before } from "node:test";4import assert from "node:assert/strict";5import fs from "node:fs";6import path from "node:path";7import * as P from "../../packages/protocol/src/index.ts";8import { ApiError } from "../../apps/web/src/core/engine.ts";9import { Authenticator, dataDir, device, newAccount, ORIGIN, pair, sql, startServer, stopServer } from "../harness.ts";1011const LOG = path.join(dataDir, "server.log");12before(() => startServer({ SPV_LOG_LEVEL: "info", SPV_RATE_SCALE: "50", SPV_TEST_LOG_FILE: LOG }));13after(() => stopServer());14const raw = (method: string, p: string, init: { body?: unknown; headers?: Record<string, string> } = {}) =>15  fetch(ORIGIN + p, { method, headers: { ...(init.body !== undefined ? { "content-type": "application/json" } : {}), ...init.headers }, body: init.body === undefined ? undefined : typeof init.body === "string" ? init.body : JSON.stringify(init.body) });16const U = () => P.uuid();17const login = (title: string, pw = "pw-" + title) => { const it = P.newItem("login", title); it.fields = { username: "u", password: pw }; return it; };1819test("security headers, cookie flags, no CORS", async () => {20  const r = await raw("GET", "/api/health/ready");21  assert.match(r.headers.get("content-security-policy")!, /default-src 'none'.*frame-ancestors 'none'.*require-trusted-types-for 'script'/);22  assert.equal(r.headers.get("x-frame-options"), "DENY");23  assert.equal(r.headers.get("x-content-type-options"), "nosniff");24  assert.match(r.headers.get("strict-transport-security")!, /max-age=63072000/);25  assert.equal(r.headers.get("referrer-policy"), "no-referrer");26  assert.equal(r.headers.get("cache-control"), "no-store");27  const pre = await raw("OPTIONS", "/api/v1/sync", { headers: { origin: "https://evil.example", "access-control-request-method": "POST" } });28  assert.equal(pre.headers.get("access-control-allow-origin"), null);29  const a = await newAccount("hdr");30  assert.match(a.api.cookie, /^spv=/);31  const res = await a.api.fetch("POST", "/api/v1/auth/login/options", {});32  assert.equal(res.headers.get("access-control-allow-origin"), null);33  const d = device(a.auth); const lr = await d.api.fetch("POST", "/api/v1/auth/login/options", {}); const lo = await lr.json();34  const vr = await d.api.fetch("POST", "/api/v1/auth/login/verify", { challengeId: lo.challengeId, response: await a.auth.get(lo.options) });35  const setCookie = vr.headers.getSetCookie()[0]!;36  assert.match(setCookie, /HttpOnly/i); assert.match(setCookie, /SameSite=Strict/i); assert.match(setCookie, /Path=\//);37});3839test("every protected route refuses unauthenticated callers", async () => {40  const v = U(), r = U();41  const routes: [string, string][] = [42    ["POST", "/api/v1/sync"], ["GET", "/api/v1/devices"], ["DELETE", `/api/v1/devices/${v}`], ["POST", "/api/v1/vaults"], ["DELETE", `/api/v1/vaults/${v}`],43    ["PUT", `/api/v1/vaults/${v}/records/${r}`], ["GET", `/api/v1/vaults/${v}/records/${r}/history`], ["POST", `/api/v1/vaults/${v}/members`], ["POST", `/api/v1/vaults/${v}/rotate`],44    ["POST", `/api/v1/vaults/${v}/attachments`], ["PUT", `/api/v1/attachments/${v}/chunks/0`], ["GET", `/api/v1/attachments/${v}/chunks/0`], ["POST", `/api/v1/attachments/${v}/complete`],45    ["POST", "/api/v1/shares"], ["GET", "/api/v1/shares"], ["POST", `/api/v1/shares/${v}/open`], ["DELETE", `/api/v1/shares/${v}`], ["GET", "/api/v1/audit"], ["POST", "/api/v1/audit/client"], ["GET", "/api/v1/events"],46    ["GET", "/api/v1/breach/range/ABCDE"], ["GET", "/api/v1/auth/session"], ["POST", "/api/v1/auth/stepup/options"], ["POST", "/api/v1/auth/stepup/verify"], ["GET", "/api/v1/auth/passkeys"],47    ["POST", "/api/v1/auth/passkeys/options"], ["DELETE", "/api/v1/auth/passkeys/x"], ["POST", "/api/v1/pairings"], ["GET", `/api/v1/pairings/${v}`], ["POST", `/api/v1/pairings/${v}/approve`],48    ["POST", `/api/v1/pairings/${v}/complete`], ["POST", "/api/v1/recovery/enroll"], ["GET", "/api/v1/recovery"], ["POST", "/api/v1/recovery/rotate"], ["POST", "/api/v1/account/rekey"],49    ["GET", "/api/v1/accounts/lookup?handle=hdr"], ["GET", "/api/v1/connect"], ["POST", "/api/v1/connect/identities"], ["POST", "/api/v1/connect/secrets"], ["POST", "/api/v1/connect/grants"],50    ["POST", `/api/v1/connect/approvals/${v}`], ["POST", "/api/v1/connect/kill"], ["GET", "/api/v1/agent/grants"], ["POST", "/api/v1/agent/use"],51  ];52  for (const [m, p] of routes) {53    const res = await raw(m, p, { headers: { "x-spv": "1" }, body: m === "GET" || m === "DELETE" ? undefined : {} });54    assert.ok(res.status === 401 || res.status === 400, `${m} ${p} → ${res.status}`);55    assert.notEqual(res.status, 200);56    if (res.status === 400) assert.ok(!/"rev"|envelope|arkEnvelope/.test(await res.text()));57  }58  assert.equal((await raw("GET", "/api/v1/does-not-exist")).status, 404);59});6061test("CSRF: cookie-authenticated writes need our origin and the custom header", async () => {62  const a = await newAccount("csrf");63  const cookie = a.api.cookie;64  assert.equal((await raw("POST", "/api/v1/sync", { headers: { cookie }, body: {} })).status, 403, "no custom header (plain cross-site form/fetch)");65  assert.equal((await raw("POST", "/api/v1/sync", { headers: { cookie, "x-spv": "1", origin: "https://evil.example" }, body: {} })).status, 403, "foreign origin");66  assert.equal((await raw("POST", "/api/v1/sync", { headers: { cookie, "x-spv": "1", origin: ORIGIN }, body: {} })).status, 200);67  // a form-encoded body is not accepted as JSON68  assert.equal((await fetch(ORIGIN + "/api/v1/auth/logout", { method: "POST", headers: { cookie, "content-type": "text/plain", "x-spv": "1" }, body: "{}" })).status, 415);69});7071test("cross-tenant isolation (IDOR): another account cannot read, write or learn anything", async () => {72  const a = await newAccount("victim"), b = await newAccount("attacker");73  const v = a.engine.vaults()[0]!.vaultId;74  const id = await a.engine.saveItem(v, null, login("victim-item"));75  const ref = await a.engine.upload(v, "f", "text/plain", P.utf8("attachment"));76  const env = (await sql`select envelope from records where id = ${id}`)[0]!.envelope;77  const is404 = (e: ApiError) => e.status === 404;78  await assert.rejects(b.api.request("PUT", `/api/v1/vaults/${v}/records/${id}`, { type: "item", baseRev: 1, envelope: env }), is404);79  await assert.rejects(b.api.request("PUT", `/api/v1/vaults/${v}/records/${U()}`, { type: "item", baseRev: 0, envelope: env }), is404);80  await assert.rejects(b.api.request("GET", `/api/v1/vaults/${v}/records/${id}/history`), is404);81  await assert.rejects(b.api.request("GET", `/api/v1/attachments/${ref.id}/chunks/0`), is404);82  await assert.rejects(b.api.request("POST", `/api/v1/vaults/${v}/attachments`, { id: U(), chunks: 1, size: 5 }), is404);83  await assert.rejects(b.engine.revokeDevice(a.engine.identity!.deviceId), is404);84  await assert.rejects(b.engine.deleteVault(v), is404);85  const g = (await sql`select * from vault_grants where vault_id = ${v}`)[0]!;86  // a forged self-invitation to someone else's vault87  await assert.rejects(b.api.request("POST", `/api/v1/vaults/${v}/members`, { grants: [{ vaultId: v, epoch: 1, memberAccountId: b.engine.identity!.accountId, role: "editor", envelope: g.envelope, granterAccountId: b.engine.identity!.accountId, sig: g.sig }] }), is404);88  await assert.rejects(b.api.request("POST", `/api/v1/vaults/${v}/rotate`, { epoch: 2, grants: [{ vaultId: v, epoch: 2, memberAccountId: b.engine.identity!.accountId, role: "owner", envelope: g.envelope, granterAccountId: b.engine.identity!.accountId, sig: g.sig }] }), is404);89  // sync with a cursor for a vault that is not ours returns nothing about it90  const s = await b.api.request("POST", "/api/v1/sync", { cursors: { [v]: 0 } });91  assert.ok(!JSON.stringify(s).includes(v));92  // unknown and foreign resources are indistinguishable93  await assert.rejects(b.api.request("GET", `/api/v1/vaults/${U()}/records/${U()}/history`), is404);94  const share = await a.engine.shareWithAccount(login("x"), await a.engine.lookupAccount("victim"), 600);95  await assert.rejects(b.api.request("POST", `/api/v1/shares/${share}/open`, {}), is404);96  await assert.rejects(b.api.request("DELETE", `/api/v1/shares/${share}`), is404);97  assert.equal((await b.engine.audit()).some((e) => JSON.stringify(e).includes(a.engine.identity!.accountId)), false);98});99100test("WebAuthn: wrong origin, replayed challenge and foreign passkeys are refused; sessions are not fixable", async () => {101  const a = await newAccount("wa");102  const d = device(a.auth);103  const o1 = await d.api.request("POST", "/api/v1/auth/login/options", {});104  const assertion = await a.auth.get(o1.options);105  await d.api.request("POST", "/api/v1/auth/login/verify", { challengeId: o1.challengeId, response: assertion });106  await assert.rejects(d.api.request("POST", "/api/v1/auth/login/verify", { challengeId: o1.challengeId, response: assertion }), (e: ApiError) => e.code === "challenge_expired");107  // the same signed assertion against a fresh challenge108  const o2 = await d.api.request("POST", "/api/v1/auth/login/options", {});109  await assert.rejects(d.api.request("POST", "/api/v1/auth/login/verify", { challengeId: o2.challengeId, response: assertion }), (e: ApiError) => e.status === 401);110  // phishing: the authenticator was used on another origin111  const phished = new Authenticator(); phished.creds = a.auth.creds; phished.origin = "https://vault-spboucher.example";112  const o3 = await d.api.request("POST", "/api/v1/auth/login/options", {});113  await assert.rejects(d.api.request("POST", "/api/v1/auth/login/verify", { challengeId: o3.challengeId, response: await phished.get(o3.options) }), (e: ApiError) => e.status === 401);114  // passkey + a device id of another account, or a forged device proof115  const other = await newAccount("wa2");116  const o4 = await d.api.request("POST", "/api/v1/auth/login/options", {});117  await assert.rejects(d.api.request("POST", "/api/v1/auth/login/verify", { challengeId: o4.challengeId, response: await a.auth.get(o4.options), device: { deviceId: other.engine.identity!.deviceId, proof: "A".repeat(86) } }), (e: ApiError) => e.code === "wrong_account");118  // picking another account's passkey on an enrolled device: refused, and the device is NOT erased119  const mixed = device(other.auth); mixed.engine.identity = a.engine.identity;120  await assert.rejects(mixed.engine.signIn(), (e: ApiError) => e.code === "wrong_account");121  assert.ok(mixed.engine.identity, "local data kept");122  const o5 = await d.api.request("POST", "/api/v1/auth/login/options", {});123  await assert.rejects(d.api.request("POST", "/api/v1/auth/login/verify", { challengeId: o5.challengeId, response: await a.auth.get(o5.options), device: { deviceId: a.engine.identity!.deviceId, proof: "A".repeat(86) } }), (e: ApiError) => e.status === 401);124  // session fixation: a cookie chosen by an attacker is never adopted125  const fixed = "spv=" + "F".repeat(43), v = device(a.auth); v.api.cookie = fixed;126  const o6 = await v.api.request("POST", "/api/v1/auth/login/options", {});127  await v.api.request("POST", "/api/v1/auth/login/verify", { challengeId: o6.challengeId, response: await a.auth.get(o6.options) });128  assert.notEqual(v.api.cookie, fixed);129  assert.equal((await raw("GET", "/api/v1/auth/session", { headers: { cookie: fixed } })).status, 401);130  // logout really ends the session131  const old = a.api.cookie; await a.engine.signOut();132  assert.equal((await raw("GET", "/api/v1/auth/session", { headers: { cookie: old } })).status, 401);133  // tokens are stored hashed134  assert.ok(!(await sql`select token_hash from sessions`).some((r) => v.api.cookie.includes(r.token_hash)));135});136137test("step-up: sensitive routes need a recent authentication, enforced by the server", async () => {138  const a = await newAccount("stepup"); const b = await pair(a);139  await sql`update sessions set strong_at = now() - interval '10 minutes'`;140  for (const [m, p, body] of [["DELETE", `/api/v1/devices/${b.engine.identity!.deviceId}`, undefined], ["GET", "/api/v1/recovery", undefined], ["POST", "/api/v1/audit/client", { kind: "export.plaintext" }],141    ["POST", "/api/v1/recovery/rotate", { epoch: 2, envelope: "A".repeat(80), authHash: "A".repeat(43) }], ["DELETE", `/api/v1/vaults/${a.engine.vaults()[0]!.vaultId}`, undefined]] as const)142    await assert.rejects(a.api.request(m, p, body), (e: ApiError) => e.status === 401 && e.code === "reauth_required", `${m} ${p}`);143  await a.engine.revokeDevice(b.engine.identity!.deviceId); // the engine performs the passkey step-up and retries144  assert.equal((await a.engine.devices()).length, 1);145});146147test("enumeration and brute force: decoys for unknown handles, rate limits on recovery", async () => {148  await newAccount("realuser");149  const anon = device();150  const known = await anon.api.request("POST", "/api/v1/recovery/start", { handle: "realuser" });151  const u1 = await anon.api.request("POST", "/api/v1/recovery/start", { handle: "ghost" }), u2 = await anon.api.request("POST", "/api/v1/recovery/start", { handle: "ghost" });152  assert.deepEqual(Object.keys(known), Object.keys(u1)); assert.equal(u1.accountId, u2.accountId); assert.ok(P.isUuid(u1.accountId));153  const bad1 = await anon.api.fetch("POST", "/api/v1/recovery/verify", { accountId: known.accountId, auth: P.b64u(P.random(32)) });154  const bad2 = await anon.api.fetch("POST", "/api/v1/recovery/verify", { accountId: u1.accountId, auth: P.b64u(P.random(32)) });155  assert.equal(bad1.status, 401); assert.deepEqual(await bad1.json(), await bad2.json(), "wrong key and unknown account look the same");156  let limited = 0;157  for (let i = 0; i < 520; i++) { const r = await anon.api.fetch("POST", "/api/v1/recovery/verify", { accountId: known.accountId, auth: P.b64u(P.random(32)) }); if (r.status === 429) { limited++; assert.ok(r.headers.get("retry-after")); } }158  assert.ok(limited >= 15, "recovery guesses are rate limited");159  // login options never depend on a handle160  const lo = await anon.api.request("POST", "/api/v1/auth/login/options", {});161  assert.equal(lo.options.allowCredentials?.length ?? 0, 0);162});163164test("malformed and hostile input never causes a 500 and never bypasses validation", async () => {165  const a = await newAccount("fuzz"); const v = a.engine.vaults()[0]!.vaultId;166  const id = await a.engine.saveItem(v, null, login("ok"));167  const env = (await sql`select envelope from records where id = ${id}`)[0]!.envelope;168  const bads: unknown[] = [169    { ...env, v: 2 }, { ...env, alg: 9 }, { ...env, salt: "AAAA" }, { ...env, nonce: env.nonce + "A" }, { ...env, ct: "!!!!" }, { ...env, ct: "A".repeat(100) }, { ...env, extra: 1 }, { ...env, kid: 0 }, { ...env, kid: "1" }, null, "x", [],170  ];171  for (const e of bads) await assert.rejects(a.api.request("PUT", `/api/v1/vaults/${v}/records/${U()}`, { type: "item", baseRev: 0, envelope: e }), (er: ApiError) => er.status === 400);172  await assert.rejects(a.api.request("PUT", `/api/v1/vaults/${v}/records/${id}`, { type: "collection", baseRev: 1, envelope: env }), (e: ApiError) => e.status === 400, "record type cannot change");173  await assert.rejects(a.api.request("PUT", `/api/v1/vaults/${v}/records/not-a-uuid`, { type: "item", baseRev: 0, envelope: env }), (e: ApiError) => e.status === 400);174  await assert.rejects(a.api.request("PUT", `/api/v1/vaults/${v}/records/${U()}`, { type: "item", baseRev: 0, envelope: { ...env, kid: 7 } }), (e: ApiError) => e.status === 409 && e.code === "stale_key");175  assert.equal((await raw("POST", "/api/v1/sync", { headers: { cookie: a.api.cookie, "x-spv": "1" }, body: "{not json" })).status, 400);176  assert.equal((await raw("POST", "/api/v1/sync", { headers: { cookie: a.api.cookie, "x-spv": "1" }, body: JSON.stringify({ cursors: { [v]: -1 } }) })).status, 400);177  assert.equal((await raw("POST", "/api/v1/sync", { headers: { cookie: a.api.cookie, "x-spv": "1" }, body: "x".repeat(3 * 1024 * 1024) })).status, 413);178  // random structured garbage on every JSON route179  const routes = ["/api/v1/auth/register/options", "/api/v1/auth/register/verify", "/api/v1/auth/login/verify", "/api/v1/vaults", "/api/v1/shares", "/api/v1/pairings", "/api/v1/recovery/start", "/api/v1/recovery/verify",180    "/api/v1/account/rekey", `/api/v1/vaults/${v}/members`, `/api/v1/vaults/${v}/rotate`, `/api/v1/vaults/${v}/attachments`, "/api/v1/connect/secrets", "/api/v1/connect/grants", "/api/v1/auth/stepup/verify"];181  const junk = [{}, { a: 1 }, [], "s", 1, null, { challengeId: U(), response: { id: "x", response: {} } }, { __proto__: { admin: true } }, { handle: "a".repeat(5000) }, { vaultId: U(), grant: {}, meta: {} }, { cursors: "x" }];182  for (const p of routes) for (const j of junk) {183    const r = await raw("POST", p, { headers: { cookie: a.api.cookie, "x-spv": "1" }, body: JSON.stringify(j) });184    assert.ok(r.status >= 400 && r.status < 500, `${p} with ${JSON.stringify(j).slice(0, 30)} → ${r.status}`);185  }186});187188test("idempotency and optimistic concurrency: retries do not duplicate, stale writes do not overwrite", async () => {189  const a = await newAccount("idem"); const v = a.engine.vaults()[0]!.vaultId;190  const id = await a.engine.saveItem(v, null, login("one"));191  const env = (await sql`select envelope from records where id = ${id}`)[0]!.envelope, rid = U(), key = P.b64u(P.random(18));192  const put = () => a.api.fetch("PUT", `/api/v1/vaults/${v}/records/${rid}`, { type: "item", baseRev: 0, envelope: env }, { headers: { "idempotency-key": key } });193  const r1 = await (await put()).json(), r2 = await (await put()).json();194  assert.deepEqual(r1, r2); assert.equal(r1.rev, 1);195  assert.equal((await sql`select rev from records where id = ${rid}`)[0]!.rev, 1);196  const stale = await a.api.fetch("PUT", `/api/v1/vaults/${v}/records/${rid}`, { type: "item", baseRev: 0, envelope: env });197  assert.equal(stale.status, 409); assert.equal((await stale.json()).current.rev, 1);198  // concurrent writers on the same base revision: exactly one wins199  const res = await Promise.all(Array.from({ length: 8 }, () => a.api.fetch("PUT", `/api/v1/vaults/${v}/records/${rid}`, { type: "item", baseRev: 1, envelope: env })));200  assert.equal(res.filter((r) => r.status === 200).length, 1); assert.equal(res.filter((r) => r.status === 409).length, 7);201  const seqs = (await sql`select seq from records where vault_id = ${v} order by seq`).map((r) => Number(r.seq));202  assert.equal(new Set(seqs).size, seqs.length, "sequence numbers are unique per vault");203});204205test("public share links cannot be guessed or over-read", async () => {206  const a = await newAccount("links");207  const url = await a.engine.shareByLink(login("door"), ORIGIN, 600, 2);208  const [, id, secret] = /#\/s\/([0-9a-f-]+)\/([A-Za-z0-9_-]+)$/.exec(url)!;209  assert.ok(!(await sql`select * from shares where id = ${id!}`).some((r) => JSON.stringify(r).includes(secret!)), "the fragment secret never reaches the server");210  const anon = device();211  let nf = 0; for (let i = 0; i < 5; i++) { const r = await anon.api.fetch("POST", `/api/v1/public/shares/${id}`, { auth: P.b64u(P.random(32)) }); if (r.status === 404) nf++; }212  assert.equal(nf, 5);213  assert.equal((await sql`select views from shares where id = ${id!}`)[0]!.views, 0, "failed guesses do not consume views");214});215216test("server logs contain no secrets, tokens, ciphertext or identifiers of items", async () => {217  const a = await newAccount("logs"); const v = a.engine.vaults()[0]!.vaultId;218  const id = await a.engine.saveItem(v, null, login("LOGCANARY-title", "LOGCANARY-password"));219  await a.api.fetch("GET", `/api/v1/vaults/${v}/records/${id}/history?secret=LOGCANARY-query`);220  await new Promise((r) => setTimeout(r, 300));221  const log = fs.readFileSync(LOG, "utf8");222  assert.ok(log.length > 1000 && /"route":"\/api\/v1\/vaults\/:vid\/records\/:rid"/.test(log), "requests are logged by route template");223  const env = (await sql`select envelope from records where id = ${id}`)[0]!.envelope;224  for (const needle of ["LOGCANARY", a.api.cookie.split("=")[1]!, env.ct.slice(0, 40), id, v, a.recoveryKey, "authorization", "cookie"]) assert.ok(!log.includes(needle), `log contains ${needle.slice(0, 20)}`);225});226
Files main
Menu

Theme