Skip to content

fix(auth): cache Clerk JWKS instead of nil-panic on fetch failure#3301

Merged
moshloop merged 1 commit into
mainfrom
fix/clerk-jwks-nil-panic
Jun 30, 2026
Merged

fix(auth): cache Clerk JWKS instead of nil-panic on fetch failure#3301
moshloop merged 1 commit into
mainfrom
fix/clerk-jwks-nil-panic

Conversation

@adityathebe

@adityathebe adityathebe commented Jun 29, 2026

Copy link
Copy Markdown
Member

Problem

A transient network blip reaching Clerk's JWKS endpoint (context deadline exceeded fetching .../.well-known/jwks.json) caused a nil-pointer panic in the auth flow, taking down request goroutines and the OIDC callback:

@coderabbitai

coderabbitai Bot commented Jun 29, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

@moshloop, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 18 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 54f0ac7b-6ab3-4e34-bf38-7b2fa6993292

📥 Commits

Reviewing files that changed from the base of the PR and between 623d042 and e3432d4.

📒 Files selected for processing (2)
  • auth/clerk_client.go
  • auth/tokens.go

Walkthrough

getJWTKeyFunc in auth/tokens.go is renamed to newClerkKeyfunc and updated to return (jwt.Keyfunc, error) instead of using logger.Fatalf. A new jwksCache struct in auth/clerk_client.go lazily initializes and memoizes the keyfunc using a sync.Mutex, replacing the per-request call pattern in ClerkHandler.

Changes

Lazy JWKS keyfunc caching

Layer / File(s) Summary
newClerkKeyfunc helper
auth/tokens.go
Renames getJWTKeyFunc to newClerkKeyfunc, changes return type to (jwt.Keyfunc, error), and replaces logger.Fatalf with a wrapped error return on JWKS fetch failure.
jwksCache and ClerkHandler wiring
auth/clerk_client.go
Adds sync import, introduces jwksCache with mutex-guarded lazy initialization of the keyfunc, and updates NewClerkHandler and parseJWTToken to use h.jwks.keyfunc() instead of calling the helper per request.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ 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%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly matches the main fix: caching Clerk JWKS and preventing nil-pointer panics on fetch failure.
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.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/clerk-jwks-nil-panic
✨ Simplify code
  • Create PR with simplified code
  • Commit simplified code in branch fix/clerk-jwks-nil-panic

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.

@moshloop moshloop enabled auto-merge (rebase) June 29, 2026 19:24
getJWTKeyFunc handled a failed JWKS fetch with logger.Fatalf, but the
slog logger's Fatalf only logs and does not os.Exit. Execution fell
through to `return jwks.Keyfunc` with a nil *keyfunc.JWKS, which later
panicked inside ParseWithClaims -> (*JWKS).getKey on a nil receiver.
So a transient network blip to Clerk crashed request goroutines and the
OIDC callback.

It was also called from parseJWTToken on every Clerk-authenticated
request, so each request did a synchronous JWKS HTTP fetch and spawned a
background-refresh goroutine that lived forever (per-request fetch +
goroutine leak).

Build the JWKS once and reuse it via a pointer-held jwksCache (shared
across ClerkHandler value-receiver copies). Failed fetches are not
cached, so a transient outage retries on the next request instead of
poisoning the handler, and degrades to the existing logged-error/401
path instead of panicking. Key rotation is still handled by keyfunc's
RefreshUnknownKID + hourly refresh against the single long-lived
instance.
@moshloop moshloop force-pushed the fix/clerk-jwks-nil-panic branch from 623d042 to e3432d4 Compare June 30, 2026 06:26
@moshloop moshloop merged commit 7afa082 into main Jun 30, 2026
12 of 13 checks passed
@moshloop moshloop deleted the fix/clerk-jwks-nil-panic branch June 30, 2026 09:14
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants