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
// Copyright 2021 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

use crate::{
    error::{StringPatternError, ValidationError},
    types::{
        self, ComparisonOperator, FilterExpression, Identifier, InclusionOperator, OneOrMany,
        Operator, Value,
    },
};
use fidl_fuchsia_diagnostics as fdiagnostics;

// NOTE: if we could use the negative_impls unstable feature, we could have a single ValidateExt
// trait instead of one for each type of selector we need.
pub trait ValidateExt {
    fn validate(&self) -> Result<(), ValidationError>;
}

pub trait ValidateComponentSelectorExt {
    fn validate(&self) -> Result<(), ValidationError>;
}

pub trait ValidateTreeSelectorExt {
    fn validate(&self) -> Result<(), ValidationError>;
}

pub trait ValidateMetadataSelectorExt {
    fn validate(&self) -> Result<(), ValidationError>;
}

pub trait Selector {
    type Component: ComponentSelector;
    type Tree: TreeSelector;
    type Metadata: MetadataSelector;

    fn component(&self) -> Option<&Self::Component>;
    fn tree(&self) -> Option<&Self::Tree>;
    fn metadata(&self) -> Option<&Self::Metadata>;
}

pub trait ComponentSelector {
    type Segment: StringSelector;
    fn segments(&self) -> Option<&[Self::Segment]>;
}

pub trait TreeSelector {
    type Segment: StringSelector;

    fn node_path(&self) -> Option<&[Self::Segment]>;
    fn property(&self) -> Option<&Self::Segment>;
}

pub trait MetadataSelector {
    fn filters(&self) -> &[types::FilterExpression<'_>];
}

pub trait StringSelector {
    fn exact_match(&self) -> Option<&str>;
    fn pattern(&self) -> Option<&str>;
}

impl<T: Selector> ValidateExt for T {
    fn validate(&self) -> Result<(), ValidationError> {
        match (self.component(), self.tree()) {
            (Some(component), Some(tree)) => {
                component.validate()?;
                tree.validate()?;
            }
            (None, _) => return Err(ValidationError::MissingComponentSelector),
            (_, None) => return Err(ValidationError::MissingTreeSelector),
        }
        if let Some(metadata) = self.metadata() {
            metadata.validate()?;
        }
        Ok(())
    }
}

impl<T: ComponentSelector> ValidateComponentSelectorExt for T {
    fn validate(&self) -> Result<(), ValidationError> {
        let segments = self.segments().unwrap_or(&[]);
        if segments.is_empty() {
            return Err(ValidationError::EmptyComponentSelector);
        }
        let last_idx = segments.len() - 1;
        for segment in &segments[..last_idx] {
            segment.validate(StringSelectorValidationOpts::default())?;
        }
        segments[last_idx].validate(StringSelectorValidationOpts { allow_recursive_glob: true })?;
        Ok(())
    }
}

impl<T: TreeSelector> ValidateTreeSelectorExt for T {
    fn validate(&self) -> Result<(), ValidationError> {
        let node_path = self.node_path().unwrap_or(&[]);
        if node_path.is_empty() {
            return Err(ValidationError::EmptySubtreeSelector);
        }
        for segment in node_path {
            segment.validate(StringSelectorValidationOpts::default())?;
        }
        if let Some(segment) = self.property() {
            segment.validate(StringSelectorValidationOpts::default())?;
        }
        Ok(())
    }
}

impl<T: MetadataSelector> ValidateMetadataSelectorExt for T {
    fn validate(&self) -> Result<(), ValidationError> {
        for filter in self.filters() {
            filter.validate_identifier_and_operator()?;
            filter.validate_identifier_and_value()?;
            filter.validate_operator_and_value()?;
        }
        Ok(())
    }
}

// This macro is purely a utility fo validating that all the values in the given `$one_or_many` are
// of a given type.
macro_rules! match_one_or_many_value {
    ($one_or_many:ident, $variant:pat) => {
        match $one_or_many {
            OneOrMany::One($variant) => true,
            OneOrMany::Many(values) => values.iter().all(|value| matches!(value, $variant)),
            _ => false,
        }
    };
}

impl FilterExpression<'_> {
    /// Validates that all the values are of a type that can be used in an operation with this
    /// identifier.
    fn validate_identifier_and_value(&self) -> Result<(), ValidationError> {
        let is_valid = match (&self.identifier, &self.value) {
            (Identifier::Filename | Identifier::LifecycleEventType | Identifier::Tags, value) => {
                match_one_or_many_value!(value, Value::StringLiteral(_))
            }
            (
                Identifier::Pid | Identifier::Tid | Identifier::LineNumber | Identifier::Timestamp,
                value,
            ) => {
                match_one_or_many_value!(value, Value::Number(_))
            }
            // TODO(https://fxbug.dev/42168030): it should also be possible to compare severities with a fixed
            // set of numbers.
            (Identifier::Severity, value) => {
                match_one_or_many_value!(value, Value::Severity(_))
            }
        };
        if is_valid {
            Ok(())
        } else {
            Err(ValidationError::InvalidValueType(self.identifier.clone(), self.value.ty()))
        }
    }

    /// Validates that this identifier can be used in an operation defined by the given `operator`.
    fn validate_identifier_and_operator(&self) -> Result<(), ValidationError> {
        match (&self.identifier, &self.operator) {
            (
                Identifier::Filename
                | Identifier::LifecycleEventType
                | Identifier::Pid
                | Identifier::Tid
                | Identifier::LineNumber
                | Identifier::Severity,
                Operator::Comparison(ComparisonOperator::Equal)
                | Operator::Comparison(ComparisonOperator::NotEq)
                | Operator::Inclusion(InclusionOperator::In),
            ) => Ok(()),
            (Identifier::Severity | Identifier::Timestamp, Operator::Comparison(_)) => Ok(()),
            (
                Identifier::Tags,
                Operator::Inclusion(InclusionOperator::HasAny | InclusionOperator::HasAll),
            ) => Ok(()),
            _ => Err(ValidationError::InvalidOperator(
                self.identifier.clone(),
                self.operator.clone(),
            )),
        }
    }

    fn validate_operator_and_value(&self) -> Result<(), ValidationError> {
        // Validate the operation can be used with the type of value.
        match (&self.operator, &self.value) {
            (Operator::Inclusion(_), OneOrMany::Many(_)) => Ok(()),
            (Operator::Comparison(_), OneOrMany::One(_)) => Ok(()),
            (Operator::Inclusion(_), OneOrMany::One(_))
            | (Operator::Comparison(_), OneOrMany::Many(_)) => {
                Err(ValidationError::InvalidOperatorRhs(self.operator.clone(), self.value.ty()))
            }
        }
    }
}

#[derive(Default)]
struct StringSelectorValidationOpts {
    allow_recursive_glob: bool,
}

trait ValidateStringSelectorExt {
    fn validate(&self, opts: StringSelectorValidationOpts) -> Result<(), ValidationError>;
}

// TODO(https://fxbug.dev/42132713): we might want to just implement this differently for FIDL and the
// internal types. The parser should cover all of the string pattern requirements. Verify.
impl<T: StringSelector> ValidateStringSelectorExt for T {
    fn validate(&self, opts: StringSelectorValidationOpts) -> Result<(), ValidationError> {
        match (self.exact_match(), self.pattern()) {
            (None, None) | (Some(_), Some(_)) => {
                return Err(ValidationError::InvalidStringSelector)
            }
            (Some(_), None) => {
                // A exact match is always valid.
                return Ok(());
            }
            (None, Some(pattern)) => {
                if opts.allow_recursive_glob && pattern == "**" {
                    return Ok(());
                } else {
                    return validate_pattern(pattern);
                }
            }
        }
    }
}

/// Checks if the `target` string contains the `forbidden` string without the
/// character `/` preceding the `forbidden` string.
fn contains_unescaped(target: &str, forbidden: &str) -> bool {
    if target.len() < forbidden.len() {
        return false;
    }
    if target.starts_with(forbidden) {
        return true;
    }
    let flen = forbidden.len();
    for i in 1..(target.len() - flen + 1) {
        if &target[i..i + flen] == forbidden && !target[i - 1..i + flen].starts_with("\\") {
            return true;
        }
    }
    false
}

fn validate_pattern(pattern: &str) -> Result<(), ValidationError> {
    if pattern.is_empty() {
        return Err(ValidationError::EmptyStringPattern);
    }

    let mut errors = vec![];
    if contains_unescaped(pattern, "**") {
        errors.push(StringPatternError::UnescapedGlob);
    }
    if contains_unescaped(pattern, ":") {
        errors.push(StringPatternError::UnescapedColon);
    }
    if contains_unescaped(pattern, "/") {
        errors.push(StringPatternError::UnescapedForwardSlash);
    }
    if !errors.is_empty() {
        return Err(ValidationError::InvalidStringPattern(pattern.to_string(), errors));
    }
    Ok(())
}

impl Selector for fdiagnostics::Selector {
    type Component = fdiagnostics::ComponentSelector;
    type Tree = fdiagnostics::TreeSelector;
    // TODO(https://fxbug.dev/42132713): placeholder implementation until we have metadata in the FIDL API.
    type Metadata = ();

    fn component(&self) -> Option<&Self::Component> {
        self.component_selector.as_ref()
    }

    fn tree(&self) -> Option<&Self::Tree> {
        self.tree_selector.as_ref()
    }

    fn metadata(&self) -> Option<&Self::Metadata> {
        // TODO(https://fxbug.dev/42132713): placeholder implementation until we have metadata in the FIDL API.
        None
    }
}

impl MetadataSelector for () {
    fn filters(&self) -> &[types::FilterExpression<'_>] {
        unreachable!("placholder impl. Metadata FIDL not implemented yet")
    }
}

impl ComponentSelector for fdiagnostics::ComponentSelector {
    type Segment = fdiagnostics::StringSelector;

    fn segments(&self) -> Option<&[Self::Segment]> {
        self.moniker_segments.as_ref().map(|s| s.as_slice())
    }
}

impl TreeSelector for fdiagnostics::TreeSelector {
    type Segment = fdiagnostics::StringSelector;

    fn node_path(&self) -> Option<&[Self::Segment]> {
        match self {
            Self::SubtreeSelector(t) => Some(&t.node_path[..]),
            Self::PropertySelector(p) => Some(&p.node_path[..]),
            fdiagnostics::TreeSelectorUnknown!() => None,
        }
    }

    fn property(&self) -> Option<&Self::Segment> {
        match self {
            Self::SubtreeSelector(_) => None,
            Self::PropertySelector(p) => Some(&p.target_properties),
            fdiagnostics::TreeSelectorUnknown!() => None,
        }
    }
}

impl StringSelector for fdiagnostics::StringSelector {
    fn exact_match(&self) -> Option<&str> {
        match self {
            Self::ExactMatch(s) => Some(s),
            _ => None,
        }
    }

    fn pattern(&self) -> Option<&str> {
        match self {
            Self::StringPattern(s) => Some(s),
            _ => None,
        }
    }
}

impl<'a> Selector for types::Selector<'a> {
    type Component = types::ComponentSelector<'a>;
    type Tree = types::TreeSelector<'a>;
    type Metadata = types::MetadataSelector<'a>;

    fn component(&self) -> Option<&Self::Component> {
        Some(&self.component)
    }

    fn tree(&self) -> Option<&Self::Tree> {
        Some(&self.tree)
    }

    fn metadata(&self) -> Option<&Self::Metadata> {
        self.metadata.as_ref()
    }
}

impl<'a> ComponentSelector for types::ComponentSelector<'a> {
    type Segment = types::Segment<'a>;

    fn segments(&self) -> Option<&[Self::Segment]> {
        Some(&self.segments[..])
    }
}

impl<'a> TreeSelector for types::TreeSelector<'a> {
    type Segment = types::Segment<'a>;

    fn node_path(&self) -> Option<&[Self::Segment]> {
        Some(&self.node)
    }

    fn property(&self) -> Option<&Self::Segment> {
        self.property.as_ref()
    }
}

impl<'a> MetadataSelector for types::MetadataSelector<'a> {
    fn filters(&self) -> &[types::FilterExpression<'a>] {
        self.filters()
    }
}

impl<'a> StringSelector for types::Segment<'a> {
    fn exact_match(&self) -> Option<&str> {
        match self {
            Self::ExactMatch(s) => Some(s),
            _ => None,
        }
    }

    fn pattern(&self) -> Option<&str> {
        match self {
            Self::Pattern(s) => Some(s),
            _ => None,
        }
    }
}

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

    lazy_static! {
        static ref SHARED_PASSING_TEST_CASES: Vec<(Vec<&'static str>, &'static str)> = {
            vec![
                (vec![r#"abc"#, r#"def"#, r#"g"#], r#"bob"#),
                (vec![r#"\**"#], r#"\**"#),
                (vec![r#"\/"#], r#"\/"#),
                (vec![r#"\:"#], r#"\:"#),
                (vec![r#"asda\\\:"#], r#"a"#),
                (vec![r#"asda*"#], r#"a"#),
            ]
        };
        static ref SHARED_FAILING_TEST_CASES: Vec<(Vec<&'static str>, &'static str)> = {
            vec![
                // Slashes aren't allowed in path nodes.
                (vec![r#"/"#], r#"a"#),
                // Colons aren't allowed in path nodes.
                (vec![r#":"#], r#"a"#),
                // Checking that path nodes ending with offlimits
                // chars are still identified.
                (vec![r#"asdasd:"#], r#"a"#),
                (vec![r#"a**"#], r#"a"#),
                // Checking that path nodes starting with offlimits
                // chars are still identified.
                (vec![r#":asdasd"#], r#"a"#),
                (vec![r#"**a"#], r#"a"#),
                // Neither moniker segments nor node paths
                // are allowed to be empty.
                (vec![], r#"bob"#),
            ]
        };
    }

    #[fuchsia::test]
    fn tree_selector_validator_test() {
        let unique_failing_test_cases = vec![
            // All failing validators due to property selectors are
            // unique since the component validator doesn't look at them.
            (vec![r#"a"#], r#"**"#),
            (vec![r#"a"#], r#"/"#),
        ];

        fn create_tree_selector(
            node_path: &Vec<&str>,
            property: &str,
        ) -> fdiagnostics::TreeSelector {
            let node_path = node_path
                .iter()
                .map(|path_node_str| {
                    fdiagnostics::StringSelector::StringPattern(path_node_str.to_string())
                })
                .collect::<Vec<fdiagnostics::StringSelector>>();
            let target_properties =
                fdiagnostics::StringSelector::StringPattern(property.to_string());
            fdiagnostics::TreeSelector::PropertySelector(fdiagnostics::PropertySelector {
                node_path,
                target_properties,
            })
        }

        for (node_path, property) in SHARED_PASSING_TEST_CASES.iter() {
            let tree_selector = create_tree_selector(node_path, property);
            assert!(tree_selector.validate().is_ok());
        }

        for (node_path, property) in SHARED_FAILING_TEST_CASES.iter() {
            let tree_selector = create_tree_selector(node_path, property);
            assert!(
                ValidateTreeSelectorExt::validate(&tree_selector).is_err(),
                "Failed to validate tree selector: {:?}",
                tree_selector
            );
        }

        for (node_path, property) in unique_failing_test_cases.iter() {
            let tree_selector = create_tree_selector(node_path, property);
            assert!(
                ValidateTreeSelectorExt::validate(&tree_selector).is_err(),
                "Failed to validate tree selector: {:?}",
                tree_selector
            );
        }
    }

    #[fuchsia::test]
    fn component_selector_validator_test() {
        fn create_component_selector(
            component_moniker: &Vec<&str>,
        ) -> fdiagnostics::ComponentSelector {
            let mut component_selector = fdiagnostics::ComponentSelector::default();
            component_selector.moniker_segments = Some(
                component_moniker
                    .into_iter()
                    .map(|path_node_str| {
                        fdiagnostics::StringSelector::StringPattern(path_node_str.to_string())
                    })
                    .collect::<Vec<fdiagnostics::StringSelector>>(),
            );
            component_selector
        }

        for (component_moniker, _) in SHARED_PASSING_TEST_CASES.iter() {
            let component_selector = create_component_selector(component_moniker);

            assert!(component_selector.validate().is_ok());
        }

        for (component_moniker, _) in SHARED_FAILING_TEST_CASES.iter() {
            let component_selector = create_component_selector(component_moniker);

            assert!(
                component_selector.validate().is_err(),
                "Failed to validate component selector: {:?}",
                component_selector
            );
        }
    }
}