Skip to main content

ic_bn_lib/http/
mod.rs

1pub mod body;
2pub mod cache;
3pub mod client;
4pub mod headers;
5pub mod middleware;
6pub mod proxy;
7pub mod server;
8pub mod shed;
9
10use axum::response::{IntoResponse, Redirect};
11use http::{HeaderMap, Method, Request, StatusCode, Uri, Version, header::HOST, uri::PathAndQuery};
12use url::Url;
13
14#[cfg(feature = "clients-hyper")]
15pub use client::clients_hyper::{HyperClient, HyperClientLeastLoaded};
16pub use client::clients_reqwest::{
17    ReqwestClient, ReqwestClientLeastLoaded, ReqwestClientRoundRobin,
18};
19pub use client::{Client, ClientHttp};
20pub use server::{Server, ServerBuilder};
21
22use crate::{http::headers::X_FORWARDED_HOST, network::AsyncReadWrite};
23
24/// HTTP error
25#[derive(thiserror::Error, Debug)]
26pub enum Error {
27    #[error("HTTP body reading timed out")]
28    BodyTimedOut,
29    #[error("HTTP body is too big")]
30    BodyTooBig,
31    #[error("HTTP body reading failed: {0}")]
32    BodyReadingFailed(String),
33    #[error("HTTP request failed: {0}")]
34    RequestFailed(#[from] reqwest::Error),
35    #[error("No Proxy Protocol v2 detected")]
36    NoProxyProtocolDetected,
37    #[error("DNS resolving failed: {0}")]
38    DnsError(String),
39    #[error("Generic HTTP failure: {0}")]
40    HttpError(#[from] http::Error),
41    #[error("{0}")]
42    HyperClientError(#[from] hyper_util::client::legacy::Error),
43    #[error("{0}")]
44    HyperError(#[from] hyper::Error),
45    #[error(transparent)]
46    Generic(#[from] anyhow::Error),
47}
48
49/// Calculate very approximate HTTP request/response headers size in bytes.
50/// More or less accurate only for http/1.1 since in h2 headers are in HPACK-compressed.
51/// But it seems there's no better way.
52pub fn calc_headers_size(h: &HeaderMap) -> usize {
53    h.iter().map(|(k, v)| k.as_str().len() + v.len() + 2).sum()
54}
55
56/// Get a static string representing given HTTP version
57pub const fn http_version(v: Version) -> &'static str {
58    match v {
59        Version::HTTP_09 => "0.9",
60        Version::HTTP_10 => "1.0",
61        Version::HTTP_11 => "1.1",
62        Version::HTTP_2 => "2.0",
63        Version::HTTP_3 => "3.0",
64        _ => "-",
65    }
66}
67
68/// Get a static string representing given HTTP method
69pub const fn http_method(v: &Method) -> &'static str {
70    match *v {
71        Method::OPTIONS => "OPTIONS",
72        Method::GET => "GET",
73        Method::POST => "POST",
74        Method::PUT => "PUT",
75        Method::DELETE => "DELETE",
76        Method::HEAD => "HEAD",
77        Method::TRACE => "TRACE",
78        Method::CONNECT => "CONNECT",
79        Method::PATCH => "PATCH",
80        _ => "",
81    }
82}
83
84/// Attempts to extract "host" from "host:port" format.
85/// Host can be either FQDN or IPv4/IPv6 address.
86pub fn extract_host(host_port: &str) -> Option<&str> {
87    if host_port.is_empty() {
88        return None;
89    }
90
91    // Cover IPv6 case
92    if host_port.as_bytes()[0] == b'[' {
93        host_port.find(']').map(|i| &host_port[1..i])
94    } else {
95        host_port.split(':').next()
96    }
97    .filter(|x| !x.is_empty())
98}
99
100/// Attempts to extract host from `X-Forwarded-Host` header, HTTP2 "authority" pseudo-header or from HTTP/1.1 `Host` header
101/// (in this order of preference)
102pub fn extract_authority<T>(request: &Request<T>) -> Option<&str> {
103    // Try `X-Forwarded-Host` header first
104    request
105        .headers()
106        .get(X_FORWARDED_HOST)
107        .and_then(|x| x.to_str().ok())
108        // Then URI authority
109        .or_else(|| request.uri().authority().map(|x| x.host()))
110        // THen `Host` header
111        .or_else(|| request.headers().get(HOST).and_then(|x| x.to_str().ok()))
112        // Extract host w/o port
113        .and_then(extract_host)
114}
115
116/// Error that might happen during Url to Uri conversion
117#[derive(thiserror::Error, Debug)]
118pub enum UrlToUriError {
119    #[error("No Authority")]
120    NoAuthority,
121    #[error("No Host")]
122    NoHost,
123    #[error(transparent)]
124    Http(#[from] http::Error),
125}
126
127/// Converts `Url` to `Uri`
128pub fn url_to_uri(url: &Url) -> Result<Uri, UrlToUriError> {
129    if !url.has_authority() {
130        return Err(UrlToUriError::NoAuthority);
131    }
132
133    if !url.has_host() {
134        return Err(UrlToUriError::NoHost);
135    }
136
137    let scheme = url.scheme();
138    let authority = url.authority();
139
140    let authority_end = scheme.len() + "://".len() + authority.len();
141    let path_and_query = &url.as_str()[authority_end..];
142
143    Uri::builder()
144        .scheme(scheme)
145        .authority(authority)
146        .path_and_query(path_and_query)
147        .build()
148        .map_err(UrlToUriError::Http)
149}
150
151/// Redirects any request to an HTTPS scheme
152pub async fn redirect_to_https(
153    request: axum::extract::Request,
154) -> Result<impl IntoResponse, impl IntoResponse> {
155    let host = extract_authority(&request)
156        .ok_or((StatusCode::BAD_REQUEST, "Unable to extract authority"))?;
157    let uri = request.uri().clone();
158
159    let fallback_path = PathAndQuery::from_static("/");
160    let pq = uri.path_and_query().unwrap_or(&fallback_path).as_str();
161
162    Ok::<_, (_, _)>(Redirect::permanent(
163        &Uri::builder()
164            .scheme("https")
165            .authority(host)
166            .path_and_query(pq)
167            .build()
168            .map_err(|_| (StatusCode::BAD_REQUEST, "Incorrect URL"))?
169            .to_string(),
170    ))
171}
172
173#[cfg(test)]
174mod test {
175    use axum::{Router, body::Body};
176    use http::{
177        Uri,
178        header::{HOST, LOCATION},
179    };
180    use tower::ServiceExt;
181
182    use crate::hval;
183
184    use super::*;
185
186    #[test]
187    fn test_extract_host() {
188        assert_eq!(extract_host("foo.bar"), Some("foo.bar"));
189        assert_eq!(extract_host("foo.bar:443"), Some("foo.bar"));
190        assert_eq!(extract_host("foo.bar:"), Some("foo.bar"));
191        assert_eq!(extract_host("foo:443"), Some("foo"));
192
193        assert_eq!(extract_host("127.0.0.1:443"), Some("127.0.0.1"));
194        assert_eq!(extract_host("[::1]:443"), Some("::1"));
195
196        assert_eq!(
197            extract_host("[fe80::b696:91ff:fe84:3ae8]"),
198            Some("fe80::b696:91ff:fe84:3ae8")
199        );
200        assert_eq!(
201            extract_host("[fe80::b696:91ff:fe84:3ae8]:123"),
202            Some("fe80::b696:91ff:fe84:3ae8")
203        );
204
205        // Unterminated bracket
206        assert_eq!(extract_host("[fe80::b696:91ff:fe84:3ae8:123"), None);
207        // Empty
208        assert_eq!(extract_host(""), None);
209        assert_eq!(extract_host("[]:443"), None);
210    }
211
212    #[test]
213    fn test_extract_authority() {
214        // No authority & no host header
215        let mut req = Request::new(());
216        *req.uri_mut() = Uri::builder()
217            .path_and_query("/foo?bar=baz")
218            .build()
219            .unwrap();
220        assert_eq!(extract_authority(&req), None);
221
222        // Authority
223        let mut req = Request::new(());
224        *req.uri_mut() = Uri::builder()
225            .scheme("http")
226            .authority("foo.bar:443")
227            .path_and_query("/foo?bar=baz")
228            .build()
229            .unwrap();
230        assert_eq!(extract_authority(&req), Some("foo.bar"));
231
232        let mut req = Request::new(());
233        *req.uri_mut() = Uri::builder()
234            .scheme("http")
235            .authority("[::1]:443")
236            .path_and_query("/foo?bar=baz")
237            .build()
238            .unwrap();
239        assert_eq!(extract_authority(&req), Some("::1"));
240
241        // Host header
242        let mut req = Request::new(());
243        *req.uri_mut() = Uri::builder()
244            .path_and_query("/foo?bar=baz")
245            .build()
246            .unwrap();
247        (*req.headers_mut()).insert(HOST, hval!("foo.baz:443"));
248        assert_eq!(extract_authority(&req), Some("foo.baz"));
249
250        // XFH header
251        let mut req = Request::new(());
252        *req.uri_mut() = Uri::builder()
253            .path_and_query("/foo?bar=baz")
254            .build()
255            .unwrap();
256        (*req.headers_mut()).insert(X_FORWARDED_HOST, hval!("foo.baz:443"));
257        assert_eq!(extract_authority(&req), Some("foo.baz"));
258
259        // Host+Authority: authority should take precedence
260        let mut req = Request::new(());
261        *req.uri_mut() = Uri::builder()
262            .scheme("http")
263            .authority("foo.bar:443")
264            .path_and_query("/foo?bar=baz")
265            .build()
266            .unwrap();
267        (*req.headers_mut()).insert(HOST, hval!("foo.baz:443"));
268        assert_eq!(extract_authority(&req), Some("foo.bar"));
269
270        // XFH+Host+Authority: XFH should take precedence
271        let mut req = Request::new(());
272        *req.uri_mut() = Uri::builder()
273            .scheme("http")
274            .authority("foo.bar:443")
275            .path_and_query("/foo?bar=baz")
276            .build()
277            .unwrap();
278        (*req.headers_mut()).insert(HOST, hval!("foo.baz:443"));
279        (*req.headers_mut()).insert(X_FORWARDED_HOST, hval!("dead.beef:443"));
280        assert_eq!(extract_authority(&req), Some("dead.beef"));
281    }
282
283    #[test]
284    fn test_url_to_uri() {
285        let url = "https://foo.bar/baz?dead=beef".parse().unwrap();
286
287        assert_eq!(
288            url_to_uri(&url).unwrap(),
289            Uri::from_static("https://foo.bar/baz?dead=beef")
290        );
291
292        let url = "unix:/foo/bar".parse().unwrap();
293        assert!(url_to_uri(&url).is_err());
294    }
295
296    #[tokio::test]
297    async fn test_redirect_to_https() {
298        let mut request = axum::extract::Request::new(Body::empty());
299        *request.uri_mut() = Uri::from_static("http://foo/bar/baz.bin?a=b");
300
301        let router = Router::new().fallback(redirect_to_https);
302
303        let response = router.oneshot(request).await.unwrap();
304        let location = response.headers().get(LOCATION).unwrap().to_str().unwrap();
305        assert_eq!(location, "https://foo/bar/baz.bin?a=b");
306    }
307}