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

A device-flow short link redirects only to the origin's own host, for a bounded time #15013

Merged opened this

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

Merged

scout/forge:scout/14952-a-device-flow-short-link-redirects-only → main 1 commit fork

  • Merged. scout/14952-a-device-flow-short-link-redirects-only was merged into main as edc33eb.

Review

Sign in to review this change.
4 files changed +156 −4
src/origins/oauth.ts +54 −3
@@ -148,15 +148,66 @@ export async function startDevice(
148148 if (deviceCode === "" || userCode === "" || uri === "") {
149149 return err(fault(body.value, "the origin did not start a device flow"));
150150 }
151 const verificationUri = onOriginHost(app, uri);
152 if (verificationUri === undefined) {
153 return err({
154 error: "invalid_response",
155 message: "the origin sent a verification address off its own host",
156 });
157 }
151158 return ok({
152159 deviceCode,
153160 userCode,
154 verificationUri: uri,
155 intervalSecs: Math.max(num(body.value, "interval") || 5, 1),
156 expiresInSecs: num(body.value, "expires_in") || 900,
161 verificationUri,
162 intervalSecs: clamp(num(body.value, "interval") || 5, 1, MAX_DEVICE_INTERVAL_SECS),
163 expiresInSecs: clamp(num(body.value, "expires_in") || 900, 1, MAX_DEVICE_EXPIRES_SECS),
157164 });
158165 }
159166
167 /**
168 * A device flow's short link (`/go/<code>`) redirects anonymously to the
169 * verification address and lives as long as `expires_in` says, so neither is
170 * the origin's to choose freely. RFC 8628 suggests 15 minutes; GitHub uses
171 * exactly that.
172 */
173 export const MAX_DEVICE_EXPIRES_SECS = 15 * 60;
174 /** Polling slower than this is a flow nobody would wait for. */
175 export const MAX_DEVICE_INTERVAL_SECS = 60;
176
177 const clamp = (n: number, lo: number, hi: number): number =>
178 Math.min(Math.max(n, lo), hi);
179
180 /**
181 * The verification address, normalised, when it is on one of the hosts this
182 * origin was registered with (its web or API URL) over https; plaintext only
183 * when the registered web URL is itself plaintext on that same origin, which
184 * discovery allows only for loopback or an operator-named host. Undefined
185 * for anything else: a foreign host, credentials in the URL, another scheme.
186 */
187 export function onOriginHost(app: AppRegistration, raw: string): string | undefined {
188 let url: URL;
189 try {
190 url = new URL(raw);
191 } catch {
192 return undefined;
193 }
194 if (url.username !== "" || url.password !== "") return undefined;
195 const configured: URL[] = [];
196 for (const base of [app.webUrl, app.apiUrl]) {
197 try {
198 configured.push(new URL(base));
199 } catch {
200 // An unparseable registration contributes no host.
201 }
202 }
203 const fits = configured.some((base) =>
204 url.protocol === "https:"
205 ? url.hostname === base.hostname
206 : url.protocol === "http:" && base.protocol === "http:" && url.host === base.host,
207 );
208 return fits ? url.href : undefined;
209 }
210
160211 /**
161212 * One poll. `pending` and `slow_down` are the normal states of a flow whose
162213 * human has not finished yet — the worker treats them as "call again",
test/fake-origin.ts +5 −1
@@ -1316,7 +1316,9 @@ export function newFakeOAuth(clientId: string, secret = ""): FakeOAuth {
13161316 clientSecret: secret,
13171317 deviceCode: "device-code-abc",
13181318 userCode: "WXYZ-1234",
1319 verificationUri: "https://example.invalid/device",
1319 // Filled in with this server's own `/login/device` on the first start,
1320 // since a verification address off the origin's host is refused.
1321 verificationUri: "",
13201322 intervalSecs: 1,
13211323 approved: false,
13221324 slowDownOnce: false,
@@ -1348,6 +1350,8 @@ export function oauthRoute(
13481350 if (url.pathname === "/login/device/code" && request.method === "POST") {
13491351 if (form.client_id !== oauth.clientId)
13501352 return jsonResponse({ error: "Not Found" });
1353 if (oauth.verificationUri === "")
1354 oauth.verificationUri = `${url.origin}/login/device`;
13511355 return jsonResponse({
13521356 device_code: oauth.deviceCode,
13531357 user_code: oauth.userCode,
test/oauth-device-target.test.ts added +94
@@ -0,0 +1,94 @@
1 import { afterAll, describe, expect, test } from "bun:test";
2 import {
3 MAX_DEVICE_EXPIRES_SECS,
4 MAX_DEVICE_INTERVAL_SECS,
5 onOriginHost,
6 startDevice,
7 type AppRegistration,
8 } from "../src/origins/oauth.ts";
9
10 /**
11 * A device flow's verification address becomes an anonymous `/go/<code>`
12 * redirect that lives for `expires_in`; an origin may not point it at
13 * another host, nor keep it alive for years (#14952, from #14771).
14 */
15
16 let reply: Record<string, unknown> = {};
17 const server = Bun.serve({
18 port: 0,
19 hostname: "127.0.0.1",
20 fetch: () => Response.json(reply),
21 });
22 afterAll(() => server.stop(true));
23
24 const web = `http://127.0.0.1:${server.port}`;
25 const app: AppRegistration = {
26 kind: "github",
27 apiUrl: `${web}/api/v3`,
28 webUrl: web,
29 clientId: "Iv1.test",
30 clientSecret: "",
31 };
32 const started = (fields: Record<string, unknown>) => {
33 reply = { device_code: "dc", user_code: "UC-1", ...fields };
34 return startDevice(app, "repo");
35 };
36
37 describe("startDevice keeps the short link on the origin, briefly", () => {
38 test("a foreign verification_uri is refused", async () => {
39 const r = await started({ verification_uri: "https://phish.example/login", expires_in: 900 });
40 expect(r.ok).toBe(false);
41 if (!r.ok) expect(r.error.error).toBe("invalid_response");
42 });
43
44 test("a foreign verification_uri_complete is refused even beside a good one", async () => {
45 const r = await started({
46 verification_uri: `${web}/login/device`,
47 verification_uri_complete: "https://phish.example/?code=UC-1",
48 });
49 expect(r.ok).toBe(false);
50 });
51
52 test("a huge expires_in and interval are clamped", async () => {
53 const r = await started({
54 verification_uri: `${web}/login/device`,
55 expires_in: 315_360_000,
56 interval: 86_400,
57 });
58 expect(r.ok).toBe(true);
59 if (!r.ok) return;
60 expect(r.value.verificationUri).toBe(`${web}/login/device`);
61 expect(r.value.expiresInSecs).toBe(MAX_DEVICE_EXPIRES_SECS);
62 expect(r.value.intervalSecs).toBe(MAX_DEVICE_INTERVAL_SECS);
63 });
64 });
65
66 describe("onOriginHost", () => {
67 const gh: AppRegistration = {
68 kind: "github",
69 apiUrl: "https://api.github.com",
70 webUrl: "https://github.com",
71 clientId: "x",
72 clientSecret: "",
73 };
74 test("accepts the web or API host over https", () => {
75 expect(onOriginHost(gh, "https://github.com/login/device")).toBe("https://github.com/login/device");
76 expect(onOriginHost(gh, "https://api.github.com/x")).toBe("https://api.github.com/x");
77 });
78 test("refuses plaintext, other hosts, look-alikes, credentials and other schemes", () => {
79 for (const bad of [
80 "http://github.com/login/device",
81 "https://github.com.evil.example/login/device",
82 "https://evil.example/github.com",
83 "https://user:[email protected]/login/device",
84 "javascript:alert(1)",
85 "//github.com/login/device",
86 "not a url",
87 ])
88 expect(onOriginHost(gh, bad)).toBeUndefined();
89 });
90 test("plaintext only on a plaintext registration's exact origin", () => {
91 expect(onOriginHost(app, `${web}/login/device`)).toBe(`${web}/login/device`);
92 expect(onOriginHost(app, "http://127.0.0.1:1/login/device")).toBeUndefined();
93 });
94 });
test/origin-broker.test.ts +3
@@ -145,6 +145,9 @@ beforeAll(async () => {
145145 code = { fake: serveFakeForge(forgejo), oauth: forgejoOauth };
146146 const github = newFakeState("github", LOGIN, "unused-pat");
147147 const githubOauth = newFakeOAuth(CLIENT_ID);
148 // The parent sees this fake as `https://localhost`: the verification address must sit on that
149 // host.
150 githubOauth.verificationUri = "https://localhost/login/device";
148151 github.oauth = githubOauth;
149152 device = { fake: serveFakeForge(github), oauth: githubOauth };
150153 current = code;

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs