Skip to main content

decision_cert/
lib.rs

1//! Load, verify and apply decision certificates: `decision-certificate.v1`
2//! (spec/decision-certificate.v1.md) and `decision-certificate.v1.1` (spec/decision-certificate.v1.1.md).
3//!
4//! Verification canonicalises the JSON value exactly as received (RFC 8785, JCS), never a
5//! re-serialised struct, so number formatting can't drift from the issuer's. The typed
6//! [`Certificate`] is read from the same value afterwards, rejecting unknown fields.
7
8use std::collections::BTreeMap;
9
10use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};
11use chrono::{DateTime, Utc};
12use ed25519_dalek::{Signature, VerifyingKey};
13use serde::Deserialize;
14use sha2::{Digest, Sha256};
15
16/// The `spec` of a certificate produced by the v1 procedure.
17pub const SPEC: &str = "decision-certificate.v1";
18/// The `spec` of a certificate produced by the v1.1 procedure (the per-test grid start).
19pub const SPEC_V1_1: &str = "decision-certificate.v1.1";
20/// Every `spec` this verifier accepts. The fields, and so the checks, are the same for each.
21pub const SPECS: [&str; 2] = [SPEC, SPEC_V1_1];
22/// `abstain_below` that abstains on every case (as `dk calibrate` writes it).
23pub const ABSTAIN_ALL: f64 = 1.01;
24
25#[derive(Debug, thiserror::Error)]
26pub enum CertError {
27    #[error("certificate is not a valid decision certificate: {0}")]
28    Invalid(String),
29    #[error("certificate signed by {0}, which is not a trusted key")]
30    UntrustedKey(String),
31    #[error("trusted key {0} is malformed or does not hash to its id")]
32    BadKey(String),
33    #[error("certificate signature does not verify")]
34    BadSignature,
35}
36
37#[derive(Deserialize, Clone, Debug, PartialEq)]
38#[serde(deny_unknown_fields)]
39pub struct Band {
40    pub level: f64,
41    pub low: f64,
42    pub high: f64,
43}
44
45#[derive(Deserialize, Clone, Debug, PartialEq)]
46#[serde(deny_unknown_fields)]
47pub struct Segment {
48    pub field: String,
49    pub value: String,
50    pub n: u64,
51    pub abstain_below: f64,
52    pub coverage: f64,
53    #[serde(deserialize_with = "nullable")]
54    pub ucb: Option<f64>,
55    #[serde(deserialize_with = "nullable")]
56    pub realized_band: Option<Band>,
57    pub inherited: bool,
58}
59
60#[derive(Deserialize, Clone, Debug, PartialEq)]
61#[serde(deny_unknown_fields)]
62pub struct Split {
63    pub method: String,
64    #[serde(deserialize_with = "nullable")]
65    pub seed: Option<i64>,
66}
67
68#[derive(Deserialize, Clone, Debug, PartialEq)]
69#[serde(deny_unknown_fields)]
70pub struct CalibrationMap {
71    pub kind: String,
72    pub params: BTreeMap<String, f64>,
73    #[serde(deserialize_with = "nullable")]
74    pub label_budget: Option<u64>,
75}
76
77#[derive(Deserialize, Clone, Debug, PartialEq)]
78#[serde(deny_unknown_fields)]
79pub struct Rule {
80    #[serde(deserialize_with = "nullable")]
81    pub cannot_tell_above: Option<f64>,
82    pub unscored: String,
83}
84
85#[derive(Deserialize, Clone, Debug, PartialEq)]
86#[serde(deny_unknown_fields)]
87pub struct Window {
88    pub start: String,
89    pub end: String,
90}
91
92#[derive(Deserialize, Clone, Debug, PartialEq)]
93#[serde(deny_unknown_fields)]
94pub struct Audit {
95    pub mode: String,
96    pub rate: f64,
97    pub n: u64,
98    pub propensity_logged: bool,
99}
100
101#[derive(Deserialize, Clone, Debug, PartialEq)]
102#[serde(deny_unknown_fields)]
103pub struct Issuer {
104    pub tool: String,
105    pub version: String,
106}
107
108/// Every field is required; `Option` fields must be present (as null): a missing field is an error.
109#[derive(Deserialize, Clone, Debug, PartialEq)]
110#[serde(deny_unknown_fields)]
111pub struct Certificate {
112    pub spec: String,
113    pub domain: String,
114    pub decision: String,
115    pub options: Vec<String>,
116    pub model_id: String,
117    #[serde(deserialize_with = "nullable")]
118    pub manifest_hash: Option<String>,
119    pub data_hash: String,
120    pub n_cal: u64,
121    pub n_temperature: u64,
122    pub split: Split,
123    pub calibration_map: CalibrationMap,
124    pub rule: Rule,
125    pub alpha: f64,
126    #[serde(deserialize_with = "nullable")]
127    pub delta: Option<f64>,
128    pub method: String,
129    pub risk: String,
130    pub n: u64,
131    pub abstain_below: f64,
132    pub coverage: f64,
133    #[serde(deserialize_with = "nullable")]
134    pub ucb: Option<f64>,
135    pub realized_band: Band,
136    pub segments: Vec<Segment>,
137    #[serde(deserialize_with = "nullable")]
138    pub window: Option<Window>,
139    pub fitted_at: String,
140    pub expires_at: String,
141    pub audit: Audit,
142    pub issuer: Issuer,
143    pub signer_key_id: String,
144    pub signature: String,
145}
146
147/// A present field that may be null. serde reads a missing `Option` as null, the spec does not:
148/// with `deserialize_with` and no `default`, a missing field is an error at every level.
149fn nullable<'de, D: serde::Deserializer<'de>, T: Deserialize<'de>>(
150    d: D,
151) -> Result<Option<T>, D::Error> {
152    Option::deserialize(d)
153}
154
155/// A certificate whose signature verified against a trusted key.
156#[derive(Clone, Debug, PartialEq)]
157pub struct Verified {
158    /// `sha256:<hex>` of the signed certificate's JCS bytes.
159    pub id: String,
160    pub cert: Certificate,
161    pub expires_at: DateTime<Utc>,
162}
163
164impl Verified {
165    /// The threshold for a case in `segment`: a certified segment's own, else the top-level one.
166    pub fn threshold_for(&self, segment: Option<&str>) -> f64 {
167        segment
168            .and_then(|v| {
169                self.cert
170                    .segments
171                    .iter()
172                    .find(|s| !s.inherited && s.value == v)
173            })
174            .map_or(self.cert.abstain_below, |s| s.abstain_below)
175    }
176
177    pub fn is_expired(&self, now: DateTime<Utc>) -> bool {
178        now >= self.expires_at
179    }
180
181    /// The temperature of a `kind: temperature` calibration map; None for other kinds.
182    pub fn temperature(&self) -> Option<f64> {
183        (self.cert.calibration_map.kind == "temperature")
184            .then(|| self.cert.calibration_map.params.get("temperature").copied())
185            .flatten()
186    }
187}
188
189/// The JCS bytes of a JSON value.
190pub fn canonical(v: &serde_json::Value) -> Result<Vec<u8>, CertError> {
191    serde_jcs::to_vec(v).map_err(|e| CertError::Invalid(format!("not canonicalisable: {e}")))
192}
193
194pub fn certificate_id(v: &serde_json::Value) -> Result<String, CertError> {
195    Ok(format!("sha256:{}", hex(&Sha256::digest(canonical(v)?))))
196}
197
198/// `ed25519:` + the first 16 hex chars of SHA-256 of the raw public key.
199pub fn key_id(key: &VerifyingKey) -> String {
200    format!("ed25519:{}", &hex(&Sha256::digest(key.as_bytes()))[..16])
201}
202
203/// Verify `v` against `keys` (key id → base64url raw public key) and read it.
204pub fn verify(
205    v: &serde_json::Value,
206    keys: &BTreeMap<String, String>,
207) -> Result<Verified, CertError> {
208    let obj = v
209        .as_object()
210        .ok_or_else(|| CertError::Invalid("not a JSON object".into()))?;
211    let cert: Certificate =
212        serde_json::from_value(v.clone()).map_err(|e| CertError::Invalid(e.to_string()))?;
213    check(&cert)?;
214
215    let raw = keys
216        .get(&cert.signer_key_id)
217        .ok_or_else(|| CertError::UntrustedKey(cert.signer_key_id.clone()))?;
218    let key = URL_SAFE_NO_PAD
219        .decode(raw)
220        .ok()
221        .and_then(|b| <[u8; 32]>::try_from(b).ok())
222        .and_then(|b| VerifyingKey::from_bytes(&b).ok())
223        .filter(|k| key_id(k) == cert.signer_key_id)
224        .ok_or_else(|| CertError::BadKey(cert.signer_key_id.clone()))?;
225    let sig = URL_SAFE_NO_PAD
226        .decode(&cert.signature)
227        .ok()
228        .and_then(|b| Signature::from_slice(&b).ok())
229        .ok_or(CertError::BadSignature)?;
230    let mut body = obj.clone();
231    body.remove("signature");
232    key.verify_strict(&canonical(&serde_json::Value::Object(body))?, &sig)
233        .map_err(|_| CertError::BadSignature)?;
234
235    Ok(Verified {
236        id: certificate_id(v)?,
237        expires_at: timestamp(&cert.expires_at)?,
238        cert,
239    })
240}
241
242/// The schema's constraints (spec/decision-certificate.v1.schema.json, and the v1.1 schema, which
243/// differs only in `spec`) that a typed read doesn't already enforce, so this verifier accepts
244/// exactly what the schemas accept.
245fn check(c: &Certificate) -> Result<(), CertError> {
246    let bad = |m: &str| Err(CertError::Invalid(m.to_string()));
247    let unit = |x: f64| (0.0..=1.0).contains(&x);
248    let open = |x: f64| x > 0.0 && x < 1.0;
249    let threshold = |x: f64| (0.0..=ABSTAIN_ALL).contains(&x);
250    if !SPECS.contains(&c.spec.as_str()) {
251        return bad("spec is not decision-certificate.v1 or decision-certificate.v1.1");
252    }
253    let mut seen = std::collections::BTreeSet::new();
254    if c.options.len() < 2 || !c.options.iter().all(|o| !o.is_empty() && seen.insert(o)) {
255        return bad("options needs at least 2 distinct non-empty ids");
256    }
257    if [
258        &c.domain,
259        &c.decision,
260        &c.calibration_map.kind,
261        &c.issuer.tool,
262        &c.issuer.version,
263    ]
264    .iter()
265    .any(|s| s.is_empty())
266    {
267        return bad("domain, decision, calibration_map.kind and issuer must be non-empty");
268    }
269    match (c.method.as_str(), c.risk.as_str(), c.delta, c.ucb) {
270        ("ltt", "selective_error", Some(d), _) if open(d) => {}
271        ("crc", "joint_error", None, None) => {}
272        _ => return bad("method, risk, delta and ucb disagree"),
273    }
274    if !open(c.alpha) || !threshold(c.abstain_below) || !unit(c.coverage) {
275        return bad("alpha, abstain_below or coverage out of range");
276    }
277    if c.ucb.is_some_and(|u| !unit(u)) || !band_ok(&c.realized_band) {
278        return bad("ucb or realized_band out of range");
279    }
280    for s in &c.segments {
281        if s.field.is_empty()
282            || !threshold(s.abstain_below)
283            || !unit(s.coverage)
284            || s.ucb.is_some_and(|u| !unit(u))
285            || s.realized_band.as_ref().is_some_and(|b| !band_ok(b))
286        {
287            return bad("a segment is out of range");
288        }
289    }
290    if !matches!(
291        (c.split.method.as_str(), c.split.seed),
292        ("time", None) | ("seeded", Some(_))
293    ) {
294        return bad("split.method and split.seed disagree");
295    }
296    if c.rule.unscored != "abstain" || c.rule.cannot_tell_above.is_some_and(|x| !unit(x)) {
297        return bad("rule out of range");
298    }
299    if !matches!(c.audit.mode.as_str(), "sample" | "full-label")
300        || !(c.audit.rate > 0.0 && c.audit.rate <= 1.0)
301    {
302        return bad("audit out of range");
303    }
304    if !model_id_ok(&c.model_id) {
305        return bad("model_id must be <backend>/<model>@<version>");
306    }
307    if !sha256_ok(&c.data_hash) || c.manifest_hash.as_deref().is_some_and(|h| !sha256_ok(h)) {
308        return bad("data_hash and manifest_hash must be sha256:<64 hex>");
309    }
310    let key_hex = c.signer_key_id.strip_prefix("ed25519:");
311    if !key_hex.is_some_and(|h| h.len() == 16 && lower_hex(h)) {
312        return bad("signer_key_id must be ed25519:<16 hex>");
313    }
314    if c.signature.len() != 86
315        || !c
316            .signature
317            .bytes()
318            .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
319    {
320        return bad("signature must be 86 base64url characters");
321    }
322    timestamp(&c.fitted_at)?;
323    timestamp(&c.expires_at)?;
324    if let Some(w) = &c.window {
325        timestamp(&w.start)?;
326        timestamp(&w.end)?;
327    }
328    Ok(())
329}
330
331/// `^[^/]+/.+@.+$`, and not ending in `@?` (an unknown version).
332fn model_id_ok(m: &str) -> bool {
333    // The pattern's `.` matches no line terminator.
334    if m.chars()
335        .any(|c| matches!(c, '\n' | '\r' | '\u{2028}' | '\u{2029}'))
336    {
337        return false;
338    }
339    let Some((backend, rest)) = m.split_once('/') else {
340        return false;
341    };
342    let at = rest
343        .char_indices()
344        .skip(1)
345        .any(|(i, ch)| ch == '@' && i + 1 < rest.len());
346    !backend.is_empty() && at && !m.ends_with("@?")
347}
348
349fn sha256_ok(h: &str) -> bool {
350    h.strip_prefix("sha256:")
351        .is_some_and(|x| x.len() == 64 && lower_hex(x))
352}
353
354fn lower_hex(s: &str) -> bool {
355    s.bytes()
356        .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
357}
358
359fn band_ok(b: &Band) -> bool {
360    b.level > 0.0 && b.level < 1.0 && (0.0..=1.0).contains(&b.low) && (0.0..=1.0).contains(&b.high)
361}
362
363/// Parse the spec's timestamp form, `YYYY-MM-DDTHH:MM:SSZ`, and nothing else.
364pub fn timestamp(s: &str) -> Result<DateTime<Utc>, CertError> {
365    // The schema's `^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$` exactly: chrono also takes `t` or a space.
366    let b = s.as_bytes();
367    let ok = b.len() == 20
368        && b.iter().enumerate().all(|(i, &c)| match i {
369            4 | 7 => c == b'-',
370            10 => c == b'T',
371            13 | 16 => c == b':',
372            19 => c == b'Z',
373            _ => c.is_ascii_digit(),
374        });
375    DateTime::parse_from_rfc3339(s)
376        .ok()
377        .filter(|_| ok)
378        .map(|t| t.with_timezone(&Utc))
379        .ok_or_else(|| CertError::Invalid(format!("timestamp {s:?} is not YYYY-MM-DDTHH:MM:SSZ")))
380}
381
382fn hex(b: &[u8]) -> String {
383    b.iter().map(|x| format!("{x:02x}")).collect()
384}
385
386#[cfg(test)]
387mod tests {
388    use super::*;
389
390    fn valid() -> serde_json::Value {
391        let f: serde_json::Value =
392            serde_json::from_str(include_str!("../../fixtures/valid_segments_unicode.json"))
393                .unwrap();
394        f["certificate"].clone()
395    }
396
397    #[test]
398    fn check_rejects_what_the_schema_rejects() {
399        let typed =
400            |v: &serde_json::Value| serde_json::from_value::<Certificate>(v.clone()).unwrap();
401        assert!(check(&typed(&valid())).is_ok());
402        let edits: [(&str, serde_json::Value); 15] = [
403            ("data_hash", serde_json::json!("sha256:XYZ")),
404            ("manifest_hash", serde_json::json!("md5:00")),
405            ("signer_key_id", serde_json::json!("ed25519:short")),
406            ("model_id", serde_json::json!("/x@y")),
407            ("model_id", serde_json::json!("b/m@?")),
408            (
409                "window",
410                serde_json::json!({"start": "2023-01-02", "end": "2023-12-29T23:59:59Z"}),
411            ),
412            ("expires_at", serde_json::json!("2027-01-23T12:00:00+00:00")),
413            ("expires_at", serde_json::json!("2027-01-23 12:00:00Z")),
414            ("fitted_at", serde_json::json!("2026-10-25t12:00:00Z")),
415            ("domain", serde_json::json!("")),
416            ("options", serde_json::json!(["yes", "yes"])),
417            ("split", serde_json::json!({"method": "time", "seed": 3})),
418            ("alpha", serde_json::json!(1.0)),
419            ("signature", serde_json::json!("abc")),
420            ("model_id", serde_json::json!("a/b\n@c")),
421        ];
422        for (field, value) in edits {
423            let mut v = valid();
424            v[field] = value.clone();
425            assert!(check(&typed(&v)).is_err(), "{field} = {value}");
426        }
427    }
428
429    #[test]
430    fn nested_nullable_fields_must_be_present() {
431        let paths: [(&str, &str); 5] = [
432            ("segments", "ucb"),
433            ("segments", "realized_band"),
434            ("split", "seed"),
435            ("calibration_map", "label_budget"),
436            ("rule", "cannot_tell_above"),
437        ];
438        for (outer, inner) in paths {
439            let mut v = valid();
440            let o = if outer == "segments" {
441                &mut v[outer][0]
442            } else {
443                &mut v[outer]
444            };
445            o.as_object_mut().unwrap().remove(inner);
446            let e = serde_json::from_value::<Certificate>(v).err();
447            assert!(
448                e.is_some_and(|e| e.to_string().contains(inner)),
449                "{outer}.{inner}"
450            );
451        }
452    }
453
454    /// The same table as python/tests/test_ed25519.py: every small-order encoding is a key
455    /// `verify_strict` refuses (the Python verifier must refuse the same ones).
456    #[test]
457    fn small_order_keys_are_weak() {
458        let table = [
459            "0100000000000000000000000000000000000000000000000000000000000000",
460            "ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f",
461            "0000000000000000000000000000000000000000000000000000000000000000",
462            "0000000000000000000000000000000000000000000000000000000000000080",
463            "26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05",
464            "26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85",
465            "c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a",
466            "c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa",
467            "0100000000000000000000000000000000000000000000000000000000000080",
468            "ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
469            "edffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f",
470            "edffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
471            "eeffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f",
472            "eeffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
473        ];
474        for h in table {
475            let b: [u8; 32] = (0..32)
476                .map(|i| u8::from_str_radix(&h[2 * i..2 * i + 2], 16).unwrap())
477                .collect::<Vec<_>>()
478                .try_into()
479                .unwrap();
480            let k = VerifyingKey::from_bytes(&b).unwrap_or_else(|e| panic!("{h}: {e}"));
481            assert!(k.is_weak(), "{h}");
482        }
483    }
484
485    #[test]
486    fn certified_segments_set_the_threshold_and_inherited_ones_do_not() {
487        let cert: Certificate = serde_json::from_value(valid()).unwrap();
488        let v = Verified {
489            id: String::new(),
490            expires_at: timestamp(&cert.expires_at).unwrap(),
491            cert,
492        };
493        assert_eq!(v.threshold_for(Some("east")), 0.9);
494        assert_eq!(
495            v.threshold_for(Some("z\u{fc}rich \u{2603}")),
496            v.cert.abstain_below
497        );
498        assert_eq!(v.threshold_for(None), v.cert.abstain_below);
499        assert!(
500            v.is_expired(v.expires_at)
501                && !v.is_expired(v.expires_at - chrono::Duration::seconds(1))
502        );
503    }
504}