-
Notifications
You must be signed in to change notification settings - Fork 411
feat(backend): Error if azp is missing on a cookie-based token #7332
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 GitHub.
|
WalkthroughThe changes add validation for the Changes
Estimated code review effort🎯 2 (Simple) | ⏱️ ~12 minutes
Poem
Pre-merge checks and finishing touches❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
Comment |
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)
packages/backend/src/tokens/__tests__/request_azp.test.ts (1)
29-30: Improve type safety in tests.The tests use
@ts-ignore(lines 54, 56) andas any(lines 30, 36, 73, 79, 111, 117) to bypass TypeScript's type checking, which violates the coding guidelines requiring proper type annotations and avoidinganytypes.For the
@ts-ignoreusage: Use type narrowing instead:const result = await authenticateRequest(request, options); expect(result.status).toBe('signed-out'); -// @ts-ignore -expect(result.reason).toBe(TokenVerificationErrorReason.TokenMissingAzp); -// @ts-ignore -expect(result.message).toBe( - 'Session tokens from cookies must have an azp claim. (reason=token-missing-azp, token-carrier=cookie)', -); +if (result.status === 'signed-out') { + expect(result.reason).toBe(TokenVerificationErrorReason.TokenMissingAzp); + expect(result.message).toBe( + 'Session tokens from cookies must have an azp claim. (reason=token-missing-azp, token-carrier=cookie)', + ); +}For the
as anycasts: Consider creating a properly typed mock payload or usingsatisfiesoperator:const payload = { sub: 'user_123', sid: 'sess_123', iat: 1234567891, exp: 1234567991, azp: 'http://localhost:3000', -}; +} satisfies Partial<JwtPayload>; vi.mocked(verifyToken).mockResolvedValue({ - data: payload as any, + data: payload, errors: undefined, });As per coding guidelines: "Avoid
anytype - preferunknownwhen type is uncertain" and "Usesatisfiesoperator for type checking without widening types."Also applies to: 35-36, 54-55, 72-73, 78-79, 110-111, 116-117
📜 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 (3)
packages/backend/src/errors.ts(1 hunks)packages/backend/src/tokens/__tests__/request_azp.test.ts(1 hunks)packages/backend/src/tokens/request.ts(1 hunks)
🧰 Additional context used
📓 Path-based instructions (9)
**/*.{js,jsx,ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
All code must pass ESLint checks with the project's configuration
Files:
packages/backend/src/tokens/request.tspackages/backend/src/errors.tspackages/backend/src/tokens/__tests__/request_azp.test.ts
**/*.{js,jsx,ts,tsx,json,md,yml,yaml}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
Use Prettier for consistent code formatting
Files:
packages/backend/src/tokens/request.tspackages/backend/src/errors.tspackages/backend/src/tokens/__tests__/request_azp.test.ts
packages/**/src/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
TypeScript is required for all packages
Files:
packages/backend/src/tokens/request.tspackages/backend/src/errors.tspackages/backend/src/tokens/__tests__/request_azp.test.ts
**/*.{ts,tsx,js,jsx}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
Follow established naming conventions (PascalCase for components, camelCase for variables)
Prefer importing types from
@clerk/shared/typesinstead of the deprecated@clerk/typesalias
Files:
packages/backend/src/tokens/request.tspackages/backend/src/errors.tspackages/backend/src/tokens/__tests__/request_azp.test.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/tokens/request.tspackages/backend/src/errors.tspackages/backend/src/tokens/__tests__/request_azp.test.ts
**/*.ts?(x)
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
Use proper TypeScript error types
Files:
packages/backend/src/tokens/request.tspackages/backend/src/errors.tspackages/backend/src/tokens/__tests__/request_azp.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:
packages/backend/src/tokens/request.tspackages/backend/src/errors.tspackages/backend/src/tokens/__tests__/request_azp.test.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:
packages/backend/src/tokens/__tests__/request_azp.test.ts
**/*.{test,spec,e2e}.{ts,tsx,js,jsx}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
Use real Clerk instances for integration tests
Files:
packages/backend/src/tokens/__tests__/request_azp.test.ts
🧬 Code graph analysis (2)
packages/backend/src/tokens/request.ts (1)
packages/backend/src/errors.ts (3)
TokenVerificationError(42-70)TokenVerificationErrorReason(9-26)TokenVerificationErrorReason(28-29)
packages/backend/src/tokens/__tests__/request_azp.test.ts (3)
packages/backend/src/jwt/verifyJwt.ts (1)
decodeJwt(45-95)packages/backend/src/tokens/request.ts (1)
authenticateRequest(147-815)packages/backend/src/errors.ts (2)
TokenVerificationErrorReason(9-26)TokenVerificationErrorReason(28-29)
⏰ 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). (5)
- GitHub Check: Build Packages
- GitHub Check: Formatting | Dedupe | Changeset
- GitHub Check: semgrep-cloud-platform/scan
- GitHub Check: semgrep-cloud-platform/scan
- GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (4)
packages/backend/src/errors.ts (1)
14-14: LGTM!The new
TokenMissingAzperror reason follows the established pattern and naming conventions. The placement within the error reasons list is appropriate.packages/backend/src/tokens/request.ts (1)
568-573: LGTM! Cookie-based azp enforcement implemented correctly.The validation correctly enforces the presence of the
azpclaim only for cookie-based tokens, aligning with the PR objectives. The error will be caught by the try-catch block and handled appropriately byhandleSessionTokenError, which will return a signed-out state sinceTokenMissingAzpis not in the list of reasons that trigger a handshake.The falsy check (
!data.azp) is appropriate for this use case, as it treats empty strings, null, and undefined as invalid, which is correct for an authorized party claim that should contain a valid origin.packages/backend/src/tokens/__tests__/request_azp.test.ts (2)
18-97: Test coverage looks comprehensive.The test suite properly covers both the failure case (missing azp in cookie token) and success case (present azp in cookie token), with appropriate mocking of the verification flow.
99-135: Good coverage of header-based authentication flow.This test correctly verifies that header-based tokens do not require the
azpclaim, confirming the asymmetric enforcement intended by the PR objectives (cookie tokens require azp, header tokens do not).
@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: |
|
This would be a breaking change |
Description
If a session token is sent via cookie, this usually means it's being sent through the browser. When an app is browser-based, it's expected that requests are sent with an Origin header and session JWTs are built with an
azpclaim. For native apps, this isn't the case, as they don't have urls or enforce an origin header. Because of this, we don't enforceazpclaims on session tokens.This PR makes a small change, such that if session tokens are sent via cookie and are missing an
azpclaim, which generally is suspicious, as there's no natural scenario where this would make a lot of sense, we error instead of accepting it.Checklist
pnpm testruns as expected.pnpm buildruns as expected.Type of change
Summary by CodeRabbit
✏️ Tip: You can customize this high-level summary in your review settings.