micromegas_auth/
url_validation.rs

1//! URL validation utilities for authentication flows
2//!
3//! Provides secure validation functions to prevent common web vulnerabilities
4//! like open redirects in OAuth flows and other authentication redirects.
5
6use percent_encoding;
7use url::Url;
8
9/// Validate that a return URL is a safe relative path
10///
11/// This function prevents open redirect attacks by ensuring the URL:
12/// 1. Is URL-decoded to prevent encoding bypasses
13/// 2. Is a relative path starting with exactly one /
14/// 3. Does not contain protocol-relative URLs (//) or absolute URLs
15/// 4. Does not contain backslashes (which some browsers treat as forward slashes)
16/// 5. Parses correctly as a relative URL
17///
18/// # Security
19///
20/// This function defends against various open redirect attack vectors:
21/// - URL encoding bypasses: `/%2F/evil.com` → `//evil.com`
22/// - Protocol-relative URLs: `//evil.com`
23/// - Absolute URLs: `https://evil.com`
24/// - Backslash variants: `/\evil.com` (some browsers normalize to `//evil.com`)
25/// - Encoded protocols: `/http%3A%2F%2Fevil.com`
26///
27/// # Examples
28///
29/// ```
30/// use micromegas_auth::url_validation::validate_return_url;
31///
32/// // Valid relative paths
33/// assert!(validate_return_url("/"));
34/// assert!(validate_return_url("/dashboard"));
35/// assert!(validate_return_url("/path/to/resource?query=value"));
36/// assert!(validate_return_url("/path%20with%20spaces"));
37///
38/// // Invalid: absolute URLs
39/// assert!(!validate_return_url("https://evil.com"));
40/// assert!(!validate_return_url("//evil.com"));
41///
42/// // Invalid: URL-encoded open redirect attempts
43/// assert!(!validate_return_url("/%2F/evil.com"));
44/// assert!(!validate_return_url("/http%3A%2F%2Fevil.com"));
45///
46/// // Invalid: backslash variants
47/// assert!(!validate_return_url("/\\evil.com"));
48/// ```
49pub fn validate_return_url(url: &str) -> bool {
50    // Decode URL to prevent encoding bypasses like /%2F/evil.com
51    // Use percent_decode_str which handles all URL encoding variants
52    let decoded = match percent_encoding::percent_decode_str(url).decode_utf8() {
53        Ok(s) => s.to_string(),
54        Err(_) => return false, // Invalid UTF-8 after decoding
55    };
56
57    // Must start with exactly one /
58    if !decoded.starts_with('/') {
59        return false;
60    }
61
62    // Must not start with // (protocol-relative URL)
63    if decoded.starts_with("//") {
64        return false;
65    }
66
67    // Must not contain protocol markers (://), even after decoding
68    if decoded.contains("://") {
69        return false;
70    }
71
72    // Additional check: ensure no path traversal attempts after the first /
73    // Reject URLs like /\\/evil.com or /\evil.com (backslash variants)
74    if decoded.contains('\\') {
75        return false;
76    }
77
78    // Validate that it parses as a valid relative URL when joined with a base
79    Url::options()
80        .base_url(Some(
81            &Url::parse("http://localhost").expect("base URL should parse"),
82        ))
83        .parse(&decoded)
84        .is_ok()
85}