praxis-proxy-core 0.6.0

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
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
// SPDX-License-Identifier: Apache-2.0
// Copyright (c) 2024 Praxis Contributors

//! Validation for clusters defined inline in load-balancer filter configs.
//!
//! The `load_balancer` and `tcp_load_balancer` filters accept a `clusters:`
//! list inside their opaque filter config. Those clusters must pass the same
//! validation as top-level `clusters:` — endpoint weight ceiling, SSRF
//! endpoint gating, insecure-TLS gating, timeouts — otherwise the inline
//! form silently bypasses every safety check (`validate_clusters` runs only
//! over `Config::clusters`).

use std::collections::HashSet;

use super::cluster::validate_clusters;
use crate::{
    config::{ChainRef, Cluster, FilterChainConfig, FilterEntry, InsecureOptions, Listener, ProtocolKind},
    errors::ProxyError,
};

/// Filter type names whose config may define inline clusters.
const CLUSTER_BEARING_FILTERS: &[&str] = &["load_balancer", "tcp_load_balancer"];

/// Filter type whose config nests filter entries under `steps[].filters`.
pub(super) const STEP_BEARING_FILTER: &str = "iterative_request_router";

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

/// Validate inline `clusters:` lists in every load-balancer filter entry,
/// including entries nested in inline branch chains.
pub(super) fn validate_inline_clusters(
    chains: &[FilterChainConfig],
    insecure_options: &InsecureOptions,
) -> Result<(), ProxyError> {
    for chain in chains {
        validate_chain_entries_inline_clusters(&chain.name, &chain.filters, insecure_options)?;
    }
    Ok(())
}

/// Validate inline `clusters:` lists in a single chain's filter entries.
///
/// This is the entry-level slice of the whole-config `validate_inline_clusters`
/// pass: it gates one list of [`FilterEntry`] under a given logical chain name,
/// recursing into
/// inline branch chains and `iterative_request_router` steps exactly as the
/// whole-config pass does. It exists so outbound chains bound at pipeline-build
/// time — which never appear in `Config::filter_chains` — are held to the same
/// SSRF and insecure-TLS rules as top-level `clusters:` instead of bypassing
/// them.
///
/// # Errors
///
/// Returns [`ProxyError::Config`] if any inline cluster is malformed, names a
/// duplicate, or fails endpoint/TLS validation under `insecure_options`.
pub fn validate_chain_entries_inline_clusters(
    chain_name: &str,
    entries: &[FilterEntry],
    insecure_options: &InsecureOptions,
) -> Result<(), ProxyError> {
    for entry in entries {
        validate_entry(chain_name, entry, insecure_options)?;
    }
    Ok(())
}

/// Validate one filter entry and recurse into its inline branch chains.
fn validate_entry(chain_name: &str, entry: &FilterEntry, insecure_options: &InsecureOptions) -> Result<(), ProxyError> {
    if CLUSTER_BEARING_FILTERS.contains(&entry.filter_type.as_str()) {
        let clusters = extract_clusters(chain_name, entry)?;
        validate_inline_names(chain_name, &entry.filter_type, &clusters)?;
        validate_clusters(&clusters, insecure_options).map_err(|err| {
            ProxyError::Config(format!(
                "chain '{chain_name}': filter '{}': inline {err}",
                entry.filter_type
            ))
        })?;
    }

    for branch in entry.branch_chains.as_deref().unwrap_or_default() {
        for chain_ref in &branch.chains {
            if let ChainRef::Inline { name, filters } = chain_ref {
                for nested in filters {
                    validate_entry(name, nested, insecure_options)?;
                }
            }
        }
    }

    if entry.filter_type == STEP_BEARING_FILTER {
        for nested in extract_step_filters(chain_name, entry)? {
            validate_entry(chain_name, &nested, insecure_options)?;
        }
    }
    Ok(())
}

/// Validate that every TCP listener's `cluster` reference resolves.
///
/// A TCP listener's `cluster` is consumed only by the `tcp_load_balancer`
/// filter, which looks the name up in its own inline `clusters:` list. A
/// name that matches none of those inline clusters is never resolvable, so
/// every connection to the listener fails at connect time — a startup-time
/// typo surfacing only as a total per-listener outage.
pub(super) fn validate_tcp_listener_clusters(
    listeners: &[Listener],
    chains: &[FilterChainConfig],
) -> Result<(), ProxyError> {
    // Chain names are unique (validated elsewhere), so index once
    // instead of scanning the chain list per listener reference.
    let chains_by_name: std::collections::HashMap<&str, &FilterChainConfig> =
        chains.iter().map(|chain| (chain.name.as_str(), chain)).collect();

    for listener in listeners {
        if listener.protocol != ProtocolKind::Tcp {
            continue;
        }
        let Some(cluster_name) = listener.cluster.as_deref() else {
            continue;
        };

        if !listener_defines_tcp_cluster(listener, &chains_by_name, cluster_name)? {
            return Err(ProxyError::Config(format!(
                "listener '{}': cluster '{cluster_name}' is not defined by any tcp_load_balancer \
                 filter in its chains (a TCP listener's cluster must name an inline \
                 tcp_load_balancer cluster)",
                listener.name
            )));
        }
    }
    Ok(())
}

/// Whether any `tcp_load_balancer` filter in the listener's chains
/// defines an inline cluster named `cluster_name`.
///
/// Short-circuiting on the first match is equivalent to collecting
/// every name first: `validate_inline_clusters` has already parsed and
/// validated every inline list by the time this check runs, so
/// `extract_clusters` cannot surface a new error here.
fn listener_defines_tcp_cluster(
    listener: &Listener,
    chains_by_name: &std::collections::HashMap<&str, &FilterChainConfig>,
    cluster_name: &str,
) -> Result<bool, ProxyError> {
    for chain_name in &listener.filter_chains {
        let Some(chain) = chains_by_name.get(chain_name.as_str()) else {
            continue;
        };
        for entry in &chain.filters {
            if entry.filter_type == "tcp_load_balancer"
                && extract_clusters(&chain.name, entry)?
                    .iter()
                    .any(|cluster| cluster.name.as_ref() == cluster_name)
            {
                return Ok(true);
            }
        }
    }
    Ok(false)
}

/// Deserialize filter entries nested under an `iterative_request_router`
/// filter's `steps[].filters`.
///
/// These live in the opaque filter config exactly like inline branch
/// filters, and can themselves declare inline load-balancer clusters that
/// would otherwise bypass validation.
pub(super) fn extract_step_filters(chain_name: &str, entry: &FilterEntry) -> Result<Vec<FilterEntry>, ProxyError> {
    let serde_yaml::Value::Mapping(mapping) = &entry.config else {
        return Ok(Vec::new());
    };
    let Some(serde_yaml::Value::Sequence(steps)) = mapping.get("steps") else {
        return Ok(Vec::new());
    };
    let mut filters = Vec::new();
    for step in steps {
        let serde_yaml::Value::Mapping(step_map) = step else {
            continue;
        };
        let Some(step_filters) = step_map.get("filters") else {
            continue;
        };
        let parsed: Vec<FilterEntry> = serde_yaml::from_value(step_filters.clone()).map_err(|err| {
            ProxyError::Config(format!(
                "chain '{chain_name}': filter '{}': invalid step filters: {err}",
                entry.filter_type
            ))
        })?;
        filters.extend(parsed);
    }
    Ok(filters)
}

/// Deserialize the `clusters` key from an opaque filter config, if present.
///
/// A malformed list is an error here (with chain/filter context) rather
/// than a startup failure deep inside the filter factory.
fn extract_clusters(chain_name: &str, entry: &FilterEntry) -> Result<Vec<Cluster>, ProxyError> {
    let serde_yaml::Value::Mapping(mapping) = &entry.config else {
        return Ok(Vec::new());
    };
    let Some(clusters_value) = mapping.get("clusters") else {
        return Ok(Vec::new());
    };
    serde_yaml::from_value(clusters_value.clone()).map_err(|err| {
        ProxyError::Config(format!(
            "chain '{chain_name}': filter '{}': invalid inline clusters: {err}",
            entry.filter_type
        ))
    })
}

/// Reject duplicate cluster names within one filter's inline list.
fn validate_inline_names(chain_name: &str, filter_type: &str, clusters: &[Cluster]) -> Result<(), ProxyError> {
    let mut seen = HashSet::new();
    for cluster in clusters {
        if !seen.insert(&cluster.name) {
            return Err(ProxyError::Config(format!(
                "chain '{chain_name}': filter '{filter_type}': duplicate inline cluster name '{}'",
                cluster.name
            )));
        }
    }
    Ok(())
}

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

#[cfg(test)]
#[expect(clippy::allow_attributes, reason = "blanket test suppressions")]
#[allow(
    clippy::unwrap_used,
    clippy::expect_used,
    clippy::str_to_string,
    clippy::indexing_slicing,
    reason = "tests use unwrap/expect/indexing for brevity"
)]
mod tests {
    use crate::config::{Config, FilterChainConfig, Listener};

    /// Base YAML with an inline `load_balancer` cluster spliced in.
    fn config_with_inline_cluster(cluster_yaml: &str) -> String {
        format!(
            "listeners:\n  - name: main\n    address: \"127.0.0.1:18080\"\n    protocol: http\n    filter_chains: [chain]\nfilter_chains:\n  - name: chain\n    filters:\n      - filter: load_balancer\n        clusters:\n{cluster_yaml}"
        )
    }

    #[test]
    fn tcp_listener_unknown_chain_skipped_without_panic() {
        let listener: Listener = serde_yaml::from_str(
            "name: t\naddress: \"127.0.0.1:19999\"\nprotocol: tcp\ncluster: pool\nfilter_chains: [missing]\n",
        )
        .expect("listener yaml");
        let chains: Vec<FilterChainConfig> = Vec::new();
        let err = super::validate_tcp_listener_clusters(&[listener], &chains).unwrap_err();
        assert!(
            err.to_string().contains("pool"),
            "the undefined cluster must be reported even with an unknown chain: {err}"
        );
    }

    #[test]
    fn inline_cluster_weight_over_ceiling_rejected() {
        let yaml = config_with_inline_cluster(
            "          - name: web\n            endpoints:\n              - address: \"192.0.2.1:80\"\n                weight: 2000000000\n",
        );
        let err = Config::from_yaml(&yaml).unwrap_err();
        assert!(
            err.to_string().contains("weight") && err.to_string().contains("chain"),
            "inline endpoint weight must hit the same ceiling as top-level clusters: {err}"
        );
    }

    #[test]
    fn inline_cluster_insecure_tls_rejected_without_flag() {
        let yaml = config_with_inline_cluster(
            "          - name: web\n            tls:\n              verify: false\n            endpoints:\n              - address: \"192.0.2.1:443\"\n",
        );
        let err = Config::from_yaml(&yaml).unwrap_err();
        assert!(
            err.to_string().contains("verify"),
            "inline tls.verify: false must be gated like top-level clusters: {err}"
        );
    }

    #[test]
    fn inline_cluster_empty_endpoints_rejected() {
        let yaml = config_with_inline_cluster("          - name: web\n            endpoints: []\n");
        let err = Config::from_yaml(&yaml).unwrap_err();
        assert!(
            err.to_string().contains("endpoint"),
            "inline cluster without endpoints must be rejected: {err}"
        );
    }

    #[test]
    fn inline_cluster_duplicate_names_rejected() {
        let yaml = config_with_inline_cluster(
            "          - name: web\n            endpoints:\n              - address: \"192.0.2.1:80\"\n          - name: web\n            endpoints:\n              - address: \"192.0.2.2:80\"\n",
        );
        let err = Config::from_yaml(&yaml).unwrap_err();
        assert!(
            err.to_string().contains("duplicate inline cluster name"),
            "duplicate inline cluster names must be rejected: {err}"
        );
    }

    #[test]
    fn inline_cluster_malformed_list_rejected() {
        let yaml = config_with_inline_cluster("          - just-a-string\n");
        let err = Config::from_yaml(&yaml).unwrap_err();
        assert!(
            err.to_string().contains("invalid inline clusters"),
            "malformed inline clusters must fail validation with context: {err}"
        );
    }

    #[test]
    fn valid_inline_cluster_accepted() {
        let yaml = config_with_inline_cluster(
            "          - name: web\n            endpoints:\n              - address: \"192.0.2.1:80\"\n                weight: 5\n",
        );
        Config::from_yaml(&yaml).expect("valid inline cluster should pass validation");
    }

    #[test]
    fn tcp_listener_unknown_cluster_rejected() {
        let yaml = "listeners:\n  - name: db\n    address: \"127.0.0.1:15432\"\n    protocol: tcp\n    cluster: db_pool_typo\n    filter_chains: [tcp_lb]\nfilter_chains:\n  - name: tcp_lb\n    filters:\n      - filter: tcp_load_balancer\n        clusters:\n          - name: db_pool\n            endpoints: [\"10.0.0.1:5432\"]\ninsecure_options:\n  allow_private_endpoints: true\n";
        let err = Config::from_yaml(yaml).unwrap_err();
        assert!(
            err.to_string().contains("db_pool_typo") && err.to_string().contains("tcp_load_balancer"),
            "a TCP listener cluster typo must be rejected at startup: {err}"
        );
    }

    #[test]
    fn tcp_listener_known_cluster_accepted() {
        let yaml = "listeners:\n  - name: db\n    address: \"127.0.0.1:15432\"\n    protocol: tcp\n    cluster: db_pool\n    filter_chains: [tcp_lb]\nfilter_chains:\n  - name: tcp_lb\n    filters:\n      - filter: tcp_load_balancer\n        clusters:\n          - name: db_pool\n            endpoints: [\"10.0.0.1:5432\"]\ninsecure_options:\n  allow_private_endpoints: true\n";
        Config::from_yaml(yaml).expect("a TCP listener naming a defined tcp_load_balancer cluster must pass");
    }

    #[test]
    fn inline_cluster_in_iterative_router_step_validated() {
        let yaml = "listeners:\n  - name: main\n    address: \"127.0.0.1:18080\"\n    protocol: http\n    filter_chains: [main]\nfilter_chains:\n  - name: main\n    filters:\n      - filter: iterative_request_router\n        steps:\n          - name: call\n            filters:\n              - filter: load_balancer\n                clusters:\n                  - name: web\n                    endpoints:\n                      - address: \"192.0.2.1:80\"\n                        weight: 2000000000\n";
        let err = Config::from_yaml(yaml).unwrap_err();
        assert!(
            err.to_string().contains("weight"),
            "clusters inside iterative_request_router steps must be validated: {err}"
        );
    }

    #[test]
    fn inline_cluster_in_branch_chain_validated() {
        let yaml = "listeners:\n  - name: main\n    address: \"127.0.0.1:18080\"\n    protocol: http\n    filter_chains: [chain]\nfilter_chains:\n  - name: chain\n    filters:\n      - filter: header_static\n        headers:\n          x-a: b\n        branch_chains:\n          - name: br\n            chains:\n              - name: inline-sub\n                filters:\n                  - filter: load_balancer\n                    clusters:\n                      - name: web\n                        endpoints:\n                          - address: \"192.0.2.1:80\"\n                            weight: 2000000000\n            rejoin: next\n";
        let err = Config::from_yaml(yaml).unwrap_err();
        assert!(
            err.to_string().contains("weight"),
            "branch-chain inline clusters must be validated too: {err}"
        );
    }

    #[test]
    fn extract_step_filters_with_non_mapping_config() {
        use serde_yaml::Value;

        use crate::config::FilterEntry;

        let entry = FilterEntry {
            filter_type: super::STEP_BEARING_FILTER.to_string(),
            config: Value::String("not-a-mapping".to_string()),
            name: None,
            conditions: Vec::new(),
            response_conditions: Vec::new(),
            failure_mode: crate::config::filters::FailureMode::default(),
            branch_chains: None,
        };

        let result = super::extract_step_filters("test_chain", &entry);
        assert!(
            result.is_ok(),
            "non-mapping config should return empty vec without error"
        );
        assert!(
            result.unwrap().is_empty(),
            "should return empty vec for non-mapping config"
        );
    }

    #[test]
    fn extract_step_filters_with_non_sequence_steps() {
        use serde_yaml::{Mapping, Value};

        use crate::config::FilterEntry;

        let mut mapping = Mapping::new();
        mapping.insert(
            Value::String("steps".to_string()),
            Value::String("not-a-sequence".to_string()),
        );

        let entry = FilterEntry {
            filter_type: super::STEP_BEARING_FILTER.to_string(),
            config: Value::Mapping(mapping),
            name: None,
            conditions: Vec::new(),
            response_conditions: Vec::new(),
            failure_mode: crate::config::filters::FailureMode::default(),
            branch_chains: None,
        };

        let result = super::extract_step_filters("test_chain", &entry);
        assert!(result.is_ok(), "should handle non-sequence steps");
        assert!(result.unwrap().is_empty(), "should return empty vec");
    }

    #[test]
    fn extract_step_filters_with_non_mapping_step() {
        use serde_yaml::{Mapping, Value};

        use crate::config::FilterEntry;

        let mut mapping = Mapping::new();
        let steps = vec![Value::String("not-a-mapping".to_string())];
        mapping.insert(Value::String("steps".to_string()), Value::Sequence(steps));

        let entry = FilterEntry {
            filter_type: super::STEP_BEARING_FILTER.to_string(),
            config: Value::Mapping(mapping),
            name: None,
            conditions: Vec::new(),
            response_conditions: Vec::new(),
            failure_mode: crate::config::filters::FailureMode::default(),
            branch_chains: None,
        };

        let result = super::extract_step_filters("test_chain", &entry);
        assert!(result.is_ok(), "should skip non-mapping steps");
        assert!(result.unwrap().is_empty(), "should return empty vec");
    }

    #[test]
    fn extract_step_filters_with_missing_filters_key() {
        use serde_yaml::{Mapping, Value};

        use crate::config::FilterEntry;

        let mut step_map = Mapping::new();
        step_map.insert(Value::String("name".to_string()), Value::String("step1".to_string()));

        let mut mapping = Mapping::new();
        let steps = vec![Value::Mapping(step_map)];
        mapping.insert(Value::String("steps".to_string()), Value::Sequence(steps));

        let entry = FilterEntry {
            filter_type: super::STEP_BEARING_FILTER.to_string(),
            config: Value::Mapping(mapping),
            name: None,
            conditions: Vec::new(),
            response_conditions: Vec::new(),
            failure_mode: crate::config::filters::FailureMode::default(),
            branch_chains: None,
        };

        let result = super::extract_step_filters("test_chain", &entry);
        assert!(result.is_ok(), "should skip steps without filters key");
        assert!(result.unwrap().is_empty(), "should return empty vec");
    }

    #[test]
    fn extract_clusters_with_non_mapping_config() {
        use serde_yaml::Value;

        use crate::config::FilterEntry;

        let entry = FilterEntry {
            filter_type: "load_balancer".to_string(),
            config: Value::String("not-a-mapping".to_string()),
            name: None,
            conditions: Vec::new(),
            response_conditions: Vec::new(),
            failure_mode: crate::config::filters::FailureMode::default(),
            branch_chains: None,
        };

        let result = super::extract_clusters("test_chain", &entry);
        assert!(result.is_ok(), "non-mapping config should return empty vec");
        assert!(result.unwrap().is_empty(), "should return empty vec");
    }

    #[test]
    fn extract_clusters_with_missing_clusters_key() {
        use serde_yaml::{Mapping, Value};

        use crate::config::FilterEntry;

        let mut mapping = Mapping::new();
        mapping.insert(Value::String("other".to_string()), Value::String("value".to_string()));

        let entry = FilterEntry {
            filter_type: "load_balancer".to_string(),
            config: Value::Mapping(mapping),
            name: None,
            conditions: Vec::new(),
            response_conditions: Vec::new(),
            failure_mode: crate::config::filters::FailureMode::default(),
            branch_chains: None,
        };

        let result = super::extract_clusters("test_chain", &entry);
        assert!(result.is_ok(), "missing clusters key should return empty vec");
        assert!(result.unwrap().is_empty(), "should return empty vec");
    }

    #[test]
    fn tcp_listener_without_cluster_field() {
        let yaml = "listeners:\n  - name: tcp_no_cluster\n    address: \"127.0.0.1:19000\"\n    protocol: tcp\n    filter_chains: [tcp_lb]\nfilter_chains:\n  - name: tcp_lb\n    filters:\n      - filter: tcp_load_balancer\n        clusters:\n          - name: backend\n            endpoints: [\"10.0.0.1:5000\"]\ninsecure_options:\n  allow_private_endpoints: true\n";
        let config = Config::from_yaml(yaml).expect("should parse TCP listener without cluster field");
        assert_eq!(config.listeners.len(), 1);
        assert!(config.listeners[0].cluster.is_none());
    }

    #[test]
    fn http_listener_skipped_in_tcp_validation() {
        let yaml = "listeners:\n  - name: http_listener\n    address: \"127.0.0.1:18080\"\n    protocol: http\n    cluster: should_be_ignored\n    filter_chains: [chain]\nfilter_chains:\n  - name: chain\n    filters:\n      - filter: load_balancer\n        clusters:\n          - name: web\n            endpoints: [\"192.0.2.1:80\"]\n";
        Config::from_yaml(yaml).expect("HTTP listener with cluster field should be ignored in TCP validation");
    }

    #[test]
    fn tcp_listener_referencing_missing_chain() {
        let yaml = "listeners:\n  - name: tcp_listener\n    address: \"127.0.0.1:19000\"\n    protocol: tcp\n    cluster: backend\n    filter_chains: [missing_chain]\nfilter_chains:\n  - name: different_chain\n    filters:\n      - filter: tcp_load_balancer\n        clusters:\n          - name: backend\n            endpoints: [\"10.0.0.1:5000\"]\ninsecure_options:\n  allow_private_endpoints: true\n";
        let err = Config::from_yaml(yaml).unwrap_err();
        assert!(
            err.to_string().contains("missing_chain"),
            "should report the missing chain name: {err}"
        );
    }

    #[test]
    fn validate_inline_clusters_with_empty_chains() {
        use super::{InsecureOptions, validate_inline_clusters};

        let chains = vec![];
        let insecure_options = InsecureOptions::default();
        let result = validate_inline_clusters(&chains, &insecure_options);
        assert!(result.is_ok(), "empty chains should validate successfully");
    }

    #[test]
    fn tcp_load_balancer_filter_validated() {
        let yaml = "listeners:\n  - name: tcp_listener\n    address: \"127.0.0.1:19000\"\n    protocol: tcp\n    cluster: backend\n    filter_chains: [tcp_chain]\nfilter_chains:\n  - name: tcp_chain\n    filters:\n      - filter: tcp_load_balancer\n        clusters:\n          - name: backend\n            endpoints:\n              - address: \"192.0.2.1:80\"\n                weight: 2000000000\ninsecure_options:\n  allow_private_endpoints: true\n";
        let err = Config::from_yaml(yaml).unwrap_err();
        assert!(
            err.to_string().contains("weight"),
            "tcp_load_balancer inline clusters must be validated: {err}"
        );
    }

    #[test]
    fn branch_chain_with_named_reference() {
        let yaml = "listeners:\n  - name: main\n    address: \"127.0.0.1:18080\"\n    protocol: http\n    filter_chains: [chain]\nfilter_chains:\n  - name: chain\n    filters:\n      - filter: header_static\n        headers:\n          x-test: value\n        branch_chains:\n          - name: br\n            chains: [other_chain]\n            rejoin: next\n  - name: other_chain\n    filters:\n      - filter: load_balancer\n        clusters:\n          - name: web\n            endpoints: [\"192.0.2.1:80\"]\n";
        Config::from_yaml(yaml).expect("branch chain with named reference should be valid");
    }

    #[test]
    fn validate_chain_entries_empty_entries() {
        use super::{InsecureOptions, validate_chain_entries_inline_clusters};

        let entries = vec![];
        let insecure_options = InsecureOptions::default();
        let result = validate_chain_entries_inline_clusters("test_chain", &entries, &insecure_options);
        assert!(result.is_ok(), "empty entries should validate successfully");
    }

    #[test]
    fn extract_step_filters_with_valid_filters() {
        use serde_yaml::{Mapping, Value};

        use crate::config::FilterEntry;

        let mut step_map = Mapping::new();
        let filters_yaml = r#"
- filter: load_balancer
  clusters:
    - name: web
      endpoints: ["192.0.2.1:80"]
"#;
        let filters_value: Value = serde_yaml::from_str(filters_yaml).unwrap();
        step_map.insert(Value::String("filters".to_string()), filters_value);

        let mut mapping = Mapping::new();
        let steps = vec![Value::Mapping(step_map)];
        mapping.insert(Value::String("steps".to_string()), Value::Sequence(steps));

        let entry = FilterEntry {
            filter_type: super::STEP_BEARING_FILTER.to_string(),
            config: Value::Mapping(mapping),
            name: None,
            conditions: Vec::new(),
            response_conditions: Vec::new(),
            failure_mode: crate::config::filters::FailureMode::default(),
            branch_chains: None,
        };

        let result = super::extract_step_filters("test_chain", &entry);
        assert!(result.is_ok(), "should parse valid step filters");
        let filters = result.unwrap();
        assert_eq!(filters.len(), 1, "should extract one filter");
        assert_eq!(filters[0].filter_type, "load_balancer");
    }

    #[test]
    fn extract_step_filters_with_malformed_filters() {
        use serde_yaml::{Mapping, Value};

        use crate::config::FilterEntry;

        let mut step_map = Mapping::new();
        step_map.insert(
            Value::String("filters".to_string()),
            Value::String("not-valid-filters".to_string()),
        );

        let mut mapping = Mapping::new();
        let steps = vec![Value::Mapping(step_map)];
        mapping.insert(Value::String("steps".to_string()), Value::Sequence(steps));

        let entry = FilterEntry {
            filter_type: super::STEP_BEARING_FILTER.to_string(),
            config: Value::Mapping(mapping),
            name: None,
            conditions: Vec::new(),
            response_conditions: Vec::new(),
            failure_mode: crate::config::filters::FailureMode::default(),
            branch_chains: None,
        };

        let result = super::extract_step_filters("test_chain", &entry);
        assert!(result.is_err(), "malformed filters should return error");
        assert!(
            result.unwrap_err().to_string().contains("invalid step filters"),
            "error should mention invalid step filters"
        );
    }
}