filigree 0.4.1

Filigree web application framework
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
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
719
720
721
722
723
724
725
726
727
728
//! Code for validating requests against JSON schemas
// Schema caching code in this file originally inspired by [axum-jsonschema](https://github.com/tamasfe/aide/blob/master/crates/axum-jsonschema/src/lib.rs).

use std::{
    any::TypeId,
    cell::RefCell,
    collections::{BTreeMap, HashMap, VecDeque},
};

use jsonschema::{
    output::{BasicOutput, ErrorDescription, OutputUnit},
    JSONSchema,
};
use schemars::{
    gen::{SchemaGenerator, SchemaSettings},
    schema::{InstanceType, RootSchema, SingleOrVec},
    JsonSchema,
};
use serde::Serialize;
use serde_json::Number;

#[cfg(feature = "maud")]
use crate::html::HtmlList;

thread_local! {
    static SCHEMAS: RefCell<Schemas> = RefCell::new(Schemas::new());
}

#[derive(Debug, Default, PartialEq, Eq, Clone, Copy)]
enum CoerceOp {
    #[default]
    // Don't coerce the value
    None,
    // Coerce the value's type
    Singleton,
    // Coerce the value's type and make sure it's an array
    Array,
}

impl CoerceOp {
    fn new(coerce: bool, array: bool) -> Self {
        match (coerce, array) {
            (true, true) => CoerceOp::Array,
            (true, false) => CoerceOp::Singleton,
            _ => CoerceOp::None,
        }
    }

    // Combine this CoerceOp with another. When two ops combine and one is an array, the output is
    // Singleton because that means that we don't have to coerce it into an array for validation to
    // pass.
    fn extend(&mut self, other: &CoerceOp) {
        match (&self, other) {
            (CoerceOp::None, a) => {
                *self = *a;
            }
            (CoerceOp::Singleton, _) => {}
            (CoerceOp::Array, CoerceOp::Singleton) => {
                *self = CoerceOp::Singleton;
            }
            (CoerceOp::Array, _) => {}
        }
    }

    // Create a version of this op, filtered on if array coercion is allowed in the caller's
    // context.
    fn with_array(&self, allow_array: bool) -> Self {
        match (self, allow_array) {
            (CoerceOp::Array, false) => CoerceOp::Singleton,
            _ => *self,
        }
    }

    fn is_none(&self) -> bool {
        matches!(self, CoerceOp::None)
    }

    fn is_singleton(&self) -> bool {
        matches!(self, CoerceOp::Singleton)
    }

    fn is_array(&self) -> bool {
        matches!(self, CoerceOp::Array)
    }

    fn coerce_singleton_or_array(&self, output: &mut serde_json::Value, input: serde_json::Value) {
        if self.is_array() {
            *output = serde_json::Value::Array(vec![input]);
        } else if self.is_singleton() {
            *output = input;
        }
    }
}

#[derive(Debug, Default, PartialEq, Eq)]
struct CoerceTo {
    number: CoerceOp,
    integer: CoerceOp,
    boolean: CoerceOp,
    string: CoerceOp,
}

impl CoerceTo {
    fn from_instance_types(t: &SingleOrVec<InstanceType>, array: bool) -> Self {
        Self {
            number: CoerceOp::new(t.contains(&InstanceType::Number), array),
            integer: CoerceOp::new(t.contains(&InstanceType::Integer), array),
            boolean: CoerceOp::new(t.contains(&InstanceType::Boolean), array),
            string: CoerceOp::new(t.contains(&InstanceType::String), array),
        }
    }

    fn extend(&mut self, other: &CoerceTo) {
        self.number.extend(&other.number);
        self.integer.extend(&other.integer);
        self.boolean.extend(&other.boolean);
        self.string.extend(&other.string);
    }

    fn into_option(self) -> Option<Self> {
        if self.is_empty() {
            None
        } else {
            Some(self)
        }
    }

    fn is_empty(&self) -> bool {
        self.number.is_none()
            && self.integer.is_none()
            && self.boolean.is_none()
            && !self.string.is_array()
    }

    /// Coerce from string to boolean, accounting for values that come from forms
    fn coerce_to_boolean(&self, op: CoerceOp, input: &mut serde_json::Value) {
        match input {
            serde_json::Value::String(s) => {
                let value = match s.as_str() {
                    "true" => true,
                    "on" => true,
                    "false" => false,
                    "" => false,
                    _ => {
                        return;
                    }
                };

                op.coerce_singleton_or_array(input, serde_json::Value::Bool(value));
            }
            _ => {}
        }
    }

    fn coerce_to_integer(&self, op: CoerceOp, input: &mut serde_json::Value) {
        match input {
            serde_json::Value::String(s) => {
                let n = s.parse::<i64>().ok();
                if let Some(number) = n {
                    op.coerce_singleton_or_array(input, serde_json::Value::Number(number.into()));
                }
            }
            _ => {}
        }
    }

    fn coerce_to_number(&self, op: CoerceOp, input: &mut serde_json::Value) {
        match input {
            serde_json::Value::String(s) => {
                if s.contains('.') {
                    let n = s.parse::<f64>().ok().and_then(Number::from_f64);
                    if let Some(number) = n {
                        op.coerce_singleton_or_array(input, serde_json::Value::Number(number));
                    }
                } else {
                    let n = s.parse::<i64>().ok();
                    if let Some(number) = n {
                        op.coerce_singleton_or_array(
                            input,
                            serde_json::Value::Number(number.into()),
                        );
                    }
                }
            }
            _ => {}
        }
    }

    fn coerce(&self, input: &mut serde_json::Value, do_array_coercion: bool) {
        if !self.number.is_none() {
            self.coerce_to_number(self.number.with_array(do_array_coercion), input);
        } else if !self.integer.is_none() {
            self.coerce_to_integer(self.integer.with_array(do_array_coercion), input);
        }

        if !self.boolean.is_none() {
            self.coerce_to_boolean(self.boolean.with_array(do_array_coercion), input);
        }

        // Everything is a string already, so only do array coercion for strings.
        if do_array_coercion && input.is_string() && self.string.is_array() {
            *input = serde_json::Value::Array(vec![input.take()]);
        }
    }
}

#[derive(Debug)]
struct FieldInfo {
    name: String,
    required: bool,
    coerce: CoerceTo,
}

impl FieldInfo {
    // Browsers omit checkboxes completely if they are not checked, so supply `false` or vec![] if the
    // validator is expecting a value.
    fn coerce_none(&self) -> Option<serde_json::Value> {
        if !self.required {
            return None;
        }

        match self.coerce.boolean {
            CoerceOp::Singleton => Some(serde_json::Value::Bool(false)),
            CoerceOp::Array => Some(serde_json::Value::Array(vec![])),
            CoerceOp::None => None,
        }
    }
}

struct SchemaInfo {
    schema: JSONSchema,
    coerce_fields: Vec<FieldInfo>,
}

struct Schemas {
    generator: SchemaGenerator,
    schemas: HashMap<TypeId, SchemaInfo>,
}

impl Schemas {
    fn new() -> Self {
        Self {
            generator: SchemaSettings::draft07()
                .with(|g| g.inline_subschemas = true)
                .into_generator(),
            schemas: HashMap::new(),
        }
    }
}

/// Errors returned from JSON schema validation
pub type SchemaErrors = VecDeque<OutputUnit<ErrorDescription>>;

/// Validation errors, formatted for return to the client
#[derive(Debug, Default, Serialize)]
pub struct ValidationErrorResponse {
    /// Validation messages not specific to a particular field.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub messages: Vec<String>,
    /// Validation messages for particular fields. For nested fields, the paths are in
    /// JSON Pointer format.
    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
    pub fields: BTreeMap<String, Vec<String>>,
}

impl ValidationErrorResponse {
    /// Return true if there are no validation errors
    pub fn is_empty(&self) -> bool {
        self.messages.is_empty() && self.fields.is_empty()
    }

    /// Add a validation error for a field
    pub fn add_field(&mut self, field: impl Into<String>, message: impl Into<String>) {
        self.fields
            .entry(field.into())
            .or_default()
            .push(message.into());
    }
}

// Something to send to HtmlList when there are no items.
#[cfg(feature = "maud")]
const EMPTY: [String; 0] = [];

#[cfg(feature = "maud")]
impl ValidationErrorResponse {
    /// Get the errors for a field, formatted with `<li>` elements.
    pub fn field_li<'a>(&'a self, field: &str) -> HtmlList<'a, 'static, String> {
        HtmlList::new(
            self.fields
                .get(field)
                .map(|v| v.as_slice())
                .unwrap_or(&EMPTY),
        )
    }

    /// Get the errors for a field, wrapping the output of [field_li] in a `<ul>` tag.
    pub fn field_ul<'a, 'b>(&'a self, field: &str, class: &'b str) -> HtmlList<'a, 'b, String> {
        self.field_li(field).ul_class(class)
    }
}

impl From<SchemaErrors> for ValidationErrorResponse {
    fn from(value: SchemaErrors) -> Self {
        let mut result = ValidationErrorResponse {
            messages: vec![],
            fields: BTreeMap::default(),
        };

        for err in value {
            let field = err.instance_location().to_string();
            let message = err.error_description().to_string();
            result.fields.entry(field).or_default().push(message);
        }

        result
    }
}

/// Validate a JSON value against a JSON schema
/// If `coerce_arrays` is true, non-array values will be coerced to `Vec<_>` if the schema
/// specifies an array. This should be used when the original input format is not completely
/// self-describing, such as `application/x-www-form-urlencoded`.
pub fn validate<T: JsonSchema + 'static>(
    mut input: serde_json::Value,
    coerce_values: bool,
) -> Result<serde_json::Value, (serde_json::Value, SchemaErrors)> {
    SCHEMAS.with(|sch| {
        let sch = &mut *sch.borrow_mut();
        let schema = sch
            .schemas
            .entry(TypeId::of::<T>())
            .or_insert_with(|| compile_schema(sch.generator.root_schema_for::<T>()));

        if coerce_values {
            // When a browser submits a form, everything is a string and there's no distinction between singletons
            // and single-element arrays. This code attempts to match the submitted data to the
            // actual format. It specifically only attempts to handle HTML form submissions, rather
            // than every possible input.
            for field in &schema.coerce_fields {
                if let Some(data) = input.get_mut(&field.name) {
                    match data {
                        serde_json::Value::Array(a) => {
                            for v in a {
                                field.coerce.coerce(v, false);
                            }
                        }
                        serde_json::Value::Null => {}
                        _ => {
                            field.coerce.coerce(data, true);
                        }
                    }
                } else if let Some(none_value) = field.coerce_none() {
                    input[field.name.clone()] = none_value;
                }
            }
        }

        match schema.schema.apply(&input).basic() {
            BasicOutput::Valid(_) => Ok(input),
            BasicOutput::Invalid(err) => Err((input, err)),
        }
    })
}

fn compile_schema(input: RootSchema) -> SchemaInfo {
    let coerce_fields = input
        .schema
        .object
        .as_ref()
        .map(|root| {
            root.properties
                .iter()
                .filter_map(|(name, s)| {
                    get_coerce_type::get_coerce_type_from_schema(s, false).map(|ct| FieldInfo {
                        name: name.to_string(),
                        required: root.required.contains(name),
                        coerce: ct,
                    })
                })
                .collect::<Vec<_>>()
        })
        .unwrap_or_default();

    let schema = match JSONSchema::compile(&serde_json::to_value(input).unwrap()) {
        Ok(schema) => schema,
        Err(_) => JSONSchema::compile(&serde_json::json!({})).unwrap(),
    };

    SchemaInfo {
        schema,
        coerce_fields,
    }
}

mod get_coerce_type {
    use schemars::schema::{Schema, SchemaObject, SingleOrVec};

    use super::CoerceTo;

    /// When there are multiple subschemas for a field, combine the coercion info from them all.
    fn get_coerce_type_from_subschemas(ss: &Option<Vec<Schema>>, array: bool) -> Option<CoerceTo> {
        let Some(ss) = ss.as_deref() else {
            return None;
        };

        let mut ct = CoerceTo::default();

        for schema in ss {
            if let Some(c) = get_coerce_type_from_schema(schema, array) {
                ct.extend(&c);
            }
        }

        ct.into_option()
    }

    /// Get the schemas from an array's items.
    fn get_coerce_type_from_array_items(items: &SingleOrVec<Schema>) -> Option<CoerceTo> {
        match items {
            SingleOrVec::Single(schema) => get_coerce_type_from_schema(schema, true),
            SingleOrVec::Vec(schemas) => schemas
                .iter()
                .find_map(|s| get_coerce_type_from_schema(s, true)),
        }
    }

    /// Get the coercion info from a schema object, accounting for it using the "type" field
    /// or "anyOf" or "oneOf".
    fn get_coerce_type_from_schema_object(o: &SchemaObject, array: bool) -> Option<CoerceTo> {
        o.instance_type
            .as_ref()
            .and_then(|t| CoerceTo::from_instance_types(t, array).into_option())
            .or_else(|| {
                o.subschemas.as_ref().and_then(|ss| {
                    get_coerce_type_from_subschemas(&ss.any_of, array)
                        .or_else(|| get_coerce_type_from_subschemas(&ss.one_of, array))
                })
            })
    }

    /// Get the coercion info from a field's schema.
    pub fn get_coerce_type_from_schema(schema: &Schema, array: bool) -> Option<CoerceTo> {
        match schema {
            Schema::Object(o) => {
                if let Some(ct) = get_coerce_type_from_schema_object(o, array) {
                    Some(ct)
                } else if let Some(array) = o.array.as_ref() {
                    let ct = array
                        .items
                        .as_ref()
                        .and_then(get_coerce_type_from_array_items)
                        .unwrap_or_else(CoerceTo::default);
                    Some(ct)
                } else {
                    None
                }
            }
            _ => None,
        }
    }
}

#[cfg(test)]
#[allow(dead_code)]
mod test {
    use serde::Deserialize;
    use serde_json::json;

    use super::*;

    #[test]
    fn strings() {
        #[derive(Deserialize, JsonSchema, Debug, PartialEq, Eq)]
        struct Data {
            s: String,
            s_vec1: Vec<String>,
            s_vec2: Vec<String>,
            s_vec3: Vec<String>,
        }

        let data = json!({
            "s": "foo",
            "s_vec1": "foo",
            "s_vec2": "foo",
            "s_vec3": ["foo", "bar"],
        });

        let res = validate::<Data>(data, true);
        println!("{res:#?}");
        let data = res.unwrap();
        assert_eq!(
            data,
            json!({
                "s": "foo",
                "s_vec1": ["foo"],
                "s_vec2": ["foo"],
                "s_vec3": ["foo", "bar"],
            })
        )
    }

    #[derive(Debug, PartialEq, Eq, JsonSchema)]
    #[serde(untagged)]
    enum NumOrBool {
        Num(i32),
        Bool(bool),
    }

    #[derive(Debug, PartialEq, Eq, JsonSchema)]
    #[serde(untagged)]
    enum NumVecOrBool {
        Num(Vec<i32>),
        Bool(bool),
    }

    #[derive(Debug, PartialEq, Eq, JsonSchema)]
    #[serde(untagged)]
    enum NumOrBoolVec {
        Num(i32),
        Bool(Vec<bool>),
    }

    #[derive(Debug, PartialEq, Eq, JsonSchema)]
    #[serde(untagged)]
    enum NumVecOrBoolVec {
        Num(Vec<i32>),
        Bool(Vec<bool>),
    }

    #[test]
    fn num_or_bool() {
        #[derive(JsonSchema, Debug, PartialEq, Eq)]
        struct Data {
            nob_n: NumOrBool,
            nob_b: NumOrBool,
            nob_b_option: Option<NumOrBool>,
            nob_b_omitted: NumOrBool,
            nob_v1: Vec<NumOrBool>,
            nob_v2: Vec<NumOrBool>,
            nob_v3: Vec<NumOrBool>,
        }

        let data = json!({
            "nob_n": "1",
            "nob_b": "on",
            "nob_v1": "1",
            "nob_v2": "on",
            "nob_v3": ["on", 1, 23],
        });

        let res = validate::<Data>(data, true);
        println!("{res:#?}");
        let data = res.unwrap();
        assert_eq!(
            data,
            json!({
                "nob_n": 1,
                "nob_b": true,
                "nob_b_omitted": false,
                "nob_v1": [1],
                "nob_v2": [true],
                "nob_v3": [true, 1, 23],
            })
        )
    }

    #[test]
    fn num_vec_or_bool_vec() {
        #[derive(JsonSchema, Debug, PartialEq, Eq)]
        struct Data {
            b1: NumVecOrBoolVec,
            n1: NumVecOrBoolVec,
            b2: NumVecOrBoolVec,
            n2: NumVecOrBoolVec,
        }

        let data = json!({
            "b1": "on",
            "n1": "1",
            "b2": ["on", "on"],
            "n2": ["1", "2"],
        });

        let res = validate::<Data>(data, true);
        println!("{res:#?}");
        let data = res.unwrap();
        assert_eq!(
            data,
            json!({
                "b1": [true],
                "n1": [1],
                "b2": [true, true],
                "n2": [1, 2],
            })
        );
    }

    #[test]
    fn num_or_bool_vec() {
        #[derive(JsonSchema, Debug, PartialEq, Eq)]
        struct Data {
            n: NumOrBoolVec,
            b1: NumOrBoolVec,
            b2: NumOrBoolVec,
        }

        let data = json!({
            "n": "1",
            "b1": "on",
            "b2": ["on", "on"],
        });

        let res = validate::<Data>(data, true);
        println!("{res:#?}");
        let data = res.unwrap();
        assert_eq!(
            data,
            json!({
                "n": 1,
                "b1": [true],
                "b2": [true, true],
            })
        );
    }

    #[test]
    fn coerce_none() {
        #[derive(JsonSchema, Debug, PartialEq, Eq)]
        struct Data {
            b: bool,
            bv: Vec<bool>,
        }

        let data = json!({});

        let res = validate::<Data>(data, true);
        println!("{res:#?}");
        let data = res.unwrap();
        assert_eq!(
            data,
            json!({
                "b": false,
                "bv": [],
            })
        );
    }

    #[test]
    fn comprehensive_coerce() {
        #[derive(JsonSchema, Debug, PartialEq, Eq)]
        struct Data {
            s: String,
            s_vec1: Vec<String>,
            s_vec2: Vec<String>,
            i: i32,
            i_vec1: Vec<i32>,
            i_vec2: Vec<i32>,
            nob_n: NumOrBool,
            nob_b: NumOrBool,
            nob_vec1: Vec<NumOrBool>,
            nob_vec2: Vec<NumOrBool>,
            nobv1: NumOrBoolVec,
            nobv2: NumOrBoolVec,
            nvob1: NumVecOrBool,
            nvob2: NumVecOrBool,
            nvobv1: NumVecOrBoolVec,
            nvobv2: NumVecOrBoolVec,
            b: bool,
            b_omitted: bool,
            ob: Option<bool>,
            b_vec1: Vec<bool>,
            b_vec2: Vec<bool>,
        }

        let data = json!({
            "s": "a",
            "s_vec1": "a",
            "s_vec2": ["a", "b"],
            "i": "1",
            "i_vec1": "1",
            "i_vec2": ["1", "2"],
            "nob_n": "1",
            "nob_b": "on",
            "nob_vec1": "1",
            "nob_vec2": ["1", "on"],
            "nobv1": "1",
            "nobv2": "on",
            "nvob1": "1",
            "nvob2": "on",
            "nvobv1": "1",
            "nvobv2": "on",
            "b": "on",
            "b_vec1": "on",
            "b_vec2": ["on", "false"]
        });

        let res = validate::<Data>(data, true);
        println!("{res:#?}");
        let data = res.unwrap();

        assert_eq!(
            data,
            json!({
                "s": "a",
                "s_vec1": ["a"],
                "s_vec2": ["a", "b"],
                "i": 1,
                "i_vec1": [1],
                "i_vec2": [1, 2],
                "nob_n": 1,
                "nob_b": true,
                "nob_vec1": [1],
                "nob_vec2": [1, true],
                "nobv1": 1,
                "nobv2": [true],
                "nvob1": [1],
                "nvob2": true,
                "nvobv1": [1],
                "nvobv2": [true],
                "b": true,
                "b_omitted": false,
                "b_vec1": [true],
                "b_vec2": [true, false]
            })
        );
    }
}