Skip to content

Conversation

@jescalan
Copy link
Contributor

@jescalan jescalan commented Nov 29, 2025

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 azp claim. 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 enforce azp claims on session tokens.

This PR makes a small change, such that if session tokens are sent via cookie and are missing an azp claim, 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 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

  • Bug Fixes
    • Strengthened token validation by enforcing required security claim verification. Session tokens missing critical claims are now properly rejected, improving authentication security and reliability.

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

@changeset-bot
Copy link

changeset-bot bot commented Nov 29, 2025

⚠️ No Changeset found

Latest commit: ffdf235

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

@vercel
Copy link

vercel bot commented Nov 29, 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 3, 2025 6:12pm

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Nov 29, 2025

Walkthrough

The changes add validation for the azp (authorized party) claim in JWT tokens. A new error reason TokenMissingAzp is introduced in the errors module, along with corresponding tests for cookie-based authentication flows. Production code now enforces the presence of azp in session tokens received via cookies.

Changes

Cohort / File(s) Summary
Error Definition
packages/backend/src/errors.ts
Added new token verification error reason TokenMissingAzp with value 'token-missing-azp' to expand the set of defined verification failure reasons.
Token Validation
packages/backend/src/tokens/request.ts
Introduced enforcement check for azp claim presence in session tokens from cookies; throws TokenVerificationError with TokenMissingAzp reason if the claim is missing.
Tests
packages/backend/src/tokens/__tests__/request_azp.test.ts
Added new test suite for authenticateRequest covering cookie-based token flows with azp present and absent, and header-based authentication with missing azp.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

  • Error constant addition is straightforward and follows existing patterns
  • Test file introduces multiple test cases but follows conventional mocking patterns already established in the codebase
  • Production logic change is a single validation check integrated into existing error handling flow

Poem

🐰 The azp must present be,
In tokens flowing wild and free,
A guardian check, so swift and keen,
Now validates what's never seen!
No missing party shall slip through,
Our JWT vault is safe and true! 🔐

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'Error if azp is missing on a cookie-based token' directly and clearly describes the main change: enforcing azp claim presence for cookie-based tokens and throwing an error when it's absent.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch je.error-on-missing-azp-in-cookie

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

@jescalan jescalan changed the title Error if azp is missing on a cookie-based token feat(backend): Error if azp is missing on a cookie-based token Nov 29, 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 (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) and as any (lines 30, 36, 73, 79, 111, 117) to bypass TypeScript's type checking, which violates the coding guidelines requiring proper type annotations and avoiding any types.

For the @ts-ignore usage: 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 any casts: Consider creating a properly typed mock payload or using satisfies operator:

 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 any type - prefer unknown when type is uncertain" and "Use satisfies operator 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.

📥 Commits

Reviewing files that changed from the base of the PR and between d4aef71 and e8716ed.

📒 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.ts
  • packages/backend/src/errors.ts
  • packages/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.ts
  • packages/backend/src/errors.ts
  • packages/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.ts
  • packages/backend/src/errors.ts
  • packages/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/types instead of the deprecated @clerk/types alias

Files:

  • packages/backend/src/tokens/request.ts
  • packages/backend/src/errors.ts
  • packages/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.ts
  • packages/backend/src/errors.ts
  • packages/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.ts
  • packages/backend/src/errors.ts
  • packages/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
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:

  • packages/backend/src/tokens/request.ts
  • packages/backend/src/errors.ts
  • packages/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 TokenMissingAzp error 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 azp claim only for cookie-based tokens, aligning with the PR objectives. The error will be caught by the try-catch block and handled appropriately by handleSessionTokenError, which will return a signed-out state since TokenMissingAzp is 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 azp claim, confirming the asymmetric enforcement intended by the PR objectives (cookie tokens require azp, header tokens do not).

@pkg-pr-new
Copy link

pkg-pr-new bot commented Nov 29, 2025

Open in StackBlitz

@clerk/agent-toolkit

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

@clerk/astro

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

@clerk/backend

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

@clerk/chrome-extension

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

@clerk/clerk-js

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

@clerk/dev-cli

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

@clerk/elements

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

@clerk/clerk-expo

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

@clerk/expo-passkeys

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

@clerk/express

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

@clerk/fastify

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

@clerk/localizations

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

@clerk/nextjs

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

@clerk/nuxt

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

@clerk/clerk-react

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

@clerk/react-router

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

@clerk/remix

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

@clerk/shared

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

@clerk/tanstack-react-start

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

@clerk/testing

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

@clerk/themes

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

@clerk/types

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

@clerk/upgrade

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

@clerk/vue

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

commit: ffdf235

@brkalow
Copy link
Member

brkalow commented Dec 3, 2025

This would be a breaking change

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

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants