praxis-proxy-core 0.5.6

Configuration, error types, and server factory for Praxis
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
// SPDX-License-Identifier: Apache-2.0
// Copyright (c) 2024 Praxis Contributors

//! Endpoint count, weight, and SSRF validation for clusters.

use std::net::IpAddr;

use super::{
    MAX_ENDPOINT_WEIGHT, MAX_ENDPOINTS,
    health_check::{extract_host, is_ssrf_sensitive, is_ssrf_sensitive_hostname},
};
use crate::{
    config::{Cluster, InsecureOptions},
    connectivity::normalize_mapped_ipv4,
    errors::ProxyError,
};

// -----------------------------------------------------------------------------
// Endpoint Validation
// -----------------------------------------------------------------------------

/// Validate endpoint count, per-endpoint weights, and SSRF safety.
pub(super) fn validate_endpoints(cluster: &Cluster, insecure_options: &InsecureOptions) -> Result<(), ProxyError> {
    if cluster.endpoints.is_empty() {
        return Err(ProxyError::Config(format!(
            "cluster '{}' has no endpoints",
            cluster.name
        )));
    }
    if cluster.endpoints.len() > MAX_ENDPOINTS {
        return Err(ProxyError::Config(format!(
            "cluster '{}' has too many endpoints ({}, max {MAX_ENDPOINTS})",
            cluster.name,
            cluster.endpoints.len()
        )));
    }
    let mut seen = std::collections::HashSet::with_capacity(cluster.endpoints.len());
    for ep in &cluster.endpoints {
        validate_endpoint_address(ep.address(), &cluster.name)?;
        validate_endpoint_weight(ep.weight(), ep.address(), &cluster.name)?;
        // A duplicate address collapses the health address->index map (last
        // wins), so passive health outcomes are misattributed and the address
        // is never fully drained. Use `weight` to bias traffic, not repetition.
        if !seen.insert(ep.address()) {
            return Err(ProxyError::Config(format!(
                "cluster '{}': endpoint '{}' is listed more than once (use 'weight' to bias traffic)",
                cluster.name,
                ep.address()
            )));
        }
    }
    validate_endpoint_ssrf(cluster, insecure_options)
}

/// Validate an endpoint address is well-formed `host:port`.
///
/// Accepts `SocketAddr` (`1.2.3.4:80`), bracketed IPv6
/// (`[::1]:80`), or `hostname:port` with a valid `u16` port.
fn validate_endpoint_address(addr: &str, cluster_name: &str) -> Result<(), ProxyError> {
    if addr.is_empty() {
        return Err(ProxyError::Config(format!(
            "cluster '{cluster_name}': endpoint address must not be empty"
        )));
    }
    if addr.parse::<std::net::SocketAddr>().is_ok() {
        return Ok(());
    }
    let Some((host, port_str)) = addr.rsplit_once(':') else {
        return Err(ProxyError::Config(format!(
            "cluster '{cluster_name}': endpoint '{addr}' must be 'host:port' with a valid port"
        )));
    };
    if port_str.parse::<u16>().is_err() {
        return Err(ProxyError::Config(format!(
            "cluster '{cluster_name}': endpoint '{addr}' must be 'host:port' with a valid port"
        )));
    }
    // A valid port with an empty host (`:80`) parses here but has no
    // resolvable host, so every request to the cluster fails at connect;
    // the empty host also slips past the SSRF hostname check.
    let host = host.strip_prefix('[').and_then(|h| h.strip_suffix(']')).unwrap_or(host);
    if host.is_empty() {
        return Err(ProxyError::Config(format!(
            "cluster '{cluster_name}': endpoint '{addr}' has an empty host (expected 'host:port')"
        )));
    }
    Ok(())
}

/// Reject a zero or out-of-range endpoint weight.
///
/// Weighted balancers expand each endpoint into `weight` replicas at
/// build time, so an unbounded weight is an out-of-memory vector.
fn validate_endpoint_weight(weight: u32, addr: &str, cluster_name: &str) -> Result<(), ProxyError> {
    if weight == 0 {
        return Err(ProxyError::Config(format!(
            "cluster '{cluster_name}': endpoint '{addr}' has weight 0 (must be >= 1)"
        )));
    }
    if weight > MAX_ENDPOINT_WEIGHT {
        return Err(ProxyError::Config(format!(
            "cluster '{cluster_name}': endpoint '{addr}' has weight {weight} (max {MAX_ENDPOINT_WEIGHT})"
        )));
    }
    Ok(())
}

/// Reject endpoints that resolve to SSRF-sensitive addresses
/// when the cluster has no health check configured.
///
/// Clusters with health checks are covered by
/// [`validate_health_check_ssrf`], gated by `allow_private_health_checks`.
///
/// [`validate_health_check_ssrf`]: super::health_check::validate_health_check_ssrf
fn validate_endpoint_ssrf(cluster: &Cluster, insecure_options: &InsecureOptions) -> Result<(), ProxyError> {
    if cluster.health_check.is_some() || insecure_options.allow_private_endpoints {
        return Ok(());
    }
    for ep in &cluster.endpoints {
        let addr_str = ep.address();
        let host = extract_host(addr_str);
        reject_ssrf_host(host, &cluster.name, addr_str)?;
    }
    Ok(())
}

/// Return an error when a host resolves to an SSRF-sensitive address.
fn reject_ssrf_host(host: &str, cluster_name: &str, addr_str: &str) -> Result<(), ProxyError> {
    let sensitive = match host.parse::<IpAddr>() {
        Ok(raw) => is_ssrf_sensitive(&normalize_mapped_ipv4(raw)),
        Err(_) => is_ssrf_sensitive_hostname(host),
    };
    if sensitive {
        return Err(ProxyError::Config(format!(
            "cluster '{cluster_name}': endpoint '{addr_str}' resolves to a sensitive \
             address; set insecure_options.allow_private_endpoints: true to allow"
        )));
    }
    Ok(())
}

// -----------------------------------------------------------------------------
// Tests
// -----------------------------------------------------------------------------

#[cfg(test)]
#[expect(clippy::allow_attributes, reason = "blanket test suppressions")]
#[allow(
    clippy::unwrap_used,
    clippy::expect_used,
    clippy::indexing_slicing,
    clippy::needless_raw_strings,
    clippy::needless_raw_string_hashes,
    reason = "tests use unwrap/expect/indexing/raw strings for brevity"
)]
mod tests {
    use super::super::{MAX_ENDPOINT_WEIGHT, validate_clusters};
    use crate::config::{Cluster, Config, InsecureOptions};

    #[test]
    fn reject_empty_endpoints() {
        let clusters = vec![Cluster::with_defaults("empty", vec![])];
        let err = validate_clusters(&clusters, &InsecureOptions::default()).unwrap_err();
        assert!(err.to_string().contains("cluster 'empty' has no endpoints"));
    }

    #[test]
    fn reject_too_many_endpoints() {
        let endpoints: Vec<_> = (0..10_001)
            .map(|i| format!("10.0.{}.{}:80", i / 256, i % 256).into())
            .collect();
        let clusters = vec![Cluster::with_defaults("big", endpoints)];
        let err = validate_clusters(&clusters, &InsecureOptions::default()).unwrap_err();
        assert!(
            err.to_string().contains("too many endpoints"),
            "should reject cluster exceeding MAX_ENDPOINTS: {err}"
        );
    }

    #[test]
    fn accept_exactly_max_endpoints() {
        let endpoints: Vec<_> = (0..10_000)
            .map(|i| format!("10.{}.{}.{}:80", i / 65536, (i / 256) % 256, i % 256).into())
            .collect();
        let clusters = vec![Cluster::with_defaults("big", endpoints)];
        validate_clusters(&clusters, &InsecureOptions::default()).expect("exactly MAX_ENDPOINTS should be accepted");
    }

    #[test]
    fn reject_loopback_endpoint_without_health_check() {
        let clusters = vec![Cluster::with_defaults("web", vec!["127.0.0.1:80".into()])];
        let err = validate_clusters(&clusters, &InsecureOptions::default()).unwrap_err();
        assert!(err.to_string().contains("sensitive address"), "got: {err}");
    }

    #[test]
    fn reject_localhost_hostname_endpoint() {
        let clusters = vec![Cluster::with_defaults("web", vec!["localhost:80".into()])];
        let err = validate_clusters(&clusters, &InsecureOptions::default()).unwrap_err();
        assert!(err.to_string().contains("sensitive address"), "got: {err}");
    }

    #[test]
    fn reject_metadata_internal_hostname() {
        let clusters = vec![Cluster::with_defaults(
            "web",
            vec!["metadata.google.internal:80".into()],
        )];
        let err = validate_clusters(&clusters, &InsecureOptions::default()).unwrap_err();
        assert!(err.to_string().contains("sensitive address"), "got: {err}");
    }

    #[test]
    fn reject_ipv6_link_local_endpoint() {
        let clusters = vec![Cluster::with_defaults("web", vec!["[fe80::1]:80".into()])];
        let err = validate_clusters(&clusters, &InsecureOptions::default()).unwrap_err();
        assert!(err.to_string().contains("sensitive address"), "got: {err}");
    }

    #[test]
    fn allow_private_endpoint_with_override() {
        let clusters = vec![Cluster::with_defaults("web", vec!["127.0.0.1:80".into()])];
        let opts = InsecureOptions {
            allow_private_endpoints: true,
            ..InsecureOptions::default()
        };
        validate_clusters(&clusters, &opts).expect("allow_private_endpoints should allow loopback");
    }

    #[test]
    fn ssrf_skip_endpoint_check_when_health_check_present() {
        let clusters = vec![Cluster {
            health_check: Some(crate::config::HealthCheckConfig {
                check_type: crate::config::HealthCheckType::Http,
                expected_status: 200,
                healthy_threshold: 2,
                interval_ms: 5000,
                passive_healthy_threshold: None,
                passive_unhealthy_threshold: None,
                path: "/health".to_owned(),
                timeout_ms: 2000,
                unhealthy_threshold: 3,
            }),
            ..Cluster::with_defaults("web", vec!["127.0.0.1:80".into()])
        }];
        let opts = InsecureOptions {
            allow_private_health_checks: true,
            ..InsecureOptions::default()
        };
        validate_clusters(&clusters, &opts)
            .expect("endpoint SSRF defers to health check SSRF when health check present");
    }

    #[test]
    fn accept_rfc1918_endpoint_without_override() {
        let clusters = vec![Cluster::with_defaults("web", vec!["10.0.0.1:80".into()])];
        validate_clusters(&clusters, &InsecureOptions::default()).expect("RFC 1918 addresses should not be flagged");
    }

    #[test]
    fn accept_public_hostname_endpoint() {
        let clusters = vec![Cluster::with_defaults("web", vec!["api.example.com:443".into()])];
        validate_clusters(&clusters, &InsecureOptions::default()).expect("public hostnames should not be flagged");
    }

    #[test]
    fn reject_endpoint_missing_port() {
        let clusters = vec![Cluster::with_defaults("web", vec!["10.0.0.1".into()])];
        let err = validate_clusters(&clusters, &InsecureOptions::default()).unwrap_err();
        assert!(
            err.to_string().contains("host:port"),
            "endpoint without port should be rejected: {err}"
        );
    }

    #[test]
    fn reject_endpoint_invalid_port() {
        let clusters = vec![Cluster::with_defaults("web", vec!["10.0.0.1:99999".into()])];
        let err = validate_clusters(&clusters, &InsecureOptions::default()).unwrap_err();
        assert!(
            err.to_string().contains("host:port"),
            "endpoint with invalid port should be rejected: {err}"
        );
    }

    #[test]
    fn reject_empty_endpoint_address() {
        let clusters = vec![Cluster::with_defaults("web", vec!["".into()])];
        let err = validate_clusters(&clusters, &InsecureOptions::default()).unwrap_err();
        assert!(
            err.to_string().contains("must not be empty"),
            "empty endpoint address should be rejected: {err}"
        );
    }

    #[test]
    fn reject_duplicate_endpoint_addresses() {
        let clusters = vec![Cluster::with_defaults(
            "web",
            vec!["10.0.0.1:80".into(), "10.0.0.2:80".into(), "10.0.0.1:80".into()],
        )];
        let err = validate_clusters(&clusters, &InsecureOptions::default()).unwrap_err();
        assert!(
            err.to_string().contains("listed more than once"),
            "a duplicate endpoint address must be rejected: {err}"
        );
    }

    #[test]
    fn reject_empty_host_endpoint() {
        let clusters = vec![Cluster::with_defaults("web", vec![":80".into()])];
        let err = validate_clusters(&clusters, &InsecureOptions::default()).unwrap_err();
        assert!(
            err.to_string().contains("empty host"),
            "an endpoint with a valid port but empty host must be rejected: {err}"
        );
    }

    #[test]
    fn reject_empty_bracketed_host_endpoint() {
        let clusters = vec![Cluster::with_defaults("web", vec!["[]:80".into()])];
        let err = validate_clusters(&clusters, &InsecureOptions::default()).unwrap_err();
        assert!(err.to_string().contains("empty host"), "got: {err}");
    }

    #[test]
    fn accept_ipv4_endpoint() {
        let clusters = vec![Cluster::with_defaults("web", vec!["10.0.0.1:8080".into()])];
        validate_clusters(&clusters, &InsecureOptions::default()).expect("valid IPv4:port should be accepted");
    }

    #[test]
    fn accept_bracketed_ipv6_endpoint() {
        let clusters = vec![Cluster::with_defaults("web", vec!["[2001:db8::1]:80".into()])];
        validate_clusters(&clusters, &InsecureOptions::default()).expect("bracketed IPv6 should be accepted");
    }

    #[test]
    fn accept_hostname_endpoint() {
        let clusters = vec![Cluster::with_defaults("web", vec!["api.example.com:443".into()])];
        validate_clusters(&clusters, &InsecureOptions::default()).expect("hostname:port should be accepted");
    }

    #[test]
    fn reject_ipv4_mapped_ipv6_loopback_endpoint() {
        let clusters = vec![Cluster::with_defaults("web", vec!["[::ffff:127.0.0.1]:80".into()])];
        let err = validate_clusters(&clusters, &InsecureOptions::default()).unwrap_err();
        assert!(
            err.to_string().contains("sensitive address"),
            "IPv4-mapped IPv6 loopback should be flagged: {err}"
        );
    }

    #[test]
    fn reject_zero_weight_endpoint() {
        let yaml = r#"
listeners:
  - name: web
    address: "0.0.0.0:80"
    filter_chains: [main]
filter_chains:
  - name: main
    filters:
      - filter: static_response
        status: 200
clusters:
  - name: "backend"
    endpoints:
      - address: "10.0.0.1:80"
        weight: 0
"#;
        let err = Config::from_yaml(yaml).unwrap_err();
        assert!(err.to_string().contains("weight 0"), "got: {err}");
    }

    #[test]
    fn reject_overweight_endpoint() {
        let yaml = r#"
listeners:
  - name: web
    address: "0.0.0.0:80"
    filter_chains: [main]
filter_chains:
  - name: main
    filters:
      - filter: static_response
        status: 200
clusters:
  - name: "backend"
    endpoints:
      - address: "10.0.0.1:80"
        weight: 4000000000 # 4 billion replicas if expanded
"#;
        let err = Config::from_yaml(yaml).unwrap_err();
        assert!(
            err.to_string().contains(&format!("max {MAX_ENDPOINT_WEIGHT}")),
            "got: {err}"
        );
    }

    #[test]
    fn reject_decimal_loopback_endpoint() {
        let clusters = vec![Cluster::with_defaults("web", vec!["2130706433:80".into()])];
        let err = validate_clusters(&clusters, &InsecureOptions::default()).unwrap_err();
        assert!(
            err.to_string().contains("sensitive address"),
            "decimal 2130706433 (127.0.0.1) should be rejected: {err}"
        );
    }

    #[test]
    fn reject_hex_loopback_endpoint() {
        let clusters = vec![Cluster::with_defaults("web", vec!["0x7f000001:80".into()])];
        let err = validate_clusters(&clusters, &InsecureOptions::default()).unwrap_err();
        assert!(
            err.to_string().contains("sensitive address"),
            "hex 0x7f000001 (127.0.0.1) should be rejected: {err}"
        );
    }

    #[test]
    fn reject_octal_dotted_loopback_endpoint() {
        let clusters = vec![Cluster::with_defaults("web", vec!["0177.0.0.1:80".into()])];
        let err = validate_clusters(&clusters, &InsecureOptions::default()).unwrap_err();
        assert!(
            err.to_string().contains("sensitive address"),
            "octal 0177.0.0.1 (127.0.0.1) should be rejected: {err}"
        );
    }

    #[test]
    fn reject_hex_dotted_loopback_endpoint() {
        let clusters = vec![Cluster::with_defaults("web", vec!["0x7f.0.0.1:80".into()])];
        let err = validate_clusters(&clusters, &InsecureOptions::default()).unwrap_err();
        assert!(
            err.to_string().contains("sensitive address"),
            "hex dotted 0x7f.0.0.1 (127.0.0.1) should be rejected: {err}"
        );
    }

    #[test]
    fn reject_decimal_link_local_endpoint() {
        let clusters = vec![Cluster::with_defaults("web", vec!["2852039166:80".into()])];
        let err = validate_clusters(&clusters, &InsecureOptions::default()).unwrap_err();
        assert!(
            err.to_string().contains("sensitive address"),
            "decimal 2852039166 (169.254.169.254) should be rejected: {err}"
        );
    }

    #[test]
    fn accept_decimal_public_ip_endpoint() {
        let clusters = vec![Cluster::with_defaults("web", vec!["134744072:80".into()])];
        validate_clusters(&clusters, &InsecureOptions::default())
            .expect("decimal 134744072 (8.8.8.8) should not be flagged");
    }
}