pactum-annotations 0.6.0

Declarative field normalization and validation for pactum contracts
Documentation
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://`, non-empty host, 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 rest = if let Some(rest) = value.strip_prefix("https://") {
        rest
    } else if !require_https {
        let Some(rest) = value.strip_prefix("http://") else {
            return Err(FieldIssue::new(
                field,
                "INVALID_URL",
                "url must start with http:// or https://",
            ));
        };
        rest
    } else {
        return Err(FieldIssue::new(
            field,
            "INVALID_URL",
            "url must start with https://",
        ));
    };

    let authority = rest.split(['/', '?', '#']).next().unwrap_or("");
    let host = authority.rsplit('@').next().unwrap_or("");
    if host.is_empty() || host.starts_with(':') || host.starts_with('.') || host.ends_with('.') {
        return Err(FieldIssue::new(
            field,
            "INVALID_URL",
            "url must include a valid host",
        ));
    }
    Ok(())
}

/// 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 ASCII class spec such as `"a-z0-9_-"`.
pub fn check_charset(field: &str, value: &str, spec: &str) -> Result<(), FieldIssue> {
    if value.chars().all(|ch| char_matches_spec(ch, spec)) {
        Ok(())
    } else {
        Err(FieldIssue::new(
            field,
            "STRING_INVALID_CHARSET",
            format!("contains characters outside allowed set [{spec}]"),
        ))
    }
}

fn char_matches_spec(ch: char, spec: &str) -> bool {
    let bytes = spec.as_bytes();
    let mut i = 0;
    while i < bytes.len() {
        if i + 2 < bytes.len() && bytes[i + 1] == b'-' {
            let start = bytes[i] as char;
            let end = bytes[i + 2] as char;
            if ch >= start && ch <= end {
                return true;
            }
            i += 3;
        } else {
            if ch == bytes[i] as char {
                return true;
            }
            i += 1;
        }
    }
    false
}

/// 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 labels: Vec<&str> = value.split('.').collect();
    for label in &labels {
        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();
        }
    }
    if labels.len() > 1 {
        let last = labels[labels.len() - 1];
        if 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 nums: Vec<&str> = core_part.split('.').collect();
    if nums.len() != 3 {
        return bad();
    }
    for n in nums {
        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", "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());
    }

    #[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!", "a-z0-9_-").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());
    }
}