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
#[macro_use]
extern crate pest_derive;
#[macro_use]
extern crate pest;
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate serde;
extern crate regex;

mod conditionals;
use regex::Regex;
use serde::de::{self, Deserialize, Deserializer, MapAccess, Visitor};
use std::{cmp, collections::HashMap, error::Error, fmt};

// #[derive(Deserialize)]
pub struct Rule {
    pub name: String,
    pub variables: Vec<Variable>,
    // #[serde(deserialize_with = "de_conditional")]
    pub conditional: Conditional,
}

impl<'de> Deserialize<'de> for Rule {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        enum Field {
            Name,
            Variables,
            Conditional,
        }

        impl<'de> Deserialize<'de> for Field {
            fn deserialize<D>(deserializer: D) -> Result<Field, D::Error>
            where
                D: Deserializer<'de>,
            {
                struct FieldVisitor;

                impl<'de> Visitor<'de> for FieldVisitor {
                    type Value = Field;

                    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                        formatter.write_str("`name` or `variables` or `conditional`")
                    }

                    fn visit_str<E>(self, value: &str) -> Result<Field, E>
                    where
                        E: de::Error,
                    {
                        match value {
                            "name" => Ok(Field::Name),
                            "variables" => Ok(Field::Variables),
                            "conditional" => Ok(Field::Conditional),
                            _ => Err(de::Error::unknown_field(value, FIELDS)),
                        }
                    }
                }

                deserializer.deserialize_identifier(FieldVisitor)
            }
        }
        struct RuleVisitor;
        impl<'de> Visitor<'de> for RuleVisitor {
            type Value = Rule;
            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                formatter.write_str("struct Rule")
            }
            fn visit_map<V>(self, mut map: V) -> Result<Rule, V::Error>
            where
                V: MapAccess<'de>,
            {
                let mut name: Option<String> = None;
                let mut variables: Option<Vec<Variable>> = None;
                let mut raw_conditional: Option<String> = None;
                while let Some(key) = map.next_key()? {
                    match key {
                        Field::Name => {
                            if name.is_some() {
                                return Err(de::Error::duplicate_field("name"));
                            }
                            name = Some(map.next_value()?);
                        }
                        Field::Variables => {
                            if variables.is_some() {
                                return Err(de::Error::duplicate_field("variables"));
                            }
                            variables = Some(map.next_value()?);
                        }
                        Field::Conditional => {
                            if raw_conditional.is_some() {
                                return Err(de::Error::duplicate_field("conditional"));
                            }
                            raw_conditional = Some(map.next_value()?);
                        }
                    }
                }
                let conditional = match (&variables, &raw_conditional) {
                    (Some(variables), Some(conditional)) => {
                        //
                        match Conditional::new(
                            &conditional,
                            variables.iter().map(|v| v.get_name().to_string()).collect(),
                        ) {
                            Ok(c) => Ok(c),
                            Err(e) => Err(serde::de::Error::custom(e)),
                        }
                    }
                    _ => return Err(de::Error::missing_field("conditional")),
                }?;
                let name = name.ok_or_else(|| de::Error::missing_field("name"))?;
                let variables = variables.ok_or_else(|| de::Error::missing_field("variables"))?;
                Ok(Rule {
                    name,
                    variables,
                    conditional,
                })
            }
        }

        const FIELDS: &[&str] = &["name", "variables", "conditional"];
        deserializer.deserialize_struct("Rule", FIELDS, RuleVisitor)
    }
}

#[derive(Deserialize)]
// #[serde(untagged)]
#[serde(tag = "type")]
pub enum Variable {
    Regex {
        name: String,
        field: String,
        #[serde(deserialize_with = "de_regex")]
        regex: Regex,
    },
    Exact {
        name: String,
        field: String,
        #[serde(deserialize_with = "de_bytes")]
        exact: Vec<u8>,
    },
    Contains {
        name: String,
        field: String,
        #[serde(deserialize_with = "de_bytes")]
        contains: Vec<u8>,
    },
    Compare {
        name: String,
        field: String,
        #[serde(deserialize_with = "de_ordering")]
        ordering: cmp::Ordering,
        value: f64,
    },
}

fn de_regex<'de, D>(deserializer: D) -> Result<Regex, D::Error>
where
    D: serde::Deserializer<'de>,
{
    let s: String = serde::Deserialize::deserialize(deserializer)?;
    match Regex::new(&s) {
        Ok(r) => Ok(r),
        Err(e) => Err(serde::de::Error::custom(e)),
    }
}

/// Accepts:
/// * ">" or "greater" or "gt" for a Greater than comparison.
/// * "<" or "less" or "lt" for a Less than comparison.
/// * "=" or "==" or "equal" or  "eq" for a Equal to comparison.
fn de_ordering<'de, D>(deserializer: D) -> Result<cmp::Ordering, D::Error>
where
    D: serde::Deserializer<'de>,
{
    let s: String = serde::Deserialize::deserialize(deserializer)?;
    Ok(match s.trim_end().trim_start().to_lowercase().as_str() {
        ">" | "greater" | "gt" => (cmp::Ordering::Greater),
        "<" | "less" | "lt" => cmp::Ordering::Less,
        "=" | "==" | "equal" | "eq" => cmp::Ordering::Greater,
        _ => {
            return Err(serde::de::Error::custom(format!(
                "\"{}\" is not a suitable ordering.",
                s
            )))
        }
    })
}

fn de_bytes<'de, D>(deserializer: D) -> Result<Vec<u8>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    let s: String = serde::Deserialize::deserialize(deserializer)?;
    Ok(s.as_bytes().to_owned())
}

impl Variable {
    pub fn get_field(&self) -> &str {
        match self {
            Self::Regex {
                ref field,
                regex: _,
                name: _,
            } => field,
            Self::Contains {
                ref field,
                contains: _,
                name: _,
            } => field,
            Self::Compare {
                ref field,
                value: _,
                ordering: _,
                name: _,
            } => field,
            Self::Exact {
                ref field,
                exact: _,
                name: _,
            } => field,
        }
    }
    pub fn get_name(&self) -> &str {
        match self {
            Self::Regex {
                field: _,
                regex: _,
                ref name,
            } => name,
            Self::Contains {
                field: _,
                contains: _,
                ref name,
            } => name,
            Self::Compare {
                field: _,
                value: _,
                ordering: _,
                ref name,
            } => name,
            Self::Exact {
                field: _,
                exact: _,
                ref name,
            } => name,
        }
    }

    pub fn match_against(&self, json: &str) -> (&str, bool) {
        match &self {
            Variable::Regex {
                ref name,
                field,
                regex,
            } => (name, regex.is_match(gjson::get(json, field).str())),
            Variable::Exact {
                ref name,
                field,
                exact,
            } => (name, gjson::get(json, field).str().as_bytes() == exact),
            Variable::Compare {
                ref name,
                field,
                ordering,
                value,
            } => match gjson::get(json, field).kind() {
                gjson::Kind::Number => (
                    name,
                    match ordering {
                        // cmp::Ordering::Equal => gjson::get(json, field).f64() == *value,
                        cmp::Ordering::Equal => {
                            (gjson::get(json, field).f64() - *value).abs() < f64::EPSILON
                        }
                        cmp::Ordering::Greater => gjson::get(json, field).f64() > *value,
                        cmp::Ordering::Less => gjson::get(json, field).f64() < *value,
                    },
                ),
                _ => (name, false),
            },
            Variable::Contains {
                ref name,
                field,
                ref contains,
            } => match contains
                .len()
                .cmp(&gjson::get(json, field).str().as_bytes().len())
            {
                cmp::Ordering::Greater => (name, false),
                cmp::Ordering::Equal => {
                    (name, gjson::get(json, field).str().as_bytes() == contains)
                }
                cmp::Ordering::Less => {
                    let increment = gjson::get(json, field).str().as_bytes().len()
                        - gjson::get(json, field).str().as_bytes().len() % contains.len();
                    let data: Vec<u8> = gjson::get(json, field).str().as_bytes().to_owned();
                    for i in 0..(data.len() % contains.len() + 1) {
                        // println!("data: {:?} slice: {:?}", data, slice);
                        // println!("range: {:?}", (i)..(i + increment));
                        // println!("conditional: {:?}", (slice == contains));
                        // is_match = is_match | (slice == contains);
                        if &data[i..i + increment] == contains {
                            return (name, true);
                        }
                    }
                    (name, false)
                }
            },
        }
    }
}

pub struct Conditional {
    pub raw: String,
    pub variables: Vec<String>,
}

impl Conditional {
    /// Creates an, unvalidated, conditional.
    pub fn new(
        conditional: &str,
        variables: Vec<String>,
    ) -> Result<Self, conditionals::ParseError> {
        let inner = conditionals::parse(conditional)?;
        if !conditionals::validate(inner, variables.iter().map(|v| v.as_str()).collect()) {
            return Err(conditionals::ParseError {
                reason: "Could not validate conditional statement".into(),
            });
        }
        Ok(Self {
            raw: conditional.into(),
            variables,
            // eval: Box::new(eval),
        })
    }
    pub fn eval(&self, variables: &HashMap<&str, bool>) -> bool {
        conditionals::eval(conditionals::parse(&self.raw).unwrap(), variables)
    }
    pub fn validate(&self, variables: Vec<&str>) -> bool {
        conditionals::validate(conditionals::parse(&self.raw).unwrap(), variables)
    }
}

//
impl Rule {
    pub fn validate(self) -> Result<Self, Box<dyn Error>> {
        let keys = self.variables.iter().map(|v| v.get_name()).collect();
        match self.conditional.validate(keys) {
            true => Ok(self),
            false => Err("Could not validate conditional statement".into()),
        }
    }

    pub fn match_json(&self, json: &str) -> bool {
        let mut map = HashMap::new();
        // Collect and match each Variable
        for v in &self.variables {
            let (k, v) = v.match_against(json);
            map.insert(k, v);
        }
        // Run results map against Conditional
        self.conditional.eval(&map)
    }

    pub fn get_matches_json(&self, json: &str) -> HashMap<String, String> {
        self.variables
            .iter()
            .map(|v| {
                (
                    v.get_field().into(),
                    gjson::get(json, v.get_field()).str().into(),
                )
            })
            .collect()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn rule() {
        let mut rule = Rule {
            name: "test_rule".to_string(),
            variables: vec![
                Variable::Contains {
                    name: "A".to_string(),
                    field: "field".to_string(),
                    contains: "abc123".as_bytes().to_vec(),
                },
                Variable::Regex {
                    name: "B".to_string(),
                    field: "obj*.field".to_string(),
                    regex: Regex::new("[a-z]{3}[0-9]{3}").unwrap(),
                },
            ],
            conditional: Conditional::new("A and B", vec!["A".to_string(), "B".to_string()])
                .unwrap(),
        };
        let json = r#"{ "field": "xabc1234", "object": { "field": "xyz321" } }"#;
        rule = rule.validate().unwrap();
        assert!(rule.match_json(json));
    }
}