ferronconf 0.1.3

A Rust library for parsing `ferron.conf` configuration files — a domain-specific language for custom web server configurations.
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
#![cfg(test)]

use crate::ast::*;
use std::str::FromStr;

#[test]
fn test_parser_example() {
    let input = r#"
# Global runtime settings
{
  runtime {
    io_uring true
  }
}

# Snippet
snippet set_curl {
  header X-Curl 1
}

# Matcher definition
match curl_client {
  request.header.user_agent ~ "curl"
}

# Edge case test ("true" would be classified as a boolean by the lexer here)
true.example {
  root {{env.TRUE_WWWROOT}}
}

# Default HTTP settings
http * {
  header X-Powered-By MyServer
}

# Main site
example.com {
  root /var/www/example

  if curl_client {
    use set_curl
  }
}

# Wildcard subdomains
*.example.com {
  reverse_proxy localhost:9000
}

# TCP service
tcp *:5432 {
  proxy localhost:5432
}
"#;

    let config = Config::from_str(input).expect("Failed to parse config");

    // 1. Check Global Block
    let global_block = config
        .statements
        .iter()
        .find(|s| matches!(s, Statement::GlobalBlock(_)))
        .expect("Global block not found");
    if let Statement::GlobalBlock(block) = global_block {
        let runtime = block
            .find_directive("runtime")
            .expect("runtime directive not found");
        assert!(runtime.has_block());
        let io_uring = runtime
            .block
            .as_ref()
            .unwrap()
            .find_directive("io_uring")
            .expect("io_uring not found");
        assert_eq!(io_uring.get_boolean_arg(0), Some(true));
    }

    // 2. Check Snippet
    let snippet_block = config
        .statements
        .iter()
        .find(|s| matches!(s, Statement::SnippetBlock(_)))
        .expect("Snippet block not found");
    if let Statement::SnippetBlock(sb) = snippet_block {
        assert_eq!(sb.name, "set_curl");
        let header = sb
            .block
            .find_directive("header")
            .expect("header directive not found");
        assert_eq!(header.get_string_arg(0), Some("X-Curl"));
        assert_eq!(header.get_integer_arg(1), Some(1));
    }

    // 3. Check Matcher
    let match_blocks = config.find_match_blocks();
    let curl_client = match_blocks
        .iter()
        .find(|m| m.matcher == "curl_client")
        .expect("curl_client matcher not found");
    assert!(curl_client.has_expressions());
    let expr = &curl_client.expr[0];
    assert!(expr.is_regex());
    assert_eq!(
        expr.left.as_identifier().map(|v| v.join(".")),
        Some("request.header.user_agent".to_string())
    );
    assert_eq!(expr.right.as_str(), Some("curl"));

    // 4. Check 'true.example' Host Block
    let true_example = config
        .statements
        .iter()
        .find_map(|s| {
            if let Statement::HostBlock(hb) = s {
                if hb.matches_host("true.example") {
                    Some(hb)
                } else {
                    None
                }
            } else {
                None
            }
        })
        .expect("true.example host block not found");

    let root = true_example
        .block
        .find_directive("root")
        .expect("root directive not found");
    if let Value::InterpolatedString(parts, _) = &root.args[0] {
        assert_eq!(
            parts,
            &vec![StringPart::Expression(vec![
                "env".to_string(),
                "TRUE_WWWROOT".to_string()
            ])]
        );
    } else {
        panic!("Expected interpolation for root argument");
    }

    // 5. Check 'http *' Host Block
    let http_star = config
        .statements
        .iter()
        .find_map(|s| {
            if let Statement::HostBlock(hb) = s {
                if hb.hosts.iter().any(|h| {
                    h.protocol.as_deref() == Some("http")
                        && h.labels == crate::ast::HostLabels::Wildcard
                }) {
                    Some(hb)
                } else {
                    None
                }
            } else {
                None
            }
        })
        .expect("http * host block not found");

    let powered_by = http_star
        .block
        .find_directive("header")
        .expect("header directive not found");
    assert_eq!(powered_by.get_string_arg(0), Some("X-Powered-By"));
    assert_eq!(powered_by.get_string_arg(1), Some("MyServer"));

    // 6. Check 'example.com' Host Block
    let example_com = config
        .statements
        .iter()
        .find_map(|s| {
            if let Statement::HostBlock(hb) = s {
                if hb.matches_host("example.com") {
                    Some(hb)
                } else {
                    None
                }
            } else {
                None
            }
        })
        .expect("example.com host block not found");

    let root = example_com
        .block
        .find_directive("root")
        .expect("root directive not found");
    assert_eq!(root.get_string_arg(0), Some("/var/www/example"));

    let if_directive = example_com
        .block
        .find_directive("if")
        .expect("if directive not found");
    assert_eq!(if_directive.args[0].as_str(), Some("curl_client"));

    // 7. Check TCP service
    let tcp_service = config
        .statements
        .iter()
        .find_map(|s| {
            if let Statement::HostBlock(hb) = s {
                if hb
                    .hosts
                    .iter()
                    .any(|h| h.protocol.as_deref() == Some("tcp") && h.port == Some(5432))
                {
                    Some(hb)
                } else {
                    None
                }
            } else {
                None
            }
        })
        .expect("tcp *:5432 host block not found");

    let proxy = tcp_service
        .block
        .find_directive("proxy")
        .expect("proxy directive not found");
    assert_eq!(proxy.get_string_arg(0), Some("localhost:5432"));
}

#[allow(clippy::approx_constant)]
#[test]
fn test_complex_values() {
    let input = r#"
directive_float 3.14
directive_neg -10
directive_neg_float -3.14
directive_string "string with \"escape\""
directive_interp {{ nested.var }}
directive_interp_multi "prefix {{ nested.var }} suffix {{ other.value }}"
directive_bools true false
"#;
    let config = Config::from_str(input).expect("Failed to parse complex values");

    // Float
    let d_float = config.find_directives("directive_float")[0];
    assert_eq!(d_float.args[0].as_f64(), Some(3.14));

    // Negative Number
    let d_neg = config.find_directives("directive_neg")[0];
    assert_eq!(d_neg.args[0].as_i64(), Some(-10));

    // Negative Float
    let d_neg_float = config.find_directives("directive_neg_float")[0];
    assert_eq!(d_neg_float.args[0].as_f64(), Some(-3.14));

    // String Escapes
    let d_str = config.find_directives("directive_string")[0];
    assert_eq!(d_str.args[0].as_str(), Some("string with \"escape\""));

    // Interpolation
    let d_interp = config.find_directives("directive_interp")[0];
    assert_eq!(
        d_interp.args[0].as_interpolated_string(),
        Some(&[StringPart::Expression(vec![
            "nested".to_string(),
            "var".to_string()
        ])] as &[StringPart])
    );

    let d_interp_multi = config.find_directives("directive_interp_multi")[0];
    assert_eq!(
        d_interp_multi.args[0].as_interpolated_string(),
        Some(&[
            StringPart::Literal("prefix ".to_string()),
            StringPart::Expression(vec!["nested".to_string(), "var".to_string()]),
            StringPart::Literal(" suffix ".to_string()),
            StringPart::Expression(vec!["other".to_string(), "value".to_string()]),
        ] as &[StringPart])
    );

    // Booleans
    let d_bool = config.find_directives("directive_bools")[0];
    assert_eq!(d_bool.get_boolean_arg(0), Some(true));
    assert_eq!(d_bool.get_boolean_arg(1), Some(false));
}

#[test]
fn test_host_patterns() {
    let input = r#"
[::1] {}
[2001:db8::1]:8080 {}
127.0.0.1 {}
"#;
    let config = Config::from_str(input).expect("Failed to parse host patterns");

    config
        .statements
        .iter()
        .find_map(|s| {
            if let Statement::HostBlock(hb) = s {
                if hb.hosts[0].labels
                    == crate::ast::HostLabels::IpAddr(std::net::IpAddr::V6(
                        std::net::Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1),
                    ))
                {
                    Some(hb)
                } else {
                    None
                }
            } else {
                None
            }
        })
        .expect("IPv6 localhost not found");

    let ipv6_port = config
        .statements
        .iter()
        .find_map(|s| {
            if let Statement::HostBlock(hb) = s {
                if hb.hosts[0].port == Some(8080) {
                    Some(hb)
                } else {
                    None
                }
            } else {
                None
            }
        })
        .expect("IPv6 with port not found");

    // Check IPv6 address explicitly
    if let crate::ast::HostLabels::IpAddr(std::net::IpAddr::V6(addr)) = &ipv6_port.hosts[0].labels {
        assert_eq!(addr.to_string(), "2001:db8::1");
    } else {
        panic!("Expected IPv6 address");
    }

    let ipv4 = config
        .statements
        .iter()
        .find_map(|s| {
            if let Statement::HostBlock(hb) = s {
                if hb.hosts[0].as_str() == "127.0.0.1" {
                    Some(hb)
                } else {
                    None
                }
            } else {
                None
            }
        })
        .expect("IPv4 not found");
    assert!(matches!(
        ipv4.hosts[0].labels,
        crate::ast::HostLabels::IpAddr(std::net::IpAddr::V4(_))
    ));
}

#[test]
fn test_top_level_ambiguity() {
    // Case 1: Directive with Quoted String and Block.
    let input_quoted = r#"
    dir_quoted "arg" {
        inside true
    }
    "#;
    let config = Config::from_str(input_quoted).expect("dir_quoted should parse successfully now");
    if let Statement::Directive(d) = &config.statements[0] {
        assert_eq!(d.name, "dir_quoted");
        assert_eq!(d.args[0].as_str(), Some("arg"));
        assert!(d.has_block());
    } else {
        panic!("dir_quoted did not parse as Directive");
    }

    // Case 2: Directive with Bare String and Block.
    // Parses as HostBlock.
    let input_bare = r#"
    dir_bare arg { }
    "#;
    let config = Config::from_str(input_bare).expect("dir_bare failed");
    if let Statement::HostBlock(hb) = &config.statements[0] {
        assert_eq!(hb.hosts[0].protocol.as_deref(), Some("dir_bare"));
        // "arg" is parsed as part of the host label sequence.
        // wait, parse_host_pattern consumes "dir_bare" then "arg".
        // labels=["dir_bare", "arg"].
        // then it sees protocol is None.
        // "dir_bare" becomes protocol. "arg" stays in labels.
        // Correct.
        assert_eq!(hb.hosts[0].as_str(), "arg");
    } else {
        panic!("dir_bare did not parse as HostBlock");
    }
}

#[test]
fn test_mixed_string_edge_case() {
    let input = r#"
    dir_mixed "arg1" arg2 "arg3"
    "#;
    let config = Config::from_str(input).expect("dir_mixed failed");
    if let Statement::Directive(d) = &config.statements[0] {
        assert_eq!(d.name, "dir_mixed");
        assert_eq!(d.args[0].as_str(), Some("arg1"));
        assert_eq!(d.args[1].as_str(), Some("arg2"));
        assert_eq!(d.args[2].as_str(), Some("arg3"));
    } else {
        panic!("dir_quoted did not parse as Directive");
    }
}