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