Public: anyone can read this; the crew can change it.
One authorization server in the forge: people, agents, MCP clients, hosted apps, and later other forges #1404
scout/forge:scout/666-one-authorization-server-in-the-forge-pe → main 1 commit fork
9 files
changed +432
−8
docs/MCP.md +12
| @@ -109,6 +109,18 @@ can call `apps` and is refused `tell`. | ||
| 109 | 109 | |
| 110 | 110 | `src/http/mcp.ts`, `src/actions/tell.ts`, `test/mcp.test.ts`. |
| 111 | 111 | |
| 112 | ## Signing in with the forge (OpenID Connect) | |
| 113 | ||
| 114 | The same server is an OpenID Connect provider. A hosted app or another forge | |
| 115 | reads `/.well-known/openid-configuration`, sends the person to | |
| 116 | `/oauth/authorize` with `scope=openid` (and a `nonce`), exchanges the code at | |
| 117 | `/oauth/token`, and gets an ES256 `id_token` beside the access token. Verify | |
| 118 | it against `/oauth/jwks`; `/oauth/userinfo` answers `sub`, | |
| 119 | `preferred_username` and `name` for a bearer token and stops answering the | |
| 120 | moment the token is revoked. Signing keys rotate after 30 days (a retired key | |
| 121 | stays published ten minutes more); the private half is sealed with the data | |
| 122 | key. Not yet: refresh tokens, and `email` in the claims. | |
| 123 | ||
| 112 | 124 | ## `plan` |
| 113 | 125 | |
| 114 | 126 | Opens several small issues and their links in one transaction. Each item is |
scripts/gate.ts +1
| @@ -207,6 +207,7 @@ export const GATE: readonly string[] = [ | ||
| 207 | 207 | "test/home-feed.test.ts", |
| 208 | 208 | "test/oauth-discovery.test.ts", |
| 209 | 209 | "test/oauth-flow.test.ts", |
| 210 | "test/oidc.test.ts", | |
| 210 | 211 | "test/data-home.test.ts", |
| 211 | 212 | "test/tree.test.ts", |
| 212 | 213 | "test/reports.test.ts", |
src/core/oauth.ts +33 −5
| @@ -158,11 +158,15 @@ export interface AuthRequest { | ||
| 158 | 158 | readonly challenge: string; |
| 159 | 159 | readonly state: string; |
| 160 | 160 | readonly scope: OAuthScope; |
| 161 | /** The client asked for the `openid` scope: it wants an id_token too. */ | |
| 162 | readonly openid: boolean; | |
| 163 | readonly nonce: string; | |
| 161 | 164 | } |
| 162 | 165 | |
| 163 | 166 | const CHALLENGE = /^[A-Za-z0-9_-]{43}$/; |
| 164 | 167 | const VERIFIER = /^[A-Za-z0-9._~-]{43,128}$/; |
| 165 | 168 | const STATE_MAX = 1000; |
| 169 | const NONCE_MAX = 500; | |
| 166 | 170 | |
| 167 | 171 | /** |
| 168 | 172 | * Check the untrusted parameters of an authorization request. Anything wrong |
| @@ -188,8 +192,18 @@ export function parseAuthRequest( | ||
| 188 | 192 | return err("The code_challenge is not a base64url SHA-256."); |
| 189 | 193 | const state = get("state"); |
| 190 | 194 | if (state.length > STATE_MAX) return err("The state is too long."); |
| 191 | const asked = get("scope").split(/\s+/).find(isOAuthScope); | |
| 192 | return ok({ client, redirectUri, challenge, state, scope: asked ?? "ro" }); | |
| 195 | const nonce = get("nonce"); | |
| 196 | if (nonce.length > NONCE_MAX) return err("The nonce is too long."); | |
| 197 | const scopes = get("scope").split(/\s+/); | |
| 198 | return ok({ | |
| 199 | client, | |
| 200 | redirectUri, | |
| 201 | challenge, | |
| 202 | state, | |
| 203 | scope: scopes.find(isOAuthScope) ?? "ro", | |
| 204 | openid: scopes.includes("openid"), | |
| 205 | nonce, | |
| 206 | }); | |
| 193 | 207 | } |
| 194 | 208 | |
| 195 | 209 | /** The name a person gave a token: plain text, bounded, never empty. */ |
| @@ -219,8 +233,8 @@ export function issueCode( | ||
| 219 | 233 | ): string { |
| 220 | 234 | const code = secret(); |
| 221 | 235 | db.query( |
| 222 | `INSERT INTO oauth_code (code_hash, client_id, user_id, redirect_uri, challenge, scope, name, lifetime_s, expires_at) | |
| 223 | VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)`, | |
| 236 | `INSERT INTO oauth_code (code_hash, client_id, user_id, redirect_uri, challenge, scope, name, lifetime_s, expires_at, openid, nonce) | |
| 237 | VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11)`, | |
| 224 | 238 | ).run( |
| 225 | 239 | sha256(code), |
| 226 | 240 | request.client.id, |
| @@ -231,6 +245,8 @@ export function issueCode( | ||
| 231 | 245 | grant.name, |
| 232 | 246 | grant.lifetimeS, |
| 233 | 247 | new Date(Date.now() + CODE_TTL_MS).toISOString(), |
| 248 | request.openid ? 1 : 0, | |
| 249 | request.nonce, | |
| 234 | 250 | ); |
| 235 | 251 | db.query("DELETE FROM oauth_code WHERE expires_at <= ?1").run( |
| 236 | 252 | new Date().toISOString(), |
| @@ -240,6 +256,9 @@ export function issueCode( | ||
| 240 | 256 | |
| 241 | 257 | export interface Minted { |
| 242 | 258 | readonly token: string; |
| 259 | readonly userId: string; | |
| 260 | readonly openid: boolean; | |
| 261 | readonly nonce: string; | |
| 243 | 262 | readonly scope: OAuthScope; |
| 244 | 263 | /** Seconds the token lives, or null for one that does not expire. */ |
| 245 | 264 | readonly expiresIn: number | null; |
| @@ -270,6 +289,8 @@ export function redeemCode( | ||
| 270 | 289 | name: string; |
| 271 | 290 | lifetime_s: number | null; |
| 272 | 291 | expires_at: string; |
| 292 | openid: number; | |
| 293 | nonce: string; | |
| 273 | 294 | }, |
| 274 | 295 | [string] |
| 275 | 296 | >("DELETE FROM oauth_code WHERE code_hash = ?1 RETURNING *") |
| @@ -288,5 +309,12 @@ export function redeemCode( | ||
| 288 | 309 | ? {} |
| 289 | 310 | : { expiresAt: new Date(Date.now() + row.lifetime_s * 1000).toISOString() }), |
| 290 | 311 | }); |
| 291 | return ok({ token: minted.token, scope: row.scope, expiresIn: row.lifetime_s }); | |
| 312 | return ok({ | |
| 313 | token: minted.token, | |
| 314 | userId: row.user_id, | |
| 315 | openid: row.openid === 1, | |
| 316 | nonce: row.nonce, | |
| 317 | scope: row.scope, | |
| 318 | expiresIn: row.lifetime_s, | |
| 319 | }); | |
| 292 | 320 | } |
src/core/oidc.ts added +134
| @@ -0,0 +1,134 @@ | ||
| 1 | /** | |
| 2 | * The forge as an OpenID Connect provider: ES256 signing keys that rotate, | |
| 3 | * the JWKS that publishes them, and the id_token a hosted app (or another | |
| 4 | * forge) verifies to know who signed in. Keys live in the database with the | |
| 5 | * private half sealed by the data-dir key; nothing here reads the edge. | |
| 6 | */ | |
| 7 | import type { Database } from "bun:sqlite"; | |
| 8 | import { id } from "../kernel/id.ts"; | |
| 9 | import { open, seal } from "../kernel/secret.ts"; | |
| 10 | import type { User } from "./users.ts"; | |
| 11 | ||
| 12 | /** A key signs for a month, then a new one takes over. */ | |
| 13 | export const KEY_LIFE_MS = 30 * 86_400_000; | |
| 14 | /** An id_token is good for ten minutes: it proves a sign-in, it is not a session. */ | |
| 15 | export const ID_TOKEN_TTL_S = 600; | |
| 16 | /** A retired key stays published as long as a token it signed could live. */ | |
| 17 | const RETIRED_GRACE_MS = ID_TOKEN_TTL_S * 1000 + 60_000; | |
| 18 | ||
| 19 | const ALG = { name: "ECDSA", namedCurve: "P-256" } as const; | |
| 20 | const b64 = (bytes: ArrayBuffer | Uint8Array | string): string => | |
| 21 | Buffer.from(typeof bytes === "string" ? bytes : new Uint8Array(bytes)).toString("base64url"); | |
| 22 | ||
| 23 | interface KeyRow { | |
| 24 | kid: string; | |
| 25 | private_enc: string; | |
| 26 | public_jwk: string; | |
| 27 | created_at: string; | |
| 28 | retired_at: string | null; | |
| 29 | } | |
| 30 | ||
| 31 | /** Make a new signing key and retire the ones before it. */ | |
| 32 | export async function rotateKey(db: Database, dataDir: string): Promise<string> { | |
| 33 | const pair = await crypto.subtle.generateKey(ALG, true, ["sign", "verify"]); | |
| 34 | const kid = id(); | |
| 35 | const priv = JSON.stringify(await crypto.subtle.exportKey("jwk", pair.privateKey)); | |
| 36 | const pub = await crypto.subtle.exportKey("jwk", pair.publicKey); | |
| 37 | const now = new Date().toISOString(); | |
| 38 | db.transaction(() => { | |
| 39 | db.query("UPDATE oidc_key SET retired_at = ?1 WHERE retired_at IS NULL").run(now); | |
| 40 | db.query( | |
| 41 | "INSERT INTO oidc_key (kid, private_enc, public_jwk, created_at) VALUES (?1, ?2, ?3, ?4)", | |
| 42 | ).run( | |
| 43 | kid, | |
| 44 | seal(dataDir, priv, kid), | |
| 45 | JSON.stringify({ kty: pub.kty, crv: pub.crv, x: pub.x, y: pub.y }), | |
| 46 | now, | |
| 47 | ); | |
| 48 | })(); | |
| 49 | return kid; | |
| 50 | } | |
| 51 | ||
| 52 | /** The key that signs now: the newest, replaced once it is a month old. */ | |
| 53 | async function activeKey(db: Database, dataDir: string): Promise<KeyRow> { | |
| 54 | const row = db | |
| 55 | .query<KeyRow, []>( | |
| 56 | "SELECT * FROM oidc_key WHERE retired_at IS NULL ORDER BY created_at DESC LIMIT 1", | |
| 57 | ) | |
| 58 | .get(); | |
| 59 | if (row !== null && Date.now() - Date.parse(row.created_at) < KEY_LIFE_MS) | |
| 60 | return row; | |
| 61 | await rotateKey(db, dataDir); | |
| 62 | return activeKey(db, dataDir); | |
| 63 | } | |
| 64 | ||
| 65 | /** The public keys a verifier may need: the active one and any still-fresh retired ones. */ | |
| 66 | export async function jwks( | |
| 67 | db: Database, | |
| 68 | dataDir: string, | |
| 69 | ): Promise<{ keys: Record<string, string>[] }> { | |
| 70 | await activeKey(db, dataDir); | |
| 71 | const cutoff = new Date(Date.now() - RETIRED_GRACE_MS).toISOString(); | |
| 72 | const rows = db | |
| 73 | .query<KeyRow, [string]>( | |
| 74 | "SELECT * FROM oidc_key WHERE retired_at IS NULL OR retired_at > ?1 ORDER BY created_at DESC", | |
| 75 | ) | |
| 76 | .all(cutoff); | |
| 77 | return { | |
| 78 | keys: rows.map((r) => ({ | |
| 79 | ...(JSON.parse(r.public_jwk) as Record<string, string>), | |
| 80 | kid: r.kid, | |
| 81 | use: "sig", | |
| 82 | alg: "ES256", | |
| 83 | })), | |
| 84 | }; | |
| 85 | } | |
| 86 | ||
| 87 | export interface IdTokenInput { | |
| 88 | readonly issuer: string; | |
| 89 | readonly clientId: string; | |
| 90 | readonly user: User; | |
| 91 | readonly nonce: string; | |
| 92 | } | |
| 93 | ||
| 94 | /** The claims about a person that userinfo and the id_token share. */ | |
| 95 | export const profileClaims = (user: User): Record<string, string> => ({ | |
| 96 | sub: user.id, | |
| 97 | preferred_username: user.username, | |
| 98 | name: user.displayName === "" ? user.username : user.displayName, | |
| 99 | }); | |
| 100 | ||
| 101 | export async function signIdToken( | |
| 102 | db: Database, | |
| 103 | dataDir: string, | |
| 104 | input: IdTokenInput, | |
| 105 | ): Promise<string> { | |
| 106 | const row = await activeKey(db, dataDir); | |
| 107 | const opened = open(dataDir, row.private_enc, row.kid); | |
| 108 | if (!opened.ok) throw new Error("the signing key cannot be opened"); | |
| 109 | const key = await crypto.subtle.importKey( | |
| 110 | "jwk", | |
| 111 | JSON.parse(opened.value), | |
| 112 | ALG, | |
| 113 | false, | |
| 114 | ["sign"], | |
| 115 | ); | |
| 116 | const iat = Math.floor(Date.now() / 1000); | |
| 117 | const header = b64(JSON.stringify({ alg: "ES256", typ: "JWT", kid: row.kid })); | |
| 118 | const body = b64( | |
| 119 | JSON.stringify({ | |
| 120 | iss: input.issuer, | |
| 121 | aud: input.clientId, | |
| 122 | iat, | |
| 123 | exp: iat + ID_TOKEN_TTL_S, | |
| 124 | ...profileClaims(input.user), | |
| 125 | ...(input.nonce === "" ? {} : { nonce: input.nonce }), | |
| 126 | }), | |
| 127 | ); | |
| 128 | const sig = await crypto.subtle.sign( | |
| 129 | { name: "ECDSA", hash: "SHA-256" }, | |
| 130 | key, | |
| 131 | new TextEncoder().encode(`${header}.${body}`), | |
| 132 | ); | |
| 133 | return `${header}.${body}.${b64(sig)}`; | |
| 134 | } |
src/core/schema.ts +16
| @@ -1578,6 +1578,22 @@ export const migrations: readonly string[] = [ | ||
| 1578 | 1578 | expires_at TEXT NOT NULL |
| 1579 | 1579 | ); |
| 1580 | 1580 | `, |
| 1581 | ||
| 1582 | // 74 — the forge as an OpenID Connect provider (#666): the signing keys | |
| 1583 | // (private half sealed with the data-dir key, bound to the key id; a | |
| 1584 | // retired key stays published until tokens signed by it have expired), | |
| 1585 | // and what an authorization code needs to remember to mint an id_token. | |
| 1586 | ` | |
| 1587 | CREATE TABLE oidc_key ( | |
| 1588 | kid TEXT PRIMARY KEY, | |
| 1589 | private_enc TEXT NOT NULL, | |
| 1590 | public_jwk TEXT NOT NULL, | |
| 1591 | created_at TEXT NOT NULL, | |
| 1592 | retired_at TEXT | |
| 1593 | ); | |
| 1594 | ALTER TABLE oauth_code ADD COLUMN openid INTEGER NOT NULL DEFAULT 0; | |
| 1595 | ALTER TABLE oauth_code ADD COLUMN nonce TEXT NOT NULL DEFAULT ''; | |
| 1596 | `, | |
| 1581 | 1597 | ]; |
| 1582 | 1598 | |
| 1583 | 1599 | /** |
src/http/oauth.ts +53 −2
| @@ -9,6 +9,9 @@ | ||
| 9 | 9 | * checked on its POST. |
| 10 | 10 | */ |
| 11 | 11 | import type { App } from "../app.ts"; |
| 12 | import { signIdToken, jwks, profileClaims } from "../core/oidc.ts"; | |
| 13 | import { verifyToken } from "../core/tokens.ts"; | |
| 14 | import { getUserById } from "../core/users.ts"; | |
| 12 | 15 | import { createClient, parseRegistration, redeemCode } from "../core/oauth.ts"; |
| 13 | 16 | import { RateLimiter } from "../core/ratelimit.ts"; |
| 14 | 17 | import type { Handler } from "./context.ts"; |
| @@ -78,11 +81,24 @@ export function oauthRoutes(router: Router<Handler>): void { | ||
| 78 | 81 | verifier: get("code_verifier"), |
| 79 | 82 | }); |
| 80 | 83 | if (!minted.ok) return grantError(minted.error); |
| 84 | const user = getUserById(ctx.app.db, minted.value.userId); | |
| 85 | const idToken = | |
| 86 | minted.value.openid && user !== undefined | |
| 87 | ? await signIdToken(ctx.app.db, ctx.app.config.dataDir, { | |
| 88 | issuer: ctx.url.origin, | |
| 89 | clientId: get("client_id"), | |
| 90 | user, | |
| 91 | nonce: minted.value.nonce, | |
| 92 | }) | |
| 93 | : null; | |
| 81 | 94 | return json( |
| 82 | 95 | { |
| 83 | 96 | access_token: minted.value.token, |
| 84 | 97 | token_type: "Bearer", |
| 85 | scope: minted.value.scope, | |
| 98 | scope: minted.value.openid | |
| 99 | ? `openid ${minted.value.scope}` | |
| 100 | : minted.value.scope, | |
| 101 | ...(idToken === null ? {} : { id_token: idToken }), | |
| 86 | 102 | ...(minted.value.expiresIn === null |
| 87 | 103 | ? {} |
| 88 | 104 | : { expires_in: minted.value.expiresIn }), |
| @@ -91,6 +107,41 @@ export function oauthRoutes(router: Router<Handler>): void { | ||
| 91 | 107 | noStore, |
| 92 | 108 | ); |
| 93 | 109 | }); |
| 110 | router.add("GET", "/oauth/jwks", async (ctx) => | |
| 111 | json(await jwks(ctx.app.db, ctx.app.config.dataDir), 200, docHeaders), | |
| 112 | ); | |
| 113 | router.add("GET", "/oauth/userinfo", (ctx) => { | |
| 114 | const match = /^Bearer (\S+)$/.exec(ctx.request.headers.get("authorization") ?? ""); | |
| 115 | const verdict = match === null ? null : verifyToken(ctx.app.db, match[1]!); | |
| 116 | if (verdict === null || !verdict.ok) | |
| 117 | return json({ error: "invalid_token" }, 401, { | |
| 118 | ...noStore, | |
| 119 | "www-authenticate": 'Bearer error="invalid_token"', | |
| 120 | }); | |
| 121 | return json(profileClaims(verdict.value.user), 200, noStore); | |
| 122 | }); | |
| 123 | router.add("GET", "/.well-known/openid-configuration", (ctx) => | |
| 124 | json( | |
| 125 | { | |
| 126 | issuer: ctx.url.origin, | |
| 127 | authorization_endpoint: `${ctx.url.origin}/oauth/authorize`, | |
| 128 | token_endpoint: `${ctx.url.origin}/oauth/token`, | |
| 129 | userinfo_endpoint: `${ctx.url.origin}/oauth/userinfo`, | |
| 130 | jwks_uri: `${ctx.url.origin}/oauth/jwks`, | |
| 131 | registration_endpoint: `${ctx.url.origin}/oauth/register`, | |
| 132 | scopes_supported: ["openid", "ro", "rw"], | |
| 133 | response_types_supported: ["code"], | |
| 134 | grant_types_supported: ["authorization_code"], | |
| 135 | subject_types_supported: ["public"], | |
| 136 | id_token_signing_alg_values_supported: ["ES256"], | |
| 137 | claims_supported: ["sub", "iss", "aud", "iat", "exp", "nonce", "name", "preferred_username"], | |
| 138 | code_challenge_methods_supported: ["S256"], | |
| 139 | token_endpoint_auth_methods_supported: ["none"], | |
| 140 | }, | |
| 141 | 200, | |
| 142 | docHeaders, | |
| 143 | ), | |
| 144 | ); | |
| 94 | 145 | router.add("GET", "/.well-known/oauth-protected-resource", (ctx) => |
| 95 | 146 | json( |
| 96 | 147 | { |
| @@ -110,7 +161,7 @@ export function oauthRoutes(router: Router<Handler>): void { | ||
| 110 | 161 | authorization_endpoint: `${ctx.url.origin}/oauth/authorize`, |
| 111 | 162 | token_endpoint: `${ctx.url.origin}/oauth/token`, |
| 112 | 163 | registration_endpoint: `${ctx.url.origin}/oauth/register`, |
| 113 | scopes_supported: ["ro", "rw"], | |
| 164 | scopes_supported: ["openid", "ro", "rw"], | |
| 114 | 165 | response_types_supported: ["code"], |
| 115 | 166 | grant_types_supported: ["authorization_code"], |
| 116 | 167 | code_challenge_methods_supported: ["S256"], |
src/web/pages/oauth.ts +1
| @@ -29,6 +29,7 @@ const PARAMS = [ | ||
| 29 | 29 | "code_challenge_method", |
| 30 | 30 | "state", |
| 31 | 31 | "scope", |
| 32 | "nonce", | |
| 32 | 33 | ] as const; |
| 33 | 34 | |
| 34 | 35 | /** Nothing here is cacheable, and nothing here may be sent on as a referrer. */ |
test/oauth-discovery.test.ts +1 −1
| @@ -53,7 +53,7 @@ describe("oauth discovery and registration", () => { | ||
| 53 | 53 | expect(doc.token_endpoint).toBe(`${base}/oauth/token`); |
| 54 | 54 | expect(doc.registration_endpoint).toBe(`${base}/oauth/register`); |
| 55 | 55 | expect(doc.code_challenge_methods_supported).toEqual(["S256"]); |
| 56 | expect(doc.scopes_supported).toEqual(["ro", "rw"]); | |
| 56 | expect(doc.scopes_supported).toEqual(["openid", "ro", "rw"]); | |
| 57 | 57 | }); |
| 58 | 58 | |
| 59 | 59 | test("a 401 from /mcp names the resource metadata", async () => { |
test/oidc.test.ts added +181
| @@ -0,0 +1,181 @@ | ||
| 1 | /** | |
| 2 | * The forge as an OpenID Connect provider (#666): discovery, a hosted app | |
| 3 | * signing a person in and verifying the id_token against the JWKS, userinfo, | |
| 4 | * key rotation, and a revoked token that stops working at once. | |
| 5 | */ | |
| 6 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 7 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 8 | import { tmpdir } from "node:os"; | |
| 9 | import { join } from "node:path"; | |
| 10 | import { createApp, type App } from "../src/app.ts"; | |
| 11 | import { rotateKey } from "../src/core/oidc.ts"; | |
| 12 | import { createSession } from "../src/core/sessions.ts"; | |
| 13 | import { listTokens, revokeToken } from "../src/core/tokens.ts"; | |
| 14 | import { createUser } from "../src/core/users.ts"; | |
| 15 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 16 | ||
| 17 | const REDIRECT = "https://app.example/callback"; | |
| 18 | const verifier = "o".repeat(60); | |
| 19 | const challenge = new Bun.CryptoHasher("sha256").update(verifier).digest("base64url"); | |
| 20 | ||
| 21 | describe("openid connect provider", () => { | |
| 22 | let dataDir: string; | |
| 23 | let app: App; | |
| 24 | let servers: Servers; | |
| 25 | let base: string; | |
| 26 | let cookie: string; | |
| 27 | let clientId: string; | |
| 28 | ||
| 29 | beforeAll(async () => { | |
| 30 | dataDir = await mkdtemp(join(tmpdir(), "forge-oidc-")); | |
| 31 | app = createApp({ dataDir, port: 0 }); | |
| 32 | servers = await serve(app); | |
| 33 | base = servers.url; | |
| 34 | const made = await createUser(app.db, { | |
| 35 | trusted: true, | |
| 36 | username: "alice", | |
| 37 | email: "[email protected]", | |
| 38 | password: "a-good-passphrase", | |
| 39 | adminIfFirst: true, | |
| 40 | }); | |
| 41 | if (!made.ok) throw new Error(made.error); | |
| 42 | cookie = `forge_session=${createSession(app.db, made.value.id).token}`; | |
| 43 | const res = await fetch(`${base}/oauth/register`, { | |
| 44 | method: "POST", | |
| 45 | headers: { "content-type": "application/json" }, | |
| 46 | body: JSON.stringify({ client_name: "Hosted app", redirect_uris: [REDIRECT] }), | |
| 47 | }); | |
| 48 | clientId = ((await res.json()) as any).client_id; | |
| 49 | }); | |
| 50 | afterAll(async () => { | |
| 51 | servers.stop(); | |
| 52 | await rm(dataDir, { recursive: true, force: true }); | |
| 53 | }); | |
| 54 | ||
| 55 | /** The app's whole sign-in: consent, code, exchange. */ | |
| 56 | async function signIn(scope: string, nonce = "n-1") { | |
| 57 | const consent = await fetch(`${base}/oauth/authorize`, { | |
| 58 | method: "POST", | |
| 59 | redirect: "manual", | |
| 60 | headers: { cookie, origin: base }, | |
| 61 | body: new URLSearchParams({ | |
| 62 | response_type: "code", | |
| 63 | client_id: clientId, | |
| 64 | redirect_uri: REDIRECT, | |
| 65 | code_challenge: challenge, | |
| 66 | code_challenge_method: "S256", | |
| 67 | state: "s", | |
| 68 | scope, | |
| 69 | nonce, | |
| 70 | decision: "allow", | |
| 71 | grant: "ro", | |
| 72 | name: "hosted app", | |
| 73 | lifetime: "day", | |
| 74 | }), | |
| 75 | }); | |
| 76 | const code = new URL(consent.headers.get("location")!).searchParams.get("code")!; | |
| 77 | const res = await fetch(`${base}/oauth/token`, { | |
| 78 | method: "POST", | |
| 79 | body: new URLSearchParams({ | |
| 80 | grant_type: "authorization_code", | |
| 81 | client_id: clientId, | |
| 82 | redirect_uri: REDIRECT, | |
| 83 | code_verifier: verifier, | |
| 84 | code, | |
| 85 | }), | |
| 86 | }); | |
| 87 | return (await res.json()) as any; | |
| 88 | } | |
| 89 | ||
| 90 | async function verify(jwt: string) { | |
| 91 | const [h, b, s] = jwt.split(".") as [string, string, string]; | |
| 92 | const kid = JSON.parse(Buffer.from(h, "base64url").toString()).kid; | |
| 93 | const { keys } = (await (await fetch(`${base}/oauth/jwks`)).json()) as any; | |
| 94 | const jwk = keys.find((k: any) => k.kid === kid); | |
| 95 | if (jwk === undefined) return null; | |
| 96 | const key = await crypto.subtle.importKey( | |
| 97 | "jwk", | |
| 98 | jwk, | |
| 99 | { name: "ECDSA", namedCurve: "P-256" }, | |
| 100 | false, | |
| 101 | ["verify"], | |
| 102 | ); | |
| 103 | const good = await crypto.subtle.verify( | |
| 104 | { name: "ECDSA", hash: "SHA-256" }, | |
| 105 | key, | |
| 106 | Buffer.from(s, "base64url"), | |
| 107 | new TextEncoder().encode(`${h}.${b}`), | |
| 108 | ); | |
| 109 | return good ? JSON.parse(Buffer.from(b, "base64url").toString()) : null; | |
| 110 | } | |
| 111 | ||
| 112 | test("discovery names the endpoints and the signing algorithm", async () => { | |
| 113 | const doc = (await (await fetch(`${base}/.well-known/openid-configuration`)).json()) as any; | |
| 114 | expect(doc.issuer).toBe(base); | |
| 115 | expect(doc.jwks_uri).toBe(`${base}/oauth/jwks`); | |
| 116 | expect(doc.userinfo_endpoint).toBe(`${base}/oauth/userinfo`); | |
| 117 | expect(doc.scopes_supported).toContain("openid"); | |
| 118 | expect(doc.id_token_signing_alg_values_supported).toEqual(["ES256"]); | |
| 119 | }); | |
| 120 | ||
| 121 | test("an app signs a person in: the id_token verifies against the JWKS", async () => { | |
| 122 | const out = await signIn("openid ro", "nonce-xyz"); | |
| 123 | expect(out.scope).toBe("openid ro"); | |
| 124 | const claims = await verify(out.id_token); | |
| 125 | expect(claims).not.toBeNull(); | |
| 126 | expect(claims.iss).toBe(base); | |
| 127 | expect(claims.aud).toBe(clientId); | |
| 128 | expect(claims.nonce).toBe("nonce-xyz"); | |
| 129 | expect(claims.preferred_username).toBe("alice"); | |
| 130 | expect(claims.exp).toBeGreaterThan(claims.iat); | |
| 131 | const info = await fetch(`${base}/oauth/userinfo`, { | |
| 132 | headers: { authorization: `Bearer ${out.access_token}` }, | |
| 133 | }); | |
| 134 | expect(((await info.json()) as any).sub).toBe(claims.sub); | |
| 135 | }); | |
| 136 | ||
| 137 | test("a tampered id_token does not verify", async () => { | |
| 138 | const out = await signIn("openid"); | |
| 139 | const [h, b, s] = out.id_token.split("."); | |
| 140 | const forged = Buffer.from( | |
| 141 | JSON.stringify({ ...JSON.parse(Buffer.from(b, "base64url").toString()), sub: "someone-else" }), | |
| 142 | ).toString("base64url"); | |
| 143 | expect(await verify(`${h}.${forged}.${s}`)).toBeNull(); | |
| 144 | }); | |
| 145 | ||
| 146 | test("without the openid scope there is no id_token", async () => { | |
| 147 | const out = await signIn("ro"); | |
| 148 | expect(out.id_token).toBeUndefined(); | |
| 149 | expect(out.access_token).toStartWith("forge_"); | |
| 150 | }); | |
| 151 | ||
| 152 | test("a revoked token stops working at once", async () => { | |
| 153 | const out = await signIn("openid"); | |
| 154 | const ask = () => | |
| 155 | fetch(`${base}/oauth/userinfo`, { headers: { authorization: `Bearer ${out.access_token}` } }); | |
| 156 | expect((await ask()).status).toBe(200); | |
| 157 | const mine = listTokens(app.db, ((await (await ask()).json()) as any).sub); | |
| 158 | for (const t of mine) revokeToken(app.db, t.id); | |
| 159 | expect((await ask()).status).toBe(401); | |
| 160 | const none = await fetch(`${base}/oauth/userinfo`); | |
| 161 | expect(none.status).toBe(401); | |
| 162 | }); | |
| 163 | ||
| 164 | test("rotation: new tokens use the new key, old ones still verify", async () => { | |
| 165 | const before = await signIn("openid"); | |
| 166 | const oldKid = JSON.parse(Buffer.from(before.id_token.split(".")[0], "base64url").toString()).kid; | |
| 167 | const newKid = await rotateKey(app.db, dataDir); | |
| 168 | const after = await signIn("openid"); | |
| 169 | const kidOf = (t: string) => JSON.parse(Buffer.from(t.split(".")[0]!, "base64url").toString()).kid; | |
| 170 | expect(kidOf(after.id_token)).toBe(newKid); | |
| 171 | expect(newKid).not.toBe(oldKid); | |
| 172 | expect(await verify(before.id_token)).not.toBeNull(); | |
| 173 | expect(await verify(after.id_token)).not.toBeNull(); | |
| 174 | }); | |
| 175 | ||
| 176 | test("the private key is not in the database in the clear", () => { | |
| 177 | const row = app.db.query<{ private_enc: string }, []>("SELECT private_enc FROM oidc_key LIMIT 1").get()!; | |
| 178 | expect(row.private_enc.startsWith("v1:")).toBe(true); | |
| 179 | expect(row.private_enc).not.toContain('"d"'); | |
| 180 | }); | |
| 181 | }); |
new above
offline