Skip to content
Merged
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
9 changes: 9 additions & 0 deletions src/auth/oauth-handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,11 @@ interface AuthEnv extends Env {
OAUTH_PROVIDER: OAuthHelpers
}

/** The provider has already validated the client; only a CIMD client ID is an https URL. */
function isClientIdMetadataDocumentUrl(clientId: string): boolean {
return clientId.startsWith('https://')
}

// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- The OAuth provider attaches this helper binding at runtime.
const env = cloudflareEnv as AuthEnv
const ALLOWED_SCOPES = new Set<string>(ALL_SCOPES)
Expand Down Expand Up @@ -372,6 +377,10 @@ export function createAuthHandlers() {
const { redirectTo } = await env.OAUTH_PROVIDER.completeAuthorization({
request: oauthReqInfo,
userId: identity.user.id,
// A CIMD client ID and its callback are shared by every connection a hosted client
// holds, so replacing "existing" grants revokes the user's other live connections.
// Registered clients get a client ID per install and keep replacement.
revokeExistingGrants: !isClientIdMetadataDocumentUrl(oauthReqInfo.clientId),
metadata: { label: identity.user.email },
scope: grantedScopes(oauthReqInfo.scope, upstreamScope),
props: {
Expand Down
71 changes: 71 additions & 0 deletions tests/auth/cimd.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,60 @@ function useCloudflareAuthSuccess(): void {
)
}

/** Run the full CIMD authorization and code exchange, returning the issued refresh token. */
async function authorizeAndExchange(): Promise<string> {
const authorization = await exports.default.fetch(new Request(authorizeUrl()))
const handle = (await authorization.text()).match(/name="handle" value="([^"]+)"/)?.[1]
const approval = await exports.default.fetch(
new Request(`${MCP_ORIGIN}/authorize`, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
Cookie: cookiesFrom(authorization)
},
body: new URLSearchParams({ handle: handle!, scopes: 'user:read' }).toString(),
redirect: 'manual'
})
)
const upstreamState = new URL(approval.headers.get('location')!).searchParams.get('state')
const callback = await exports.default.fetch(
new Request(
`${MCP_ORIGIN}/oauth/callback?code=authcode&state=${encodeURIComponent(upstreamState!)}`,
{ headers: { Cookie: cookiesFrom(approval) }, redirect: 'manual' }
)
)
const code = new URL(callback.headers.get('location')!).searchParams.get('code')
const tokenResponse = await exports.default.fetch(
new Request(`${MCP_ORIGIN}/token`, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({
grant_type: 'authorization_code',
code: code!,
client_id: CIMD_CLIENT_ID,
redirect_uri: REDIRECT_URI,
code_verifier: DOWNSTREAM_CODE_VERIFIER,
resource: MCP_RESOURCE
}).toString()
})
)
expect(tokenResponse.status).toBe(200)
return ((await tokenResponse.json()) as { refresh_token: string }).refresh_token
}

function refreshRequest(refreshToken: string): Request {
return new Request(`${MCP_ORIGIN}/token`, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({
grant_type: 'refresh_token',
refresh_token: refreshToken,
client_id: CIMD_CLIENT_ID,
resource: MCP_RESOURCE
}).toString()
})
}

afterEach(async () => {
await clearKv(env.OAUTH_KV)
})
Expand Down Expand Up @@ -170,6 +224,23 @@ describe('Client ID Metadata Documents', () => {
expect((await env.OAUTH_KV.list({ prefix: 'client:' })).keys).toHaveLength(0)
})

it('keeps an earlier grant when the same user authorizes the same CIMD client again', async () => {
// A hosted CIMD client (one client ID, one callback) can hold several independent
// connections for one Cloudflare user; a new one must not revoke the others.
server.use(http.get(CIMD_CLIENT_ID, () => HttpResponse.json(cimdMetadata())))
useCloudflareAuthSuccess()

const first = await authorizeAndExchange()
const second = await authorizeAndExchange()
expect(first.split(':')[1]).not.toBe(second.split(':')[1])
expect((await env.OAUTH_KV.list({ prefix: 'grant:' })).keys).toHaveLength(2)

const firstRefresh = await exports.default.fetch(refreshRequest(first))
expect(firstRefresh.status).toBe(200)
const secondRefresh = await exports.default.fetch(refreshRequest(second))
expect(secondRefresh.status).toBe(200)
})

it('returns a local retryable error when metadata cannot be fetched', async () => {
const unavailableClientId = 'https://unavailable.example.com/oauth/client.json'
server.use(http.get(unavailableClientId, () => new HttpResponse(null, { status: 502 })))
Expand Down