// @vitest-environment node import { createHash } from 'node:crypto'; import { createServer, type Server } from 'node:http'; import type { AddressInfo } from 'node:net'; import { exportJWK, generateKeyPair, type JWK, type JWTPayload, type KeyLike, SignJWT, } from 'jose'; import { afterAll, beforeAll, describe, expect, it } from 'vitest'; import { AUTH_ENV, AUTH_PATHS, authorizeClaims, createAuth, DEFAULT_CLOCK_TOLERANCE_SECONDS, DEFAULT_COOKIE_NAME, DEFAULT_SESSION_MAX_AGE_SECONDS, isLoopbackAddress, LOGIN_TIMEOUT_SECONDS, MAX_TOKEN_LENGTH, MIN_SESSION_SECRET_LENGTH, parseCookies, READ_ONLY_ENV, resolveAuthConfig, sanitizeReturnTo, WorkflowWebAuthConfigError, } from './auth.js'; type Handle = Awaited>; /** A resolved configuration's fields, whichever mode it is for. */ type AnyConfig = Record; const resolved = (input: Parameters[0]) => resolveAuthConfig(input) as AnyConfig; // --- A JWKS server and an OIDC provider on 127.0.0.1 ------------------------- interface SigningKey { kid: string; alg: string; privateKey: KeyLike; jwk: JWK; } async function makeKey(kid: string, alg = 'RS256'): Promise { const { privateKey, publicKey } = await generateKeyPair(alg, { extractable: true, }); const jwk = { ...(await exportJWK(publicKey)), kid, alg, use: 'sig' }; return { kid, alg, privateKey, jwk }; } interface Provider { url: string; issuer: string; keys: SigningKey[]; discovery: Record; /** Claims the next token response carries, on top of the defaults. */ nextClaims: Record; /** Overrides the nonce the next ID token carries. */ nextNonce?: string; codes: Map; tokenRequests: Array<{ authorization?: string; body: URLSearchParams }>; jwksRequests: number; server: Server; } const CLIENT_ID = 'workflow-ui'; const CLIENT_SECRET = 'client secret with spaces'; const SESSION_SECRET = 'a'.repeat(MIN_SESSION_SECRET_LENGTH); async function startProvider(): Promise { const provider = { keys: [await makeKey('k1')], nextClaims: {}, codes: new Map(), tokenRequests: [], jwksRequests: 0, } as unknown as Provider; provider.server = createServer(async (req, res) => { const url = new URL(req.url ?? '/', provider.url); if (url.pathname === '/.well-known/openid-configuration') { res.writeHead(200, { 'content-type': 'application/json' }); return res.end(JSON.stringify(provider.discovery)); } if (url.pathname === '/jwks') { provider.jwksRequests++; res.writeHead(200, { 'content-type': 'application/json' }); return res.end(JSON.stringify({ keys: provider.keys.map((k) => k.jwk) })); } if (url.pathname === '/token' && req.method === 'POST') { let raw = ''; for await (const chunk of req) raw += chunk; const body = new URLSearchParams(raw); provider.tokenRequests.push({ authorization: req.headers.authorization, body, }); const pending = provider.codes.get(body.get('code') ?? ''); const verifier = body.get('code_verifier') ?? ''; const challenge = createHash('sha256') .update(verifier) .digest('base64url'); if ( !pending || pending.challenge !== challenge || pending.redirectUri !== body.get('redirect_uri') ) { res.writeHead(400, { 'content-type': 'application/json' }); return res.end(JSON.stringify({ error: 'invalid_grant' })); } provider.codes.delete(body.get('code') ?? ''); const idToken = await sign(provider.keys[0], { iss: provider.issuer, aud: CLIENT_ID, sub: 'user-1', nonce: provider.nextNonce ?? pending.nonce, email: 'ada@example.com', email_verified: true, ...provider.nextClaims, }); res.writeHead(200, { 'content-type': 'application/json' }); return res.end( JSON.stringify({ id_token: idToken, token_type: 'Bearer' }) ); } res.writeHead(404).end(); }); await new Promise((resolve) => provider.server.listen(0, '127.0.0.1', resolve) ); const { port } = provider.server.address() as AddressInfo; provider.url = `http://127.0.0.1:${port}`; provider.issuer = provider.url; provider.discovery = { issuer: provider.issuer, authorization_endpoint: `${provider.url}/authorize`, token_endpoint: `${provider.url}/token`, jwks_uri: `${provider.url}/jwks`, code_challenge_methods_supported: ['S256'], token_endpoint_auth_methods_supported: [ 'client_secret_basic', 'client_secret_post', ], id_token_signing_alg_values_supported: ['RS256'], }; return provider; } async function sign( key: SigningKey, claims: JWTPayload, { expiresIn = 300, issuedAt, }: { expiresIn?: number | null; issuedAt?: number } = {} ) { const now = issuedAt ?? Math.floor(Date.now() / 1000); const jwt = new SignJWT(claims) .setProtectedHeader({ alg: key.alg, kid: key.kid }) .setIssuedAt(now); if (expiresIn !== null) jwt.setExpirationTime(now + expiresIn); return jwt.sign(key.privateKey); } let provider: Provider; beforeAll(async () => { provider = await startProvider(); }); afterAll(async () => { await new Promise((resolve) => provider.server.close(resolve)); }); const PUBLIC_HOST = 'workflow.example.com'; function request( path: string, init: RequestInit & { ip?: string; host?: string } = {} ): Request { const { ip, host = PUBLIC_HOST, ...rest } = init; const headers = new Headers(rest.headers); if (!headers.has('host')) headers.set('host', host); const req = new Request(`http://${host}${path}`, { ...rest, headers }); if (ip !== undefined) Object.defineProperty(req, 'ip', { value: ip }); return req; } function responseOf(result: Awaited>) { if (!('response' in result)) throw new Error('expected a response'); return result.response; } function contextOf(result: Awaited>) { if (!('context' in result)) { throw new Error(`expected a context, got ${result.response.status}`); } return result.context; } function configError(fn: () => unknown): WorkflowWebAuthConfigError { try { fn(); } catch (error) { expect(error).toBeInstanceOf(WorkflowWebAuthConfigError); return error as WorkflowWebAuthConfigError; } throw new Error('expected a configuration error'); } // --- Configuration ----------------------------------------------------------- describe('resolveAuthConfig', () => { const jwtEnv = () => ({ [AUTH_ENV.mode]: 'jwt', [AUTH_ENV.issuer]: 'https://issuer.example.com', [AUTH_ENV.audience]: 'workflow-ui', [AUTH_ENV.jwksUrl]: 'https://issuer.example.com/jwks', }); it('defaults to the loopback-only mode without any variable', () => { expect(resolveAuthConfig({ env: {} })).toMatchObject({ mode: 'local', readOnly: false, }); }); it('refuses auth variables without a mode', () => { const error = configError(() => resolveAuthConfig({ env: { [AUTH_ENV.issuer]: 'https://issuer.example.com' }, }) ); expect(error.message).toContain(AUTH_ENV.issuer); expect(error.message).toContain(AUTH_ENV.mode); }); it('refuses an unknown mode and settings that none ignores', () => { configError(() => resolveAuthConfig({ env: { [AUTH_ENV.mode]: 'basic' } })); configError(() => resolveAuthConfig({ env: { [AUTH_ENV.mode]: 'none', [AUTH_ENV.issuer]: 'https://x.dev' }, }) ); }); it('reads a complete jwt configuration with its defaults', () => { const config = resolveAuthConfig({ env: jwtEnv() }); expect(config).toMatchObject({ mode: 'jwt', audience: ['workflow-ui'], tokenHeader: 'authorization', clockTolerance: DEFAULT_CLOCK_TOLERANCE_SECONDS, }); expect((config as AnyConfig).algorithms).not.toContain('HS256'); }); it('lists every missing jwt setting at once', () => { const error = configError(() => resolveAuthConfig({ env: { [AUTH_ENV.mode]: 'jwt' } }) ); expect(error.problems).toHaveLength(3); }); it.each([ [AUTH_ENV.algorithms, 'HS256'], [AUTH_ENV.algorithms, 'none'], [AUTH_ENV.jwksUrl, 'http://issuer.example.com/jwks'], [AUTH_ENV.jwksUrl, 'not a url'], [AUTH_ENV.clockTolerance, '-1'], [AUTH_ENV.clockTolerance, '1.5'], [AUTH_ENV.requiredClaims, '{not json'], [AUTH_ENV.requiredClaims, '["environment"]'], [AUTH_ENV.allowedDomains, 'localhost'], [AUTH_ENV.tokenHeader, 'bad header'], [AUTH_ENV.clientId, 'oidc-only'], ])('refuses %s=%s', (name, value) => { configError(() => resolveAuthConfig({ env: { ...jwtEnv(), [name]: value } }) ); }); it('accepts http only for loopback key and issuer URLs', () => { const config = resolved({ env: { ...jwtEnv(), [AUTH_ENV.issuer]: 'http://localhost:8080', [AUTH_ENV.jwksUrl]: 'http://127.0.0.1:8080/jwks', }, }); expect(config.jwksUrl?.href).toBe('http://127.0.0.1:8080/jwks'); }); it('lets the auth option replace the variables', () => { expect( resolveAuthConfig({ auth: 'none', env: { [AUTH_ENV.mode]: 'jwt' } }).mode ).toBe('none'); expect(resolveAuthConfig({ auth: false, env: jwtEnv() }).mode).toBe('none'); }); it('reads WORKFLOW_WEB_READ_ONLY in every mode', () => { expect(resolveAuthConfig({ env: { [READ_ONLY_ENV]: '1' } }).readOnly).toBe( true ); expect(resolveAuthConfig({ env: { [READ_ONLY_ENV]: '' } }).readOnly).toBe( false ); configError(() => resolveAuthConfig({ env: { [READ_ONLY_ENV]: 'yes' } })); }); describe('oidc', () => { const oidcEnv = (basename = '') => ({ [AUTH_ENV.mode]: 'oidc', [AUTH_ENV.issuer]: 'https://login.example.com', [AUTH_ENV.clientId]: CLIENT_ID, [AUTH_ENV.redirectUri]: `https://${PUBLIC_HOST}${basename}${AUTH_PATHS.callback}`, [AUTH_ENV.sessionSecret]: SESSION_SECRET, }); it('accepts an algorithm restriction for ID tokens', () => { expect( resolved({ env: { ...oidcEnv(), [AUTH_ENV.algorithms]: 'ES256' } }) .algorithms ).toEqual(['ES256']); }); it('derives discovery, scopes and cookie settings', () => { const config = resolveAuthConfig({ env: oidcEnv() }); expect(config).toMatchObject({ discoveryUrl: new URL( 'https://login.example.com/.well-known/openid-configuration' ), scopes: ['openid', 'email', 'profile'], cookieSecure: true, cookieName: `__Host-${DEFAULT_COOKIE_NAME}`, sessionMaxAge: DEFAULT_SESSION_MAX_AGE_SECONDS, }); }); it('always requests the openid scope', () => { const config = resolved({ env: { ...oidcEnv(), [AUTH_ENV.scopes]: 'email groups' }, }); expect(config.scopes).toEqual(['openid', 'email', 'groups']); }); it('requires the redirect URI to be the callback under the basename', () => { expect( resolved({ env: oidcEnv('/workflows'), basename: '/workflows', }).redirectUri ).toBe(`https://${PUBLIC_HOST}/workflows${AUTH_PATHS.callback}`); configError(() => resolveAuthConfig({ env: oidcEnv(), basename: '/workflows' }) ); }); it.each([ [AUTH_ENV.sessionSecret, 'short'], [AUTH_ENV.redirectUri, `http://${PUBLIC_HOST}${AUTH_PATHS.callback}`], [ AUTH_ENV.redirectUri, `https://${PUBLIC_HOST}${AUTH_PATHS.callback}?x=1`, ], [AUTH_ENV.cookieSecure, 'false'], [AUTH_ENV.sessionMaxAge, '10'], [AUTH_ENV.audience, 'anything'], [AUTH_ENV.jwksUrl, 'https://login.example.com/jwks'], ])('refuses %s=%s', (name, value) => { configError(() => resolveAuthConfig({ env: { ...oidcEnv(), [name]: value } }) ); }); it('refuses to start when discovery names another issuer', async () => { const error = await createAuth({ env: { ...oidcEnv(), [AUTH_ENV.issuer]: `${provider.issuer}/other`, [AUTH_ENV.discoveryUrl]: `${provider.url}/.well-known/openid-configuration`, }, }).catch((e) => e); expect(error).toBeInstanceOf(WorkflowWebAuthConfigError); expect(error.message).toContain('issuer'); }); it('refuses to start when discovery cannot be read', async () => { const error = await createAuth({ env: { ...oidcEnv(), [AUTH_ENV.issuer]: `${provider.url}/missing`, }, }).catch((e) => e); expect(error).toBeInstanceOf(WorkflowWebAuthConfigError); }); }); }); // --- local and none ---------------------------------------------------------- describe('local mode', () => { let auth: Handle; beforeAll(async () => { auth = await createAuth({ env: {} }); }); it.each([ ['127.0.0.1', 'localhost:3456'], ['::1', 'localhost:3456'], ['::ffff:127.0.0.1', '127.0.0.1:3456'], ['127.0.0.1', 'app.localhost:3456'], [undefined, 'localhost:3456'], ])('serves client %s at Host %s', async (ip, host) => { const context = contextOf(await auth.handle(request('/', { ip, host }))); expect(context).toEqual({ mode: 'local', access: 'write' }); }); it.each([ // A remote client, even one that claims a loopback Host. ['10.0.0.5', 'localhost:3456'], ['192.168.1.20', '192.168.1.10:3456'], // A reverse proxy on the same machine that keeps the public Host. ['127.0.0.1', `${PUBLIC_HOST}`], [undefined, '10.0.0.1:3456'], ])('refuses client %s at Host %s', async (ip, host) => { const response = responseOf(await auth.handle(request('/', { ip, host }))); expect(response.status).toBe(403); expect(await response.text()).toContain(AUTH_ENV.mode); }); it('treats only 127.0.0.0/8 and ::1 as loopback', () => { expect(isLoopbackAddress('127.10.0.1')).toBe(true); expect(isLoopbackAddress('::ffff:10.0.0.1')).toBe(false); expect(isLoopbackAddress('0.0.0.0')).toBe(false); }); it('serves anyone with mode none, read-only when asked', async () => { const none = await createAuth({ env: { [AUTH_ENV.mode]: 'none', [READ_ONLY_ENV]: 'true' }, }); const context = contextOf( await none.handle(request('/', { ip: '10.0.0.5' })) ); expect(context).toEqual({ mode: 'none', access: 'read' }); }); }); // --- jwt --------------------------------------------------------------------- describe('jwt mode', () => { const env = (extra: Record = {}) => ({ [AUTH_ENV.mode]: 'jwt', [AUTH_ENV.issuer]: provider.issuer, [AUTH_ENV.audience]: 'https://workflow.example.com', [AUTH_ENV.jwksUrl]: `${provider.url}/jwks`, ...extra, }); const claims = (extra: JWTPayload = {}) => ({ iss: provider.issuer, aud: 'https://workflow.example.com', sub: 'owner:acme:project:console:environment:production', environment: 'production', ...extra, }); const bearer = (token: string) => ({ authorization: `Bearer ${token}` }); it('accepts a valid bearer token with write access', async () => { const auth = await createAuth({ env: env() }); const token = await sign(provider.keys[0], claims()); const context = contextOf( await auth.handle(request('/api/rpc', { headers: bearer(token) })) ); expect(context).toMatchObject({ mode: 'jwt', access: 'write', subject: claims().sub, }); }); it('answers 401 with a Bearer challenge without a token', async () => { const auth = await createAuth({ env: env() }); const response = responseOf(await auth.handle(request('/'))); expect(response.status).toBe(401); expect(response.headers.get('www-authenticate')).toMatch(/^Bearer /); }); it.each([ ['another audience', { aud: 'https://other.example.com' }], ['another issuer', { iss: 'https://evil.example.com' }], ])('refuses a token for %s', async (_, extra) => { const auth = await createAuth({ env: env() }); const token = await sign(provider.keys[0], claims(extra)); const response = responseOf( await auth.handle(request('/', { headers: bearer(token) })) ); expect(response.status).toBe(401); }); it('refuses a token without exp', async () => { const auth = await createAuth({ env: env() }); const token = await sign(provider.keys[0], claims(), { expiresIn: null }); expect( responseOf(await auth.handle(request('/', { headers: bearer(token) }))) .status ).toBe(401); }); it('accepts expiry within the clock tolerance only', async () => { const auth = await createAuth({ env: env() }); const now = Math.floor(Date.now() / 1000); const lifetime = 60; const justExpired = await sign(provider.keys[0], claims(), { issuedAt: now - lifetime - 1, expiresIn: lifetime, }); contextOf( await auth.handle(request('/', { headers: bearer(justExpired) })) ); const longExpired = await sign(provider.keys[0], claims(), { issuedAt: now - lifetime - DEFAULT_CLOCK_TOLERANCE_SECONDS - 1, expiresIn: lifetime, }); expect( responseOf( await auth.handle(request('/', { headers: bearer(longExpired) })) ).status ).toBe(401); }); it('refuses an algorithm outside the allowed list', async () => { const es = await makeKey('es1', 'ES256'); provider.keys.push(es); try { const auth = await createAuth({ env: env({ [AUTH_ENV.algorithms]: 'RS256' }), }); const token = await sign(es, claims()); expect( responseOf(await auth.handle(request('/', { headers: bearer(token) }))) .status ).toBe(401); } finally { provider.keys.pop(); } }); it('verifies tokens from every key the JWKS publishes, for rotation', async () => { const next = await makeKey('k2'); provider.keys.push(next); try { const auth = await createAuth({ env: env() }); for (const key of provider.keys) { const token = await sign(key, claims()); contextOf(await auth.handle(request('/', { headers: bearer(token) }))); } } finally { provider.keys.pop(); } }); it('refuses an oversized token without verifying it', async () => { const auth = await createAuth({ env: env() }); const response = responseOf( await auth.handle( request('/', { headers: bearer('x'.repeat(MAX_TOKEN_LENGTH + 1)) }) ) ); expect(response.status).toBe(401); }); it('reads a bare token from a custom header', async () => { const auth = await createAuth({ env: env({ [AUTH_ENV.tokenHeader]: 'X-Proxy-Token' }), }); const token = await sign(provider.keys[0], claims()); contextOf( await auth.handle(request('/', { headers: { 'x-proxy-token': token } })) ); // The default header is no longer read. expect( responseOf(await auth.handle(request('/', { headers: bearer(token) }))) .status ).toBe(401); }); it('accepts a cookie token, but only for same-origin writes', async () => { const auth = await createAuth({ env: env({ [AUTH_ENV.tokenCookie]: 'ui_token' }), }); const token = await sign(provider.keys[0], claims()); const cookie = `other=1; ui_token=${token}`; contextOf(await auth.handle(request('/', { headers: { cookie } }))); const post = (headers: Record) => auth.handle( request('/api/rpc', { method: 'POST', headers: { cookie, ...headers }, }), { allowedHosts: true, } ); contextOf(await post({ origin: `http://${PUBLIC_HOST}` })); expect(responseOf(await post({})).status).toBe(403); expect( responseOf(await post({ origin: 'https://evil.example.com' })).status ).toBe(403); }); it('enforces required claims and the subject allowlist', async () => { const auth = await createAuth({ env: env({ [AUTH_ENV.requiredClaims]: JSON.stringify({ environment: ['production', 'preview'], }), [AUTH_ENV.allowedSubjects]: claims().sub, }), }); contextOf( await auth.handle( request('/', { headers: bearer(await sign(provider.keys[0], claims())), }) ) ); for (const extra of [ { environment: 'development' }, { sub: 'owner:acme:project:other:environment:production' }, ]) { const token = await sign(provider.keys[0], claims(extra)); expect( responseOf(await auth.handle(request('/', { headers: bearer(token) }))) .status ).toBe(403); } }); it('grants read access with WORKFLOW_WEB_READ_ONLY', async () => { const auth = await createAuth({ env: { ...env(), [READ_ONLY_ENV]: '1' } }); const token = await sign(provider.keys[0], claims()); expect( contextOf(await auth.handle(request('/', { headers: bearer(token) }))) .access ).toBe('read'); }); }); // --- Authorization ----------------------------------------------------------- describe('authorizeClaims', () => { const config = (extra: Record = {}) => resolveAuthConfig({ auth: { mode: 'jwt', issuer: 'https://issuer.example.com', audience: 'aud', jwksUrl: 'https://issuer.example.com/jwks', ...extra, }, env: {}, }); it('allows any verified token without an allowlist', async () => { expect(await authorizeClaims({ sub: 'x' }, config())).toEqual({ ok: true, access: 'write', }); }); it('counts emails and domains only when verified', async () => { const policy = config({ allowedEmails: 'Ada@Example.com', allowedDomains: 'corp.example', }); expect( ( await authorizeClaims( { email: 'ada@example.com', email_verified: true }, policy ) ).ok ).toBe(true); expect( ( await authorizeClaims( { email: 'bob@corp.example', email_verified: true }, policy ) ).ok ).toBe(true); expect( (await authorizeClaims({ email: 'ada@example.com' }, policy)).ok ).toBe(false); expect( ( await authorizeClaims( { email: 'bob@sub.corp.example', email_verified: true }, policy ) ).ok ).toBe(false); }); it('gives write access only to writeGroups when set', async () => { const policy = config({ allowedGroups: ['viewers', 'admins'], writeGroups: 'admins', }); expect(await authorizeClaims({ groups: ['viewers'] }, policy)).toEqual({ ok: true, access: 'read', }); expect(await authorizeClaims({ groups: ['admins'] }, policy)).toEqual({ ok: true, access: 'write', }); expect((await authorizeClaims({ groups: ['others'] }, policy)).ok).toBe( false ); }); it('lets authorize refuse or downgrade, but never lift read-only', async () => { expect( await authorizeClaims({}, config({ authorize: () => 'read' })) ).toEqual({ ok: true, access: 'read' }); expect( (await authorizeClaims({}, config({ authorize: () => false }))).ok ).toBe(false); const readOnly = resolveAuthConfig({ auth: { mode: 'jwt', issuer: 'https://issuer.example.com', audience: 'aud', jwksUrl: 'https://issuer.example.com/jwks', authorize: () => 'write', }, readOnly: true, env: {}, }); expect(await authorizeClaims({}, readOnly)).toEqual({ ok: true, access: 'read', }); }); }); // --- Return URLs ------------------------------------------------------------- describe('sanitizeReturnTo', () => { it.each([ ['/.//evil.example.com'], ['/a/..//evil.example.com'], ['//evil.example.com'], ])('keeps %s on this origin with the root basename', (raw) => { expect(sanitizeReturnTo(raw, '')).toBe('/'); }); it.each([ ['/run/wrun_1?tab=events', '', '/run/wrun_1?tab=events'], ['/workflows/run/wrun_1', '/workflows', '/workflows/run/wrun_1'], ['/workflows', '/workflows', '/workflows'], ])('keeps %s under %s', (raw, basename, expected) => { expect(sanitizeReturnTo(raw, basename)).toBe(expected); }); it.each([ ['//evil.example.com/'], ['/.//evil.example.com'], ['/./\\evil.example.com'], ['/workflows/..//evil.example.com'], ['https://evil.example.com/'], ['/\\evil.example.com'], ['\\\\evil.example.com'], ['/\t/evil.example.com'], ['javascript:alert(1)'], ['/other-app/'], ['/workflows-other/'], [`/workflows${AUTH_PATHS.login}`], [null], [`/${'a'.repeat(4096)}`], ])('replaces %s with the dashboard root', (raw) => { expect(sanitizeReturnTo(raw, '/workflows')).toBe('/workflows/'); }); }); // --- oidc ---------------------------------------------------------------------- /** Follow the login redirect the way the provider would, and return a code. */ function authorizeAtProvider(location: string) { const url = new URL(location); expect(url.origin + url.pathname).toBe(`${provider.url}/authorize`); expect(url.searchParams.get('code_challenge_method')).toBe('S256'); const code = `code-${Math.random()}`; provider.codes.set(code, { challenge: url.searchParams.get('code_challenge') ?? '', nonce: url.searchParams.get('nonce') ?? '', redirectUri: url.searchParams.get('redirect_uri') ?? '', }); return { code, state: url.searchParams.get('state') ?? '' }; } function setCookies(response: Response) { return response.headers.getSetCookie(); } function cookieValue(response: Response, name: string) { const line = setCookies(response).find((c) => c.startsWith(`${name}=`)); return line?.slice(name.length + 1).split(';')[0]; } describe('oidc mode', () => { const basename = '/workflows'; const env = (extra: Record = {}) => ({ [AUTH_ENV.mode]: 'oidc', [AUTH_ENV.issuer]: provider.issuer, [AUTH_ENV.clientId]: CLIENT_ID, [AUTH_ENV.clientSecret]: CLIENT_SECRET, [AUTH_ENV.redirectUri]: `https://${PUBLIC_HOST}${basename}${AUTH_PATHS.callback}`, [AUTH_ENV.sessionSecret]: SESSION_SECRET, [AUTH_ENV.allowedDomains]: 'example.com', ...extra, }); const cookieName = `__Host-${DEFAULT_COOKIE_NAME}`; async function signIn(auth: Handle, returnTo = `${basename}/run/wrun_1`) { const start = responseOf( await auth.handle( request( `${basename}${AUTH_PATHS.login}?returnTo=${encodeURIComponent(returnTo)}` ) ) ); expect(start.status).toBe(302); const loginCookie = setCookies(start)[0].split(';')[0]; const { code, state } = authorizeAtProvider( start.headers.get('location') ?? '' ); const callback = responseOf( await auth.handle( request( `${basename}${AUTH_PATHS.callback}?code=${code}&state=${state}`, { headers: { cookie: loginCookie }, } ) ) ); return { start, callback, loginCookie }; } it('signs in with PKCE and a client secret, then serves the session', async () => { const auth = await createAuth({ env: env(), basename }); const { start, callback } = await signIn(auth); expect(setCookies(start)[0]).toMatch( new RegExp( `^${cookieName}_login=.+; Path=/; Max-Age=${LOGIN_TIMEOUT_SECONDS}; HttpOnly; SameSite=Lax; Secure$` ) ); expect(callback.status).toBe(303); expect(callback.headers.get('location')).toBe(`${basename}/run/wrun_1`); const session = setCookies(callback).find((c) => c.startsWith(`${cookieName}=`) ); expect(session).toMatch( new RegExp( `; Path=/; Max-Age=${DEFAULT_SESSION_MAX_AGE_SECONDS}; HttpOnly; SameSite=Lax; Secure$` ) ); // The login cookie is cleared. expect(setCookies(callback)).toContainEqual( expect.stringMatching(new RegExp(`^${cookieName}_login=; .*Max-Age=0`)) ); // RFC 6749 2.3.1: the secret is form-encoded inside the Basic header. const sent = provider.tokenRequests.at(-1); expect(sent?.authorization).toBe( `Basic ${Buffer.from(`${CLIENT_ID}:${CLIENT_SECRET.replace(/ /g, '+')}`).toString('base64')}` ); expect(sent?.body.get('client_secret')).toBeNull(); const value = cookieValue(callback, cookieName); const context = contextOf( await auth.handle( request(`${basename}/api/rpc`, { method: 'POST', headers: { cookie: `${cookieName}=${value}`, origin: `https://${PUBLIC_HOST}`, }, }) ) ); expect(context).toMatchObject({ mode: 'oidc', access: 'write', subject: 'user-1', email: 'ada@example.com', }); }); it('redirects page loads to the login, and answers API calls with 401', async () => { const auth = await createAuth({ env: env(), basename }); const page = responseOf( await auth.handle( request(`${basename}/run/wrun_1?tab=events`, { headers: { accept: 'text/html' }, }) ) ); expect(page.status).toBe(302); expect(page.headers.get('location')).toBe( `${basename}${AUTH_PATHS.login}?returnTo=${encodeURIComponent(`${basename}/run/wrun_1?tab=events`)}` ); for (const path of ['/api/rpc', '/api/stream/s1?runId=r']) { const response = responseOf( await auth.handle( request(`${basename}${path}`, { headers: { accept: 'text/html' } }) ) ); expect(response.status).toBe(401); } const asset = responseOf( await auth.handle( request(`${basename}/assets/app.js`, { headers: { accept: '*/*' } }) ) ); expect(asset.status).toBe(401); }); it('never redirects back off the dashboard', async () => { const auth = await createAuth({ env: env(), basename }); const { callback } = await signIn(auth, '//evil.example.com/'); expect(callback.headers.get('location')).toBe(`${basename}/`); }); it('refuses a callback whose state does not match the browser', async () => { const auth = await createAuth({ env: env(), basename }); const start = responseOf( await auth.handle(request(`${basename}${AUTH_PATHS.login}`)) ); const loginCookie = setCookies(start)[0].split(';')[0]; const { code } = authorizeAtProvider(start.headers.get('location') ?? ''); const response = responseOf( await auth.handle( request(`${basename}${AUTH_PATHS.callback}?code=${code}&state=forged`, { headers: { cookie: loginCookie }, }) ) ); expect(response.status).toBe(400); expect( setCookies(response).some((c) => c.startsWith(`${cookieName}=`)) ).toBe(false); }); it('refuses a callback without the login cookie', async () => { const auth = await createAuth({ env: env(), basename }); const response = responseOf( await auth.handle( request(`${basename}${AUTH_PATHS.callback}?code=c&state=s`) ) ); expect(response.status).toBe(400); }); it('refuses an ID token with another nonce', async () => { const auth = await createAuth({ env: env(), basename }); provider.nextNonce = 'replayed'; try { const { callback } = await signIn(auth); expect(callback.status).toBe(401); } finally { provider.nextNonce = undefined; } }); it('refuses a callback naming another issuer (RFC 9207)', async () => { const auth = await createAuth({ env: env(), basename }); const start = responseOf( await auth.handle(request(`${basename}${AUTH_PATHS.login}`)) ); const loginCookie = setCookies(start)[0].split(';')[0]; const { code, state } = authorizeAtProvider( start.headers.get('location') ?? '' ); const response = responseOf( await auth.handle( request( `${basename}${AUTH_PATHS.callback}?code=${code}&state=${state}&iss=${encodeURIComponent('https://evil.example.com')}`, { headers: { cookie: loginCookie } } ) ) ); expect(response.status).toBe(400); }); it.each([ ['outside the allowed domains', { email: 'eve@evil.example' }], ['with an unverified email', { email_verified: false }], ])('refuses an account %s', async (_, extra) => { const auth = await createAuth({ env: env(), basename }); provider.nextClaims = extra; try { const { callback } = await signIn(auth); expect(callback.status).toBe(403); expect( setCookies(callback).some((c) => c.startsWith(`${cookieName}=`)) ).toBe(false); } finally { provider.nextClaims = {}; } }); it('refuses a cross-site write even with a valid session', async () => { const auth = await createAuth({ env: env(), basename }); const value = cookieValue((await signIn(auth)).callback, cookieName); const response = responseOf( await auth.handle( request(`${basename}/api/rpc`, { method: 'POST', headers: { cookie: `${cookieName}=${value}`, origin: 'https://evil.example.com', }, }), { allowedHosts: true } ) ); expect(response.status).toBe(403); }); it('rejects tampered sessions and those from before a policy change', async () => { const auth = await createAuth({ env: env(), basename }); const value = cookieValue((await signIn(auth)).callback, cookieName) ?? ''; const tampered = `${value.slice(0, -2)}${value.endsWith('A') ? 'B' : 'A'}`; const api = (cookie: string, handle: Handle) => handle.handle( request(`${basename}/api/rpc?method=x`, { headers: { cookie } }) ); expect( responseOf(await api(`${cookieName}=${tampered}`, auth)).status ).toBe(401); const stricter = await createAuth({ env: env({ [AUTH_ENV.allowedDomains]: 'corp.example' }), basename, }); expect( responseOf(await api(`${cookieName}=${value}`, stricter)).status ).toBe(401); }); it('opens sessions sealed with a rotated-out secret', async () => { const before = await createAuth({ env: env(), basename }); const value = cookieValue((await signIn(before)).callback, cookieName); const rotated = await createAuth({ env: env({ [AUTH_ENV.sessionSecret]: `${'b'.repeat(MIN_SESSION_SECRET_LENGTH)},${SESSION_SECRET}`, }), basename, }); contextOf( await rotated.handle( request(`${basename}/`, { headers: { cookie: `${cookieName}=${value}` }, }) ) ); const dropped = await createAuth({ env: env({ [AUTH_ENV.sessionSecret]: 'b'.repeat(MIN_SESSION_SECRET_LENGTH), }), basename, }); expect( responseOf( await dropped.handle( request(`${basename}/api/rpc`, { headers: { cookie: `${cookieName}=${value}` }, }) ) ).status ).toBe(401); }); it('signs out by clearing the session cookie', async () => { const auth = await createAuth({ env: env(), basename }); const response = responseOf( await auth.handle(request(`${basename}${AUTH_PATHS.logout}`)) ); expect(response.status).toBe(200); expect(setCookies(response)[0]).toMatch( new RegExp(`^${cookieName}=; .*Max-Age=0`) ); }); it('sends a public client id in the body, without a secret', async () => { const values = env(); delete (values as Record)[AUTH_ENV.clientSecret]; const auth = await createAuth({ env: values, basename }); const { callback } = await signIn(auth); expect(callback.status).toBe(303); const sent = provider.tokenRequests.at(-1); expect(sent?.authorization).toBeUndefined(); expect(sent?.body.get('client_id')).toBe(CLIENT_ID); expect(sent?.body.get('code_verifier')).toBeTruthy(); }); it('rejects HEAD on login and callback without exchanging codes', async () => { const auth = await createAuth({ env: env(), basename }); const loginHead = responseOf( await auth.handle( request(`${basename}${AUTH_PATHS.login}`, { method: 'HEAD' }) ) ); expect(loginHead.status).toBe(405); expect(loginHead.headers.get('allow')).toBe('GET'); const start = responseOf( await auth.handle(request(`${basename}${AUTH_PATHS.login}`)) ); const loginCookie = setCookies(start)[0].split(';')[0]; const { code, state } = authorizeAtProvider( start.headers.get('location') ?? '' ); const tokenRequestsBefore = provider.tokenRequests.length; const cbHead = responseOf( await auth.handle( request( `${basename}${AUTH_PATHS.callback}?code=${code}&state=${state}`, { method: 'HEAD', headers: { cookie: loginCookie }, } ) ) ); expect(cbHead.status).toBe(405); expect(provider.tokenRequests.length).toBe(tokenRequestsBefore); }); it('requires azp matching clientId when the ID token has multiple audiences', async () => { const auth = await createAuth({ env: env(), basename }); provider.nextClaims = { aud: [CLIENT_ID, 'other-client'] }; try { const { callback } = await signIn(auth); expect(callback.status).toBe(401); } finally { provider.nextClaims = {}; } provider.nextClaims = { aud: [CLIENT_ID, 'other-client'], azp: CLIENT_ID }; try { const { callback } = await signIn(auth); expect(callback.status).toBe(303); } finally { provider.nextClaims = {}; } }); it('requires iss on callback when discovery advertises RFC 9207 support', async () => { provider.discovery.authorization_response_iss_parameter_supported = true; try { const auth = await createAuth({ env: env(), basename }); const start = responseOf( await auth.handle(request(`${basename}${AUTH_PATHS.login}`)) ); const loginCookie = setCookies(start)[0].split(';')[0]; const { code, state } = authorizeAtProvider( start.headers.get('location') ?? '' ); const missingIss = responseOf( await auth.handle( request( `${basename}${AUTH_PATHS.callback}?code=${code}&state=${state}`, { headers: { cookie: loginCookie } } ) ) ); expect(missingIss.status).toBe(400); } finally { delete provider.discovery.authorization_response_iss_parameter_supported; } }); }); describe('parseCookies', () => { it('keeps the first of duplicate names', () => { expect(parseCookies('a=1; b="2"; a=3')).toEqual( new Map([ ['a', '1'], ['b', '2'], ]) ); }); });