Diffinery

homeflare/diffinerypublic

Open-source, agent-first GitHub and GitHub Actions alternative that runs on your own Cloudflare account: git hosting, pull requests, code review and drop-in GitHub Actions YAML on Workers, Durable Objects, R2 and Containers.

diffinery/apps/diffinery/test/unit/security-reports.test.ts
114 lines · 7.9 KBRaw History
1import { describe, expect, it } from "vitest";
2import type { Env } from "../../src/env.js";
3import type { Account } from "../../src/lib/directory.js";
4import { HttpError } from "../../src/lib/util.js";
5import { ANONYMOUS_REPORTS_PER_DAY, MAX_DETAILS, MAX_SUMMARY, REPORTS_PER_ACCOUNT_PER_DAY, REPORTS_PER_IP_PER_DAY, SecurityReports, changeReport, reportJson, submitReport, validateReport } from "../../src/lib/security-reports.js";
6import type { MailJob } from "../../src/mail/types.js";
7import { testD1 } from "./stubs/d1.js";
8
9const at = "2026-10-01T00:00:00.000Z";
10const PUB = "https://diffinery.example";
11
12/** A D1 with two site administrators (one disabled), one person, and a mail queue that records what it gets. */
13function setup() {
14 const DB = testD1();
15 const add = DB.sqlite.prepare("INSERT INTO accounts (id, login, kind, email, status, site_admin, created_at) VALUES (?, ?, 'user', ?, ?, ?, ?)");
16 add.run("u-root", "root", "[email protected]", "active", 1, at);
17 add.run("u-old", "old", "[email protected]", "disabled", 1, at);
18 add.run("u-ann", "ann", "[email protected]", "active", 0, at);
19 const queued: MailJob[] = [];
20 const MAIL = { sendBatch: async (b: Array<{ body: MailJob }>) => void queued.push(...b.map((m) => m.body)) };
21 const env = { DB, MAIL, PUBLIC_URL: PUB } as unknown as Env;
22 const audits: Array<{ action: string; target?: string; actorLogin?: string; detail?: unknown }> = [];
23 const audit = async (e: (typeof audits)[number]) => void audits.push(e);
24 const ann = DB.sqlite.prepare("SELECT * FROM accounts WHERE id = 'u-ann'").get() as unknown as Account;
25 const root = DB.sqlite.prepare("SELECT * FROM accounts WHERE id = 'u-root'").get() as unknown as Account;
26 return { env, DB, queued, audits, audit, ann, root };
27}
28
29const refused = (f: () => unknown, status: number, msg: RegExp) => {
30 try {
31 f();
32 } catch (e) {
33 expect(e).toBeInstanceOf(HttpError);
34 expect((e as HttpError).status).toBe(status);
35 expect((e as HttpError).detail).toMatch(msg);
36 return;
37 }
38 throw new Error("expected it to be refused");
39};
40
41describe("report validation", () => {
42 const good = { summary: " Stored XSS\n in release notes ", details: "\n\nSteps:\r\n1. Create a release\r\n2. Open it\n\n ", area: " /acme/app/releases ", replyTo: " [email protected] " };
43
44 it("keeps a one-line summary, the details' lines, the area and a lower-cased reply-to", () => {
45 expect(validateReport(good, false)).toEqual({ summary: "Stored XSS in release notes", details: "Steps:\n1. Create a release\n2. Open it", area: "/acme/app/releases", replyTo: "[email protected]" });
46 expect(validateReport({ ...good, area: " ", replyTo: "" }, true)).toMatchObject({ area: null, replyTo: null });
47 });
48
49 it("needs a summary and details, refuses too much rather than cutting it, and checks the address", () => {
50 refused(() => validateReport({ ...good, summary: " \n " }, true), 422, /summary/);
51 refused(() => validateReport({ ...good, details: "\n \n" }, true), 422, /Describe the problem/);
52 refused(() => validateReport({ ...good, summary: "x".repeat(MAX_SUMMARY + 1) }, true), 422, /200 characters/);
53 expect(validateReport({ ...good, summary: "x".repeat(MAX_SUMMARY) }, true).summary).toHaveLength(MAX_SUMMARY);
54 refused(() => validateReport({ ...good, details: "x".repeat(MAX_DETAILS + 1) }, true), 422, /20,000 characters/);
55 expect(validateReport({ ...good, details: "x".repeat(MAX_DETAILS) }, true).details).toHaveLength(MAX_DETAILS);
56 refused(() => validateReport({ ...good, area: "x".repeat(501) }, true), 422, /500 characters/);
57 refused(() => validateReport({ ...good, replyTo: "not an address" }, true), 422, /valid email address/);
58 refused(() => validateReport({ ...good, summary: 42, details: ["x"] }, true), 422, /summary/);
59 });
60
61 it("asks for a reply-to address only from someone who isn't signed in", () => {
62 refused(() => validateReport({ ...good, replyTo: "" }, false), 422, /reply to, or sign in/);
63 expect(validateReport({ ...good, replyTo: "" }, true).replyTo).toBeNull();
64 });
65});
66
67describe("sending and triaging reports", () => {
68 const input = validateReport({ summary: "Token leak in logs", details: "Tokens show up in job logs.", area: "", replyTo: "" }, true);
69
70 it("stores a report, audits it without its content and emails each active site administrator only the summary", async () => {
71 const { env, queued, audits, audit, ann } = setup();
72 const r = await submitReport(env, audit, input, ann, "203.0.113.9");
73 expect(r).toMatchObject({ summary: "Token leak in logs", reply_to: "[email protected]", account_id: "u-ann", reporter_login: "ann", state: "new" });
74 expect(r.ip_hash).toMatch(/^[0-9a-f]{64}$/);
75 expect(await new SecurityReports(env.DB).get(r.id)).toMatchObject({ id: r.id, details: "Tokens show up in job logs." });
76 expect(audits).toEqual([{ actorId: "u-ann", actorLogin: "ann", action: "security_report.create", target: r.id, detail: { signed_in: true } }]);
77 expect(queued).toEqual([{ kind: "security_report", data: { id: r.id, summary: "Token leak in logs" }, to: { accountId: "u-root" }, reason: "admin", at: r.created_at }]);
78 expect(JSON.stringify(queued)).not.toContain("job logs");
79 expect(reportJson(env, r).html_url).toBe(`${PUB}/settings/admin/security-reports/${r.id}`);
80 });
81
82 it("limits reports per day: per IP address for anyone not signed in, per account, and for everyone not signed in together", async () => {
83 const { env, audit, ann } = setup();
84 const anon = { ...input, replyTo: "[email protected]" };
85 for (let i = 0; i < REPORTS_PER_IP_PER_DAY; i++) await submitReport(env, audit, anon, null, "203.0.113.9");
86 await expect(submitReport(env, audit, anon, null, "203.0.113.9")).rejects.toMatchObject({ status: 429 });
87 // Another network, or signed in from the same one, still works.
88 await submitReport(env, audit, anon, null, "198.51.100.7");
89 for (let i = 0; i < REPORTS_PER_ACCOUNT_PER_DAY; i++) await submitReport(env, audit, input, ann, "203.0.113.9");
90 await expect(submitReport(env, audit, input, ann, "198.51.100.8")).rejects.toMatchObject({ status: 429 });
91 // Everyone not signed in, together.
92 const fill = env.DB.sqlite.prepare("INSERT INTO security_reports (id, summary, details, ip_hash, created_at) VALUES (lower(hex(randomblob(16))), 's', 'd', ?, ?)");
93 for (let i = 0; i < ANONYMOUS_REPORTS_PER_DAY; i++) fill.run(`h${i}`, new Date().toISOString());
94 await expect(submitReport(env, audit, anon, null, "192.0.2.1")).rejects.toMatchObject({ status: 429 });
95 });
96
97 it("marks a report triaged or resolved with a note, audited; refuses junk", async () => {
98 const { env, audits, audit, ann, root } = setup();
99 const r = await submitReport(env, audit, input, ann, null);
100 audits.length = 0;
101 const t = await changeReport(env.DB, audit, root, r.id, "triaged", " Reproduced.\r\nFix next week. ", "web");
102 expect(t).toMatchObject({ state: "triaged", note: "Reproduced.\nFix next week.", updated_by: "root" });
103 const done = await changeReport(env.DB, audit, root, r.id, "resolved", undefined, "api");
104 expect(done).toMatchObject({ state: "resolved", note: null });
105 expect(audits).toEqual([
106 { actorId: "u-root", actorLogin: "root", action: "security_report.triage", target: r.id, detail: { from: "new", to: "triaged", note: "Reproduced.\nFix next week.", via: "web" } },
107 { actorId: "u-root", actorLogin: "root", action: "security_report.resolve", target: r.id, detail: { from: "triaged", to: "resolved", note: null, via: "api" } },
108 ]);
109 await expect(changeReport(env.DB, audit, root, r.id, "closed", "", "api")).rejects.toMatchObject({ status: 422 });
110 await expect(changeReport(env.DB, audit, root, r.id, "triaged", 7, "api")).rejects.toMatchObject({ status: 422 });
111 await expect(changeReport(env.DB, audit, root, "0".repeat(32), "triaged", "", "api")).rejects.toMatchObject({ status: 404 });
112 expect(await new SecurityReports(env.DB).counts()).toEqual({ new: 0, triaged: 0, resolved: 1 });
113 });
114});