1use std::collections::BTreeMap;
8
9use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};
10use chrono::{DateTime, Utc};
11use ed25519_dalek::{Signature, VerifyingKey};
12use serde::Deserialize;
13use sha2::{Digest, Sha256};
14
15pub const SPEC: &str = "decision-certificate.v1";
16pub const ABSTAIN_ALL: f64 = 1.01;
18
19#[derive(Debug, thiserror::Error)]
20pub enum CertError {
21 #[error("certificate is not a valid {SPEC}: {0}")]
22 Invalid(String),
23 #[error("certificate signed by {0}, which is not a trusted key")]
24 UntrustedKey(String),
25 #[error("trusted key {0} is malformed or does not hash to its id")]
26 BadKey(String),
27 #[error("certificate signature does not verify")]
28 BadSignature,
29}
30
31#[derive(Deserialize, Clone, Debug, PartialEq)]
32#[serde(deny_unknown_fields)]
33pub struct Band {
34 pub level: f64,
35 pub low: f64,
36 pub high: f64,
37}
38
39#[derive(Deserialize, Clone, Debug, PartialEq)]
40#[serde(deny_unknown_fields)]
41pub struct Segment {
42 pub field: String,
43 pub value: String,
44 pub n: u64,
45 pub abstain_below: f64,
46 pub coverage: f64,
47 #[serde(deserialize_with = "nullable")]
48 pub ucb: Option<f64>,
49 #[serde(deserialize_with = "nullable")]
50 pub realized_band: Option<Band>,
51 pub inherited: bool,
52}
53
54#[derive(Deserialize, Clone, Debug, PartialEq)]
55#[serde(deny_unknown_fields)]
56pub struct Split {
57 pub method: String,
58 #[serde(deserialize_with = "nullable")]
59 pub seed: Option<i64>,
60}
61
62#[derive(Deserialize, Clone, Debug, PartialEq)]
63#[serde(deny_unknown_fields)]
64pub struct CalibrationMap {
65 pub kind: String,
66 pub params: BTreeMap<String, f64>,
67 #[serde(deserialize_with = "nullable")]
68 pub label_budget: Option<u64>,
69}
70
71#[derive(Deserialize, Clone, Debug, PartialEq)]
72#[serde(deny_unknown_fields)]
73pub struct Rule {
74 #[serde(deserialize_with = "nullable")]
75 pub cannot_tell_above: Option<f64>,
76 pub unscored: String,
77}
78
79#[derive(Deserialize, Clone, Debug, PartialEq)]
80#[serde(deny_unknown_fields)]
81pub struct Window {
82 pub start: String,
83 pub end: String,
84}
85
86#[derive(Deserialize, Clone, Debug, PartialEq)]
87#[serde(deny_unknown_fields)]
88pub struct Audit {
89 pub mode: String,
90 pub rate: f64,
91 pub n: u64,
92 pub propensity_logged: bool,
93}
94
95#[derive(Deserialize, Clone, Debug, PartialEq)]
96#[serde(deny_unknown_fields)]
97pub struct Issuer {
98 pub tool: String,
99 pub version: String,
100}
101
102#[derive(Deserialize, Clone, Debug, PartialEq)]
104#[serde(deny_unknown_fields)]
105pub struct Certificate {
106 pub spec: String,
107 pub domain: String,
108 pub decision: String,
109 pub options: Vec<String>,
110 pub model_id: String,
111 #[serde(deserialize_with = "nullable")]
112 pub manifest_hash: Option<String>,
113 pub data_hash: String,
114 pub n_cal: u64,
115 pub n_temperature: u64,
116 pub split: Split,
117 pub calibration_map: CalibrationMap,
118 pub rule: Rule,
119 pub alpha: f64,
120 #[serde(deserialize_with = "nullable")]
121 pub delta: Option<f64>,
122 pub method: String,
123 pub risk: String,
124 pub n: u64,
125 pub abstain_below: f64,
126 pub coverage: f64,
127 #[serde(deserialize_with = "nullable")]
128 pub ucb: Option<f64>,
129 pub realized_band: Band,
130 pub segments: Vec<Segment>,
131 #[serde(deserialize_with = "nullable")]
132 pub window: Option<Window>,
133 pub fitted_at: String,
134 pub expires_at: String,
135 pub audit: Audit,
136 pub issuer: Issuer,
137 pub signer_key_id: String,
138 pub signature: String,
139}
140
141fn nullable<'de, D: serde::Deserializer<'de>, T: Deserialize<'de>>(
144 d: D,
145) -> Result<Option<T>, D::Error> {
146 Option::deserialize(d)
147}
148
149#[derive(Clone, Debug, PartialEq)]
151pub struct Verified {
152 pub id: String,
154 pub cert: Certificate,
155 pub expires_at: DateTime<Utc>,
156}
157
158impl Verified {
159 pub fn threshold_for(&self, segment: Option<&str>) -> f64 {
161 segment
162 .and_then(|v| {
163 self.cert
164 .segments
165 .iter()
166 .find(|s| !s.inherited && s.value == v)
167 })
168 .map_or(self.cert.abstain_below, |s| s.abstain_below)
169 }
170
171 pub fn is_expired(&self, now: DateTime<Utc>) -> bool {
172 now >= self.expires_at
173 }
174
175 pub fn temperature(&self) -> Option<f64> {
177 (self.cert.calibration_map.kind == "temperature")
178 .then(|| self.cert.calibration_map.params.get("temperature").copied())
179 .flatten()
180 }
181}
182
183pub fn canonical(v: &serde_json::Value) -> Result<Vec<u8>, CertError> {
185 serde_jcs::to_vec(v).map_err(|e| CertError::Invalid(format!("not canonicalisable: {e}")))
186}
187
188pub fn certificate_id(v: &serde_json::Value) -> Result<String, CertError> {
189 Ok(format!("sha256:{}", hex(&Sha256::digest(canonical(v)?))))
190}
191
192pub fn key_id(key: &VerifyingKey) -> String {
194 format!("ed25519:{}", &hex(&Sha256::digest(key.as_bytes()))[..16])
195}
196
197pub fn verify(
199 v: &serde_json::Value,
200 keys: &BTreeMap<String, String>,
201) -> Result<Verified, CertError> {
202 let obj = v
203 .as_object()
204 .ok_or_else(|| CertError::Invalid("not a JSON object".into()))?;
205 let cert: Certificate =
206 serde_json::from_value(v.clone()).map_err(|e| CertError::Invalid(e.to_string()))?;
207 check(&cert)?;
208
209 let raw = keys
210 .get(&cert.signer_key_id)
211 .ok_or_else(|| CertError::UntrustedKey(cert.signer_key_id.clone()))?;
212 let key = URL_SAFE_NO_PAD
213 .decode(raw)
214 .ok()
215 .and_then(|b| <[u8; 32]>::try_from(b).ok())
216 .and_then(|b| VerifyingKey::from_bytes(&b).ok())
217 .filter(|k| key_id(k) == cert.signer_key_id)
218 .ok_or_else(|| CertError::BadKey(cert.signer_key_id.clone()))?;
219 let sig = URL_SAFE_NO_PAD
220 .decode(&cert.signature)
221 .ok()
222 .and_then(|b| Signature::from_slice(&b).ok())
223 .ok_or(CertError::BadSignature)?;
224 let mut body = obj.clone();
225 body.remove("signature");
226 key.verify_strict(&canonical(&serde_json::Value::Object(body))?, &sig)
227 .map_err(|_| CertError::BadSignature)?;
228
229 Ok(Verified {
230 id: certificate_id(v)?,
231 expires_at: timestamp(&cert.expires_at)?,
232 cert,
233 })
234}
235
236fn check(c: &Certificate) -> Result<(), CertError> {
239 let bad = |m: &str| Err(CertError::Invalid(m.to_string()));
240 let unit = |x: f64| (0.0..=1.0).contains(&x);
241 let open = |x: f64| x > 0.0 && x < 1.0;
242 let threshold = |x: f64| (0.0..=ABSTAIN_ALL).contains(&x);
243 if c.spec != SPEC {
244 return bad("spec is not decision-certificate.v1");
245 }
246 let mut seen = std::collections::BTreeSet::new();
247 if c.options.len() < 2 || !c.options.iter().all(|o| !o.is_empty() && seen.insert(o)) {
248 return bad("options needs at least 2 distinct non-empty ids");
249 }
250 if [
251 &c.domain,
252 &c.decision,
253 &c.calibration_map.kind,
254 &c.issuer.tool,
255 &c.issuer.version,
256 ]
257 .iter()
258 .any(|s| s.is_empty())
259 {
260 return bad("domain, decision, calibration_map.kind and issuer must be non-empty");
261 }
262 match (c.method.as_str(), c.risk.as_str(), c.delta, c.ucb) {
263 ("ltt", "selective_error", Some(d), _) if open(d) => {}
264 ("crc", "joint_error", None, None) => {}
265 _ => return bad("method, risk, delta and ucb disagree"),
266 }
267 if !open(c.alpha) || !threshold(c.abstain_below) || !unit(c.coverage) {
268 return bad("alpha, abstain_below or coverage out of range");
269 }
270 if c.ucb.is_some_and(|u| !unit(u)) || !band_ok(&c.realized_band) {
271 return bad("ucb or realized_band out of range");
272 }
273 for s in &c.segments {
274 if s.field.is_empty()
275 || !threshold(s.abstain_below)
276 || !unit(s.coverage)
277 || s.ucb.is_some_and(|u| !unit(u))
278 || s.realized_band.as_ref().is_some_and(|b| !band_ok(b))
279 {
280 return bad("a segment is out of range");
281 }
282 }
283 if !matches!(
284 (c.split.method.as_str(), c.split.seed),
285 ("time", None) | ("seeded", Some(_))
286 ) {
287 return bad("split.method and split.seed disagree");
288 }
289 if c.rule.unscored != "abstain" || c.rule.cannot_tell_above.is_some_and(|x| !unit(x)) {
290 return bad("rule out of range");
291 }
292 if !matches!(c.audit.mode.as_str(), "sample" | "full-label")
293 || !(c.audit.rate > 0.0 && c.audit.rate <= 1.0)
294 {
295 return bad("audit out of range");
296 }
297 if !model_id_ok(&c.model_id) {
298 return bad("model_id must be <backend>/<model>@<version>");
299 }
300 if !sha256_ok(&c.data_hash) || c.manifest_hash.as_deref().is_some_and(|h| !sha256_ok(h)) {
301 return bad("data_hash and manifest_hash must be sha256:<64 hex>");
302 }
303 let key_hex = c.signer_key_id.strip_prefix("ed25519:");
304 if !key_hex.is_some_and(|h| h.len() == 16 && lower_hex(h)) {
305 return bad("signer_key_id must be ed25519:<16 hex>");
306 }
307 if c.signature.len() != 86
308 || !c
309 .signature
310 .bytes()
311 .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
312 {
313 return bad("signature must be 86 base64url characters");
314 }
315 timestamp(&c.fitted_at)?;
316 timestamp(&c.expires_at)?;
317 if let Some(w) = &c.window {
318 timestamp(&w.start)?;
319 timestamp(&w.end)?;
320 }
321 Ok(())
322}
323
324fn model_id_ok(m: &str) -> bool {
326 if m.chars()
328 .any(|c| matches!(c, '\n' | '\r' | '\u{2028}' | '\u{2029}'))
329 {
330 return false;
331 }
332 let Some((backend, rest)) = m.split_once('/') else {
333 return false;
334 };
335 let at = rest
336 .char_indices()
337 .skip(1)
338 .any(|(i, ch)| ch == '@' && i + 1 < rest.len());
339 !backend.is_empty() && at && !m.ends_with("@?")
340}
341
342fn sha256_ok(h: &str) -> bool {
343 h.strip_prefix("sha256:")
344 .is_some_and(|x| x.len() == 64 && lower_hex(x))
345}
346
347fn lower_hex(s: &str) -> bool {
348 s.bytes()
349 .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
350}
351
352fn band_ok(b: &Band) -> bool {
353 b.level > 0.0 && b.level < 1.0 && (0.0..=1.0).contains(&b.low) && (0.0..=1.0).contains(&b.high)
354}
355
356pub fn timestamp(s: &str) -> Result<DateTime<Utc>, CertError> {
358 let b = s.as_bytes();
360 let ok = b.len() == 20
361 && b.iter().enumerate().all(|(i, &c)| match i {
362 4 | 7 => c == b'-',
363 10 => c == b'T',
364 13 | 16 => c == b':',
365 19 => c == b'Z',
366 _ => c.is_ascii_digit(),
367 });
368 DateTime::parse_from_rfc3339(s)
369 .ok()
370 .filter(|_| ok)
371 .map(|t| t.with_timezone(&Utc))
372 .ok_or_else(|| CertError::Invalid(format!("timestamp {s:?} is not YYYY-MM-DDTHH:MM:SSZ")))
373}
374
375fn hex(b: &[u8]) -> String {
376 b.iter().map(|x| format!("{x:02x}")).collect()
377}
378
379#[cfg(test)]
380mod tests {
381 use super::*;
382
383 fn valid() -> serde_json::Value {
384 let f: serde_json::Value =
385 serde_json::from_str(include_str!("../../fixtures/valid_segments_unicode.json"))
386 .unwrap();
387 f["certificate"].clone()
388 }
389
390 #[test]
391 fn check_rejects_what_the_schema_rejects() {
392 let typed =
393 |v: &serde_json::Value| serde_json::from_value::<Certificate>(v.clone()).unwrap();
394 assert!(check(&typed(&valid())).is_ok());
395 let edits: [(&str, serde_json::Value); 15] = [
396 ("data_hash", serde_json::json!("sha256:XYZ")),
397 ("manifest_hash", serde_json::json!("md5:00")),
398 ("signer_key_id", serde_json::json!("ed25519:short")),
399 ("model_id", serde_json::json!("/x@y")),
400 ("model_id", serde_json::json!("b/m@?")),
401 (
402 "window",
403 serde_json::json!({"start": "2023-01-02", "end": "2023-12-29T23:59:59Z"}),
404 ),
405 ("expires_at", serde_json::json!("2027-01-23T12:00:00+00:00")),
406 ("expires_at", serde_json::json!("2027-01-23 12:00:00Z")),
407 ("fitted_at", serde_json::json!("2026-10-25t12:00:00Z")),
408 ("domain", serde_json::json!("")),
409 ("options", serde_json::json!(["yes", "yes"])),
410 ("split", serde_json::json!({"method": "time", "seed": 3})),
411 ("alpha", serde_json::json!(1.0)),
412 ("signature", serde_json::json!("abc")),
413 ("model_id", serde_json::json!("a/b\n@c")),
414 ];
415 for (field, value) in edits {
416 let mut v = valid();
417 v[field] = value.clone();
418 assert!(check(&typed(&v)).is_err(), "{field} = {value}");
419 }
420 }
421
422 #[test]
423 fn nested_nullable_fields_must_be_present() {
424 let paths: [(&str, &str); 5] = [
425 ("segments", "ucb"),
426 ("segments", "realized_band"),
427 ("split", "seed"),
428 ("calibration_map", "label_budget"),
429 ("rule", "cannot_tell_above"),
430 ];
431 for (outer, inner) in paths {
432 let mut v = valid();
433 let o = if outer == "segments" {
434 &mut v[outer][0]
435 } else {
436 &mut v[outer]
437 };
438 o.as_object_mut().unwrap().remove(inner);
439 let e = serde_json::from_value::<Certificate>(v).err();
440 assert!(
441 e.is_some_and(|e| e.to_string().contains(inner)),
442 "{outer}.{inner}"
443 );
444 }
445 }
446
447 #[test]
450 fn small_order_keys_are_weak() {
451 let table = [
452 "0100000000000000000000000000000000000000000000000000000000000000",
453 "ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f",
454 "0000000000000000000000000000000000000000000000000000000000000000",
455 "0000000000000000000000000000000000000000000000000000000000000080",
456 "26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05",
457 "26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85",
458 "c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a",
459 "c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa",
460 "0100000000000000000000000000000000000000000000000000000000000080",
461 "ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
462 "edffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f",
463 "edffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
464 "eeffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f",
465 "eeffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
466 ];
467 for h in table {
468 let b: [u8; 32] = (0..32)
469 .map(|i| u8::from_str_radix(&h[2 * i..2 * i + 2], 16).unwrap())
470 .collect::<Vec<_>>()
471 .try_into()
472 .unwrap();
473 let k = VerifyingKey::from_bytes(&b).unwrap_or_else(|e| panic!("{h}: {e}"));
474 assert!(k.is_weak(), "{h}");
475 }
476 }
477
478 #[test]
479 fn certified_segments_set_the_threshold_and_inherited_ones_do_not() {
480 let cert: Certificate = serde_json::from_value(valid()).unwrap();
481 let v = Verified {
482 id: String::new(),
483 expires_at: timestamp(&cert.expires_at).unwrap(),
484 cert,
485 };
486 assert_eq!(v.threshold_for(Some("east")), 0.9);
487 assert_eq!(
488 v.threshold_for(Some("z\u{fc}rich \u{2603}")),
489 v.cert.abstain_below
490 );
491 assert_eq!(v.threshold_for(None), v.cert.abstain_below);
492 assert!(
493 v.is_expired(v.expires_at)
494 && !v.is_expired(v.expires_at - chrono::Duration::seconds(1))
495 );
496 }
497}