forked from matrix-org/matrix-rust-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttp_client.rs
More file actions
190 lines (165 loc) · 6.68 KB
/
http_client.rs
File metadata and controls
190 lines (165 loc) · 6.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
// Copyright 2025 Kévin Commaille
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! HTTP client and helpers for making OAuth 2.0 requests.
use matrix_sdk_base::BoxFuture;
use oauth2::{
AsyncHttpClient, ErrorResponse, HttpClientError, HttpRequest, HttpResponse, RequestTokenError,
};
use oauth2_reqwest::ReqwestClient;
/// An HTTP client for making OAuth 2.0 requests.
#[derive(Debug, Clone)]
pub(super) struct OAuthHttpClient {
pub(super) inner: reqwest::Client,
/// Rewrite HTTPS requests to use HTTP instead.
///
/// This is a workaround to bypass some checks that require an HTTPS URL,
/// but we can only mock HTTP URLs.
#[cfg(test)]
pub(super) insecure_rewrite_https_to_http: bool,
}
impl<'c> AsyncHttpClient<'c> for OAuthHttpClient {
type Error = HttpClientError<reqwest::Error>;
type Future = BoxFuture<'c, Result<HttpResponse, Self::Error>>;
fn call(&'c self, request: HttpRequest) -> Self::Future {
Box::pin(async move {
#[cfg(test)]
let request = if self.insecure_rewrite_https_to_http
&& request.uri().scheme().is_some_and(|scheme| *scheme == http::uri::Scheme::HTTPS)
{
let mut request = request;
let mut uri_parts = request.uri().clone().into_parts();
uri_parts.scheme = Some(http::uri::Scheme::HTTP);
*request.uri_mut() = http::uri::Uri::from_parts(uri_parts)
.expect("reconstructing URI from parts should work");
request
} else {
request
};
let response = ReqwestClient::from(&self.inner).call(request).await?;
Ok(response)
})
}
}
/// Check the status code of the given HTTP response to identify errors.
pub(super) fn check_http_response_status_code<T: ErrorResponse + 'static>(
http_response: &HttpResponse,
) -> Result<(), RequestTokenError<HttpClientError<reqwest::Error>, T>> {
if http_response.status().as_u16() < 400 {
return Ok(());
}
let reason = http_response.body().as_slice();
let error = if reason.is_empty() {
RequestTokenError::Other("server returned an empty error response".to_owned())
} else {
match serde_json::from_slice(reason) {
Ok(error) => RequestTokenError::ServerResponse(error),
Err(error) => RequestTokenError::Other(error.to_string()),
}
};
Err(error)
}
/// Check that the server returned a response with a JSON `Content-Type`.
pub(super) fn check_http_response_json_content_type<T: ErrorResponse + 'static>(
http_response: &HttpResponse,
) -> Result<(), RequestTokenError<HttpClientError<reqwest::Error>, T>> {
let Some(content_type) = http_response.headers().get(http::header::CONTENT_TYPE) else {
return Ok(());
};
if content_type
.to_str()
// Check only the beginning of the content type, because there might be extra
// parameters, like a charset.
.is_ok_and(|ct| ct.to_lowercase().starts_with(mime::APPLICATION_JSON.essence_str()))
{
Ok(())
} else {
Err(RequestTokenError::Other(format!(
"unexpected response Content-Type: {content_type:?}, should be `{}`",
mime::APPLICATION_JSON
)))
}
}
#[cfg(test)]
mod tests {
use assert_matches2::assert_matches;
use oauth2::{RequestTokenError, basic::BasicErrorResponse};
use super::{check_http_response_json_content_type, check_http_response_status_code};
#[test]
fn test_check_http_response_status_code() {
// OK
let response = http::Response::builder().status(200).body(Vec::<u8>::new()).unwrap();
assert_matches!(check_http_response_status_code::<BasicErrorResponse>(&response), Ok(()));
// Error without body.
let response = http::Response::builder().status(404).body(Vec::<u8>::new()).unwrap();
assert_matches!(
check_http_response_status_code::<BasicErrorResponse>(&response),
Err(RequestTokenError::Other(_))
);
// Error with invalid body.
let response =
http::Response::builder().status(404).body(b"invalid error format".to_vec()).unwrap();
assert_matches!(
check_http_response_status_code::<BasicErrorResponse>(&response),
Err(RequestTokenError::Other(_))
);
// Error with valid body.
let response = http::Response::builder()
.status(404)
.body(br#"{"error": "invalid_request"}"#.to_vec())
.unwrap();
assert_matches!(
check_http_response_status_code::<BasicErrorResponse>(&response),
Err(RequestTokenError::ServerResponse(_))
);
}
#[test]
fn test_check_http_response_json_content_type() {
// Valid content type.
let response = http::Response::builder()
.status(200)
.header(http::header::CONTENT_TYPE, "application/json")
.body(b"{}".to_vec())
.unwrap();
assert_matches!(
check_http_response_json_content_type::<BasicErrorResponse>(&response),
Ok(())
);
// Valid content type with charset.
let response = http::Response::builder()
.status(200)
.header(http::header::CONTENT_TYPE, "application/json; charset=utf-8")
.body(b"{}".to_vec())
.unwrap();
assert_matches!(
check_http_response_json_content_type::<BasicErrorResponse>(&response),
Ok(())
);
// Without content type.
let response = http::Response::builder().status(200).body(b"{}".to_vec()).unwrap();
assert_matches!(
check_http_response_json_content_type::<BasicErrorResponse>(&response),
Ok(())
);
// Wrong content type.
let response = http::Response::builder()
.status(200)
.header(http::header::CONTENT_TYPE, "text/html")
.body(b"<html><body><h1>HTML!</h1></body></html>".to_vec())
.unwrap();
assert_matches!(
check_http_response_json_content_type::<BasicErrorResponse>(&response),
Err(RequestTokenError::Other(_))
);
}
}