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