Skip to main content

lean_ctx/core/providers/
hardened_http.rs

1use std::time::{Duration, Instant};
2
3const DEFAULT_RESOLVE_TIMEOUT: Duration = Duration::from_secs(5);
4const DEFAULT_CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
5const DEFAULT_RESPONSE_TIMEOUT: Duration = Duration::from_secs(30);
6const DEGRADED_MULTIPLIER: u32 = 2;
7const MAX_RESPONSE_BODY_BYTES: u64 = 10 * 1024 * 1024;
8
9#[cfg(test)]
10pub(crate) mod redirect_tests;
11
12#[derive(Debug, Clone)]
13pub enum HttpOutcome {
14    Success {
15        status: u16,
16        body: String,
17        elapsed_ms: u64,
18    },
19    Timeout {
20        elapsed_ms: u64,
21        phase: String,
22    },
23    NetworkError {
24        message: String,
25        elapsed_ms: u64,
26    },
27    HttpError {
28        status: u16,
29        body: String,
30        elapsed_ms: u64,
31    },
32}
33
34pub struct HardenedClient {
35    agent: ureq::Agent,
36    provider_id: String,
37}
38
39pub fn hardened_agent() -> ureq::Agent {
40    if let Some(remaining) = super::provenance::reuse_time_remaining() {
41        return ureq::config::Config::builder()
42            .tls_config(crate::core::http_client::platform_tls_config())
43            .max_redirects(0)
44            .timeout_global(Some(remaining.max(Duration::from_nanos(1))))
45            .build()
46            .into();
47    }
48    let multiplier = if crate::core::io_health::environment()
49        == crate::core::io_health::IoEnvironment::Degraded
50    {
51        DEGRADED_MULTIPLIER
52    } else {
53        1
54    };
55
56    // Provider credentials include custom headers (for example PRIVATE-TOKEN)
57    // that HTTP clients do not remove on cross-origin redirects. A configured
58    // endpoint is the authority: require the operator to select its final URL.
59    crate::core::http_client::ureq_agent_without_redirects(
60        Some(DEFAULT_RESOLVE_TIMEOUT * multiplier),
61        Some(DEFAULT_CONNECT_TIMEOUT * multiplier),
62        Some(DEFAULT_RESPONSE_TIMEOUT * multiplier),
63    )
64}
65
66impl HardenedClient {
67    pub fn new(provider_id: &str) -> Self {
68        Self {
69            agent: hardened_agent(),
70            provider_id: provider_id.to_owned(),
71        }
72    }
73
74    pub fn get(&self, url: &str) -> HttpOutcome {
75        let request = self.agent.get(url);
76        self.execute_request(|| request.call())
77    }
78
79    pub fn get_with_headers(&self, url: &str, headers: &[(&str, &str)]) -> HttpOutcome {
80        let mut request = self.agent.get(url);
81        for &(key, value) in headers {
82            request = request.header(key, value);
83        }
84        self.execute_request(|| request.call())
85    }
86
87    pub fn post(&self, url: &str, body: &str) -> HttpOutcome {
88        let request = self.agent.post(url);
89        self.execute_request(|| request.send(body))
90    }
91
92    pub fn post_with_headers(
93        &self,
94        url: &str,
95        body: &str,
96        headers: &[(&str, &str)],
97    ) -> HttpOutcome {
98        let mut request = self.agent.post(url);
99        for &(key, value) in headers {
100            request = request.header(key, value);
101        }
102        self.execute_request(|| request.send(body))
103    }
104
105    fn execute_request<F>(&self, request: F) -> HttpOutcome
106    where
107        F: FnOnce() -> Result<ureq::http::Response<ureq::Body>, ureq::Error>,
108    {
109        let started = Instant::now();
110        let response = match request() {
111            Ok(response) => response,
112            Err(error) => return self.error_outcome(error, elapsed_ms(started)),
113        };
114        let status = response.status().as_u16();
115        if !(200..300).contains(&status) {
116            // Neither a Location value nor a server error body is safe context:
117            // either may echo credentials, URLs or private response contents.
118            return HttpOutcome::HttpError {
119                status,
120                body: String::new(),
121                elapsed_ms: elapsed_ms(started),
122            };
123        }
124        let body = match response
125            .into_body()
126            .into_with_config()
127            .limit(MAX_RESPONSE_BODY_BYTES)
128            .read_to_string()
129        {
130            Ok(body) => body,
131            Err(error) => return self.error_outcome(error, elapsed_ms(started)),
132        };
133        let elapsed_ms = elapsed_ms(started);
134
135        HttpOutcome::Success {
136            status,
137            body,
138            elapsed_ms,
139        }
140    }
141
142    fn error_outcome(&self, error: ureq::Error, elapsed_ms: u64) -> HttpOutcome {
143        match error {
144            ureq::Error::Timeout(timeout) => HttpOutcome::Timeout {
145                elapsed_ms,
146                phase: timeout.to_string(),
147            },
148            ureq::Error::StatusCode(status) => HttpOutcome::HttpError {
149                status,
150                body: String::new(),
151                elapsed_ms,
152            },
153            error => HttpOutcome::NetworkError {
154                message: format!("{}: {error}", self.provider_id),
155                elapsed_ms,
156            },
157        }
158    }
159}
160
161impl HttpOutcome {
162    pub fn into_body(self) -> Result<String, String> {
163        match self {
164            Self::Success { body, .. } => Ok(body),
165            Self::Timeout { phase, .. } => Err(format!("timeout during {phase}")),
166            Self::NetworkError { message, .. } => Err(message),
167            Self::HttpError { status, body, .. } => Err(format!("HTTP {status}: {body}")),
168        }
169    }
170
171    pub fn is_success(&self) -> bool {
172        matches!(self, Self::Success { .. })
173    }
174
175    pub fn body(&self) -> Option<&str> {
176        match self {
177            Self::Success { body, .. } => Some(body),
178            _ => None,
179        }
180    }
181
182    pub fn elapsed_ms(&self) -> u64 {
183        match self {
184            Self::Success { elapsed_ms, .. }
185            | Self::Timeout { elapsed_ms, .. }
186            | Self::NetworkError { elapsed_ms, .. }
187            | Self::HttpError { elapsed_ms, .. } => *elapsed_ms,
188        }
189    }
190
191    pub fn into_result(self) -> Result<String, String> {
192        match self {
193            Self::Success { body, .. } => Ok(body),
194            Self::Timeout { phase, .. } => Err(format!("HTTP request timed out during {phase}")),
195            Self::NetworkError { message, .. } => Err(message),
196            Self::HttpError { status, body, .. } => {
197                if body.is_empty() {
198                    Err(format!("HTTP request failed with status {status}"))
199                } else {
200                    Err(format!("HTTP request failed with status {status}: {body}"))
201                }
202            }
203        }
204    }
205}
206
207pub fn provider_get(provider_id: &str, url: &str) -> HttpOutcome {
208    HardenedClient::new(provider_id).get(url)
209}
210
211pub fn provider_get_with_headers(
212    provider_id: &str,
213    url: &str,
214    headers: &[(&str, &str)],
215) -> HttpOutcome {
216    HardenedClient::new(provider_id).get_with_headers(url, headers)
217}
218
219pub fn provider_post(provider_id: &str, url: &str, body: &str) -> HttpOutcome {
220    HardenedClient::new(provider_id).post(url, body)
221}
222
223fn elapsed_ms(started: Instant) -> u64 {
224    u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX)
225}
226
227#[cfg(test)]
228mod tests {
229    use super::{
230        DEFAULT_CONNECT_TIMEOUT, DEFAULT_RESOLVE_TIMEOUT, DEFAULT_RESPONSE_TIMEOUT,
231        DEGRADED_MULTIPLIER, HardenedClient, HttpOutcome, hardened_agent,
232    };
233    use std::io::{Read, Write};
234    use std::net::TcpListener;
235    use std::sync::mpsc::{self, Receiver};
236    use std::time::Duration;
237
238    #[test]
239    fn test_hardened_agent_creates_agent() {
240        let _agent = hardened_agent();
241    }
242
243    #[test]
244    fn test_http_outcome_success_is_success() {
245        let outcome = success_outcome(12);
246        assert!(outcome.is_success());
247    }
248
249    #[test]
250    fn test_http_outcome_timeout_not_success() {
251        let outcome = timeout_outcome(12);
252        assert!(!outcome.is_success());
253    }
254
255    #[test]
256    fn test_http_outcome_network_error_not_success() {
257        let outcome = HttpOutcome::NetworkError {
258            message: "offline".to_owned(),
259            elapsed_ms: 12,
260        };
261        assert!(!outcome.is_success());
262    }
263
264    #[test]
265    fn test_http_outcome_into_result_success() {
266        assert_eq!(success_outcome(12).into_result(), Ok("payload".to_owned()));
267    }
268
269    #[test]
270    fn test_http_outcome_into_result_timeout() {
271        let error = timeout_outcome(12)
272            .into_result()
273            .expect_err("timeout expected");
274        assert!(error.contains("timed out"));
275        assert!(error.contains("connect"));
276    }
277
278    #[test]
279    fn test_http_outcome_into_body_variants() {
280        assert_eq!(success_outcome(12).into_body(), Ok("payload".to_owned()));
281        assert_eq!(
282            timeout_outcome(12).into_body(),
283            Err("timeout during connect".to_owned())
284        );
285        assert_eq!(
286            HttpOutcome::NetworkError {
287                message: "offline".to_owned(),
288                elapsed_ms: 12,
289            }
290            .into_body(),
291            Err("offline".to_owned())
292        );
293        assert_eq!(
294            HttpOutcome::HttpError {
295                status: 503,
296                body: "unavailable".to_owned(),
297                elapsed_ms: 12,
298            }
299            .into_body(),
300            Err("HTTP 503: unavailable".to_owned())
301        );
302    }
303
304    #[test]
305    fn test_get_with_headers() {
306        let (get_url, get_request) = serve_once();
307        let client = HardenedClient::new("test");
308        assert!(
309            client
310                .get_with_headers(&get_url, &[("X-Test-Header", "get-value")])
311                .is_success()
312        );
313        assert!(
314            get_request
315                .recv()
316                .expect("GET request expected")
317                .to_ascii_lowercase()
318                .contains("x-test-header: get-value")
319        );
320    }
321
322    #[test]
323    fn test_http_outcome_body_extraction() {
324        let success = success_outcome(12);
325        let error = timeout_outcome(12);
326        assert_eq!(success.body(), Some("payload"));
327        assert_eq!(error.body(), None);
328    }
329
330    #[test]
331    fn test_http_outcome_elapsed_tracking() {
332        let outcomes = [
333            success_outcome(1),
334            timeout_outcome(2),
335            HttpOutcome::NetworkError {
336                message: "offline".to_owned(),
337                elapsed_ms: 3,
338            },
339            HttpOutcome::HttpError {
340                status: 503,
341                body: "unavailable".to_owned(),
342                elapsed_ms: 4,
343            },
344        ];
345        let elapsed: Vec<u64> = outcomes.iter().map(HttpOutcome::elapsed_ms).collect();
346        assert_eq!(elapsed, [1, 2, 3, 4]);
347    }
348
349    #[test]
350    fn test_degraded_multiplier_value() {
351        assert_eq!(DEGRADED_MULTIPLIER, 2);
352    }
353
354    #[test]
355    fn test_default_timeouts_reasonable() {
356        assert_eq!(DEFAULT_RESOLVE_TIMEOUT, Duration::from_secs(5));
357        assert_eq!(DEFAULT_CONNECT_TIMEOUT, Duration::from_secs(10));
358        assert_eq!(DEFAULT_RESPONSE_TIMEOUT, Duration::from_secs(30));
359    }
360
361    fn success_outcome(elapsed_ms: u64) -> HttpOutcome {
362        HttpOutcome::Success {
363            status: 200,
364            body: "payload".to_owned(),
365            elapsed_ms,
366        }
367    }
368
369    fn timeout_outcome(elapsed_ms: u64) -> HttpOutcome {
370        HttpOutcome::Timeout {
371            elapsed_ms,
372            phase: "connect".to_owned(),
373        }
374    }
375
376    fn serve_once() -> (String, Receiver<String>) {
377        let listener = TcpListener::bind("127.0.0.1:0").expect("test listener should bind");
378        let address = listener
379            .local_addr()
380            .expect("test listener address should exist");
381        let (sender, receiver) = mpsc::channel();
382        std::thread::spawn(move || {
383            let (mut stream, _) = listener.accept().expect("request should connect");
384            let mut buffer = [0_u8; 4096];
385            let length = stream
386                .read(&mut buffer)
387                .expect("request should be readable");
388            sender
389                .send(String::from_utf8_lossy(&buffer[..length]).into_owned())
390                .expect("request should be received");
391            stream
392                .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok")
393                .expect("response should be writable");
394        });
395        (format!("http://{address}/test"), receiver)
396    }
397}