Skip to main content

utopia_validators/
validator.rs

1//! Validators as values that return what they checked, for Rust callers.
2//!
3//! The functions of this crate answer `isValid()`: a `bool`, for the PHP extension, which keeps
4//! the value. A Rust caller wants the value in its type instead, so a [`Validator`] returns it:
5//! [`Port`] a `u16`, [`Range`] an `i64`, [`Text`] a `String`. Each one runs the same checks
6//! and has the same description as its PHP class.
7//!
8//! They are loose where PHP has the choice: a value is accepted in its own type or as its text
9//! (`6379` and `"6379"`), since an environment variable is always text.
10
11use crate::{
12    HOSTNAME_DESCRIPTION, Input, Integer, Number, boolean, float, hostname, port_number, range_description,
13    range_number, text_description, text_length, white_list_description,
14};
15
16/// A check of one value that returns it in the type it was checked as.
17///
18/// ```
19/// use utopia_validators::{Input, Port, Validator};
20///
21/// assert_eq!(Port.validate(Input::Str(b"6379")), Some(6379));
22/// assert_eq!(Port.validate(Input::Int(70000)), None);
23/// assert_eq!(Port.description(), "Value must be a port between 1 and 65535");
24/// ```
25///
26/// ```php
27/// use Utopia\Validator\Port;
28///
29/// $port = new Port();
30/// var_dump($port->isValid('6379'));  // true
31/// var_dump($port->isValid(70000));   // false
32/// ```
33pub trait Validator {
34    /// The type of a value that passed.
35    type Output;
36
37    /// The value, when it is valid.
38    ///
39    /// PHP: `isValid()`.
40    fn validate(&self, value: Input<'_>) -> Option<Self::Output>;
41
42    /// What a valid value is, to tell whoever sent one that is not.
43    ///
44    /// PHP: `getDescription()`.
45    fn description(&self) -> String;
46}
47
48/// The bytes of a description, which are ASCII but for what the caller put in them.
49fn text(description: Vec<u8>) -> String {
50    String::from_utf8_lossy(&description).into_owned()
51}
52
53/// `true`, `false`, `1` or `0`, as a boolean or as text.
54///
55/// PHP: `new Boolean(loose: true)`.
56#[derive(Debug, Clone, Copy, PartialEq, Eq)]
57pub struct Boolean;
58
59impl Validator for Boolean {
60    type Output = bool;
61
62    fn validate(&self, value: Input<'_>) -> Option<bool> {
63        if !boolean(true, value) {
64            return None;
65        }
66        Some(match value {
67            Input::Bool(b) => b,
68            Input::Int(i) => i == 1,
69            Input::Str(s) => matches!(s, b"true" | b"1"),
70            _ => false,
71        })
72    }
73
74    fn description(&self) -> String {
75        "Value must be a valid boolean".to_string()
76    }
77}
78
79/// An integer within the bounds, as an int or as text.
80///
81/// PHP: `new Integer(loose: true, $bits, $unsigned)`.
82impl Validator for Integer {
83    type Output = i64;
84
85    fn validate(&self, value: Input<'_>) -> Option<i64> {
86        match value.numeric() {
87            Some(Number::Int(i)) if self.accepts(true, value) => Some(i),
88            _ => None,
89        }
90    }
91
92    fn description(&self) -> String {
93        let mut description = Vec::new();
94        Integer::description(*self, &mut description);
95        text(description)
96    }
97}
98
99/// Any number, as an int, a float or text.
100///
101/// PHP: `new FloatValidator(loose: true)`.
102#[derive(Debug, Clone, Copy, PartialEq, Eq)]
103pub struct Float;
104
105impl Validator for Float {
106    type Output = f64;
107
108    fn validate(&self, value: Input<'_>) -> Option<f64> {
109        if !float(true, value) {
110            return None;
111        }
112        value.numeric().map(Number::as_f64)
113    }
114
115    fn description(&self) -> String {
116        "Value must be a valid float".to_string()
117    }
118}
119
120/// An integer from `min` to `max`, both included, as an int or as text.
121///
122/// PHP: `new Range($min, $max)`.
123#[derive(Debug, Clone, Copy, PartialEq, Eq)]
124pub struct Range {
125    /// The smallest valid value.
126    pub min: i64,
127    /// The largest valid value.
128    pub max: i64,
129}
130
131impl Range {
132    /// The integers from `min` to `max`.
133    pub fn new(min: i64, max: i64) -> Self {
134        Self { min, max }
135    }
136}
137
138impl Validator for Range {
139    type Output = i64;
140
141    fn validate(&self, value: Input<'_>) -> Option<i64> {
142        match range_number(b"integer", value) {
143            Some(Number::Int(i)) if i >= self.min && i <= self.max => Some(i),
144            _ => None,
145        }
146    }
147
148    fn description(&self) -> String {
149        let mut description = Vec::new();
150        range_description(Number::Int(self.min), Number::Int(self.max), &mut description);
151        text(description)
152    }
153}
154
155/// A port from 1 to 65535, as an int or as text.
156///
157/// PHP: `new Port()`, which also accepts a port after an IP address (`127.0.0.1:80`). That is
158/// not a `u16`, so it is refused here.
159#[derive(Debug, Clone, Copy, PartialEq, Eq)]
160pub struct Port;
161
162impl Validator for Port {
163    type Output = u16;
164
165    fn validate(&self, value: Input<'_>) -> Option<u16> {
166        let digits;
167        let value = match value {
168            Input::Int(i) => {
169                digits = i.to_string();
170                digits.as_bytes()
171            }
172            Input::Str(s) => s,
173            _ => return None,
174        };
175        if !port_number(value) {
176            return None;
177        }
178        std::str::from_utf8(value).ok()?.parse().ok()
179    }
180
181    fn description(&self) -> String {
182        "Value must be a port between 1 and 65535".to_string()
183    }
184}
185
186/// A UTF-8 string of `min` to `length` characters.
187///
188/// PHP: `new Text($length, $min)`.
189#[derive(Debug, Clone, Copy, PartialEq, Eq)]
190pub struct Text {
191    /// The most characters, or 0 for any number.
192    pub length: i64,
193    /// The fewest characters.
194    pub min: i64,
195}
196
197impl Text {
198    /// A string of 1 to `length` characters, or of any length when `length` is 0.
199    pub fn new(length: i64) -> Self {
200        Self { length, min: 1 }
201    }
202
203    /// At least `min` characters instead of 1.
204    pub fn min(mut self, min: i64) -> Self {
205        self.min = min;
206        self
207    }
208}
209
210impl Validator for Text {
211    type Output = String;
212
213    fn validate(&self, value: Input<'_>) -> Option<String> {
214        let Input::Str(value) = value else {
215            return None;
216        };
217        if !text_length(value, self.min, self.length) {
218            return None;
219        }
220        String::from_utf8(value.to_vec()).ok()
221    }
222
223    fn description(&self) -> String {
224        let mut description = Vec::new();
225        text_description(self.length, self.min, None, false, &mut description);
226        text(description)
227    }
228}
229
230/// A hostname: no path, port or protocol, and at most 253 characters.
231///
232/// PHP: `new Hostname()`.
233#[derive(Debug, Clone, Copy, PartialEq, Eq)]
234pub struct Hostname;
235
236impl Validator for Hostname {
237    type Output = String;
238
239    fn validate(&self, value: Input<'_>) -> Option<String> {
240        let Input::Str(value) = value else {
241            return None;
242        };
243        if !hostname(value) {
244            return None;
245        }
246        String::from_utf8(value.to_vec()).ok()
247    }
248
249    fn description(&self) -> String {
250        HOSTNAME_DESCRIPTION.to_string()
251    }
252}
253
254/// One of the strings of a list, exactly as the list spells it.
255///
256/// PHP: `new WhiteList($list, strict: true)`.
257#[derive(Debug, Clone, Copy, PartialEq, Eq)]
258pub struct WhiteList<'a> {
259    /// The valid values.
260    pub list: &'a [&'a str],
261}
262
263impl<'a> WhiteList<'a> {
264    /// One of `list`.
265    pub fn new(list: &'a [&'a str]) -> Self {
266        Self { list }
267    }
268}
269
270impl Validator for WhiteList<'_> {
271    type Output = String;
272
273    fn validate(&self, value: Input<'_>) -> Option<String> {
274        let Input::Str(value) = value else {
275            return None;
276        };
277        self.list.iter().find(|allowed| allowed.as_bytes() == value).map(|allowed| allowed.to_string())
278    }
279
280    fn description(&self) -> String {
281        let mut description = Vec::new();
282        white_list_description(self.list.join(", ").as_bytes(), &mut description);
283        text(description)
284    }
285}
286
287#[cfg(test)]
288mod tests {
289    use super::*;
290
291    #[test]
292    fn booleans() {
293        assert_eq!(Boolean.validate(Input::Bool(true)), Some(true));
294        assert_eq!(Boolean.validate(Input::Str(b"true")), Some(true));
295        assert_eq!(Boolean.validate(Input::Str(b"0")), Some(false));
296        assert_eq!(Boolean.validate(Input::Int(1)), Some(true));
297        assert_eq!(Boolean.validate(Input::Str(b"yes")), None);
298        assert_eq!(Boolean.validate(Input::Int(2)), None);
299    }
300
301    #[test]
302    fn integers() {
303        let byte = Integer::new(8, true).unwrap();
304        assert_eq!(byte.validate(Input::Int(255)), Some(255));
305        assert_eq!(byte.validate(Input::Str(b"255")), Some(255));
306        assert_eq!(byte.validate(Input::Str(b"256")), None);
307        assert_eq!(byte.validate(Input::Float(1.0)), None);
308        assert_eq!(Validator::description(&byte), "Value must be a valid unsigned 8-bit integer between 0 and 255");
309    }
310
311    #[test]
312    fn floats() {
313        assert_eq!(Float.validate(Input::Float(1.5)), Some(1.5));
314        assert_eq!(Float.validate(Input::Int(15)), Some(15.0));
315        assert_eq!(Float.validate(Input::Str(b"1.5")), Some(1.5));
316        assert_eq!(Float.validate(Input::Str(b"fast")), None);
317        assert_eq!(Float.validate(Input::Bool(true)), None);
318    }
319
320    #[test]
321    fn ranges() {
322        let range = Range::new(0, 10);
323        assert_eq!(range.validate(Input::Int(10)), Some(10));
324        assert_eq!(range.validate(Input::Str(b"0")), Some(0));
325        assert_eq!(range.validate(Input::Str(b"11")), None);
326        assert_eq!(range.validate(Input::Int(-1)), None);
327        assert_eq!(range.validate(Input::Float(5.0)), None);
328        assert_eq!(range.validate(Input::Float(f64::INFINITY)), None);
329        assert_eq!(range.description(), "Value must be a valid range between 0 and 10");
330    }
331
332    #[test]
333    fn ports() {
334        assert_eq!(Port.validate(Input::Int(6379)), Some(6379));
335        assert_eq!(Port.validate(Input::Str(b"65535")), Some(65535));
336        assert_eq!(Port.validate(Input::Str(b"65536")), None);
337        assert_eq!(Port.validate(Input::Str(b"080")), None);
338        assert_eq!(Port.validate(Input::Int(0)), None);
339        assert_eq!(Port.validate(Input::Str(b"127.0.0.1:80")), None);
340    }
341
342    #[test]
343    fn texts() {
344        assert_eq!(Text::new(5).validate(Input::Str(b"redis")), Some("redis".to_string()));
345        assert_eq!(Text::new(5).validate(Input::Str(b"redis6")), None);
346        assert_eq!(Text::new(5).validate(Input::Str(b"")), None);
347        assert_eq!(Text::new(5).min(0).validate(Input::Str(b"")), Some(String::new()));
348        assert_eq!(Text::new(0).validate(Input::Str(&[b'a'; 4096])).map(|text| text.len()), Some(4096));
349        assert_eq!(Text::new(5).validate(Input::Int(5)), None);
350        assert_eq!(Text::new(5).validate(Input::Str(b"\xff")), None);
351        assert_eq!(
352            Text::new(5).description(),
353            "Value must be a valid string and at least 1 chars and no longer than 5 chars"
354        );
355    }
356
357    #[test]
358    fn hostnames() {
359        assert_eq!(Hostname.validate(Input::Str(b"redis.internal")), Some("redis.internal".to_string()));
360        assert_eq!(Hostname.validate(Input::Str(b"redis:6379")), None);
361        assert_eq!(Hostname.validate(Input::Str(b"")), None);
362    }
363
364    #[test]
365    fn white_lists() {
366        let level = WhiteList::new(&["high", "low"]);
367        assert_eq!(level.validate(Input::Str(b"low")), Some("low".to_string()));
368        assert_eq!(level.validate(Input::Str(b"LOW")), None);
369        assert_eq!(level.validate(Input::Int(1)), None);
370        assert_eq!(level.description(), "Value must be one of (high, low)");
371    }
372}