Skip to main content

utopia_validators/
compose.rs

1//! The composing validators' own logic: what `ArrayList`, `Assoc`, `JSON`,
2//! `JSON\ArrayValidator`, `JSON\ObjectValidator`, `JSON\FCM` and `Globstar` decide by
3//! themselves. Asking the validators they wrap, and the PHP functions whose state is
4//! observable (`json_decode()` and `json_last_error()`, `preg_match()` and its warnings,
5//! `filter_var()`), is left to the PHP engine.
6
7use crate::decimal;
8
9/// `Assoc::getDescription()`.
10pub const ASSOC_DESCRIPTION: &str = "Value must be a valid object.";
11
12/// `JSON::getDescription()`.
13pub const JSON_DESCRIPTION: &str = "Value must be a valid JSON string";
14
15/// `Globstar::getDescription()`.
16pub const GLOBSTAR_DESCRIPTION: &str =
17    "Value must match a specific inclusion, or a wildcard inclusion not overridden by any exclusion.";
18
19/// `FCM::getDescription()` before a check has failed.
20pub const FCM_DESCRIPTION: &str = "Value must be valid Google service account JSON for FCM";
21
22/// `ArrayList::getDescription()`: `item` is the wrapped validator's description, `None` when
23/// it is `''` or `'0'` (which PHP leaves out).
24///
25/// Appended to `message`.
26pub fn array_list_description(length: i64, item: Option<&[u8]>, message: &mut Vec<u8>) {
27    message.extend_from_slice(b"Value must a valid array");
28    if length > 0 {
29        message.extend_from_slice(b" no longer than ");
30        decimal(length, message);
31        message.extend_from_slice(b" items");
32    }
33    if let Some(item) = item {
34        message.extend_from_slice(b" and ");
35        message.extend_from_slice(item);
36    }
37}
38
39/// `JSON\ArrayValidator::getDescription()`, appended to `message`.
40pub fn json_array_description(length: i64, message: &mut Vec<u8>) {
41    json_description("Value must be a valid JSON array", length, message);
42}
43
44/// `JSON\ObjectValidator::getDescription()`, appended to `message`.
45pub fn json_object_description(length: i64, message: &mut Vec<u8>) {
46    json_description("Value must be a valid JSON object", length, message);
47}
48
49fn json_description(prefix: &str, length: i64, message: &mut Vec<u8>) {
50    message.extend_from_slice(prefix.as_bytes());
51    if length > 0 {
52        message.extend_from_slice(b" no longer than ");
53        decimal(length, message);
54        message.extend_from_slice(b" characters when encoded");
55    }
56}
57
58/// `hasValidLength()` of the JSON validators: `encoded` is `None` for `false`.
59pub fn json_length(length: i64, encoded: Option<&[u8]>) -> bool {
60    if length == 0 {
61        return true;
62    }
63    encoded.is_some_and(|encoded| i64::try_from(encoded.len()).is_ok_and(|len| len <= length))
64}
65
66/// PHP `trim($value)`: the default characters (`" \t\n\r\0\x0B"`) from both ends.
67pub fn trim(value: &[u8]) -> &[u8] {
68    const WHITESPACE: &[u8] = b" \t\n\r\0\x0B";
69    let start = value.iter().position(|b| !WHITESPACE.contains(b)).unwrap_or(value.len());
70    let end = value.iter().rposition(|b| !WHITESPACE.contains(b)).map_or(start, |i| i + 1);
71    &value[start..end]
72}
73
74/// `FCM::isNonEmptyString()` of a string.
75pub fn non_empty(value: &[u8]) -> bool {
76    !trim(value).is_empty()
77}
78
79/// `FCM::REQUIRED_FIELDS`: each field and what it is for, in PHP's order.
80pub const FCM_REQUIRED: [(&str, &str); 5] = [
81    ("type", "identifies the credentials as a Google service account"),
82    ("project_id", "identifies the Firebase project receiving messages"),
83    ("private_key", "signs the OAuth access-token request"),
84    ("client_email", "identifies the service account used for authentication"),
85    ("token_uri", "identifies the OAuth token endpoint"),
86];
87
88/// `FCM::OPTIONAL_FIELDS`.
89pub const FCM_OPTIONAL: [&str; 6] = [
90    "private_key_id",
91    "client_id",
92    "auth_uri",
93    "auth_provider_x509_cert_url",
94    "client_x509_cert_url",
95    "universe_domain",
96];
97
98/// `FCM::URL_FIELDS`.
99pub const FCM_URL: [&str; 4] = ["auth_uri", "token_uri", "auth_provider_x509_cert_url", "client_x509_cert_url"];
100
101/// The error `FCM::isValid()` records for a required field that is missing or blank.
102pub fn fcm_required_error(field: &str, purpose: &str) -> String {
103    format!("FCM service account JSON must include a non-empty '{field}' field, which {purpose}.")
104}
105
106/// The error for an optional field given but not a non-empty string.
107pub fn fcm_optional_error(field: &str) -> String {
108    format!("FCM service account JSON field '{field}' must be a non-empty string when provided.")
109}
110
111/// The error for a `type` other than `service_account`.
112pub const FCM_TYPE_ERROR: &str = "FCM service account JSON field 'type' must be 'service_account'.";
113/// The error for a `client_email` `filter_var()` refuses.
114pub const FCM_EMAIL_ERROR: &str = "FCM service account JSON field 'client_email' must contain a valid email address.";
115/// The error for a `private_key` that is not PEM.
116pub const FCM_KEY_ERROR: &str = "FCM service account JSON field 'private_key' must contain a PEM-encoded private key.";
117
118/// The error for a URL field that is not an HTTPS URL.
119pub fn fcm_url_error(field: &str) -> String {
120    format!("FCM service account JSON field '{field}' must contain a valid HTTPS URL.")
121}
122
123/// The first line of a PEM private key.
124pub const PEM_BEGIN: &str = concat!("-----", "BEGIN PRIVATE", " KEY-----");
125/// The last line of a PEM private key.
126pub const PEM_END: &str = concat!("-----", "END PRIVATE", " KEY-----");
127
128/// `str_starts_with($key, PEM_BEGIN) && str_ends_with(trim($key), PEM_END)`.
129pub fn pem_private_key(key: &[u8]) -> bool {
130    key.starts_with(PEM_BEGIN.as_bytes()) && trim(key).ends_with(PEM_END.as_bytes())
131}
132
133/// PHP `strtolower($scheme) === 'https'` (ASCII lowercasing, as PHP 8 does).
134pub fn https_scheme(scheme: &[u8]) -> bool {
135    scheme.eq_ignore_ascii_case(b"https")
136}
137
138/// PHP `preg_quote($value, '~')` of one byte, appended to `out`.
139fn quote(out: &mut Vec<u8>, byte: u8) {
140    match byte {
141        b'.' | b'\\' | b'+' | b'*' | b'?' | b'[' | b'^' | b']' | b'$' | b'(' | b')' | b'{' | b'}' | b'=' | b'!'
142        | b'>' | b'<' | b'|' | b':' | b'-' | b'#' | b'~' => {
143            out.push(b'\\');
144            out.push(byte);
145        }
146        0 => out.extend_from_slice(b"\\000"),
147        _ => out.push(byte),
148    }
149}
150
151/// PHP `preg_quote($value, '~')`.
152pub fn preg_quote(value: &[u8]) -> Vec<u8> {
153    let mut out = Vec::with_capacity(value.len());
154    for &byte in value {
155        quote(&mut out, byte);
156    }
157    out
158}
159
160/// Whether a `Globstar` pattern is an exclusion (`!…`).
161pub fn exclusion(pattern: &[u8]) -> bool {
162    pattern.starts_with(b"!")
163}
164
165/// Whether a `Globstar` pattern holds a wildcard (`*`, `?` or `[`).
166pub fn wildcard(pattern: &[u8]) -> bool {
167    pattern.iter().any(|b| matches!(b, b'*' | b'?' | b'['))
168}
169
170/// The regular expression `Globstar::matchGlobstar()` hands `preg_match()` for `pattern`,
171/// delimiters and anchors included (`~^…$~`).
172pub fn globstar_regex(pattern: &[u8]) -> Vec<u8> {
173    let len = pattern.len();
174    let mut regex = b"~^".to_vec();
175    let mut i = 0;
176    while i < len {
177        let char = pattern[i];
178        if char == b'\\' && i + 1 < len {
179            quote(&mut regex, pattern[i + 1]);
180            i += 2;
181        } else if char == b'[' {
182            let mut j = i + 1;
183            let mut content = Vec::new();
184            let mut negated = false;
185            // A negation marker (`!` or `^`), unless `]` follows it: `[!]` and `[^]` hold it.
186            if j < len && (pattern[j] == b'!' || pattern[j] == b'^') {
187                let marker = pattern[j];
188                j += 1;
189                if !(j < len && pattern[j] == b']') {
190                    negated = true;
191                }
192                content.push(marker);
193            }
194            // `]` first in the class (or first after the negation marker) is a member.
195            if j < len && pattern[j] == b']' && (content.is_empty() || negated) {
196                content.push(b']');
197                j += 1;
198            }
199            while j < len && pattern[j] != b']' {
200                content.push(pattern[j]);
201                j += 1;
202            }
203            if j < len {
204                regex.push(b'[');
205                if negated && content.first() == Some(&b'!') {
206                    regex.push(b'^');
207                    regex.extend_from_slice(&content[1..]);
208                } else if !negated && content.first() == Some(&b'^') {
209                    regex.extend_from_slice(b"\\^");
210                    regex.extend_from_slice(&content[1..]);
211                } else {
212                    regex.extend_from_slice(&content);
213                }
214                regex.push(b']');
215                i = j + 1;
216            } else {
217                // An unclosed class: `[` is a literal.
218                quote(&mut regex, b'[');
219                i += 1;
220            }
221        } else if char == b'*' && i + 1 < len && pattern[i + 1] == b'*' {
222            let after_slash = i == 0 || pattern[i - 1] == b'/';
223            let before_slash = i + 2 < len && pattern[i + 2] == b'/';
224            if after_slash && before_slash {
225                // `a/**/b`: any number of directories between.
226                regex.extend_from_slice(b"(?:.+/)?");
227                i += 3;
228            } else {
229                regex.extend_from_slice(b".*");
230                i += 2;
231            }
232        } else if char == b'*' {
233            regex.extend_from_slice(b"[^/]*");
234            i += 1;
235        } else if char == b'?' {
236            regex.extend_from_slice(b"[^/]");
237            i += 1;
238        } else {
239            quote(&mut regex, char);
240            i += 1;
241        }
242    }
243    regex.extend_from_slice(b"$~");
244    regex
245}
246
247#[cfg(test)]
248mod tests {
249    use super::*;
250
251    #[test]
252    fn regexes() {
253        assert_eq!(globstar_regex(b"a/**/b"), b"~^a/(?:.+/)?b$~");
254        assert_eq!(globstar_regex(b"**"), b"~^.*$~");
255        assert_eq!(globstar_regex(b"*.md"), b"~^[^/]*\\.md$~");
256        assert_eq!(globstar_regex(b"[!a]?"), b"~^[^a][^/]$~");
257        assert_eq!(globstar_regex(b"[!]"), b"~^[!]$~");
258        assert_eq!(globstar_regex(b"[^]"), b"~^[\\^]$~");
259        assert_eq!(globstar_regex(b"[]a]"), b"~^[]a]$~");
260        assert_eq!(globstar_regex(b"[!]a]"), b"~^[!]a\\]$~");
261        assert_eq!(globstar_regex(b"[abc"), b"~^\\[abc$~");
262        assert_eq!(globstar_regex(b"\\*"), b"~^\\*$~");
263        assert_eq!(globstar_regex(b"a\\"), b"~^a\\\\$~");
264        assert_eq!(globstar_regex(b"\0~"), b"~^\\000\\~$~");
265    }
266
267    #[test]
268    fn helpers() {
269        assert_eq!(trim(b" \t\x0Bab\0 "), b"ab");
270        assert_eq!(trim(b"  "), b"");
271        assert!(!non_empty(b" \n"));
272        let key = format!("{PEM_BEGIN}\nx\n{PEM_END}\n");
273        assert!(pem_private_key(key.as_bytes()));
274        assert!(!pem_private_key(format!(" {PEM_BEGIN}{PEM_END}").as_bytes()));
275        assert!(json_length(0, None));
276        assert!(!json_length(3, None));
277        assert!(json_length(3, Some(b"[1]")));
278        assert!(!json_length(2, Some(b"[1]")));
279        let mut out = Vec::new();
280        array_list_description(0, None, &mut out);
281        assert_eq!(out, b"Value must a valid array");
282        out.clear();
283        array_list_description(2, Some(b"x"), &mut out);
284        assert_eq!(out, b"Value must a valid array no longer than 2 items and x");
285        out.clear();
286        json_object_description(1024, &mut out);
287        assert_eq!(out, b"Value must be a valid JSON object no longer than 1024 characters when encoded");
288    }
289}