1pub 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};
50pub 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
62pub const SPEC: &str = "decision-certificate.v1";
64pub const SPEC_V1_1: &str = "decision-certificate.v1.1";
66pub const SPEC_V1_2: &str = "decision-certificate.v1.2";
68pub const SPEC_V1_3: &str = "decision-certificate.v1.3";
71pub const SPEC_V1_4: &str = "decision-certificate.v1.4";
73pub const SPEC_V1_5: &str = "decision-certificate.v1.5";
76pub const SPEC_V1_6: &str = "decision-certificate.v1.6";
79pub const SPEC_V1_7: &str = "decision-certificate.v1.7";
82pub 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];
87pub const CONTEXT_V1_5: &str = "decision-cert/certificate.v1.5";
89pub const CONTEXT_V1_6: &str = "decision-cert/certificate.v1.6";
91pub const CONTEXT_V1_7: &str = "decision-cert/certificate.v1.7";
93pub const MAX_TENANT: usize = 128;
95pub const MAX_BINS: usize = 100;
97pub 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 #[error("certificate is for tenant {0}, not the expected tenant")]
112 WrongTenant(String),
113 #[error("trusted key {0} may not sign in this mode")]
116 KeyMode(String),
117 #[error("certificate is for flow {0}, not the expected flow")]
119 WrongFlow(String),
120 #[error("certificate is for environment {0}, not the expected environment")]
122 WrongEnv(String),
123 #[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#[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#[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 #[serde(default, deserialize_with = "present")]
159 pub loss_sum: Option<Option<u64>>,
160 #[serde(default, deserialize_with = "present")]
163 pub realized_cost: Option<Option<f64>>,
164}
165
166#[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 #[serde(default, deserialize_with = "present")]
192 pub confidence_histogram: Option<Option<Histogram>>,
193 #[serde(default, deserialize_with = "present")]
195 pub automated: Option<Automated>,
196 #[serde(default, deserialize_with = "present")]
198 pub loss_sum: Option<Option<u64>>,
199 #[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#[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#[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 #[serde(default, deserialize_with = "present")]
302 pub confidence_bins: Option<Vec<f64>>,
303 #[serde(default, deserialize_with = "present")]
305 pub confidence_histogram: Option<Option<Histogram>>,
306 #[serde(default, deserialize_with = "present")]
309 pub automate_options: Option<Vec<String>>,
310 #[serde(default, deserialize_with = "present")]
312 pub automated: Option<Automated>,
313 #[serde(default, deserialize_with = "present")]
316 pub cost: Option<Option<Cost>>,
317 #[serde(default, deserialize_with = "present")]
319 pub pvalue: Option<Option<String>>,
320 #[serde(default, deserialize_with = "present")]
322 pub loss_sum: Option<Option<u64>>,
323 #[serde(default, deserialize_with = "present")]
325 pub realized_cost: Option<Option<f64>>,
326 #[serde(default, deserialize_with = "present")]
328 pub tenant: Option<String>,
329 #[serde(default, deserialize_with = "present")]
331 pub signer: Option<Signer>,
332 #[serde(default, deserialize_with = "present")]
335 pub sequential: Option<Sequential>,
336 #[serde(skip)]
339 pub attempt_role: Option<AttemptRole>,
340}
341
342fn 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
350fn 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#[derive(Clone, Debug, PartialEq)]
360pub struct Verified {
361 pub id: String,
363 pub cert: Certificate,
364 pub expires_at: UtcDateTime,
365}
366
367impl Verified {
368 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 pub fn is_expired(&self, now: UtcDateTime) -> bool {
382 now >= self.expires_at
383 }
384
385 pub fn confidence_bins(&self) -> Option<&[f64]> {
387 self.cert.confidence_bins.as_deref()
388 }
389
390 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 pub fn automate_options(&self) -> Option<&[String]> {
409 self.cert.automate_options.as_deref()
410 }
411
412 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 pub fn cost(&self) -> Option<&Cost> {
431 self.cert.cost.as_ref().and_then(|c| c.as_ref())
432 }
433
434 pub fn sequential(&self) -> Option<&Sequential> {
437 self.cert.sequential.as_ref()
438 }
439
440 pub fn attempt_role(&self) -> Option<&AttemptRole> {
443 self.cert.attempt_role.as_ref()
444 }
445
446 pub fn tenant(&self) -> Option<&str> {
449 self.cert.tenant.as_deref()
450 }
451
452 pub fn signer(&self) -> Option<&Signer> {
454 self.cert.signer.as_ref()
455 }
456
457 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 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 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
490pub 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
499pub fn key_id(key: &VerifyingKey) -> String {
501 format!("ed25519:{}", &hex(&Sha256::digest(key.as_bytes()))[..16])
502}
503
504pub 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#[derive(Clone, Debug, PartialEq, Eq)]
536pub enum KeyMode {
537 Operator,
538 Hosted { host: String },
539}
540
541#[derive(Clone, Debug, PartialEq, Eq)]
544pub struct TrustedKey {
545 pub key: String,
546 pub mode: KeyMode,
547}
548
549pub type TenantKeys = BTreeMap<String, TrustedKey>;
551
552pub 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
596pub 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
634const V1_6_ONLY_SEQUENTIAL: &str =
636 "a v1.6 certificate is verified with its expected tenant, flow and environment (verify_sequential)";
637
638const V1_7_ONLY_ATTEMPT: &str =
640 "a v1.7 certificate is verified with its expected tenant, flow and environment (verify_attempt)";
641
642fn 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
653pub 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 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
699pub 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 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#[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 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
878fn 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 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 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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
923pub struct Expiry {
924 pub now: UtcDateTime,
926 pub expires_at: UtcDateTime,
928 pub expired: bool,
930}
931
932#[derive(Debug)]
935pub struct DocumentVerdict {
936 pub certificate_id: Option<String>,
939 pub verification: Result<Verified, CertError>,
942 pub expiry: Option<Expiry>,
944}
945
946pub 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
960pub 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
973pub 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
986pub 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
1018fn 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 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
1049fn 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
1060fn 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
1067fn 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
1093fn 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
1100fn key_id_form(s: &str) -> bool {
1102 s.strip_prefix("ed25519:")
1103 .is_some_and(|h| h.len() == 16 && lower_hex(h))
1104}
1105
1106fn 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 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
1237fn 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 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
1306fn 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
1336fn 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, ))
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 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 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
1411pub const MAX_C: u64 = 1_000_000;
1419const 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 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 let answered = (coverage * n as f64 + 0.5).floor();
1502 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
1523fn model_id_ok(m: &str) -> bool {
1525 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
1555pub 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 #[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 #[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 "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 "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 #[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 #[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}