|
| 1 | +/** |
| 2 | + * Server-side Turnstile enforcement on |
| 3 | + * POST /_emdash/api/comments/:collection/:contentId (issue #1589). |
| 4 | + * |
| 5 | + * The form widget submits a `turnstileToken`, but the route previously |
| 6 | + * never verified it — a bot POSTing directly to the API bypassed |
| 7 | + * Turnstile entirely. When a secret key is configured |
| 8 | + * (EMDASH_TURNSTILE_SECRET_KEY / TURNSTILE_SECRET_KEY), the route must |
| 9 | + * verify the token via Cloudflare's siteverify before persisting, and |
| 10 | + * reject submissions without a valid token. Without a configured secret |
| 11 | + * the behavior is unchanged (backward compatible). |
| 12 | + */ |
| 13 | + |
| 14 | +import type { APIContext } from "astro"; |
| 15 | +import type { Kysely } from "kysely"; |
| 16 | +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; |
| 17 | + |
| 18 | +import { POST as postComment } from "../../../src/astro/routes/api/comments/[collection]/[contentId]/index.js"; |
| 19 | +import type { Database } from "../../../src/database/types.js"; |
| 20 | +import { SchemaRegistry } from "../../../src/schema/registry.js"; |
| 21 | +import { setupTestDatabase, teardownTestDatabase } from "../../utils/test-db.js"; |
| 22 | + |
| 23 | +function buildRequest(body: Record<string, unknown>, headers?: Record<string, string>): Request { |
| 24 | + return new Request("http://localhost/_emdash/api/comments/post/post-1", { |
| 25 | + method: "POST", |
| 26 | + headers: { "content-type": "application/json", ...headers }, |
| 27 | + body: JSON.stringify(body), |
| 28 | + }); |
| 29 | +} |
| 30 | + |
| 31 | +function buildContext( |
| 32 | + db: Kysely<Database>, |
| 33 | + request: Request, |
| 34 | + config: Record<string, unknown> = {}, |
| 35 | +): APIContext { |
| 36 | + return { |
| 37 | + params: { collection: "post", contentId: "post-1" }, |
| 38 | + request, |
| 39 | + locals: { |
| 40 | + emdash: { |
| 41 | + db, |
| 42 | + config, |
| 43 | + hooks: { |
| 44 | + runCommentBeforeCreate: async (event: unknown) => event, |
| 45 | + invokeExclusiveHook: async () => null, |
| 46 | + runCommentAfterCreate: async () => undefined, |
| 47 | + }, |
| 48 | + }, |
| 49 | + user: null, |
| 50 | + }, |
| 51 | + // eslint-disable-next-line typescript/no-unsafe-type-assertion -- minimal stub for tests |
| 52 | + } as unknown as APIContext; |
| 53 | +} |
| 54 | + |
| 55 | +const VALID_BODY = { |
| 56 | + authorName: "Alice", |
| 57 | + authorEmail: "alice@example.com", |
| 58 | + body: "Nice post!", |
| 59 | +}; |
| 60 | + |
| 61 | +/** Stub global fetch for the siteverify call; returns the spy. */ |
| 62 | +function stubSiteverify(success: boolean) { |
| 63 | + const fetchSpy = vi.fn(async () => |
| 64 | + Response.json(success ? { success: true } : { success: false, "error-codes": ["bad-token"] }), |
| 65 | + ); |
| 66 | + vi.stubGlobal("fetch", fetchSpy); |
| 67 | + return fetchSpy; |
| 68 | +} |
| 69 | + |
| 70 | +describe("POST /comments — Turnstile verification", () => { |
| 71 | + let db: Kysely<Database>; |
| 72 | + |
| 73 | + beforeEach(async () => { |
| 74 | + db = await setupTestDatabase(); |
| 75 | + const registry = new SchemaRegistry(db); |
| 76 | + await registry.createCollection({ |
| 77 | + slug: "post", |
| 78 | + label: "Posts", |
| 79 | + labelSingular: "Post", |
| 80 | + commentsEnabled: true, |
| 81 | + }); |
| 82 | + await registry.createField("post", { slug: "title", label: "Title", type: "string" }); |
| 83 | + await db |
| 84 | + .insertInto("ec_post" as never) |
| 85 | + .values({ |
| 86 | + id: "post-1", |
| 87 | + slug: "post-1", |
| 88 | + status: "published", |
| 89 | + published_at: new Date().toISOString(), |
| 90 | + title: "Test post", |
| 91 | + } as never) |
| 92 | + .execute(); |
| 93 | + }); |
| 94 | + |
| 95 | + afterEach(async () => { |
| 96 | + await teardownTestDatabase(db); |
| 97 | + vi.unstubAllEnvs(); |
| 98 | + vi.unstubAllGlobals(); |
| 99 | + }); |
| 100 | + |
| 101 | + async function commentCount(): Promise<number> { |
| 102 | + const rows = await db.selectFrom("_emdash_comments").select("id").execute(); |
| 103 | + return rows.length; |
| 104 | + } |
| 105 | + |
| 106 | + it("rejects a submission without a token when a secret is configured", async () => { |
| 107 | + vi.stubEnv("EMDASH_TURNSTILE_SECRET_KEY", "test-secret"); |
| 108 | + const fetchSpy = stubSiteverify(true); |
| 109 | + |
| 110 | + const res = await postComment(buildContext(db, buildRequest(VALID_BODY))); |
| 111 | + |
| 112 | + expect(res.status).toBe(403); |
| 113 | + // No siteverify subrequest for a missing token |
| 114 | + expect(fetchSpy).not.toHaveBeenCalled(); |
| 115 | + expect(await commentCount()).toBe(0); |
| 116 | + }); |
| 117 | + |
| 118 | + it("rejects a submission whose token fails siteverify", async () => { |
| 119 | + vi.stubEnv("EMDASH_TURNSTILE_SECRET_KEY", "test-secret"); |
| 120 | + const fetchSpy = stubSiteverify(false); |
| 121 | + |
| 122 | + const res = await postComment( |
| 123 | + buildContext(db, buildRequest({ ...VALID_BODY, turnstileToken: "forged" })), |
| 124 | + ); |
| 125 | + |
| 126 | + expect(res.status).toBe(403); |
| 127 | + expect(fetchSpy).toHaveBeenCalledOnce(); |
| 128 | + expect(await commentCount()).toBe(0); |
| 129 | + }); |
| 130 | + |
| 131 | + it("accepts a submission whose token passes siteverify", async () => { |
| 132 | + vi.stubEnv("EMDASH_TURNSTILE_SECRET_KEY", "test-secret"); |
| 133 | + const fetchSpy = stubSiteverify(true); |
| 134 | + |
| 135 | + const res = await postComment( |
| 136 | + buildContext(db, buildRequest({ ...VALID_BODY, turnstileToken: "valid-token" })), |
| 137 | + ); |
| 138 | + |
| 139 | + expect(res.status).toBe(201); |
| 140 | + expect(fetchSpy).toHaveBeenCalledOnce(); |
| 141 | + // The secret and token must reach siteverify |
| 142 | + // eslint-disable-next-line typescript/no-unsafe-type-assertion -- shape fixed by the code under test |
| 143 | + const [url, init] = fetchSpy.mock.calls[0] as unknown as [string, { body: string }]; |
| 144 | + expect(url).toBe("https://challenges.cloudflare.com/turnstile/v0/siteverify"); |
| 145 | + expect(JSON.parse(init.body)).toMatchObject({ |
| 146 | + secret: "test-secret", |
| 147 | + response: "valid-token", |
| 148 | + }); |
| 149 | + expect(await commentCount()).toBe(1); |
| 150 | + }); |
| 151 | + |
| 152 | + it("forwards the trusted remote IP to siteverify", async () => { |
| 153 | + vi.stubEnv("EMDASH_TURNSTILE_SECRET_KEY", "test-secret"); |
| 154 | + const fetchSpy = stubSiteverify(true); |
| 155 | + |
| 156 | + const request = buildRequest( |
| 157 | + { ...VALID_BODY, turnstileToken: "valid-token" }, |
| 158 | + { "x-forwarded-for": "203.0.113.45" }, |
| 159 | + ); |
| 160 | + const res = await postComment( |
| 161 | + buildContext(db, request, { trustedProxyHeaders: ["x-forwarded-for"] }), |
| 162 | + ); |
| 163 | + |
| 164 | + expect(res.status).toBe(201); |
| 165 | + expect(fetchSpy).toHaveBeenCalledOnce(); |
| 166 | + // eslint-disable-next-line typescript/no-unsafe-type-assertion -- shape fixed by the code under test |
| 167 | + const [, init] = fetchSpy.mock.calls[0] as unknown as [string, { body: string }]; |
| 168 | + expect(JSON.parse(init.body)).toMatchObject({ |
| 169 | + secret: "test-secret", |
| 170 | + response: "valid-token", |
| 171 | + remoteip: "203.0.113.45", |
| 172 | + }); |
| 173 | + }); |
| 174 | + |
| 175 | + it("fails closed when siteverify itself errors", async () => { |
| 176 | + vi.stubEnv("EMDASH_TURNSTILE_SECRET_KEY", "test-secret"); |
| 177 | + vi.stubGlobal( |
| 178 | + "fetch", |
| 179 | + vi.fn(async () => { |
| 180 | + throw new Error("network down"); |
| 181 | + }), |
| 182 | + ); |
| 183 | + |
| 184 | + const res = await postComment( |
| 185 | + buildContext(db, buildRequest({ ...VALID_BODY, turnstileToken: "valid-token" })), |
| 186 | + ); |
| 187 | + |
| 188 | + expect(res.status).toBe(403); |
| 189 | + expect(await commentCount()).toBe(0); |
| 190 | + }); |
| 191 | + |
| 192 | + it("ignores the token when no secret is configured (backward compatible)", async () => { |
| 193 | + const fetchSpy = stubSiteverify(true); |
| 194 | + |
| 195 | + const res = await postComment( |
| 196 | + buildContext(db, buildRequest({ ...VALID_BODY, turnstileToken: "anything" })), |
| 197 | + ); |
| 198 | + |
| 199 | + expect(res.status).toBe(201); |
| 200 | + expect(fetchSpy).not.toHaveBeenCalled(); |
| 201 | + expect(await commentCount()).toBe(1); |
| 202 | + }); |
| 203 | +}); |
0 commit comments