Skip to main content

decision_cert/
lib.rs

1//! Load, verify and apply decision certificates: `decision-certificate.v1`
2//! (spec/decision-certificate.v1.md), `decision-certificate.v1.1` (spec/decision-certificate.v1.1.md)
3//! `decision-certificate.v1.2` (spec/decision-certificate.v1.2.md), `decision-certificate.v1.3`
4//! (spec/decision-certificate.v1.3.md), `decision-certificate.v1.4` (spec/decision-certificate.v1.4.md)
5//! and `decision-certificate.v1.5` (spec/decision-certificate.v1.5.md).
6//!
7//! Verification canonicalises the JSON value exactly as received (RFC 8785, JCS), never a
8//! re-serialised struct, so number formatting can't drift from the issuer's. The typed
9//! [`Certificate`] is read from the same value afterwards, rejecting unknown fields.
10//!
11//! A v1.2 certificate also stores the confidence histogram of its threshold split, so a consumer can
12//! monitor without labels: [`Histogram::of`] bins a window of use-time confidences and
13//! [`shift_score`] compares it with the stored one. The score is descriptive, a prompt to measure
14//! again; it never shows that the bound holds or has failed.
15//!
16//! [`probabilities`] applies a certificate's calibration map to a case's raw scores, for the map
17//! kinds v1.2 defines (`temperature` and `dr`, [`MAP_KINDS`]).
18//!
19//! A v1.3 certificate also names the options a consumer automates (`automate_options`) and reports,
20//! per test, the share and error of the answered cases whose answer is one of them ([`Automated`]).
21//!
22//! A v1.5 certificate also names its `tenant` and who signed it ([`Signer`]: the tenant as operator,
23//! or a hosting service for the tenant), and its signature covers the tenant. It is verified with
24//! the tenant the consumer expects and that tenant's moded keys: [`verify_for_tenant`]. [`verify`]
25//! keeps its meaning for v1 to v1.4 and refuses a v1.5 certificate.
26//!
27//! [`inclusion`] checks `decision-cert-inclusion.v1`
28//! (spec/decision-cert-inclusion.v1.md) offline: a bundle showing that a tenant's
29//! transparency log recorded a leaf in a checkpoint its witnesses cosigned
30//! ([`inclusion::verify_bundle`]), a consistency proof between two checkpoints
31//! ([`inclusion::verify_consistency`]), and the consumer's policy for a certificate without a bundle
32//! ([`inclusion::apply_policy`]).
33
34pub mod inclusion;
35mod map;
36mod monitor;
37
38pub use map::{confidence, probabilities, MAP_KINDS};
39pub use monitor::{bin_of, chi2_sf, shift_score, ShiftScore};
40
41use std::collections::BTreeMap;
42
43use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};
44use chrono::{DateTime, Utc};
45use ed25519_dalek::{Signature, VerifyingKey};
46use serde::Deserialize;
47use sha2::{Digest, Sha256};
48
49/// The `spec` of a certificate produced by the v1 procedure.
50pub const SPEC: &str = "decision-certificate.v1";
51/// The `spec` of a certificate produced by the v1.1 procedure (the per-test grid start).
52pub const SPEC_V1_1: &str = "decision-certificate.v1.1";
53/// The `spec` of a v1.2 certificate: v1.1's procedure, plus the stored confidence histogram.
54pub const SPEC_V1_2: &str = "decision-certificate.v1.2";
55/// The `spec` of a v1.3 certificate: v1.2, plus the automated options and their answered share and
56/// error per test.
57pub const SPEC_V1_3: &str = "decision-certificate.v1.3";
58/// The `spec` of a v1.4 certificate: v1.3, plus the cost risk `selective_cost`.
59pub const SPEC_V1_4: &str = "decision-certificate.v1.4";
60/// The `spec` of a v1.5 certificate: v1.4, plus `tenant` and `signer`, signed over bytes that bind
61/// the tenant.
62pub const SPEC_V1_5: &str = "decision-certificate.v1.5";
63/// Every `spec` this verifier accepts. v1 and v1.1 have the same fields; v1.2 adds some, v1.3 more,
64/// v1.4 more again, v1.5 more again.
65pub const SPECS: [&str; 6] = [SPEC, SPEC_V1_1, SPEC_V1_2, SPEC_V1_3, SPEC_V1_4, SPEC_V1_5];
66/// The context string a v1.5 signature's bytes start with (spec v1.5 §3).
67pub const CONTEXT_V1_5: &str = "decision-cert/certificate.v1.5";
68/// The longest `tenant` (spec v1.5 §2).
69pub const MAX_TENANT: usize = 128;
70/// Most bins a `confidence_bins` may define.
71pub const MAX_BINS: usize = 100;
72/// `abstain_below` that abstains on every case (as `dk calibrate` writes it).
73pub const ABSTAIN_ALL: f64 = 1.01;
74
75#[derive(Debug, thiserror::Error)]
76pub enum CertError {
77    #[error("certificate is not a valid decision certificate: {0}")]
78    Invalid(String),
79    #[error("certificate signed by {0}, which is not a trusted key")]
80    UntrustedKey(String),
81    #[error("trusted key {0} is malformed or does not hash to its id")]
82    BadKey(String),
83    #[error("certificate signature does not verify")]
84    BadSignature,
85    /// v1.5 check 1: the certificate's `tenant` is not the tenant the verifier expects.
86    #[error("certificate is for tenant {0}, not the expected tenant")]
87    WrongTenant(String),
88    /// v1.5 check 3 (and an earlier certificate under a hosted key): the key's entry does not allow
89    /// the certificate's signer mode, or its `host` is not the certificate's.
90    #[error("trusted key {0} may not sign in this mode")]
91    KeyMode(String),
92}
93
94#[derive(Deserialize, Clone, Debug, PartialEq)]
95#[serde(deny_unknown_fields)]
96pub struct Band {
97    pub level: f64,
98    pub low: f64,
99    pub high: f64,
100}
101
102/// A test's threshold-split cases per bin of `confidence_bins`, and the cases the rule abstains on
103/// whatever the threshold (unscored, or above the `cannot_tell` cut). v1.2.
104#[derive(Deserialize, Clone, Debug, PartialEq, Eq)]
105#[serde(deny_unknown_fields)]
106pub struct Histogram {
107    pub counts: Vec<u64>,
108    pub unscored: u64,
109}
110
111/// A test's answered cases whose answer is one of `automate_options` (v1.3): their share of the
112/// test's `n` cases, and `ucb` and `realized_band` of their error, as the test's own (descriptive,
113/// spec v1.2 §1.2). Null exactly where the test's are.
114#[derive(Deserialize, Clone, Debug, PartialEq)]
115#[serde(deny_unknown_fields)]
116pub struct Automated {
117    pub coverage: f64,
118    #[serde(deserialize_with = "nullable")]
119    pub ucb: Option<f64>,
120    #[serde(deserialize_with = "nullable")]
121    pub realized_band: Option<Band>,
122    /// v1.4 only (absent before v1.4): the automated cases' exact sum of whole costs under
123    /// `selective_cost`; present and null otherwise.
124    #[serde(default, deserialize_with = "present")]
125    pub loss_sum: Option<Option<u64>>,
126    /// v1.4 only (absent before v1.4): the automated cases' mean normalised cost under
127    /// `selective_cost`, `loss_sum / (c_max * answered)`; present and null otherwise.
128    #[serde(default, deserialize_with = "present")]
129    pub realized_cost: Option<Option<f64>>,
130}
131
132/// A v1.4 `selective_cost` certificate's costs: `matrix[label][answered option]`, in the options'
133/// order, whole numbers in the consumer's `unit` (informational), and its largest entry `c_max`.
134#[derive(Deserialize, Clone, Debug, PartialEq)]
135#[serde(deny_unknown_fields)]
136pub struct Cost {
137    pub matrix: Vec<Vec<u64>>,
138    pub c_max: u64,
139    #[serde(deserialize_with = "nullable")]
140    pub unit: Option<String>,
141}
142
143#[derive(Deserialize, Clone, Debug, PartialEq)]
144#[serde(deny_unknown_fields)]
145pub struct Segment {
146    pub field: String,
147    pub value: String,
148    pub n: u64,
149    pub abstain_below: f64,
150    pub coverage: f64,
151    #[serde(deserialize_with = "nullable")]
152    pub ucb: Option<f64>,
153    #[serde(deserialize_with = "nullable")]
154    pub realized_band: Option<Band>,
155    pub inherited: bool,
156    /// v1.2 only: absent (None) before v1.2; present and null (Some(None)) when withheld.
157    #[serde(default, deserialize_with = "present")]
158    pub confidence_histogram: Option<Option<Histogram>>,
159    /// v1.3 only: absent (None) before v1.3.
160    #[serde(default, deserialize_with = "present")]
161    pub automated: Option<Automated>,
162    /// v1.4 only: absent (None) before v1.4.
163    #[serde(default, deserialize_with = "present")]
164    pub loss_sum: Option<Option<u64>>,
165    /// v1.4 only: absent (None) before v1.4.
166    #[serde(default, deserialize_with = "present")]
167    pub realized_cost: Option<Option<f64>>,
168}
169
170#[derive(Deserialize, Clone, Debug, PartialEq)]
171#[serde(deny_unknown_fields)]
172pub struct Split {
173    pub method: String,
174    #[serde(deserialize_with = "nullable")]
175    pub seed: Option<i64>,
176}
177
178#[derive(Deserialize, Clone, Debug, PartialEq)]
179#[serde(deny_unknown_fields)]
180pub struct CalibrationMap {
181    pub kind: String,
182    pub params: BTreeMap<String, f64>,
183    #[serde(deserialize_with = "nullable")]
184    pub label_budget: Option<u64>,
185}
186
187#[derive(Deserialize, Clone, Debug, PartialEq)]
188#[serde(deny_unknown_fields)]
189pub struct Rule {
190    #[serde(deserialize_with = "nullable")]
191    pub cannot_tell_above: Option<f64>,
192    pub unscored: String,
193}
194
195#[derive(Deserialize, Clone, Debug, PartialEq)]
196#[serde(deny_unknown_fields)]
197pub struct Window {
198    pub start: String,
199    pub end: String,
200}
201
202#[derive(Deserialize, Clone, Debug, PartialEq)]
203#[serde(deny_unknown_fields)]
204pub struct Audit {
205    pub mode: String,
206    pub rate: f64,
207    pub n: u64,
208    pub propensity_logged: bool,
209}
210
211#[derive(Deserialize, Clone, Debug, PartialEq)]
212#[serde(deny_unknown_fields)]
213pub struct Issuer {
214    pub tool: String,
215    pub version: String,
216}
217
218/// Who signed a v1.5 certificate: `mode` `operator` (the tenant, with its own key; no `host`), or
219/// `hosted` (a hosting service for the tenant; `host` is the hosting service's own key id,
220/// `ed25519:<16 lowercase hex>`).
221#[derive(Deserialize, Clone, Debug, PartialEq, Eq)]
222#[serde(deny_unknown_fields)]
223pub struct Signer {
224    pub mode: String,
225    #[serde(default, deserialize_with = "present")]
226    pub host: Option<String>,
227}
228
229/// Every field is required; `Option` fields must be present (as null): a missing field is an error.
230#[derive(Deserialize, Clone, Debug, PartialEq)]
231#[serde(deny_unknown_fields)]
232pub struct Certificate {
233    pub spec: String,
234    pub domain: String,
235    pub decision: String,
236    pub options: Vec<String>,
237    pub model_id: String,
238    #[serde(deserialize_with = "nullable")]
239    pub manifest_hash: Option<String>,
240    pub data_hash: String,
241    pub n_cal: u64,
242    pub n_temperature: u64,
243    pub split: Split,
244    pub calibration_map: CalibrationMap,
245    pub rule: Rule,
246    pub alpha: f64,
247    #[serde(deserialize_with = "nullable")]
248    pub delta: Option<f64>,
249    pub method: String,
250    pub risk: String,
251    pub n: u64,
252    pub abstain_below: f64,
253    pub coverage: f64,
254    #[serde(deserialize_with = "nullable")]
255    pub ucb: Option<f64>,
256    pub realized_band: Band,
257    pub segments: Vec<Segment>,
258    #[serde(deserialize_with = "nullable")]
259    pub window: Option<Window>,
260    pub fitted_at: String,
261    pub expires_at: String,
262    pub audit: Audit,
263    pub issuer: Issuer,
264    pub signer_key_id: String,
265    pub signature: String,
266    /// v1.2 only (absent, so None, before v1.2): the histogram bin edges, rising from 0 to 1.
267    #[serde(default, deserialize_with = "present")]
268    pub confidence_bins: Option<Vec<f64>>,
269    /// v1.2 only: the remainder's histogram; present and null (Some(None)) when withheld.
270    #[serde(default, deserialize_with = "present")]
271    pub confidence_histogram: Option<Option<Histogram>>,
272    /// v1.3 only (absent before v1.3): the options a consumer decides automatically; a case answered
273    /// with another option goes to a person.
274    #[serde(default, deserialize_with = "present")]
275    pub automate_options: Option<Vec<String>>,
276    /// v1.3 only: the remainder's automated cases.
277    #[serde(default, deserialize_with = "present")]
278    pub automated: Option<Automated>,
279    /// v1.4 only (absent before v1.4): the costs of a `selective_cost` certificate; present and null
280    /// for the error risks.
281    #[serde(default, deserialize_with = "present")]
282    pub cost: Option<Option<Cost>>,
283    /// v1.4 only: the `ltt` p-value, `binomial` or `hoeffding_bentkus`; null for `crc`.
284    #[serde(default, deserialize_with = "present")]
285    pub pvalue: Option<Option<String>>,
286    /// v1.4 only: the remainder's exact sum of whole costs over its answered cases.
287    #[serde(default, deserialize_with = "present")]
288    pub loss_sum: Option<Option<u64>>,
289    /// v1.4 only: the remainder's mean normalised cost of its answered cases (descriptive).
290    #[serde(default, deserialize_with = "present")]
291    pub realized_cost: Option<Option<f64>>,
292    /// v1.5 only (absent before v1.5): the tenant the certificate is issued for.
293    #[serde(default, deserialize_with = "present")]
294    pub tenant: Option<String>,
295    /// v1.5 only: who signed, the tenant as operator or a hosting service for it.
296    #[serde(default, deserialize_with = "present")]
297    pub signer: Option<Signer>,
298}
299
300/// A field that may be absent (with `default`, as None) but, when present, is read as `T`: so a
301/// present null reads as `Some(None)` for `T = Option<_>`, and is an error for any other `T`.
302fn present<'de, D: serde::Deserializer<'de>, T: Deserialize<'de>>(
303    d: D,
304) -> Result<Option<T>, D::Error> {
305    T::deserialize(d).map(Some)
306}
307
308/// A present field that may be null. serde reads a missing `Option` as null, the spec does not:
309/// with `deserialize_with` and no `default`, a missing field is an error at every level.
310fn nullable<'de, D: serde::Deserializer<'de>, T: Deserialize<'de>>(
311    d: D,
312) -> Result<Option<T>, D::Error> {
313    Option::deserialize(d)
314}
315
316/// A certificate whose signature verified against a trusted key.
317#[derive(Clone, Debug, PartialEq)]
318pub struct Verified {
319    /// `sha256:<hex>` of the signed certificate's JCS bytes.
320    pub id: String,
321    pub cert: Certificate,
322    pub expires_at: DateTime<Utc>,
323}
324
325impl Verified {
326    /// The threshold for a case in `segment`: a certified segment's own, else the top-level one.
327    pub fn threshold_for(&self, segment: Option<&str>) -> f64 {
328        segment
329            .and_then(|v| {
330                self.cert
331                    .segments
332                    .iter()
333                    .find(|s| !s.inherited && s.value == v)
334            })
335            .map_or(self.cert.abstain_below, |s| s.abstain_below)
336    }
337
338    pub fn is_expired(&self, now: DateTime<Utc>) -> bool {
339        now >= self.expires_at
340    }
341
342    /// The bin edges of a v1.2 certificate's confidence histograms; None before v1.2.
343    pub fn confidence_bins(&self) -> Option<&[f64]> {
344        self.cert.confidence_bins.as_deref()
345    }
346
347    /// The stored confidence histogram of the cases decided by the same threshold as a case in
348    /// `segment`: a certified segment's own, else the top level's. None before v1.2, or when the
349    /// issuer withheld it.
350    pub fn histogram_for(&self, segment: Option<&str>) -> Option<&Histogram> {
351        let own = segment.and_then(|v| {
352            self.cert
353                .segments
354                .iter()
355                .find(|s| !s.inherited && s.value == v)
356        });
357        match own {
358            Some(s) => s.confidence_histogram.as_ref()?.as_ref(),
359            None => self.cert.confidence_histogram.as_ref()?.as_ref(),
360        }
361    }
362
363    /// The options a v1.3 certificate's consumer automates; None before v1.3. A consumer refuses a
364    /// certificate whose list differs from the options it automates (spec v1.3 §4).
365    pub fn automate_options(&self) -> Option<&[String]> {
366        self.cert.automate_options.as_deref()
367    }
368
369    /// The automated cases of the test that decides a case in `segment` (a certified segment's own,
370    /// else the top level's): their share and error. None before v1.3.
371    pub fn automated_for(&self, segment: Option<&str>) -> Option<&Automated> {
372        let own = segment.and_then(|v| {
373            self.cert
374                .segments
375                .iter()
376                .find(|s| !s.inherited && s.value == v)
377        });
378        match own {
379            Some(s) => s.automated.as_ref(),
380            None => self.cert.automated.as_ref(),
381        }
382    }
383
384    /// A v1.4 `selective_cost` certificate's costs; None otherwise. A consumer refuses a certificate
385    /// whose matrix differs from the costs it is configured with (spec v1.4 §4), and reports the
386    /// bound as `alpha * c_max` in `unit`.
387    pub fn cost(&self) -> Option<&Cost> {
388        self.cert.cost.as_ref().and_then(|c| c.as_ref())
389    }
390
391    /// A v1.5 certificate's tenant (equal to the expected tenant it was verified with); None before
392    /// v1.5.
393    pub fn tenant(&self) -> Option<&str> {
394        self.cert.tenant.as_deref()
395    }
396
397    /// Who signed a v1.5 certificate; None before v1.5.
398    pub fn signer(&self) -> Option<&Signer> {
399        self.cert.signer.as_ref()
400    }
401
402    /// The probabilities the certificate's calibration map gives a case's raw scores, one per
403    /// option (spec v1.2 §1, [`probabilities`]). None when the map's kind is not one this crate
404    /// applies ([`MAP_KINDS`]), its params do not fit that kind, or `scores` does not have one score
405    /// per option, or the map is `dr` in a certificate before v1.2, which did not define it. A
406    /// consumer refuses a certificate whose map it does not apply (spec v1.2 §4).
407    pub fn probabilities(&self, scores: &[f64]) -> Option<Vec<f64>> {
408        let defined = self.cert.calibration_map.kind == "temperature"
409            || self.cert.spec == SPEC_V1_2
410            || self.cert.spec == SPEC_V1_3
411            || self.cert.spec == SPEC_V1_4
412            || self.cert.spec == SPEC_V1_5;
413        (defined && scores.len() == self.cert.options.len())
414            .then(|| probabilities(&self.cert.calibration_map, scores))
415            .flatten()
416    }
417
418    /// A case's confidence: the largest of its [`Verified::probabilities`]. A case is answered when
419    /// this is at least [`Verified::threshold_for`] its segment (and the rule does not abstain on it).
420    pub fn confidence(&self, scores: &[f64]) -> Option<f64> {
421        self.probabilities(scores)
422            .map(|p| p.into_iter().fold(f64::NEG_INFINITY, f64::max))
423    }
424
425    /// The temperature of a `kind: temperature` calibration map; None for other kinds.
426    pub fn temperature(&self) -> Option<f64> {
427        (self.cert.calibration_map.kind == "temperature")
428            .then(|| self.cert.calibration_map.params.get("temperature").copied())
429            .flatten()
430    }
431}
432
433/// The JCS bytes of a JSON value.
434pub fn canonical(v: &serde_json::Value) -> Result<Vec<u8>, CertError> {
435    serde_jcs::to_vec(v).map_err(|e| CertError::Invalid(format!("not canonicalisable: {e}")))
436}
437
438pub fn certificate_id(v: &serde_json::Value) -> Result<String, CertError> {
439    Ok(format!("sha256:{}", hex(&Sha256::digest(canonical(v)?))))
440}
441
442/// `ed25519:` + the first 16 hex chars of SHA-256 of the raw public key.
443pub fn key_id(key: &VerifyingKey) -> String {
444    format!("ed25519:{}", &hex(&Sha256::digest(key.as_bytes()))[..16])
445}
446
447/// Verify `v` against `keys` (key id → base64url raw public key) and read it.
448///
449/// For v1 to v1.4. A v1.5 certificate binds a tenant, so it is refused here; verify it with the
450/// tenant the consumer expects, [`verify_for_tenant`].
451pub fn verify(
452    v: &serde_json::Value,
453    keys: &BTreeMap<String, String>,
454) -> Result<Verified, CertError> {
455    let (obj, cert) = read(v)?;
456    if cert.spec == SPEC_V1_5 {
457        return Err(CertError::Invalid(
458            "a v1.5 certificate is verified with its expected tenant (verify_for_tenant)".into(),
459        ));
460    }
461    let raw = keys
462        .get(&cert.signer_key_id)
463        .ok_or_else(|| CertError::UntrustedKey(cert.signer_key_id.clone()))?;
464    let key = public_key(raw, &cert.signer_key_id)?;
465    check_signature(&key, &cert, &bare_body(obj)?)?;
466    verified(v, cert)
467}
468
469/// The mode a trusted key may sign in (spec v1.5 §4): `Operator` (the tenant's own key, as every key
470/// in v1 to v1.4), or `Hosted` by the hosting service whose own key id is `host`.
471#[derive(Clone, Debug, PartialEq, Eq)]
472pub enum KeyMode {
473    Operator,
474    Hosted { host: String },
475}
476
477/// A trusted certificate-signing key of one tenant: the base64url raw Ed25519 public key, and the
478/// mode it may sign in.
479#[derive(Clone, Debug, PartialEq, Eq)]
480pub struct TrustedKey {
481    pub key: String,
482    pub mode: KeyMode,
483}
484
485/// One tenant's trusted keys: key id → [`TrustedKey`].
486pub type TenantKeys = BTreeMap<String, TrustedKey>;
487
488/// Read a tenant's trusted keys from a JSON object of key id → entry. An entry is a bare base64url
489/// string (an `operator` key, as in a v1 to v1.4 key map), `{"key": ..., "mode": "operator"}`, or
490/// `{"key": ..., "mode": "hosted", "host": "ed25519:<16 lowercase hex>"}` (spec v1.5 §4). Any
491/// other entry, an unknown field, or a `host` not in that form is refused as [`CertError::BadKey`].
492/// The key is checked against its id when a certificate is verified, as in [`verify`].
493pub fn tenant_keys_from_json(v: &serde_json::Value) -> Result<TenantKeys, CertError> {
494    let obj = v.as_object().ok_or_else(|| {
495        CertError::Invalid("trusted keys are not a JSON object of key id -> key entry".into())
496    })?;
497    let mut out = TenantKeys::new();
498    for (kid, entry) in obj {
499        let bad = || CertError::BadKey(kid.clone());
500        let trusted = match entry {
501            serde_json::Value::String(key) => TrustedKey {
502                key: key.clone(),
503                mode: KeyMode::Operator,
504            },
505            serde_json::Value::Object(e) => {
506                if e.keys()
507                    .any(|k| !matches!(k.as_str(), "key" | "mode" | "host"))
508                {
509                    return Err(bad());
510                }
511                let key = e.get("key").and_then(|k| k.as_str()).ok_or_else(bad)?;
512                let host = e.get("host");
513                let mode = match (e.get("mode").and_then(|m| m.as_str()), host) {
514                    (Some("operator"), None) => KeyMode::Operator,
515                    (Some("hosted"), Some(serde_json::Value::String(h))) if key_id_form(h) => {
516                        KeyMode::Hosted { host: h.clone() }
517                    }
518                    _ => return Err(bad()),
519                };
520                TrustedKey {
521                    key: key.to_string(),
522                    mode,
523                }
524            }
525            _ => return Err(bad()),
526        };
527        out.insert(kid.clone(), trusted);
528    }
529    Ok(out)
530}
531
532/// Verify `v` for the tenant the consumer expects, against that tenant's moded keys, and read it
533/// (spec v1.5 §4).
534///
535/// A v1.5 certificate: its `tenant` equals `tenant` (check 1, [`CertError::WrongTenant`]); its key
536/// is in `keys` and hashes to its id (check 2); the key's entry allows the certificate's signer mode,
537/// a hosted entry with the certificate's `host` (check 3, [`CertError::KeyMode`]); and the signature
538/// verifies strictly over `"decision-cert/certificate.v1.5" 0x0A tenant 0x0A JCS(body)`, built with
539/// the expected `tenant` (check 4). A v1 to v1.4 certificate binds no tenant: it verifies as with
540/// [`verify`], and only under an `operator` entry.
541pub fn verify_for_tenant(
542    v: &serde_json::Value,
543    tenant: &str,
544    keys: &TenantKeys,
545) -> Result<Verified, CertError> {
546    if !tenant_ok(tenant) {
547        return Err(CertError::Invalid(format!(
548            "the expected tenant must be 1 to {MAX_TENANT} characters of A-Z a-z 0-9 . _ : -"
549        )));
550    }
551    let (obj, cert) = read(v)?;
552    let kid = &cert.signer_key_id;
553    if cert.spec != SPEC_V1_5 {
554        let entry = keys
555            .get(kid)
556            .ok_or_else(|| CertError::UntrustedKey(kid.clone()))?;
557        let key = public_key(&entry.key, kid)?;
558        if entry.mode != KeyMode::Operator {
559            return Err(CertError::KeyMode(kid.clone()));
560        }
561        check_signature(&key, &cert, &bare_body(obj)?)?;
562        return verified(v, cert);
563    }
564    // check() has made both present, the tenant well-formed and the signer one of the two modes
565    let (Some(own), Some(signer)) = (&cert.tenant, &cert.signer) else {
566        return Err(CertError::Invalid(
567            "a v1.5 certificate needs tenant and signer".into(),
568        ));
569    };
570    if own != tenant {
571        return Err(CertError::WrongTenant(own.clone()));
572    }
573    let entry = keys
574        .get(kid)
575        .ok_or_else(|| CertError::UntrustedKey(kid.clone()))?;
576    let key = public_key(&entry.key, kid)?;
577    let allowed = match (&entry.mode, signer.mode.as_str()) {
578        (KeyMode::Operator, "operator") => true,
579        (KeyMode::Hosted { host }, "hosted") => signer.host.as_deref() == Some(host.as_str()),
580        _ => false,
581    };
582    if !allowed {
583        return Err(CertError::KeyMode(kid.clone()));
584    }
585    let mut msg = format!("{CONTEXT_V1_5}\n{tenant}\n").into_bytes();
586    msg.extend(bare_body(obj)?);
587    check_signature(&key, &cert, &msg)?;
588    verified(v, cert)
589}
590
591/// The value as a JSON object and its typed, checked certificate.
592fn read(
593    v: &serde_json::Value,
594) -> Result<(&serde_json::Map<String, serde_json::Value>, Certificate), CertError> {
595    let obj = v
596        .as_object()
597        .ok_or_else(|| CertError::Invalid("not a JSON object".into()))?;
598    let cert: Certificate =
599        serde_json::from_value(v.clone()).map_err(|e| CertError::Invalid(e.to_string()))?;
600    check(&cert)?;
601    Ok((obj, cert))
602}
603
604/// A trusted key's base64url raw public key, which must hash to `kid`.
605fn public_key(raw: &str, kid: &str) -> Result<VerifyingKey, CertError> {
606    URL_SAFE_NO_PAD
607        .decode(raw)
608        .ok()
609        .and_then(|b| <[u8; 32]>::try_from(b).ok())
610        .and_then(|b| VerifyingKey::from_bytes(&b).ok())
611        .filter(|k| key_id(k) == kid)
612        .ok_or_else(|| CertError::BadKey(kid.to_string()))
613}
614
615/// The JCS bytes of the certificate without `signature`.
616fn bare_body(obj: &serde_json::Map<String, serde_json::Value>) -> Result<Vec<u8>, CertError> {
617    let mut body = obj.clone();
618    body.remove("signature");
619    canonical(&serde_json::Value::Object(body))
620}
621
622/// `verify_strict` of the certificate's signature over `msg`.
623fn check_signature(key: &VerifyingKey, cert: &Certificate, msg: &[u8]) -> Result<(), CertError> {
624    let sig = URL_SAFE_NO_PAD
625        .decode(&cert.signature)
626        .ok()
627        .and_then(|b| Signature::from_slice(&b).ok())
628        .ok_or(CertError::BadSignature)?;
629    key.verify_strict(msg, &sig)
630        .map_err(|_| CertError::BadSignature)
631}
632
633fn verified(v: &serde_json::Value, cert: Certificate) -> Result<Verified, CertError> {
634    Ok(Verified {
635        id: certificate_id(v)?,
636        expires_at: timestamp(&cert.expires_at)?,
637        cert,
638    })
639}
640
641/// 1 to 128 characters of `A-Z a-z 0-9 . _ : -` (spec v1.5 §2).
642fn tenant_ok(t: &str) -> bool {
643    (1..=MAX_TENANT).contains(&t.len())
644        && t.bytes()
645            .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b':' | b'-'))
646}
647
648/// `ed25519:` and 16 lowercase hex characters: a key id's form.
649fn key_id_form(s: &str) -> bool {
650    s.strip_prefix("ed25519:")
651        .is_some_and(|h| h.len() == 16 && lower_hex(h))
652}
653
654/// The schema's constraints (spec/decision-certificate.v1.schema.json, the v1.1 schema, which
655/// differs only in `spec`, and the v1.2 schema) that a typed read doesn't already enforce, so this
656/// verifier accepts exactly what the schemas accept; and for v1.2, the histogram and calibration map
657/// checks the schema cannot express (spec v1.2 §2).
658fn check(c: &Certificate) -> Result<(), CertError> {
659    let bad = |m: &str| Err(CertError::Invalid(m.to_string()));
660    let unit = |x: f64| (0.0..=1.0).contains(&x);
661    let open = |x: f64| x > 0.0 && x < 1.0;
662    let threshold = |x: f64| (0.0..=ABSTAIN_ALL).contains(&x);
663    if !SPECS.contains(&c.spec.as_str()) {
664        return bad("spec is not decision-certificate.v1, decision-certificate.v1.1, decision-certificate.v1.2, decision-certificate.v1.3, decision-certificate.v1.4 or decision-certificate.v1.5");
665    }
666    fields_for_spec(c)?;
667    let mut seen = std::collections::BTreeSet::new();
668    if c.options.len() < 2 || !c.options.iter().all(|o| !o.is_empty() && seen.insert(o)) {
669        return bad("options needs at least 2 distinct non-empty ids");
670    }
671    if [
672        &c.domain,
673        &c.decision,
674        &c.calibration_map.kind,
675        &c.issuer.tool,
676        &c.issuer.version,
677    ]
678    .iter()
679    .any(|s| s.is_empty())
680    {
681        return bad("domain, decision, calibration_map.kind and issuer must be non-empty");
682    }
683    let v15 = c.spec == SPEC_V1_5;
684    let v14 = c.spec == SPEC_V1_4 || v15;
685    match (c.method.as_str(), c.risk.as_str(), c.delta, c.ucb) {
686        ("ltt", "selective_error", Some(d), _) if open(d) => {}
687        ("ltt", "selective_cost", Some(d), _) if v14 && open(d) => {}
688        ("crc", "joint_error", None, None) => {}
689        _ => return bad("method, risk, delta and ucb disagree"),
690    }
691    if !open(c.alpha) || !threshold(c.abstain_below) || !unit(c.coverage) {
692        return bad("alpha, abstain_below or coverage out of range");
693    }
694    if c.ucb.is_some_and(|u| !unit(u)) || !band_ok(&c.realized_band) {
695        return bad("ucb or realized_band out of range");
696    }
697    for s in &c.segments {
698        if s.field.is_empty()
699            || !threshold(s.abstain_below)
700            || !unit(s.coverage)
701            || s.ucb.is_some_and(|u| !unit(u))
702            || s.realized_band.as_ref().is_some_and(|b| !band_ok(b))
703        {
704            return bad("a segment is out of range");
705        }
706    }
707    if !matches!(
708        (c.split.method.as_str(), c.split.seed),
709        ("time", None) | ("seeded", Some(_))
710    ) {
711        return bad("split.method and split.seed disagree");
712    }
713    if c.rule.unscored != "abstain" || c.rule.cannot_tell_above.is_some_and(|x| !unit(x)) {
714        return bad("rule out of range");
715    }
716    if !matches!(c.audit.mode.as_str(), "sample" | "full-label")
717        || !(c.audit.rate > 0.0 && c.audit.rate <= 1.0)
718    {
719        return bad("audit out of range");
720    }
721    if !model_id_ok(&c.model_id) {
722        return bad("model_id must be <backend>/<model>@<version>");
723    }
724    if !sha256_ok(&c.data_hash) || c.manifest_hash.as_deref().is_some_and(|h| !sha256_ok(h)) {
725        return bad("data_hash and manifest_hash must be sha256:<64 hex>");
726    }
727    if !key_id_form(&c.signer_key_id) {
728        return bad("signer_key_id must be ed25519:<16 hex>");
729    }
730    if c.signature.len() != 86
731        || !c
732            .signature
733            .bytes()
734            .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
735    {
736        return bad("signature must be 86 base64url characters");
737    }
738    timestamp(&c.fitted_at)?;
739    timestamp(&c.expires_at)?;
740    if let Some(w) = &c.window {
741        timestamp(&w.start)?;
742        timestamp(&w.end)?;
743    }
744    if c.spec == SPEC_V1_2 || c.spec == SPEC_V1_3 || v14 {
745        histograms(c)?;
746        map::check(&c.calibration_map, c.options.len())?;
747    }
748    if c.spec == SPEC_V1_3 || v14 {
749        automated(c)?;
750    }
751    if v14 {
752        cost(c)?;
753    }
754    if v15 {
755        if !c.tenant.as_deref().is_some_and(tenant_ok) {
756            return Err(CertError::Invalid(format!(
757                "tenant must be 1 to {MAX_TENANT} characters of A-Z a-z 0-9 . _ : -"
758            )));
759        }
760        let signer_ok =
761            c.signer
762                .as_ref()
763                .is_some_and(|s| match (s.mode.as_str(), s.host.as_deref()) {
764                    ("operator", None) => true,
765                    ("hosted", Some(h)) => key_id_form(h),
766                    _ => false,
767                });
768        if !signer_ok {
769            return bad("signer must be {\"mode\": \"operator\"} or {\"mode\": \"hosted\", \"host\": \"ed25519:<16 hex>\"}");
770        }
771    }
772    Ok(())
773}
774
775/// A v1.2 certificate has every v1.2 field, a v1.3 certificate every v1.2 and v1.3 field, and an
776/// earlier certificate none of them, at the top level and in every segment. A certificate whose
777/// fields belong to another spec is refused as a spec it is not, so a v1.1-shaped certificate naming
778/// v1.2, or a v1.2-shaped one naming v1.3, is still refused as an unknown spec.
779fn fields_for_spec(c: &Certificate) -> Result<(), CertError> {
780    let v15 = c.spec == SPEC_V1_5;
781    let v14 = c.spec == SPEC_V1_4 || v15;
782    let v13 = c.spec == SPEC_V1_3 || v14;
783    let v12 = c.spec == SPEC_V1_2 || v13;
784    // (name, present, required by this spec): the v1.2 fields first, then the v1.3 ones.
785    let mut present = vec![
786        ("confidence_bins", c.confidence_bins.is_some(), v12),
787        (
788            "confidence_histogram",
789            c.confidence_histogram.is_some(),
790            v12,
791        ),
792        ("automate_options", c.automate_options.is_some(), v13),
793        ("automated", c.automated.is_some(), v13),
794        ("cost", c.cost.is_some(), v14),
795        ("pvalue", c.pvalue.is_some(), v14),
796        ("loss_sum", c.loss_sum.is_some(), v14),
797        ("realized_cost", c.realized_cost.is_some(), v14),
798        ("tenant", c.tenant.is_some(), v15),
799        ("signer", c.signer.is_some(), v15),
800    ];
801    for s in &c.segments {
802        present.push((
803            "segments[].confidence_histogram",
804            s.confidence_histogram.is_some(),
805            v12,
806        ));
807        present.push(("segments[].automated", s.automated.is_some(), v13));
808        present.push(("segments[].loss_sum", s.loss_sum.is_some(), v14));
809        present.push(("segments[].realized_cost", s.realized_cost.is_some(), v14));
810    }
811    if let Some(a) = &c.automated {
812        present.push(("automated.loss_sum", a.loss_sum.is_some(), v14));
813        present.push(("automated.realized_cost", a.realized_cost.is_some(), v14));
814    }
815    for s in &c.segments {
816        if let Some(a) = &s.automated {
817            present.push(("segments[].automated.loss_sum", a.loss_sum.is_some(), v14));
818            present.push((
819                "segments[].automated.realized_cost",
820                a.realized_cost.is_some(),
821                v14,
822            ));
823        }
824    }
825    for (name, here, required) in present {
826        if required && !here {
827            return Err(CertError::Invalid(format!(
828                "spec is not consistent with the fields: {} requires `{name}`",
829                c.spec
830            )));
831        }
832        if !required && here {
833            return Err(CertError::Invalid(format!(
834                "unknown field `{name}` in a {} certificate",
835                c.spec
836            )));
837        }
838    }
839    Ok(())
840}
841
842/// v1.2's checks beyond the schema: the bins rise strictly from 0 to 1, and each histogram has one
843/// count per bin and counts exactly its test's `n` cases.
844fn histograms(c: &Certificate) -> Result<(), CertError> {
845    let bins = c.confidence_bins.as_deref().unwrap_or_default();
846    let rising = bins.windows(2).all(|w| w[0] < w[1]);
847    if !(2..=MAX_BINS + 1).contains(&bins.len())
848        || bins[0] != 0.0
849        || bins[bins.len() - 1] != 1.0
850        || !rising
851    {
852        return Err(CertError::Invalid(format!(
853            "confidence_bins must rise strictly from 0 to 1, with 1 to {MAX_BINS} bins"
854        )));
855    }
856    let tests = std::iter::once((&c.confidence_histogram, c.n))
857        .chain(c.segments.iter().map(|s| (&s.confidence_histogram, s.n)));
858    for (h, n) in tests {
859        if let Some(Some(h)) = h {
860            let total: u128 =
861                h.counts.iter().map(|&x| u128::from(x)).sum::<u128>() + u128::from(h.unscored);
862            if h.counts.len() != bins.len() - 1 || total != u128::from(n) {
863                return Err(CertError::Invalid(
864                    "a confidence_histogram needs one count per bin, and its counts and unscored must sum to n".into(),
865                ));
866            }
867        }
868    }
869    Ok(())
870}
871
872/// v1.3's checks beyond the schema: `automate_options` names options of the certificate, once each
873/// and in their order; each test's `automated` share is at most its `coverage`, its numbers are in
874/// range, and its `ucb` and `realized_band` are null exactly where the test's are.
875fn automated(c: &Certificate) -> Result<(), CertError> {
876    let auto = c.automate_options.as_deref().unwrap_or_default();
877    let mut at = c.options.iter();
878    if auto.is_empty() || !auto.iter().all(|o| at.any(|x| x == o)) {
879        return Err(CertError::Invalid(
880            "automate_options must name one or more of the options, once each and in their order"
881                .into(),
882        ));
883    }
884    let unit = |x: f64| (0.0..=1.0).contains(&x);
885    let tests = std::iter::once((
886        &c.automated,
887        c.coverage,
888        c.ucb.is_some(),
889        true, // the top level's realized_band is never null
890    ))
891    .chain(c.segments.iter().map(|s| {
892        (
893            &s.automated,
894            s.coverage,
895            s.ucb.is_some(),
896            s.realized_band.is_some(),
897        )
898    }));
899    for (a, coverage, ucb, band) in tests {
900        let Some(a) = a else { continue };
901        if !unit(a.coverage)
902            || a.coverage > coverage
903            || a.ucb.is_some_and(|u| !unit(u))
904            || a.realized_band.as_ref().is_some_and(|b| !band_ok(b))
905            || a.ucb.is_some() != ucb
906            || a.realized_band.is_some() != band
907        {
908            return Err(CertError::Invalid(
909                "automated must agree with its test: coverage at most the test's, and ucb and realized_band null exactly where the test's are".into(),
910            ));
911        }
912    }
913    // Every option automated: the automated cases are the answered cases, so each block is its
914    // test's own numbers.
915    if auto.len() == c.options.len() {
916        let same = |a: &Option<Automated>, coverage: f64, ucb: Option<f64>, band: Option<&Band>| {
917            a.as_ref().is_none_or(|a| {
918                a.coverage == coverage && a.ucb == ucb && a.realized_band.as_ref() == band
919            })
920        };
921        // v1.4: the loss sums (whole numbers, compared exactly) and realized costs agree too (both
922        // absent before v1.4)
923        let same_cost =
924            |a: &Option<Automated>, ls: Option<Option<u64>>, rc: Option<Option<f64>>| {
925                a.as_ref()
926                    .is_none_or(|a| a.loss_sum == ls && a.realized_cost == rc)
927            };
928        if !same(&c.automated, c.coverage, c.ucb, Some(&c.realized_band))
929            || !same_cost(&c.automated, c.loss_sum, c.realized_cost)
930            || !c
931                .segments
932                .iter()
933                .all(|s| same(&s.automated, s.coverage, s.ucb, s.realized_band.as_ref()))
934            || !c
935                .segments
936                .iter()
937                .all(|s| same_cost(&s.automated, s.loss_sum, s.realized_cost))
938        {
939            return Err(CertError::Invalid(
940                "automated must equal its test's coverage, ucb and realized_band when every option is automated".into(),
941            ));
942        }
943    }
944    Ok(())
945}
946
947/// v1.4's checks beyond the schema (spec v1.4 §2): `cost` and `pvalue` pair with `risk`; the cost
948/// matrix is options x options with a zero diagonal, whole-number entries in [0, c_max], `c_max` its
949/// largest entry, above 0 and at most 10^6, and its off-diagonal entries not all equal; `loss_sum`
950/// and `realized_cost` are null for the error risks, for an inherited segment and wherever their test
951/// answered no case, and otherwise `loss_sum` is at most c_max * k and `realized_cost` is exactly
952/// `loss_sum / (c_max * k)`, k = floor(coverage * n + 1/2) the answered cases.
953/// v1.4: the largest `c_max`.
954pub const MAX_C: u64 = 1_000_000;
955/// v1.4: the largest `c_max * answered`, 2^53, so that it and every `loss_sum` are exact in an f64.
956const SAFE_SCALE: f64 = 9_007_199_254_740_992.0;
957
958fn cost(c: &Certificate) -> Result<(), CertError> {
959    let bad = |m: &str| Err(CertError::Invalid(m.to_string()));
960    let cost = c.cost.clone().flatten();
961    let pvalue = c.pvalue.clone().flatten();
962    let want = match c.risk.as_str() {
963        "selective_error" => Some("binomial"),
964        "selective_cost" => Some("hoeffding_bentkus"),
965        _ => None,
966    };
967    if cost.is_some() != (c.risk == "selective_cost") || pvalue.as_deref() != want {
968        return bad("cost, pvalue and risk disagree");
969    }
970    if let Some(k) = &cost {
971        let n = c.options.len();
972        let m = &k.matrix;
973        let all = || m.iter().flatten().copied();
974        let ok = m.len() == n
975            && m.iter().all(|r| r.len() == n)
976            && (0..n).all(|i| m[i][i] == 0)
977            && all().all(|x| x <= k.c_max)
978            && (1..=MAX_C).contains(&k.c_max)
979            && all().max() == Some(k.c_max)
980            && k.unit.as_deref() != Some("");
981        if !ok {
982            return bad("cost.matrix must be options x options with a zero diagonal and entries in [0, c_max], c_max its largest entry, above 0 and at most 10^6");
983        }
984        let off: Vec<u64> = (0..n)
985            .flat_map(|i| (0..n).filter(move |&j| j != i).map(move |j| (i, j)))
986            .map(|(i, j)| m[i][j])
987            .collect();
988        if off.iter().all(|&x| x == off[0]) {
989            return bad("a cost risk needs unequal off-diagonal costs; with equal costs it is selective_error");
990        }
991    }
992    let unit = |x: f64| (0.0..=1.0).contains(&x);
993    // (realized_cost, loss_sum, coverage, its test's n, own test): each test, and each test's automated
994    // cases, whose coverage is a share of the test's n
995    type Row = (Option<f64>, Option<u64>, f64, u64, bool);
996    let auto = |a: &Option<Automated>, n: u64, own: bool| -> Row {
997        a.as_ref().map_or((None, None, 0.0, n, own), |a| {
998            (
999                a.realized_cost.flatten(),
1000                a.loss_sum.flatten(),
1001                a.coverage,
1002                n,
1003                own,
1004            )
1005        })
1006    };
1007    let mut tests: Vec<Row> = vec![(
1008        c.realized_cost.flatten(),
1009        c.loss_sum.flatten(),
1010        c.coverage,
1011        c.n,
1012        true,
1013    )];
1014    tests.extend(c.segments.iter().map(|s| {
1015        (
1016            s.realized_cost.flatten(),
1017            s.loss_sum.flatten(),
1018            s.coverage,
1019            s.n,
1020            !s.inherited,
1021        )
1022    }));
1023    tests.push(auto(&c.automated, c.n, true));
1024    tests.extend(
1025        c.segments
1026            .iter()
1027            .map(|s| auto(&s.automated, s.n, !s.inherited)),
1028    );
1029    for (rc, ls, coverage, n, own) in tests {
1030        let expect = cost.is_some() && own && coverage > 0.0;
1031        if rc.is_some() != expect || ls.is_some() != expect || rc.is_some_and(|x| !unit(x)) {
1032            return bad("realized_cost and loss_sum must be null for the error risks, an inherited segment and a test that answered no case, and only there");
1033        }
1034        if let (Some(rc), Some(ls), Some(k)) = (rc, ls, &cost) {
1035            // whole costs: one exact division, so every verifier, in any language, gets the same
1036            // number. Both operands are exact in f64 (at most 2^53).
1037            let answered = (coverage * n as f64 + 0.5).floor();
1038            // k can't be fudged by rounding: coverage is exactly k / n, one correctly rounded division
1039            // of two exact integers, as the issuer writes it
1040            if !(1..=1u64 << 53).contains(&n) || coverage != answered / n as f64 {
1041                return bad(
1042                    "coverage must be exactly answered / n, a whole number of answered cases",
1043                );
1044            }
1045            let ok = (1.0..=SAFE_SCALE).contains(&answered) && {
1046                let scale = u128::from(k.c_max) * answered as u128;
1047                scale <= SAFE_SCALE as u128
1048                    && u128::from(ls) <= scale
1049                    && rc == ls as f64 / scale as f64
1050            };
1051            if !ok {
1052                return bad("realized_cost must be loss_sum / (c_max * answered), with loss_sum at most c_max * answered");
1053            }
1054        }
1055    }
1056    Ok(())
1057}
1058
1059/// `^[^/]+/.+@.+$`, and not ending in `@?` (an unknown version).
1060fn model_id_ok(m: &str) -> bool {
1061    // The pattern's `.` matches no line terminator.
1062    if m.chars()
1063        .any(|c| matches!(c, '\n' | '\r' | '\u{2028}' | '\u{2029}'))
1064    {
1065        return false;
1066    }
1067    let Some((backend, rest)) = m.split_once('/') else {
1068        return false;
1069    };
1070    let at = rest
1071        .char_indices()
1072        .skip(1)
1073        .any(|(i, ch)| ch == '@' && i + 1 < rest.len());
1074    !backend.is_empty() && at && !m.ends_with("@?")
1075}
1076
1077fn sha256_ok(h: &str) -> bool {
1078    h.strip_prefix("sha256:")
1079        .is_some_and(|x| x.len() == 64 && lower_hex(x))
1080}
1081
1082fn lower_hex(s: &str) -> bool {
1083    s.bytes()
1084        .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
1085}
1086
1087fn band_ok(b: &Band) -> bool {
1088    b.level > 0.0 && b.level < 1.0 && (0.0..=1.0).contains(&b.low) && (0.0..=1.0).contains(&b.high)
1089}
1090
1091/// Parse the spec's timestamp form, `YYYY-MM-DDTHH:MM:SSZ`, and nothing else.
1092pub fn timestamp(s: &str) -> Result<DateTime<Utc>, CertError> {
1093    // 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.
1094    let b = s.as_bytes();
1095    let ok = b.len() == 20
1096        && b.iter().enumerate().all(|(i, &c)| match i {
1097            4 | 7 => c == b'-',
1098            10 => c == b'T',
1099            13 | 16 => c == b':',
1100            19 => c == b'Z',
1101            _ => c.is_ascii_digit(),
1102        });
1103    DateTime::parse_from_rfc3339(s)
1104        .ok()
1105        .filter(|_| ok)
1106        .map(|t| t.with_timezone(&Utc))
1107        .ok_or_else(|| CertError::Invalid(format!("timestamp {s:?} is not YYYY-MM-DDTHH:MM:SSZ")))
1108}
1109
1110fn hex(b: &[u8]) -> String {
1111    b.iter().map(|x| format!("{x:02x}")).collect()
1112}
1113
1114#[cfg(test)]
1115mod tests {
1116    use super::*;
1117
1118    fn valid() -> serde_json::Value {
1119        let f: serde_json::Value =
1120            serde_json::from_str(include_str!("../../fixtures/valid_segments_unicode.json"))
1121                .unwrap();
1122        f["certificate"].clone()
1123    }
1124
1125    /// v1 and v1.1 define only `temperature`, so a `dr` map in one of them gives no probabilities,
1126    /// though the certificate verifies as it always did.
1127    #[test]
1128    fn dr_maps_are_applied_in_v1_2_certificates_only() {
1129        let mut cert: Certificate = serde_json::from_value(valid()).unwrap();
1130        cert.calibration_map = CalibrationMap {
1131            kind: "dr".into(),
1132            params: [("a", 1.0), ("b0", 0.0), ("b1", 0.0)]
1133                .iter()
1134                .map(|(k, v)| (k.to_string(), *v))
1135                .collect(),
1136            label_budget: None,
1137        };
1138        let v = Verified {
1139            id: String::new(),
1140            cert,
1141            expires_at: Utc::now(),
1142        };
1143        assert!(v.probabilities(&[1.0, 0.0]).is_none() && v.confidence(&[1.0, 0.0]).is_none());
1144        let mut v12 = v.clone();
1145        v12.cert.spec = SPEC_V1_2.into();
1146        assert!(v12.confidence(&[1.0, 0.0]).unwrap() > 0.73);
1147    }
1148
1149    #[test]
1150    fn check_rejects_what_the_schema_rejects() {
1151        let typed =
1152            |v: &serde_json::Value| serde_json::from_value::<Certificate>(v.clone()).unwrap();
1153        assert!(check(&typed(&valid())).is_ok());
1154        let edits: [(&str, serde_json::Value); 15] = [
1155            ("data_hash", serde_json::json!("sha256:XYZ")),
1156            ("manifest_hash", serde_json::json!("md5:00")),
1157            ("signer_key_id", serde_json::json!("ed25519:short")),
1158            ("model_id", serde_json::json!("/x@y")),
1159            ("model_id", serde_json::json!("b/m@?")),
1160            (
1161                "window",
1162                serde_json::json!({"start": "2023-01-02", "end": "2023-12-29T23:59:59Z"}),
1163            ),
1164            ("expires_at", serde_json::json!("2027-01-23T12:00:00+00:00")),
1165            ("expires_at", serde_json::json!("2027-01-23 12:00:00Z")),
1166            ("fitted_at", serde_json::json!("2026-10-25t12:00:00Z")),
1167            ("domain", serde_json::json!("")),
1168            ("options", serde_json::json!(["yes", "yes"])),
1169            ("split", serde_json::json!({"method": "time", "seed": 3})),
1170            ("alpha", serde_json::json!(1.0)),
1171            ("signature", serde_json::json!("abc")),
1172            ("model_id", serde_json::json!("a/b\n@c")),
1173        ];
1174        for (field, value) in edits {
1175            let mut v = valid();
1176            v[field] = value.clone();
1177            assert!(check(&typed(&v)).is_err(), "{field} = {value}");
1178        }
1179    }
1180
1181    #[test]
1182    fn nested_nullable_fields_must_be_present() {
1183        let paths: [(&str, &str); 5] = [
1184            ("segments", "ucb"),
1185            ("segments", "realized_band"),
1186            ("split", "seed"),
1187            ("calibration_map", "label_budget"),
1188            ("rule", "cannot_tell_above"),
1189        ];
1190        for (outer, inner) in paths {
1191            let mut v = valid();
1192            let o = if outer == "segments" {
1193                &mut v[outer][0]
1194            } else {
1195                &mut v[outer]
1196            };
1197            o.as_object_mut().unwrap().remove(inner);
1198            let e = serde_json::from_value::<Certificate>(v).err();
1199            assert!(
1200                e.is_some_and(|e| e.to_string().contains(inner)),
1201                "{outer}.{inner}"
1202            );
1203        }
1204    }
1205
1206    /// The same table as python/tests/test_ed25519.py: every small-order encoding is a key
1207    /// `verify_strict` refuses (the Python verifier must refuse the same ones).
1208    #[test]
1209    fn small_order_keys_are_weak() {
1210        let table = [
1211            "0100000000000000000000000000000000000000000000000000000000000000",
1212            "ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f",
1213            "0000000000000000000000000000000000000000000000000000000000000000",
1214            "0000000000000000000000000000000000000000000000000000000000000080",
1215            "26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05",
1216            "26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85",
1217            "c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a",
1218            "c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa",
1219            "0100000000000000000000000000000000000000000000000000000000000080",
1220            "ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
1221            "edffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f",
1222            "edffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
1223            "eeffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f",
1224            "eeffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
1225        ];
1226        for h in table {
1227            let b: [u8; 32] = (0..32)
1228                .map(|i| u8::from_str_radix(&h[2 * i..2 * i + 2], 16).unwrap())
1229                .collect::<Vec<_>>()
1230                .try_into()
1231                .unwrap();
1232            let k = VerifyingKey::from_bytes(&b).unwrap_or_else(|e| panic!("{h}: {e}"));
1233            assert!(k.is_weak(), "{h}");
1234        }
1235    }
1236
1237    #[test]
1238    fn certified_segments_set_the_threshold_and_inherited_ones_do_not() {
1239        let cert: Certificate = serde_json::from_value(valid()).unwrap();
1240        let v = Verified {
1241            id: String::new(),
1242            expires_at: timestamp(&cert.expires_at).unwrap(),
1243            cert,
1244        };
1245        assert_eq!(v.threshold_for(Some("east")), 0.9);
1246        assert_eq!(
1247            v.threshold_for(Some("z\u{fc}rich \u{2603}")),
1248            v.cert.abstain_below
1249        );
1250        assert_eq!(v.threshold_for(None), v.cert.abstain_below);
1251        assert!(
1252            v.is_expired(v.expires_at)
1253                && !v.is_expired(v.expires_at - chrono::Duration::seconds(1))
1254        );
1255    }
1256}