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/// Format whole seconds since the Unix epoch as `YYYY-MM-DDTHH:MM:SSZ`, the
172/// inverse of [`iso_to_epoch_seconds`] for whole-second UTC instants. The
173/// wrappers use it to turn the host clock into the `now` a verifier passes to
174/// the core.
175pub fn epoch_seconds_to_iso(epoch: i64) -> String {
176    let days = epoch.div_euclid(86_400);
177    let secs = epoch.rem_euclid(86_400);
178    // Howard Hinnant's civil-from-days.
179    let z = days + 719_468;
180    let era = (if z >= 0 { z } else { z - 146_096 }) / 146_097;
181    let doe = z - era * 146_097;
182    let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
183    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
184    let mp = (5 * doy + 2) / 153;
185    let d = doy - (153 * mp + 2) / 5 + 1;
186    let m = if mp < 10 { mp + 3 } else { mp - 9 };
187    let y = yoe + era * 400 + i64::from(m <= 2);
188    format!(
189        "{y:04}-{m:02}-{d:02}T{:02}:{:02}:{:02}Z",
190        secs / 3600,
191        (secs % 3600) / 60,
192        secs % 60
193    )
194}
195
196/// Return the clock skew in nanoseconds when it is an allowed value (0 to
197/// [`MAX_CLOCK_SKEW_SECONDS`] seconds), else an error.
198pub fn check_clock_skew(clock_skew_seconds: i64) -> Result<i128> {
199    if !(0..=MAX_CLOCK_SKEW_SECONDS).contains(&clock_skew_seconds) {
200        return Err(CoreError::Json(format!(
201            "clock skew must be between 0 and {MAX_CLOCK_SKEW_SECONDS} seconds, got {clock_skew_seconds}"
202        )));
203    }
204    Ok(i128::from(clock_skew_seconds) * NS_PER_SECOND)
205}
206
207/// Read a clock skew from a JSON request: a whole number of seconds (an
208/// integral float such as 30.0 counts as 30) in 0 to
209/// [`MAX_CLOCK_SKEW_SECONDS`]. Booleans, strings, null, fractions and numbers
210/// outside the range are refused.
211pub fn clock_skew_from_json(value: &serde_json::Value) -> Result<i64> {
212    crate::attenuation::as_int(value, 0, MAX_CLOCK_SKEW_SECONDS).ok_or_else(|| {
213        CoreError::Json(format!(
214            "clock skew must be a whole number of seconds from 0 to {MAX_CLOCK_SKEW_SECONDS}"
215        ))
216    })
217}
218
219/// Seconds to nanoseconds, for comparing a whole-second bound (a max age, an
220/// interval) against parsed instants.
221pub fn seconds_to_ns(seconds: i64) -> i128 {
222    i128::from(seconds) * NS_PER_SECOND
223}
224
225/// Where `now` falls against a validity window.
226#[derive(Debug, Clone, Copy, PartialEq, Eq)]
227pub enum WindowState {
228    /// Inside the window (allowing the skew at each edge).
229    Ok,
230    /// `validFrom` is more than the skew ahead of `now`.
231    NotYetValid,
232    /// `now` is more than the skew past `validUntil`.
233    Expired,
234    /// `validFrom` is after `validUntil`: the window is empty.
235    Inverted,
236}
237
238impl WindowState {
239    pub fn as_str(self) -> &'static str {
240        match self {
241            WindowState::Ok => "ok",
242            WindowState::NotYetValid => "not_yet_valid",
243            WindowState::Expired => "expired",
244            WindowState::Inverted => "inverted",
245        }
246    }
247}
248
249/// Place `now_ns` against `[from - skew, until + skew]` at full precision. A
250/// missing bound is open on that side. An inverted window is reported first.
251pub fn window_state_ns(
252    now_ns: i128,
253    from_ns: Option<i128>,
254    until_ns: Option<i128>,
255    skew_ns: i128,
256) -> WindowState {
257    if let (Some(f), Some(u)) = (from_ns, until_ns) {
258        if f > u {
259            return WindowState::Inverted;
260        }
261    }
262    if let Some(f) = from_ns {
263        if f - now_ns > skew_ns {
264            return WindowState::NotYetValid;
265        }
266    }
267    if let Some(u) = until_ns {
268        if now_ns - u > skew_ns {
269            return WindowState::Expired;
270        }
271    }
272    WindowState::Ok
273}
274
275/// [`window_state_ns`] over protocol-time strings. Errors on a malformed time
276/// or an out-of-range skew.
277pub fn window_state(
278    now_iso: &str,
279    valid_from: Option<&str>,
280    valid_until: Option<&str>,
281    clock_skew_seconds: i64,
282) -> Result<WindowState> {
283    let skew = check_clock_skew(clock_skew_seconds)?;
284    let now = parse_protocol_time_ns(now_iso)?;
285    let from = valid_from.map(parse_protocol_time_ns).transpose()?;
286    let until = valid_until.map(parse_protocol_time_ns).transpose()?;
287    Ok(window_state_ns(now, from, until, skew))
288}
289
290/// Days since the Unix epoch (1970-01-01) for a civil date.
291/// Howard Hinnant's algorithm; valid for the full proleptic Gregorian range.
292fn days_from_civil(year: i64, month: i64, day: i64) -> i64 {
293    let y = if month <= 2 { year - 1 } else { year };
294    let era = (if y >= 0 { y } else { y - 399 }) / 400;
295    let yoe = y - era * 400;
296    let mp = if month > 2 { month - 3 } else { month + 9 };
297    let doy = (153 * mp + 2) / 5 + day - 1;
298    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
299    era * 146097 + doe - 719468
300}
301
302#[cfg(test)]
303mod tests {
304    use super::*;
305
306    #[test]
307    fn epoch_seconds_to_iso_round_trips() {
308        for iso in [
309            "1970-01-01T00:00:00Z",
310            "2000-02-29T23:59:59Z",
311            "2026-12-03T09:54:03Z",
312            "2100-03-01T00:00:00Z",
313            "9999-12-31T23:59:59Z",
314        ] {
315            let secs = iso_to_epoch_seconds(iso).unwrap();
316            assert_eq!(epoch_seconds_to_iso(secs), iso);
317        }
318    }
319
320    #[test]
321    fn parses_known_instants() {
322        assert_eq!(iso_to_epoch_seconds("1970-01-01T00:00:00Z").unwrap(), 0);
323        assert_eq!(
324            iso_to_epoch_seconds("2026-04-26T10:00:00Z").unwrap(),
325            1777197600
326        );
327    }
328
329    #[test]
330    fn window_ordering() {
331        let a = iso_to_epoch_seconds("2026-04-26T10:00:00Z").unwrap();
332        let b = iso_to_epoch_seconds("2026-04-26T10:05:00Z").unwrap();
333        assert_eq!(b - a, 300);
334    }
335
336    #[test]
337    fn rejects_malformed_without_panic() {
338        for s in [
339            "",
340            "garbage",
341            "2026-13-99T10:00:00Z",
342            "20\u{00e9}6-04-26T10:00:00Z",
343            "2026-04-26 10:00:00",
344            "2026-04-26T10:0",
345            "2026-04-26T25:00:00Z",
346            "2026-04-26T10:00:00+9999",
347            "2026-04-26T10:00:00",
348            "2026-04-26T10:00:00z",
349            "2026-04-26t10:00:00Z",
350            "2026-02-29T10:00:00Z",
351            "2016-12-31T23:59:60Z",
352            "2026-04-26T10:00:00+24:00",
353            "2026-04-26T10:00:00Z\n",
354            "2026-04-26T10:00:00.Z",
355            "2026-04-26T10:00:00.1234567890Z",
356            "0000-01-01T00:00:00Z",
357            "0001-01-01T00:00:00+00:01",
358            "9999-12-31T23:59:59-00:01",
359            "2026-04-26T10:00:00\u{00e9}",
360            "2026-04-26T10:00:00.\u{00e9}Z",
361        ] {
362            assert!(parse_protocol_time_ns(s).is_err(), "{s:?} should error");
363        }
364    }
365
366    #[test]
367    fn keeps_fractions_and_offsets() {
368        let z = parse_protocol_time_ns("2026-04-26T10:00:00Z").unwrap();
369        assert_eq!(
370            parse_protocol_time_ns("2026-04-26T10:00:00.250Z").unwrap(),
371            z + 250_000_000
372        );
373        assert_eq!(
374            parse_protocol_time_ns("2026-04-26T10:00:00.000000001Z").unwrap(),
375            z + 1
376        );
377        assert_eq!(
378            parse_protocol_time_ns("2026-04-26T12:00:00+02:00").unwrap(),
379            z
380        );
381        assert_eq!(
382            iso_to_epoch_seconds("1969-12-31T23:59:59.5Z").unwrap(),
383            -1,
384            "whole seconds are the floor, also before the epoch"
385        );
386    }
387
388    #[test]
389    fn skew_bounds() {
390        assert!(check_clock_skew(0).is_ok());
391        assert!(check_clock_skew(120).is_ok());
392        for s in [-1, 121, i64::MAX, i64::MIN] {
393            assert!(check_clock_skew(s).is_err(), "{s}");
394        }
395    }
396
397    #[test]
398    fn window_edges() {
399        let w = |now, f, u, s| window_state(now, Some(f), Some(u), s).unwrap();
400        assert_eq!(
401            w(
402                "2026-04-26T11:00:00Z",
403                "2026-04-26T09:00:00Z",
404                "2026-04-26T11:00:00Z",
405                0
406            ),
407            WindowState::Ok
408        );
409        assert_eq!(
410            w(
411                "2026-04-26T11:00:00.000000001Z",
412                "2026-04-26T09:00:00Z",
413                "2026-04-26T11:00:00Z",
414                0
415            ),
416            WindowState::Expired
417        );
418        assert_eq!(
419            w(
420                "2026-04-26T10:00:00Z",
421                "2026-04-26T11:00:00Z",
422                "2026-04-26T09:00:00Z",
423                0
424            ),
425            WindowState::Inverted
426        );
427    }
428}