Skip to main content

nitr_std/validate/
coerce.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2// This file is part of Nitr.
3// See https://nitrweb.com/ for more information
4// Copyright (C) 2024-present Jose Quintana <joseluisq.net>
5
6//! Text inputs — a query string, a form, path parameters, headers — are
7//! strings; the schema says what they mean. This turns the raw pairs into
8//! the typed table the checker expects: `integer`/`number`/`boolean`
9//! parsed strictly, repeated keys collected for `array` rules, blank
10//! optional non-string fields treated as absent, `name[]` as `name`.
11//!
12//! A value that does not parse is left as the string it was, so the
13//! checker's own type rule reports it — one message for one mistake.
14
15use mlua::{AnyUserData, Lua, Table, Value};
16
17use super::{Kind, Rule, SchemaDef};
18
19/// One text-part value: a string field, or a spooled upload.
20#[derive(Debug)]
21pub enum TextValue {
22    /// A form field, query parameter, path parameter or header value.
23    Text(String),
24    /// A validated upload (`nitr.File` userdata), for multipart parts.
25    File(AnyUserData),
26}
27
28/// Strict decimal integer: the text must be the integer's own spelling —
29/// no `+`, no whitespace, no exponent, no leading zeros, no `-0`, no
30/// overflow. Spelled as one relation (`parsed.to_string() == text`) so
31/// the rule cannot drift from its list.
32fn parse_integer(text: &str) -> Option<i64> {
33    let digits = text.strip_prefix('-').unwrap_or(text);
34    if digits.is_empty() || !digits.bytes().all(|b| b.is_ascii_digit()) {
35        return None;
36    }
37    text.parse::<i64>()
38        .ok()
39        .filter(|parsed| parsed.to_string() == text)
40}
41
42fn parse_number(text: &str) -> Option<f64> {
43    if text.is_empty() || text.starts_with('+') || text.trim() != text {
44        return None;
45    }
46    if text.contains(['x', 'X', 'n', 'N', 'i', 'I', 'e', 'E']) {
47        // `0x10`, `nan`, `inf`, `1e3`: a form never means those.
48        return None;
49    }
50    text.parse::<f64>().ok().filter(|n| n.is_finite())
51}
52
53fn parse_boolean(text: &str) -> Option<bool> {
54    match text {
55        "true" | "1" | "on" => Some(true),
56        "false" | "0" => Some(false),
57        _ => None,
58    }
59}
60
61/// Coerces one text value to the rule's scalar kind, or leaves it as the
62/// string it was so the checker names the type mismatch.
63fn coerce_scalar(lua: &Lua, rule: &Rule, text: &str) -> mlua::Result<Value> {
64    Ok(match rule.kind {
65        Kind::Integer => match parse_integer(text) {
66            Some(i) => Value::Integer(i),
67            None => Value::String(lua.create_string(text)?),
68        },
69        Kind::Number => match parse_number(text) {
70            Some(n) if n.fract() == 0.0 && n.abs() < 9.0e15 => Value::Integer(n as i64),
71            Some(n) => Value::Number(n),
72            None => Value::String(lua.create_string(text)?),
73        },
74        Kind::Boolean => match parse_boolean(text) {
75            Some(b) => Value::Boolean(b),
76            None => Value::String(lua.create_string(text)?),
77        },
78        _ => Value::String(lua.create_string(text)?),
79    })
80}
81
82/// Whether a blank text value means "not given" for this rule: every
83/// kind but `string`, where the empty string is a value and `min_len`
84/// decides.
85fn blank_is_absent(rule: &Rule, text: &str) -> bool {
86    rule.kind != Kind::String && text.trim().is_empty()
87}
88
89/// Builds the typed table for the checker from raw text pairs.
90pub(super) fn build_table(
91    lua: &Lua,
92    schema: &SchemaDef,
93    pairs: Vec<(String, TextValue)>,
94) -> mlua::Result<Table> {
95    let out = lua.create_table()?;
96    // Group by normalized name, keeping arrival order within a name.
97    let mut grouped: Vec<(String, Vec<TextValue>)> = Vec::new();
98    for (name, value) in pairs {
99        let name = name.strip_suffix("[]").unwrap_or(&name).to_string();
100        match grouped.iter_mut().find(|(n, _)| *n == name) {
101            Some((_, values)) => values.push(value),
102            None => grouped.push((name, vec![value])),
103        }
104    }
105    for (name, values) in grouped {
106        match schema.rule(&name) {
107            Some(rule) if rule.kind == Kind::Array => {
108                // Invariant: schema compilation only builds an array rule
109                // with its `items` present.
110                #[allow(clippy::expect_used)]
111                let items = rule.items.as_ref().expect("array rules carry `items`");
112                let list = lua.create_table_with_capacity(values.len(), 0)?;
113                let mut n = 0;
114                for value in values {
115                    let item = match value {
116                        TextValue::Text(text) => {
117                            if blank_is_absent(items, &text) {
118                                continue;
119                            }
120                            coerce_scalar(lua, items, &text)?
121                        }
122                        TextValue::File(ud) => Value::UserData(ud),
123                    };
124                    n += 1;
125                    list.raw_set(n, item)?;
126                }
127                out.set(name.as_str(), list)?;
128            }
129            Some(rule) => {
130                // Last value wins, like `req.query`.
131                let Some(last) = values.into_iter().last() else {
132                    continue;
133                };
134                let value = match last {
135                    TextValue::Text(text) => {
136                        if blank_is_absent(rule, &text) {
137                            continue;
138                        }
139                        coerce_scalar(lua, rule, &text)?
140                    }
141                    TextValue::File(ud) => Value::UserData(ud),
142                };
143                out.set(name.as_str(), value)?;
144            }
145            None => {
146                // Undeclared: kept as raw text so `strict` can report it;
147                // the checker strips it otherwise.
148                let Some(last) = values.into_iter().last() else {
149                    continue;
150                };
151                let value = match last {
152                    TextValue::Text(text) => Value::String(lua.create_string(&text)?),
153                    TextValue::File(ud) => Value::UserData(ud),
154                };
155                out.set(name.as_str(), value)?;
156            }
157        }
158    }
159    Ok(out)
160}
161
162/// Exposed for the `validate-coerce` fuzz target: the three strict parsers
163/// over arbitrary text.
164#[doc(hidden)]
165pub fn coerce_for_fuzzing(text: &str) -> (Option<i64>, Option<f64>, Option<bool>) {
166    (parse_integer(text), parse_number(text), parse_boolean(text))
167}
168
169#[cfg(test)]
170mod tests {
171    use super::*;
172
173    #[test]
174    fn integers_parse_strictly() {
175        for ok in ["0", "42", "-7", "9223372036854775807"] {
176            assert!(parse_integer(ok).is_some(), "{ok}");
177        }
178        for bad in [
179            "",
180            "+5",
181            " 5",
182            "5 ",
183            "1e3",
184            "0x10",
185            "1.0",
186            "007",
187            "-0",
188            "99999999999999999999",
189            "٣",
190        ] {
191            assert!(parse_integer(bad).is_none(), "{bad}");
192        }
193    }
194
195    #[test]
196    fn numbers_and_booleans_parse_the_form_way() {
197        assert_eq!(parse_number("1.5"), Some(1.5));
198        assert_eq!(parse_number("-2"), Some(-2.0));
199        for bad in ["", "+1", "1e3", "1e400", "inf", "nan", "0x1", " 1"] {
200            assert!(parse_number(bad).is_none(), "{bad}");
201        }
202        assert_eq!(parse_boolean("on"), Some(true));
203        assert_eq!(parse_boolean("0"), Some(false));
204        assert_eq!(parse_boolean("yes"), None);
205    }
206}