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    req_parts: &http::request::Parts,
208    target_addr: Option<SocketAddr>,
209    policy: &ProxyPolicy,
210    loop_detector: &LoopDetector,
211) -> Result<Request<HttpBody>, Response<HttpBody>> {
212    let current_req = if let Layer::Http(http) = &flow.layer {
213        &http.request
214    } else {
215        return Err(create_error_response(StatusCode::INTERNAL_SERVER_ERROR, "Invalid Flow Layer State"));
216    };
217
218    let mut forward_req_builder = Request::builder()
219        .method(current_req.method.as_str());
220
221    // Determine upstream URI
222    let mut target_url = current_req.url.clone();
223    
224    // Transparent Proxy Routing Logic
225    if policy.transparent_enabled
226        && let Some(addr) = target_addr {
227            flow.tags.push("transparent".to_string());
228            
229            // Update Flow Network Info
230            flow.network.server_ip = addr.ip().to_string();
231            flow.network.server_port = addr.port();
232
233            // Loop Detection
234            if loop_detector.would_loop(addr) {
235                if let Layer::Http(http) = &mut flow.layer {
236                    http.error = Some("Loop Detected".to_string());
237                }
238                return Err(create_error_response(StatusCode::LOOP_DETECTED, "Loop Detected"));
239            }
240
241            // Rewrite URI to use target IP
242            if target_url.set_ip_host(addr.ip()).is_ok() {
243                 target_url.set_port(Some(addr.port())).ok();
244            }
245
246            // Update scheme if MITM
247            if flow.network.tls && target_url.scheme() == "http" {
248                target_url.set_scheme("https").ok();
249            }
250        }
251
252    forward_req_builder = forward_req_builder.uri(target_url.as_str());
253
254    for (k, v) in &current_req.headers {
255        // Filter out hop-by-hop headers to allow connection pooling
256        if is_hop_by_hop(k) {
257            continue;
258        }
259
260        if let (Ok(name), Ok(val)) = (HeaderName::from_bytes(k.as_bytes()), HeaderValue::from_str(v)) {
261            forward_req_builder = forward_req_builder.header(name, val);
262        }
263    }
264
265    match forward_req_builder.body(body) {
266        Ok(req) => Ok(req),
267        Err(e) => Err(create_error_response(StatusCode::INTERNAL_SERVER_ERROR, format!("Failed to build forward request: {}", e))),
268    }
269}
270
271pub fn update_flow_with_response_headers(
272    flow: &mut Flow,
273    status: StatusCode,
274    version: hyper::Version,
275    headers: &hyper::HeaderMap,
276) {
277    let mut response_cookies = Vec::new();
278    for (k, v) in headers.iter() {
279        if k == hyper::header::SET_COOKIE
280            && let Ok(v_str) = v.to_str()
281                && let Ok(c) = CookieCrate::parse(v_str) {
282                    response_cookies.push(Cookie {
283                        name: c.name().to_string(),
284                        value: c.value().to_string(),
285                        path: c.path().map(|s| s.to_string()),
286                        domain: c.domain().map(|s| s.to_string()),
287                        expires: c.expires().map(|e| format!("{:?}", e)),
288                        http_only: c.http_only(),
289                        secure: c.secure(),
290                    });
291                }
292    }
293
294    let resp_headers_vec: Vec<(String, String)> = headers.iter()
295        .map(|(k, v)| (k.to_string(), v.to_str().unwrap_or("").to_string()))
296        .collect();
297
298    let http_response = HttpResponse {
299        status: status.as_u16(),
300        status_text: status.to_string(),
301        version: format!("{:?}", version),
302        headers: resp_headers_vec,
303        cookies: response_cookies,
304        body: None,
305        timing: relay_core_api::flow::ResponseTiming {
306            time_to_first_byte: None,
307            time_to_last_byte: None,
308        },
309    };
310
311    match &mut flow.layer {
312        Layer::Http(http) => {
313            http.response = Some(http_response);
314        },
315        Layer::WebSocket(ws) => {
316            ws.handshake_response = http_response;
317        },
318        _ => {}
319    }
320}
321
322pub fn update_flow_with_response_body(
323    flow: &mut Flow,
324    body_bytes: Bytes,
325) {
326    let headers = match &flow.layer {
327        Layer::Http(http) => http.response.as_ref().map(|r| r.headers.clone()).unwrap_or_default(),
328        Layer::WebSocket(ws) => ws.handshake_response.headers.clone(),
329        _ => Vec::new(),
330    };
331
332    let (resp_encoding, resp_content) = process_body(&body_bytes, &headers);
333    
334    let body_data = BodyData {
335        encoding: resp_encoding,
336        content: resp_content,
337        size: body_bytes.len() as u64,
338    };
339
340    match &mut flow.layer {
341        Layer::Http(http) => {
342            if let Some(resp) = &mut http.response {
343                resp.body = Some(body_data);
344            }
345        },
346        Layer::WebSocket(ws) => {
347            ws.handshake_response.body = Some(body_data);
348        },
349        _ => {}
350    }
351}
352
353pub fn update_flow_with_response(
354    flow: &mut Flow,
355    status: StatusCode,
356    version: hyper::Version,
357    headers: &hyper::HeaderMap,
358    body_bytes: Bytes,
359) {
360    update_flow_with_response_headers(flow, status, version, headers);
361    update_flow_with_response_body(flow, body_bytes);
362}
363
364pub fn build_client_response_from_flow(flow: &Flow, default_version: hyper::Version, strict_mode: bool) -> Result<Response<Full<Bytes>>, String> {
365    if let Layer::Http(http) = &flow.layer {
366        if let Some(response) = &http.response {
367            let status = match StatusCode::from_u16(response.status) {
368                Ok(s) => s,
369                Err(_) => {
370                    if strict_mode {
371                        return Err(format!("Invalid status code: {}", response.status));
372                    }
373                    StatusCode::OK
374                }
375            };
376
377            let mut builder = Response::builder()
378                .status(status)
379                .version(default_version); // TODO: Parse version from flow string if needed
380
381            for (k, v) in &response.headers {
382                // Filter out transport-level headers that might conflict with the new body
383                if k.eq_ignore_ascii_case("content-length") 
384                    || k.eq_ignore_ascii_case("transfer-encoding") 
385                    || k.eq_ignore_ascii_case("connection") {
386                    continue;
387                }
388
389                if let (Ok(name), Ok(val)) = (HeaderName::from_bytes(k.as_bytes()), HeaderValue::from_str(v)) {
390                    builder = builder.header(name, val);
391                } else if strict_mode {
392                    return Err(format!("Invalid header: {}: {}", k, v));
393                }
394            }
395
396            let body_bytes = if let Some(b) = &response.body {
397                 if b.encoding == "base64" {
398                    match BASE64.decode(b.content.as_bytes()) {
399                        Ok(bytes) => Bytes::from(bytes),
400                        Err(_e) => {
401                            // Fallback
402                            Bytes::from(b.content.clone()) 
403                        }
404                    }
405                 } else {
406                    Bytes::from(b.content.clone())
407                 }
408            } else {
409                Bytes::new()
410            };
411
412            builder.body(Full::new(body_bytes))
413                .map_err(|e| format!("Failed to build response: {}", e))
414        } else {
415             Err("No response in flow".to_string())
416        }
417    } else {
418        Err("Not HTTP layer".to_string())
419    }
420}
421
422#[cfg(test)]
423mod tests {
424    use super::{build_client_response_from_flow, parse_request_meta};
425    use chrono::Utc;
426    use http_body_util::BodyExt;
427    use hyper::{Request, StatusCode, Version};
428    use relay_core_api::flow::{
429        Flow, HttpLayer, HttpRequest, HttpResponse, Layer, NetworkInfo, ResponseTiming,
430        TransportProtocol,
431    };
432    use std::collections::HashMap;
433    use url::Url;
434    use uuid::Uuid;
435
436    fn sample_flow_with_response(status: u16) -> Flow {
437        Flow {
438            id: Uuid::new_v4(),
439            start_time: Utc::now(),
440            end_time: None,
441            network: NetworkInfo {
442                client_ip: "127.0.0.1".to_string(),
443                client_port: 12345,
444                server_ip: "1.1.1.1".to_string(),
445                server_port: 80,
446                protocol: TransportProtocol::TCP,
447                tls: false,
448                tls_version: None,
449                sni: None,
450            },
451            layer: Layer::Http(HttpLayer {
452                request: HttpRequest {
453                    method: "GET".to_string(),
454                    url: Url::parse("http://example.com/a").expect("url"),
455                    version: "HTTP/1.1".to_string(),
456                    headers: vec![],
457                    cookies: vec![],
458                    query: vec![],
459                    body: None,
460                },
461                response: Some(HttpResponse {
462                    status,
463                    status_text: "X".to_string(),
464                    version: "HTTP/2.0".to_string(),
465                    headers: vec![
466                        ("X-Test".to_string(), "1".to_string()),
467                        ("content-length".to_string(), "999".to_string()),
468                        ("connection".to_string(), "keep-alive".to_string()),
469                    ],
470                    cookies: vec![],
471                    body: None,
472                    timing: ResponseTiming {
473                        time_to_first_byte: None,
474                        time_to_last_byte: None,
475                    },
476                }),
477                error: None,
478            }),
479            tags: vec![],
480            meta: HashMap::new(),
481        }
482    }
483
484    #[test]
485    fn test_parse_request_meta_relative_uri_uses_host_http() {
486        let req = Request::builder()
487            .uri("/api/v1?q=1")
488            .header("Host", "example.com:8080")
489            .body(())
490            .expect("request");
491        let meta = parse_request_meta(&req, false);
492        assert_eq!(meta.url_str, "http://example.com:8080/api/v1?q=1");
493        assert_eq!(meta.query, vec![("q".to_string(), "1".to_string())]);
494    }
495
496    #[test]
497    fn test_parse_request_meta_relative_uri_uses_host_https_in_mitm() {
498        let req = Request::builder()
499            .uri("/secure")
500            .header("Host", "secure.example.com")
501            .body(())
502            .expect("request");
503        let meta = parse_request_meta(&req, true);
504        assert_eq!(meta.url_str, "https://secure.example.com/secure");
505    }
506
507    #[test]
508    fn test_build_client_response_from_flow_uses_default_version_currently() {
509        let flow = sample_flow_with_response(201);
510        let resp = build_client_response_from_flow(&flow, Version::HTTP_11, true)
511            .expect("response should build");
512        assert_eq!(resp.version(), Version::HTTP_11);
513        assert_eq!(resp.status(), StatusCode::CREATED);
514        assert_eq!(resp.headers().get("x-test").and_then(|v| v.to_str().ok()), Some("1"));
515        assert!(
516            resp.headers().get("content-length").is_none(),
517            "content-length should be stripped from forwarded mock response"
518        );
519        assert!(resp.headers().get("connection").is_none());
520    }
521
522    #[test]
523    fn test_build_client_response_from_flow_invalid_status_strict_fails() {
524        let flow = sample_flow_with_response(1000);
525        let err = build_client_response_from_flow(&flow, Version::HTTP_11, true)
526            .expect_err("strict mode should reject invalid status");
527        assert!(err.contains("Invalid status code"));
528    }
529
530    #[tokio::test]
531    async fn test_build_client_response_from_flow_invalid_status_non_strict_fallback_ok() {
532        let mut flow = sample_flow_with_response(1000);
533        if let Layer::Http(http) = &mut flow.layer {
534            if let Some(res) = &mut http.response {
535                res.body = Some(relay_core_api::flow::BodyData {
536                    encoding: "utf-8".to_string(),
537                    content: "hello".to_string(),
538                    size: 5,
539                });
540            }
541        }
542
543        let resp = build_client_response_from_flow(&flow, Version::HTTP_11, false)
544            .expect("non-strict should fallback");
545        assert_eq!(resp.status(), StatusCode::OK);
546        let body = resp
547            .into_body()
548            .collect()
549            .await
550            .expect("collect body")
551            .to_bytes();
552        assert_eq!(body.as_ref(), b"hello");
553    }
554}