Public: anyone can read this; the crew can change it.

A sign-in or consent redirect target that points off this origin is ignored #13607

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

scout/forge:scout/13580-a-sign-in-or-consent-redirect-target-tha → main 4 commits fork

  • Merged. scout/13580-a-sign-in-or-consent-redirect-target-tha was merged into main as 8e06626.

Review

Sign in to review this change.
3 files changed +138 −2
src/web/return_to.ts +15 −2
@@ -15,7 +15,17 @@ import type { Ctx } from "../http/context.ts";
1515 export function safeNext(raw: string | null): string | undefined {
1616 if (raw === null || raw === "") return undefined;
1717 if (!raw.startsWith("/") || raw.startsWith("//")) return undefined;
18 if (raw.includes("\\") || /[\n\r]/.test(raw)) return undefined;
18 // A browser drops tabs and newlines from an address before reading it, so `/\t/evil.example`
19 // arrives as `//evil.example`; every control character is refused, with the backslash a browser
20 // reads as a slash.
21 if (raw.includes("\\") || /[\u0000-\u001f\u007f]/.test(raw)) return undefined;
22 // And whatever else a URL parser makes of it, it must still be a path on this origin.
23 const base = "http://here.invalid";
24 try {
25 if (new URL(raw, base).origin !== base) return undefined;
26 } catch {
27 return undefined;
28 }
1929 return raw;
2030 }
2131
@@ -31,7 +41,10 @@ const DOORS = /^\/(?:signin|signup|recover|claim|first-admin)$/;
3141 */
3242 const NO_RETURN = /^\/(?:(?:go|claim|first-admin|verify|signin\/access|signin\/parent|recover|broker)(?:\/|$)|[^/]+\/[^/]+\/toolbar$)/;
3343
34 /** The address a link into the sign-in door from this page should carry: the page itself, or on a door page the address it was entered with. */
44 /**
45 * The address a link into the sign-in door from this page should carry: the page itself, or on a
46 * door page the address it was entered with.
47 */
3548 export function returnTo(ctx: Ctx): string | undefined {
3649 if (DOORS.test(ctx.url.pathname)) return safeNext(ctx.url.searchParams.get("next"));
3750 if (NO_RETURN.test(ctx.url.pathname)) return undefined;
test/fork-follow-word.test.ts +4
@@ -47,6 +47,10 @@ beforeAll(async () => {
4747 // is behind, never fast-forwarded.
4848 const own = await commitToBranch(app, bob.value, forked.value, { message: "Mine", files: [{ path: "mine.txt", content: "m\n" }] });
4949 if (!own.ok) throw new Error(JSON.stringify(own.error));
50 // Not following while the parent moves: the follow that push starts would otherwise run in the
51 // background, and on a busy machine finish once a test has switched the fork to take-updates,
52 // merge the parent, and leave the fork no longer behind.
53 setForkFollowMode(app.db, forked.value.id, "dont-follow");
5054 const more = await commitToBranch(app, alice.value, lib.value, { message: "Two", files: [{ path: "two.txt", content: "2\n" }] });
5155 if (!more.ok) throw new Error(JSON.stringify(more.error));
5256 }, 60_000);
test/redirect-targets.test.ts added +119
@@ -0,0 +1,119 @@
1 /**
2 * A sign-in or consent redirect target that points off this origin is ignored (#13580): one table
3 * of hostile `next` values, walked through every door that reads one — the sign-in POST, the
4 * `/login` and `/sign-in` aliases, the sign-in and sign-up forms, the OAuth consent page and the
5 * everyday-account switch — each landing on `/` (or the door with no `next`), while a deep link
6 * with a query string still goes where it was going.
7 */
8 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
9 import { mkdtemp, rm } from "node:fs/promises";
10 import { tmpdir } from "node:os";
11 import { join } from "node:path";
12 import { signUp } from "../src/actions/users.ts";
13 import { createApp, type App } from "../src/app.ts";
14 import { serve, type Servers } from "../src/http/server.ts";
15 import { safeNext } from "../src/web/return_to.ts";
16 import { fixtureSlot } from "./helpers/slot.ts";
17
18 /** Each is decoded once by `searchParams.get`, as the door reads it. */
19 const HOSTILE = [
20 "//evil.example",
21 "//evil.example/x?y=1",
22 "https://evil.example",
23 "http:evil.example",
24 "javascript:alert(1)",
25 "/\\evil.example",
26 "\\\\evil.example",
27 "/\t/evil.example",
28 "/\n/evil.example",
29 "/\r\n/evil.example",
30 "/\u0000/evil.example",
31 "%2F%2Fevil.example",
32 "%2f%2fevil.example",
33 "///evil.example",
34 " //evil.example",
35 "evil.example",
36 ];
37
38 /** Deep links that must keep working, query string and all. */
39 const GOOD = ["/kim/proj/issues?state=open&q=a%20b", "/settings/keys", "/oauth/authorize?client_id=c&state=s"];
40
41 test("safeNext refuses every hostile form and keeps every deep link", () => {
42 for (const bad of HOSTILE) expect([bad, safeNext(bad)]).toEqual([bad, undefined]);
43 for (const good of GOOD) expect(safeNext(good)).toBe(good);
44 });
45
46 describe("every door that reads a return address", () => {
47 let dataDir: string;
48 let app: App;
49 let servers: Servers;
50 let base: string;
51
52 beforeAll(async () => {
53 dataDir = await mkdtemp(join(tmpdir(), "forge-redirect-targets-"));
54 app = createApp({ dataDir, port: 0 });
55 servers = await serve(app);
56 base = servers.url;
57 const kim = await signUp(app, { username: "kim", email: "[email protected]", password: "a-long-passphrase" }, { slot: fixtureSlot(app) });
58 if (!kim.ok) throw new Error("signup failed");
59 });
60
61 afterAll(async () => {
62 servers.stop();
63 app.close();
64 await rm(dataDir, { recursive: true, force: true });
65 });
66
67 const q = (next: string) => new URLSearchParams({ next }).toString();
68 const get = (path: string) => fetch(`${base}${path}`, { redirect: "manual" });
69 const signIn = (next: string) =>
70 fetch(`${base}/signin?${q(next)}`, {
71 method: "POST",
72 headers: { origin: base },
73 body: new URLSearchParams({ username: "kim", password: "a-long-passphrase" }),
74 redirect: "manual",
75 });
76
77 test("POST /signin lands a hostile next on / and a deep link on itself", async () => {
78 for (const bad of HOSTILE) {
79 const res = await signIn(bad);
80 expect([bad, res.status, res.headers.get("location")]).toEqual([bad, 303, "/"]);
81 }
82 for (const good of GOOD) expect((await signIn(good)).headers.get("location")).toBe(good);
83 });
84
85 test("/login and /sign-in drop a hostile next and keep a deep link", async () => {
86 for (const alias of ["/login", "/sign-in"]) {
87 for (const bad of HOSTILE) expect([bad, (await get(`${alias}?${q(bad)}`)).headers.get("location")]).toEqual([bad, "/signin"]);
88 for (const good of GOOD) expect((await get(`${alias}?${q(good)}`)).headers.get("location")).toBe(`/signin?${q(good)}`);
89 }
90 });
91
92 test("the sign-in and sign-up forms carry no hostile next anywhere on the page", async () => {
93 for (const door of ["/signin", "/signup"]) {
94 for (const bad of HOSTILE) {
95 const body = await (await get(`${door}?${q(bad)}`)).text();
96 expect([door, bad, body.includes("evil.example")]).toEqual([door, bad, false]);
97 }
98 const body = await (await get(`${door}?${q(GOOD[0]!)}`)).text();
99 expect(body).toContain(`next=${encodeURIComponent(GOOD[0]!)}`.replaceAll("&", "&"));
100 }
101 });
102
103 test("the OAuth consent page sends a signed-out person to sign in and back to itself only", async () => {
104 for (const bad of HOSTILE) {
105 const res = await get(`/oauth/authorize?client_id=nobody&response_type=code&${new URLSearchParams({ redirect_uri: bad, next: bad })}`);
106 const location = res.headers.get("location") ?? "";
107 expect([bad, location.startsWith("/signin?next=%2Foauth%2Fauthorize")]).toEqual([bad, true]);
108 expect(safeNext(new URL(location, base).searchParams.get("next"))).toStartWith("/oauth/authorize?");
109 }
110 });
111
112 test("the everyday-account switch sends a signed-out person to sign in, never off-site", async () => {
113 for (const bad of HOSTILE) {
114 const res = await fetch(`${base}/settings/everyday/switch?${q(bad)}`, { method: "POST", headers: { origin: base }, redirect: "manual" });
115 const location = res.headers.get("location") ?? "";
116 expect([bad, location.startsWith("/signin?next=%2Fsettings%2Feveryday%2Fswitch")]).toEqual([bad, true]);
117 }
118 });
119 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs