Repository navigation
fix: harden Pages same-origin auth and session CSRF #5
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
d156511
fix: keep CSRF stable across session reads
zskbot babe87c
fix: validate same-origin Pages requests and preserve 304
zskbot 7ba408b
test: exercise Pages auth routing and browser edge cases
zskbot b5c5f0f
docs: record Pages auth review fixes
zskbot e89608c
test: guard session expiry and stable CSRF invariants
zskbot 30d1b00
docs: update staging review branch status
zskbot 571af87
fix: allow verified OAuth callback navigations
zskbot f20c5e2
fix: migrate legacy session CSRF hashes
zskbot 6b1d50d
test: cover OAuth callback and legacy CSRF migration
zskbot 78b6efb
test: require compatibility migration for stored CSRF hashes
zskbot b33a1ae
docs: document OAuth callback and legacy CSRF compatibility
zskbot 1086750
fix: require Origin on writes and preserve OAuth callback
zskbot 5e6eeb1
test: verify Worker delegation and reject originless writes
zskbot 46b0075
test: provide D1 rate-limit stub for OAuth callback
zskbot File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,16 +1,170 @@ | ||
| import test from "node:test"; | ||
| import assert from "node:assert/strict"; | ||
| import { readFile } from "node:fs/promises"; | ||
| import { webcrypto } from "node:crypto"; | ||
| import { onRequest } from "../../functions/[[path]].js"; | ||
|
|
||
| const source = await readFile(new URL("../../functions/[[path]].js", import.meta.url), "utf8"); | ||
| if (!globalThis.crypto) globalThis.crypto = webcrypto; | ||
|
|
||
| test("Pages Functions routes auth endpoints through the same-origin Worker", () => { | ||
| assert.match(source, /AUTH_ROUTE/); | ||
| assert.match(source, /authWorker\.fetch\(request, \{ \.\.\.env, APP_ORIGIN: url\.origin \}\)/); | ||
| assert.match(source, /context\.next\(\)/); | ||
| const secret = "test-session-secret-for-pages-contract"; | ||
| const sessionId = "test-session-cookie-value"; | ||
| const b64url = bytes => Buffer.from(bytes).toString("base64url"); | ||
| async function hmac(value) { | ||
| const key = await crypto.subtle.importKey( | ||
| "raw", | ||
| new TextEncoder().encode(secret), | ||
| { name: "HMAC", hash: "SHA-256" }, | ||
| false, | ||
| ["sign"] | ||
| ); | ||
| return b64url(await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(value))); | ||
| } | ||
|
|
||
| function envWithDb(initialRow) { | ||
| let row = initialRow; | ||
| const updates = []; | ||
| return { | ||
| SESSION_SECRET: secret, | ||
| TOKEN_ENCRYPTION_KEY: Buffer.alloc(32, 7).toString("base64"), | ||
| __updates: updates, | ||
| __getRow: () => row, | ||
| DB: { | ||
| prepare(sql) { | ||
| let values = []; | ||
| return { | ||
| bind(...args) { values = args; return this; }, | ||
| async first() { return row; }, | ||
| async run() { | ||
| if (sql.startsWith("UPDATE auth_sessions")) { | ||
| updates.push(values); | ||
| row = { ...row, csrf_hash: values[0] }; | ||
| } | ||
| return { success: true }; | ||
| } | ||
| }; | ||
| } | ||
| } | ||
| }; | ||
| } | ||
|
|
||
| test("Pages delegates health requests to the injected auth Worker", async () => { | ||
| const calls = []; | ||
| const worker = { | ||
| async fetch(request, env) { | ||
| calls.push({ url: request.url, origin: request.headers.get("Origin"), appOrigin: env.APP_ORIGIN }); | ||
| return Response.json({ service: "test-worker" }); | ||
| } | ||
| }; | ||
| const response = await onRequest({ | ||
| request: new Request("https://preview.pages.dev/health"), | ||
| env: {}, | ||
| next: async () => { throw new Error("static asset pipeline must not run"); } | ||
| }, worker); | ||
| assert.equal(response.status, 200); | ||
| assert.equal((await response.json()).service, "test-worker"); | ||
| assert.equal(calls.length, 1); | ||
| assert.equal(new URL(calls[0].url).pathname, "/health"); | ||
| assert.equal(calls[0].origin, "https://preview.pages.dev"); | ||
| assert.equal(calls[0].appOrigin, "https://preview.pages.dev"); | ||
| }); | ||
|
|
||
| test("Pages safely supplies Origin for same-origin GET requests without Origin", async () => { | ||
| const response = await onRequest({ | ||
| request: new Request("https://preview.pages.dev/api/github/user"), | ||
| env: envWithDb(null), | ||
| next: async () => { throw new Error("auth route must not reach static assets"); } | ||
| }); | ||
| assert.equal(response.status, 401); | ||
| assert.deepEqual(await response.json(), { error: "not_authenticated" }); | ||
| }); | ||
|
|
||
| test("session reads migrate legacy CSRF hashes and stay stable across tabs", async () => { | ||
| const legacyHash = await hmac("legacy-random-csrf-token"); | ||
| const row = { | ||
| id_hash: await hmac(sessionId), | ||
| github_id: "123", | ||
| csrf_hash: legacyHash, | ||
| expires_at: Date.now() + 60_000, | ||
| github_login: "ocodejs-test", | ||
| token_ciphertext: "unused", | ||
| token_kind: "pat", | ||
| scopes: "[]" | ||
| }; | ||
| const env = envWithDb(row); | ||
| const readSession = () => onRequest({ | ||
| request: new Request("https://preview.pages.dev/auth/session", { | ||
| headers: { Cookie: "ocode_session=" + sessionId } | ||
| }), | ||
| env, | ||
| next: async () => { throw new Error("auth route must not reach static assets"); } | ||
| }); | ||
| const first = await (await readSession()).json(); | ||
| const second = await (await readSession()).json(); | ||
| assert.equal(first.connected, true); | ||
| assert.equal(first.csrfToken, second.csrfToken); | ||
| assert.equal(first.csrfToken, await hmac("csrf:" + sessionId)); | ||
| assert.equal(env.__updates.length, 1); | ||
| assert.equal(env.__getRow().csrf_hash, await hmac(first.csrfToken)); | ||
| }); | ||
|
|
||
| test("HTML responses receive the active Pages origin configuration", async () => { | ||
| const response = await onRequest({ | ||
| request: new Request("https://preview.pages.dev/"), | ||
| env: {}, | ||
| next: async () => new Response("<html><head></head><body>ok</body></html>", { | ||
| headers: { "content-type": "text/html; charset=utf-8" } | ||
| }) | ||
| }); | ||
| assert.match(await response.text(), /window\.OCODE_AUTH_API = location\.origin/); | ||
| }); | ||
|
|
||
| test("conditional HTML requests preserve bodyless 304 responses", async () => { | ||
| const original = new Response(null, { | ||
| status: 304, | ||
| headers: { "content-type": "text/html; charset=utf-8", etag: '"cached"' } | ||
| }); | ||
| const response = await onRequest({ | ||
| request: new Request("https://preview.pages.dev/"), | ||
| env: {}, | ||
| next: async () => original | ||
| }); | ||
| assert.equal(response.status, 304); | ||
| assert.equal(await response.text(), ""); | ||
| assert.equal(response.headers.get("etag"), '"cached"'); | ||
| }); | ||
|
|
||
| test("state-changing auth requests without Origin are rejected", async () => { | ||
| const response = await onRequest({ | ||
| request: new Request("https://preview.pages.dev/auth/pat", { | ||
| method: "POST", | ||
| headers: { "content-type": "application/json" }, | ||
| body: JSON.stringify({ token: "ghp_exampletokenvalue1234567890" }) | ||
| }), | ||
| env: {}, | ||
| next: async () => { throw new Error("auth route must not reach static assets"); } | ||
| }); | ||
| assert.equal(response.status, 403); | ||
| }); | ||
|
|
||
| test("cross-site auth requests are rejected before reaching the Worker", async () => { | ||
| const response = await onRequest({ | ||
| request: new Request("https://preview.pages.dev/auth/logout", { | ||
| method: "POST", | ||
| headers: { Origin: "https://attacker.example", "Sec-Fetch-Site": "cross-site" } | ||
| }), | ||
| env: {}, | ||
| next: async () => { throw new Error("auth route must not reach static assets"); } | ||
| }); | ||
| assert.equal(response.status, 403); | ||
| }); | ||
|
|
||
| test("Pages HTML configures the auth API to use the current origin", () => { | ||
| assert.match(source, /window\.OCODE_AUTH_API = location\.origin/); | ||
| assert.match(source, /contentType\.includes\("text\/html"\)/); | ||
| test("GitHub OAuth callback permits cross-site top-level GET navigation", async () => { | ||
| const response = await onRequest({ | ||
| request: new Request("https://preview.pages.dev/auth/github/callback?error=access_denied", { | ||
| headers: { Origin: "https://github.com", "Sec-Fetch-Site": "cross-site" } | ||
| }), | ||
| env: envWithDb(null), | ||
| next: async () => { throw new Error("auth route must not reach static assets"); } | ||
| }); | ||
| assert.equal(response.status, 302); | ||
| assert.equal(response.headers.get("location"), "https://preview.pages.dev/?auth=cancelled"); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.