Skip to content

chore(nextjs): Improve machine auth verification calls #6367

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 10 commits into from
Jul 23, 2025
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
5 changes: 5 additions & 0 deletions .changeset/eight-impalas-fetch.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@clerk/nextjs": patch
---

Improved machine auth verification within API routes
6 changes: 5 additions & 1 deletion packages/nextjs/src/app-router/server/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,11 @@ export const auth: AuthFn = (async (options?: AuthOptions) => {
});
};

return Object.assign(authObject, { redirectToSignIn, redirectToSignUp });
if (authObject.tokenType === TokenType.SessionToken) {
return Object.assign(authObject, { redirectToSignIn, redirectToSignUp });
}

return authObject;
Comment on lines +182 to +186
Copy link
Contributor

@coderabbitai coderabbitai bot Jul 22, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Verification agent

🧩 Analysis chain

Conditional redirect methods based on token type - approve with security review needed.

This change correctly restricts redirect methods to session tokens only, which makes semantic sense since machine tokens, API keys, and OAuth tokens are for programmatic access and don't need user redirect capabilities.

However, this modifies core authentication logic and should be reviewed by the security team.

Please tag clerk/security for review of this authentication logic change.

Also, ensure test coverage exists for both branches of this conditional logic:

If test coverage is missing, please add tests to verify:

  1. Session tokens return authObject with redirect methods
  2. Non-session tokens return authObject without redirect methods
  3. The redirect methods work correctly when present

🏁 Script executed:

#!/bin/bash
# Description: Check for test coverage of conditional redirect method behavior

# Search for tests related to auth function with different token types
rg -A 10 -B 5 "auth.*tokenType|tokenType.*auth" --type ts --type js

# Search for tests of redirect methods on auth objects
rg -A 10 -B 5 "redirectToSignIn|redirectToSignUp" --type ts --type js packages/nextjs/src/app-router/server/__tests__/ || echo "No tests directory found"

# Search for machine token or API key auth tests
rg -A 10 -B 5 "machine_token|api_key|MachineAuthObject" --type ts --type js packages/nextjs/src/app-router/server/__tests__/ || echo "No tests directory found"

Length of output: 76688


Conditional redirect methods for session tokens – approve with security review and add missing tests

The change correctly restricts redirectToSignIn/redirectToSignUp to SessionToken cases, aligning behavior with token semantics.
However, no unit tests currently cover this branch in packages/nextjs/src/app-router/server/auth.ts.

• Tag clerk/security for review of the updated authentication logic.
• Add a new test suite under packages/nextjs/src/app-router/server/__tests__/auth.test.ts covering:

  • When authObject.tokenType === TokenType.SessionToken, the returned object includes working redirectToSignIn and redirectToSignUp methods.
  • When authObject.tokenType !== TokenType.SessionToken, the returned object does not expose redirect methods (calls should error or be undefined).
🤖 Prompt for AI Agents
In packages/nextjs/src/app-router/server/auth.ts lines 182-186, the code
conditionally adds redirectToSignIn and redirectToSignUp methods only for
SessionToken token types. To fix, request a security review from the
clerk/security team for this authentication logic update. Then, add a new test
suite in packages/nextjs/src/app-router/server/__tests__/auth.test.ts that
verifies when tokenType is SessionToken, the returned object includes
functioning redirect methods, and when tokenType is not SessionToken, these
redirect methods are absent or cause errors.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@wobsoriano Do types already cover this case ?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Seems like the humans are having a chat. I'll hop back into my burrow for now. If you need me again, just tag @coderabbitai in a new comment, and I'll come hopping out!

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@panteliselef yes, but want to make sure machine auth objects dont include redirect functions at runtime as well

}) as AuthFn;

auth.protect = async (...args: any[]) => {
Expand Down
175 changes: 124 additions & 51 deletions packages/nextjs/src/server/__tests__/getAuthDataFromRequest.test.ts
Original file line number Diff line number Diff line change
@@ -1,115 +1,188 @@
import type { AuthenticatedMachineObject, SignedOutAuthObject } from '@clerk/backend/internal';
import { constants, verifyMachineAuthToken } from '@clerk/backend/internal';
import type { MachineAuthObject } from '@clerk/backend';
import type { AuthenticatedMachineObject, MachineTokenType, SignedOutAuthObject } from '@clerk/backend/internal';
import { constants } from '@clerk/backend/internal';
import { NextRequest } from 'next/server';
import { beforeEach, describe, expect, it, vi } from 'vitest';

import { getAuthDataFromRequestAsync, getAuthDataFromRequestSync } from '../data/getAuthDataFromRequest';
import { getAuthDataFromRequest } from '../data/getAuthDataFromRequest';
import { encryptClerkRequestData } from '../utils';

vi.mock('@clerk/backend/internal', async () => {
const actual = await vi.importActual('@clerk/backend/internal');
vi.mock(import('../constants.js'), async importOriginal => {
const actual = await importOriginal();
return {
...actual,
verifyMachineAuthToken: vi.fn(),
ENCRYPTION_KEY: 'encryption-key',
PUBLISHABLE_KEY: 'pk_test_Y2xlcmsuaW5jbHVkZWQua2F0eWRpZC05Mi5sY2wuZGV2JA',
SECRET_KEY: 'sk_test_xxxxxxxxxxxxxxxxxx',
};
});

type MockRequestParams = {
url: string;
appendDevBrowserCookie?: boolean;
method?: string;
headers?: any;
headers?: Headers;
machineAuthObject?: Partial<MachineAuthObject<MachineTokenType>>;
};

const mockRequest = (params: MockRequestParams) => {
const { url, appendDevBrowserCookie = false, method = 'GET', headers = new Headers() } = params;
const { url, appendDevBrowserCookie = false, method = 'GET', headers = new Headers(), machineAuthObject } = params;
const headersWithCookie = new Headers(headers);

if (appendDevBrowserCookie) {
headersWithCookie.append('cookie', '__clerk_db_jwt=test_jwt');
}

// Add encrypted auth object header if provided
if (machineAuthObject) {
const encryptedData = encryptClerkRequestData(
{}, // requestData
{}, // keylessModeKeys
// @ts-expect-error - mock machine auth object
machineAuthObject,
);
if (encryptedData) {
headersWithCookie.set(constants.Headers.ClerkRequestData, encryptedData);
}
}

return new NextRequest(new URL(url, 'https://www.clerk.com').toString(), { method, headers: headersWithCookie });
};

const machineTokenErrorMock = [
{
message: 'Token type mismatch',
code: 'token-invalid',
status: 401,
name: 'MachineTokenVerificationError',
getFullMessage: () => 'Token type mismatch',
},
];

describe('getAuthDataFromRequestAsync', () => {
// Helper function to create mock machine auth objects
const createMockMachineAuthObject = <T extends MachineTokenType>(data: Partial<MachineAuthObject<T>>) => data;

describe('getAuthDataFromRequest', () => {
beforeEach(() => {
vi.clearAllMocks();
});

it('returns invalid token auth object when token type does not match any in acceptsToken array', async () => {
it('returns invalid token auth object when token type does not match any in acceptsToken array', () => {
const machineAuthObject = createMockMachineAuthObject({
tokenType: 'api_key',
isAuthenticated: true,
});

const req = mockRequest({
url: '/api/protected',
headers: new Headers({
[constants.Headers.Authorization]: 'Bearer ak_xxx',
}),
machineAuthObject,
});

const auth = await getAuthDataFromRequestAsync(req, {
const auth = getAuthDataFromRequest(req, {
acceptsToken: ['machine_token', 'oauth_token', 'session_token'],
});

expect(auth.tokenType).toBeNull();
expect(auth.isAuthenticated).toBe(false);
});

it('returns unauthenticated auth object when token type does not match single acceptsToken', async () => {
it('handles mixed token types in acceptsToken array', () => {
const machineAuthObject = createMockMachineAuthObject({
tokenType: 'api_key',
isAuthenticated: true,
id: 'ak_id123',
});

const req = mockRequest({
url: '/api/protected',
headers: new Headers({
[constants.Headers.Authorization]: 'Bearer ak_xxx',
}),
machineAuthObject,
});

const auth = getAuthDataFromRequest(req, {
acceptsToken: ['api_key', 'session_token'],
});

expect(auth.tokenType).toBe('api_key');
expect(auth.isAuthenticated).toBe(true);
});

it('falls back to session logic when machine token is not accepted', () => {
const machineAuthObject = createMockMachineAuthObject({
tokenType: 'api_key',
isAuthenticated: true,
});

const req = mockRequest({
url: '/api/protected',
headers: new Headers({
[constants.Headers.Authorization]: 'Bearer ak_xxx',
}),
machineAuthObject,
});

const auth = getAuthDataFromRequest(req, {
acceptsToken: 'session_token',
});

expect(auth.tokenType).toBe('session_token');
expect(auth.isAuthenticated).toBe(false);
});

it('returns unauthenticated auth object when token type does not match single acceptsToken', () => {
const machineAuthObject = createMockMachineAuthObject({
tokenType: 'api_key',
isAuthenticated: true,
});

const req = mockRequest({
url: '/api/protected',
headers: new Headers({
[constants.Headers.Authorization]: 'Bearer ak_xxx',
}),
machineAuthObject,
});

const auth = await getAuthDataFromRequestAsync(req, { acceptsToken: 'oauth_token' });
const auth = getAuthDataFromRequest(req, { acceptsToken: 'oauth_token' });

expect(auth.tokenType).toBe('oauth_token');
expect(auth.isAuthenticated).toBe(false);
});

it('returns authenticated auth object for any valid token type', async () => {
vi.mocked(verifyMachineAuthToken).mockResolvedValueOnce({
data: { id: 'ak_id123', subject: 'user_12345' } as any,
it('returns authenticated auth object for any valid token type', () => {
const machineAuthObject = createMockMachineAuthObject({
tokenType: 'api_key',
errors: undefined,
id: 'ak_id123',
isAuthenticated: true,
});

const req = mockRequest({
url: '/api/protected',
headers: new Headers({
[constants.Headers.Authorization]: 'Bearer ak_xxx',
}),
machineAuthObject,
});

const auth = await getAuthDataFromRequestAsync(req, { acceptsToken: 'any' });
const auth = getAuthDataFromRequest(req, { acceptsToken: 'any' });

expect(auth.tokenType).toBe('api_key');
expect((auth as AuthenticatedMachineObject<'api_key'>).id).toBe('ak_id123');
expect(auth.isAuthenticated).toBe(true);
});

it('returns authenticated object when token type exists in acceptsToken array', async () => {
vi.mocked(verifyMachineAuthToken).mockResolvedValueOnce({
data: { id: 'ak_id123', subject: 'user_12345' } as any,
it('returns authenticated object when token type exists in acceptsToken array', () => {
const machineAuthObject = createMockMachineAuthObject({
tokenType: 'api_key',
errors: undefined,
id: 'ak_id123',
subject: 'user_12345',
isAuthenticated: true,
});

const req = mockRequest({
url: '/api/protected',
headers: new Headers({
[constants.Headers.Authorization]: 'Bearer ak_secret123',
[constants.Headers.Authorization]: 'Bearer ak_xxx',
}),
machineAuthObject,
});

const auth = await getAuthDataFromRequestAsync(req, {
const auth = getAuthDataFromRequest(req, {
acceptsToken: ['api_key', 'machine_token'],
});

Expand All @@ -136,21 +209,22 @@ describe('getAuthDataFromRequestAsync', () => {
},
])(
'returns authenticated $tokenType object when token is valid and acceptsToken is $tokenType',
async ({ tokenType, token, data }) => {
vi.mocked(verifyMachineAuthToken).mockResolvedValueOnce({
data: data as any,
({ tokenType, token, data }) => {
const machineAuthObject = createMockMachineAuthObject({
tokenType,
errors: undefined,
isAuthenticated: true,
...data,
});

const req = mockRequest({
url: '/api/protected',
headers: new Headers({
[constants.Headers.Authorization]: `Bearer ${token}`,
}),
machineAuthObject,
});

const auth = await getAuthDataFromRequestAsync(req, { acceptsToken: tokenType });
const auth = getAuthDataFromRequest(req, { acceptsToken: tokenType });

expect(auth.tokenType).toBe(tokenType);
expect(auth.isAuthenticated).toBe(true);
Expand All @@ -173,56 +247,55 @@ describe('getAuthDataFromRequestAsync', () => {
token: 'mt_123',
data: undefined,
},
])('returns unauthenticated $tokenType object when token is invalid', async ({ tokenType, token, data }) => {
vi.mocked(verifyMachineAuthToken).mockResolvedValueOnce({
data: data as any,
])('returns unauthenticated $tokenType object when token is invalid', ({ tokenType, token }) => {
const machineAuthObject = createMockMachineAuthObject({
tokenType,
errors: machineTokenErrorMock as any,
isAuthenticated: false,
});

// For invalid tokens, we don't include encrypted auth object
const req = mockRequest({
url: '/api/protected',
headers: new Headers({
[constants.Headers.Authorization]: `Bearer ${token}`,
}),
machineAuthObject,
});

const auth = await getAuthDataFromRequestAsync(req, { acceptsToken: tokenType });
const auth = getAuthDataFromRequest(req, { acceptsToken: tokenType });

expect(auth.tokenType).toBe(tokenType);
expect(auth.isAuthenticated).toBe(false);
});

it('falls back to session token handling', async () => {
it('falls back to session token handling when no encrypted auth object is present', () => {
const req = mockRequest({
url: '/api/protected',
headers: new Headers({
[constants.Headers.Authorization]: 'Bearer session_xxx',
}),
});

const auth = await getAuthDataFromRequestAsync(req);
const auth = getAuthDataFromRequest(req);
expect(auth.tokenType).toBe('session_token');
expect((auth as SignedOutAuthObject).userId).toBeNull();
expect(auth.isAuthenticated).toBe(false);
});
});

describe('getAuthDataFromRequestSync', () => {
it('only accepts session tokens', () => {
it('only accepts session tokens when encrypted auth object is not present', () => {
const req = mockRequest({
url: '/api/protected',
headers: new Headers({
[constants.Headers.Authorization]: 'Bearer ak_123',
}),
});

const auth = getAuthDataFromRequestSync(req, {
const auth = getAuthDataFromRequest(req, {
acceptsToken: 'api_key',
});

expect(auth.tokenType).toBe('session_token');
expect(auth.userId).toBeNull();
expect((auth as SignedOutAuthObject).userId).toBeNull();
expect(auth.isAuthenticated).toBe(false);
});
});
4 changes: 2 additions & 2 deletions packages/nextjs/src/server/buildClerkProps.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type { AuthObject, Organization, Session, User } from '@clerk/backend';
import { makeAuthObjectSerializable, stripPrivateDataFromObject } from '@clerk/backend/internal';

import { getAuthDataFromRequestSync } from './data/getAuthDataFromRequest';
import { getAuthDataFromRequest } from './data/getAuthDataFromRequest';
import type { RequestLike } from './types';

type BuildClerkPropsInitState = { user?: User | null; session?: Session | null; organization?: Organization | null };
Expand Down Expand Up @@ -59,7 +59,7 @@ export const buildClerkProps: BuildClerkProps = (req, initialState = {}) => {
};

export function getDynamicAuthData(req: RequestLike, initialState = {}) {
const authObject = getAuthDataFromRequestSync(req);
const authObject = getAuthDataFromRequest(req);

return makeAuthObjectSerializable(stripPrivateDataFromObject({ ...authObject, ...initialState })) as AuthObject;
}
10 changes: 9 additions & 1 deletion packages/nextjs/src/server/clerkMiddleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import {
getAuthObjectForAcceptedToken,
isMachineTokenByPrefix,
isTokenTypeAccepted,
makeAuthObjectSerializable,
TokenType,
} from '@clerk/backend/internal';
import { parsePublishableKey } from '@clerk/shared/keys';
Expand Down Expand Up @@ -265,7 +266,14 @@ export const clerkMiddleware = ((...args: unknown[]): NextMiddleware | NextMiddl
}
: {};

decorateRequest(clerkRequest, handlerResult, requestState, resolvedParams, keylessKeysForRequestData);
decorateRequest(
clerkRequest,
handlerResult,
requestState,
resolvedParams,
keylessKeysForRequestData,
authObject.tokenType === 'session_token' ? null : makeAuthObjectSerializable(authObject),
);

return handlerResult;
});
Expand Down
Loading
Loading