zentinel-config 0.5.7

Configuration loading and validation for Zentinel reverse proxy
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
//! KDL parsing for namespace and service configuration blocks.
//!
//! This module handles parsing of the hierarchical namespace/service
//! configuration structure from KDL format.

use anyhow::{Context, Result};
use tracing::trace;

use crate::namespace::{ExportConfig, NamespaceConfig, ServiceConfig};
use crate::ListenerConfig;

use super::helpers::get_first_arg_string;
use super::{parse_filter_definitions, parse_listeners, parse_routes, parse_upstreams};

// ============================================================================
// Namespace Parsing
// ============================================================================

/// Parse a namespace block from KDL.
///
/// # Example KDL
///
/// ```kdl
/// namespace "api" {
///     limits { ... }
///     listeners { ... }
///     upstreams { ... }
///     routes { ... }
///     agents { ... }
///     filters { ... }
///     service "payments" { ... }
///     exports { ... }
/// }
/// ```
pub fn parse_namespace(node: &kdl::KdlNode) -> Result<NamespaceConfig> {
    let id = get_first_arg_string(node)
        .ok_or_else(|| anyhow::anyhow!("Namespace requires an ID as first argument"))?;

    trace!(namespace_id = %id, "Parsing namespace");

    let mut ns = NamespaceConfig::new(id.clone());

    let children = node.children().ok_or_else(|| {
        anyhow::anyhow!(
            "Namespace '{}' requires a configuration block with braces {{}}",
            id
        )
    })?;

    for child in children.nodes() {
        let child_name = child.name().value();
        trace!(namespace = %id, block = child_name, "Parsing namespace child block");

        match child_name {
            "limits" => {
                ns.limits = Some(super::parse_limits_config(child)?);
                trace!(namespace = %id, "Parsed namespace limits");
            }
            "listeners" => {
                ns.listeners = parse_listeners(child)?;
                trace!(namespace = %id, count = ns.listeners.len(), "Parsed namespace listeners");
            }
            "upstreams" => {
                ns.upstreams = parse_upstreams(child)?;
                trace!(namespace = %id, count = ns.upstreams.len(), "Parsed namespace upstreams");
            }
            "routes" => {
                ns.routes = parse_routes(child)?;
                trace!(namespace = %id, count = ns.routes.len(), "Parsed namespace routes");
            }
            "agents" => {
                ns.agents = super::parse_agents(child)?;
                trace!(namespace = %id, count = ns.agents.len(), "Parsed namespace agents");
            }
            "filters" => {
                ns.filters = parse_filter_definitions(child)?;
                trace!(namespace = %id, count = ns.filters.len(), "Parsed namespace filters");
            }
            "service" => {
                let service = parse_service(child)?;
                trace!(namespace = %id, service = %service.id, "Parsed service");
                ns.services.push(service);
            }
            "exports" => {
                ns.exports = parse_exports(child)?;
                trace!(namespace = %id, exports = ns.exports.len(), "Parsed exports");
            }
            other => {
                return Err(anyhow::anyhow!(
                    "Unknown block '{}' in namespace '{}'\n\
                     Valid blocks are: limits, listeners, upstreams, routes, agents, filters, service, exports",
                    other, id
                ));
            }
        }
    }

    Ok(ns)
}

// ============================================================================
// Service Parsing
// ============================================================================

/// Parse a service block from KDL.
///
/// # Example KDL
///
/// ```kdl
/// service "payments" {
///     listener {
///         address "0.0.0.0:8443"
///         protocol "https"
///     }
///     upstreams { ... }
///     routes { ... }
///     agents { ... }
///     filters { ... }
///     limits { ... }
/// }
/// ```
pub fn parse_service(node: &kdl::KdlNode) -> Result<ServiceConfig> {
    let id = get_first_arg_string(node)
        .ok_or_else(|| anyhow::anyhow!("Service requires an ID as first argument"))?;

    trace!(service_id = %id, "Parsing service");

    let mut svc = ServiceConfig::new(id.clone());

    let children = node.children().ok_or_else(|| {
        anyhow::anyhow!(
            "Service '{}' requires a configuration block with braces {{}}",
            id
        )
    })?;

    for child in children.nodes() {
        let child_name = child.name().value();
        trace!(service = %id, block = child_name, "Parsing service child block");

        match child_name {
            "listener" => {
                // Service has a singular listener, not a collection
                svc.listener = Some(parse_single_listener(child)?);
                trace!(service = %id, "Parsed service listener");
            }
            "upstreams" => {
                svc.upstreams = parse_upstreams(child)?;
                trace!(service = %id, count = svc.upstreams.len(), "Parsed service upstreams");
            }
            "routes" => {
                svc.routes = parse_routes(child)?;
                trace!(service = %id, count = svc.routes.len(), "Parsed service routes");
            }
            "agents" => {
                svc.agents = super::parse_agents(child)?;
                trace!(service = %id, count = svc.agents.len(), "Parsed service agents");
            }
            "filters" => {
                svc.filters = parse_filter_definitions(child)?;
                trace!(service = %id, count = svc.filters.len(), "Parsed service filters");
            }
            "limits" => {
                svc.limits = Some(super::parse_limits_config(child)?);
                trace!(service = %id, "Parsed service limits");
            }
            other => {
                return Err(anyhow::anyhow!(
                    "Unknown block '{}' in service '{}'\n\
                     Valid blocks are: listener, upstreams, routes, agents, filters, limits",
                    other,
                    id
                ));
            }
        }
    }

    Ok(svc)
}

// ============================================================================
// Single Listener Parsing (for services)
// ============================================================================

/// Parse a single listener block (used for services).
///
/// Unlike the `listeners` block which contains multiple `listener` children,
/// a service's `listener` block directly contains the listener configuration.
///
/// # Example KDL
///
/// ```kdl
/// listener {
///     id "payments-https"
///     address "0.0.0.0:8443"
///     protocol "https"
///     tls { ... }
/// }
/// ```
fn parse_single_listener(node: &kdl::KdlNode) -> Result<ListenerConfig> {
    use super::helpers::{get_int_entry, get_string_entry};
    use crate::server::ListenerProtocol;

    // Get ID from first argument or from 'id' property in node
    let id = get_first_arg_string(node)
        .or_else(|| get_string_entry(node, "id"))
        .unwrap_or_else(|| "service-listener".to_string());

    let address = get_string_entry(node, "address")
        .ok_or_else(|| anyhow::anyhow!("Listener '{}' requires an 'address'", id))?;

    let protocol_str = get_string_entry(node, "protocol").unwrap_or_else(|| "http".to_string());
    let protocol = match protocol_str.to_lowercase().as_str() {
        "http" => ListenerProtocol::Http,
        "https" => ListenerProtocol::Https,
        "h2" | "http2" => ListenerProtocol::Http2,
        "h3" | "http3" => ListenerProtocol::Http3,
        other => {
            return Err(anyhow::anyhow!(
                "Invalid protocol '{}' for listener '{}'. Valid protocols: http, https, h2, h3",
                other,
                id
            ))
        }
    };

    // Parse TLS config if present
    let tls = if let Some(children) = node.children() {
        children
            .nodes()
            .iter()
            .find(|n| n.name().value() == "tls")
            .map(|n| super::server::parse_tls_config(n, &id))
            .transpose()
            .context("Failed to parse TLS config")?
    } else {
        None
    };

    Ok(ListenerConfig {
        id,
        address,
        protocol,
        tls,
        default_route: get_string_entry(node, "default-route"),
        request_timeout_secs: get_int_entry(node, "request-timeout-secs")
            .map(|v| v as u64)
            .unwrap_or(60),
        keepalive_timeout_secs: get_int_entry(node, "keepalive-timeout-secs")
            .map(|v| v as u64)
            .unwrap_or(75),
        max_concurrent_streams: get_int_entry(node, "max-concurrent-streams")
            .map(|v| v as u32)
            .unwrap_or(100),
    })
}

// ============================================================================
// Export Parsing
// ============================================================================

/// Parse an exports block from KDL.
///
/// # Example KDL
///
/// ```kdl
/// exports {
///     upstreams "shared-auth" "shared-cache"
///     agents "global-waf"
///     filters "rate-limiter"
/// }
/// ```
fn parse_exports(node: &kdl::KdlNode) -> Result<ExportConfig> {
    let mut exports = ExportConfig::default();

    let children = match node.children() {
        Some(c) => c,
        None => return Ok(exports), // Empty exports block is valid
    };

    for child in children.nodes() {
        let child_name = child.name().value();

        match child_name {
            "upstreams" => {
                exports.upstreams = parse_string_list(child);
            }
            "agents" => {
                exports.agents = parse_string_list(child);
            }
            "filters" => {
                exports.filters = parse_string_list(child);
            }
            other => {
                return Err(anyhow::anyhow!(
                    "Unknown export type '{}'\n\
                     Valid export types are: upstreams, agents, filters",
                    other
                ));
            }
        }
    }

    Ok(exports)
}

/// Parse a list of string arguments from a KDL node.
///
/// # Example KDL
///
/// ```kdl
/// upstreams "shared-auth" "shared-cache" "another"
/// ```
fn parse_string_list(node: &kdl::KdlNode) -> Vec<String> {
    node.entries()
        .iter()
        .filter_map(|entry| {
            if entry.name().is_none() {
                // It's a positional argument
                entry.value().as_string().map(|s| s.to_string())
            } else {
                None
            }
        })
        .collect()
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;

    fn parse_kdl_node(kdl: &str) -> kdl::KdlNode {
        let doc: kdl::KdlDocument = kdl.parse().unwrap();
        doc.nodes().first().unwrap().clone()
    }

    #[test]
    fn test_parse_empty_namespace() {
        let kdl = r#"namespace "api" {}"#;
        let node = parse_kdl_node(kdl);
        let ns = parse_namespace(&node).unwrap();
        assert_eq!(ns.id, "api");
        assert!(ns.is_empty());
    }

    #[test]
    fn test_parse_namespace_with_upstreams() {
        let kdl = r#"
            namespace "api" {
                upstreams {
                    upstream "backend" {
                        target "127.0.0.1:8080"
                    }
                }
            }
        "#;
        let node = parse_kdl_node(kdl);
        let ns = parse_namespace(&node).unwrap();
        assert_eq!(ns.id, "api");
        assert_eq!(ns.upstreams.len(), 1);
        assert!(ns.upstreams.contains_key("backend"));
    }

    #[test]
    fn test_parse_empty_service() {
        let kdl = r#"service "payments" {}"#;
        let node = parse_kdl_node(kdl);
        let svc = parse_service(&node).unwrap();
        assert_eq!(svc.id, "payments");
        assert!(svc.is_empty());
    }

    #[test]
    fn test_parse_service_with_listener() {
        let kdl = r#"
            service "payments" {
                listener {
                    id "payments-https"
                    address "0.0.0.0:8443"
                    protocol "https"
                }
            }
        "#;
        let node = parse_kdl_node(kdl);
        let svc = parse_service(&node).unwrap();
        assert_eq!(svc.id, "payments");
        assert!(svc.listener.is_some());
        let listener = svc.listener.unwrap();
        assert_eq!(listener.id, "payments-https");
        assert_eq!(listener.address, "0.0.0.0:8443");
    }

    #[test]
    fn test_parse_exports() {
        let kdl = r#"
            exports {
                upstreams "shared-auth" "shared-cache"
                agents "global-waf"
            }
        "#;
        let node = parse_kdl_node(kdl);
        let exports = parse_exports(&node).unwrap();
        assert_eq!(exports.upstreams.len(), 2);
        assert_eq!(exports.upstreams[0], "shared-auth");
        assert_eq!(exports.upstreams[1], "shared-cache");
        assert_eq!(exports.agents.len(), 1);
        assert_eq!(exports.agents[0], "global-waf");
    }

    #[test]
    fn test_parse_string_list() {
        let kdl = r#"items "a" "b" "c""#;
        let node = parse_kdl_node(kdl);
        let list = parse_string_list(&node);
        assert_eq!(list, vec!["a", "b", "c"]);
    }

    #[test]
    fn test_namespace_requires_id() {
        let kdl = r#"namespace {}"#;
        let node = parse_kdl_node(kdl);
        let result = parse_namespace(&node);
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("requires an ID"));
    }

    #[test]
    fn test_service_requires_id() {
        let kdl = r#"service {}"#;
        let node = parse_kdl_node(kdl);
        let result = parse_service(&node);
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("requires an ID"));
    }
}