| 1 | import { beforeEach, describe, expect, it } from "vitest"; |
| 2 | import { resetAccessCache, teamName } from "../src/access"; |
| 3 | import { handleFetch } from "../src/index"; |
| 4 | import { createRunner } from "../src/sql"; |
| 5 | import { answer, FakeD1, INSTALL_A } from "./support"; |
| 6 | |
| 7 | const TEAM = "codewhale"; |
| 8 | const AUD = "aud-123"; |
| 9 | const NOW = new Date("2026-11-12T10:00:00Z"); |
| 10 | |
| 11 | const b64 = (input: ArrayBuffer | string) => { |
| 12 | const bytes = typeof input === "string" ? new TextEncoder().encode(input) : new Uint8Array(input); |
| 13 | return btoa(String.fromCharCode(...bytes)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); |
| 14 | }; |
| 15 | |
| 16 | async function signer() { |
| 17 | const pair = (await crypto.subtle.generateKey({ name: "RSASSA-PKCS1-v1_5", modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 1]), hash: "SHA-256" }, true, ["sign", "verify"])) as CryptoKeyPair; |
| 18 | const jwk = (await crypto.subtle.exportKey("jwk", pair.publicKey)) as JsonWebKey; |
| 19 | const token = async (claims: Record<string, unknown>) => { |
| 20 | const head = b64(JSON.stringify({ alg: "RS256", kid: "k1" })); |
| 21 | const body = b64(JSON.stringify(claims)); |
| 22 | const sig = await crypto.subtle.sign("RSASSA-PKCS1-v1_5", pair.privateKey, new TextEncoder().encode(`${head}.${body}`)); |
| 23 | return `${head}.${body}.${b64(sig)}`; |
| 24 | }; |
| 25 | return { jwk: { ...jwk, kid: "k1" }, token }; |
| 26 | } |
| 27 | |
| 28 | const good = (extra: Record<string, unknown> = {}) => ({ iss: `https://${TEAM}.cloudflareaccess.com`, aud: [AUD], exp: NOW.getTime() / 1000 + 600, ...extra }); |
| 29 | |
| 30 | function env(overrides = {}) { |
| 31 | const queries: string[] = []; |
| 32 | return { |
| 33 | queries, |
| 34 | env: { |
| 35 | ACCESS_TEAM_DOMAIN: TEAM, |
| 36 | ACCESS_AUD: AUD, |
| 37 | ANALYTICS_SQL: { |
| 38 | async query({ query }: { query: string }) { |
| 39 | queries.push(query); |
| 40 | return { data: (answer(query) as Record<string, unknown>[]).map((row) => ({ ...row, index1: INSTALL_A })) }; |
| 41 | }, |
| 42 | }, |
| 43 | DB: new FakeD1(), |
| 44 | ...overrides, |
| 45 | }, |
| 46 | }; |
| 47 | } |
| 48 | |
| 49 | describe("worker", () => { |
| 50 | beforeEach(() => resetAccessCache()); |
| 51 | |
| 52 | it("fails closed when Access is not configured, and rejects missing or bad tokens", async () => { |
| 53 | const request = new Request("https://stats.test/api/stats"); |
| 54 | expect((await handleFetch(request, { ...env().env, ACCESS_AUD: "" }, NOW)).status).toBe(503); |
| 55 | expect((await handleFetch(request, env().env, NOW)).status).toBe(403); |
| 56 | expect((await handleFetch(new Request("https://stats.test/api/stats", { headers: { "cf-access-jwt-assertion": "a.b.c" } }), env().env, NOW)).status).toBe(403); |
| 57 | expect((await handleFetch(new Request("https://stats.test/api/stats", { method: "POST" }), env().env, NOW)).status).toBe(405); |
| 58 | }); |
| 59 | |
| 60 | it("serves aggregate stats with a valid Access token and never an install id", async () => { |
| 61 | const { jwk, token } = await signer(); |
| 62 | const realFetch = globalThis.fetch; |
| 63 | globalThis.fetch = (async () => new Response(JSON.stringify({ keys: [jwk] }))) as typeof fetch; |
| 64 | try { |
| 65 | const { env: e, queries } = env(); |
| 66 | const headers = { "cf-access-jwt-assertion": await token(good()) }; |
| 67 | const response = await handleFetch(new Request("https://stats.test/api/stats?days=7", { headers }), e, NOW); |
| 68 | expect(response.status).toBe(200); |
| 69 | const text = await response.text(); |
| 70 | expect(text).not.toMatch(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i); |
| 71 | expect(text).not.toMatch(/install_id|index1/); |
| 72 | const body = JSON.parse(text); |
| 73 | expect(body.source).toBe("binding"); |
| 74 | expect(body.from).toBe("2026-11-06"); |
| 75 | expect(body.to).toBe("2026-11-12"); |
| 76 | expect(body.rows.length).toBeGreaterThan(10); |
| 77 | const before = queries.length; |
| 78 | await handleFetch(new Request("https://stats.test/api/stats?days=7", { headers }), e, NOW); |
| 79 | expect(queries.length).toBe(before); |
| 80 | |
| 81 | const wrongAud = { "cf-access-jwt-assertion": await token(good({ aud: ["other"] })) }; |
| 82 | expect((await handleFetch(new Request("https://stats.test/api/stats", { headers: wrongAud }), e, NOW)).status).toBe(403); |
| 83 | const expired = { "cf-access-jwt-assertion": await token(good({ exp: 1 })) }; |
| 84 | expect((await handleFetch(new Request("https://stats.test/api/stats", { headers: expired }), e, NOW)).status).toBe(403); |
| 85 | } finally { |
| 86 | globalThis.fetch = realFetch; |
| 87 | } |
| 88 | }); |
| 89 | |
| 90 | it("reads the kept totals from the rollup store for the trend", async () => { |
| 91 | const { jwk, token } = await signer(); |
| 92 | const realFetch = globalThis.fetch; |
| 93 | globalThis.fetch = (async () => new Response(JSON.stringify({ keys: [jwk] }))) as typeof fetch; |
| 94 | try { |
| 95 | const { env: e } = env(); |
| 96 | const db = e.DB as FakeD1; |
| 97 | db.rows.set("a", { day: "2026-01-02", metric: "active_installs", dim: "all", key: "all", value: 7 }); |
| 98 | db.rows.set("b", { day: "2026-01-02", metric: "active_installs", dim: "version", key: "0.9", value: 3 }); |
| 99 | const headers = { "cf-access-jwt-assertion": await token(good()) }; |
| 100 | const response = await handleFetch(new Request("https://stats.test/api/trend?days=400", { headers }), e, NOW); |
| 101 | expect((await response.json()).rows).toEqual([{ day: "2026-01-02", metric: "active_installs", dim: "all", key: "all", value: 7 }]); |
| 102 | } finally { |
| 103 | globalThis.fetch = realFetch; |
| 104 | } |
| 105 | }); |
| 106 | }); |
| 107 | |
| 108 | describe("teamName", () => { |
| 109 | it("accepts the bare team name or the full cloudflareaccess.com host, and refuses anything else", () => { |
| 110 | expect(teamName({ ACCESS_TEAM_DOMAIN: "codewhale" })).toBe("codewhale"); |
| 111 | expect(teamName({ ACCESS_TEAM_DOMAIN: "https://CodeWhale.cloudflareaccess.com/" })).toBe("codewhale"); |
| 112 | expect(teamName({ ACCESS_TEAM_DOMAIN: "evil.example.com" })).toBe(""); |
| 113 | }); |
| 114 | }); |
| 115 | |
| 116 | describe("createRunner", () => { |
| 117 | it("prefers the binding, falls back to the REST API with a token, else none", async () => { |
| 118 | expect(createRunner({ ANALYTICS_SQL: { query: async () => ({ data: [] }) } })?.source).toBe("binding"); |
| 119 | expect(createRunner({})).toBeNull(); |
| 120 | const calls: { url: string; body: string; auth: string }[] = []; |
| 121 | const runner = createRunner({ CF_ACCOUNT_ID: "acct", CF_API_TOKEN: "tok" }, (async (url: string, init: RequestInit) => { |
| 122 | calls.push({ url, body: String(init.body), auth: (init.headers as Record<string, string>).Authorization }); |
| 123 | return new Response(JSON.stringify({ data: [{ a: 1 }] })); |
| 124 | }) as unknown as typeof fetch); |
| 125 | expect(runner?.source).toBe("rest"); |
| 126 | expect(await runner?.run("SELECT 1")).toEqual([{ a: 1 }]); |
| 127 | expect(calls[0]).toEqual({ url: "https://api.cloudflare.com/client/v4/accounts/acct/analytics_engine/sql", body: "SELECT 1 FORMAT JSON", auth: "Bearer tok" }); |
| 128 | }); |
| 129 | }); |
| 130 |