1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
//! URL validation utilities for authentication flows
//!
//! Provides secure validation functions to prevent common web vulnerabilities
//! like open redirects in OAuth flows and other authentication redirects.
use percent_encoding;
use Url;
/// Validate that a return URL is a safe relative path
///
/// This function prevents open redirect attacks by ensuring the URL:
/// 1. Is URL-decoded to prevent encoding bypasses
/// 2. Is a relative path starting with exactly one /
/// 3. Does not contain protocol-relative URLs (//) or absolute URLs
/// 4. Does not contain backslashes (which some browsers treat as forward slashes)
/// 5. Parses correctly as a relative URL
///
/// # Security
///
/// This function defends against various open redirect attack vectors:
/// - URL encoding bypasses: `/%2F/evil.com` → `//evil.com`
/// - Protocol-relative URLs: `//evil.com`
/// - Absolute URLs: `https://evil.com`
/// - Backslash variants: `/\evil.com` (some browsers normalize to `//evil.com`)
/// - Encoded protocols: `/http%3A%2F%2Fevil.com`
///
/// # Examples
///
/// ```
/// use micromegas_auth::url_validation::validate_return_url;
///
/// // Valid relative paths
/// assert!(validate_return_url("/"));
/// assert!(validate_return_url("/dashboard"));
/// assert!(validate_return_url("/path/to/resource?query=value"));
/// assert!(validate_return_url("/path%20with%20spaces"));
///
/// // Invalid: absolute URLs
/// assert!(!validate_return_url("https://evil.com"));
/// assert!(!validate_return_url("//evil.com"));
///
/// // Invalid: URL-encoded open redirect attempts
/// assert!(!validate_return_url("/%2F/evil.com"));
/// assert!(!validate_return_url("/http%3A%2F%2Fevil.com"));
///
/// // Invalid: backslash variants
/// assert!(!validate_return_url("/\\evil.com"));
/// ```