Skip to content

Conversation

@Ayush2k02
Copy link

@Ayush2k02 Ayush2k02 commented Dec 26, 2025

Summary

Fixes token-type-mismatch error when using multiple acceptsToken values in authenticateRequest.

Problem

When acceptsToken is an array containing both session and machine token types (e.g., ['session_token', 'api_key']), the function would always route to the machine token authentication handler, causing session tokens to fail with token-type-mismatch errors.

Root Cause

In request.ts:784-792, the routing logic checked:

if (authenticateContext.tokenInHeader) {
  if (acceptsToken === 'any') {
    return authenticateAnyRequestWithTokenInHeader();
  }
  if (acceptsToken === TokenType.SessionToken) {  // ❌ FALSE when acceptsToken is an array
    return authenticateRequestWithTokenInHeader();
  }
  return authenticateMachineRequestWithTokenInHeader();  // ❌ Always executed for arrays
}

When acceptsToken is ['session_token', 'api_key'], the condition acceptsToken === TokenType.SessionToken evaluates to false (array !== string), causing all tokens to be routed to authenticateMachineRequestWithTokenInHeader().

Solution

Added routing logic that checks the actual token type when acceptsToken is an array:

// When acceptsToken is an array, route based on the actual token type
if (Array.isArray(acceptsToken)) {
  if (isMachineToken(authenticateContext.tokenInHeader)) {
    return authenticateMachineRequestWithTokenInHeader();
  }
  return authenticateRequestWithTokenInHeader();
}

Now:

  • If the token is a machine token (api_key, m2m_token, oauth_token) → routes to machine handler
  • Otherwise → routes to session token handler

Changes

  • Modified authenticateRequest in packages/backend/src/tokens/request.ts to handle array routing correctly
  • Added test for session_token in array with machine tokens
  • Added test for api_key in array with session_token
  • Added changeset for patch release

Testing

Added two new test cases:

  1. session_token is accepted when in array with api_key
  2. api_key is accepted when in array with session_token

Both scenarios now work correctly without token-type-mismatch errors.

Backward Compatibility

This change is fully backward compatible:

  • Single token type strings work as before
  • 'any' works as before
  • Arrays with only machine tokens work as before
  • Arrays with only session tokens work as before
  • NEW: Mixed arrays now work correctly

Fixes #7520

Summary by CodeRabbit

Bug Fixes

  • Fixed authentication routing to properly handle multiple accepted token types (e.g., session tokens and API keys), ensuring the appropriate authentication handler is correctly selected based on the actual token type in use.

Tests

  • Added test coverage for multi-token authentication scenarios, verifying proper token type handling and routing behavior in various combinations.

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

Fixes token-type-mismatch error when using arrays in acceptsToken option.
Previously, when acceptsToken was an array like ['session_token', 'api_key'],
the code would always route to the machine token handler, causing session
tokens to fail with token-type-mismatch errors.

Now, when acceptsToken is an array, the function checks the actual token
type and routes to the appropriate handler (session or machine).

- Added routing logic for array acceptsToken values
- Added tests for mixed token type arrays
- Preserves backward compatibility with existing usage

Fixes clerk#7520
@changeset-bot
Copy link

changeset-bot bot commented Dec 26, 2025

🦋 Changeset detected

Latest commit: a90fad5

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

This PR includes changesets to release 10 packages
Name Type
@clerk/backend Patch
@clerk/agent-toolkit Patch
@clerk/astro Patch
@clerk/express Patch
@clerk/fastify Patch
@clerk/nextjs Patch
@clerk/nuxt Patch
@clerk/react-router 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

@vercel
Copy link

vercel bot commented Dec 26, 2025

@Ayush2k02 is attempting to deploy a commit to the Clerk Production Team on Vercel.

A member of the Team first needs to authorize it.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Dec 26, 2025

📝 Walkthrough

Walkthrough

This pull request fixes authentication request routing when acceptsToken is configured as an array containing multiple token types. Previously, requests would fail with a token-type-mismatch error when using a valid token type that wasn't processed first. The fix introduces routing logic to inspect the actual token type in the request header and delegate to the appropriate authentication handler (machine token or session token verifier) based on what was actually sent, while preserving existing behavior for non-array acceptsToken configurations. Two test cases validate the fix for session and API key token scenarios.

Pre-merge checks

✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately and concisely describes the main change: handling multiple token types in the acceptsToken array parameter, which is the core fix addressed by the PR.
Linked Issues check ✅ Passed The code changes successfully address issue #7520: they implement routing logic to distinguish between session and machine tokens when acceptsToken is an array, include tests validating both token types are now accepted, and resolve the token-type-mismatch error previously occurring with session tokens in mixed arrays.
Out of Scope Changes check ✅ Passed All changes remain focused on the stated objective: fixing token routing in the authenticateRequest function, adding corresponding tests, and creating a changeset. No unrelated modifications are present.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

📜 Recent review details

Configuration used: Repository YAML (base), Organization UI (inherited)

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 063ab4d and a90fad5.

📒 Files selected for processing (3)
  • .changeset/fix-multiple-token-types-array.md
  • packages/backend/src/tokens/__tests__/request.test.ts
  • packages/backend/src/tokens/request.ts
🧰 Additional context used
📓 Path-based instructions (13)
**/*.{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/tokens/__tests__/request.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/tokens/__tests__/request.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/tokens/__tests__/request.test.ts
**/*.{ts,tsx,js,jsx}

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

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

Files:

  • packages/backend/src/tokens/request.ts
  • packages/backend/src/tokens/__tests__/request.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/tokens/__tests__/request.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/tokens/__tests__/request.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/tokens/__tests__/request.test.ts
**/*.{js,ts,jsx,tsx}

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

Use ESLint with custom configurations tailored for different package types

Files:

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

  • packages/backend/src/tokens/request.ts
  • packages/backend/src/tokens/__tests__/request.test.ts
**/*

⚙️ CodeRabbit configuration file

If there are no tests added or modified as part of the PR, please suggest that tests be added to cover the changes.

**/*: Only comment on issues that would block merging, ignore minor or stylistic concerns.
Restrict feedback to errors, security risks, or functionality-breaking problems.
Do not post comments on code style, formatting, or non-critical improvements.
Keep reviews short: flag only issues that make the PR unsafe to merge.
Group similar issues into a single comment instead of posting multiple notes.
Skip repetition: if a pattern repeats, mention it once at a summary level only.
Do not add general suggestions, focus strictly on merge-blocking concerns.
If there are no critical problems, respond with minimal approval (e.g., 'Looks good'). Do not add additional review.
Avoid line-by-line commentary unless it highlights a critical bug or security hole.
Highlight only issues that could cause runtime errors, data loss, or severe maintainability issues.
Ignore minor optimization opportunities, focus solely on correctness and safety.
Provide a top-level summary of critical blockers rather than detailed per-line notes.
Comment only when the issue must be resolved before merge, otherwise remain silent.
When in doubt, err on the side of fewer comments, brevity and blocking issues only.
Avoid posting any refactoring issues.

Files:

  • packages/backend/src/tokens/request.ts
  • packages/backend/src/tokens/__tests__/request.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.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.test.ts
**/*.test.{ts,tsx}

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

Use React Testing Library for component testing

Files:

  • packages/backend/src/tokens/__tests__/request.test.ts
🧬 Code graph analysis (2)
packages/backend/src/tokens/request.ts (1)
packages/backend/src/tokens/machine.ts (1)
  • isMachineToken (68-70)
packages/backend/src/tokens/__tests__/request.test.ts (3)
packages/backend/src/fixtures/index.ts (1)
  • mockJwks (59-61)
packages/backend/src/tokens/request.ts (1)
  • authenticateRequest (147-815)
packages/backend/src/fixtures/machine.ts (2)
  • mockMachineAuthResponses (54-67)
  • mockVerificationResults (7-52)
⏰ 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). (1)
  • GitHub Check: semgrep-cloud-platform/scan

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

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.

token-type-mismatch When using multiple acceptsToken in authenticateRequest

1 participant