Skip to content

fix(backend): Scope the JWKS cache per Clerk instance - #9394

Open
dominic-clerk wants to merge 2 commits into
mainfrom
dominic/sdk-148-cross-tenant-authentication-bypass-in-clerkbackend-module
Open

fix(backend): Scope the JWKS cache per Clerk instance#9394
dominic-clerk wants to merge 2 commits into
mainfrom
dominic/sdk-148-cross-tenant-authentication-bypass-in-clerkbackend-module

Conversation

@dominic-clerk

Copy link
Copy Markdown
Contributor

Description

The module-level JWKS cache was keyed on the bare kid. Because a Clerk kid is the instance id, a key cached for one instance was a direct hit for another instance's verification in the same process, and the lookup short-circuits before secretKey is consulted. Since verifyJwt never asserts iss, a session token minted by instance B authenticated against instance A in any process serving both — the documented Dynamic Keys / multi-tenant pattern. The same cache backs the M2M and OAuth sinks via resolveKeyAndVerifyJwt.

Remote keys are now cached per (apiUrl, apiVersion, secretKey), each namespace carrying its own TTL, so a cross-instance lookup misses and forces the secret-key-authenticated fetch. Local PEM keys move to their own store, which also stops a local jwtKey from disabling the remote TTL process-wide.

The jwk-kid-mismatch message no longer enumerates cached kids, which disclosed the instance ids warm in a shared process.

Fixes SDK-148

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:

The module-level JWKS cache was keyed on the bare `kid`. Because a Clerk
`kid` is the instance id, a key cached for one instance was a direct hit
for another instance's verification in the same process, and the lookup
short-circuits before `secretKey` is consulted. Since `verifyJwt` never
asserts `iss`, a session token minted by instance B authenticated against
instance A in any process serving both — the documented Dynamic Keys /
multi-tenant pattern. The same cache backs the M2M and OAuth sinks via
`resolveKeyAndVerifyJwt`.

Remote keys are now cached per `(apiUrl, apiVersion, secretKey)`, each
namespace carrying its own TTL, so a cross-instance lookup misses and
forces the secret-key-authenticated fetch. Local PEM keys move to their
own store, which also stops a local `jwtKey` from disabling the remote
TTL process-wide.

The `jwk-kid-mismatch` message no longer enumerates cached kids, which
disclosed the instance ids warm in a shared process.

SDK-148
@vercel

vercel Bot commented Aug 11, 2026

Copy link
Copy Markdown

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

Project Deployment Actions Updated (UTC)
clerk-js-sandbox Ready Ready Preview Aug 13, 2026 11:19am
swingset Ready Ready Preview Aug 13, 2026 11:19am

Request Review

@changeset-bot

changeset-bot Bot commented Aug 11, 2026

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 8808214

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/astro Patch
@clerk/express Patch
@clerk/fastify Patch
@clerk/hono 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

@pkg-pr-new

pkg-pr-new Bot commented Aug 11, 2026

Copy link
Copy Markdown

Open in StackBlitz

@clerk/astro

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

@clerk/backend

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

@clerk/chrome-extension

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

@clerk/clerk-js

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

@clerk/electron

npm i https://pkg.pr.new/@clerk/electron@9394

@clerk/electron-passkeys

npm i https://pkg.pr.new/@clerk/electron-passkeys@9394

@clerk/eslint-plugin

npm i https://pkg.pr.new/@clerk/eslint-plugin@9394

@clerk/expo

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

@clerk/expo-google-signin

npm i https://pkg.pr.new/@clerk/expo-google-signin@9394

@clerk/expo-passkeys

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

@clerk/express

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

@clerk/fastify

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

@clerk/hono

npm i https://pkg.pr.new/@clerk/hono@9394

@clerk/localizations

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

@clerk/nextjs

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

@clerk/nuxt

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

@clerk/react

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

@clerk/react-router

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

@clerk/shared

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

@clerk/tanstack-react-start

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

@clerk/testing

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

@clerk/ui

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

@clerk/upgrade

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

@clerk/vue

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

commit: 8808214

@github-actions

github-actions Bot commented Aug 11, 2026

Copy link
Copy Markdown
Contributor

API Changes Report

Generated by Break Check on 2026-08-13T11:20:53.116Z

Summary

Metric Count
Packages analyzed 19
Packages with changes 0
🔴 Breaking changes 0
🟡 Non-breaking changes 0
🟢 Additions 0

No API Changes Detected

All packages have stable APIs with no detected changes.


Report generated by Break Check

Last ran on 8808214.

@coderabbitai

coderabbitai Bot commented Aug 11, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

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

Review profile: CHILL

Plan: Pro Plus

Run ID: 7ef736a3-a668-443d-91b5-e709c2b7b416

📥 Commits

Reviewing files that changed from the base of the PR and between 7cc23a0 and 8808214.

📒 Files selected for processing (3)
  • .changeset/scope-jwks-cache-per-instance.md
  • packages/backend/src/tokens/__tests__/keys.test.ts
  • packages/backend/src/tokens/keys.ts
🔗 Linked repositories identified

CodeRabbit considers these linked repositories for cross-repo context during reviews:

  • clerk/clerk_go (manual)
  • clerk/dashboard (manual)
  • clerk/accounts (manual)
  • clerk/backoffice (manual)
  • clerk/clerk (manual)
  • clerk/clerk-docs (manual)
  • clerk/cloudflare-workers (manual)
  • clerk/clerk-ios (auto-detected)
  • clerk/cli (auto-detected)
  • clerk/clerk-android (auto-detected)

📝 Walkthrough

Walkthrough

The backend derives local PEM keys on each call and stores remote JWKS keys in caches scoped by API URL, API version, and secret key. Each remote cache has independent expiration. Missing-key errors no longer list cached key IDs. Tests cover local key derivation, cache isolation, TTL behavior, and error output.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Mergeability Score: ⚪ Minimal · up to 88082

The change scopes JWKS caching per Clerk instance and separates local key handling, preventing cross-instance key reuse while preserving normal verification behavior; no actionable merge-blocking risk remains beyond normal checks and review.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes scoping the backend JWKS cache per Clerk instance.
Description check ✅ Passed The description explains the cross-instance authentication issue and the cache-scoping changes that resolve it.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/backend/src/tokens/__tests__/keys.test.ts`:
- Around line 229-266: Extend the cache-isolation tests in keys.test.ts to cover
apiUrl and apiVersion without using skipJwksCache. For each field, keep
secretKey and kid identical across scopes, configure distinct values, assert the
second request performs an independent fetch, and verify it returns the key from
its own JWKS response.

In `@packages/backend/src/tokens/keys.ts`:
- Around line 34-47: Update getRemoteCache and the related cache-expiration
paths around cacheHasExpired to evict expired remote-cache namespaces from
remoteCaches, not merely clear their keys. Implement a bounded LRU or idle-entry
policy so unused scopes are removed while preserving reuse of active scopes and
existing key-expiration behavior.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

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

Review profile: CHILL

Plan: Pro Plus

Run ID: 190d1fcf-c228-426b-b194-97a49d8ee5d3

📥 Commits

Reviewing files that changed from the base of the PR and between 29c9017 and 7cc23a0.

📒 Files selected for processing (3)
  • .changeset/scope-jwks-cache-per-instance.md
  • packages/backend/src/tokens/__tests__/keys.test.ts
  • packages/backend/src/tokens/keys.ts
🔗 Linked repositories identified

CodeRabbit considers these linked repositories for cross-repo context during reviews:

  • clerk/clerk_go (manual)
  • clerk/dashboard (manual)
  • clerk/accounts (manual)
  • clerk/backoffice (manual)
  • clerk/clerk (manual)
  • clerk/clerk-docs (manual)
  • clerk/cloudflare-workers (manual)
  • clerk/cli (auto-detected)
  • clerk/clerk-ios (auto-detected)
  • clerk/clerk-android (auto-detected)

Comment thread packages/backend/src/tokens/__tests__/keys.test.ts
Comment thread packages/backend/src/tokens/keys.ts
Comment thread packages/backend/src/tokens/keys.ts Outdated
…e JWKS cache

Address review: the PEM-derived JWK was cached by kid alone (an untrusted
token-header value), so a warm hit could serve one instance's key to another
instance's verifier. Derivation is cheap, so drop the cache entirely.

Also evict expired JWKS cache scopes on new-scope creation and add apiUrl/
apiVersion cache-isolation tests.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
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.

1 participant