Skip to main content

nitr_std/validate/
format.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2// This file is part of Nitr.
3// See https://nitrweb.com/ for more information
4// Copyright (C) 2024-present Jose Quintana <joseluisq.net>
5
6//! The string formats a rule can require: one careful, dependency-free
7//! Rust implementation each, plus the per-state registry of formats a
8//! script defines itself (`nitr.validate.format`).
9
10use std::collections::HashMap;
11use std::sync::Arc;
12
13use super::message::Template;
14
15/// String formats with one careful, dependency-free Rust implementation
16/// each: syntactic sanity checks, not full RFC validation.
17#[derive(Debug, Clone, Copy, PartialEq, Eq)]
18pub(crate) enum Format {
19    Email,
20    Uuid,
21    Ulid,
22    Url,
23    Domain,
24    Ip,
25    Ipv4,
26    Ipv6,
27    Cidr,
28    Mac,
29    Hostname,
30    Date,
31    Datetime,
32    Time,
33    Hex,
34    Base64,
35    Base64Url,
36    Alphanumeric,
37    Alpha,
38    Numeric,
39    AlphaDash,
40    Lowercase,
41    Uppercase,
42    Ascii,
43    Printable,
44    Slug,
45    Semver,
46    Phone,
47    CountryCode,
48    CurrencyCode,
49    LanguageTag,
50    CreditCard,
51    Iban,
52    HexColor,
53    Json,
54    Jwt,
55}
56
57/// Every recognized format, for the compile-time error message and the
58/// `nitr.validate.formats()` listing.
59pub(super) const FORMATS: &[(&str, Format)] = &[
60    ("alpha", Format::Alpha),
61    ("alpha_dash", Format::AlphaDash),
62    ("alphanumeric", Format::Alphanumeric),
63    ("ascii", Format::Ascii),
64    ("base64", Format::Base64),
65    ("base64url", Format::Base64Url),
66    ("cidr", Format::Cidr),
67    ("country_code", Format::CountryCode),
68    ("credit_card", Format::CreditCard),
69    ("currency_code", Format::CurrencyCode),
70    ("date", Format::Date),
71    ("datetime", Format::Datetime),
72    ("domain", Format::Domain),
73    ("email", Format::Email),
74    ("hex", Format::Hex),
75    ("hex_color", Format::HexColor),
76    ("hostname", Format::Hostname),
77    ("iban", Format::Iban),
78    ("ip", Format::Ip),
79    ("ipv4", Format::Ipv4),
80    ("ipv6", Format::Ipv6),
81    ("json", Format::Json),
82    ("jwt", Format::Jwt),
83    ("language_tag", Format::LanguageTag),
84    ("lowercase", Format::Lowercase),
85    ("mac", Format::Mac),
86    ("numeric", Format::Numeric),
87    ("phone", Format::Phone),
88    ("printable", Format::Printable),
89    ("semver", Format::Semver),
90    ("slug", Format::Slug),
91    ("time", Format::Time),
92    ("ulid", Format::Ulid),
93    ("uppercase", Format::Uppercase),
94    ("url", Format::Url),
95    ("uuid", Format::Uuid),
96];
97
98/// Checks `value` against the named built-in format, for the
99/// `validate-formats` fuzz target: `None` when no such format exists,
100/// else the verdict.
101///
102/// A function rather than a `pub` [`Format`] so the hand-rolled
103/// validators can be fuzzed without making the enum — and a doc comment
104/// per variant — part of any public surface.
105#[doc(hidden)]
106pub fn check_format(name: &str, value: &str) -> Option<bool> {
107    Format::parse(name).map(|format| format.check(value))
108}
109
110/// Every built-in format name [`check_format`] accepts.
111#[doc(hidden)]
112pub fn format_names() -> Vec<&'static str> {
113    FORMATS.iter().map(|(name, _)| *name).collect()
114}
115
116/// One DNS label: 1–63 chars, alphanumeric plus inner hyphens.
117fn is_hostname_label(label: &str) -> bool {
118    !label.is_empty()
119        && label.len() <= 63
120        && label.chars().all(|c| c.is_ascii_alphanumeric() || c == '-')
121        && !label.starts_with('-')
122        && !label.ends_with('-')
123}
124
125fn is_hostname(value: &str) -> bool {
126    !value.is_empty() && value.len() <= 253 && value.split('.').all(is_hostname_label)
127}
128
129/// Luhn checksum over a digit string.
130fn luhn(digits: &str) -> bool {
131    let mut sum = 0u32;
132    for (i, c) in digits.chars().rev().enumerate() {
133        let Some(d) = c.to_digit(10) else {
134            return false;
135        };
136        let d = if i % 2 == 1 {
137            let doubled = d * 2;
138            if doubled > 9 { doubled - 9 } else { doubled }
139        } else {
140            d
141        };
142        sum += d;
143    }
144    sum.is_multiple_of(10)
145}
146
147/// IBAN mod-97: rotate the first four characters to the end, map letters
148/// to `10..35`, and reduce iteratively so the number never overflows.
149fn iban_mod97(value: &str) -> bool {
150    let bytes = value.as_bytes();
151    if bytes.len() < 5 {
152        return false;
153    }
154    let rotated = bytes[4..].iter().chain(bytes[..4].iter());
155    let mut rem: u32 = 0;
156    for &b in rotated {
157        let piece: u32 = match b {
158            b'0'..=b'9' => u32::from(b - b'0'),
159            b'A'..=b'Z' => u32::from(b - b'A') + 10,
160            _ => return false,
161        };
162        rem = if piece >= 10 {
163            (rem * 100 + piece) % 97
164        } else {
165            (rem * 10 + piece) % 97
166        };
167    }
168    rem == 1
169}
170
171/// A semver numeric identifier: digits without a leading zero.
172fn semver_numeric(part: &str) -> bool {
173    !part.is_empty()
174        && part.bytes().all(|b| b.is_ascii_digit())
175        && (part == "0" || !part.starts_with('0'))
176}
177
178/// A semver prerelease or build identifier chain (`alpha.1`, `build.5`).
179fn semver_identifiers(part: &str, prerelease: bool) -> bool {
180    !part.is_empty()
181        && part.split('.').all(|id| {
182            !id.is_empty()
183                && id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-')
184                && (!prerelease || !id.bytes().all(|b| b.is_ascii_digit()) || semver_numeric(id))
185        })
186}
187
188fn is_semver(value: &str) -> bool {
189    let (core, build) = match value.split_once('+') {
190        Some((core, build)) => (core, Some(build)),
191        None => (value, None),
192    };
193    let (core, pre) = match core.split_once('-') {
194        Some((core, pre)) => (core, Some(pre)),
195        None => (core, None),
196    };
197    let mut parts = core.split('.');
198    let ok = matches!(
199        (parts.next(), parts.next(), parts.next(), parts.next()),
200        (Some(a), Some(b), Some(c), None) if semver_numeric(a) && semver_numeric(b) && semver_numeric(c)
201    );
202    ok && pre.is_none_or(|p| semver_identifiers(p, true))
203        && build.is_none_or(|b| semver_identifiers(b, false))
204}
205
206fn is_language_tag(value: &str) -> bool {
207    let mut parts = value.split('-');
208    let Some(lang) = parts.next() else {
209        return false;
210    };
211    if !(2..=3).contains(&lang.len()) || !lang.bytes().all(|b| b.is_ascii_alphabetic()) {
212        return false;
213    }
214    let is_region = |p: &str| {
215        (p.len() == 2 && p.bytes().all(|b| b.is_ascii_alphabetic()))
216            || (p.len() == 3 && p.bytes().all(|b| b.is_ascii_digit()))
217    };
218    let is_script = |p: &str| p.len() == 4 && p.bytes().all(|b| b.is_ascii_alphabetic());
219    match (parts.next(), parts.next(), parts.next()) {
220        (None, _, _) => true,
221        (Some(second), None, _) => is_script(second) || is_region(second),
222        (Some(second), Some(third), None) => is_script(second) && is_region(third),
223        _ => false,
224    }
225}
226
227fn is_base64url(value: &str) -> bool {
228    use base64::Engine as _;
229    let trimmed = value.trim_end_matches('=');
230    !trimmed.is_empty()
231        && base64::engine::general_purpose::URL_SAFE_NO_PAD
232            .decode(trimmed)
233            .is_ok()
234}
235
236impl Format {
237    pub(super) fn parse(name: &str) -> Option<Self> {
238        FORMATS
239            .iter()
240            .find(|(n, _)| *n == name)
241            .map(|(_, format)| *format)
242    }
243
244    /// The configuration name of the format.
245    pub(super) fn name(self) -> &'static str {
246        FORMATS
247            .iter()
248            .find(|(_, f)| *f == self)
249            .map(|(n, _)| *n)
250            .unwrap_or("format")
251    }
252
253    pub(super) fn check(self, value: &str) -> bool {
254        match self {
255            Self::Email => {
256                let Some((local, domain)) = value.split_once('@') else {
257                    return false;
258                };
259                !local.is_empty()
260                    && local.len() <= 64
261                    && domain.contains('.')
262                    && is_hostname(domain)
263                    && !local.contains(|c: char| c.is_whitespace() || c.is_control())
264            }
265            Self::Uuid => {
266                let groups: Vec<&str> = value.split('-').collect();
267                groups.len() == 5
268                    && groups
269                        .iter()
270                        .zip([8usize, 4, 4, 4, 12])
271                        .all(|(g, len)| g.len() == len && g.chars().all(|c| c.is_ascii_hexdigit()))
272            }
273            Self::Ulid => {
274                const ALPHABET: &[u8] = b"0123456789ABCDEFGHJKMNPQRSTVWXYZ";
275                value.len() == 26
276                    && value
277                        .bytes()
278                        .next()
279                        .is_some_and(|b| (b'0'..=b'7').contains(&b))
280                    && value
281                        .bytes()
282                        .all(|b| ALPHABET.contains(&b.to_ascii_uppercase()))
283            }
284            Self::Url => {
285                let rest = value
286                    .strip_prefix("http://")
287                    .or_else(|| value.strip_prefix("https://"));
288                matches!(rest, Some(rest) if !rest.is_empty() && !rest.starts_with('/'))
289                    && !value.contains(|c: char| c.is_whitespace() || c.is_control())
290            }
291            Self::Domain => {
292                is_hostname(value)
293                    && value.matches('.').count() >= 1
294                    && value
295                        .rsplit('.')
296                        .next()
297                        .is_some_and(|tld| tld.bytes().all(|b| b.is_ascii_alphabetic()))
298            }
299            Self::Ip => value.parse::<std::net::IpAddr>().is_ok(),
300            Self::Ipv4 => value.parse::<std::net::Ipv4Addr>().is_ok(),
301            Self::Ipv6 => value.parse::<std::net::Ipv6Addr>().is_ok(),
302            Self::Cidr => {
303                let Some((ip, prefix_text)) = value.split_once('/') else {
304                    return false;
305                };
306                let Ok(prefix) = prefix_text.parse::<u8>() else {
307                    return false;
308                };
309                // The prefix is written the one canonical way: no leading
310                // zero, no sign (`u8::parse` takes `+8`).
311                if prefix.to_string() != prefix_text {
312                    return false;
313                }
314                match ip.parse::<std::net::IpAddr>() {
315                    Ok(std::net::IpAddr::V4(_)) => prefix <= 32,
316                    Ok(std::net::IpAddr::V6(_)) => prefix <= 128,
317                    Err(_) => false,
318                }
319            }
320            Self::Mac => {
321                let sep = if value.contains(':') { ':' } else { '-' };
322                let groups: Vec<&str> = value.split(sep).collect();
323                groups.len() == 6
324                    && groups
325                        .iter()
326                        .all(|g| g.len() == 2 && g.chars().all(|c| c.is_ascii_hexdigit()))
327            }
328            Self::Hostname => is_hostname(value),
329            Self::Date => chrono::NaiveDate::parse_from_str(value, "%Y-%m-%d").is_ok(),
330            Self::Datetime => chrono::DateTime::parse_from_rfc3339(value).is_ok(),
331            Self::Time => parse_time(value).is_some(),
332            Self::Hex => !value.is_empty() && value.chars().all(|c| c.is_ascii_hexdigit()),
333            Self::Base64 => {
334                use base64::Engine as _;
335                !value.is_empty()
336                    && base64::engine::general_purpose::STANDARD
337                        .decode(value)
338                        .is_ok()
339            }
340            Self::Base64Url => is_base64url(value),
341            Self::Alphanumeric => {
342                !value.is_empty() && value.chars().all(|c| c.is_ascii_alphanumeric())
343            }
344            Self::Alpha => !value.is_empty() && value.chars().all(|c| c.is_ascii_alphabetic()),
345            Self::Numeric => !value.is_empty() && value.chars().all(|c| c.is_ascii_digit()),
346            Self::AlphaDash => {
347                !value.is_empty()
348                    && value
349                        .chars()
350                        .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
351            }
352            Self::Lowercase => !value.is_empty() && !value.chars().any(char::is_uppercase),
353            Self::Uppercase => !value.is_empty() && !value.chars().any(char::is_lowercase),
354            Self::Ascii => !value.is_empty() && value.is_ascii(),
355            Self::Printable => !value.is_empty() && !value.chars().any(char::is_control),
356            Self::Slug => {
357                !value.is_empty()
358                    && value
359                        .chars()
360                        .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')
361                    && !value.starts_with('-')
362                    && !value.ends_with('-')
363            }
364            Self::Semver => is_semver(value),
365            Self::Phone => {
366                let Some(digits) = value.strip_prefix('+') else {
367                    return false;
368                };
369                (8..=15).contains(&digits.len()) && digits.bytes().all(|b| b.is_ascii_digit())
370            }
371            Self::CountryCode => value.len() == 2 && value.bytes().all(|b| b.is_ascii_uppercase()),
372            Self::CurrencyCode => value.len() == 3 && value.bytes().all(|b| b.is_ascii_uppercase()),
373            Self::LanguageTag => is_language_tag(value),
374            Self::CreditCard => {
375                let digits: String = value.chars().filter(|c| *c != ' ' && *c != '-').collect();
376                (12..=19).contains(&digits.len())
377                    && digits.bytes().all(|b| b.is_ascii_digit())
378                    && luhn(&digits)
379            }
380            Self::Iban => {
381                (15..=34).contains(&value.len())
382                    && value.bytes().take(2).all(|b| b.is_ascii_uppercase())
383                    && value.bytes().skip(2).take(2).all(|b| b.is_ascii_digit())
384                    && value.bytes().all(|b| b.is_ascii_alphanumeric())
385                    && iban_mod97(value)
386            }
387            Self::HexColor => value.strip_prefix('#').is_some_and(|hex| {
388                matches!(hex.len(), 3 | 6 | 8) && hex.chars().all(|c| c.is_ascii_hexdigit())
389            }),
390            Self::Json => serde_json::from_str::<serde_json::Value>(value).is_ok(),
391            Self::Jwt => {
392                // Shape only, in linear time: three base64url segments,
393                // header and payload non-empty, the signature possibly
394                // empty (an unsecured JWS). Verification is `nitr.jwt`'s
395                // job, not a format's.
396                let alphabet = |p: &str| {
397                    p.bytes()
398                        .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
399                };
400                let parts: Vec<&str> = value.split('.').collect();
401                parts.len() == 3
402                    && parts[..2].iter().all(|p| !p.is_empty() && alphabet(p))
403                    && alphabet(parts[2])
404            }
405        }
406    }
407
408    /// The noun phrase completing "must be …".
409    pub(super) fn describe(self) -> &'static str {
410        match self {
411            Self::Email => "an email address",
412            Self::Uuid => "a UUID",
413            Self::Ulid => "a ULID",
414            Self::Url => "an http(s) URL",
415            Self::Domain => "a domain name",
416            Self::Ip => "an IP address",
417            Self::Ipv4 => "an IPv4 address",
418            Self::Ipv6 => "an IPv6 address",
419            Self::Cidr => "an IP range in CIDR notation",
420            Self::Mac => "a MAC address",
421            Self::Hostname => "a hostname",
422            Self::Date => "a date (YYYY-MM-DD)",
423            Self::Datetime => "an RFC 3339 datetime",
424            Self::Time => "a time (HH:MM or HH:MM:SS)",
425            Self::Hex => "a hex string",
426            Self::Base64 => "a base64 string",
427            Self::Base64Url => "a URL-safe base64 string",
428            Self::Alphanumeric => "letters and digits only",
429            Self::Alpha => "letters only",
430            Self::Numeric => "digits only",
431            Self::AlphaDash => "letters, digits, hyphens or underscores",
432            Self::Lowercase => "lowercase",
433            Self::Uppercase => "uppercase",
434            Self::Ascii => "ASCII text",
435            Self::Printable => "printable text",
436            Self::Slug => "a slug (lowercase letters, digits, hyphens)",
437            Self::Semver => "a semantic version",
438            Self::Phone => "a phone number in E.164 form (+ and digits)",
439            Self::CountryCode => "a two-letter country code",
440            Self::CurrencyCode => "a three-letter currency code",
441            Self::LanguageTag => "a language tag (en, en-US)",
442            Self::CreditCard => "a valid card number",
443            Self::Iban => "a valid IBAN",
444            Self::HexColor => "a hex color (#RGB, #RRGGBB or #RRGGBBAA)",
445            Self::Json => "valid JSON",
446            Self::Jwt => "a JWT",
447        }
448    }
449}
450
451/// Parses a 24-hour time in the shapes `HH:MM`, `HH:MM:SS`, `HH:MM:SS.frac`.
452pub(super) fn parse_time(value: &str) -> Option<chrono::NaiveTime> {
453    // `HH:MM`, `HH:MM:SS` or `HH:MM:SS.fff`: two digits each, no leap
454    // second (chrono would take `9:00` and `23:59:60`).
455    let two_digits = |p: &str| p.len() == 2 && p.bytes().all(|b| b.is_ascii_digit());
456    let mut parts = value.split(':');
457    let (Some(h), Some(m)) = (parts.next(), parts.next()) else {
458        return None;
459    };
460    if !two_digits(h) || !two_digits(m) {
461        return None;
462    }
463    if let Some(s) = parts.next() {
464        let (whole, frac) = s.split_once('.').unwrap_or((s, "0"));
465        if !two_digits(whole)
466            || whole >= "60"
467            || frac.is_empty()
468            || !frac.bytes().all(|b| b.is_ascii_digit())
469        {
470            return None;
471        }
472    }
473    if parts.next().is_some() {
474        return None;
475    }
476    ["%H:%M:%S%.f", "%H:%M:%S", "%H:%M"]
477        .iter()
478        .find_map(|fmt| chrono::NaiveTime::parse_from_str(value, fmt).ok())
479}
480
481/// A script-defined format (`nitr.validate.format(name, {...})`).
482#[derive(Debug)]
483pub(crate) struct CustomFormat {
484    pub(crate) name: String,
485    /// Documentation only: emitted by the API description, never read
486    /// by the checker.
487    pub(crate) description: String,
488    pub(crate) message: Option<Template>,
489    pub(crate) check: mlua::Function,
490    /// Documentation only: emitted by the API description, never executed.
491    pub(crate) pattern: Option<String>,
492    pub(crate) example: Option<String>,
493}
494
495/// What the document says about a script-defined format.
496#[derive(Debug, Clone, PartialEq, Eq)]
497pub struct CustomFormatInfo {
498    /// The name a rule's `format` key refers to.
499    pub name: String,
500    /// What the check enforces, in the author's words.
501    pub description: String,
502    /// The advisory pattern, when the registration gave one.
503    pub pattern: Option<String>,
504    /// An example value, when the registration gave one.
505    pub example: Option<String>,
506}
507
508/// Every custom format registered in this state, sorted by name, for the
509/// document's `x-nitr-formats` vocabulary.
510pub fn custom_formats(lua: &mlua::Lua) -> Vec<CustomFormatInfo> {
511    let mut out: Vec<CustomFormatInfo> = lua
512        .app_data_ref::<FormatRegistry>()
513        .map(|registry| {
514            registry
515                .formats
516                .values()
517                .map(|f| CustomFormatInfo {
518                    name: f.name.clone(),
519                    description: f.description.clone(),
520                    pattern: f.pattern.clone(),
521                    example: f.example.clone(),
522                })
523                .collect()
524        })
525        .unwrap_or_default();
526    out.sort_by(|a, b| a.name.cmp(&b.name));
527    out
528}
529
530/// The per-state registry of custom formats, kept in the Lua app data.
531#[derive(Debug, Default)]
532pub(crate) struct FormatRegistry {
533    pub(crate) formats: HashMap<String, Arc<CustomFormat>>,
534}
535
536/// A rule's format: built in, or one the script registered.
537#[derive(Debug, Clone)]
538pub(crate) enum FormatRule {
539    Builtin(Format),
540    Custom(Arc<CustomFormat>),
541}
542
543impl FormatRule {
544    pub(crate) fn name(&self) -> &str {
545        match self {
546            Self::Builtin(f) => f.name(),
547            Self::Custom(c) => &c.name,
548        }
549    }
550
551    /// Looks a name up: built-ins first, then the state's registry.
552    pub(crate) fn resolve(lua: &mlua::Lua, name: &str) -> Option<Self> {
553        if let Some(builtin) = Format::parse(name) {
554            return Some(Self::Builtin(builtin));
555        }
556        let registry = lua.app_data_ref::<FormatRegistry>()?;
557        registry.formats.get(name).cloned().map(Self::Custom)
558    }
559}
560
561/// Every format name a schema in this state may use, sorted.
562pub(crate) fn all_format_names(lua: &mlua::Lua) -> Vec<String> {
563    let mut names: Vec<String> = format_names().into_iter().map(String::from).collect();
564    if let Some(registry) = lua.app_data_ref::<FormatRegistry>() {
565        names.extend(registry.formats.keys().cloned());
566    }
567    names.sort();
568    names
569}