diff --git a/src/scenarios/authorization-server/auth/spec-references.ts b/src/scenarios/authorization-server/auth/spec-references.ts index 38a1beec..e1a254a2 100644 --- a/src/scenarios/authorization-server/auth/spec-references.ts +++ b/src/scenarios/authorization-server/auth/spec-references.ts @@ -9,6 +9,22 @@ export const SpecReferences: { [key: string]: SpecReference } = { id: 'OAUTH-2.1-authorization-code-grant', url: 'https://www.ietf.org/archive/id/draft-ietf-oauth-v2-1-13.html#section-4.1' }, + RFC_7636_AUTHORIZATION_REQUEST_ERROR: { + id: 'RFC-7636-authorization-request-error', + url: 'https://www.rfc-editor.org/rfc/rfc7636.html#section-4.4.1' + }, + RFC_9700_PKCE: { + id: 'RFC-9700-pkce', + url: 'https://www.rfc-editor.org/rfc/rfc9700.html#section-2.1.1' + }, + RFC_6749_AUTHORIZATION_ERROR_RESPONSE: { + id: 'RFC-6749-authorization-error-response', + url: 'https://www.rfc-editor.org/rfc/rfc6749.html#section-4.1.2.1' + }, + RFC_9700_REDIRECT_URI_MATCHING: { + id: 'RFC-9700-redirect-uri-matching', + url: 'https://www.rfc-editor.org/rfc/rfc9700.html#section-2.1' + }, // DPoP (SEP-1932 / RFC 9449) — authorization-server concerns. SEP_1932_DPOP: { id: 'SEP-1932-DPoP', diff --git a/src/scenarios/authorization-server/authorization-code-grant.test.ts b/src/scenarios/authorization-server/authorization-code-grant.test.ts index e2eaf06a..c167c75d 100644 --- a/src/scenarios/authorization-server/authorization-code-grant.test.ts +++ b/src/scenarios/authorization-server/authorization-code-grant.test.ts @@ -11,6 +11,12 @@ vi.mock('../authorization-server/auth/helpers/createCallbackServer', () => ({ startCallbackServer: vi.fn() })); +// The authorization endpoint probes have their own tests +// (authorization-endpoint-probes*.test.ts); here they add no checks. +vi.mock('./authorization-endpoint-probes', () => ({ + runAuthorizationEndpointProbes: vi.fn().mockResolvedValue([]) +})); + const mockedRequest = vi.mocked(request); const mockedStartCallbackServer = vi.mocked(startCallbackServer); diff --git a/src/scenarios/authorization-server/authorization-code-grant.ts b/src/scenarios/authorization-server/authorization-code-grant.ts index 13f3ba04..7f38c872 100644 --- a/src/scenarios/authorization-server/authorization-code-grant.ts +++ b/src/scenarios/authorization-server/authorization-code-grant.ts @@ -10,6 +10,7 @@ import { request } from 'undici'; import { createHash, randomBytes } from 'crypto'; import { AuthorizationServerOptions } from '../../schemas'; import { SpecReferences } from '../authorization-server/auth/spec-references'; +import { runAuthorizationEndpointProbes } from './authorization-endpoint-probes'; const REDIRECT_URI_ORIGIN = 'http://127.0.0.1'; const REDIRECT_URI_PATH = '/callback'; @@ -58,12 +59,18 @@ export class AuthorizationCodeGrantScenario implements ClientScenarioForAuthoriz - HTTP response status code of token response MUST be 200 OK - Content-Type header of token response MUST be application/json - Cache-Control header of token response MUST be no-store -- Token response MUST return a JSON response including access_token and token_type`; +- Token response MUST return a JSON response including access_token and token_type +- An authorization request without a code_challenge MUST be answered with the invalid_request authorization error response, an error redirect to the redirect URI (RFC 7636 §4.4.1, RFC 6749 §4.1.2.1); a code_verifier is accepted only if a code_challenge was sent (RFC 9700 §2.1.1) +- An error redirect to the redirect URI MUST carry the state of the request (RFC 6749 §4.1.2.1) +- The server MUST NOT redirect to a redirect URI that is not an exact match of a registered one (RFC 9700 §2.1; RFC 6749 §4.1.2.1) + +The last three requirements are checked without a login, by reading the authorization endpoint's answer to requests next to a valid control request. A server that answers every anonymous request with a login page, or refuses the control request, gets those checks reported as failed with a 'Not testable' reason (#248), not as passed.`; async run( options: AuthorizationServerOptions, details: Record ): Promise { + let probeChecks: ConformanceCheck[] = []; try { if (!options.clientId) { return [ @@ -88,8 +95,18 @@ export class AuthorizationCodeGrantScenario implements ClientScenarioForAuthoriz // Decide how we'll authenticate to the token endpoint *before* // binding a port and asking the user to open a browser. const authMethod = this.selectTokenAuthMethod(metadata, options); + + // Negative checks that need no login: sent before the interactive + // login, so they are reported even if the login fails or is skipped. + probeChecks = await runAuthorizationEndpointProbes( + metadata, + options, + `${REDIRECT_URI_ORIGIN}:${options.port}${REDIRECT_URI_PATH}`, + authMethod + ); if (authMethod === null) { return [ + ...probeChecks, this.skippedCheck( 'Server does not support client_secret_post, client_secret_basic, or none auth methods' ) @@ -134,10 +151,11 @@ export class AuthorizationCodeGrantScenario implements ClientScenarioForAuthoriz this.validateTokenResponse(tokenResponse, errors); if (errors.length > 0) { - return [this.failureCheck(errors.join(', '))]; + return [...probeChecks, this.failureCheck(errors.join(', '))]; } return [ + ...probeChecks, this.successCheck({ authorizationRequest, authorizationResponseUrl, @@ -148,7 +166,7 @@ export class AuthorizationCodeGrantScenario implements ClientScenarioForAuthoriz callback.close(); } } catch (error) { - return [this.failureCheck(error)]; + return [...probeChecks, this.failureCheck(error)]; } } @@ -172,7 +190,10 @@ export class AuthorizationCodeGrantScenario implements ClientScenarioForAuthoriz params.set('resource', options.resource); } - return `${metadata.authorization_endpoint}?${params.toString()}`; + // The endpoint may already have a query (RFC 6749 3.1): keep it. + const url = new URL(metadata.authorization_endpoint); + for (const [key, value] of params) url.searchParams.set(key, value); + return url.toString(); } private validateAuthorizationResponse( diff --git a/src/scenarios/authorization-server/authorization-endpoint-probes.http.test.ts b/src/scenarios/authorization-server/authorization-endpoint-probes.http.test.ts new file mode 100644 index 00000000..dfd6009e --- /dev/null +++ b/src/scenarios/authorization-server/authorization-endpoint-probes.http.test.ts @@ -0,0 +1,287 @@ +/** + * The authorization endpoint probes against a small authorization server over + * real HTTP: one that behaves, and one broken in each way a check looks for. + * A check that cannot fail would pass here as well, so each broken server must + * turn its own check to FAILURE and leave the others alone. A check that could + * not be exercised also fails, as "Not testable" (#248), and is told apart here. + */ +import { describe, it, expect, beforeAll, afterAll } from 'vitest'; +import http from 'node:http'; +import { AddressInfo } from 'node:net'; +import { runAuthorizationEndpointProbes } from './authorization-endpoint-probes.js'; + +type Mode = + | 'strict' + | 'ignores-pkce' + | 'drops-state' + | 'prefix-match' + | 'login-first' + | 'optional-pkce' + | 'inline-login' + | 'html-400' + | 'json-400' + | 'tenant'; + +const CLIENT_ID = 'client'; +const REGISTERED = 'http://127.0.0.1:3000/callback'; + +/** + * 'ignores-pkce' accepts any code_verifier. 'optional-pkce' issued a code to a + * request without a challenge, as a server may for a client that does not use + * PKCE, but refuses a code_verifier for it, as RFC 9700 2.1.1 requires. + */ +function tokenEndpoint( + mode: Mode, + req: http.IncomingMessage, + res: http.ServerResponse +) { + let body = ''; + req.on('data', (chunk) => (body += chunk)); + req.on('end', () => { + const form = new URLSearchParams(body); + res.setHeader('content-type', 'application/json'); + if (mode === 'optional-pkce' && form.has('code_verifier')) { + res.writeHead(400).end(JSON.stringify({ error: 'invalid_grant' })); + return; + } + res + .writeHead(200) + .end(JSON.stringify({ access_token: 't', token_type: 'Bearer' })); + }); +} + +function authorizationEndpoint(mode: Mode) { + return (req: http.IncomingMessage, res: http.ServerResponse) => { + const url = new URL(req.url ?? '/', 'http://localhost'); + if (url.pathname === '/token') { + tokenEndpoint(mode, req, res); + return; + } + const q = url.searchParams; + const redirect = (to: URL) => { + res.writeHead(302, { location: to.href }).end(); + }; + + if (mode === 'inline-login') { + // A login page shown with a 200 for every request, with no redirect. + res.writeHead(200, { 'content-type': 'text/html' }); + res.end('Please log in'); + return; + } + if (mode === 'login-first') { + res.writeHead(302, { location: '/login' }).end(); + return; + } + if (q.get('client_id') !== CLIENT_ID) { + res.writeHead(400, { 'content-type': 'application/json' }); + res.end(JSON.stringify({ error: 'invalid_client' })); + return; + } + if (mode === 'tenant' && q.get('tenant') !== 'abc') { + // An endpoint that needs its own query parameter to be kept. + res.writeHead(400, { 'content-type': 'application/json' }); + res.end(JSON.stringify({ error: 'invalid_request' })); + return; + } + const redirectUri = q.get('redirect_uri') ?? ''; + if ( + mode === 'json-400' && + q.get('response_type') === 'code' && + redirectUri === REGISTERED && + !q.has('code_challenge') + ) { + // Refuses a request without a challenge, but directly, not by redirecting. + res.writeHead(400, { 'content-type': 'application/json' }); + res.end(JSON.stringify({ error: 'invalid_request' })); + return; + } + if ( + mode === 'html-400' && + (!q.has('code_challenge') || + q.get('response_type') !== 'code' || + redirectUri !== REGISTERED) + ) { + // Every invalid request gets an HTML error page, with no OAuth error code. + res.writeHead(400, { 'content-type': 'text/html' }); + res.end('Bad request'); + return; + } + const matches = + mode === 'prefix-match' + ? redirectUri.startsWith(REGISTERED) + : redirectUri === REGISTERED; + if (!matches) { + res.writeHead(400, { 'content-type': 'application/json' }); + res.end(JSON.stringify({ error: 'invalid_request' })); + return; + } + + const back = new URL(redirectUri); + const withState = (target: URL) => { + if (mode !== 'drops-state' && q.has('state')) { + target.searchParams.set('state', q.get('state')!); + } + return target; + }; + if (q.get('response_type') !== 'code') { + back.searchParams.set('error', 'unsupported_response_type'); + redirect(withState(back)); + return; + } + if (!q.has('code_challenge')) { + if (mode === 'ignores-pkce' || mode === 'optional-pkce') { + back.searchParams.set('code', 'a-code'); + } else { + back.searchParams.set('error', 'invalid_request'); + } + redirect(withState(back)); + return; + } + res.writeHead(200, { 'content-type': 'text/html' }); + res.end('consent'); + }; +} + +const servers = new Map(); +const endpoints = new Map(); + +beforeAll(async () => { + for (const mode of [ + 'strict', + 'ignores-pkce', + 'drops-state', + 'prefix-match', + 'login-first', + 'optional-pkce', + 'inline-login', + 'html-400', + 'json-400', + 'tenant' + ] as Mode[]) { + const server = http.createServer(authorizationEndpoint(mode)); + await new Promise((resolve) => + server.listen(0, '127.0.0.1', resolve) + ); + servers.set(mode, server); + endpoints.set( + mode, + `http://127.0.0.1:${(server.address() as AddressInfo).port}/authorize` + ); + } +}); + +afterAll(async () => { + await Promise.all( + [...servers.values()].map( + (server) => new Promise((resolve) => server.close(resolve)) + ) + ); +}); + +async function statuses(mode: Mode, clientId = CLIENT_ID) { + const checks = await runAuthorizationEndpointProbes( + { + authorization_endpoint: + mode === 'tenant' + ? `${endpoints.get(mode)}?tenant=abc` + : endpoints.get(mode), + token_endpoint: endpoints.get(mode)!.replace('/authorize', '/token') + }, + { url: 'http://127.0.0.1', clientId, port: 3000 }, + REGISTERED, + 'none' + ); + return Object.fromEntries( + checks.map((c) => [c.id, c.details?.untestable ? 'NOT TESTABLE' : c.status]) + ); +} + +describe('authorization endpoint probes over HTTP', () => { + it('passes all three against a server that behaves', async () => { + expect(await statuses('strict')).toEqual({ + 'pkce-downgrade': 'SUCCESS', + 'error-redirect-state': 'SUCCESS', + 'redirect-uri-exact': 'SUCCESS' + }); + }); + + it('fails pkce-downgrade against a server that issues a code without a code_challenge and accepts a code_verifier for it', async () => { + expect(await statuses('ignores-pkce')).toEqual({ + 'pkce-downgrade': 'FAILURE', + 'error-redirect-state': 'SUCCESS', + 'redirect-uri-exact': 'SUCCESS' + }); + }); + + it('passes pkce-downgrade against a server that issues a code but refuses a code_verifier for it', async () => { + expect(await statuses('optional-pkce')).toEqual({ + 'pkce-downgrade': 'SUCCESS', + 'error-redirect-state': 'SUCCESS', + 'redirect-uri-exact': 'SUCCESS' + }); + }); + + it('fails error-redirect-state against a server whose error redirect drops the state', async () => { + expect(await statuses('drops-state')).toEqual({ + 'pkce-downgrade': 'SUCCESS', + 'error-redirect-state': 'FAILURE', + 'redirect-uri-exact': 'SUCCESS' + }); + }); + + it('fails redirect-uri-exact against a server that matches redirect URIs by prefix', async () => { + expect(await statuses('prefix-match')).toEqual({ + 'pkce-downgrade': 'SUCCESS', + 'error-redirect-state': 'SUCCESS', + 'redirect-uri-exact': 'FAILURE' + }); + }); + + it('cannot test any of the three against a server that asks for a login first', async () => { + expect(await statuses('login-first')).toEqual({ + 'pkce-downgrade': 'NOT TESTABLE', + 'error-redirect-state': 'NOT TESTABLE', + 'redirect-uri-exact': 'NOT TESTABLE' + }); + }); + + it('fails pkce-downgrade against a server that refuses directly with a 400 instead of an error redirect', async () => { + expect(await statuses('json-400')).toEqual({ + 'pkce-downgrade': 'FAILURE', + 'error-redirect-state': 'SUCCESS', + 'redirect-uri-exact': 'SUCCESS' + }); + }); + + it('passes all three against an endpoint that has its own query parameter, because it is kept', async () => { + expect(await statuses('tenant')).toEqual({ + 'pkce-downgrade': 'SUCCESS', + 'error-redirect-state': 'SUCCESS', + 'redirect-uri-exact': 'SUCCESS' + }); + }); + + it('does not read a login page shown with a 200 as accepting anything', async () => { + expect(await statuses('inline-login')).toEqual({ + 'pkce-downgrade': 'NOT TESTABLE', + 'error-redirect-state': 'NOT TESTABLE', + 'redirect-uri-exact': 'NOT TESTABLE' + }); + }); + + it('cannot test any of the three against a server that answers every invalid request with an HTML 400, because no error code is seen', async () => { + expect(await statuses('html-400')).toEqual({ + 'pkce-downgrade': 'NOT TESTABLE', + 'error-redirect-state': 'NOT TESTABLE', + 'redirect-uri-exact': 'NOT TESTABLE' + }); + }); + + it('cannot test any of the three when the client is not registered, because the control request is refused', async () => { + expect(await statuses('strict', 'not-registered')).toEqual({ + 'pkce-downgrade': 'NOT TESTABLE', + 'error-redirect-state': 'NOT TESTABLE', + 'redirect-uri-exact': 'NOT TESTABLE' + }); + }); +}); diff --git a/src/scenarios/authorization-server/authorization-endpoint-probes.test.ts b/src/scenarios/authorization-server/authorization-endpoint-probes.test.ts new file mode 100644 index 00000000..85d45f08 --- /dev/null +++ b/src/scenarios/authorization-server/authorization-endpoint-probes.test.ts @@ -0,0 +1,626 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest'; +import { request } from 'undici'; +import { runAuthorizationEndpointProbes } from './authorization-endpoint-probes.js'; +import { AuthorizationCodeGrantScenario } from './authorization-code-grant.js'; +import { startCallbackServer } from '../authorization-server/auth/helpers/createCallbackServer'; + +vi.mock('undici', () => ({ + request: vi.fn() +})); + +vi.mock('../authorization-server/auth/helpers/createCallbackServer', () => ({ + startCallbackServer: vi.fn() +})); + +const mockedRequest = vi.mocked(request); +const mockedStartCallbackServer = vi.mocked(startCallbackServer); + +const AUTHORIZATION_ENDPOINT = 'https://example.com/authorize'; +const TOKEN_ENDPOINT = 'https://example.com/token'; +const REDIRECT_URI = 'http://127.0.0.1:3000/callback'; + +const OPTIONS = { + url: 'https://example.com', + clientId: 'client', + port: 3000 +}; +const METADATA = { + authorization_endpoint: AUTHORIZATION_ENDPOINT, + token_endpoint: TOKEN_ENDPOINT +}; + +type Reply = { + status: number; + location?: string; + body?: string; + headers?: Record; +}; +/** A reply, or a function of the state the request sent (for redirects that echo it). */ +type Answer = Reply | ((state: string) => Reply); + +/** What each kind of request gets. A request kind that is not listed gets a login redirect. */ +type Server = Partial<{ + control: Answer; + downgrade: Answer; + unsupported: Answer; + near: Answer; + token: Reply; +}>; + +const LOGIN: Reply = { status: 302, location: 'https://example.com/login' }; +const PAGE: Reply = { status: 200 }; +const BAD_REQUEST: Reply = { status: 400 }; +const json = (status: number, body: object): Reply => ({ + status, + body: JSON.stringify(body) +}); +const errorRedirect = + (error: string, withState = true): Answer => + (state) => ({ + status: 302, + location: `${REDIRECT_URI}?error=${error}${withState ? `&state=${state}` : ''}` + }); + +/** Routes each request by its shape, so tests do not depend on the order of requests. */ +function serve(server: Server) { + mockedRequest.mockReset(); + mockedRequest.mockImplementation((async (input: any) => { + const url = new URL(String(input)); + let answer: Answer | undefined; + if (url.origin + url.pathname === TOKEN_ENDPOINT) { + answer = server.token ?? json(400, { error: 'invalid_grant' }); + } else { + const q = url.searchParams; + if (q.get('redirect_uri') !== REDIRECT_URI) answer = server.near; + else if (q.get('response_type') !== 'code') answer = server.unsupported; + else if (!q.has('code_challenge')) answer = server.downgrade; + else answer = server.control; + } + const reply = + typeof answer === 'function' + ? answer(url.searchParams.get('state') ?? '') + : (answer ?? LOGIN); + const text = reply.body ?? ''; + return { + statusCode: reply.status, + headers: { + ...(reply.location ? { location: reply.location } : {}), + ...(reply.headers ?? {}) + }, + body: { + text: async () => text, + json: async () => JSON.parse(text) + } + }; + }) as any); +} + +async function run(authMethod: 'none' | null = 'none') { + const checks = await runAuthorizationEndpointProbes( + METADATA, + OPTIONS, + REDIRECT_URI, + authMethod + ); + return Object.fromEntries(checks.map((c) => [c.id, c])); +} + +/** Expects a check that failed because it could not be exercised (#248). */ +function expectNotTestable(check: any, textInReason?: string) { + expect(check.status).toBe('FAILURE'); + expect(check.details?.untestable).toBe(true); + expect(check.errorMessage).toMatch(/^Not testable: /); + if (textInReason) expect(check.errorMessage).toContain(textInReason); +} + +describe('authorization endpoint probes', () => { + beforeEach(() => { + mockedRequest.mockReset(); + mockedStartCallbackServer.mockReset(); + }); + + it('returns no checks without a client id or an authorization endpoint', async () => { + expect( + await runAuthorizationEndpointProbes( + METADATA, + { url: 'x' } as any, + REDIRECT_URI + ) + ).toEqual([]); + expect( + await runAuthorizationEndpointProbes({}, OPTIONS, REDIRECT_URI) + ).toEqual([]); + expect(mockedRequest).not.toHaveBeenCalled(); + }); + + it('sends a valid control, a request without code_challenge, an unsupported response_type and two near-match redirect URIs', async () => { + serve({ control: PAGE }); + await run(); + + const calls = mockedRequest.mock.calls; + const urls = calls.map((call) => new URL(String(call[0]))); + expect(urls).toHaveLength(5); + for (const url of urls) { + expect(url.origin + url.pathname).toBe(AUTHORIZATION_ENDPOINT); + expect(url.searchParams.get('client_id')).toBe('client'); + expect(url.searchParams.get('state')).toBeTruthy(); + } + const [control, downgrade, unsupported, near1, near2] = urls; + // The control is valid in every way. + expect(control.searchParams.get('response_type')).toBe('code'); + expect(control.searchParams.get('redirect_uri')).toBe(REDIRECT_URI); + expect(control.searchParams.get('code_challenge_method')).toBe('S256'); + expect(control.searchParams.get('code_challenge')).toBeTruthy(); + // Each probe changes one thing. + expect(downgrade.searchParams.has('code_challenge')).toBe(false); + expect(downgrade.searchParams.has('code_challenge_method')).toBe(false); + expect(unsupported.searchParams.get('response_type')).toBe( + 'conformance-unsupported' + ); + expect(unsupported.searchParams.get('code_challenge')).toBeTruthy(); + expect(near1.searchParams.get('redirect_uri')).toBe( + `${REDIRECT_URI}/extra` + ); + expect(near2.searchParams.get('redirect_uri')).toBe(`${REDIRECT_URI}x`); + // The near-match requests elicit the same error as the baseline, so a + // refusal can be compared with an error redirect for the registered URI. + expect(near1.searchParams.get('response_type')).toBe( + 'conformance-unsupported' + ); + expect(near2.searchParams.get('response_type')).toBe( + 'conformance-unsupported' + ); + // A different state for every request, and a timeout on every request. + expect(new Set(urls.map((u) => u.searchParams.get('state'))).size).toBe(5); + for (const call of calls) { + expect((call[1] as any).headersTimeout).toBeGreaterThan(0); + expect((call[1] as any).bodyTimeout).toBeGreaterThan(0); + } + }); + + describe('when the control request is refused', () => { + it.each([ + ['400 invalid_client', json(400, { error: 'invalid_client' })], + ['a bare 403', { status: 403 }], + ['a 429', { status: 429 }], + ['a 500', { status: 500 }], + ['an error redirect', errorRedirect('invalid_request')] + ] as [string, Answer][])( + 'reports all three as not testable, for %s', + async (_label, control) => { + serve({ control, downgrade: BAD_REQUEST, near: BAD_REQUEST }); + const checks = await run(); + for (const id of [ + 'pkce-downgrade', + 'error-redirect-state', + 'redirect-uri-exact' + ]) { + expectNotTestable(checks[id], 'control request'); + } + } + ); + + it('stops after the control request', async () => { + serve({ control: { status: 400 } }); + await run(); + expect(mockedRequest).toHaveBeenCalledTimes(1); + }); + }); + + it('reports not testable, not a pass, when every answer is a login page', async () => { + serve({}); + const checks = await run(); + for (const id of [ + 'pkce-downgrade', + 'error-redirect-state', + 'redirect-uri-exact' + ]) { + expectNotTestable(checks[id], 'login'); + } + }); + + it('does not read a 200 page as accepting a near-match redirect URI', async () => { + // A login page or an "invalid redirect URI" page, shown with a 200 for + // every request, says nothing about how the redirect URI is matched. + serve({ + control: PAGE, + downgrade: PAGE, + unsupported: PAGE, + near: PAGE + }); + const checks = await run(); + expectNotTestable(checks['pkce-downgrade']); + expectNotTestable(checks['error-redirect-state']); + expectNotTestable(checks['redirect-uri-exact']); + }); + + describe('pkce-downgrade', () => { + it('passes on an error redirect with invalid_request', async () => { + serve({ control: PAGE, downgrade: errorRedirect('invalid_request') }); + expect((await run())['pkce-downgrade'].status).toBe('SUCCESS'); + }); + + it('fails when the refusal is for another reason (the wrong-reason trap)', async () => { + serve({ control: PAGE, downgrade: errorRedirect('access_denied') }); + const check = (await run())['pkce-downgrade']; + expect(check.status).toBe('FAILURE'); + expect(check.details?.untestable).toBeUndefined(); + expect(check.errorMessage).toContain('invalid_request'); + + serve({ + control: PAGE, + downgrade: json(400, { error: 'invalid_scope' }) + }); + const direct = (await run())['pkce-downgrade']; + expect(direct.status).toBe('FAILURE'); + expect(direct.errorMessage).toContain('invalid_scope'); + }); + + it('fails on a direct 400 with invalid_request: it refuses, but is not the authorization error response', async () => { + serve({ + control: PAGE, + downgrade: json(400, { error: 'invalid_request' }) + }); + const check = (await run())['pkce-downgrade']; + expect(check.status).toBe('FAILURE'); + expect(check.details?.untestable).toBeUndefined(); + expect(check.errorMessage).toContain('answered directly'); + expect(check.errorMessage).toContain('redirecting to the redirect URI'); + }); + + it.each([401, 403, 404, 429])( + 'is not testable for HTTP %i even when the body says invalid_request', + async (status) => { + serve({ + control: PAGE, + downgrade: json(status, { error: 'invalid_request' }) + }); + expectNotTestable((await run())['pkce-downgrade'], `HTTP ${status}`); + } + ); + + it.each([ + ['an HTML page', { status: 400, body: 'Bad request' }], + ['malformed JSON', { status: 400, body: '{"error": ' }], + ['an empty body', { status: 400 }], + ['JSON with no error', json(400, { message: 'bad' })] + ] as [string, Reply][])( + 'is not testable for a 400 with %s, because invalid_request is not seen', + async (_label, downgrade) => { + serve({ control: PAGE, downgrade }); + expectNotTestable( + (await run())['pkce-downgrade'], + 'no OAuth error code' + ); + } + ); + + it.each([401, 403, 404, 429])( + 'is not testable for a bare %i, which is not the server answering the request', + async (status) => { + serve({ control: PAGE, downgrade: { status } }); + expectNotTestable((await run())['pkce-downgrade'], `HTTP ${status}`); + } + ); + + it('is not testable on a server error', async () => { + serve({ control: PAGE, downgrade: { status: 500 } }); + expectNotTestable((await run())['pkce-downgrade'], 'HTTP 500'); + }); + + it('is not testable when the server cannot be reached, because the control fails', async () => { + mockedRequest.mockReset(); + mockedRequest.mockRejectedValue(new Error('connect ECONNREFUSED')); + expectNotTestable((await run())['pkce-downgrade'], 'ECONNREFUSED'); + }); + + it('does not mistake a malformed Location header for a lost connection', async () => { + serve({ + control: PAGE, + downgrade: { status: 302, location: 'http://[' } + }); + const check = (await run())['pkce-downgrade']; + expectNotTestable(check, 'login'); + expect(check.errorMessage).not.toContain('no answer'); + }); + + describe('when a code is issued to a request without a code_challenge', () => { + const issued: Answer = { + status: 302, + location: `${REDIRECT_URI}?code=abc&state=s` + }; + + it.each([ + [ + 'an HTTP 400 that carries an access_token', + json(400, { error: 'invalid_grant', access_token: 't' }) + ], + [ + 'an HTTP 200 with only a refresh_token', + json(200, { refresh_token: 'r' }) + ], + [ + 'an HTTP 401 that carries an id_token', + json(401, { error: 'invalid_client', id_token: 'i' }) + ] + ] as [string, Reply][])( + 'fails when the token response is %s: a token means the code was redeemed', + async (_label, token) => { + serve({ control: PAGE, downgrade: issued, token }); + const check = (await run())['pkce-downgrade']; + expect(check.status).toBe('FAILURE'); + expect(check.details?.untestable).toBeUndefined(); + expect(check.errorMessage).toContain('redeemed'); + } + ); + + it('fails when the code can be redeemed with a code_verifier', async () => { + serve({ + control: PAGE, + downgrade: issued, + token: json(200, { access_token: 't' }) + }); + const check = (await run())['pkce-downgrade']; + expect(check.status).toBe('FAILURE'); + expect(check.details?.untestable).toBeUndefined(); + expect(check.errorMessage).toContain('code_verifier'); + // The redemption went to the token endpoint, with the code and a verifier. + const call = mockedRequest.mock.calls.find( + (c) => String(c[0]) === TOKEN_ENDPOINT + )!; + const body = new URLSearchParams((call[1] as any).body); + expect(body.get('code')).toBe('abc'); + expect(body.get('code_verifier')).toBeTruthy(); + expect(body.get('client_id')).toBe('client'); + }); + + it.each([ + ['invalid_grant', json(400, { error: 'invalid_grant' })], + ['invalid_request', json(400, { error: 'invalid_request' })] + ])( + 'passes when the token request is refused with %s', + async (_e, token) => { + serve({ control: PAGE, downgrade: issued, token }); + expect((await run())['pkce-downgrade'].status).toBe('SUCCESS'); + } + ); + + it.each([ + ['invalid_client (a 401)', json(401, { error: 'invalid_client' })], + ['a 429', { status: 429 }], + ['a 400 with no error', { status: 400 }], + [ + 'unsupported_grant_type', + json(400, { error: 'unsupported_grant_type' }) + ] + ] as [string, Reply][])( + 'is not testable when the token request is refused with %s, which does not show the verifier was the reason', + async (_e, token) => { + serve({ control: PAGE, downgrade: issued, token }); + expectNotTestable((await run())['pkce-downgrade'], 'verifier'); + } + ); + + it('is not testable when no client authentication method is known', async () => { + serve({ control: PAGE, downgrade: issued }); + expectNotTestable((await run(null))['pkce-downgrade'], 'not tried'); + }); + + it('is not testable when the token endpoint has a server error', async () => { + serve({ control: PAGE, downgrade: issued, token: { status: 500 } }); + expectNotTestable((await run())['pkce-downgrade'], 'HTTP 500'); + }); + }); + }); + + describe('error-redirect-state', () => { + it('passes when the error redirects carry the state', async () => { + serve({ + control: PAGE, + downgrade: errorRedirect('invalid_request'), + unsupported: errorRedirect('unsupported_response_type') + }); + expect((await run())['error-redirect-state'].status).toBe('SUCCESS'); + }); + + it('fails when the state is missing, wrong or repeated', async () => { + const bad: Answer[] = [ + errorRedirect('unsupported_response_type', false), + () => ({ + status: 302, + location: `${REDIRECT_URI}?error=unsupported_response_type&state=not-the-state` + }), + (state) => ({ + status: 302, + location: `${REDIRECT_URI}?error=unsupported_response_type&state=${state}&state=${state}` + }) + ]; + for (const unsupported of bad) { + serve({ control: PAGE, unsupported }); + const check = (await run())['error-redirect-state']; + expect(check.status).toBe('FAILURE'); + expect(check.details?.untestable).toBeUndefined(); + expect(check.errorMessage).toContain('state'); + } + }); + + it('is not testable when no probe produced an error redirect', async () => { + serve({ + control: PAGE, + downgrade: BAD_REQUEST, + unsupported: BAD_REQUEST + }); + expectNotTestable((await run())['error-redirect-state']); + }); + }); + + describe('redirect-uri-exact', () => { + // The baseline: the same request with the registered redirect URI gets an + // error redirect, so a refusal of a near-match is about the redirect URI. + const baseline = errorRedirect('unsupported_response_type'); + + it('passes when every near-match is refused with a 400 and the registered URI gets an error redirect', async () => { + serve({ control: PAGE, unsupported: baseline, near: BAD_REQUEST }); + expect((await run())['redirect-uri-exact'].status).toBe('SUCCESS'); + }); + + it('is not testable when the registered URI gets no error redirect, because a 400 could be for another reason', async () => { + serve({ control: PAGE, unsupported: BAD_REQUEST, near: BAD_REQUEST }); + expectNotTestable((await run())['redirect-uri-exact'], 'another reason'); + }); + + it('fails when the server redirects an error to a URI that only starts with the registered one', async () => { + serve({ + control: PAGE, + unsupported: baseline, + near: { + status: 302, + location: `${REDIRECT_URI}/extra?error=unsupported_response_type&state=s` + } + }); + const check = (await run())['redirect-uri-exact']; + expect(check.status).toBe('FAILURE'); + expect(check.details?.untestable).toBeUndefined(); + expect(check.errorMessage).toContain(`${REDIRECT_URI}/extra`); + }); + + it('fails when the near-match is given a code', async () => { + serve({ + control: PAGE, + unsupported: baseline, + near: { status: 302, location: `${REDIRECT_URI}x?code=abc&state=s` } + }); + const check = (await run())['redirect-uri-exact']; + expect(check.status).toBe('FAILURE'); + expect(check.errorMessage).toContain(`${REDIRECT_URI}x`); + }); + + it('fails even if the registered URI gets no error redirect, when a near-match is redirected to', async () => { + serve({ + control: PAGE, + unsupported: BAD_REQUEST, + near: { status: 302, location: `${REDIRECT_URI}x?error=invalid_scope` } + }); + expect((await run())['redirect-uri-exact'].status).toBe('FAILURE'); + }); + + it('is not testable when a near-match gets a 200 page, which says nothing about matching', async () => { + serve({ control: PAGE, unsupported: baseline, near: PAGE }); + const check = (await run())['redirect-uri-exact']; + expectNotTestable(check); + expect(check.errorMessage).not.toContain('redirected to a redirect URI'); + }); + + it.each([401, 403, 404, 429])( + 'is not testable when the near-matches get a bare %i', + async (status) => { + serve({ control: PAGE, unsupported: baseline, near: { status } }); + expectNotTestable((await run())['redirect-uri-exact']); + } + ); + + it('is not testable when the server asks for a login', async () => { + serve({ control: LOGIN, unsupported: LOGIN, near: LOGIN }); + expectNotTestable((await run())['redirect-uri-exact'], 'login'); + }); + + it('is not testable on a server error', async () => { + serve({ control: PAGE, unsupported: baseline, near: { status: 500 } }); + expectNotTestable((await run())['redirect-uri-exact'], 'HTTP 500'); + }); + }); + + it("keeps the authorization endpoint's own query parameters (RFC 6749 3.1)", async () => { + const metadata = { + authorization_endpoint: `${AUTHORIZATION_ENDPOINT}?tenant=abc`, + token_endpoint: TOKEN_ENDPOINT + }; + serve({ control: PAGE }); + await runAuthorizationEndpointProbes( + metadata, + OPTIONS, + REDIRECT_URI, + 'none' + ); + expect(mockedRequest.mock.calls.length).toBeGreaterThan(0); + for (const call of mockedRequest.mock.calls) { + const url = new URL(String(call[0])); + expect(url.origin + url.pathname).toBe(AUTHORIZATION_ENDPOINT); + expect(url.searchParams.get('tenant')).toBe('abc'); + expect(url.searchParams.get('client_id')).toBe('client'); + expect(url.searchParams.get('response_type')).toBeTruthy(); + } + }); + + it('keeps the endpoint query in the URL the scenario asks the tester to open', async () => { + const scenario = new AuthorizationCodeGrantScenario(); + serve({ control: PAGE }); + const log = vi.spyOn(console, 'log').mockImplementation(() => {}); + mockedStartCallbackServer.mockReturnValue({ + waitForCallback: vi.fn().mockRejectedValue(new Error('stop here')), + close: vi.fn() + } as any); + try { + await scenario.run(OPTIONS, { + 'authorization-server-metadata-endpoint': { + body: { + issuer: 'https://example.com', + authorization_endpoint: `${AUTHORIZATION_ENDPOINT}?tenant=abc`, + token_endpoint: TOKEN_ENDPOINT + } + } + }); + const printed = log.mock.calls + .map((c) => String(c[0])) + .find((line) => line.startsWith(AUTHORIZATION_ENDPOINT))!; + const url = new URL(printed); + expect(url.searchParams.get('tenant')).toBe('abc'); + expect(url.searchParams.get('response_type')).toBe('code'); + expect(url.searchParams.get('code_challenge')).toBeTruthy(); + } finally { + log.mockRestore(); + } + }); + + it('adds the three checks to the authorization-code-grant scenario, before the login', async () => { + const scenario = new AuthorizationCodeGrantScenario(); + serve({ + control: PAGE, + token: { + status: 200, + body: JSON.stringify({ access_token: 't', token_type: 'Bearer' }), + headers: { + 'content-type': 'application/json', + 'cache-control': 'no-store' + } + } + }); + mockedStartCallbackServer.mockReturnValue({ + waitForCallback: vi + .fn() + .mockImplementation( + async () => + `${REDIRECT_URI}?code=abc&state=${(scenario as any).state}` + ), + close: vi.fn() + } as any); + + const checks = await scenario.run(OPTIONS, { + 'authorization-server-metadata-endpoint': { + body: { + issuer: 'https://example.com', + authorization_endpoint: AUTHORIZATION_ENDPOINT, + token_endpoint: TOKEN_ENDPOINT + } + } + }); + + expect(checks.map((c) => c.id)).toEqual([ + 'pkce-downgrade', + 'error-redirect-state', + 'redirect-uri-exact', + 'authorization-code-grant' + ]); + expect(checks[3].status).toBe('SUCCESS'); + }); +}); diff --git a/src/scenarios/authorization-server/authorization-endpoint-probes.ts b/src/scenarios/authorization-server/authorization-endpoint-probes.ts new file mode 100644 index 00000000..7c2c1904 --- /dev/null +++ b/src/scenarios/authorization-server/authorization-endpoint-probes.ts @@ -0,0 +1,686 @@ +/** + * Negative checks of the authorization endpoint that need no login and no + * browser: each sends a request and reads the response without following + * redirects. They run inside the `authorization-code-grant` scenario. + * + * A control request, valid in every way, goes first. If the server refuses + * it, the client or the redirect URI is not registered, or the probes are + * blocked, so a refusal of a probe would say nothing about the requirement. + * Many servers also answer an anonymous request with a login page; then how + * the server treats the request cannot be seen. In both cases the checks + * report "not testable" (#248) and do not read as a pass. + * + * Policy for every check: it passes only when the requirement is seen to hold, + * and fails only when it is seen to be violated. Anything else, such as a + * login page, a refusal whose reason is not visible, a server error or a + * timeout, is "not testable": red, with the reason, and never a pass. + */ +import { request } from 'undici'; +import { createHash, randomBytes } from 'crypto'; +import { ConformanceCheck, CheckStatus, SpecReference } from '../../types'; +import { AuthorizationServerOptions } from '../../schemas'; +import { SpecReferences } from './auth/spec-references'; +import { untestableCheck } from '../untestable'; + +const TIMEOUT_MS = 10_000; + +type Probe = + /** A redirect to the probed redirect URI that carries an authorization code. */ + | { kind: 'code'; location: string } + /** A redirect to the probed redirect URI that carries an error. */ + | { + kind: 'error-redirect'; + location: string; + error: string | null; + state: string[]; + } + /** A redirect to the probed redirect URI with neither a code nor an error. */ + | { kind: 'redirect'; location: string } + /** A redirect somewhere else, such as a login page. */ + | { kind: 'elsewhere'; location: string } + /** A 4xx answer shown directly, with the OAuth error code if the body has one. */ + | { kind: 'refused'; status: number; error: string | null } + /** A 2xx answer, such as a login page or a consent page. */ + | { kind: 'page'; status: number } + | { kind: 'server-error'; status: number } + | { kind: 'unreachable'; message: string }; + +type AuthMethod = 'none' | 'client_secret_post' | 'client_secret_basic'; + +/** What happened when a code issued to a request without a challenge was redeemed with a verifier. */ +type Redemption = + | { kind: 'issued' } + | { kind: 'refused'; status: number; error: string | null } + | { kind: 'not-tried'; reason: string } + | { kind: 'unexpected'; message: string }; + +function check( + id: string, + name: string, + description: string, + status: CheckStatus, + specReferences: SpecReference[], + errorMessage?: string, + details?: Record +): ConformanceCheck { + return { + id, + name, + description, + status, + timestamp: new Date().toISOString(), + specReferences, + ...(errorMessage ? { errorMessage } : {}), + ...(details ? { details } : {}) + }; +} + +function describeProbe(probe: Probe): string { + switch (probe.kind) { + case 'code': + return `a redirect with an authorization code (${probe.location})`; + case 'error-redirect': + return `a redirect to the redirect URI with error=${probe.error ?? '(none)'} (${probe.location})`; + case 'redirect': + return `a redirect to the redirect URI with neither a code nor an error (${probe.location})`; + case 'elsewhere': + return `a redirect to ${probe.location}, probably a login page`; + case 'refused': + return `HTTP ${probe.status}${probe.error ? ` ${probe.error}` : ''}`; + case 'page': + return `HTTP ${probe.status}, probably a login or consent page`; + case 'server-error': + return `HTTP ${probe.status}`; + case 'unreachable': + return `no answer (${probe.message})`; + } +} + +async function probeAuthorizationEndpoint( + endpoint: string, + params: URLSearchParams, + redirectUri: string +): Promise { + try { + // The endpoint may already have a query (RFC 6749 3.1): keep it. + const url = new URL(endpoint); + for (const [key, value] of params) url.searchParams.set(key, value); + const response = await request(url.toString(), { + method: 'GET', + headersTimeout: TIMEOUT_MS, + bodyTimeout: TIMEOUT_MS + }); + const status = response.statusCode; + const text = await response.body.text(); + + if (status >= 300 && status < 400) { + const header = response.headers.location; + const raw = Array.isArray(header) ? header[0] : header; + if (!raw) { + return { kind: 'elsewhere', location: '(no Location header)' }; + } + let location: URL; + try { + location = new URL(raw, endpoint); + } catch { + return { kind: 'elsewhere', location: raw }; + } + const target = new URL(redirectUri); + if ( + location.origin !== target.origin || + location.pathname !== target.pathname + ) { + return { kind: 'elsewhere', location: location.href }; + } + if (location.searchParams.has('code')) { + return { kind: 'code', location: location.href }; + } + if (location.searchParams.has('error')) { + return { + kind: 'error-redirect', + location: location.href, + error: location.searchParams.get('error'), + state: location.searchParams.getAll('state') + }; + } + return { kind: 'redirect', location: location.href }; + } + if (status >= 400 && status < 500) { + let error: string | null = null; + try { + const body = JSON.parse(text); + if (typeof body?.error === 'string') error = body.error; + } catch { + // An HTML error page has no machine-readable code. + } + return { kind: 'refused', status, error }; + } + if (status >= 500) { + return { kind: 'server-error', status }; + } + return { kind: 'page', status }; + } catch (error) { + return { + kind: 'unreachable', + message: error instanceof Error ? error.message : String(error) + }; + } +} + +/** + * RFC 9700 2.1.1: when the authorization request had no code_challenge, the + * server must not accept a code_verifier at the token endpoint. Redeem the + * code with a verifier and see. + */ +async function redeemWithVerifier( + metadata: Record, + options: AuthorizationServerOptions, + authMethod: AuthMethod | null, + redirectUri: string, + code: string +): Promise { + const tokenEndpoint = metadata?.token_endpoint; + if (typeof tokenEndpoint !== 'string') { + return { kind: 'not-tried', reason: 'the metadata has no token_endpoint' }; + } + if (authMethod === null) { + return { + kind: 'not-tried', + reason: 'no supported client authentication method for the token endpoint' + }; + } + const params = new URLSearchParams({ + grant_type: 'authorization_code', + code, + redirect_uri: redirectUri, + code_verifier: randomBytes(32).toString('base64url') + }); + if (options.resource) { + params.set('resource', options.resource); + } + const headers: Record = { + 'content-type': 'application/x-www-form-urlencoded' + }; + if (authMethod === 'none') { + params.set('client_id', options.clientId!); + } else if (authMethod === 'client_secret_post') { + params.set('client_id', options.clientId!); + params.set('client_secret', options.clientSecret!); + } else { + // RFC 6749 2.3.1: form-urlencode each component before base64. + headers.authorization = `Basic ${Buffer.from( + `${encodeURIComponent(options.clientId!)}:${encodeURIComponent(options.clientSecret!)}` + ).toString('base64')}`; + } + try { + const response = await request(tokenEndpoint, { + method: 'POST', + headers, + body: params.toString(), + headersTimeout: TIMEOUT_MS, + bodyTimeout: TIMEOUT_MS + }); + const text = await response.body.text(); + let body: any = null; + try { + body = JSON.parse(text); + } catch { + // Not JSON: nothing to read an error code from. + } + // Any token in the body means the code was redeemed, whatever the status: + // a 400 that also carries an access_token is not a refusal. + if ( + ['access_token', 'refresh_token', 'id_token'].some( + (key) => typeof body?.[key] === 'string' + ) + ) { + return { kind: 'issued' }; + } + if (response.statusCode >= 400 && response.statusCode < 500) { + return { + kind: 'refused', + status: response.statusCode, + error: typeof body?.error === 'string' ? body.error : null + }; + } + return { + kind: 'unexpected', + message: `HTTP ${response.statusCode} from the token endpoint` + }; + } catch (error) { + return { + kind: 'unexpected', + message: error instanceof Error ? error.message : String(error) + }; + } +} + +/** + * An authorization request that is valid in every way: the registered client + * and redirect URI, a state, and a PKCE challenge. The probes change one + * thing at a time, so what the server does about it is what the probe shows. + */ +function validParams( + options: AuthorizationServerOptions, + redirectUri: string, + state: string +): URLSearchParams { + const verifier = randomBytes(32).toString('base64url'); + const params = new URLSearchParams({ + response_type: 'code', + client_id: options.clientId ?? '', + state, + redirect_uri: redirectUri, + code_challenge: createHash('sha256').update(verifier).digest('base64url'), + code_challenge_method: 'S256' + }); + if (options.resource) { + params.set('resource', options.resource); + } + return params; +} + +function newState(): string { + return randomBytes(16).toString('base64url'); +} + +const PKCE_REFS = [ + SpecReferences.RFC_7636_AUTHORIZATION_REQUEST_ERROR, + SpecReferences.RFC_9700_PKCE +]; +const STATE_REFS = [SpecReferences.RFC_6749_AUTHORIZATION_ERROR_RESPONSE]; +const REDIRECT_REFS = [ + SpecReferences.RFC_9700_REDIRECT_URI_MATCHING, + SpecReferences.RFC_6749_AUTHORIZATION_ERROR_RESPONSE +]; + +const PKCE_DOWNGRADE = { + id: 'pkce-downgrade', + name: 'PKCEDowngrade', + description: + 'Authorization request without a code_challenge gets an invalid_request error redirect, or the code it gets cannot be redeemed with a code_verifier' +}; +const ERROR_REDIRECT_STATE = { + id: 'error-redirect-state', + name: 'ErrorRedirectState', + description: + 'Error redirect to the redirect URI carries the state of the request' +}; +const REDIRECT_URI_EXACT = { + id: 'redirect-uri-exact', + name: 'RedirectURIExact', + description: + 'Authorization request with a redirect URI that only starts with the registered one is not redirected to it' +}; + +/** + * Sends the probes and returns the checks `pkce-downgrade`, + * `error-redirect-state` and `redirect-uri-exact`. + */ +export async function runAuthorizationEndpointProbes( + metadata: Record, + options: AuthorizationServerOptions, + redirectUri: string, + authMethod: AuthMethod | null = null +): Promise { + const endpoint = metadata?.authorization_endpoint; + if (typeof endpoint !== 'string' || !options.clientId) { + return []; + } + + // The control: valid in every way. If the server refuses it, the client or + // the redirect URI is not registered, or the probes are blocked. + const control = await probeAuthorizationEndpoint( + endpoint, + validParams(options, redirectUri, newState()), + redirectUri + ); + const controlRefused = [ + 'refused', + 'error-redirect', + 'redirect', + 'server-error', + 'unreachable' + ].includes(control.kind); + if (controlRefused) { + const reason = `the control request, a valid authorization request for client '${options.clientId}' and redirect URI ${redirectUri}, got ${describeProbe(control)}; is the client registered with that redirect URI?`; + return [ + untestableCheck( + PKCE_DOWNGRADE.id, + PKCE_DOWNGRADE.name, + PKCE_DOWNGRADE.description, + reason, + PKCE_REFS + ), + untestableCheck( + ERROR_REDIRECT_STATE.id, + ERROR_REDIRECT_STATE.name, + ERROR_REDIRECT_STATE.description, + reason, + STATE_REFS + ), + untestableCheck( + REDIRECT_URI_EXACT.id, + REDIRECT_URI_EXACT.name, + REDIRECT_URI_EXACT.description, + reason, + REDIRECT_REFS + ) + ]; + } + + // Authorization request with no code_challenge (and so no method). + const downgradeState = newState(); + const downgradeParams = validParams(options, redirectUri, downgradeState); + downgradeParams.delete('code_challenge'); + downgradeParams.delete('code_challenge_method'); + const downgrade = await probeAuthorizationEndpoint( + endpoint, + downgradeParams, + redirectUri + ); + // A server may issue a code to a request without a challenge (a client that + // does not use PKCE); it must then refuse any code_verifier. + let redemption: Redemption | undefined; + if (downgrade.kind === 'code') { + const code = new URL(downgrade.location).searchParams.get('code') ?? ''; + redemption = await redeemWithVerifier( + metadata, + options, + authMethod, + redirectUri, + code + ); + } + + // An error the server can only report by redirecting: a response type it + // does not support. The client and the redirect URI are valid, so + // RFC 6749 4.1.2.1 has the server redirect with the error and the state. + const unsupportedState = newState(); + const unsupportedParams = validParams(options, redirectUri, unsupportedState); + unsupportedParams.set('response_type', 'conformance-unsupported'); + const unsupported = await probeAuthorizationEndpoint( + endpoint, + unsupportedParams, + redirectUri + ); + + // A redirect URI that is not the registered one but starts with it, in the + // same request as the unsupported response_type above. With a valid client + // and redirect URI the server redirects that error, so the registered URI is + // the baseline: if it gets an error redirect and a near-match does not, the + // difference is the redirect URI. A page tells nothing, so it is not used. + // Only path variants are tried: a query, host or port variant needs more + // care (a native app's loopback redirect may use any port, RFC 8252 7.3). + const near = [`${redirectUri}/extra`, `${redirectUri}x`]; + const nearProbes: { uri: string; probe: Probe }[] = []; + for (const uri of near) { + const nearParams = validParams(options, uri, newState()); + nearParams.set('response_type', 'conformance-unsupported'); + nearProbes.push({ + uri, + probe: await probeAuthorizationEndpoint(endpoint, nearParams, uri) + }); + } + + return [ + pkceDowngradeCheck(downgrade, redemption), + errorRedirectStateCheck([ + { sent: downgradeState, probe: downgrade, label: 'no code_challenge' }, + { + sent: unsupportedState, + probe: unsupported, + label: 'unsupported response_type' + } + ]), + redirectUriExactCheck(unsupported, nearProbes) + ]; +} + +function pkceDowngradeCheck( + probe: Probe, + redemption?: Redemption +): ConformanceCheck { + const { id, name, description } = PKCE_DOWNGRADE; + const refs = PKCE_REFS; + const details = { response: describeProbe(probe), redemption }; + const untestable = (reason: string) => + untestableCheck(id, name, description, reason, refs); + + if (probe.kind === 'code' && redemption) { + return redemptionCheck(redemption, details); + } + + switch (probe.kind) { + case 'error-redirect': + return probe.error === 'invalid_request' + ? check(id, name, description, 'SUCCESS', refs, undefined, details) + : check( + id, + name, + description, + 'FAILURE', + refs, + `Refused with error=${probe.error ?? '(none)'}; RFC 7636 4.4.1 requires invalid_request`, + details + ); + case 'refused': + // The control request was not refused, so a 400 is about the missing + // code_challenge. Other statuses (401, 403, 404, 429) are a gate or a + // rate limit in front of the server, not its answer to the request, + // whatever the body says. + if (probe.status !== 400) { + return untestable( + `the request without a code_challenge got HTTP ${probe.status}, which does not show how the server treats it` + ); + } + // The reason must be seen: a 400 with an HTML page or a body with no + // error says nothing about invalid_request. + if (probe.error === null) { + return untestable( + `the request without a code_challenge got HTTP ${probe.status} with no OAuth error code in the body, so it cannot be told what the refusal was` + ); + } + // A direct 400 does refuse the request, but RFC 7636 4.4.1 requires the + // authorization error response, and with a valid client and redirect URI + // RFC 6749 4.1.2.1 delivers that by redirecting to the redirect URI. + return check( + id, + name, + description, + 'FAILURE', + refs, + probe.error === 'invalid_request' + ? `The request without a code_challenge was answered directly with HTTP ${probe.status} invalid_request; RFC 7636 4.4.1 requires the authorization error response, which RFC 6749 4.1.2.1 delivers by redirecting to the redirect URI with error=invalid_request` + : `Refused with HTTP ${probe.status} ${probe.error}; RFC 7636 4.4.1 requires an error redirect with error=invalid_request`, + details + ); + case 'code': + case 'redirect': + return check( + id, + name, + description, + 'FAILURE', + refs, + `A request without a code_challenge got ${describeProbe(probe)}; RFC 9700 2.1.1 allows a code_verifier only when a code_challenge was sent`, + details + ); + case 'elsewhere': + case 'page': + return untestable( + `the server answered the request without a code_challenge with ${describeProbe(probe)}, so how it treats that request cannot be seen without a login` + ); + default: + return untestable( + `the request without a code_challenge got ${describeProbe(probe)}, which does not show how the server treats it` + ); + } +} + +function redemptionCheck( + redemption: Redemption, + details: Record +): ConformanceCheck { + const { id, name, description } = PKCE_DOWNGRADE; + const refs = PKCE_REFS; + switch (redemption.kind) { + case 'issued': + return check( + id, + name, + description, + 'FAILURE', + refs, + 'A code issued to a request without a code_challenge was redeemed with a code_verifier and got an access token; RFC 9700 2.1.1 requires the server to refuse a code_verifier when no code_challenge was sent', + details + ); + case 'refused': + // Only invalid_grant (RFC 7636 4.6) or invalid_request show that the + // verifier was refused. A 401, a 429, invalid_client or a body with no + // error could have any other cause. + return redemption.status === 400 && + (redemption.error === 'invalid_grant' || + redemption.error === 'invalid_request') + ? check(id, name, description, 'SUCCESS', refs, undefined, details) + : untestableCheck( + id, + name, + description, + `the token request with a code_verifier was refused with HTTP ${redemption.status}${redemption.error ? ` ${redemption.error}` : ''}, which does not show that the verifier was the reason`, + refs + ); + case 'not-tried': + return untestableCheck( + id, + name, + description, + `a code was issued to a request without a code_challenge, but redeeming it with a code_verifier was not tried: ${redemption.reason}`, + refs + ); + case 'unexpected': + return untestableCheck( + id, + name, + description, + `redeeming the code with a code_verifier got an unexpected answer (${redemption.message}), so it cannot be told whether the verifier was refused`, + refs + ); + } +} + +function errorRedirectStateCheck( + probes: { sent: string; probe: Probe; label: string }[] +): ConformanceCheck { + const { id, name, description } = ERROR_REDIRECT_STATE; + const refs = STATE_REFS; + + const seen: string[] = []; + const wrong: string[] = []; + for (const { sent, probe, label } of probes) { + if (probe.kind !== 'error-redirect') continue; + seen.push(label); + if (probe.state.length !== 1 || probe.state[0] !== sent) { + wrong.push( + `${label}: error=${probe.error ?? '(none)'}, state ${probe.state.length === 0 ? 'missing' : `${probe.state.join(',')}`}` + ); + } + } + const details = { + responses: probes.map(({ label, probe }) => ({ + request: label, + response: describeProbe(probe) + })) + }; + + if (wrong.length > 0) { + return check( + id, + name, + description, + 'FAILURE', + refs, + `The error redirect did not carry the request's state exactly once (RFC 6749 4.1.2.1): ${wrong.join('; ')}`, + details + ); + } + if (seen.length === 0) { + return untestableCheck( + id, + name, + description, + 'no probe produced an error redirect to the redirect URI, probably because the server asks for a login first', + refs + ); + } + return check(id, name, description, 'SUCCESS', refs, undefined, details); +} + +function redirectUriExactCheck( + baseline: Probe, + probes: { uri: string; probe: Probe }[] +): ConformanceCheck { + const { id, name, description } = REDIRECT_URI_EXACT; + const refs = REDIRECT_REFS; + const details = { + baseline: describeProbe(baseline), + responses: probes.map(({ uri, probe }) => ({ + redirect_uri: uri, + response: describeProbe(probe) + })) + }; + + // The server redirected to a redirect URI that is not registered. + const accepted = probes.filter(({ probe }) => + ['code', 'error-redirect', 'redirect'].includes(probe.kind) + ); + if (accepted.length > 0) { + return check( + id, + name, + description, + 'FAILURE', + refs, + `The server redirected to a redirect URI that is not an exact match of the registered one: ${accepted.map(({ uri, probe }) => `${uri}: ${describeProbe(probe)}`).join('; ')} (RFC 9700 2.1; RFC 6749 4.1.2.1 forbids redirecting to an invalid URI)`, + details + ); + } + const unexpected = probes.filter(({ probe }) => + ['server-error', 'unreachable'].includes(probe.kind) + ); + if (unexpected.length > 0) { + return untestableCheck( + id, + name, + description, + `a near-match redirect URI got an unexpected answer (${unexpected.map(({ uri, probe }) => `${uri}: ${describeProbe(probe)}`).join('; ')}), so it cannot be told whether the server accepts it`, + refs + ); + } + // A refusal says something about the redirect URI only if the same request + // with the registered URI was answered with an error redirect. Otherwise the + // server may refuse the request for another reason (or show a page, or ask + // for a login), and a 400 for a near-match proves nothing. + if (baseline.kind !== 'error-redirect') { + return untestableCheck( + id, + name, + description, + `the same request with the registered redirect URI got ${describeProbe(baseline)} and not an error redirect, so a refusal of a near-match redirect URI cannot be told apart from a refusal of the request for another reason`, + refs + ); + } + const refused = probes.filter( + ({ probe }) => probe.kind === 'refused' && probe.status === 400 + ); + if (refused.length === probes.length) { + return check(id, name, description, 'SUCCESS', refs, undefined, details); + } + return untestableCheck( + id, + name, + description, + 'the server did not answer every near-match redirect URI with a 400 and did not redirect to any of them (a page, a login, or another status), so how it matches the redirect URI cannot be seen', + refs + ); +}