Skip to main content

feedparser_rs/util/
base_url.rs

1//! Base URL resolution for xml:base support
2//!
3//! This module provides URL resolution following RFC 3986, supporting
4//! the `xml:base` attribute used in Atom and some RSS feeds.
5
6use super::ssrf;
7use url::Url;
8
9/// Validates that a URL is safe for external use (no SSRF risks)
10///
11/// This function checks for common SSRF attack vectors including:
12/// - Non-HTTP(S) schemes (file://, data://, etc.)
13/// - Localhost addresses (127.0.0.1, `::1`, localhost)
14/// - Private IP ranges (192.168.x.x, 10.x.x.x, 172.16-31.x.x)
15/// - Cloud metadata endpoints (169.254.169.254)
16///
17/// Delegates to the same [`crate::http::validation::validate_url`] rule set used
18/// by the HTTP fetcher, so `xml:base`-derived links and fetched feed URLs are
19/// held to identical SSRF protections.
20///
21/// # Arguments
22///
23/// * `url` - The URL to validate
24///
25/// # Returns
26///
27/// `true` if the URL is safe to use, `false` if it poses SSRF risks
28///
29/// # Examples
30///
31/// ```
32/// use feedparser_rs::util::base_url::is_safe_url;
33///
34/// // Safe URLs
35/// assert!(is_safe_url("http://example.com/"));
36/// assert!(is_safe_url("https://github.com/"));
37///
38/// // Unsafe URLs
39/// assert!(!is_safe_url("file:///etc/passwd"));
40/// assert!(!is_safe_url("http://localhost/"));
41/// assert!(!is_safe_url("http://192.168.1.1/"));
42/// assert!(!is_safe_url("http://169.254.169.254/"));
43/// ```
44#[must_use]
45pub fn is_safe_url(url: &str) -> bool {
46    ssrf::validate_url(url).is_ok()
47}
48
49/// Resolves a potentially relative URL against a base URL
50///
51/// If `href` is already absolute, returns it unchanged.
52/// If `base` is None or invalid, returns `href` unchanged.
53/// Otherwise, resolves `href` relative to `base`.
54///
55/// # Arguments
56///
57/// * `href` - The URL to resolve (may be relative or absolute)
58/// * `base` - The base URL to resolve against (may be None)
59///
60/// # Returns
61///
62/// The resolved URL as a string
63///
64/// # Examples
65///
66/// ```
67/// use feedparser_rs::util::base_url::resolve_url;
68///
69/// // Absolute URLs are returned unchanged
70/// assert_eq!(
71///     resolve_url("http://example.com/page", Some("http://other.com/")),
72///     "http://example.com/page"
73/// );
74///
75/// // Relative URLs are resolved against the base
76/// assert_eq!(
77///     resolve_url("page.html", Some("http://example.com/dir/")),
78///     "http://example.com/dir/page.html"
79/// );
80///
81/// // Without a base, relative URLs are returned unchanged
82/// assert_eq!(resolve_url("page.html", None), "page.html");
83/// ```
84#[must_use]
85pub fn resolve_url(href: &str, base: Option<&str>) -> String {
86    // If href is already absolute, return it
87    if href.starts_with("http://")
88        || href.starts_with("https://")
89        || href.starts_with("mailto:")
90        || href.starts_with("tel:")
91    {
92        return href.to_string();
93    }
94
95    // If no base URL, return href unchanged
96    let Some(base_str) = base else {
97        return href.to_string();
98    };
99
100    // Try to parse base URL
101    let Ok(base_url) = Url::parse(base_str) else {
102        return href.to_string();
103    };
104
105    // Resolve href against base
106    base_url
107        .join(href)
108        .map_or_else(|_| href.to_string(), |resolved| resolved.to_string())
109}
110
111/// Combines two base URLs, with child overriding parent
112///
113/// This handles nested `xml:base` attributes where a child element's
114/// base URL may be relative to its parent's base.
115///
116/// # Arguments
117///
118/// * `parent_base` - The parent element's base URL (may be None)
119/// * `child_base` - The child element's xml:base value (may be None)
120///
121/// # Returns
122///
123/// The effective base URL for the child element, or None if no base is set
124///
125/// # Examples
126///
127/// ```
128/// use feedparser_rs::util::base_url::combine_bases;
129///
130/// // Child absolute base overrides parent
131/// assert_eq!(
132///     combine_bases(Some("http://parent.com/"), Some("http://child.com/")),
133///     Some("http://child.com/".to_string())
134/// );
135///
136/// // Child relative base is resolved against parent
137/// assert_eq!(
138///     combine_bases(Some("http://example.com/feed/"), Some("items/")),
139///     Some("http://example.com/feed/items/".to_string())
140/// );
141///
142/// // No child base, parent is used
143/// assert_eq!(
144///     combine_bases(Some("http://example.com/"), None),
145///     Some("http://example.com/".to_string())
146/// );
147///
148/// // No bases at all
149/// assert_eq!(combine_bases(None, None), None);
150/// ```
151#[must_use]
152pub fn combine_bases(parent_base: Option<&str>, child_base: Option<&str>) -> Option<String> {
153    match (parent_base, child_base) {
154        (_, Some(child)) => {
155            // Child has a base - resolve it against parent if parent exists
156            Some(resolve_url(child, parent_base))
157        }
158        (Some(parent), None) => Some(parent.to_string()),
159        (None, None) => None,
160    }
161}
162
163/// Longest base URL a [`BaseUrlContext`] adopts from `update_base` or `child_with_base`.
164///
165/// Every relative URL and text construct under a base carries a copy of it.
166const MAX_BASE_URL_LEN: usize = 512;
167
168/// Context for tracking base URLs during parsing
169///
170/// This struct maintains the current base URL context and provides
171/// methods for URL resolution within a parsing context.
172#[derive(Debug, Clone)]
173pub struct BaseUrlContext {
174    /// The current effective base URL
175    base: Option<String>,
176    /// Whether `resolve`/`resolve_safe` actually resolve relative URLs against
177    /// `base`, or pass `href` through unchanged (`ParseOptions::resolve_relative_uris`)
178    resolve: bool,
179}
180
181impl Default for BaseUrlContext {
182    fn default() -> Self {
183        Self::new()
184    }
185}
186
187impl BaseUrlContext {
188    /// Creates a new context with no base URL
189    #[must_use]
190    pub const fn new() -> Self {
191        Self {
192            base: None,
193            resolve: true,
194        }
195    }
196
197    /// Creates a new context with an initial base URL
198    #[must_use]
199    pub fn with_base(base: impl Into<String>) -> Self {
200        Self {
201            base: Some(base.into()),
202            resolve: true,
203        }
204    }
205
206    /// Sets whether relative URL resolution is enabled (builder pattern)
207    ///
208    /// When `false`, [`Self::resolve`] never joins `href` against `base` — it
209    /// always returns `href` unchanged. [`Self::resolve_safe`] is different:
210    /// it still validates whatever `resolve` returns (dangerous schemes,
211    /// SSRF/private-IP checks) even when this is `false`, so it does **not**
212    /// simply return `href` unchanged — see its docs for why. Mirrors
213    /// `ParseOptions::resolve_relative_uris`.
214    #[must_use]
215    pub const fn with_resolve(mut self, resolve: bool) -> Self {
216        self.resolve = resolve;
217        self
218    }
219
220    /// Gets the current base URL
221    #[must_use]
222    pub fn base(&self) -> Option<&str> {
223        self.base.as_deref()
224    }
225
226    /// Updates the base URL with a new xml:base value
227    ///
228    /// The new base is resolved against the current base if it's relative. A result
229    /// longer than 512 bytes is not adopted: the current base stays in effect.
230    pub fn update_base(&mut self, xml_base: &str) {
231        let new_base = resolve_url(xml_base, self.base.as_deref());
232        if new_base.len() <= MAX_BASE_URL_LEN {
233            self.base = Some(new_base);
234        }
235    }
236
237    /// Resolves a URL against the current base
238    ///
239    /// Returns `href` unchanged when relative URL resolution is disabled
240    /// (see [`Self::with_resolve`]).
241    #[must_use]
242    pub fn resolve(&self, href: &str) -> String {
243        if !self.resolve {
244            return href.to_string();
245        }
246        resolve_url(href, self.base.as_deref())
247    }
248
249    /// Resolves a URL against the current base with SSRF protection
250    ///
251    /// This method performs URL resolution and validates the result to prevent
252    /// Server-Side Request Forgery (SSRF) attacks via malicious xml:base attributes.
253    ///
254    /// # Security
255    ///
256    /// If the resolved URL fails SSRF safety checks (localhost, private IPs,
257    /// dangerous schemes), the original `href` is returned unchanged instead
258    /// of the resolved URL.
259    ///
260    /// # Security
261    ///
262    /// These safety checks run **unconditionally**, even when relative URL
263    /// resolution is disabled via [`Self::with_resolve`]. `with_resolve(false)`
264    /// only disables joining `href` against `base`; it never skips scheme/SSRF
265    /// validation, so a feed-supplied `href` that is itself an absolute
266    /// dangerous or private-network URL is still blocked (#438).
267    ///
268    /// # Arguments
269    ///
270    /// * `href` - The URL to resolve (may be relative or absolute)
271    ///
272    /// # Returns
273    ///
274    /// The resolved URL if safe, otherwise the original `href`
275    ///
276    /// # Examples
277    ///
278    /// ```
279    /// use feedparser_rs::util::base_url::BaseUrlContext;
280    ///
281    /// // Safe URL resolution
282    /// let ctx = BaseUrlContext::with_base("http://example.com/");
283    /// assert_eq!(ctx.resolve_safe("page.html"), "http://example.com/page.html");
284    ///
285    /// // SSRF blocked - returns original href
286    /// let dangerous_ctx = BaseUrlContext::with_base("http://localhost/");
287    /// assert_eq!(dangerous_ctx.resolve_safe("admin"), "admin");
288    ///
289    /// // Safety checks still run when relative resolution is disabled
290    /// let no_resolve_ctx = BaseUrlContext::new().with_resolve(false);
291    /// assert_eq!(
292    ///     no_resolve_ctx.resolve_safe("http://169.254.169.254/latest/meta-data/"),
293    ///     ""
294    /// );
295    /// ```
296    #[must_use]
297    pub fn resolve_safe(&self, href: &str) -> String {
298        // `self.resolve()` already respects `self.resolve`: it returns `href`
299        // unchanged (no base joining) when relative resolution is disabled. The
300        // scheme/SSRF checks below always run on whatever it returns, so a
301        // feed-supplied absolute `href` is validated regardless of that setting.
302        let resolved = self.resolve(href);
303
304        // Use lowercase for case-insensitive scheme comparison (RFC 3986)
305        let resolved_lower = resolved.to_lowercase();
306
307        // Block dangerous schemes (file://, data://, javascript://, etc.)
308        // Case-insensitive to prevent bypass via FILE://, JAVASCRIPT:, etc.
309        if resolved_lower.starts_with("file://")
310            || resolved_lower.starts_with("data:")
311            || resolved_lower.starts_with("javascript:")
312            || resolved_lower.starts_with("ftp://")
313            || resolved_lower.starts_with("gopher://")
314        {
315            // Dangerous scheme - return original href
316            return href.to_string();
317        }
318
319        // Validate HTTP(S) URLs for SSRF
320        if resolved_lower.starts_with("http://") || resolved_lower.starts_with("https://") {
321            if is_safe_url(&resolved) {
322                resolved
323            } else {
324                // SSRF blocked - check if href itself is an unsafe absolute URL
325                // If href is an absolute URL pointing to dangerous target, return empty
326                // Otherwise return original relative href (safe since it requires base to resolve)
327                let href_is_unsafe_absolute = Url::parse(href).is_ok_and(|parsed_href| {
328                    let is_http_scheme = matches!(parsed_href.scheme(), "http" | "https");
329                    is_http_scheme && !is_safe_url(href)
330                });
331
332                if href_is_unsafe_absolute {
333                    String::new()
334                } else {
335                    href.to_string()
336                }
337            }
338        } else {
339            // Other schemes (mailto:, tel:) or relative URLs pass through
340            resolved
341        }
342    }
343
344    /// Creates a child context inheriting this context's base
345    #[must_use]
346    pub fn child(&self) -> Self {
347        Self {
348            base: self.base.clone(),
349            resolve: self.resolve,
350        }
351    }
352
353    /// Creates a child context with an additional xml:base
354    ///
355    /// If the combined base is longer than 512 bytes, the child inherits this
356    /// context's base unchanged.
357    #[must_use]
358    pub fn child_with_base(&self, xml_base: &str) -> Self {
359        let new_base = combine_bases(self.base.as_deref(), Some(xml_base))
360            .filter(|base| base.len() <= MAX_BASE_URL_LEN)
361            .or_else(|| self.base.clone());
362        Self {
363            base: new_base,
364            resolve: self.resolve,
365        }
366    }
367}
368
369#[cfg(test)]
370mod tests {
371    use super::*;
372
373    #[test]
374    fn test_resolve_absolute_url() {
375        assert_eq!(
376            resolve_url("http://example.com/page", Some("http://other.com/")),
377            "http://example.com/page"
378        );
379        assert_eq!(
380            resolve_url("https://example.com/page", Some("http://other.com/")),
381            "https://example.com/page"
382        );
383    }
384
385    #[test]
386    fn test_resolve_relative_url() {
387        assert_eq!(
388            resolve_url("page.html", Some("http://example.com/dir/")),
389            "http://example.com/dir/page.html"
390        );
391        assert_eq!(
392            resolve_url("/absolute/path", Some("http://example.com/dir/")),
393            "http://example.com/absolute/path"
394        );
395        assert_eq!(
396            resolve_url("../sibling/page", Some("http://example.com/dir/sub/")),
397            "http://example.com/dir/sibling/page"
398        );
399    }
400
401    #[test]
402    fn test_resolve_without_base() {
403        assert_eq!(resolve_url("page.html", None), "page.html");
404        assert_eq!(
405            resolve_url("http://example.com", None),
406            "http://example.com"
407        );
408    }
409
410    #[test]
411    fn test_resolve_invalid_base() {
412        assert_eq!(
413            resolve_url("page.html", Some("not a valid url")),
414            "page.html"
415        );
416    }
417
418    #[test]
419    fn test_resolve_special_schemes() {
420        assert_eq!(
421            resolve_url("mailto:test@example.com", Some("http://example.com/")),
422            "mailto:test@example.com"
423        );
424        assert_eq!(
425            resolve_url("tel:+1234567890", Some("http://example.com/")),
426            "tel:+1234567890"
427        );
428    }
429
430    #[test]
431    fn test_combine_bases_child_absolute() {
432        assert_eq!(
433            combine_bases(Some("http://parent.com/"), Some("http://child.com/")),
434            Some("http://child.com/".to_string())
435        );
436    }
437
438    #[test]
439    fn test_combine_bases_child_relative() {
440        assert_eq!(
441            combine_bases(Some("http://example.com/feed/"), Some("items/")),
442            Some("http://example.com/feed/items/".to_string())
443        );
444    }
445
446    #[test]
447    fn test_combine_bases_no_child() {
448        assert_eq!(
449            combine_bases(Some("http://example.com/"), None),
450            Some("http://example.com/".to_string())
451        );
452    }
453
454    #[test]
455    fn test_combine_bases_no_parent() {
456        assert_eq!(
457            combine_bases(None, Some("http://example.com/")),
458            Some("http://example.com/".to_string())
459        );
460    }
461
462    #[test]
463    fn test_combine_bases_none() {
464        assert_eq!(combine_bases(None, None), None);
465    }
466
467    #[test]
468    fn test_context_new() {
469        let ctx = BaseUrlContext::new();
470        assert!(ctx.base().is_none());
471    }
472
473    #[test]
474    fn test_context_with_base() {
475        let ctx = BaseUrlContext::with_base("http://example.com/");
476        assert_eq!(ctx.base(), Some("http://example.com/"));
477    }
478
479    #[test]
480    fn test_context_update_base() {
481        let mut ctx = BaseUrlContext::with_base("http://example.com/feed/");
482        ctx.update_base("items/");
483        assert_eq!(ctx.base(), Some("http://example.com/feed/items/"));
484    }
485
486    #[test]
487    fn test_context_resolve() {
488        let ctx = BaseUrlContext::with_base("http://example.com/feed/");
489        assert_eq!(
490            ctx.resolve("item.html"),
491            "http://example.com/feed/item.html"
492        );
493        assert_eq!(ctx.resolve("http://other.com/"), "http://other.com/");
494    }
495
496    #[test]
497    fn test_context_child() {
498        let parent = BaseUrlContext::with_base("http://example.com/");
499        let child = parent.child();
500        assert_eq!(child.base(), Some("http://example.com/"));
501    }
502
503    #[test]
504    fn test_context_resolve_disabled() {
505        let ctx = BaseUrlContext::with_base("http://example.com/feed/").with_resolve(false);
506        assert_eq!(ctx.resolve("item.html"), "item.html");
507        assert_eq!(ctx.resolve_safe("item.html"), "item.html");
508    }
509
510    #[test]
511    fn test_context_resolve_disabled_propagates_to_children() {
512        let ctx = BaseUrlContext::with_base("http://example.com/").with_resolve(false);
513        assert_eq!(ctx.child().resolve("page.html"), "page.html");
514        assert_eq!(
515            ctx.child_with_base("sub/").resolve("page.html"),
516            "page.html"
517        );
518    }
519
520    #[test]
521    fn test_context_base_length_limit() {
522        const OUTER: &str = "http://example.com/";
523        let fits = format!("{OUTER}{}", "a".repeat(MAX_BASE_URL_LEN - OUTER.len()));
524        let too_long = format!("{fits}a");
525
526        for (xml_base, expected) in [(&fits, fits.as_str()), (&too_long, OUTER)] {
527            let mut ctx = BaseUrlContext::with_base(OUTER);
528            assert_eq!(ctx.child_with_base(xml_base).base(), Some(expected));
529            ctx.update_base(xml_base);
530            assert_eq!(ctx.base(), Some(expected));
531        }
532        assert_eq!(
533            BaseUrlContext::new().child_with_base(&too_long).base(),
534            None
535        );
536    }
537
538    #[test]
539    fn test_context_child_with_base() {
540        let parent = BaseUrlContext::with_base("http://example.com/feed/");
541        let child = parent.child_with_base("items/");
542        assert_eq!(child.base(), Some("http://example.com/feed/items/"));
543    }
544
545    #[test]
546    fn test_fragment_preservation() {
547        assert_eq!(
548            resolve_url("#section", Some("http://example.com/page.html")),
549            "http://example.com/page.html#section"
550        );
551    }
552
553    #[test]
554    fn test_query_string_preservation() {
555        assert_eq!(
556            resolve_url("?query=value", Some("http://example.com/page.html")),
557            "http://example.com/page.html?query=value"
558        );
559    }
560
561    #[test]
562    fn test_empty_href() {
563        // Empty href should resolve to base URL itself
564        assert_eq!(
565            resolve_url("", Some("http://example.com/page.html")),
566            "http://example.com/page.html"
567        );
568    }
569
570    // SSRF Protection Tests
571    #[test]
572    fn test_is_safe_url_file_scheme() {
573        assert!(!is_safe_url("file:///etc/passwd"));
574        assert!(!is_safe_url("file:///C:/Windows/System32/config/sam"));
575    }
576
577    #[test]
578    fn test_is_safe_url_localhost() {
579        assert!(!is_safe_url("http://localhost/"));
580        assert!(!is_safe_url("http://127.0.0.1/"));
581        assert!(!is_safe_url("http://[::1]/"));
582        assert!(!is_safe_url("https://localhost:8080/api"));
583    }
584
585    #[test]
586    fn test_is_safe_url_private_ip() {
587        // 192.168.x.x range
588        assert!(!is_safe_url("http://192.168.1.1/"));
589        assert!(!is_safe_url("http://192.168.0.1/"));
590        assert!(!is_safe_url("http://192.168.255.255/"));
591
592        // 10.x.x.x range
593        assert!(!is_safe_url("http://10.0.0.1/"));
594        assert!(!is_safe_url("http://10.255.255.255/"));
595
596        // 172.16-31.x.x range
597        assert!(!is_safe_url("http://172.16.0.1/"));
598        assert!(!is_safe_url("http://172.31.255.255/"));
599        assert!(!is_safe_url("http://172.20.10.5/"));
600
601        // 127.x.x.x range
602        assert!(!is_safe_url("http://127.0.0.2/"));
603        assert!(!is_safe_url("http://127.255.255.255/"));
604    }
605
606    #[test]
607    fn test_is_safe_url_cloud_metadata() {
608        assert!(!is_safe_url("http://169.254.169.254/"));
609        assert!(!is_safe_url("http://169.254.169.254/latest/meta-data/"));
610        assert!(!is_safe_url("http://metadata.google.internal/"));
611    }
612
613    #[test]
614    fn test_is_safe_url_valid_urls() {
615        assert!(is_safe_url("http://example.com/"));
616        assert!(is_safe_url("https://github.com/"));
617        assert!(is_safe_url("http://1.1.1.1/"));
618        assert!(is_safe_url("https://8.8.8.8/"));
619        assert!(is_safe_url("http://example.com:8080/path"));
620    }
621
622    #[test]
623    fn test_is_safe_url_other_schemes() {
624        assert!(!is_safe_url("ftp://example.com/"));
625        assert!(!is_safe_url("data:text/html,<script>alert('xss')</script>"));
626        assert!(!is_safe_url("javascript:alert('xss')"));
627        assert!(!is_safe_url("gopher://example.com/"));
628    }
629
630    #[test]
631    fn test_is_safe_url_ipv6() {
632        // Loopback
633        assert!(!is_safe_url("http://[::1]/"));
634        assert!(!is_safe_url("http://[0:0:0:0:0:0:0:1]/"));
635
636        // Private ULA (fc00::/7)
637        assert!(!is_safe_url("http://[fc00::1]/"));
638        assert!(!is_safe_url("http://[fd00::1]/"));
639
640        // Public IPv6 should be allowed
641        assert!(is_safe_url("http://[2001:4860:4860::8888]/"));
642    }
643
644    #[test]
645    fn test_is_safe_url_ipv4_mapped_ipv6_loopback_blocked() {
646        // Regression pin: before consolidating onto `util::ssrf`, this
647        // module's own is_private_ip()/is_loopback() checks did not unwrap
648        // IPv4-mapped IPv6 addresses, so `::ffff:127.0.0.1` (which reaches
649        // 127.0.0.1 on the wire) passed as "safe" through xml:base
650        // resolution.
651        assert!(!is_safe_url("http://[::ffff:127.0.0.1]/"));
652    }
653
654    #[test]
655    fn test_is_safe_url_invalid_urls() {
656        assert!(!is_safe_url("not a url"));
657        assert!(!is_safe_url(""));
658        assert!(!is_safe_url("://invalid"));
659    }
660}