firewall_audit 0.1.0

Cross-platform firewall audit tool and library (YAML/JSON rules, CSV/HTML/JSON export)
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
use super::types::{CriteriaExpr, CriteriaOperator};
use crate::firewall_rule::FirewallRule;
use serde_yaml::Value;

pub fn validate_criteria_expr(expr: &CriteriaExpr, path: &str) -> Vec<String> {
    let mut errors = Vec::new();
    match expr {
        CriteriaExpr::Group { and } => {
            for (i, sub) in and.iter().enumerate() {
                errors.extend(validate_criteria_expr(sub, &format!("{path}->and[{i}]")));
            }
        }
        CriteriaExpr::OrGroup { or } => {
            for (i, sub) in or.iter().enumerate() {
                errors.extend(validate_criteria_expr(sub, &format!("{path}->or[{i}]")));
            }
        }
        CriteriaExpr::NotGroup { not } => {
            errors.extend(validate_criteria_expr(not, &format!("{path}->not")));
        }
        CriteriaExpr::Condition(cond) => {
            if !FirewallRule::valid_fields().contains(&cond.field.as_str()) {
                errors.push(format!("Unknown field '{}' at {path}", cond.field));
                return errors;
            }
            let mut cond = cond.clone();
            cond.parse_operator();
            let Some(op) = cond.operator.as_ref() else {
                return errors;
            };
            let val = &cond.value;
            let err = match op {
                CriteriaOperator::Equals | CriteriaOperator::Not | CriteriaOperator::Matches => {
                    None
                }
                CriteriaOperator::StartsWith
                | CriteriaOperator::EndsWith
                | CriteriaOperator::Regex
                | CriteriaOperator::Wildcard
                | CriteriaOperator::Contains
                | CriteriaOperator::ApplicationExists
                | CriteriaOperator::ServiceExists => {
                    if let Some(Value::String(_)) = val {
                        None
                    } else {
                        Some("must be a string")
                    }
                }
                CriteriaOperator::InRange => {
                    if let Some(Value::Sequence(seq)) = val {
                        if seq.len() == 2 && seq.iter().all(|v| matches!(v, Value::Number(_))) {
                            None
                        } else {
                            Some("must be a list of 2 numbers")
                        }
                    } else {
                        Some("must be a list of 2 numbers")
                    }
                }
                CriteriaOperator::Lt
                | CriteriaOperator::Lte
                | CriteriaOperator::Gt
                | CriteriaOperator::Gte => {
                    if let Some(Value::Number(_)) = val {
                        None
                    } else {
                        Some("must be a number")
                    }
                }
                CriteriaOperator::Cidr => {
                    if let Some(Value::String(_)) = val {
                        None
                    } else {
                        Some("must be a string (IP or CIDR)")
                    }
                }
                CriteriaOperator::IsNull => {
                    if val.is_none() {
                        None
                    } else {
                        Some("must not have a value")
                    }
                }
            };
            if let Some(msg) = err {
                errors.push(format!(
                    "Invalid value for operator '{op:?}' at {path}: {msg} (got {val:?})"
                ));
            }
        }
    }
    errors
}

#[cfg(test)]
mod tests {

    use crate::criteria::{
        types::{CriteriaCondition, CriteriaExpr},
        validation::validate_criteria_expr,
    };
    use serde_yaml::Value;

    #[test]
    fn test_validate_criteria_expr_unknown_field() {
        let cond = CriteriaCondition {
            field: "notafield".to_string(),
            operator_raw: "equals".to_string(),
            value: Some(Value::String("foo".to_string())),
            operator: None,
        };
        let expr = CriteriaExpr::Condition(cond);
        let errors = validate_criteria_expr(&expr, "root");
        assert!(errors.iter().any(|e| e.contains("Unknown field")));
    }

    #[test]
    fn test_validate_criteria_expr_wrong_type() {
        let cond = CriteriaCondition {
            field: "name".to_string(),
            operator_raw: "in_range".to_string(),
            value: Some(Value::String("notalist".to_string())),
            operator: None,
        };
        let expr = CriteriaExpr::Condition(cond);
        let errors = validate_criteria_expr(&expr, "root");
        assert!(errors
            .iter()
            .any(|e| e.contains("must be a list of 2 numbers")));
    }

    #[test]
    fn test_validate_criteria_expr_unknown_operator() {
        let cond = CriteriaCondition {
            field: "name".to_string(),
            operator_raw: "notanop".to_string(),
            value: Some(Value::String("foo".to_string())),
            operator: None,
        };
        let expr = CriteriaExpr::Condition(cond);
        let errors = validate_criteria_expr(&expr, "root");
        assert!(errors.is_empty());
    }

    #[test]
    fn test_validate_criteria_expr_valid_field_wrong_operator_type() {
        let cond = CriteriaCondition {
            field: "local_ports".to_string(),
            operator_raw: "starts_with".to_string(),
            value: Some(Value::Number(22.into())),
            operator: None,
        };
        let expr = CriteriaExpr::Condition(cond);
        let errors = super::validate_criteria_expr(&expr, "root");
        assert!(errors.iter().any(|e| e.contains("must be a string")));
    }

    #[test]
    fn test_starts_with_wrong_type_on_name() {
        let cond = crate::criteria::types::CriteriaCondition {
            field: "name".to_string(),
            operator_raw: "starts_with".to_string(),
            value: Some(serde_yaml::Value::Number(1.into())),
            operator: None,
        };
        let expr = crate::criteria::types::CriteriaExpr::Condition(cond);
        let errors = super::validate_criteria_expr(&expr, "root");
        assert!(
            errors.iter().any(|e| e.contains("must be a string")),
            "Should catch error for starts_with on name with number"
        );
    }

    #[test]
    fn test_ends_with_wrong_type_on_name() {
        let cond = crate::criteria::types::CriteriaCondition {
            field: "name".to_string(),
            operator_raw: "ends_with".to_string(),
            value: Some(serde_yaml::Value::Number(1.into())),
            operator: None,
        };
        let expr = crate::criteria::types::CriteriaExpr::Condition(cond);
        let errors = super::validate_criteria_expr(&expr, "root");
        assert!(
            errors.iter().any(|e| e.contains("must be a string")),
            "Should catch error for ends_with on name with number"
        );
    }

    #[test]
    fn test_regex_wrong_type_on_name() {
        let cond = crate::criteria::types::CriteriaCondition {
            field: "name".to_string(),
            operator_raw: "regex".to_string(),
            value: Some(serde_yaml::Value::Number(1.into())),
            operator: None,
        };
        let expr = crate::criteria::types::CriteriaExpr::Condition(cond);
        let errors = super::validate_criteria_expr(&expr, "root");
        assert!(
            errors.iter().any(|e| e.contains("must be a string")),
            "Should catch error for regex on name with number"
        );
    }

    #[test]
    fn test_wildcard_wrong_type_on_name() {
        let cond = crate::criteria::types::CriteriaCondition {
            field: "name".to_string(),
            operator_raw: "wildcard".to_string(),
            value: Some(serde_yaml::Value::Number(1.into())),
            operator: None,
        };
        let expr = crate::criteria::types::CriteriaExpr::Condition(cond);
        let errors = super::validate_criteria_expr(&expr, "root");
        assert!(
            errors.iter().any(|e| e.contains("must be a string")),
            "Should catch error for wildcard on name with number"
        );
    }

    #[test]
    fn test_contains_wrong_type_on_name() {
        let cond = crate::criteria::types::CriteriaCondition {
            field: "name".to_string(),
            operator_raw: "contains".to_string(),
            value: Some(serde_yaml::Value::Number(1.into())),
            operator: None,
        };
        let expr = crate::criteria::types::CriteriaExpr::Condition(cond);
        let errors = super::validate_criteria_expr(&expr, "root");
        assert!(
            errors.iter().any(|e| e.contains("must be a string")),
            "Should catch error for contains on name with number"
        );
    }

    #[test]
    fn test_application_exists_wrong_type_on_application_name() {
        let cond = crate::criteria::types::CriteriaCondition {
            field: "application_name".to_string(),
            operator_raw: "application_exists".to_string(),
            value: Some(serde_yaml::Value::Number(1.into())),
            operator: None,
        };
        let expr = crate::criteria::types::CriteriaExpr::Condition(cond);
        let errors = super::validate_criteria_expr(&expr, "root");
        assert!(
            errors.iter().any(|e| e.contains("must be a string")),
            "Should catch error for application_exists on application_name with number"
        );
    }

    #[test]
    fn test_service_exists_wrong_type_on_service_name() {
        let cond = crate::criteria::types::CriteriaCondition {
            field: "service_name".to_string(),
            operator_raw: "service_exists".to_string(),
            value: Some(serde_yaml::Value::Number(1.into())),
            operator: None,
        };
        let expr = crate::criteria::types::CriteriaExpr::Condition(cond);
        let errors = super::validate_criteria_expr(&expr, "root");
        assert!(
            errors.iter().any(|e| e.contains("must be a string")),
            "Should catch error for service_exists on service_name with number"
        );
    }

    #[test]
    fn test_in_range_wrong_type_on_local_ports() {
        let cond = crate::criteria::types::CriteriaCondition {
            field: "local_ports".to_string(),
            operator_raw: "in_range".to_string(),
            value: Some(serde_yaml::Value::String("notalist".into())),
            operator: None,
        };
        let expr = crate::criteria::types::CriteriaExpr::Condition(cond);
        let errors = super::validate_criteria_expr(&expr, "root");
        assert!(
            errors
                .iter()
                .any(|e| e.contains("must be a list of 2 numbers")),
            "Should catch error for in_range on local_ports with string"
        );
    }

    #[test]
    fn test_lt_wrong_type_on_local_ports() {
        let cond = crate::criteria::types::CriteriaCondition {
            field: "local_ports".to_string(),
            operator_raw: "lt".to_string(),
            value: Some(serde_yaml::Value::String("notanumber".into())),
            operator: None,
        };
        let expr = crate::criteria::types::CriteriaExpr::Condition(cond);
        let errors = super::validate_criteria_expr(&expr, "root");
        assert!(
            errors.iter().any(|e| e.contains("must be a number")),
            "Should catch error for lt on local_ports with string"
        );
    }

    #[test]
    fn test_lte_wrong_type_on_local_ports() {
        let cond = crate::criteria::types::CriteriaCondition {
            field: "local_ports".to_string(),
            operator_raw: "lte".to_string(),
            value: Some(serde_yaml::Value::String("notanumber".into())),
            operator: None,
        };
        let expr = crate::criteria::types::CriteriaExpr::Condition(cond);
        let errors = super::validate_criteria_expr(&expr, "root");
        assert!(
            errors.iter().any(|e| e.contains("must be a number")),
            "Should catch error for lte on local_ports with string"
        );
    }

    #[test]
    fn test_gt_wrong_type_on_local_ports() {
        let cond = crate::criteria::types::CriteriaCondition {
            field: "local_ports".to_string(),
            operator_raw: "gt".to_string(),
            value: Some(serde_yaml::Value::String("notanumber".into())),
            operator: None,
        };
        let expr = crate::criteria::types::CriteriaExpr::Condition(cond);
        let errors = super::validate_criteria_expr(&expr, "root");
        assert!(
            errors.iter().any(|e| e.contains("must be a number")),
            "Should catch error for gt on local_ports with string"
        );
    }

    #[test]
    fn test_gte_wrong_type_on_local_ports() {
        let cond = crate::criteria::types::CriteriaCondition {
            field: "local_ports".to_string(),
            operator_raw: "gte".to_string(),
            value: Some(serde_yaml::Value::String("notanumber".into())),
            operator: None,
        };
        let expr = crate::criteria::types::CriteriaExpr::Condition(cond);
        let errors = super::validate_criteria_expr(&expr, "root");
        assert!(
            errors.iter().any(|e| e.contains("must be a number")),
            "Should catch error for gte on local_ports with string"
        );
    }

    #[test]
    fn test_cidr_wrong_type_on_local_addresses() {
        let cond = crate::criteria::types::CriteriaCondition {
            field: "local_addresses".to_string(),
            operator_raw: "cidr".to_string(),
            value: Some(serde_yaml::Value::Number(1.into())),
            operator: None,
        };
        let expr = crate::criteria::types::CriteriaExpr::Condition(cond);
        let errors = super::validate_criteria_expr(&expr, "root");
        assert!(
            errors
                .iter()
                .any(|e| e.contains("must be a string (IP or CIDR)")),
            "Should catch error for cidr on local_addresses with number"
        );
    }

    #[test]
    fn test_is_null_wrong_type_on_name() {
        let cond = crate::criteria::types::CriteriaCondition {
            field: "name".to_string(),
            operator_raw: "is_null".to_string(),
            value: Some(serde_yaml::Value::String("foo".into())),
            operator: None,
        };
        let expr = crate::criteria::types::CriteriaExpr::Condition(cond);
        let errors = super::validate_criteria_expr(&expr, "root");
        assert!(
            errors.iter().any(|e| e.contains("must not have a value")),
            "Should catch error for is_null on name with string"
        );
    }
}

#[cfg(test)]
mod extra_coverage {
    use super::*;
    use crate::criteria::types::{CriteriaCondition, CriteriaExpr};
    use serde_yaml::Value;

    #[test]
    fn test_group_and_or_not_branches() {
        // Group with two valid conditions
        let cond1 = CriteriaCondition {
            field: "name".to_string(),
            operator_raw: "equals".to_string(),
            value: Some(Value::String("foo".to_string())),
            operator: None,
        };
        let cond2 = CriteriaCondition {
            field: "name".to_string(),
            operator_raw: "equals".to_string(),
            value: Some(Value::String("bar".to_string())),
            operator: None,
        };
        let expr = CriteriaExpr::Group {
            and: vec![
                CriteriaExpr::Condition(cond1.clone()),
                CriteriaExpr::Condition(cond2),
            ],
        };
        let errors = validate_criteria_expr(&expr, "root");
        assert!(errors.is_empty());

        // OrGroup with one valid, one invalid
        let bad_cond = CriteriaCondition {
            field: "notafield".to_string(),
            operator_raw: "equals".to_string(),
            value: Some(Value::String("foo".to_string())),
            operator: None,
        };
        let expr = CriteriaExpr::OrGroup {
            or: vec![
                CriteriaExpr::Condition(cond1),
                CriteriaExpr::Condition(bad_cond.clone()),
            ],
        };
        let errors = validate_criteria_expr(&expr, "root");
        assert!(errors.iter().any(|e| e.contains("Unknown field")));

        // NotGroup with invalid
        let expr = CriteriaExpr::NotGroup {
            not: Box::new(CriteriaExpr::Condition(bad_cond)),
        };
        let errors = validate_criteria_expr(&expr, "root");
        assert!(errors.iter().any(|e| e.contains("Unknown field")));
    }

    #[test]
    fn test_all_criteria_operators_types() {
        let field = "name".to_string();
        let path = "root";
        let string_val = Some(Value::String("foo".to_string()));
        let number_val = Some(Value::Number(1.into()));
        let bool_val = Some(Value::Bool(true));
        let list_val = Some(Value::Sequence(vec![
            Value::Number(1.into()),
            Value::Number(2.into()),
        ]));
        let bad_list_val = Some(Value::Sequence(vec![Value::Number(1.into())]));
        let null_val = None;

        // Equals, Not, Matches accept any type
        for op in ["equals", "not", "matches"] {
            for val in [
                string_val.clone(),
                number_val.clone(),
                bool_val.clone(),
                list_val.clone(),
            ] {
                let cond = CriteriaCondition {
                    field: field.clone(),
                    operator_raw: op.to_string(),
                    value: val,
                    operator: None,
                };
                let expr = CriteriaExpr::Condition(cond);
                let errors = validate_criteria_expr(&expr, path);
                assert!(errors.is_empty(), "{op} should accept any type");
            }
        }

        // StartsWith, EndsWith, Regex, Wildcard, Contains, ApplicationExists, ServiceExists require string
        for op in [
            "starts_with",
            "ends_with",
            "regex",
            "wildcard",
            "contains",
            "application_exists",
            "service_exists",
        ] {
            let cond = CriteriaCondition {
                field: field.clone(),
                operator_raw: op.to_string(),
                value: string_val.clone(),
                operator: None,
            };
            let expr = CriteriaExpr::Condition(cond);
            let errors = validate_criteria_expr(&expr, path);
            assert!(errors.is_empty(), "{op} should accept string");
            let cond = CriteriaCondition {
                field: field.clone(),
                operator_raw: op.to_string(),
                value: number_val.clone(),
                operator: None,
            };
            let expr = CriteriaExpr::Condition(cond);
            let errors = validate_criteria_expr(&expr, path);
            assert!(
                errors.iter().any(|e| e.contains("must be a string")),
                "{op} should reject non-string"
            );
        }

        // InRange requires list of 2 numbers
        let cond = CriteriaCondition {
            field: field.clone(),
            operator_raw: "in_range".to_string(),
            value: list_val,
            operator: None,
        };
        let expr = CriteriaExpr::Condition(cond);
        let errors = validate_criteria_expr(&expr, path);
        assert!(errors.is_empty());
        let cond = CriteriaCondition {
            field: field.clone(),
            operator_raw: "in_range".to_string(),
            value: bad_list_val,
            operator: None,
        };
        let expr = CriteriaExpr::Condition(cond);
        let errors = validate_criteria_expr(&expr, path);
        assert!(errors
            .iter()
            .any(|e| e.contains("must be a list of 2 numbers")));

        // Lt, Lte, Gt, Gte require number
        for op in ["lt", "lte", "gt", "gte"] {
            let cond = CriteriaCondition {
                field: field.clone(),
                operator_raw: op.to_string(),
                value: number_val.clone(),
                operator: None,
            };
            let expr = CriteriaExpr::Condition(cond);
            let errors = validate_criteria_expr(&expr, path);
            assert!(errors.is_empty(), "{op} should accept number");
            let cond = CriteriaCondition {
                field: field.clone(),
                operator_raw: op.to_string(),
                value: string_val.clone(),
                operator: None,
            };
            let expr = CriteriaExpr::Condition(cond);
            let errors = validate_criteria_expr(&expr, path);
            assert!(
                errors.iter().any(|e| e.contains("must be a number")),
                "{op} should reject non-number"
            );
        }

        // Cidr requires string
        let cond = CriteriaCondition {
            field: field.clone(),
            operator_raw: "cidr".to_string(),
            value: string_val.clone(),
            operator: None,
        };
        let expr = CriteriaExpr::Condition(cond);
        let errors = validate_criteria_expr(&expr, path);
        assert!(errors.is_empty());
        let cond = CriteriaCondition {
            field: field.clone(),
            operator_raw: "cidr".to_string(),
            value: number_val,
            operator: None,
        };
        let expr = CriteriaExpr::Condition(cond);
        let errors = validate_criteria_expr(&expr, path);
        assert!(errors
            .iter()
            .any(|e| e.contains("must be a string (IP or CIDR)")));

        // IsNull requires no value
        let cond = CriteriaCondition {
            field: field.clone(),
            operator_raw: "is_null".to_string(),
            value: null_val,
            operator: None,
        };
        let expr = CriteriaExpr::Condition(cond);
        let errors = validate_criteria_expr(&expr, path);
        assert!(errors.is_empty());
        let cond = CriteriaCondition {
            field,
            operator_raw: "is_null".to_string(),
            value: string_val,
            operator: None,
        };
        let expr = CriteriaExpr::Condition(cond);
        let errors = validate_criteria_expr(&expr, path);
        assert!(errors.iter().any(|e| e.contains("must not have a value")));
    }
}