Skip to content

Commit 5e2a46f

Browse files
fix(nextjs): isolate middleware request data per request (#9723)
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
1 parent 71c3d07 commit 5e2a46f

4 files changed

Lines changed: 156 additions & 66 deletions

File tree

‎.changeset/olive-poets-shake.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@clerk/nextjs': patch
3+
---
4+
5+
Fix a cross-request credential leak in `clerkMiddleware()`. When using dynamic keys (an options callback that resolves a different `secretKey` per request), a `clerkClient()` call made inside the middleware handler could be built with another concurrent request's secret key. Each request now gets its own isolated store, so the keys resolved for a request are only ever visible to that request.
Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
import { createClerkClient } from '@clerk/backend';
2+
import { TokenType } from '@clerk/backend/internal';
3+
import type { NextFetchEvent } from 'next/server';
4+
import { NextRequest } from 'next/server';
5+
import { beforeEach, describe, expect, it, vi } from 'vitest';
6+
7+
import { clerkClient } from '../clerkClient';
8+
import { clerkMiddleware } from '../clerkMiddleware';
9+
10+
const { publishableKey } = vi.hoisted(() => ({
11+
publishableKey: 'pk_test_Y2xlcmsuaW5jbHVkZWQua2F0eWRpZC05Mi5sY2wuZGV2JA',
12+
}));
13+
14+
let gateAuthenticateRequest: (secretKey: string) => Promise<void>;
15+
16+
vi.mock('@clerk/backend', async importOriginal => {
17+
const actual: any = await importOriginal();
18+
return {
19+
...actual,
20+
createClerkClient: vi.fn((options: any) => ({
21+
secretKey: options.secretKey,
22+
telemetry: { record: vi.fn() },
23+
authenticateRequest: async () => {
24+
await gateAuthenticateRequest(options.secretKey);
25+
return {
26+
toAuth: () => ({ tokenType: TokenType.SessionToken, debug: (d: any) => d }),
27+
headers: new Headers(),
28+
publishableKey,
29+
};
30+
},
31+
})),
32+
};
33+
});
34+
35+
vi.mock(import('../constants.js'), async importOriginal => {
36+
const actual = await importOriginal();
37+
return {
38+
...actual,
39+
ENCRYPTION_KEY: 'encryption-key',
40+
PUBLISHABLE_KEY: publishableKey,
41+
SECRET_KEY: 'sk_test_environment',
42+
};
43+
});
44+
45+
// The mocked `createClerkClient` exposes the key it was constructed with
46+
const secretKeyOf = async () => ((await clerkClient()) as unknown as { secretKey: string }).secretKey;
47+
48+
const requestForTenant = (tenant: string) =>
49+
new NextRequest('https://www.clerk.com/', { headers: new Headers({ 'x-tenant': tenant }) });
50+
51+
describe('clerkMiddleware request isolation', () => {
52+
beforeEach(() => {
53+
vi.mocked(createClerkClient).mockClear();
54+
});
55+
56+
it('does not leak dynamic keys between concurrent requests', async () => {
57+
let releaseTenantA!: () => void;
58+
const tenantAGate = new Promise<void>(resolve => {
59+
releaseTenantA = resolve;
60+
});
61+
gateAuthenticateRequest = secretKey => (secretKey === 'sk_test_a' ? tenantAGate : Promise.resolve());
62+
63+
const secretKeyInHandler: Record<string, string | undefined> = {};
64+
const middleware = clerkMiddleware(
65+
async (_auth, request) => {
66+
const tenant = request.headers.get('x-tenant') as string;
67+
secretKeyInHandler[tenant] = await secretKeyOf();
68+
},
69+
request => ({ publishableKey, secretKey: `sk_test_${request.headers.get('x-tenant')}` }),
70+
);
71+
72+
// Tenant A parks inside `authenticateRequest` while tenant B runs to completion.
73+
const tenantA = middleware(requestForTenant('a'), {} as NextFetchEvent);
74+
await middleware(requestForTenant('b'), {} as NextFetchEvent);
75+
releaseTenantA();
76+
await tenantA;
77+
78+
expect(secretKeyInHandler).toEqual({ a: 'sk_test_a', b: 'sk_test_b' });
79+
});
80+
81+
it('falls back to the environment key outside of a middleware request', async () => {
82+
gateAuthenticateRequest = () => Promise.resolve();
83+
84+
expect(await secretKeyOf()).toBe('sk_test_environment');
85+
});
86+
});

‎packages/nextjs/src/server/clerkMiddleware.ts‎

Lines changed: 62 additions & 64 deletions
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,8 @@ import { clerkClient } from './clerkClient';
3737
import { DOMAIN, PROXY_URL, PUBLISHABLE_KEY, SECRET_KEY, SIGN_IN_URL, SIGN_UP_URL } from './constants';
3838
import { type ContentSecurityPolicyOptions, createContentSecurityPolicyHeaders } from './content-security-policy';
3939
import { errorThrower } from './errorThrower';
40-
import { clerkMiddlewareRequestDataStorage, clerkMiddlewareRequestDataStore } from './middleware-storage';
40+
import type { ClerkMiddlewareRequestDataStore } from './middleware-storage';
41+
import { clerkMiddlewareRequestDataStorage } from './middleware-storage';
4142
import {
4243
isNextjsNotFoundError,
4344
isNextjsRedirectError,
@@ -145,63 +146,64 @@ export const clerkMiddleware = ((...args: unknown[]): NextMiddleware | NextMiddl
145146
const [request, event] = parseRequestAndEvent(args);
146147
const [handler, params] = parseHandlerAndOptions(args);
147148

148-
const middleware = clerkMiddlewareRequestDataStorage.run(clerkMiddlewareRequestDataStore, () => {
149-
const baseNextMiddleware: NextMiddleware = withLogger('clerkMiddleware', logger => async (request, event) => {
150-
// Handles the case where `options` is a callback function to dynamically access `NextRequest`
151-
const resolvedParams = typeof params === 'function' ? await params(request) : params;
149+
const baseNextMiddleware: NextMiddleware = withLogger('clerkMiddleware', logger => async (request, event) => {
150+
// Handles the case where `options` is a callback function to dynamically access `NextRequest`
151+
const resolvedParams = typeof params === 'function' ? await params(request) : params;
152152

153-
const publishableKey = assertKey(resolvedParams.publishableKey || PUBLISHABLE_KEY, () =>
154-
errorThrower.throwMissingPublishableKeyError(),
155-
);
153+
const publishableKey = assertKey(resolvedParams.publishableKey || PUBLISHABLE_KEY, () =>
154+
errorThrower.throwMissingPublishableKeyError(),
155+
);
156156

157-
const secretKey = assertKey(resolvedParams.secretKey || SECRET_KEY, () =>
158-
errorThrower.throwMissingSecretKeyError(),
159-
);
157+
const secretKey = assertKey(resolvedParams.secretKey || SECRET_KEY, () =>
158+
errorThrower.throwMissingSecretKeyError(),
159+
);
160160

161-
// Handle Frontend API proxy requests early, before authentication
162-
const requestUrl = new URL(request.nextUrl.href);
163-
let frontendApiProxyConfig = resolvedParams.frontendApiProxy;
164-
165-
// Auto-detect when no explicit proxy or domain is configured
166-
const hasExplicitProxyOrDomain = resolvedParams.proxyUrl || PROXY_URL || resolvedParams.domain || DOMAIN;
167-
if (
168-
!frontendApiProxyConfig &&
169-
!hasExplicitProxyOrDomain &&
170-
!isAutoProxyDisabledFromEnvironment() &&
171-
isProductionFromPublishableKey(publishableKey)
172-
) {
173-
if (shouldAutoProxy(requestUrl.hostname)) {
174-
frontendApiProxyConfig = { enabled: true };
175-
}
161+
// Handle Frontend API proxy requests early, before authentication
162+
const requestUrl = new URL(request.nextUrl.href);
163+
let frontendApiProxyConfig = resolvedParams.frontendApiProxy;
164+
165+
// Auto-detect when no explicit proxy or domain is configured
166+
const hasExplicitProxyOrDomain = resolvedParams.proxyUrl || PROXY_URL || resolvedParams.domain || DOMAIN;
167+
if (
168+
!frontendApiProxyConfig &&
169+
!hasExplicitProxyOrDomain &&
170+
!isAutoProxyDisabledFromEnvironment() &&
171+
isProductionFromPublishableKey(publishableKey)
172+
) {
173+
if (shouldAutoProxy(requestUrl.hostname)) {
174+
frontendApiProxyConfig = { enabled: true };
176175
}
177-
if (frontendApiProxyConfig) {
178-
const { enabled, path: proxyPath = DEFAULT_PROXY_PATH } = frontendApiProxyConfig;
179-
180-
// Resolve enabled - either boolean or function
181-
const isEnabled = typeof enabled === 'function' ? enabled(requestUrl) : enabled;
182-
183-
if (isEnabled && matchProxyPath(request, { proxyPath })) {
184-
return clerkFrontendApiProxy(request, {
185-
proxyPath,
186-
publishableKey,
187-
secretKey,
188-
});
189-
}
176+
}
177+
if (frontendApiProxyConfig) {
178+
const { enabled, path: proxyPath = DEFAULT_PROXY_PATH } = frontendApiProxyConfig;
179+
180+
// Resolve enabled - either boolean or function
181+
const isEnabled = typeof enabled === 'function' ? enabled(requestUrl) : enabled;
182+
183+
if (isEnabled && matchProxyPath(request, { proxyPath })) {
184+
return clerkFrontendApiProxy(request, {
185+
proxyPath,
186+
publishableKey,
187+
secretKey,
188+
});
190189
}
190+
}
191+
192+
const signInUrl = resolvedParams.signInUrl || SIGN_IN_URL;
193+
const signUpUrl = resolvedParams.signUpUrl || SIGN_UP_URL;
191194

192-
const signInUrl = resolvedParams.signInUrl || SIGN_IN_URL;
193-
const signUpUrl = resolvedParams.signUpUrl || SIGN_UP_URL;
195+
const options = {
196+
publishableKey,
197+
secretKey,
198+
signInUrl,
199+
signUpUrl,
200+
...resolvedParams,
201+
};
194202

195-
const options = {
196-
publishableKey,
197-
secretKey,
198-
signInUrl,
199-
signUpUrl,
200-
...resolvedParams,
201-
};
203+
// Propagates the request data to be accessed on the server application runtime from helpers such as `clerkClient`
204+
const requestDataStore: ClerkMiddlewareRequestDataStore = new Map([['requestData', options]]);
202205

203-
// Propagates the request data to be accessed on the server application runtime from helpers such as `clerkClient`
204-
clerkMiddlewareRequestDataStore.set('requestData', options);
206+
return clerkMiddlewareRequestDataStorage.run(requestDataStore, async () => {
205207
const resolvedClerkClient = await clerkClient();
206208

207209
if (options.debug) {
@@ -239,19 +241,17 @@ export const clerkMiddleware = ((...args: unknown[]): NextMiddleware | NextMiddl
239241
logger,
240242
});
241243
});
242-
243-
// If we have a request and event, we're being called as a middleware directly
244-
// eg, export default clerkMiddleware;
245-
if (request && event) {
246-
return baseNextMiddleware(request, event);
247-
}
248-
249-
// Otherwise, return a middleware that can be called with a request and event
250-
// eg, export default clerkMiddleware(auth => { ... });
251-
return baseNextMiddleware;
252244
});
253245

254-
return middleware;
246+
// If we have a request and event, we're being called as a middleware directly
247+
// eg, export default clerkMiddleware;
248+
if (request && event) {
249+
return baseNextMiddleware(request, event);
250+
}
251+
252+
// Otherwise, return a middleware that can be called with a request and event
253+
// eg, export default clerkMiddleware(auth => { ... });
254+
return baseNextMiddleware;
255255
}) as ClerkMiddleware;
256256

257257
const parseRequestAndEvent = (args: unknown[]) => {
@@ -338,9 +338,7 @@ async function runHandlerWithRequestState({
338338

339339
let handlerResult: Response = NextResponse.next();
340340
try {
341-
const userHandlerResult = await clerkMiddlewareRequestDataStorage.run(clerkMiddlewareRequestDataStore, async () =>
342-
handler?.(authHandler, request, event),
343-
);
341+
const userHandlerResult = await handler?.(authHandler, request, event);
344342
handlerResult = userHandlerResult || handlerResult;
345343
} catch (e: any) {
346344
handlerResult = handleControlFlowErrors(e, clerkRequest, request, requestState);

‎packages/nextjs/src/server/middleware-storage.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,5 +2,6 @@ import { AsyncLocalStorage } from 'node:async_hooks';
22

33
import type { AuthenticateRequestOptions } from '@clerk/backend/internal';
44

5-
export const clerkMiddlewareRequestDataStore = new Map<'requestData', AuthenticateRequestOptions>();
6-
export const clerkMiddlewareRequestDataStorage = new AsyncLocalStorage<typeof clerkMiddlewareRequestDataStore>();
5+
export type ClerkMiddlewareRequestDataStore = Map<'requestData', AuthenticateRequestOptions>;
6+
7+
export const clerkMiddlewareRequestDataStorage = new AsyncLocalStorage<ClerkMiddlewareRequestDataStore>();

0 commit comments

Comments
 (0)