Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .changeset/scope-jwks-cache-per-instance.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
'@clerk/backend': patch
---

Scope the JWKS cache per Clerk instance. The cache was keyed on the JWT `kid` alone and shared across the whole process, so an application verifying tokens for more than one Clerk instance (for example the Dynamic Keys / multi-tenant pattern) could resolve a signing key that was fetched for a different instance. Keys are now cached separately per secret key and API URL, so a token can only be verified against the instance whose credentials fetched its signing key.

The `jwk-kid-mismatch` error message no longer lists the key IDs currently held in the cache.
88 changes: 87 additions & 1 deletion packages/backend/src/tokens/__tests__/keys.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -200,10 +200,96 @@ describe('tokens.loadClerkJWKFromRemote(options)', () => {
kid,
}),
).rejects.toThrowError(
"Unable to find a signing key in JWKS that matches the kid='ins_whatever' of the provided session token. Please make sure that the __session cookie or the HTTP authorization header contain a Clerk-generated session JWT. The following kid is available: ins_2GIoQhbUpy0hX7B2cVkuTMinXoD",
"Unable to find a signing key in JWKS that matches the kid='ins_whatever' of the provided session token. Please make sure that the __session cookie or the HTTP authorization header contain a Clerk-generated session JWT.",
);
});

// The cached kids are instance ids; enumerating them discloses which co-tenants
// are warm in a shared process.
it('does not enumerate cached kids in the error message', async () => {
server.use(
http.get(
'https://api.clerk.com/v1/jwks',
validateHeaders(() => {
return HttpResponse.json(mockJwks);
}),
),
);

const error = await loadClerkJWKFromRemote({ secretKey: 'deadbeef', kid: 'ins_whatever' }).catch(e => e);

expect(error).toBeInstanceOf(TokenVerificationError);
expect(error.message).not.toContain(mockRsaJwkKid);
});

// Regression test for SDK-148. The cache was keyed on `kid` alone. Since a Clerk `kid`
// is the instance id and the lookup short-circuits before `secretKey` is consulted, a
// key fetched for one instance was served to another instance's verifier, and
// `verifyJwt` never asserts `iss`.
it('does not serve a cached key to a different secretKey', async () => {
const instanceAKid = 'ins_tenant_a';
let secretKeysUsed: string[] = [];

server.use(
http.get(
'https://api.clerk.com/v1/jwks',
validateHeaders(({ request }) => {
secretKeysUsed.push((request.headers.get('Authorization') ?? '').replace('Bearer ', ''));
// Each instance's JWKS contains only its own signing key.
return HttpResponse.json({ keys: [{ ...mockRsaJwk, kid: instanceAKid }] });
}),
),
);

// Instance A warms the cache with its own key.
const jwk = await loadClerkJWKFromRemote({ secretKey: 'sk_test_a', kid: instanceAKid });
expect(jwk).toMatchObject({ kid: instanceAKid });
expect(secretKeysUsed).toEqual(['sk_test_a']);

// Instance B asking for instance A's kid must miss the cache and fetch under its
// own secretKey.
secretKeysUsed = [];
server.use(
http.get(
'https://api.clerk.com/v1/jwks',
validateHeaders(({ request }) => {
secretKeysUsed.push((request.headers.get('Authorization') ?? '').replace('Bearer ', ''));
return HttpResponse.json({ keys: [{ ...mockRsaJwk, kid: 'ins_tenant_b' }] });
}),
),
);

await expect(() => loadClerkJWKFromRemote({ secretKey: 'sk_test_b', kid: instanceAKid })).rejects.toThrowError(
TokenVerificationError,
);
expect(secretKeysUsed).toEqual(['sk_test_b']);
});
Comment on lines +229 to +266

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.

🔒 Security & Privacy | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

ast-grep outline packages/backend/src/tokens/__tests__/keys.test.ts --items all --type function

rg -n -C 6 \
  'loadClerkJWKFromRemote|apiUrl|apiVersion|skipJwksCache' \
  packages/backend/src/tokens/__tests__/keys.test.ts

Repository: clerk/javascript

Length of output: 7239


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '%s\n' '--- cache implementation and callers ---'
rg -n -C 12 'getRemoteCache|apiVersion|apiUrl' packages/backend/src/tokens packages/backend/src -g '*.ts' -g '*.tsx' | head -n 320

printf '%s\n' '--- all cache-related tests ---'
rg -n -C 8 'getRemoteCache|apiVersion|apiUrl|separate cache|cache.*instance|secretKey.*kid|kid.*secretKey' packages -g '*.{test,spec}.{ts,tsx,js,jsx}' | head -n 400

Repository: clerk/javascript

Length of output: 50372


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '%s\n' '--- relevant file outline ---'
ast-grep outline packages/backend/src/tokens/keys.ts --items all --type function || true
printf '%s\n' '--- implementation ---'
cat -n packages/backend/src/tokens/keys.ts | sed -n '1,280p'

Repository: clerk/javascript

Length of output: 10885


🏁 Script executed:

#!/bin/bash
set -euo pipefail

python3 - <<'PY'
from pathlib import Path
import re

implementation = Path("packages/backend/src/tokens/keys.ts").read_text()
tests = Path("packages/backend/src/tokens/__tests__/keys.test.ts").read_text()

scope = re.search(r"getRemoteCache\(([^)]*)\)", implementation)
print("scope_expression:", scope.group(1) if scope else "MISSING")
print("scope_fields:", {
    field: bool(re.search(rf"\b{field}\b", scope.group(1) if scope else ""))
    for field in ("apiUrl", "apiVersion", "secretKey")
})

for field in ("apiUrl", "apiVersion"):
    matches = list(re.finditer(rf"\b{field}\s*:", tests))
    print(f"{field}_test_occurrences:", len(matches))
    for match in matches:
        start = max(0, tests.rfind("it(", 0, match.start()))
        end = tests.find("\n  });", match.start())
        block = tests[start:end if end != -1 else match.end()]
        print("  has_skipJwksCache:", "skipJwksCache" in block)
PY

Repository: clerk/javascript

Length of output: 343


Add cache-isolation tests for apiUrl and apiVersion.

The existing apiUrl test bypasses the cache with skipJwksCache: true, and no apiVersion test exists. For each field, keep secretKey and kid unchanged, then assert that the new scope performs an independent fetch and returns its own key.

🤖 Prompt for 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.

In `@packages/backend/src/tokens/__tests__/keys.test.ts` around lines 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.

Source: Coding guidelines


it('keeps a separate cache TTL per instance', async () => {
let fetchCount = 0;
server.use(
http.get(
'https://api.clerk.com/v1/jwks',
validateHeaders(() => {
fetchCount++;
return HttpResponse.json(mockJwks);
}),
),
);

await loadClerkJWKFromRemote({ secretKey: 'sk_ttl_a', kid: mockRsaJwkKid });
expect(fetchCount).toBe(1);

// A second instance must not ride on the first instance's fresh TTL.
await loadClerkJWKFromRemote({ secretKey: 'sk_ttl_b', kid: mockRsaJwkKid });
expect(fetchCount).toBe(2);

// Each instance now serves from its own cache.
await loadClerkJWKFromRemote({ secretKey: 'sk_ttl_a', kid: mockRsaJwkKid });
await loadClerkJWKFromRemote({ secretKey: 'sk_ttl_b', kid: mockRsaJwkKid });
expect(fetchCount).toBe(2);
});

it('cache TTLs do not conflict', async () => {
server.use(
http.get(
Expand Down
71 changes: 40 additions & 31 deletions packages/backend/src/tokens/keys.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,20 +19,33 @@ type JsonWebKeyWithKid = JsonWebKey & { kid: string };

type JsonWebKeyCache = Record<string, JsonWebKeyWithKid>;

let cache: JsonWebKeyCache = {};
let lastUpdatedAt = 0;
type RemoteJwksCache = {
keys: JsonWebKeyCache;
lastUpdatedAt: number;
};

function getFromCache(kid: string) {
return cache[kid];
}
/**
* Remote JWKS caches, one per Clerk instance. A single process-wide cache keyed by `kid`
* alone hands one instance's signing key to another instance's verification: a Clerk `kid`
* is the instance id, the lookup short-circuits before `secretKey` is consulted, and
* `verifyJwt` does not assert `iss`. That let a session token minted by instance B
* authenticate against instance A in any process serving both.
*/
const remoteCaches = new Map<string, RemoteJwksCache>();

function getCacheValues() {
return Object.values(cache);
}
/** Local PEM keys are not tied to a secret key, and never expire. */
const localCache: JsonWebKeyCache = {};

function setInCache(cacheKey: string, jwk: JsonWebKeyWithKid, shouldExpire = true) {
cache[cacheKey] = jwk;
lastUpdatedAt = shouldExpire ? Date.now() : -1;
/**
* The scope is held in memory only as a Map key. It is never logged or surfaced in errors.
*/
function getRemoteCache(scope: string): RemoteJwksCache {
let cache = remoteCaches.get(scope);
if (!cache) {
cache = { keys: {}, lastUpdatedAt: 0 };
remoteCaches.set(scope, cache);
}
Comment on lines +34 to +47

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.

🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift

Evict unused remote-cache namespaces.

Every distinct scope remains in remoteCaches for the process lifetime. cacheHasExpired only clears keys after the same scope is used again. It never removes the Map entry. A multi-tenant service can therefore grow remoteCaches without a bound.

Add a bounded LRU policy or idle-entry eviction that removes expired cache namespaces.

Also applies to: 147-147, 235-240

🤖 Prompt for 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.

In `@packages/backend/src/tokens/keys.ts` around lines 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.

return cache;
}

const PEM_HEADER = '-----BEGIN PUBLIC KEY-----';
Expand All @@ -56,7 +69,7 @@ export function loadClerkJwkFromPem(params: LoadClerkJwkFromPemOptions): JsonWeb
// cache conflicts when loadClerkJwkFromPem and loadClerkJWKFromRemote
// are called with the same kid
const prefixedKid = `local-${kid}`;
const cachedJwk = getFromCache(prefixedKid);
const cachedJwk = localCache[prefixedKid];

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

[MEDIUM] Local PEM (jwtKey) cache still shared across instances by kid alone

The remote cache is now correctly scoped by apiUrl|apiVersion|secretKey, but loadClerkJwkFromPem still keys localCache on local-${kid} only — global across every instance in the process, with no scoping by the supplied pem and no TTL. On a cache hit it returns the cached JWK and ignores the passed pem. Since verifyJwt never asserts iss and verifyToken prefers options.jwtKey, an app doing networkless multi-tenant verification is exposed: (1) an instance-A token (kid=insA) presented to instance B (jwtKey=pemB) gets a warm hit returning instance A's key and authenticates cross-tenant; (2) an attacker can poison localCache['local-insA'] with pemB, permanently breaking instance-A verification until restart. Fix: scope the localCache key by a hash of the pem/instance (as the remote cache was fixed) and add a TTL.

— Comment generated with Claude with @dominic-clerk's supervision


if (cachedJwk) {
return cachedJwk;
Expand All @@ -81,7 +94,7 @@ export function loadClerkJwkFromPem(params: LoadClerkJwkFromPemOptions): JsonWeb

// https://datatracker.ietf.org/doc/html/rfc7517
const jwk = { kid: prefixedKid, kty: 'RSA', alg: 'RS256', n: modulus, e: 'AQAB' };
setInCache(prefixedKid, jwk, false); // local key never expires in cache
localCache[prefixedKid] = jwk;
return jwk;
}

Expand Down Expand Up @@ -131,7 +144,9 @@ export type LoadClerkJWKFromRemoteOptions = {
export async function loadClerkJWKFromRemote(params: LoadClerkJWKFromRemoteOptions): Promise<JsonWebKey> {
const { secretKey, apiUrl = API_URL, apiVersion = API_VERSION, kid, skipJwksCache } = params;

if (skipJwksCache || cacheHasExpired() || !getFromCache(kid)) {
const cache = getRemoteCache(`${apiUrl}|${apiVersion}|${secretKey ?? ''}`);

if (skipJwksCache || cacheHasExpired(cache) || !cache.keys[kid]) {
if (!secretKey) {
throw new TokenVerificationError({
action: TokenVerificationErrorAction.ContactSupport,
Expand All @@ -150,21 +165,20 @@ export async function loadClerkJWKFromRemote(params: LoadClerkJWKFromRemoteOptio
});
}

keys.forEach(key => setInCache(key.kid, key));
keys.forEach(key => {
cache.keys[key.kid] = key;
});
cache.lastUpdatedAt = Date.now();
}

const jwk = getFromCache(kid);
const jwk = cache.keys[kid];

if (!jwk) {
const cacheValues = getCacheValues();
const jwkKeys = cacheValues
.map(jwk => jwk.kid)
.sort()
.join(', ');

// The available kids are deliberately omitted: they are instance ids, and enumerating
// them would disclose which co-tenants are warm in a shared process.
throw new TokenVerificationError({
action: `Go to your Dashboard and validate your secret and public keys are correct. ${TokenVerificationErrorAction.ContactSupport} if the issue persists.`,
message: `Unable to find a signing key in JWKS that matches the kid='${kid}' of the provided session token. Please make sure that the __session cookie or the HTTP authorization header contain a Clerk-generated session JWT. The following kid is available: ${jwkKeys}`,
message: `Unable to find a signing key in JWKS that matches the kid='${kid}' of the provided session token. Please make sure that the __session cookie or the HTTP authorization header contain a Clerk-generated session JWT.`,
reason: TokenVerificationErrorReason.JWKKidMismatch,
});
}
Expand Down Expand Up @@ -218,17 +232,12 @@ async function fetchJWKSFromBAPI(apiUrl: string, key: string, apiVersion: string
return response.json();
}

function cacheHasExpired() {
// If lastUpdatedAt is -1, it means that we're using a local JWKS and it never expires
if (lastUpdatedAt === -1) {
return false;
}

function cacheHasExpired(cache: RemoteJwksCache) {
// If the cache has expired, clear the value so we don't attempt to make decisions based on stale data
const isExpired = Date.now() - lastUpdatedAt >= MAX_CACHE_LAST_UPDATED_AT_SECONDS * 1000;
const isExpired = Date.now() - cache.lastUpdatedAt >= MAX_CACHE_LAST_UPDATED_AT_SECONDS * 1000;

if (isExpired) {
cache = {};
cache.keys = {};
}

return isExpired;
Expand Down
Loading