1use http_body_util::{BodyExt, Full};
22use hyper::{Request, Response, StatusCode, body::Incoming};
23use std::convert::Infallible;
24use std::sync::Arc;
25
26use crate::types::{ConfigProvider, RateLimiter};
27use crate::{auth, headers, ip_filter, rate_limiter};
28
29pub async fn handle_request<C: ConfigProvider>(
59 req: Request<Incoming>,
60 forward_host: String,
61 forward_port: u16,
62 limiter: RateLimiter,
63 config: Arc<C>,
64 http_client: reqwest::Client,
65) -> Result<Response<Full<bytes::Bytes>>, Infallible> {
66 let real_client_ip =
68 match ip_filter::extract_and_validate_real_ip(req.headers(), config.as_ref()) {
69 Some(ip) => ip,
70 None => {
71 if config.allowed_proxy_ips().is_none() {
74 "unknown".to_string()
75 } else {
76 return Ok(create_error_response(
78 StatusCode::FORBIDDEN,
79 "Invalid request: missing or invalid proxy headers",
80 ));
81 }
82 }
83 };
84
85 if real_client_ip != "unknown" && ip_filter::is_ip_blocked(&real_client_ip, config.as_ref()) {
87 return Ok(create_error_response(
88 StatusCode::FORBIDDEN,
89 "IP address is blocked",
90 ));
91 }
92
93 let request_path = req.uri().path();
95 if is_url_pattern_blocked(request_path, config.as_ref()) {
96 return Ok(create_error_response(StatusCode::NOT_FOUND, "Not Found"));
97 }
98
99 let request_method = req.method().as_str();
101 if is_method_blocked(request_method, config.as_ref()) {
102 return Ok(create_error_response(
103 StatusCode::METHOD_NOT_ALLOWED,
104 "HTTP method not allowed",
105 ));
106 }
107
108 if config.is_auth_enabled() {
110 let auth_header = req
111 .headers()
112 .get(headers::AUTHORIZATION)
113 .and_then(|v| v.to_str().ok());
114
115 if !auth::check_basic_auth(auth_header, config.auth_credentials()) {
116 return Ok(create_unauthorized_response(config.auth_realm()));
117 }
118 }
119
120 if real_client_ip != "unknown"
122 && !rate_limiter::check_rate_limit(&limiter, &real_client_ip, config.as_ref()).await
123 {
124 return Ok(create_error_response(
125 StatusCode::TOO_MANY_REQUESTS,
126 "Rate limit exceeded",
127 ));
128 }
129
130 let mut req = req;
132 if real_client_ip != "unknown"
133 && let Ok(header_value) = real_client_ip.parse()
134 {
135 req.headers_mut().insert("x-real-ip", header_value);
136 }
137
138 forward_request(
140 req,
141 &forward_host,
142 forward_port,
143 config.as_ref(),
144 &http_client,
145 )
146 .await
147}
148
149async fn forward_request(
151 req: Request<Incoming>,
152 host: &str,
153 port: u16,
154 config: &impl ConfigProvider,
155 http_client: &reqwest::Client,
156) -> Result<Response<Full<bytes::Bytes>>, Infallible> {
157 let proxy_config = config.proxy_config();
158 let (parts, body) = req.into_parts();
159 let body_bytes = match body.collect().await {
160 Ok(bytes) => {
161 let collected_bytes = bytes.to_bytes();
162
163 if proxy_config.max_body_size > 0 && collected_bytes.len() > proxy_config.max_body_size
165 {
166 return Ok(create_error_response(
167 StatusCode::PAYLOAD_TOO_LARGE,
168 "Request body too large",
169 ));
170 }
171
172 collected_bytes
173 }
174 Err(_) => {
175 return Ok(create_error_response(
176 StatusCode::BAD_REQUEST,
177 "Failed to read request body",
178 ));
179 }
180 };
181
182 forward_with_reqwest(parts, body_bytes, host, port, http_client).await
183}
184
185async fn forward_with_reqwest(
187 parts: hyper::http::request::Parts,
188 body_bytes: bytes::Bytes,
189 host: &str,
190 port: u16,
191 client: &reqwest::Client,
192) -> Result<Response<Full<bytes::Bytes>>, Infallible> {
193 let destination_uri = format!(
195 "http://{}:{}{}",
196 host,
197 port,
198 parts.uri.path_and_query().map_or("", |pq| pq.as_str())
199 );
200
201 let mut req_builder = match parts.method.as_str() {
203 "GET" => client.get(&destination_uri),
204 "POST" => client.post(&destination_uri),
205 "PUT" => client.put(&destination_uri),
206 "DELETE" => client.delete(&destination_uri),
207 "HEAD" => client.head(&destination_uri),
208 "PATCH" => client.patch(&destination_uri),
209 "OPTIONS" => client.request(reqwest::Method::OPTIONS, &destination_uri),
210 method => {
211 match reqwest::Method::from_bytes(method.as_bytes()) {
213 Ok(custom_method) => client.request(custom_method, &destination_uri),
214 Err(_) => {
215 return Ok(create_error_response(
216 StatusCode::METHOD_NOT_ALLOWED,
217 "HTTP method not supported",
218 ));
219 }
220 }
221 }
222 };
223
224 for (name, value) in parts.headers.iter() {
226 if name != "host"
227 && name != "content-length"
228 && let Ok(header_value) = value.to_str()
229 {
230 req_builder = req_builder.header(name.as_str(), header_value);
231 }
232 }
233
234 if !body_bytes.is_empty() {
236 req_builder = req_builder.body(body_bytes.to_vec());
237 }
238
239 match req_builder.send().await {
241 Ok(response) => {
242 let status = response.status();
243 let resp_headers = response.headers().clone();
244
245 match response.bytes().await {
246 Ok(body_bytes) => {
247 let mut hyper_response = match Response::builder()
248 .status(status.as_u16())
249 .body(Full::new(body_bytes))
250 {
251 Ok(resp) => resp,
252 Err(_) => {
253 return Ok(create_error_response(
254 StatusCode::INTERNAL_SERVER_ERROR,
255 "Failed to build response",
256 ));
257 }
258 };
259
260 for (name, value) in resp_headers.iter() {
262 let header_name = name.as_str().to_lowercase();
263 if !headers::is_hop_by_hop(&header_name)
265 && let (Ok(hyper_name), Ok(hyper_value)) = (
266 hyper::header::HeaderName::from_bytes(name.as_str().as_bytes()),
267 hyper::header::HeaderValue::from_bytes(value.as_bytes()),
268 )
269 {
270 hyper_response.headers_mut().insert(hyper_name, hyper_value);
271 }
272 }
273
274 Ok(hyper_response)
275 }
276 Err(_) => Ok(create_error_response(
277 StatusCode::BAD_GATEWAY,
278 "Failed to read response body",
279 )),
280 }
281 }
282 Err(err) => {
283 if err.is_timeout() {
285 Ok(create_error_response(
286 StatusCode::GATEWAY_TIMEOUT,
287 "Upstream service timeout",
288 ))
289 } else if err.is_connect() {
290 Ok(create_error_response(
291 StatusCode::BAD_GATEWAY,
292 "Could not connect to upstream service",
293 ))
294 } else {
295 Ok(create_error_response(
296 StatusCode::BAD_GATEWAY,
297 "Upstream service error",
298 ))
299 }
300 }
301 }
302}
303
304pub fn create_error_response(status: StatusCode, message: &str) -> Response<Full<bytes::Bytes>> {
329 Response::builder()
330 .status(status)
331 .header("content-type", "text/plain")
332 .body(Full::new(bytes::Bytes::from(message.to_string())))
333 .unwrap_or_else(|_| {
334 Response::new(Full::new(bytes::Bytes::from("Internal Server Error")))
336 })
337}
338
339pub fn create_unauthorized_response(realm: &str) -> Response<Full<bytes::Bytes>> {
352 Response::builder()
353 .status(StatusCode::UNAUTHORIZED)
354 .header(
355 headers::WWW_AUTHENTICATE,
356 format!("Basic realm=\"{}\"", realm),
357 )
358 .header("content-type", "text/plain")
359 .body(Full::new(bytes::Bytes::from("401 Unauthorized")))
360 .unwrap_or_else(|_| Response::new(Full::new(bytes::Bytes::from("401 Unauthorized"))))
361}
362
363fn is_url_pattern_blocked(path: &str, config: &impl ConfigProvider) -> bool {
366 let blocked_patterns = config.blocked_patterns();
367 if blocked_patterns.is_empty() {
368 return false;
369 }
370
371 let decoded_path = url_decode(path);
373
374 blocked_patterns
376 .iter()
377 .any(|pattern| path.contains(pattern) || decoded_path.contains(pattern))
378}
379
380fn url_decode(input: &str) -> String {
384 let mut bytes = Vec::with_capacity(input.len());
385 let mut chars = input.chars().peekable();
386
387 while let Some(c) = chars.next() {
388 if c == '%' {
389 let hex: String = chars.by_ref().take(2).collect();
391 if hex.len() == 2
392 && let Ok(byte) = u8::from_str_radix(&hex, 16)
393 {
394 bytes.push(byte);
395 continue;
396 }
397 bytes.extend_from_slice(b"%");
399 bytes.extend_from_slice(hex.as_bytes());
400 } else {
401 let mut buf = [0u8; 4];
403 bytes.extend_from_slice(c.encode_utf8(&mut buf).as_bytes());
404 }
405 }
406
407 String::from_utf8_lossy(&bytes).into_owned()
409}
410
411fn is_method_blocked(method: &str, config: &impl ConfigProvider) -> bool {
413 let blocked_methods = config.blocked_methods();
414 blocked_methods
415 .iter()
416 .any(|blocked_method| blocked_method == &method.to_uppercase())
417}
418
419#[cfg(test)]
420mod tests {
421 use super::*;
422 use crate::test_utils::TestConfig;
423 use http_body_util::BodyExt;
424
425 #[test]
430 fn test_url_decode_no_encoding() {
431 assert_eq!(url_decode("/path/to/file"), "/path/to/file");
432 assert_eq!(url_decode("hello"), "hello");
433 assert_eq!(url_decode(""), "");
434 }
435
436 #[test]
437 fn test_url_decode_simple_encoding() {
438 assert_eq!(url_decode("%20"), " ");
439 assert_eq!(url_decode("hello%20world"), "hello world");
440 assert_eq!(url_decode("%2F"), "/");
441 }
442
443 #[test]
444 fn test_url_decode_dot_encoding() {
445 assert_eq!(url_decode("%2e"), ".");
447 assert_eq!(url_decode("%2E"), ".");
448 assert_eq!(url_decode(".%2ephp"), "..php");
449 }
450
451 #[test]
452 fn test_url_decode_php_bypass() {
453 assert_eq!(url_decode(".ph%70"), ".php");
455 assert_eq!(url_decode("%2ephp"), ".php");
456 assert_eq!(url_decode(".%70%68%70"), ".php");
457 }
458
459 #[test]
460 fn test_url_decode_env_bypass() {
461 assert_eq!(url_decode(".%65nv"), ".env");
463 assert_eq!(url_decode("%2eenv"), ".env");
464 assert_eq!(url_decode("%2e%65%6e%76"), ".env");
465 }
466
467 #[test]
468 fn test_url_decode_multiple_encodings() {
469 assert_eq!(url_decode("%2F%2e%2e%2Fetc%2Fpasswd"), "/../etc/passwd");
470 }
471
472 #[test]
473 fn test_url_decode_invalid_hex() {
474 assert_eq!(url_decode("%GG"), "%GG");
476 assert_eq!(url_decode("%"), "%");
477 assert_eq!(url_decode("%2"), "%2");
478 assert_eq!(url_decode("%ZZ"), "%ZZ");
479 }
480
481 #[test]
482 fn test_url_decode_mixed_content() {
483 assert_eq!(url_decode("path%2Fto%2Ffile.txt"), "path/to/file.txt");
484 assert_eq!(url_decode("hello%20%26%20world"), "hello & world");
485 }
486
487 #[test]
488 fn test_url_decode_unicode() {
489 assert_eq!(url_decode("%C3%A9"), "é"); assert_eq!(url_decode("caf%C3%A9"), "café");
492 }
493
494 #[test]
499 fn test_url_pattern_blocked_simple() {
500 let config = TestConfig::new().with_blocked_patterns(vec![".php", ".env"]);
501
502 assert!(is_url_pattern_blocked("/file.php", &config));
503 assert!(is_url_pattern_blocked("/.env", &config));
504 assert!(is_url_pattern_blocked("/path/to/file.php", &config));
505 }
506
507 #[test]
508 fn test_url_pattern_not_blocked() {
509 let config = TestConfig::new().with_blocked_patterns(vec![".php", ".env"]);
510
511 assert!(!is_url_pattern_blocked("/file.html", &config));
512 assert!(!is_url_pattern_blocked("/path/to/file.js", &config));
513 assert!(!is_url_pattern_blocked("/", &config));
514 }
515
516 #[test]
517 fn test_url_pattern_blocked_empty_patterns() {
518 let config = TestConfig::new();
519
520 assert!(!is_url_pattern_blocked("/file.php", &config));
521 assert!(!is_url_pattern_blocked("/.env", &config));
522 }
523
524 #[test]
525 fn test_url_pattern_blocked_bypass_attempt() {
526 let config = TestConfig::new().with_blocked_patterns(vec![".php", ".env", "admin"]);
527
528 assert!(is_url_pattern_blocked("/.ph%70", &config)); assert!(is_url_pattern_blocked("/%2eenv", &config)); assert!(is_url_pattern_blocked("/adm%69n", &config)); }
533
534 #[test]
535 fn test_url_pattern_blocked_double_encoding_attempt() {
536 let config = TestConfig::new().with_blocked_patterns(vec![".php"]);
537
538 assert!(is_url_pattern_blocked("/.ph%70", &config));
540 }
541
542 #[test]
543 fn test_url_pattern_blocked_case_sensitive() {
544 let config = TestConfig::new().with_blocked_patterns(vec![".PHP"]);
545
546 assert!(is_url_pattern_blocked("/file.PHP", &config));
548 assert!(!is_url_pattern_blocked("/file.php", &config)); }
550
551 #[test]
552 fn test_url_pattern_blocked_partial_match() {
553 let config = TestConfig::new().with_blocked_patterns(vec!["admin"]);
554
555 assert!(is_url_pattern_blocked("/admin/panel", &config));
556 assert!(is_url_pattern_blocked("/path/admin", &config));
557 assert!(is_url_pattern_blocked("/administrator", &config)); }
559
560 #[test]
565 fn test_method_blocked() {
566 let config = TestConfig::new().with_blocked_methods(vec!["TRACE", "CONNECT"]);
567
568 assert!(is_method_blocked("TRACE", &config));
569 assert!(is_method_blocked("CONNECT", &config));
570 }
571
572 #[test]
573 fn test_method_not_blocked() {
574 let config = TestConfig::new().with_blocked_methods(vec!["TRACE", "CONNECT"]);
575
576 assert!(!is_method_blocked("GET", &config));
577 assert!(!is_method_blocked("POST", &config));
578 assert!(!is_method_blocked("PUT", &config));
579 assert!(!is_method_blocked("DELETE", &config));
580 }
581
582 #[test]
583 fn test_method_blocked_empty_list() {
584 let config = TestConfig::new();
585
586 assert!(!is_method_blocked("TRACE", &config));
587 assert!(!is_method_blocked("GET", &config));
588 }
589
590 #[test]
591 fn test_method_blocked_case_insensitive() {
592 let config = TestConfig::new().with_blocked_methods(vec!["TRACE"]);
593
594 assert!(is_method_blocked("TRACE", &config));
595 assert!(is_method_blocked("trace", &config));
596 assert!(is_method_blocked("Trace", &config));
597 }
598
599 #[test]
604 fn test_create_error_response_status() {
605 let response = create_error_response(StatusCode::NOT_FOUND, "Not Found");
606 assert_eq!(response.status(), StatusCode::NOT_FOUND);
607
608 let response = create_error_response(StatusCode::FORBIDDEN, "Forbidden");
609 assert_eq!(response.status(), StatusCode::FORBIDDEN);
610
611 let response = create_error_response(StatusCode::TOO_MANY_REQUESTS, "Rate limited");
612 assert_eq!(response.status(), StatusCode::TOO_MANY_REQUESTS);
613 }
614
615 #[test]
616 fn test_create_error_response_content_type() {
617 let response = create_error_response(StatusCode::NOT_FOUND, "Not Found");
618 assert_eq!(
619 response.headers().get("content-type").unwrap(),
620 "text/plain"
621 );
622 }
623
624 #[tokio::test]
625 async fn test_create_error_response_body() {
626 let response = create_error_response(StatusCode::NOT_FOUND, "Resource not found");
627 let body = response.into_body().collect().await.unwrap().to_bytes();
628 assert_eq!(body, "Resource not found");
629 }
630
631 #[tokio::test]
632 async fn test_create_error_response_empty_message() {
633 let response = create_error_response(StatusCode::NO_CONTENT, "");
634 let body = response.into_body().collect().await.unwrap().to_bytes();
635 assert_eq!(body, "");
636 }
637}