|
| 1 | +/* |
| 2 | + * SPDX-FileCopyrightText: 2026 Zextras <https://www.zextras.com> |
| 3 | + * |
| 4 | + * SPDX-License-Identifier: AGPL-3.0-only |
| 5 | + */ |
| 6 | +/* eslint-disable no-script-url */ |
| 7 | + |
| 8 | +import { isSafeRedirect } from '../utils'; |
| 9 | + |
| 10 | +const ORIGIN = 'https://mail.example.com'; |
| 11 | + |
| 12 | +describe('isSafeRedirect', () => { |
| 13 | + const originalLocation = window.location; |
| 14 | + |
| 15 | + beforeEach(() => { |
| 16 | + Object.defineProperty(window, 'location', { |
| 17 | + writable: true, |
| 18 | + value: { ...originalLocation, origin: ORIGIN } |
| 19 | + }); |
| 20 | + }); |
| 21 | + |
| 22 | + afterEach(() => { |
| 23 | + Object.defineProperty(window, 'location', { |
| 24 | + writable: true, |
| 25 | + value: originalLocation |
| 26 | + }); |
| 27 | + }); |
| 28 | + |
| 29 | + describe('should allow safe URLs', () => { |
| 30 | + it.each([ |
| 31 | + ['/', 'root path'], |
| 32 | + ['/inbox', 'simple relative path'], |
| 33 | + ['/mail/inbox?page=1', 'relative path with query string'], |
| 34 | + ['/settings#account', 'relative path with fragment'], |
| 35 | + [`${ORIGIN}/inbox`, 'absolute same-origin URL'], |
| 36 | + [`${ORIGIN}/mail/inbox?page=1&sort=date`, 'absolute same-origin with query params'], |
| 37 | + ['relative-path', 'plain relative segment'], |
| 38 | + ['', 'empty string'], |
| 39 | + ['https://saml-validation.com', 'https external domain'], |
| 40 | + ['http://saml-validation.com', 'http external domain'], |
| 41 | + ['http://mail.example.com/inbox', 'same host but different scheme (http vs https)'] |
| 42 | + ])('%s (%s)', (url) => { |
| 43 | + expect(isSafeRedirect(url)).toBe(true); |
| 44 | + }); |
| 45 | + }); |
| 46 | + |
| 47 | + describe('should block dangerous URLs', () => { |
| 48 | + it.each([ |
| 49 | + ['javascript:alert(document.cookie)', 'javascript: scheme'], |
| 50 | + ['javascript:void(0)', 'javascript:void'], |
| 51 | + ['javascript:eval(alert(1))', 'javascript:eval'], |
| 52 | + ['data:text/html,<script>alert(1)</script>', 'data: URI with script'], |
| 53 | + ['data:text/html;base64,PHNjcmlwdD5hbGVydCgxKTwvc2NyaXB0Pg==', 'data: URI base64 encoded'], |
| 54 | + ['vbscript:msgbox("xss")', 'vbscript: scheme'], |
| 55 | + ['blob:https://evil.com/some-id', 'blob: URI'], |
| 56 | + ['ftp://files.example.com/secret', 'ftp: scheme'] |
| 57 | + ])('%s (%s)', (url) => { |
| 58 | + expect(isSafeRedirect(url)).toBe(false); |
| 59 | + }); |
| 60 | + }); |
| 61 | + |
| 62 | + describe('edge cases', () => { |
| 63 | + it('should block falsy values', () => { |
| 64 | + expect(isSafeRedirect(null)).toBe(false); |
| 65 | + }); |
| 66 | + |
| 67 | + it('should handle backslash-based bypass attempts', () => { |
| 68 | + const result = isSafeRedirect('\\\\evil.com'); |
| 69 | + expect(result).toBe(false); |
| 70 | + }); |
| 71 | + }); |
| 72 | +}); |
0 commit comments