Add a content security policy and expire mailed export links.
Responses had no CSP, the 48-hour download token never changed, and short share slugs could be guessed without a miss limit.
This commit is contained in:
1 parent
0fe2624002
commit
75649a9a42
18 files changed
+249
-19
No files matched your search
@@ -10,6 +10,15 @@ vi.mock("next/navigation", () => ({
|
||||
notFound: () => notFoundMock(),
|
||||
}));
|
||||
|
||||
vi.mock("next/headers", () => ({
|
||||
headers: async () =>
|
||||
new Headers({ "x-forwarded-for": "203.0.113.8" }),
|
||||
}));
|
||||
|
||||
vi.mock("../../lib/server/rateLimit", () => ({
|
||||
rateLimitKey: () => ({ ok: true }),
|
||||
}));
|
||||
|
||||
vi.mock("../../lib/server/publishedRules", () => ({
|
||||
getReadablePublishedRule: (...args: unknown[]) =>
|
||||
getReadablePublishedRuleMock(...args),
|
||||
|
||||
@@ -2,6 +2,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const isDatabaseConfiguredMock = vi.fn();
|
||||
const findUniqueMock = vi.fn();
|
||||
const rateLimitKeyMock = vi.fn();
|
||||
const findManyMock = vi.fn();
|
||||
const stakeholderFindManyMock = vi.fn();
|
||||
const browserHoldsClaimForHashMock = vi.fn();
|
||||
@@ -12,6 +13,10 @@ vi.mock("../../lib/server/env", () => ({
|
||||
isDatabaseConfigured: () => isDatabaseConfiguredMock(),
|
||||
}));
|
||||
|
||||
vi.mock("../../lib/server/rateLimit", () => ({
|
||||
rateLimitKey: (...args: unknown[]) => rateLimitKeyMock(...args),
|
||||
}));
|
||||
|
||||
vi.mock("../../lib/server/db", () => ({
|
||||
prisma: {
|
||||
publishedRule: {
|
||||
@@ -71,9 +76,11 @@ beforeEach(() => {
|
||||
browserHoldsClaimForHashMock.mockReset();
|
||||
isRuleAdminEmailMock.mockReset();
|
||||
logAdminRuleReadMock.mockReset();
|
||||
rateLimitKeyMock.mockReset();
|
||||
browserHoldsClaimForHashMock.mockResolvedValue(false);
|
||||
isRuleAdminEmailMock.mockReturnValue(false);
|
||||
logAdminRuleReadMock.mockResolvedValue(undefined);
|
||||
rateLimitKeyMock.mockReturnValue({ ok: true });
|
||||
});
|
||||
|
||||
describe("getReadablePublishedRule", () => {
|
||||
@@ -220,6 +227,24 @@ describe("getReadablePublishedRule", () => {
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("rate limits failed share-slug lookups", async () => {
|
||||
isDatabaseConfiguredMock.mockReturnValue(true);
|
||||
findUniqueMock.mockResolvedValueOnce(null);
|
||||
expect(
|
||||
await getReadablePublishedRule({
|
||||
idOrSlug: "k7f2-9qxm",
|
||||
user: null,
|
||||
viaShareSlug: true,
|
||||
requestPath: "/r/k7f2-9qxm",
|
||||
failedLookupKey: "203.0.113.8",
|
||||
}),
|
||||
).toBeNull();
|
||||
expect(rateLimitKeyMock).toHaveBeenCalledWith(
|
||||
"share-lookup-miss:203.0.113.8",
|
||||
1_000,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("listListedPublishedRules", () => {
|
||||
|
||||
@@ -1,16 +1,30 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
RULE_EXPORT_TOKEN_TTL_MS,
|
||||
ruleExportToken,
|
||||
ruleExportTokenMatches,
|
||||
} from "../../lib/server/ruleExportToken";
|
||||
|
||||
describe("ruleExportToken", () => {
|
||||
it("accepts the matching token and rejects another rule or token", () => {
|
||||
const pepper = "test-pepper-16chars";
|
||||
const token = ruleExportToken("rule-1", pepper);
|
||||
expect(ruleExportTokenMatches("rule-1", token, pepper)).toBe(true);
|
||||
expect(ruleExportTokenMatches("rule-2", token, pepper)).toBe(false);
|
||||
expect(ruleExportTokenMatches("rule-1", `${token}x`, pepper)).toBe(false);
|
||||
expect(ruleExportTokenMatches("rule-1", "", pepper)).toBe(false);
|
||||
const pepper = "test-pepper-16chars";
|
||||
const now = new Date("2026-11-21T12:00:00.000Z");
|
||||
|
||||
it("accepts the matching token and rejects another rule, version, or token", () => {
|
||||
const token = ruleExportToken("rule-1", pepper, 0, now);
|
||||
expect(ruleExportTokenMatches("rule-1", token, pepper, 0, now)).toBe(true);
|
||||
expect(ruleExportTokenMatches("rule-2", token, pepper, 0, now)).toBe(false);
|
||||
expect(ruleExportTokenMatches("rule-1", token, pepper, 1, now)).toBe(false);
|
||||
expect(ruleExportTokenMatches("rule-1", `${token}x`, pepper, 0, now)).toBe(
|
||||
false,
|
||||
);
|
||||
expect(ruleExportTokenMatches("rule-1", "", pepper, 0, now)).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects a token after it expires", () => {
|
||||
const token = ruleExportToken("rule-1", pepper, 0, now);
|
||||
const afterExpiry = new Date(now.getTime() + RULE_EXPORT_TOKEN_TTL_MS + 1);
|
||||
expect(
|
||||
ruleExportTokenMatches("rule-1", token, pepper, 0, afterExpiry),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -49,6 +49,7 @@ describe("sendDueRuleFollowUpEmails", () => {
|
||||
{
|
||||
id: "rule-1",
|
||||
title: "Garden Norms",
|
||||
exportTokenVersion: 0,
|
||||
user: { email: "pen@example.com" },
|
||||
},
|
||||
]);
|
||||
@@ -85,7 +86,7 @@ describe("sendDueRuleFollowUpEmails", () => {
|
||||
|
||||
it("skips rows with no mailbox and does not mark them sent", async () => {
|
||||
findManyMock.mockResolvedValueOnce([
|
||||
{ id: "rule-2", title: "Guest", user: { email: "" } },
|
||||
{ id: "rule-2", title: "Guest", exportTokenVersion: 0, user: { email: "" } },
|
||||
]);
|
||||
const result = await sendDueRuleFollowUpEmails(db as never);
|
||||
expect(result.skipped).toBe(1);
|
||||
@@ -98,6 +99,7 @@ describe("sendDueRuleFollowUpEmails", () => {
|
||||
{
|
||||
id: "rule-4",
|
||||
title: "Race",
|
||||
exportTokenVersion: 0,
|
||||
user: { email: "pen@example.com" },
|
||||
},
|
||||
]);
|
||||
@@ -112,6 +114,7 @@ describe("sendDueRuleFollowUpEmails", () => {
|
||||
{
|
||||
id: "rule-3",
|
||||
title: "Retry",
|
||||
exportTokenVersion: 0,
|
||||
user: { email: "pen@example.com" },
|
||||
},
|
||||
]);
|
||||
|
||||
@@ -221,6 +221,7 @@ describe("patchOwnedRuleShare", () => {
|
||||
data: {
|
||||
visibility: RULE_VISIBILITY.private,
|
||||
shareSlug: null,
|
||||
exportTokenVersion: { increment: 1 },
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -52,6 +52,7 @@ function row() {
|
||||
},
|
||||
createdAt: new Date("2026-11-08T00:00:00.000Z"),
|
||||
userId: "user-1",
|
||||
exportTokenVersion: 0,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -86,7 +87,7 @@ describe("GET /api/rules/[id]/export/[format]", () => {
|
||||
});
|
||||
|
||||
it("returns a PDF attachment when the export token matches", async () => {
|
||||
const token = ruleExportToken("rule-1", PEPPER);
|
||||
const token = ruleExportToken("rule-1", PEPPER, 0);
|
||||
const res = await GET(
|
||||
new NextRequest(
|
||||
`https://x.test/api/rules/rule-1/export/pdf?t=${token}`,
|
||||
@@ -117,4 +118,19 @@ describe("GET /api/rules/[id]/export/[format]", () => {
|
||||
expect(text).toContain("# Garden Norms");
|
||||
expect(text).toContain("## Shared terms");
|
||||
});
|
||||
|
||||
it("rejects a mailed token after the share link is turned off", async () => {
|
||||
const token = ruleExportToken("rule-1", PEPPER, 0);
|
||||
findUniqueMock.mockResolvedValueOnce({
|
||||
...row(),
|
||||
exportTokenVersion: 1,
|
||||
});
|
||||
const res = await GET(
|
||||
new NextRequest(
|
||||
`https://x.test/api/rules/rule-1/export/pdf?t=${token}`,
|
||||
),
|
||||
makeContext("rule-1", "pdf"),
|
||||
);
|
||||
expect(res.status).toBe(401);
|
||||
});
|
||||
});
|
||||
@@ -2,6 +2,7 @@ import { NextRequest } from "next/server";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const findFirstRuleMock = vi.fn();
|
||||
const publishedRuleUpdateMock = vi.fn();
|
||||
const findFirstStakeholderMock = vi.fn();
|
||||
const countMock = vi.fn();
|
||||
const deleteMock = vi.fn();
|
||||
@@ -20,6 +21,7 @@ vi.mock("../../lib/server/db", () => ({
|
||||
prisma: {
|
||||
publishedRule: {
|
||||
findFirst: (...args: unknown[]) => findFirstRuleMock(...args),
|
||||
update: (...args: unknown[]) => publishedRuleUpdateMock(...args),
|
||||
},
|
||||
ruleStakeholder: {
|
||||
findFirst: (...args: unknown[]) => findFirstStakeholderMock(...args),
|
||||
@@ -67,6 +69,7 @@ const memberCtx = {
|
||||
|
||||
beforeEach(() => {
|
||||
findFirstRuleMock.mockReset();
|
||||
publishedRuleUpdateMock.mockReset();
|
||||
findFirstStakeholderMock.mockReset();
|
||||
countMock.mockReset();
|
||||
deleteMock.mockReset();
|
||||
@@ -177,6 +180,10 @@ describe("DELETE /api/rules/[id]/stakeholders/[stakeholderId]", () => {
|
||||
expect(res.status).toBe(200);
|
||||
expect(await res.json()).toEqual({ ok: true });
|
||||
expect(deleteMock).toHaveBeenCalledWith({ where: { id: "st-1" } });
|
||||
expect(publishedRuleUpdateMock).toHaveBeenCalledWith({
|
||||
where: { id: "rule-1" },
|
||||
data: { exportTokenVersion: { increment: 1 } },
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import nextConfig from "../../next.config.mjs";
|
||||
|
||||
describe("security headers", () => {
|
||||
it("drops X-Powered-By and sends a same-origin CSP", async () => {
|
||||
expect(nextConfig.poweredByHeader).toBe(false);
|
||||
const rows = await nextConfig.headers();
|
||||
const globalHeaders = rows.find((row) => row.source === "/(.*)")?.headers;
|
||||
expect(globalHeaders).toBeDefined();
|
||||
const byKey = Object.fromEntries(
|
||||
(globalHeaders ?? []).map((header) => [header.key, header.value]),
|
||||
);
|
||||
expect(byKey["Content-Security-Policy"]).toContain("default-src 'self'");
|
||||
expect(byKey["Content-Security-Policy"]).toContain("script-src 'self'");
|
||||
expect(byKey["Content-Security-Policy"]).toContain("style-src 'self'");
|
||||
expect(byKey["Content-Security-Policy"]).toContain("font-src 'self'");
|
||||
expect(byKey["Content-Security-Policy"]).toContain("img-src 'self'");
|
||||
expect(byKey["Permissions-Policy"]).toBe(
|
||||
"camera=(), microphone=(), geolocation=()",
|
||||
);
|
||||
expect(byKey["Referrer-Policy"]).toBe("same-origin");
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user