vouch-core 3.1.0

Vouch Protocol canonical core: JCS canonicalization, Ed25519 + ML-DSA proofs, did:key/multikey, Data Integrity (eddsa-jcs-2022), credentials, delegation, revocation. One byte-exact implementation shared by every language SDK via WASM and UniFFI/C-FFI.
Documentation
//! One strict grammar for every protocol time.
//!
//! Credentials, status lists, receipts and every other signed object carry
//! their times as strings. If two modules (or two languages) read the same
//! string differently, a time one of them refuses can pass in another. So every
//! protocol time in the core goes through this module, and the grammar is the
//! same one the Python, TypeScript and Go implementations use
//! (`test-vectors/time/vector.json` is the shared contract):
//!
//! ```text
//! YYYY-MM-DDTHH:MM:SS[.fraction](Z | +HH:MM | -HH:MM)
//! ```
//!
//! * `T` and `Z` are upper case and nothing else may appear in the string (no
//!   spaces, no trailing newline, no missing offset).
//! * Years run 0001-9999, months and days are real calendar days, hours are
//!   00-23, minutes and seconds 00-59 (a leap second `:60` is refused).
//! * The fraction has 1 to 9 digits and is kept at full precision: compare
//!   instants with [`parse_protocol_time_ns`], never with whole seconds.
//! * The offset is at most 23:59 either way, and the instant it names, moved
//!   to UTC, must still fall inside 0001-01-01T00:00:00Z ..
//!   9999-12-31T23:59:59.999999999Z.
//!
//! A `now` without a timezone does not match the grammar, so it is refused like
//! any other malformed time. Clock skew is 0 to 120 seconds
//! ([`check_clock_skew`]); anything else is refused.

use crate::error::{CoreError, Result};

/// The largest clock skew a verifier may allow, in seconds.
pub const MAX_CLOCK_SKEW_SECONDS: i64 = 120;

const NS_PER_SECOND: i128 = 1_000_000_000;
/// 0001-01-01T00:00:00Z in nanoseconds since the Unix epoch.
const MIN_NS: i128 = -62_135_596_800 * NS_PER_SECOND;
/// 9999-12-31T23:59:59.999999999Z in nanoseconds since the Unix epoch.
const MAX_NS: i128 = 253_402_300_799 * NS_PER_SECOND + 999_999_999;

fn bad(s: &str) -> CoreError {
    // Bound the echoed input so a huge string is not copied into the error.
    let shown: String = s.chars().take(64).collect();
    CoreError::Json(format!("invalid protocol time: {shown:?}"))
}

fn days_in_month(year: i64, month: i64) -> i64 {
    match month {
        2 => {
            let leap = year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
            if leap {
                29
            } else {
                28
            }
        }
        4 | 6 | 9 | 11 => 30,
        _ => 31,
    }
}

/// Parse a protocol time into exact nanoseconds since 1970-01-01T00:00:00Z
/// (negative before 1970). Works on bytes and checks every position, so
/// malformed or non-ASCII input returns an error and never panics.
pub fn parse_protocol_time_ns(s: &str) -> Result<i128> {
    let b = s.as_bytes();
    // "YYYY-MM-DDTHH:MM:SSZ" is the shortest valid form; the longest is the
    // 9-digit fraction plus a numeric offset (35 bytes).
    if b.len() < 20 || b.len() > 35 {
        return Err(bad(s));
    }
    let digits = |i: usize, len: usize| -> Result<i64> {
        let mut v: i64 = 0;
        for &c in &b[i..i + len] {
            if !c.is_ascii_digit() {
                return Err(bad(s));
            }
            v = v * 10 + i64::from(c - b'0');
        }
        Ok(v)
    };
    if b[4] != b'-' || b[7] != b'-' || b[10] != b'T' || b[13] != b':' || b[16] != b':' {
        return Err(bad(s));
    }
    let year = digits(0, 4)?;
    let month = digits(5, 2)?;
    let day = digits(8, 2)?;
    let hour = digits(11, 2)?;
    let minute = digits(14, 2)?;
    let second = digits(17, 2)?;
    if !(1..=9999).contains(&year)
        || !(1..=12).contains(&month)
        || day < 1
        || day > days_in_month(year, month)
        || hour > 23
        || minute > 59
        || second > 59
    {
        return Err(bad(s));
    }

    let mut j = 19usize;
    let mut nanos: i128 = 0;
    if b[j] == b'.' {
        j += 1;
        let start = j;
        while j < b.len() && b[j].is_ascii_digit() {
            j += 1;
        }
        let n = j - start;
        if n == 0 || n > 9 {
            return Err(bad(s));
        }
        let mut v: i128 = 0;
        for &c in &b[start..j] {
            v = v * 10 + i128::from(c - b'0');
        }
        for _ in n..9 {
            v *= 10;
        }
        nanos = v;
    }
    if j >= b.len() {
        return Err(bad(s)); // no offset
    }
    let offset_seconds: i64 = match b[j] {
        b'Z' => {
            if j + 1 != b.len() {
                return Err(bad(s));
            }
            0
        }
        b'+' | b'-' => {
            if j + 6 != b.len() || b[j + 3] != b':' {
                return Err(bad(s));
            }
            let oh = digits(j + 1, 2)?;
            let om = digits(j + 4, 2)?;
            if oh > 23 || om > 59 {
                return Err(bad(s));
            }
            let mag = oh * 3600 + om * 60;
            if b[j] == b'+' {
                mag
            } else {
                -mag
            }
        }
        _ => return Err(bad(s)),
    };

    let days = days_from_civil(year, month, day);
    let seconds = days * 86_400 + hour * 3_600 + minute * 60 + second - offset_seconds;
    let total = i128::from(seconds) * NS_PER_SECOND + nanos;
    if !(MIN_NS..=MAX_NS).contains(&total) {
        return Err(bad(s));
    }
    Ok(total)
}

/// Parse a protocol time to whole Unix epoch seconds (the floor of the exact
/// instant). Uses the strict grammar of [`parse_protocol_time_ns`].
///
/// Whole seconds drop the fraction, so a validity comparison must use
/// [`parse_protocol_time_ns`] instead; this remains for callers that only need
/// second resolution (for example to derive and format a later time).
pub fn iso_to_epoch_seconds(s: &str) -> Result<i64> {
    let ns = parse_protocol_time_ns(s)?;
    // The parser's range check keeps this well inside i64.
    Ok(ns.div_euclid(NS_PER_SECOND) as i64)
}

/// Return the clock skew in nanoseconds when it is an allowed value (0 to
/// [`MAX_CLOCK_SKEW_SECONDS`] seconds), else an error.
pub fn check_clock_skew(clock_skew_seconds: i64) -> Result<i128> {
    if !(0..=MAX_CLOCK_SKEW_SECONDS).contains(&clock_skew_seconds) {
        return Err(CoreError::Json(format!(
            "clock skew must be between 0 and {MAX_CLOCK_SKEW_SECONDS} seconds, got {clock_skew_seconds}"
        )));
    }
    Ok(i128::from(clock_skew_seconds) * NS_PER_SECOND)
}

/// Read a clock skew from a JSON request: a whole number of seconds (an
/// integral float such as 30.0 counts as 30) in 0 to
/// [`MAX_CLOCK_SKEW_SECONDS`]. Booleans, strings, null, fractions and numbers
/// outside the range are refused.
pub fn clock_skew_from_json(value: &serde_json::Value) -> Result<i64> {
    crate::attenuation::as_int(value, 0, MAX_CLOCK_SKEW_SECONDS).ok_or_else(|| {
        CoreError::Json(format!(
            "clock skew must be a whole number of seconds from 0 to {MAX_CLOCK_SKEW_SECONDS}"
        ))
    })
}

/// Seconds to nanoseconds, for comparing a whole-second bound (a max age, an
/// interval) against parsed instants.
pub fn seconds_to_ns(seconds: i64) -> i128 {
    i128::from(seconds) * NS_PER_SECOND
}

/// Where `now` falls against a validity window.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WindowState {
    /// Inside the window (allowing the skew at each edge).
    Ok,
    /// `validFrom` is more than the skew ahead of `now`.
    NotYetValid,
    /// `now` is more than the skew past `validUntil`.
    Expired,
    /// `validFrom` is after `validUntil`: the window is empty.
    Inverted,
}

impl WindowState {
    pub fn as_str(self) -> &'static str {
        match self {
            WindowState::Ok => "ok",
            WindowState::NotYetValid => "not_yet_valid",
            WindowState::Expired => "expired",
            WindowState::Inverted => "inverted",
        }
    }
}

/// Place `now_ns` against `[from - skew, until + skew]` at full precision. A
/// missing bound is open on that side. An inverted window is reported first.
pub fn window_state_ns(
    now_ns: i128,
    from_ns: Option<i128>,
    until_ns: Option<i128>,
    skew_ns: i128,
) -> WindowState {
    if let (Some(f), Some(u)) = (from_ns, until_ns) {
        if f > u {
            return WindowState::Inverted;
        }
    }
    if let Some(f) = from_ns {
        if f - now_ns > skew_ns {
            return WindowState::NotYetValid;
        }
    }
    if let Some(u) = until_ns {
        if now_ns - u > skew_ns {
            return WindowState::Expired;
        }
    }
    WindowState::Ok
}

/// [`window_state_ns`] over protocol-time strings. Errors on a malformed time
/// or an out-of-range skew.
pub fn window_state(
    now_iso: &str,
    valid_from: Option<&str>,
    valid_until: Option<&str>,
    clock_skew_seconds: i64,
) -> Result<WindowState> {
    let skew = check_clock_skew(clock_skew_seconds)?;
    let now = parse_protocol_time_ns(now_iso)?;
    let from = valid_from.map(parse_protocol_time_ns).transpose()?;
    let until = valid_until.map(parse_protocol_time_ns).transpose()?;
    Ok(window_state_ns(now, from, until, skew))
}

/// Days since the Unix epoch (1970-01-01) for a civil date.
/// Howard Hinnant's algorithm; valid for the full proleptic Gregorian range.
fn days_from_civil(year: i64, month: i64, day: i64) -> i64 {
    let y = if month <= 2 { year - 1 } else { year };
    let era = (if y >= 0 { y } else { y - 399 }) / 400;
    let yoe = y - era * 400;
    let mp = if month > 2 { month - 3 } else { month + 9 };
    let doy = (153 * mp + 2) / 5 + day - 1;
    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
    era * 146097 + doe - 719468
}

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

    #[test]
    fn parses_known_instants() {
        assert_eq!(iso_to_epoch_seconds("1970-01-01T00:00:00Z").unwrap(), 0);
        assert_eq!(
            iso_to_epoch_seconds("2026-04-26T10:00:00Z").unwrap(),
            1777197600
        );
    }

    #[test]
    fn window_ordering() {
        let a = iso_to_epoch_seconds("2026-04-26T10:00:00Z").unwrap();
        let b = iso_to_epoch_seconds("2026-04-26T10:05:00Z").unwrap();
        assert_eq!(b - a, 300);
    }

    #[test]
    fn rejects_malformed_without_panic() {
        for s in [
            "",
            "garbage",
            "2026-13-99T10:00:00Z",
            "20\u{00e9}6-04-26T10:00:00Z",
            "2026-04-26 10:00:00",
            "2026-04-26T10:0",
            "2026-04-26T25:00:00Z",
            "2026-04-26T10:00:00+9999",
            "2026-04-26T10:00:00",
            "2026-04-26T10:00:00z",
            "2026-04-26t10:00:00Z",
            "2026-02-29T10:00:00Z",
            "2016-12-31T23:59:60Z",
            "2026-04-26T10:00:00+24:00",
            "2026-04-26T10:00:00Z\n",
            "2026-04-26T10:00:00.Z",
            "2026-04-26T10:00:00.1234567890Z",
            "0000-01-01T00:00:00Z",
            "0001-01-01T00:00:00+00:01",
            "9999-12-31T23:59:59-00:01",
            "2026-04-26T10:00:00\u{00e9}",
            "2026-04-26T10:00:00.\u{00e9}Z",
        ] {
            assert!(parse_protocol_time_ns(s).is_err(), "{s:?} should error");
        }
    }

    #[test]
    fn keeps_fractions_and_offsets() {
        let z = parse_protocol_time_ns("2026-04-26T10:00:00Z").unwrap();
        assert_eq!(
            parse_protocol_time_ns("2026-04-26T10:00:00.250Z").unwrap(),
            z + 250_000_000
        );
        assert_eq!(
            parse_protocol_time_ns("2026-04-26T10:00:00.000000001Z").unwrap(),
            z + 1
        );
        assert_eq!(
            parse_protocol_time_ns("2026-04-26T12:00:00+02:00").unwrap(),
            z
        );
        assert_eq!(
            iso_to_epoch_seconds("1969-12-31T23:59:59.5Z").unwrap(),
            -1,
            "whole seconds are the floor, also before the epoch"
        );
    }

    #[test]
    fn skew_bounds() {
        assert!(check_clock_skew(0).is_ok());
        assert!(check_clock_skew(120).is_ok());
        for s in [-1, 121, i64::MAX, i64::MIN] {
            assert!(check_clock_skew(s).is_err(), "{s}");
        }
    }

    #[test]
    fn window_edges() {
        let w = |now, f, u, s| window_state(now, Some(f), Some(u), s).unwrap();
        assert_eq!(
            w(
                "2026-04-26T11:00:00Z",
                "2026-04-26T09:00:00Z",
                "2026-04-26T11:00:00Z",
                0
            ),
            WindowState::Ok
        );
        assert_eq!(
            w(
                "2026-04-26T11:00:00.000000001Z",
                "2026-04-26T09:00:00Z",
                "2026-04-26T11:00:00Z",
                0
            ),
            WindowState::Expired
        );
        assert_eq!(
            w(
                "2026-04-26T10:00:00Z",
                "2026-04-26T11:00:00Z",
                "2026-04-26T09:00:00Z",
                0
            ),
            WindowState::Inverted
        );
    }
}