pactum-annotations 0.7.0

Declarative field normalization and validation for pactum contracts
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
use crate::error::FieldIssue;

/// Canonical lowercase/uppercase hyphenated UUID (`8-4-4-4-12` hex digits).
pub fn check_uuid(field: &str, value: &str) -> Result<(), FieldIssue> {
    let bytes = value.as_bytes();
    if bytes.len() != 36 {
        return Err(FieldIssue::new(
            field,
            "INVALID_UUID",
            "must be a canonical UUID (8-4-4-4-12)",
        ));
    }
    for (idx, &b) in bytes.iter().enumerate() {
        let expect_dash = matches!(idx, 8 | 13 | 18 | 23);
        if expect_dash {
            if b != b'-' {
                return Err(FieldIssue::new(
                    field,
                    "INVALID_UUID",
                    "must be a canonical UUID (8-4-4-4-12)",
                ));
            }
        } else if !b.is_ascii_hexdigit() {
            return Err(FieldIssue::new(
                field,
                "INVALID_UUID",
                "must be a canonical UUID (8-4-4-4-12)",
            ));
        }
    }
    Ok(())
}

/// Structural URL check (`http://` or `https://`, valid host and optional port, no whitespace/control chars).
pub fn check_url(field: &str, value: &str, require_https: bool) -> Result<(), FieldIssue> {
    if value.chars().any(|c| c.is_whitespace() || c.is_control()) {
        return Err(FieldIssue::new(
            field,
            "INVALID_URL",
            "url must not contain whitespace or control characters",
        ));
    }
    let bytes = value.as_bytes();
    let rest = if bytes.len() >= 8 && bytes[..8].eq_ignore_ascii_case(b"https://") {
        &value[8..]
    } else if !require_https && bytes.len() >= 7 && bytes[..7].eq_ignore_ascii_case(b"http://") {
        &value[7..]
    } else if require_https {
        return Err(FieldIssue::new(
            field,
            "INVALID_URL",
            "url must start with https://",
        ));
    } else {
        return Err(FieldIssue::new(
            field,
            "INVALID_URL",
            "url must start with http:// or https://",
        ));
    };

    let authority = rest.split(['/', '?', '#']).next().unwrap_or("");
    let host_port = if let Some((userinfo, hp)) = authority.split_once('@') {
        if userinfo.is_empty()
            || hp.contains('@')
            || userinfo.bytes().any(|b| {
                matches!(
                    b,
                    b'<' | b'>' | b'"' | b'{' | b'}' | b'|' | b'\\' | b'^' | b'`' | b'[' | b']'
                )
            })
        {
            return Err(FieldIssue::new(
                field,
                "INVALID_URL",
                "url contains invalid authority userinfo",
            ));
        }
        hp
    } else {
        authority
    };

    if !is_valid_url_host_port(host_port) {
        return Err(FieldIssue::new(
            field,
            "INVALID_URL",
            "url must include a valid host",
        ));
    }
    Ok(())
}

fn is_valid_url_port(port: &str) -> bool {
    !port.is_empty()
        && port.bytes().all(|b| b.is_ascii_digit())
        && matches!(port.parse::<u16>(), Ok(1..=u16::MAX))
}

fn is_valid_url_host_port(host_port: &str) -> bool {
    if host_port.is_empty() {
        return false;
    }
    if let Some(after_open) = host_port.strip_prefix('[') {
        let Some((ipv6_lit, after_close)) = after_open.split_once(']') else {
            return false;
        };
        if ipv6_lit.parse::<core::net::Ipv6Addr>().is_err() {
            return false;
        }
        return match after_close.strip_prefix(':') {
            Some(port) => is_valid_url_port(port),
            None => after_close.is_empty(),
        };
    }

    let (host, port) = match host_port.split_once(':') {
        Some((h, p)) => (h, Some(p)),
        None => (host_port, None),
    };
    if let Some(port) = port {
        if !is_valid_url_port(port) {
            return false;
        }
    }
    if host.is_empty() || host.starts_with('.') || host.ends_with('.') || host.contains("..") {
        return false;
    }
    if host.parse::<core::net::Ipv4Addr>().is_ok() {
        return true;
    }
    for label in host.split('.') {
        let b = label.as_bytes();
        if b.is_empty()
            || b.len() > 63
            || b[0] == b'-'
            || b[b.len() - 1] == b'-'
            || !b
                .iter()
                .all(|&c| c.is_ascii_alphanumeric() || c == b'-' || c == b'_')
        {
            return false;
        }
    }
    true
}

/// Lowercase ASCII slug: `[a-z0-9]` segments joined by single `-` characters.
pub fn check_slug(field: &str, value: &str) -> Result<(), FieldIssue> {
    if value.is_empty()
        || value.starts_with('-')
        || value.ends_with('-')
        || value.contains("--")
        || !value
            .bytes()
            .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
    {
        return Err(FieldIssue::new(
            field,
            "INVALID_SLUG",
            "must be lowercase alphanumeric words separated by single hyphens",
        ));
    }
    Ok(())
}

/// Validate every character against a compact character class spec such as `"a-z0-9_-"`.
pub fn check_charset(field: &str, value: &str, spec: &str) -> Result<(), FieldIssue> {
    let ok = if spec.is_ascii() {
        let mask = build_ascii_charset_mask(spec.as_bytes());
        value
            .bytes()
            .all(|b| b < 128 && (mask & (1_u128 << b)) != 0)
    } else {
        value.chars().all(|ch| char_matches_unicode_spec(ch, spec))
    };
    if ok {
        Ok(())
    } else {
        Err(FieldIssue::new(
            field,
            "STRING_INVALID_CHARSET",
            format!("contains characters outside allowed set [{spec}]"),
        ))
    }
}

fn build_ascii_charset_mask(bytes: &[u8]) -> u128 {
    let mut mask = 0_u128;
    let mut i = 0;
    while i < bytes.len() {
        if i + 2 < bytes.len() && bytes[i] != b'-' && bytes[i + 1] == b'-' && bytes[i + 2] != b'-' {
            let start = bytes[i];
            let end = bytes[i + 2];
            if start <= end {
                for b in start..=end {
                    mask |= 1_u128 << b;
                }
            }
            i += 3;
        } else {
            mask |= 1_u128 << bytes[i];
            i += 1;
        }
    }
    mask
}

fn char_matches_unicode_spec(ch: char, spec: &str) -> bool {
    let mut iter = spec.chars().peekable();
    while let Some(first) = iter.next() {
        if first != '-' && iter.peek() == Some(&'-') {
            let _dash = iter.next();
            if let Some(end) = iter.next() {
                if end != '-' {
                    if start_to_end_contains(first, end, ch) {
                        return true;
                    }
                    continue;
                }
                if ch == first || ch == '-' {
                    return true;
                }
                continue;
            }
            if ch == first || ch == '-' {
                return true;
            }
        } else if ch == first {
            return true;
        }
    }
    false
}

const fn start_to_end_contains(start: char, end: char, ch: char) -> bool {
    start <= end && ch >= start && ch <= end
}

/// Strict dotted-quad IPv4 address.
pub fn check_ipv4(field: &str, value: &str) -> Result<(), FieldIssue> {
    value
        .parse::<core::net::Ipv4Addr>()
        .map(|_| ())
        .map_err(|_| FieldIssue::new(field, "INVALID_IPV4", "must be a valid IPv4 address"))
}

/// IPv6 address (any textual form accepted by `core::net::Ipv6Addr`).
pub fn check_ipv6(field: &str, value: &str) -> Result<(), FieldIssue> {
    value
        .parse::<core::net::Ipv6Addr>()
        .map(|_| ())
        .map_err(|_| FieldIssue::new(field, "INVALID_IPV6", "must be a valid IPv6 address"))
}

/// IPv4 or IPv6 address.
pub fn check_ip(field: &str, value: &str) -> Result<(), FieldIssue> {
    value
        .parse::<core::net::IpAddr>()
        .map(|_| ())
        .map_err(|_| FieldIssue::new(field, "INVALID_IP", "must be a valid IPv4 or IPv6 address"))
}

/// RFC 1123 ASCII hostname (labels of `[A-Za-z0-9-]`, max 63 bytes each, 253 total).
pub fn check_hostname(field: &str, value: &str) -> Result<(), FieldIssue> {
    let bad = || {
        Err(FieldIssue::new(
            field,
            "INVALID_HOSTNAME",
            "must be a valid RFC 1123 hostname",
        ))
    };
    if value.is_empty() || value.len() > 253 || value.starts_with('.') || value.ends_with('.') {
        return bad();
    }
    let mut count = 0usize;
    let mut last = "";
    for label in value.split('.') {
        let b = label.as_bytes();
        if b.is_empty()
            || b.len() > 63
            || b[0] == b'-'
            || b[b.len() - 1] == b'-'
            || !b.iter().all(|c| c.is_ascii_alphanumeric() || *c == b'-')
        {
            return bad();
        }
        count += 1;
        last = label;
    }
    if count > 1 && last.bytes().all(|c| c.is_ascii_digit()) {
        return bad();
    }
    Ok(())
}

/// Strict SemVer 2.0.0 (`MAJOR.MINOR.PATCH[-PRERELEASE][+BUILD]`).
pub fn check_semver(field: &str, value: &str) -> Result<(), FieldIssue> {
    let bad = || {
        Err(FieldIssue::new(
            field,
            "INVALID_SEMVER",
            "must be a valid SemVer 2.0.0 version",
        ))
    };
    let (rest, build) = match value.split_once('+') {
        Some((r, b)) => (r, Some(b)),
        None => (value, None),
    };
    let (core_part, pre) = match rest.split_once('-') {
        Some((c, p)) => (c, Some(p)),
        None => (rest, None),
    };
    let mut core_iter = core_part.split('.');
    let (Some(major), Some(minor), Some(patch), None) = (
        core_iter.next(),
        core_iter.next(),
        core_iter.next(),
        core_iter.next(),
    ) else {
        return bad();
    };
    for n in [major, minor, patch] {
        if n.is_empty()
            || !n.bytes().all(|c| c.is_ascii_digit())
            || (n.len() > 1 && n.starts_with('0'))
        {
            return bad();
        }
    }
    if let Some(pre) = pre {
        for id in pre.split('.') {
            if id.is_empty() || !id.bytes().all(|c| c.is_ascii_alphanumeric() || c == b'-') {
                return bad();
            }
            if id.bytes().all(|c| c.is_ascii_digit()) && id.len() > 1 && id.starts_with('0') {
                return bad();
            }
        }
    }
    if let Some(build) = build {
        for id in build.split('.') {
            if id.is_empty() || !id.bytes().all(|c| c.is_ascii_alphanumeric() || c == b'-') {
                return bad();
            }
        }
    }
    Ok(())
}

/// Non-empty string of ASCII hexadecimal digits.
pub fn check_hex(field: &str, value: &str) -> Result<(), FieldIssue> {
    if !value.is_empty() && value.bytes().all(|b| b.is_ascii_hexdigit()) {
        Ok(())
    } else {
        Err(FieldIssue::new(
            field,
            "INVALID_HEX",
            "must be a non-empty hexadecimal string",
        ))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn uuid_check() {
        assert!(check_uuid("id", "550e8400-e29b-41d4-a716-446655440000").is_ok());
        assert!(check_uuid("id", "not-a-uuid").is_err());
    }

    #[test]
    fn url_check() {
        assert!(check_url("u", "https://example.com/a?b=1", true).is_ok());
        assert!(check_url("u", "HTTPS://example.com:8443/a", true).is_ok());
        assert!(check_url("u", "http://[::1]:8080/health", false).is_ok());
        assert!(check_url("u", "http://example.com", true).is_err());
        assert!(check_url("u", "http://example.com", false).is_ok());
        assert!(check_url("u", "https:///path", true).is_err());
        assert!(check_url("u", "https://<>\"{}|\\^`[]", true).is_err());
        assert!(check_url("u", "https://example.com:99999", true).is_err());
        assert!(check_url("u", "https://example.com:notaport", true).is_err());
        assert!(check_url("u", "https://example.com:80:80", true).is_err());
        assert!(check_url("u", "https://user@host@evil.com", true).is_err());
        assert!(check_url("u", "https://[not-ipv6]", true).is_err());
        assert!(check_url("u", "https://a..b", true).is_err());
        assert!(check_url("u", "https://bad.:80", true).is_err());
    }

    #[test]
    fn slug_and_charset_checks() {
        assert!(check_slug("slug", "wire-v1-alpha").is_ok());
        assert!(check_slug("slug", "Bad_Slug").is_err());
        assert!(check_slug("slug", "a--b").is_err());
        assert!(check_charset("handle", "ada_99-x", "a-z0-9_-").is_ok());
        assert!(check_charset("handle", "ada-x", "-a-z").is_ok());
        assert!(check_charset("handle", "ada.x", "--z").is_err());
        assert!(check_charset("handle", "Ada!", "a-z0-9_-").is_err());
        assert!(check_charset("umlaut", "äöü", "äöü").is_ok());
        assert!(check_charset("umlaut", "Ã", "äöü").is_err());
    }

    #[test]
    fn ip_checks() {
        assert!(check_ipv4("ip", "192.168.0.1").is_ok());
        assert!(check_ipv4("ip", "256.1.1.1").is_err());
        assert!(check_ipv4("ip", "::1").is_err());
        assert!(check_ipv6("ip", "::1").is_ok());
        assert!(check_ipv6("ip", "2001:db8::ff00:42:8329").is_ok());
        assert!(check_ipv6("ip", "1.2.3.4").is_err());
        assert!(check_ip("ip", "1.2.3.4").is_ok());
        assert!(check_ip("ip", "::1").is_ok());
        assert!(check_ip("ip", "nope").is_err());
    }

    #[test]
    fn hostname_checks() {
        assert!(check_hostname("h", "example.com").is_ok());
        assert!(check_hostname("h", "localhost").is_ok());
        assert!(check_hostname("h", "a-b.example.org").is_ok());
        assert!(check_hostname("h", "").is_err());
        assert!(check_hostname("h", "-bad.com").is_err());
        assert!(check_hostname("h", "bad-.com").is_err());
        assert!(check_hostname("h", "a..b").is_err());
        assert!(check_hostname("h", ".a.com").is_err());
        assert!(check_hostname("h", "a.com.").is_err());
        assert!(check_hostname("h", "1.2.3.4").is_err());
        assert!(check_hostname("h", "under_score.com").is_err());
        assert!(check_hostname("h", &"a".repeat(64)).is_err());
        assert!(check_hostname("h", &"a".repeat(63)).is_ok());
    }

    #[test]
    fn semver_checks() {
        assert!(check_semver("v", "1.2.3").is_ok());
        assert!(check_semver("v", "0.0.0").is_ok());
        assert!(check_semver("v", "1.0.0-alpha.1+build.5").is_ok());
        assert!(check_semver("v", "1.0.0-0.3.7").is_ok());
        assert!(check_semver("v", "1.2").is_err());
        assert!(check_semver("v", "01.2.3").is_err());
        assert!(check_semver("v", "1.2.3-01").is_err());
        assert!(check_semver("v", "1.2.3-").is_err());
        assert!(check_semver("v", "1.2.3+").is_err());
        assert!(check_semver("v", "v1.2.3").is_err());
    }

    #[test]
    fn hex_checks() {
        assert!(check_hex("h", "deadBEEF09").is_ok());
        assert!(check_hex("h", "").is_err());
        assert!(check_hex("h", "xyz").is_err());
    }
}