Skip to main content

vouch_core/
time.rs

1//! One strict grammar for every protocol time.
2//!
3//! Credentials, status lists, receipts and every other signed object carry
4//! their times as strings. If two modules (or two languages) read the same
5//! string differently, a time one of them refuses can pass in another. So every
6//! protocol time in the core goes through this module, and the grammar is the
7//! same one the Python, TypeScript and Go implementations use
8//! (`test-vectors/time/vector.json` is the shared contract):
9//!
10//! ```text
11//! YYYY-MM-DDTHH:MM:SS[.fraction](Z | +HH:MM | -HH:MM)
12//! ```
13//!
14//! * `T` and `Z` are upper case and nothing else may appear in the string (no
15//!   spaces, no trailing newline, no missing offset).
16//! * Years run 0001-9999, months and days are real calendar days, hours are
17//!   00-23, minutes and seconds 00-59 (a leap second `:60` is refused).
18//! * The fraction has 1 to 9 digits and is kept at full precision: compare
19//!   instants with [`parse_protocol_time_ns`], never with whole seconds.
20//! * The offset is at most 23:59 either way, and the instant it names, moved
21//!   to UTC, must still fall inside 0001-01-01T00:00:00Z ..
22//!   9999-12-31T23:59:59.999999999Z.
23//!
24//! A `now` without a timezone does not match the grammar, so it is refused like
25//! any other malformed time. Clock skew is 0 to 120 seconds
26//! ([`check_clock_skew`]); anything else is refused.
27
28use crate::error::{CoreError, Result};
29
30/// The largest clock skew a verifier may allow, in seconds.
31pub const MAX_CLOCK_SKEW_SECONDS: i64 = 120;
32
33const NS_PER_SECOND: i128 = 1_000_000_000;
34/// 0001-01-01T00:00:00Z in nanoseconds since the Unix epoch.
35const MIN_NS: i128 = -62_135_596_800 * NS_PER_SECOND;
36/// 9999-12-31T23:59:59.999999999Z in nanoseconds since the Unix epoch.
37const MAX_NS: i128 = 253_402_300_799 * NS_PER_SECOND + 999_999_999;
38
39fn bad(s: &str) -> CoreError {
40    // Bound the echoed input so a huge string is not copied into the error.
41    let shown: String = s.chars().take(64).collect();
42    CoreError::Json(format!("invalid protocol time: {shown:?}"))
43}
44
45fn days_in_month(year: i64, month: i64) -> i64 {
46    match month {
47        2 => {
48            let leap = year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
49            if leap {
50                29
51            } else {
52                28
53            }
54        }
55        4 | 6 | 9 | 11 => 30,
56        _ => 31,
57    }
58}
59
60/// Parse a protocol time into exact nanoseconds since 1970-01-01T00:00:00Z
61/// (negative before 1970). Works on bytes and checks every position, so
62/// malformed or non-ASCII input returns an error and never panics.
63pub fn parse_protocol_time_ns(s: &str) -> Result<i128> {
64    let b = s.as_bytes();
65    // "YYYY-MM-DDTHH:MM:SSZ" is the shortest valid form; the longest is the
66    // 9-digit fraction plus a numeric offset (35 bytes).
67    if b.len() < 20 || b.len() > 35 {
68        return Err(bad(s));
69    }
70    let digits = |i: usize, len: usize| -> Result<i64> {
71        let mut v: i64 = 0;
72        for &c in &b[i..i + len] {
73            if !c.is_ascii_digit() {
74                return Err(bad(s));
75            }
76            v = v * 10 + i64::from(c - b'0');
77        }
78        Ok(v)
79    };
80    if b[4] != b'-' || b[7] != b'-' || b[10] != b'T' || b[13] != b':' || b[16] != b':' {
81        return Err(bad(s));
82    }
83    let year = digits(0, 4)?;
84    let month = digits(5, 2)?;
85    let day = digits(8, 2)?;
86    let hour = digits(11, 2)?;
87    let minute = digits(14, 2)?;
88    let second = digits(17, 2)?;
89    if !(1..=9999).contains(&year)
90        || !(1..=12).contains(&month)
91        || day < 1
92        || day > days_in_month(year, month)
93        || hour > 23
94        || minute > 59
95        || second > 59
96    {
97        return Err(bad(s));
98    }
99
100    let mut j = 19usize;
101    let mut nanos: i128 = 0;
102    if b[j] == b'.' {
103        j += 1;
104        let start = j;
105        while j < b.len() && b[j].is_ascii_digit() {
106            j += 1;
107        }
108        let n = j - start;
109        if n == 0 || n > 9 {
110            return Err(bad(s));
111        }
112        let mut v: i128 = 0;
113        for &c in &b[start..j] {
114            v = v * 10 + i128::from(c - b'0');
115        }
116        for _ in n..9 {
117            v *= 10;
118        }
119        nanos = v;
120    }
121    if j >= b.len() {
122        return Err(bad(s)); // no offset
123    }
124    let offset_seconds: i64 = match b[j] {
125        b'Z' => {
126            if j + 1 != b.len() {
127                return Err(bad(s));
128            }
129            0
130        }
131        b'+' | b'-' => {
132            if j + 6 != b.len() || b[j + 3] != b':' {
133                return Err(bad(s));
134            }
135            let oh = digits(j + 1, 2)?;
136            let om = digits(j + 4, 2)?;
137            if oh > 23 || om > 59 {
138                return Err(bad(s));
139            }
140            let mag = oh * 3600 + om * 60;
141            if b[j] == b'+' {
142                mag
143            } else {
144                -mag
145            }
146        }
147        _ => return Err(bad(s)),
148    };
149
150    let days = days_from_civil(year, month, day);
151    let seconds = days * 86_400 + hour * 3_600 + minute * 60 + second - offset_seconds;
152    let total = i128::from(seconds) * NS_PER_SECOND + nanos;
153    if !(MIN_NS..=MAX_NS).contains(&total) {
154        return Err(bad(s));
155    }
156    Ok(total)
157}
158
159/// Parse a protocol time to whole Unix epoch seconds (the floor of the exact
160/// instant). Uses the strict grammar of [`parse_protocol_time_ns`].
161///
162/// Whole seconds drop the fraction, so a validity comparison must use
163/// [`parse_protocol_time_ns`] instead; this remains for callers that only need
164/// second resolution (for example to derive and format a later time).
165pub fn iso_to_epoch_seconds(s: &str) -> Result<i64> {
166    let ns = parse_protocol_time_ns(s)?;
167    // The parser's range check keeps this well inside i64.
168    Ok(ns.div_euclid(NS_PER_SECOND) as i64)
169}
170
171/// Return the clock skew in nanoseconds when it is an allowed value (0 to
172/// [`MAX_CLOCK_SKEW_SECONDS`] seconds), else an error.
173pub fn check_clock_skew(clock_skew_seconds: i64) -> Result<i128> {
174    if !(0..=MAX_CLOCK_SKEW_SECONDS).contains(&clock_skew_seconds) {
175        return Err(CoreError::Json(format!(
176            "clock skew must be between 0 and {MAX_CLOCK_SKEW_SECONDS} seconds, got {clock_skew_seconds}"
177        )));
178    }
179    Ok(i128::from(clock_skew_seconds) * NS_PER_SECOND)
180}
181
182/// Read a clock skew from a JSON request: a whole number of seconds (an
183/// integral float such as 30.0 counts as 30) in 0 to
184/// [`MAX_CLOCK_SKEW_SECONDS`]. Booleans, strings, null, fractions and numbers
185/// outside the range are refused.
186pub fn clock_skew_from_json(value: &serde_json::Value) -> Result<i64> {
187    crate::attenuation::as_int(value, 0, MAX_CLOCK_SKEW_SECONDS).ok_or_else(|| {
188        CoreError::Json(format!(
189            "clock skew must be a whole number of seconds from 0 to {MAX_CLOCK_SKEW_SECONDS}"
190        ))
191    })
192}
193
194/// Seconds to nanoseconds, for comparing a whole-second bound (a max age, an
195/// interval) against parsed instants.
196pub fn seconds_to_ns(seconds: i64) -> i128 {
197    i128::from(seconds) * NS_PER_SECOND
198}
199
200/// Where `now` falls against a validity window.
201#[derive(Debug, Clone, Copy, PartialEq, Eq)]
202pub enum WindowState {
203    /// Inside the window (allowing the skew at each edge).
204    Ok,
205    /// `validFrom` is more than the skew ahead of `now`.
206    NotYetValid,
207    /// `now` is more than the skew past `validUntil`.
208    Expired,
209    /// `validFrom` is after `validUntil`: the window is empty.
210    Inverted,
211}
212
213impl WindowState {
214    pub fn as_str(self) -> &'static str {
215        match self {
216            WindowState::Ok => "ok",
217            WindowState::NotYetValid => "not_yet_valid",
218            WindowState::Expired => "expired",
219            WindowState::Inverted => "inverted",
220        }
221    }
222}
223
224/// Place `now_ns` against `[from - skew, until + skew]` at full precision. A
225/// missing bound is open on that side. An inverted window is reported first.
226pub fn window_state_ns(
227    now_ns: i128,
228    from_ns: Option<i128>,
229    until_ns: Option<i128>,
230    skew_ns: i128,
231) -> WindowState {
232    if let (Some(f), Some(u)) = (from_ns, until_ns) {
233        if f > u {
234            return WindowState::Inverted;
235        }
236    }
237    if let Some(f) = from_ns {
238        if f - now_ns > skew_ns {
239            return WindowState::NotYetValid;
240        }
241    }
242    if let Some(u) = until_ns {
243        if now_ns - u > skew_ns {
244            return WindowState::Expired;
245        }
246    }
247    WindowState::Ok
248}
249
250/// [`window_state_ns`] over protocol-time strings. Errors on a malformed time
251/// or an out-of-range skew.
252pub fn window_state(
253    now_iso: &str,
254    valid_from: Option<&str>,
255    valid_until: Option<&str>,
256    clock_skew_seconds: i64,
257) -> Result<WindowState> {
258    let skew = check_clock_skew(clock_skew_seconds)?;
259    let now = parse_protocol_time_ns(now_iso)?;
260    let from = valid_from.map(parse_protocol_time_ns).transpose()?;
261    let until = valid_until.map(parse_protocol_time_ns).transpose()?;
262    Ok(window_state_ns(now, from, until, skew))
263}
264
265/// Days since the Unix epoch (1970-01-01) for a civil date.
266/// Howard Hinnant's algorithm; valid for the full proleptic Gregorian range.
267fn days_from_civil(year: i64, month: i64, day: i64) -> i64 {
268    let y = if month <= 2 { year - 1 } else { year };
269    let era = (if y >= 0 { y } else { y - 399 }) / 400;
270    let yoe = y - era * 400;
271    let mp = if month > 2 { month - 3 } else { month + 9 };
272    let doy = (153 * mp + 2) / 5 + day - 1;
273    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
274    era * 146097 + doe - 719468
275}
276
277#[cfg(test)]
278mod tests {
279    use super::*;
280
281    #[test]
282    fn parses_known_instants() {
283        assert_eq!(iso_to_epoch_seconds("1970-01-01T00:00:00Z").unwrap(), 0);
284        assert_eq!(
285            iso_to_epoch_seconds("2026-04-26T10:00:00Z").unwrap(),
286            1777197600
287        );
288    }
289
290    #[test]
291    fn window_ordering() {
292        let a = iso_to_epoch_seconds("2026-04-26T10:00:00Z").unwrap();
293        let b = iso_to_epoch_seconds("2026-04-26T10:05:00Z").unwrap();
294        assert_eq!(b - a, 300);
295    }
296
297    #[test]
298    fn rejects_malformed_without_panic() {
299        for s in [
300            "",
301            "garbage",
302            "2026-13-99T10:00:00Z",
303            "20\u{00e9}6-04-26T10:00:00Z",
304            "2026-04-26 10:00:00",
305            "2026-04-26T10:0",
306            "2026-04-26T25:00:00Z",
307            "2026-04-26T10:00:00+9999",
308            "2026-04-26T10:00:00",
309            "2026-04-26T10:00:00z",
310            "2026-04-26t10:00:00Z",
311            "2026-02-29T10:00:00Z",
312            "2016-12-31T23:59:60Z",
313            "2026-04-26T10:00:00+24:00",
314            "2026-04-26T10:00:00Z\n",
315            "2026-04-26T10:00:00.Z",
316            "2026-04-26T10:00:00.1234567890Z",
317            "0000-01-01T00:00:00Z",
318            "0001-01-01T00:00:00+00:01",
319            "9999-12-31T23:59:59-00:01",
320            "2026-04-26T10:00:00\u{00e9}",
321            "2026-04-26T10:00:00.\u{00e9}Z",
322        ] {
323            assert!(parse_protocol_time_ns(s).is_err(), "{s:?} should error");
324        }
325    }
326
327    #[test]
328    fn keeps_fractions_and_offsets() {
329        let z = parse_protocol_time_ns("2026-04-26T10:00:00Z").unwrap();
330        assert_eq!(
331            parse_protocol_time_ns("2026-04-26T10:00:00.250Z").unwrap(),
332            z + 250_000_000
333        );
334        assert_eq!(
335            parse_protocol_time_ns("2026-04-26T10:00:00.000000001Z").unwrap(),
336            z + 1
337        );
338        assert_eq!(
339            parse_protocol_time_ns("2026-04-26T12:00:00+02:00").unwrap(),
340            z
341        );
342        assert_eq!(
343            iso_to_epoch_seconds("1969-12-31T23:59:59.5Z").unwrap(),
344            -1,
345            "whole seconds are the floor, also before the epoch"
346        );
347    }
348
349    #[test]
350    fn skew_bounds() {
351        assert!(check_clock_skew(0).is_ok());
352        assert!(check_clock_skew(120).is_ok());
353        for s in [-1, 121, i64::MAX, i64::MIN] {
354            assert!(check_clock_skew(s).is_err(), "{s}");
355        }
356    }
357
358    #[test]
359    fn window_edges() {
360        let w = |now, f, u, s| window_state(now, Some(f), Some(u), s).unwrap();
361        assert_eq!(
362            w(
363                "2026-04-26T11:00:00Z",
364                "2026-04-26T09:00:00Z",
365                "2026-04-26T11:00:00Z",
366                0
367            ),
368            WindowState::Ok
369        );
370        assert_eq!(
371            w(
372                "2026-04-26T11:00:00.000000001Z",
373                "2026-04-26T09:00:00Z",
374                "2026-04-26T11:00:00Z",
375                0
376            ),
377            WindowState::Expired
378        );
379        assert_eq!(
380            w(
381                "2026-04-26T10:00:00Z",
382                "2026-04-26T11:00:00Z",
383                "2026-04-26T09:00:00Z",
384                0
385            ),
386            WindowState::Inverted
387        );
388    }
389}