|
| 1 | +import type { User } from '@clerk/backend'; |
| 2 | +import { TokenType } from '@clerk/backend/internal'; |
| 3 | +import { expect, test } from '@playwright/test'; |
| 4 | + |
| 5 | +import type { Application } from '../../models/application'; |
| 6 | +import { appConfigs } from '../../presets'; |
| 7 | +import type { FakeAPIKey, FakeUser } from '../../testUtils'; |
| 8 | +import { createTestUtils } from '../../testUtils'; |
| 9 | + |
| 10 | +test.describe('Next.js API key auth within clerkMiddleware() @nextjs', () => { |
| 11 | + test.describe.configure({ mode: 'parallel' }); |
| 12 | + let app: Application; |
| 13 | + let fakeUser: FakeUser; |
| 14 | + let fakeBapiUser: User; |
| 15 | + let fakeAPIKey: FakeAPIKey; |
| 16 | + |
| 17 | + test.beforeAll(async () => { |
| 18 | + app = await appConfigs.next.appRouter |
| 19 | + .clone() |
| 20 | + .addFile( |
| 21 | + `src/middleware.ts`, |
| 22 | + () => ` |
| 23 | + import { clerkMiddleware, createRouteMatcher } from '@clerk/nextjs/server'; |
| 24 | +
|
| 25 | + const isProtectedRoute = createRouteMatcher(['/api(.*)']); |
| 26 | +
|
| 27 | + export default clerkMiddleware(async (auth, req) => { |
| 28 | + if (isProtectedRoute(req)) { |
| 29 | + await auth.protect({ token: 'api_key' }); |
| 30 | + } |
| 31 | + }); |
| 32 | +
|
| 33 | + export const config = { |
| 34 | + matcher: [ |
| 35 | + '/((?!.*\\..*|_next).*)', // Don't run middleware on static files |
| 36 | + '/', // Run middleware on index page |
| 37 | + '/(api|trpc)(.*)', |
| 38 | + ], // Run middleware on API routes |
| 39 | + }; |
| 40 | + `, |
| 41 | + ) |
| 42 | + .addFile( |
| 43 | + 'src/app/api/me/route.ts', |
| 44 | + () => ` |
| 45 | + import { auth } from '@clerk/nextjs/server'; |
| 46 | +
|
| 47 | + export async function GET() { |
| 48 | + const { userId, tokenType } = await auth({ acceptsToken: 'api_key' }); |
| 49 | +
|
| 50 | + return Response.json({ userId, tokenType }); |
| 51 | + } |
| 52 | + `, |
| 53 | + ) |
| 54 | + .commit(); |
| 55 | + |
| 56 | + await app.setup(); |
| 57 | + await app.withEnv(appConfigs.envs.withAPIKeys); |
| 58 | + await app.dev(); |
| 59 | + |
| 60 | + const u = createTestUtils({ app }); |
| 61 | + fakeUser = u.services.users.createFakeUser(); |
| 62 | + fakeBapiUser = await u.services.users.createBapiUser(fakeUser); |
| 63 | + fakeAPIKey = await u.services.users.createFakeAPIKey(fakeBapiUser.id); |
| 64 | + }); |
| 65 | + |
| 66 | + test.afterAll(async () => { |
| 67 | + await fakeAPIKey.revoke(); |
| 68 | + await fakeUser.deleteIfExists(); |
| 69 | + await app.teardown(); |
| 70 | + }); |
| 71 | + |
| 72 | + test('should return 401 if no API key is provided', async ({ request }) => { |
| 73 | + const url = new URL('/api/me', app.serverUrl); |
| 74 | + const res = await request.get(url.toString()); |
| 75 | + expect(res.status()).toBe(401); |
| 76 | + }); |
| 77 | + |
| 78 | + test('should return 401 if API key is invalid', async ({ request }) => { |
| 79 | + const url = new URL('/api/me', app.serverUrl); |
| 80 | + const res = await request.get(url.toString(), { |
| 81 | + headers: { Authorization: 'Bearer invalid_key' }, |
| 82 | + }); |
| 83 | + expect(res.status()).toBe(401); |
| 84 | + }); |
| 85 | + |
| 86 | + test('should return 200 with auth object if API key is valid', async ({ request }) => { |
| 87 | + const url = new URL('/api/me', app.serverUrl); |
| 88 | + const res = await request.get(url.toString(), { |
| 89 | + headers: { |
| 90 | + Authorization: `Bearer ${fakeAPIKey.secret}`, |
| 91 | + }, |
| 92 | + }); |
| 93 | + const apiKeyData = await res.json(); |
| 94 | + expect(res.status()).toBe(200); |
| 95 | + expect(apiKeyData.userId).toBe(fakeBapiUser.id); |
| 96 | + expect(apiKeyData.tokenType).toBe(TokenType.ApiKey); |
| 97 | + }); |
| 98 | +}); |
| 99 | + |
| 100 | +test.describe('Next.js API key auth within routes @nextjs', () => { |
| 101 | + test.describe.configure({ mode: 'parallel' }); |
| 102 | + let app: Application; |
| 103 | + let fakeUser: FakeUser; |
| 104 | + let fakeBapiUser: User; |
| 105 | + let fakeAPIKey: FakeAPIKey; |
| 106 | + |
| 107 | + test.beforeAll(async () => { |
| 108 | + app = await appConfigs.next.appRouter |
| 109 | + .clone() |
| 110 | + .addFile( |
| 111 | + 'src/app/api/me/route.ts', |
| 112 | + () => ` |
| 113 | + import { auth } from '@clerk/nextjs/server'; |
| 114 | +
|
| 115 | + export async function GET() { |
| 116 | + const { userId, tokenType } = await auth({ acceptsToken: 'api_key' }); |
| 117 | +
|
| 118 | + if (!userId) { |
| 119 | + return Response.json({ error: 'Unauthorized' }, { status: 401 }); |
| 120 | + } |
| 121 | +
|
| 122 | + return Response.json({ userId, tokenType }); |
| 123 | + } |
| 124 | +
|
| 125 | + export async function POST() { |
| 126 | + const authObject = await auth({ acceptsToken: ['api_key', 'session_token'] }); |
| 127 | +
|
| 128 | + if (!authObject.isAuthenticated) { |
| 129 | + return Response.json({ error: 'Unauthorized' }, { status: 401 }); |
| 130 | + } |
| 131 | +
|
| 132 | + return Response.json({ userId: authObject.userId, tokenType: authObject.tokenType }); |
| 133 | + } |
| 134 | + `, |
| 135 | + ) |
| 136 | + .commit(); |
| 137 | + |
| 138 | + await app.setup(); |
| 139 | + await app.withEnv(appConfigs.envs.withAPIKeys); |
| 140 | + await app.dev(); |
| 141 | + |
| 142 | + const u = createTestUtils({ app }); |
| 143 | + fakeUser = u.services.users.createFakeUser(); |
| 144 | + fakeBapiUser = await u.services.users.createBapiUser(fakeUser); |
| 145 | + fakeAPIKey = await u.services.users.createFakeAPIKey(fakeBapiUser.id); |
| 146 | + }); |
| 147 | + |
| 148 | + test.afterAll(async () => { |
| 149 | + await fakeAPIKey.revoke(); |
| 150 | + await fakeUser.deleteIfExists(); |
| 151 | + await app.teardown(); |
| 152 | + }); |
| 153 | + |
| 154 | + test('should return 401 if no API key is provided', async ({ request }) => { |
| 155 | + const url = new URL('/api/me', app.serverUrl); |
| 156 | + const res = await request.get(url.toString()); |
| 157 | + expect(res.status()).toBe(401); |
| 158 | + }); |
| 159 | + |
| 160 | + test('should return 401 if API key is invalid', async ({ request }) => { |
| 161 | + const url = new URL('/api/me', app.serverUrl); |
| 162 | + const res = await request.get(url.toString(), { |
| 163 | + headers: { Authorization: 'Bearer invalid_key' }, |
| 164 | + }); |
| 165 | + expect(res.status()).toBe(401); |
| 166 | + }); |
| 167 | + |
| 168 | + test('should return 200 with auth object if API key is valid', async ({ request }) => { |
| 169 | + const url = new URL('/api/me', app.serverUrl); |
| 170 | + const res = await request.get(url.toString(), { |
| 171 | + headers: { |
| 172 | + Authorization: `Bearer ${fakeAPIKey.secret}`, |
| 173 | + }, |
| 174 | + }); |
| 175 | + const apiKeyData = await res.json(); |
| 176 | + expect(res.status()).toBe(200); |
| 177 | + expect(apiKeyData.userId).toBe(fakeBapiUser.id); |
| 178 | + expect(apiKeyData.tokenType).toBe(TokenType.ApiKey); |
| 179 | + }); |
| 180 | + |
| 181 | + test('should handle multiple token types', async ({ page, context }) => { |
| 182 | + const u = createTestUtils({ app, page, context }); |
| 183 | + const url = new URL('/api/me', app.serverUrl); |
| 184 | + |
| 185 | + // Sign in to get a session token |
| 186 | + await u.po.signIn.goTo(); |
| 187 | + await u.po.signIn.waitForMounted(); |
| 188 | + await u.po.signIn.signInWithEmailAndInstantPassword({ email: fakeUser.email, password: fakeUser.password }); |
| 189 | + await u.po.expect.toBeSignedIn(); |
| 190 | + |
| 191 | + // GET endpoint (only accepts api_key) |
| 192 | + const getRes = await u.page.request.get(url.toString()); |
| 193 | + expect(getRes.status()).toBe(401); |
| 194 | + |
| 195 | + // POST endpoint (accepts both api_key and session_token) |
| 196 | + // Test with session token |
| 197 | + const postWithSessionRes = await u.page.request.post(url.toString()); |
| 198 | + const sessionData = await postWithSessionRes.json(); |
| 199 | + expect(postWithSessionRes.status()).toBe(200); |
| 200 | + expect(sessionData.userId).toBe(fakeBapiUser.id); |
| 201 | + expect(sessionData.tokenType).toBe(TokenType.SessionToken); |
| 202 | + |
| 203 | + // Test with API key |
| 204 | + const postWithApiKeyRes = await u.page.request.post(url.toString(), { |
| 205 | + headers: { |
| 206 | + Authorization: `Bearer ${fakeAPIKey.secret}`, |
| 207 | + }, |
| 208 | + }); |
| 209 | + const apiKeyData = await postWithApiKeyRes.json(); |
| 210 | + expect(postWithApiKeyRes.status()).toBe(200); |
| 211 | + expect(apiKeyData.userId).toBe(fakeBapiUser.id); |
| 212 | + expect(apiKeyData.tokenType).toBe(TokenType.ApiKey); |
| 213 | + }); |
| 214 | +}); |
0 commit comments