codive-relay 0.1.0

Relay server for secure tunneling
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
//! HTTP proxy handler that routes requests to tunnels

use axum::{
    body::Body,
    extract::State,
    http::{Request, Response, StatusCode},
    response::IntoResponse,
};
use base64::Engine;
use bytes::Bytes;
use std::sync::Arc;
use std::time::Duration;
use tokio_stream::wrappers::ReceiverStream;
use tracing::{debug, info, warn};

use crate::state::RelayState;
use crate::tunnel::WsMessage;

/// Check if this is an SSE request
fn is_sse_request(request: &Request<Body>) -> bool {
    // Check Accept header
    if let Some(accept) = request.headers().get("accept") {
        if let Ok(accept_str) = accept.to_str() {
            if accept_str.contains("text/event-stream") {
                return true;
            }
        }
    }

    // Check path pattern (common SSE endpoint patterns)
    let path = request.uri().path();
    path.ends_with("/events") || path.contains("/events/") || path.ends_with("/stream")
}

/// Proxy handler that routes HTTP requests to the appropriate tunnel
pub async fn proxy_handler(
    State(state): State<Arc<RelayState>>,
    request: Request<Body>,
) -> impl IntoResponse {
    // Extract host from request headers
    let host = request
        .headers()
        .get(axum::http::header::HOST)
        .and_then(|v| v.to_str().ok())
        .unwrap_or("");

    // Extract tunnel_id from subdomain
    // Host format: {tunnel_id}.relay.example.com
    let tunnel_id = match extract_tunnel_id(host, &state.config.base_domain) {
        Some(id) => id,
        None => {
            return (
                StatusCode::NOT_FOUND,
                format!("No tunnel found for host: {}", host),
            )
                .into_response();
        }
    };

    // Look up the tunnel
    let tunnel = match state.get_tunnel(&tunnel_id) {
        Some(t) => t,
        None => {
            return (
                StatusCode::BAD_GATEWAY,
                format!("Tunnel '{}' is not connected", tunnel_id),
            )
                .into_response();
        }
    };

    // Check if this is an SSE request
    let is_sse = is_sse_request(&request);

    info!(
        tunnel_id = %tunnel_id,
        method = %request.method(),
        uri = %request.uri(),
        is_sse = %is_sse,
        "Proxying request"
    );

    // Generate request ID
    let request_id = uuid::Uuid::new_v4().to_string();

    // Convert HTTP request to tunnel message
    let method = request.method().to_string();
    let path = request.uri().path().to_string();
    let query = request.uri().query().map(|s| s.to_string());

    let mut headers = std::collections::HashMap::new();
    for (name, value) in request.headers() {
        if let Ok(v) = value.to_str() {
            headers.insert(name.to_string(), v.to_string());
        }
    }

    // Read body
    let body_bytes = match axum::body::to_bytes(request.into_body(), 10 * 1024 * 1024).await {
        Ok(bytes) => bytes,
        Err(e) => {
            warn!(error = %e, "Failed to read request body");
            return (StatusCode::BAD_REQUEST, "Failed to read request body").into_response();
        }
    };

    let body = if body_bytes.is_empty() {
        None
    } else {
        Some(base64::engine::general_purpose::STANDARD.encode(&body_bytes))
    };

    // Create the data message
    let data_msg = codive_tunnel::DataMessage::HttpRequest {
        request_id: request_id.clone(),
        client_id: "proxy".to_string(),
        method,
        path,
        query,
        headers,
        body,
    };

    // Serialize the request
    let msg_bytes = serde_json::to_vec(&data_msg).unwrap();
    let wire_msg = codive_tunnel::WireMessage::encode_encrypted(
        codive_tunnel::message_type::ENCRYPTED_REQUEST,
        msg_bytes,
    );

    // IMPORTANT: Register pending request BEFORE sending to avoid race condition
    // The tunnel client might respond before we're listening otherwise
    enum ResponseReceiver {
        Regular(tokio::sync::oneshot::Receiver<codive_tunnel::DataMessage>),
        Streaming(tokio::sync::mpsc::Receiver<codive_tunnel::DataMessage>),
    }

    let response_rx = if is_sse {
        ResponseReceiver::Streaming(tunnel.register_streaming_request(request_id.clone()))
    } else {
        ResponseReceiver::Regular(tunnel.register_request(request_id.clone()))
    };

    debug!(
        request_id = %request_id,
        tunnel_id = %tunnel_id,
        is_sse = is_sse,
        "Sending request to tunnel"
    );

    if tunnel.ws_sender.send(WsMessage::Binary(wire_msg)).await.is_err() {
        tunnel.pending_requests.remove(&request_id);
        return (StatusCode::BAD_GATEWAY, "Tunnel connection lost").into_response();
    }

    debug!(
        request_id = %request_id,
        "Request sent, waiting for response"
    );

    // Handle SSE vs regular requests differently
    match response_rx {
        ResponseReceiver::Streaming(rx) => {
            handle_sse_response(tunnel, request_id, rx).await
        }
        ResponseReceiver::Regular(rx) => {
            handle_regular_response(tunnel, request_id, rx).await
        }
    }
}

/// Handle regular (non-streaming) HTTP response
async fn handle_regular_response(
    tunnel: Arc<crate::tunnel::TunnelConnection>,
    request_id: String,
    response_rx: tokio::sync::oneshot::Receiver<codive_tunnel::DataMessage>,
) -> Response<Body> {
    // Wait for response with timeout
    let timeout = Duration::from_secs(30);
    match tokio::time::timeout(timeout, response_rx).await {
        Ok(Ok(response_msg)) => {
            // Convert tunnel response to HTTP response
            build_http_response(response_msg)
        }
        Ok(Err(_)) => {
            // Channel closed - tunnel disconnected
            (StatusCode::BAD_GATEWAY, "Tunnel disconnected").into_response()
        }
        Err(_) => {
            // Timeout
            tunnel.pending_requests.remove(&request_id);
            (StatusCode::GATEWAY_TIMEOUT, "Request timed out").into_response()
        }
    }
}

/// Handle SSE streaming response
async fn handle_sse_response(
    tunnel: Arc<crate::tunnel::TunnelConnection>,
    request_id: String,
    mut response_rx: tokio::sync::mpsc::Receiver<codive_tunnel::DataMessage>,
) -> Response<Body> {
    // Wait for the initial response with headers
    let timeout = Duration::from_secs(30);
    let initial_response = match tokio::time::timeout(timeout, response_rx.recv()).await {
        Ok(Some(msg)) => msg,
        Ok(None) => {
            tunnel.complete_streaming_request(&request_id);
            return (StatusCode::BAD_GATEWAY, "Tunnel disconnected").into_response();
        }
        Err(_) => {
            tunnel.complete_streaming_request(&request_id);
            return (StatusCode::GATEWAY_TIMEOUT, "Request timed out").into_response();
        }
    };

    // Extract initial response headers
    let (status, initial_headers, initial_body) = match initial_response {
        codive_tunnel::DataMessage::HttpResponse {
            status,
            headers,
            body,
            streaming,
            ..
        } => {
            if !streaming {
                // Not actually a streaming response, handle as regular
                tunnel.complete_streaming_request(&request_id);
                let response_msg = codive_tunnel::DataMessage::HttpResponse {
                    request_id: request_id.clone(),
                    status,
                    headers,
                    body,
                    streaming: false,
                };
                return build_http_response(response_msg);
            }
            (status, headers, body)
        }
        codive_tunnel::DataMessage::RequestError { message, .. } => {
            tunnel.complete_streaming_request(&request_id);
            return Response::builder()
                .status(StatusCode::BAD_GATEWAY)
                .body(Body::from(message))
                .unwrap();
        }
        _ => {
            tunnel.complete_streaming_request(&request_id);
            return (StatusCode::INTERNAL_SERVER_ERROR, "Unexpected response type").into_response();
        }
    };

    debug!(
        request_id = %request_id,
        status = %status,
        "Starting SSE stream"
    );

    // Create a channel for the streaming body
    let (body_tx, body_rx) = tokio::sync::mpsc::channel::<Result<Bytes, std::io::Error>>(100);

    // Send initial body chunk if present
    if let Some(b64_body) = initial_body {
        if let Ok(bytes) = base64::engine::general_purpose::STANDARD.decode(&b64_body) {
            let _ = body_tx.send(Ok(Bytes::from(bytes))).await;
        }
    }

    // Spawn task to forward chunks
    let req_id = request_id.clone();
    tokio::spawn(async move {
        while let Some(msg) = response_rx.recv().await {
            match msg {
                codive_tunnel::DataMessage::HttpResponseChunk {
                    chunk,
                    is_final,
                    ..
                } => {
                    // Decode and forward chunk
                    if let Ok(bytes) = base64::engine::general_purpose::STANDARD.decode(&chunk) {
                        if body_tx.send(Ok(Bytes::from(bytes))).await.is_err() {
                            debug!(request_id = %req_id, "Client disconnected");
                            break;
                        }
                    }

                    if is_final {
                        debug!(request_id = %req_id, "SSE stream completed");
                        break;
                    }
                }
                codive_tunnel::DataMessage::RequestError { message, .. } => {
                    warn!(request_id = %req_id, error = %message, "SSE stream error");
                    break;
                }
                _ => {
                    // Ignore other message types in streaming context
                }
            }
        }
        // Channel will be dropped here, ending the stream
    });

    // Build response with streaming body
    let status = StatusCode::from_u16(status).unwrap_or(StatusCode::OK);
    let mut response = Response::builder().status(status);

    for (name, value) in initial_headers {
        response = response.header(name, value);
    }

    // Use ReceiverStream to convert mpsc receiver to stream
    let body_stream = ReceiverStream::new(body_rx);
    let body = Body::from_stream(body_stream);

    response.body(body).unwrap_or_else(|_| {
        Response::builder()
            .status(StatusCode::INTERNAL_SERVER_ERROR)
            .body(Body::from("Internal error"))
            .unwrap()
    })
}

/// Extract tunnel ID from the host header
fn extract_tunnel_id(host: &str, base_domain: &str) -> Option<String> {
    // Remove port if present
    let host = host.split(':').next().unwrap_or(host);
    let base = base_domain.split(':').next().unwrap_or(base_domain);

    // Check if host ends with base domain
    if let Some(prefix) = host.strip_suffix(base) {
        // Remove trailing dot
        let prefix = prefix.strip_suffix('.').unwrap_or(prefix);
        if !prefix.is_empty() {
            return Some(prefix.to_string());
        }
    }

    // For development: if host matches tunnel_id.localhost pattern
    if let Some(tunnel_id) = host.strip_suffix(".localhost") {
        return Some(tunnel_id.to_string());
    }

    None
}

/// Build an HTTP response from a tunnel response message
fn build_http_response(msg: codive_tunnel::DataMessage) -> Response<Body> {
    match msg {
        codive_tunnel::DataMessage::HttpResponse {
            status,
            headers,
            body,
            ..
        } => {
            let status = StatusCode::from_u16(status).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);

            let mut response = Response::builder().status(status);

            for (name, value) in headers {
                response = response.header(name, value);
            }

            let body = if let Some(b64_body) = body {
                match base64::engine::general_purpose::STANDARD.decode(&b64_body) {
                    Ok(bytes) => Body::from(bytes),
                    Err(_) => Body::from(b64_body), // Fallback to raw if not base64
                }
            } else {
                Body::empty()
            };

            response.body(body).unwrap_or_else(|_| {
                Response::builder()
                    .status(StatusCode::INTERNAL_SERVER_ERROR)
                    .body(Body::from("Internal error"))
                    .unwrap()
            })
        }
        codive_tunnel::DataMessage::RequestError { message, .. } => Response::builder()
            .status(StatusCode::BAD_GATEWAY)
            .body(Body::from(message))
            .unwrap(),
        _ => Response::builder()
            .status(StatusCode::INTERNAL_SERVER_ERROR)
            .body(Body::from("Unexpected response type"))
            .unwrap(),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_extract_tunnel_id() {
        assert_eq!(
            extract_tunnel_id("abc123.relay.example.com", "relay.example.com"),
            Some("abc123".to_string())
        );

        assert_eq!(
            extract_tunnel_id("abc123.relay.example.com:3001", "relay.example.com:3001"),
            Some("abc123".to_string())
        );

        assert_eq!(
            extract_tunnel_id("abc123.localhost", "localhost"),
            Some("abc123".to_string())
        );

        assert_eq!(
            extract_tunnel_id("relay.example.com", "relay.example.com"),
            None
        );
    }
}