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
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
#![cfg(feature = "std")]

use super::{ast::*, lexer::Lexer, parser::Parser, token};
use serde_json;
use serde_json::Value;
use std::{error::Error, f64, fmt, result};

/// Alias for `Result` with an error of type `cddl::ValidationError`
pub type Result = result::Result<(), ValidationError>;

/// Represents the various JSON validation errors that can occur
#[derive(Debug)]
pub enum ValidationError {
  CDDL(String),
  JSON(JSONError),
  Compilation(String),
  Occurrence(String),
  MultiError(Vec<ValidationError>),
}

#[derive(Debug)]
pub struct JSONError {
  expected: String,
  actual: Value,
}

impl fmt::Display for ValidationError {
  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
    match self {
      ValidationError::CDDL(ce) => write!(f, "malformed CDDL: {}", ce),
      ValidationError::JSON(je) => write!(
        f,
        "failed to validate JSON against CDDL\n\nexpected: {}\nactual: {}",
        je.expected,
        serde_json::to_string_pretty(&je.actual).map_err(|_| fmt::Error)?,
      ),
      ValidationError::Compilation(ce) => write!(f, "error on compilation: {}", ce),
      ValidationError::Occurrence(oe) => write!(f, "occurrence error: {}", oe),
      ValidationError::MultiError(me) => {
        let mut errors = String::new();

        for e in me.iter() {
          match e {
            // Temporary work around for nested MultiError's
            ValidationError::MultiError(_) => errors.push_str(&format!("{}", e)),
            _ => errors.push_str(&format!("{}\n", e)),
          }
        }

        write!(f, "{}", errors)
      }
    }
  }
}

impl Error for ValidationError {
  fn description(&self) -> &str {
    "ValidationError"
  }

  fn cause(&self) -> Option<&Error> {
    None
  }
}

pub fn validate_json_from_str(cddl: &str, json: &str) -> Result {
  let mut l = Lexer::new(cddl);

  let mut p = Parser::new(&mut l).map_err(|e| ValidationError::Compilation(e.to_string()))?;

  validate_json(
    &p.parse_cddl()
      .map_err(|e| ValidationError::Compilation(e.to_string()))?,
    &serde_json::from_str(json).map_err(|e| ValidationError::Compilation(e.to_string()))?,
  )
}

fn validate_json(cddl: &CDDL, json: &Value) -> Result {
  for rule in cddl.rules.iter() {
    // First type rule is root
    if let Rule::Type(tr) = rule {
      return cddl.validate_type_rule(tr, None, json);
    }
  }

  Ok(())
}

impl<'a> CDDL<'a> {
  // TODO: support socket plug evaluation
  fn validate_rule_for_ident(
    &self,
    ident: &Identifier,
    occur: Option<&Occur>,
    json: &Value,
  ) -> Result {
    for rule in self.rules.iter() {
      match rule {
        Rule::Type(tr) if tr.name == *ident => return self.validate_type_rule(tr, occur, json),
        Rule::Group(gr) if gr.name == *ident => return self.validate_group_rule(gr, occur, json),
        _ => continue,
      }
    }

    Err(ValidationError::CDDL(format!(
      "No rule with name {} defined\n",
      (ident.0).0
    )))
  }

  // TODO: support generic parameter and type choice alternative evaluation
  fn validate_type_rule(&self, tr: &TypeRule, occur: Option<&Occur>, json: &Value) -> Result {
    self.validate_type(&tr.value, occur, json)
  }

  // TODO: support generic parameter and group choice alternative evaluation
  fn validate_group_rule(&self, gr: &GroupRule, occur: Option<&Occur>, json: &Value) -> Result {
    self.validate_group_entry(&gr.entry, occur, json)
  }

  fn validate_type(&self, t: &Type, occur: Option<&Occur>, json: &Value) -> Result {
    let mut validation_errors: Vec<ValidationError> = Vec::new();

    // Find the first type choice that validates to true
    if t
      .0
      .iter()
      .any(|t1| match self.validate_type1(t1, occur, json) {
        Ok(()) => true,
        Err(e) => {
          validation_errors.push(e);
          false
        }
      })
    {
      return Ok(());
    }

    Err(ValidationError::MultiError(validation_errors))
  }

  fn validate_type1(&self, t1: &Type1, occur: Option<&Occur>, json: &Value) -> Result {
    self.validate_type2(&t1.type2, occur, json)
  }

  fn validate_type2(&self, t2: &Type2, occur: Option<&Occur>, json: &Value) -> Result {
    match t2 {
      Type2::Value(v) => match json {
        Value::Number(_) => validate_numeric_value(v, json),
        Value::String(s) => validate_string_value(v, s),
        _ => Err(ValidationError::JSON(JSONError {
          expected: t2.to_string(),
          actual: json.clone(),
        })),
      },
      // TODO: evaluate genericarg
      Type2::Typename((tn, _)) => match json {
        Value::Null => expect_null((tn.0).0),
        Value::Bool(_) => expect_bool((tn.0).0, json),
        Value::String(_) => {
          if (tn.0).0 == "tstr" || (tn.0).0 == "text" {
            Ok(())
          } else {
            self.validate_rule_for_ident(tn, occur, json)
          }
        }
        Value::Number(_) => validate_numeric_data_type((tn.0).0, json),
        Value::Object(_) => self.validate_rule_for_ident(tn, occur, json),
        Value::Array(_) => self.validate_rule_for_ident(tn, occur, json),
      },
      Type2::Array(g) => match json {
        Value::Array(_) => self.validate_group(g, occur, json),
        _ => Err(ValidationError::JSON(JSONError {
          expected: t2.to_string(),
          actual: json.clone(),
        })),
      },
      Type2::Map(g) => match json {
        Value::Object(_) => self.validate_group(g, occur, json),
        _ => Err(ValidationError::JSON(JSONError {
          expected: t2.to_string(),
          actual: json.clone(),
        })),
      },
      _ => Err(ValidationError::CDDL(format!(
        "CDDL type {} can't be used to validate JSON {}",
        t2, json
      ))),
    }
  }

  fn validate_group(&self, g: &Group, occur: Option<&Occur>, json: &Value) -> Result {
    let mut validation_errors: Vec<ValidationError> = Vec::new();

    // Find the first group choice that validates to true
    if g
      .0
      .iter()
      .any(|gc| match self.validate_group_choice(gc, occur, json) {
        Ok(()) => true,
        Err(e) => {
          validation_errors.push(e);
          false
        }
      })
    {
      return Ok(());
    }

    Err(ValidationError::MultiError(validation_errors))
  }

  fn validate_group_choice(&self, gc: &GroupChoice, occur: Option<&Occur>, json: &Value) -> Result {
    'geiter: for ge in gc.0.iter() {
      match json {
        Value::Array(values) => {
          if let GroupEntry::TypeGroupname(tge) = ge {
            if let Some(o) = &tge.occur {
              validate_array_occurrence(o, &tge.name.to_string(), values)?;
            }
          }

          if let GroupEntry::InlineGroup((geo, g)) = ge {
            if let Some(o) = geo {
              validate_array_occurrence(o, &g.to_string(), values)?;
            }
          }

          let mut errors: Vec<ValidationError> = Vec::new();

          for v in values.iter() {
            match self.validate_group_entry(ge, occur, v) {
              Ok(()) => continue 'geiter,
              Err(e) => errors.push(e),
            }
          }

          if !errors.is_empty() {
            return Err(ValidationError::MultiError(errors));
          }
        }
        Value::Object(_) => match self.validate_group_entry(ge, occur, json) {
          Ok(()) => continue,
          Err(e) => return Err(e),
        },
        _ => {
          return Err(ValidationError::JSON(JSONError {
            expected: gc.to_string(),
            actual: json.clone(),
          }))
        }
      }
    }

    Ok(())
  }

  fn validate_group_entry(&self, ge: &GroupEntry, occur: Option<&Occur>, json: &Value) -> Result {
    match ge {
      GroupEntry::ValueMemberKey(vmke) => {
        if let Some(mk) = &vmke.member_key {
          match mk {
            MemberKey::Type1(t1) => match &t1.0.type2 {
              Type2::Value(token::Value::TEXT(t)) => match json {
                // CDDL { "my-key" => tstr, } validates JSON { "my-key": "myvalue" }
                Value::Object(om) => {
                  if !is_type_json_prelude(&vmke.entry_type.to_string()) {
                    if let Some(v) = om.get(*t) {
                      return self.validate_type(&vmke.entry_type, occur, v);
                    }

                    return self.validate_type(&vmke.entry_type, occur, json);
                  }

                  if let Some(v) = om.get(*t) {
                    self.validate_type(&vmke.entry_type, occur, v)
                  } else {
                    Err(ValidationError::JSON(JSONError {
                      expected: ge.to_string(),
                      actual: json.clone(),
                    }))
                  }
                }
                // Otherwise, validate JSON against the type of the entry.
                // Matched when in an array and the key for the group entry is
                // ignored.
                // CDDL [ city: tstr, ] validates JSON [ "city" ]
                _ => self.validate_type(&vmke.entry_type, occur, json),
              },
              // CDDL { * tstr => any } validates { "otherkey1": "anyvalue", "otherkey2": true }
              Type2::Typename((ident, _)) if (ident.0).0 == "tstr" || (ident.0).0 == "text" => {
                Ok(())
              }
              _ => Err(ValidationError::CDDL(
                "CDDL member key must be quoted string or bareword for validating JSON objects"
                  .to_string(),
              )),
            },
            MemberKey::Bareword(ident) => match json {
              Value::Object(om) => {
                if !is_type_json_prelude(&vmke.entry_type.to_string()) {
                  if let Some(v) = om.get((ident.0).0) {
                    return self.validate_type(&vmke.entry_type, vmke.occur.as_ref(), v);
                  }

                  return self.validate_type(&vmke.entry_type, vmke.occur.as_ref(), json);
                }

                if let Some(v) = om.get((ident.0).0) {
                  return self.validate_type(&vmke.entry_type, vmke.occur.as_ref(), v);
                }

                if let Some(o) = occur {
                  match o {
                    // If optional occurence, return Ok
                    Occur::Optional | Occur::ZeroOrMore => return Ok(()),
                    _ => {
                      return Err(ValidationError::JSON(JSONError {
                        expected: ge.to_string(),
                        actual: json.clone(),
                      }))
                    }
                  }
                }

                self.validate_type(&vmke.entry_type, vmke.occur.as_ref(), json)
              }
              _ => self.validate_type(&vmke.entry_type, vmke.occur.as_ref(), json),
            },
            _ => Err(ValidationError::CDDL(
              "CDDL member key must be quoted string or bareword for validating JSON objects"
                .to_string(),
            )),
          }
        } else {
          // TODO: Inline type
          unimplemented!()
        }
      }
      GroupEntry::TypeGroupname(tge) => {
        self.validate_rule_for_ident(&tge.name, tge.occur.as_ref(), json)
      }
      GroupEntry::InlineGroup((igo, g)) => {
        if igo.is_some() {
          self.validate_group(g, igo.as_ref(), json)
        } else {
          self.validate_group(g, occur, json)
        }
      }
    }
  }
}

fn validate_array_occurrence(occur: &Occur, group: &str, values: &[Value]) -> Result {
  match occur {
    Occur::ZeroOrMore | Occur::Optional => Ok(()),
    Occur::OneOrMore => {
      if values.is_empty() {
        Err(ValidationError::Occurrence(format!(
          "Expecting one or more values of group {}",
          group
        )))
      } else {
        Ok(())
      }
    }
    Occur::Exact((l, u)) => {
      if let Some(li) = l {
        if let Some(ui) = u {
          if values.len() < *li || values.len() > *ui {
            if li == ui {
              return Err(ValidationError::Occurrence(format!(
                "Expecting exactly {} values of group {}. Got {} values",
                li,
                group,
                values.len()
              )));
            }

            return Err(ValidationError::Occurrence(format!(
              "Expecting between {} and {} values of group {}. Got {} values",
              li,
              ui,
              group,
              values.len()
            )));
          }
        }

        if values.len() < *li {
          return Err(ValidationError::Occurrence(format!(
            "Expecting at least {} values of group {}. Got {} values",
            li,
            group,
            values.len()
          )));
        }
      }

      if let Some(ui) = u {
        if values.len() > *ui {
          return Err(ValidationError::Occurrence(format!(
            "Expecting no more than {} values of group {}. Got {} values",
            ui,
            group,
            values.len()
          )));
        }
      }

      Ok(())
    }
  }
}

fn expect_null(ident: &str) -> Result {
  match ident {
    "null" | "nil" => Ok(()),
    _ => Err(ValidationError::JSON(JSONError {
      expected: ident.to_string(),
      actual: Value::Null,
    })),
  }
}

fn expect_bool(ident: &str, json: &Value) -> Result {
  match json {
    Value::Bool(b) => {
      if ident == "bool" {
        return Ok(());
      }

      if let Ok(bfs) = ident.parse::<bool>() {
        if bfs == *b {
          return Ok(());
        }

        return Err(ValidationError::JSON(JSONError {
          expected: ident.to_string(),
          actual: json.clone(),
        }));
      }

      Err(ValidationError::JSON(JSONError {
        expected: ident.to_string(),
        actual: json.clone(),
      }))
    }
    _ => Err(ValidationError::JSON(JSONError {
      expected: ident.to_string(),
      actual: json.clone(),
    })),
  }
}

fn validate_numeric_value(v: &token::Value, json: &Value) -> Result {
  match json {
    Value::Number(n) => match *v {
      token::Value::INT(i) => match n.as_i64() {
        Some(n64) if n64 == i as i64 => Ok(()),
        _ => Err(ValidationError::JSON(JSONError {
          expected: v.to_string(),
          actual: json.clone(),
        })),
      },
      token::Value::FLOAT(f) => match n.as_f64() {
        Some(n64) if (n64 - f as f64).abs() < f64::EPSILON => Ok(()),
        _ => Err(ValidationError::JSON(JSONError {
          expected: v.to_string(),
          actual: json.clone(),
        })),
      },
      _ => Ok(()),
    },
    _ => Err(ValidationError::JSON(JSONError {
      expected: v.to_string(),
      actual: json.clone(),
    })),
  }
}

fn validate_numeric_data_type(ident: &str, json: &Value) -> Result {
  match json {
    Value::Number(n) => match ident {
      "uint" => n
        .as_u64()
        .ok_or_else(|| {
          ValidationError::JSON(JSONError {
            expected: ident.to_string(),
            actual: json.clone(),
          })
        })
        .map(|_| ()),
      "nint" => match n.as_i64() {
        Some(n64) if n64 < 0 => Ok(()),
        _ => Err(ValidationError::JSON(JSONError {
          expected: ident.to_string(),
          actual: json.clone(),
        })),
      },
      "int" => n
        .as_i64()
        .ok_or_else(|| {
          ValidationError::JSON(JSONError {
            expected: ident.to_string(),
            actual: json.clone(),
          })
        })
        .map(|_| ()),
      "number" => Ok(()),
      "float16" => match n.as_f64() {
        Some(_) => Ok(()),
        _ => Err(ValidationError::JSON(JSONError {
          expected: ident.to_string(),
          actual: json.clone(),
        })),
      },
      // TODO: Finish rest of numerical data types
      "float32" => match n.as_f64() {
        Some(_) => Ok(()),
        _ => Err(ValidationError::JSON(JSONError {
          expected: ident.to_string(),
          actual: json.clone(),
        })),
      },
      // TODO: Finish rest of numerical data types
      _ => Err(ValidationError::JSON(JSONError {
        expected: ident.to_string(),
        actual: json.clone(),
      })),
    },
    _ => Err(ValidationError::JSON(JSONError {
      expected: ident.to_string(),
      actual: json.clone(),
    })),
  }
}

fn validate_string_value(v: &token::Value, s: &str) -> Result {
  match *v {
    token::Value::TEXT(t) if t == s => Ok(()),
    _ => Err(ValidationError::JSON(JSONError {
      expected: v.to_string(),
      actual: Value::String(s.to_string()),
    })),
  }
}

fn is_type_json_prelude(t: &str) -> bool {
  match t {
    "any" | "uint" | "nint" | "tstr" | "text" | "number" | "float16" | "float32" | "float64"
    | "float16-32" | "float32-64" | "float" | "false" | "true" | "bool" | "nil" | "null" => true,
    _ => false,
  }
}

#[cfg(test)]
mod tests {
  use super::super::{lexer::Lexer, parser::Parser};
  use super::*;
  use serde_json;

  #[test]
  fn validate_json_null() -> Result {
    let json_input = r#"null"#;

    let cddl_input = r#"mynullrule = null"#;

    let mut l = Lexer::new(cddl_input);
    let mut p = Parser::new(&mut l).map_err(|e| ValidationError::Compilation(e.to_string()))?;

    let cddl = p
      .parse_cddl()
      .map_err(|e| ValidationError::Compilation(e.to_string()))?;

    validate_json(
      &cddl,
      &serde_json::from_str(json_input).map_err(|e| ValidationError::Compilation(e.to_string()))?,
    )?;

    Ok(())
  }

  #[test]
  fn validate_json_bool() -> Result {
    let json_input = r#"true"#;

    let cddl_input = r#"myboolrule = true"#;

    let mut l = Lexer::new(cddl_input);
    let mut p = Parser::new(&mut l).map_err(|e| ValidationError::Compilation(e.to_string()))?;

    let cddl = p
      .parse_cddl()
      .map_err(|e| ValidationError::Compilation(e.to_string()))?;

    validate_json(
      &cddl,
      &serde_json::from_str(json_input).map_err(|e| ValidationError::Compilation(e.to_string()))?,
    )?;

    Ok(())
  }

  #[test]
  fn validate_json_number() -> Result {
    let json_inputs = [r#"3"#, r#"1.5"#, r#"10"#];

    let cddl_input = r#"mynumericrule = 3 / 1.5 / 10"#;

    let mut l = Lexer::new(cddl_input);
    let mut p = Parser::new(&mut l).map_err(|e| ValidationError::Compilation(e.to_string()))?;

    let cddl = p
      .parse_cddl()
      .map_err(|e| ValidationError::Compilation(e.to_string()))?;

    for ji in json_inputs.iter() {
      validate_json(
        &cddl,
        &serde_json::from_str(ji).map_err(|e| ValidationError::Compilation(e.to_string()))?,
      )?;
    }

    Ok(())
  }

  #[test]
  fn validate_json_string() -> Result {
    let json_input = r#""mystring""#;

    let cddl_input = r#"mystringrule = "mystring""#;

    let mut l = Lexer::new(cddl_input);
    let mut p = Parser::new(&mut l).map_err(|e| ValidationError::Compilation(e.to_string()))?;

    let cddl = p
      .parse_cddl()
      .map_err(|e| ValidationError::Compilation(e.to_string()))?;

    validate_json(
      &cddl,
      &serde_json::from_str(json_input).map_err(|e| ValidationError::Compilation(e.to_string()))?,
    )?;

    Ok(())
  }

  #[test]
  fn validate_json_object() -> Result {
    let json_input = r#"{
      "mykey": "myvalue",
      "myarray": [
        {
          "myotherkey": "myothervalue"
        }
      ]
    }"#;

    let cddl_input = r#"myobject = {
      mykey: tstr,
      myarray: [* arraytype],
    }
    
    arraytype = {
      myotherkey: tstr,
    }"#;

    let mut l = Lexer::new(cddl_input);
    let mut p = Parser::new(&mut l).map_err(|e| ValidationError::Compilation(e.to_string()))?;

    let cddl = p
      .parse_cddl()
      .map_err(|e| ValidationError::Compilation(e.to_string()))?;

    validate_json(
      &cddl,
      &serde_json::from_str(json_input).map_err(|e| ValidationError::Compilation(e.to_string()))?,
    )?;

    Ok(())
  }

  #[test]
  fn validate_json_array() -> Result {
    let json_input = r#"[
      "item1",
      {
        "longitude": 1234,
        "latitude": 3947
      }
    ]"#;

    let cddl_input = r#"Geography = [
      city           : tstr,
      gpsCoordinates : GpsCoordinates,
    ]

    GpsCoordinates = {
      longitude      : uint,            ; degrees, scaled by 10^7
      latitude       : uint,            ; degrees, scaled by 10^7
    }"#;

    let mut l = Lexer::new(cddl_input);
    let mut p = Parser::new(&mut l).map_err(|e| ValidationError::Compilation(e.to_string()))?;

    let cddl = p
      .parse_cddl()
      .map_err(|e| ValidationError::Compilation(e.to_string()))?;

    validate_json(
      &cddl,
      &serde_json::from_str(json_input).map_err(|e| ValidationError::Compilation(e.to_string()))?,
    )?;

    Ok(())
  }
}