Skip to main content

vouch_core/
time_json.rs

1//! The protocol time rules for the language SDKs, as JSON.
2//!
3//! The grammar, the window check and the clock-skew rule live in
4//! [`crate::time`]; this module gives them to the SDKs with the Python
5//! reference's refusal texts (`vouch.timefmt.ProtocolTimeError`), so every
6//! language refuses a time with the same words. The SDKs keep only the
7//! conversions between their own clock types and protocol times.
8
9#[allow(unused_imports)]
10use crate::prelude::*;
11
12use serde_json::{json, Value};
13
14use crate::error::{CoreError, Result};
15use crate::time::{self, WindowState, MAX_CLOCK_SKEW_SECONDS};
16
17const NS_PER_SECOND: i128 = 1_000_000_000;
18const MIN_NS: i128 = -62_135_596_800 * NS_PER_SECOND;
19const MAX_NS: i128 = 253_402_300_799 * NS_PER_SECOND + 999_999_999;
20
21fn refuse(msg: String) -> CoreError {
22    CoreError::Json(msg)
23}
24
25/// The first 64 characters of a value, quoted as Python's `repr` quotes them.
26fn quoted(value: &str) -> String {
27    let head: String = value.chars().take(64).collect();
28    crate::grant_chain::py_repr_str(&head)
29}
30
31/// The type name the reference names for a JSON value that is not text.
32pub fn py_type_name(v: &Value) -> &'static str {
33    match v {
34        Value::Null => "NoneType",
35        Value::Bool(_) => "bool",
36        Value::Number(n) if n.is_f64() => "float",
37        Value::Number(_) => "int",
38        Value::String(_) => "str",
39        Value::Array(_) => "list",
40        Value::Object(_) => "dict",
41    }
42}
43
44/// Parse a protocol time to nanoseconds since the epoch, refusing with the
45/// reference's text: the grammar, then the year, month, calendar day, time
46/// of day and offset ranges, then the UTC range.
47pub fn parse_ns(value: &str) -> Result<i128> {
48    let b = value.as_bytes();
49    let not_time = || refuse(format!("not a protocol time: {}", quoted(value)));
50    let digits = |from: usize, len: usize| -> Option<i64> {
51        let part = b.get(from..from + len)?;
52        part.iter().all(u8::is_ascii_digit).then(|| {
53            part.iter()
54                .fold(0i64, |acc, d| acc * 10 + i64::from(d - b'0'))
55        })
56    };
57    let at = |i: usize, c: u8| b.get(i) == Some(&c);
58    // (\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})
59    let fields = (|| {
60        if !(at(4, b'-') && at(7, b'-') && at(10, b'T') && at(13, b':') && at(16, b':')) {
61            return None;
62        }
63        Some((
64            digits(0, 4)?,
65            digits(5, 2)?,
66            digits(8, 2)?,
67            digits(11, 2)?,
68            digits(14, 2)?,
69            digits(17, 2)?,
70        ))
71    })();
72    let Some((year, month, day, hour, minute, second)) = fields else {
73        return Err(not_time());
74    };
75    // (?:\.(\d{1,9}))?
76    let mut j = 19;
77    let mut nanos: i128 = 0;
78    if at(j, b'.') {
79        let start = j + 1;
80        let mut end = start;
81        while end < b.len() && b[end].is_ascii_digit() {
82            end += 1;
83        }
84        let n = end - start;
85        if n == 0 || n > 9 {
86            return Err(not_time());
87        }
88        for &d in &b[start..end] {
89            nanos = nanos * 10 + i128::from(d - b'0');
90        }
91        for _ in n..9 {
92            nanos *= 10;
93        }
94        j = end;
95    }
96    // (Z|[+-]\d{2}:\d{2}), and nothing after it.
97    let offset = match b.get(j) {
98        Some(b'Z') if j + 1 == b.len() => None,
99        Some(sign @ (b'+' | b'-')) if j + 6 == b.len() && at(j + 3, b':') => {
100            match (digits(j + 1, 2), digits(j + 4, 2)) {
101                (Some(h), Some(m)) => Some((*sign, h, m)),
102                _ => return Err(not_time()),
103            }
104        }
105        _ => return Err(not_time()),
106    };
107    let range = |what: &str| refuse(format!("{what}: {}", quoted(value)));
108    if !(1..=9999).contains(&year) {
109        return Err(range("year out of range"));
110    }
111    if !(1..=12).contains(&month) {
112        return Err(range("month out of range"));
113    }
114    if day < 1 || day > days_in_month(year, month) {
115        return Err(range("no such calendar day"));
116    }
117    if hour > 23 || minute > 59 || second > 59 {
118        return Err(range("time of day out of range"));
119    }
120    let offset_seconds = match offset {
121        None => 0,
122        Some((sign, h, m)) => {
123            if h > 23 || m > 59 {
124                return Err(range("offset out of range"));
125            }
126            (h * 3600 + m * 60) * if sign == b'+' { 1 } else { -1 }
127        }
128    };
129    let seconds = days_from_civil(year, month, day) * 86_400 + hour * 3_600 + minute * 60 + second
130        - offset_seconds;
131    let total = i128::from(seconds) * NS_PER_SECOND + nanos;
132    if !(MIN_NS..=MAX_NS).contains(&total) {
133        return Err(range("instant out of range once moved to UTC"));
134    }
135    Ok(total)
136}
137
138fn days_in_month(year: i64, month: i64) -> i64 {
139    match month {
140        2 if year % 4 == 0 && (year % 100 != 0 || year % 400 == 0) => 29,
141        2 => 28,
142        4 | 6 | 9 | 11 => 30,
143        _ => 31,
144    }
145}
146
147fn days_from_civil(year: i64, month: i64, day: i64) -> i64 {
148    let y = if month <= 2 { year - 1 } else { year };
149    let era = (if y >= 0 { y } else { y - 399 }).div_euclid(400);
150    let yoe = y - era * 400;
151    let mp = (month + 9) % 12;
152    let doy = (153 * mp + 2) / 5 + day - 1;
153    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
154    era * 146_097 + doe - 719_468
155}
156
157/// A JSON value as a protocol time: text that follows the grammar.
158pub fn parse_value_ns(v: &Value) -> Result<i128> {
159    match v {
160        Value::String(s) => parse_ns(s),
161        other => Err(refuse(format!(
162            "a protocol time is a string, not {}",
163            py_type_name(other)
164        ))),
165    }
166}
167
168/// An allowed clock skew (a whole number of seconds from 0 to 120; a float
169/// only when whole), with the reference's refusals.
170pub fn check_skew(v: &Value) -> Result<i64> {
171    let Value::Number(n) = v else {
172        return Err(refuse(format!(
173            "clock skew must be a number of seconds, not {}",
174            py_type_name(v)
175        )));
176    };
177    let whole = if let Some(i) = n.as_i64() {
178        Some(i as f64)
179    } else if let Some(u) = n.as_u64() {
180        Some(u as f64)
181    } else {
182        n.as_f64()
183    };
184    let f = whole.unwrap_or(f64::NAN);
185    if !f.is_finite() {
186        return Err(refuse("clock skew must be finite".into()));
187    }
188    if crate::float::fract(f) != 0.0 {
189        return Err(refuse(
190            "clock skew must be a whole number of seconds".into(),
191        ));
192    }
193    if f < 0.0 || f > MAX_CLOCK_SKEW_SECONDS as f64 {
194        return Err(refuse(format!(
195            "clock skew must be between 0 and {MAX_CLOCK_SKEW_SECONDS} seconds"
196        )));
197    }
198    Ok(f as i64)
199}
200
201/// `{"ns": decimal text, "epochSeconds", "nanos"}` for an instant.
202fn instant_json(ns: i128) -> Value {
203    json!({
204        "ns": ns.to_string(),
205        "epochSeconds": ns.div_euclid(NS_PER_SECOND) as i64,
206        "nanos": ns.rem_euclid(NS_PER_SECOND) as i64,
207    })
208}
209
210fn optional_bound(request: &Value, name: &str) -> Result<Option<i128>> {
211    match request.get(name) {
212        None | Some(Value::Null) => Ok(None),
213        Some(v) => parse_value_ns(v).map(Some),
214    }
215}
216
217/// The time rules, `{"op": ...}` in:
218///
219/// * `parse` `{value}` -> `{ns, epochSeconds, nanos}` (`ns` as decimal
220///   text); a refusal is an error with the reference's text.
221/// * `isTime` `{value}` -> `{ok}`.
222/// * `window` `{now, validFrom?, validUntil?, clockSkewSeconds?}` ->
223///   `{state}`: "ok", "not_yet_valid", "expired" or "inverted" (checked
224///   first). The skew is checked before the times.
225/// * `checkSkew` `{seconds}` -> `{seconds}`.
226/// * `compare` `{a, b}` -> `{sign}`: -1, 0 or 1 at full precision.
227/// * `format` `{epochSeconds}` -> `{text}`: `YYYY-MM-DDTHH:MM:SSZ`.
228pub fn rules_json(request: &Value) -> Result<Value> {
229    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); request);
230    let op = request
231        .get("op")
232        .and_then(Value::as_str)
233        .ok_or_else(|| refuse("op is required".into()))?;
234    let field = |name: &str| request.get(name).unwrap_or(&Value::Null);
235    match op {
236        "parse" => Ok(instant_json(parse_value_ns(field("value"))?)),
237        "isTime" => Ok(json!({"ok": parse_value_ns(field("value")).is_ok()})),
238        "window" => {
239            let skew = match request.get("clockSkewSeconds") {
240                None => 0,
241                Some(v) => check_skew(v)?,
242            };
243            let now = parse_value_ns(field("now"))?;
244            let from = optional_bound(request, "validFrom")?;
245            let until = optional_bound(request, "validUntil")?;
246            let state: WindowState =
247                time::window_state_ns(now, from, until, time::seconds_to_ns(skew));
248            Ok(json!({"state": state.as_str()}))
249        }
250        "checkSkew" => Ok(json!({"seconds": check_skew(field("seconds"))?})),
251        "compare" => {
252            let a = parse_value_ns(field("a"))?;
253            let b = parse_value_ns(field("b"))?;
254            Ok(json!({"sign": a.cmp(&b) as i8}))
255        }
256        "format" => {
257            let secs = field("epochSeconds")
258                .as_i64()
259                .ok_or_else(|| refuse("epochSeconds must be a whole number".into()))?;
260            if !(MIN_NS / NS_PER_SECOND..=MAX_NS / NS_PER_SECOND).contains(&i128::from(secs)) {
261                return Err(refuse(
262                    "the instant is outside the years 0001-9999 in UTC".into(),
263                ));
264            }
265            Ok(json!({"text": time::epoch_seconds_to_iso(secs)}))
266        }
267        other => Err(refuse(format!(
268            "unknown time op {}",
269            crate::grant_chain::py_repr_str(other)
270        ))),
271    }
272}
273
274#[cfg(test)]
275mod tests {
276    use super::*;
277
278    fn vector() -> Value {
279        let path = format!(
280            "{}/../../test-vectors/time/vector.json",
281            env!("CARGO_MANIFEST_DIR")
282        );
283        serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap()
284    }
285
286    #[test]
287    fn parse_matches_the_vector_and_the_core_grammar() {
288        let v = vector();
289        for case in v["parse"].as_array().unwrap() {
290            let input = case["input"].as_str().unwrap();
291            let got = parse_ns(input);
292            assert_eq!(got.is_ok(), case["valid"].as_bool().unwrap(), "{input}");
293            assert_eq!(
294                got.is_ok(),
295                time::parse_protocol_time_ns(input).is_ok(),
296                "{input}"
297            );
298            if let Ok(ns) = got {
299                assert_eq!(
300                    ns.div_euclid(NS_PER_SECOND) as i64,
301                    case["epoch_seconds"].as_i64().unwrap()
302                );
303                assert_eq!(
304                    ns.rem_euclid(NS_PER_SECOND) as i64,
305                    case["nanos"].as_i64().unwrap()
306                );
307            }
308        }
309        for case in v["non_string"].as_array().unwrap() {
310            let value = case.get("input").unwrap_or(case);
311            assert!(parse_value_ns(value).is_err());
312        }
313    }
314
315    #[test]
316    fn refusal_texts_are_the_references() {
317        assert_eq!(
318            parse_ns("2026-02-30T00:00:00Z").unwrap_err(),
319            refuse("no such calendar day: '2026-02-30T00:00:00Z'".into())
320        );
321        assert_eq!(
322            parse_ns("nope").unwrap_err(),
323            refuse("not a protocol time: 'nope'".into())
324        );
325        assert_eq!(
326            check_skew(&json!(0.5)).unwrap_err(),
327            refuse("clock skew must be a whole number of seconds".into())
328        );
329        assert_eq!(check_skew(&json!(30.0)).unwrap(), 30);
330        assert_eq!(
331            check_skew(&json!(true)).unwrap_err(),
332            refuse("clock skew must be a number of seconds, not bool".into())
333        );
334    }
335
336    #[test]
337    fn window_and_clock_skew_match_the_vector() {
338        let v = vector();
339        for case in v["window"].as_array().unwrap() {
340            let mut req = case.clone();
341            req["op"] = json!("window");
342            let obj = req.as_object_mut().unwrap();
343            for (from, to) in [
344                ("valid_from", "validFrom"),
345                ("valid_until", "validUntil"),
346                ("clock_skew_seconds", "clockSkewSeconds"),
347                ("skew", "clockSkewSeconds"),
348            ] {
349                if let Some(x) = obj.remove(from) {
350                    obj.insert(to.into(), x);
351                }
352            }
353            if let Some(want) = case.get("expected").and_then(Value::as_str) {
354                assert_eq!(rules_json(&req).unwrap()["state"], json!(want), "{case}");
355            }
356        }
357        for case in v["clock_skew"].as_array().unwrap() {
358            let ok = check_skew(case.get("input").unwrap_or(&Value::Null)).is_ok();
359            assert_eq!(ok, case["valid"].as_bool().unwrap(), "{case}");
360        }
361    }
362}