1mod map;
18mod monitor;
19
20pub use map::{confidence, probabilities, MAP_KINDS};
21pub use monitor::{bin_of, chi2_sf, shift_score, ShiftScore};
22
23use std::collections::BTreeMap;
24
25use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};
26use chrono::{DateTime, Utc};
27use ed25519_dalek::{Signature, VerifyingKey};
28use serde::Deserialize;
29use sha2::{Digest, Sha256};
30
31pub const SPEC: &str = "decision-certificate.v1";
33pub const SPEC_V1_1: &str = "decision-certificate.v1.1";
35pub const SPEC_V1_2: &str = "decision-certificate.v1.2";
37pub const SPECS: [&str; 3] = [SPEC, SPEC_V1_1, SPEC_V1_2];
39pub const MAX_BINS: usize = 100;
41pub const ABSTAIN_ALL: f64 = 1.01;
43
44#[derive(Debug, thiserror::Error)]
45pub enum CertError {
46 #[error("certificate is not a valid decision certificate: {0}")]
47 Invalid(String),
48 #[error("certificate signed by {0}, which is not a trusted key")]
49 UntrustedKey(String),
50 #[error("trusted key {0} is malformed or does not hash to its id")]
51 BadKey(String),
52 #[error("certificate signature does not verify")]
53 BadSignature,
54}
55
56#[derive(Deserialize, Clone, Debug, PartialEq)]
57#[serde(deny_unknown_fields)]
58pub struct Band {
59 pub level: f64,
60 pub low: f64,
61 pub high: f64,
62}
63
64#[derive(Deserialize, Clone, Debug, PartialEq, Eq)]
67#[serde(deny_unknown_fields)]
68pub struct Histogram {
69 pub counts: Vec<u64>,
70 pub unscored: u64,
71}
72
73#[derive(Deserialize, Clone, Debug, PartialEq)]
74#[serde(deny_unknown_fields)]
75pub struct Segment {
76 pub field: String,
77 pub value: String,
78 pub n: u64,
79 pub abstain_below: f64,
80 pub coverage: f64,
81 #[serde(deserialize_with = "nullable")]
82 pub ucb: Option<f64>,
83 #[serde(deserialize_with = "nullable")]
84 pub realized_band: Option<Band>,
85 pub inherited: bool,
86 #[serde(default, deserialize_with = "present")]
88 pub confidence_histogram: Option<Option<Histogram>>,
89}
90
91#[derive(Deserialize, Clone, Debug, PartialEq)]
92#[serde(deny_unknown_fields)]
93pub struct Split {
94 pub method: String,
95 #[serde(deserialize_with = "nullable")]
96 pub seed: Option<i64>,
97}
98
99#[derive(Deserialize, Clone, Debug, PartialEq)]
100#[serde(deny_unknown_fields)]
101pub struct CalibrationMap {
102 pub kind: String,
103 pub params: BTreeMap<String, f64>,
104 #[serde(deserialize_with = "nullable")]
105 pub label_budget: Option<u64>,
106}
107
108#[derive(Deserialize, Clone, Debug, PartialEq)]
109#[serde(deny_unknown_fields)]
110pub struct Rule {
111 #[serde(deserialize_with = "nullable")]
112 pub cannot_tell_above: Option<f64>,
113 pub unscored: String,
114}
115
116#[derive(Deserialize, Clone, Debug, PartialEq)]
117#[serde(deny_unknown_fields)]
118pub struct Window {
119 pub start: String,
120 pub end: String,
121}
122
123#[derive(Deserialize, Clone, Debug, PartialEq)]
124#[serde(deny_unknown_fields)]
125pub struct Audit {
126 pub mode: String,
127 pub rate: f64,
128 pub n: u64,
129 pub propensity_logged: bool,
130}
131
132#[derive(Deserialize, Clone, Debug, PartialEq)]
133#[serde(deny_unknown_fields)]
134pub struct Issuer {
135 pub tool: String,
136 pub version: String,
137}
138
139#[derive(Deserialize, Clone, Debug, PartialEq)]
141#[serde(deny_unknown_fields)]
142pub struct Certificate {
143 pub spec: String,
144 pub domain: String,
145 pub decision: String,
146 pub options: Vec<String>,
147 pub model_id: String,
148 #[serde(deserialize_with = "nullable")]
149 pub manifest_hash: Option<String>,
150 pub data_hash: String,
151 pub n_cal: u64,
152 pub n_temperature: u64,
153 pub split: Split,
154 pub calibration_map: CalibrationMap,
155 pub rule: Rule,
156 pub alpha: f64,
157 #[serde(deserialize_with = "nullable")]
158 pub delta: Option<f64>,
159 pub method: String,
160 pub risk: String,
161 pub n: u64,
162 pub abstain_below: f64,
163 pub coverage: f64,
164 #[serde(deserialize_with = "nullable")]
165 pub ucb: Option<f64>,
166 pub realized_band: Band,
167 pub segments: Vec<Segment>,
168 #[serde(deserialize_with = "nullable")]
169 pub window: Option<Window>,
170 pub fitted_at: String,
171 pub expires_at: String,
172 pub audit: Audit,
173 pub issuer: Issuer,
174 pub signer_key_id: String,
175 pub signature: String,
176 #[serde(default, deserialize_with = "present")]
178 pub confidence_bins: Option<Vec<f64>>,
179 #[serde(default, deserialize_with = "present")]
181 pub confidence_histogram: Option<Option<Histogram>>,
182}
183
184fn present<'de, D: serde::Deserializer<'de>, T: Deserialize<'de>>(
187 d: D,
188) -> Result<Option<T>, D::Error> {
189 T::deserialize(d).map(Some)
190}
191
192fn nullable<'de, D: serde::Deserializer<'de>, T: Deserialize<'de>>(
195 d: D,
196) -> Result<Option<T>, D::Error> {
197 Option::deserialize(d)
198}
199
200#[derive(Clone, Debug, PartialEq)]
202pub struct Verified {
203 pub id: String,
205 pub cert: Certificate,
206 pub expires_at: DateTime<Utc>,
207}
208
209impl Verified {
210 pub fn threshold_for(&self, segment: Option<&str>) -> f64 {
212 segment
213 .and_then(|v| {
214 self.cert
215 .segments
216 .iter()
217 .find(|s| !s.inherited && s.value == v)
218 })
219 .map_or(self.cert.abstain_below, |s| s.abstain_below)
220 }
221
222 pub fn is_expired(&self, now: DateTime<Utc>) -> bool {
223 now >= self.expires_at
224 }
225
226 pub fn confidence_bins(&self) -> Option<&[f64]> {
228 self.cert.confidence_bins.as_deref()
229 }
230
231 pub fn histogram_for(&self, segment: Option<&str>) -> Option<&Histogram> {
235 let own = segment.and_then(|v| {
236 self.cert
237 .segments
238 .iter()
239 .find(|s| !s.inherited && s.value == v)
240 });
241 match own {
242 Some(s) => s.confidence_histogram.as_ref()?.as_ref(),
243 None => self.cert.confidence_histogram.as_ref()?.as_ref(),
244 }
245 }
246
247 pub fn probabilities(&self, scores: &[f64]) -> Option<Vec<f64>> {
253 let defined =
254 self.cert.calibration_map.kind == "temperature" || self.cert.spec == SPEC_V1_2;
255 (defined && scores.len() == self.cert.options.len())
256 .then(|| probabilities(&self.cert.calibration_map, scores))
257 .flatten()
258 }
259
260 pub fn confidence(&self, scores: &[f64]) -> Option<f64> {
263 self.probabilities(scores)
264 .map(|p| p.into_iter().fold(f64::NEG_INFINITY, f64::max))
265 }
266
267 pub fn temperature(&self) -> Option<f64> {
269 (self.cert.calibration_map.kind == "temperature")
270 .then(|| self.cert.calibration_map.params.get("temperature").copied())
271 .flatten()
272 }
273}
274
275pub fn canonical(v: &serde_json::Value) -> Result<Vec<u8>, CertError> {
277 serde_jcs::to_vec(v).map_err(|e| CertError::Invalid(format!("not canonicalisable: {e}")))
278}
279
280pub fn certificate_id(v: &serde_json::Value) -> Result<String, CertError> {
281 Ok(format!("sha256:{}", hex(&Sha256::digest(canonical(v)?))))
282}
283
284pub fn key_id(key: &VerifyingKey) -> String {
286 format!("ed25519:{}", &hex(&Sha256::digest(key.as_bytes()))[..16])
287}
288
289pub fn verify(
291 v: &serde_json::Value,
292 keys: &BTreeMap<String, String>,
293) -> Result<Verified, CertError> {
294 let obj = v
295 .as_object()
296 .ok_or_else(|| CertError::Invalid("not a JSON object".into()))?;
297 let cert: Certificate =
298 serde_json::from_value(v.clone()).map_err(|e| CertError::Invalid(e.to_string()))?;
299 check(&cert)?;
300
301 let raw = keys
302 .get(&cert.signer_key_id)
303 .ok_or_else(|| CertError::UntrustedKey(cert.signer_key_id.clone()))?;
304 let key = URL_SAFE_NO_PAD
305 .decode(raw)
306 .ok()
307 .and_then(|b| <[u8; 32]>::try_from(b).ok())
308 .and_then(|b| VerifyingKey::from_bytes(&b).ok())
309 .filter(|k| key_id(k) == cert.signer_key_id)
310 .ok_or_else(|| CertError::BadKey(cert.signer_key_id.clone()))?;
311 let sig = URL_SAFE_NO_PAD
312 .decode(&cert.signature)
313 .ok()
314 .and_then(|b| Signature::from_slice(&b).ok())
315 .ok_or(CertError::BadSignature)?;
316 let mut body = obj.clone();
317 body.remove("signature");
318 key.verify_strict(&canonical(&serde_json::Value::Object(body))?, &sig)
319 .map_err(|_| CertError::BadSignature)?;
320
321 Ok(Verified {
322 id: certificate_id(v)?,
323 expires_at: timestamp(&cert.expires_at)?,
324 cert,
325 })
326}
327
328fn check(c: &Certificate) -> Result<(), CertError> {
333 let bad = |m: &str| Err(CertError::Invalid(m.to_string()));
334 let unit = |x: f64| (0.0..=1.0).contains(&x);
335 let open = |x: f64| x > 0.0 && x < 1.0;
336 let threshold = |x: f64| (0.0..=ABSTAIN_ALL).contains(&x);
337 if !SPECS.contains(&c.spec.as_str()) {
338 return bad("spec is not decision-certificate.v1, decision-certificate.v1.1 or decision-certificate.v1.2");
339 }
340 fields_for_spec(c)?;
341 let mut seen = std::collections::BTreeSet::new();
342 if c.options.len() < 2 || !c.options.iter().all(|o| !o.is_empty() && seen.insert(o)) {
343 return bad("options needs at least 2 distinct non-empty ids");
344 }
345 if [
346 &c.domain,
347 &c.decision,
348 &c.calibration_map.kind,
349 &c.issuer.tool,
350 &c.issuer.version,
351 ]
352 .iter()
353 .any(|s| s.is_empty())
354 {
355 return bad("domain, decision, calibration_map.kind and issuer must be non-empty");
356 }
357 match (c.method.as_str(), c.risk.as_str(), c.delta, c.ucb) {
358 ("ltt", "selective_error", Some(d), _) if open(d) => {}
359 ("crc", "joint_error", None, None) => {}
360 _ => return bad("method, risk, delta and ucb disagree"),
361 }
362 if !open(c.alpha) || !threshold(c.abstain_below) || !unit(c.coverage) {
363 return bad("alpha, abstain_below or coverage out of range");
364 }
365 if c.ucb.is_some_and(|u| !unit(u)) || !band_ok(&c.realized_band) {
366 return bad("ucb or realized_band out of range");
367 }
368 for s in &c.segments {
369 if s.field.is_empty()
370 || !threshold(s.abstain_below)
371 || !unit(s.coverage)
372 || s.ucb.is_some_and(|u| !unit(u))
373 || s.realized_band.as_ref().is_some_and(|b| !band_ok(b))
374 {
375 return bad("a segment is out of range");
376 }
377 }
378 if !matches!(
379 (c.split.method.as_str(), c.split.seed),
380 ("time", None) | ("seeded", Some(_))
381 ) {
382 return bad("split.method and split.seed disagree");
383 }
384 if c.rule.unscored != "abstain" || c.rule.cannot_tell_above.is_some_and(|x| !unit(x)) {
385 return bad("rule out of range");
386 }
387 if !matches!(c.audit.mode.as_str(), "sample" | "full-label")
388 || !(c.audit.rate > 0.0 && c.audit.rate <= 1.0)
389 {
390 return bad("audit out of range");
391 }
392 if !model_id_ok(&c.model_id) {
393 return bad("model_id must be <backend>/<model>@<version>");
394 }
395 if !sha256_ok(&c.data_hash) || c.manifest_hash.as_deref().is_some_and(|h| !sha256_ok(h)) {
396 return bad("data_hash and manifest_hash must be sha256:<64 hex>");
397 }
398 let key_hex = c.signer_key_id.strip_prefix("ed25519:");
399 if !key_hex.is_some_and(|h| h.len() == 16 && lower_hex(h)) {
400 return bad("signer_key_id must be ed25519:<16 hex>");
401 }
402 if c.signature.len() != 86
403 || !c
404 .signature
405 .bytes()
406 .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
407 {
408 return bad("signature must be 86 base64url characters");
409 }
410 timestamp(&c.fitted_at)?;
411 timestamp(&c.expires_at)?;
412 if let Some(w) = &c.window {
413 timestamp(&w.start)?;
414 timestamp(&w.end)?;
415 }
416 if c.spec == SPEC_V1_2 {
417 histograms(c)?;
418 map::check(&c.calibration_map, c.options.len())?;
419 }
420 Ok(())
421}
422
423fn fields_for_spec(c: &Certificate) -> Result<(), CertError> {
427 let v12 = c.spec == SPEC_V1_2;
428 let mut present = vec![
429 ("confidence_bins", c.confidence_bins.is_some()),
430 ("confidence_histogram", c.confidence_histogram.is_some()),
431 ];
432 present.extend(c.segments.iter().map(|s| {
433 (
434 "segments[].confidence_histogram",
435 s.confidence_histogram.is_some(),
436 )
437 }));
438 for (name, here) in present {
439 if v12 && !here {
440 return Err(CertError::Invalid(format!(
441 "spec is not consistent with the fields: {SPEC_V1_2} requires `{name}`"
442 )));
443 }
444 if !v12 && here {
445 return Err(CertError::Invalid(format!(
446 "unknown field `{name}` in a {} certificate",
447 c.spec
448 )));
449 }
450 }
451 Ok(())
452}
453
454fn histograms(c: &Certificate) -> Result<(), CertError> {
457 let bins = c.confidence_bins.as_deref().unwrap_or_default();
458 let rising = bins.windows(2).all(|w| w[0] < w[1]);
459 if !(2..=MAX_BINS + 1).contains(&bins.len())
460 || bins[0] != 0.0
461 || bins[bins.len() - 1] != 1.0
462 || !rising
463 {
464 return Err(CertError::Invalid(format!(
465 "confidence_bins must rise strictly from 0 to 1, with 1 to {MAX_BINS} bins"
466 )));
467 }
468 let tests = std::iter::once((&c.confidence_histogram, c.n))
469 .chain(c.segments.iter().map(|s| (&s.confidence_histogram, s.n)));
470 for (h, n) in tests {
471 if let Some(Some(h)) = h {
472 let total: u128 =
473 h.counts.iter().map(|&x| u128::from(x)).sum::<u128>() + u128::from(h.unscored);
474 if h.counts.len() != bins.len() - 1 || total != u128::from(n) {
475 return Err(CertError::Invalid(
476 "a confidence_histogram needs one count per bin, and its counts and unscored must sum to n".into(),
477 ));
478 }
479 }
480 }
481 Ok(())
482}
483
484fn model_id_ok(m: &str) -> bool {
486 if m.chars()
488 .any(|c| matches!(c, '\n' | '\r' | '\u{2028}' | '\u{2029}'))
489 {
490 return false;
491 }
492 let Some((backend, rest)) = m.split_once('/') else {
493 return false;
494 };
495 let at = rest
496 .char_indices()
497 .skip(1)
498 .any(|(i, ch)| ch == '@' && i + 1 < rest.len());
499 !backend.is_empty() && at && !m.ends_with("@?")
500}
501
502fn sha256_ok(h: &str) -> bool {
503 h.strip_prefix("sha256:")
504 .is_some_and(|x| x.len() == 64 && lower_hex(x))
505}
506
507fn lower_hex(s: &str) -> bool {
508 s.bytes()
509 .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
510}
511
512fn band_ok(b: &Band) -> bool {
513 b.level > 0.0 && b.level < 1.0 && (0.0..=1.0).contains(&b.low) && (0.0..=1.0).contains(&b.high)
514}
515
516pub fn timestamp(s: &str) -> Result<DateTime<Utc>, CertError> {
518 let b = s.as_bytes();
520 let ok = b.len() == 20
521 && b.iter().enumerate().all(|(i, &c)| match i {
522 4 | 7 => c == b'-',
523 10 => c == b'T',
524 13 | 16 => c == b':',
525 19 => c == b'Z',
526 _ => c.is_ascii_digit(),
527 });
528 DateTime::parse_from_rfc3339(s)
529 .ok()
530 .filter(|_| ok)
531 .map(|t| t.with_timezone(&Utc))
532 .ok_or_else(|| CertError::Invalid(format!("timestamp {s:?} is not YYYY-MM-DDTHH:MM:SSZ")))
533}
534
535fn hex(b: &[u8]) -> String {
536 b.iter().map(|x| format!("{x:02x}")).collect()
537}
538
539#[cfg(test)]
540mod tests {
541 use super::*;
542
543 fn valid() -> serde_json::Value {
544 let f: serde_json::Value =
545 serde_json::from_str(include_str!("../../fixtures/valid_segments_unicode.json"))
546 .unwrap();
547 f["certificate"].clone()
548 }
549
550 #[test]
553 fn dr_maps_are_applied_in_v1_2_certificates_only() {
554 let mut cert: Certificate = serde_json::from_value(valid()).unwrap();
555 cert.calibration_map = CalibrationMap {
556 kind: "dr".into(),
557 params: [("a", 1.0), ("b0", 0.0), ("b1", 0.0)]
558 .iter()
559 .map(|(k, v)| (k.to_string(), *v))
560 .collect(),
561 label_budget: None,
562 };
563 let v = Verified {
564 id: String::new(),
565 cert,
566 expires_at: Utc::now(),
567 };
568 assert!(v.probabilities(&[1.0, 0.0]).is_none() && v.confidence(&[1.0, 0.0]).is_none());
569 let mut v12 = v.clone();
570 v12.cert.spec = SPEC_V1_2.into();
571 assert!(v12.confidence(&[1.0, 0.0]).unwrap() > 0.73);
572 }
573
574 #[test]
575 fn check_rejects_what_the_schema_rejects() {
576 let typed =
577 |v: &serde_json::Value| serde_json::from_value::<Certificate>(v.clone()).unwrap();
578 assert!(check(&typed(&valid())).is_ok());
579 let edits: [(&str, serde_json::Value); 15] = [
580 ("data_hash", serde_json::json!("sha256:XYZ")),
581 ("manifest_hash", serde_json::json!("md5:00")),
582 ("signer_key_id", serde_json::json!("ed25519:short")),
583 ("model_id", serde_json::json!("/x@y")),
584 ("model_id", serde_json::json!("b/m@?")),
585 (
586 "window",
587 serde_json::json!({"start": "2023-01-02", "end": "2023-12-29T23:59:59Z"}),
588 ),
589 ("expires_at", serde_json::json!("2027-01-23T12:00:00+00:00")),
590 ("expires_at", serde_json::json!("2027-01-23 12:00:00Z")),
591 ("fitted_at", serde_json::json!("2026-10-25t12:00:00Z")),
592 ("domain", serde_json::json!("")),
593 ("options", serde_json::json!(["yes", "yes"])),
594 ("split", serde_json::json!({"method": "time", "seed": 3})),
595 ("alpha", serde_json::json!(1.0)),
596 ("signature", serde_json::json!("abc")),
597 ("model_id", serde_json::json!("a/b\n@c")),
598 ];
599 for (field, value) in edits {
600 let mut v = valid();
601 v[field] = value.clone();
602 assert!(check(&typed(&v)).is_err(), "{field} = {value}");
603 }
604 }
605
606 #[test]
607 fn nested_nullable_fields_must_be_present() {
608 let paths: [(&str, &str); 5] = [
609 ("segments", "ucb"),
610 ("segments", "realized_band"),
611 ("split", "seed"),
612 ("calibration_map", "label_budget"),
613 ("rule", "cannot_tell_above"),
614 ];
615 for (outer, inner) in paths {
616 let mut v = valid();
617 let o = if outer == "segments" {
618 &mut v[outer][0]
619 } else {
620 &mut v[outer]
621 };
622 o.as_object_mut().unwrap().remove(inner);
623 let e = serde_json::from_value::<Certificate>(v).err();
624 assert!(
625 e.is_some_and(|e| e.to_string().contains(inner)),
626 "{outer}.{inner}"
627 );
628 }
629 }
630
631 #[test]
634 fn small_order_keys_are_weak() {
635 let table = [
636 "0100000000000000000000000000000000000000000000000000000000000000",
637 "ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f",
638 "0000000000000000000000000000000000000000000000000000000000000000",
639 "0000000000000000000000000000000000000000000000000000000000000080",
640 "26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05",
641 "26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85",
642 "c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a",
643 "c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa",
644 "0100000000000000000000000000000000000000000000000000000000000080",
645 "ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
646 "edffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f",
647 "edffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
648 "eeffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f",
649 "eeffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
650 ];
651 for h in table {
652 let b: [u8; 32] = (0..32)
653 .map(|i| u8::from_str_radix(&h[2 * i..2 * i + 2], 16).unwrap())
654 .collect::<Vec<_>>()
655 .try_into()
656 .unwrap();
657 let k = VerifyingKey::from_bytes(&b).unwrap_or_else(|e| panic!("{h}: {e}"));
658 assert!(k.is_weak(), "{h}");
659 }
660 }
661
662 #[test]
663 fn certified_segments_set_the_threshold_and_inherited_ones_do_not() {
664 let cert: Certificate = serde_json::from_value(valid()).unwrap();
665 let v = Verified {
666 id: String::new(),
667 expires_at: timestamp(&cert.expires_at).unwrap(),
668 cert,
669 };
670 assert_eq!(v.threshold_for(Some("east")), 0.9);
671 assert_eq!(
672 v.threshold_for(Some("z\u{fc}rich \u{2603}")),
673 v.cert.abstain_below
674 );
675 assert_eq!(v.threshold_for(None), v.cert.abstain_below);
676 assert!(
677 v.is_expired(v.expires_at)
678 && !v.is_expired(v.expires_at - chrono::Duration::seconds(1))
679 );
680 }
681}