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