Skip to content

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

Open
wants to merge 36 commits into
base: main
Choose a base branch
from

Conversation

wobsoriano
Copy link
Member

@wobsoriano wobsoriano commented Jun 19, 2025

Description

  • Implements the necessary methods for managing API keys
  • Fixes an issue where auth.protect() calls are not correctly terminating requests for invalid tokens
  • Fixes an issue where auth.protect() in route handlers failed to respect the token option
  • Respects tokenType in auth() and auth.protect() calls inside clerkMiddleware
  • Adds integration tests for Next.js to verify token validation with both auth() and auth.protect()

The underlying tests also validate the general token acceptance mechanism, which is applicable to other token types like oauth_token and machine_token simply by changing the acceptsToken option.

Resolves USER-2233

Checklist

  • pnpm test runs as expected.
  • pnpm build runs as expected.
  • (If applicable) JSDoc comments have been added or updated for any package exports
  • (If applicable) Documentation has been updated

Type of change

  • 🐛 Bug fix
  • 🌟 New feature
  • 🔨 Breaking change
  • 📖 Refactoring / dependency upgrade / documentation
  • other:

Summary by CodeRabbit

  • New Features
    • Introduced API key authentication support for Next.js environments, including the ability to create, list, update, revoke, and retrieve secrets for API keys.
    • Added new environment and app presets for testing API key scenarios.
  • Bug Fixes
    • Improved middleware authentication handling to centralize token acceptance logic and error responses.
  • Tests
    • Added comprehensive integration tests covering API key authentication in Next.js middleware and API routes, including validation of multiple token types.
  • Chores
    • Updated sample configuration files and test utility exports to support API key testing.
    • Added a new script for running integration tests with API key scenarios.
    • Enabled debug mode in Next.js app-router middleware for enhanced troubleshooting.

Copy link

changeset-bot bot commented Jun 19, 2025

⚠️ No Changeset found

Latest commit: 2106816

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

Copy link

vercel bot commented Jun 19, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
clerk-js-sandbox ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jun 21, 2025 4:33am

@wobsoriano wobsoriano changed the title chore(repo): Machine auth integration tests chore(backend,next): Machine auth integration tests Jun 19, 2025
@wobsoriano wobsoriano changed the title chore(backend,next): Machine auth integration tests chore(backend,nextjs): Machine auth integration tests Jun 19, 2025
@wobsoriano wobsoriano changed the title chore(backend,nextjs): Machine auth integration tests chore(backend,nextjs): API keys integration tests Jun 20, 2025
@wobsoriano wobsoriano changed the title chore(backend,nextjs): API keys integration tests chore(backend,nextjs): auth function helpers and integration tests Jun 20, 2025
@wobsoriano wobsoriano changed the title chore(backend,nextjs): auth function helpers and integration tests chore(backend,nextjs): auth helper improvements and integration tests Jun 20, 2025
@wobsoriano wobsoriano marked this pull request as ready for review June 20, 2025 16:32
Copy link
Contributor

coderabbitai bot commented Jun 20, 2025

📝 Walkthrough

"""

Walkthrough

This change introduces new API key management methods (create, update, revoke, and getSecret) to the backend SDK. It also adds comprehensive integration tests for Next.js environments, verifying API key authentication and authorization with the auth() and auth.protect() helpers, including middleware scenarios. Supporting test utilities and environment presets are updated to facilitate API key creation and usage in integration tests. No changes are made to existing exported or public interfaces outside of the new API key methods and types.

Assessment against linked issues

Objective Addressed Explanation
Add create, update, revoke, and getSecret methods to Backend SDK (clerkClient.apiKeys.*) ([USER-2233])
Integration tests with Nextjs using auth() and auth.protect() helpers ([USER-2233])

Suggested reviewers

  • dstaley
  • aeliox
    """

📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6ad36ee and 2106816.

📒 Files selected for processing (1)
  • integration/templates/next-app-router/src/middleware.ts (1 hunks)
⏰ 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 (1)
integration/templates/next-app-router/src/middleware.ts (1)

15-30: LGTM! Debug flag addition supports testing objectives.

The addition of { debug: true } to the clerkMiddleware configuration is a sensible change for an integration test template. This will enable enhanced debugging output during authentication testing, which aligns well with the PR's objectives of improving auth helpers and adding comprehensive integration tests.

The core middleware logic remains unchanged, preserving existing functionality while adding valuable debugging capabilities.


🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need 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)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

pkg-pr-new bot commented Jun 20, 2025

Open in StackBlitz

@clerk/agent-toolkit

npm i https://pkg.pr.new/@clerk/agent-toolkit@6163

@clerk/astro

npm i https://pkg.pr.new/@clerk/astro@6163

@clerk/backend

npm i https://pkg.pr.new/@clerk/backend@6163

@clerk/chrome-extension

npm i https://pkg.pr.new/@clerk/chrome-extension@6163

@clerk/clerk-js

npm i https://pkg.pr.new/@clerk/clerk-js@6163

@clerk/dev-cli

npm i https://pkg.pr.new/@clerk/dev-cli@6163

@clerk/elements

npm i https://pkg.pr.new/@clerk/elements@6163

@clerk/clerk-expo

npm i https://pkg.pr.new/@clerk/clerk-expo@6163

@clerk/expo-passkeys

npm i https://pkg.pr.new/@clerk/expo-passkeys@6163

@clerk/express

npm i https://pkg.pr.new/@clerk/express@6163

@clerk/fastify

npm i https://pkg.pr.new/@clerk/fastify@6163

@clerk/localizations

npm i https://pkg.pr.new/@clerk/localizations@6163

@clerk/nextjs

npm i https://pkg.pr.new/@clerk/nextjs@6163

@clerk/nuxt

npm i https://pkg.pr.new/@clerk/nuxt@6163

@clerk/clerk-react

npm i https://pkg.pr.new/@clerk/clerk-react@6163

@clerk/react-router

npm i https://pkg.pr.new/@clerk/react-router@6163

@clerk/remix

npm i https://pkg.pr.new/@clerk/remix@6163

@clerk/shared

npm i https://pkg.pr.new/@clerk/shared@6163

@clerk/tanstack-react-start

npm i https://pkg.pr.new/@clerk/tanstack-react-start@6163

@clerk/testing

npm i https://pkg.pr.new/@clerk/testing@6163

@clerk/themes

npm i https://pkg.pr.new/@clerk/themes@6163

@clerk/types

npm i https://pkg.pr.new/@clerk/types@6163

@clerk/upgrade

npm i https://pkg.pr.new/@clerk/upgrade@6163

@clerk/vue

npm i https://pkg.pr.new/@clerk/vue@6163

commit: 2106816

Copy link
Contributor

@coderabbitai coderabbitai bot left a 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

📥 Commits

Reviewing files that changed from the base of the PR and between 1ce6a5c and e327d62.

📒 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/bash

Correctly 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 -->

@wobsoriano wobsoriano changed the title chore(backend,nextjs): auth helper improvements and integration tests chore(backend,nextjs): [WIP] auth helper improvements and integration tests Jun 20, 2025
Copy link
Contributor

@coderabbitai coderabbitai bot left a 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 the afterAll 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 with fakeUser credentials. While this should be correct since fakeBapiUser is created from fakeUser, 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

📥 Commits

Reviewing files that changed from the base of the PR and between 5a1b77a and d9cd5a9.

📒 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 vs fetch) 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 });
Copy link
Member Author

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.

Copy link
Contributor

@coderabbitai coderabbitai bot left a 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

📥 Commits

Reviewing files that changed from the base of the PR and between b06204b and 760435e.

📒 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 using auth.protect(), providing comprehensive coverage for both authentication approaches. The test logic is consistent and thorough.


70-74: I need to locate where fakeBapiUser 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 .

Copy link
Contributor

@coderabbitai coderabbitai bot left a 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() and u.page.request.post() with regular fetch(). 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

📥 Commits

Reviewing files that changed from the base of the PR and between 760435e and d3f6c05.

📒 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

Comment on lines +9 to +127
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);
});
});
Copy link
Contributor

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants