relay-core-lib 0.3.6

[Internal] Transport and interception engine for relay-core-runtime. Use `relay-core-runtime` instead.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
use std::convert::Infallible;
use std::net::SocketAddr;
use std::sync::Arc;
use tokio::sync::{mpsc::Sender, watch};

use crate::capture::loop_detection::LoopDetector;
use crate::interceptor::{
    BoxError, HttpBody, InterceptionResult, Interceptor, RequestAction, ResponseAction,
};
use crate::proxy::http_utils::{
    HttpsClient, build_forward_request, create_error_response, create_initial_flow,
    mock_to_response, parse_request_meta, update_flow_with_response_headers,
};
use crate::proxy::tap::TapBody;
use crate::proxy::tunnel;
use crate::proxy::websocket::handle_websocket_handshake;
use crate::tls::CertificateAuthority;
use http_body_util::{BodyExt, Full};
use hyper::body::{Body, Bytes, Incoming};
use hyper::{Method, Request, Response, StatusCode};
use relay_core_api::flow::{Direction, FlowUpdate, Layer};
use relay_core_api::policy::ProxyPolicy;

/// Main entry point for HTTP Proxy handling
#[allow(clippy::too_many_arguments)]
pub async fn handle_request(
    req: Request<Incoming>,
    client_addr: SocketAddr,
    on_flow: Sender<FlowUpdate>,
    ca: Arc<CertificateAuthority>,
    client: Arc<HttpsClient>,
    interceptor: Arc<dyn Interceptor>,
    target_addr: Option<SocketAddr>,
    policy_rx: watch::Receiver<ProxyPolicy>,
    loop_detector: Arc<LoopDetector>,
) -> Result<Response<HttpBody>, Infallible> {
    if req.method() == Method::CONNECT {
        // Handle CONNECT (HTTPS Tunnel)
        // Extract host from authority
        let host = if let Some(authority) = req.uri().authority() {
            authority.to_string()
        } else {
            // Fallback: try to get from Host header
            req.headers()
                .get("Host")
                .and_then(|v| v.to_str().ok())
                .map(|s| s.to_string())
                .unwrap_or_else(|| "unknown".to_string())
        };

        if host == "unknown" {
            return Ok(create_error_response(
                StatusCode::BAD_REQUEST,
                "CONNECT must have authority",
            ));
        }

        let loop_detector = loop_detector.clone();
        let policy_rx = policy_rx.clone();

        tokio::task::spawn(async move {
            match hyper::upgrade::on(req).await {
                Ok(upgraded) => {
                    if let Err(e) = tunnel::handle_tunnel(
                        upgraded,
                        host,
                        client_addr,
                        ca,
                        on_flow,
                        client,
                        interceptor,
                        policy_rx,
                        target_addr,
                        loop_detector,
                    )
                    .await
                    {
                        tracing::error!("Tunnel error: {}", e);
                    }
                }
                Err(e) => tracing::error!("Upgrade error: {}", e),
            }
        });
        return Ok(Response::new(
            Full::new(Bytes::new()).map_err(|e| e.into()).boxed(),
        ));
    }

    // Handle Standard HTTP / WebSocket
    handle_http_request(
        req,
        client_addr,
        on_flow,
        client,
        interceptor,
        false,
        policy_rx,
        target_addr,
        loop_detector,
    )
    .await
}

#[allow(clippy::too_many_arguments)]
pub(crate) async fn handle_http_request<B>(
    req: Request<B>,
    client_addr: SocketAddr,
    on_flow: Sender<FlowUpdate>,
    client: Arc<HttpsClient>,
    interceptor: Arc<dyn Interceptor>,
    is_mitm: bool,
    policy_rx: watch::Receiver<ProxyPolicy>,
    target_addr: Option<SocketAddr>,
    loop_detector: Arc<LoopDetector>,
) -> Result<Response<HttpBody>, Infallible>
where
    B: Body + Send + Sync + Unpin + 'static,
    B::Data: Send + Into<Bytes>,
    B::Error: Into<BoxError>,
{
    let policy = policy_rx.borrow().clone();

    // Check Content-Length against policy
    if let Some(cl) = req.headers().get(hyper::header::CONTENT_LENGTH)
        && let Ok(len) = cl.to_str().unwrap_or_default().parse::<usize>()
        && len > policy.max_body_size
    {
        return Ok(create_error_response(
            StatusCode::PAYLOAD_TOO_LARGE,
            "Request body too large",
        ));
    }

    // Create Flow
    let meta = parse_request_meta(&req, is_mitm);

    // Note: We don't read body here for streaming support
    let mut flow = create_initial_flow(meta, None, client_addr, is_mitm, false);

    // Check for WebSocket
    if hyper_tungstenite::is_upgrade_request(&req) {
        return handle_websocket_handshake(
            req,
            client_addr,
            on_flow,
            client,
            interceptor,
            is_mitm,
            policy_rx,
            target_addr,
            loop_detector,
        )
        .await;
    }

    if let Err(e) = on_flow.send(FlowUpdate::Full(Box::new(flow.clone()))).await {
        tracing::error!("Failed to send flow update: {}", e);
    }

    // Phase 1: Request Headers Interception
    match interceptor.on_request_headers(&mut flow).await {
        InterceptionResult::Continue => {}
        InterceptionResult::Drop => {
            if let Err(e) = on_flow.send(FlowUpdate::Full(Box::new(flow.clone()))).await {
                tracing::error!("Failed to send flow update on drop: {}", e);
            }
            return Ok(create_error_response(
                StatusCode::FORBIDDEN,
                "Request dropped by policy",
            ));
        }
        InterceptionResult::MockResponse(resp) => {
            if let Err(e) = on_flow.send(FlowUpdate::Full(Box::new(flow.clone()))).await {
                tracing::error!("Failed to send flow update on mock: {}", e);
            }
            return Ok(mock_to_response(resp));
        }
        InterceptionResult::ModifiedRequest(_) => {}
        InterceptionResult::ModifiedResponse(res) => {
            if let Err(e) = on_flow.send(FlowUpdate::Full(Box::new(flow.clone()))).await {
                tracing::error!("Failed to send flow update on modified response: {}", e);
            }
            return Ok(mock_to_response(res));
        }
        _ => {}
    }

    // Phase 2: Request Body Streaming & Interception
    let (_, body) = req.into_parts();
    let body: HttpBody = body
        .map_frame(|f| f.map_data(|d| d.into()))
        .map_err(|e| e.into())
        .boxed();

    // Wrap in TapBody for streaming visualization BEFORE interception
    let req_headers = if let Layer::Http(http) = &flow.layer {
        http.request.headers.clone()
    } else {
        vec![]
    };

    let tap_body = TapBody::new(
        body,
        flow.id.to_string(),
        on_flow.clone(),
        Direction::ClientToServer,
        policy.max_body_size,
        req_headers,
    );
    let mut current_body = tap_body.boxed();

    match interceptor.on_request(&mut flow, current_body).await {
        Ok(RequestAction::Continue(new_body)) => {
            current_body = new_body;
        }
        Ok(RequestAction::Drop) => {
            if let Err(e) = on_flow.send(FlowUpdate::Full(Box::new(flow.clone()))).await {
                tracing::error!("Failed to send flow update on request drop: {}", e);
            }
            return Ok(create_error_response(
                StatusCode::FORBIDDEN,
                "Request dropped by interceptor",
            ));
        }
        Ok(RequestAction::MockResponse(res)) => {
            if let Err(e) = on_flow.send(FlowUpdate::Full(Box::new(flow.clone()))).await {
                tracing::error!("Failed to send flow update on request mock: {}", e);
            }
            let (parts, body) = res.into_parts();
            return Ok(Response::from_parts(parts, body));
        }
        Err(e) => {
            tracing::error!("Interceptor error on_request: {}", e);
            return Ok(create_error_response(
                StatusCode::INTERNAL_SERVER_ERROR,
                format!("Interceptor Error: {}", e),
            ));
        }
    }

    let forward_req = match build_forward_request(
        &mut flow,
        current_body,
        target_addr,
        &policy,
        &loop_detector,
    ) {
        Ok(req) => req,
        Err(res) => return Ok(res),
    };

    // Send Request
    let upstream_start = std::time::Instant::now();
    let res = match tokio::time::timeout(
        std::time::Duration::from_millis(policy.request_timeout_ms),
        client.request(forward_req),
    )
    .await
    {
        Ok(Ok(res)) => res,
        Ok(Err(e)) => {
            tracing::error!("Upstream request failed: {}", e);
            if let Layer::Http(http) = &mut flow.layer {
                http.error = Some(format!("Upstream Error: {}", e));
            }
            if let Err(e) = on_flow.send(FlowUpdate::Full(Box::new(flow.clone()))).await {
                tracing::error!("Failed to send flow update on upstream error: {}", e);
            }
            return Ok(create_error_response(
                StatusCode::BAD_GATEWAY,
                format!("Upstream Error: {}", e),
            ));
        }
        Err(_) => {
            tracing::error!("Upstream request timed out");
            if let Layer::Http(http) = &mut flow.layer {
                http.error = Some("Upstream Request Timed Out".to_string());
            }
            if let Err(e) = on_flow.send(FlowUpdate::Full(Box::new(flow.clone()))).await {
                tracing::error!("Failed to send flow update on upstream timeout: {}", e);
            }
            return Ok(create_error_response(
                StatusCode::GATEWAY_TIMEOUT,
                "Upstream Request Timed Out",
            ));
        }
    };

    // Phase 3: Response Headers Interception
    let (mut res_parts, res_body) = res.into_parts();

    // Apply QUIC Downgrade
    apply_quic_downgrade(&mut res_parts, &mut flow, &policy);

    update_flow_with_response_headers(
        &mut flow,
        res_parts.status,
        res_parts.version,
        &res_parts.headers,
    );

    let ttfbs_ms = upstream_start.elapsed().as_millis() as u64;
    if let Layer::Http(http) = &mut flow.layer
        && let Some(response) = &mut http.response
    {
        response.timing.time_to_first_byte = Some(ttfbs_ms);
    }

    match interceptor.on_response_headers(&mut flow).await {
        InterceptionResult::Continue => {}
        InterceptionResult::Drop => {
            if let Err(e) = on_flow.send(FlowUpdate::Full(Box::new(flow.clone()))).await {
                tracing::error!("Failed to send flow update on response drop: {}", e);
            }
            return Ok(create_error_response(
                StatusCode::FORBIDDEN,
                "Response dropped by policy",
            ));
        }
        InterceptionResult::MockResponse(resp) => {
            if let Err(e) = on_flow.send(FlowUpdate::Full(Box::new(flow.clone()))).await {
                tracing::error!("Failed to send flow update on response mock: {}", e);
            }
            return Ok(mock_to_response(resp));
        }
        InterceptionResult::ModifiedResponse(resp) => {
            if let Err(e) = on_flow.send(FlowUpdate::Full(Box::new(flow.clone()))).await {
                tracing::error!("Failed to send flow update on response modification: {}", e);
            }
            return Ok(mock_to_response(resp));
        }
        _ => {}
    }

    // Phase 4: Response Body Streaming & Interception
    let res_body: HttpBody = res_body
        .map_frame(|f| f.map_data(|d| d))
        .map_err(|e| e.into())
        .boxed();

    // Wrap in TapBody for streaming visualization BEFORE interception
    let res_headers = if let Layer::Http(http) = &flow.layer {
        http.response
            .as_ref()
            .map(|r| r.headers.clone())
            .unwrap_or_default()
    } else {
        vec![]
    };

    let tap_res_body = TapBody::new(
        res_body,
        flow.id.to_string(),
        on_flow.clone(),
        Direction::ServerToClient,
        policy.max_body_size,
        res_headers,
    );
    let mut current_res_body = tap_res_body.boxed();

    match interceptor.on_response(&mut flow, current_res_body).await {
        Ok(ResponseAction::Continue(new_body)) => {
            current_res_body = new_body;
        }
        Ok(ResponseAction::Drop) => {
            if let Err(e) = on_flow.send(FlowUpdate::Full(Box::new(flow.clone()))).await {
                tracing::error!("Failed to send flow update on response body drop: {}", e);
            }
            return Ok(create_error_response(
                StatusCode::FORBIDDEN,
                "Response dropped by interceptor",
            ));
        }
        Ok(ResponseAction::ModifiedResponse(res)) => {
            if let Err(e) = on_flow.send(FlowUpdate::Full(Box::new(flow.clone()))).await {
                tracing::error!(
                    "Failed to send flow update on response body modification: {}",
                    e
                );
            }
            let (parts, body) = res.into_parts();
            return Ok(Response::from_parts(parts, body));
        }
        Err(e) => {
            tracing::error!("Interceptor error on_response: {}", e);
            return Ok(create_error_response(
                StatusCode::INTERNAL_SERVER_ERROR,
                format!("Interceptor Error: {}", e),
            ));
        }
    }

    if let Err(e) = on_flow.send(FlowUpdate::Full(Box::new(flow.clone()))).await {
        tracing::error!("Failed to send final flow update: {}", e);
    }

    // Record time-to-last-byte as total upstream-to-client latency
    if let Layer::Http(http) = &mut flow.layer
        && let Some(response) = &mut http.response
    {
        response.timing.time_to_last_byte = Some(upstream_start.elapsed().as_millis() as u64);
    }

    Ok(Response::from_parts(res_parts, current_res_body))
}

pub(crate) fn apply_quic_downgrade(
    parts: &mut hyper::http::response::Parts,
    flow: &mut relay_core_api::flow::Flow,
    policy: &ProxyPolicy,
) {
    use relay_core_api::policy::QuicMode;
    if policy.quic_mode == QuicMode::Downgrade {
        if parts.headers.remove("Alt-Svc").is_some() {
            flow.tags.push("quic-downgraded".to_string());
        }
        if policy.quic_downgrade_clear_cache {
            parts.headers.insert(
                "Clear-Site-Data",
                hyper::header::HeaderValue::from_static("\"cache\""),
            );
        }
    }
}

#[cfg(test)]
mod http_tests;