pub mod challenger;
pub mod inclusion;
mod map;
mod monitor;
pub mod sequential;
pub use challenger::AttemptRole;
pub use map::{confidence, probabilities, MAP_KINDS};
pub use monitor::{bin_of, chi2_sf, shift_score, ShiftScore};
pub use sequential::{explore_bucket, salt_commitment, tail_trips, Sequential};
pub use time::UtcDateTime;
use std::collections::BTreeMap;
use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};
use ed25519_dalek::{Signature, VerifyingKey};
use serde::Deserialize;
use sha2::{Digest, Sha256};
use time::{Date, Month, Time};
pub const SPEC: &str = "decision-certificate.v1";
pub const SPEC_V1_1: &str = "decision-certificate.v1.1";
pub const SPEC_V1_2: &str = "decision-certificate.v1.2";
pub const SPEC_V1_3: &str = "decision-certificate.v1.3";
pub const SPEC_V1_4: &str = "decision-certificate.v1.4";
pub const SPEC_V1_5: &str = "decision-certificate.v1.5";
pub const SPEC_V1_6: &str = "decision-certificate.v1.6";
pub const SPEC_V1_7: &str = "decision-certificate.v1.7";
pub const SPECS: [&str; 8] = [
SPEC, SPEC_V1_1, SPEC_V1_2, SPEC_V1_3, SPEC_V1_4, SPEC_V1_5, SPEC_V1_6, SPEC_V1_7,
];
pub const CONTEXT_V1_5: &str = "decision-cert/certificate.v1.5";
pub const CONTEXT_V1_6: &str = "decision-cert/certificate.v1.6";
pub const CONTEXT_V1_7: &str = "decision-cert/certificate.v1.7";
pub const MAX_TENANT: usize = 128;
pub const MAX_BINS: usize = 100;
pub const ABSTAIN_ALL: f64 = 1.01;
#[derive(Debug, thiserror::Error)]
pub enum CertError {
#[error("certificate is not a valid decision certificate: {0}")]
Invalid(String),
#[error("certificate signed by {0}, which is not a trusted key")]
UntrustedKey(String),
#[error("trusted key {0} is malformed or does not hash to its id")]
BadKey(String),
#[error("certificate signature does not verify")]
BadSignature,
#[error("certificate is for tenant {0}, not the expected tenant")]
WrongTenant(String),
#[error("trusted key {0} may not sign in this mode")]
KeyMode(String),
#[error("certificate is for flow {0}, not the expected flow")]
WrongFlow(String),
#[error("certificate is for environment {0}, not the expected environment")]
WrongEnv(String),
#[error("challenger is not promotable: {0}")]
NotPromotable(String),
}
#[derive(Deserialize, Clone, Debug, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct Band {
pub level: f64,
pub low: f64,
pub high: f64,
}
#[derive(Deserialize, Clone, Debug, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct Histogram {
pub counts: Vec<u64>,
pub unscored: u64,
}
#[derive(Deserialize, Clone, Debug, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct Automated {
pub coverage: f64,
#[serde(deserialize_with = "nullable")]
pub ucb: Option<f64>,
#[serde(deserialize_with = "nullable")]
pub realized_band: Option<Band>,
#[serde(default, deserialize_with = "present")]
pub loss_sum: Option<Option<u64>>,
#[serde(default, deserialize_with = "present")]
pub realized_cost: Option<Option<f64>>,
}
#[derive(Deserialize, Clone, Debug, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct Cost {
pub matrix: Vec<Vec<u64>>,
pub c_max: u64,
#[serde(deserialize_with = "nullable")]
pub unit: Option<String>,
}
#[derive(Deserialize, Clone, Debug, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct Segment {
pub field: String,
pub value: String,
pub n: u64,
pub abstain_below: f64,
pub coverage: f64,
#[serde(deserialize_with = "nullable")]
pub ucb: Option<f64>,
#[serde(deserialize_with = "nullable")]
pub realized_band: Option<Band>,
pub inherited: bool,
#[serde(default, deserialize_with = "present")]
pub confidence_histogram: Option<Option<Histogram>>,
#[serde(default, deserialize_with = "present")]
pub automated: Option<Automated>,
#[serde(default, deserialize_with = "present")]
pub loss_sum: Option<Option<u64>>,
#[serde(default, deserialize_with = "present")]
pub realized_cost: Option<Option<f64>>,
}
#[derive(Deserialize, Clone, Debug, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct Split {
pub method: String,
#[serde(deserialize_with = "nullable")]
pub seed: Option<i64>,
}
#[derive(Deserialize, Clone, Debug, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct CalibrationMap {
pub kind: String,
pub params: BTreeMap<String, f64>,
#[serde(deserialize_with = "nullable")]
pub label_budget: Option<u64>,
}
#[derive(Deserialize, Clone, Debug, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct Rule {
#[serde(deserialize_with = "nullable")]
pub cannot_tell_above: Option<f64>,
pub unscored: String,
}
#[derive(Deserialize, Clone, Debug, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct Window {
pub start: String,
pub end: String,
}
#[derive(Deserialize, Clone, Debug, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct Audit {
pub mode: String,
pub rate: f64,
pub n: u64,
pub propensity_logged: bool,
}
#[derive(Deserialize, Clone, Debug, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct Issuer {
pub tool: String,
pub version: String,
}
#[derive(Deserialize, Clone, Debug, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct Signer {
pub mode: String,
#[serde(default, deserialize_with = "present")]
pub host: Option<String>,
}
#[derive(Deserialize, Clone, Debug, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct Certificate {
pub spec: String,
pub domain: String,
pub decision: String,
pub options: Vec<String>,
pub model_id: String,
#[serde(deserialize_with = "nullable")]
pub manifest_hash: Option<String>,
pub data_hash: String,
pub n_cal: u64,
pub n_temperature: u64,
pub split: Split,
pub calibration_map: CalibrationMap,
pub rule: Rule,
pub alpha: f64,
#[serde(deserialize_with = "nullable")]
pub delta: Option<f64>,
pub method: String,
pub risk: String,
pub n: u64,
pub abstain_below: f64,
pub coverage: f64,
#[serde(deserialize_with = "nullable")]
pub ucb: Option<f64>,
pub realized_band: Band,
pub segments: Vec<Segment>,
#[serde(deserialize_with = "nullable")]
pub window: Option<Window>,
pub fitted_at: String,
pub expires_at: String,
pub audit: Audit,
pub issuer: Issuer,
pub signer_key_id: String,
pub signature: String,
#[serde(default, deserialize_with = "present")]
pub confidence_bins: Option<Vec<f64>>,
#[serde(default, deserialize_with = "present")]
pub confidence_histogram: Option<Option<Histogram>>,
#[serde(default, deserialize_with = "present")]
pub automate_options: Option<Vec<String>>,
#[serde(default, deserialize_with = "present")]
pub automated: Option<Automated>,
#[serde(default, deserialize_with = "present")]
pub cost: Option<Option<Cost>>,
#[serde(default, deserialize_with = "present")]
pub pvalue: Option<Option<String>>,
#[serde(default, deserialize_with = "present")]
pub loss_sum: Option<Option<u64>>,
#[serde(default, deserialize_with = "present")]
pub realized_cost: Option<Option<f64>>,
#[serde(default, deserialize_with = "present")]
pub tenant: Option<String>,
#[serde(default, deserialize_with = "present")]
pub signer: Option<Signer>,
#[serde(default, deserialize_with = "present")]
pub sequential: Option<Sequential>,
#[serde(skip)]
pub attempt_role: Option<AttemptRole>,
}
fn present<'de, D: serde::Deserializer<'de>, T: Deserialize<'de>>(
d: D,
) -> Result<Option<T>, D::Error> {
T::deserialize(d).map(Some)
}
fn nullable<'de, D: serde::Deserializer<'de>, T: Deserialize<'de>>(
d: D,
) -> Result<Option<T>, D::Error> {
Option::deserialize(d)
}
#[derive(Clone, Debug, PartialEq)]
pub struct Verified {
pub id: String,
pub cert: Certificate,
pub expires_at: UtcDateTime,
}
impl Verified {
pub fn threshold_for(&self, segment: Option<&str>) -> f64 {
segment
.and_then(|v| {
self.cert
.segments
.iter()
.find(|s| !s.inherited && s.value == v)
})
.map_or(self.cert.abstain_below, |s| s.abstain_below)
}
pub fn is_expired(&self, now: UtcDateTime) -> bool {
now >= self.expires_at
}
pub fn confidence_bins(&self) -> Option<&[f64]> {
self.cert.confidence_bins.as_deref()
}
pub fn histogram_for(&self, segment: Option<&str>) -> Option<&Histogram> {
let own = segment.and_then(|v| {
self.cert
.segments
.iter()
.find(|s| !s.inherited && s.value == v)
});
match own {
Some(s) => s.confidence_histogram.as_ref()?.as_ref(),
None => self.cert.confidence_histogram.as_ref()?.as_ref(),
}
}
pub fn automate_options(&self) -> Option<&[String]> {
self.cert.automate_options.as_deref()
}
pub fn automated_for(&self, segment: Option<&str>) -> Option<&Automated> {
let own = segment.and_then(|v| {
self.cert
.segments
.iter()
.find(|s| !s.inherited && s.value == v)
});
match own {
Some(s) => s.automated.as_ref(),
None => self.cert.automated.as_ref(),
}
}
pub fn cost(&self) -> Option<&Cost> {
self.cert.cost.as_ref().and_then(|c| c.as_ref())
}
pub fn sequential(&self) -> Option<&Sequential> {
self.cert.sequential.as_ref()
}
pub fn attempt_role(&self) -> Option<&AttemptRole> {
self.cert.attempt_role.as_ref()
}
pub fn tenant(&self) -> Option<&str> {
self.cert.tenant.as_deref()
}
pub fn signer(&self) -> Option<&Signer> {
self.cert.signer.as_ref()
}
pub fn probabilities(&self, scores: &[f64]) -> Option<Vec<f64>> {
let defined = self.cert.calibration_map.kind == "temperature"
|| self.cert.spec == SPEC_V1_2
|| self.cert.spec == SPEC_V1_3
|| self.cert.spec == SPEC_V1_4
|| self.cert.spec == SPEC_V1_5
|| self.cert.spec == SPEC_V1_6
|| self.cert.spec == SPEC_V1_7;
(defined && scores.len() == self.cert.options.len())
.then(|| probabilities(&self.cert.calibration_map, scores))
.flatten()
}
pub fn confidence(&self, scores: &[f64]) -> Option<f64> {
self.probabilities(scores)
.map(|p| p.into_iter().fold(f64::NEG_INFINITY, f64::max))
}
pub fn temperature(&self) -> Option<f64> {
(self.cert.calibration_map.kind == "temperature")
.then(|| self.cert.calibration_map.params.get("temperature").copied())
.flatten()
}
}
pub fn canonical(v: &serde_json::Value) -> Result<Vec<u8>, CertError> {
serde_jcs::to_vec(v).map_err(|e| CertError::Invalid(format!("not canonicalisable: {e}")))
}
pub fn certificate_id(v: &serde_json::Value) -> Result<String, CertError> {
Ok(format!("sha256:{}", hex(&Sha256::digest(canonical(v)?))))
}
pub fn key_id(key: &VerifyingKey) -> String {
format!("ed25519:{}", &hex(&Sha256::digest(key.as_bytes()))[..16])
}
pub fn verify(
v: &serde_json::Value,
keys: &BTreeMap<String, String>,
) -> Result<Verified, CertError> {
let (obj, cert) = read(v)?;
if cert.spec == SPEC_V1_5 {
return Err(CertError::Invalid(
"a v1.5 certificate is verified with its expected tenant (verify_for_tenant)".into(),
));
}
if cert.spec == SPEC_V1_6 {
return Err(CertError::Invalid(V1_6_ONLY_SEQUENTIAL.into()));
}
if cert.spec == SPEC_V1_7 {
return Err(CertError::Invalid(V1_7_ONLY_ATTEMPT.into()));
}
let raw = keys
.get(&cert.signer_key_id)
.ok_or_else(|| CertError::UntrustedKey(cert.signer_key_id.clone()))?;
let key = public_key(raw, &cert.signer_key_id)?;
check_signature(&key, &cert, &bare_body(obj)?)?;
verified(v, cert)
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum KeyMode {
Operator,
Hosted { host: String },
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TrustedKey {
pub key: String,
pub mode: KeyMode,
}
pub type TenantKeys = BTreeMap<String, TrustedKey>;
pub fn tenant_keys_from_json(v: &serde_json::Value) -> Result<TenantKeys, CertError> {
let obj = v.as_object().ok_or_else(|| {
CertError::Invalid("trusted keys are not a JSON object of key id -> key entry".into())
})?;
let mut out = TenantKeys::new();
for (kid, entry) in obj {
let bad = || CertError::BadKey(kid.clone());
let trusted = match entry {
serde_json::Value::String(key) => TrustedKey {
key: key.clone(),
mode: KeyMode::Operator,
},
serde_json::Value::Object(e) => {
if e.keys()
.any(|k| !matches!(k.as_str(), "key" | "mode" | "host"))
{
return Err(bad());
}
let key = e.get("key").and_then(|k| k.as_str()).ok_or_else(bad)?;
let host = e.get("host");
let mode = match (e.get("mode").and_then(|m| m.as_str()), host) {
(Some("operator"), None) => KeyMode::Operator,
(Some("hosted"), Some(serde_json::Value::String(h))) if key_id_form(h) => {
KeyMode::Hosted { host: h.clone() }
}
_ => return Err(bad()),
};
TrustedKey {
key: key.to_string(),
mode,
}
}
_ => return Err(bad()),
};
out.insert(kid.clone(), trusted);
}
Ok(out)
}
pub fn verify_for_tenant(
v: &serde_json::Value,
tenant: &str,
keys: &TenantKeys,
) -> Result<Verified, CertError> {
expect_tenant(tenant)?;
let (obj, cert) = read(v)?;
if cert.spec == SPEC_V1_6 {
return Err(CertError::Invalid(V1_6_ONLY_SEQUENTIAL.into()));
}
if cert.spec == SPEC_V1_7 {
return Err(CertError::Invalid(V1_7_ONLY_ATTEMPT.into()));
}
let kid = &cert.signer_key_id;
if cert.spec != SPEC_V1_5 {
let entry = keys
.get(kid)
.ok_or_else(|| CertError::UntrustedKey(kid.clone()))?;
let key = public_key(&entry.key, kid)?;
if entry.mode != KeyMode::Operator {
return Err(CertError::KeyMode(kid.clone()));
}
check_signature(&key, &cert, &bare_body(obj)?)?;
return verified(v, cert);
}
tenant_bound(obj, cert, tenant, keys, CONTEXT_V1_5)
}
const V1_6_ONLY_SEQUENTIAL: &str =
"a v1.6 certificate is verified with its expected tenant, flow and environment (verify_sequential)";
const V1_7_ONLY_ATTEMPT: &str =
"a v1.7 certificate is verified with its expected tenant, flow and environment (verify_attempt)";
fn expect_tenant(tenant: &str) -> Result<(), CertError> {
if tenant_ok(tenant) {
Ok(())
} else {
Err(CertError::Invalid(format!(
"the expected tenant must be 1 to {MAX_TENANT} characters of A-Z a-z 0-9 . _ : -"
)))
}
}
pub fn verify_sequential(
v: &serde_json::Value,
tenant: &str,
keys: &TenantKeys,
flow: &str,
env: &str,
) -> Result<Verified, CertError> {
expect_tenant(tenant)?;
if !tenant_ok(flow) || !tenant_ok(env) {
return Err(CertError::Invalid(format!(
"the expected flow and environment must be 1 to {MAX_TENANT} characters of A-Z a-z 0-9 . _ : -"
)));
}
let (obj, cert) = read(v)?;
if cert.spec != SPEC_V1_6 {
return Err(CertError::Invalid(format!(
"verify_sequential verifies a {SPEC_V1_6} certificate, not {}",
cert.spec
)));
}
let verified = tenant_bound(obj, cert, tenant, keys, CONTEXT_V1_6)?;
let (own_flow, own_env) = verified
.cert
.sequential
.as_ref()
.map(|s| (s.flow.clone(), s.env.clone()))
.unwrap_or_default();
if own_flow != flow {
return Err(CertError::WrongFlow(own_flow));
}
if own_env != env {
return Err(CertError::WrongEnv(own_env));
}
Ok(verified)
}
pub fn verify_attempt(
v: &serde_json::Value,
tenant: &str,
keys: &TenantKeys,
flow: &str,
env: &str,
) -> Result<Verified, CertError> {
expect_tenant(tenant)?;
if !tenant_ok(flow) || !tenant_ok(env) {
return Err(CertError::Invalid(format!(
"the expected flow and environment must be 1 to {MAX_TENANT} characters of A-Z a-z 0-9 . _ : -"
)));
}
let (obj, cert) = read(v)?;
if cert.spec != SPEC_V1_7 {
return Err(CertError::Invalid(format!(
"verify_attempt verifies a {SPEC_V1_7} certificate, not {}",
cert.spec
)));
}
let verified = tenant_bound(obj, cert, tenant, keys, CONTEXT_V1_7)?;
let (own_flow, own_env) = verified
.cert
.sequential
.as_ref()
.map(|s| (s.flow.clone(), s.env.clone()))
.unwrap_or_default();
if own_flow != flow {
return Err(CertError::WrongFlow(own_flow));
}
if own_env != env {
return Err(CertError::WrongEnv(own_env));
}
Ok(verified)
}
#[allow(clippy::too_many_arguments)]
pub fn verify_promotion(
challenger: &serde_json::Value,
champion: &serde_json::Value,
tenant: &str,
keys: &TenantKeys,
flow: &str,
env: &str,
now: UtcDateTime,
) -> Result<Verified, CertError> {
let no = |m: String| Err(CertError::NotPromotable(m));
let ch = verify_attempt(challenger, tenant, keys, flow, env)?;
let Some(cited) = ch
.attempt_role()
.and_then(|r| r.challenger.as_ref())
.cloned()
else {
return no("the certificate is a standalone attempt, not a challenger".into());
};
let champion_spec = champion.get("spec").and_then(|s| s.as_str());
let verified = match champion_spec {
Some(SPEC_V1_6) => verify_sequential(champion, tenant, keys, flow, env),
Some(SPEC_V1_7) => verify_attempt(champion, tenant, keys, flow, env),
_ => Err(CertError::Invalid(
"the champion's spec is not decision-certificate.v1.6 or decision-certificate.v1.7"
.into(),
)),
};
let cv = match verified {
Ok(x) => x,
Err(e) => return no(format!("the champion does not verify: {e}")),
};
let (a, b) = (&ch.cert, &cv.cert);
let (Some(sa), Some(sb)) = (&a.sequential, &b.sequential) else {
return no("a sequential certificate needs sequential".into());
};
let cp = &cited.champion;
let experiment = sb
.preregistration
.exploration
.as_ref()
.map(|e| &e.experiment_id);
let own = [
(
"certificate_id",
certificate_id(champion)? == cp.certificate_id,
),
("spec", b.spec == cp.spec),
("attempt", sb.attempt == cp.attempt),
(
"preregistration_digest",
sb.preregistration.digest == cp.preregistration_digest,
),
("experiment_id", experiment == cp.experiment_id.as_ref()),
("model_id", b.model_id == cp.model_id),
("manifest_hash", b.manifest_hash == cp.manifest_hash),
("expires_at", b.expires_at == cp.expires_at),
];
if let Some((field, _)) = own.iter().find(|(_, same)| !same) {
return no(format!(
"the champion is not the certificate the challenger cites: its {field} differs"
));
}
if a.domain != b.domain || a.decision != b.decision || a.options != b.options {
return no("the champion and the challenger differ in domain, decision or options".into());
}
if timestamp(&b.fitted_at)? > timestamp(&sa.preregistration.sealed_at)? {
return no(
"the challenger was pre-registered before its champion was issued (fitted_at)".into(),
);
}
for (name, differs) in challenger::differences((a, challenger), (b, champion))? {
if differs != cited.changes.iter().any(|x| x == name) {
return no(format!(
"changes must list {name} exactly when the two certificates differ in it"
));
}
}
let same_config = sa.preregistration.config_digest == sb.preregistration.config_digest;
if cited.changes.is_empty() && !same_config {
return no("a renewal (no changes) pre-registers its champion's config_digest".into());
}
if cited.changes.iter().any(|x| x == "configuration") && same_config {
return no("changes lists configuration, but the config_digest is the champion's".into());
}
if a.alpha > b.alpha {
return no("a promotion never raises alpha".into());
}
let (Some(ab), bb) = (
ch.attempt_role().map(|r| &r.budget),
b.attempt_role.as_ref().map(|r| &r.budget),
) else {
return no("the certificate is a standalone attempt, not a challenger".into());
};
if bb.is_some_and(|bb| ab.window_days != bb.window_days || ab.total_ppm != bb.total_ppm) {
return no("the challenger's window_days and total_ppm differ from its champion's: one account (spec v1.7 §1.5)".into());
}
let (sealed_a, sealed_b) = (
sequential::v16_timestamp(&sa.preregistration.sealed_at)?,
sequential::v16_timestamp(&sb.preregistration.sealed_at)?,
);
let from = sealed_a.checked_sub(time::Duration::days(i64::from(ab.window_days)));
if from.is_none_or(|f| f < sealed_b) && sealed_b <= sealed_a {
let debit = match bb {
Some(bb) => bb.debit_ppm,
None => challenger::debit_ppm(b.delta.unwrap_or(0.0)),
};
if ab.spent_ppm < debit {
return no("the challenger's spent_ppm omits its champion's debit, sealed in its window (spec v1.7 §1.5)".into());
}
}
if now >= cv.expires_at {
return no("the champion has expired".into());
}
if now >= ch.expires_at {
return no("the challenger has expired".into());
}
Ok(ch)
}
fn tenant_bound(
obj: &serde_json::Map<String, serde_json::Value>,
cert: Certificate,
tenant: &str,
keys: &TenantKeys,
context: &str,
) -> Result<Verified, CertError> {
let kid = &cert.signer_key_id;
let (Some(own), Some(signer)) = (&cert.tenant, &cert.signer) else {
return Err(CertError::Invalid(
"a certificate that binds its tenant needs tenant and signer".into(),
));
};
if own != tenant {
return Err(CertError::WrongTenant(own.clone()));
}
let entry = keys
.get(kid)
.ok_or_else(|| CertError::UntrustedKey(kid.clone()))?;
let key = public_key(&entry.key, kid)?;
let allowed = match (&entry.mode, signer.mode.as_str()) {
(KeyMode::Operator, "operator") => true,
(KeyMode::Hosted { host }, "hosted") => signer.host.as_deref() == Some(host.as_str()),
_ => false,
};
if !allowed {
return Err(CertError::KeyMode(kid.clone()));
}
let mut msg = format!("{context}\n{tenant}\n").into_bytes();
let body = bare_body(obj)?;
if context == CONTEXT_V1_6 || context == CONTEXT_V1_7 {
msg.extend(Sha256::digest(&body));
} else {
msg.extend(body);
}
check_signature(&key, &cert, &msg)?;
verified_obj(obj, cert)
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Expiry {
pub now: UtcDateTime,
pub expires_at: UtcDateTime,
pub expired: bool,
}
#[derive(Debug)]
pub struct DocumentVerdict {
pub certificate_id: Option<String>,
pub verification: Result<Verified, CertError>,
pub expiry: Option<Expiry>,
}
pub fn verify_document(
v: &serde_json::Value,
tenant: &str,
keys: &TenantKeys,
now: UtcDateTime,
) -> DocumentVerdict {
document_verdict(v, verify_for_tenant(v, tenant, keys), now)
}
pub fn verify_sequential_document(
v: &serde_json::Value,
tenant: &str,
keys: &TenantKeys,
flow: &str,
env: &str,
now: UtcDateTime,
) -> DocumentVerdict {
document_verdict(v, verify_sequential(v, tenant, keys, flow, env), now)
}
pub fn verify_attempt_document(
v: &serde_json::Value,
tenant: &str,
keys: &TenantKeys,
flow: &str,
env: &str,
now: UtcDateTime,
) -> DocumentVerdict {
document_verdict(v, verify_attempt(v, tenant, keys, flow, env), now)
}
pub fn verify_promotion_document(
challenger: &serde_json::Value,
champion: &serde_json::Value,
tenant: &str,
keys: &TenantKeys,
flow: &str,
env: &str,
now: UtcDateTime,
) -> DocumentVerdict {
let verdict = verify_promotion(challenger, champion, tenant, keys, flow, env, now);
document_verdict(challenger, verdict, now)
}
fn document_verdict(
v: &serde_json::Value,
verification: Result<Verified, CertError>,
now: UtcDateTime,
) -> DocumentVerdict {
let expiry = verification.as_ref().ok().map(|x| Expiry {
now,
expires_at: x.expires_at,
expired: x.is_expired(now),
});
DocumentVerdict {
certificate_id: certificate_id(v).ok(),
verification,
expiry,
}
}
fn read(
v: &serde_json::Value,
) -> Result<(&serde_json::Map<String, serde_json::Value>, Certificate), CertError> {
let obj = v
.as_object()
.ok_or_else(|| CertError::Invalid("not a JSON object".into()))?;
let invalid = |e: serde_json::Error| CertError::Invalid(e.to_string());
let mut body = v.clone();
let mut role = None;
if obj.get("spec").and_then(|s| s.as_str()) == Some(SPEC_V1_7) {
if let Some(seq) = body.get_mut("sequential").and_then(|s| s.as_object_mut()) {
let mut own = serde_json::Map::new();
for k in challenger::FIELDS {
if let Some(x) = seq.remove(k) {
own.insert(k.to_string(), x);
}
}
role = Some(serde_json::Value::Object(own));
}
}
let mut cert: Certificate = serde_json::from_value(body).map_err(invalid)?;
if let Some(r) = role {
cert.attempt_role = Some(serde_json::from_value(r).map_err(invalid)?);
}
check(&cert)?;
Ok((obj, cert))
}
fn public_key(raw: &str, kid: &str) -> Result<VerifyingKey, CertError> {
URL_SAFE_NO_PAD
.decode(raw)
.ok()
.and_then(|b| <[u8; 32]>::try_from(b).ok())
.and_then(|b| VerifyingKey::from_bytes(&b).ok())
.filter(|k| key_id(k) == kid)
.ok_or_else(|| CertError::BadKey(kid.to_string()))
}
fn bare_body(obj: &serde_json::Map<String, serde_json::Value>) -> Result<Vec<u8>, CertError> {
let mut body = obj.clone();
body.remove("signature");
canonical(&serde_json::Value::Object(body))
}
fn check_signature(key: &VerifyingKey, cert: &Certificate, msg: &[u8]) -> Result<(), CertError> {
let sig = URL_SAFE_NO_PAD
.decode(&cert.signature)
.ok()
.and_then(|b| Signature::from_slice(&b).ok())
.ok_or(CertError::BadSignature)?;
key.verify_strict(msg, &sig)
.map_err(|_| CertError::BadSignature)
}
fn verified_obj(
obj: &serde_json::Map<String, serde_json::Value>,
cert: Certificate,
) -> Result<Verified, CertError> {
verified(&serde_json::Value::Object(obj.clone()), cert)
}
fn verified(v: &serde_json::Value, cert: Certificate) -> Result<Verified, CertError> {
Ok(Verified {
id: certificate_id(v)?,
expires_at: timestamp(&cert.expires_at)?,
cert,
})
}
fn tenant_ok(t: &str) -> bool {
(1..=MAX_TENANT).contains(&t.len())
&& t.bytes()
.all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b':' | b'-'))
}
fn key_id_form(s: &str) -> bool {
s.strip_prefix("ed25519:")
.is_some_and(|h| h.len() == 16 && lower_hex(h))
}
fn check(c: &Certificate) -> Result<(), CertError> {
let bad = |m: &str| Err(CertError::Invalid(m.to_string()));
let unit = |x: f64| (0.0..=1.0).contains(&x);
let open = |x: f64| x > 0.0 && x < 1.0;
let threshold = |x: f64| (0.0..=ABSTAIN_ALL).contains(&x);
if !SPECS.contains(&c.spec.as_str()) {
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");
}
fields_for_spec(c)?;
let mut seen = std::collections::BTreeSet::new();
if c.options.len() < 2 || !c.options.iter().all(|o| !o.is_empty() && seen.insert(o)) {
return bad("options needs at least 2 distinct non-empty ids");
}
if [
&c.domain,
&c.decision,
&c.calibration_map.kind,
&c.issuer.tool,
&c.issuer.version,
]
.iter()
.any(|s| s.is_empty())
{
return bad("domain, decision, calibration_map.kind and issuer must be non-empty");
}
let v17 = c.spec == SPEC_V1_7;
let v16 = c.spec == SPEC_V1_6 || v17;
let v15 = c.spec == SPEC_V1_5 || v16;
let v14 = c.spec == SPEC_V1_4 || v15;
match (c.method.as_str(), c.risk.as_str(), c.delta, c.ucb) {
("ltt", "selective_error", Some(d), _) if !v16 && open(d) => {}
("ltt", "selective_cost", Some(d), _) if v14 && !v16 && open(d) => {}
("crc", "joint_error", None, None) if !v16 => {}
("confidence_sequence", "automated_error", Some(d), None) if v16 && open(d) => {}
_ => return bad("method, risk, delta and ucb disagree"),
}
if !open(c.alpha) || !threshold(c.abstain_below) || !unit(c.coverage) {
return bad("alpha, abstain_below or coverage out of range");
}
if c.ucb.is_some_and(|u| !unit(u)) || !band_ok(&c.realized_band) {
return bad("ucb or realized_band out of range");
}
for s in &c.segments {
if s.field.is_empty()
|| !threshold(s.abstain_below)
|| !unit(s.coverage)
|| s.ucb.is_some_and(|u| !unit(u))
|| s.realized_band.as_ref().is_some_and(|b| !band_ok(b))
{
return bad("a segment is out of range");
}
}
if !matches!(
(c.split.method.as_str(), c.split.seed),
("time", None) | ("seeded", Some(_))
) {
return bad("split.method and split.seed disagree");
}
if c.rule.unscored != "abstain" || c.rule.cannot_tell_above.is_some_and(|x| !unit(x)) {
return bad("rule out of range");
}
if !matches!(c.audit.mode.as_str(), "sample" | "full-label")
|| !(c.audit.rate > 0.0 && c.audit.rate <= 1.0)
{
return bad("audit out of range");
}
if !model_id_ok(&c.model_id) {
return bad("model_id must be <backend>/<model>@<version>");
}
if !sha256_ok(&c.data_hash) || c.manifest_hash.as_deref().is_some_and(|h| !sha256_ok(h)) {
return bad("data_hash and manifest_hash must be sha256:<64 hex>");
}
if !key_id_form(&c.signer_key_id) {
return bad("signer_key_id must be ed25519:<16 hex>");
}
if c.signature.len() != 86
|| !c
.signature
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
{
return bad("signature must be 86 base64url characters");
}
timestamp(&c.fitted_at)?;
timestamp(&c.expires_at)?;
if let Some(w) = &c.window {
timestamp(&w.start)?;
timestamp(&w.end)?;
}
if c.spec == SPEC_V1_2 || c.spec == SPEC_V1_3 || v14 {
histograms(c)?;
map::check(&c.calibration_map, c.options.len())?;
}
if c.spec == SPEC_V1_3 || v14 {
automated(c)?;
}
if v14 {
cost(c)?;
}
if v15 {
if !c.tenant.as_deref().is_some_and(tenant_ok) {
return Err(CertError::Invalid(format!(
"tenant must be 1 to {MAX_TENANT} characters of A-Z a-z 0-9 . _ : -"
)));
}
let signer_ok =
c.signer
.as_ref()
.is_some_and(|s| match (s.mode.as_str(), s.host.as_deref()) {
("operator", None) => true,
("hosted", Some(h)) => key_id_form(h),
_ => false,
});
if !signer_ok {
return bad("signer must be {\"mode\": \"operator\"} or {\"mode\": \"hosted\", \"host\": \"ed25519:<16 hex>\"}");
}
}
if v16 {
sequential::check(c)?;
}
if v17 {
challenger::check(c)?;
}
Ok(())
}
fn fields_for_spec(c: &Certificate) -> Result<(), CertError> {
let v16 = c.spec == SPEC_V1_6 || c.spec == SPEC_V1_7;
let v15 = c.spec == SPEC_V1_5 || v16;
let v14 = c.spec == SPEC_V1_4 || v15;
let v13 = c.spec == SPEC_V1_3 || v14;
let v12 = c.spec == SPEC_V1_2 || v13;
let mut present = vec![
("confidence_bins", c.confidence_bins.is_some(), v12),
(
"confidence_histogram",
c.confidence_histogram.is_some(),
v12,
),
("automate_options", c.automate_options.is_some(), v13),
("automated", c.automated.is_some(), v13),
("cost", c.cost.is_some(), v14),
("pvalue", c.pvalue.is_some(), v14),
("loss_sum", c.loss_sum.is_some(), v14),
("realized_cost", c.realized_cost.is_some(), v14),
("tenant", c.tenant.is_some(), v15),
("signer", c.signer.is_some(), v15),
("sequential", c.sequential.is_some(), v16),
];
for s in &c.segments {
present.push((
"segments[].confidence_histogram",
s.confidence_histogram.is_some(),
v12,
));
present.push(("segments[].automated", s.automated.is_some(), v13));
present.push(("segments[].loss_sum", s.loss_sum.is_some(), v14));
present.push(("segments[].realized_cost", s.realized_cost.is_some(), v14));
}
if let Some(a) = &c.automated {
present.push(("automated.loss_sum", a.loss_sum.is_some(), v14));
present.push(("automated.realized_cost", a.realized_cost.is_some(), v14));
}
for s in &c.segments {
if let Some(a) = &s.automated {
present.push(("segments[].automated.loss_sum", a.loss_sum.is_some(), v14));
present.push((
"segments[].automated.realized_cost",
a.realized_cost.is_some(),
v14,
));
}
}
for (name, here, required) in present {
if required && !here {
return Err(CertError::Invalid(format!(
"spec is not consistent with the fields: {} requires `{name}`",
c.spec
)));
}
if !required && here {
return Err(CertError::Invalid(format!(
"unknown field `{name}` in a {} certificate",
c.spec
)));
}
}
Ok(())
}
fn histograms(c: &Certificate) -> Result<(), CertError> {
let bins = c.confidence_bins.as_deref().unwrap_or_default();
let rising = bins.windows(2).all(|w| w[0] < w[1]);
if !(2..=MAX_BINS + 1).contains(&bins.len())
|| bins[0] != 0.0
|| bins[bins.len() - 1] != 1.0
|| !rising
{
return Err(CertError::Invalid(format!(
"confidence_bins must rise strictly from 0 to 1, with 1 to {MAX_BINS} bins"
)));
}
let tests = std::iter::once((&c.confidence_histogram, c.n))
.chain(c.segments.iter().map(|s| (&s.confidence_histogram, s.n)));
for (h, n) in tests {
if let Some(Some(h)) = h {
let total: u128 =
h.counts.iter().map(|&x| u128::from(x)).sum::<u128>() + u128::from(h.unscored);
if h.counts.len() != bins.len() - 1 || total != u128::from(n) {
return Err(CertError::Invalid(
"a confidence_histogram needs one count per bin, and its counts and unscored must sum to n".into(),
));
}
}
}
Ok(())
}
fn automated(c: &Certificate) -> Result<(), CertError> {
let auto = c.automate_options.as_deref().unwrap_or_default();
let mut at = c.options.iter();
if auto.is_empty() || !auto.iter().all(|o| at.any(|x| x == o)) {
return Err(CertError::Invalid(
"automate_options must name one or more of the options, once each and in their order"
.into(),
));
}
let unit = |x: f64| (0.0..=1.0).contains(&x);
let tests = std::iter::once((
&c.automated,
c.coverage,
c.ucb.is_some(),
true, ))
.chain(c.segments.iter().map(|s| {
(
&s.automated,
s.coverage,
s.ucb.is_some(),
s.realized_band.is_some(),
)
}));
for (a, coverage, ucb, band) in tests {
let Some(a) = a else { continue };
if !unit(a.coverage)
|| a.coverage > coverage
|| a.ucb.is_some_and(|u| !unit(u))
|| a.realized_band.as_ref().is_some_and(|b| !band_ok(b))
|| a.ucb.is_some() != ucb
|| a.realized_band.is_some() != band
{
return Err(CertError::Invalid(
"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(),
));
}
}
if auto.len() == c.options.len() {
let same = |a: &Option<Automated>, coverage: f64, ucb: Option<f64>, band: Option<&Band>| {
a.as_ref().is_none_or(|a| {
a.coverage == coverage && a.ucb == ucb && a.realized_band.as_ref() == band
})
};
let same_cost =
|a: &Option<Automated>, ls: Option<Option<u64>>, rc: Option<Option<f64>>| {
a.as_ref()
.is_none_or(|a| a.loss_sum == ls && a.realized_cost == rc)
};
if !same(&c.automated, c.coverage, c.ucb, Some(&c.realized_band))
|| !same_cost(&c.automated, c.loss_sum, c.realized_cost)
|| !c
.segments
.iter()
.all(|s| same(&s.automated, s.coverage, s.ucb, s.realized_band.as_ref()))
|| !c
.segments
.iter()
.all(|s| same_cost(&s.automated, s.loss_sum, s.realized_cost))
{
return Err(CertError::Invalid(
"automated must equal its test's coverage, ucb and realized_band when every option is automated".into(),
));
}
}
Ok(())
}
pub const MAX_C: u64 = 1_000_000;
const SAFE_SCALE: f64 = 9_007_199_254_740_992.0;
fn cost(c: &Certificate) -> Result<(), CertError> {
let bad = |m: &str| Err(CertError::Invalid(m.to_string()));
let cost = c.cost.clone().flatten();
let pvalue = c.pvalue.clone().flatten();
let want = match c.risk.as_str() {
"selective_error" => Some("binomial"),
"selective_cost" => Some("hoeffding_bentkus"),
_ => None,
};
if cost.is_some() != (c.risk == "selective_cost") || pvalue.as_deref() != want {
return bad("cost, pvalue and risk disagree");
}
if let Some(k) = &cost {
let n = c.options.len();
let m = &k.matrix;
let all = || m.iter().flatten().copied();
let ok = m.len() == n
&& m.iter().all(|r| r.len() == n)
&& (0..n).all(|i| m[i][i] == 0)
&& all().all(|x| x <= k.c_max)
&& (1..=MAX_C).contains(&k.c_max)
&& all().max() == Some(k.c_max)
&& k.unit.as_deref() != Some("");
if !ok {
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");
}
let off: Vec<u64> = (0..n)
.flat_map(|i| (0..n).filter(move |&j| j != i).map(move |j| (i, j)))
.map(|(i, j)| m[i][j])
.collect();
if off.iter().all(|&x| x == off[0]) {
return bad("a cost risk needs unequal off-diagonal costs; with equal costs it is selective_error");
}
}
let unit = |x: f64| (0.0..=1.0).contains(&x);
type Row = (Option<f64>, Option<u64>, f64, u64, bool);
let auto = |a: &Option<Automated>, n: u64, own: bool| -> Row {
a.as_ref().map_or((None, None, 0.0, n, own), |a| {
(
a.realized_cost.flatten(),
a.loss_sum.flatten(),
a.coverage,
n,
own,
)
})
};
let mut tests: Vec<Row> = vec![(
c.realized_cost.flatten(),
c.loss_sum.flatten(),
c.coverage,
c.n,
true,
)];
tests.extend(c.segments.iter().map(|s| {
(
s.realized_cost.flatten(),
s.loss_sum.flatten(),
s.coverage,
s.n,
!s.inherited,
)
}));
tests.push(auto(&c.automated, c.n, true));
tests.extend(
c.segments
.iter()
.map(|s| auto(&s.automated, s.n, !s.inherited)),
);
for (rc, ls, coverage, n, own) in tests {
let expect = cost.is_some() && own && coverage > 0.0;
if rc.is_some() != expect || ls.is_some() != expect || rc.is_some_and(|x| !unit(x)) {
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");
}
if let (Some(rc), Some(ls), Some(k)) = (rc, ls, &cost) {
let answered = (coverage * n as f64 + 0.5).floor();
if !(1..=1u64 << 53).contains(&n) || coverage != answered / n as f64 {
return bad(
"coverage must be exactly answered / n, a whole number of answered cases",
);
}
let ok = (1.0..=SAFE_SCALE).contains(&answered) && {
let scale = u128::from(k.c_max) * answered as u128;
scale <= SAFE_SCALE as u128
&& u128::from(ls) <= scale
&& rc == ls as f64 / scale as f64
};
if !ok {
return bad("realized_cost must be loss_sum / (c_max * answered), with loss_sum at most c_max * answered");
}
}
}
Ok(())
}
fn model_id_ok(m: &str) -> bool {
if m.chars()
.any(|c| matches!(c, '\n' | '\r' | '\u{2028}' | '\u{2029}'))
{
return false;
}
let Some((backend, rest)) = m.split_once('/') else {
return false;
};
let at = rest
.char_indices()
.skip(1)
.any(|(i, ch)| ch == '@' && i + 1 < rest.len());
!backend.is_empty() && at && !m.ends_with("@?")
}
fn sha256_ok(h: &str) -> bool {
h.strip_prefix("sha256:")
.is_some_and(|x| x.len() == 64 && lower_hex(x))
}
fn lower_hex(s: &str) -> bool {
s.bytes()
.all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
}
fn band_ok(b: &Band) -> bool {
b.level > 0.0 && b.level < 1.0 && (0.0..=1.0).contains(&b.low) && (0.0..=1.0).contains(&b.high)
}
pub fn timestamp(s: &str) -> Result<UtcDateTime, CertError> {
timestamp_parts(s)
.ok_or_else(|| CertError::Invalid(format!("timestamp {s:?} is not YYYY-MM-DDTHH:MM:SSZ")))
}
fn timestamp_parts(s: &str) -> Option<UtcDateTime> {
let b = s.as_bytes();
let form = b.len() == 20
&& b.iter().enumerate().all(|(i, &c)| match i {
4 | 7 => c == b'-',
10 => c == b'T',
13 | 16 => c == b':',
19 => c == b'Z',
_ => c.is_ascii_digit(),
});
if !form {
return None;
}
let n = |i: usize, len: usize| {
b[i..i + len]
.iter()
.fold(0u16, |acc, &c| acc * 10 + u16::from(c - b'0'))
};
let month = Month::try_from(u8::try_from(n(5, 2)).ok()?).ok()?;
let date = Date::from_calendar_date(i32::from(n(0, 4)), month, u8::try_from(n(8, 2)).ok()?);
let (second, nano) = match n(17, 2) {
60 => (59, 999_999_999),
sec => (u8::try_from(sec).ok()?, 0),
};
let time = Time::from_hms_nano(
u8::try_from(n(11, 2)).ok()?,
u8::try_from(n(14, 2)).ok()?,
second,
nano,
);
Some(UtcDateTime::new(date.ok()?, time.ok()?))
}
fn hex(b: &[u8]) -> String {
b.iter().map(|x| format!("{x:02x}")).collect()
}
#[cfg(test)]
mod tests {
use super::*;
fn valid() -> serde_json::Value {
let f: serde_json::Value =
serde_json::from_str(include_str!("../../fixtures/valid_segments_unicode.json"))
.unwrap();
f["certificate"].clone()
}
#[test]
fn dr_maps_are_applied_in_v1_2_certificates_only() {
let mut cert: Certificate = serde_json::from_value(valid()).unwrap();
cert.calibration_map = CalibrationMap {
kind: "dr".into(),
params: [("a", 1.0), ("b0", 0.0), ("b1", 0.0)]
.iter()
.map(|(k, v)| (k.to_string(), *v))
.collect(),
label_budget: None,
};
let v = Verified {
id: String::new(),
cert,
expires_at: UtcDateTime::now(),
};
assert!(v.probabilities(&[1.0, 0.0]).is_none() && v.confidence(&[1.0, 0.0]).is_none());
let mut v12 = v.clone();
v12.cert.spec = SPEC_V1_2.into();
assert!(v12.confidence(&[1.0, 0.0]).unwrap() > 0.73);
}
#[test]
fn check_rejects_what_the_schema_rejects() {
let typed =
|v: &serde_json::Value| serde_json::from_value::<Certificate>(v.clone()).unwrap();
assert!(check(&typed(&valid())).is_ok());
let edits: [(&str, serde_json::Value); 15] = [
("data_hash", serde_json::json!("sha256:XYZ")),
("manifest_hash", serde_json::json!("md5:00")),
("signer_key_id", serde_json::json!("ed25519:short")),
("model_id", serde_json::json!("/x@y")),
("model_id", serde_json::json!("b/m@?")),
(
"window",
serde_json::json!({"start": "2023-01-02", "end": "2023-12-29T23:59:59Z"}),
),
("expires_at", serde_json::json!("2027-01-23T12:00:00+00:00")),
("expires_at", serde_json::json!("2027-01-23 12:00:00Z")),
("fitted_at", serde_json::json!("2026-10-25t12:00:00Z")),
("domain", serde_json::json!("")),
("options", serde_json::json!(["yes", "yes"])),
("split", serde_json::json!({"method": "time", "seed": 3})),
("alpha", serde_json::json!(1.0)),
("signature", serde_json::json!("abc")),
("model_id", serde_json::json!("a/b\n@c")),
];
for (field, value) in edits {
let mut v = valid();
v[field] = value.clone();
assert!(check(&typed(&v)).is_err(), "{field} = {value}");
}
}
#[test]
fn nested_nullable_fields_must_be_present() {
let paths: [(&str, &str); 5] = [
("segments", "ucb"),
("segments", "realized_band"),
("split", "seed"),
("calibration_map", "label_budget"),
("rule", "cannot_tell_above"),
];
for (outer, inner) in paths {
let mut v = valid();
let o = if outer == "segments" {
&mut v[outer][0]
} else {
&mut v[outer]
};
o.as_object_mut().unwrap().remove(inner);
let e = serde_json::from_value::<Certificate>(v).err();
assert!(
e.is_some_and(|e| e.to_string().contains(inner)),
"{outer}.{inner}"
);
}
}
fn utc(y: i32, m: Month, d: u8, hh: u8, mm: u8, ss: u8, ns: u32) -> UtcDateTime {
UtcDateTime::new(
Date::from_calendar_date(y, m, d).unwrap(),
Time::from_hms_nano(hh, mm, ss, ns).unwrap(),
)
}
#[test]
fn timestamps_accept_the_spec_form_and_real_dates_only() {
let at = |s: &str| timestamp(s).unwrap_or_else(|e| panic!("{s}: {e}"));
assert_eq!(
at("2027-01-23T12:00:00Z"),
utc(2027, Month::January, 23, 12, 0, 0, 0)
);
assert_eq!(at("1970-01-01T00:00:00Z"), UtcDateTime::UNIX_EPOCH);
assert_eq!(at("2024-02-29T00:00:00Z").unix_timestamp(), 1_709_164_800);
assert_eq!(
at("0000-01-01T00:00:00Z"),
utc(0, Month::January, 1, 0, 0, 0, 0)
);
assert_eq!(
at("9999-12-31T23:59:59Z"),
utc(9999, Month::December, 31, 23, 59, 59, 0)
);
for s in [
"2000-02-29T00:00:00Z",
"0000-02-29T00:00:00Z",
"2400-02-29T00:00:00Z",
"2027-12-31T00:00:00Z",
"2027-04-30T00:00:00Z",
"2027-01-01T23:59:59Z",
] {
at(s);
}
let refused = [
"2023-02-29T00:00:00Z",
"1900-02-29T00:00:00Z",
"2100-02-29T00:00:00Z",
"2027-04-31T00:00:00Z",
"2027-00-01T00:00:00Z",
"2027-13-01T00:00:00Z",
"2027-01-00T00:00:00Z",
"2027-01-32T00:00:00Z",
"2027-01-23T24:00:00Z",
"2027-01-23T12:60:00Z",
"2027-01-23T12:00:61Z",
"2027-01-23T12:00:99Z",
"2027-01-23t12:00:00Z",
"2027-01-23T12:00:00z",
"2027-01-23 12:00:00Z",
"2027-01-23T12:00:00+00:00",
"2027-01-23T12:00:00-00:00",
"2027-01-23T12:00:00+01:00",
"2027-01-23T12:00:00.5Z",
"2027-01-23T12:00:00.000Z",
"2027-01-23T12:00:00",
"2027-01-23",
"2027-01-23T12:00Z",
"2027-1-23T12:00:00Z",
"+2027-01-23T12:00:00Z",
"-0001-01-01T00:00:00Z",
"10000-01-01T00:00:00Z",
" 2027-01-23T12:00:00Z",
"2027-01-23T12:00:00Z ",
"2027-01-23T12:00:00ZZ",
"2027-01-23T12:00:00Z\n",
"\u{ff12}027-01-23T12:00:00Z",
"",
];
for s in refused {
let e = timestamp(s).expect_err(s);
assert_eq!(
e.to_string(),
format!(
"certificate is not a valid decision certificate: timestamp {s:?} is not \
YYYY-MM-DDTHH:MM:SSZ"
)
);
}
}
#[test]
fn leap_seconds_are_accepted_and_ordered() {
let leap = timestamp("2026-12-31T23:59:60Z").unwrap();
let before = timestamp("2026-12-31T23:59:59Z").unwrap();
let after = timestamp("2027-01-01T00:00:00Z").unwrap();
assert!(before < leap && leap < after);
assert_eq!(
leap,
utc(2026, Month::December, 31, 23, 59, 59, 999_999_999)
);
let mid = timestamp("2027-06-15T12:34:60Z").unwrap();
assert!(
timestamp("2027-06-15T12:34:59Z").unwrap() < mid
&& mid < timestamp("2027-06-15T12:35:00Z").unwrap()
);
assert!(timestamp("0000-01-01T00:00:60Z").is_ok());
assert!(timestamp("9999-12-31T23:59:60Z").is_ok());
let mut cert: Certificate = serde_json::from_value(valid()).unwrap();
cert.expires_at = "2026-12-31T23:59:60Z".into();
let v = Verified {
id: String::new(),
expires_at: timestamp(&cert.expires_at).unwrap(),
cert,
};
assert!(!v.is_expired(before));
assert!(v.is_expired(leap));
assert!(v.is_expired(after));
}
#[test]
fn small_order_keys_are_weak() {
let table = [
"0100000000000000000000000000000000000000000000000000000000000000",
"ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f",
"0000000000000000000000000000000000000000000000000000000000000000",
"0000000000000000000000000000000000000000000000000000000000000080",
"26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05",
"26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85",
"c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a",
"c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa",
"0100000000000000000000000000000000000000000000000000000000000080",
"ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
"edffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f",
"edffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
"eeffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f",
"eeffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
];
for h in table {
let b: [u8; 32] = (0..32)
.map(|i| u8::from_str_radix(&h[2 * i..2 * i + 2], 16).unwrap())
.collect::<Vec<_>>()
.try_into()
.unwrap();
let k = VerifyingKey::from_bytes(&b).unwrap_or_else(|e| panic!("{h}: {e}"));
assert!(k.is_weak(), "{h}");
}
}
#[test]
fn certified_segments_set_the_threshold_and_inherited_ones_do_not() {
let cert: Certificate = serde_json::from_value(valid()).unwrap();
let v = Verified {
id: String::new(),
expires_at: timestamp(&cert.expires_at).unwrap(),
cert,
};
assert_eq!(v.threshold_for(Some("east")), 0.9);
assert_eq!(
v.threshold_for(Some("z\u{fc}rich \u{2603}")),
v.cert.abstain_below
);
assert_eq!(v.threshold_for(None), v.cert.abstain_below);
assert!(
v.is_expired(v.expires_at) && !v.is_expired(v.expires_at - time::Duration::seconds(1))
);
}
}