Skip to main content

subspace_web/
lib.rs

1//! Bounded web reads and the provider boundary for optional web search.
2
3mod fetch;
4mod rate;
5mod safety;
6mod text;
7
8use chrono::{SecondsFormat, Utc};
9use fetch::{Backend, Response, UreqBackend};
10use rate::Limits;
11use serde::Serialize;
12use serde_json::Value;
13use std::fmt;
14use std::sync::Arc;
15use std::time::{Duration, Instant};
16use url::Url;
17
18const MAX_REDIRECTS: usize = 3;
19const TOTAL_TIMEOUT: Duration = Duration::from_secs(10);
20
21/// One optional search implementation supplied by a host outside this repository.
22pub trait SearchProvider: Send + Sync {
23    fn id(&self) -> &str;
24    fn search(&self, query: &str) -> Result<Value, String>;
25}
26
27#[derive(Clone, Debug, PartialEq, Eq)]
28pub struct Policy {
29    pub allowed_hosts: Vec<String>,
30    pub silent_hosts: Vec<String>,
31}
32
33impl Policy {
34    pub fn allows_silently(&self, url: &str) -> bool {
35        safety::parsed_host(url).is_ok_and(|host| safety::host_allowed(&host, &self.silent_hosts))
36    }
37}
38
39#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
40pub struct WebReadResult {
41    pub source: &'static str,
42    pub untrusted: bool,
43    pub url: String,
44    pub final_url: String,
45    pub fetched_at: String,
46    pub content_type: String,
47    pub text: String,
48    pub truncated: bool,
49}
50
51#[derive(Clone)]
52pub struct Client {
53    policy: Policy,
54    backend: Arc<dyn Backend>,
55    limits: Limits,
56}
57
58impl Client {
59    pub fn new(policy: Policy) -> Self {
60        Self {
61            policy,
62            backend: Arc::new(UreqBackend),
63            limits: Limits::shared(),
64        }
65    }
66
67    pub fn read(&self, requested: &str) -> Result<WebReadResult, String> {
68        self.limits.take()?;
69        let started = Instant::now();
70        let initial = safety::validate_url(requested, &self.policy.allowed_hosts)?;
71        self.follow(requested, initial, started)
72    }
73
74    fn follow(
75        &self,
76        requested: &str,
77        mut current: Url,
78        started: Instant,
79    ) -> Result<WebReadResult, String> {
80        for redirects in 0..=MAX_REDIRECTS {
81            let response = self
82                .backend
83                .get(&current, TOTAL_TIMEOUT.saturating_sub(started.elapsed()))?;
84            if let Some(location) = response.location {
85                current = self.redirect(&current, &location, redirects)?;
86                continue;
87            }
88            return result(requested, current, response);
89        }
90        Err("web_read redirect handling failed".into())
91    }
92
93    fn redirect(&self, current: &Url, location: &str, count: usize) -> Result<Url, String> {
94        if count == MAX_REDIRECTS {
95            return Err("web_read refused more than three redirects".into());
96        }
97        let next = current
98            .join(location)
99            .map_err(|_| "web_read received an invalid redirect")?;
100        safety::validate_url(next.as_str(), &self.policy.allowed_hosts)
101    }
102
103    pub fn policy(&self) -> &Policy {
104        &self.policy
105    }
106
107    #[cfg(test)]
108    fn with_backend(policy: Policy, backend: impl Backend + 'static) -> Self {
109        Self {
110            policy,
111            backend: Arc::new(backend),
112            limits: Limits::isolated(),
113        }
114    }
115}
116
117fn result(requested: &str, current: Url, response: Response) -> Result<WebReadResult, String> {
118    let content_type = text::accepted_content_type(&response.content_type)?;
119    let (body, truncated) = text::bounded_text(response.body);
120    Ok(WebReadResult {
121        source: "web",
122        untrusted: true,
123        url: requested.to_owned(),
124        final_url: current.into(),
125        fetched_at: Utc::now().to_rfc3339_opts(SecondsFormat::Secs, true),
126        content_type: content_type.to_owned(),
127        text: text::strip_active_content(&body, content_type),
128        truncated,
129    })
130}
131
132impl fmt::Debug for Client {
133    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
134        formatter
135            .debug_struct("Client")
136            .field("policy", &self.policy)
137            .finish_non_exhaustive()
138    }
139}
140
141#[cfg(test)]
142mod tests;