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
5 changes: 5 additions & 0 deletions .changeset/silent-fastify-handshakes.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@clerk/fastify': patch
---

Fixed an issue where secrets passed directly to clerkPlugin() were not used when verifying sessions, causing authentication failures when keys are loaded at runtime (e.g. AWS Secrets Manager on Lambda).
125 changes: 119 additions & 6 deletions packages/fastify/src/__tests__/withClerkMiddleware.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,19 @@ import { beforeEach, describe, expect, test, vi } from 'vitest';

import { clerkPlugin, getAuth } from '../index';

const authenticateRequestMock = vi.fn();
const { authenticateRequestMock, createClerkClientMock, mockClerkClient } = vi.hoisted(() => {
const authenticateRequestMock = vi.fn();
const mockClerkClient = { authenticateRequest: (...args: any) => authenticateRequestMock(...args) };
const createClerkClientMock = vi.fn(() => mockClerkClient);

return { authenticateRequestMock, createClerkClientMock, mockClerkClient };
});

vi.mock('@clerk/backend', async () => {
const actual = await vi.importActual('@clerk/backend');
return {
...actual,
createClerkClient: () => {
return {
authenticateRequest: (...args: any) => authenticateRequestMock(...args),
};
},
createClerkClient: createClerkClientMock,
};
});

Expand All @@ -24,6 +26,38 @@ describe('withClerkMiddleware(options)', () => {
vi.restoreAllMocks();
});

test('creates the request client with plugin runtime keys', async () => {
authenticateRequestMock.mockResolvedValueOnce({
headers: new Headers(),
toAuth: () => ({
tokenType: 'session_token',
}),
});
const fastify = Fastify();
await fastify.register(clerkPlugin, {
secretKey: 'runtime_secret_key',
publishableKey: 'runtime_publishable_key',
});

fastify.get('/', (request: FastifyRequest, reply: FastifyReply) => {
const auth = getAuth(request);
reply.send({ auth });
});

const response = await fastify.inject({
method: 'GET',
path: '/',
});

expect(response.statusCode).toEqual(200);
expect(createClerkClientMock).toHaveBeenLastCalledWith(
expect.objectContaining({
secretKey: 'runtime_secret_key',
publishableKey: 'runtime_publishable_key',
}),
);
});

test('handles signin with Authorization Bearer', async () => {
authenticateRequestMock.mockResolvedValueOnce({
headers: new Headers(),
Expand Down Expand Up @@ -142,6 +176,85 @@ describe('withClerkMiddleware(options)', () => {
});
});

test('skips handshake redirect when enableHandshake is false', async () => {
authenticateRequestMock.mockResolvedValueOnce({
status: 'handshake',
headers: new Headers({
location: 'https://fapi.example.com/v1/clients/handshake',
'x-clerk-auth-status': 'handshake',
}),
toAuth: () => ({
tokenType: 'session_token',
}),
});
const fastify = Fastify();
await fastify.register(clerkPlugin, { enableHandshake: false });

fastify.get('/', (request: FastifyRequest, reply: FastifyReply) => {
const auth = getAuth(request);
reply.send({ auth });
});

const response = await fastify.inject({
method: 'GET',
path: '/',
headers: {
cookie: '__clerk_handshake_nonce=deadbeef; __client_uat=1675692233',
},
});

expect(response.statusCode).toEqual(200);
expect(response.body).toEqual(JSON.stringify({ auth: { tokenType: 'session_token' } }));
});

test('strips handshake cookies and query params before authenticating when enableHandshake is false', async () => {
authenticateRequestMock.mockResolvedValueOnce({
headers: new Headers(),
toAuth: () => ({ tokenType: 'session_token' }),
});
const fastify = Fastify();
await fastify.register(clerkPlugin, { enableHandshake: false });

fastify.get('/', (_request: FastifyRequest, reply: FastifyReply) => {
reply.send({});
});

await fastify.inject({
method: 'GET',
path: '/?__clerk_handshake=token123&__clerk_handshake_nonce=nonce456&foo=bar',
headers: {
cookie: '__clerk_handshake=token123; __clerk_handshake_nonce=nonce456; __client_uat=1675692233',
},
});

const [req] = authenticateRequestMock.mock.calls[0];
expect(new URL(req.url).searchParams.has('__clerk_handshake')).toBe(false);
expect(new URL(req.url).searchParams.has('__clerk_handshake_nonce')).toBe(false);
expect(new URL(req.url).searchParams.get('foo')).toBe('bar');
expect(req.headers.get('cookie')).not.toContain('__clerk_handshake=');
expect(req.headers.get('cookie')).not.toContain('__clerk_handshake_nonce=');
expect(req.headers.get('cookie')).toContain('__client_uat=1675692233');
});

test('exposes the clerk client instance on request.clerk', async () => {
authenticateRequestMock.mockResolvedValueOnce({
headers: new Headers(),
toAuth: () => ({ tokenType: 'session_token' }),
});
const fastify = Fastify();
await fastify.register(clerkPlugin);

let clerkOnRequest: unknown;
fastify.get('/', (request: FastifyRequest, reply: FastifyReply) => {
clerkOnRequest = request.clerk;
reply.send({});
});

await fastify.inject({ method: 'GET', path: '/' });

expect(clerkOnRequest).toBe(mockClerkClient);
});

test('handles signout case by populating the req.auth', async () => {
authenticateRequestMock.mockResolvedValueOnce({
headers: new Headers(),
Expand Down
3 changes: 3 additions & 0 deletions packages/fastify/src/clerkPlugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@ const plugin: FastifyPluginCallback<ClerkFastifyOptions> = (
done,
) => {
instance.decorateRequest('auth', null);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
instance.decorateRequest('clerk', null as any);

// run clerk as a middleware to all scoped routes
const hookName = opts.hookName || 'preHandler';
if (!ALLOWED_HOOKS.includes(hookName)) {
Expand Down
16 changes: 15 additions & 1 deletion packages/fastify/src/types.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
import type { ClerkOptions } from '@clerk/backend';
import type { ClerkClient, ClerkOptions } from '@clerk/backend';
import type { ShouldProxyFn } from '@clerk/shared/proxy';

declare module 'fastify' {
interface FastifyRequest {
clerk: ClerkClient;
}
}

export const ALLOWED_HOOKS = ['onRequest', 'preHandler'] as const;

/**
Expand All @@ -21,4 +27,12 @@ export interface FrontendApiProxyOptions {
export type ClerkFastifyOptions = ClerkOptions & {
hookName?: (typeof ALLOWED_HOOKS)[number];
frontendApiProxy?: FrontendApiProxyOptions;
/**
* Whether to enable the handshake flow for session verification.
* Disable this when using Clerk with a first-party API backend (e.g. a SPA calling
* a Fastify server) to prevent handshake nonce cookies set during OAuth callbacks
* from blocking authentication on subsequent API requests.
* @default true
*/
enableHandshake?: boolean;
};
62 changes: 52 additions & 10 deletions packages/fastify/src/withClerkMiddleware.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,56 @@
import { createClerkClient } from '@clerk/backend';
import { AuthStatus } from '@clerk/backend/internal';
import { clerkFrontendApiProxy, DEFAULT_PROXY_PATH, stripTrailingSlashes } from '@clerk/backend/proxy';
import type { FastifyReply, FastifyRequest } from 'fastify';
import { Readable } from 'stream';

import { clerkClient } from './clerkClient';
import * as constants from './constants';
import type { ClerkFastifyOptions } from './types';
import { fastifyRequestToRequest, requestToProxyRequest } from './utils';

function stripHandshakeCookiesAndParams(req: Request, cookieNames: string[]): Request {
const url = new URL(req.url);
for (const name of cookieNames) {
url.searchParams.delete(name);
}

const headers = new Headers(req.headers);
const cookieHeader = headers.get('cookie');
if (cookieHeader) {
const filtered = cookieHeader
.split(';')
.map(c => c.trim())
.filter(c => !cookieNames.some(name => c === name || c.startsWith(`${name}=`)))
.join('; ');
if (filtered) {
headers.set('cookie', filtered);
} else {
headers.delete('cookie');
}
}

return new Request(url.toString(), { method: req.method, headers });
}

export const withClerkMiddleware = (options: ClerkFastifyOptions) => {
const frontendApiProxy = options.frontendApiProxy;
const proxyPath = stripTrailingSlashes(frontendApiProxy?.path ?? DEFAULT_PROXY_PATH) || DEFAULT_PROXY_PATH;
const publishableKey = options.publishableKey || constants.PUBLISHABLE_KEY;
const secretKey = options.secretKey || constants.SECRET_KEY;
const clerkClient = createClerkClient({
...options,
publishableKey,
secretKey,
machineSecretKey: options.machineSecretKey || constants.MACHINE_SECRET_KEY,
apiUrl: options.apiUrl || constants.API_URL,
apiVersion: options.apiVersion || constants.API_VERSION,
jwtKey: options.jwtKey || constants.JWT_KEY,
userAgent: options.userAgent || `${constants.SDK_METADATA.name}@${constants.SDK_METADATA.version}`,
sdkMetadata: options.sdkMetadata || constants.SDK_METADATA,
});
const enableHandshake = options.enableHandshake ?? true;

return async (fastifyRequest: FastifyRequest, reply: FastifyReply) => {
const publishableKey = options.publishableKey || constants.PUBLISHABLE_KEY;
const secretKey = options.secretKey || constants.SECRET_KEY;

// Handle Frontend API proxy requests and auto-derive proxyUrl
let resolvedProxyUrl = options.proxyUrl;
if (frontendApiProxy) {
Expand Down Expand Up @@ -46,7 +81,7 @@
if (proxyResponse.body) {
const reader = proxyResponse.body.getReader();
const stream = new Readable({
async read() {

Check warning on line 84 in packages/fastify/src/withClerkMiddleware.ts

View workflow job for this annotation

GitHub Actions / Static analysis

Promise-returning function provided to property where a void return was expected
try {
const { done, value } = await reader.read();
if (done) {
Expand All @@ -72,7 +107,11 @@
}
}

const req = fastifyRequestToRequest(fastifyRequest);
let req = fastifyRequestToRequest(fastifyRequest);

if (!enableHandshake) {
req = stripHandshakeCookiesAndParams(req, [constants.Cookies.Handshake, constants.Cookies.HandshakeNonce]);
}

const requestState = await clerkClient.authenticateRequest(req, {
...options,
Expand All @@ -82,16 +121,19 @@
acceptsToken: 'any',
});

requestState.headers.forEach((value, key) => reply.header(key, value));

Check warning on line 124 in packages/fastify/src/withClerkMiddleware.ts

View workflow job for this annotation

GitHub Actions / Static analysis

Promise returned in function argument where a void return was expected

const locationHeader = requestState.headers.get(constants.Headers.Location);
if (locationHeader) {
return reply.code(307).send();
} else if (requestState.status === AuthStatus.Handshake) {
throw new Error('Clerk: handshake status without redirect');
if (enableHandshake) {
const locationHeader = requestState.headers.get(constants.Headers.Location);
if (locationHeader) {
return reply.code(307).send();
} else if (requestState.status === AuthStatus.Handshake) {
throw new Error('Clerk: handshake status without redirect');
}
}

// @ts-expect-error Inject auth so getAuth can read it
fastifyRequest.auth = requestState.toAuth();
fastifyRequest.clerk = clerkClient;
};
};
Loading