-
Notifications
You must be signed in to change notification settings - Fork 357
chore(backend,nextjs): [WIP] auth helper improvements and integration tests #6163
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
base: main
Are you sure you want to change the base?
Conversation
|
The latest updates on your projects. Learn more about Vercel for Git ↗︎
|
📝 Walkthrough""" WalkthroughThis change introduces new API key management methods ( Assessment against linked issues
Suggested reviewers
📜 Recent review detailsConfiguration used: CodeRabbit UI 📒 Files selected for processing (1)
⏰ Context from checks skipped due to timeout of 90000ms (5)
🔇 Additional comments (1)
🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
@clerk/agent-toolkit
@clerk/astro
@clerk/backend
@clerk/chrome-extension
@clerk/clerk-js
@clerk/dev-cli
@clerk/elements
@clerk/clerk-expo
@clerk/expo-passkeys
@clerk/express
@clerk/fastify
@clerk/localizations
@clerk/nextjs
@clerk/nuxt
@clerk/clerk-react
@clerk/react-router
@clerk/remix
@clerk/shared
@clerk/tanstack-react-start
@clerk/testing
@clerk/themes
@clerk/types
@clerk/upgrade
@clerk/vue
commit: |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 1
🧹 Nitpick comments (2)
integration/templates/next-app-router/src/app/api/machine/route.ts (1)
8-8
: Inconsistent error response format with middleware.The error response format
{ error: 'Unauthorized' }
differs from the middleware's{ message: 'Unauthorized' }
format. Consider using consistent error response structure across the application.Apply this diff for consistency:
- return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); + return NextResponse.json({ message: 'Unauthorized' }, { status: 401 });And similarly for the POST handler:
- return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); + return NextResponse.json({ message: 'Unauthorized' }, { status: 401 });Also applies to: 18-18
integration/testUtils/usersService.ts (1)
185-202
: LGTM! Solid implementation with good practices.The implementation correctly:
- Uses a reasonable 1-hour expiration for testing
- Retrieves the secret after creation
- Provides cleanup via the revoke method
- Uses faker for realistic test data
Consider adding error handling for the secret retrieval:
- const { secret } = await clerkClient.apiKeys.getSecret(apiKey.id); + try { + const { secret } = await clerkClient.apiKeys.getSecret(apiKey.id); + // ... rest of the implementation + } catch (error) { + // Clean up the created API key if secret retrieval fails + await clerkClient.apiKeys.revoke({ apiKeyId: apiKey.id, revocationReason: 'Failed to retrieve secret' }); + throw error; + }
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (12)
integration/.keys.json.sample
(1 hunks)integration/presets/envs.ts
(2 hunks)integration/presets/longRunningApps.ts
(1 hunks)integration/templates/next-app-router/src/app/api/machine/route.ts
(1 hunks)integration/testUtils/index.ts
(1 hunks)integration/testUtils/usersService.ts
(4 hunks)integration/tests/api-keys/auth.test.ts
(1 hunks)integration/tests/api-keys/protect.test.ts
(1 hunks)packages/backend/src/api/endpoints/APIKeysApi.ts
(1 hunks)packages/backend/src/index.ts
(1 hunks)packages/nextjs/src/app-router/server/auth.ts
(1 hunks)packages/nextjs/src/server/clerkMiddleware.ts
(1 hunks)
🧰 Additional context used
🧠 Learnings (1)
packages/nextjs/src/app-router/server/auth.ts (1)
Learnt from: wobsoriano
PR: clerk/javascript#6123
File: packages/nextjs/src/server/__tests__/getAuthDataFromRequest.test.ts:63-75
Timestamp: 2025-06-16T01:27:54.563Z
Learning: In packages/nextjs/src/server/data/getAuthDataFromRequest.ts, the tokenType behavior on mismatch is intentionally different between array and single acceptsToken values: when acceptsToken is an array and the token type doesn't match any in the array, tokenType returns null; when acceptsToken is a single value and the token type doesn't match, tokenType returns the requested single value. This design aligns with developer intent and provides a more ergonomic API for common use cases.
🔇 Additional comments (19)
integration/.keys.json.sample (1)
57-61
: LGTM! Clean configuration addition.The new API key entry follows the established format and naming conventions perfectly.
packages/backend/src/index.ts (1)
109-109
: LGTM! Proper type export addition.The APIKey type export is correctly positioned and follows the established pattern.
integration/presets/longRunningApps.ts (1)
45-45
: LGTM! Well-structured configuration addition.The new long-running app configuration correctly reuses existing components and follows the established pattern.
integration/testUtils/index.ts (1)
9-9
: LGTM! Consistent type handling.The FakeAPIKey type import and export follow the established pattern for other fake types.
Also applies to: 12-12
integration/presets/envs.ts (1)
166-170
: LGTM! Exemplary pattern adherence.The withAPIKeys environment configuration follows the established structure perfectly and uses the correct instance keys.
Also applies to: 196-196
packages/nextjs/src/server/clerkMiddleware.ts (1)
468-468
: Correct fix for terminating unauthorized requests.This change properly terminates requests with invalid tokens by returning a JSON response instead of continuing the middleware chain. This aligns with the requirement mentioned in the past review comment.
integration/templates/next-app-router/src/app/api/machine/route.ts (2)
4-12
: LGTM! Good demonstration of API key-only authentication.The GET handler correctly demonstrates restricting access to API keys only, which is useful for machine-to-machine authentication scenarios.
14-22
: LGTM! Good demonstration of flexible token acceptance.The POST handler correctly demonstrates accepting multiple token types, which provides flexibility for different client authentication methods.
packages/nextjs/src/app-router/server/auth.ts (1)
190-191
: LGTM! Correctly implements configurable token type support.The implementation properly extracts the token type from parameters and passes it to the auth() call, enabling auth.protect() to specify which token types it accepts. The fallback to SessionToken maintains backward compatibility.
integration/testUtils/usersService.ts (1)
60-64
: LGTM! Well-designed API key testing utility type.The FakeAPIKey type provides a clean interface with the API key object, its secret, and a convenient revoke method for test cleanup.
integration/tests/api-keys/auth.test.ts (4)
8-26
: LGTM! Excellent test setup and teardown.The test properly sets up fake users and API keys before all tests and cleans them up afterward. The serial test execution mode is appropriate for stateful integration tests.
28-51
: LGTM! Comprehensive API key validation testing.The test correctly covers all authentication scenarios:
- Missing API key (401)
- Invalid API key (401)
- Valid API key (200 with correct userId)
53-91
: LGTM! Thorough testing of multiple token type scenarios.The test effectively validates that:
- GET endpoint restricts to API keys only (rejects session tokens)
- POST endpoint accepts both token types
- Both authentication methods return correct user IDs
70-79
: ```shell
#!/bin/bashCorrectly display the headers-utils.ts to inspect header and cookie fallback logic
file=$(fd headers-utils.ts packages/nextjs/src/server)
echo "=== File: $file ==="
sed -n '1,200p' "$file"</details> <details> <summary>integration/tests/api-keys/protect.test.ts (3)</summary> `16-46`: **Excellent test setup with comprehensive API route configuration.** The beforeAll setup correctly configures the test environment with: - Proper app cloning and file addition - Clear separation of GET (API key only) and POST (multiple token types) handlers - Appropriate environment configuration and resource creation --- `54-85`: **Thorough API key validation test coverage.** This test comprehensively validates API key protection by testing all the critical scenarios: - Missing API key (401) - Invalid API key (401) - Malformed authorization header (401) - Valid API key (200 with correct userId) The test assertions are appropriate and the flow is logical. --- `87-124`: **Well-designed test for multiple token type handling.** This test effectively validates the mixed token authentication scenario by: - Establishing a session through sign-in - Testing GET endpoint rejection without API key - Verifying POST endpoint accepts both session tokens and API keys - Asserting correct userId response in both cases The test logic correctly demonstrates the different token acceptance policies between endpoints. </details> <details> <summary>packages/backend/src/api/endpoints/APIKeysApi.ts (2)</summary> `7-49`: **Well-defined parameter types for API key operations.** The type definitions are comprehensive and well-documented: - `CreateAPIKeyParams` includes all necessary fields with clear JSDoc comments - `UpdateAPIKeyParams` and `RevokeAPIKeyParams` are appropriately structured - Optional fields are correctly typed with null unions --- `52-58`: **LGTM for create, revoke, and getSecret methods.** These methods are correctly implemented: - `create`: POST to base path with all parameters - `revoke`: POST to specific revoke endpoint with proper path construction - `getSecret`: GET to secret endpoint with proper ID validation The HTTP methods and paths are appropriate for their respective operations. Also applies to: 72-91 </details> </blockquote></details> </details> <!-- This is an auto-generated comment by CodeRabbit for review status -->
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
🧹 Nitpick comments (3)
integration/tests/api-keys/auth.test.ts (3)
16-26
: Consider removing redundant teardown call.The resource cleanup is well-implemented, but
app.teardown()
in theafterAll
hook might be redundant if the test framework already handles app lifecycle management.test.afterAll(async () => { await fakeAPIKey.revoke(); await fakeUser.deleteIfExists(); - await app.teardown(); });
28-42
: Enhance error response validation.The test properly validates status codes for unauthorized scenarios, but it doesn't verify the error response format or message content. This could help catch regressions in error handling.
Consider adding response body validation for error cases:
// No API key provided const noKeyRes = await fetch(url); expect(noKeyRes.status).toBe(401); + const noKeyError = await noKeyRes.json(); + expect(noKeyError).toHaveProperty('error'); // Invalid API key const invalidKeyRes = await fetch(url, { headers: { Authorization: 'Bearer invalid_key', }, }); expect(invalidKeyRes.status).toBe(401); + const invalidKeyError = await invalidKeyRes.json(); + expect(invalidKeyError).toHaveProperty('error');
54-73
: Verify user ID consistency assumption.The test assumes that
fakeBapiUser.id
matches the user ID from the session token after signing in withfakeUser
credentials. While this should be correct sincefakeBapiUser
is created fromfakeUser
, it would be helpful to make this relationship more explicit.Consider adding a comment to clarify the user relationship:
+ // Both fakeUser and fakeBapiUser represent the same user in different systems // 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);
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (5)
integration/templates/next-app-router/src/app/api/machine/route.ts
(1 hunks)integration/tests/api-keys/auth.test.ts
(1 hunks)integration/tests/api-keys/protect.test.ts
(1 hunks)packages/nextjs/src/app-router/server/auth.ts
(1 hunks)packages/nextjs/src/server/protect.ts
(2 hunks)
✅ Files skipped from review due to trivial changes (1)
- packages/nextjs/src/server/protect.ts
🚧 Files skipped from review as they are similar to previous changes (3)
- integration/templates/next-app-router/src/app/api/machine/route.ts
- packages/nextjs/src/app-router/server/auth.ts
- integration/tests/api-keys/protect.test.ts
⏰ Context from checks skipped due to timeout of 90000ms (5)
- GitHub Check: semgrep-cloud-platform/scan
- GitHub Check: Build Packages
- GitHub Check: Formatting | Dedupe | Changeset
- GitHub Check: Analyze (javascript-typescript)
- GitHub Check: semgrep/ci
🔇 Additional comments (3)
integration/tests/api-keys/auth.test.ts (3)
1-14
: Test setup looks well-structured.The imports, test configuration, and variable declarations follow good testing practices with proper typing and parallel test execution.
43-52
: Good validation of successful API key authentication.The test properly validates both the HTTP status and the returned user ID, which ensures the API key is correctly associated with the expected user.
74-85
: Excellent test coverage for multiple authentication methods.The test effectively validates that the POST endpoint accepts both session tokens and API keys, demonstrating proper token type flexibility. The use of different request methods (
u.page.request
vsfetch
) correctly tests authenticated vs unauthenticated contexts.
@@ -465,7 +446,7 @@ const handleControlFlowErrors = ( | |||
requestState: RequestState, | |||
): Response => { | |||
if (isNextjsUnauthorizedError(e)) { | |||
const response = NextResponse.next({ status: 401 }); | |||
const response = new NextResponse(null, { status: 401 }); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
We need to terminate requests for invalid tokens. The previous one continues processing the middleware chain instead of ending the request.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
🧹 Nitpick comments (1)
integration/templates/next-app-router/src/app/api/machine2/route.ts (1)
1-12
: Consider adding error handling for production-ready code.While the current implementation is suitable for integration testing, consider adding explicit error handling and input validation for production use cases.
export async function GET() { + try { const { userId } = await auth.protect({ token: 'api_key' }); return NextResponse.json({ userId }); + } catch (error) { + return NextResponse.json({ error: 'Authentication failed' }, { status: 401 }); + } }
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (3)
integration/templates/next-app-router/src/app/api/machine2/route.ts
(1 hunks)integration/tests/api-keys/auth.test.ts
(1 hunks)integration/tests/api-keys/protect.test.ts
(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- integration/tests/api-keys/protect.test.ts
⏰ Context from checks skipped due to timeout of 90000ms (5)
- GitHub Check: semgrep-cloud-platform/scan
- GitHub Check: Formatting | Dedupe | Changeset
- GitHub Check: Build Packages
- GitHub Check: semgrep/ci
- GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (7)
integration/templates/next-app-router/src/app/api/machine2/route.ts (2)
4-7
: LGTM! Clean implementation for API key-only authentication.The GET handler correctly restricts access to API keys only, which aligns with the PR objectives for testing token type specificity in
auth.protect()
.
9-12
: LGTM! Proper multi-token type configuration.The POST handler correctly accepts both API keys and session tokens, providing good test coverage for the enhanced token acceptance logic.
integration/tests/api-keys/auth.test.ts (5)
8-26
: Excellent test setup with proper resource management.The test suite setup properly creates fake users and API keys with appropriate cleanup in
afterAll
. The parallel execution configuration is also a good practice for performance.
28-52
: Comprehensive API key validation testing.The test covers all essential scenarios: no key, invalid key, and valid key with proper assertions. This validates the core API key authentication functionality.
54-85
: Thorough multi-token type validation.The test properly validates that GET endpoints reject session tokens while POST endpoints accept both session tokens and API keys. This directly tests the token type specificity mentioned in the PR objectives.
88-169
: Well-structured parallel test suite for auth.protect().The second test suite mirrors the first but tests the
/api/machine2
endpoint usingauth.protect()
, providing comprehensive coverage for both authentication approaches. The test logic is consistent and thorough.
70-74
: I need to locate wherefakeBapiUser
and the API‐key/session helpers are set up. Running these to inspect the test file and any fixture helpers:#!/bin/bash # Locate fakeBapiUser in the API-keys auth test rg "fakeBapiUser" -n integration/tests/api-keys/auth.test.ts # Show the test setup to see how users and API keys are created sed -n '1,200p' integration/tests/api-keys/auth.test.ts # Search for any helper functions that create API keys or users rg "create.*ApiKey" -n . rg "create.*User" -n .
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 1
🧹 Nitpick comments (4)
integration/tests/api-keys/middleware.test.ts (1)
26-30
: Consider adding error handling for async middleware.The middleware implementation looks correct, but consider adding error handling around the
auth.protect()
call to ensure proper error responses are returned.export default clerkMiddleware(async (auth, req) => { if (isProtectedRoute(req)) { + try { await auth.protect({ token: 'api_key' }); + } catch (error) { + console.error('Auth protection failed:', error); + throw error; + } } });integration/tests/api-keys/auth.test.ts (3)
69-73
: Remove debug logging statements.These console.log statements appear to be leftover debug code and should be removed before merging.
- if (noKeyRes.status !== 401) { - console.log('Unexpected status for "noKeyRes". Status:', noKeyRes.status, noKeyRes.statusText); - const body = await noKeyRes.text(); - console.log(`error body ${body} error body`); - }
179-183
: Remove duplicate debug logging statements.Same debug logging issue as in the first test suite - these should be removed.
- if (noKeyRes.status !== 401) { - console.log('Unexpected status for "noKeyRes". Status:', noKeyRes.status, noKeyRes.statusText); - const body = await noKeyRes.text(); - console.log(`error body ${body} error body`); - }
106-107
: Inconsistent request methods may cause confusion.The test mixes
u.page.request.get()
andu.page.request.post()
with regularfetch()
. Consider using a consistent approach throughout the test for clarity.Consider using either Playwright's request methods consistently:
- const postWithApiKeyRes = await fetch(url, { - method: 'POST', - headers: { - Authorization: `Bearer ${fakeAPIKey.secret}`, - }, - }); + const postWithApiKeyRes = await u.page.request.post(url.toString(), { + headers: { + Authorization: `Bearer ${fakeAPIKey.secret}`, + }, + }); - const apiKeyData = await postWithApiKeyRes.json(); - expect(postWithApiKeyRes.status).toBe(200); + const apiKeyData = await postWithApiKeyRes.json(); + expect(postWithApiKeyRes.status()).toBe(200);Also applies to: 111-111, 117-125
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
integration/tests/api-keys/auth.test.ts
(1 hunks)integration/tests/api-keys/middleware.test.ts
(1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
- GitHub Check: semgrep-cloud-platform/scan
- GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (2)
integration/tests/api-keys/middleware.test.ts (1)
71-95
: Test coverage is comprehensive and well-structured.The test effectively covers all three authentication scenarios (no key, invalid key, valid key) with appropriate assertions. The status code checks and response validation are correct.
integration/tests/api-keys/auth.test.ts (1)
9-9
: Verify the tag naming convention.One test suite uses
@nextjs
while the other uses@xnextjs
. Please confirm this is intentional and aligns with your testing infrastructure.Could you clarify the difference between
@nextjs
and@xnextjs
tags? This appears inconsistent and might affect test filtering.Also applies to: 129-129
if (!userId) { | ||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); | ||
} | ||
return NextResponse.json({ userId }); | ||
} | ||
export async function POST() { | ||
const authObject = await auth({ acceptsToken: ['api_key', 'session_token'] }); | ||
if (!authObject.isAuthenticated) { | ||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); | ||
} | ||
return NextResponse.json({ userId: authObject.userId }); | ||
} | ||
`, | ||
) | ||
.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 validate API key', async () => { | ||
const url = new URL('/api/me', app.serverUrl); | ||
|
||
// No API key provided | ||
const noKeyRes = await fetch(url); | ||
if (noKeyRes.status !== 401) { | ||
console.log('Unexpected status for "noKeyRes". Status:', noKeyRes.status, noKeyRes.statusText); | ||
const body = await noKeyRes.text(); | ||
console.log(`error body ${body} error body`); | ||
} | ||
expect(noKeyRes.status).toBe(401); | ||
|
||
// Invalid API key | ||
const invalidKeyRes = await fetch(url, { | ||
headers: { | ||
Authorization: 'Bearer invalid_key', | ||
}, | ||
}); | ||
expect(invalidKeyRes.status).toBe(401); | ||
|
||
// Valid API key | ||
const validKeyRes = await fetch(url, { | ||
headers: { | ||
Authorization: `Bearer ${fakeAPIKey.secret}`, | ||
}, | ||
}); | ||
const apiKeyData = await validKeyRes.json(); | ||
expect(validKeyRes.status).toBe(200); | ||
expect(apiKeyData.userId).toBe(fakeBapiUser.id); | ||
}); | ||
|
||
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); | ||
|
||
// Test with API key | ||
const postWithApiKeyRes = await fetch(url, { | ||
method: 'POST', | ||
headers: { | ||
Authorization: `Bearer ${fakeAPIKey.secret}`, | ||
}, | ||
}); | ||
const apiKeyData = await postWithApiKeyRes.json(); | ||
expect(postWithApiKeyRes.status).toBe(200); | ||
expect(apiKeyData.userId).toBe(fakeBapiUser.id); | ||
}); | ||
}); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Significant code duplication between test suites.
The two test suites have nearly identical structure and test logic, differing mainly in using auth()
vs auth.protect()
. Consider extracting common test scenarios into shared helper functions to reduce duplication.
Here's a suggested approach to reduce duplication:
+const createApiKeyTestSuite = (suiteName: string, authMethod: 'auth' | 'auth.protect') => {
+ const getRouteImplementation = () => {
+ if (authMethod === 'auth') {
+ return `
+ export async function GET() {
+ const { userId } = await auth({ acceptsToken: 'api_key' });
+ if (!userId) {
+ return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
+ }
+ return NextResponse.json({ userId });
+ }
+ `;
+ } else {
+ return `
+ export async function GET() {
+ const { userId } = await auth.protect({ token: 'api_key' });
+ return NextResponse.json({ userId });
+ }
+ `;
+ }
+ };
+
+ // Common test implementation...
+};
Also applies to: 129-237
🤖 Prompt for AI Agents
In integration/tests/api-keys/auth.test.ts around lines 9 to 127, there is
significant duplication between the test suites that use auth() and
auth.protect(), with nearly identical test logic and structure. To fix this,
extract the common test scenarios such as API key validation and multiple token
handling into shared helper functions that accept parameters to differentiate
between auth() and auth.protect() usage. Then call these helpers from each test
suite to reduce code duplication and improve maintainability.
Description
auth.protect()
calls are not correctly terminating requests for invalid tokensauth.protect()
in route handlers failed to respect thetoken
optionauth()
andauth.protect()
calls insideclerkMiddleware
auth()
andauth.protect()
The underlying tests also validate the general token acceptance mechanism, which is applicable to other token types like
oauth_token
andmachine_token
simply by changing theacceptsToken
option.Resolves USER-2233
Checklist
pnpm test
runs as expected.pnpm build
runs as expected.Type of change
Summary by CodeRabbit