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;
9
10const DEFAULT_TIMEOUT: Duration = Duration::from_secs(10);
11const DEFAULT_USER_AGENT: &str = concat!("openauth-oauth/", env!("CARGO_PKG_VERSION"));
12const SENSITIVE_OAUTH_FIELDS: &[&str] = &[
13    "access_token",
14    "refresh_token",
15    "id_token",
16    "client_secret",
17    "client_assertion",
18    "subject_token",
19    "device_code",
20    "code",
21    "token",
22    "authorization",
23];
24
25#[derive(Debug, Clone)]
26pub struct OAuthHttpClient {
27    client: Client,
28}
29
30#[derive(Debug, Clone, PartialEq, Eq)]
31pub struct OAuthHttpClientConfig {
32    pub timeout: Duration,
33    pub user_agent: Option<String>,
34}
35
36impl Default for OAuthHttpClientConfig {
37    fn default() -> Self {
38        Self {
39            timeout: DEFAULT_TIMEOUT,
40            user_agent: Some(DEFAULT_USER_AGENT.to_owned()),
41        }
42    }
43}
44
45impl OAuthHttpClient {
46    pub fn new(client: Client) -> Self {
47        Self { client }
48    }
49
50    pub fn default_client() -> Result<Self, OAuthError> {
51        Self::from_config(OAuthHttpClientConfig::default())
52    }
53
54    pub fn from_config(config: OAuthHttpClientConfig) -> Result<Self, OAuthError> {
55        if config.timeout.is_zero() {
56            return Err(OAuthError::InvalidConfiguration(
57                "HTTP timeout must be greater than zero".to_owned(),
58            ));
59        }
60        let mut builder = Client::builder().timeout(config.timeout);
61        if let Some(user_agent) = config.user_agent {
62            builder = builder.user_agent(user_agent);
63        }
64        builder.build().map(Self::new).map_err(Into::into)
65    }
66
67    pub async fn get_bytes(&self, url: &str) -> Result<Vec<u8>, OAuthError> {
68        let response = self
69            .client
70            .get(url)
71            .header("accept", "application/json")
72            .send()
73            .await?;
74        response_bytes(response).await
75    }
76
77    pub async fn post_form(
78        &self,
79        token_endpoint: &str,
80        request: OAuthFormRequest,
81    ) -> Result<Value, OAuthError> {
82        let mut builder = self.client.post(token_endpoint);
83        for (key, value) in &request.headers {
84            builder = builder.header(key, value);
85        }
86        let response = builder.body(request.to_form_urlencoded()).send().await?;
87        response_json(response).await
88    }
89}
90
91pub fn default_http_client() -> Result<OAuthHttpClient, OAuthError> {
92    static CLIENT: OnceLock<Result<OAuthHttpClient, String>> = OnceLock::new();
93
94    CLIENT
95        .get_or_init(|| OAuthHttpClient::default_client().map_err(|error| error.to_string()))
96        .clone()
97        .map_err(OAuthError::InvalidConfiguration)
98}
99
100async fn response_bytes(response: Response) -> Result<Vec<u8>, OAuthError> {
101    let status = response.status();
102    let bytes = response.bytes().await?;
103    if status.is_success() {
104        return Ok(bytes.to_vec());
105    }
106    Err(http_status_error(status.as_u16(), &bytes))
107}
108
109async fn response_json(response: Response) -> Result<Value, OAuthError> {
110    let status = response.status();
111    let bytes = response.bytes().await?;
112    let value = serde_json::from_slice::<Value>(&bytes);
113    if status.is_success() {
114        return value.map_err(|error| OAuthError::InvalidResponse(error.to_string()));
115    }
116    if let Ok(value) = value {
117        if let Some(error) = value.get("error").and_then(Value::as_str) {
118            return Err(OAuthError::ErrorResponse {
119                error: error.to_owned(),
120                description: oauth_error_description(redact_error_description(
121                    value.get("error_description").and_then(Value::as_str),
122                )),
123                uri: value
124                    .get("error_uri")
125                    .and_then(Value::as_str)
126                    .map(str::to_owned),
127            });
128        }
129    }
130    Err(http_status_error(status.as_u16(), &bytes))
131}
132
133fn http_status_error(status: u16, body: &[u8]) -> OAuthError {
134    OAuthError::HttpStatus {
135        status,
136        body: redact_body(&String::from_utf8_lossy(body)),
137    }
138}
139
140fn redact_body(body: &str) -> String {
141    if let Ok(mut value) = serde_json::from_str::<Value>(body) {
142        redact_json_value(&mut value);
143        return value.to_string();
144    }
145
146    let lower = body.to_ascii_lowercase();
147    if SENSITIVE_OAUTH_FIELDS.iter().any(|key| lower.contains(key))
148        || lower.contains("bearer ")
149        || lower.contains("basic ")
150    {
151        return "<redacted OAuth response body>".to_owned();
152    }
153    body.to_owned()
154}
155
156fn redact_json_value(value: &mut Value) {
157    match value {
158        Value::Object(object) => {
159            for (key, value) in object {
160                if SENSITIVE_OAUTH_FIELDS
161                    .iter()
162                    .any(|sensitive| key.eq_ignore_ascii_case(sensitive))
163                {
164                    *value = Value::String("<redacted>".to_owned());
165                } else {
166                    redact_json_value(value);
167                }
168            }
169        }
170        Value::Array(values) => {
171            for value in values {
172                redact_json_value(value);
173            }
174        }
175        _ => {}
176    }
177}
178
179fn redact_error_description(description: Option<&str>) -> Option<String> {
180    let description = description?;
181    let lower = description.to_ascii_lowercase();
182    if [
183        "access_token",
184        "refresh_token",
185        "id_token",
186        "client_secret",
187        "client_assertion",
188        "subject_token",
189        "device_code",
190        "authorization",
191        "bearer ",
192        "basic ",
193    ]
194    .iter()
195    .any(|needle| lower.contains(needle))
196    {
197        return Some("<redacted error_description>".to_owned());
198    }
199    Some(description.to_owned())
200}