1use std::collections::BTreeMap;
18
19use serde_json::{json, Map, Value};
20
21use crate::credentials::{
22 proof_bound_to_issuer, verify_temporal, VerifyResult, VC_CONTEXT_V2, VC_TYPE, VOUCH_CONTEXT_V1,
23};
24use crate::data_integrity::{self, BuildProofOptions};
25use crate::error::{CoreError, Result};
26
27pub const AUTHORITY_STATE_TYPE: &str = "AuthorityState";
28
29pub const STATUS_ACTIVE: &str = "active";
30pub const STATUS_SUSPENDED: &str = "suspended";
31pub const STATUS_INCIDENT: &str = "incident";
32pub const STATUS_EXPOSURE_BREACHED: &str = "exposure_breached";
33pub const STATUS_REVOKED: &str = "revoked";
34
35pub const AUTHORITY_STATE_MISSING: &str = "authority_state_missing";
38pub const AUTHORITY_STATE_DIGEST_MISMATCH: &str = "authority_state_digest_mismatch";
39pub const AUTHORITY_ISSUER_UNTRUSTED: &str = "authority_issuer_untrusted";
40pub const MAX_AUTHORITY_STATE_BYTES: usize = 8192;
43
44pub const VALID_AUTHORITY_STATUSES: [&str; 5] = [
45 STATUS_ACTIVE,
46 STATUS_SUSPENDED,
47 STATUS_INCIDENT,
48 STATUS_EXPOSURE_BREACHED,
49 STATUS_REVOKED,
50];
51
52pub const CONSEQUENCE_ROUTINE: &str = "routine";
55pub const CONSEQUENCE_SENSITIVE: &str = "sensitive";
56pub const CONSEQUENCE_CRITICAL: &str = "critical";
57
58fn is_valid_status(status: &str) -> bool {
59 VALID_AUTHORITY_STATUSES.contains(&status)
60}
61
62fn epoch_str(epoch: Option<i64>) -> String {
65 match epoch {
66 Some(e) => e.to_string(),
67 None => "?".to_string(),
68 }
69}
70
71#[derive(Debug, Clone)]
74pub struct BuildAuthorityStateOptions {
75 pub issuer_did: String,
76 pub credential_id: String,
77 pub authority_epoch: i64,
78 pub status: String,
79 pub valid_from: String,
80 pub valid_until: String,
81 pub subject_did: Option<String>,
83}
84
85pub fn build_authority_state(opts: &BuildAuthorityStateOptions) -> Result<Value> {
87 if !(0..=MAX_AUTHORITY_EPOCH).contains(&opts.authority_epoch) {
88 return Err(CoreError::Json(
89 "authorityEpoch must be a whole number from 0 to 2^53-1".into(),
90 ));
91 }
92 if !is_valid_status(&opts.status) {
93 return Err(CoreError::Json(format!(
94 "status must be one of {VALID_AUTHORITY_STATUSES:?}"
95 )));
96 }
97 if opts.issuer_did.is_empty() {
98 return Err(CoreError::Json("issuer_did is required".into()));
99 }
100
101 let subject_did = opts
102 .subject_did
103 .clone()
104 .unwrap_or_else(|| opts.issuer_did.clone());
105
106 let mut subject = Map::new();
107 subject.insert("id".into(), json!(subject_did));
108 subject.insert("authorityEpoch".into(), json!(opts.authority_epoch));
109 subject.insert("status".into(), json!(opts.status));
110
111 let mut vc = Map::new();
112 vc.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
113 vc.insert("id".into(), json!(opts.credential_id));
114 vc.insert("type".into(), json!([VC_TYPE, AUTHORITY_STATE_TYPE]));
115 vc.insert("issuer".into(), json!(opts.issuer_did));
116 vc.insert("validFrom".into(), json!(opts.valid_from));
117 vc.insert("validUntil".into(), json!(opts.valid_until));
118 vc.insert("credentialSubject".into(), Value::Object(subject));
119 Ok(Value::Object(vc))
120}
121
122pub fn sign_authority_state(
124 opts: &BuildAuthorityStateOptions,
125 raw_private_seed: &[u8],
126 proof_opts: &BuildProofOptions,
127) -> Result<Value> {
128 let cred = build_authority_state(opts)?;
129 data_integrity::sign(&cred, raw_private_seed, proof_opts)
130}
131
132pub const MAX_AUTHORITY_EPOCH: i64 = (1 << 53) - 1;
134
135fn epoch_of(v: &Value) -> Option<i64> {
139 let Value::Number(n) = v else {
140 return None;
141 };
142 if let Some(i) = n.as_i64() {
143 return (0..=MAX_AUTHORITY_EPOCH).contains(&i).then_some(i);
144 }
145 match n.as_f64() {
147 Some(f) if f == 0.0 && f.is_sign_negative() => Some(0),
148 _ => None,
149 }
150}
151
152pub fn check_epoch_literal(credential_text: &str) -> Result<()> {
158 use serde_json::value::RawValue;
159 type Raw = std::collections::HashMap<String, Box<RawValue>>;
160 let json_err = |e: serde_json::Error| CoreError::Json(e.to_string());
161 let top: Raw = serde_json::from_str(credential_text).map_err(json_err)?;
162 let Some(subject) = top.get("credentialSubject") else {
163 return Ok(());
164 };
165 let Ok(subject) = serde_json::from_str::<Raw>(subject.get()) else {
166 return Ok(());
167 };
168 let Some(epoch) = subject.get("authorityEpoch") else {
169 return Ok(());
170 };
171 let lit = epoch.get().trim();
172 let digits = lit.strip_prefix('-').unwrap_or(lit);
173 let is_int = !digits.is_empty()
174 && digits.bytes().all(|b| b.is_ascii_digit())
175 && (digits.len() == 1 || !digits.starts_with('0'));
176 if lit.starts_with(|c: char| c == '-' || c.is_ascii_digit()) && !is_int {
177 return Err(CoreError::Json(
178 "authorityEpoch must be written as an integer".into(),
179 ));
180 }
181 Ok(())
182}
183
184fn authority_issuer(credential: &Value) -> Option<&str> {
188 let s = match credential.get("issuer")? {
189 Value::String(s) => s.as_str(),
190 Value::Array(a) => a.first()?.as_str()?,
191 _ => return None,
192 };
193 (!s.is_empty()).then_some(s)
194}
195
196pub fn verify(
206 credential: &Value,
207 raw_public_key: &[u8],
208 now_iso: &str,
209 clock_skew_seconds: i64,
210) -> Result<VerifyResult> {
211 let is_authority_state = match credential.get("type") {
212 Some(Value::Array(arr)) => {
214 arr.iter().all(Value::is_string)
215 && arr.iter().any(|t| t.as_str() == Some(AUTHORITY_STATE_TYPE))
216 }
217 Some(Value::String(s)) => s == AUTHORITY_STATE_TYPE,
218 _ => false,
219 };
220 if !is_authority_state {
221 return Err(CoreError::Json(
222 "credential is not an AuthorityState".into(),
223 ));
224 }
225 let signature_valid = data_integrity::verify_proof(credential, raw_public_key)?;
226 let bound = match (authority_issuer(credential), credential.get("proof")) {
227 (Some(issuer), Some(proof)) => proof_bound_to_issuer(proof, issuer),
228 _ => false,
229 };
230 let own_key = match authority_issuer(credential) {
233 Some(issuer) if issuer.starts_with("did:key:") => {
234 did_key_ed25519(issuer).as_deref() == Some(raw_public_key)
235 }
236 _ => true,
237 };
238 if !credential
240 .get("credentialSubject")
241 .map(Value::is_object)
242 .unwrap_or(false)
243 {
244 return Err(CoreError::Json(
245 "credentialSubject must be an object".into(),
246 ));
247 }
248 read_authority_epoch(credential)?;
249 read_authority_status(credential)?;
250 crate::time::check_clock_skew(clock_skew_seconds)?;
253 crate::time::parse_protocol_time_ns(now_iso)?;
254 let time_valid = verify_temporal(credential, now_iso, clock_skew_seconds).unwrap_or(false);
255 Ok(VerifyResult {
256 proof_valid: signature_valid && bound && own_key,
257 time_valid,
258 chain_valid: true,
260 })
261}
262
263pub fn read_authority_epoch(credential: &Value) -> Result<i64> {
267 credential
268 .get("credentialSubject")
269 .and_then(|s| s.get("authorityEpoch"))
270 .and_then(epoch_of)
271 .ok_or_else(|| CoreError::Json("missing or invalid authorityEpoch".into()))
272}
273
274pub fn read_authority_status(credential: &Value) -> Result<String> {
276 credential
277 .get("credentialSubject")
278 .and_then(|s| s.get("status"))
279 .and_then(|v| v.as_str())
280 .filter(|s| is_valid_status(s))
281 .map(|s| s.to_string())
282 .ok_or_else(|| CoreError::Json("missing or invalid status".into()))
283}
284
285pub fn did_key_ed25519(did: &str) -> Option<Vec<u8>> {
292 let mk = did.strip_prefix("did:key:")?;
293 let decoded = crate::multikey::decode(mk).ok()?;
294 (decoded.algorithm == "Ed25519" && decoded.raw_key.len() == 32).then_some(decoded.raw_key)
295}
296
297pub fn parse_json_no_duplicates(text: &str) -> Result<Value> {
301 struct NoDup(Value);
302 struct Visit;
303 impl<'de> serde::de::Visitor<'de> for Visit {
304 type Value = Value;
305 fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
306 f.write_str("JSON")
307 }
308 fn visit_bool<E>(self, v: bool) -> std::result::Result<Value, E> {
309 Ok(Value::Bool(v))
310 }
311 fn visit_i64<E>(self, v: i64) -> std::result::Result<Value, E> {
312 Ok(Value::from(v))
313 }
314 fn visit_u64<E>(self, v: u64) -> std::result::Result<Value, E> {
315 Ok(Value::from(v))
316 }
317 fn visit_f64<E: serde::de::Error>(self, v: f64) -> std::result::Result<Value, E> {
318 serde_json::Number::from_f64(v)
319 .map(Value::Number)
320 .ok_or_else(|| E::custom("a number that is not finite"))
321 }
322 fn visit_str<E>(self, v: &str) -> std::result::Result<Value, E> {
323 Ok(Value::String(v.to_owned()))
324 }
325 fn visit_string<E>(self, v: String) -> std::result::Result<Value, E> {
326 Ok(Value::String(v))
327 }
328 fn visit_unit<E>(self) -> std::result::Result<Value, E> {
329 Ok(Value::Null)
330 }
331 fn visit_seq<A: serde::de::SeqAccess<'de>>(
332 self,
333 mut seq: A,
334 ) -> std::result::Result<Value, A::Error> {
335 let mut out = Vec::new();
336 while let Some(NoDup(v)) = seq.next_element()? {
337 out.push(v);
338 }
339 Ok(Value::Array(out))
340 }
341 fn visit_map<A: serde::de::MapAccess<'de>>(
342 self,
343 mut map: A,
344 ) -> std::result::Result<Value, A::Error> {
345 let mut out = Map::new();
346 while let Some(key) = map.next_key::<String>()? {
347 if out.contains_key(&key) {
348 return Err(serde::de::Error::custom(format!("duplicate key {key:?}")));
349 }
350 let NoDup(v) = map.next_value()?;
351 out.insert(key, v);
352 }
353 Ok(Value::Object(out))
354 }
355 }
356 impl<'de> serde::Deserialize<'de> for NoDup {
357 fn deserialize<D: serde::Deserializer<'de>>(d: D) -> std::result::Result<Self, D::Error> {
358 d.deserialize_any(Visit).map(NoDup)
359 }
360 }
361 if let Some(literal) = integer_out_of_range(text) {
362 return Err(CoreError::Json(format!(
363 "the whole number {literal} is outside the 64-bit range, so it has no exact \
364 JSON reading"
365 )));
366 }
367 serde_json::from_str::<NoDup>(text)
368 .map(|NoDup(v)| v)
369 .map_err(|e| CoreError::Json(e.to_string()))
370}
371
372fn integer_out_of_range(text: &str) -> Option<String> {
377 let bytes = text.as_bytes();
378 let mut i = 0;
379 while i < bytes.len() {
380 match bytes[i] {
381 b'"' => {
382 i += 1;
383 while i < bytes.len() && bytes[i] != b'"' {
384 if bytes[i] == b'\\' {
385 i += 1;
386 }
387 i += 1;
388 }
389 i += 1;
390 }
391 b'-' | b'0'..=b'9' => {
392 let start = i;
393 i += 1;
394 while i < bytes.len()
395 && matches!(bytes[i], b'0'..=b'9' | b'.' | b'e' | b'E' | b'+' | b'-')
396 {
397 i += 1;
398 }
399 let literal = &text[start..i];
400 let integer = !literal.contains(['.', 'e', 'E']);
401 if integer && literal.parse::<i64>().is_err() && literal.parse::<u64>().is_err() {
402 return Some(literal.chars().take(40).collect());
403 }
404 }
405 _ => i += 1,
406 }
407 }
408 None
409}
410
411pub fn parse_authority_state_text(text: &str) -> Result<Value> {
415 let value = parse_json_no_duplicates(text)?;
416 check_epoch_literal(text)?;
417 Ok(value)
418}
419
420pub fn authority_state_digest(credential: &Value) -> Result<String> {
428 let Some(obj) = credential.as_object() else {
429 return Err(CoreError::Json(
430 "an AuthorityState must be a JSON object".into(),
431 ));
432 };
433 let mut body = obj.clone();
434 body.remove("proof");
435 crate::grant_chain::grant_digest(&Value::Object(body))
436 .map_err(|e| CoreError::Json(e.to_string()))
437}
438
439pub fn authority_state_digest_text(text: &str) -> Result<String> {
441 authority_state_digest(&parse_json_no_duplicates(text)?)
442}
443
444pub const EMPTY_TRUSTED_AUTHORITIES: &str = "the trusted-authority list is empty: name at least one authority, or leave trusted_authorities out";
447
448fn empty_trusted_authorities() -> CoreError {
449 CoreError::Json(EMPTY_TRUSTED_AUTHORITIES.into())
450}
451
452pub fn trusted_authority_keys(
460 entries: &[(String, Option<Vec<u8>>)],
461) -> Result<BTreeMap<String, Vec<u8>>> {
462 if entries.is_empty() {
463 return Err(empty_trusted_authorities());
464 }
465 let mut out = BTreeMap::new();
466 for (did, key) in entries {
467 if !did.starts_with("did:") {
468 return Err(CoreError::Json(format!(
469 "trusted authority {did:?} is not a DID"
470 )));
471 }
472 let own = if did.starts_with("did:key:") {
473 did_key_ed25519(did)
474 } else {
475 None
476 };
477 let resolved = match key {
478 Some(k) if k.len() == 32 && crate::keys::strict_verifying_key(k).is_ok() => {
479 Some(k.clone())
480 }
481 Some(_) => None,
482 None => own.clone(),
483 };
484 let Some(resolved) = resolved else {
485 return Err(CoreError::Json(format!(
486 "trusted authority {did}: no usable Ed25519 key"
487 )));
488 };
489 if let Some(own) = own {
490 if own != resolved {
491 return Err(CoreError::Json(format!(
492 "trusted authority {did}: the key is not the one its DID names"
493 )));
494 }
495 }
496 out.insert(did.clone(), resolved);
497 }
498 Ok(out)
499}
500
501#[derive(Debug, Clone, PartialEq, Eq)]
503pub struct AuthorityStatePassport {
504 pub issuer_did: String,
505 pub subject_did: String,
506 pub authority_epoch: i64,
507 pub status: String,
508 pub valid_from: String,
509 pub valid_until: String,
510}
511
512impl AuthorityStatePassport {
513 pub fn is_active(&self) -> bool {
514 self.status == STATUS_ACTIVE
515 }
516
517 pub fn to_json(&self) -> Value {
520 json!({
521 "issuerDid": self.issuer_did,
522 "subjectDid": self.subject_did,
523 "authorityEpoch": self.authority_epoch,
524 "status": self.status,
525 "validFrom": self.valid_from,
526 "validUntil": self.valid_until,
527 })
528 }
529}
530
531pub fn trusted_authorities_from_json(value: &Value) -> Result<BTreeMap<String, Vec<u8>>> {
535 use base64::{engine::general_purpose::STANDARD, Engine};
536 let mut entries: Vec<(String, Option<Vec<u8>>)> = Vec::new();
537 match value {
538 Value::Object(map) => {
539 for (did, key) in map {
540 let key = match key {
541 Value::Null => None,
542 Value::String(k) => Some(STANDARD.decode(k).map_err(|_| {
543 CoreError::Json(format!("trusted authority {did}: the key is not base64"))
544 })?),
545 _ => {
546 return Err(CoreError::Json(format!(
547 "trusted authority {did}: the key must be base64 text or null"
548 )))
549 }
550 };
551 entries.push((did.clone(), key));
552 }
553 }
554 Value::Array(list) => {
555 for did in list {
556 let Some(did) = did.as_str() else {
557 return Err(CoreError::Json("trusted authorities must be DIDs".into()));
558 };
559 entries.push((did.to_string(), None));
560 }
561 }
562 _ => {
563 return Err(CoreError::Json(
564 "trusted authorities must be {DID: key} or a list of did:key DIDs".into(),
565 ))
566 }
567 }
568 trusted_authority_keys(&entries)
569}
570
571pub fn voucher_authority_json(voucher: &Value) -> Value {
574 match voucher_authority(voucher) {
575 Some(a) => json!({
576 "digest": a.digest,
577 "epoch": a.epoch,
578 "status": a.status,
579 "issuer": a.issuer,
580 }),
581 None => Value::Null,
582 }
583}
584
585pub fn verify_authority_state_bound(
602 credential: &Value,
603 public_key: Option<&[u8]>,
604 trusted_authorities: Option<&BTreeMap<String, Vec<u8>>>,
605 issuer_did: Option<&str>,
606 now_iso: &str,
607 clock_skew_seconds: i64,
608) -> Result<Option<AuthorityStatePassport>> {
609 crate::time::check_clock_skew(clock_skew_seconds)?;
610 if trusted_authorities.is_some_and(BTreeMap::is_empty) {
611 return Err(empty_trusted_authorities());
612 }
613 if !credential.is_object() {
614 return Ok(None);
615 }
616 let Some(claimed) = authority_issuer(credential) else {
617 return Ok(None);
618 };
619 if issuer_did.is_some_and(|expected| expected != claimed) {
620 return Ok(None);
621 }
622 let key: Vec<u8> = if let Some(trusted) = trusted_authorities {
623 match trusted.get(claimed) {
624 Some(k) => k.clone(),
625 None => return Ok(None),
626 }
627 } else if let Some(k) = public_key {
628 k.to_vec()
629 } else {
630 match did_key_ed25519(claimed) {
631 Some(k) => k,
632 None => return Ok(None),
633 }
634 };
635 let Ok(result) = verify(credential, &key, now_iso, clock_skew_seconds) else {
636 return Ok(None);
637 };
638 if !result.is_valid() {
639 return Ok(None);
640 }
641 let (Ok(epoch), Ok(status)) = (
642 read_authority_epoch(credential),
643 read_authority_status(credential),
644 ) else {
645 return Ok(None);
646 };
647 let subject_did = credential["credentialSubject"]
648 .get("id")
649 .and_then(Value::as_str)
650 .filter(|s| !s.is_empty())
651 .unwrap_or(claimed)
652 .to_string();
653 Ok(Some(AuthorityStatePassport {
654 issuer_did: claimed.to_string(),
655 subject_did,
656 authority_epoch: epoch,
657 status,
658 valid_from: credential["validFrom"]
659 .as_str()
660 .unwrap_or_default()
661 .to_string(),
662 valid_until: credential["validUntil"]
663 .as_str()
664 .unwrap_or_default()
665 .to_string(),
666 }))
667}
668
669pub fn verify_authority_state_bound_text(
672 credential_text: &str,
673 public_key: Option<&[u8]>,
674 trusted_authorities: Option<&BTreeMap<String, Vec<u8>>>,
675 issuer_did: Option<&str>,
676 now_iso: &str,
677 clock_skew_seconds: i64,
678) -> Result<Option<AuthorityStatePassport>> {
679 crate::time::check_clock_skew(clock_skew_seconds)?;
680 if trusted_authorities.is_some_and(BTreeMap::is_empty) {
681 return Err(empty_trusted_authorities());
682 }
683 let Ok(credential) = parse_authority_state_text(credential_text) else {
684 return Ok(None);
685 };
686 verify_authority_state_bound(
687 &credential,
688 public_key,
689 trusted_authorities,
690 issuer_did,
691 now_iso,
692 clock_skew_seconds,
693 )
694}
695
696pub const VOUCHER_AUTHORITY_FIELDS: [&str; 4] = [
701 "authorityStateDigest",
702 "authorityEpoch",
703 "authorityStatus",
704 "authorityIssuer",
705];
706
707pub fn voucher_authority_problem(subject: &Value) -> Option<String> {
712 let obj = subject.as_object()?;
713 let present: Vec<&str> = VOUCHER_AUTHORITY_FIELDS
714 .iter()
715 .copied()
716 .filter(|name| obj.contains_key(*name))
717 .collect();
718 if present.is_empty() || present == ["authorityEpoch"] {
719 return None;
720 }
721 if present.len() != VOUCHER_AUTHORITY_FIELDS.len() {
722 return Some("the authority fields must be all present or all absent".into());
723 }
724 for name in ["authorityStateDigest", "authorityStatus", "authorityIssuer"] {
725 if obj[name].as_str().is_none_or(str::is_empty) {
726 return Some(format!("{name} must be a non-empty string"));
727 }
728 }
729 None
730}
731
732#[derive(Debug, Clone, PartialEq, Eq)]
734pub struct VoucherAuthority {
735 pub digest: String,
736 pub epoch: i64,
737 pub status: String,
738 pub issuer: String,
739}
740
741pub fn voucher_authority(voucher: &Value) -> Option<VoucherAuthority> {
746 let subject = voucher.get("credentialSubject")?;
747 let obj = subject.as_object()?;
748 if voucher_authority_problem(subject).is_some() || !obj.contains_key("authorityStateDigest") {
749 return None;
750 }
751 Some(VoucherAuthority {
752 digest: obj["authorityStateDigest"].as_str()?.to_string(),
753 epoch: epoch_of(&obj["authorityEpoch"])?,
754 status: obj["authorityStatus"].as_str()?.to_string(),
755 issuer: obj["authorityIssuer"].as_str()?.to_string(),
756 })
757}
758
759pub fn voucher_authority_epoch(voucher: &Value) -> Option<i64> {
762 voucher_authority(voucher).map(|a| a.epoch)
763}
764
765pub fn check_attached_authority_state(
781 state: Option<&Value>,
782 trusted_authorities: &BTreeMap<String, Vec<u8>>,
783 voucher: Option<&Value>,
784 caller: Option<&str>,
785 now_iso: &str,
786 clock_skew_seconds: i64,
787) -> Result<std::result::Result<AuthorityStatePassport, &'static str>> {
788 crate::time::check_clock_skew(clock_skew_seconds)?;
789 if trusted_authorities.is_empty() {
790 return Err(empty_trusted_authorities());
791 }
792 let Some(state) = state.filter(|s| s.is_object()) else {
793 return Ok(Err(AUTHORITY_STATE_MISSING));
794 };
795 let Some(issuer) = authority_issuer(state).filter(|i| trusted_authorities.contains_key(*i))
796 else {
797 return Ok(Err(AUTHORITY_ISSUER_UNTRUSTED));
798 };
799 let passport = verify_authority_state_bound(
800 state,
801 None,
802 Some(trusted_authorities),
803 None,
804 now_iso,
805 clock_skew_seconds,
806 )?;
807 let Some(passport) = passport.filter(|p| caller == Some(p.subject_did.as_str())) else {
808 return Ok(Err(AUTHORITY_STATE_MISSING));
809 };
810 let Ok(digest) = authority_state_digest(state) else {
811 return Ok(Err(AUTHORITY_STATE_MISSING));
812 };
813 match voucher.and_then(voucher_authority) {
814 Some(recorded) if recorded.digest == digest && recorded.issuer == issuer => {
815 Ok(Ok(passport))
816 }
817 _ => Ok(Err(AUTHORITY_STATE_DIGEST_MISMATCH)),
818 }
819}
820
821pub fn check_attached_authority_state_text(
824 state_text: Option<&str>,
825 trusted_authorities: &BTreeMap<String, Vec<u8>>,
826 voucher: Option<&Value>,
827 caller: Option<&str>,
828 now_iso: &str,
829 clock_skew_seconds: i64,
830) -> Result<std::result::Result<AuthorityStatePassport, &'static str>> {
831 crate::time::check_clock_skew(clock_skew_seconds)?;
832 if trusted_authorities.is_empty() {
833 return Err(empty_trusted_authorities());
834 }
835 let parsed = match state_text {
836 None => None,
837 Some(text) => match parse_authority_state_text(text) {
838 Ok(v) => Some(v),
839 Err(_) => return Ok(Err(AUTHORITY_STATE_MISSING)),
840 },
841 };
842 check_attached_authority_state(
843 parsed.as_ref(),
844 trusted_authorities,
845 voucher,
846 caller,
847 now_iso,
848 clock_skew_seconds,
849 )
850}
851
852#[derive(Debug, Clone, Copy, PartialEq, Eq)]
854pub struct FreshnessRule {
855 pub enforce_epoch: bool,
856 pub require_live_cosign: bool,
857}
858
859pub fn freshness_rule(tier: &str) -> FreshnessRule {
861 match tier {
862 CONSEQUENCE_ROUTINE => FreshnessRule {
863 enforce_epoch: false,
864 require_live_cosign: false,
865 },
866 CONSEQUENCE_SENSITIVE => FreshnessRule {
867 enforce_epoch: true,
868 require_live_cosign: false,
869 },
870 _ => FreshnessRule {
872 enforce_epoch: true,
873 require_live_cosign: true,
874 },
875 }
876}
877
878#[derive(Debug, Clone, PartialEq, Eq)]
880pub struct AuthorityFreshnessVerdict {
881 pub allow: bool,
882 pub tier: String,
883 pub reason: String,
884}
885
886pub fn evaluate_authority_freshness(
896 tier: &str,
897 voucher_epoch: Option<i64>,
898 last_seen_epoch: Option<i64>,
899 current_status: Option<&str>,
900 live_cosign_ok: Option<bool>,
901) -> Result<AuthorityFreshnessVerdict> {
902 let policy: BTreeMap<String, FreshnessRule> = [
903 CONSEQUENCE_ROUTINE,
904 CONSEQUENCE_SENSITIVE,
905 CONSEQUENCE_CRITICAL,
906 ]
907 .iter()
908 .map(|t| (t.to_string(), freshness_rule(t)))
909 .collect();
910 evaluate_authority_freshness_with(
911 tier,
912 voucher_epoch,
913 last_seen_epoch,
914 current_status,
915 live_cosign_ok,
916 &policy,
917 )
918}
919
920pub fn evaluate_authority_freshness_with(
925 tier: &str,
926 voucher_epoch: Option<i64>,
927 last_seen_epoch: Option<i64>,
928 current_status: Option<&str>,
929 live_cosign_ok: Option<bool>,
930 policy: &BTreeMap<String, FreshnessRule>,
931) -> Result<AuthorityFreshnessVerdict> {
932 for (name, e) in [
933 ("voucher_epoch", voucher_epoch),
934 ("last_seen_epoch", last_seen_epoch),
935 ] {
936 if let Some(e) = e {
937 if !(0..=MAX_AUTHORITY_EPOCH).contains(&e) {
938 return Err(CoreError::Json(format!(
939 "{name} must be a whole number from 0 to 2^53 - 1"
940 )));
941 }
942 }
943 }
944 let canonical_tier = match tier {
945 CONSEQUENCE_ROUTINE | CONSEQUENCE_SENSITIVE | CONSEQUENCE_CRITICAL => tier,
946 _ => CONSEQUENCE_CRITICAL,
947 };
948 let rule = policy
949 .get(canonical_tier)
950 .copied()
951 .unwrap_or(FreshnessRule {
952 enforce_epoch: true,
953 require_live_cosign: true,
954 });
955 let mk = |allow: bool, reason: String| AuthorityFreshnessVerdict {
956 allow,
957 tier: canonical_tier.to_string(),
958 reason,
959 };
960
961 if !rule.enforce_epoch && !rule.require_live_cosign {
962 return Ok(mk(true, "routine tier: time-decay only".into()));
963 }
964
965 if let Some(status) = current_status {
966 if status != STATUS_ACTIVE {
967 return Ok(mk(
968 false,
969 format!("authority_status_not_active:status={status}"),
970 ));
971 }
972 }
973
974 if rule.require_live_cosign && live_cosign_ok != Some(true) {
975 return Ok(mk(
976 false,
977 format!("live_cosign_required:tier={canonical_tier}"),
978 ));
979 }
980
981 if rule.enforce_epoch {
982 match (voucher_epoch, last_seen_epoch) {
991 (Some(v), Some(seen)) => {
992 if v < seen {
993 return Ok(mk(
994 false,
995 format!("authority_epoch_stale:seen={seen},voucher={v}"),
996 ));
997 }
998 }
999 _ => {
1000 return Ok(mk(
1003 false,
1004 format!(
1005 "authority_epoch_unknown:voucher={},seen={}",
1006 epoch_str(voucher_epoch),
1007 epoch_str(last_seen_epoch)
1008 ),
1009 ));
1010 }
1011 }
1012 }
1013
1014 Ok(mk(
1015 true,
1016 format!("{canonical_tier} tier: authority state fresh"),
1017 ))
1018}
1019
1020pub fn freshness_json(req: &Value) -> Result<Value> {
1025 let epoch = |name: &str| -> Result<Option<i64>> {
1026 match req.get(name).filter(|v| !v.is_null()) {
1027 None => Ok(None),
1028 Some(v) => v
1029 .as_i64()
1030 .filter(|e| (0..=MAX_AUTHORITY_EPOCH).contains(e))
1031 .map(Some)
1032 .ok_or_else(|| {
1033 CoreError::Json(format!("{name} must be a whole number from 0 to 2^53-1"))
1034 }),
1035 }
1036 };
1037 let wrong = |what: String| CoreError::Json(what);
1038 let tier = match req.get("tier") {
1039 Some(Value::String(t)) => t.as_str(),
1040 _ => return Err(wrong("tier must be text".into())),
1041 };
1042 let status = match req.get("currentStatus") {
1043 None | Some(Value::Null) => None,
1044 Some(Value::String(s)) => Some(s.as_str()),
1045 Some(_) => return Err(wrong("currentStatus must be text or null".into())),
1046 };
1047 let cosign = match req.get("liveCosignOk") {
1048 None | Some(Value::Null) => None,
1049 Some(Value::Bool(b)) => Some(*b),
1050 Some(_) => return Err(wrong("liveCosignOk must be true, false or null".into())),
1051 };
1052 let policy_map = match req.get("policy") {
1053 None | Some(Value::Null) => None,
1054 Some(Value::Object(map)) => Some(map),
1055 Some(_) => return Err(wrong("policy must be an object".into())),
1056 };
1057 let verdict = match policy_map {
1058 None => evaluate_authority_freshness(
1059 tier,
1060 epoch("voucherEpoch")?,
1061 epoch("lastSeenEpoch")?,
1062 status,
1063 cosign,
1064 )?,
1065 Some(map) => {
1066 let mut policy = BTreeMap::new();
1067 for (name, rule) in map {
1068 let flag = |k: &str| -> Result<bool> {
1069 rule.get(k)
1070 .and_then(Value::as_bool)
1071 .ok_or_else(|| wrong(format!("policy.{name}.{k} must be true or false")))
1072 };
1073 policy.insert(
1074 name.clone(),
1075 FreshnessRule {
1076 enforce_epoch: flag("enforceEpoch")?,
1077 require_live_cosign: flag("requireLiveCosign")?,
1078 },
1079 );
1080 }
1081 evaluate_authority_freshness_with(
1082 tier,
1083 epoch("voucherEpoch")?,
1084 epoch("lastSeenEpoch")?,
1085 status,
1086 cosign,
1087 &policy,
1088 )?
1089 }
1090 };
1091 Ok(json!({
1092 "allow": verdict.allow,
1093 "tier": verdict.tier,
1094 "reason": verdict.reason,
1095 }))
1096}
1097
1098pub fn rules_json(req: &Value) -> Result<Value> {
1107 let text = |name: &str| {
1108 req.get(name)
1109 .and_then(Value::as_str)
1110 .unwrap_or("")
1111 .to_string()
1112 };
1113 let parse = |t: &str| -> Result<Value> {
1114 serde_json::from_str(t).map_err(|e| CoreError::Json(e.to_string()))
1115 };
1116 match req.get("fn").and_then(Value::as_str).unwrap_or("") {
1117 "build" => {
1118 let epoch = match req.get("authorityEpoch") {
1119 Some(Value::Number(n)) => n.as_i64().ok_or_else(|| {
1120 CoreError::Json("authorityEpoch must be a whole number from 0 to 2^53-1".into())
1121 })?,
1122 _ => {
1123 return Err(CoreError::Json(
1124 "authorityEpoch must be a whole number from 0 to 2^53-1".into(),
1125 ))
1126 }
1127 };
1128 let opts = BuildAuthorityStateOptions {
1129 issuer_did: text("issuerDid"),
1130 credential_id: text("credentialId"),
1131 authority_epoch: epoch,
1132 status: text("status"),
1133 valid_from: text("validFrom"),
1134 valid_until: text("validUntil"),
1135 subject_did: req
1136 .get("subjectDid")
1137 .and_then(Value::as_str)
1138 .filter(|s| !s.is_empty())
1139 .map(str::to_string),
1140 };
1141 build_authority_state(&opts)
1142 }
1143 "verify" => {
1144 let cred_text = text("credential");
1145 check_epoch_literal(&cred_text)?;
1146 let key = {
1147 use base64::{engine::general_purpose::STANDARD, Engine};
1148 STANDARD
1149 .decode(text("publicKey"))
1150 .map_err(|e| CoreError::Json(format!("base64: {e}")))?
1151 };
1152 let skew = match req.get("clockSkewSeconds") {
1153 None | Some(Value::Null) => 30,
1154 Some(v) => crate::time::clock_skew_from_json(v)?,
1155 };
1156 let r = verify(&parse(&cred_text)?, &key, &text("now"), skew)?;
1157 Ok(
1158 json!({"proofValid": r.proof_valid, "timeValid": r.time_valid, "valid": r.is_valid()}),
1159 )
1160 }
1161 "readEpoch" => {
1162 let cred_text = text("credential");
1163 check_epoch_literal(&cred_text)?;
1164 Ok(json!(read_authority_epoch(&parse(&cred_text)?)?))
1165 }
1166 "readStatus" => Ok(json!(read_authority_status(&parse(&text("credential"))?)?)),
1167 "freshnessRule" => {
1168 let r = freshness_rule(&text("tier"));
1169 Ok(json!({"enforceEpoch": r.enforce_epoch, "requireLiveCosign": r.require_live_cosign}))
1170 }
1171 other => Err(CoreError::Json(format!(
1172 "unknown authority state rule {:?}",
1173 other.chars().take(40).collect::<String>()
1174 ))),
1175 }
1176}
1177
1178#[cfg(test)]
1179mod tests {
1180 use super::*;
1181
1182 #[test]
1183 fn freshness_options_are_read_strictly() {
1184 let ok = json!({"tier": "critical", "voucherEpoch": 3, "lastSeenEpoch": 3,
1185 "currentStatus": "active", "liveCosignOk": true});
1186 assert_eq!(freshness_json(&ok).unwrap()["allow"], json!(true));
1187 let policy = json!({"critical": {"enforceEpoch": true, "requireLiveCosign": false}});
1188 let mut with_policy = ok.clone();
1189 with_policy["policy"] = policy;
1190 assert_eq!(freshness_json(&with_policy).unwrap()["allow"], json!(true));
1191 for (name, value) in [
1192 ("tier", json!(null)),
1193 ("tier", json!(1)),
1194 ("currentStatus", json!(true)),
1195 ("liveCosignOk", json!("true")),
1196 ("liveCosignOk", json!(1)),
1197 ("policy", json!([])),
1198 (
1199 "policy",
1200 json!({"critical": {"enforceEpoch": "yes", "requireLiveCosign": false}}),
1201 ),
1202 ("policy", json!({"critical": {"enforceEpoch": true}})),
1203 (
1204 "policy",
1205 json!({"critical": {"requireLiveCosign": 0, "enforceEpoch": true}}),
1206 ),
1207 ] {
1208 let mut request = ok.clone();
1209 request[name] = value.clone();
1210 assert!(freshness_json(&request).is_err(), "{name} {value}");
1211 }
1212 let mut no_tier = ok.clone();
1213 no_tier.as_object_mut().unwrap().remove("tier");
1214 assert!(freshness_json(&no_tier).is_err());
1215 }
1216
1217 fn opts() -> BuildAuthorityStateOptions {
1218 BuildAuthorityStateOptions {
1219 issuer_did: "did:web:treasury.example.com".into(),
1220 credential_id: "urn:uuid:00000000-0000-4000-8000-000000000000".into(),
1221 authority_epoch: 7,
1222 status: STATUS_ACTIVE.into(),
1223 valid_from: "2026-07-26T10:00:00Z".into(),
1224 valid_until: "2026-07-26T10:05:00Z".into(),
1225 subject_did: None,
1226 }
1227 }
1228
1229 #[test]
1230 fn builds_expected_shape() {
1231 let vc = build_authority_state(&opts()).unwrap();
1232 assert_eq!(
1233 vc["type"],
1234 json!(["VerifiableCredential", "AuthorityState"])
1235 );
1236 assert_eq!(vc["credentialSubject"]["authorityEpoch"], json!(7));
1237 assert_eq!(vc["credentialSubject"]["status"], json!("active"));
1238 }
1239
1240 #[test]
1241 fn rejects_bad_status() {
1242 let mut o = opts();
1243 o.status = "bogus".into();
1244 assert!(build_authority_state(&o).is_err());
1245 }
1246
1247 #[test]
1248 fn sign_and_verify_within_window() {
1249 let seed = [7u8; 32];
1250 let proof_opts =
1251 BuildProofOptions::new("did:web:treasury.example.com#key-1", "2026-07-26T10:00:00Z");
1252 let signed = sign_authority_state(&opts(), &seed, &proof_opts).unwrap();
1253 let pk = crate::keys::Ed25519KeyPair::from_seed(&seed).public_key();
1254 let r = verify(&signed, &pk, "2026-07-26T10:02:00Z", 30).unwrap();
1255 assert!(r.is_valid());
1256 assert_eq!(read_authority_epoch(&signed).unwrap(), 7);
1257 assert_eq!(read_authority_status(&signed).unwrap(), "active");
1258 }
1259
1260 fn cred_with_epoch(text: &str) -> Value {
1261 serde_json::from_str(&format!(
1262 r#"{{"credentialSubject":{{"authorityEpoch":{text},"status":"active"}}}}"#
1263 ))
1264 .unwrap()
1265 }
1266
1267 #[test]
1268 fn epoch_must_be_an_integer_in_range() {
1269 assert_eq!(read_authority_epoch(&cred_with_epoch("0")).unwrap(), 0);
1270 assert_eq!(read_authority_epoch(&cred_with_epoch("-0")).unwrap(), 0);
1271 assert_eq!(
1272 read_authority_epoch(&cred_with_epoch("9007199254740991")).unwrap(),
1273 MAX_AUTHORITY_EPOCH
1274 );
1275 for bad in [
1276 "9007199254740992",
1277 "9223372036854775807",
1278 "18446744073709551616",
1279 "-1",
1280 "5.0",
1281 "5.5",
1282 "1e2",
1283 "\"5\"",
1284 "true",
1285 "null",
1286 ] {
1287 assert!(
1288 read_authority_epoch(&cred_with_epoch(bad)).is_err(),
1289 "{bad} must be refused"
1290 );
1291 }
1292 }
1293
1294 fn signed_with(mutate: impl Fn(&mut Value)) -> (Value, Vec<u8>) {
1295 let seed = [7u8; 32];
1296 let proof_opts =
1297 BuildProofOptions::new("did:web:treasury.example.com#key-1", "2026-07-26T10:00:00Z");
1298 let mut vc = build_authority_state(&opts()).unwrap();
1299 mutate(&mut vc);
1300 let signed = data_integrity::sign(&vc, &seed, &proof_opts).unwrap();
1301 let pk = crate::keys::Ed25519KeyPair::from_seed(&seed).public_key();
1302 (signed, pk.to_vec())
1303 }
1304
1305 #[test]
1306 fn verify_refuses_unbound_or_malformed_states() {
1307 let now = "2026-07-26T10:02:00Z";
1308 let ok = |m: &dyn Fn(&mut Value)| {
1309 let (c, pk) = signed_with(|v| m(v));
1310 verify(&c, &pk, now, 30)
1311 .map(|r| r.is_valid())
1312 .unwrap_or(false)
1313 };
1314 assert!(ok(&|_| {}));
1315 assert!(ok(&|v| v["type"] = json!("AuthorityState")));
1316 assert!(!ok(
1317 &|v| v["issuer"] = json!({"id": "did:web:treasury.example.com"})
1318 ));
1319 assert!(!ok(&|v| v["issuer"] = json!("did:web:other.example")));
1320 assert!(!ok(&|v| v["validFrom"] = Value::Null));
1321 assert!(!ok(&|v| v["validUntil"] = Value::Null));
1322 assert!(!ok(&|v| v["credentialSubject"]["status"] = json!("bogus")));
1323 assert!(!ok(
1324 &|v| v["credentialSubject"]["authorityEpoch"] = json!(5.5)
1325 ));
1326 assert!(!ok(&|v| v["credentialSubject"] = json!([])));
1327 }
1328
1329 #[test]
1330 fn epoch_literal_floats_are_refused() {
1331 let text = |lit: &str| {
1332 format!(r#"{{"credentialSubject":{{"authorityEpoch":{lit},"status":"active"}}}}"#)
1333 };
1334 for ok in ["0", "-0", "5", "9007199254740991"] {
1335 assert!(check_epoch_literal(&text(ok)).is_ok(), "{ok}");
1336 }
1337 for bad in ["-0.0", "0.0", "5.0", "1e2", "1E2", "-0e0", "5.5", "01"] {
1338 assert!(check_epoch_literal(&text(bad)).is_err(), "{bad}");
1339 }
1340 }
1341
1342 #[test]
1343 fn type_array_entries_must_be_strings() {
1344 let now = "2026-07-26T10:02:00Z";
1345 let (c, pk) = signed_with(|v| v["type"] = json!([1, "AuthorityState"]));
1346 assert!(verify(&c, &pk, now, 30).is_err());
1347 let (c, pk) = signed_with(|v| v["type"] = json!(["AuthorityState", null]));
1348 assert!(verify(&c, &pk, now, 30).is_err());
1349 }
1350
1351 #[test]
1352 fn freshness_refuses_out_of_range_epochs() {
1353 for bad in [-1, MAX_AUTHORITY_EPOCH + 1, i64::MIN, i64::MAX] {
1354 for tier in [
1355 CONSEQUENCE_ROUTINE,
1356 CONSEQUENCE_SENSITIVE,
1357 CONSEQUENCE_CRITICAL,
1358 ] {
1359 assert!(
1360 evaluate_authority_freshness(tier, Some(bad), Some(5), None, None).is_err()
1361 );
1362 assert!(
1363 evaluate_authority_freshness(tier, Some(5), Some(bad), None, None).is_err()
1364 );
1365 }
1366 }
1367 assert!(evaluate_authority_freshness(
1368 CONSEQUENCE_SENSITIVE,
1369 Some(MAX_AUTHORITY_EPOCH),
1370 Some(0),
1371 None,
1372 None
1373 )
1374 .is_ok());
1375 }
1376
1377 #[test]
1378 fn routine_ignores_stale_epoch() {
1379 let v = evaluate_authority_freshness(CONSEQUENCE_ROUTINE, Some(1), Some(9), None, None)
1380 .unwrap();
1381 assert!(v.allow);
1382 }
1383
1384 #[test]
1385 fn sensitive_rejects_stale_epoch() {
1386 let v = evaluate_authority_freshness(CONSEQUENCE_SENSITIVE, Some(5), Some(7), None, None)
1387 .unwrap();
1388 assert!(!v.allow);
1389 assert_eq!(v.reason, "authority_epoch_stale:seen=7,voucher=5");
1390 }
1391
1392 #[test]
1393 fn sensitive_rejects_unknown_epoch() {
1394 let v =
1397 evaluate_authority_freshness(CONSEQUENCE_SENSITIVE, None, Some(3), None, None).unwrap();
1398 assert!(!v.allow);
1399 assert_eq!(v.reason, "authority_epoch_unknown:voucher=?,seen=3");
1400 let v2 =
1401 evaluate_authority_freshness(CONSEQUENCE_SENSITIVE, Some(5), None, None, None).unwrap();
1402 assert_eq!(v2.reason, "authority_epoch_unknown:voucher=5,seen=?");
1403 }
1404
1405 #[test]
1406 fn sensitive_allows_current_epoch() {
1407 let v = evaluate_authority_freshness(CONSEQUENCE_SENSITIVE, Some(9), Some(9), None, None)
1408 .unwrap();
1409 assert!(v.allow);
1410 }
1411
1412 #[test]
1413 fn non_active_status_fails_closed() {
1414 let v = evaluate_authority_freshness(
1415 CONSEQUENCE_SENSITIVE,
1416 Some(9),
1417 Some(9),
1418 Some(STATUS_SUSPENDED),
1419 None,
1420 )
1421 .unwrap();
1422 assert!(!v.allow);
1423 assert_eq!(v.reason, "authority_status_not_active:status=suspended");
1424 }
1425
1426 #[test]
1427 fn critical_requires_live_cosign() {
1428 let denied =
1429 evaluate_authority_freshness(CONSEQUENCE_CRITICAL, Some(9), Some(9), None, None)
1430 .unwrap();
1431 assert!(!denied.allow);
1432 assert!(denied.reason.starts_with("live_cosign_required"));
1433 let allowed =
1434 evaluate_authority_freshness(CONSEQUENCE_CRITICAL, Some(9), Some(9), None, Some(true))
1435 .unwrap();
1436 assert!(allowed.allow);
1437 }
1438
1439 #[test]
1440 fn unknown_tier_coerces_to_critical() {
1441 let v = evaluate_authority_freshness("made-up", Some(9), Some(9), None, None).unwrap();
1442 assert_eq!(v.tier, "critical");
1443 assert!(!v.allow);
1444 }
1445
1446 #[test]
1447 fn whole_numbers_outside_64_bits_are_refused() {
1448 for text in [
1449 r#"{"a":18446744073709551616}"#,
1450 r#"{"a":-9223372036854775809}"#,
1451 r#"{"a":[1,2,99999999999999999999]}"#,
1452 ] {
1453 assert!(parse_json_no_duplicates(text).is_err(), "{text}");
1454 }
1455 for text in [
1456 r#"{"a":18446744073709551615}"#,
1457 r#"{"a":-9223372036854775808}"#,
1458 r#"{"a":1.8446744073709552e19}"#,
1459 r#"{"a":"18446744073709551616"}"#,
1460 r#"{"a\"":18446744073709551615}"#,
1461 ] {
1462 assert!(parse_json_no_duplicates(text).is_ok(), "{text}");
1463 }
1464 }
1465}