Skip to main content

relay_core_lib/proxy/
http_utils.rs

1use std::net::SocketAddr;
2use hyper::{Response, Request, StatusCode};
3use hyper::body::Bytes;
4use hyper::header::{HeaderName, HeaderValue};
5use http_body_util::{Full, BodyExt};
6use hyper_util::client::legacy::Client;
7use hyper_util::client::legacy::connect::HttpConnector;
8use hyper_rustls::HttpsConnector;
9use relay_core_api::flow::{
10    BodyData, Flow, HttpLayer, HttpRequest, HttpResponse, Layer, NetworkInfo, TransportProtocol,
11    WebSocketLayer, Cookie,
12};
13use relay_core_api::policy::ProxyPolicy;
14use crate::capture::loop_detection::LoopDetector;
15use uuid::Uuid;
16use chrono::Utc;
17use url::Url;
18use cookie::Cookie as CookieCrate;
19use data_encoding::BASE64;
20use crate::proxy::body_codec::process_body;
21use crate::interceptor::HttpBody;
22
23pub type HttpsClient = Client<HttpsConnector<HttpConnector>, HttpBody>;
24
25#[derive(Clone, Debug)]
26pub struct RequestMeta {
27    pub method: String,
28    pub url_str: String,
29    pub version: String,
30    pub headers: Vec<(String, String)>,
31    pub query: Vec<(String, String)>,
32    pub cookies: Vec<Cookie>,
33}
34
35pub fn parse_request_meta<B>(req: &Request<B>, is_mitm: bool) -> RequestMeta {
36    let method = req.method().to_string();
37    let mut url_str = req.uri().to_string();
38    
39    // Attempt to construct absolute URL if relative
40    if Url::parse(&url_str).is_err()
41        && let Some(host) = req.headers().get("Host").and_then(|v| v.to_str().ok()) {
42             let scheme = if is_mitm { "https" } else { "http" };
43             let new_url = format!("{}://{}{}", scheme, host, url_str);
44             if Url::parse(&new_url).is_ok() {
45                 url_str = new_url;
46             }
47        }
48
49    let version = format!("{:?}", req.version());
50    
51    let headers: Vec<(String, String)> = req.headers()
52        .iter()
53        .map(|(k, v)| (k.to_string(), v.to_str().unwrap_or("").to_string()))
54        .collect();
55
56    let query: Vec<(String, String)> = if let Ok(parsed_url) = Url::parse(&url_str) {
57        parsed_url.query_pairs().into_owned().collect()
58    } else {
59        vec![]
60    };
61
62    let mut cookies = Vec::new();
63    if let Some(cookie_header) = req.headers().get(hyper::header::COOKIE)
64        && let Ok(cookie_str) = cookie_header.to_str() {
65             for c in CookieCrate::split_parse(cookie_str).flatten() {
66                 cookies.push(Cookie {
67                     name: c.name().to_string(),
68                     value: c.value().to_string(),
69                     path: None,
70                     domain: None,
71                     expires: None,
72                     http_only: None,
73                     secure: None,
74                 });
75             }
76        }
77
78    RequestMeta {
79        method,
80        url_str,
81        version,
82        headers,
83        query,
84        cookies,
85    }
86}
87
88pub fn is_hop_by_hop(name: &str) -> bool {
89    name.eq_ignore_ascii_case("connection")
90        || name.eq_ignore_ascii_case("keep-alive")
91        || name.eq_ignore_ascii_case("proxy-authenticate")
92        || name.eq_ignore_ascii_case("proxy-authorization")
93        || name.eq_ignore_ascii_case("te")
94        || name.eq_ignore_ascii_case("trailers")
95        || name.eq_ignore_ascii_case("transfer-encoding")
96        || name.eq_ignore_ascii_case("upgrade")
97        || name.eq_ignore_ascii_case("content-length")
98}
99
100pub fn create_initial_flow(
101    meta: RequestMeta,
102    req_body: Option<BodyData>,
103    client_addr: SocketAddr,
104    is_mitm: bool,
105    is_websocket: bool,
106) -> Flow {
107    let flow_id = Uuid::new_v4();
108    let start_time = Utc::now();
109    
110    let network_info = NetworkInfo {
111        client_ip: client_addr.ip().to_string(),
112        client_port: client_addr.port(),
113        server_ip: "0.0.0.0".to_string(), // Placeholder
114        server_port: 0,                   // Placeholder
115        protocol: TransportProtocol::TCP,
116        tls: is_mitm,
117        tls_version: None,
118        sni: None,
119    };
120
121    let http_request = HttpRequest {
122        method: meta.method,
123        url: Url::parse(&meta.url_str).unwrap_or_else(|_| Url::parse("http://unknown").unwrap()),
124        version: meta.version,
125        headers: meta.headers,
126        cookies: meta.cookies,
127        query: meta.query,
128        body: req_body, 
129    };
130
131    let mut flow = if is_websocket {
132        Flow {
133            id: flow_id,
134            start_time,
135            end_time: None,
136            network: network_info,
137            layer: Layer::WebSocket(WebSocketLayer {
138                handshake_request: http_request,
139                handshake_response: HttpResponse {
140                    status: 0,
141                    status_text: "".to_string(),
142                    version: "".to_string(),
143                    headers: vec![],
144                    cookies: vec![],
145                    body: None,
146                    timing: relay_core_api::flow::ResponseTiming { time_to_first_byte: None, time_to_last_byte: None },
147                },
148                messages: vec![],
149                closed: false,
150            }),
151            tags: vec!["websocket".to_string()],
152            meta: std::collections::HashMap::new(),
153        }
154    } else {
155        Flow {
156            id: flow_id,
157            start_time,
158            end_time: None,
159            network: network_info,
160            layer: Layer::Http(HttpLayer {
161                request: http_request,
162                response: None,
163                error: None,
164            }),
165            tags: vec!["proxy".to_string()],
166            meta: std::collections::HashMap::new(),
167        }
168    };
169
170    if is_mitm {
171        flow.tags.push("mitm".to_string());
172    }
173
174    flow
175}
176
177pub fn create_error_response(status: StatusCode, message: impl Into<Bytes>) -> Response<HttpBody> {
178    Response::builder()
179        .status(status)
180        .body(Full::new(message.into()).map_err(|e| e.into()).boxed())
181        .unwrap_or_else(|_| Response::new(Full::new(Bytes::from("Internal Error")).map_err(|e| e.into()).boxed()))
182}
183
184pub fn mock_to_response(mock: HttpResponse) -> Response<HttpBody> {
185     let mut builder = Response::builder()
186        .status(StatusCode::from_u16(mock.status).unwrap_or(StatusCode::OK));
187        
188    for (k, v) in mock.headers {
189        if let (Ok(name), Ok(val)) = (HeaderName::from_bytes(k.as_bytes()), HeaderValue::from_str(&v)) {
190            builder = builder.header(name, val);
191        }
192    }
193    
194    let body = if let Some(b) = mock.body {
195        Bytes::from(b.content)
196    } else {
197        Bytes::new()
198    };
199    
200    builder.body(Full::new(body).map_err(|e| e.into()).boxed()).unwrap_or_else(|_| create_error_response(StatusCode::INTERNAL_SERVER_ERROR, "Failed to build mock response"))
201}
202
203#[allow(clippy::result_large_err)]
204pub fn build_forward_request(
205    flow: &mut Flow,
206    body: HttpBody,
207    target_addr: Option<SocketAddr>,
208    policy: &ProxyPolicy,
209    loop_detector: &LoopDetector,
210) -> Result<Request<HttpBody>, Response<HttpBody>> {
211    let current_req = if let Layer::Http(http) = &flow.layer {
212        &http.request
213    } else {
214        return Err(create_error_response(StatusCode::INTERNAL_SERVER_ERROR, "Invalid Flow Layer State"));
215    };
216
217    let mut forward_req_builder = Request::builder()
218        .method(current_req.method.as_str());
219
220    // Determine upstream URI
221    let mut target_url = current_req.url.clone();
222    
223    // Transparent Proxy Routing Logic
224    if policy.transparent_enabled
225        && let Some(addr) = target_addr {
226            flow.tags.push("transparent".to_string());
227            
228            // Update Flow Network Info
229            flow.network.server_ip = addr.ip().to_string();
230            flow.network.server_port = addr.port();
231
232            // Loop Detection
233            if loop_detector.would_loop(addr) {
234                if let Layer::Http(http) = &mut flow.layer {
235                    http.error = Some("Loop Detected".to_string());
236                }
237                return Err(create_error_response(StatusCode::LOOP_DETECTED, "Loop Detected"));
238            }
239
240            // Rewrite URI to use target IP
241            if target_url.set_ip_host(addr.ip()).is_ok() {
242                 target_url.set_port(Some(addr.port())).ok();
243            }
244
245            // Update scheme if MITM
246            if flow.network.tls && target_url.scheme() == "http" {
247                target_url.set_scheme("https").ok();
248            }
249        }
250
251    forward_req_builder = forward_req_builder.uri(target_url.as_str());
252
253    for (k, v) in &current_req.headers {
254        // Filter out hop-by-hop headers to allow connection pooling
255        if is_hop_by_hop(k) {
256            continue;
257        }
258
259        if let (Ok(name), Ok(val)) = (HeaderName::from_bytes(k.as_bytes()), HeaderValue::from_str(v)) {
260            forward_req_builder = forward_req_builder.header(name, val);
261        }
262    }
263
264    match forward_req_builder.body(body) {
265        Ok(req) => Ok(req),
266        Err(e) => Err(create_error_response(StatusCode::INTERNAL_SERVER_ERROR, format!("Failed to build forward request: {}", e))),
267    }
268}
269
270pub fn update_flow_with_response_headers(
271    flow: &mut Flow,
272    status: StatusCode,
273    version: hyper::Version,
274    headers: &hyper::HeaderMap,
275) {
276    let mut response_cookies = Vec::new();
277    for (k, v) in headers.iter() {
278        if k == hyper::header::SET_COOKIE
279            && let Ok(v_str) = v.to_str()
280                && let Ok(c) = CookieCrate::parse(v_str) {
281                    response_cookies.push(Cookie {
282                        name: c.name().to_string(),
283                        value: c.value().to_string(),
284                        path: c.path().map(|s| s.to_string()),
285                        domain: c.domain().map(|s| s.to_string()),
286                        expires: c.expires().map(|e| format!("{:?}", e)),
287                        http_only: c.http_only(),
288                        secure: c.secure(),
289                    });
290                }
291    }
292
293    let resp_headers_vec: Vec<(String, String)> = headers.iter()
294        .map(|(k, v)| (k.to_string(), v.to_str().unwrap_or("").to_string()))
295        .collect();
296
297    let http_response = HttpResponse {
298        status: status.as_u16(),
299        status_text: status.to_string(),
300        version: format!("{:?}", version),
301        headers: resp_headers_vec,
302        cookies: response_cookies,
303        body: None,
304        timing: relay_core_api::flow::ResponseTiming {
305            time_to_first_byte: None,
306            time_to_last_byte: None,
307        },
308    };
309
310    match &mut flow.layer {
311        Layer::Http(http) => {
312            http.response = Some(http_response);
313        },
314        Layer::WebSocket(ws) => {
315            ws.handshake_response = http_response;
316        },
317        _ => {}
318    }
319}
320
321pub fn update_flow_with_response_body(
322    flow: &mut Flow,
323    body_bytes: Bytes,
324) {
325    let headers = match &flow.layer {
326        Layer::Http(http) => http.response.as_ref().map(|r| r.headers.clone()).unwrap_or_default(),
327        Layer::WebSocket(ws) => ws.handshake_response.headers.clone(),
328        _ => Vec::new(),
329    };
330
331    let (resp_encoding, resp_content) = process_body(&body_bytes, &headers);
332    
333    let body_data = BodyData {
334        encoding: resp_encoding,
335        content: resp_content,
336        size: body_bytes.len() as u64,
337    };
338
339    match &mut flow.layer {
340        Layer::Http(http) => {
341            if let Some(resp) = &mut http.response {
342                resp.body = Some(body_data);
343            }
344        },
345        Layer::WebSocket(ws) => {
346            ws.handshake_response.body = Some(body_data);
347        },
348        _ => {}
349    }
350}
351
352pub fn update_flow_with_response(
353    flow: &mut Flow,
354    status: StatusCode,
355    version: hyper::Version,
356    headers: &hyper::HeaderMap,
357    body_bytes: Bytes,
358) {
359    update_flow_with_response_headers(flow, status, version, headers);
360    update_flow_with_response_body(flow, body_bytes);
361}
362
363pub fn build_client_response_from_flow(flow: &Flow, default_version: hyper::Version, strict_mode: bool) -> Result<Response<Full<Bytes>>, String> {
364    if let Layer::Http(http) = &flow.layer {
365        if let Some(response) = &http.response {
366            let status = match StatusCode::from_u16(response.status) {
367                Ok(s) => s,
368                Err(_) => {
369                    if strict_mode {
370                        return Err(format!("Invalid status code: {}", response.status));
371                    }
372                    StatusCode::OK
373                }
374            };
375
376            let mut builder = Response::builder()
377                .status(status)
378                .version(default_version); // TODO: Parse version from flow string if needed
379
380            for (k, v) in &response.headers {
381                // Filter out transport-level headers that might conflict with the new body
382                if k.eq_ignore_ascii_case("content-length") 
383                    || k.eq_ignore_ascii_case("transfer-encoding") 
384                    || k.eq_ignore_ascii_case("connection") {
385                    continue;
386                }
387
388                if let (Ok(name), Ok(val)) = (HeaderName::from_bytes(k.as_bytes()), HeaderValue::from_str(v)) {
389                    builder = builder.header(name, val);
390                } else if strict_mode {
391                    return Err(format!("Invalid header: {}: {}", k, v));
392                }
393            }
394
395            let body_bytes = if let Some(b) = &response.body {
396                 if b.encoding == "base64" {
397                    match BASE64.decode(b.content.as_bytes()) {
398                        Ok(bytes) => Bytes::from(bytes),
399                        Err(_e) => {
400                            // Fallback
401                            Bytes::from(b.content.clone()) 
402                        }
403                    }
404                 } else {
405                    Bytes::from(b.content.clone())
406                 }
407            } else {
408                Bytes::new()
409            };
410
411            builder.body(Full::new(body_bytes))
412                .map_err(|e| format!("Failed to build response: {}", e))
413        } else {
414             Err("No response in flow".to_string())
415        }
416    } else {
417        Err("Not HTTP layer".to_string())
418    }
419}
420
421#[cfg(test)]
422mod tests {
423    use super::{build_client_response_from_flow, parse_request_meta};
424    use chrono::Utc;
425    use http_body_util::BodyExt;
426    use hyper::{Request, StatusCode, Version};
427    use relay_core_api::flow::{
428        Flow, HttpLayer, HttpRequest, HttpResponse, Layer, NetworkInfo, ResponseTiming,
429        TransportProtocol,
430    };
431    use std::collections::HashMap;
432    use url::Url;
433    use uuid::Uuid;
434
435    fn sample_flow_with_response(status: u16) -> Flow {
436        Flow {
437            id: Uuid::new_v4(),
438            start_time: Utc::now(),
439            end_time: None,
440            network: NetworkInfo {
441                client_ip: "127.0.0.1".to_string(),
442                client_port: 12345,
443                server_ip: "1.1.1.1".to_string(),
444                server_port: 80,
445                protocol: TransportProtocol::TCP,
446                tls: false,
447                tls_version: None,
448                sni: None,
449            },
450            layer: Layer::Http(HttpLayer {
451                request: HttpRequest {
452                    method: "GET".to_string(),
453                    url: Url::parse("http://example.com/a").expect("url"),
454                    version: "HTTP/1.1".to_string(),
455                    headers: vec![],
456                    cookies: vec![],
457                    query: vec![],
458                    body: None,
459                },
460                response: Some(HttpResponse {
461                    status,
462                    status_text: "X".to_string(),
463                    version: "HTTP/2.0".to_string(),
464                    headers: vec![
465                        ("X-Test".to_string(), "1".to_string()),
466                        ("content-length".to_string(), "999".to_string()),
467                        ("connection".to_string(), "keep-alive".to_string()),
468                    ],
469                    cookies: vec![],
470                    body: None,
471                    timing: ResponseTiming {
472                        time_to_first_byte: None,
473                        time_to_last_byte: None,
474                    },
475                }),
476                error: None,
477            }),
478            tags: vec![],
479            meta: HashMap::new(),
480        }
481    }
482
483    #[test]
484    fn test_parse_request_meta_relative_uri_uses_host_http() {
485        let req = Request::builder()
486            .uri("/api/v1?q=1")
487            .header("Host", "example.com:8080")
488            .body(())
489            .expect("request");
490        let meta = parse_request_meta(&req, false);
491        assert_eq!(meta.url_str, "http://example.com:8080/api/v1?q=1");
492        assert_eq!(meta.query, vec![("q".to_string(), "1".to_string())]);
493    }
494
495    #[test]
496    fn test_parse_request_meta_relative_uri_uses_host_https_in_mitm() {
497        let req = Request::builder()
498            .uri("/secure")
499            .header("Host", "secure.example.com")
500            .body(())
501            .expect("request");
502        let meta = parse_request_meta(&req, true);
503        assert_eq!(meta.url_str, "https://secure.example.com/secure");
504    }
505
506    #[test]
507    fn test_build_client_response_from_flow_uses_default_version_currently() {
508        let flow = sample_flow_with_response(201);
509        let resp = build_client_response_from_flow(&flow, Version::HTTP_11, true)
510            .expect("response should build");
511        assert_eq!(resp.version(), Version::HTTP_11);
512        assert_eq!(resp.status(), StatusCode::CREATED);
513        assert_eq!(resp.headers().get("x-test").and_then(|v| v.to_str().ok()), Some("1"));
514        assert!(
515            resp.headers().get("content-length").is_none(),
516            "content-length should be stripped from forwarded mock response"
517        );
518        assert!(resp.headers().get("connection").is_none());
519    }
520
521    #[test]
522    fn test_build_client_response_from_flow_invalid_status_strict_fails() {
523        let flow = sample_flow_with_response(1000);
524        let err = build_client_response_from_flow(&flow, Version::HTTP_11, true)
525            .expect_err("strict mode should reject invalid status");
526        assert!(err.contains("Invalid status code"));
527    }
528
529    #[tokio::test]
530    async fn test_build_client_response_from_flow_invalid_status_non_strict_fallback_ok() {
531        let mut flow = sample_flow_with_response(1000);
532        if let Layer::Http(http) = &mut flow.layer {
533            if let Some(res) = &mut http.response {
534                res.body = Some(relay_core_api::flow::BodyData {
535                    encoding: "utf-8".to_string(),
536                    content: "hello".to_string(),
537                    size: 5,
538                });
539            }
540        }
541
542        let resp = build_client_response_from_flow(&flow, Version::HTTP_11, false)
543            .expect("non-strict should fallback");
544        assert_eq!(resp.status(), StatusCode::OK);
545        let body = resp
546            .into_body()
547            .collect()
548            .await
549            .expect("collect body")
550            .to_bytes();
551        assert_eq!(body.as_ref(), b"hello");
552    }
553}