Skip to main content

vector_core/
net.rs

1//! Network utilities — SSRF protection, HTTP client helpers.
2
3use url::Url;
4
5/// Reject URLs that resolve to private/loopback/link-local addresses (SSRF protection).
6pub fn validate_url_not_private(url_str: &str) -> Result<(), &'static str> {
7    let parsed = Url::parse(url_str).map_err(|_| "Invalid URL")?;
8
9    match parsed.scheme() {
10        "http" | "https" => {}
11        _ => return Err("Only HTTP(S) URLs are allowed"),
12    }
13
14    match parsed.host() {
15        Some(url::Host::Ipv4(ip)) => {
16            let o = ip.octets();
17            if ip.is_loopback() || ip.is_private() || ip.is_link_local()
18                || ip.is_broadcast() || ip.is_unspecified()
19                || (o[0] == 100 && o[1] >= 64 && o[1] <= 127)
20            {
21                return Err("Private/internal IP addresses are not allowed");
22            }
23        }
24        Some(url::Host::Ipv6(ip)) => {
25            if ip.is_loopback() || ip.is_unspecified() || is_ipv6_private(&ip) {
26                return Err("Private/internal IP addresses are not allowed");
27            }
28        }
29        Some(url::Host::Domain(domain)) => {
30            if domain == "localhost" || domain.ends_with(".local") || domain.ends_with(".internal") {
31                return Err("Local hostnames are not allowed");
32            }
33        }
34        None => return Err("URL has no host"),
35    }
36
37    Ok(())
38}
39
40fn is_ipv6_private(ip: &std::net::Ipv6Addr) -> bool {
41    if let Some(ipv4) = ip.to_ipv4_mapped() {
42        return ipv4.is_loopback() || ipv4.is_private() || ipv4.is_link_local();
43    }
44    let segments = ip.segments();
45    if segments[0] & 0xfe00 == 0xfc00 { return true; } // Unique local
46    if segments[0] & 0xffc0 == 0xfe80 { return true; } // Link-local
47    false
48}
49
50/// Build an HTTP client with the given timeout.
51///
52/// Honors the Tor failsafe: when the user has Tor enabled, every connection
53/// goes through Tor — period. If Tor is enabled but not currently running
54/// (bootstrap in flight, mid-restart, service crashed), the returned client
55/// is wired to a blackhole SOCKS proxy so requests fail at the TCP layer
56/// without any chance of leaking clearnet traffic. Direct connections are
57/// only ever issued when the user has explicitly disabled Tor.
58///
59/// Callers should use this rather than `reqwest::Client::builder()` directly
60/// so the failsafe automatically covers their traffic. The `disallowed_methods`
61/// clippy lint enforces this everywhere except this one canonical call site.
62#[allow(clippy::disallowed_methods)]
63pub fn build_http_client(timeout: std::time::Duration) -> Result<reqwest::Client, String> {
64    build_http_client_with_options(timeout, true)
65}
66
67/// Like `build_http_client`, optionally without redirect-following.
68/// Blossom PUT uses `false`: a 3xx mid-upload would re-issue as GET and
69/// drop the body, so we surface the 3xx as the real failure status.
70#[allow(clippy::disallowed_methods)]
71pub fn build_http_client_with_options(
72    timeout: std::time::Duration,
73    follow_redirects: bool,
74) -> Result<reqwest::Client, String> {
75    let mut builder = reqwest::Client::builder().timeout(timeout);
76    if !follow_redirects {
77        builder = builder.redirect(reqwest::redirect::Policy::none());
78    } else {
79        // Validate EVERY redirect hop, not just the initial URL: a public
80        // host answering `302 Location: http://169.254.169.254/…` would
81        // otherwise walk the request straight past the SSRF check.
82        builder = builder.redirect(reqwest::redirect::Policy::custom(|attempt| {
83            if attempt.previous().len() >= 10 {
84                return attempt.error("too many redirects");
85            }
86            match validate_url_not_private(attempt.url().as_str()) {
87                Ok(()) => attempt.follow(),
88                Err(e) => attempt.error(e),
89            }
90        }));
91    }
92
93    #[cfg(feature = "tor")]
94    {
95        match crate::tor::transport_state() {
96            crate::tor::TorTransportState::Active(addr) => {
97                // Use the addr from the variant directly — re-querying via
98                // proxy_url() races against TorService::stop() and can panic.
99                let url = format!("socks5h://{addr}");
100                let proxy = reqwest::Proxy::all(&url)
101                    .map_err(|e| format!("Tor proxy URL ({url}) invalid: {e}"))?;
102                builder = builder.proxy(proxy);
103            }
104            crate::tor::TorTransportState::RequiredButInactive => {
105                // Tor failsafe: route to a blackhole so connections fail safe
106                // instead of leaking direct.
107                let url = format!("socks5h://{}", crate::tor::blackhole_proxy_addr());
108                let proxy = reqwest::Proxy::all(&url)
109                    .map_err(|e| format!("blackhole proxy invalid: {e}"))?;
110                builder = builder.proxy(proxy);
111            }
112            crate::tor::TorTransportState::Disabled => {
113                // No proxy — user has Tor off.
114            }
115        }
116    }
117
118    builder
119        .build()
120        .map_err(|e| format!("Failed to build HTTP client: {}", e))
121}
122
123// ============================================================================
124// Shared HTTP client — proxy-aware + rebuildable on Tor toggle
125// ============================================================================
126//
127// Some call sites (image-cache fetches, PIVX wallet polling) make frequent
128// requests and benefit from a shared `reqwest::Client` to reuse connection
129// pools / TLS sessions. A bare `LazyLock<Client>` doesn't work for us because
130// a Tor toggle should affect future requests immediately — but the static is
131// frozen at first init. Instead, we hold an `Arc<Client>` behind a `RwLock`
132// and rebuild it via `rebuild_shared_http_client()` whenever the Tor state
133// changes. In-flight requests finish on the old Arc; new requests pick up
134// the new one.
135
136use std::sync::{Arc, OnceLock, RwLock};
137
138static SHARED_HTTP_CLIENT: OnceLock<RwLock<Arc<reqwest::Client>>> = OnceLock::new();
139
140const DEFAULT_SHARED_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);
141
142fn shared_cell() -> &'static RwLock<Arc<reqwest::Client>> {
143    SHARED_HTTP_CLIENT.get_or_init(|| {
144        let client = build_http_client(DEFAULT_SHARED_TIMEOUT)
145            .expect("initial shared HTTP client build cannot fail");
146        RwLock::new(Arc::new(client))
147    })
148}
149
150/// Get a shared HTTP client. Cheap clone (Arc), proxy-aware, picks up Tor
151/// toggles on the next call after `rebuild_shared_http_client()` runs.
152pub fn shared_http_client() -> Arc<reqwest::Client> {
153    shared_cell().read().unwrap().clone()
154}
155
156/// Rebuild the shared client. Call this when Tor state flips so the next
157/// request goes through the freshly-configured proxy. In-flight requests on
158/// the old client continue to completion on the previous Arc.
159pub fn rebuild_shared_http_client() -> Result<(), String> {
160    let new = Arc::new(build_http_client(DEFAULT_SHARED_TIMEOUT)?);
161    *shared_cell().write().unwrap() = new;
162    Ok(())
163}
164
165/// Find the byte index where a bracket/paren group opened at `start` closes,
166/// tracking nesting depth and honoring backslash escapes — markdown balances
167/// both, so a naive first-closer scan desyncs on `[[claim]](evil)` or
168/// `[claim\]](evil)` and lets the claim reach the URL scan. All compared
169/// bytes are ASCII, so the returned index is char-boundary-safe.
170fn md_group_close(bytes: &[u8], start: usize, open: u8, close: u8) -> Option<usize> {
171    let mut depth = 1usize;
172    let mut escaped = false;
173    let mut j = start;
174    loop {
175        match bytes.get(j).copied() {
176            None => return None,
177            Some(b'\\') if !escaped => escaped = true,
178            Some(b) if b == open && !escaped => depth += 1,
179            Some(b) if b == close && !escaped => {
180                depth -= 1;
181                if depth == 0 {
182                    return Some(j);
183                }
184            }
185            _ => escaped = false,
186        }
187        j += 1;
188    }
189}
190
191/// Rewrite markdown links so a preview-URL scan sees only real DESTINATIONS:
192/// `[text](href)` keeps the href and drops the display text — a URL claimed in
193/// the text must never win the OG preview over where the link actually goes —
194/// `[text](<href>)` drops entirely (angle brackets are the no-preview syntax),
195/// and `[text][ref]` drops the label (its destination is a definition scanned
196/// on its own elsewhere in the text). Images (`![alt](url)`) render as literal
197/// text in chat, so they pass through untouched.
198pub fn strip_md_link_claims(text: &str) -> String {
199    let bytes = text.as_bytes();
200    let mut out = String::with_capacity(text.len());
201    let mut last = 0;
202    let mut i = 0;
203    while i < bytes.len() {
204        if bytes[i] != b'[' || (i > 0 && bytes[i - 1] == b'!') {
205            i += 1;
206            continue;
207        }
208        let Some(close) = md_group_close(bytes, i + 1, b'[', b']') else { break };
209        match bytes.get(close + 1).copied() {
210            // Inline link: drop the label, contribute the destination.
211            Some(b'(') => {
212                let Some(paren) = md_group_close(bytes, close + 2, b'(', b')') else {
213                    i = close + 1;
214                    continue;
215                };
216                out.push_str(&text[last..i]);
217                let href = text[close + 2..paren].trim();
218                if !(href.starts_with('<') && href.ends_with('>')) {
219                    out.push(' ');
220                    out.push_str(href);
221                    out.push(' ');
222                }
223                i = paren + 1;
224                last = i;
225            }
226            // Reference link: drop the label; the `[ref]: url` definition line
227            // carries the real destination and gets scanned as plain text.
228            Some(b'[') => {
229                let Some(ref_close) = md_group_close(bytes, close + 2, b'[', b']') else {
230                    i = close + 1;
231                    continue;
232                };
233                out.push_str(&text[last..i]);
234                i = ref_close + 1;
235                last = i;
236            }
237            _ => {
238                i = close + 1;
239            }
240        }
241    }
242    out.push_str(&text[last..]);
243    out
244}
245
246#[cfg(test)]
247mod tests {
248    use super::*;
249
250    // ========================================================================
251    // strip_md_link_claims — preview scan must see destinations, not claims
252    // ========================================================================
253
254    #[test]
255    fn md_link_claim_text_dropped_href_kept() {
256        // The spoof shape: claimed URL first in raw text, real destination second.
257        let out = strip_md_link_claims("[https://your-bank.com](https://evil.io)");
258        assert!(!out.contains("your-bank.com"), "claimed text must not reach the scan: {out}");
259        assert!(out.contains("https://evil.io"), "real destination must reach the scan: {out}");
260    }
261
262    #[test]
263    fn md_no_preview_link_dropped_entirely() {
264        let out = strip_md_link_claims("see [docs](<https://vector.app/docs>) ok");
265        assert!(!out.contains("vector.app"), "no-preview href must not reach the scan: {out}");
266        assert!(out.contains("see ") && out.contains(" ok"));
267    }
268
269    #[test]
270    fn md_image_passes_through() {
271        let text = "![shot](https://host.io/img.png)";
272        assert_eq!(strip_md_link_claims(text), text);
273    }
274
275    #[test]
276    fn plain_text_and_bare_urls_untouched() {
277        let text = "check https://vector.app and [also] (spaced) brackets";
278        assert_eq!(strip_md_link_claims(text), text);
279    }
280
281    #[test]
282    fn multiple_links_keep_document_order() {
283        let out = strip_md_link_claims("[a](https://one.io) mid [b](https://two.io)");
284        let one = out.find("https://one.io").expect("first href kept");
285        let two = out.find("https://two.io").expect("second href kept");
286        assert!(one < two);
287    }
288
289    #[test]
290    fn nested_bracket_label_still_drops_claim() {
291        let out = strip_md_link_claims("[[https://trusted.com]](https://evil.io)");
292        assert!(!out.contains("trusted.com"), "nested-bracket claim must not reach the scan: {out}");
293        assert!(out.contains("https://evil.io"));
294    }
295
296    #[test]
297    fn escaped_bracket_label_still_drops_claim() {
298        let out = strip_md_link_claims(r"[https://trusted.com\]](https://evil.io)");
299        assert!(!out.contains("trusted.com"), "escaped-bracket claim must not reach the scan: {out}");
300        assert!(out.contains("https://evil.io"));
301    }
302
303    #[test]
304    fn paren_path_href_survives_whole() {
305        let out = strip_md_link_claims("[wiki](https://en.wikipedia.org/wiki/Foo_(bar))");
306        assert!(out.contains("https://en.wikipedia.org/wiki/Foo_(bar)"), "balanced-paren href kept intact: {out}");
307    }
308
309    #[test]
310    fn reference_link_label_dropped_definition_scanned() {
311        let out = strip_md_link_claims("[https://trusted.com][1]\n[1]: https://evil.io");
312        assert!(!out.contains("trusted.com"), "reflink claim must not reach the scan: {out}");
313        assert!(out.contains("https://evil.io"), "definition URL stays scannable: {out}");
314    }
315
316    #[test]
317    fn multibyte_label_no_panic() {
318        let out = strip_md_link_claims("[🔒 sécurisé — café](https://evil.io) 日本語");
319        assert!(out.contains("https://evil.io"));
320        assert!(out.contains("日本語"));
321    }
322
323    // ========================================================================
324    // Valid public URLs — should pass
325    // ========================================================================
326
327    #[test]
328    fn valid_public_https_url_passes() {
329        assert!(validate_url_not_private("https://example.com/path").is_ok(),
330            "https://example.com should be allowed");
331    }
332
333    #[test]
334    fn valid_public_http_url_passes() {
335        assert!(validate_url_not_private("http://example.com").is_ok(),
336            "http://example.com should be allowed");
337    }
338
339    #[test]
340    fn valid_public_ip_8888_passes() {
341        assert!(validate_url_not_private("https://8.8.8.8/dns").is_ok(),
342            "8.8.8.8 (Google DNS) is a public IP and should be allowed");
343    }
344
345    #[test]
346    fn valid_public_ip_1111_passes() {
347        assert!(validate_url_not_private("https://1.1.1.1").is_ok(),
348            "1.1.1.1 (Cloudflare DNS) is a public IP and should be allowed");
349    }
350
351    #[test]
352    fn valid_url_with_port_passes() {
353        assert!(validate_url_not_private("https://example.com:8080/api").is_ok(),
354            "URL with port on public domain should be allowed");
355    }
356
357    // ========================================================================
358    // Loopback addresses — should be rejected
359    // ========================================================================
360
361    #[test]
362    fn localhost_rejected() {
363        let result = validate_url_not_private("http://localhost/secret");
364        assert!(result.is_err(), "localhost should be rejected");
365    }
366
367    #[test]
368    fn ip_127_0_0_1_rejected() {
369        let result = validate_url_not_private("http://127.0.0.1/admin");
370        assert!(result.is_err(), "127.0.0.1 (loopback) should be rejected");
371    }
372
373    #[test]
374    fn ip_127_255_255_255_rejected() {
375        let result = validate_url_not_private("http://127.255.255.255");
376        assert!(result.is_err(), "127.255.255.255 (loopback range) should be rejected");
377    }
378
379    // ========================================================================
380    // Private IP ranges — should be rejected
381    // ========================================================================
382
383    #[test]
384    fn private_class_a_10_rejected() {
385        let result = validate_url_not_private("http://10.0.0.1/internal");
386        assert!(result.is_err(), "10.0.0.1 (private class A) should be rejected");
387    }
388
389    #[test]
390    fn private_class_b_172_16_rejected() {
391        let result = validate_url_not_private("http://172.16.0.1/internal");
392        assert!(result.is_err(), "172.16.0.1 (private class B) should be rejected");
393    }
394
395    #[test]
396    fn private_class_b_172_31_rejected() {
397        let result = validate_url_not_private("http://172.31.255.255");
398        assert!(result.is_err(), "172.31.255.255 (private class B upper bound) should be rejected");
399    }
400
401    #[test]
402    fn private_class_c_192_168_rejected() {
403        let result = validate_url_not_private("http://192.168.1.1/router");
404        assert!(result.is_err(), "192.168.1.1 (private class C) should be rejected");
405    }
406
407    // ========================================================================
408    // Special addresses — should be rejected
409    // ========================================================================
410
411    #[test]
412    fn link_local_169_254_rejected() {
413        let result = validate_url_not_private("http://169.254.1.1");
414        assert!(result.is_err(), "169.254.1.1 (link-local) should be rejected");
415    }
416
417    #[test]
418    fn cgn_100_64_rejected() {
419        let result = validate_url_not_private("http://100.64.0.1");
420        assert!(result.is_err(), "100.64.0.1 (CGN / shared address space) should be rejected");
421    }
422
423    #[test]
424    fn cgn_100_127_rejected() {
425        let result = validate_url_not_private("http://100.127.255.255");
426        assert!(result.is_err(), "100.127.255.255 (CGN upper bound) should be rejected");
427    }
428
429    #[test]
430    fn broadcast_255_rejected() {
431        let result = validate_url_not_private("http://255.255.255.255");
432        assert!(result.is_err(), "255.255.255.255 (broadcast) should be rejected");
433    }
434
435    #[test]
436    fn unspecified_0_0_0_0_rejected() {
437        let result = validate_url_not_private("http://0.0.0.0");
438        assert!(result.is_err(), "0.0.0.0 (unspecified) should be rejected");
439    }
440
441    // ========================================================================
442    // IPv6 addresses — should be rejected
443    // ========================================================================
444
445    #[test]
446    fn ipv6_loopback_rejected() {
447        let result = validate_url_not_private("http://[::1]/secret");
448        assert!(result.is_err(), "::1 (IPv6 loopback) should be rejected");
449    }
450
451    #[test]
452    fn ipv6_unique_local_fc00_rejected() {
453        let result = validate_url_not_private("http://[fc00::1]");
454        assert!(result.is_err(), "fc00::1 (IPv6 unique-local) should be rejected");
455    }
456
457    #[test]
458    fn ipv6_unique_local_fd00_rejected() {
459        let result = validate_url_not_private("http://[fd00::1]");
460        assert!(result.is_err(), "fd00::1 (IPv6 unique-local) should be rejected");
461    }
462
463    #[test]
464    fn ipv6_link_local_fe80_rejected() {
465        let result = validate_url_not_private("http://[fe80::1]");
466        assert!(result.is_err(), "fe80::1 (IPv6 link-local) should be rejected");
467    }
468
469    #[test]
470    fn ipv4_mapped_ipv6_loopback_rejected() {
471        let result = validate_url_not_private("http://[::ffff:127.0.0.1]");
472        assert!(result.is_err(), "::ffff:127.0.0.1 (IPv4-mapped loopback) should be rejected");
473    }
474
475    #[test]
476    fn ipv4_mapped_ipv6_private_rejected() {
477        let result = validate_url_not_private("http://[::ffff:192.168.1.1]");
478        assert!(result.is_err(), "::ffff:192.168.1.1 (IPv4-mapped private) should be rejected");
479    }
480
481    // ========================================================================
482    // Domain name restrictions
483    // ========================================================================
484
485    #[test]
486    fn dot_local_domain_rejected() {
487        let result = validate_url_not_private("http://mydevice.local/api");
488        assert!(result.is_err(), ".local domain should be rejected");
489    }
490
491    #[test]
492    fn dot_internal_domain_rejected() {
493        let result = validate_url_not_private("http://service.internal/health");
494        assert!(result.is_err(), ".internal domain should be rejected");
495    }
496
497    // ========================================================================
498    // Scheme restrictions
499    // ========================================================================
500
501    #[test]
502    fn ftp_scheme_rejected() {
503        let result = validate_url_not_private("ftp://example.com/file.txt");
504        assert!(result.is_err(), "ftp:// scheme should be rejected");
505        assert_eq!(result.unwrap_err(), "Only HTTP(S) URLs are allowed");
506    }
507
508    #[test]
509    fn file_scheme_rejected() {
510        let result = validate_url_not_private("file:///etc/passwd");
511        assert!(result.is_err(), "file:// scheme should be rejected");
512        assert_eq!(result.unwrap_err(), "Only HTTP(S) URLs are allowed");
513    }
514
515    #[test]
516    fn javascript_scheme_rejected() {
517        let result = validate_url_not_private("javascript:alert(1)");
518        assert!(result.is_err(), "javascript: scheme should be rejected");
519    }
520
521    #[test]
522    fn data_scheme_rejected() {
523        let result = validate_url_not_private("data:text/html,<h1>hi</h1>");
524        assert!(result.is_err(), "data: scheme should be rejected");
525    }
526
527    // ========================================================================
528    // Missing / invalid URL
529    // ========================================================================
530
531    #[test]
532    fn no_host_rejected() {
533        // http:// with no host is actually an invalid URL for the url crate
534        let result = validate_url_not_private("http://");
535        assert!(result.is_err(), "URL with no host should be rejected");
536    }
537
538    #[test]
539    fn invalid_url_rejected() {
540        let result = validate_url_not_private("not a url at all");
541        assert!(result.is_err(), "invalid URL string should be rejected");
542        assert_eq!(result.unwrap_err(), "Invalid URL");
543    }
544
545    #[test]
546    fn empty_string_rejected() {
547        let result = validate_url_not_private("");
548        assert!(result.is_err(), "empty string should be rejected");
549    }
550
551    // ========================================================================
552    // Edge cases
553    // ========================================================================
554
555    #[test]
556    fn cgn_100_63_not_rejected() {
557        // 100.63.x.x is NOT in the CGN range (100.64-100.127)
558        assert!(validate_url_not_private("http://100.63.255.255").is_ok(),
559            "100.63.255.255 is outside CGN range and should be allowed");
560    }
561
562    #[test]
563    fn cgn_100_128_not_rejected() {
564        // 100.128.x.x is NOT in the CGN range
565        assert!(validate_url_not_private("http://100.128.0.1").is_ok(),
566            "100.128.0.1 is outside CGN range and should be allowed");
567    }
568
569    #[test]
570    fn private_172_15_not_rejected() {
571        // 172.15.x.x is NOT private (private is 172.16-172.31)
572        assert!(validate_url_not_private("http://172.15.255.255").is_ok(),
573            "172.15.255.255 is outside private class B range and should be allowed");
574    }
575
576    #[test]
577    fn private_172_32_not_rejected() {
578        // 172.32.x.x is NOT private
579        assert!(validate_url_not_private("http://172.32.0.1").is_ok(),
580            "172.32.0.1 is outside private class B range and should be allowed");
581    }
582}
583
584// ============================================================================
585// Remote File Size
586// ============================================================================
587
588/// Get the size of a remote file via HEAD request or Range fallback.
589/// Returns None if the URL is private, unreachable, or size can't be determined.
590pub async fn get_remote_file_size(url: &str) -> Option<u64> {
591    validate_url_not_private(url).ok()?;
592    let client = build_http_client(std::time::Duration::from_secs(8)).ok()?;
593
594    // Method 1: HEAD request
595    if let Ok(head_res) = client.head(url).send().await {
596        if let Some(length) = head_res.content_length() {
597            if length > 0 {
598                return Some(length);
599            }
600        }
601    }
602
603    // Method 2: Range request fallback
604    if let Ok(partial_res) = client
605        .get(url)
606        .header("Range", "bytes=0-1")
607        .send()
608        .await
609    {
610        if let Some(content_range) = partial_res.headers().get("content-range") {
611            if let Ok(range_str) = content_range.to_str() {
612                if let Some(size_part) = range_str.split('/').nth(1) {
613                    if let Ok(size) = size_part.parse::<u64>() {
614                        return Some(size);
615                    }
616                }
617            }
618        }
619        if let Some(length) = partial_res.content_length() {
620            if length > 100 {
621                return Some(length);
622            }
623        }
624    }
625
626    None
627}