diff --git a/lib/auth.ts b/lib/auth.ts index 5b16f41..e1d7c80 100644 --- a/lib/auth.ts +++ b/lib/auth.ts @@ -15,6 +15,9 @@ export const LOGIN_PAGE = "/"; export const CONSENT_PAGE = "/consent"; export const ERROR_PAGE = "/problem"; +/** How long an authorization code can be redeemed. The plugin's default is ten minutes. */ +export const CODE_TTL_SECONDS = 60; + /** * How a client secret is kept: SHA-256, never the secret itself. Stated here * (rather than left to the plugin's default) because `syncClients` (lib/sync-clients.ts) writes @@ -130,6 +133,18 @@ export async function createSigninAuth(options: CreateSigninAuthOptions) { pairwiseSecret: config.pairwiseSecret, grantTypes: ["authorization_code", "refresh_token"], allowDynamicClientRegistration: false, + // Exact string match against the client's registered list, nothing + // else. The plugin's own check also forgives the PORT of a loopback + // address (RFC 8252, for native apps); no client here is native, and + // that forgiveness would let one app's localhost address stand in for + // another's. A refusal lands on the error page (ERROR_PAGE), never on + // the rejected address. The registered list is what lib/sync-clients.ts + // writes from lib/clients.ts `redirectUris()`, so this is the same test + // as `isRegisteredRedirect()`. + validateRedirectUri: (requested: string, registered: readonly string[]) => registered.includes(requested), + // A code is redeemed by the app's server seconds after it is issued, + // once, for the redirect URI it was bound to (the plugin enforces both). + codeExpiresIn: CODE_TTL_SECONDS, // Clients are the registry's rows (lib/clients.ts, lib/sync-clients.ts). storeClientSecret: { hash: async (secret: string) => hashClientSecret(secret) }, customUserInfoClaims: ({ user, jwt: token }) => { diff --git a/test/flow.test.ts b/test/flow.test.ts index aed85ea..1762499 100644 --- a/test/flow.test.ts +++ b/test/flow.test.ts @@ -205,6 +205,135 @@ describe("authorization code + PKCE, end to end", () => { }); }); +describe("redirect_uri is matched exactly, before any code exists", () => { + /** A browser that is already signed in at the broker (one app's sign-in done). */ + async function signedInBrowser() { + const browser = new Browser(network); + await complete(HEIDI, ADA, browser); + return browser; + } + async function authorizeWith(browser: Browser, app: ClientApp, redirect_uri: string) { + const { verifier, challenge } = pkce(); + const url = new URL(discovery.authorization_endpoint); + url.search = new URLSearchParams({ + response_type: "code", client_id: app.id, redirect_uri, + scope: "openid profile email", state: "s", nonce: "n", + code_challenge: challenge, code_challenge_method: "S256", + }).toString(); + return { verifier, response: await browser.request(url.toString()) }; + } + /** The refusal: the error page, no code, nothing sent to the rejected address. */ + function expectRefused(response: Response, bad: string) { + expect(response.status).toBeGreaterThanOrEqual(300); + expect(response.status).toBeLessThan(400); + const location = new URL(response.headers.get("location") ?? "http://missing.invalid/", BROKER); + expect(location.origin + location.pathname).toBe(`${BROKER}/problem`); + expect(location.searchParams.get("code")).toBeNull(); + expect(response.headers.get("location")).not.toContain("code="); + expect(location.href.startsWith(bad)).toBe(false); + } + const token = (body: Record) => + fetch(discovery.token_endpoint, { + method: "POST", + headers: { "content-type": "application/x-www-form-urlencoded" }, + body: new URLSearchParams(body).toString(), + }); + + it("issues no code to an unregistered address for a browser that is already signed in", async () => { + const browser = await signedInBrowser(); + const evil = "https://evil.example/api/auth/callback/bitbaum-signin"; + const { response } = await authorizeWith(browser, HEIDI, evil); + expectRefused(response, evil); + }); + + it("does not treat a registered address plus a path, or plus a query, as registered", async () => { + const browser = await signedInBrowser(); + for (const bad of [ + `${redirectUri(HEIDI)}/extra`, + `${redirectUri(HEIDI)}?next=https://evil.example`, + `${redirectUri(HEIDI)}/../../elsewhere`, + `${HEIDI.origin}@evil.example/api/auth/callback/bitbaum-signin`, + ]) { + const { response } = await authorizeWith(browser, HEIDI, bad); + expectRefused(response, bad); + } + }); + + it("does not take an address registered to another app, or a loopback port that was not registered", async () => { + const browser = await signedInBrowser(); + for (const bad of [ + redirectUri(SOLON), + redirectUri({ origin: "http://localhost:4999" }), + ]) { + const { response } = await authorizeWith(browser, HEIDI, bad); + expectRefused(response, bad); + } + }); + + it("still issues a code to each registered address, signed in", async () => { + const browser = await signedInBrowser(); + for (const good of redirectUris(MOVING)) { + const { response } = await authorizeWith(browser, MOVING, good); + const location = new URL(response.headers.get("location")!); + expect(location.origin + location.pathname).toBe(good); + expect(location.searchParams.get("code")).toBeTruthy(); + } + }); + + it("refuses a token request whose redirect_uri differs from the one the code was issued for", async () => { + const browser = await signedInBrowser(); + const { verifier, response } = await authorizeWith(browser, MOVING, redirectUri(MOVING)); + const code = new URL(response.headers.get("location")!).searchParams.get("code")!; + const exchange = { + grant_type: "authorization_code", code, client_id: MOVING.id, + client_secret: broker.secrets.get(MOVING.id)!, code_verifier: verifier, + }; + // Registered, but not the one this code was bound to. + const other = await token({ ...exchange, redirect_uri: redirectUris(MOVING)[1] }); + expect(other.status).toBe(400); + expect((await other.json()).access_token).toBeUndefined(); + // The attempt spent the code: even the right address cannot redeem it now. + const right = await token({ ...exchange, redirect_uri: redirectUri(MOVING) }); + expect(right.status).not.toBe(200); + // And a missing or invented one is refused too. + const fresh = await authorizeWith(browser, MOVING, redirectUri(MOVING)); + const code2 = new URL(fresh.response.headers.get("location")!).searchParams.get("code")!; + const body = { ...exchange, code: code2, code_verifier: fresh.verifier }; + expect((await token({ ...body, redirect_uri: "https://evil.example/cb" })).status).toBe(400); + }); + + it("lets a code live a minute at most, and only once", async () => { + const browser = await signedInBrowser(); + const { verifier, response } = await authorizeWith(browser, HEIDI, redirectUri(HEIDI)); + const code = new URL(response.headers.get("location")!).searchParams.get("code")!; + const rows = await broker.db.client.query<{ expires_at: Date }>( + `select expires_at from verification order by created_at desc limit 1`, + ); + const lifetime = (rows.rows[0].expires_at.getTime() - Date.now()) / 1000; + expect(lifetime).toBeGreaterThan(0); + expect(lifetime).toBeLessThanOrEqual(60); + const exchange = { + grant_type: "authorization_code", code, client_id: HEIDI.id, redirect_uri: redirectUri(HEIDI), + client_secret: broker.secrets.get(HEIDI.id)!, code_verifier: verifier, + }; + expect((await token(exchange)).status).toBe(200); + expect((await token(exchange)).status).not.toBe(200); + }); + + it("refuses a code after its minute is up", async () => { + const browser = await signedInBrowser(); + const { verifier, response } = await authorizeWith(browser, HEIDI, redirectUri(HEIDI)); + const code = new URL(response.headers.get("location")!).searchParams.get("code")!; + await broker.db.client.query(`update verification set expires_at = now() - interval '1 second'`); + const late = await token({ + grant_type: "authorization_code", code, client_id: HEIDI.id, redirect_uri: redirectUri(HEIDI), + client_secret: broker.secrets.get(HEIDI.id)!, code_verifier: verifier, + }); + expect(late.status).toBe(400); + expect((await late.json()).access_token).toBeUndefined(); + }); +}); + describe("pairwise subject", () => { it("is stable for one app and different between apps", async () => { const browser = new Browser(network);