Skip to main content

pactum_annotations/
formats.rs

1use crate::error::FieldIssue;
2
3/// Canonical lowercase/uppercase hyphenated UUID (`8-4-4-4-12` hex digits).
4pub fn check_uuid(field: &str, value: &str) -> Result<(), FieldIssue> {
5    let bytes = value.as_bytes();
6    if bytes.len() != 36 {
7        return Err(FieldIssue::new(
8            field,
9            "INVALID_UUID",
10            "must be a canonical UUID (8-4-4-4-12)",
11        ));
12    }
13    for (idx, &b) in bytes.iter().enumerate() {
14        let expect_dash = matches!(idx, 8 | 13 | 18 | 23);
15        if expect_dash {
16            if b != b'-' {
17                return Err(FieldIssue::new(
18                    field,
19                    "INVALID_UUID",
20                    "must be a canonical UUID (8-4-4-4-12)",
21                ));
22            }
23        } else if !b.is_ascii_hexdigit() {
24            return Err(FieldIssue::new(
25                field,
26                "INVALID_UUID",
27                "must be a canonical UUID (8-4-4-4-12)",
28            ));
29        }
30    }
31    Ok(())
32}
33
34/// Structural URL check (`http://` or `https://`, valid host and optional port, no whitespace/control chars).
35pub fn check_url(field: &str, value: &str, require_https: bool) -> Result<(), FieldIssue> {
36    if value.chars().any(|c| c.is_whitespace() || c.is_control()) {
37        return Err(FieldIssue::new(
38            field,
39            "INVALID_URL",
40            "url must not contain whitespace or control characters",
41        ));
42    }
43    let bytes = value.as_bytes();
44    let rest = if bytes.len() >= 8 && bytes[..8].eq_ignore_ascii_case(b"https://") {
45        &value[8..]
46    } else if !require_https && bytes.len() >= 7 && bytes[..7].eq_ignore_ascii_case(b"http://") {
47        &value[7..]
48    } else if require_https {
49        return Err(FieldIssue::new(
50            field,
51            "INVALID_URL",
52            "url must start with https://",
53        ));
54    } else {
55        return Err(FieldIssue::new(
56            field,
57            "INVALID_URL",
58            "url must start with http:// or https://",
59        ));
60    };
61
62    let authority = rest.split(['/', '?', '#']).next().unwrap_or("");
63    let host_port = if let Some((userinfo, hp)) = authority.split_once('@') {
64        if userinfo.is_empty()
65            || hp.contains('@')
66            || userinfo.bytes().any(|b| {
67                matches!(
68                    b,
69                    b'<' | b'>' | b'"' | b'{' | b'}' | b'|' | b'\\' | b'^' | b'`' | b'[' | b']'
70                )
71            })
72        {
73            return Err(FieldIssue::new(
74                field,
75                "INVALID_URL",
76                "url contains invalid authority userinfo",
77            ));
78        }
79        hp
80    } else {
81        authority
82    };
83
84    if !is_valid_url_host_port(host_port) {
85        return Err(FieldIssue::new(
86            field,
87            "INVALID_URL",
88            "url must include a valid host",
89        ));
90    }
91    Ok(())
92}
93
94fn is_valid_url_port(port: &str) -> bool {
95    !port.is_empty()
96        && port.bytes().all(|b| b.is_ascii_digit())
97        && matches!(port.parse::<u16>(), Ok(1..=u16::MAX))
98}
99
100fn is_valid_url_host_port(host_port: &str) -> bool {
101    if host_port.is_empty() {
102        return false;
103    }
104    if let Some(after_open) = host_port.strip_prefix('[') {
105        let Some((ipv6_lit, after_close)) = after_open.split_once(']') else {
106            return false;
107        };
108        if ipv6_lit.parse::<core::net::Ipv6Addr>().is_err() {
109            return false;
110        }
111        return match after_close.strip_prefix(':') {
112            Some(port) => is_valid_url_port(port),
113            None => after_close.is_empty(),
114        };
115    }
116
117    let (host, port) = match host_port.split_once(':') {
118        Some((h, p)) => (h, Some(p)),
119        None => (host_port, None),
120    };
121    if let Some(port) = port {
122        if !is_valid_url_port(port) {
123            return false;
124        }
125    }
126    if host.is_empty() || host.starts_with('.') || host.ends_with('.') || host.contains("..") {
127        return false;
128    }
129    if host.parse::<core::net::Ipv4Addr>().is_ok() {
130        return true;
131    }
132    for label in host.split('.') {
133        let b = label.as_bytes();
134        if b.is_empty()
135            || b.len() > 63
136            || b[0] == b'-'
137            || b[b.len() - 1] == b'-'
138            || !b
139                .iter()
140                .all(|&c| c.is_ascii_alphanumeric() || c == b'-' || c == b'_')
141        {
142            return false;
143        }
144    }
145    true
146}
147
148/// Lowercase ASCII slug: `[a-z0-9]` segments joined by single `-` characters.
149pub fn check_slug(field: &str, value: &str) -> Result<(), FieldIssue> {
150    if value.is_empty()
151        || value.starts_with('-')
152        || value.ends_with('-')
153        || value.contains("--")
154        || !value
155            .bytes()
156            .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
157    {
158        return Err(FieldIssue::new(
159            field,
160            "INVALID_SLUG",
161            "must be lowercase alphanumeric words separated by single hyphens",
162        ));
163    }
164    Ok(())
165}
166
167/// Validate every character against a compact character class spec such as `"a-z0-9_-"`.
168pub fn check_charset(field: &str, value: &str, spec: &str) -> Result<(), FieldIssue> {
169    let ok = if spec.is_ascii() {
170        let mask = build_ascii_charset_mask(spec.as_bytes());
171        value
172            .bytes()
173            .all(|b| b < 128 && (mask & (1_u128 << b)) != 0)
174    } else {
175        value.chars().all(|ch| char_matches_unicode_spec(ch, spec))
176    };
177    if ok {
178        Ok(())
179    } else {
180        Err(FieldIssue::new(
181            field,
182            "STRING_INVALID_CHARSET",
183            format!("contains characters outside allowed set [{spec}]"),
184        ))
185    }
186}
187
188fn build_ascii_charset_mask(bytes: &[u8]) -> u128 {
189    let mut mask = 0_u128;
190    let mut i = 0;
191    while i < bytes.len() {
192        if i + 2 < bytes.len() && bytes[i] != b'-' && bytes[i + 1] == b'-' && bytes[i + 2] != b'-' {
193            let start = bytes[i];
194            let end = bytes[i + 2];
195            if start <= end {
196                for b in start..=end {
197                    mask |= 1_u128 << b;
198                }
199            }
200            i += 3;
201        } else {
202            mask |= 1_u128 << bytes[i];
203            i += 1;
204        }
205    }
206    mask
207}
208
209fn char_matches_unicode_spec(ch: char, spec: &str) -> bool {
210    let mut iter = spec.chars().peekable();
211    while let Some(first) = iter.next() {
212        if first != '-' && iter.peek() == Some(&'-') {
213            let _dash = iter.next();
214            if let Some(end) = iter.next() {
215                if end != '-' {
216                    if start_to_end_contains(first, end, ch) {
217                        return true;
218                    }
219                    continue;
220                }
221                if ch == first || ch == '-' {
222                    return true;
223                }
224                continue;
225            }
226            if ch == first || ch == '-' {
227                return true;
228            }
229        } else if ch == first {
230            return true;
231        }
232    }
233    false
234}
235
236const fn start_to_end_contains(start: char, end: char, ch: char) -> bool {
237    start <= end && ch >= start && ch <= end
238}
239
240/// Strict dotted-quad IPv4 address.
241pub fn check_ipv4(field: &str, value: &str) -> Result<(), FieldIssue> {
242    value
243        .parse::<core::net::Ipv4Addr>()
244        .map(|_| ())
245        .map_err(|_| FieldIssue::new(field, "INVALID_IPV4", "must be a valid IPv4 address"))
246}
247
248/// IPv6 address (any textual form accepted by `core::net::Ipv6Addr`).
249pub fn check_ipv6(field: &str, value: &str) -> Result<(), FieldIssue> {
250    value
251        .parse::<core::net::Ipv6Addr>()
252        .map(|_| ())
253        .map_err(|_| FieldIssue::new(field, "INVALID_IPV6", "must be a valid IPv6 address"))
254}
255
256/// IPv4 or IPv6 address.
257pub fn check_ip(field: &str, value: &str) -> Result<(), FieldIssue> {
258    value
259        .parse::<core::net::IpAddr>()
260        .map(|_| ())
261        .map_err(|_| FieldIssue::new(field, "INVALID_IP", "must be a valid IPv4 or IPv6 address"))
262}
263
264/// RFC 1123 ASCII hostname (labels of `[A-Za-z0-9-]`, max 63 bytes each, 253 total).
265pub fn check_hostname(field: &str, value: &str) -> Result<(), FieldIssue> {
266    let bad = || {
267        Err(FieldIssue::new(
268            field,
269            "INVALID_HOSTNAME",
270            "must be a valid RFC 1123 hostname",
271        ))
272    };
273    if value.is_empty() || value.len() > 253 || value.starts_with('.') || value.ends_with('.') {
274        return bad();
275    }
276    let mut count = 0usize;
277    let mut last = "";
278    for label in value.split('.') {
279        let b = label.as_bytes();
280        if b.is_empty()
281            || b.len() > 63
282            || b[0] == b'-'
283            || b[b.len() - 1] == b'-'
284            || !b.iter().all(|c| c.is_ascii_alphanumeric() || *c == b'-')
285        {
286            return bad();
287        }
288        count += 1;
289        last = label;
290    }
291    if count > 1 && last.bytes().all(|c| c.is_ascii_digit()) {
292        return bad();
293    }
294    Ok(())
295}
296
297/// Strict SemVer 2.0.0 (`MAJOR.MINOR.PATCH[-PRERELEASE][+BUILD]`).
298pub fn check_semver(field: &str, value: &str) -> Result<(), FieldIssue> {
299    let bad = || {
300        Err(FieldIssue::new(
301            field,
302            "INVALID_SEMVER",
303            "must be a valid SemVer 2.0.0 version",
304        ))
305    };
306    let (rest, build) = match value.split_once('+') {
307        Some((r, b)) => (r, Some(b)),
308        None => (value, None),
309    };
310    let (core_part, pre) = match rest.split_once('-') {
311        Some((c, p)) => (c, Some(p)),
312        None => (rest, None),
313    };
314    let mut core_iter = core_part.split('.');
315    let (Some(major), Some(minor), Some(patch), None) = (
316        core_iter.next(),
317        core_iter.next(),
318        core_iter.next(),
319        core_iter.next(),
320    ) else {
321        return bad();
322    };
323    for n in [major, minor, patch] {
324        if n.is_empty()
325            || !n.bytes().all(|c| c.is_ascii_digit())
326            || (n.len() > 1 && n.starts_with('0'))
327        {
328            return bad();
329        }
330    }
331    if let Some(pre) = pre {
332        for id in pre.split('.') {
333            if id.is_empty() || !id.bytes().all(|c| c.is_ascii_alphanumeric() || c == b'-') {
334                return bad();
335            }
336            if id.bytes().all(|c| c.is_ascii_digit()) && id.len() > 1 && id.starts_with('0') {
337                return bad();
338            }
339        }
340    }
341    if let Some(build) = build {
342        for id in build.split('.') {
343            if id.is_empty() || !id.bytes().all(|c| c.is_ascii_alphanumeric() || c == b'-') {
344                return bad();
345            }
346        }
347    }
348    Ok(())
349}
350
351/// Non-empty string of ASCII hexadecimal digits.
352pub fn check_hex(field: &str, value: &str) -> Result<(), FieldIssue> {
353    if !value.is_empty() && value.bytes().all(|b| b.is_ascii_hexdigit()) {
354        Ok(())
355    } else {
356        Err(FieldIssue::new(
357            field,
358            "INVALID_HEX",
359            "must be a non-empty hexadecimal string",
360        ))
361    }
362}
363
364#[cfg(test)]
365mod tests {
366    use super::*;
367
368    #[test]
369    fn uuid_check() {
370        assert!(check_uuid("id", "550e8400-e29b-41d4-a716-446655440000").is_ok());
371        assert!(check_uuid("id", "not-a-uuid").is_err());
372    }
373
374    #[test]
375    fn url_check() {
376        assert!(check_url("u", "https://example.com/a?b=1", true).is_ok());
377        assert!(check_url("u", "HTTPS://example.com:8443/a", true).is_ok());
378        assert!(check_url("u", "http://[::1]:8080/health", false).is_ok());
379        assert!(check_url("u", "http://example.com", true).is_err());
380        assert!(check_url("u", "http://example.com", false).is_ok());
381        assert!(check_url("u", "https:///path", true).is_err());
382        assert!(check_url("u", "https://<>\"{}|\\^`[]", true).is_err());
383        assert!(check_url("u", "https://example.com:99999", true).is_err());
384        assert!(check_url("u", "https://example.com:notaport", true).is_err());
385        assert!(check_url("u", "https://example.com:80:80", true).is_err());
386        assert!(check_url("u", "https://user@host@evil.com", true).is_err());
387        assert!(check_url("u", "https://[not-ipv6]", true).is_err());
388        assert!(check_url("u", "https://a..b", true).is_err());
389        assert!(check_url("u", "https://bad.:80", true).is_err());
390    }
391
392    #[test]
393    fn slug_and_charset_checks() {
394        assert!(check_slug("slug", "wire-v1-alpha").is_ok());
395        assert!(check_slug("slug", "Bad_Slug").is_err());
396        assert!(check_slug("slug", "a--b").is_err());
397        assert!(check_charset("handle", "ada_99-x", "a-z0-9_-").is_ok());
398        assert!(check_charset("handle", "ada-x", "-a-z").is_ok());
399        assert!(check_charset("handle", "ada.x", "--z").is_err());
400        assert!(check_charset("handle", "Ada!", "a-z0-9_-").is_err());
401        assert!(check_charset("umlaut", "äöü", "äöü").is_ok());
402        assert!(check_charset("umlaut", "Ã", "äöü").is_err());
403    }
404
405    #[test]
406    fn ip_checks() {
407        assert!(check_ipv4("ip", "192.168.0.1").is_ok());
408        assert!(check_ipv4("ip", "256.1.1.1").is_err());
409        assert!(check_ipv4("ip", "::1").is_err());
410        assert!(check_ipv6("ip", "::1").is_ok());
411        assert!(check_ipv6("ip", "2001:db8::ff00:42:8329").is_ok());
412        assert!(check_ipv6("ip", "1.2.3.4").is_err());
413        assert!(check_ip("ip", "1.2.3.4").is_ok());
414        assert!(check_ip("ip", "::1").is_ok());
415        assert!(check_ip("ip", "nope").is_err());
416    }
417
418    #[test]
419    fn hostname_checks() {
420        assert!(check_hostname("h", "example.com").is_ok());
421        assert!(check_hostname("h", "localhost").is_ok());
422        assert!(check_hostname("h", "a-b.example.org").is_ok());
423        assert!(check_hostname("h", "").is_err());
424        assert!(check_hostname("h", "-bad.com").is_err());
425        assert!(check_hostname("h", "bad-.com").is_err());
426        assert!(check_hostname("h", "a..b").is_err());
427        assert!(check_hostname("h", ".a.com").is_err());
428        assert!(check_hostname("h", "a.com.").is_err());
429        assert!(check_hostname("h", "1.2.3.4").is_err());
430        assert!(check_hostname("h", "under_score.com").is_err());
431        assert!(check_hostname("h", &"a".repeat(64)).is_err());
432        assert!(check_hostname("h", &"a".repeat(63)).is_ok());
433    }
434
435    #[test]
436    fn semver_checks() {
437        assert!(check_semver("v", "1.2.3").is_ok());
438        assert!(check_semver("v", "0.0.0").is_ok());
439        assert!(check_semver("v", "1.0.0-alpha.1+build.5").is_ok());
440        assert!(check_semver("v", "1.0.0-0.3.7").is_ok());
441        assert!(check_semver("v", "1.2").is_err());
442        assert!(check_semver("v", "01.2.3").is_err());
443        assert!(check_semver("v", "1.2.3-01").is_err());
444        assert!(check_semver("v", "1.2.3-").is_err());
445        assert!(check_semver("v", "1.2.3+").is_err());
446        assert!(check_semver("v", "v1.2.3").is_err());
447    }
448
449    #[test]
450    fn hex_checks() {
451        assert!(check_hex("h", "deadBEEF09").is_ok());
452        assert!(check_hex("h", "").is_err());
453        assert!(check_hex("h", "xyz").is_err());
454    }
455}