Skip to content

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 16 commits into from
Jun 23, 2025

Conversation

wobsoriano
Copy link
Member

@wobsoriano wobsoriano commented Jun 21, 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

    • Added support for creating, revoking, and retrieving API keys, including their secrets.
    • Introduced integration tests for API key authentication in Next.js middleware and route handlers.
    • Enabled environment and app configurations that utilize API keys for authentication.
  • Bug Fixes

    • Improved token type handling in authentication protection to support multiple token types.
  • Refactor

    • Simplified and unified authentication logic in Next.js Clerk middleware for better consistency.
  • Tests

    • Added comprehensive tests for API key authentication scenarios, including error handling and multi-token acceptance.
  • Chores

    • Updated type exports and sample configuration files to support API key functionality.

Copy link

changeset-bot bot commented Jun 21, 2025

🦋 Changeset detected

Latest commit: 429802b

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 11 packages
Name Type
@clerk/nextjs Minor
@clerk/backend Minor
@clerk/agent-toolkit Patch
@clerk/astro Patch
@clerk/express Patch
@clerk/fastify Patch
@clerk/nuxt Patch
@clerk/react-router Patch
@clerk/remix Patch
@clerk/tanstack-react-start Patch
@clerk/testing Patch

Not sure what this means? Click here to learn what changesets are.

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

Copy link

vercel bot commented Jun 21, 2025

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

1 Skipped Deployment
Name Status Preview Comments Updated (UTC)
clerk-js-sandbox ⬜️ Skipped (Inspect) Jun 23, 2025 2:39pm

@wobsoriano wobsoriano marked this pull request as ready for review June 21, 2025 23:36
Copy link
Contributor

coderabbitai bot commented Jun 21, 2025

Caution

Review failed

The head commit changed during the review from 35c82ff to 429802b.

📝 Walkthrough

"""

Walkthrough

The changes introduce support for API key management and authentication in the integration and backend layers. New methods for creating, revoking, and retrieving API key secrets are added to the backend SDK. Integration tests for Next.js validate API key authentication using Clerk's middleware and route handlers. Test utilities are updated to create and manage fake API keys. Environment and app configuration files are modified to support scenarios involving API keys. The Next.js authentication and middleware logic is refactored to handle explicit token types, enabling support for API key tokens in addition to session tokens.

Assessment against linked issues

Objective Addressed Explanation
Add create, update, revoke, and getSecret methods to Backend SDK (clerkClient.apiKeys.create({...})) (USER-2233) The update method is missing; only create, revoke, and getSecret methods are added.
Integration tests with Nextjs with auth() and auth.protect() helpers (USER-2233)

Assessment against linked issues: Out-of-scope changes

Code Change Explanation
Addition of FakeAPIKey type and related test utility methods (integration/testUtils/usersService.ts, integration/testUtils/index.ts) These changes are supportive for testing but are not explicitly required by the linked objectives.
Addition of sample API key entry in .keys.json.sample (integration/.keys.json.sample) Modifying the sample key file is not specified in the objectives of the linked issue.
Refactoring of middleware auth handling logic (packages/nextjs/src/server/clerkMiddleware.ts) The refactor goes beyond enabling API key support and changes internal logic not explicitly required by the issue.

Suggested reviewers

  • aeliox
  • panteliselef
    """

🪧 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 21, 2025

Open in StackBlitz

@clerk/agent-toolkit

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

@clerk/astro

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

@clerk/backend

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

@clerk/chrome-extension

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

@clerk/clerk-js

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

@clerk/dev-cli

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

@clerk/elements

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

@clerk/clerk-expo

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

@clerk/expo-passkeys

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

@clerk/express

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

@clerk/fastify

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

@clerk/localizations

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

@clerk/nextjs

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

@clerk/nuxt

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

@clerk/clerk-react

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

@clerk/react-router

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

@clerk/remix

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

@clerk/shared

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

@clerk/tanstack-react-start

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

@clerk/testing

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

@clerk/themes

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

@clerk/types

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

@clerk/upgrade

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

@clerk/vue

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

commit: 429802b

@@ -465,7 +449,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 machine tokens when used inside middleware. The previous one continues processing the middleware chain instead of ending the request.

@wobsoriano wobsoriano changed the title chore(backend,nextjs): API keys integration tests chore(backend,nextjs): Introduce API keys methods and integration tests Jun 22, 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: 2

🧹 Nitpick comments (1)
.changeset/weak-adults-clean.md (1)

6-7: Inconsistent bullet formatting
Ensure all bullet items follow a consistent punctuation style (either all sentences ending with a period or none).

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 3f8b5a9 and a94adda.

📒 Files selected for processing (1)
  • .changeset/weak-adults-clean.md (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (5)
  • GitHub Check: Integration Tests (astro, chrome)
  • GitHub Check: Unit Tests (22, **)
  • GitHub Check: Static analysis
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: Analyze (javascript-typescript)

Comment on lines 6 to 7
- Introduce API keys Backend SDK methods
- Fix `auth.protect()` unauthorized error propagation within middleware
Copy link
Member

Choose a reason for hiding this comment

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

Can we split into 2 changesets ?

@@ -187,7 +187,8 @@ auth.protect = async (...args: any[]) => {
require('server-only');

const request = await buildRequestLike();
const authObject = await auth();
const requestedToken = args?.[0]?.token || args?.[1]?.token || TokenType.SessionToken;
Copy link
Member

Choose a reason for hiding this comment

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

I don't mind for the default, but I assume acceptToken is not required here, right ?

Copy link
Member Author

Choose a reason for hiding this comment

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

Correct.

  • acceptsToken for auth()
  • token for auth.protect()

@wobsoriano wobsoriano enabled auto-merge (squash) June 23, 2025 14:40
@wobsoriano wobsoriano merged commit 2692124 into main Jun 23, 2025
60 of 61 checks passed
@wobsoriano wobsoriano deleted the rob/api-keys-integration-tests branch June 23, 2025 14:59
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.

3 participants