utopia_validators/
compose.rs1use crate::decimal;
8
9pub const ASSOC_DESCRIPTION: &str = "Value must be a valid object.";
11
12pub const JSON_DESCRIPTION: &str = "Value must be a valid JSON string";
14
15pub const GLOBSTAR_DESCRIPTION: &str =
17 "Value must match a specific inclusion, or a wildcard inclusion not overridden by any exclusion.";
18
19pub const FCM_DESCRIPTION: &str = "Value must be valid Google service account JSON for FCM";
21
22pub 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
39pub fn json_array_description(length: i64, message: &mut Vec<u8>) {
41 json_description("Value must be a valid JSON array", length, message);
42}
43
44pub 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
58pub 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
66pub 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
74pub fn non_empty(value: &[u8]) -> bool {
76 !trim(value).is_empty()
77}
78
79pub 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
88pub 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
98pub const FCM_URL: [&str; 4] = ["auth_uri", "token_uri", "auth_provider_x509_cert_url", "client_x509_cert_url"];
100
101pub 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
106pub 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
111pub const FCM_TYPE_ERROR: &str = "FCM service account JSON field 'type' must be 'service_account'.";
113pub const FCM_EMAIL_ERROR: &str = "FCM service account JSON field 'client_email' must contain a valid email address.";
115pub const FCM_KEY_ERROR: &str = "FCM service account JSON field 'private_key' must contain a PEM-encoded private key.";
117
118pub fn fcm_url_error(field: &str) -> String {
120 format!("FCM service account JSON field '{field}' must contain a valid HTTPS URL.")
121}
122
123pub const PEM_BEGIN: &str = concat!("-----", "BEGIN PRIVATE", " KEY-----");
125pub const PEM_END: &str = concat!("-----", "END PRIVATE", " KEY-----");
127
128pub 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
133pub fn https_scheme(scheme: &[u8]) -> bool {
135 scheme.eq_ignore_ascii_case(b"https")
136}
137
138fn 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
151pub 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
160pub fn exclusion(pattern: &[u8]) -> bool {
162 pattern.starts_with(b"!")
163}
164
165pub fn wildcard(pattern: &[u8]) -> bool {
167 pattern.iter().any(|b| matches!(b, b'*' | b'?' | b'['))
168}
169
170pub 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 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 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 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 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}