aien-edge
aien-dev/aien-edge
Brought by drakestapleton
| 1 | //! Request handling: host routing, redirects, conditional GET, and encoding negotiation. |
| 2 | |
| 3 | use crate::site::{pick_encoding, Encoding, SiteFiles}; |
| 4 | use bytes::Bytes; |
| 5 | use http::{header, HeaderValue, Method, Request, Response, StatusCode}; |
| 6 | use http_body_util::Full; |
| 7 | use std::collections::HashMap; |
| 8 | use std::sync::Arc; |
| 9 | |
| 10 | pub struct Sites { |
| 11 | pub by_host: HashMap<String, Arc<SiteFiles>>, |
| 12 | /// Alias host to canonical host. |
| 13 | pub redirects: HashMap<String, String>, |
| 14 | } |
| 15 | |
| 16 | #[derive(Clone, Copy)] |
| 17 | pub enum Scheme { |
| 18 | /// Plain HTTP on a TLS-enabled server: redirect everything to HTTPS. |
| 19 | HttpRedirect, |
| 20 | /// Plain HTTP without TLS configured: serve content. |
| 21 | HttpServe, |
| 22 | Https, |
| 23 | } |
| 24 | |
| 25 | pub fn handle<B>(req: &Request<B>, sites: &Sites, scheme: Scheme) -> Response<Full<Bytes>> { |
| 26 | let host = request_host(req); |
| 27 | let path_and_query = req |
| 28 | .uri() |
| 29 | .path_and_query() |
| 30 | .map(|p| p.as_str()) |
| 31 | .unwrap_or("/"); |
| 32 | |
| 33 | if let Some(canonical) = sites.redirects.get(&host) { |
| 34 | return redirect(&format!("https://{canonical}{path_and_query}"), scheme); |
| 35 | } |
| 36 | let Some(site) = sites.by_host.get(&host) else { |
| 37 | return plain(StatusCode::MISDIRECTED_REQUEST, "unknown host\n", scheme); |
| 38 | }; |
| 39 | if let Scheme::HttpRedirect = scheme { |
| 40 | return redirect(&format!("https://{host}{path_and_query}"), scheme); |
| 41 | } |
| 42 | if req.method() != Method::GET && req.method() != Method::HEAD { |
| 43 | let mut r = plain( |
| 44 | StatusCode::METHOD_NOT_ALLOWED, |
| 45 | "method not allowed\n", |
| 46 | scheme, |
| 47 | ); |
| 48 | r.headers_mut() |
| 49 | .insert(header::ALLOW, HeaderValue::from_static("GET, HEAD")); |
| 50 | return r; |
| 51 | } |
| 52 | let Some((asset, code)) = site.resolve(req.uri().path()) else { |
| 53 | return plain(StatusCode::NOT_FOUND, "not found\n", scheme); |
| 54 | }; |
| 55 | |
| 56 | let mut builder = Response::builder() |
| 57 | .header(header::CONTENT_TYPE, &asset.content_type) |
| 58 | .header(header::ETAG, &asset.etag) |
| 59 | .header(header::CACHE_CONTROL, asset.cache_control) |
| 60 | .header(header::VARY, "Accept-Encoding"); |
| 61 | if code == 200 { |
| 62 | let inm = req |
| 63 | .headers() |
| 64 | .get(header::IF_NONE_MATCH) |
| 65 | .and_then(|v| v.to_str().ok()); |
| 66 | if inm.is_some_and(|v| { |
| 67 | v.split(',') |
| 68 | .any(|t| t.trim() == asset.etag || t.trim() == "*") |
| 69 | }) { |
| 70 | let mut r = builder |
| 71 | .status(StatusCode::NOT_MODIFIED) |
| 72 | .body(Full::new(Bytes::new())) |
| 73 | .unwrap(); |
| 74 | security_headers(&mut r, scheme); |
| 75 | return r; |
| 76 | } |
| 77 | } |
| 78 | let accept = req |
| 79 | .headers() |
| 80 | .get(header::ACCEPT_ENCODING) |
| 81 | .and_then(|v| v.to_str().ok()); |
| 82 | let body = match pick_encoding(accept, asset) { |
| 83 | Encoding::Brotli => { |
| 84 | builder = builder.header(header::CONTENT_ENCODING, "br"); |
| 85 | asset.br.clone().unwrap() |
| 86 | } |
| 87 | Encoding::Gzip => { |
| 88 | builder = builder.header(header::CONTENT_ENCODING, "gzip"); |
| 89 | asset.gzip.clone().unwrap() |
| 90 | } |
| 91 | Encoding::Identity => asset.body.clone(), |
| 92 | }; |
| 93 | builder = builder.header(header::CONTENT_LENGTH, body.len()); |
| 94 | let body = if req.method() == Method::HEAD { |
| 95 | Bytes::new() |
| 96 | } else { |
| 97 | body |
| 98 | }; |
| 99 | let mut r = builder.status(code).body(Full::new(body)).unwrap(); |
| 100 | security_headers(&mut r, scheme); |
| 101 | r |
| 102 | } |
| 103 | |
| 104 | fn request_host<B>(req: &Request<B>) -> String { |
| 105 | let raw = req |
| 106 | .uri() |
| 107 | .host() |
| 108 | .map(str::to_string) |
| 109 | .or_else(|| { |
| 110 | req.headers() |
| 111 | .get(header::HOST) |
| 112 | .and_then(|h| h.to_str().ok()) |
| 113 | .map(str::to_string) |
| 114 | }) |
| 115 | .unwrap_or_default(); |
| 116 | // Strip a port and any trailing dot, and compare case-insensitively. |
| 117 | let no_port = match raw.rsplit_once(':') { |
| 118 | Some((h, p)) if !h.contains(']') && p.chars().all(|c| c.is_ascii_digit()) => h.to_string(), |
| 119 | _ => raw, |
| 120 | }; |
| 121 | no_port.trim_end_matches('.').to_ascii_lowercase() |
| 122 | } |
| 123 | |
| 124 | fn redirect(location: &str, scheme: Scheme) -> Response<Full<Bytes>> { |
| 125 | let mut r = Response::builder() |
| 126 | .status(StatusCode::MOVED_PERMANENTLY) |
| 127 | .header(header::LOCATION, location) |
| 128 | .header(header::CONTENT_LENGTH, 0) |
| 129 | .body(Full::new(Bytes::new())) |
| 130 | .unwrap(); |
| 131 | security_headers(&mut r, scheme); |
| 132 | r |
| 133 | } |
| 134 | |
| 135 | fn plain(status: StatusCode, msg: &'static str, scheme: Scheme) -> Response<Full<Bytes>> { |
| 136 | let mut r = Response::builder() |
| 137 | .status(status) |
| 138 | .header(header::CONTENT_TYPE, "text/plain; charset=utf-8") |
| 139 | .header(header::CONTENT_LENGTH, msg.len()) |
| 140 | .body(Full::new(Bytes::from_static(msg.as_bytes()))) |
| 141 | .unwrap(); |
| 142 | security_headers(&mut r, scheme); |
| 143 | r |
| 144 | } |
| 145 | |
| 146 | fn security_headers(r: &mut Response<Full<Bytes>>, scheme: Scheme) { |
| 147 | let h = r.headers_mut(); |
| 148 | h.insert(header::SERVER, HeaderValue::from_static("aien-edge")); |
| 149 | h.insert( |
| 150 | header::X_CONTENT_TYPE_OPTIONS, |
| 151 | HeaderValue::from_static("nosniff"), |
| 152 | ); |
| 153 | h.insert( |
| 154 | header::REFERRER_POLICY, |
| 155 | HeaderValue::from_static("strict-origin-when-cross-origin"), |
| 156 | ); |
| 157 | h.insert(header::X_FRAME_OPTIONS, HeaderValue::from_static("DENY")); |
| 158 | h.insert( |
| 159 | "permissions-policy", |
| 160 | HeaderValue::from_static("camera=(), microphone=(), geolocation=()"), |
| 161 | ); |
| 162 | if let Scheme::Https = scheme { |
| 163 | h.insert( |
| 164 | header::STRICT_TRANSPORT_SECURITY, |
| 165 | HeaderValue::from_static("max-age=31536000"), |
| 166 | ); |
| 167 | } |
| 168 | } |
| 169 | |
| 170 | #[cfg(test)] |
| 171 | mod tests { |
| 172 | use super::*; |
| 173 | use crate::site::SiteFiles; |
| 174 | |
| 175 | fn sites() -> (tempfile::TempDir, Sites) { |
| 176 | let dir = tempfile::tempdir().unwrap(); |
| 177 | std::fs::write(dir.path().join("index.html"), "x".repeat(3000)).unwrap(); |
| 178 | let s = Arc::new(SiteFiles::load(dir.path(), true).unwrap()); |
| 179 | let mut by_host = HashMap::new(); |
| 180 | by_host.insert("www.example.com".to_string(), s); |
| 181 | let mut redirects = HashMap::new(); |
| 182 | redirects.insert("example.com".to_string(), "www.example.com".to_string()); |
| 183 | (dir, Sites { by_host, redirects }) |
| 184 | } |
| 185 | |
| 186 | fn get(host: &str, path: &str) -> Request<()> { |
| 187 | Request::builder() |
| 188 | .uri(path) |
| 189 | .header("host", host) |
| 190 | .body(()) |
| 191 | .unwrap() |
| 192 | } |
| 193 | |
| 194 | #[test] |
| 195 | fn apex_redirects_to_canonical_https() { |
| 196 | let (_d, s) = sites(); |
| 197 | let r = handle(&get("Example.com.", "/a?b=1"), &s, Scheme::Https); |
| 198 | assert_eq!(r.status(), 301); |
| 199 | assert_eq!( |
| 200 | r.headers()[header::LOCATION], |
| 201 | "https://www.example.com/a?b=1" |
| 202 | ); |
| 203 | } |
| 204 | |
| 205 | #[test] |
| 206 | fn http_redirects_when_tls_enabled() { |
| 207 | let (_d, s) = sites(); |
| 208 | let r = handle(&get("www.example.com:80", "/x"), &s, Scheme::HttpRedirect); |
| 209 | assert_eq!(r.headers()[header::LOCATION], "https://www.example.com/x"); |
| 210 | } |
| 211 | |
| 212 | #[test] |
| 213 | fn serves_brotli_and_honors_etag() { |
| 214 | let (_d, s) = sites(); |
| 215 | let mut req = get("www.example.com", "/"); |
| 216 | req.headers_mut() |
| 217 | .insert(header::ACCEPT_ENCODING, HeaderValue::from_static("br")); |
| 218 | let r = handle(&req, &s, Scheme::Https); |
| 219 | assert_eq!(r.status(), 200); |
| 220 | assert_eq!(r.headers()[header::CONTENT_ENCODING], "br"); |
| 221 | assert!(r.headers().contains_key(header::STRICT_TRANSPORT_SECURITY)); |
| 222 | let etag = r.headers()[header::ETAG].clone(); |
| 223 | req.headers_mut().insert(header::IF_NONE_MATCH, etag); |
| 224 | assert_eq!(handle(&req, &s, Scheme::Https).status(), 304); |
| 225 | } |
| 226 | |
| 227 | #[test] |
| 228 | fn unknown_host_and_bad_method() { |
| 229 | let (_d, s) = sites(); |
| 230 | assert_eq!( |
| 231 | handle(&get("evil.test", "/"), &s, Scheme::Https).status(), |
| 232 | 421 |
| 233 | ); |
| 234 | let post = Request::builder() |
| 235 | .method("POST") |
| 236 | .uri("/") |
| 237 | .header("host", "www.example.com") |
| 238 | .body(()) |
| 239 | .unwrap(); |
| 240 | assert_eq!(handle(&post, &s, Scheme::Https).status(), 405); |
| 241 | } |
| 242 | } |