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

Sign in with your forge: a forge in the fork tree signs people in through its parent's OpenID provider #1886

Parked opened this
Closed without merging

scout/forge:scout/748-sign-in-with-your-forge-a-forge-in-the-f → main 4 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
10 files changed +783 −0
README.md +11
@@ -123,6 +123,17 @@ The relying party is the address the browser used (or
123123 `FORGE_URL`), so a passkey does not follow a forge to another hostname.
124124 Sign-up is a username, an email address and a passkey (`/signup`, `src/web/pages/signup-passkey.ts`); the running server refuses a password-only sign-up on the form, `POST /api/v1/users` and the terminal (`passkeyOnlySignup`, set in `main.ts`). Accounts that already have a password still sign in. Two paths still make an account without a passkey and are the next step: the owner claim of a spawned forge (`web/pages/claim.ts`) and an admin's everyday account (`web/pages/everyday.ts`).
125125
126 A forge with a parent (`FORGE_PARENT_URL`, or the `upstream` in a spawned
127 forge's `parent.json`) offers "Continue with <parent>" on `/signin`. The forge
128 registers itself once at the parent's `/oauth/register` (the client id is kept
129 in `rp_client`), sends the person through the parent's authorize page with
130 PKCE, and on return checks state (also bound to the browser by an HttpOnly
131 cookie), nonce, `iss`, `aud`, `exp` and the ES256 signature against the
132 parent's JWKS (`kernel/jwt.ts`; keys are cached ten minutes and an unknown
133 `kid` refetches them once a minute at most). The parent's `sub` — never the
134 username — maps to a local account made on first sight with no password
135 (`core/federation.ts`; `http/rp.ts` has the two routes). No dependency added.
136
126137 Your SSH key is your identity. A key the forge knows signs you straight in; any
127138 other key browses public repos as a guest and can press `s` to sign in with a
128139 username and password — which links that key to your account, so the next
scripts/gate.ts +1
@@ -338,6 +338,7 @@ export const GATE: readonly string[] = [
338338 "test/flags.test.ts",
339339 "test/home-feed.test.ts",
340340 "test/home-walk.test.ts",
341 "test/forge-signin.test.ts",
341342 "test/oauth-discovery.test.ts",
342343 "test/oauth-flow.test.ts",
343344 "test/oidc.test.ts",
src/core/federation.ts added +142
@@ -0,0 +1,142 @@
1 /**
2 * Signing in through another forge (#748): what this forge, as a relying
3 * party, keeps. The client id it was given at the issuer (one per redirect
4 * address), a sign-in in flight (the state only as a hash, so a leaked
5 * database starts nothing), and which local account an issuer's `sub` is.
6 * The username is never the key: it can be renamed, and a name the parent
7 * frees may be taken by someone else.
8 */
9 import type { Database } from "bun:sqlite";
10 import { readFileSync } from "node:fs";
11 import { join } from "node:path";
12 import { sha256 } from "../kernel/hash.ts";
13 import { parentUrlProblem } from "./parent_releases.ts";
14 import { createUser, getUserById, getUserByName, isActive, type User } from "./users.ts";
15
16 /** A sign-in not finished in this long is gone. */
17 export const LOGIN_TTL_MS = 10 * 60_000;
18 /** The most sign-ins in flight at once; the oldest make room. */
19 export const LOGIN_MAX = 1000;
20 /** A `sub` we accept: an id, not free text. */
21 export const SUB = /^[A-Za-z0-9_-]{1,64}$/;
22
23 export const clientFor = (db: Database, issuer: string, redirectUri: string): string | undefined =>
24 db
25 .query<{ client_id: string }, [string, string]>(
26 "SELECT client_id FROM rp_client WHERE issuer = ?1 AND redirect_uri = ?2",
27 )
28 .get(issuer, redirectUri)?.client_id;
29
30 /** Keep the first client id for an address; a racing second registration loses. */
31 export function keepClient(db: Database, issuer: string, redirectUri: string, clientId: string): string {
32 db.query(
33 "INSERT INTO rp_client (issuer, redirect_uri, client_id) VALUES (?1, ?2, ?3) ON CONFLICT DO NOTHING",
34 ).run(issuer, redirectUri, clientId);
35 return clientFor(db, issuer, redirectUri) ?? clientId;
36 }
37
38 export interface Login {
39 readonly verifier: string;
40 readonly nonce: string;
41 readonly issuer: string;
42 readonly redirectUri: string;
43 }
44
45 export function startLogin(db: Database, state: string, login: Login, now = Date.now()): void {
46 db.query("DELETE FROM rp_login WHERE expires_at <= ?1").run(now);
47 db.query(
48 `DELETE FROM rp_login WHERE state_hash IN
49 (SELECT state_hash FROM rp_login ORDER BY expires_at LIMIT max(0, (SELECT count(*) FROM rp_login) - ?1))`,
50 ).run(LOGIN_MAX - 1);
51 db.query(
52 "INSERT INTO rp_login (state_hash, verifier, nonce, issuer, redirect_uri, expires_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
53 ).run(sha256(state), login.verifier, login.nonce, login.issuer, login.redirectUri, now + LOGIN_TTL_MS);
54 }
55
56 /** The sign-in a state began, used up by asking: a state works once. */
57 export function takeLogin(db: Database, state: string, now = Date.now()): Login | undefined {
58 const row = db
59 .query<
60 { verifier: string; nonce: string; issuer: string; redirect_uri: string; expires_at: number },
61 [string]
62 >("DELETE FROM rp_login WHERE state_hash = ?1 RETURNING verifier, nonce, issuer, redirect_uri, expires_at")
63 .get(sha256(state));
64 if (row === null || row.expires_at <= now) return undefined;
65 return { verifier: row.verifier, nonce: row.nonce, issuer: row.issuer, redirectUri: row.redirect_uri };
66 }
67
68 /** A local username for a parent's person: their name if free and fit, else made unique by their `sub`. */
69 async function makeAccount(db: Database, sub: string, preferred: string): Promise<User | undefined> {
70 const base = preferred.toLowerCase().replace(/[^a-z0-9.-]/g, "").replace(/^[.-]+/, "").slice(0, 30);
71 const tail = sub.toLowerCase().replace(/[^a-z0-9]/g, "").slice(-8);
72 for (const username of [base, `${base}-${tail}`, `user-${tail}`]) {
73 if (username === "" || username.startsWith("-")) continue;
74 if (getUserByName(db, username) !== undefined) continue;
75 const made = await createUser(db, {
76 username,
77 // Unique, never mailed: `.invalid` is reserved and resolves nowhere.
78 email: `${sub.toLowerCase()}@sso.invalid`,
79 displayName: preferred,
80 });
81 if (made.ok) return made.value;
82 }
83 return undefined;
84 }
85
86 const making = new Map<string, Promise<User | undefined>>();
87
88 /**
89 * The local account for an issuer's `sub`, made on first sight with no
90 * password. Two returns of the same person at once make one account.
91 */
92 export function accountFor(
93 db: Database,
94 issuer: string,
95 sub: string,
96 preferred: string,
97 ): Promise<User | undefined> {
98 const key = `${issuer}\0${sub}`;
99 const pending = making.get(key);
100 if (pending !== undefined) return pending;
101 const attempt = (async (): Promise<User | undefined> => {
102 const known = db
103 .query<{ user_id: string }, [string, string]>(
104 "SELECT user_id FROM federated_identity WHERE issuer = ?1 AND sub = ?2",
105 )
106 .get(issuer, sub);
107 if (known !== null) {
108 const user = getUserById(db, known.user_id);
109 return user !== undefined && isActive(user) ? user : undefined;
110 }
111 const made = await makeAccount(db, sub, preferred);
112 if (made === undefined) return undefined;
113 db.query("INSERT INTO federated_identity (issuer, sub, user_id) VALUES (?1, ?2, ?3)").run(
114 issuer,
115 sub,
116 made.id,
117 );
118 return made;
119 })();
120 making.set(key, attempt);
121 void attempt.finally(() => making.delete(key));
122 return attempt;
123 }
124
125 /** The parent forge's origin: the address this forge was started with, or the spawn record's. Undefined for a forge with none. */
126 export function parentIssuerOf(config: {
127 parentUrl?: string;
128 parentLoopback?: boolean;
129 dataDir: string;
130 }): string | undefined {
131 let raw = config.parentUrl;
132 if (raw === undefined) {
133 try {
134 const doc = JSON.parse(readFileSync(join(config.dataDir, "parent.json"), "utf8")) as { upstream?: unknown };
135 if (typeof doc.upstream === "string") raw = doc.upstream;
136 } catch {
137 return undefined;
138 }
139 }
140 if (raw === undefined || parentUrlProblem(raw, config.parentLoopback === true) !== null) return undefined;
141 return new URL(raw).origin;
142 }
src/core/migrations/20261016130000-sign-in-with-the-parent.ts added +25
@@ -0,0 +1,25 @@
1 // Sign in with the parent forge (#748, core/federation.ts): the client id this
2 // forge was given at its parent, a sign-in in flight (state kept only as a
3 // hash), and which local account a parent's `sub` is.
4 export default `
5 CREATE TABLE rp_client (
6 issuer TEXT NOT NULL,
7 redirect_uri TEXT NOT NULL,
8 client_id TEXT NOT NULL,
9 PRIMARY KEY (issuer, redirect_uri)
10 ) WITHOUT ROWID;
11 CREATE TABLE rp_login (
12 state_hash TEXT PRIMARY KEY,
13 verifier TEXT NOT NULL,
14 nonce TEXT NOT NULL,
15 issuer TEXT NOT NULL,
16 redirect_uri TEXT NOT NULL,
17 expires_at INTEGER NOT NULL
18 ) WITHOUT ROWID;
19 CREATE TABLE federated_identity (
20 issuer TEXT NOT NULL,
21 sub TEXT NOT NULL,
22 user_id TEXT NOT NULL REFERENCES user(id) ON DELETE CASCADE,
23 PRIMARY KEY (issuer, sub)
24 ) WITHOUT ROWID;
25 `;
src/http/jwks.ts added +51
@@ -0,0 +1,51 @@
1 /**
2 * Another forge's signing keys, fetched once and kept. A key id that is not
3 * in what was kept may mean the issuer rotated, so the set is fetched again
4 * — once, and not again for a minute however many tokens name an unknown
5 * kid, so a forged token cannot make this forge hammer its parent.
6 */
7 import type { Jwk } from "../kernel/jwt.ts";
8
9 export const JWKS_FRESH_MS = 10 * 60_000;
10 export const JWKS_REFETCH_MS = 60_000;
11 const BODY_MAX = 64 * 1024;
12
13 export type Fetch = (url: string, init?: RequestInit) => Promise<Response>;
14
15 export class KeySet {
16 private keys: Jwk[] = [];
17 private at = -Infinity;
18 private pending: Promise<void> | undefined;
19
20 constructor(
21 private readonly url: string,
22 private readonly fetcher: Fetch = fetch,
23 ) {}
24
25 async find(kid: string, now = Date.now()): Promise<Jwk | undefined> {
26 const kept = (): Jwk | undefined => this.keys.find((k) => k["kid"] === kid);
27 if (now - this.at < JWKS_FRESH_MS && kept() !== undefined) return kept();
28 if (now - this.at >= JWKS_REFETCH_MS) await this.load(now);
29 return kept();
30 }
31
32 private load(now: number): Promise<void> {
33 this.pending ??= (async () => {
34 try {
35 const res = await this.fetcher(this.url, { redirect: "error", signal: AbortSignal.timeout(5000) });
36 if (!res.ok) return;
37 const text = await res.text();
38 if (text.length > BODY_MAX) return;
39 const list = (JSON.parse(text) as { keys?: unknown }).keys;
40 if (!Array.isArray(list)) return;
41 this.keys = list.filter((k): k is Jwk => typeof k === "object" && k !== null);
42 this.at = now;
43 } catch {
44 // Unreachable or malformed: keep what we had; the caller refuses the token.
45 } finally {
46 this.pending = undefined;
47 }
48 })();
49 return this.pending;
50 }
51 }
src/http/rp.ts added +196
@@ -0,0 +1,196 @@
1 /**
2 * Continue with the parent forge (#748): this forge as a relying party of
3 * the OpenID provider its parent already is. `/signin/parent` registers
4 * this forge at the parent once (the client id is kept), then sends the
5 * person there with a state, a nonce and a PKCE challenge; the state also
6 * rides in an HttpOnly cookie so only the browser that began can finish.
7 * `/signin/parent/callback` trades the code, checks the id_token (state,
8 * nonce, iss, aud, exp, signature against the parent's JWKS) and signs in
9 * the local account the parent's `sub` maps to, made on first sight.
10 * Both are GETs that change nothing a stranger could use: a callback with
11 * no matching cookie and state is refused before anything is fetched.
12 */
13 import { createHash, randomBytes } from "node:crypto";
14 import type { App } from "../app.ts";
15 import {
16 accountFor,
17 clientFor,
18 keepClient,
19 parentIssuerOf,
20 SUB,
21 startLogin,
22 takeLogin,
23 } from "../core/federation.ts";
24 import { createSession } from "../core/sessions.ts";
25 import { verifyJwt } from "../kernel/jwt.ts";
26 import { html } from "../web/html.ts";
27 import { page, redirect } from "../web/layout.ts";
28 import { sessionCookie } from "../web/pages/site.ts";
29 import { cookieValue, type Ctx } from "./context.ts";
30 import { KeySet } from "./jwks.ts";
31
32 export const STATE_COOKIE = "forge_rp";
33 const SCOPE = "openid profile";
34 const rand = (bytes: number): string => randomBytes(bytes).toString("base64url");
35
36 const parentIssuer = (app: App): string | undefined => parentIssuerOf(app.config);
37
38 const keySets = new WeakMap<App, Map<string, KeySet>>();
39 const keysOf = (app: App, issuer: string): KeySet => {
40 let sets = keySets.get(app);
41 if (sets === undefined) keySets.set(app, (sets = new Map()));
42 let set = sets.get(issuer);
43 if (set === undefined) sets.set(issuer, (set = new KeySet(`${issuer}/oauth/jwks`)));
44 return set;
45 };
46
47 const redirectUriOf = (ctx: Ctx): string => `${ctx.url.origin}/signin/parent/callback`;
48
49 /** The client id at the issuer for this address, registering once if there is none. */
50 const registering = new Map<string, Promise<string>>();
51 async function clientId(ctx: Ctx, issuer: string, redirectUri: string): Promise<string> {
52 const known = clientFor(ctx.app.db, issuer, redirectUri);
53 if (known !== undefined) return known;
54 const key = `${issuer}\0${redirectUri}`;
55 let pending = registering.get(key);
56 if (pending === undefined) {
57 pending = (async () => {
58 const res = await fetch(`${issuer}/oauth/register`, {
59 method: "POST",
60 headers: { "content-type": "application/json" },
61 body: JSON.stringify({
62 client_name: ctx.url.host.slice(0, 100),
63 redirect_uris: [redirectUri],
64 }),
65 redirect: "error",
66 signal: AbortSignal.timeout(5000),
67 });
68 const body = (await res.json()) as { client_id?: unknown };
69 if (res.status !== 201 || typeof body.client_id !== "string" || body.client_id === "")
70 throw new Error(`registration refused (${res.status})`);
71 return keepClient(ctx.app.db, issuer, redirectUri, body.client_id);
72 })();
73 registering.set(key, pending);
74 void pending.then(
75 () => registering.delete(key),
76 () => registering.delete(key),
77 );
78 }
79 return pending;
80 }
81
82 function failure(ctx: Ctx, message: string, status: number): Response {
83 const response = page(
84 {
85 ctx,
86 title: "Sign in",
87 body: html`<div class="narrow">
88 <div class="page-head"><h1>Could not sign you in</h1></div>
89 <p role="alert">${message}</p>
90 <p><a href="/signin">Back to sign in</a></p>
91 </div>`,
92 },
93 status,
94 );
95 response.headers.set("cache-control", "no-store");
96 return response;
97 }
98
99 const cookieHeader = (value: string, maxAge: number, url: URL, forgeUrl?: string): string => {
100 const secure = url.protocol === "https:" || forgeUrl?.startsWith("https://") ? "; Secure" : "";
101 return `${STATE_COOKIE}=${value}; Path=/signin/parent; HttpOnly; SameSite=Lax; Max-Age=${maxAge}${secure}`;
102 };
103
104 export async function parentStart(ctx: Ctx): Promise<Response> {
105 const issuer = parentIssuer(ctx.app);
106 if (issuer === undefined) return failure(ctx, "This forge has no parent to sign in through.", 404);
107 const redirectUri = redirectUriOf(ctx);
108 let client: string;
109 try {
110 client = await clientId(ctx, issuer, redirectUri);
111 } catch {
112 return failure(ctx, "The parent forge could not be reached.", 502);
113 }
114 const state = rand(24);
115 const verifier = rand(48);
116 const nonce = rand(24);
117 startLogin(ctx.app.db, state, { verifier, nonce, issuer, redirectUri });
118 const query = new URLSearchParams({
119 response_type: "code",
120 client_id: client,
121 redirect_uri: redirectUri,
122 scope: SCOPE,
123 state,
124 nonce,
125 code_challenge: createHash("sha256").update(verifier).digest("base64url"),
126 code_challenge_method: "S256",
127 });
128 const headers = new Headers({
129 location: `${issuer}/oauth/authorize?${query}`,
130 "cache-control": "no-store",
131 });
132 headers.append("set-cookie", cookieHeader(state, 600, ctx.url, ctx.app.config.url));
133 return new Response(null, { status: 303, headers });
134 }
135
136 const clean = (s: unknown, max: number): string =>
137 // eslint-disable-next-line no-control-regex
138 typeof s === "string" ? s.replace(/[\u0000-\u001f\u007f]/g, "").trim().slice(0, max) : "";
139
140 export async function parentCallback(ctx: Ctx): Promise<Response> {
141 const q = ctx.url.searchParams;
142 const state = q.get("state") ?? "";
143 const code = q.get("code") ?? "";
144 // The cookie is the browser that began; without it nothing is fetched or spent.
145 if (state === "" || state !== cookieValue(ctx.request, STATE_COOKIE))
146 return failure(ctx, "This sign-in did not start in this browser.", 400);
147 const login = takeLogin(ctx.app.db, state);
148 const clear = cookieHeader("", 0, ctx.url, ctx.app.config.url);
149 const refuse = (message: string, status = 400): Response => {
150 const response = failure(ctx, message, status);
151 response.headers.append("set-cookie", clear);
152 return response;
153 };
154 if (login === undefined || login.issuer !== parentIssuer(ctx.app) || login.redirectUri !== redirectUriOf(ctx))
155 return refuse("This sign-in took too long or was already used.");
156 if (q.has("error") || code === "" || code.length > 512)
157 return refuse("The parent forge did not sign you in.");
158 try {
159 const client = await clientId(ctx, login.issuer, login.redirectUri);
160 const res = await fetch(`${login.issuer}/oauth/token`, {
161 method: "POST",
162 body: new URLSearchParams({
163 grant_type: "authorization_code",
164 code,
165 client_id: client,
166 redirect_uri: login.redirectUri,
167 code_verifier: login.verifier,
168 }),
169 redirect: "error",
170 signal: AbortSignal.timeout(5000),
171 });
172 const body = (await res.json()) as { id_token?: unknown };
173 if (!res.ok || typeof body.id_token !== "string")
174 return refuse("The parent forge did not accept the sign-in.", 502);
175 const keys = keysOf(ctx.app, login.issuer);
176 const verified = await verifyJwt(
177 body.id_token,
178 (kid) => keys.find(kid),
179 { issuer: login.issuer, audience: client, nonce: login.nonce },
180 );
181 if (!verified.ok) return refuse("The parent forge's answer did not verify.", 502);
182 const sub = verified.value["sub"];
183 if (typeof sub !== "string" || !SUB.test(sub))
184 return refuse("The parent forge's answer did not verify.", 502);
185 const name = clean(verified.value["preferred_username"], 64);
186 const user = await accountFor(ctx.app.db, login.issuer, sub, name);
187 if (user === undefined) return refuse("An account for you could not be made or is not allowed in.", 403);
188 const session = createSession(ctx.app.db, user.id);
189 const done = redirect("/", sessionCookie(session.token, session.expiresAt, ctx.url, ctx.app.config.url));
190 done.headers.append("set-cookie", clear);
191 done.headers.set("cache-control", "no-store");
192 return done;
193 } catch {
194 return refuse("The parent forge could not be reached.", 502);
195 }
196 }
src/http/server.ts +3
@@ -8,6 +8,7 @@
88 import { signupOptions, signupPasskey } from "../web/pages/signup-passkey.ts";
99 import { TOOLBAR_NAME, toolbarResponse } from "../apps/toolbar.ts";
1010 import { unsealReleased } from "../actions/sealed.ts";
11 import { parentCallback, parentStart } from "./rp.ts";
1112 import { accessPage } from "../web/pages/access.ts";
1213 import { capacityPage, capacitySet } from "../web/pages/capacity.ts";
1314 import { flowPage } from "../web/pages/flow.ts";
@@ -605,6 +606,8 @@ export function buildRouter(): Router<Handler> {
605606 router.add("POST", "/front", frontUpdate);
606607 router.add("GET", "/signin", signinPage);
607608 router.add("POST", "/signin", signinSubmit);
609 router.add("GET", "/signin/parent", parentStart);
610 router.add("GET", "/signin/parent/callback", parentCallback);
608611 router.add("GET", "/signup", signupPage);
609612 router.add("GET", "/verify", verifyPage);
610613 router.add("POST", "/signup", signupSubmit);
src/kernel/jwt.ts added +63
@@ -0,0 +1,63 @@
1 /**
2 * Verifying a JWT someone else signed: ES256 only, the key looked up by
3 * `kid` through a function the caller gives (so where keys come from — a
4 * cache, a fetch, a test — is not this file's business), then the claims a
5 * relying party must check: issuer, audience, expiry and, when asked, nonce.
6 * Anything off is `invalid_token`; the reason is not told to the caller.
7 */
8 import { err, ok, type Result } from "./result.ts";
9
10 export type Jwk = Record<string, unknown>;
11
12 export interface JwtExpect {
13 readonly issuer: string;
14 readonly audience: string;
15 readonly nonce?: string;
16 }
17
18 const KEY = { name: "ECDSA", namedCurve: "P-256" } as const;
19 const SIGN = { name: "ECDSA", hash: "SHA-256" } as const;
20 const SEGMENT = /^[A-Za-z0-9_-]+$/;
21
22 const decode = (part: string): Record<string, unknown> => {
23 const parsed: unknown = JSON.parse(Buffer.from(part, "base64url").toString());
24 if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed))
25 throw new Error("not an object");
26 return parsed as Record<string, unknown>;
27 };
28
29 export async function verifyJwt(
30 jwt: string,
31 keyFor: (kid: string) => Promise<Jwk | undefined>,
32 expect: JwtExpect,
33 now = Date.now(),
34 ): Promise<Result<Record<string, unknown>, "invalid_token">> {
35 const parts = jwt.split(".");
36 if (parts.length !== 3 || !parts.every((p) => SEGMENT.test(p)))
37 return err("invalid_token");
38 try {
39 const head = decode(parts[0]!);
40 if (head["alg"] !== "ES256" || typeof head["kid"] !== "string")
41 return err("invalid_token");
42 const jwk = await keyFor(head["kid"]);
43 if (jwk === undefined) return err("invalid_token");
44 const pub = await crypto.subtle.importKey("jwk", jwk as never, KEY, false, ["verify"]);
45 const good = await crypto.subtle.verify(
46 SIGN,
47 pub,
48 Buffer.from(parts[2]!, "base64url"),
49 new TextEncoder().encode(`${parts[0]}.${parts[1]}`),
50 );
51 if (!good) return err("invalid_token");
52 const claims = decode(parts[1]!);
53 if (claims["iss"] !== expect.issuer || claims["aud"] !== expect.audience)
54 return err("invalid_token");
55 if (typeof claims["exp"] !== "number" || claims["exp"] * 1000 <= now)
56 return err("invalid_token");
57 if (expect.nonce !== undefined && claims["nonce"] !== expect.nonce)
58 return err("invalid_token");
59 return ok(claims);
60 } catch {
61 return err("invalid_token");
62 }
63 }
src/web/pages/site.ts +10
@@ -45,6 +45,7 @@ import {
4545 import { existsSync } from "node:fs";
4646 import { join } from "node:path";
4747 import { hasAdmin } from "../../spawn/claim.ts";
48 import { parentIssuerOf } from "../../core/federation.ts";
4849
4950 export function sessionCookie(
5051 value: string,
@@ -368,6 +369,15 @@ function authForm(
368369 <a class="small" href="/recover">Lost your device?</a>
369370 </p>`,
370371 )}
372 ${when(
373 kind === "signin" ? parentIssuerOf(ctx.app.config) : undefined,
374 (parent) => html`<p class="mt">
375 ${btn(`Continue with ${new URL(parent).host}`, {
376 href: "/signin/parent",
377 variant: "outline",
378 })}
379 </p>`,
380 )}
371381 ${claimable
372382 ? html`<p class="muted small mt" id="claim-door">
373383 Was this forge made for you? <a href="/claim">Claim it with your code</a>.
test/forge-signin.test.ts added +281
@@ -0,0 +1,281 @@
1 /**
2 * Sign in with your forge (#748): two forges booted, a person signed into the
3 * child through the parent's OpenID provider. The id_token's checks are tried
4 * one spoiled claim at a time, and the parent's keys are fetched once and
5 * again only for a key id they do not hold.
6 */
7 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
8 import { mkdtemp, rm } from "node:fs/promises";
9 import { tmpdir } from "node:os";
10 import { join } from "node:path";
11 import { createApp, type App } from "../src/app.ts";
12 import { createSession } from "../src/core/sessions.ts";
13 import { createUser, getUserByName, verifyPassword } from "../src/core/users.ts";
14 import { KeySet } from "../src/http/jwks.ts";
15 import { serve, type Servers } from "../src/http/server.ts";
16 import { verifyJwt } from "../src/kernel/jwt.ts";
17 import { quietLogs } from "./helpers/globals.ts";
18
19 quietLogs();
20
21 const PASSWORD = "a-long-family-passphrase";
22
23 describe("sign in through the parent forge", () => {
24 let dirs: string[] = [];
25 let parent: App;
26 let child: App;
27 let parentServers: Servers;
28 let childServers: Servers;
29 let alice = "";
30 let aliceCookie = "";
31
32 const cookieOf = (res: Response, name: string): string | undefined =>
33 res.headers
34 .getSetCookie()
35 .map((c) => c.split(";")[0]!)
36 .find((c) => c.startsWith(`${name}=`));
37
38 /** Begin at the child, consent at the parent as the person with `cookie`; the child's callback address and its state cookie. */
39 const begin = async (cookie: string) => {
40 const start = await fetch(`${childServers.url}/signin/parent`, { redirect: "manual" });
41 expect(start.status).toBe(303);
42 const to = new URL(start.headers.get("location")!);
43 expect(to.origin).toBe(parentServers.url);
44 expect(to.pathname).toBe("/oauth/authorize");
45 const state = cookieOf(start, "forge_rp")!;
46 expect(state).toBeDefined();
47 const consent = await fetch(`${parentServers.url}/oauth/authorize`, {
48 method: "POST",
49 redirect: "manual",
50 headers: { cookie, origin: parentServers.url },
51 body: new URLSearchParams({
52 ...Object.fromEntries(to.searchParams),
53 decision: "allow",
54 grant: "ro",
55 name: "child",
56 lifetime: "never",
57 }),
58 });
59 expect(consent.status).toBe(303);
60 return { callback: new URL(consent.headers.get("location")!), state };
61 };
62 const finish = (callback: URL, state: string | undefined) =>
63 fetch(`${childServers.url}${callback.pathname}${callback.search}`, {
64 redirect: "manual",
65 headers: state === undefined ? {} : { cookie: state },
66 });
67
68 beforeAll(async () => {
69 const make = async () => {
70 const dir = await mkdtemp(join(tmpdir(), "forge-signin-"));
71 dirs.push(dir);
72 return dir;
73 };
74 parent = createApp({ dataDir: await make(), port: 0 });
75 parentServers = await serve(parent);
76 child = createApp({
77 dataDir: await make(),
78 port: 0,
79 parentUrl: parentServers.url,
80 parentLoopback: true,
81 });
82 childServers = await serve(child);
83 const made = await createUser(parent.db, {
84 username: "alice",
85 email: "[email protected]",
86 password: PASSWORD,
87 adminIfFirst: true,
88 });
89 if (!made.ok) throw new Error(made.error);
90 alice = made.value.id;
91 aliceCookie = `forge_session=${createSession(parent.db, alice).token}`;
92 });
93 afterAll(async () => {
94 parentServers.stop();
95 childServers.stop();
96 for (const dir of dirs) await rm(dir, { recursive: true, force: true });
97 });
98
99 test("only a forge with a parent offers the button", async () => {
100 const onChild = await (await fetch(`${childServers.url}/signin`)).text();
101 expect(onChild).toContain(`Continue with ${new URL(parentServers.url).host}`);
102 expect(onChild).toContain('href="/signin/parent"');
103 expect(await (await fetch(`${parentServers.url}/signin`)).text()).not.toContain("Continue with");
104 const none = await fetch(`${parentServers.url}/signin/parent`, { redirect: "manual" });
105 expect(none.status).toBe(404);
106 });
107
108 test("a person signs into the child through the parent, and the account keys on sub", async () => {
109 const { callback, state } = await begin(aliceCookie);
110 expect(callback.origin).toBe(childServers.url);
111 const done = await finish(callback, state);
112 expect(done.status).toBe(303);
113 expect(done.headers.get("location")).toBe("/");
114 const session = cookieOf(done, "forge_session")!;
115 expect(session).toBeDefined();
116 expect(done.headers.getSetCookie().find((c) => c.startsWith("forge_session="))).toContain("HttpOnly");
117
118 const local = getUserByName(child.db, "alice")!;
119 expect(local.id).not.toBe("");
120 // No password was ever set: only the parent vouches for this account.
121 expect((await verifyPassword(child.db, "alice", "")).ok).toBe(false);
122 expect((await verifyPassword(child.db, "alice", PASSWORD)).ok).toBe(false);
123 const settings = await fetch(`${childServers.url}/settings`, { headers: { cookie: session }, redirect: "manual" });
124 expect(settings.status).toBe(200);
125
126 // Renamed at the parent, the same person is the same local account.
127 parent.db.query("UPDATE user SET username = 'alice-renamed' WHERE id = ?1").run(alice);
128 const again = await begin(aliceCookie);
129 const second = await finish(again.callback, again.state);
130 expect(second.status).toBe(303);
131 expect(getUserByName(child.db, "alice-renamed")).toBeUndefined();
132 expect(child.db.query("SELECT COUNT(*) AS n FROM user WHERE username LIKE 'alice%'").get()).toEqual({ n: 1 });
133 // Registered at the parent once, and the id kept.
134 expect(parent.db.query("SELECT COUNT(*) AS n FROM oauth_client").get()).toEqual({ n: 1 });
135 expect(child.db.query("SELECT COUNT(*) AS n FROM rp_client").get()).toEqual({ n: 1 });
136 parent.db.query("UPDATE user SET username = 'alice' WHERE id = ?1").run(alice);
137 });
138
139 test("a parent's name that is taken here does not take over the local account", async () => {
140 const bob = await createUser(parent.db, { username: "bob", email: "[email protected]", password: PASSWORD });
141 if (!bob.ok) throw new Error(bob.error);
142 const local = await createUser(child.db, { username: "bob", email: "[email protected]", password: PASSWORD });
143 if (!local.ok) throw new Error(local.error);
144 const { callback, state } = await begin(`forge_session=${createSession(parent.db, bob.value.id).token}`);
145 const done = await finish(callback, state);
146 expect(done.status).toBe(303);
147 const row = child.db
148 .query<{ user_id: string }, [string]>("SELECT user_id FROM federated_identity WHERE sub = ?1")
149 .get(bob.value.id)!;
150 expect(row.user_id).not.toBe(local.value.id);
151 });
152
153 test("a callback is refused without its browser's cookie, with another state, or a second time", async () => {
154 const { callback, state } = await begin(aliceCookie);
155 expect((await finish(callback, undefined)).status).toBe(400);
156 expect((await finish(callback, "forge_rp=other")).status).toBe(400);
157 const sessions = () => child.db.query("SELECT COUNT(*) AS n FROM session").get();
158 const before = sessions();
159 expect((await finish(callback, state)).status).toBe(303);
160 const replay = await finish(callback, state);
161 expect(replay.status).toBe(400);
162 expect(cookieOf(replay, "forge_session")).toBeUndefined();
163 expect(sessions()).toEqual({ n: (before as { n: number }).n + 1 });
164 });
165
166 test("a nonce that is not the one this browser sent is refused", async () => {
167 const { callback, state } = await begin(aliceCookie);
168 child.db.query("UPDATE rp_login SET nonce = 'not-the-nonce'").run();
169 const done = await finish(callback, state);
170 expect(done.status).toBe(502);
171 expect(cookieOf(done, "forge_session")).toBeUndefined();
172 });
173
174 test("an error from the parent, or no code, signs no one in", async () => {
175 const { state } = await begin(aliceCookie);
176 const value = state.slice("forge_rp=".length);
177 const done = await finish(new URL(`${childServers.url}/signin/parent/callback?state=${value}&error=access_denied`), state);
178 expect(done.status).toBe(400);
179 expect(cookieOf(done, "forge_session")).toBeUndefined();
180 });
181 });
182
183 describe("verifyJwt", () => {
184 const b64 = (v: unknown) => Buffer.from(typeof v === "string" ? v : JSON.stringify(v)).toString("base64url");
185 let pair: CryptoKeyPair;
186 let jwk: Record<string, unknown>;
187 const now = 1_700_000_000_000;
188 const expectation = { issuer: "https://p", audience: "c1", nonce: "n1" };
189
190 beforeAll(async () => {
191 pair = (await crypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, true, ["sign", "verify"])) as CryptoKeyPair;
192 jwk = { ...(await crypto.subtle.exportKey("jwk", pair.publicKey)), kid: "k1" };
193 });
194 const mint = async (claims: Record<string, unknown> = {}, head: Record<string, unknown> = {}) => {
195 const h = b64({ alg: "ES256", kid: "k1", ...head });
196 const p = b64({ iss: "https://p", aud: "c1", nonce: "n1", sub: "s", exp: now / 1000 + 60, ...claims });
197 const sig = await crypto.subtle.sign({ name: "ECDSA", hash: "SHA-256" }, pair.privateKey, new TextEncoder().encode(`${h}.${p}`));
198 return `${h}.${p}.${Buffer.from(sig).toString("base64url")}`;
199 };
200 const keys = async (kid: string) => (kid === "k1" ? jwk : undefined);
201
202 test("a good token passes", async () => {
203 const out = await verifyJwt(await mint(), keys, expectation, now);
204 expect(out.ok && out.value["sub"]).toBe("s");
205 });
206
207 test("each spoiled claim, key and signature is refused", async () => {
208 const good = await mint();
209 const [h, p, s] = good.split(".");
210 const forged = `${h}.${b64({ iss: "https://p", aud: "c1", nonce: "n1", sub: "root", exp: now / 1000 + 60 })}.${s}`;
211 const cases: [string, string][] = [
212 ["wrong iss", await mint({ iss: "https://evil" })],
213 ["wrong aud", await mint({ aud: "c2" })],
214 ["wrong nonce", await mint({ nonce: "n2" })],
215 ["no nonce", await mint({ nonce: undefined })],
216 ["expired", await mint({ exp: now / 1000 - 1 })],
217 ["no exp", await mint({ exp: undefined })],
218 ["unknown kid", await mint({}, { kid: "k2" })],
219 ["alg none", await mint({}, { alg: "none" })],
220 ["alg HS256", await mint({}, { alg: "HS256" })],
221 ["tampered payload", forged],
222 ["two parts", `${h}.${p}`],
223 ["not base64", "a.b.c!"],
224 ];
225 for (const [name, jwt] of cases) {
226 const out = await verifyJwt(jwt, keys, expectation, now);
227 expect([name, out.ok]).toEqual([name, false]);
228 }
229 // A key that is not the signer's refuses a good token.
230 const other = (await crypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, true, ["sign", "verify"])) as CryptoKeyPair;
231 const otherJwk = { ...(await crypto.subtle.exportKey("jwk", other.publicKey)), kid: "k1" };
232 expect((await verifyJwt(good, async () => otherJwk, expectation, now)).ok).toBe(false);
233 });
234 });
235
236 describe("a parent's keys, cached", () => {
237 const set = (keys: string[]) => {
238 const calls: string[] = [];
239 const fetcher = async (url: string) => {
240 calls.push(url);
241 return Response.json({ keys: keys.map((kid) => ({ kid, kty: "EC" })) });
242 };
243 return { calls, fetcher };
244 };
245
246 test("fetched once, then served from memory", async () => {
247 const { calls, fetcher } = set(["a", "b"]);
248 const keys = new KeySet("https://p/oauth/jwks", fetcher);
249 expect((await keys.find("a", 1000))?.["kid"]).toBe("a");
250 expect((await keys.find("b", 2000))?.["kid"]).toBe("b");
251 expect((await keys.find("a", 3000))?.["kid"]).toBe("a");
252 expect(calls).toHaveLength(1);
253 });
254
255 test("an unknown kid looks again once, and not again within the minute", async () => {
256 const live = set(["a"]);
257 const keys = new KeySet("https://p/oauth/jwks", live.fetcher);
258 await keys.find("a", 0);
259 // The parent rotated: the next fetch has the new key.
260 const rotated = set(["a", "b"]);
261 (keys as unknown as { fetcher: unknown }).fetcher = rotated.fetcher;
262 expect(await keys.find("b", 70_000)).toBeDefined();
263 expect(rotated.calls).toHaveLength(1);
264 // A kid nobody has: one more look at most, then none for a minute.
265 expect(await keys.find("zzz", 140_000)).toBeUndefined();
266 expect(await keys.find("zzz", 141_000)).toBeUndefined();
267 expect(await keys.find("yyy", 150_000)).toBeUndefined();
268 expect(rotated.calls).toHaveLength(2);
269 });
270
271 test("an unreachable parent keeps the keys it had", async () => {
272 const good = set(["a"]);
273 const keys = new KeySet("https://p/oauth/jwks", good.fetcher);
274 await keys.find("a", 0);
275 (keys as unknown as { fetcher: unknown }).fetcher = async () => {
276 throw new Error("down");
277 };
278 expect(await keys.find("nope", 100_000)).toBeUndefined();
279 expect(await keys.find("a", 100_001)).toBeDefined();
280 });
281 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs