kcode-web-fetch 0.1.2

Bounded public-web fetching with SSRF protection and readable text extraction
Documentation
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
//! Bounded public-web fetching with SSRF protection and text extraction.

#![deny(missing_docs)]
#![forbid(unsafe_code)]

use std::{
    error::Error as StdError,
    fmt,
    net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr},
    time::{Duration, SystemTime},
};

use reqwest::{Client, StatusCode, Url, header};

/// Stable web-fetch failure classification.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ErrorKind {
    /// The URL or limits were invalid.
    InvalidInput,
    /// The URL did not resolve exclusively to public web addresses.
    UnsafeDestination,
    /// The request exceeded its configured timeout.
    Timeout,
    /// The destination could not be reached or returned malformed transport data.
    Transport,
    /// The destination returned a non-success HTTP status.
    HttpStatus,
    /// The destination returned a non-text content type.
    UnsupportedContent,
    /// The page contained no readable text.
    EmptyContent,
}

/// A sanitized URL, transport, HTTP, or content failure.
#[derive(Debug)]
pub struct Error {
    kind: ErrorKind,
    message: String,
    status: Option<u16>,
}

impl Error {
    fn new(kind: ErrorKind, message: impl Into<String>) -> Self {
        Self {
            kind,
            message: message.into(),
            status: None,
        }
    }

    fn with_status(mut self, status: StatusCode) -> Self {
        self.status = Some(status.as_u16());
        self
    }

    /// Returns the stable failure classification.
    pub const fn kind(&self) -> ErrorKind {
        self.kind
    }

    /// Returns the destination HTTP status, when one caused the failure.
    pub const fn status(&self) -> Option<u16> {
        self.status
    }

    /// Returns the sanitized failure detail.
    pub fn message(&self) -> &str {
        &self.message
    }
}

impl fmt::Display for Error {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(&self.message)
    }
}

impl StdError for Error {}

/// Result type returned by web-fetch operations.
pub type Result<T> = std::result::Result<T, Error>;

/// Resource and redirect limits applied to every fetch.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct FetchLimits {
    /// Timeout applied to each HTTP request.
    pub request_timeout: Duration,
    /// Maximum downloaded response bytes.
    pub max_bytes: usize,
    /// Maximum returned Unicode characters.
    pub max_characters: usize,
    /// Maximum manually validated redirects.
    pub max_redirects: usize,
}

impl Default for FetchLimits {
    fn default() -> Self {
        Self {
            request_timeout: Duration::from_secs(90),
            max_bytes: 2_000_000,
            max_characters: 50_000,
            max_redirects: 5,
        }
    }
}

/// A fetched page converted into readable text.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct FetchedPage {
    /// Final URL after validated redirects.
    pub url: String,
    /// HTML title, when one was present.
    pub title: Option<String>,
    /// Normalized response media type without parameters.
    pub content_type: String,
    /// Readable text content.
    pub content: String,
    /// Whether byte or character limits truncated the page.
    pub truncated: bool,
    /// Local time at which retrieval completed.
    pub retrieved_at: SystemTime,
}

/// Cloneable public-web fetcher.
#[derive(Clone, Debug)]
pub struct WebFetcher {
    limits: FetchLimits,
}

impl WebFetcher {
    /// Constructs a fetcher after validating nonzero limits.
    pub fn new(limits: FetchLimits) -> Result<Self> {
        if limits.request_timeout.is_zero() || limits.max_bytes == 0 || limits.max_characters == 0 {
            return Err(Error::new(
                ErrorKind::InvalidInput,
                "web-fetch timeout and content limits must be greater than zero",
            ));
        }
        Ok(Self { limits })
    }

    /// Fetches one public HTTP(S) URL and returns bounded readable text.
    pub async fn fetch(&self, value: &str) -> Result<FetchedPage> {
        let requested = parse_public_web_url(value.trim())?;
        let fetched = fetch_page(&requested, &self.limits).await?;
        let raw = String::from_utf8_lossy(&fetched.body);
        let title = is_html_content(&fetched.content_type)
            .then(|| extract_html_title(&raw))
            .flatten();
        let readable = if is_html_content(&fetched.content_type) {
            html2text::from_read(raw.as_bytes(), 100).map_err(|_| {
                Error::new(
                    ErrorKind::Transport,
                    "the page could not be converted to readable text",
                )
            })?
        } else {
            raw.into_owned()
        };
        let (content, character_truncated) =
            truncate_characters(readable.trim(), self.limits.max_characters);
        if content.is_empty() {
            return Err(Error::new(
                ErrorKind::EmptyContent,
                "the page contained no readable text",
            ));
        }
        Ok(FetchedPage {
            url: fetched.url.to_string(),
            title,
            content_type: fetched.content_type,
            content,
            truncated: fetched.truncated || character_truncated,
            retrieved_at: SystemTime::now(),
        })
    }
}

impl Default for WebFetcher {
    fn default() -> Self {
        Self::new(FetchLimits::default()).expect("default web-fetch limits are valid")
    }
}

struct RawPage {
    url: Url,
    content_type: String,
    body: Vec<u8>,
    truncated: bool,
}

async fn fetch_page(url: &Url, limits: &FetchLimits) -> Result<RawPage> {
    let mut current = url.clone();
    for redirect_count in 0..=limits.max_redirects {
        let client = safe_client(&current, limits.request_timeout).await?;
        let mut response = client
            .get(current.clone())
            .header(
                header::ACCEPT,
                "text/html,application/xhtml+xml,text/plain,application/json;q=0.8",
            )
            .send()
            .await
            .map_err(transport_error)?;
        if response.status().is_redirection() {
            if redirect_count == limits.max_redirects {
                return Err(Error::new(
                    ErrorKind::Transport,
                    "the page exceeded the redirect limit",
                ));
            }
            let location = response
                .headers()
                .get(header::LOCATION)
                .and_then(|value| value.to_str().ok())
                .ok_or_else(|| {
                    Error::new(
                        ErrorKind::Transport,
                        "the page returned an invalid redirect",
                    )
                })?;
            current = parse_public_web_url(
                current
                    .join(location)
                    .map_err(|_| {
                        Error::new(
                            ErrorKind::Transport,
                            "the page returned an invalid redirect URL",
                        )
                    })?
                    .as_str(),
            )?;
            continue;
        }
        if !response.status().is_success() {
            let status = response.status();
            return Err(Error::new(
                ErrorKind::HttpStatus,
                format!("the page returned HTTP {status}"),
            )
            .with_status(status));
        }
        let content_type = response
            .headers()
            .get(header::CONTENT_TYPE)
            .and_then(|value| value.to_str().ok())
            .unwrap_or("application/octet-stream")
            .split(';')
            .next()
            .unwrap_or("application/octet-stream")
            .trim()
            .to_ascii_lowercase();
        if !is_supported_text_content(&content_type) {
            return Err(Error::new(
                ErrorKind::UnsupportedContent,
                format!("the page returned unsupported content type {content_type}"),
            ));
        }
        let mut body = Vec::new();
        let mut truncated = false;
        while let Some(chunk) = response.chunk().await.map_err(transport_error)? {
            let remaining = limits.max_bytes.saturating_sub(body.len());
            if chunk.len() > remaining {
                body.extend_from_slice(&chunk[..remaining]);
                truncated = true;
                break;
            }
            body.extend_from_slice(&chunk);
            if body.len() == limits.max_bytes {
                truncated = true;
                break;
            }
        }
        return Ok(RawPage {
            url: current,
            content_type,
            body,
            truncated,
        });
    }
    unreachable!("redirect loop returns or continues within its bound")
}

fn transport_error(error: reqwest::Error) -> Error {
    if error.is_timeout() {
        Error::new(ErrorKind::Timeout, "the page fetch timed out")
    } else {
        Error::new(ErrorKind::Transport, "the page could not be fetched")
    }
}

fn parse_public_web_url(value: &str) -> Result<Url> {
    if value.is_empty() || value.len() > 4_096 {
        return Err(Error::new(
            ErrorKind::InvalidInput,
            "URL must contain between 1 and 4096 bytes",
        ));
    }
    let url = Url::parse(value)
        .map_err(|_| Error::new(ErrorKind::InvalidInput, "URL must be absolute"))?;
    if !matches!(url.scheme(), "http" | "https") {
        return Err(Error::new(
            ErrorKind::InvalidInput,
            "URL must use HTTP or HTTPS",
        ));
    }
    if !url.username().is_empty() || url.password().is_some() {
        return Err(Error::new(
            ErrorKind::InvalidInput,
            "URL must not contain credentials",
        ));
    }
    let host = url
        .host_str()
        .ok_or_else(|| Error::new(ErrorKind::InvalidInput, "URL must contain a host"))?;
    let lookup_host = host.trim_start_matches('[').trim_end_matches(']');
    let normalized = lookup_host.trim_end_matches('.').to_ascii_lowercase();
    if normalized == "localhost" || normalized.ends_with(".localhost") {
        return Err(unsafe_destination());
    }
    if !matches!(url.port_or_known_default(), Some(80 | 443)) {
        return Err(Error::new(
            ErrorKind::InvalidInput,
            "URL must use standard HTTP or HTTPS ports",
        ));
    }
    if lookup_host
        .parse::<IpAddr>()
        .is_ok_and(|address| !is_public_ip(address))
    {
        return Err(unsafe_destination());
    }
    Ok(url)
}

fn unsafe_destination() -> Error {
    Error::new(
        ErrorKind::UnsafeDestination,
        "URL does not refer to a public web destination",
    )
}

async fn safe_client(url: &Url, timeout: Duration) -> Result<Client> {
    let host = url
        .host_str()
        .ok_or_else(|| Error::new(ErrorKind::InvalidInput, "URL must contain a host"))?;
    let lookup_name = host.trim_start_matches('[').trim_end_matches(']');
    let port = url
        .port_or_known_default()
        .ok_or_else(|| Error::new(ErrorKind::InvalidInput, "URL must contain a valid port"))?;
    let addresses = tokio::net::lookup_host((lookup_name, port))
        .await
        .map_err(|_| Error::new(ErrorKind::Transport, "the page host could not be resolved"))?
        .collect::<Vec<SocketAddr>>();
    if addresses.is_empty() || addresses.iter().any(|address| !is_public_ip(address.ip())) {
        return Err(unsafe_destination());
    }
    Client::builder()
        .timeout(timeout)
        .redirect(reqwest::redirect::Policy::none())
        .retry(reqwest::retry::never())
        .referer(false)
        .no_proxy()
        .user_agent(concat!("kcode-web-fetch/", env!("CARGO_PKG_VERSION")))
        .resolve_to_addrs(lookup_name, &addresses)
        .build()
        .map_err(|_| {
            Error::new(
                ErrorKind::Transport,
                "the safe page-fetch client could not be created",
            )
        })
}

fn is_public_ip(address: IpAddr) -> bool {
    match address {
        IpAddr::V4(address) => is_public_ipv4(address),
        IpAddr::V6(address) => is_public_ipv6(address),
    }
}

fn is_public_ipv4(address: Ipv4Addr) -> bool {
    let [a, b, c, _] = address.octets();
    !(a == 0
        || a == 10
        || a == 127
        || (a == 100 && (64..=127).contains(&b))
        || (a == 169 && b == 254)
        || (a == 172 && (16..=31).contains(&b))
        || (a == 192 && b == 0 && c == 0)
        || (a == 192 && b == 0 && c == 2)
        || (a == 192 && b == 168)
        || (a == 198 && (b == 18 || b == 19))
        || (a == 198 && b == 51 && c == 100)
        || (a == 203 && b == 0 && c == 113)
        || a >= 224)
}

fn is_public_ipv6(address: Ipv6Addr) -> bool {
    if let Some(mapped) = address.to_ipv4_mapped() {
        return is_public_ipv4(mapped);
    }
    let segments = address.segments();
    !(address.is_unspecified()
        || address.is_loopback()
        || address.is_multicast()
        || segments[0] & 0xfe00 == 0xfc00
        || segments[0] & 0xffc0 == 0xfe80
        || (segments[0] == 0x2001 && segments[1] == 0x0db8))
}

fn is_html_content(content_type: &str) -> bool {
    matches!(content_type, "text/html" | "application/xhtml+xml")
}

fn is_supported_text_content(content_type: &str) -> bool {
    is_html_content(content_type)
        || content_type.starts_with("text/")
        || content_type == "application/json"
}

fn extract_html_title(html: &str) -> Option<String> {
    let lowercase = html.to_ascii_lowercase();
    let start = lowercase.find("<title")?;
    let content_start = lowercase[start..].find('>')? + start + 1;
    let end = lowercase[content_start..].find("</title>")? + content_start;
    let title = html[content_start..end]
        .split_whitespace()
        .collect::<Vec<_>>()
        .join(" ");
    (!title.is_empty()).then_some(title)
}

fn truncate_characters(value: &str, limit: usize) -> (String, bool) {
    let mut iter = value.char_indices();
    let Some((boundary, _)) = iter.nth(limit) else {
        return (value.to_owned(), false);
    };
    (value[..boundary].trim_end().to_owned(), true)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn private_and_credentialed_urls_are_rejected() {
        for value in [
            "http://127.0.0.1/",
            "http://[::1]/",
            "http://localhost/",
            "https://user:secret@example.com/",
            "file:///etc/passwd",
            "https://example.com:8443/",
        ] {
            assert!(parse_public_web_url(value).is_err(), "accepted {value}");
        }
        assert!(parse_public_web_url("https://example.com/path").is_ok());
    }

    #[test]
    fn readable_helpers_are_bounded() {
        assert_eq!(
            extract_html_title("<TITLE>  Example page </TITLE>"),
            Some("Example page".into())
        );
        assert_eq!(truncate_characters("éclair", 2), ("éc".into(), true));
        assert_eq!(truncate_characters("short", 20), ("short".into(), false));
    }
}