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
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
// Copyright Amazon Web Services, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0

/* require return types marked as must_use to be used (such as Result types) */
#![deny(unused_must_use)]

pub mod commands;
mod rules;
pub mod utils;

pub use crate::commands::helper::{validate_and_return_json as run_checks, ValidateInput};
use crate::commands::parse_tree::ParseTree;
use crate::commands::rulegen::Rulegen;
use crate::commands::test::Test;
use crate::commands::validate::{OutputFormatType, ShowSummaryType, Validate};
use crate::commands::Executable;
pub use crate::rules::errors::Error;

pub trait CommandBuilder<T: Executable> {
    fn try_build(self) -> crate::rules::Result<T>;
}

#[derive(Default, Debug)]
/// .
/// A builder to help construct the `ParseTree` command
pub struct ParseTreeBuilder {
    rules: Option<String>,
    output: Option<String>,
    print_json: bool,
    print_yaml: bool,
}

impl CommandBuilder<ParseTree> for ParseTreeBuilder {
    /// .
    /// builds a parse tree command
    fn try_build(self) -> crate::rules::Result<ParseTree> {
        let ParseTreeBuilder {
            rules,
            output,
            print_json,
            print_yaml,
        } = self;

        Ok(ParseTree {
            rules,
            output,
            print_json,
            print_yaml,
        })
    }
}

impl ParseTreeBuilder {
    /// path to the rules file to be evaluated
    pub fn rules(mut self, rules: Option<String>) -> Self {
        self.rules = rules;

        self
    }

    /// path to the output file where the parse tree will be printed to
    pub fn output(mut self, output: Option<String>) -> Self {
        self.output = output;

        self
    }

    /// print parse tree in JSON format
    pub fn print_json(mut self, arg: bool) -> Self {
        self.print_json = arg;

        self
    }

    /// print parse tree in YAML format
    pub fn print_yaml(mut self, arg: bool) -> Self {
        self.print_yaml = arg;

        self
    }
}

#[derive(Debug)]
/// .
/// A builder to help construct the `Validate` command
pub struct ValidateBuilder {
    rules: Vec<String>,
    data: Vec<String>,
    input_params: Vec<String>,
    template_type: Option<String>,
    output_format: OutputFormatType,
    show_summary: Vec<ShowSummaryType>,
    alphabetical: bool,
    last_modified: bool,
    verbose: bool,
    print_json: bool,
    payload: bool,
    structured: bool,
}

impl Default for ValidateBuilder {
    fn default() -> Self {
        Self {
            rules: Default::default(),
            data: Default::default(),
            input_params: Default::default(),
            template_type: Default::default(),
            output_format: Default::default(),
            show_summary: vec![Default::default()],
            alphabetical: Default::default(),
            last_modified: false,
            verbose: false,
            print_json: false,
            payload: false,
            structured: false,
        }
    }
}

impl CommandBuilder<Validate> for ValidateBuilder {
    /// .
    /// attempts to construct a `Validate` command
    ///
    /// This function will return an error if
    /// - conflicting attributes have been set
    /// - both rules is empty, and payload is false
    #[allow(deprecated)]
    fn try_build(self) -> crate::rules::Result<Validate> {
        if self.structured {
            if self.output_format == OutputFormatType::SingleLineSummary {
                return Err(Error::IllegalArguments(String::from(
                        "single-line-summary is not able to be used when the `structured` flag is present",
                    )));
            }

            if self.print_json {
                return Err(Error::IllegalArguments(String::from("unable to construct validate command when both structured and print_json are set to true")));
            }

            if self.verbose {
                return Err(Error::IllegalArguments(String::from("unable to construct validate command when both structured and verbose are set to true")));
            }

            if self.show_summary.iter().any(|st| {
                matches!(
                    st,
                    ShowSummaryType::Pass
                        | ShowSummaryType::Fail
                        | ShowSummaryType::Skip
                        | ShowSummaryType::All
                )
            }) {
                return Err(Error::IllegalArguments(String::from(
                    "Cannot provide a summary-type other than `none` when the `structured` flag is present",
                )));
            }
        } else if matches!(
            self.output_format,
            OutputFormatType::Junit | OutputFormatType::Sarif
        ) {
            return Err(Error::IllegalArguments(format!(
                "the structured flag must be set when output is set to {:?}",
                self.output_format
            )));
        }

        if self.payload && (!self.rules.is_empty() || !self.data.is_empty()) {
            return Err(Error::IllegalArguments(String::from("cannot construct a validate command payload conflicts with both data and rules arguments")));
        }

        if !self.payload && self.rules.is_empty() {
            return Err(Error::IllegalArguments(String::from("cannot construct a validate command: either payload must be set to true, or rules must not be empty")));
        }

        if self.last_modified && self.alphabetical {
            return Err(Error::IllegalArguments(String::from(
                "cannot have both last modified, and alphabetical arguments set to true",
            )));
        }

        let ValidateBuilder {
            rules,
            data,
            input_params,
            template_type,
            output_format,
            show_summary,
            alphabetical,
            last_modified,
            verbose,
            print_json,
            payload,
            structured,
        } = self;

        Ok(Validate {
            rules,
            data,
            input_params,
            template_type,
            output_format,
            show_summary,
            alphabetical,
            last_modified,
            verbose,
            print_json,
            payload,
            structured,
        })
    }
}

impl ValidateBuilder {
    /// a list of paths that point to rule files, or a directory containing rule files on a local machine. Only files that end with .guard or .ruleset will be evaluated
    /// conflicts with payload
    pub fn rules(mut self, rules: Vec<String>) -> Self {
        self.rules = rules;

        self
    }

    /// a list of paths that point to data files, or a directory containing data files  for the rules to be evaluated against. Only JSON, or YAML files will be used
    /// conflicts with payload
    pub fn data(mut self, data: Vec<String>) -> Self {
        self.data = data;

        self
    }

    /// Controls if the summary table needs to be displayed. --show-summary fail (default) or --show-summary pass,fail (only show rules that did pass/fail) or --show-summary none (to turn it off) or --show-summary all (to show all the rules that pass, fail or skip)
    /// default is failed
    /// must be set to none if used together with the structured flag
    pub fn show_summary(mut self, args: Vec<ShowSummaryType>) -> Self {
        self.show_summary = args;

        self
    }

    /// a list of paths that point to data files, or a directory containing data files to be merged with the data argument and then the  rules will be evaluated against them. Only JSON, or YAML files will be used
    pub fn input_params(mut self, input_params: Vec<String>) -> Self {
        self.input_params = input_params;

        self
    }

    /// Specify the format in which the output should be displayed
    /// default is single-line-summary
    /// if junit is used, `structured` attributed must be set to true
    pub fn output_format(mut self, output: OutputFormatType) -> Self {
        self.output_format = output;

        self
    }

    /// Tells the command that rules, and data will be passed via a reader, as a json payload.
    /// Conflicts with both rules, and data
    /// default is false
    pub fn payload(mut self, arg: bool) -> Self {
        self.payload = arg;

        self
    }

    /// Validate files in a directory ordered alphabetically, conflicts with `last_modified` field
    pub fn alphabetical(mut self, arg: bool) -> Self {
        self.alphabetical = arg;

        self
    }

    /// Validate files in a directory ordered by last modified times, conflicts with `alphabetical` field
    pub fn last_modified(mut self, arg: bool) -> Self {
        self.last_modified = arg;

        self
    }

    /// Output verbose logging, conflicts with `structured` field
    /// default is false
    pub fn verbose(mut self, arg: bool) -> Self {
        self.verbose = arg;

        self
    }

    /// Print the parse tree in a json format. This can be used to get more details on how the clauses were evaluated
    /// conflicts with the `structured` attribute
    /// default is false
    pub fn print_json(mut self, arg: bool) -> Self {
        self.print_json = arg;

        self
    }

    /// Prints the output which must be specified to JSON/YAML/JUnit in a structured format
    /// Conflicts with the following attributes `verbose`, `print-json`, `output-format` when set
    /// to "single-line-summary", show-summary when set to anything other than "none"
    /// default is false
    pub fn structured(mut self, arg: bool) -> Self {
        self.structured = arg;

        self
    }
}

#[derive(Default, Debug)]
/// .
/// A builder to help construct the `Test` command
pub struct TestBuilder {
    rules: Option<String>,
    test_data: Option<String>,
    directory: Option<String>,
    alphabetical: bool,
    last_modified: bool,
    verbose: bool,
    output_format: OutputFormatType,
}

impl CommandBuilder<Test> for TestBuilder {
    /// .
    /// attempts to construct a `Test` command
    ///
    /// This function will return an error if
    /// - conflicting attributes have been set
    /// - rules, test-data, and directory is set to None
    fn try_build(self) -> crate::rules::Result<Test> {
        if self.last_modified && self.alphabetical {
            return Err(Error::IllegalArguments(String::from("unable to construct a test command: cannot have both last modified, and alphabetical arguments set to true")));
        }

        if self.directory.is_some() && self.rules.is_some() {
            return Err(Error::IllegalArguments(String::from("unable to construct a test command: cannot pass both a directory argument, and a rules argument")));
        }

        if !matches!(self.output_format, OutputFormatType::SingleLineSummary) && self.verbose {
            return Err(Error::IllegalArguments(String::from("Cannot provide an output_type of JSON, YAML, or JUnit while the verbose flag is set")));
        }

        let TestBuilder {
            rules,
            test_data,
            directory,
            alphabetical,
            last_modified,
            verbose,
            output_format,
        } = self;

        Ok(Test {
            rules,
            test_data,
            directory,
            alphabetical,
            last_modified,
            verbose,
            output_format,
        })
    }
}

impl TestBuilder {
    // the path to the rule file
    // conflicts with directory
    pub fn rules(mut self, rules: Option<String>) -> Self {
        self.rules = rules;

        self
    }

    // the path to the test-data file
    // conflicts with directory
    pub fn test_data(mut self, test_data: Option<String>) -> Self {
        self.test_data = test_data;

        self
    }

    // A path to a directory containing rule file(s), and a subdirectory called tests containing
    // data input file(s)
    // conflicts with rules, and test_data
    pub fn directory(mut self, directory: Option<String>) -> Self {
        self.directory = directory;

        self
    }

    /// Test files in a directory ordered alphabetically, conflicts with `last_modified` field
    /// default is false
    pub fn alphabetical(mut self, arg: bool) -> Self {
        self.alphabetical = arg;

        self
    }

    /// Test files in a directory ordered by last modified times, conflicts with `alphabetical` field
    /// default is false
    pub fn last_modified(mut self, arg: bool) -> Self {
        self.last_modified = arg;

        self
    }

    /// Output verbose logging, conflicts with output_format if not single-line-summary
    /// default is false
    pub fn verbose(mut self, arg: bool) -> Self {
        self.verbose = arg;

        self
    }

    /// Specify the format in which the output should be displayed
    /// default is single-line-summary
    /// will conflict with verbose if set to something other than single-line-summary and verbose
    /// is set to true
    pub fn output_format(mut self, output: OutputFormatType) -> Self {
        self.output_format = output;

        self
    }
}

#[derive(Debug, Default)]
/// .
/// A builder to help construct the `Rulegen` command
pub struct RulegenBuilder {
    output: Option<String>,
    template: String,
}

impl CommandBuilder<Rulegen> for RulegenBuilder {
    /// construct a rulegen command
    fn try_build(self) -> crate::rules::Result<Rulegen> {
        let RulegenBuilder { output, template } = self;
        Ok(Rulegen { output, template })
    }
}

impl RulegenBuilder {
    /// path for the output file where the generated rules will be written to
    /// if no path is specified output will be printed to the stdout
    pub fn output(mut self, output: Option<String>) -> Self {
        self.output = output;

        self
    }

    /// path to the template which the rules will be autogenerated from
    pub fn template(mut self, template: String) -> Self {
        self.template = template;

        self
    }
}

#[cfg(test)]
mod cfn_guard_lib_tests {
    use crate::{
        commands::validate::ShowSummaryType, CommandBuilder, TestBuilder, ValidateBuilder,
    };

    #[test]
    fn validate_with_errors() {
        // fails cause structured, but show_summary fail
        let cmd = ValidateBuilder::default()
            .data(vec![String::from("resources/validate/data-dir")])
            .rules(vec![String::from("resources/validate/rules-dir")])
            .structured(true)
            .output_format(crate::commands::validate::OutputFormatType::JSON)
            .try_build();
        assert!(cmd.is_err());

        // fails cause structured, but single-line-summary
        let cmd = ValidateBuilder::default()
            .data(vec![String::from("resources/validate/data-dir")])
            .rules(vec![String::from("resources/validate/rules-dir")])
            .structured(true)
            .show_summary(vec![ShowSummaryType::None])
            .try_build();
        assert!(cmd.is_err());

        // fails cause structured, but verbose
        let cmd = ValidateBuilder::default()
            .data(vec![String::from("resources/validate/data-dir")])
            .rules(vec![String::from("resources/validate/rules-dir")])
            .structured(true)
            .output_format(crate::commands::validate::OutputFormatType::JSON)
            .verbose(true)
            .show_summary(vec![ShowSummaryType::None])
            .try_build();
        assert!(cmd.is_err());

        // fails cause structured, but print_json
        let cmd = ValidateBuilder::default()
            .data(vec![String::from("resources/validate/data-dir")])
            .rules(vec![String::from("resources/validate/rules-dir")])
            .structured(true)
            .output_format(crate::commands::validate::OutputFormatType::JSON)
            .print_json(true)
            .show_summary(vec![ShowSummaryType::None])
            .try_build();
        assert!(cmd.is_err());

        // fails cause junit or sarif, but not structured
        vec![
            crate::commands::validate::OutputFormatType::Junit,
            crate::commands::validate::OutputFormatType::Sarif,
        ]
        .into_iter()
        .for_each(|output_format| {
            let cmd = ValidateBuilder::default()
                .data(vec![String::from("resources/validate/data-dir")])
                .rules(vec![String::from("resources/validate/rules-dir")])
                .output_format(output_format)
                .show_summary(vec![ShowSummaryType::None])
                .try_build();

            assert!(cmd.is_err());
        });

        // fails cause no payload, or rules
        let cmd = ValidateBuilder::default()
            .output_format(crate::commands::validate::OutputFormatType::Junit)
            .structured(true)
            .show_summary(vec![ShowSummaryType::None])
            .try_build();

        assert!(cmd.is_err());

        // fails cause payload, and rules conflict
        let cmd = ValidateBuilder::default()
            .rules(vec![String::from("resources/validate/rules-dir")])
            .payload(true)
            .output_format(crate::commands::validate::OutputFormatType::Junit)
            .structured(true)
            .show_summary(vec![ShowSummaryType::None])
            .try_build();

        assert!(cmd.is_err());

        // fails cause payload, and data conflict
        let cmd = ValidateBuilder::default()
            .data(vec![String::from("resources/validate/data-dir")])
            .payload(true)
            .output_format(crate::commands::validate::OutputFormatType::Junit)
            .structured(true)
            .show_summary(vec![ShowSummaryType::None])
            .try_build();

        assert!(cmd.is_err());

        // fails cause last_modified, and alphabetical conflict
        let cmd = ValidateBuilder::default()
            .payload(true)
            .alphabetical(true)
            .last_modified(true)
            .output_format(crate::commands::validate::OutputFormatType::Junit)
            .structured(true)
            .show_summary(vec![ShowSummaryType::None])
            .try_build();

        assert!(cmd.is_err());
    }

    #[test]
    fn validate_happy_path() {
        let data = vec![String::from("resources/validate/data-dir")];
        let rules = vec![String::from("resources/validate/rules-dir")];
        let cmd = ValidateBuilder::default()
            .verbose(true)
            .output_format(crate::commands::validate::OutputFormatType::JSON)
            .data(data.clone())
            .rules(rules.clone())
            .try_build();

        assert!(cmd.is_ok());

        let cmd = ValidateBuilder::default()
            .verbose(true)
            .show_summary(vec![
                ShowSummaryType::Pass,
                ShowSummaryType::Fail,
                ShowSummaryType::Skip,
            ])
            .output_format(crate::commands::validate::OutputFormatType::JSON)
            .data(data.clone())
            .rules(rules.clone())
            .try_build();

        assert!(cmd.is_ok());

        let cmd = ValidateBuilder::default()
            .verbose(true)
            .output_format(crate::commands::validate::OutputFormatType::JSON)
            .data(data.clone())
            .rules(rules.clone())
            .try_build();

        assert!(cmd.is_ok());

        let cmd = ValidateBuilder::default()
            .data(data.clone())
            .rules(rules.clone())
            .structured(true)
            .output_format(crate::commands::validate::OutputFormatType::JSON)
            .show_summary(vec![ShowSummaryType::None])
            .try_build();

        assert!(cmd.is_ok());

        let cmd = ValidateBuilder::default()
            .data(data.clone())
            .rules(rules.clone())
            .output_format(crate::commands::validate::OutputFormatType::Junit)
            .structured(true)
            .show_summary(vec![ShowSummaryType::None])
            .try_build();

        assert!(cmd.is_ok());
    }

    #[test]
    fn build_test_command_happy_path() {
        let data = String::from("resources/validate/data-dir");
        let rules = String::from("resources/validate/rules-dir");
        let cmd = TestBuilder::default()
            .test_data(Option::from(data.clone()))
            .rules(Option::from(rules.clone()))
            .try_build();

        assert!(cmd.is_ok());

        let cmd = TestBuilder::default()
            .directory(Option::from(data.clone()))
            .try_build();
        assert!(cmd.is_ok());

        let cmd = TestBuilder::default()
            .directory(Option::from(data.clone()))
            .alphabetical(true)
            .try_build();

        assert!(cmd.is_ok())
    }

    #[test]
    fn build_test_command_with_errors() {
        let data = String::from("resources/validate/data-dir");
        let rules = String::from("resources/validate/rules-dir");

        // fails cause rules and dir
        let cmd = TestBuilder::default()
            .rules(Option::from(rules.clone()))
            .directory(Option::from(data.clone()))
            .try_build();

        assert!(cmd.is_err());

        // fails cause alphabetical and last_modified
        let cmd = TestBuilder::default()
            .directory(Option::from(data.clone()))
            .last_modified(true)
            .alphabetical(true)
            .try_build();

        assert!(cmd.is_err());
    }
}