use crate::decimal;
pub const ASSOC_DESCRIPTION: &str = "Value must be a valid object.";
pub const JSON_DESCRIPTION: &str = "Value must be a valid JSON string";
pub const GLOBSTAR_DESCRIPTION: &str =
"Value must match a specific inclusion, or a wildcard inclusion not overridden by any exclusion.";
pub const FCM_DESCRIPTION: &str = "Value must be valid Google service account JSON for FCM";
pub fn array_list_description(length: i64, item: Option<&[u8]>, message: &mut Vec<u8>) {
message.extend_from_slice(b"Value must a valid array");
if length > 0 {
message.extend_from_slice(b" no longer than ");
decimal(length, message);
message.extend_from_slice(b" items");
}
if let Some(item) = item {
message.extend_from_slice(b" and ");
message.extend_from_slice(item);
}
}
pub fn json_array_description(length: i64, message: &mut Vec<u8>) {
json_description("Value must be a valid JSON array", length, message);
}
pub fn json_object_description(length: i64, message: &mut Vec<u8>) {
json_description("Value must be a valid JSON object", length, message);
}
fn json_description(prefix: &str, length: i64, message: &mut Vec<u8>) {
message.extend_from_slice(prefix.as_bytes());
if length > 0 {
message.extend_from_slice(b" no longer than ");
decimal(length, message);
message.extend_from_slice(b" characters when encoded");
}
}
pub fn json_length(length: i64, encoded: Option<&[u8]>) -> bool {
if length == 0 {
return true;
}
encoded.is_some_and(|encoded| i64::try_from(encoded.len()).is_ok_and(|len| len <= length))
}
pub fn trim(value: &[u8]) -> &[u8] {
const WHITESPACE: &[u8] = b" \t\n\r\0\x0B";
let start = value.iter().position(|b| !WHITESPACE.contains(b)).unwrap_or(value.len());
let end = value.iter().rposition(|b| !WHITESPACE.contains(b)).map_or(start, |i| i + 1);
&value[start..end]
}
pub fn non_empty(value: &[u8]) -> bool {
!trim(value).is_empty()
}
pub const FCM_REQUIRED: [(&str, &str); 5] = [
("type", "identifies the credentials as a Google service account"),
("project_id", "identifies the Firebase project receiving messages"),
("private_key", "signs the OAuth access-token request"),
("client_email", "identifies the service account used for authentication"),
("token_uri", "identifies the OAuth token endpoint"),
];
pub const FCM_OPTIONAL: [&str; 6] = [
"private_key_id",
"client_id",
"auth_uri",
"auth_provider_x509_cert_url",
"client_x509_cert_url",
"universe_domain",
];
pub const FCM_URL: [&str; 4] = ["auth_uri", "token_uri", "auth_provider_x509_cert_url", "client_x509_cert_url"];
pub fn fcm_required_error(field: &str, purpose: &str) -> String {
format!("FCM service account JSON must include a non-empty '{field}' field, which {purpose}.")
}
pub fn fcm_optional_error(field: &str) -> String {
format!("FCM service account JSON field '{field}' must be a non-empty string when provided.")
}
pub const FCM_TYPE_ERROR: &str = "FCM service account JSON field 'type' must be 'service_account'.";
pub const FCM_EMAIL_ERROR: &str = "FCM service account JSON field 'client_email' must contain a valid email address.";
pub const FCM_KEY_ERROR: &str = "FCM service account JSON field 'private_key' must contain a PEM-encoded private key.";
pub fn fcm_url_error(field: &str) -> String {
format!("FCM service account JSON field '{field}' must contain a valid HTTPS URL.")
}
pub const PEM_BEGIN: &str = concat!("-----", "BEGIN PRIVATE", " KEY-----");
pub const PEM_END: &str = concat!("-----", "END PRIVATE", " KEY-----");
pub fn pem_private_key(key: &[u8]) -> bool {
key.starts_with(PEM_BEGIN.as_bytes()) && trim(key).ends_with(PEM_END.as_bytes())
}
pub fn https_scheme(scheme: &[u8]) -> bool {
scheme.eq_ignore_ascii_case(b"https")
}
fn quote(out: &mut Vec<u8>, byte: u8) {
match byte {
b'.' | b'\\' | b'+' | b'*' | b'?' | b'[' | b'^' | b']' | b'$' | b'(' | b')' | b'{' | b'}' | b'=' | b'!'
| b'>' | b'<' | b'|' | b':' | b'-' | b'#' | b'~' => {
out.push(b'\\');
out.push(byte);
}
0 => out.extend_from_slice(b"\\000"),
_ => out.push(byte),
}
}
pub fn preg_quote(value: &[u8]) -> Vec<u8> {
let mut out = Vec::with_capacity(value.len());
for &byte in value {
quote(&mut out, byte);
}
out
}
pub fn exclusion(pattern: &[u8]) -> bool {
pattern.starts_with(b"!")
}
pub fn wildcard(pattern: &[u8]) -> bool {
pattern.iter().any(|b| matches!(b, b'*' | b'?' | b'['))
}
pub fn globstar_regex(pattern: &[u8]) -> Vec<u8> {
let len = pattern.len();
let mut regex = b"~^".to_vec();
let mut i = 0;
while i < len {
let char = pattern[i];
if char == b'\\' && i + 1 < len {
quote(&mut regex, pattern[i + 1]);
i += 2;
} else if char == b'[' {
let mut j = i + 1;
let mut content = Vec::new();
let mut negated = false;
if j < len && (pattern[j] == b'!' || pattern[j] == b'^') {
let marker = pattern[j];
j += 1;
if !(j < len && pattern[j] == b']') {
negated = true;
}
content.push(marker);
}
if j < len && pattern[j] == b']' && (content.is_empty() || negated) {
content.push(b']');
j += 1;
}
while j < len && pattern[j] != b']' {
content.push(pattern[j]);
j += 1;
}
if j < len {
regex.push(b'[');
if negated && content.first() == Some(&b'!') {
regex.push(b'^');
regex.extend_from_slice(&content[1..]);
} else if !negated && content.first() == Some(&b'^') {
regex.extend_from_slice(b"\\^");
regex.extend_from_slice(&content[1..]);
} else {
regex.extend_from_slice(&content);
}
regex.push(b']');
i = j + 1;
} else {
quote(&mut regex, b'[');
i += 1;
}
} else if char == b'*' && i + 1 < len && pattern[i + 1] == b'*' {
let after_slash = i == 0 || pattern[i - 1] == b'/';
let before_slash = i + 2 < len && pattern[i + 2] == b'/';
if after_slash && before_slash {
regex.extend_from_slice(b"(?:.+/)?");
i += 3;
} else {
regex.extend_from_slice(b".*");
i += 2;
}
} else if char == b'*' {
regex.extend_from_slice(b"[^/]*");
i += 1;
} else if char == b'?' {
regex.extend_from_slice(b"[^/]");
i += 1;
} else {
quote(&mut regex, char);
i += 1;
}
}
regex.extend_from_slice(b"$~");
regex
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn regexes() {
assert_eq!(globstar_regex(b"a/**/b"), b"~^a/(?:.+/)?b$~");
assert_eq!(globstar_regex(b"**"), b"~^.*$~");
assert_eq!(globstar_regex(b"*.md"), b"~^[^/]*\\.md$~");
assert_eq!(globstar_regex(b"[!a]?"), b"~^[^a][^/]$~");
assert_eq!(globstar_regex(b"[!]"), b"~^[!]$~");
assert_eq!(globstar_regex(b"[^]"), b"~^[\\^]$~");
assert_eq!(globstar_regex(b"[]a]"), b"~^[]a]$~");
assert_eq!(globstar_regex(b"[!]a]"), b"~^[!]a\\]$~");
assert_eq!(globstar_regex(b"[abc"), b"~^\\[abc$~");
assert_eq!(globstar_regex(b"\\*"), b"~^\\*$~");
assert_eq!(globstar_regex(b"a\\"), b"~^a\\\\$~");
assert_eq!(globstar_regex(b"\0~"), b"~^\\000\\~$~");
}
#[test]
fn helpers() {
assert_eq!(trim(b" \t\x0Bab\0 "), b"ab");
assert_eq!(trim(b" "), b"");
assert!(!non_empty(b" \n"));
let key = format!("{PEM_BEGIN}\nx\n{PEM_END}\n");
assert!(pem_private_key(key.as_bytes()));
assert!(!pem_private_key(format!(" {PEM_BEGIN}{PEM_END}").as_bytes()));
assert!(json_length(0, None));
assert!(!json_length(3, None));
assert!(json_length(3, Some(b"[1]")));
assert!(!json_length(2, Some(b"[1]")));
let mut out = Vec::new();
array_list_description(0, None, &mut out);
assert_eq!(out, b"Value must a valid array");
out.clear();
array_list_description(2, Some(b"x"), &mut out);
assert_eq!(out, b"Value must a valid array no longer than 2 items and x");
out.clear();
json_object_description(1024, &mut out);
assert_eq!(out, b"Value must be a valid JSON object no longer than 1024 characters when encoded");
}
}