-
Notifications
You must be signed in to change notification settings - Fork 470
fix(backend,fastify): Skip handshake resolution for non-navigation requests when opted out #9636
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
wobsoriano
wants to merge
9
commits into
main
Choose a base branch
from
fix/backend-resolve-handshake-only-for-navigation
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
b11c802
fix(backend): Add __internal_resolveHandshakeOnlyForNavigation option
wobsoriano f5e75e5
refactor(backend): Simplify handshake gate and drop express proof test
wobsoriano 9dc19db
test(backend): Fold handshake opt-out tests into request.test.ts
wobsoriano 7ac792e
refactor(fastify): Delegate handshake opt-out to @clerk/backend
wobsoriano a94833e
docs(backend): Describe handshake opt-out by eligibility rule
wobsoriano b2054bb
docs(fastify): Rewrap __internal_enableHandshake JSDoc
wobsoriano 028d609
refactor(fastify): Drop handshake redirect suppression
wobsoriano 8cfe459
chore(repo): Shorten handshake changesets
wobsoriano 4194473
refactor(fastify): Tighten handshake test types and drop redundant va…
wobsoriano File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| --- | ||
| '@clerk/backend': patch | ||
| --- | ||
|
|
||
| Add internal `__internal_resolveHandshakeOnlyForNavigation` option to `authenticateRequest()`. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| --- | ||
| '@clerk/fastify': patch | ||
| --- | ||
|
|
||
| `__internal_enableHandshake` now delegates to `@clerk/backend`. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -461,8 +461,14 @@ export const authenticateRequest: AuthenticateRequest = (async ( | |
|
|
||
| /** | ||
| * If we have a handshakeToken, resolve the handshake and attempt to return a definitive signed in or signed out state. | ||
| * With `__internal_resolveHandshakeOnlyForNavigation`, requests that are not eligible for a handshake redirect | ||
| * skip this, so a stale handshake cookie does not trigger a failing payload exchange. | ||
| */ | ||
| if (authenticateContext.handshakeNonce || authenticateContext.handshakeToken) { | ||
| const hasHandshakeToken = authenticateContext.handshakeNonce || authenticateContext.handshakeToken; | ||
| const canResolveHandshake = | ||
| !authenticateContext.__internal_resolveHandshakeOnlyForNavigation || | ||
| handshakeService.isRequestEligibleForHandshake(); | ||
| if (hasHandshakeToken && canResolveHandshake) { | ||
|
Comment on lines
+467
to
+471
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This is backwards compatible. Only fastify passes a value here, mapped from its existing |
||
| try { | ||
| return await handshakeService.resolveHandshake(); | ||
| } catch (error) { | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
127 changes: 127 additions & 0 deletions
127
packages/fastify/src/__tests__/withClerkMiddleware.handshake.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,127 @@ | ||
| import type { AddressInfo } from 'node:net'; | ||
|
|
||
| import Fastify from 'fastify'; | ||
| import { afterAll, afterEach, beforeAll, describe, expect, test, vi } from 'vitest'; | ||
|
|
||
| import { clerkPlugin } from '../index'; | ||
| import type { ClerkFastifyOptions } from '../types'; | ||
|
|
||
| // Runs the real @clerk/backend against a local stand-in for the Backend API. | ||
| const PK_LIVE = 'pk_live_Y2xlcmsuaW5zcGlyZWQucHVtYS03NC5sY2wuZGV2JA'; | ||
| const PK_TEST = 'pk_test_Y2xlcmsuaW5zcGlyZWQucHVtYS03NC5sY2wuZGV2JA'; | ||
|
|
||
| const payloadRequests: string[] = []; | ||
| const fakeBackendApi = Fastify(); | ||
| fakeBackendApi.get('/v1/clients/handshake_payload', (request, reply) => { | ||
| payloadRequests.push(request.url); | ||
| reply.code(404).send({ errors: [{ code: 'resource_not_found', message: 'not found' }] }); | ||
| }); | ||
|
|
||
| let apiUrl = ''; | ||
|
|
||
| beforeAll(async () => { | ||
| await fakeBackendApi.listen({ port: 0, host: '127.0.0.1' }); | ||
| apiUrl = `http://127.0.0.1:${(fakeBackendApi.server.address() as AddressInfo).port}`; | ||
| }); | ||
|
|
||
| afterAll(async () => { | ||
| await fakeBackendApi.close(); | ||
| }); | ||
|
|
||
| afterEach(() => { | ||
| payloadRequests.length = 0; | ||
| vi.restoreAllMocks(); | ||
| }); | ||
|
|
||
| const buildApp = async (pluginOptions: Partial<ClerkFastifyOptions>) => { | ||
| vi.spyOn(console, 'error').mockImplementation(() => {}); | ||
| const app = Fastify(); | ||
| await app.register(clerkPlugin, { apiUrl, ...pluginOptions }); | ||
| app.get('/api/me', (_request, reply) => { | ||
| reply.send({ | ||
| status: reply.getHeader('x-clerk-auth-status'), | ||
| reason: reply.getHeader('x-clerk-auth-reason'), | ||
| }); | ||
| }); | ||
| return app; | ||
| }; | ||
|
|
||
| const production = { secretKey: 'sk_live_deadbeef', publishableKey: PK_LIVE }; | ||
| const development = { secretKey: 'sk_test_deadbeef', publishableKey: PK_TEST }; | ||
|
|
||
| const fetchHeaders = { 'sec-fetch-dest': 'empty', accept: '*/*' }; | ||
| const navigationHeaders = { 'sec-fetch-dest': 'document', accept: 'text/html' }; | ||
|
|
||
| describe('clerkPlugin handshake handling (real @clerk/backend)', () => { | ||
| test('by default a stale nonce on a fetch request is exchanged with the Backend API', async () => { | ||
| const app = await buildApp(production); | ||
|
|
||
| const response = await app.inject({ | ||
| method: 'GET', | ||
| url: '/api/me', | ||
| headers: { ...fetchHeaders, cookie: '__clerk_handshake_nonce=stale; __client_uat=12345' }, | ||
| }); | ||
|
|
||
| expect(response.statusCode).toBe(200); | ||
| expect(payloadRequests).toHaveLength(1); | ||
| expect(response.json()).toEqual({ status: 'signed-out', reason: 'session-token-missing' }); | ||
| }); | ||
|
|
||
| test('with __internal_enableHandshake: false a stale nonce on a fetch request is ignored', async () => { | ||
| const app = await buildApp({ ...production, __internal_enableHandshake: false }); | ||
|
|
||
| const response = await app.inject({ | ||
| method: 'GET', | ||
| url: '/api/me', | ||
| headers: { ...fetchHeaders, cookie: '__clerk_handshake_nonce=stale; __client_uat=12345' }, | ||
| }); | ||
|
|
||
| expect(response.statusCode).toBe(200); | ||
| expect(payloadRequests).toHaveLength(0); | ||
| expect(response.json()).toEqual({ status: 'signed-out', reason: 'client-uat-but-no-session-token' }); | ||
| }); | ||
|
|
||
| test('with __internal_enableHandshake: false a stale nonce on a POST request is ignored', async () => { | ||
| const app = await buildApp({ ...production, __internal_enableHandshake: false }); | ||
| app.post('/api/submit', (_request, reply) => { | ||
| reply.send({ status: reply.getHeader('x-clerk-auth-status') }); | ||
| }); | ||
|
|
||
| const response = await app.inject({ | ||
| method: 'POST', | ||
| url: '/api/submit', | ||
| headers: { ...navigationHeaders, cookie: '__clerk_handshake_nonce=stale; __client_uat=12345' }, | ||
| }); | ||
|
|
||
| expect(response.statusCode).toBe(200); | ||
| expect(payloadRequests).toHaveLength(0); | ||
| expect(response.json()).toEqual({ status: 'signed-out' }); | ||
| }); | ||
|
|
||
| test('with __internal_enableHandshake: false a development navigation still redirects to the dev browser handshake', async () => { | ||
| const app = await buildApp({ ...development, __internal_enableHandshake: false }); | ||
|
|
||
| const response = await app.inject({ method: 'GET', url: '/api/me', headers: navigationHeaders }); | ||
|
|
||
| expect(response.statusCode).toBe(307); | ||
| expect(response.headers.location).toContain('/v1/client/handshake'); | ||
| expect(response.headers['x-clerk-auth-reason']).toBe('dev-browser-missing'); | ||
| expect(payloadRequests).toHaveLength(0); | ||
| }); | ||
|
|
||
| test('with __internal_enableHandshake: false a development navigation returning from the handshake still resolves the nonce', async () => { | ||
| const app = await buildApp({ ...development, __internal_enableHandshake: false }); | ||
|
|
||
| const response = await app.inject({ | ||
| method: 'GET', | ||
| url: '/api/me?__clerk_handshake_nonce=fresh', | ||
| headers: navigationHeaders, | ||
| }); | ||
|
|
||
| expect(payloadRequests).toHaveLength(1); | ||
| expect(payloadRequests[0]).toContain('nonce=fresh'); | ||
| // Development resolution redirects to the same URL with the handshake params removed. | ||
| expect(response.statusCode).toBe(307); | ||
| expect(response.headers.location).not.toContain('__clerk_handshake_nonce'); | ||
| }); | ||
| }); |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win
🔎 Supported by static analysis
🏁 Script executed:
Repository: clerk/javascript
Length of output: 9313
🏁 Script executed:
Repository: clerk/javascript
Length of output: 38046
🏁 Script executed:
Repository: clerk/javascript
Length of output: 25282
🏁 Script executed:
Repository: clerk/javascript
Length of output: 338
🏁 Script executed:
Repository: clerk/javascript
Length of output: 10358
🏁 Script executed:
Repository: clerk/javascript
Length of output: 5329
Add non-navigation query-string handshake coverage.
The request tests contain no query-string handshake artifact.
initHandshakeValuesmaps query parameters tohandshakeNonceorhandshakeToken, and the navigation-only gate applies to both fields. Add a non-navigation request with a stale query-string handshake nonce and assert that the payload exchange is skipped.🤖 Prompt for AI Agents
Source: Coding guidelines