praxis-proxy-core 0.7.3

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

//! Cluster validation: endpoints, weights, SNI hostnames, timeouts, and health check addresses.

mod application;
mod authority;
mod endpoints;
mod health_check;
mod load_balancer;
mod timeouts;
mod tls;

pub use health_check::is_ssrf_sensitive;

use crate::{config::InsecureOptions, errors::ProxyError};

/// Validate the configured authority override for one cluster.
pub(in crate::config) fn validate_authority(authority: &str, cluster_name: &str) -> Result<(), ProxyError> {
    authority::validate_authority(authority, cluster_name)
}

// -----------------------------------------------------------------------------
// Cluster Validation Constants
// -----------------------------------------------------------------------------

/// Maximum number of clusters allowed in the configuration.
const MAX_CLUSTERS: usize = 10_000;

/// Maximum allowed timeout value in milliseconds (1 hour).
pub(crate) const MAX_TIMEOUT_MS: u64 = 3_600_000;

/// Maximum number of endpoints allowed per cluster.
pub(crate) const MAX_ENDPOINTS: usize = 10_000;

/// Maximum relative weight for a single endpoint.
///
/// Weighted load balancers (Maglev, consistent hashing) expand each
/// endpoint into `weight` replicas at build time, so an unbounded weight
/// is an out-of-memory vector — a `weight` typo would allocate billions
/// of replicas during a live reload. A ratio of 1000:1 is far beyond any
/// real hardware-capacity spread.
pub(crate) const MAX_ENDPOINT_WEIGHT: u32 = 1_000;

// -----------------------------------------------------------------------------
// Cluster Validation
// -----------------------------------------------------------------------------

/// Validate endpoint counts, weights, SNI hostnames, and timeout consistency.
pub(in crate::config::validate) fn validate_clusters(
    clusters: &[crate::config::Cluster],
    insecure_options: &InsecureOptions,
) -> Result<(), ProxyError> {
    if clusters.len() > MAX_CLUSTERS {
        return Err(ProxyError::Config(format!(
            "too many clusters ({}, max {MAX_CLUSTERS})",
            clusters.len()
        )));
    }
    for cluster in clusters {
        if cluster.name.is_empty() {
            return Err(ProxyError::Config("cluster name must not be empty".into()));
        }
        super::validate_name_chars(&cluster.name, "cluster")?;
        cluster.validate_authority()?;
        application::validate_application_metadata(cluster)?;
        endpoints::validate_endpoints(cluster, insecure_options)?;
        validate_endpoint_hosts(cluster)?;
        tls::validate_tls_settings(cluster, insecure_options)?;
        timeouts::validate_timeouts(cluster)?;
        validate_cluster_max_connections(cluster)?;
        load_balancer::validate_lb_strategy(cluster)?;
        if let Some(hc) = &cluster.health_check {
            health_check::validate_health_check(hc, &cluster.name)?;
        }
        health_check::validate_grpc_probe_transport(cluster)?;
        health_check::validate_health_check_ssrf(cluster, insecure_options)?;
        health_check::warn_tls_http_probe_mismatch(cluster);
    }
    Ok(())
}

// -----------------------------------------------------------------------------
// Trusted Private Endpoints Validation
// -----------------------------------------------------------------------------

/// Each entry must be a hostname naming one of the cluster's endpoints.
fn validate_endpoint_hosts(cluster: &crate::config::Cluster) -> Result<(), ProxyError> {
    if cluster.trusted_private_endpoints.is_empty() {
        return Ok(());
    }
    let context = format!("cluster '{}'", cluster.name);
    crate::connectivity::validate_host_entries(&context, &cluster.trusted_private_endpoints)
        .map_err(ProxyError::Config)?;
    for entry in &cluster.trusted_private_endpoints {
        let unbracketed = entry
            .strip_prefix('[')
            .and_then(|inner| inner.strip_suffix(']'))
            .unwrap_or(entry);
        let host = crate::connectivity::strip_root_dot(entry);
        let fault = if unbracketed.parse::<std::net::IpAddr>().is_ok() {
            // Literal endpoints are never resolved, so the entry could not match.
            "is an IP address"
        } else if host.is_empty() || host.ends_with('.') {
            "is not a hostname"
        } else if !cluster.endpoints.iter().any(|ep| {
            crate::connectivity::strip_root_dot(health_check::extract_host(ep.address())).eq_ignore_ascii_case(host)
        }) {
            "matches no endpoint host"
        } else {
            continue;
        };
        return Err(ProxyError::Config(format!(
            "{context}: trusted_private_endpoints entry {entry:?} {fault}"
        )));
    }
    Ok(())
}

// -----------------------------------------------------------------------------
// Max Connections Validation
// -----------------------------------------------------------------------------

/// Validate `max_connections` is at least 1 and within the allowed ceiling.
fn validate_cluster_max_connections(cluster: &crate::config::Cluster) -> Result<(), ProxyError> {
    let Some(max_connections) = cluster.max_connections else {
        return Ok(());
    };
    let name = &cluster.name;
    if max_connections == 0 {
        return Err(ProxyError::Config(format!(
            "cluster '{name}': max_connections must be >= 1"
        )));
    }
    if max_connections > super::MAX_CONNECTIONS {
        return Err(ProxyError::Config(format!(
            "cluster '{name}': max_connections ({max_connections}) exceeds maximum ({})",
            super::MAX_CONNECTIONS,
        )));
    }
    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::validate_clusters;
    use crate::config::{Cluster, Config, InsecureOptions};

    #[test]
    fn reject_too_many_clusters() {
        let clusters: Vec<Cluster> = (0..10_001)
            .map(|i| Cluster::with_defaults(&format!("c{i}"), vec!["10.0.0.1:80".into()]))
            .collect();
        let err = validate_clusters(&clusters, &InsecureOptions::default()).unwrap_err();
        assert!(err.to_string().contains("too many clusters"), "got: {err}");
    }

    #[test]
    fn no_tls_skips_tls_validation() {
        let clusters = vec![Cluster::with_defaults("web", vec!["10.0.0.1:80".into()])];
        validate_clusters(&clusters, &InsecureOptions::default()).expect("no TLS should skip TLS validation");
    }

    #[test]
    fn reject_cluster_zero_max_connections() {
        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: ["10.0.0.1:80"]
    max_connections: 0
"#;
        let err = Config::from_yaml(yaml).unwrap_err();
        assert!(
            err.to_string().contains("max_connections must be >= 1"),
            "should reject zero cluster max_connections: {err}"
        );
    }

    #[test]
    fn reject_cluster_max_connections_exceeding_maximum() {
        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: ["10.0.0.1:80"]
    max_connections: 1000001
"#;
        let err = Config::from_yaml(yaml).unwrap_err();
        assert!(
            err.to_string().contains("exceeds maximum"),
            "should reject cluster max_connections > 1M: {err}"
        );
    }

    #[test]
    fn accept_cluster_with_authority() {
        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: api
    endpoints: ["10.0.0.1:443"]
    http:
      authority: "api.example.com"
"#;
        Config::from_yaml(yaml).unwrap();
    }

    #[test]
    fn accept_cluster_with_authority_and_port() {
        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: api
    endpoints: ["10.0.0.1:8443"]
    http:
      authority: "api.example.com:8443"
"#;
        Config::from_yaml(yaml).unwrap();
    }

    #[test]
    fn accept_cluster_with_endpoint_authority() {
        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: api
    endpoints: ["api-a.example.com:443", "api-b.example.com:443"]
    http:
      authority: { from: endpoint }
    tls: {}
"#;
        let config = Config::from_yaml(yaml).unwrap();
        assert!(
            config.clusters[0]
                .http
                .authority
                .as_ref()
                .is_some_and(crate::config::UpstreamAuthority::follows_endpoint),
            "authority should parse as the endpoint-derived form"
        );
    }

    #[test]
    fn reject_cluster_with_unknown_authority_source() {
        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: api
    endpoints: ["10.0.0.1:80"]
    http:
      authority: { from: upstream }
"#;
        let err = Config::from_yaml(yaml).unwrap_err();
        assert!(
            err.to_string().contains("upstream"),
            "the unknown authority source should be named: {err}"
        );
    }

    #[test]
    fn accept_cluster_without_authority() {
        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: ["10.0.0.1:80"]
"#;
        Config::from_yaml(yaml).unwrap();
    }

    #[test]
    fn reject_cluster_with_empty_authority() {
        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: ["10.0.0.1:80"]
    http:
      authority: ""
"#;
        let err = Config::from_yaml(yaml).unwrap_err();
        assert!(
            err.to_string().contains("must not be empty"),
            "should reject empty authority: {err}"
        );
    }

    #[test]
    fn reject_cluster_with_scheme_in_authority() {
        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: ["10.0.0.1:443"]
    http:
      authority: "https://api.example.com"
"#;
        let err = Config::from_yaml(yaml).unwrap_err();
        assert!(
            err.to_string().contains("not a valid HTTP authority"),
            "should reject authority with scheme: {err}"
        );
    }

    #[test]
    fn reject_cluster_with_path_in_authority() {
        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: ["10.0.0.1:443"]
    http:
      authority: "api.example.com/v1"
"#;
        let err = Config::from_yaml(yaml).unwrap_err();
        assert!(
            err.to_string().contains("not a valid HTTP authority"),
            "should reject authority with path: {err}"
        );
    }

    #[test]
    fn accept_cluster_max_connections_at_maximum() {
        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: ["10.0.0.1:80"]
    max_connections: 1000000
"#;
        Config::from_yaml(yaml).unwrap();
    }

    #[test]
    fn accept_cluster_application_metadata() {
        config_with_http_block("      application_protocol: openai_chat_completions\n      application_provider: vllm")
            .expect("valid application metadata should be accepted");
    }

    #[test]
    fn accept_cluster_application_protocol_alone() {
        config_with_http_block("      application_protocol: openai_responses")
            .expect("application_protocol without provider should be accepted");
    }

    #[test]
    fn accept_cluster_application_provider_alone() {
        config_with_http_block("      application_provider: vllm")
            .expect("application_provider without protocol should be accepted");
    }

    #[test]
    fn reject_cluster_invalid_application_protocol() {
        let err = config_with_http_block("      application_protocol: OpenAI").unwrap_err();
        assert!(
            err.to_string().contains("application_protocol"),
            "should reject invalid application_protocol: {err}"
        );
    }

    #[test]
    fn reject_cluster_invalid_application_provider() {
        let err = config_with_http_block("      application_provider: \"vllm!\"").unwrap_err();
        assert!(
            err.to_string().contains("application_provider"),
            "should reject invalid application_provider: {err}"
        );
    }

    #[test]
    fn reject_cluster_empty_application_protocol() {
        let err = config_with_http_block("      application_protocol: \"\"").unwrap_err();
        assert!(
            err.to_string().contains("must not be empty"),
            "should reject empty application_protocol: {err}"
        );
    }

    #[test]
    fn reject_inline_load_balancer_cluster_invalid_application_protocol() {
        let yaml = r#"
listeners:
  - name: web
    address: "0.0.0.0:80"
    filter_chains: [main]
filter_chains:
  - name: main
    filters:
      - filter: load_balancer
        clusters:
          - name: api
            endpoints: ["10.0.0.1:443"]
            http:
              application_protocol: OpenAI
"#;
        let err = Config::from_yaml(yaml).unwrap_err();
        assert!(
            err.to_string().contains("application_protocol"),
            "inline load-balancer cluster must reject an invalid application_protocol \
             (same validation as top-level clusters): {err}"
        );
    }

    // -------------------------------------------------------------------------
    // Test Utilities
    // -------------------------------------------------------------------------

    // Build a config with one cluster carrying the given `http:` block.
    fn config_with_http_block(http_block: &str) -> Result<Config, crate::errors::ProxyError> {
        let yaml = format!(
            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: api
    endpoints: ["10.0.0.1:443"]
    http:
{http_block}
"#
        );
        Config::from_yaml(&yaml)
    }
}