Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 36 additions & 4 deletions src/auth/oauth-handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,40 @@ function authErrorMessage(prefix: string, e: unknown): string {
return `${prefix}: ${message}`
}

/**
* workers-oauth-provider's descriptions of a sign-in transaction it can't use, and what to tell the
* person instead. The provider gives these no distinct error code, so they are matched by text;
* tests/auth/oauth-routes.test.ts drives each through the real provider, so a reworded provider
* message fails a test rather than silently falling back to the provider's text.
*/
const TRANSACTION_ERROR_PAGES: readonly {
readonly matches: readonly string[]
readonly title: string
readonly message: string
}[] = [
{
matches: ['expired or was already used'],
title: 'This sign-in has already finished',
message:
'This sign-in was already completed, or it took longer than 10 minutes. If your app shows Cloudflare as connected, you can close this page. Otherwise, go back to the app and connect again.'
},
{
matches: ['not started in this browser', 'belongs to a different browser session'],
title: 'Finish signing in where you started',
message:
'This sign-in was started in a different browser or browser profile. Go back to the app, connect again, and complete every step in the same browser.'
}
]

/** The error page for an `AuthorizationError`, explaining unusable sign-in transactions in plain words. */
function authorizationErrorResponse(error: AuthorizationError): Response {
const page = TRANSACTION_ERROR_PAGES.find(({ matches }) =>
matches.some((match) => error.description.includes(match))
)
if (!page) return new OAuthError(error.code, error.description).toHtmlResponse()
return renderErrorPage(page.title, page.message, `Error code: ${error.code}`, 400)
}

/**
* The scopes an MCP token may claim: those requested that Cloudflare actually granted. Cloudflare can
* grant fewer than requested (the account can't grant one, or the user narrows them on its consent);
Expand Down Expand Up @@ -286,8 +320,7 @@ export function createAuthHandlers() {
} catch (e) {
metrics.logEvent(new AuthUser({ errorMessage: authErrorMessage('Authorize POST Error', e) }))
// Consent/upstream transaction expired, used, or opened in another browser: render locally.
if (e instanceof AuthorizationError)
return new OAuthError(e.code, e.description).toHtmlResponse()
if (e instanceof AuthorizationError) return authorizationErrorResponse(e)
if (e instanceof OAuthError) return e.toHtmlResponse()
const errorId = crypto.randomUUID()
console.error(`Authorize POST error [${errorId}]:`, e)
Expand Down Expand Up @@ -369,8 +402,7 @@ export function createAuthHandlers() {
if (e instanceof CimdFetchError) return cimdCallbackFailureResponse()
metrics.logEvent(new AuthUser({ errorMessage: authErrorMessage('Callback Error', e) }))
// Consent/upstream transaction expired, used, or opened in another browser: render locally.
if (e instanceof AuthorizationError)
return new OAuthError(e.code, e.description).toHtmlResponse()
if (e instanceof AuthorizationError) return authorizationErrorResponse(e)
if (e instanceof OAuthError) return e.toHtmlResponse()
const errorId = crypto.randomUUID()
console.error(`Callback error [${errorId}]:`, e)
Expand Down
42 changes: 39 additions & 3 deletions tests/auth/oauth-routes.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1006,7 +1006,9 @@ describe('GET /oauth/callback', () => {
)

expect(res.status).toBe(400)
expect(await res.text()).toContain('not started in this browser')
const html = await res.text()
expect(html).toContain('started in a different browser or browser profile')
expect(html).toContain('Error code: invalid_request')
})

it('rejects a valid state token bound to a different browser session', async () => {
Expand All @@ -1021,7 +1023,7 @@ describe('GET /oauth/callback', () => {
)

expect(res.status).toBe(400)
expect(await res.text()).toContain('not started in this browser')
expect(await res.text()).toContain('started in a different browser or browser profile')
})

it('rejects replay after a state token has completed authorization', async () => {
Expand All @@ -1038,7 +1040,41 @@ describe('GET /oauth/callback', () => {
new Request(callbackUrl, { headers: { Cookie: sessionCookie }, redirect: 'manual' })
)
expect(replay.status).toBe(400)
expect(await replay.text()).toContain('expired or was already used')
const html = await replay.text()
expect(html).toContain('This sign-in has already finished')
expect(html).toContain('If your app shows Cloudflare as connected, you can close this page.')
expect(html).not.toContain('start again')
})

it('explains a consent form submitted twice as a finished sign-in', async () => {
const clientId = await registerClient()
const authRes = await exports.default.fetch(
new Request(
authorizeUrl({
response_type: 'code',
client_id: clientId,
redirect_uri: REDIRECT_URI,
scope: 'user:read'
})
)
)
const consentCookie = cookiesFrom(authRes)
const handle = consentHandle(await authRes.text())
const submit = () =>
exports.default.fetch(
new Request(`${MCP_ORIGIN}/authorize`, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded', Cookie: consentCookie },
body: new URLSearchParams({ handle, scopes: 'user:read' }).toString(),
redirect: 'manual'
})
)

expect((await submit()).status).toBe(302)
const again = await submit()

expect(again.status).toBe(400)
expect(await again.text()).toContain('This sign-in has already finished')
})

it('returns 400 invalid_request when the code is missing', async () => {
Expand Down