fix(auth): prevent open redirect vulnerability on sign-in callback#409
Conversation
|
@godamongstmen897 Great news! 🎉 Based on an automated assessment of this PR, the linked Wave issue(s) no longer count against your application limits. You can now already apply to more issues while waiting for a review of this PR. Keep up the great work! 🚀 |
📝 WalkthroughWalkthroughThis PR fixes an open redirect vulnerability in the sign-in flow by implementing redirect validation. A new ChangesOpen Redirect Security Fix
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~22 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
Pull request overview
Note
Copilot was unable to run its full agentic suite in this review.
Adds an open-redirect mitigation utility and uses it to honor a redirect query parameter through the sign-in (and 2FA) flow, persisting a validated path across the 2FA step via sessionStorage.
Changes:
- New
isSafeRedirecthelper that returns a same-origin path or null. - Sign-in flow reads
redirectquery param, validates, and routes to it (storing it for the 2FA continuation). - 2FA flow consumes and clears the stored post-auth redirect.
Reviewed changes
Copilot reviewed 4 out of 4 changed files in this pull request and generated 3 comments.
| File | Description |
|---|---|
| lib/redirect.ts | New helper validating redirect targets are same-origin paths. |
| lib/tests/redirect.test.ts | Vitest unit tests covering allow/deny cases. |
| app/auth/signin/page.tsx | Reads/validates redirect param; stores it for 2FA or navigates immediately; also large indentation reformat of the form JSX. |
| app/auth/2fa/page.tsx | Reads and clears stored post-auth redirect, validates, and routes accordingly. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| }); | ||
|
|
||
| it('rejects malformed urls', () => { | ||
| expect(isSafeRedirect('\\\not a url', 'http://localhost')).toBeNull(); |
| if (target.startsWith("//")) return null; | ||
| try { | ||
| const base = baseOrigin ?? (typeof window !== 'undefined' ? window.location.origin : 'http://localhost'); | ||
| const url = new URL(target, base); | ||
| if (url.origin !== base) return null; | ||
| if (!url.pathname.startsWith('/')) return null; | ||
| return url.pathname + (url.search || '') + (url.hash || ''); |
| const safe = isSafeRedirect(redirectParam); | ||
| if (safe) sessionStorage.setItem('post_auth_redirect', safe); |
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
lib/__tests__/redirect.test.ts (1)
4-26: ⚡ Quick winConsider adding edge case tests for security completeness.
The current coverage is good for common cases. For a security-critical function, consider adding tests for:
null/ empty string inputs →nulljavascript:alert(1)→null(XSS vector)data:text/html,...→nullSuggested additional tests
it('rejects malformed urls', () => { expect(isSafeRedirect('\\\not a url', 'http://localhost')).toBeNull(); }); + + it('rejects null and empty inputs', () => { + expect(isSafeRedirect(null, 'http://localhost')).toBeNull(); + expect(isSafeRedirect('', 'http://localhost')).toBeNull(); + }); + + it('rejects javascript and data URLs', () => { + expect(isSafeRedirect('javascript:alert(1)', 'http://localhost')).toBeNull(); + expect(isSafeRedirect('data:text/html,<script>alert(1)</script>', 'http://localhost')).toBeNull(); + }); });🤖 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 `@lib/__tests__/redirect.test.ts` around lines 4 - 26, Add edge-case tests to the isSafeRedirect suite: add cases that pass null and empty string to isSafeRedirect and assert they return null, add a test that passes a javascript: URL (e.g., "javascript:alert(1)") and asserts null, and add a test that passes a data: URL (e.g., "data:text/html,...") and asserts null; update the existing lib/__tests__/redirect.test.ts tests (the describe('isSafeRedirect') block and its it(...) cases) to include these additional expectations to cover XSS/data URL vectors and empty input handling.
🤖 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 `@app/auth/signin/page.tsx`:
- Around line 70-71: Replace the hard-coded 'post_auth_redirect' literal with
the shared constant used by the 2FA page: import POST_AUTH_REDIRECT_KEY from the
shared module (e.g., lib/redirect.ts or your constants file) and use
sessionStorage.setItem(POST_AUTH_REDIRECT_KEY, safe) in the block where
isSafeRedirect(redirectParam) is checked; ensure the constant is exported from
the shared file so both the 2FA page and app/auth/signin/page.tsx reference the
same symbol.
---
Nitpick comments:
In `@lib/__tests__/redirect.test.ts`:
- Around line 4-26: Add edge-case tests to the isSafeRedirect suite: add cases
that pass null and empty string to isSafeRedirect and assert they return null,
add a test that passes a javascript: URL (e.g., "javascript:alert(1)") and
asserts null, and add a test that passes a data: URL (e.g.,
"data:text/html,...") and asserts null; update the existing
lib/__tests__/redirect.test.ts tests (the describe('isSafeRedirect') block and
its it(...) cases) to include these additional expectations to cover XSS/data
URL vectors and empty input handling.
🪄 Autofix (Beta)
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: defaults
Review profile: CHILL
Plan: Pro
Run ID: 5126d48e-5e16-410f-a03a-994fb2a82c18
📒 Files selected for processing (4)
app/auth/2fa/page.tsxapp/auth/signin/page.tsxlib/__tests__/redirect.test.tslib/redirect.ts
| const safe = isSafeRedirect(redirectParam); | ||
| if (safe) sessionStorage.setItem('post_auth_redirect', safe); |
There was a problem hiding this comment.
Use a shared constant for the sessionStorage key.
The 2FA page defines POST_AUTH_REDIRECT_KEY = 'post_auth_redirect' but this file uses the string literal directly. If either changes independently, the redirect flow silently breaks.
Proposed fix
Export the constant from a shared location (e.g., lib/redirect.ts or a constants file) and import it in both pages:
// In lib/redirect.ts (add export)
+export const POST_AUTH_REDIRECT_KEY = 'post_auth_redirect';
// In app/auth/signin/page.tsx
-import { isSafeRedirect } from "`@/lib/redirect`";
+import { isSafeRedirect, POST_AUTH_REDIRECT_KEY } from "`@/lib/redirect`";
...
- if (safe) sessionStorage.setItem('post_auth_redirect', safe);
+ if (safe) sessionStorage.setItem(POST_AUTH_REDIRECT_KEY, safe);🤖 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 `@app/auth/signin/page.tsx` around lines 70 - 71, Replace the hard-coded
'post_auth_redirect' literal with the shared constant used by the 2FA page:
import POST_AUTH_REDIRECT_KEY from the shared module (e.g., lib/redirect.ts or
your constants file) and use sessionStorage.setItem(POST_AUTH_REDIRECT_KEY,
safe) in the block where isSafeRedirect(redirectParam) is checked; ensure the
constant is exported from the shared file so both the 2FA page and
app/auth/signin/page.tsx reference the same symbol.
This pull request introduces a secure redirect mechanism to prevent open redirect vulnerabilities during authentication flows. The main changes add a utility function to validate redirect URLs, update the sign-in and 2FA flows to use this validation, and include tests to ensure correct behavior.
Security Improvements:
isSafeRedirectutility inlib/redirect.tsto validate and sanitize redirect URLs, only allowing same-origin and relative paths, and rejecting external, protocol-relative, or malformed URLs.app/auth/signin/page.tsx) and 2FA (app/auth/2fa/page.tsx) flows to useisSafeRedirectbefore redirecting users, ensuring that only validated URLs are used for post-authentication navigation. [1] [2] [3] [4] [5] [6]Testing:
isSafeRedirectinlib/__tests__/redirect.test.tsto check acceptance of safe URLs and rejection of unsafe or malformed ones.Session Management:
post_auth_redirectsession storage key to temporarily store validated redirect targets between authentication steps. [1] [2] [3]These changes collectively harden the authentication flow against open redirect attacks and improve session-based redirect handling.
Closes #312
Summary by CodeRabbit
New Features
Tests