Skip to content

chore(repo): Backport backend API keys methods update (#7400)#7427

Merged
wobsoriano merged 3 commits intomainfrom
rob/backport-7400
Dec 10, 2025
Merged

chore(repo): Backport backend API keys methods update (#7400)#7427
wobsoriano merged 3 commits intomainfrom
rob/backport-7400

Conversation

@wobsoriano
Copy link
Member

@wobsoriano wobsoriano commented Dec 10, 2025

Description

Backports changes from #7400 to main

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

    • Retrieve, update, delete, and revoke API keys; revocation now accepts an optional reason.
  • Tests

    • Comprehensive test coverage for API key management (list, create, get, update, delete, revoke, verify).
    • Test cleanup updated to pass revocation reasons where applicable.

✏️ Tip: You can customize this high-level summary in your review settings.

@changeset-bot
Copy link

changeset-bot bot commented Dec 10, 2025

🦋 Changeset detected

Latest commit: 4fc83f1

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

This PR includes changesets to release 0 packages

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

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

@vercel
Copy link

vercel bot commented Dec 10, 2025

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Preview Comments Updated (UTC)
clerk-js-sandbox Ready Ready Preview Comment Dec 10, 2025 6:05pm

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Dec 10, 2025

Walkthrough

Adds CRUD operations (get, update, delete) to the backend APIKeys API, changes the API key revoke payload and FakeAPIKey.revoke signature to accept an optional reason, updates tests and test utilities accordingly, and adds a small changeset file.

Changes

Cohort / File(s) Summary
Test Utilities
integration/testUtils/usersService.ts
Changed FakeAPIKey.revoke signature from () => Promise<APIKey> to `(reason?: string
Integration Tests
integration/tests/machine-auth/api-keys.test.ts
Updated cleanup to call fakeAPIKey.revoke('Testing purposes within clerkMiddleware()') (passes a string reason).
Backend API Tests
packages/backend/src/api/__tests__/APIKeysApi.test.ts
Added/expanded tests covering API keys: list, create (full/minimal), get, update, delete, revoke (with and without reason), and verify; asserts headers, request bodies, and response shapes using MSW mocks.
Backend API Implementation
packages/backend/src/api/endpoints/APIKeysApi.ts
Added UpdateAPIKeyParams type; added get(apiKeyId: string), update(params: UpdateAPIKeyParams), and delete(apiKeyId: string) methods; modified revoke to send body { revocationReason } (payload construction changed).
Changeset
.changeset/kind-humans-retire.md
Added a placeholder changeset file containing YAML delimiters (---).

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

  • Inspect APIKeysApi.test.ts assertions and MSW handlers for correctness and coverage.
  • Review new endpoint implementations in APIKeysApi.ts for validation, request/response shapes, and consistency with existing API patterns.
  • Confirm FakeAPIKey.revoke signature change is correctly propagated to all call sites and tests.
  • Verify revoke payload change (only revocationReason) matches backend expectations.

Poem

🐰 I nibble code and tidy keys with cheer,
I let them go—"the reason" whispered near;
GET, UPDATE, DELETE — I hop and say,
Tests keep watch while secrets hop away.
A tiny changelog hop to mark the day. 🥕✨

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main change: backporting backend API keys methods updates. It is concise, clear, and directly reflects the primary purpose of the pull request.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch rob/backport-7400

📜 Recent review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 5892d28 and 4fc83f1.

📒 Files selected for processing (1)
  • .changeset/kind-humans-retire.md (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • .changeset/kind-humans-retire.md
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (21)
  • GitHub Check: Publish with pkg-pr-new
  • GitHub Check: Unit Tests (**)
  • GitHub Check: Static analysis
  • GitHub Check: Integration Tests (quickstart, chrome, 16)
  • GitHub Check: Integration Tests (handshake:staging, chrome)
  • GitHub Check: Integration Tests (quickstart, chrome, 15)
  • GitHub Check: Integration Tests (nextjs, chrome, 16, RQ)
  • GitHub Check: Integration Tests (machine, chrome, RQ)
  • GitHub Check: Integration Tests (billing, chrome, RQ)
  • GitHub Check: Integration Tests (custom, chrome)
  • GitHub Check: Integration Tests (nextjs, chrome, 16)
  • GitHub Check: Integration Tests (ap-flows, chrome)
  • GitHub Check: Integration Tests (astro, chrome)
  • GitHub Check: Integration Tests (localhost, chrome)
  • GitHub Check: Integration Tests (react-router, chrome)
  • GitHub Check: Integration Tests (billing, chrome)
  • GitHub Check: Integration Tests (nuxt, chrome)
  • GitHub Check: Integration Tests (machine, chrome)
  • GitHub Check: Integration Tests (generic, chrome)
  • GitHub Check: Integration Tests (sessions:staging, chrome)
  • GitHub Check: Integration Tests (sessions, chrome)

Comment @coderabbitai help to get the list of available commands and usage tips.

@pkg-pr-new
Copy link

pkg-pr-new bot commented Dec 10, 2025

Open in StackBlitz

@clerk/agent-toolkit

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

@clerk/astro

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

@clerk/backend

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

@clerk/chrome-extension

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

@clerk/clerk-js

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

@clerk/dev-cli

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

@clerk/expo

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

@clerk/expo-passkeys

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

@clerk/express

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

@clerk/fastify

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

@clerk/localizations

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

@clerk/nextjs

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

@clerk/nuxt

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

@clerk/react

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

@clerk/react-router

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

@clerk/shared

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

@clerk/tanstack-react-start

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

@clerk/testing

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

@clerk/ui

npm i https://pkg.pr.new/@clerk/ui@7427

@clerk/upgrade

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

@clerk/vue

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

commit: 4fc83f1

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 (2)
packages/backend/src/api/__tests__/APIKeysApi.test.ts (1)

202-210: Consider validating request body in update test.

Unlike the create test (lines 82-93) which validates the request body parameters, this mock only checks the Authorization header. Consider asserting on the body to ensure parameters like description, scopes, claims, and secondsUntilExpiration are correctly transformed and sent to the API.

       server.use(
         http.patch(
           `https://api.clerk.test/api_keys/${apiKeyId}`,
-          validateHeaders(({ request }) => {
+          validateHeaders(async ({ request }) => {
             expect(request.headers.get('Authorization')).toBe('Bearer sk_xxxxx');
+            const body = (await request.json()) as Record<string, unknown>;
+            expect(body.description).toBe('Updated description');
+            expect(body.scopes).toEqual(['scope1', 'scope2', 'scope3']);
+            expect(body.claims).toEqual(updatedClaims);
+            expect(body.seconds_until_expiration).toBe(3600);
             return HttpResponse.json(updatedMockAPIKey);
           }),
         ),
       );
integration/testUtils/usersService.ts (1)

235-237: Missing withErrorLogging wrapper for consistency.

The revoke call doesn't use withErrorLogging, unlike other API operations in this file (e.g., createBapiUser at line 142, deleteIfExists at line 179, createFakeOrganization at line 208). This inconsistency means revocation failures won't include detailed error logging (status, message, errors, clerkTraceId), potentially making integration test failures harder to debug.

-        revoke: (reason?: string | null) =>
-          clerkClient.apiKeys.revoke({ apiKeyId: apiKey.id, revocationReason: reason }),
+        revoke: (reason?: string | null) =>
+          withErrorLogging('revokeAPIKey', () =>
+            clerkClient.apiKeys.revoke({ apiKeyId: apiKey.id, revocationReason: reason }),
+          ),
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between f81aaa8 and 5892d28.

📒 Files selected for processing (4)
  • integration/testUtils/usersService.ts (2 hunks)
  • integration/tests/machine-auth/api-keys.test.ts (1 hunks)
  • packages/backend/src/api/__tests__/APIKeysApi.test.ts (1 hunks)
  • packages/backend/src/api/endpoints/APIKeysApi.ts (3 hunks)
🧰 Additional context used
📓 Path-based instructions (12)
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

All code must pass ESLint checks with the project's configuration

Files:

  • integration/tests/machine-auth/api-keys.test.ts
  • packages/backend/src/api/__tests__/APIKeysApi.test.ts
  • integration/testUtils/usersService.ts
  • packages/backend/src/api/endpoints/APIKeysApi.ts
**/*.{js,jsx,ts,tsx,json,md,yml,yaml}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Use Prettier for consistent code formatting

Files:

  • integration/tests/machine-auth/api-keys.test.ts
  • packages/backend/src/api/__tests__/APIKeysApi.test.ts
  • integration/testUtils/usersService.ts
  • packages/backend/src/api/endpoints/APIKeysApi.ts
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Follow established naming conventions (PascalCase for components, camelCase for variables)

Files:

  • integration/tests/machine-auth/api-keys.test.ts
  • packages/backend/src/api/__tests__/APIKeysApi.test.ts
  • integration/testUtils/usersService.ts
  • packages/backend/src/api/endpoints/APIKeysApi.ts
**/*.{test,spec}.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

**/*.{test,spec}.{ts,tsx,js,jsx}: Unit tests are required for all new functionality
Verify proper error handling and edge cases
Include tests for all new features

Files:

  • integration/tests/machine-auth/api-keys.test.ts
  • packages/backend/src/api/__tests__/APIKeysApi.test.ts
**/*.ts?(x)

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Use proper TypeScript error types

Files:

  • integration/tests/machine-auth/api-keys.test.ts
  • packages/backend/src/api/__tests__/APIKeysApi.test.ts
  • integration/testUtils/usersService.ts
  • packages/backend/src/api/endpoints/APIKeysApi.ts
**/*.{test,spec,e2e}.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Use real Clerk instances for integration tests

Files:

  • integration/tests/machine-auth/api-keys.test.ts
  • packages/backend/src/api/__tests__/APIKeysApi.test.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/typescript.mdc)

**/*.{ts,tsx}: Always define explicit return types for functions, especially public APIs
Use proper type annotations for variables and parameters where inference isn't clear
Avoid any type - prefer unknown when type is uncertain, then narrow with type guards
Implement type guards for unknown types using the pattern function isType(value: unknown): value is Type
Use interface for object shapes that might be extended
Use type for unions, primitives, and computed types
Prefer readonly properties for immutable data structures
Use private for internal implementation details in classes
Use protected for inheritance hierarchies
Use public explicitly for clarity in public APIs
Use mixins for shared behavior across unrelated classes in TypeScript
Use generic constraints with bounded type parameters like <T extends { id: string }>
Use utility types like Omit, Partial, and Pick for data transformation instead of manual type construction
Use discriminated unions instead of boolean flags for state management and API responses
Use mapped types for transforming object types
Use conditional types for type-level logic
Leverage template literal types for string manipulation at the type level
Use ES6 imports/exports consistently
Use default exports sparingly, prefer named exports
Document functions with JSDoc comments including @param, @returns, @throws, and @example tags
Create custom error classes that extend Error for specific error types
Use the Result pattern for error handling instead of throwing exceptions
Use optional chaining (?.) and nullish coalescing (??) operators for safe property access
Let TypeScript infer obvious types to reduce verbosity
Use const assertions with as const for literal types
Use satisfies operator for type checking without widening types
Declare readonly arrays and objects for immutable data structures
Use spread operator and array spread for immutable updates instead of mutations
Use lazy loading for large types...

Files:

  • integration/tests/machine-auth/api-keys.test.ts
  • packages/backend/src/api/__tests__/APIKeysApi.test.ts
  • integration/testUtils/usersService.ts
  • packages/backend/src/api/endpoints/APIKeysApi.ts
**/*.test.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)

Use React Testing Library for component testing

Files:

  • integration/tests/machine-auth/api-keys.test.ts
  • packages/backend/src/api/__tests__/APIKeysApi.test.ts
**/*.{js,ts,jsx,tsx}

📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)

Use ESLint with custom configurations tailored for different package types

Files:

  • integration/tests/machine-auth/api-keys.test.ts
  • packages/backend/src/api/__tests__/APIKeysApi.test.ts
  • integration/testUtils/usersService.ts
  • packages/backend/src/api/endpoints/APIKeysApi.ts
**/*.{js,ts,jsx,tsx,json,md,yml,yaml}

📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)

Use Prettier for code formatting across all packages

Files:

  • integration/tests/machine-auth/api-keys.test.ts
  • packages/backend/src/api/__tests__/APIKeysApi.test.ts
  • integration/testUtils/usersService.ts
  • packages/backend/src/api/endpoints/APIKeysApi.ts
packages/**/src/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

TypeScript is required for all packages

Files:

  • packages/backend/src/api/__tests__/APIKeysApi.test.ts
  • packages/backend/src/api/endpoints/APIKeysApi.ts
packages/**/src/**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

packages/**/src/**/*.{ts,tsx,js,jsx}: Maintain comprehensive JSDoc comments for public APIs
Use tree-shaking friendly exports
Validate all inputs and sanitize outputs
All public APIs must be documented with JSDoc
Use dynamic imports for optional features
Provide meaningful error messages to developers
Include error recovery suggestions where applicable
Log errors appropriately for debugging
Lazy load components and features when possible
Implement proper caching strategies
Use efficient data structures and algorithms
Implement proper logging with different levels

Files:

  • packages/backend/src/api/__tests__/APIKeysApi.test.ts
  • packages/backend/src/api/endpoints/APIKeysApi.ts
🧬 Code graph analysis (3)
packages/backend/src/api/__tests__/APIKeysApi.test.ts (2)
packages/backend/src/api/factory.ts (1)
  • createBackendApiClient (39-96)
packages/backend/src/mock-server.ts (2)
  • server (6-6)
  • validateHeaders (9-47)
integration/testUtils/usersService.ts (1)
packages/clerk-js/src/core/resources/APIKey.ts (1)
  • APIKey (6-75)
packages/backend/src/api/endpoints/APIKeysApi.ts (3)
packages/backend/src/index.ts (1)
  • APIKey (113-113)
packages/backend/src/api/resources/APIKey.ts (1)
  • APIKey (3-43)
packages/shared/src/types/clerk.ts (1)
  • RevokeAPIKeyParams (1984-1987)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (26)
  • GitHub Check: Integration Tests (ap-flows, chrome)
  • GitHub Check: Integration Tests (machine, chrome)
  • GitHub Check: Integration Tests (nextjs, chrome, 16, RQ)
  • GitHub Check: Integration Tests (nextjs, chrome, 15)
  • GitHub Check: Integration Tests (nextjs, chrome, 16)
  • GitHub Check: Integration Tests (react-router, chrome)
  • GitHub Check: Integration Tests (handshake:staging, chrome)
  • GitHub Check: Integration Tests (handshake, chrome)
  • GitHub Check: Integration Tests (billing, chrome, RQ)
  • GitHub Check: Integration Tests (astro, chrome)
  • GitHub Check: Integration Tests (quickstart, chrome, 16)
  • GitHub Check: Integration Tests (quickstart, chrome, 15)
  • GitHub Check: Integration Tests (localhost, chrome)
  • GitHub Check: Integration Tests (machine, chrome, RQ)
  • GitHub Check: Integration Tests (nuxt, chrome)
  • GitHub Check: Integration Tests (custom, chrome)
  • GitHub Check: Integration Tests (express, chrome)
  • GitHub Check: Integration Tests (generic, chrome)
  • GitHub Check: Integration Tests (vue, chrome)
  • GitHub Check: Integration Tests (billing, chrome)
  • GitHub Check: Integration Tests (tanstack-react-start, chrome)
  • GitHub Check: Integration Tests (sessions, chrome)
  • GitHub Check: Integration Tests (sessions:staging, chrome)
  • GitHub Check: Build Packages
  • GitHub Check: Formatting | Dedupe | Changeset
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (6)
integration/tests/machine-auth/api-keys.test.ts (1)

67-71: LGTM! Revocation reason now provided for cleanup.

The change correctly passes a descriptive reason to the revoke method, aligning with the updated FakeAPIKey.revoke(reason?: string | null) signature.

Note: The second test suite at line 152 calls fakeAPIKey.revoke() without a reason. Both usages are valid since the parameter is optional, but you may want to consider consistency across test suites for better traceability of revoked keys.

packages/backend/src/api/__tests__/APIKeysApi.test.ts (1)

1-29: Well-structured test suite with comprehensive coverage.

The test file provides thorough coverage for all API key operations (list, create, get, update, delete, revoke, verify) with proper MSW mocking, header validation, and error case handling for missing IDs. The mock data structure aligns well with the API response format.

integration/testUtils/usersService.ts (1)

75-79: Type signature correctly updated.

The FakeAPIKey type now properly reflects the optional reason parameter with string | null union, matching the revocationReason field in RevokeAPIKeyParams.

packages/backend/src/api/endpoints/APIKeysApi.ts (3)

90-118: New CRUD methods implemented correctly.

The get, update, and delete methods follow the established patterns in the codebase:

  • Proper ID validation via requireId()
  • Correct HTTP methods (GET, PATCH, DELETE)
  • Appropriate return types (APIKey and DeletedObject)
  • Consistent path construction using joinPaths

120-130: Revoke method correctly simplified to send only revocationReason.

The method now properly defaults revocationReason to null (line 121) and sends only this field in the request body, which aligns with the test expectations and provides a cleaner API contract.


55-71: Verify if subject is required for update operations.

The subject field is marked as required in UpdateAPIKeyParams, but update operations typically only need the resource ID. While the implementation does send subject to the backend API in the request body, the tests don't validate that it's actually required by the API—the mock only validates response fields.

Confirm with the backend API documentation whether subject is required for the update endpoint. If it's optional on the backend, make it optional in the type:

 type UpdateAPIKeyParams = {
   /**
    * API key ID
    */
   apiKeyId: string;
   /**
-   * The user or Organization ID to associate the API key with
+   * The user or Organization ID (optional, for authorization)
    */
-  subject: string;
+  subject?: string;
   /**
    * API key description
    */

@wobsoriano wobsoriano enabled auto-merge (squash) December 10, 2025 19:01
@wobsoriano wobsoriano merged commit 8328348 into main Dec 10, 2025
99 of 102 checks passed
@wobsoriano wobsoriano deleted the rob/backport-7400 branch December 10, 2025 19:09
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