-
Notifications
You must be signed in to change notification settings - Fork 460
chore(backend,nextjs): Introduce API keys methods and integration tests #6169
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
Changes from 7 commits
Commits
Show all changes
16 commits
Select commit
Hold shift + click to select a range
b310543
chore: introduce api keys integration tests
wobsoriano 5a6de7b
chore: reduce expiration time for tests
wobsoriano 352a70c
chore: remove api key listing for now
wobsoriano 7826215
chore: remove other api key methods for now
wobsoriano 3f8b5a9
chore: clean up tests
wobsoriano 1b749b4
chore: add changeset
wobsoriano a94adda
chore: add changeset
wobsoriano 96a80d5
chore: update changeset
wobsoriano bdee047
chore: update fake api key generated name
wobsoriano 3da4f2b
chore: remove revoked test
wobsoriano 0e6e6f4
chore: clean up var names
wobsoriano dd63435
chore: clear passed values
wobsoriano 1ac3d7b
chore: separate nextjs changeset
wobsoriano 07f8ca8
chore: update changeset
wobsoriano 35c82ff
Merge branch 'main' into rob/api-keys-integration-tests
wobsoriano 429802b
chore: clean up auth helper
wobsoriano File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,7 @@ | ||
| --- | ||
| "@clerk/backend": minor | ||
| "@clerk/nextjs": patch | ||
| --- | ||
|
|
||
| - Introduce API keys Backend SDK methods | ||
| - Fix `auth.protect()` unauthorized error bubbling within middleware | ||
|
wobsoriano marked this conversation as resolved.
Outdated
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -54,5 +54,9 @@ | |
| "with-whatsapp-phone-code": { | ||
| "pk": "", | ||
| "sk": "" | ||
| }, | ||
| "with-api-keys": { | ||
| "pk": "", | ||
| "sk": "" | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,238 @@ | ||
| import type { User } from '@clerk/backend'; | ||
| import { TokenType } from '@clerk/backend/internal'; | ||
| import { expect, test } from '@playwright/test'; | ||
|
|
||
| import type { Application } from '../../models/application'; | ||
| import { appConfigs } from '../../presets'; | ||
| import type { FakeAPIKey, FakeUser } from '../../testUtils'; | ||
| import { createTestUtils } from '../../testUtils'; | ||
|
|
||
| test.describe('Next.js API key auth within clerkMiddleware() @nextjs', () => { | ||
| test.describe.configure({ mode: 'parallel' }); | ||
| let app: Application; | ||
| let fakeUser: FakeUser; | ||
| let fakeBapiUser: User; | ||
| let fakeAPIKey: FakeAPIKey; | ||
|
|
||
| test.beforeAll(async () => { | ||
| app = await appConfigs.next.appRouter | ||
| .clone() | ||
| .addFile( | ||
| `src/middleware.ts`, | ||
| () => ` | ||
| import { clerkMiddleware, createRouteMatcher } from '@clerk/nextjs/server'; | ||
|
|
||
| const isProtectedRoute = createRouteMatcher(['/api(.*)']); | ||
|
|
||
| export default clerkMiddleware(async (auth, req) => { | ||
| if (isProtectedRoute(req)) { | ||
| await auth.protect({ token: 'api_key' }); | ||
| } | ||
| }); | ||
|
|
||
| export const config = { | ||
| matcher: [ | ||
| '/((?!.*\\..*|_next).*)', // Don't run middleware on static files | ||
| '/', // Run middleware on index page | ||
| '/(api|trpc)(.*)', | ||
| ], // Run middleware on API routes | ||
| }; | ||
| `, | ||
| ) | ||
| .addFile( | ||
| 'src/app/api/me/route.ts', | ||
| () => ` | ||
| import { auth } from '@clerk/nextjs/server'; | ||
|
|
||
| export async function GET() { | ||
| const { userId, tokenType } = await auth({ acceptsToken: 'api_key' }); | ||
|
|
||
| return Response.json({ userId, tokenType }); | ||
| } | ||
| `, | ||
| ) | ||
| .commit(); | ||
|
|
||
| await app.setup(); | ||
| await app.withEnv(appConfigs.envs.withAPIKeys); | ||
| await app.dev(); | ||
|
|
||
| const u = createTestUtils({ app }); | ||
| fakeUser = u.services.users.createFakeUser(); | ||
| fakeBapiUser = await u.services.users.createBapiUser(fakeUser); | ||
| fakeAPIKey = await u.services.users.createFakeAPIKey(fakeBapiUser.id); | ||
| }); | ||
|
|
||
| test.afterAll(async () => { | ||
| await fakeAPIKey.revoke(); | ||
| await fakeUser.deleteIfExists(); | ||
| await app.teardown(); | ||
| }); | ||
|
|
||
| test('should return 401 if no API key is provided', async ({ request }) => { | ||
| const url = new URL('/api/me', app.serverUrl); | ||
| const res = await request.get(url.toString()); | ||
| expect(res.status()).toBe(401); | ||
| }); | ||
|
|
||
| test('should return 401 if API key is invalid', async ({ request }) => { | ||
| const url = new URL('/api/me', app.serverUrl); | ||
| const res = await request.get(url.toString(), { | ||
| headers: { Authorization: 'Bearer invalid_key' }, | ||
| }); | ||
| expect(res.status()).toBe(401); | ||
| }); | ||
|
|
||
| test('should return 401 if API key is revoked', async ({ request }) => { | ||
| const url = new URL('/api/me', app.serverUrl); | ||
| const u = createTestUtils({ app }); | ||
| const tempApiKey = await u.services.users.createFakeAPIKey(fakeBapiUser.id); | ||
| await tempApiKey.revoke(); | ||
|
|
||
| const res = await request.get(url.toString(), { | ||
| headers: { Authorization: `Bearer ${tempApiKey.secret}` }, | ||
| }); | ||
| expect(res.status()).toBe(401); | ||
| }); | ||
|
|
||
| test('should return 200 with auth object if API key is valid', async ({ request }) => { | ||
| const url = new URL('/api/me', app.serverUrl); | ||
| const res = await request.get(url.toString(), { | ||
| headers: { | ||
| Authorization: `Bearer ${fakeAPIKey.secret}`, | ||
| }, | ||
| }); | ||
| const apiKeyData = await res.json(); | ||
| expect(res.status()).toBe(200); | ||
| expect(apiKeyData.userId).toBe(fakeBapiUser.id); | ||
| expect(apiKeyData.tokenType).toBe(TokenType.ApiKey); | ||
| }); | ||
| }); | ||
|
|
||
| test.describe('Next.js API key auth within routes @nextjs', () => { | ||
| test.describe.configure({ mode: 'parallel' }); | ||
| let app: Application; | ||
| let fakeUser: FakeUser; | ||
| let fakeBapiUser: User; | ||
| let fakeAPIKey: FakeAPIKey; | ||
|
|
||
| test.beforeAll(async () => { | ||
| app = await appConfigs.next.appRouter | ||
| .clone() | ||
| .addFile( | ||
| 'src/app/api/me/route.ts', | ||
| () => ` | ||
| import { auth } from '@clerk/nextjs/server'; | ||
|
|
||
| export async function GET() { | ||
| const { userId, tokenType } = await auth({ acceptsToken: 'api_key' }); | ||
|
|
||
| if (!userId) { | ||
| return Response.json({ error: 'Unauthorized' }, { status: 401 }); | ||
| } | ||
|
|
||
| return Response.json({ userId, tokenType }); | ||
| } | ||
|
|
||
| export async function POST() { | ||
| const authObject = await auth({ acceptsToken: ['api_key', 'session_token'] }); | ||
|
|
||
| if (!authObject.isAuthenticated) { | ||
| return Response.json({ error: 'Unauthorized' }, { status: 401 }); | ||
| } | ||
|
|
||
| return Response.json({ userId: authObject.userId, tokenType: authObject.tokenType }); | ||
| } | ||
| `, | ||
| ) | ||
| .commit(); | ||
|
|
||
| await app.setup(); | ||
| await app.withEnv(appConfigs.envs.withAPIKeys); | ||
| await app.dev(); | ||
|
|
||
| const u = createTestUtils({ app }); | ||
| fakeUser = u.services.users.createFakeUser(); | ||
| fakeBapiUser = await u.services.users.createBapiUser(fakeUser); | ||
| fakeAPIKey = await u.services.users.createFakeAPIKey(fakeBapiUser.id); | ||
| }); | ||
|
|
||
| test.afterAll(async () => { | ||
| await fakeAPIKey.revoke(); | ||
| await fakeUser.deleteIfExists(); | ||
| await app.teardown(); | ||
| }); | ||
|
|
||
| test('should return 401 if no API key is provided', async ({ request }) => { | ||
| const url = new URL('/api/me', app.serverUrl); | ||
| const res = await request.get(url.toString()); | ||
| expect(res.status()).toBe(401); | ||
| }); | ||
|
|
||
| test('should return 401 if API key is invalid', async ({ request }) => { | ||
| const url = new URL('/api/me', app.serverUrl); | ||
| const res = await request.get(url.toString(), { | ||
| headers: { Authorization: 'Bearer invalid_key' }, | ||
| }); | ||
| expect(res.status()).toBe(401); | ||
| }); | ||
|
|
||
| test('should return 401 if API key is revoked', async ({ request }) => { | ||
| const url = new URL('/api/me', app.serverUrl); | ||
| const u = createTestUtils({ app }); | ||
| const tempApiKey = await u.services.users.createFakeAPIKey(fakeBapiUser.id); | ||
| await tempApiKey.revoke(); | ||
|
|
||
| const res = await request.get(url.toString(), { | ||
| headers: { Authorization: `Bearer ${tempApiKey.secret}` }, | ||
| }); | ||
| expect(res.status()).toBe(401); | ||
| }); | ||
|
|
||
| test('should return 200 with auth object if API key is valid', async ({ request }) => { | ||
| const url = new URL('/api/me', app.serverUrl); | ||
| const res = await request.get(url.toString(), { | ||
| headers: { | ||
| Authorization: `Bearer ${fakeAPIKey.secret}`, | ||
| }, | ||
| }); | ||
| const apiKeyData = await res.json(); | ||
| expect(res.status()).toBe(200); | ||
| expect(apiKeyData.userId).toBe(fakeBapiUser.id); | ||
| expect(apiKeyData.tokenType).toBe(TokenType.ApiKey); | ||
| }); | ||
|
|
||
| test('should handle multiple token types', async ({ page, context }) => { | ||
| const u = createTestUtils({ app, page, context }); | ||
| const url = new URL('/api/me', app.serverUrl); | ||
|
|
||
| // Sign in to get a session token | ||
| await u.po.signIn.goTo(); | ||
| await u.po.signIn.waitForMounted(); | ||
| await u.po.signIn.signInWithEmailAndInstantPassword({ email: fakeUser.email, password: fakeUser.password }); | ||
| await u.po.expect.toBeSignedIn(); | ||
|
|
||
| // GET endpoint (only accepts api_key) | ||
| const getRes = await u.page.request.get(url.toString()); | ||
| expect(getRes.status()).toBe(401); | ||
|
|
||
| // POST endpoint (accepts both api_key and session_token) | ||
| // Test with session token | ||
| const postWithSessionRes = await u.page.request.post(url.toString()); | ||
| const sessionData = await postWithSessionRes.json(); | ||
| expect(postWithSessionRes.status()).toBe(200); | ||
| expect(sessionData.userId).toBe(fakeBapiUser.id); | ||
| expect(sessionData.tokenType).toBe(TokenType.SessionToken); | ||
|
|
||
| // Test with API key | ||
| const postWithApiKeyRes = await u.page.request.post(url.toString(), { | ||
| headers: { | ||
| Authorization: `Bearer ${fakeAPIKey.secret}`, | ||
| }, | ||
| }); | ||
| const apiKeyData = await postWithApiKeyRes.json(); | ||
| expect(postWithApiKeyRes.status()).toBe(200); | ||
| expect(apiKeyData.userId).toBe(fakeBapiUser.id); | ||
| expect(apiKeyData.tokenType).toBe(TokenType.ApiKey); | ||
| }); | ||
| }); |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.