mockforge-http 0.3.116

HTTP/REST protocol support for MockForge
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
//! Browser/Mobile Proxy Server
//!
//! Provides an intercepting proxy for frontend/mobile clients with HTTPS support,
//! certificate injection, and comprehensive request/response logging.

use axum::{
    extract::Request, http::StatusCode, middleware::Next, response::Response, routing::get, Router,
};
use mockforge_core::proxy::{body_transform::BodyTransformationMiddleware, config::ProxyConfig};
use serde::Serialize;
use std::net::SocketAddr;
use std::sync::Arc;
use tokio::sync::RwLock;
use tracing::{debug, error, info, warn};

/// Proxy server state
#[derive(Debug)]
pub struct ProxyServer {
    /// Proxy configuration
    config: Arc<RwLock<ProxyConfig>>,
    /// Request logging enabled
    log_requests: bool,
    /// Response logging enabled
    log_responses: bool,
    /// Request counter for logging
    request_counter: Arc<RwLock<u64>>,
    /// Server start time for uptime and rate calculations
    start_time: std::time::Instant,
    /// Total response time in milliseconds for average calculation
    total_response_time_ms: Arc<RwLock<u64>>,
    /// Error counter for error rate calculation
    error_counter: Arc<RwLock<u64>>,
}

impl ProxyServer {
    /// Create a new proxy server
    pub fn new(config: ProxyConfig, log_requests: bool, log_responses: bool) -> Self {
        Self {
            config: Arc::new(RwLock::new(config)),
            log_requests,
            log_responses,
            request_counter: Arc::new(RwLock::new(0)),
            start_time: std::time::Instant::now(),
            total_response_time_ms: Arc::new(RwLock::new(0)),
            error_counter: Arc::new(RwLock::new(0)),
        }
    }

    /// Get the Axum router for the proxy server
    pub fn router(self) -> Router {
        let state = Arc::new(self);
        let state_for_middleware = state.clone();

        Router::new()
            // Health check endpoint
            .route("/proxy/health", get(health_check))
            // Catch-all proxy handler - use fallback for all methods
            .fallback(proxy_handler)
            .with_state(state)
            .layer(axum::middleware::from_fn_with_state(state_for_middleware, logging_middleware))
    }
}

/// Health check endpoint for the proxy
async fn health_check() -> Result<Response<String>, StatusCode> {
    // Response builder should never fail with known-good values, but handle errors gracefully
    Response::builder()
        .status(StatusCode::OK)
        .header("Content-Type", "application/json")
        .body(r#"{"status":"healthy","service":"mockforge-proxy"}"#.to_string())
        .map_err(|e| {
            tracing::error!("Failed to build health check response: {}", e);
            StatusCode::INTERNAL_SERVER_ERROR
        })
}

/// Main proxy handler that intercepts and forwards requests
async fn proxy_handler(
    axum::extract::State(state): axum::extract::State<Arc<ProxyServer>>,
    request: http::Request<axum::body::Body>,
) -> Result<Response<String>, StatusCode> {
    // Extract client address from request extensions (set by ConnectInfo middleware)
    let client_addr = request
        .extensions()
        .get::<SocketAddr>()
        .copied()
        .unwrap_or_else(|| SocketAddr::from(([0, 0, 0, 0], 0)));

    let method = request.method().clone();
    let uri = request.uri().clone();
    let headers = request.headers().clone();

    // Read request body early for conditional evaluation (consume the body)
    let body_bytes = match axum::body::to_bytes(request.into_body(), usize::MAX).await {
        Ok(bytes) => Some(bytes.to_vec()),
        Err(e) => {
            error!("Failed to read request body: {}", e);
            None
        }
    };

    let config = state.config.read().await;

    // Check if proxy is enabled
    if !config.enabled {
        return Err(StatusCode::SERVICE_UNAVAILABLE);
    }

    // Determine if this request should be proxied (with conditional evaluation)
    if !config.should_proxy_with_condition(&method, &uri, &headers, body_bytes.as_deref()) {
        return Err(StatusCode::NOT_FOUND);
    }

    // Get the stripped path (without proxy prefix)
    let stripped_path = config.strip_prefix(uri.path());

    // Get the base upstream URL and construct the full URL
    let base_upstream_url = config.get_upstream_url(uri.path());
    let full_upstream_url =
        if stripped_path.starts_with("http://") || stripped_path.starts_with("https://") {
            stripped_path.clone()
        } else {
            let base = base_upstream_url.trim_end_matches('/');
            let path = stripped_path.trim_start_matches('/');
            let query = uri.query().map(|q| format!("?{}", q)).unwrap_or_default();
            if path.is_empty() || path == "/" {
                format!("{}{}", base, query)
            } else {
                format!("{}/{}", base, path) + &query
            }
        };

    // Create a new URI with the full upstream URL for the proxy handler
    let _modified_uri = full_upstream_url.parse::<http::Uri>().unwrap_or_else(|_| uri.clone());

    // Log the request if enabled
    if state.log_requests {
        let mut counter = state.request_counter.write().await;
        *counter += 1;
        let request_id = *counter;

        info!(
            request_id = request_id,
            method = %method,
            path = %uri.path(),
            upstream = %full_upstream_url,
            client_ip = %client_addr.ip(),
            "Proxy request intercepted"
        );
    }

    // Convert headers to HashMap for the proxy handler
    let mut header_map = std::collections::HashMap::new();
    for (key, value) in &headers {
        if let Ok(value_str) = value.to_str() {
            header_map.insert(key.to_string(), value_str.to_string());
        }
    }

    // Use ProxyClient directly with the full upstream URL to bypass ProxyHandler's URL construction
    use mockforge_core::proxy::client::ProxyClient;
    let proxy_client = ProxyClient::new();

    // Convert method to reqwest method
    let reqwest_method = match method.as_str() {
        "GET" => reqwest::Method::GET,
        "POST" => reqwest::Method::POST,
        "PUT" => reqwest::Method::PUT,
        "DELETE" => reqwest::Method::DELETE,
        "HEAD" => reqwest::Method::HEAD,
        "OPTIONS" => reqwest::Method::OPTIONS,
        "PATCH" => reqwest::Method::PATCH,
        _ => {
            error!("Unsupported HTTP method: {}", method);
            return Err(StatusCode::METHOD_NOT_ALLOWED);
        }
    };

    // Add any configured headers
    for (key, value) in &config.headers {
        header_map.insert(key.clone(), value.clone());
    }

    // Apply request body transformations if configured
    let mut transformed_request_body = body_bytes.clone();
    if !config.request_replacements.is_empty() {
        let transform_middleware = BodyTransformationMiddleware::new(
            config.request_replacements.clone(),
            Vec::new(), // No response rules needed here
        );
        if let Err(e) =
            transform_middleware.transform_request_body(uri.path(), &mut transformed_request_body)
        {
            warn!("Failed to transform request body: {}", e);
            // Continue with original body if transformation fails
        }
    }

    match proxy_client
        .send_request(
            reqwest_method,
            &full_upstream_url,
            &header_map,
            transformed_request_body.as_deref(),
        )
        .await
    {
        Ok(response) => {
            let status = StatusCode::from_u16(response.status().as_u16())
                .unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);

            // Log the response if enabled
            if state.log_responses {
                info!(
                    method = %method,
                    path = %uri.path(),
                    status = status.as_u16(),
                    "Proxy response sent"
                );
            }

            // Convert response headers
            let mut response_headers = http::HeaderMap::new();
            for (name, value) in response.headers() {
                if let (Ok(header_name), Ok(header_value)) = (
                    http::HeaderName::try_from(name.as_str()),
                    http::HeaderValue::try_from(value.as_bytes()),
                ) {
                    response_headers.insert(header_name, header_value);
                }
            }

            // Read response body
            let response_body_bytes = response.bytes().await.map_err(|e| {
                error!("Failed to read proxy response body: {}", e);
                StatusCode::BAD_GATEWAY
            })?;

            // Apply response body transformations if configured
            let mut final_body_bytes = response_body_bytes.to_vec();
            {
                let config_for_response = state.config.read().await;
                if !config_for_response.response_replacements.is_empty() {
                    let transform_middleware = BodyTransformationMiddleware::new(
                        Vec::new(), // No request rules needed here
                        config_for_response.response_replacements.clone(),
                    );
                    let mut body_option = Some(final_body_bytes.clone());
                    if let Err(e) = transform_middleware.transform_response_body(
                        uri.path(),
                        status.as_u16(),
                        &mut body_option,
                    ) {
                        warn!("Failed to transform response body: {}", e);
                        // Continue with original body if transformation fails
                    } else if let Some(transformed_body) = body_option {
                        final_body_bytes = transformed_body;
                    }
                }
            }

            let body_string = String::from_utf8_lossy(&final_body_bytes).to_string();

            // Build Axum response
            let mut response_builder = Response::builder().status(status);
            for (name, value) in response_headers.iter() {
                response_builder = response_builder.header(name, value);
            }

            response_builder
                .body(body_string)
                .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)
        }
        Err(e) => {
            error!("Proxy request failed: {}", e);
            Err(StatusCode::BAD_GATEWAY)
        }
    }
}

/// Middleware for logging requests and responses
async fn logging_middleware(
    axum::extract::State(state): axum::extract::State<Arc<ProxyServer>>,
    request: Request,
    next: Next,
) -> Response {
    let start = std::time::Instant::now();
    let method = request.method().clone();
    let uri = request.uri().clone();

    // Extract client address from request extensions
    let client_addr = request
        .extensions()
        .get::<SocketAddr>()
        .copied()
        .unwrap_or_else(|| SocketAddr::from(([0, 0, 0, 0], 0)));

    debug!(
        method = %method,
        uri = %uri,
        client_ip = %client_addr.ip(),
        "Request received"
    );

    let response = next.run(request).await;
    let duration = start.elapsed();

    // Track response time
    {
        let mut total_time = state.total_response_time_ms.write().await;
        *total_time += duration.as_millis() as u64;
    }

    // Track server errors
    if response.status().is_server_error() {
        let mut errors = state.error_counter.write().await;
        *errors += 1;
    }

    debug!(
        method = %method,
        uri = %uri,
        status = %response.status(),
        duration_ms = duration.as_millis(),
        "Response sent"
    );

    response
}

/// Proxy statistics for monitoring
#[derive(Debug, Serialize)]
pub struct ProxyStats {
    /// Total requests processed
    pub total_requests: u64,
    /// Requests per second
    pub requests_per_second: f64,
    /// Average response time in milliseconds
    pub avg_response_time_ms: f64,
    /// Error rate percentage
    pub error_rate_percent: f64,
}

/// Get proxy statistics
pub async fn get_proxy_stats(state: &ProxyServer) -> ProxyStats {
    let total_requests = *state.request_counter.read().await;
    let total_response_time_ms = *state.total_response_time_ms.read().await;
    let error_count = *state.error_counter.read().await;

    let elapsed_secs = state.start_time.elapsed().as_secs_f64();
    let requests_per_second = if elapsed_secs > 0.0 {
        total_requests as f64 / elapsed_secs
    } else {
        0.0
    };

    let avg_response_time_ms = if total_requests > 0 {
        total_response_time_ms as f64 / total_requests as f64
    } else {
        0.0
    };

    let error_rate_percent = if total_requests > 0 {
        (error_count as f64 / total_requests as f64) * 100.0
    } else {
        0.0
    };

    ProxyStats {
        total_requests,
        requests_per_second,
        avg_response_time_ms,
        error_rate_percent,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use axum::http::StatusCode;
    use mockforge_core::proxy::config::ProxyConfig;

    #[tokio::test]
    async fn test_proxy_server_creation() {
        let config = ProxyConfig::default();
        let server = ProxyServer::new(config, true, true);

        // Test that the server can be created
        assert!(server.log_requests);
        assert!(server.log_responses);
    }

    #[tokio::test]
    async fn test_health_check() {
        let response = health_check().await.unwrap();
        assert_eq!(response.status(), StatusCode::OK);

        // Response body is already a String
        let body = response.into_body();

        assert!(body.contains("healthy"));
        assert!(body.contains("mockforge-proxy"));
    }

    #[tokio::test]
    async fn test_proxy_stats() {
        let config = ProxyConfig::default();
        let server = ProxyServer::new(config, false, false);

        // With zero requests, all derived stats should be zero
        let stats = get_proxy_stats(&server).await;
        assert_eq!(stats.total_requests, 0);
        assert_eq!(stats.avg_response_time_ms, 0.0);
        assert_eq!(stats.error_rate_percent, 0.0);
    }
}