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//! `decision-certificate.v1.5` (spec/decision-certificate.v1.5.md) and `decision-certificate.v1.6`
6//! (spec/decision-certificate.v1.6.md).
7//!
8//! Verification canonicalises the JSON value exactly as received (RFC 8785, JCS), never a
9//! re-serialised struct, so number formatting can't drift from the issuer's. The typed
10//! [`Certificate`] is read from the same value afterwards, rejecting unknown fields.
11//!
12//! A v1.2 certificate also stores the confidence histogram of its threshold split, so a consumer can
13//! monitor without labels: [`Histogram::of`] bins a window of use-time confidences and
14//! [`shift_score`] compares it with the stored one. The score is descriptive, a prompt to measure
15//! again; it never shows that the bound holds or has failed.
16//!
17//! [`probabilities`] applies a certificate's calibration map to a case's raw scores, for the map
18//! kinds v1.2 defines (`temperature` and `dr`, [`MAP_KINDS`]).
19//!
20//! A v1.3 certificate also names the options a consumer automates (`automate_options`) and reports,
21//! per test, the share and error of the answered cases whose answer is one of them ([`Automated`]).
22//!
23//! A v1.5 certificate also names its `tenant` and who signed it ([`Signer`]: the tenant as operator,
24//! or a hosting service for the tenant), and its signature covers the tenant. It is verified with
25//! the tenant the consumer expects and that tenant's moded keys: [`verify_for_tenant`]. [`verify`]
26//! keeps its meaning for v1 to v1.4 and refuses a v1.5 certificate.
27//!
28//! A v1.6 certificate is a sequential, anytime-valid measurement over the records of a
29//! pre-registered attempt in one flow and environment ([`sequential`]). It is verified only on
30//! request, with the expected tenant, flow and environment: [`verify_sequential`].
31//! [`verify_for_tenant`] refuses it, so a consumer that only upgrades the crate never accepts one.
32//!
33//! [`inclusion`] checks `decision-cert-inclusion.v1`
34//! (spec/decision-cert-inclusion.v1.md) offline: a bundle showing that a tenant's
35//! transparency log recorded a leaf in a checkpoint its witnesses cosigned
36//! ([`inclusion::verify_bundle`]), a consistency proof between two checkpoints
37//! ([`inclusion::verify_consistency`]), and the consumer's policy for a certificate without a bundle
38//! ([`inclusion::apply_policy`]).
39
40pub mod challenger;
41pub mod inclusion;
42mod map;
43mod monitor;
44pub mod sequential;
45
46pub use challenger::AttemptRole;
47pub use map::{confidence, probabilities, MAP_KINDS};
48pub use monitor::{bin_of, chi2_sf, shift_score, ShiftScore};
49pub use sequential::{explore_bucket, salt_commitment, tail_trips, Sequential};
50/// The UTC time type of [`timestamp`], [`Verified::expires_at`] and [`Verified::is_expired`],
51/// re-exported so a caller need not depend on `time` to name it.
52pub use time::UtcDateTime;
53
54use std::collections::BTreeMap;
55
56use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};
57use ed25519_dalek::{Signature, VerifyingKey};
58use serde::Deserialize;
59use sha2::{Digest, Sha256};
60use time::{Date, Month, Time};
61
62/// The `spec` of a certificate produced by the v1 procedure.
63pub const SPEC: &str = "decision-certificate.v1";
64/// The `spec` of a certificate produced by the v1.1 procedure (the per-test grid start).
65pub const SPEC_V1_1: &str = "decision-certificate.v1.1";
66/// The `spec` of a v1.2 certificate: v1.1's procedure, plus the stored confidence histogram.
67pub const SPEC_V1_2: &str = "decision-certificate.v1.2";
68/// The `spec` of a v1.3 certificate: v1.2, plus the automated options and their answered share and
69/// error per test.
70pub const SPEC_V1_3: &str = "decision-certificate.v1.3";
71/// The `spec` of a v1.4 certificate: v1.3, plus the cost risk `selective_cost`.
72pub const SPEC_V1_4: &str = "decision-certificate.v1.4";
73/// The `spec` of a v1.5 certificate: v1.4, plus `tenant` and `signer`, signed over bytes that bind
74/// the tenant.
75pub const SPEC_V1_5: &str = "decision-certificate.v1.5";
76/// The `spec` of a v1.6 certificate: v1.5's fields, with fixed values for the calibration split, and
77/// the `sequential` block; method `confidence_sequence`, risk `automated_error`.
78pub const SPEC_V1_6: &str = "decision-certificate.v1.6";
79/// The `spec` of a v1.7 certificate: v1.6, plus the attempt's role (standalone or challenger, with
80/// the champion it runs beside) and its delta budget, in `sequential`.
81pub const SPEC_V1_7: &str = "decision-certificate.v1.7";
82/// Every `spec` this verifier accepts. v1 and v1.1 have the same fields; v1.2 adds some, v1.3 more,
83/// v1.4 more again, v1.5 more again.
84pub const SPECS: [&str; 8] = [
85    SPEC, SPEC_V1_1, SPEC_V1_2, SPEC_V1_3, SPEC_V1_4, SPEC_V1_5, SPEC_V1_6, SPEC_V1_7,
86];
87/// The context string a v1.5 signature's bytes start with (spec v1.5 §3).
88pub const CONTEXT_V1_5: &str = "decision-cert/certificate.v1.5";
89/// The context string a v1.6 signature's bytes start with (spec v1.6 §3).
90pub const CONTEXT_V1_6: &str = "decision-cert/certificate.v1.6";
91/// The context string a v1.7 signature's bytes start with (spec v1.7 §3).
92pub const CONTEXT_V1_7: &str = "decision-cert/certificate.v1.7";
93/// The longest `tenant` (spec v1.5 §2).
94pub const MAX_TENANT: usize = 128;
95/// Most bins a `confidence_bins` may define.
96pub const MAX_BINS: usize = 100;
97/// `abstain_below` that abstains on every case (as `dk calibrate` writes it).
98pub const ABSTAIN_ALL: f64 = 1.01;
99
100#[derive(Debug, thiserror::Error)]
101pub enum CertError {
102    #[error("certificate is not a valid decision certificate: {0}")]
103    Invalid(String),
104    #[error("certificate signed by {0}, which is not a trusted key")]
105    UntrustedKey(String),
106    #[error("trusted key {0} is malformed or does not hash to its id")]
107    BadKey(String),
108    #[error("certificate signature does not verify")]
109    BadSignature,
110    /// v1.5 check 1: the certificate's `tenant` is not the tenant the verifier expects.
111    #[error("certificate is for tenant {0}, not the expected tenant")]
112    WrongTenant(String),
113    /// v1.5 check 3 (and an earlier certificate under a hosted key): the key's entry does not allow
114    /// the certificate's signer mode, or its `host` is not the certificate's.
115    #[error("trusted key {0} may not sign in this mode")]
116    KeyMode(String),
117    /// v1.6 check 5: the certificate's `sequential.flow` is not the flow the verifier expects.
118    #[error("certificate is for flow {0}, not the expected flow")]
119    WrongFlow(String),
120    /// v1.6 check 6: the certificate's `sequential.env` is not the environment the verifier expects.
121    #[error("certificate is for environment {0}, not the expected environment")]
122    WrongEnv(String),
123    /// v1.7 §4.2: the pair of certificates does not allow the promotion, with the reason.
124    #[error("challenger is not promotable: {0}")]
125    NotPromotable(String),
126}
127
128#[derive(Deserialize, Clone, Debug, PartialEq)]
129#[serde(deny_unknown_fields)]
130pub struct Band {
131    pub level: f64,
132    pub low: f64,
133    pub high: f64,
134}
135
136/// A test's threshold-split cases per bin of `confidence_bins`, and the cases the rule abstains on
137/// whatever the threshold (unscored, or above the `cannot_tell` cut). v1.2.
138#[derive(Deserialize, Clone, Debug, PartialEq, Eq)]
139#[serde(deny_unknown_fields)]
140pub struct Histogram {
141    pub counts: Vec<u64>,
142    pub unscored: u64,
143}
144
145/// A test's answered cases whose answer is one of `automate_options` (v1.3): their share of the
146/// test's `n` cases, and `ucb` and `realized_band` of their error, as the test's own (descriptive,
147/// spec v1.2 §1.2). Null exactly where the test's are.
148#[derive(Deserialize, Clone, Debug, PartialEq)]
149#[serde(deny_unknown_fields)]
150pub struct Automated {
151    pub coverage: f64,
152    #[serde(deserialize_with = "nullable")]
153    pub ucb: Option<f64>,
154    #[serde(deserialize_with = "nullable")]
155    pub realized_band: Option<Band>,
156    /// v1.4 only (absent before v1.4): the automated cases' exact sum of whole costs under
157    /// `selective_cost`; present and null otherwise.
158    #[serde(default, deserialize_with = "present")]
159    pub loss_sum: Option<Option<u64>>,
160    /// v1.4 only (absent before v1.4): the automated cases' mean normalised cost under
161    /// `selective_cost`, `loss_sum / (c_max * answered)`; present and null otherwise.
162    #[serde(default, deserialize_with = "present")]
163    pub realized_cost: Option<Option<f64>>,
164}
165
166/// A v1.4 `selective_cost` certificate's costs: `matrix[label][answered option]`, in the options'
167/// order, whole numbers in the consumer's `unit` (informational), and its largest entry `c_max`.
168#[derive(Deserialize, Clone, Debug, PartialEq)]
169#[serde(deny_unknown_fields)]
170pub struct Cost {
171    pub matrix: Vec<Vec<u64>>,
172    pub c_max: u64,
173    #[serde(deserialize_with = "nullable")]
174    pub unit: Option<String>,
175}
176
177#[derive(Deserialize, Clone, Debug, PartialEq)]
178#[serde(deny_unknown_fields)]
179pub struct Segment {
180    pub field: String,
181    pub value: String,
182    pub n: u64,
183    pub abstain_below: f64,
184    pub coverage: f64,
185    #[serde(deserialize_with = "nullable")]
186    pub ucb: Option<f64>,
187    #[serde(deserialize_with = "nullable")]
188    pub realized_band: Option<Band>,
189    pub inherited: bool,
190    /// v1.2 only: absent (None) before v1.2; present and null (Some(None)) when withheld.
191    #[serde(default, deserialize_with = "present")]
192    pub confidence_histogram: Option<Option<Histogram>>,
193    /// v1.3 only: absent (None) before v1.3.
194    #[serde(default, deserialize_with = "present")]
195    pub automated: Option<Automated>,
196    /// v1.4 only: absent (None) before v1.4.
197    #[serde(default, deserialize_with = "present")]
198    pub loss_sum: Option<Option<u64>>,
199    /// v1.4 only: absent (None) before v1.4.
200    #[serde(default, deserialize_with = "present")]
201    pub realized_cost: Option<Option<f64>>,
202}
203
204#[derive(Deserialize, Clone, Debug, PartialEq)]
205#[serde(deny_unknown_fields)]
206pub struct Split {
207    pub method: String,
208    #[serde(deserialize_with = "nullable")]
209    pub seed: Option<i64>,
210}
211
212#[derive(Deserialize, Clone, Debug, PartialEq)]
213#[serde(deny_unknown_fields)]
214pub struct CalibrationMap {
215    pub kind: String,
216    pub params: BTreeMap<String, f64>,
217    #[serde(deserialize_with = "nullable")]
218    pub label_budget: Option<u64>,
219}
220
221#[derive(Deserialize, Clone, Debug, PartialEq)]
222#[serde(deny_unknown_fields)]
223pub struct Rule {
224    #[serde(deserialize_with = "nullable")]
225    pub cannot_tell_above: Option<f64>,
226    pub unscored: String,
227}
228
229#[derive(Deserialize, Clone, Debug, PartialEq)]
230#[serde(deny_unknown_fields)]
231pub struct Window {
232    pub start: String,
233    pub end: String,
234}
235
236#[derive(Deserialize, Clone, Debug, PartialEq)]
237#[serde(deny_unknown_fields)]
238pub struct Audit {
239    pub mode: String,
240    pub rate: f64,
241    pub n: u64,
242    pub propensity_logged: bool,
243}
244
245#[derive(Deserialize, Clone, Debug, PartialEq)]
246#[serde(deny_unknown_fields)]
247pub struct Issuer {
248    pub tool: String,
249    pub version: String,
250}
251
252/// Who signed a v1.5 certificate: `mode` `operator` (the tenant, with its own key; no `host`), or
253/// `hosted` (a hosting service for the tenant; `host` is the hosting service's own key id,
254/// `ed25519:<16 lowercase hex>`).
255#[derive(Deserialize, Clone, Debug, PartialEq, Eq)]
256#[serde(deny_unknown_fields)]
257pub struct Signer {
258    pub mode: String,
259    #[serde(default, deserialize_with = "present")]
260    pub host: Option<String>,
261}
262
263/// Every field is required; `Option` fields must be present (as null): a missing field is an error.
264#[derive(Deserialize, Clone, Debug, PartialEq)]
265#[serde(deny_unknown_fields)]
266pub struct Certificate {
267    pub spec: String,
268    pub domain: String,
269    pub decision: String,
270    pub options: Vec<String>,
271    pub model_id: String,
272    #[serde(deserialize_with = "nullable")]
273    pub manifest_hash: Option<String>,
274    pub data_hash: String,
275    pub n_cal: u64,
276    pub n_temperature: u64,
277    pub split: Split,
278    pub calibration_map: CalibrationMap,
279    pub rule: Rule,
280    pub alpha: f64,
281    #[serde(deserialize_with = "nullable")]
282    pub delta: Option<f64>,
283    pub method: String,
284    pub risk: String,
285    pub n: u64,
286    pub abstain_below: f64,
287    pub coverage: f64,
288    #[serde(deserialize_with = "nullable")]
289    pub ucb: Option<f64>,
290    pub realized_band: Band,
291    pub segments: Vec<Segment>,
292    #[serde(deserialize_with = "nullable")]
293    pub window: Option<Window>,
294    pub fitted_at: String,
295    pub expires_at: String,
296    pub audit: Audit,
297    pub issuer: Issuer,
298    pub signer_key_id: String,
299    pub signature: String,
300    /// v1.2 only (absent, so None, before v1.2): the histogram bin edges, rising from 0 to 1.
301    #[serde(default, deserialize_with = "present")]
302    pub confidence_bins: Option<Vec<f64>>,
303    /// v1.2 only: the remainder's histogram; present and null (Some(None)) when withheld.
304    #[serde(default, deserialize_with = "present")]
305    pub confidence_histogram: Option<Option<Histogram>>,
306    /// v1.3 only (absent before v1.3): the options a consumer decides automatically; a case answered
307    /// with another option goes to a person.
308    #[serde(default, deserialize_with = "present")]
309    pub automate_options: Option<Vec<String>>,
310    /// v1.3 only: the remainder's automated cases.
311    #[serde(default, deserialize_with = "present")]
312    pub automated: Option<Automated>,
313    /// v1.4 only (absent before v1.4): the costs of a `selective_cost` certificate; present and null
314    /// for the error risks.
315    #[serde(default, deserialize_with = "present")]
316    pub cost: Option<Option<Cost>>,
317    /// v1.4 only: the `ltt` p-value, `binomial` or `hoeffding_bentkus`; null for `crc`.
318    #[serde(default, deserialize_with = "present")]
319    pub pvalue: Option<Option<String>>,
320    /// v1.4 only: the remainder's exact sum of whole costs over its answered cases.
321    #[serde(default, deserialize_with = "present")]
322    pub loss_sum: Option<Option<u64>>,
323    /// v1.4 only: the remainder's mean normalised cost of its answered cases (descriptive).
324    #[serde(default, deserialize_with = "present")]
325    pub realized_cost: Option<Option<f64>>,
326    /// v1.5 only (absent before v1.5): the tenant the certificate is issued for.
327    #[serde(default, deserialize_with = "present")]
328    pub tenant: Option<String>,
329    /// v1.5 only: who signed, the tenant as operator or a hosting service for it.
330    #[serde(default, deserialize_with = "present")]
331    pub signer: Option<Signer>,
332    /// v1.6 only (absent before v1.6): the attempt, its pre-registration, records and per-class
333    /// results.
334    #[serde(default, deserialize_with = "present")]
335    pub sequential: Option<Sequential>,
336    /// v1.7 only (None before v1.7): the role, challenger and budget fields of `sequential`, read
337    /// apart from the v1.6 block (spec v1.7 §2.2 to §2.4).
338    #[serde(skip)]
339    pub attempt_role: Option<AttemptRole>,
340}
341
342/// A field that may be absent (with `default`, as None) but, when present, is read as `T`: so a
343/// present null reads as `Some(None)` for `T = Option<_>`, and is an error for any other `T`.
344fn present<'de, D: serde::Deserializer<'de>, T: Deserialize<'de>>(
345    d: D,
346) -> Result<Option<T>, D::Error> {
347    T::deserialize(d).map(Some)
348}
349
350/// A present field that may be null. serde reads a missing `Option` as null, the spec does not:
351/// with `deserialize_with` and no `default`, a missing field is an error at every level.
352fn nullable<'de, D: serde::Deserializer<'de>, T: Deserialize<'de>>(
353    d: D,
354) -> Result<Option<T>, D::Error> {
355    Option::deserialize(d)
356}
357
358/// A certificate whose signature verified against a trusted key.
359#[derive(Clone, Debug, PartialEq)]
360pub struct Verified {
361    /// `sha256:<hex>` of the signed certificate's JCS bytes.
362    pub id: String,
363    pub cert: Certificate,
364    pub expires_at: UtcDateTime,
365}
366
367impl Verified {
368    /// The threshold for a case in `segment`: a certified segment's own, else the top-level one.
369    pub fn threshold_for(&self, segment: Option<&str>) -> f64 {
370        segment
371            .and_then(|v| {
372                self.cert
373                    .segments
374                    .iter()
375                    .find(|s| !s.inherited && s.value == v)
376            })
377            .map_or(self.cert.abstain_below, |s| s.abstain_below)
378    }
379
380    /// Whether the certificate has expired at `now`: `now` is not before its `expires_at`.
381    pub fn is_expired(&self, now: UtcDateTime) -> bool {
382        now >= self.expires_at
383    }
384
385    /// The bin edges of a v1.2 certificate's confidence histograms; None before v1.2.
386    pub fn confidence_bins(&self) -> Option<&[f64]> {
387        self.cert.confidence_bins.as_deref()
388    }
389
390    /// The stored confidence histogram of the cases decided by the same threshold as a case in
391    /// `segment`: a certified segment's own, else the top level's. None before v1.2, or when the
392    /// issuer withheld it.
393    pub fn histogram_for(&self, segment: Option<&str>) -> Option<&Histogram> {
394        let own = segment.and_then(|v| {
395            self.cert
396                .segments
397                .iter()
398                .find(|s| !s.inherited && s.value == v)
399        });
400        match own {
401            Some(s) => s.confidence_histogram.as_ref()?.as_ref(),
402            None => self.cert.confidence_histogram.as_ref()?.as_ref(),
403        }
404    }
405
406    /// The options a v1.3 certificate's consumer automates; None before v1.3. A consumer refuses a
407    /// certificate whose list differs from the options it automates (spec v1.3 §4).
408    pub fn automate_options(&self) -> Option<&[String]> {
409        self.cert.automate_options.as_deref()
410    }
411
412    /// The automated cases of the test that decides a case in `segment` (a certified segment's own,
413    /// else the top level's): their share and error. None before v1.3.
414    pub fn automated_for(&self, segment: Option<&str>) -> Option<&Automated> {
415        let own = segment.and_then(|v| {
416            self.cert
417                .segments
418                .iter()
419                .find(|s| !s.inherited && s.value == v)
420        });
421        match own {
422            Some(s) => s.automated.as_ref(),
423            None => self.cert.automated.as_ref(),
424        }
425    }
426
427    /// A v1.4 `selective_cost` certificate's costs; None otherwise. A consumer refuses a certificate
428    /// whose matrix differs from the costs it is configured with (spec v1.4 §4), and reports the
429    /// bound as `alpha * c_max` in `unit`.
430    pub fn cost(&self) -> Option<&Cost> {
431        self.cert.cost.as_ref().and_then(|c| c.as_ref())
432    }
433
434    /// A v1.6 certificate's attempt, pre-registration citation, records and per-class results; None
435    /// before v1.6.
436    pub fn sequential(&self) -> Option<&Sequential> {
437        self.cert.sequential.as_ref()
438    }
439
440    /// A v1.7 certificate's role, the champion a challenger runs beside, and its delta budget; None
441    /// before v1.7.
442    pub fn attempt_role(&self) -> Option<&AttemptRole> {
443        self.cert.attempt_role.as_ref()
444    }
445
446    /// A v1.5 certificate's tenant (equal to the expected tenant it was verified with); None before
447    /// v1.5.
448    pub fn tenant(&self) -> Option<&str> {
449        self.cert.tenant.as_deref()
450    }
451
452    /// Who signed a v1.5 certificate; None before v1.5.
453    pub fn signer(&self) -> Option<&Signer> {
454        self.cert.signer.as_ref()
455    }
456
457    /// The probabilities the certificate's calibration map gives a case's raw scores, one per
458    /// option (spec v1.2 §1, [`probabilities`]). None when the map's kind is not one this crate
459    /// applies ([`MAP_KINDS`]), its params do not fit that kind, or `scores` does not have one score
460    /// per option, or the map is `dr` in a certificate before v1.2, which did not define it. A
461    /// consumer refuses a certificate whose map it does not apply (spec v1.2 §4).
462    pub fn probabilities(&self, scores: &[f64]) -> Option<Vec<f64>> {
463        let defined = self.cert.calibration_map.kind == "temperature"
464            || self.cert.spec == SPEC_V1_2
465            || self.cert.spec == SPEC_V1_3
466            || self.cert.spec == SPEC_V1_4
467            || self.cert.spec == SPEC_V1_5
468            || self.cert.spec == SPEC_V1_6
469            || self.cert.spec == SPEC_V1_7;
470        (defined && scores.len() == self.cert.options.len())
471            .then(|| probabilities(&self.cert.calibration_map, scores))
472            .flatten()
473    }
474
475    /// A case's confidence: the largest of its [`Verified::probabilities`]. A case is answered when
476    /// this is at least [`Verified::threshold_for`] its segment (and the rule does not abstain on it).
477    pub fn confidence(&self, scores: &[f64]) -> Option<f64> {
478        self.probabilities(scores)
479            .map(|p| p.into_iter().fold(f64::NEG_INFINITY, f64::max))
480    }
481
482    /// The temperature of a `kind: temperature` calibration map; None for other kinds.
483    pub fn temperature(&self) -> Option<f64> {
484        (self.cert.calibration_map.kind == "temperature")
485            .then(|| self.cert.calibration_map.params.get("temperature").copied())
486            .flatten()
487    }
488}
489
490/// The JCS bytes of a JSON value.
491pub fn canonical(v: &serde_json::Value) -> Result<Vec<u8>, CertError> {
492    serde_jcs::to_vec(v).map_err(|e| CertError::Invalid(format!("not canonicalisable: {e}")))
493}
494
495pub fn certificate_id(v: &serde_json::Value) -> Result<String, CertError> {
496    Ok(format!("sha256:{}", hex(&Sha256::digest(canonical(v)?))))
497}
498
499/// `ed25519:` + the first 16 hex chars of SHA-256 of the raw public key.
500pub fn key_id(key: &VerifyingKey) -> String {
501    format!("ed25519:{}", &hex(&Sha256::digest(key.as_bytes()))[..16])
502}
503
504/// Verify `v` against `keys` (key id → base64url raw public key) and read it.
505///
506/// For v1 to v1.4. A v1.5 certificate binds a tenant, so it is refused here; verify it with the
507/// tenant the consumer expects, [`verify_for_tenant`]. A v1.6 certificate is refused too
508/// ([`verify_sequential`]).
509pub fn verify(
510    v: &serde_json::Value,
511    keys: &BTreeMap<String, String>,
512) -> Result<Verified, CertError> {
513    let (obj, cert) = read(v)?;
514    if cert.spec == SPEC_V1_5 {
515        return Err(CertError::Invalid(
516            "a v1.5 certificate is verified with its expected tenant (verify_for_tenant)".into(),
517        ));
518    }
519    if cert.spec == SPEC_V1_6 {
520        return Err(CertError::Invalid(V1_6_ONLY_SEQUENTIAL.into()));
521    }
522    if cert.spec == SPEC_V1_7 {
523        return Err(CertError::Invalid(V1_7_ONLY_ATTEMPT.into()));
524    }
525    let raw = keys
526        .get(&cert.signer_key_id)
527        .ok_or_else(|| CertError::UntrustedKey(cert.signer_key_id.clone()))?;
528    let key = public_key(raw, &cert.signer_key_id)?;
529    check_signature(&key, &cert, &bare_body(obj)?)?;
530    verified(v, cert)
531}
532
533/// The mode a trusted key may sign in (spec v1.5 §4): `Operator` (the tenant's own key, as every key
534/// in v1 to v1.4), or `Hosted` by the hosting service whose own key id is `host`.
535#[derive(Clone, Debug, PartialEq, Eq)]
536pub enum KeyMode {
537    Operator,
538    Hosted { host: String },
539}
540
541/// A trusted certificate-signing key of one tenant: the base64url raw Ed25519 public key, and the
542/// mode it may sign in.
543#[derive(Clone, Debug, PartialEq, Eq)]
544pub struct TrustedKey {
545    pub key: String,
546    pub mode: KeyMode,
547}
548
549/// One tenant's trusted keys: key id → [`TrustedKey`].
550pub type TenantKeys = BTreeMap<String, TrustedKey>;
551
552/// Read a tenant's trusted keys from a JSON object of key id → entry. An entry is a bare base64url
553/// string (an `operator` key, as in a v1 to v1.4 key map), `{"key": ..., "mode": "operator"}`, or
554/// `{"key": ..., "mode": "hosted", "host": "ed25519:<16 lowercase hex>"}` (spec v1.5 §4). Any
555/// other entry, an unknown field, or a `host` not in that form is refused as [`CertError::BadKey`].
556/// The key is checked against its id when a certificate is verified, as in [`verify`].
557pub fn tenant_keys_from_json(v: &serde_json::Value) -> Result<TenantKeys, CertError> {
558    let obj = v.as_object().ok_or_else(|| {
559        CertError::Invalid("trusted keys are not a JSON object of key id -> key entry".into())
560    })?;
561    let mut out = TenantKeys::new();
562    for (kid, entry) in obj {
563        let bad = || CertError::BadKey(kid.clone());
564        let trusted = match entry {
565            serde_json::Value::String(key) => TrustedKey {
566                key: key.clone(),
567                mode: KeyMode::Operator,
568            },
569            serde_json::Value::Object(e) => {
570                if e.keys()
571                    .any(|k| !matches!(k.as_str(), "key" | "mode" | "host"))
572                {
573                    return Err(bad());
574                }
575                let key = e.get("key").and_then(|k| k.as_str()).ok_or_else(bad)?;
576                let host = e.get("host");
577                let mode = match (e.get("mode").and_then(|m| m.as_str()), host) {
578                    (Some("operator"), None) => KeyMode::Operator,
579                    (Some("hosted"), Some(serde_json::Value::String(h))) if key_id_form(h) => {
580                        KeyMode::Hosted { host: h.clone() }
581                    }
582                    _ => return Err(bad()),
583                };
584                TrustedKey {
585                    key: key.to_string(),
586                    mode,
587                }
588            }
589            _ => return Err(bad()),
590        };
591        out.insert(kid.clone(), trusted);
592    }
593    Ok(out)
594}
595
596/// Verify `v` for the tenant the consumer expects, against that tenant's moded keys, and read it
597/// (spec v1.5 §4).
598///
599/// A v1.5 certificate: its `tenant` equals `tenant` (check 1, [`CertError::WrongTenant`]); its key
600/// is in `keys` and hashes to its id (check 2); the key's entry allows the certificate's signer mode,
601/// a hosted entry with the certificate's `host` (check 3, [`CertError::KeyMode`]); and the signature
602/// verifies strictly over `"decision-cert/certificate.v1.5" 0x0A tenant 0x0A JCS(body)`, built with
603/// the expected `tenant` (check 4). A v1 to v1.4 certificate binds no tenant: it verifies as with
604/// [`verify`], and only under an `operator` entry. A v1.6 certificate is refused: it is verified
605/// with its expected flow and environment, [`verify_sequential`].
606pub fn verify_for_tenant(
607    v: &serde_json::Value,
608    tenant: &str,
609    keys: &TenantKeys,
610) -> Result<Verified, CertError> {
611    expect_tenant(tenant)?;
612    let (obj, cert) = read(v)?;
613    if cert.spec == SPEC_V1_6 {
614        return Err(CertError::Invalid(V1_6_ONLY_SEQUENTIAL.into()));
615    }
616    if cert.spec == SPEC_V1_7 {
617        return Err(CertError::Invalid(V1_7_ONLY_ATTEMPT.into()));
618    }
619    let kid = &cert.signer_key_id;
620    if cert.spec != SPEC_V1_5 {
621        let entry = keys
622            .get(kid)
623            .ok_or_else(|| CertError::UntrustedKey(kid.clone()))?;
624        let key = public_key(&entry.key, kid)?;
625        if entry.mode != KeyMode::Operator {
626            return Err(CertError::KeyMode(kid.clone()));
627        }
628        check_signature(&key, &cert, &bare_body(obj)?)?;
629        return verified(v, cert);
630    }
631    tenant_bound(obj, cert, tenant, keys, CONTEXT_V1_5)
632}
633
634/// Why [`verify`] and [`verify_for_tenant`] refuse a v1.6 certificate.
635const V1_6_ONLY_SEQUENTIAL: &str =
636    "a v1.6 certificate is verified with its expected tenant, flow and environment (verify_sequential)";
637
638/// Why [`verify`], [`verify_for_tenant`] and [`verify_sequential`] refuse a v1.7 certificate.
639const V1_7_ONLY_ATTEMPT: &str =
640    "a v1.7 certificate is verified with its expected tenant, flow and environment (verify_attempt)";
641
642/// The expected tenant's form (spec v1.5 §4).
643fn expect_tenant(tenant: &str) -> Result<(), CertError> {
644    if tenant_ok(tenant) {
645        Ok(())
646    } else {
647        Err(CertError::Invalid(format!(
648            "the expected tenant must be 1 to {MAX_TENANT} characters of A-Z a-z 0-9 . _ : -"
649        )))
650    }
651}
652
653/// Verify `v`, a `decision-certificate.v1.6`, for the expected `tenant`, `flow` and `env` (spec
654/// v1.6 §4), and read it.
655///
656/// The schema, every v1.5 check and v1.6's checks beyond the schema (spec v1.6 §2.7, among them that
657/// every pre-registered class crossed, [`sequential::crossed`], and that the revealed salt matches
658/// its commitment, [`salt_commitment`]); then v1.5's checks 1 to 4 with the v1.6 signed bytes,
659/// `"decision-cert/certificate.v1.6" 0x0A tenant 0x0A SHA-256(JCS(body))` (the digest's 32 raw
660/// bytes) built with the expected `tenant`; then check 5, `sequential.flow` equals `flow` ([`CertError::WrongFlow`]), and
661/// check 6, `sequential.env` equals `env` ([`CertError::WrongEnv`]). Any other spec is refused.
662pub fn verify_sequential(
663    v: &serde_json::Value,
664    tenant: &str,
665    keys: &TenantKeys,
666    flow: &str,
667    env: &str,
668) -> Result<Verified, CertError> {
669    expect_tenant(tenant)?;
670    if !tenant_ok(flow) || !tenant_ok(env) {
671        return Err(CertError::Invalid(format!(
672            "the expected flow and environment must be 1 to {MAX_TENANT} characters of A-Z a-z 0-9 . _ : -"
673        )));
674    }
675    let (obj, cert) = read(v)?;
676    if cert.spec != SPEC_V1_6 {
677        return Err(CertError::Invalid(format!(
678            "verify_sequential verifies a {SPEC_V1_6} certificate, not {}",
679            cert.spec
680        )));
681    }
682    let verified = tenant_bound(obj, cert, tenant, keys, CONTEXT_V1_6)?;
683    // check() has made `sequential` present
684    let (own_flow, own_env) = verified
685        .cert
686        .sequential
687        .as_ref()
688        .map(|s| (s.flow.clone(), s.env.clone()))
689        .unwrap_or_default();
690    if own_flow != flow {
691        return Err(CertError::WrongFlow(own_flow));
692    }
693    if own_env != env {
694        return Err(CertError::WrongEnv(own_env));
695    }
696    Ok(verified)
697}
698
699/// Verify `v`, a `decision-certificate.v1.7`, for the expected `tenant`, `flow` and `env` (spec
700/// v1.7 §4.1), and read it.
701///
702/// As [`verify_sequential`] does for v1.6: the schema, every v1.6 check and v1.7's (spec v1.7 §2.5:
703/// the role, the champion a challenger cites, the delta budget); v1.5's checks 1 to 4 with the v1.7
704/// signed bytes, `"decision-cert/certificate.v1.7" 0x0A tenant 0x0A SHA-256(JCS(body))`; then the
705/// flow ([`CertError::WrongFlow`]) and the environment ([`CertError::WrongEnv`]). Any other spec
706/// is refused. A challenger's certificate takes force only by promotion: see [`verify_promotion`].
707pub fn verify_attempt(
708    v: &serde_json::Value,
709    tenant: &str,
710    keys: &TenantKeys,
711    flow: &str,
712    env: &str,
713) -> Result<Verified, CertError> {
714    expect_tenant(tenant)?;
715    if !tenant_ok(flow) || !tenant_ok(env) {
716        return Err(CertError::Invalid(format!(
717            "the expected flow and environment must be 1 to {MAX_TENANT} characters of A-Z a-z 0-9 . _ : -"
718        )));
719    }
720    let (obj, cert) = read(v)?;
721    if cert.spec != SPEC_V1_7 {
722        return Err(CertError::Invalid(format!(
723            "verify_attempt verifies a {SPEC_V1_7} certificate, not {}",
724            cert.spec
725        )));
726    }
727    let verified = tenant_bound(obj, cert, tenant, keys, CONTEXT_V1_7)?;
728    // check() has made `sequential` present
729    let (own_flow, own_env) = verified
730        .cert
731        .sequential
732        .as_ref()
733        .map(|s| (s.flow.clone(), s.env.clone()))
734        .unwrap_or_default();
735    if own_flow != flow {
736        return Err(CertError::WrongFlow(own_flow));
737    }
738    if own_env != env {
739        return Err(CertError::WrongEnv(own_env));
740    }
741    Ok(verified)
742}
743
744/// Verify that `challenger` may replace `champion` as the certificate a domain automates under
745/// (spec v1.7 §4.2), for the expected `tenant`, `flow` and `env` at the caller's `now`, and read
746/// the challenger.
747///
748/// The challenger verifies ([`verify_attempt`]) and is a challenger; the champion verifies
749/// ([`verify_sequential`] for v1.6, [`verify_attempt`] for v1.7) for the same tenant, flow and
750/// environment; the champion's id and values are the ones the challenger cites; the two share
751/// `domain`, `decision` and `options`; the champion was issued before the challenger was
752/// pre-registered; `changes` lists exactly the changes that differ, a renewal keeps the champion's
753/// `config_digest`; `alpha` is not raised; and `now` is before both certificates' `expires_at`.
754/// The challenger's own failure is returned as it is; every other refusal is
755/// [`CertError::NotPromotable`]. Whether the champion is the certificate in force in the revision
756/// the promotion replaces is the caller's to check.
757#[allow(clippy::too_many_arguments)]
758pub fn verify_promotion(
759    challenger: &serde_json::Value,
760    champion: &serde_json::Value,
761    tenant: &str,
762    keys: &TenantKeys,
763    flow: &str,
764    env: &str,
765    now: UtcDateTime,
766) -> Result<Verified, CertError> {
767    let no = |m: String| Err(CertError::NotPromotable(m));
768    let ch = verify_attempt(challenger, tenant, keys, flow, env)?;
769    let Some(cited) = ch
770        .attempt_role()
771        .and_then(|r| r.challenger.as_ref())
772        .cloned()
773    else {
774        return no("the certificate is a standalone attempt, not a challenger".into());
775    };
776    let champion_spec = champion.get("spec").and_then(|s| s.as_str());
777    let verified = match champion_spec {
778        Some(SPEC_V1_6) => verify_sequential(champion, tenant, keys, flow, env),
779        Some(SPEC_V1_7) => verify_attempt(champion, tenant, keys, flow, env),
780        _ => Err(CertError::Invalid(
781            "the champion's spec is not decision-certificate.v1.6 or decision-certificate.v1.7"
782                .into(),
783        )),
784    };
785    let cv = match verified {
786        Ok(x) => x,
787        Err(e) => return no(format!("the champion does not verify: {e}")),
788    };
789    let (a, b) = (&ch.cert, &cv.cert);
790    let (Some(sa), Some(sb)) = (&a.sequential, &b.sequential) else {
791        return no("a sequential certificate needs sequential".into());
792    };
793    let cp = &cited.champion;
794    let experiment = sb
795        .preregistration
796        .exploration
797        .as_ref()
798        .map(|e| &e.experiment_id);
799    let own = [
800        (
801            "certificate_id",
802            certificate_id(champion)? == cp.certificate_id,
803        ),
804        ("spec", b.spec == cp.spec),
805        ("attempt", sb.attempt == cp.attempt),
806        (
807            "preregistration_digest",
808            sb.preregistration.digest == cp.preregistration_digest,
809        ),
810        ("experiment_id", experiment == cp.experiment_id.as_ref()),
811        ("model_id", b.model_id == cp.model_id),
812        ("manifest_hash", b.manifest_hash == cp.manifest_hash),
813        ("expires_at", b.expires_at == cp.expires_at),
814    ];
815    if let Some((field, _)) = own.iter().find(|(_, same)| !same) {
816        return no(format!(
817            "the champion is not the certificate the challenger cites: its {field} differs"
818        ));
819    }
820    if a.domain != b.domain || a.decision != b.decision || a.options != b.options {
821        return no("the champion and the challenger differ in domain, decision or options".into());
822    }
823    if timestamp(&b.fitted_at)? > timestamp(&sa.preregistration.sealed_at)? {
824        return no(
825            "the challenger was pre-registered before its champion was issued (fitted_at)".into(),
826        );
827    }
828    for (name, differs) in challenger::differences((a, challenger), (b, champion))? {
829        if differs != cited.changes.iter().any(|x| x == name) {
830            return no(format!(
831                "changes must list {name} exactly when the two certificates differ in it"
832            ));
833        }
834    }
835    let same_config = sa.preregistration.config_digest == sb.preregistration.config_digest;
836    if cited.changes.is_empty() && !same_config {
837        return no("a renewal (no changes) pre-registers its champion's config_digest".into());
838    }
839    if cited.changes.iter().any(|x| x == "configuration") && same_config {
840        return no("changes lists configuration, but the config_digest is the champion's".into());
841    }
842    if a.alpha > b.alpha {
843        return no("a promotion never raises alpha".into());
844    }
845    // check 8: one account, and the champion's READY in the challenger's spent (spec v1.7 §1.5)
846    let (Some(ab), bb) = (
847        ch.attempt_role().map(|r| &r.budget),
848        b.attempt_role.as_ref().map(|r| &r.budget),
849    ) else {
850        return no("the certificate is a standalone attempt, not a challenger".into());
851    };
852    if bb.is_some_and(|bb| ab.window_days != bb.window_days || ab.total_ppm != bb.total_ppm) {
853        return no("the challenger's window_days and total_ppm differ from its champion's: one account (spec v1.7 §1.5)".into());
854    }
855    let (sealed_a, sealed_b) = (
856        sequential::v16_timestamp(&sa.preregistration.sealed_at)?,
857        sequential::v16_timestamp(&sb.preregistration.sealed_at)?,
858    );
859    let from = sealed_a.checked_sub(time::Duration::days(i64::from(ab.window_days)));
860    if from.is_none_or(|f| f < sealed_b) && sealed_b <= sealed_a {
861        let debit = match bb {
862            Some(bb) => bb.debit_ppm,
863            None => challenger::debit_ppm(b.delta.unwrap_or(0.0)),
864        };
865        if ab.spent_ppm < debit {
866            return no("the challenger's spent_ppm omits its champion's debit, sealed in its window (spec v1.7 §1.5)".into());
867        }
868    }
869    if now >= cv.expires_at {
870        return no("the champion has expired".into());
871    }
872    if now >= ch.expires_at {
873        return no("the challenger has expired".into());
874    }
875    Ok(ch)
876}
877
878/// v1.5's checks 1 to 4 for a certificate that binds its tenant (v1.5 to v1.7), with the signed
879/// bytes' context string.
880fn tenant_bound(
881    obj: &serde_json::Map<String, serde_json::Value>,
882    cert: Certificate,
883    tenant: &str,
884    keys: &TenantKeys,
885    context: &str,
886) -> Result<Verified, CertError> {
887    let kid = &cert.signer_key_id;
888    // check() has made both present, the tenant well-formed and the signer one of the two modes
889    let (Some(own), Some(signer)) = (&cert.tenant, &cert.signer) else {
890        return Err(CertError::Invalid(
891            "a certificate that binds its tenant needs tenant and signer".into(),
892        ));
893    };
894    if own != tenant {
895        return Err(CertError::WrongTenant(own.clone()));
896    }
897    let entry = keys
898        .get(kid)
899        .ok_or_else(|| CertError::UntrustedKey(kid.clone()))?;
900    let key = public_key(&entry.key, kid)?;
901    let allowed = match (&entry.mode, signer.mode.as_str()) {
902        (KeyMode::Operator, "operator") => true,
903        (KeyMode::Hosted { host }, "hosted") => signer.host.as_deref() == Some(host.as_str()),
904        _ => false,
905    };
906    if !allowed {
907        return Err(CertError::KeyMode(kid.clone()));
908    }
909    let mut msg = format!("{context}\n{tenant}\n").into_bytes();
910    let body = bare_body(obj)?;
911    if context == CONTEXT_V1_6 || context == CONTEXT_V1_7 {
912        // v1.6 and v1.7 sign the body's SHA-256, a fixed-size message (spec v1.6 §3, v1.7 §3)
913        msg.extend(Sha256::digest(&body));
914    } else {
915        msg.extend(body);
916    }
917    check_signature(&key, &cert, &msg)?;
918    verified_obj(obj, cert)
919}
920
921/// A verified certificate's expiry at the caller's `now` ([`Verified::is_expired`]).
922#[derive(Clone, Copy, Debug, PartialEq, Eq)]
923pub struct Expiry {
924    /// The time the caller checked expiry at.
925    pub now: UtcDateTime,
926    /// The certificate's `expires_at`.
927    pub expires_at: UtcDateTime,
928    /// Whether `now` is not before `expires_at`.
929    pub expired: bool,
930}
931
932/// The separate results of [`verify_document`]. They are never folded into one yes or no: a
933/// consumer reads each.
934#[derive(Debug)]
935pub struct DocumentVerdict {
936    /// `sha256:<hex>` of the document's JCS bytes, as [`certificate_id`] computes it, whatever the
937    /// verdict; None only when the document cannot be canonicalised.
938    pub certificate_id: Option<String>,
939    /// What [`verify_for_tenant`] returns for the document: the form, tenant, key, key mode and
940    /// signature checks.
941    pub verification: Result<Verified, CertError>,
942    /// The expiry at `now`, when the document verified; None when it did not.
943    pub expiry: Option<Expiry>,
944}
945
946/// Verify `v` for the expected `tenant` exactly as [`verify_for_tenant`] does, check its expiry at
947/// the caller's `now`, and recompute its id, returning the three as separate results.
948///
949/// The crate reads no clock: the caller passes `now`, so the same document, keys and `now` give the
950/// same verdict wherever it runs.
951pub fn verify_document(
952    v: &serde_json::Value,
953    tenant: &str,
954    keys: &TenantKeys,
955    now: UtcDateTime,
956) -> DocumentVerdict {
957    document_verdict(v, verify_for_tenant(v, tenant, keys), now)
958}
959
960/// [`verify_document`] for a v1.6 certificate: [`verify_sequential`] with the expected `flow` and
961/// `env`, the expiry at the caller's `now`, and the recomputed id, as separate results.
962pub fn verify_sequential_document(
963    v: &serde_json::Value,
964    tenant: &str,
965    keys: &TenantKeys,
966    flow: &str,
967    env: &str,
968    now: UtcDateTime,
969) -> DocumentVerdict {
970    document_verdict(v, verify_sequential(v, tenant, keys, flow, env), now)
971}
972
973/// [`verify_document`] for a v1.7 certificate: [`verify_attempt`] with the expected `flow` and
974/// `env`, the expiry at the caller's `now`, and the recomputed id, as separate results.
975pub fn verify_attempt_document(
976    v: &serde_json::Value,
977    tenant: &str,
978    keys: &TenantKeys,
979    flow: &str,
980    env: &str,
981    now: UtcDateTime,
982) -> DocumentVerdict {
983    document_verdict(v, verify_attempt(v, tenant, keys, flow, env), now)
984}
985
986/// [`verify_promotion`] as separate results: the promotion's verdict, the challenger's expiry at
987/// `now` and the challenger's recomputed id.
988pub fn verify_promotion_document(
989    challenger: &serde_json::Value,
990    champion: &serde_json::Value,
991    tenant: &str,
992    keys: &TenantKeys,
993    flow: &str,
994    env: &str,
995    now: UtcDateTime,
996) -> DocumentVerdict {
997    let verdict = verify_promotion(challenger, champion, tenant, keys, flow, env, now);
998    document_verdict(challenger, verdict, now)
999}
1000
1001fn document_verdict(
1002    v: &serde_json::Value,
1003    verification: Result<Verified, CertError>,
1004    now: UtcDateTime,
1005) -> DocumentVerdict {
1006    let expiry = verification.as_ref().ok().map(|x| Expiry {
1007        now,
1008        expires_at: x.expires_at,
1009        expired: x.is_expired(now),
1010    });
1011    DocumentVerdict {
1012        certificate_id: certificate_id(v).ok(),
1013        verification,
1014        expiry,
1015    }
1016}
1017
1018/// The value as a JSON object and its typed, checked certificate.
1019fn read(
1020    v: &serde_json::Value,
1021) -> Result<(&serde_json::Map<String, serde_json::Value>, Certificate), CertError> {
1022    let obj = v
1023        .as_object()
1024        .ok_or_else(|| CertError::Invalid("not a JSON object".into()))?;
1025    let invalid = |e: serde_json::Error| CertError::Invalid(e.to_string());
1026    // A v1.7 certificate's role, challenger and budget are read apart from the v1.6 block, so a
1027    // v1.6 certificate is read, and refused, exactly as before (spec v1.7 §2.5).
1028    let mut body = v.clone();
1029    let mut role = None;
1030    if obj.get("spec").and_then(|s| s.as_str()) == Some(SPEC_V1_7) {
1031        if let Some(seq) = body.get_mut("sequential").and_then(|s| s.as_object_mut()) {
1032            let mut own = serde_json::Map::new();
1033            for k in challenger::FIELDS {
1034                if let Some(x) = seq.remove(k) {
1035                    own.insert(k.to_string(), x);
1036                }
1037            }
1038            role = Some(serde_json::Value::Object(own));
1039        }
1040    }
1041    let mut cert: Certificate = serde_json::from_value(body).map_err(invalid)?;
1042    if let Some(r) = role {
1043        cert.attempt_role = Some(serde_json::from_value(r).map_err(invalid)?);
1044    }
1045    check(&cert)?;
1046    Ok((obj, cert))
1047}
1048
1049/// A trusted key's base64url raw public key, which must hash to `kid`.
1050fn public_key(raw: &str, kid: &str) -> Result<VerifyingKey, CertError> {
1051    URL_SAFE_NO_PAD
1052        .decode(raw)
1053        .ok()
1054        .and_then(|b| <[u8; 32]>::try_from(b).ok())
1055        .and_then(|b| VerifyingKey::from_bytes(&b).ok())
1056        .filter(|k| key_id(k) == kid)
1057        .ok_or_else(|| CertError::BadKey(kid.to_string()))
1058}
1059
1060/// The JCS bytes of the certificate without `signature`.
1061fn bare_body(obj: &serde_json::Map<String, serde_json::Value>) -> Result<Vec<u8>, CertError> {
1062    let mut body = obj.clone();
1063    body.remove("signature");
1064    canonical(&serde_json::Value::Object(body))
1065}
1066
1067/// `verify_strict` of the certificate's signature over `msg`.
1068fn check_signature(key: &VerifyingKey, cert: &Certificate, msg: &[u8]) -> Result<(), CertError> {
1069    let sig = URL_SAFE_NO_PAD
1070        .decode(&cert.signature)
1071        .ok()
1072        .and_then(|b| Signature::from_slice(&b).ok())
1073        .ok_or(CertError::BadSignature)?;
1074    key.verify_strict(msg, &sig)
1075        .map_err(|_| CertError::BadSignature)
1076}
1077
1078fn verified_obj(
1079    obj: &serde_json::Map<String, serde_json::Value>,
1080    cert: Certificate,
1081) -> Result<Verified, CertError> {
1082    verified(&serde_json::Value::Object(obj.clone()), cert)
1083}
1084
1085fn verified(v: &serde_json::Value, cert: Certificate) -> Result<Verified, CertError> {
1086    Ok(Verified {
1087        id: certificate_id(v)?,
1088        expires_at: timestamp(&cert.expires_at)?,
1089        cert,
1090    })
1091}
1092
1093/// 1 to 128 characters of `A-Z a-z 0-9 . _ : -` (spec v1.5 §2).
1094fn tenant_ok(t: &str) -> bool {
1095    (1..=MAX_TENANT).contains(&t.len())
1096        && t.bytes()
1097            .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b':' | b'-'))
1098}
1099
1100/// `ed25519:` and 16 lowercase hex characters: a key id's form.
1101fn key_id_form(s: &str) -> bool {
1102    s.strip_prefix("ed25519:")
1103        .is_some_and(|h| h.len() == 16 && lower_hex(h))
1104}
1105
1106/// The schema's constraints (spec/decision-certificate.v1.schema.json, the v1.1 schema, which
1107/// differs only in `spec`, and the v1.2 schema) that a typed read doesn't already enforce, so this
1108/// verifier accepts exactly what the schemas accept; and for v1.2, the histogram and calibration map
1109/// checks the schema cannot express (spec v1.2 §2).
1110fn check(c: &Certificate) -> Result<(), CertError> {
1111    let bad = |m: &str| Err(CertError::Invalid(m.to_string()));
1112    let unit = |x: f64| (0.0..=1.0).contains(&x);
1113    let open = |x: f64| x > 0.0 && x < 1.0;
1114    let threshold = |x: f64| (0.0..=ABSTAIN_ALL).contains(&x);
1115    if !SPECS.contains(&c.spec.as_str()) {
1116        return bad("spec is not decision-certificate.v1, decision-certificate.v1.1, decision-certificate.v1.2, decision-certificate.v1.3, decision-certificate.v1.4, decision-certificate.v1.5, decision-certificate.v1.6 or decision-certificate.v1.7");
1117    }
1118    fields_for_spec(c)?;
1119    let mut seen = std::collections::BTreeSet::new();
1120    if c.options.len() < 2 || !c.options.iter().all(|o| !o.is_empty() && seen.insert(o)) {
1121        return bad("options needs at least 2 distinct non-empty ids");
1122    }
1123    if [
1124        &c.domain,
1125        &c.decision,
1126        &c.calibration_map.kind,
1127        &c.issuer.tool,
1128        &c.issuer.version,
1129    ]
1130    .iter()
1131    .any(|s| s.is_empty())
1132    {
1133        return bad("domain, decision, calibration_map.kind and issuer must be non-empty");
1134    }
1135    // a v1.7 certificate is a v1.6 one with three more fields (spec v1.7 §2.1)
1136    let v17 = c.spec == SPEC_V1_7;
1137    let v16 = c.spec == SPEC_V1_6 || v17;
1138    let v15 = c.spec == SPEC_V1_5 || v16;
1139    let v14 = c.spec == SPEC_V1_4 || v15;
1140    match (c.method.as_str(), c.risk.as_str(), c.delta, c.ucb) {
1141        ("ltt", "selective_error", Some(d), _) if !v16 && open(d) => {}
1142        ("ltt", "selective_cost", Some(d), _) if v14 && !v16 && open(d) => {}
1143        ("crc", "joint_error", None, None) if !v16 => {}
1144        ("confidence_sequence", "automated_error", Some(d), None) if v16 && open(d) => {}
1145        _ => return bad("method, risk, delta and ucb disagree"),
1146    }
1147    if !open(c.alpha) || !threshold(c.abstain_below) || !unit(c.coverage) {
1148        return bad("alpha, abstain_below or coverage out of range");
1149    }
1150    if c.ucb.is_some_and(|u| !unit(u)) || !band_ok(&c.realized_band) {
1151        return bad("ucb or realized_band out of range");
1152    }
1153    for s in &c.segments {
1154        if s.field.is_empty()
1155            || !threshold(s.abstain_below)
1156            || !unit(s.coverage)
1157            || s.ucb.is_some_and(|u| !unit(u))
1158            || s.realized_band.as_ref().is_some_and(|b| !band_ok(b))
1159        {
1160            return bad("a segment is out of range");
1161        }
1162    }
1163    if !matches!(
1164        (c.split.method.as_str(), c.split.seed),
1165        ("time", None) | ("seeded", Some(_))
1166    ) {
1167        return bad("split.method and split.seed disagree");
1168    }
1169    if c.rule.unscored != "abstain" || c.rule.cannot_tell_above.is_some_and(|x| !unit(x)) {
1170        return bad("rule out of range");
1171    }
1172    if !matches!(c.audit.mode.as_str(), "sample" | "full-label")
1173        || !(c.audit.rate > 0.0 && c.audit.rate <= 1.0)
1174    {
1175        return bad("audit out of range");
1176    }
1177    if !model_id_ok(&c.model_id) {
1178        return bad("model_id must be <backend>/<model>@<version>");
1179    }
1180    if !sha256_ok(&c.data_hash) || c.manifest_hash.as_deref().is_some_and(|h| !sha256_ok(h)) {
1181        return bad("data_hash and manifest_hash must be sha256:<64 hex>");
1182    }
1183    if !key_id_form(&c.signer_key_id) {
1184        return bad("signer_key_id must be ed25519:<16 hex>");
1185    }
1186    if c.signature.len() != 86
1187        || !c
1188            .signature
1189            .bytes()
1190            .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
1191    {
1192        return bad("signature must be 86 base64url characters");
1193    }
1194    timestamp(&c.fitted_at)?;
1195    timestamp(&c.expires_at)?;
1196    if let Some(w) = &c.window {
1197        timestamp(&w.start)?;
1198        timestamp(&w.end)?;
1199    }
1200    if c.spec == SPEC_V1_2 || c.spec == SPEC_V1_3 || v14 {
1201        histograms(c)?;
1202        map::check(&c.calibration_map, c.options.len())?;
1203    }
1204    if c.spec == SPEC_V1_3 || v14 {
1205        automated(c)?;
1206    }
1207    if v14 {
1208        cost(c)?;
1209    }
1210    if v15 {
1211        if !c.tenant.as_deref().is_some_and(tenant_ok) {
1212            return Err(CertError::Invalid(format!(
1213                "tenant must be 1 to {MAX_TENANT} characters of A-Z a-z 0-9 . _ : -"
1214            )));
1215        }
1216        let signer_ok =
1217            c.signer
1218                .as_ref()
1219                .is_some_and(|s| match (s.mode.as_str(), s.host.as_deref()) {
1220                    ("operator", None) => true,
1221                    ("hosted", Some(h)) => key_id_form(h),
1222                    _ => false,
1223                });
1224        if !signer_ok {
1225            return bad("signer must be {\"mode\": \"operator\"} or {\"mode\": \"hosted\", \"host\": \"ed25519:<16 hex>\"}");
1226        }
1227    }
1228    if v16 {
1229        sequential::check(c)?;
1230    }
1231    if v17 {
1232        challenger::check(c)?;
1233    }
1234    Ok(())
1235}
1236
1237/// A v1.2 certificate has every v1.2 field, a v1.3 certificate every v1.2 and v1.3 field, and an
1238/// earlier certificate none of them, at the top level and in every segment. A certificate whose
1239/// fields belong to another spec is refused as a spec it is not, so a v1.1-shaped certificate naming
1240/// v1.2, or a v1.2-shaped one naming v1.3, is still refused as an unknown spec.
1241fn fields_for_spec(c: &Certificate) -> Result<(), CertError> {
1242    let v16 = c.spec == SPEC_V1_6 || c.spec == SPEC_V1_7;
1243    let v15 = c.spec == SPEC_V1_5 || v16;
1244    let v14 = c.spec == SPEC_V1_4 || v15;
1245    let v13 = c.spec == SPEC_V1_3 || v14;
1246    let v12 = c.spec == SPEC_V1_2 || v13;
1247    // (name, present, required by this spec): the v1.2 fields first, then the v1.3 ones.
1248    let mut present = vec![
1249        ("confidence_bins", c.confidence_bins.is_some(), v12),
1250        (
1251            "confidence_histogram",
1252            c.confidence_histogram.is_some(),
1253            v12,
1254        ),
1255        ("automate_options", c.automate_options.is_some(), v13),
1256        ("automated", c.automated.is_some(), v13),
1257        ("cost", c.cost.is_some(), v14),
1258        ("pvalue", c.pvalue.is_some(), v14),
1259        ("loss_sum", c.loss_sum.is_some(), v14),
1260        ("realized_cost", c.realized_cost.is_some(), v14),
1261        ("tenant", c.tenant.is_some(), v15),
1262        ("signer", c.signer.is_some(), v15),
1263        ("sequential", c.sequential.is_some(), v16),
1264    ];
1265    for s in &c.segments {
1266        present.push((
1267            "segments[].confidence_histogram",
1268            s.confidence_histogram.is_some(),
1269            v12,
1270        ));
1271        present.push(("segments[].automated", s.automated.is_some(), v13));
1272        present.push(("segments[].loss_sum", s.loss_sum.is_some(), v14));
1273        present.push(("segments[].realized_cost", s.realized_cost.is_some(), v14));
1274    }
1275    if let Some(a) = &c.automated {
1276        present.push(("automated.loss_sum", a.loss_sum.is_some(), v14));
1277        present.push(("automated.realized_cost", a.realized_cost.is_some(), v14));
1278    }
1279    for s in &c.segments {
1280        if let Some(a) = &s.automated {
1281            present.push(("segments[].automated.loss_sum", a.loss_sum.is_some(), v14));
1282            present.push((
1283                "segments[].automated.realized_cost",
1284                a.realized_cost.is_some(),
1285                v14,
1286            ));
1287        }
1288    }
1289    for (name, here, required) in present {
1290        if required && !here {
1291            return Err(CertError::Invalid(format!(
1292                "spec is not consistent with the fields: {} requires `{name}`",
1293                c.spec
1294            )));
1295        }
1296        if !required && here {
1297            return Err(CertError::Invalid(format!(
1298                "unknown field `{name}` in a {} certificate",
1299                c.spec
1300            )));
1301        }
1302    }
1303    Ok(())
1304}
1305
1306/// v1.2's checks beyond the schema: the bins rise strictly from 0 to 1, and each histogram has one
1307/// count per bin and counts exactly its test's `n` cases.
1308fn histograms(c: &Certificate) -> Result<(), CertError> {
1309    let bins = c.confidence_bins.as_deref().unwrap_or_default();
1310    let rising = bins.windows(2).all(|w| w[0] < w[1]);
1311    if !(2..=MAX_BINS + 1).contains(&bins.len())
1312        || bins[0] != 0.0
1313        || bins[bins.len() - 1] != 1.0
1314        || !rising
1315    {
1316        return Err(CertError::Invalid(format!(
1317            "confidence_bins must rise strictly from 0 to 1, with 1 to {MAX_BINS} bins"
1318        )));
1319    }
1320    let tests = std::iter::once((&c.confidence_histogram, c.n))
1321        .chain(c.segments.iter().map(|s| (&s.confidence_histogram, s.n)));
1322    for (h, n) in tests {
1323        if let Some(Some(h)) = h {
1324            let total: u128 =
1325                h.counts.iter().map(|&x| u128::from(x)).sum::<u128>() + u128::from(h.unscored);
1326            if h.counts.len() != bins.len() - 1 || total != u128::from(n) {
1327                return Err(CertError::Invalid(
1328                    "a confidence_histogram needs one count per bin, and its counts and unscored must sum to n".into(),
1329                ));
1330            }
1331        }
1332    }
1333    Ok(())
1334}
1335
1336/// v1.3's checks beyond the schema: `automate_options` names options of the certificate, once each
1337/// and in their order; each test's `automated` share is at most its `coverage`, its numbers are in
1338/// range, and its `ucb` and `realized_band` are null exactly where the test's are.
1339fn automated(c: &Certificate) -> Result<(), CertError> {
1340    let auto = c.automate_options.as_deref().unwrap_or_default();
1341    let mut at = c.options.iter();
1342    if auto.is_empty() || !auto.iter().all(|o| at.any(|x| x == o)) {
1343        return Err(CertError::Invalid(
1344            "automate_options must name one or more of the options, once each and in their order"
1345                .into(),
1346        ));
1347    }
1348    let unit = |x: f64| (0.0..=1.0).contains(&x);
1349    let tests = std::iter::once((
1350        &c.automated,
1351        c.coverage,
1352        c.ucb.is_some(),
1353        true, // the top level's realized_band is never null
1354    ))
1355    .chain(c.segments.iter().map(|s| {
1356        (
1357            &s.automated,
1358            s.coverage,
1359            s.ucb.is_some(),
1360            s.realized_band.is_some(),
1361        )
1362    }));
1363    for (a, coverage, ucb, band) in tests {
1364        let Some(a) = a else { continue };
1365        if !unit(a.coverage)
1366            || a.coverage > coverage
1367            || a.ucb.is_some_and(|u| !unit(u))
1368            || a.realized_band.as_ref().is_some_and(|b| !band_ok(b))
1369            || a.ucb.is_some() != ucb
1370            || a.realized_band.is_some() != band
1371        {
1372            return Err(CertError::Invalid(
1373                "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(),
1374            ));
1375        }
1376    }
1377    // Every option automated: the automated cases are the answered cases, so each block is its
1378    // test's own numbers.
1379    if auto.len() == c.options.len() {
1380        let same = |a: &Option<Automated>, coverage: f64, ucb: Option<f64>, band: Option<&Band>| {
1381            a.as_ref().is_none_or(|a| {
1382                a.coverage == coverage && a.ucb == ucb && a.realized_band.as_ref() == band
1383            })
1384        };
1385        // v1.4: the loss sums (whole numbers, compared exactly) and realized costs agree too (both
1386        // absent before v1.4)
1387        let same_cost =
1388            |a: &Option<Automated>, ls: Option<Option<u64>>, rc: Option<Option<f64>>| {
1389                a.as_ref()
1390                    .is_none_or(|a| a.loss_sum == ls && a.realized_cost == rc)
1391            };
1392        if !same(&c.automated, c.coverage, c.ucb, Some(&c.realized_band))
1393            || !same_cost(&c.automated, c.loss_sum, c.realized_cost)
1394            || !c
1395                .segments
1396                .iter()
1397                .all(|s| same(&s.automated, s.coverage, s.ucb, s.realized_band.as_ref()))
1398            || !c
1399                .segments
1400                .iter()
1401                .all(|s| same_cost(&s.automated, s.loss_sum, s.realized_cost))
1402        {
1403            return Err(CertError::Invalid(
1404                "automated must equal its test's coverage, ucb and realized_band when every option is automated".into(),
1405            ));
1406        }
1407    }
1408    Ok(())
1409}
1410
1411/// v1.4's checks beyond the schema (spec v1.4 §2): `cost` and `pvalue` pair with `risk`; the cost
1412/// matrix is options x options with a zero diagonal, whole-number entries in [0, c_max], `c_max` its
1413/// largest entry, above 0 and at most 10^6, and its off-diagonal entries not all equal; `loss_sum`
1414/// and `realized_cost` are null for the error risks, for an inherited segment and wherever their test
1415/// answered no case, and otherwise `loss_sum` is at most c_max * k and `realized_cost` is exactly
1416/// `loss_sum / (c_max * k)`, k = floor(coverage * n + 1/2) the answered cases.
1417/// v1.4: the largest `c_max`.
1418pub const MAX_C: u64 = 1_000_000;
1419/// v1.4: the largest `c_max * answered`, 2^53, so that it and every `loss_sum` are exact in an f64.
1420const SAFE_SCALE: f64 = 9_007_199_254_740_992.0;
1421
1422fn cost(c: &Certificate) -> Result<(), CertError> {
1423    let bad = |m: &str| Err(CertError::Invalid(m.to_string()));
1424    let cost = c.cost.clone().flatten();
1425    let pvalue = c.pvalue.clone().flatten();
1426    let want = match c.risk.as_str() {
1427        "selective_error" => Some("binomial"),
1428        "selective_cost" => Some("hoeffding_bentkus"),
1429        _ => None,
1430    };
1431    if cost.is_some() != (c.risk == "selective_cost") || pvalue.as_deref() != want {
1432        return bad("cost, pvalue and risk disagree");
1433    }
1434    if let Some(k) = &cost {
1435        let n = c.options.len();
1436        let m = &k.matrix;
1437        let all = || m.iter().flatten().copied();
1438        let ok = m.len() == n
1439            && m.iter().all(|r| r.len() == n)
1440            && (0..n).all(|i| m[i][i] == 0)
1441            && all().all(|x| x <= k.c_max)
1442            && (1..=MAX_C).contains(&k.c_max)
1443            && all().max() == Some(k.c_max)
1444            && k.unit.as_deref() != Some("");
1445        if !ok {
1446            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");
1447        }
1448        let off: Vec<u64> = (0..n)
1449            .flat_map(|i| (0..n).filter(move |&j| j != i).map(move |j| (i, j)))
1450            .map(|(i, j)| m[i][j])
1451            .collect();
1452        if off.iter().all(|&x| x == off[0]) {
1453            return bad("a cost risk needs unequal off-diagonal costs; with equal costs it is selective_error");
1454        }
1455    }
1456    let unit = |x: f64| (0.0..=1.0).contains(&x);
1457    // (realized_cost, loss_sum, coverage, its test's n, own test): each test, and each test's automated
1458    // cases, whose coverage is a share of the test's n
1459    type Row = (Option<f64>, Option<u64>, f64, u64, bool);
1460    let auto = |a: &Option<Automated>, n: u64, own: bool| -> Row {
1461        a.as_ref().map_or((None, None, 0.0, n, own), |a| {
1462            (
1463                a.realized_cost.flatten(),
1464                a.loss_sum.flatten(),
1465                a.coverage,
1466                n,
1467                own,
1468            )
1469        })
1470    };
1471    let mut tests: Vec<Row> = vec![(
1472        c.realized_cost.flatten(),
1473        c.loss_sum.flatten(),
1474        c.coverage,
1475        c.n,
1476        true,
1477    )];
1478    tests.extend(c.segments.iter().map(|s| {
1479        (
1480            s.realized_cost.flatten(),
1481            s.loss_sum.flatten(),
1482            s.coverage,
1483            s.n,
1484            !s.inherited,
1485        )
1486    }));
1487    tests.push(auto(&c.automated, c.n, true));
1488    tests.extend(
1489        c.segments
1490            .iter()
1491            .map(|s| auto(&s.automated, s.n, !s.inherited)),
1492    );
1493    for (rc, ls, coverage, n, own) in tests {
1494        let expect = cost.is_some() && own && coverage > 0.0;
1495        if rc.is_some() != expect || ls.is_some() != expect || rc.is_some_and(|x| !unit(x)) {
1496            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");
1497        }
1498        if let (Some(rc), Some(ls), Some(k)) = (rc, ls, &cost) {
1499            // whole costs: one exact division, so every verifier, in any language, gets the same
1500            // number. Both operands are exact in f64 (at most 2^53).
1501            let answered = (coverage * n as f64 + 0.5).floor();
1502            // k can't be fudged by rounding: coverage is exactly k / n, one correctly rounded division
1503            // of two exact integers, as the issuer writes it
1504            if !(1..=1u64 << 53).contains(&n) || coverage != answered / n as f64 {
1505                return bad(
1506                    "coverage must be exactly answered / n, a whole number of answered cases",
1507                );
1508            }
1509            let ok = (1.0..=SAFE_SCALE).contains(&answered) && {
1510                let scale = u128::from(k.c_max) * answered as u128;
1511                scale <= SAFE_SCALE as u128
1512                    && u128::from(ls) <= scale
1513                    && rc == ls as f64 / scale as f64
1514            };
1515            if !ok {
1516                return bad("realized_cost must be loss_sum / (c_max * answered), with loss_sum at most c_max * answered");
1517            }
1518        }
1519    }
1520    Ok(())
1521}
1522
1523/// `^[^/]+/.+@.+$`, and not ending in `@?` (an unknown version).
1524fn model_id_ok(m: &str) -> bool {
1525    // The pattern's `.` matches no line terminator.
1526    if m.chars()
1527        .any(|c| matches!(c, '\n' | '\r' | '\u{2028}' | '\u{2029}'))
1528    {
1529        return false;
1530    }
1531    let Some((backend, rest)) = m.split_once('/') else {
1532        return false;
1533    };
1534    let at = rest
1535        .char_indices()
1536        .skip(1)
1537        .any(|(i, ch)| ch == '@' && i + 1 < rest.len());
1538    !backend.is_empty() && at && !m.ends_with("@?")
1539}
1540
1541fn sha256_ok(h: &str) -> bool {
1542    h.strip_prefix("sha256:")
1543        .is_some_and(|x| x.len() == 64 && lower_hex(x))
1544}
1545
1546fn lower_hex(s: &str) -> bool {
1547    s.bytes()
1548        .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
1549}
1550
1551fn band_ok(b: &Band) -> bool {
1552    b.level > 0.0 && b.level < 1.0 && (0.0..=1.0).contains(&b.low) && (0.0..=1.0).contains(&b.high)
1553}
1554
1555/// Parse the spec's timestamp form, `YYYY-MM-DDTHH:MM:SSZ`, and nothing else.
1556///
1557/// The form is the schema's `^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$` exactly (no `t`, `z`, space,
1558/// fraction or numeric offset), naming a real date in years 0000 to 9999 (proleptic Gregorian, so
1559/// 0000-02-29 exists), hours 00 to 23, minutes 00 to 59 and seconds 00 to 60. A second of 60 (a
1560/// leap second, accepted at the end of any minute) reads as the last nanosecond of that minute's
1561/// second 59: after every time of second precision up to it, and before the next minute.
1562pub fn timestamp(s: &str) -> Result<UtcDateTime, CertError> {
1563    timestamp_parts(s)
1564        .ok_or_else(|| CertError::Invalid(format!("timestamp {s:?} is not YYYY-MM-DDTHH:MM:SSZ")))
1565}
1566
1567fn timestamp_parts(s: &str) -> Option<UtcDateTime> {
1568    let b = s.as_bytes();
1569    let form = b.len() == 20
1570        && b.iter().enumerate().all(|(i, &c)| match i {
1571            4 | 7 => c == b'-',
1572            10 => c == b'T',
1573            13 | 16 => c == b':',
1574            19 => c == b'Z',
1575            _ => c.is_ascii_digit(),
1576        });
1577    if !form {
1578        return None;
1579    }
1580    let n = |i: usize, len: usize| {
1581        b[i..i + len]
1582            .iter()
1583            .fold(0u16, |acc, &c| acc * 10 + u16::from(c - b'0'))
1584    };
1585    let month = Month::try_from(u8::try_from(n(5, 2)).ok()?).ok()?;
1586    let date = Date::from_calendar_date(i32::from(n(0, 4)), month, u8::try_from(n(8, 2)).ok()?);
1587    let (second, nano) = match n(17, 2) {
1588        60 => (59, 999_999_999),
1589        sec => (u8::try_from(sec).ok()?, 0),
1590    };
1591    let time = Time::from_hms_nano(
1592        u8::try_from(n(11, 2)).ok()?,
1593        u8::try_from(n(14, 2)).ok()?,
1594        second,
1595        nano,
1596    );
1597    Some(UtcDateTime::new(date.ok()?, time.ok()?))
1598}
1599
1600fn hex(b: &[u8]) -> String {
1601    b.iter().map(|x| format!("{x:02x}")).collect()
1602}
1603
1604#[cfg(test)]
1605mod tests {
1606    use super::*;
1607
1608    fn valid() -> serde_json::Value {
1609        let f: serde_json::Value =
1610            serde_json::from_str(include_str!("../../fixtures/valid_segments_unicode.json"))
1611                .unwrap();
1612        f["certificate"].clone()
1613    }
1614
1615    /// v1 and v1.1 define only `temperature`, so a `dr` map in one of them gives no probabilities,
1616    /// though the certificate verifies as it always did.
1617    #[test]
1618    fn dr_maps_are_applied_in_v1_2_certificates_only() {
1619        let mut cert: Certificate = serde_json::from_value(valid()).unwrap();
1620        cert.calibration_map = CalibrationMap {
1621            kind: "dr".into(),
1622            params: [("a", 1.0), ("b0", 0.0), ("b1", 0.0)]
1623                .iter()
1624                .map(|(k, v)| (k.to_string(), *v))
1625                .collect(),
1626            label_budget: None,
1627        };
1628        let v = Verified {
1629            id: String::new(),
1630            cert,
1631            expires_at: UtcDateTime::now(),
1632        };
1633        assert!(v.probabilities(&[1.0, 0.0]).is_none() && v.confidence(&[1.0, 0.0]).is_none());
1634        let mut v12 = v.clone();
1635        v12.cert.spec = SPEC_V1_2.into();
1636        assert!(v12.confidence(&[1.0, 0.0]).unwrap() > 0.73);
1637    }
1638
1639    #[test]
1640    fn check_rejects_what_the_schema_rejects() {
1641        let typed =
1642            |v: &serde_json::Value| serde_json::from_value::<Certificate>(v.clone()).unwrap();
1643        assert!(check(&typed(&valid())).is_ok());
1644        let edits: [(&str, serde_json::Value); 15] = [
1645            ("data_hash", serde_json::json!("sha256:XYZ")),
1646            ("manifest_hash", serde_json::json!("md5:00")),
1647            ("signer_key_id", serde_json::json!("ed25519:short")),
1648            ("model_id", serde_json::json!("/x@y")),
1649            ("model_id", serde_json::json!("b/m@?")),
1650            (
1651                "window",
1652                serde_json::json!({"start": "2023-01-02", "end": "2023-12-29T23:59:59Z"}),
1653            ),
1654            ("expires_at", serde_json::json!("2027-01-23T12:00:00+00:00")),
1655            ("expires_at", serde_json::json!("2027-01-23 12:00:00Z")),
1656            ("fitted_at", serde_json::json!("2026-10-25t12:00:00Z")),
1657            ("domain", serde_json::json!("")),
1658            ("options", serde_json::json!(["yes", "yes"])),
1659            ("split", serde_json::json!({"method": "time", "seed": 3})),
1660            ("alpha", serde_json::json!(1.0)),
1661            ("signature", serde_json::json!("abc")),
1662            ("model_id", serde_json::json!("a/b\n@c")),
1663        ];
1664        for (field, value) in edits {
1665            let mut v = valid();
1666            v[field] = value.clone();
1667            assert!(check(&typed(&v)).is_err(), "{field} = {value}");
1668        }
1669    }
1670
1671    #[test]
1672    fn nested_nullable_fields_must_be_present() {
1673        let paths: [(&str, &str); 5] = [
1674            ("segments", "ucb"),
1675            ("segments", "realized_band"),
1676            ("split", "seed"),
1677            ("calibration_map", "label_budget"),
1678            ("rule", "cannot_tell_above"),
1679        ];
1680        for (outer, inner) in paths {
1681            let mut v = valid();
1682            let o = if outer == "segments" {
1683                &mut v[outer][0]
1684            } else {
1685                &mut v[outer]
1686            };
1687            o.as_object_mut().unwrap().remove(inner);
1688            let e = serde_json::from_value::<Certificate>(v).err();
1689            assert!(
1690                e.is_some_and(|e| e.to_string().contains(inner)),
1691                "{outer}.{inner}"
1692            );
1693        }
1694    }
1695
1696    fn utc(y: i32, m: Month, d: u8, hh: u8, mm: u8, ss: u8, ns: u32) -> UtcDateTime {
1697        UtcDateTime::new(
1698            Date::from_calendar_date(y, m, d).unwrap(),
1699            Time::from_hms_nano(hh, mm, ss, ns).unwrap(),
1700        )
1701    }
1702
1703    /// The timestamps accepted and refused are the ones the 0.7.0 crate accepted and refused
1704    /// (`chrono`'s RFC 3339 parser behind the schema's exact form).
1705    #[test]
1706    fn timestamps_accept_the_spec_form_and_real_dates_only() {
1707        let at = |s: &str| timestamp(s).unwrap_or_else(|e| panic!("{s}: {e}"));
1708        assert_eq!(
1709            at("2027-01-23T12:00:00Z"),
1710            utc(2027, Month::January, 23, 12, 0, 0, 0)
1711        );
1712        assert_eq!(at("1970-01-01T00:00:00Z"), UtcDateTime::UNIX_EPOCH);
1713        assert_eq!(at("2024-02-29T00:00:00Z").unix_timestamp(), 1_709_164_800);
1714        assert_eq!(
1715            at("0000-01-01T00:00:00Z"),
1716            utc(0, Month::January, 1, 0, 0, 0, 0)
1717        );
1718        assert_eq!(
1719            at("9999-12-31T23:59:59Z"),
1720            utc(9999, Month::December, 31, 23, 59, 59, 0)
1721        );
1722        for s in [
1723            "2000-02-29T00:00:00Z",
1724            "0000-02-29T00:00:00Z",
1725            "2400-02-29T00:00:00Z",
1726            "2027-12-31T00:00:00Z",
1727            "2027-04-30T00:00:00Z",
1728            "2027-01-01T23:59:59Z",
1729        ] {
1730            at(s);
1731        }
1732        let refused = [
1733            // not a real date or time
1734            "2023-02-29T00:00:00Z",
1735            "1900-02-29T00:00:00Z",
1736            "2100-02-29T00:00:00Z",
1737            "2027-04-31T00:00:00Z",
1738            "2027-00-01T00:00:00Z",
1739            "2027-13-01T00:00:00Z",
1740            "2027-01-00T00:00:00Z",
1741            "2027-01-32T00:00:00Z",
1742            "2027-01-23T24:00:00Z",
1743            "2027-01-23T12:60:00Z",
1744            "2027-01-23T12:00:61Z",
1745            "2027-01-23T12:00:99Z",
1746            // not the form
1747            "2027-01-23t12:00:00Z",
1748            "2027-01-23T12:00:00z",
1749            "2027-01-23 12:00:00Z",
1750            "2027-01-23T12:00:00+00:00",
1751            "2027-01-23T12:00:00-00:00",
1752            "2027-01-23T12:00:00+01:00",
1753            "2027-01-23T12:00:00.5Z",
1754            "2027-01-23T12:00:00.000Z",
1755            "2027-01-23T12:00:00",
1756            "2027-01-23",
1757            "2027-01-23T12:00Z",
1758            "2027-1-23T12:00:00Z",
1759            "+2027-01-23T12:00:00Z",
1760            "-0001-01-01T00:00:00Z",
1761            "10000-01-01T00:00:00Z",
1762            " 2027-01-23T12:00:00Z",
1763            "2027-01-23T12:00:00Z ",
1764            "2027-01-23T12:00:00ZZ",
1765            "2027-01-23T12:00:00Z\n",
1766            "\u{ff12}027-01-23T12:00:00Z",
1767            "",
1768        ];
1769        for s in refused {
1770            let e = timestamp(s).expect_err(s);
1771            assert_eq!(
1772                e.to_string(),
1773                format!(
1774                    "certificate is not a valid decision certificate: timestamp {s:?} is not \
1775                     YYYY-MM-DDTHH:MM:SSZ"
1776                )
1777            );
1778        }
1779    }
1780
1781    /// A second of 60 is accepted at the end of any minute, and orders after every second of
1782    /// that minute and before the next one, as it did with `chrono`.
1783    #[test]
1784    fn leap_seconds_are_accepted_and_ordered() {
1785        let leap = timestamp("2026-12-31T23:59:60Z").unwrap();
1786        let before = timestamp("2026-12-31T23:59:59Z").unwrap();
1787        let after = timestamp("2027-01-01T00:00:00Z").unwrap();
1788        assert!(before < leap && leap < after);
1789        assert_eq!(
1790            leap,
1791            utc(2026, Month::December, 31, 23, 59, 59, 999_999_999)
1792        );
1793        let mid = timestamp("2027-06-15T12:34:60Z").unwrap();
1794        assert!(
1795            timestamp("2027-06-15T12:34:59Z").unwrap() < mid
1796                && mid < timestamp("2027-06-15T12:35:00Z").unwrap()
1797        );
1798        assert!(timestamp("0000-01-01T00:00:60Z").is_ok());
1799        assert!(timestamp("9999-12-31T23:59:60Z").is_ok());
1800
1801        let mut cert: Certificate = serde_json::from_value(valid()).unwrap();
1802        cert.expires_at = "2026-12-31T23:59:60Z".into();
1803        let v = Verified {
1804            id: String::new(),
1805            expires_at: timestamp(&cert.expires_at).unwrap(),
1806            cert,
1807        };
1808        assert!(!v.is_expired(before));
1809        assert!(v.is_expired(leap));
1810        assert!(v.is_expired(after));
1811    }
1812
1813    /// The same table as python/tests/test_ed25519.py: every small-order encoding is a key
1814    /// `verify_strict` refuses (the Python verifier must refuse the same ones).
1815    #[test]
1816    fn small_order_keys_are_weak() {
1817        let table = [
1818            "0100000000000000000000000000000000000000000000000000000000000000",
1819            "ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f",
1820            "0000000000000000000000000000000000000000000000000000000000000000",
1821            "0000000000000000000000000000000000000000000000000000000000000080",
1822            "26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05",
1823            "26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85",
1824            "c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a",
1825            "c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa",
1826            "0100000000000000000000000000000000000000000000000000000000000080",
1827            "ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
1828            "edffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f",
1829            "edffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
1830            "eeffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f",
1831            "eeffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
1832        ];
1833        for h in table {
1834            let b: [u8; 32] = (0..32)
1835                .map(|i| u8::from_str_radix(&h[2 * i..2 * i + 2], 16).unwrap())
1836                .collect::<Vec<_>>()
1837                .try_into()
1838                .unwrap();
1839            let k = VerifyingKey::from_bytes(&b).unwrap_or_else(|e| panic!("{h}: {e}"));
1840            assert!(k.is_weak(), "{h}");
1841        }
1842    }
1843
1844    #[test]
1845    fn certified_segments_set_the_threshold_and_inherited_ones_do_not() {
1846        let cert: Certificate = serde_json::from_value(valid()).unwrap();
1847        let v = Verified {
1848            id: String::new(),
1849            expires_at: timestamp(&cert.expires_at).unwrap(),
1850            cert,
1851        };
1852        assert_eq!(v.threshold_for(Some("east")), 0.9);
1853        assert_eq!(
1854            v.threshold_for(Some("z\u{fc}rich \u{2603}")),
1855            v.cert.abstain_below
1856        );
1857        assert_eq!(v.threshold_for(None), v.cert.abstain_below);
1858        assert!(
1859            v.is_expired(v.expires_at) && !v.is_expired(v.expires_at - time::Duration::seconds(1))
1860        );
1861    }
1862}