utopia-validators 0.1.1

The checks of Utopia's request validators: booleans, integers, floats, numbers, ranges, ports, hex colors, text, identifiers, white lists, substrings, DNS labels, hostnames, domains, hosts, IP addresses, URLs, phone numbers, JSON, FCM service accounts, globstar patterns and the validators that compose others.
Documentation
//! Validators as values that return what they checked, for Rust callers.
//!
//! The functions of this crate answer `isValid()`: a `bool`, for the PHP extension, which keeps
//! the value. A Rust caller wants the value in its type instead, so a [`Validator`] returns it:
//! [`Port`] a `u16`, [`Range`] an `i64`, [`Text`] a `String`. Each one runs the same checks
//! and has the same description as its PHP class.
//!
//! They are loose where PHP has the choice: a value is accepted in its own type or as its text
//! (`6379` and `"6379"`), since an environment variable is always text.

use crate::{
    HOSTNAME_DESCRIPTION, Input, Integer, Number, boolean, float, hostname, port_number, range_description,
    range_number, text_description, text_length, white_list_description,
};

/// A check of one value that returns it in the type it was checked as.
///
/// ```
/// use utopia_validators::{Input, Port, Validator};
///
/// assert_eq!(Port.validate(Input::Str(b"6379")), Some(6379));
/// assert_eq!(Port.validate(Input::Int(70000)), None);
/// assert_eq!(Port.description(), "Value must be a port between 1 and 65535");
/// ```
///
/// ```php
/// use Utopia\Validator\Port;
///
/// $port = new Port();
/// var_dump($port->isValid('6379'));  // true
/// var_dump($port->isValid(70000));   // false
/// ```
pub trait Validator {
    /// The type of a value that passed.
    type Output;

    /// The value, when it is valid.
    ///
    /// PHP: `isValid()`.
    fn validate(&self, value: Input<'_>) -> Option<Self::Output>;

    /// What a valid value is, to tell whoever sent one that is not.
    ///
    /// PHP: `getDescription()`.
    fn description(&self) -> String;
}

/// The bytes of a description, which are ASCII but for what the caller put in them.
fn text(description: Vec<u8>) -> String {
    String::from_utf8_lossy(&description).into_owned()
}

/// `true`, `false`, `1` or `0`, as a boolean or as text.
///
/// PHP: `new Boolean(loose: true)`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Boolean;

impl Validator for Boolean {
    type Output = bool;

    fn validate(&self, value: Input<'_>) -> Option<bool> {
        if !boolean(true, value) {
            return None;
        }
        Some(match value {
            Input::Bool(b) => b,
            Input::Int(i) => i == 1,
            Input::Str(s) => matches!(s, b"true" | b"1"),
            _ => false,
        })
    }

    fn description(&self) -> String {
        "Value must be a valid boolean".to_string()
    }
}

/// An integer within the bounds, as an int or as text.
///
/// PHP: `new Integer(loose: true, $bits, $unsigned)`.
impl Validator for Integer {
    type Output = i64;

    fn validate(&self, value: Input<'_>) -> Option<i64> {
        match value.numeric() {
            Some(Number::Int(i)) if self.accepts(true, value) => Some(i),
            _ => None,
        }
    }

    fn description(&self) -> String {
        let mut description = Vec::new();
        Integer::description(*self, &mut description);
        text(description)
    }
}

/// Any number, as an int, a float or text.
///
/// PHP: `new FloatValidator(loose: true)`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Float;

impl Validator for Float {
    type Output = f64;

    fn validate(&self, value: Input<'_>) -> Option<f64> {
        if !float(true, value) {
            return None;
        }
        value.numeric().map(Number::as_f64)
    }

    fn description(&self) -> String {
        "Value must be a valid float".to_string()
    }
}

/// An integer from `min` to `max`, both included, as an int or as text.
///
/// PHP: `new Range($min, $max)`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Range {
    /// The smallest valid value.
    pub min: i64,
    /// The largest valid value.
    pub max: i64,
}

impl Range {
    /// The integers from `min` to `max`.
    pub fn new(min: i64, max: i64) -> Self {
        Self { min, max }
    }
}

impl Validator for Range {
    type Output = i64;

    fn validate(&self, value: Input<'_>) -> Option<i64> {
        match range_number(b"integer", value) {
            Some(Number::Int(i)) if i >= self.min && i <= self.max => Some(i),
            _ => None,
        }
    }

    fn description(&self) -> String {
        let mut description = Vec::new();
        range_description(Number::Int(self.min), Number::Int(self.max), &mut description);
        text(description)
    }
}

/// A port from 1 to 65535, as an int or as text.
///
/// PHP: `new Port()`, which also accepts a port after an IP address (`127.0.0.1:80`). That is
/// not a `u16`, so it is refused here.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Port;

impl Validator for Port {
    type Output = u16;

    fn validate(&self, value: Input<'_>) -> Option<u16> {
        let digits;
        let value = match value {
            Input::Int(i) => {
                digits = i.to_string();
                digits.as_bytes()
            }
            Input::Str(s) => s,
            _ => return None,
        };
        if !port_number(value) {
            return None;
        }
        std::str::from_utf8(value).ok()?.parse().ok()
    }

    fn description(&self) -> String {
        "Value must be a port between 1 and 65535".to_string()
    }
}

/// A UTF-8 string of `min` to `length` characters.
///
/// PHP: `new Text($length, $min)`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Text {
    /// The most characters, or 0 for any number.
    pub length: i64,
    /// The fewest characters.
    pub min: i64,
}

impl Text {
    /// A string of 1 to `length` characters, or of any length when `length` is 0.
    pub fn new(length: i64) -> Self {
        Self { length, min: 1 }
    }

    /// At least `min` characters instead of 1.
    pub fn min(mut self, min: i64) -> Self {
        self.min = min;
        self
    }
}

impl Validator for Text {
    type Output = String;

    fn validate(&self, value: Input<'_>) -> Option<String> {
        let Input::Str(value) = value else {
            return None;
        };
        if !text_length(value, self.min, self.length) {
            return None;
        }
        String::from_utf8(value.to_vec()).ok()
    }

    fn description(&self) -> String {
        let mut description = Vec::new();
        text_description(self.length, self.min, None, false, &mut description);
        text(description)
    }
}

/// A hostname: no path, port or protocol, and at most 253 characters.
///
/// PHP: `new Hostname()`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Hostname;

impl Validator for Hostname {
    type Output = String;

    fn validate(&self, value: Input<'_>) -> Option<String> {
        let Input::Str(value) = value else {
            return None;
        };
        if !hostname(value) {
            return None;
        }
        String::from_utf8(value.to_vec()).ok()
    }

    fn description(&self) -> String {
        HOSTNAME_DESCRIPTION.to_string()
    }
}

/// One of the strings of a list, exactly as the list spells it.
///
/// PHP: `new WhiteList($list, strict: true)`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct WhiteList<'a> {
    /// The valid values.
    pub list: &'a [&'a str],
}

impl<'a> WhiteList<'a> {
    /// One of `list`.
    pub fn new(list: &'a [&'a str]) -> Self {
        Self { list }
    }
}

impl Validator for WhiteList<'_> {
    type Output = String;

    fn validate(&self, value: Input<'_>) -> Option<String> {
        let Input::Str(value) = value else {
            return None;
        };
        self.list.iter().find(|allowed| allowed.as_bytes() == value).map(|allowed| allowed.to_string())
    }

    fn description(&self) -> String {
        let mut description = Vec::new();
        white_list_description(self.list.join(", ").as_bytes(), &mut description);
        text(description)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn booleans() {
        assert_eq!(Boolean.validate(Input::Bool(true)), Some(true));
        assert_eq!(Boolean.validate(Input::Str(b"true")), Some(true));
        assert_eq!(Boolean.validate(Input::Str(b"0")), Some(false));
        assert_eq!(Boolean.validate(Input::Int(1)), Some(true));
        assert_eq!(Boolean.validate(Input::Str(b"yes")), None);
        assert_eq!(Boolean.validate(Input::Int(2)), None);
    }

    #[test]
    fn integers() {
        let byte = Integer::new(8, true).unwrap();
        assert_eq!(byte.validate(Input::Int(255)), Some(255));
        assert_eq!(byte.validate(Input::Str(b"255")), Some(255));
        assert_eq!(byte.validate(Input::Str(b"256")), None);
        assert_eq!(byte.validate(Input::Float(1.0)), None);
        assert_eq!(Validator::description(&byte), "Value must be a valid unsigned 8-bit integer between 0 and 255");
    }

    #[test]
    fn floats() {
        assert_eq!(Float.validate(Input::Float(1.5)), Some(1.5));
        assert_eq!(Float.validate(Input::Int(15)), Some(15.0));
        assert_eq!(Float.validate(Input::Str(b"1.5")), Some(1.5));
        assert_eq!(Float.validate(Input::Str(b"fast")), None);
        assert_eq!(Float.validate(Input::Bool(true)), None);
    }

    #[test]
    fn ranges() {
        let range = Range::new(0, 10);
        assert_eq!(range.validate(Input::Int(10)), Some(10));
        assert_eq!(range.validate(Input::Str(b"0")), Some(0));
        assert_eq!(range.validate(Input::Str(b"11")), None);
        assert_eq!(range.validate(Input::Int(-1)), None);
        assert_eq!(range.validate(Input::Float(5.0)), None);
        assert_eq!(range.validate(Input::Float(f64::INFINITY)), None);
        assert_eq!(range.description(), "Value must be a valid range between 0 and 10");
    }

    #[test]
    fn ports() {
        assert_eq!(Port.validate(Input::Int(6379)), Some(6379));
        assert_eq!(Port.validate(Input::Str(b"65535")), Some(65535));
        assert_eq!(Port.validate(Input::Str(b"65536")), None);
        assert_eq!(Port.validate(Input::Str(b"080")), None);
        assert_eq!(Port.validate(Input::Int(0)), None);
        assert_eq!(Port.validate(Input::Str(b"127.0.0.1:80")), None);
    }

    #[test]
    fn texts() {
        assert_eq!(Text::new(5).validate(Input::Str(b"redis")), Some("redis".to_string()));
        assert_eq!(Text::new(5).validate(Input::Str(b"redis6")), None);
        assert_eq!(Text::new(5).validate(Input::Str(b"")), None);
        assert_eq!(Text::new(5).min(0).validate(Input::Str(b"")), Some(String::new()));
        assert_eq!(Text::new(0).validate(Input::Str(&[b'a'; 4096])).map(|text| text.len()), Some(4096));
        assert_eq!(Text::new(5).validate(Input::Int(5)), None);
        assert_eq!(Text::new(5).validate(Input::Str(b"\xff")), None);
        assert_eq!(
            Text::new(5).description(),
            "Value must be a valid string and at least 1 chars and no longer than 5 chars"
        );
    }

    #[test]
    fn hostnames() {
        assert_eq!(Hostname.validate(Input::Str(b"redis.internal")), Some("redis.internal".to_string()));
        assert_eq!(Hostname.validate(Input::Str(b"redis:6379")), None);
        assert_eq!(Hostname.validate(Input::Str(b"")), None);
    }

    #[test]
    fn white_lists() {
        let level = WhiteList::new(&["high", "low"]);
        assert_eq!(level.validate(Input::Str(b"low")), Some("low".to_string()));
        assert_eq!(level.validate(Input::Str(b"LOW")), None);
        assert_eq!(level.validate(Input::Int(1)), None);
        assert_eq!(level.description(), "Value must be one of (high, low)");
    }
}