-
Notifications
You must be signed in to change notification settings - Fork 411
DO NOT REVIEW - WIP safari ITP handshake loop #7335
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
base: main
Are you sure you want to change the base?
Conversation
|
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
WalkthroughAdded redirect-loop handling to the token authentication flow to address Safari ITP (Intelligent Tracking Prevention) scenarios. When a request lacks an active client but contains a valid session token and a redirect-loop counter, the system attempts to verify the session token. Successful verification returns a signed-in state, while failures fall back to the existing handshake flow. Changes
Sequence DiagramsequenceDiagram
participant Client
participant AuthRequest as authenticateRequest()
participant SessionVerifier
participant CookieStore
Client->>AuthRequest: Request with __clerk_redirect_count cookie
AuthRequest->>CookieStore: Check for session token & redirect count
alt No Active Client + Session Token + Redirect Count > 0
AuthRequest->>SessionVerifier: Verify session token
alt Verification Succeeds
SessionVerifier-->>AuthRequest: Valid session
AuthRequest-->>Client: Return signed-in state
Note over AuthRequest: Safari ITP workaround successful
else Verification Fails
SessionVerifier-->>AuthRequest: Invalid session
AuthRequest-->>Client: Fall back to handshake flow
Note over AuthRequest: Handshake with SessionTokenWithoutClientUAT
end
else Normal Flow
AuthRequest-->>Client: Continue standard authentication
end
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes
Poem
Pre-merge checks and finishing touches❌ Failed checks (2 warnings)
✅ Passed checks (1 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
Comment |
@clerk/agent-toolkit
@clerk/astro
@clerk/backend
@clerk/chrome-extension
@clerk/clerk-js
@clerk/dev-cli
@clerk/elements
@clerk/clerk-expo
@clerk/expo-passkeys
@clerk/express
@clerk/fastify
@clerk/localizations
@clerk/nextjs
@clerk/nuxt
@clerk/clerk-react
@clerk/react-router
@clerk/remix
@clerk/shared
@clerk/tanstack-react-start
@clerk/testing
@clerk/themes
@clerk/types
@clerk/upgrade
@clerk/vue
commit: |
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.
Actionable comments posted: 1
🧹 Nitpick comments (2)
packages/backend/src/tokens/request.ts (1)
547-560: Consider catching specific error types for better error handling.The catch block currently catches all errors indiscriminately. Consider catching only
TokenVerificationErrorto avoid masking unexpected errors.Apply this diff to catch specific error types:
try { const { data } = await verifyToken(authenticateContext.sessionTokenInCookie!, authenticateContext); if (data) { return signedIn({ tokenType: TokenType.SessionToken, authenticateContext, sessionClaims: data, headers: new Headers(), token: authenticateContext.sessionTokenInCookie!, }); } - } catch { + } catch (err) { // Token verification failed, proceed with normal handshake flow + if (err instanceof TokenVerificationError) { + console.log('Clerk: Session token verification failed in redirect loop, falling back to handshake'); + } else { + // Unexpected error - rethrow or log prominently + console.error('Clerk: Unexpected error during redirect loop token verification:', err); + throw err; + } }packages/backend/src/tokens/__tests__/request.test.ts (1)
880-925: Consider adding test coverage for expired tokens in redirect loop.While the current tests cover valid and malformed tokens, consider adding a test for expired tokens in the redirect loop scenario to ensure comprehensive coverage of all token verification error paths.
Example test to add:
test('cookieToken: returns handshake when no clientUat and redirect loop but expired session token', async () => { server.use( http.get('https://api.clerk.test/v1/jwks', () => { return HttpResponse.json(mockJwks); }), ); // Advance time to expire the token vi.advanceTimersByTime(3600 * 1000); const requestState = await authenticateRequest( mockRequestWithCookies( {}, { __clerk_db_jwt: 'deadbeef', __session: mockJwt, // Will be expired due to time advance __clerk_redirect_count: '1', }, ), mockOptions({ secretKey: 'test_deadbeef', }), ); // Should return handshake since token verification failed expect(requestState).toMatchHandshake({ reason: AuthErrorReason.SessionTokenWithoutClientUAT }); expect(requestState.toAuth()).toBeNull(); });
📜 Review details
Configuration used: Path: .coderabbit.yaml
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.
📒 Files selected for processing (2)
packages/backend/src/tokens/__tests__/request.test.ts(1 hunks)packages/backend/src/tokens/request.ts(1 hunks)
🧰 Additional context used
📓 Path-based instructions (9)
**/*.{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.tspackages/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.tspackages/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.tspackages/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)
Prefer importing types from
@clerk/shared/typesinstead of the deprecated@clerk/typesalias
Files:
packages/backend/src/tokens/request.tspackages/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.tspackages/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.tspackages/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
Avoidanytype - preferunknownwhen type is uncertain, then narrow with type guards
Implement type guards forunknowntypes using the patternfunction isType(value: unknown): value is Type
Useinterfacefor object shapes that might be extended
Usetypefor unions, primitives, and computed types
Preferreadonlyproperties for immutable data structures
Useprivatefor internal implementation details in classes
Useprotectedfor inheritance hierarchies
Usepublicexplicitly 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 likeOmit,Partial, andPickfor 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
Useconst assertionswithas constfor literal types
Usesatisfiesoperator 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.tspackages/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
🧬 Code graph analysis (1)
packages/backend/src/tokens/__tests__/request.test.ts (4)
packages/backend/src/mock-server.ts (1)
server(6-6)packages/backend/src/fixtures/index.ts (2)
mockJwks(47-49)mockMalformedJwt(14-15)packages/remix/src/ssr/authenticateRequest.ts (1)
authenticateRequest(9-54)packages/backend/src/tokens/authStatus.ts (2)
AuthErrorReason(105-122)AuthErrorReason(124-124)
⏰ 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). (5)
- GitHub Check: Formatting | Dedupe | Changeset
- GitHub Check: Build Packages
- GitHub Check: Analyze (javascript-typescript)
- GitHub Check: semgrep-cloud-platform/scan
- GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (2)
packages/backend/src/tokens/__tests__/request.test.ts (2)
880-904: Good test coverage for Safari ITP workaround scenario.The test correctly validates that when in a redirect loop with a valid session token, the authentication succeeds despite missing clientUat. This aligns with the Safari ITP mitigation logic.
906-925: Good test coverage for redirect loop with invalid token.The test correctly validates that when the session token is invalid during a redirect loop, the system falls back to the handshake flow. This ensures the workaround doesn't bypass security for invalid tokens.
| } catch { | ||
| // Token verification failed, proceed with normal handshake flow | ||
| } |
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.
Add error logging in the catch block.
The empty catch block silently swallows all token verification errors, making debugging difficult in production. At minimum, log the error before proceeding to the handshake flow.
Apply this diff to add error logging:
} catch {
// Token verification failed, proceed with normal handshake flow
+ console.log('Clerk: Session token verification failed in redirect loop, falling back to handshake');
}Or better yet, log the actual error:
- } catch {
+ } catch (err) {
// Token verification failed, proceed with normal handshake flow
+ console.log('Clerk: Session token verification failed in redirect loop, falling back to handshake:', err);
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| } catch { | |
| // Token verification failed, proceed with normal handshake flow | |
| } | |
| } catch (err) { | |
| // Token verification failed, proceed with normal handshake flow | |
| console.log('Clerk: Session token verification failed in redirect loop, falling back to handshake:', err); | |
| } |
🤖 Prompt for AI Agents
In packages/backend/src/tokens/request.ts around lines 558-560, the empty catch
block for token verification swallows errors; change it to catch the error
(e.g., catch (err)) and log the error before continuing the handshake flow — use
the module's existing logger (e.g., logger.error or processLogger.error) and
include a concise message plus the error object, and if no logger is available
fall back to console.error so token verification failures are visible in logs.
Description
Looks like Safari ITP sometimes blocks the Strict cookies on cross-origin redirects (
__clerk_uat) in development so if you are redirecting directly to a protected route, the middleware will keep trying to handshake in order to acquire that particular cookie leading to an infinite redirect loop.In the scenario where we detect a handshake redirect loop (attempt 2 +), we just validate the token and returned signed in instead of forcing a handshake.
Checklist
pnpm testruns as expected.pnpm buildruns as expected.Type of change
Summary by CodeRabbit
✏️ Tip: You can customize this high-level summary in your review settings.