Skip to main content

utopia_validators/
network.rs

1//! The network validators: `Hostname`, `Domain`, `Host`, `IP`, `URL` and `Phone`.
2//!
3//! PHP runs `filter_var()`, `parse_url()` and `Uri\Rfc3986\Uri::parse()` for them; these
4//! functions run [`php_std`]'s ports of the same, so a value is accepted exactly when PHP
5//! accepts it.
6
7use std::borrow::Cow;
8
9use php_std::filter::{
10    self, FILTER_FLAG_IPV4, FILTER_FLAG_IPV6, FILTER_VALIDATE_IP, FILTER_VALIDATE_URL, Options, Value,
11};
12use php_std::url::rfc3986::Uri;
13use php_std::url::{Component, ComponentValue, parse_url};
14
15use crate::chars;
16
17/// Whether `filter_var($value, $filter, $flags)` returns something other than `false`.
18fn passes(value: &Value, filter: i64, flags: i64) -> bool {
19    filter::filter_var(value, filter, &Options::Flags(flags))
20        .is_ok_and(|filtered| !matches!(filtered.value, Value::Bool(false)))
21}
22
23/// Whether `filter_var($value, $filter, $flags)` returns a truthy value (`IP` tests it with
24/// `if (filter_var(...))`).
25fn truthy(value: &Value, filter: i64, flags: i64) -> bool {
26    filter::filter_var(value, filter, &Options::Flags(flags)).is_ok_and(|filtered| match filtered.value {
27        Value::Bool(b) => b,
28        Value::Str(s) => !(s.is_empty() || s == b"0"),
29        Value::Null => false,
30        Value::Int(i) => i != 0,
31        Value::Float(f) => f != 0.0,
32        Value::Array(a) => !a.is_empty(),
33        Value::Object => true,
34    })
35}
36
37// Hostname --------------------------------------------------------------------------------
38
39/// `Hostname::getDescription()`.
40pub const HOSTNAME_DESCRIPTION: &str = "Value must be a valid hostname without path, port and protocol.";
41
42/// The checks of `Hostname::isValid()` before its allow list: not `''` or `'0'`, at most 253
43/// characters (`mb_strlen()`), no `/` and no `:`.
44pub fn hostname(value: &[u8]) -> bool {
45    !(value.is_empty() || value == b"0") && chars(value) <= 253 && !value.contains(&b'/') && !value.contains(&b':')
46}
47
48/// Whether `value` matches an allow-list entry `allowed` that is a string: equal to it, `*`,
49/// or a `*.suffix` wildcard that `value` ends with (the root itself is not matched).
50pub fn hostname_allowed(value: &[u8], allowed: &[u8]) -> bool {
51    value == allowed || allowed == b"*" || allowed.strip_prefix(b"*").is_some_and(|suffix| value.ends_with(suffix))
52}
53
54// Domain ----------------------------------------------------------------------------------
55
56/// `Domain::getDescription()`.
57pub const DOMAIN_DESCRIPTION: &str = "Value must be a valid domain";
58
59/// `Domain::isValid()`'s format checks on a non-empty string: `filter_var(FILTER_VALIDATE_DOMAIN)`
60/// (with `FILTER_FLAG_HOSTNAME` when `hostnames`) and no trailing `.` or `-`.
61pub fn domain(value: &[u8], hostnames: bool) -> bool {
62    // `filter_var()` of a string runs the filter on it as it is.
63    filter::validate_domain(value, hostnames) && !value.ends_with(b".") && !value.ends_with(b"-")
64}
65
66/// `count(explode('.', $value, $limit))`.
67pub fn explode_count(value: &[u8], limit: i64) -> i64 {
68    php_std::string::explode(b".", value, limit).map_or(0, |parts| i64::try_from(parts.len()).unwrap_or(i64::MAX))
69}
70
71// IP --------------------------------------------------------------------------------------
72
73/// `IP::getDescription()`.
74pub const IP_DESCRIPTION: &str = "Value must be a valid IP address";
75
76/// The IP versions `IP` accepts: `IP::ALL`, `IP::V4` or `IP::V6`.
77#[derive(Debug, Clone, Copy, PartialEq, Eq)]
78pub enum IpType {
79    All,
80    V4,
81    V6,
82}
83
84impl IpType {
85    /// The type named `name` (`'all'`, `'ipv4'`, `'ipv6'`), as `IP`'s constructor and
86    /// `isValid()` compare it.
87    pub fn from_name(name: &[u8]) -> Option<Self> {
88        match name {
89            b"all" => Some(IpType::All),
90            b"ipv4" => Some(IpType::V4),
91            b"ipv6" => Some(IpType::V6),
92            _ => None,
93        }
94    }
95}
96
97/// `IP::isValid()`: `filter_var($value, FILTER_VALIDATE_IP[, flag])` is truthy.
98pub fn ip(value: &Value, kind: IpType) -> bool {
99    truthy(value, FILTER_VALIDATE_IP, kind.flags())
100}
101
102/// [`ip`] of a string: the filter on the string as it is (an address it accepts is never
103/// `''` or `'0'`, so accepted is truthy).
104pub fn ip_str(value: &[u8], kind: IpType) -> bool {
105    filter::validate_ip(value, kind.flags())
106}
107
108impl IpType {
109    /// The `filter_var()` flags `IP` passes for the type.
110    fn flags(self) -> i64 {
111        match self {
112            IpType::All => 0,
113            IpType::V4 => FILTER_FLAG_IPV4,
114            IpType::V6 => FILTER_FLAG_IPV6,
115        }
116    }
117}
118
119// URL -------------------------------------------------------------------------------------
120
121/// `URL::getDescription()`, given `implode(', ', $allowedSchemes)` when there are schemes.
122///
123/// Appended to `description`.
124pub fn url_description(
125    schemes: Option<&[u8]>,
126    allow_fragments: bool,
127    https_or_loopback: bool,
128    description: &mut Vec<u8>,
129) {
130    let transport: &[u8] = if https_or_loopback { b" restricted to https or http on a loopback host" } else { b"" };
131    if let Some(schemes) = schemes {
132        description.extend_from_slice(b"Value must be a valid URL with following schemes (");
133        description.extend_from_slice(schemes);
134        description.push(b')');
135        if !allow_fragments {
136            description.extend_from_slice(b" and without a fragment component");
137        }
138    } else if !allow_fragments {
139        description.extend_from_slice(b"Value must be a valid URL without a fragment component");
140    } else {
141        description.extend_from_slice(b"Value must be a valid URL");
142    }
143    description.extend_from_slice(transport);
144}
145
146/// `URL::isValid()`'s IRI step: each byte above 127 as `rawurlencode()` encodes it.
147pub fn url_ascii(value: &[u8]) -> Cow<'_, [u8]> {
148    if value.is_ascii() {
149        return Cow::Borrowed(value);
150    }
151    let mut ascii = Vec::with_capacity(value.len() * 3);
152    for &byte in value {
153        if byte > 127 {
154            const HEX: &[u8; 16] = b"0123456789ABCDEF";
155            ascii.extend_from_slice(&[b'%', HEX[usize::from(byte >> 4)], HEX[usize::from(byte & 15)]]);
156        } else {
157            ascii.push(byte);
158        }
159    }
160    Cow::Owned(ascii)
161}
162
163/// Whether `filter_var($value, FILTER_VALIDATE_URL)` is not `false`.
164pub fn url(value: &Value) -> bool {
165    passes(value, FILTER_VALIDATE_URL, 0)
166}
167
168/// [`url`] of a string: the filter on the string as it is.
169pub fn url_str(value: &[u8]) -> bool {
170    filter::validate_url(value, 0, None).unwrap_or(false)
171}
172
173/// `URL::isPrivateUseSchemeURI()` on a string: `Uri\Rfc3986\Uri::parse()` succeeds, its
174/// (normalized) scheme contains a `.` and it has no host.
175pub fn private_use_scheme(value: &[u8]) -> bool {
176    Uri::parse(value)
177        .is_some_and(|uri| uri.scheme().is_some_and(|scheme| scheme.contains(&b'.')) && uri.host().is_none())
178}
179
180/// `parse_url($value, $component)` for a string component: `None` where PHP returns `false`
181/// (a malformed URL), `Some(None)` for `null` (no such component).
182pub fn url_component(value: &[u8], component: Component) -> Option<Option<Vec<u8>>> {
183    let url = parse_url(value)?;
184    Some(url.component(component).map(|found| match found {
185        ComponentValue::Str(s) => s.into_owned(),
186        ComponentValue::Port(port) => port.to_string().into_bytes(),
187    }))
188}
189
190/// The hosts `URL`'s `httpsOrLoopback` lets plain `http` reach.
191pub const LOOPBACK_HOSTS: [&[u8]; 3] = [b"localhost", b"127.0.0.1", b"[::1]"];
192
193// Host ------------------------------------------------------------------------------------
194
195/// What `Host::getDescription()` puts before `implode(', ', $whitelist)`.
196pub const HOST_DESCRIPTION_PREFIX: &str = "URL host must be one of: ";
197
198/// `Host::getDescription()`, given `implode(', ', $whitelist)`, appended to `description`.
199pub fn host_description(whitelist: &[u8], description: &mut Vec<u8>) {
200    description.extend_from_slice(HOST_DESCRIPTION_PREFIX.as_bytes());
201    description.extend_from_slice(whitelist);
202}
203
204// Phone -----------------------------------------------------------------------------------
205
206/// `Phone::getDescription()`.
207pub const PHONE_DESCRIPTION: &str = "Phone number must start with a '+' and contain between 7 and 15 digits.";
208
209/// `[1-9]\d{6,14}$` against all of `value`: PCRE's `$` (no `D` modifier) also matches before
210/// a final newline.
211fn e164_digits(value: &[u8]) -> bool {
212    let digits = value.strip_suffix(b"\n").unwrap_or(value);
213    matches!(digits.first(), Some(b'1'..=b'9'))
214        && (7..=15).contains(&digits.len())
215        && digits.iter().all(u8::is_ascii_digit)
216}
217
218/// `Phone::isValid()`'s pattern, `/^\+[1-9]\d{6,14}$/`.
219pub fn phone(value: &[u8]) -> bool {
220    value.strip_prefix(b"+").is_some_and(e164_digits)
221}
222
223/// `Phone::normalize()`: `rawurldecode()`, then a leading space (a `+` a query string decoded
224/// as a space) or no `+` at all before 7 to 15 digits becomes a `+`.
225pub fn phone_normalize(value: &[u8]) -> Vec<u8> {
226    let value = php_std::encoding::rawurldecode(value);
227    if value.strip_prefix(b" ").is_some_and(e164_digits) {
228        let mut normalized = b"+".to_vec();
229        normalized.extend_from_slice(&value[1..]);
230        return normalized;
231    }
232    if !value.is_empty() && !value.starts_with(b"+") && e164_digits(&value) {
233        let mut normalized = b"+".to_vec();
234        normalized.extend_from_slice(&value);
235        return normalized;
236    }
237    value
238}
239
240#[cfg(test)]
241mod tests {
242    use super::*;
243
244    #[test]
245    fn phone_pattern_matches_pcre() {
246        assert!(phone(b"+1234567"));
247        assert!(phone(b"+1234567\n"));
248        assert!(!phone(b"+1234567\n\n"));
249        assert!(!phone(b"+0234567"));
250        assert!(!phone(b"+123456"));
251        assert!(phone(b"+123456789012345"));
252        assert!(!phone(b"+1234567890123456"));
253        assert_eq!(phone_normalize(b"%2B1234567"), b"+1234567");
254        assert_eq!(phone_normalize(b" 1234567"), b"+1234567");
255        assert_eq!(phone_normalize(b" 1234567\n"), b"+1234567\n");
256        assert_eq!(phone_normalize(b"1234567"), b"+1234567");
257        assert_eq!(phone_normalize(b"0234567"), b"0234567");
258    }
259
260    #[test]
261    fn hostname_shape_and_wildcards() {
262        assert!(hostname(b"a.b"));
263        assert!(!hostname(b"0"));
264        assert!(!hostname(b"a/b"));
265        assert!(!hostname(b"a:1"));
266        assert!(hostname_allowed(b"x.a.com", b"*.a.com"));
267        assert!(!hostname_allowed(b"a.com", b"*.a.com"));
268        assert!(hostname_allowed(b"anything", b"*"));
269    }
270
271    #[test]
272    fn url_ascii_encodes_high_bytes() {
273        assert_eq!(&*url_ascii("https://e.com/č".as_bytes()), b"https://e.com/%C4%8D");
274    }
275}