palisade 0.1.0

An HTTP reverse proxy built on hyper, tokio, and rustls
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
//! Core proxy handler: request forwarding, body streaming, and filtering.
//!
//! Implements the full proxy pipeline including HTTP spec compliance
//! (hop-by-hop header stripping, forwarding headers, request smuggling
//! defense) and policy enforcement (header/param blocking, body size
//! limits, response masking, load balancing).
//!
//! Every inbound request is assigned a monotonically increasing request ID
//! and wrapped in a [`tracing::Span`] carrying structured fields for
//! observability.

use std::net::SocketAddr;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};

use bytes::Bytes;
use http_body_util::{BodyExt, Full};
use hyper::body::Incoming;
use hyper::header::HeaderName;
use hyper::{Method, Request, Response, Uri};
use hyper_util::client::legacy::Client;
use hyper_util::client::legacy::connect::HttpConnector;
use hyper_util::rt::TokioExecutor;
use tokio::time::timeout;
use tracing::{Instrument, debug, info, warn};

use crate::{IpRateLimiter, LoadBalancer, ProxyError, Result, RuntimeConfig, headers, tls};

/// An alias to simplify the calls to `Box<dyn std::error::Error + Send + Sync>`.
type StdError = Box<dyn std::error::Error + Send + Sync>;

/// Type-erased body used for both request forwarding and response streaming.
///
/// Wraps any body implementation behind a single boxed trait object,
/// allowing the handler to accept requests with arbitrary body types
/// (e.g. `Incoming`, `Full<Bytes>`, `Empty<Bytes>`) and return a uniform
/// response type regardless of origin.
///
/// Uses a trait-object error type so that both `Incoming` (which yields
/// `hyper::Error`) and locally constructed bodies (which are infallible)
/// can be erased into the same type without lossy conversions.
pub type BoxBody = http_body_util::combinators::BoxBody<Bytes, StdError>;

/// The HTTP client type for plain TCP upstream connections.
pub type HttpClient = Client<HttpConnector, BoxBody>;

/// The HTTPS client type for TLS-secured upstream connections.
pub type HttpsClient = Client<hyper_rustls::HttpsConnector<HttpConnector>, BoxBody>;

/// Global monotonic counter for assigning unique request IDs.
static REQUEST_ID: AtomicU64 = AtomicU64::new(1);

/// Constructs a new [`HttpClient`] for plain HTTP upstream connections.
pub fn build_client(config: &RuntimeConfig) -> HttpClient {
    Client::builder(TokioExecutor::new())
        .pool_idle_timeout(config.pool_idle_timeout)
        .pool_max_idle_per_host(config.pool_max_idle_per_host)
        .build(HttpConnector::new())
}

/// Constructs a new [`HttpsClient`] capable of both HTTP and HTTPS
/// upstream connections, using the platform root certificate store for
/// server verification.
pub fn build_https_client(config: &RuntimeConfig) -> HttpsClient {
    let connector = tls::build_https_connector();
    Client::builder(TokioExecutor::new())
        .pool_idle_timeout(config.pool_idle_timeout)
        .pool_max_idle_per_host(config.pool_max_idle_per_host)
        .build(connector)
}

/// Processes a single inbound request through the proxy pipeline.
///
/// The pipeline performs the following steps in order:
///
/// 1. **Rate limiting** — If a rate limiter is configured, the client IP is
///    checked against the per-IP token bucket. Requests exceeding the limit
///    receive a 429 Too Many Requests response with a `Retry-After` header.
/// 2. **Request smuggling defense** — Rejects requests carrying both
///    `Content-Length` and `Transfer-Encoding` headers (RFC 7230 §3.3.3).
/// 3. **Body size enforcement** — Rejects requests whose `Content-Length`
///    exceeds the configured `max_body_size` with 413 Payload Too Large.
/// 4. **GET inspection** — If the request method is GET, blocked headers and
///    query parameters are checked. Requests matching any block rule receive
///    a 403 Forbidden response.
/// 5. **Upstream selection** — The round-robin balancer selects the next
///    healthy backend. If none are available, returns 503.
/// 6. **Hop-by-hop stripping** — Connection-scoped headers are removed
///    before forwarding, per RFC 7230 §6.1.
/// 7. **Forwarding headers** — `X-Forwarded-For`, `X-Forwarded-Proto`, and
///    `X-Forwarded-Host` are injected to preserve client origin metadata.
/// 8. **Host rewriting** — The `Host` header is set to the upstream authority.
/// 9. **URI rewriting** — The request URI is rewritten to target the selected
///    upstream, preserving the original path and query string.
/// 10. **Body streaming** — The request body is passed through to the upstream
///     without buffering.
/// 11. **Passive health tracking** — On upstream success, the backend's
///     failure counter is reset. On failure/timeout, it is incremented and
///     the backend may be marked unhealthy.
/// 12. **Response hop-by-hop stripping** — Connection-scoped headers are
///     removed from the upstream response.
/// 13. **Response header stripping** — Configured internal headers (e.g.
///     `Server`, `X-Powered-By`) are removed from the response.
/// 14. **Response masking** — For text-based upstream responses, sensitive
///     parameter values are masked before returning to the client.
/// 15. **Request ID injection** — An `X-Request-Id` header carrying the
///     monotonic request ID is added to every response for client-side
///     log correlation.
pub async fn handle_request<B, C>(
    req: Request<B>,
    client: Client<C, BoxBody>,
    config: Arc<RuntimeConfig>,
    balancer: LoadBalancer,
    client_addr: SocketAddr,
    rate_limiter: Option<&IpRateLimiter>,
) -> Result<Response<BoxBody>>
where
    B: hyper::body::Body<Data = Bytes> + Send + Sync + 'static,
    B::Error: Into<StdError>,
    C: hyper_util::client::legacy::connect::Connect + Clone + Send + Sync + 'static,
{
    let request_id = REQUEST_ID.fetch_add(1, Ordering::Relaxed);
    let method = req.method().clone();
    let uri = req.uri().clone();

    let span = tracing::info_span!(
        "request",
        id = request_id,
        method = %method,
        uri = %uri,
        client = %client_addr,
    );

    async move {
        if let Some(limiter) = rate_limiter {
            limiter.check(&client_addr.ip()).map_err(|retry_after_ms| {
                warn!(
                    ip = %client_addr.ip(),
                    retry_after_ms,
                    "rate limit exceeded"
                );
                ProxyError::RateLimited { retry_after_ms }
            })?;
        }

        if headers::is_smuggling_attempt(req.headers()) {
            warn!("request smuggling attempt detected");
            return Err(ProxyError::RequestSmuggling);
        }

        if headers::content_length_exceeds(req.headers(), config.max_body_size) {
            let declared = req
                .headers()
                .get(hyper::header::CONTENT_LENGTH)
                .and_then(|v| v.to_str().ok())
                .unwrap_or("unknown");
            warn!(
                content_length = declared,
                limit = config.max_body_size,
                "request body exceeds size limit"
            );
            return Err(ProxyError::BodyTooLarge {
                limit: config.max_body_size,
            });
        }

        if method == Method::GET {
            inspect_get_request(&req, &config)?;
        }

        let upstream = balancer.next()?;
        let upstream_uri_target = upstream.uri();
        info!(upstream = %upstream_uri_target, "received request");

        let rewritten_uri = rewrite_uri(&uri, upstream_uri_target)?;
        let (mut parts, body) = req.into_parts();

        headers::strip_hop_by_hop(&mut parts.headers);
        headers::inject_forwarding_headers(&mut parts.headers, client_addr);
        headers::rewrite_host(
            &mut parts.headers,
            upstream_uri_target
                .authority()
                .ok_or_else(|| ProxyError::InvalidUpstream("upstream has no authority".into()))?,
        );

        config.blocked_headers.iter().for_each(|blocked| {
            if let Ok(name) = HeaderName::from_bytes(blocked.as_bytes()) {
                parts.headers.remove(&name);
            }
        });

        parts.uri = rewritten_uri;

        debug!(
            headers = ?parts.headers,
            upstream_uri = %parts.uri,
            "forwarding request"
        );

        let start = std::time::Instant::now();
        let boxed_body = body.map_err(|e| e.into()).boxed();
        let proxy_req = Request::from_parts(parts, boxed_body);

        let upstream_result = timeout(config.request_timeout, client.request(proxy_req)).await;

        let mut upstream_resp = match upstream_result {
            Ok(Ok(resp)) => {
                upstream.record_success(config.healthy_threshold);
                resp
            }
            Ok(Err(e)) => {
                let transitioned = upstream.record_failure(config.failure_threshold);
                warn!(
                    error = %e,
                    latency_ms = start.elapsed().as_millis() as u64,
                    upstream = %upstream_uri_target,
                    marked_unhealthy = transitioned,
                    "upstream request failed"
                );
                return Err(ProxyError::Upstream(e));
            }
            Err(_elapsed) => {
                let transitioned = upstream.record_failure(config.failure_threshold);
                warn!(
                    timeout = ?config.request_timeout,
                    latency_ms = start.elapsed().as_millis() as u64,
                    upstream = %upstream_uri_target,
                    marked_unhealthy = transitioned,
                    "upstream request timed out"
                );
                return Err(ProxyError::Timeout(config.request_timeout));
            }
        };

        let latency_ms = start.elapsed().as_millis() as u64;
        info!(
            status = upstream_resp.status().as_u16(),
            latency_ms,
            upstream = %upstream_uri_target,
            "upstream responded"
        );

        headers::strip_hop_by_hop(upstream_resp.headers_mut());
        if !config.strip_response_headers.is_empty() {
            headers::strip_response_headers(
                upstream_resp.headers_mut(),
                &config.strip_response_headers,
            );
        }

        let mut resp = build_response(upstream_resp, &config).await?;
        resp.headers_mut().insert(
            HeaderName::from_static("x-request-id"),
            hyper::header::HeaderValue::from(request_id),
        );
        Ok(resp)
    }
    .instrument(span)
    .await
}

/// Checks a GET request against configured block rules.
///
/// Returns `ProxyError::BlockedHeader` or `ProxyError::BlockedParam`
/// if any rule matches, allowing the caller to short-circuit with a 403.
fn inspect_get_request<B>(req: &Request<B>, config: &RuntimeConfig) -> Result<()> {
    let headers = req.headers();
    config
        .blocked_headers
        .iter()
        .find(|blocked| {
            HeaderName::from_bytes(blocked.as_bytes())
                .ok()
                .is_some_and(|name| headers.contains_key(&name))
        })
        .map_or(Ok(()), |name| {
            warn!(header = %name, "blocked header detected");
            Err(ProxyError::BlockedHeader(name.clone()))
        })?;

    let query = req.uri().query().unwrap_or_default();
    config
        .blocked_params
        .iter()
        .find(|param| query.contains(&format!("{param}=")))
        .map_or(Ok(()), |name| {
            warn!(param = %name, "blocked parameter detected");
            Err(ProxyError::BlockedParam(name.clone()))
        })
}

/// Rewrites the original request URI to target the configured upstream,
/// preserving the path and query string.
fn rewrite_uri(original: &Uri, upstream: &Uri) -> Result<Uri> {
    let authority = upstream
        .authority()
        .ok_or_else(|| ProxyError::InvalidUpstream("upstream has no authority".into()))?;

    let scheme = upstream
        .scheme()
        .ok_or_else(|| ProxyError::InvalidUpstream("upstream has no scheme".into()))?;

    let path_and_query = original
        .path_and_query()
        .map(|pq| pq.as_str())
        .unwrap_or("/");

    Uri::builder()
        .scheme(scheme.clone())
        .authority(authority.clone())
        .path_and_query(path_and_query)
        .build()
        .map_err(|e| ProxyError::Internal(format!("failed to build upstream URI: {e}")))
}

/// Builds the client-facing response from the upstream response.
///
/// For responses whose `Content-Type` indicates text or form-encoded data,
/// the body is collected and scanned for sensitive parameter values. All
/// other responses are streamed through unmodified.
async fn build_response(
    upstream_resp: Response<Incoming>,
    config: &RuntimeConfig,
) -> Result<Response<BoxBody>> {
    if config.mask_rules.is_empty() {
        let (parts, body) = upstream_resp.into_parts();
        return Ok(Response::from_parts(
            parts,
            body.map_err(|e| -> StdError { Box::new(e) }).boxed(),
        ));
    }

    let should_mask = upstream_resp
        .headers()
        .get(hyper::header::CONTENT_TYPE)
        .and_then(|ct| ct.to_str().ok())
        .is_some_and(|ct| ct.contains("text/") || ct.contains("application/x-www-form-urlencoded"));

    if !should_mask {
        let (parts, body) = upstream_resp.into_parts();
        return Ok(Response::from_parts(
            parts,
            body.map_err(|e| -> StdError { Box::new(e) }).boxed(),
        ));
    }

    let (parts, body) = upstream_resp.into_parts();
    let body_bytes = body
        .collect()
        .await
        .map_err(|e| ProxyError::Internal(format!("failed to read upstream body: {e}")))?
        .to_bytes();

    let body_str = String::from_utf8_lossy(&body_bytes);
    let masked = config.mask_sensitive_data(&body_str);

    let mut response = Response::new(
        Full::new(Bytes::from(masked))
            .map_err(|never| -> StdError { match never {} })
            .boxed(),
    );
    *response.status_mut() = parts.status;
    *response.headers_mut() = parts.headers;
    *response.version_mut() = parts.version;

    Ok(response)
}

#[cfg(test)]
mod tests {
    use http_body_util::Empty;

    use super::*;
    use crate::Config;
    use crate::config::UpstreamConfig;

    fn parse_uri(uri: &str) -> Uri {
        uri.parse::<Uri>().expect("failed to parse URI")
    }

    fn single_upstream(addr: &str) -> Vec<UpstreamConfig> {
        vec![UpstreamConfig {
            address: addr.into(),
            weight: 1,
        }]
    }

    #[test]
    fn rewrite_uri_preserves_path_and_query() {
        let original = parse_uri("http://client-facing.com/api/v1?key=val");
        let upstream = parse_uri("http://localhost:3000");

        let result = rewrite_uri(&original, &upstream).unwrap();
        assert_eq!(result.scheme_str(), Some("http"));
        assert_eq!(result.authority().unwrap().as_str(), "localhost:3000");
        assert_eq!(result.path_and_query().unwrap().as_str(), "/api/v1?key=val");
    }

    #[test]
    fn rewrite_uri_defaults_to_root_path() {
        let original = parse_uri("http://client-facing.com");
        let upstream = parse_uri("http://localhost:3000");

        let result = rewrite_uri(&original, &upstream).unwrap();
        assert_eq!(result.path_and_query().unwrap().as_str(), "/");
    }

    #[test]
    fn inspect_get_detects_blocked_header() {
        let config = Config {
            upstreams: single_upstream("http://localhost:3000"),
            blocked_headers: vec!["x-bad-header".into()],
            ..Default::default()
        }
        .into_runtime()
        .unwrap();

        let req = Request::builder()
            .method(Method::GET)
            .uri("http://example.com/")
            .header("x-bad-header", "anything")
            .body(Empty::<Bytes>::new())
            .unwrap();

        let result = inspect_get_request(&req, &config);
        assert!(result.is_err());
    }

    #[test]
    fn inspect_get_detects_blocked_param() {
        let config = Config {
            upstreams: single_upstream("http://localhost:3000"),
            blocked_params: vec!["secret_key".into()],
            ..Default::default()
        }
        .into_runtime()
        .unwrap();

        let req = Request::builder()
            .method(Method::GET)
            .uri("http://example.com/?secret_key=abc123")
            .body(Empty::<Bytes>::new())
            .unwrap();

        let result = inspect_get_request(&req, &config);
        assert!(result.is_err());
    }

    #[test]
    fn inspect_get_allows_clean_request() {
        let config = Config {
            upstreams: single_upstream("http://localhost:3000"),
            blocked_headers: vec!["x-bad-header".into()],
            blocked_params: vec!["secret_key".into()],
            ..Default::default()
        }
        .into_runtime()
        .unwrap();

        let req = Request::builder()
            .method(Method::GET)
            .uri("http://example.com/path?safe=true")
            .header("x-good-header", "ok")
            .body(Empty::<Bytes>::new())
            .unwrap();

        assert!(inspect_get_request(&req, &config).is_ok());
    }
}