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