Skip to main content

vouch_core/
authority_state.rs

1//! Authority Freshness: authority state as a first-class input to trust freshness.
2//!
3//! Time-decay trust answers "how long ago was this trust established". That is
4//! not enough for a high-consequence agent whose mandate can be suspended
5//! seconds after a valid credential is issued. This module adds the state axis:
6//! a signed `AuthorityState` credential carrying a monotonic `authorityEpoch`
7//! and a `status`, plus the collapse rule that rejects a voucher minted under a
8//! stale epoch for a state-freshness action, even when its time-decay trust
9//! still passes.
10//!
11//! The credential is a plain VC Data Model 2.0 object signed with the shared
12//! `eddsa-jcs-2022` path, so it canonicalizes byte-identically across every
13//! language binding. This is the canonical implementation; the TypeScript, Go,
14//! and Python ports mirror it and share the interop vector in
15//! `test-vectors/authority-state/`.
16
17use 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
35// Refusal reasons of the authority-state-by-reference rules, the same text in
36// every language binding.
37pub 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";
40/// The largest AuthorityState a heartbeat carries or a validator takes (JCS
41/// bytes).
42pub 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
52// Consequence tiers, ordered by how much a stale authority view is tolerated.
53// Shared vocabulary with bounded-staleness revocation.
54pub 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
62/// Render an epoch for a reason code; "?" when absent, so the string is
63/// identical across every language binding.
64fn epoch_str(epoch: Option<i64>) -> String {
65    match epoch {
66        Some(e) => e.to_string(),
67        None => "?".to_string(),
68    }
69}
70
71/// Inputs to build an unsigned AuthorityState credential. Deterministic and
72/// clock-free: the caller supplies the id and validity window.
73#[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    /// The DID the state is about; defaults to `issuer_did` when None.
82    pub subject_did: Option<String>,
83}
84
85/// Construct an unsigned AuthorityState credential.
86pub 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
122/// Build and sign an AuthorityState credential in one step (eddsa-jcs-2022).
123pub 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
132/// The largest epoch every language binding can hold exactly (2^53 - 1).
133pub const MAX_AUTHORITY_EPOCH: i64 = (1 << 53) - 1;
134
135/// An epoch value read as the reference reads it: a whole number from 0 to
136/// 2^53 - 1. A float, a boolean, a string and a negative number are refused.
137/// `-0` reads as 0, as a JSON integer does in the reference.
138fn 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    // serde_json reads the literal `-0` as the float -0.0.
146    match n.as_f64() {
147        Some(f) if f == 0.0 && f.is_sign_negative() => Some(0),
148        _ => None,
149    }
150}
151
152/// Refuse an `authorityEpoch` written as a float literal (`-0.0`, `5.0`, `1e2`)
153/// in the credential's JSON text. A parsed `Value` cannot tell `-0` from `-0.0`,
154/// so a caller that holds the text runs this before `verify` or
155/// `read_authority_epoch`, as the reference refuses any float epoch. Text with
156/// no epoch literal passes here and is refused by the later shape check.
157pub 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
184/// The issuer DID as the reference reads it for an AuthorityState: a non-empty
185/// string, or the first entry of a non-empty list when that is one. An issuer
186/// object is refused.
187fn 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
196/// Verify an AuthorityState credential's Data Integrity proof and validity
197/// window. Same shape as `credentials::verify`: proof and time are reported
198/// separately so "bad signature" is distinguished from "expired".
199///
200/// `proof_valid` also requires the proof to be bound to the issuer: a single
201/// proof object with proofPurpose "assertionMethod" and a verificationMethod
202/// of the issuer's DID, the issuer being a string. A credential whose
203/// validFrom or validUntil is not a string, whose subject is not an object,
204/// or whose epoch or status is malformed is refused with an error.
205pub 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        // Every entry must be a string, as the reference requires.
213        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    // A did:key names its own key: nothing else can sign for it, whatever key
231    // the caller passed.
232    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    // The shape the reference enforces at verify time.
239    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    let time_valid = verify_temporal(credential, now_iso, clock_skew_seconds)?;
251    Ok(VerifyResult {
252        proof_valid: signature_valid && bound && own_key,
253        time_valid,
254        // An AuthorityState credential carries no delegation chain.
255        chain_valid: true,
256    })
257}
258
259/// Read `credentialSubject.authorityEpoch` without verifying the proof. For
260/// deciding which of two credentials is newer; never a substitute for `verify`.
261/// The epoch is a whole number from 0 to 2^53 - 1.
262pub fn read_authority_epoch(credential: &Value) -> Result<i64> {
263    credential
264        .get("credentialSubject")
265        .and_then(|s| s.get("authorityEpoch"))
266        .and_then(epoch_of)
267        .ok_or_else(|| CoreError::Json("missing or invalid authorityEpoch".into()))
268}
269
270/// Read `credentialSubject.status` without verifying the proof.
271pub fn read_authority_status(credential: &Value) -> Result<String> {
272    credential
273        .get("credentialSubject")
274        .and_then(|s| s.get("status"))
275        .and_then(|v| v.as_str())
276        .filter(|s| is_valid_status(s))
277        .map(|s| s.to_string())
278        .ok_or_else(|| CoreError::Json("missing or invalid status".into()))
279}
280
281// --------------------------------------------------------------------------- //
282// Authority state by reference: issuer binding, content digest, voucher fields
283// --------------------------------------------------------------------------- //
284
285/// The Ed25519 key a `did:key` DID names, or None (not a did:key, not
286/// Ed25519, or not decodable).
287pub fn did_key_ed25519(did: &str) -> Option<Vec<u8>> {
288    let mk = did.strip_prefix("did:key:")?;
289    let decoded = crate::multikey::decode(mk).ok()?;
290    (decoded.algorithm == "Ed25519" && decoded.raw_key.len() == 32).then_some(decoded.raw_key)
291}
292
293/// Parse JSON text with a key named twice in one object refused (JSON readers
294/// resolve that differently, so every reader must see the same object). NaN
295/// and Infinity are not JSON and are refused too.
296pub fn parse_json_no_duplicates(text: &str) -> Result<Value> {
297    struct NoDup(Value);
298    struct Visit;
299    impl<'de> serde::de::Visitor<'de> for Visit {
300        type Value = Value;
301        fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
302            f.write_str("JSON")
303        }
304        fn visit_bool<E>(self, v: bool) -> std::result::Result<Value, E> {
305            Ok(Value::Bool(v))
306        }
307        fn visit_i64<E>(self, v: i64) -> std::result::Result<Value, E> {
308            Ok(Value::from(v))
309        }
310        fn visit_u64<E>(self, v: u64) -> std::result::Result<Value, E> {
311            Ok(Value::from(v))
312        }
313        fn visit_f64<E: serde::de::Error>(self, v: f64) -> std::result::Result<Value, E> {
314            serde_json::Number::from_f64(v)
315                .map(Value::Number)
316                .ok_or_else(|| E::custom("a number that is not finite"))
317        }
318        fn visit_str<E>(self, v: &str) -> std::result::Result<Value, E> {
319            Ok(Value::String(v.to_owned()))
320        }
321        fn visit_string<E>(self, v: String) -> std::result::Result<Value, E> {
322            Ok(Value::String(v))
323        }
324        fn visit_unit<E>(self) -> std::result::Result<Value, E> {
325            Ok(Value::Null)
326        }
327        fn visit_seq<A: serde::de::SeqAccess<'de>>(
328            self,
329            mut seq: A,
330        ) -> std::result::Result<Value, A::Error> {
331            let mut out = Vec::new();
332            while let Some(NoDup(v)) = seq.next_element()? {
333                out.push(v);
334            }
335            Ok(Value::Array(out))
336        }
337        fn visit_map<A: serde::de::MapAccess<'de>>(
338            self,
339            mut map: A,
340        ) -> std::result::Result<Value, A::Error> {
341            let mut out = Map::new();
342            while let Some(key) = map.next_key::<String>()? {
343                if out.contains_key(&key) {
344                    return Err(serde::de::Error::custom(format!("duplicate key {key:?}")));
345                }
346                let NoDup(v) = map.next_value()?;
347                out.insert(key, v);
348            }
349            Ok(Value::Object(out))
350        }
351    }
352    impl<'de> serde::Deserialize<'de> for NoDup {
353        fn deserialize<D: serde::Deserializer<'de>>(d: D) -> std::result::Result<Self, D::Error> {
354            d.deserialize_any(Visit).map(NoDup)
355        }
356    }
357    serde_json::from_str::<NoDup>(text)
358        .map(|NoDup(v)| v)
359        .map_err(|e| CoreError::Json(e.to_string()))
360}
361
362/// Parse an AuthorityState sent as JSON text: duplicate keys refused (see
363/// [`parse_json_no_duplicates`]) and the epoch's literal checked
364/// ([`check_epoch_literal`]).
365pub fn parse_authority_state_text(text: &str) -> Result<Value> {
366    let value = parse_json_no_duplicates(text)?;
367    check_epoch_literal(text)?;
368    Ok(value)
369}
370
371/// The content digest of an AuthorityState: what a heartbeat signs as
372/// `authorityStateDigest` and a SessionVoucher records.
373///
374/// `"u" + base64url_nopad(0x12 0x20 || SHA-256(JCS(credential)))` over the
375/// credential without its `proof`, the same encoding as
376/// [`crate::grant_chain::grant_digest`]. Errors when the credential is not a
377/// JSON object.
378pub fn authority_state_digest(credential: &Value) -> Result<String> {
379    let Some(obj) = credential.as_object() else {
380        return Err(CoreError::Json(
381            "an AuthorityState must be a JSON object".into(),
382        ));
383    };
384    let mut body = obj.clone();
385    body.remove("proof");
386    crate::grant_chain::grant_digest(&Value::Object(body))
387        .map_err(|e| CoreError::Json(e.to_string()))
388}
389
390/// [`authority_state_digest`] of JSON text, parsed with duplicate keys refused.
391pub fn authority_state_digest_text(text: &str) -> Result<String> {
392    authority_state_digest(&parse_json_no_duplicates(text)?)
393}
394
395/// The error for an empty trusted-authority map or list: a configuration
396/// error in every language (it would trust no one while looking set up).
397pub const EMPTY_TRUSTED_AUTHORITIES: &str = "the trusted-authority list is empty: name at least one authority, or leave trusted_authorities out";
398
399fn empty_trusted_authorities() -> CoreError {
400    CoreError::Json(EMPTY_TRUSTED_AUTHORITIES.into())
401}
402
403/// Normalise trusted authorities to {authority DID: Ed25519 key}.
404///
405/// Each entry is a DID and an optional raw key. A did:key entry with no key
406/// takes the key its DID names; a did:key entry given another key is refused.
407/// An authority is always a DID bound to one key: a state counts only when it
408/// verifies under the key of the DID it names as its issuer. No entries at all
409/// is an error ([`EMPTY_TRUSTED_AUTHORITIES`]).
410pub fn trusted_authority_keys(
411    entries: &[(String, Option<Vec<u8>>)],
412) -> Result<BTreeMap<String, Vec<u8>>> {
413    if entries.is_empty() {
414        return Err(empty_trusted_authorities());
415    }
416    let mut out = BTreeMap::new();
417    for (did, key) in entries {
418        if !did.starts_with("did:") {
419            return Err(CoreError::Json(format!(
420                "trusted authority {did:?} is not a DID"
421            )));
422        }
423        let own = if did.starts_with("did:key:") {
424            did_key_ed25519(did)
425        } else {
426            None
427        };
428        let resolved = match key {
429            Some(k) if k.len() == 32 && crate::keys::strict_verifying_key(k).is_ok() => {
430                Some(k.clone())
431            }
432            Some(_) => None,
433            None => own.clone(),
434        };
435        let Some(resolved) = resolved else {
436            return Err(CoreError::Json(format!(
437                "trusted authority {did}: no usable Ed25519 key"
438            )));
439        };
440        if let Some(own) = own {
441            if own != resolved {
442                return Err(CoreError::Json(format!(
443                    "trusted authority {did}: the key is not the one its DID names"
444                )));
445            }
446        }
447        out.insert(did.clone(), resolved);
448    }
449    Ok(out)
450}
451
452/// The verified content of an AuthorityState credential.
453#[derive(Debug, Clone, PartialEq, Eq)]
454pub struct AuthorityStatePassport {
455    pub issuer_did: String,
456    pub subject_did: String,
457    pub authority_epoch: i64,
458    pub status: String,
459    pub valid_from: String,
460    pub valid_until: String,
461}
462
463impl AuthorityStatePassport {
464    pub fn is_active(&self) -> bool {
465        self.status == STATUS_ACTIVE
466    }
467
468    /// The passport as JSON: {issuerDid, subjectDid, authorityEpoch, status,
469    /// validFrom, validUntil}.
470    pub fn to_json(&self) -> Value {
471        json!({
472            "issuerDid": self.issuer_did,
473            "subjectDid": self.subject_did,
474            "authorityEpoch": self.authority_epoch,
475            "status": self.status,
476            "validFrom": self.valid_from,
477            "validUntil": self.valid_until,
478        })
479    }
480}
481
482/// Trusted authorities from JSON, for the bindings: an object {DID: base64
483/// raw Ed25519 key, or null for a did:key} or a list of did:key DIDs. See
484/// [`trusted_authority_keys`].
485pub fn trusted_authorities_from_json(value: &Value) -> Result<BTreeMap<String, Vec<u8>>> {
486    use base64::{engine::general_purpose::STANDARD, Engine};
487    let mut entries: Vec<(String, Option<Vec<u8>>)> = Vec::new();
488    match value {
489        Value::Object(map) => {
490            for (did, key) in map {
491                let key = match key {
492                    Value::Null => None,
493                    Value::String(k) => Some(STANDARD.decode(k).map_err(|_| {
494                        CoreError::Json(format!("trusted authority {did}: the key is not base64"))
495                    })?),
496                    _ => {
497                        return Err(CoreError::Json(format!(
498                            "trusted authority {did}: the key must be base64 text or null"
499                        )))
500                    }
501                };
502                entries.push((did.clone(), key));
503            }
504        }
505        Value::Array(list) => {
506            for did in list {
507                let Some(did) = did.as_str() else {
508                    return Err(CoreError::Json("trusted authorities must be DIDs".into()));
509                };
510                entries.push((did.to_string(), None));
511            }
512        }
513        _ => {
514            return Err(CoreError::Json(
515                "trusted authorities must be {DID: key} or a list of did:key DIDs".into(),
516            ))
517        }
518    }
519    trusted_authority_keys(&entries)
520}
521
522/// A voucher's authority record as JSON ({digest, epoch, status, issuer}), or
523/// null.
524pub fn voucher_authority_json(voucher: &Value) -> Value {
525    match voucher_authority(voucher) {
526        Some(a) => json!({
527            "digest": a.digest,
528            "epoch": a.epoch,
529            "status": a.status,
530            "issuer": a.issuer,
531        }),
532        None => Value::Null,
533    }
534}
535
536/// Verify an AuthorityState under its own issuer's key.
537///
538/// - With `trusted_authorities` ({DID: key}, see [`trusted_authority_keys`])
539///   the key is the one trusted for the DID the state names as its issuer,
540///   and a state from any other issuer is refused (`public_key` is then not
541///   used).
542/// - With `public_key`, pass `issuer_did` too: the state must name that
543///   issuer. Without `issuer_did`, the key is taken as the issuer's on the
544///   caller's word (the old form, for callers that bind it themselves).
545/// - With neither, only a did:key issuer verifies, under the key its DID
546///   names.
547///
548/// A did:key issuer's state verifies only under its own key, whatever key is
549/// passed. Returns the passport, or None for any refusal (however malformed
550/// the credential). Errors when `clock_skew_seconds` is not 0 to 120, and
551/// when `trusted_authorities` is an empty map (a configuration error).
552pub fn verify_authority_state_bound(
553    credential: &Value,
554    public_key: Option<&[u8]>,
555    trusted_authorities: Option<&BTreeMap<String, Vec<u8>>>,
556    issuer_did: Option<&str>,
557    now_iso: &str,
558    clock_skew_seconds: i64,
559) -> Result<Option<AuthorityStatePassport>> {
560    crate::time::check_clock_skew(clock_skew_seconds)?;
561    if trusted_authorities.is_some_and(BTreeMap::is_empty) {
562        return Err(empty_trusted_authorities());
563    }
564    if !credential.is_object() {
565        return Ok(None);
566    }
567    let Some(claimed) = authority_issuer(credential) else {
568        return Ok(None);
569    };
570    if issuer_did.is_some_and(|expected| expected != claimed) {
571        return Ok(None);
572    }
573    let key: Vec<u8> = if let Some(trusted) = trusted_authorities {
574        match trusted.get(claimed) {
575            Some(k) => k.clone(),
576            None => return Ok(None),
577        }
578    } else if let Some(k) = public_key {
579        k.to_vec()
580    } else {
581        match did_key_ed25519(claimed) {
582            Some(k) => k,
583            None => return Ok(None),
584        }
585    };
586    let Ok(result) = verify(credential, &key, now_iso, clock_skew_seconds) else {
587        return Ok(None);
588    };
589    if !result.is_valid() {
590        return Ok(None);
591    }
592    let (Ok(epoch), Ok(status)) = (
593        read_authority_epoch(credential),
594        read_authority_status(credential),
595    ) else {
596        return Ok(None);
597    };
598    let subject_did = credential["credentialSubject"]
599        .get("id")
600        .and_then(Value::as_str)
601        .filter(|s| !s.is_empty())
602        .unwrap_or(claimed)
603        .to_string();
604    Ok(Some(AuthorityStatePassport {
605        issuer_did: claimed.to_string(),
606        subject_did,
607        authority_epoch: epoch,
608        status,
609        valid_from: credential["validFrom"]
610            .as_str()
611            .unwrap_or_default()
612            .to_string(),
613        valid_until: credential["validUntil"]
614            .as_str()
615            .unwrap_or_default()
616            .to_string(),
617    }))
618}
619
620/// [`verify_authority_state_bound`] on JSON text: text with a key named twice,
621/// or an epoch written as a float literal, is refused (None).
622pub fn verify_authority_state_bound_text(
623    credential_text: &str,
624    public_key: Option<&[u8]>,
625    trusted_authorities: Option<&BTreeMap<String, Vec<u8>>>,
626    issuer_did: Option<&str>,
627    now_iso: &str,
628    clock_skew_seconds: i64,
629) -> Result<Option<AuthorityStatePassport>> {
630    crate::time::check_clock_skew(clock_skew_seconds)?;
631    if trusted_authorities.is_some_and(BTreeMap::is_empty) {
632        return Err(empty_trusted_authorities());
633    }
634    let Ok(credential) = parse_authority_state_text(credential_text) else {
635        return Ok(None);
636    };
637    verify_authority_state_bound(
638        &credential,
639        public_key,
640        trusted_authorities,
641        issuer_did,
642        now_iso,
643        clock_skew_seconds,
644    )
645}
646
647/// The fields a SessionVoucher records from a verified AuthorityState: all
648/// four or none. A lone `authorityEpoch` (written by validators before
649/// authority state by reference) is an agent's own claim: it is ignored,
650/// never trusted.
651pub const VOUCHER_AUTHORITY_FIELDS: [&str; 4] = [
652    "authorityStateDigest",
653    "authorityEpoch",
654    "authorityStatus",
655    "authorityIssuer",
656];
657
658/// Why a voucher's authority fields (in its `credentialSubject`) are not well
659/// formed, or None. A voucher verifier refuses such a voucher as
660/// `voucher_malformed:<problem>`. The epoch's own range is checked apart, as
661/// for any voucher epoch.
662pub fn voucher_authority_problem(subject: &Value) -> Option<String> {
663    let obj = subject.as_object()?;
664    let present: Vec<&str> = VOUCHER_AUTHORITY_FIELDS
665        .iter()
666        .copied()
667        .filter(|name| obj.contains_key(*name))
668        .collect();
669    if present.is_empty() || present == ["authorityEpoch"] {
670        return None;
671    }
672    if present.len() != VOUCHER_AUTHORITY_FIELDS.len() {
673        return Some("the authority fields must be all present or all absent".into());
674    }
675    for name in ["authorityStateDigest", "authorityStatus", "authorityIssuer"] {
676        if obj[name].as_str().is_none_or(str::is_empty) {
677            return Some(format!("{name} must be a non-empty string"));
678        }
679    }
680    None
681}
682
683/// The authority record of a SessionVoucher.
684#[derive(Debug, Clone, PartialEq, Eq)]
685pub struct VoucherAuthority {
686    pub digest: String,
687    pub epoch: i64,
688    pub status: String,
689    pub issuer: String,
690}
691
692/// The authority record of a voucher, or None when it carries none. A lone
693/// `authorityEpoch` counts as none: a voucher's epoch counts only with its
694/// `authorityStateDigest` (a state the validator verified). Read only after
695/// the voucher verified.
696pub fn voucher_authority(voucher: &Value) -> Option<VoucherAuthority> {
697    let subject = voucher.get("credentialSubject")?;
698    let obj = subject.as_object()?;
699    if voucher_authority_problem(subject).is_some() || !obj.contains_key("authorityStateDigest") {
700        return None;
701    }
702    Some(VoucherAuthority {
703        digest: obj["authorityStateDigest"].as_str()?.to_string(),
704        epoch: epoch_of(&obj["authorityEpoch"])?,
705        status: obj["authorityStatus"].as_str()?.to_string(),
706        issuer: obj["authorityIssuer"].as_str()?.to_string(),
707    })
708}
709
710/// The epoch a verifier may take from a voucher for Authority Freshness: the
711/// recorded one, or None for a voucher without the four authority fields.
712pub fn voucher_authority_epoch(voucher: &Value) -> Option<i64> {
713    voucher_authority(voucher).map(|a| a.epoch)
714}
715
716/// Check the AuthorityState attached to a call against the trusted
717/// authorities and the call's voucher, as a verifier does before Authority
718/// Freshness:
719///
720/// - no state, or one that is not a JSON object: `authority_state_missing`;
721/// - its issuer is not a trusted authority: `authority_issuer_untrusted`;
722/// - it does not verify under that issuer's key, or its subject is not the
723///   caller: `authority_state_missing`;
724/// - the voucher records no authority, another digest or another issuer:
725///   `authority_state_digest_mismatch`.
726///
727/// On success the passport's epoch and status are what Authority Freshness
728/// compares; an epoch is never learned from a voucher. The outer error is a
729/// clock skew outside 0 to 120, or an empty `trusted_authorities` (a
730/// configuration error).
731pub fn check_attached_authority_state(
732    state: Option<&Value>,
733    trusted_authorities: &BTreeMap<String, Vec<u8>>,
734    voucher: Option<&Value>,
735    caller: Option<&str>,
736    now_iso: &str,
737    clock_skew_seconds: i64,
738) -> Result<std::result::Result<AuthorityStatePassport, &'static str>> {
739    crate::time::check_clock_skew(clock_skew_seconds)?;
740    if trusted_authorities.is_empty() {
741        return Err(empty_trusted_authorities());
742    }
743    let Some(state) = state.filter(|s| s.is_object()) else {
744        return Ok(Err(AUTHORITY_STATE_MISSING));
745    };
746    let Some(issuer) = authority_issuer(state).filter(|i| trusted_authorities.contains_key(*i))
747    else {
748        return Ok(Err(AUTHORITY_ISSUER_UNTRUSTED));
749    };
750    let passport = verify_authority_state_bound(
751        state,
752        None,
753        Some(trusted_authorities),
754        None,
755        now_iso,
756        clock_skew_seconds,
757    )?;
758    let Some(passport) = passport.filter(|p| caller == Some(p.subject_did.as_str())) else {
759        return Ok(Err(AUTHORITY_STATE_MISSING));
760    };
761    let Ok(digest) = authority_state_digest(state) else {
762        return Ok(Err(AUTHORITY_STATE_MISSING));
763    };
764    match voucher.and_then(voucher_authority) {
765        Some(recorded) if recorded.digest == digest && recorded.issuer == issuer => {
766            Ok(Ok(passport))
767        }
768        _ => Ok(Err(AUTHORITY_STATE_DIGEST_MISMATCH)),
769    }
770}
771
772/// [`check_attached_authority_state`] with the state as JSON text: text that
773/// does not parse (a key named twice included) is `authority_state_missing`.
774pub fn check_attached_authority_state_text(
775    state_text: Option<&str>,
776    trusted_authorities: &BTreeMap<String, Vec<u8>>,
777    voucher: Option<&Value>,
778    caller: Option<&str>,
779    now_iso: &str,
780    clock_skew_seconds: i64,
781) -> Result<std::result::Result<AuthorityStatePassport, &'static str>> {
782    crate::time::check_clock_skew(clock_skew_seconds)?;
783    if trusted_authorities.is_empty() {
784        return Err(empty_trusted_authorities());
785    }
786    let parsed = match state_text {
787        None => None,
788        Some(text) => match parse_authority_state_text(text) {
789            Ok(v) => Some(v),
790            Err(_) => return Ok(Err(AUTHORITY_STATE_MISSING)),
791        },
792    };
793    check_attached_authority_state(
794        parsed.as_ref(),
795        trusted_authorities,
796        voucher,
797        caller,
798        now_iso,
799        clock_skew_seconds,
800    )
801}
802
803/// How a consequence tier treats authority state.
804#[derive(Debug, Clone, Copy, PartialEq, Eq)]
805pub struct FreshnessRule {
806    pub enforce_epoch: bool,
807    pub require_live_cosign: bool,
808}
809
810/// The consequence -> policy map. Unknown tiers coerce to the strictest rule.
811pub fn freshness_rule(tier: &str) -> FreshnessRule {
812    match tier {
813        CONSEQUENCE_ROUTINE => FreshnessRule {
814            enforce_epoch: false,
815            require_live_cosign: false,
816        },
817        CONSEQUENCE_SENSITIVE => FreshnessRule {
818            enforce_epoch: true,
819            require_live_cosign: false,
820        },
821        // critical and any unknown tier
822        _ => FreshnessRule {
823            enforce_epoch: true,
824            require_live_cosign: true,
825        },
826    }
827}
828
829/// The outcome of an Authority Freshness evaluation.
830#[derive(Debug, Clone, PartialEq, Eq)]
831pub struct AuthorityFreshnessVerdict {
832    pub allow: bool,
833    pub tier: String,
834    pub reason: String,
835}
836
837/// Decide whether an action passes the Authority Freshness gate.
838///
839/// `voucher_epoch` and `last_seen_epoch` are None when unknown. `current_status`
840/// is None when the verifier does not hold a current AuthorityState.
841/// `live_cosign_ok` is the verified-fresh state of a live co-sign, for the
842/// critical tier only.
843///
844/// An epoch below 0 or above 2^53 - 1 is refused with an error, as the
845/// reference refuses it.
846pub fn evaluate_authority_freshness(
847    tier: &str,
848    voucher_epoch: Option<i64>,
849    last_seen_epoch: Option<i64>,
850    current_status: Option<&str>,
851    live_cosign_ok: Option<bool>,
852) -> Result<AuthorityFreshnessVerdict> {
853    for (name, e) in [
854        ("voucher_epoch", voucher_epoch),
855        ("last_seen_epoch", last_seen_epoch),
856    ] {
857        if let Some(e) = e {
858            if !(0..=MAX_AUTHORITY_EPOCH).contains(&e) {
859                return Err(CoreError::Json(format!(
860                    "{name} must be a whole number from 0 to 2^53 - 1"
861                )));
862            }
863        }
864    }
865    let canonical_tier = match tier {
866        CONSEQUENCE_ROUTINE | CONSEQUENCE_SENSITIVE | CONSEQUENCE_CRITICAL => tier,
867        _ => CONSEQUENCE_CRITICAL,
868    };
869    let rule = freshness_rule(canonical_tier);
870    let mk = |allow: bool, reason: String| AuthorityFreshnessVerdict {
871        allow,
872        tier: canonical_tier.to_string(),
873        reason,
874    };
875
876    if !rule.enforce_epoch && !rule.require_live_cosign {
877        return Ok(mk(true, "routine tier: time-decay only".into()));
878    }
879
880    if let Some(status) = current_status {
881        if status != STATUS_ACTIVE {
882            return Ok(mk(
883                false,
884                format!("authority_status_not_active:status={status}"),
885            ));
886        }
887    }
888
889    if rule.require_live_cosign && live_cosign_ok != Some(true) {
890        return Ok(mk(
891            false,
892            format!("live_cosign_required:tier={canonical_tier}"),
893        ));
894    }
895
896    if rule.enforce_epoch {
897        // Why an epoch and not a fresher timestamp: a timestamp says when the
898        // voucher was minted, never whether authority has changed since, so time
899        // alone forces the verifier to guess a safe staleness window. A new epoch
900        // is proof that a real transition happened, published and signed by the
901        // authority. A voucher minted under epoch 7 is refused once this verifier
902        // has seen epoch 8, even six seconds later with time-decay trust still
903        // passing. The limit: this only bites once the verifier has learned of the
904        // newer epoch, which is why the critical tier falls back to a live co-sign.
905        match (voucher_epoch, last_seen_epoch) {
906            (Some(v), Some(seen)) => {
907                if v < seen {
908                    return Ok(mk(
909                        false,
910                        format!("authority_epoch_stale:seen={seen},voucher={v}"),
911                    ));
912                }
913            }
914            _ => {
915                // An absent epoch renders as "?" so the reason code is identical
916                // in every language binding. Pinned by the interop vector.
917                return Ok(mk(
918                    false,
919                    format!(
920                        "authority_epoch_unknown:voucher={},seen={}",
921                        epoch_str(voucher_epoch),
922                        epoch_str(last_seen_epoch)
923                    ),
924                ));
925            }
926        }
927    }
928
929    Ok(mk(
930        true,
931        format!("{canonical_tier} tier: authority state fresh"),
932    ))
933}
934
935#[cfg(test)]
936mod tests {
937    use super::*;
938
939    fn opts() -> BuildAuthorityStateOptions {
940        BuildAuthorityStateOptions {
941            issuer_did: "did:web:treasury.example.com".into(),
942            credential_id: "urn:uuid:00000000-0000-4000-8000-000000000000".into(),
943            authority_epoch: 7,
944            status: STATUS_ACTIVE.into(),
945            valid_from: "2026-07-26T10:00:00Z".into(),
946            valid_until: "2026-07-26T10:05:00Z".into(),
947            subject_did: None,
948        }
949    }
950
951    #[test]
952    fn builds_expected_shape() {
953        let vc = build_authority_state(&opts()).unwrap();
954        assert_eq!(
955            vc["type"],
956            json!(["VerifiableCredential", "AuthorityState"])
957        );
958        assert_eq!(vc["credentialSubject"]["authorityEpoch"], json!(7));
959        assert_eq!(vc["credentialSubject"]["status"], json!("active"));
960    }
961
962    #[test]
963    fn rejects_bad_status() {
964        let mut o = opts();
965        o.status = "bogus".into();
966        assert!(build_authority_state(&o).is_err());
967    }
968
969    #[test]
970    fn sign_and_verify_within_window() {
971        let seed = [7u8; 32];
972        let proof_opts =
973            BuildProofOptions::new("did:web:treasury.example.com#key-1", "2026-07-26T10:00:00Z");
974        let signed = sign_authority_state(&opts(), &seed, &proof_opts).unwrap();
975        let pk = crate::keys::Ed25519KeyPair::from_seed(&seed).public_key();
976        let r = verify(&signed, &pk, "2026-07-26T10:02:00Z", 30).unwrap();
977        assert!(r.is_valid());
978        assert_eq!(read_authority_epoch(&signed).unwrap(), 7);
979        assert_eq!(read_authority_status(&signed).unwrap(), "active");
980    }
981
982    fn cred_with_epoch(text: &str) -> Value {
983        serde_json::from_str(&format!(
984            r#"{{"credentialSubject":{{"authorityEpoch":{text},"status":"active"}}}}"#
985        ))
986        .unwrap()
987    }
988
989    #[test]
990    fn epoch_must_be_an_integer_in_range() {
991        assert_eq!(read_authority_epoch(&cred_with_epoch("0")).unwrap(), 0);
992        assert_eq!(read_authority_epoch(&cred_with_epoch("-0")).unwrap(), 0);
993        assert_eq!(
994            read_authority_epoch(&cred_with_epoch("9007199254740991")).unwrap(),
995            MAX_AUTHORITY_EPOCH
996        );
997        for bad in [
998            "9007199254740992",
999            "9223372036854775807",
1000            "18446744073709551616",
1001            "-1",
1002            "5.0",
1003            "5.5",
1004            "1e2",
1005            "\"5\"",
1006            "true",
1007            "null",
1008        ] {
1009            assert!(
1010                read_authority_epoch(&cred_with_epoch(bad)).is_err(),
1011                "{bad} must be refused"
1012            );
1013        }
1014    }
1015
1016    fn signed_with(mutate: impl Fn(&mut Value)) -> (Value, Vec<u8>) {
1017        let seed = [7u8; 32];
1018        let proof_opts =
1019            BuildProofOptions::new("did:web:treasury.example.com#key-1", "2026-07-26T10:00:00Z");
1020        let mut vc = build_authority_state(&opts()).unwrap();
1021        mutate(&mut vc);
1022        let signed = data_integrity::sign(&vc, &seed, &proof_opts).unwrap();
1023        let pk = crate::keys::Ed25519KeyPair::from_seed(&seed).public_key();
1024        (signed, pk.to_vec())
1025    }
1026
1027    #[test]
1028    fn verify_refuses_unbound_or_malformed_states() {
1029        let now = "2026-07-26T10:02:00Z";
1030        let ok = |m: &dyn Fn(&mut Value)| {
1031            let (c, pk) = signed_with(|v| m(v));
1032            verify(&c, &pk, now, 30)
1033                .map(|r| r.is_valid())
1034                .unwrap_or(false)
1035        };
1036        assert!(ok(&|_| {}));
1037        assert!(ok(&|v| v["type"] = json!("AuthorityState")));
1038        assert!(!ok(
1039            &|v| v["issuer"] = json!({"id": "did:web:treasury.example.com"})
1040        ));
1041        assert!(!ok(&|v| v["issuer"] = json!("did:web:other.example")));
1042        assert!(!ok(&|v| v["validFrom"] = Value::Null));
1043        assert!(!ok(&|v| v["validUntil"] = Value::Null));
1044        assert!(!ok(&|v| v["credentialSubject"]["status"] = json!("bogus")));
1045        assert!(!ok(
1046            &|v| v["credentialSubject"]["authorityEpoch"] = json!(5.5)
1047        ));
1048        assert!(!ok(&|v| v["credentialSubject"] = json!([])));
1049    }
1050
1051    #[test]
1052    fn epoch_literal_floats_are_refused() {
1053        let text = |lit: &str| {
1054            format!(r#"{{"credentialSubject":{{"authorityEpoch":{lit},"status":"active"}}}}"#)
1055        };
1056        for ok in ["0", "-0", "5", "9007199254740991"] {
1057            assert!(check_epoch_literal(&text(ok)).is_ok(), "{ok}");
1058        }
1059        for bad in ["-0.0", "0.0", "5.0", "1e2", "1E2", "-0e0", "5.5", "01"] {
1060            assert!(check_epoch_literal(&text(bad)).is_err(), "{bad}");
1061        }
1062    }
1063
1064    #[test]
1065    fn type_array_entries_must_be_strings() {
1066        let now = "2026-07-26T10:02:00Z";
1067        let (c, pk) = signed_with(|v| v["type"] = json!([1, "AuthorityState"]));
1068        assert!(verify(&c, &pk, now, 30).is_err());
1069        let (c, pk) = signed_with(|v| v["type"] = json!(["AuthorityState", null]));
1070        assert!(verify(&c, &pk, now, 30).is_err());
1071    }
1072
1073    #[test]
1074    fn freshness_refuses_out_of_range_epochs() {
1075        for bad in [-1, MAX_AUTHORITY_EPOCH + 1, i64::MIN, i64::MAX] {
1076            for tier in [
1077                CONSEQUENCE_ROUTINE,
1078                CONSEQUENCE_SENSITIVE,
1079                CONSEQUENCE_CRITICAL,
1080            ] {
1081                assert!(
1082                    evaluate_authority_freshness(tier, Some(bad), Some(5), None, None).is_err()
1083                );
1084                assert!(
1085                    evaluate_authority_freshness(tier, Some(5), Some(bad), None, None).is_err()
1086                );
1087            }
1088        }
1089        assert!(evaluate_authority_freshness(
1090            CONSEQUENCE_SENSITIVE,
1091            Some(MAX_AUTHORITY_EPOCH),
1092            Some(0),
1093            None,
1094            None
1095        )
1096        .is_ok());
1097    }
1098
1099    #[test]
1100    fn routine_ignores_stale_epoch() {
1101        let v = evaluate_authority_freshness(CONSEQUENCE_ROUTINE, Some(1), Some(9), None, None)
1102            .unwrap();
1103        assert!(v.allow);
1104    }
1105
1106    #[test]
1107    fn sensitive_rejects_stale_epoch() {
1108        let v = evaluate_authority_freshness(CONSEQUENCE_SENSITIVE, Some(5), Some(7), None, None)
1109            .unwrap();
1110        assert!(!v.allow);
1111        assert_eq!(v.reason, "authority_epoch_stale:seen=7,voucher=5");
1112    }
1113
1114    #[test]
1115    fn sensitive_rejects_unknown_epoch() {
1116        // An absent epoch renders as "?" so the reason code is identical in
1117        // every language binding. Pinned by the shared interop vector.
1118        let v =
1119            evaluate_authority_freshness(CONSEQUENCE_SENSITIVE, None, Some(3), None, None).unwrap();
1120        assert!(!v.allow);
1121        assert_eq!(v.reason, "authority_epoch_unknown:voucher=?,seen=3");
1122        let v2 =
1123            evaluate_authority_freshness(CONSEQUENCE_SENSITIVE, Some(5), None, None, None).unwrap();
1124        assert_eq!(v2.reason, "authority_epoch_unknown:voucher=5,seen=?");
1125    }
1126
1127    #[test]
1128    fn sensitive_allows_current_epoch() {
1129        let v = evaluate_authority_freshness(CONSEQUENCE_SENSITIVE, Some(9), Some(9), None, None)
1130            .unwrap();
1131        assert!(v.allow);
1132    }
1133
1134    #[test]
1135    fn non_active_status_fails_closed() {
1136        let v = evaluate_authority_freshness(
1137            CONSEQUENCE_SENSITIVE,
1138            Some(9),
1139            Some(9),
1140            Some(STATUS_SUSPENDED),
1141            None,
1142        )
1143        .unwrap();
1144        assert!(!v.allow);
1145        assert_eq!(v.reason, "authority_status_not_active:status=suspended");
1146    }
1147
1148    #[test]
1149    fn critical_requires_live_cosign() {
1150        let denied =
1151            evaluate_authority_freshness(CONSEQUENCE_CRITICAL, Some(9), Some(9), None, None)
1152                .unwrap();
1153        assert!(!denied.allow);
1154        assert!(denied.reason.starts_with("live_cosign_required"));
1155        let allowed =
1156            evaluate_authority_freshness(CONSEQUENCE_CRITICAL, Some(9), Some(9), None, Some(true))
1157                .unwrap();
1158        assert!(allowed.allow);
1159    }
1160
1161    #[test]
1162    fn unknown_tier_coerces_to_critical() {
1163        let v = evaluate_authority_freshness("made-up", Some(9), Some(9), None, None).unwrap();
1164        assert_eq!(v.tier, "critical");
1165        assert!(!v.allow);
1166    }
1167}