wisegate-core 0.12.0

Core library for WiseGate reverse proxy - rate limiting, IP filtering, and request handling
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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
//! HTTP request handling and proxying.
//!
//! This module contains the core request handling logic for the reverse proxy,
//! including IP validation, rate limiting, URL pattern blocking, and request forwarding.
//!
//! # Architecture
//!
//! The request handling flow:
//! 1. Extract and validate client IP from proxy headers
//! 2. Check if IP is blocked
//! 3. Check for blocked URL patterns
//! 4. Check for blocked HTTP methods
//! 5. Apply rate limiting
//! 6. Forward request to upstream service
//!
//! # Connection Pooling
//!
//! The module accepts a shared [`reqwest::Client`] for HTTP connection pooling,
//! which should be configured by the caller with appropriate timeouts.

use http_body_util::{BodyExt, Full};
use hyper::{Request, Response, StatusCode, body::Incoming};
use std::convert::Infallible;
use std::sync::Arc;

use crate::error::WiseGateError;
use crate::types::{ConfigProvider, RateLimiter};
use crate::{auth, headers, ip_filter, rate_limiter};

/// Handles an incoming HTTP request through the proxy pipeline.
///
/// This is the main entry point for request processing. It performs:
/// - Client IP extraction and validation from proxy headers
/// - IP blocking checks
/// - URL pattern blocking (e.g., `.php`, `.env` files)
/// - HTTP method blocking (e.g., `PUT`, `DELETE`)
/// - Rate limiting per client IP
/// - Request forwarding to the upstream service
///
/// # Arguments
///
/// * `req` - The incoming HTTP request
/// * `forward_host` - The upstream host to forward requests to
/// * `forward_port` - The upstream port to forward requests to
/// * `limiter` - The shared rate limiter instance
/// * `config` - Configuration provider for all settings
/// * `http_client` - HTTP client for forwarding requests (with connection pooling)
///
/// # Returns
///
/// Always returns `Ok` with either:
/// - A successful proxied response from upstream
/// - An error response (403, 404, 405, 429, 502, etc.)
///
/// # Runtime
///
/// This is an async function backed by `reqwest`/`tokio`; it must be awaited
/// from inside a Tokio runtime (`#[tokio::main]`, `Runtime::block_on`, etc.).
///
/// # Security
///
/// * **Strict mode** (proxy allowlist configured): both `X-Forwarded-For`
///   and `Forwarded` headers must be present. The proxy IP is taken from the
///   `Forwarded` header's `by=` field and matched against the allowlist; the
///   client IP is taken from the last entry of `X-Forwarded-For`. Requests
///   missing either header, or whose proxy is not in the allowlist, are
///   rejected with `400 Bad Request`.
/// * **Permissive mode** (no allowlist): if a request supplies an
///   `X-Forwarded-For` or `Forwarded` header, the parsed IP is trusted as the
///   real client IP and re-emitted to the upstream as `X-Real-IP`. An
///   attacker can spoof this value by sending fake headers — only enable
///   permissive mode when the proxy sits behind another layer that strips or
///   normalises these headers.
/// * Any client-supplied `X-Real-IP` header is stripped before processing.
/// * The `Authorization` header is stripped before forwarding whenever
///   wisegate performed authentication (see
///   [`crate::AuthenticationProvider::forward_authorization_header`]).
pub async fn handle_request<C: ConfigProvider>(
    req: Request<Incoming>,
    forward_host: Arc<str>,
    forward_port: u16,
    limiter: RateLimiter,
    config: Arc<C>,
    http_client: reqwest::Client,
) -> Result<Response<Full<bytes::Bytes>>, Infallible> {
    // Extract and validate real client IP
    let real_client_ip: Option<String> =
        match ip_filter::extract_and_validate_real_ip(req.headers(), config.as_ref()) {
            Some(ip) => Some(ip),
            None => {
                if config.allowed_proxy_ips().is_none() {
                    // Permissive mode: continue without IP-based security
                    None
                } else {
                    // Strict mode: reject when proxy validation fails
                    let err = WiseGateError::InvalidIp("missing or invalid proxy headers".into());
                    return Ok(create_error_response(err.status_code(), err.user_message()));
                }
            }
        };

    // Check if IP is blocked
    if let Some(ref ip) = real_client_ip
        && ip_filter::is_ip_blocked(ip, config.as_ref())
    {
        let err = WiseGateError::IpBlocked(ip.clone());
        return Ok(create_error_response(err.status_code(), err.user_message()));
    }

    // Check for blocked URL patterns
    let request_path = req.uri().path();
    if is_url_pattern_blocked(request_path, config.as_ref()) {
        let err = WiseGateError::PatternBlocked(request_path.to_string());
        return Ok(create_error_response(err.status_code(), err.user_message()));
    }

    // Check for blocked HTTP methods
    let request_method = req.method().as_str();
    if is_method_blocked(request_method, config.as_ref()) {
        let err = WiseGateError::MethodBlocked(request_method.to_string());
        return Ok(create_error_response(err.status_code(), err.user_message()));
    }

    // Check Authentication if enabled (Basic Auth and/or Bearer Token)
    // Logic: if both are configured, either one passing is sufficient
    if config.is_auth_enabled() {
        let auth_header = req
            .headers()
            .get(headers::AUTHORIZATION)
            .and_then(|v| v.to_str().ok());

        let basic_auth_enabled = config.is_basic_auth_enabled();
        let bearer_auth_enabled = config.is_bearer_auth_enabled();

        let basic_auth_passed =
            basic_auth_enabled && auth::check_basic_auth(auth_header, config.auth_credentials());
        let bearer_auth_passed =
            bearer_auth_enabled && auth::check_bearer_token(auth_header, config.bearer_token());

        // Authentication fails if neither method passed
        if !basic_auth_passed && !bearer_auth_passed {
            return Ok(create_unauthorized_response(config.auth_realm()));
        }
    }

    // Apply rate limiting (only when IP is known)
    if let Some(ref ip) = real_client_ip
        && !rate_limiter::check_rate_limit(&limiter, ip, config.as_ref()).await
    {
        let err = WiseGateError::RateLimitExceeded(ip.clone());
        return Ok(create_error_response(err.status_code(), err.user_message()));
    }

    // Strip any client-supplied X-Real-IP first to prevent spoofing, then insert
    // the validated one (if any) so upstream sees only wisegate's value.
    let mut req = req;
    req.headers_mut().remove(headers::X_REAL_IP);
    if let Some(ref ip) = real_client_ip
        && let Ok(header_value) = ip.parse()
    {
        req.headers_mut().insert(headers::X_REAL_IP, header_value);
    }

    // Forward the request
    forward_request(
        req,
        &forward_host,
        forward_port,
        config.as_ref(),
        &http_client,
    )
    .await
}

/// Forward request to upstream service
async fn forward_request(
    req: Request<Incoming>,
    host: &str,
    port: u16,
    config: &impl ConfigProvider,
    http_client: &reqwest::Client,
) -> Result<Response<Full<bytes::Bytes>>, Infallible> {
    let proxy_config = config.proxy_config();
    let (parts, body) = req.into_parts();

    // Early rejection based on Content-Length header to prevent memory exhaustion
    if proxy_config.max_body_size > 0
        && let Some(content_length) = parts
            .headers
            .get(headers::CONTENT_LENGTH)
            .and_then(|v| v.to_str().ok())
            .and_then(|v| v.parse::<usize>().ok())
        && content_length > proxy_config.max_body_size
    {
        let err = WiseGateError::BodyTooLarge {
            size: content_length,
            max: proxy_config.max_body_size,
        };
        return Ok(create_error_response(err.status_code(), err.user_message()));
    }

    let body_bytes = match body.collect().await {
        Ok(bytes) => {
            let collected_bytes = bytes.to_bytes();

            // Check actual body size (Content-Length may be absent or inaccurate)
            if proxy_config.max_body_size > 0 && collected_bytes.len() > proxy_config.max_body_size
            {
                let err = WiseGateError::BodyTooLarge {
                    size: collected_bytes.len(),
                    max: proxy_config.max_body_size,
                };
                return Ok(create_error_response(err.status_code(), err.user_message()));
            }

            collected_bytes
        }
        Err(e) => {
            let err = WiseGateError::BodyReadError(e.to_string());
            return Ok(create_error_response(err.status_code(), err.user_message()));
        }
    };

    let strip_auth = config.is_auth_enabled() && !config.forward_authorization_header();
    forward_with_reqwest(parts, body_bytes, host, port, http_client, strip_auth).await
}

/// Shared forwarding logic using reqwest with connection pooling
async fn forward_with_reqwest(
    parts: hyper::http::request::Parts,
    body_bytes: bytes::Bytes,
    host: &str,
    port: u16,
    client: &reqwest::Client,
    strip_auth: bool,
) -> Result<Response<Full<bytes::Bytes>>, Infallible> {
    // Construct destination URI
    let destination_uri = format!(
        "http://{}:{}{}",
        host,
        port,
        parts.uri.path_and_query().map_or("", |pq| pq.as_str())
    );

    // Build the request with the original HTTP method
    let method = match reqwest::Method::from_bytes(parts.method.as_str().as_bytes()) {
        Ok(m) => m,
        Err(_) => {
            let err =
                WiseGateError::MethodBlocked(format!("{} (unsupported)", parts.method.as_str()));
            return Ok(create_error_response(err.status_code(), err.user_message()));
        }
    };
    let mut req_builder = client.request(method, &destination_uri);

    // Add headers (excluding host, content-length, and hop-by-hop headers per RFC 7230).
    // When `strip_auth` is set, also drop Authorization so the upstream cannot
    // re-validate or log credentials wisegate just consumed.
    for (name, value) in parts.headers.iter() {
        if name != headers::HOST
            && name != headers::CONTENT_LENGTH
            && !(strip_auth && name == headers::AUTHORIZATION)
            && !headers::is_hop_by_hop(name.as_str())
            && let Ok(header_value) = value.to_str()
        {
            req_builder = req_builder.header(name.as_str(), header_value);
        }
    }

    // Add body if not empty
    if !body_bytes.is_empty() {
        req_builder = req_builder.body(body_bytes);
    }

    // Send request
    match req_builder.send().await {
        Ok(response) => {
            let status = response.status();
            let resp_headers = response.headers().clone();

            match response.bytes().await {
                Ok(body_bytes) => {
                    let mut hyper_response = match Response::builder()
                        .status(status.as_u16())
                        .body(Full::new(body_bytes))
                    {
                        Ok(resp) => resp,
                        Err(e) => {
                            let err = WiseGateError::ProxyError(format!(
                                "Failed to build response: {}",
                                e
                            ));
                            return Ok(create_error_response(
                                err.status_code(),
                                err.user_message(),
                            ));
                        }
                    };

                    // Copy response headers (skip hop-by-hop headers)
                    for (name, value) in resp_headers.iter() {
                        // Skip hop-by-hop headers that shouldn't be forwarded
                        if !headers::is_hop_by_hop(name.as_str())
                            && let (Ok(hyper_name), Ok(hyper_value)) = (
                                hyper::header::HeaderName::from_bytes(name.as_str().as_bytes()),
                                hyper::header::HeaderValue::from_bytes(value.as_bytes()),
                            )
                        {
                            hyper_response.headers_mut().insert(hyper_name, hyper_value);
                        }
                    }

                    Ok(hyper_response)
                }
                Err(e) => {
                    let err = WiseGateError::BodyReadError(format!("response: {}", e));
                    Ok(create_error_response(err.status_code(), err.user_message()))
                }
            }
        }
        Err(err) => {
            // More specific error handling using WiseGateError
            let wise_err = if err.is_timeout() {
                WiseGateError::UpstreamTimeout(err.to_string())
            } else if err.is_connect() {
                WiseGateError::UpstreamConnectionFailed(err.to_string())
            } else {
                WiseGateError::ProxyError(err.to_string())
            };
            Ok(create_error_response(
                wise_err.status_code(),
                wise_err.user_message(),
            ))
        }
    }
}

/// Creates a standardized error response.
///
/// Builds an HTTP response with the given status code and plain text message.
/// Falls back to a minimal 500 response if building fails (should never happen
/// with valid StatusCode).
///
/// # Arguments
///
/// * `status` - The HTTP status code for the response
/// * `message` - The plain text error message body
///
/// # Returns
///
/// An HTTP response with `content-type: text/plain` header.
///
/// # Example
///
/// ```
/// use wisegate_core::request_handler::create_error_response;
/// use hyper::StatusCode;
///
/// let response = create_error_response(StatusCode::NOT_FOUND, "Resource not found");
/// assert_eq!(response.status(), StatusCode::NOT_FOUND);
/// ```
pub fn create_error_response(status: StatusCode, message: &str) -> Response<Full<bytes::Bytes>> {
    Response::builder()
        .status(status)
        .header(headers::CONTENT_TYPE, "text/plain")
        .body(Full::new(bytes::Bytes::from(message.to_string())))
        .unwrap_or_else(|_| {
            // Fallback response if builder fails (extremely unlikely)
            Response::new(Full::new(bytes::Bytes::from("Internal Server Error")))
        })
}

/// Creates a 401 Unauthorized response with WWW-Authenticate header.
///
/// Used when Basic Authentication is enabled and the request is not authenticated
/// or has invalid credentials.
///
/// # Arguments
///
/// * `realm` - The authentication realm to display in the browser dialog
///
/// # Returns
///
/// An HTTP 401 response with `WWW-Authenticate: Basic realm="..."` header.
pub fn create_unauthorized_response(realm: &str) -> Response<Full<bytes::Bytes>> {
    // Sanitize realm: escape backslashes and quotes per RFC 7235 quoted-string
    let sanitized_realm = realm.replace('\\', "\\\\").replace('"', "\\\"");
    Response::builder()
        .status(StatusCode::UNAUTHORIZED)
        .header(
            headers::WWW_AUTHENTICATE,
            format!("Basic realm=\"{}\"", sanitized_realm),
        )
        .header(headers::CONTENT_TYPE, "text/plain")
        .body(Full::new(bytes::Bytes::from("401 Unauthorized")))
        .unwrap_or_else(|_| Response::new(Full::new(bytes::Bytes::from("401 Unauthorized"))))
}

/// Check if URL path contains any blocked patterns
/// Decodes URL-encoded characters to prevent bypass via encoding (e.g., .ph%70 for .php)
fn is_url_pattern_blocked(path: &str, config: &impl ConfigProvider) -> bool {
    let blocked_patterns = config.blocked_patterns();
    if blocked_patterns.is_empty() {
        return false;
    }

    // Decode URL-encoded path to prevent bypass attacks
    let decoded_path = url_decode(path);
    let has_encoding = decoded_path != path;

    // Case-insensitive matching to prevent bypass via case variation
    let path_lower = path.to_lowercase();
    // Only allocate decoded lowercase if URL actually contained percent-encoding
    let decoded_lower = if has_encoding {
        Some(decoded_path.to_lowercase())
    } else {
        None
    };

    // Patterns are expected to be pre-normalized to lowercase
    blocked_patterns.iter().any(|pattern| {
        path_lower.contains(pattern.as_str())
            || decoded_lower
                .as_ref()
                .is_some_and(|dl| dl.contains(pattern.as_str()))
    })
}

/// Decode URL-encoded string (percent-encoding)
/// Handles common bypass attempts like %2e for '.', %70 for 'p', etc.
/// Properly handles multi-byte UTF-8 sequences.
fn url_decode(input: &str) -> String {
    let mut bytes = Vec::with_capacity(input.len());
    let input_bytes = input.as_bytes();
    let mut i = 0;

    while i < input_bytes.len() {
        if input_bytes[i] == b'%' && i + 2 < input_bytes.len() {
            // Try to decode two hex digits without allocating
            let hi = hex_digit(input_bytes[i + 1]);
            let lo = hex_digit(input_bytes[i + 2]);
            if let (Some(h), Some(l)) = (hi, lo) {
                bytes.push(h << 4 | l);
                i += 3;
                continue;
            }
        }
        bytes.push(input_bytes[i]);
        i += 1;
    }

    // Convert bytes to string, replacing invalid UTF-8 with replacement character
    String::from_utf8_lossy(&bytes).into_owned()
}

/// Converts an ASCII hex digit to its numeric value.
fn hex_digit(b: u8) -> Option<u8> {
    match b {
        b'0'..=b'9' => Some(b - b'0'),
        b'a'..=b'f' => Some(b - b'a' + 10),
        b'A'..=b'F' => Some(b - b'A' + 10),
        _ => None,
    }
}

/// Check if HTTP method is blocked
fn is_method_blocked(method: &str, config: &impl ConfigProvider) -> bool {
    let blocked_methods = config.blocked_methods();
    blocked_methods
        .iter()
        .any(|blocked_method| blocked_method.eq_ignore_ascii_case(method))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::test_utils::TestConfig;
    use http_body_util::BodyExt;

    // ===========================================
    // url_decode tests
    // ===========================================

    #[test]
    fn test_url_decode_no_encoding() {
        assert_eq!(url_decode("/path/to/file"), "/path/to/file");
        assert_eq!(url_decode("hello"), "hello");
        assert_eq!(url_decode(""), "");
    }

    #[test]
    fn test_url_decode_simple_encoding() {
        assert_eq!(url_decode("%20"), " ");
        assert_eq!(url_decode("hello%20world"), "hello world");
        assert_eq!(url_decode("%2F"), "/");
    }

    #[test]
    fn test_url_decode_dot_encoding() {
        // Common bypass attempts
        assert_eq!(url_decode("%2e"), ".");
        assert_eq!(url_decode("%2E"), ".");
        assert_eq!(url_decode(".%2ephp"), "..php");
    }

    #[test]
    fn test_url_decode_php_bypass() {
        // Attacker tries to bypass .php blocking
        assert_eq!(url_decode(".ph%70"), ".php");
        assert_eq!(url_decode("%2ephp"), ".php");
        assert_eq!(url_decode(".%70%68%70"), ".php");
    }

    #[test]
    fn test_url_decode_env_bypass() {
        // Attacker tries to bypass .env blocking
        assert_eq!(url_decode(".%65nv"), ".env");
        assert_eq!(url_decode("%2eenv"), ".env");
        assert_eq!(url_decode("%2e%65%6e%76"), ".env");
    }

    #[test]
    fn test_url_decode_multiple_encodings() {
        assert_eq!(url_decode("%2F%2e%2e%2Fetc%2Fpasswd"), "/../etc/passwd");
    }

    #[test]
    fn test_url_decode_invalid_hex() {
        // Invalid hex should be preserved
        assert_eq!(url_decode("%GG"), "%GG");
        assert_eq!(url_decode("%"), "%");
        assert_eq!(url_decode("%2"), "%2");
        assert_eq!(url_decode("%ZZ"), "%ZZ");
    }

    #[test]
    fn test_url_decode_mixed_content() {
        assert_eq!(url_decode("path%2Fto%2Ffile.txt"), "path/to/file.txt");
        assert_eq!(url_decode("hello%20%26%20world"), "hello & world");
    }

    #[test]
    fn test_url_decode_unicode() {
        // UTF-8 encoded characters
        assert_eq!(url_decode("%C3%A9"), "é"); // é in UTF-8
        assert_eq!(url_decode("caf%C3%A9"), "café");
    }

    // ===========================================
    // is_url_pattern_blocked tests
    // ===========================================

    #[test]
    fn test_url_pattern_blocked_simple() {
        let config = TestConfig::new().with_blocked_patterns(vec![".php", ".env"]);

        assert!(is_url_pattern_blocked("/file.php", &config));
        assert!(is_url_pattern_blocked("/.env", &config));
        assert!(is_url_pattern_blocked("/path/to/file.php", &config));
    }

    #[test]
    fn test_url_pattern_not_blocked() {
        let config = TestConfig::new().with_blocked_patterns(vec![".php", ".env"]);

        assert!(!is_url_pattern_blocked("/file.html", &config));
        assert!(!is_url_pattern_blocked("/path/to/file.js", &config));
        assert!(!is_url_pattern_blocked("/", &config));
    }

    #[test]
    fn test_url_pattern_blocked_empty_patterns() {
        let config = TestConfig::new();

        assert!(!is_url_pattern_blocked("/file.php", &config));
        assert!(!is_url_pattern_blocked("/.env", &config));
    }

    #[test]
    fn test_url_pattern_blocked_bypass_attempt() {
        let config = TestConfig::new().with_blocked_patterns(vec![".php", ".env", "admin"]);

        // URL-encoded bypass attempts should still be blocked
        assert!(is_url_pattern_blocked("/.ph%70", &config)); // .php
        assert!(is_url_pattern_blocked("/%2eenv", &config)); // .env
        assert!(is_url_pattern_blocked("/adm%69n", &config)); // admin
    }

    #[test]
    fn test_url_pattern_blocked_double_encoding_attempt() {
        let config = TestConfig::new().with_blocked_patterns(vec![".php"]);

        // Single encoding should be caught
        assert!(is_url_pattern_blocked("/.ph%70", &config));
    }

    #[test]
    fn test_url_pattern_blocked_case_insensitive() {
        let config = TestConfig::new().with_blocked_patterns(vec![".php"]);

        // Pattern matching is case-insensitive to prevent bypass
        assert!(is_url_pattern_blocked("/file.PHP", &config));
        assert!(is_url_pattern_blocked("/file.php", &config));
        assert!(is_url_pattern_blocked("/file.Php", &config));
    }

    #[test]
    fn test_url_pattern_blocked_partial_match() {
        let config = TestConfig::new().with_blocked_patterns(vec!["admin"]);

        assert!(is_url_pattern_blocked("/admin/panel", &config));
        assert!(is_url_pattern_blocked("/path/admin", &config));
        assert!(is_url_pattern_blocked("/administrator", &config)); // Contains "admin"
    }

    // ===========================================
    // is_method_blocked tests
    // ===========================================

    #[test]
    fn test_method_blocked() {
        let config = TestConfig::new().with_blocked_methods(vec!["TRACE", "CONNECT"]);

        assert!(is_method_blocked("TRACE", &config));
        assert!(is_method_blocked("CONNECT", &config));
    }

    #[test]
    fn test_method_not_blocked() {
        let config = TestConfig::new().with_blocked_methods(vec!["TRACE", "CONNECT"]);

        assert!(!is_method_blocked("GET", &config));
        assert!(!is_method_blocked("POST", &config));
        assert!(!is_method_blocked("PUT", &config));
        assert!(!is_method_blocked("DELETE", &config));
    }

    #[test]
    fn test_method_blocked_empty_list() {
        let config = TestConfig::new();

        assert!(!is_method_blocked("TRACE", &config));
        assert!(!is_method_blocked("GET", &config));
    }

    #[test]
    fn test_method_blocked_case_insensitive() {
        let config = TestConfig::new().with_blocked_methods(vec!["TRACE"]);

        assert!(is_method_blocked("TRACE", &config));
        assert!(is_method_blocked("trace", &config));
        assert!(is_method_blocked("Trace", &config));
    }

    // ===========================================
    // create_error_response tests
    // ===========================================

    #[test]
    fn test_create_error_response_status() {
        let response = create_error_response(StatusCode::NOT_FOUND, "Not Found");
        assert_eq!(response.status(), StatusCode::NOT_FOUND);

        let response = create_error_response(StatusCode::FORBIDDEN, "Forbidden");
        assert_eq!(response.status(), StatusCode::FORBIDDEN);

        let response = create_error_response(StatusCode::TOO_MANY_REQUESTS, "Rate limited");
        assert_eq!(response.status(), StatusCode::TOO_MANY_REQUESTS);
    }

    #[test]
    fn test_create_error_response_content_type() {
        let response = create_error_response(StatusCode::NOT_FOUND, "Not Found");
        assert_eq!(
            response.headers().get("content-type").unwrap(),
            "text/plain"
        );
    }

    #[tokio::test]
    async fn test_create_error_response_body() {
        let response = create_error_response(StatusCode::NOT_FOUND, "Resource not found");
        let body = response.into_body().collect().await.unwrap().to_bytes();
        assert_eq!(body, "Resource not found");
    }

    #[tokio::test]
    async fn test_create_error_response_empty_message() {
        let response = create_error_response(StatusCode::NO_CONTENT, "");
        let body = response.into_body().collect().await.unwrap().to_bytes();
        assert_eq!(body, "");
    }

    // ===========================================
    // create_unauthorized_response tests
    // ===========================================

    #[test]
    fn test_unauthorized_response_status() {
        let response = create_unauthorized_response("WiseGate");
        assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
    }

    #[test]
    fn test_unauthorized_response_www_authenticate_header() {
        let response = create_unauthorized_response("WiseGate");
        let header = response
            .headers()
            .get("www-authenticate")
            .unwrap()
            .to_str()
            .unwrap();
        assert_eq!(header, "Basic realm=\"WiseGate\"");
    }

    #[test]
    fn test_unauthorized_response_realm_with_quotes() {
        let response = create_unauthorized_response("My \"Realm\"");
        let header = response
            .headers()
            .get("www-authenticate")
            .unwrap()
            .to_str()
            .unwrap();
        assert_eq!(header, "Basic realm=\"My \\\"Realm\\\"\"");
    }

    #[test]
    fn test_unauthorized_response_realm_with_backslash() {
        let response = create_unauthorized_response("My\\Realm");
        let header = response
            .headers()
            .get("www-authenticate")
            .unwrap()
            .to_str()
            .unwrap();
        assert_eq!(header, "Basic realm=\"My\\\\Realm\"");
    }

    #[test]
    fn test_unauthorized_response_content_type() {
        let response = create_unauthorized_response("WiseGate");
        assert_eq!(
            response.headers().get("content-type").unwrap(),
            "text/plain"
        );
    }

    // ===========================================
    // double-encoding test
    // ===========================================

    #[test]
    fn test_url_decode_double_encoding_not_decoded_twice() {
        // %252e decodes to %2e on first pass — should NOT become '.'
        assert_eq!(url_decode("%252e"), "%2e");
        assert_eq!(url_decode("%2565nv"), "%65nv");
    }
}