chore(repo): Backport backend API keys methods update (#7400)#7427
chore(repo): Backport backend API keys methods update (#7400)#7427wobsoriano merged 3 commits intomainfrom
Conversation
🦋 Changeset detectedLatest commit: 4fc83f1 The changes in this PR will be included in the next version bump. This PR includes changesets to release 0 packagesWhen 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 |
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
WalkthroughAdds 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
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes
Poem
Pre-merge checks and finishing touches✅ Passed checks (3 passed)
✨ Finishing touches🧪 Generate unit tests (beta)
📜 Recent review detailsConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Disabled knowledge base sources:
📒 Files selected for processing (1)
✅ Files skipped from review due to trivial changes (1)
⏰ 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)
Comment |
@clerk/agent-toolkit
@clerk/astro
@clerk/backend
@clerk/chrome-extension
@clerk/clerk-js
@clerk/dev-cli
@clerk/expo
@clerk/expo-passkeys
@clerk/express
@clerk/fastify
@clerk/localizations
@clerk/nextjs
@clerk/nuxt
@clerk/react
@clerk/react-router
@clerk/shared
@clerk/tanstack-react-start
@clerk/testing
@clerk/ui
@clerk/upgrade
@clerk/vue
commit: |
There was a problem hiding this comment.
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
createtest (lines 82-93) which validates the request body parameters, this mock only checks the Authorization header. Consider asserting on the body to ensure parameters likedescription,scopes,claims, andsecondsUntilExpirationare 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: MissingwithErrorLoggingwrapper for consistency.The
revokecall doesn't usewithErrorLogging, unlike other API operations in this file (e.g.,createBapiUserat line 142,deleteIfExistsat line 179,createFakeOrganizationat 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.
📒 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.tspackages/backend/src/api/__tests__/APIKeysApi.test.tsintegration/testUtils/usersService.tspackages/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.tspackages/backend/src/api/__tests__/APIKeysApi.test.tsintegration/testUtils/usersService.tspackages/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.tspackages/backend/src/api/__tests__/APIKeysApi.test.tsintegration/testUtils/usersService.tspackages/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.tspackages/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.tspackages/backend/src/api/__tests__/APIKeysApi.test.tsintegration/testUtils/usersService.tspackages/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.tspackages/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
Avoidanytype - preferunknownwhen type is uncertain, then narrow with type guards
Implement type guards forunknowntypes using the patternfunction isType(value: unknown): value is Type
Useinterfacefor object shapes that might be extended
Usetypefor unions, primitives, and computed types
Preferreadonlyproperties for immutable data structures
Useprivatefor internal implementation details in classes
Useprotectedfor inheritance hierarchies
Usepublicexplicitly 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 likeOmit,Partial, andPickfor 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
Useconst assertionswithas constfor literal types
Usesatisfiesoperator 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.tspackages/backend/src/api/__tests__/APIKeysApi.test.tsintegration/testUtils/usersService.tspackages/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.tspackages/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.tspackages/backend/src/api/__tests__/APIKeysApi.test.tsintegration/testUtils/usersService.tspackages/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.tspackages/backend/src/api/__tests__/APIKeysApi.test.tsintegration/testUtils/usersService.tspackages/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.tspackages/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.tspackages/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
FakeAPIKeytype now properly reflects the optionalreasonparameter withstring | nullunion, matching therevocationReasonfield inRevokeAPIKeyParams.packages/backend/src/api/endpoints/APIKeysApi.ts (3)
90-118: New CRUD methods implemented correctly.The
get,update, anddeletemethods follow the established patterns in the codebase:
- Proper ID validation via
requireId()- Correct HTTP methods (GET, PATCH, DELETE)
- Appropriate return types (
APIKeyandDeletedObject)- Consistent path construction using
joinPaths
120-130: Revoke method correctly simplified to send onlyrevocationReason.The method now properly defaults
revocationReasontonull(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 ifsubjectis required for update operations.The
subjectfield is marked as required inUpdateAPIKeyParams, but update operations typically only need the resource ID. While the implementation does sendsubjectto 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
subjectis 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 */
Description
Backports changes from #7400 to main
Checklist
pnpm testruns as expected.pnpm buildruns as expected.Type of change
Summary by CodeRabbit
New Features
Tests
✏️ Tip: You can customize this high-level summary in your review settings.