Skip to main content

openauth_oauth/oauth2/
http.rs

1use std::sync::OnceLock;
2use std::time::Duration;
3
4use reqwest::{Client, Response};
5use serde_json::Value;
6
7use super::error::{oauth_error_description, OAuthError};
8use super::request::OAuthFormRequest;
9use super::ssrf::{ssrf_guarded_client_builder, url_host_is_blocked_ip};
10
11const DEFAULT_TIMEOUT: Duration = Duration::from_secs(10);
12const DEFAULT_USER_AGENT: &str = concat!("openauth-oauth/", env!("CARGO_PKG_VERSION"));
13const SENSITIVE_OAUTH_FIELDS: &[&str] = &[
14    "access_token",
15    "refresh_token",
16    "id_token",
17    "client_secret",
18    "client_assertion",
19    "subject_token",
20    "device_code",
21    "code",
22    "token",
23    "authorization",
24];
25
26#[derive(Debug, Clone)]
27pub struct OAuthHttpClient {
28    client: Client,
29    /// When `false`, requests whose URL host is a literal private/internal IP
30    /// are rejected at the request boundary, closing the SSRF gap that the
31    /// custom DNS resolver cannot see (reqwest does not resolve literal IPs).
32    allow_private_ips: bool,
33}
34
35#[derive(Debug, Clone, PartialEq, Eq)]
36pub struct OAuthHttpClientConfig {
37    pub timeout: Duration,
38    pub user_agent: Option<String>,
39    /// When `false` (the default), the client blocks requests that resolve to
40    /// private, loopback, or otherwise non-public IP addresses to mitigate
41    /// SSRF. Set to `true` only for deployments that intentionally talk to
42    /// internal identity providers.
43    pub allow_private_ips: bool,
44}
45
46impl Default for OAuthHttpClientConfig {
47    fn default() -> Self {
48        Self {
49            timeout: DEFAULT_TIMEOUT,
50            user_agent: Some(DEFAULT_USER_AGENT.to_owned()),
51            allow_private_ips: false,
52        }
53    }
54}
55
56impl OAuthHttpClient {
57    /// Wraps a caller-supplied `reqwest::Client`.
58    ///
59    /// Injected clients are treated as explicitly permissive (no
60    /// request-boundary IP guard) because the caller owns the client's SSRF
61    /// policy; this keeps custom clients usable for tests and intentionally
62    /// internal deployments. Use [`OAuthHttpClient::from_config`] to obtain a
63    /// guarded client.
64    pub fn new(client: Client) -> Self {
65        Self {
66            client,
67            allow_private_ips: true,
68        }
69    }
70
71    /// Returns the underlying `reqwest::Client`.
72    ///
73    /// Useful for callers that must issue requests outside the OAuth form-post
74    /// helpers (for example OIDC discovery, JWKS, or userinfo fetches) while
75    /// sharing the same SSRF guard, timeout, and connection pool.
76    pub fn reqwest_client(&self) -> &Client {
77        &self.client
78    }
79
80    pub fn default_client() -> Result<Self, OAuthError> {
81        Self::from_config(OAuthHttpClientConfig::default())
82    }
83
84    pub fn from_config(config: OAuthHttpClientConfig) -> Result<Self, OAuthError> {
85        if config.timeout.is_zero() {
86            return Err(OAuthError::InvalidConfiguration(
87                "HTTP timeout must be greater than zero".to_owned(),
88            ));
89        }
90        let mut builder = if config.allow_private_ips {
91            Client::builder()
92        } else {
93            ssrf_guarded_client_builder()
94        }
95        .timeout(config.timeout);
96        if let Some(user_agent) = config.user_agent {
97            builder = builder.user_agent(user_agent);
98        }
99        builder
100            .build()
101            .map(|client| Self {
102                client,
103                allow_private_ips: config.allow_private_ips,
104            })
105            .map_err(Into::into)
106    }
107
108    /// Rejects request URLs whose host is a literal blocked IP unless this
109    /// client is explicitly permissive. `reqwest` connects to literal-IP URLs
110    /// without consulting the SSRF DNS guard, so this closes that gap.
111    fn ensure_request_url_allowed(&self, url: &str) -> Result<(), OAuthError> {
112        if !self.allow_private_ips && url_host_is_blocked_ip(url) {
113            return Err(OAuthError::BlockedRequestUrl);
114        }
115        Ok(())
116    }
117
118    pub async fn get_bytes(&self, url: &str) -> Result<Vec<u8>, OAuthError> {
119        self.get_bytes_with_headers(url, &[]).await
120    }
121
122    pub async fn get_bytes_with_headers(
123        &self,
124        url: &str,
125        headers: &[(&str, &str)],
126    ) -> Result<Vec<u8>, OAuthError> {
127        self.ensure_request_url_allowed(url)?;
128        let mut builder = self.client.get(url).header("accept", "application/json");
129        for (key, value) in headers {
130            builder = builder.header(*key, *value);
131        }
132        let response = builder.send().await?;
133        response_bytes(response).await
134    }
135
136    pub async fn post_form(
137        &self,
138        token_endpoint: &str,
139        request: OAuthFormRequest,
140    ) -> Result<Value, OAuthError> {
141        self.ensure_request_url_allowed(token_endpoint)?;
142        let mut builder = self.client.post(token_endpoint);
143        for (key, value) in &request.headers {
144            builder = builder.header(key, value);
145        }
146        let response = builder.body(request.to_form_urlencoded()).send().await?;
147        response_json(response).await
148    }
149}
150
151pub fn default_http_client() -> Result<OAuthHttpClient, OAuthError> {
152    static CLIENT: OnceLock<Result<OAuthHttpClient, String>> = OnceLock::new();
153
154    CLIENT
155        .get_or_init(|| OAuthHttpClient::default_client().map_err(|error| error.to_string()))
156        .clone()
157        .map_err(OAuthError::InvalidConfiguration)
158}
159
160async fn response_bytes(response: Response) -> Result<Vec<u8>, OAuthError> {
161    let status = response.status();
162    let bytes = response.bytes().await?;
163    if status.is_success() {
164        return Ok(bytes.to_vec());
165    }
166    Err(http_status_error(status.as_u16(), &bytes))
167}
168
169async fn response_json(response: Response) -> Result<Value, OAuthError> {
170    let status = response.status();
171    let bytes = response.bytes().await?;
172    let value = serde_json::from_slice::<Value>(&bytes);
173    if status.is_success() {
174        return value.map_err(|error| OAuthError::InvalidResponse(error.to_string()));
175    }
176    if let Ok(value) = value {
177        if let Some(error) = value.get("error").and_then(Value::as_str) {
178            return Err(OAuthError::ErrorResponse {
179                error: error.to_owned(),
180                description: oauth_error_description(redact_error_description(
181                    value.get("error_description").and_then(Value::as_str),
182                )),
183                uri: value
184                    .get("error_uri")
185                    .and_then(Value::as_str)
186                    .map(str::to_owned),
187            });
188        }
189    }
190    Err(http_status_error(status.as_u16(), &bytes))
191}
192
193fn http_status_error(status: u16, body: &[u8]) -> OAuthError {
194    OAuthError::HttpStatus {
195        status,
196        body: redact_body(&String::from_utf8_lossy(body)),
197    }
198}
199
200fn redact_body(body: &str) -> String {
201    if let Ok(mut value) = serde_json::from_str::<Value>(body) {
202        redact_json_value(&mut value);
203        return value.to_string();
204    }
205
206    let lower = body.to_ascii_lowercase();
207    if SENSITIVE_OAUTH_FIELDS.iter().any(|key| lower.contains(key))
208        || lower.contains("bearer ")
209        || lower.contains("basic ")
210    {
211        return "<redacted OAuth response body>".to_owned();
212    }
213    body.to_owned()
214}
215
216fn redact_json_value(value: &mut Value) {
217    match value {
218        Value::Object(object) => {
219            for (key, value) in object {
220                if SENSITIVE_OAUTH_FIELDS
221                    .iter()
222                    .any(|sensitive| key.eq_ignore_ascii_case(sensitive))
223                {
224                    *value = Value::String("<redacted>".to_owned());
225                } else {
226                    redact_json_value(value);
227                }
228            }
229        }
230        Value::Array(values) => {
231            for value in values {
232                redact_json_value(value);
233            }
234        }
235        _ => {}
236    }
237}
238
239fn redact_error_description(description: Option<&str>) -> Option<String> {
240    let description = description?;
241    let lower = description.to_ascii_lowercase();
242    if [
243        "access_token",
244        "refresh_token",
245        "id_token",
246        "client_secret",
247        "client_assertion",
248        "subject_token",
249        "device_code",
250        "authorization",
251        "bearer ",
252        "basic ",
253    ]
254    .iter()
255    .any(|needle| lower.contains(needle))
256    {
257        return Some("<redacted error_description>".to_owned());
258    }
259    Some(description.to_owned())
260}