Skip to main content

subspace_core/
http.rs

1//! The shared HTTP agent (REQ-31), the error type the clients return, and
2//! the retry after HTTP 401 (REQ-22).
3
4use std::sync::{Arc, OnceLock};
5use std::time::Duration;
6
7use ureq::tls::{RootCerts, TlsConfig};
8
9use crate::credentials::{Credential, CredentialError, Credentials};
10
11mod service_url;
12
13pub use service_url::{InvalidUrl, plain_https_url};
14
15pub const TIMEOUT: Duration = Duration::from_secs(30);
16
17/// The body limit for a response that may be large (64 MiB).
18pub const MAX_BODY_BYTES: u64 = 64 * 1024 * 1024;
19
20/// The body limit for an error message or another small body (64 KiB).
21pub const ERROR_BODY_BYTES: u64 = 64 * 1024;
22
23/// The HTTP statuses the clients map, named so the mapping code holds no
24/// bare numbers.
25pub mod status {
26    use ureq::http::StatusCode;
27
28    pub const OK: u16 = StatusCode::OK.as_u16();
29    pub const BAD_REQUEST: u16 = StatusCode::BAD_REQUEST.as_u16();
30    pub const UNAUTHORIZED: u16 = StatusCode::UNAUTHORIZED.as_u16();
31    pub const CONFLICT: u16 = StatusCode::CONFLICT.as_u16();
32    pub const FORBIDDEN: u16 = StatusCode::FORBIDDEN.as_u16();
33    pub const NOT_FOUND: u16 = StatusCode::NOT_FOUND.as_u16();
34    pub const PAYLOAD_TOO_LARGE: u16 = StatusCode::PAYLOAD_TOO_LARGE.as_u16();
35    pub const UNSUPPORTED_MEDIA_TYPE: u16 = StatusCode::UNSUPPORTED_MEDIA_TYPE.as_u16();
36    pub const TOO_MANY_REQUESTS: u16 = StatusCode::TOO_MANY_REQUESTS.as_u16();
37    pub const BAD_GATEWAY: u16 = StatusCode::BAD_GATEWAY.as_u16();
38    pub const GATEWAY_TIMEOUT: u16 = StatusCode::GATEWAY_TIMEOUT.as_u16();
39
40    /// True for a 2xx status.
41    pub fn is_success(status: u16) -> bool {
42        StatusCode::from_u16(status).is_ok_and(|code| code.is_success())
43    }
44
45    /// True for a status that says the service is briefly unavailable, not
46    /// that the request was wrong: a 5xx, 408 or 429. Its body, often a
47    /// gateway's HTML page, says nothing about the request.
48    pub fn is_transient(status: u16) -> bool {
49        StatusCode::from_u16(status).is_ok_and(|code| {
50            code.is_server_error()
51                || code == StatusCode::REQUEST_TIMEOUT
52                || code == StatusCode::TOO_MANY_REQUESTS
53        })
54    }
55}
56
57/// One agent for every client: the platform certificate store (so a proxy
58/// certificate the system trusts is accepted), `HTTPS_PROXY` and `NO_PROXY`
59/// from the environment, and a 30 s timeout. A failure status is returned
60/// as a response, so a client can read the service's error message.
61pub fn agent() -> &'static ureq::Agent {
62    static AGENT: OnceLock<ureq::Agent> = OnceLock::new();
63    AGENT.get_or_init(|| {
64        let tls = TlsConfig::builder()
65            .root_certs(RootCerts::PlatformVerifier)
66            .unversioned_rustls_crypto_provider(Arc::new(
67                rustls::crypto::aws_lc_rs::default_provider(),
68            ))
69            .build();
70        ureq::Agent::config_builder()
71            .timeout_global(Some(TIMEOUT))
72            .http_status_as_error(false)
73            .proxy(ureq::Proxy::try_from_env())
74            .tls_config(tls)
75            .middleware(request_log::RequestLog)
76            .build()
77            .into()
78    })
79}
80
81mod request_log;
82
83/// A failed request. No variant holds a credential.
84#[derive(Debug, thiserror::Error)]
85pub enum Error {
86    /// No credential; the message says where to get one (REQ-22).
87    #[error(transparent)]
88    Credential(#[from] CredentialError),
89    /// The service answered with a failure status.
90    #[error("{message}")]
91    Status { status: u16, message: String },
92    /// The service could not be reached.
93    #[error("{0}")]
94    Network(String),
95}
96
97impl From<ureq::Error> for Error {
98    fn from(error: ureq::Error) -> Self {
99        Self::Network(error.to_string())
100    }
101}
102
103/// Sends a request with a credential from `credential`. After HTTP 401 it
104/// drops the credential, gets one again and retries once (REQ-22). A second
105/// 401 also drops the credential and is returned to the caller.
106pub fn send_with_retry<T>(
107    credentials: &Credentials,
108    credential: impl Fn(&Credentials) -> Result<Credential, CredentialError>,
109    mut send: impl FnMut(&Credential) -> Result<T, Error>,
110) -> Result<T, Error> {
111    let rejected =
112        |result: &Result<T, Error>| matches!(result, Err(Error::Status { status: 401, .. }));
113    let first = credential(credentials)?;
114    let result = send(&first);
115    if !rejected(&result) {
116        return result;
117    }
118    credentials.invalidate(&first);
119    let second = credential(credentials)?;
120    let result = send(&second);
121    if rejected(&result) {
122        credentials.invalidate(&second);
123    }
124    result
125}
126
127#[cfg(test)]
128mod tests {
129    use std::collections::HashSet;
130    use std::sync::Mutex;
131    use std::time::Duration;
132
133    use super::{Error, send_with_retry};
134    use crate::config::Config;
135    use crate::credentials::{Credential, CredentialError, Credentials, Environment, Runner};
136
137    #[test]
138    fn transient_statuses_are_server_errors_timeouts_and_rate_limits() {
139        for status in [500, 502, 503, 504, 408, 429] {
140            assert!(super::status::is_transient(status), "{status}");
141        }
142        for status in [200, 400, 401, 403, 404] {
143            assert!(!super::status::is_transient(status), "{status}");
144        }
145    }
146
147    #[test]
148    fn is_success_covers_the_2xx_range_only() {
149        assert!(super::status::is_success(
150            ureq::http::StatusCode::NON_AUTHORITATIVE_INFORMATION.as_u16()
151        ));
152        assert!(super::status::is_success(
153            ureq::http::StatusCode::OK.as_u16()
154        ));
155        assert!(!super::status::is_success(300));
156        assert!(!super::status::is_success(super::status::BAD_REQUEST));
157        assert!(!super::status::is_success(0));
158    }
159
160    #[test]
161    fn the_shared_agent_builds_once() {
162        assert!(std::ptr::eq(super::agent(), super::agent()));
163    }
164
165    struct NoEnv;
166
167    impl Environment for NoEnv {
168        fn var(&self, _name: &str) -> Option<String> {
169            None
170        }
171    }
172
173    /// `gh` answering `gh-1`, `gh-2`, ... on each call.
174    #[derive(Default)]
175    struct CountingGh(Mutex<u32>);
176
177    impl Runner for CountingGh {
178        fn run(
179            &self,
180            _program: &str,
181            _args: &[&str],
182            _remove: &[&str],
183            _timeout: Duration,
184        ) -> Result<String, String> {
185            let mut count = self.0.lock().unwrap();
186            *count += 1;
187            Ok(format!("gh-{count}\n"))
188        }
189    }
190
191    fn gh_cli(credentials: &Credentials) -> Result<Credential, CredentialError> {
192        credentials.gh_cli("fixture-user")
193    }
194
195    fn rejecting(
196        tokens: &[&str],
197    ) -> impl FnMut(&crate::credentials::Credential) -> Result<String, Error> {
198        let rejected: HashSet<String> = tokens.iter().map(ToString::to_string).collect();
199        move |credential| {
200            let token = credential.value.expose().to_owned();
201            if rejected.contains(&token) {
202                Err(Error::Status {
203                    status: 401,
204                    message: "rejected".into(),
205                })
206            } else {
207                Ok(token)
208            }
209        }
210    }
211
212    #[test]
213    fn a_401_gets_a_fresh_credential_and_retries_once() {
214        let credentials = Credentials::new(&Config::default(), NoEnv, CountingGh::default());
215        let result = send_with_retry(&credentials, gh_cli, rejecting(&["gh-1"]));
216        assert_eq!(result.unwrap(), "gh-2");
217    }
218
219    #[test]
220    fn a_second_401_is_returned() {
221        let credentials = Credentials::new(&Config::default(), NoEnv, CountingGh::default());
222        let result = send_with_retry(&credentials, gh_cli, rejecting(&["gh-1", "gh-2"]));
223        assert!(matches!(result, Err(Error::Status { status: 401, .. })));
224        // Two attempts, and the rejected second token was dropped too.
225        let next = send_with_retry(&credentials, gh_cli, rejecting(&[]));
226        assert_eq!(next.unwrap(), "gh-3");
227    }
228}