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
17#[allow(unused_imports)]
18use crate::prelude::*;
19
20use alloc::collections::BTreeMap;
21
22use serde_json::{json, Map, Value};
23
24use crate::credentials::{
25    proof_bound_to_issuer, verify_temporal, VerifyResult, VC_CONTEXT_V2, VC_TYPE, VOUCH_CONTEXT_V1,
26};
27use crate::data_integrity::{self, BuildProofOptions};
28use crate::error::{CoreError, Result};
29
30pub const AUTHORITY_STATE_TYPE: &str = "AuthorityState";
31
32pub const STATUS_ACTIVE: &str = "active";
33pub const STATUS_SUSPENDED: &str = "suspended";
34pub const STATUS_INCIDENT: &str = "incident";
35pub const STATUS_EXPOSURE_BREACHED: &str = "exposure_breached";
36pub const STATUS_REVOKED: &str = "revoked";
37
38// Refusal reasons of the authority-state-by-reference rules, the same text in
39// every language binding.
40pub const AUTHORITY_STATE_MISSING: &str = "authority_state_missing";
41pub const AUTHORITY_STATE_DIGEST_MISMATCH: &str = "authority_state_digest_mismatch";
42pub const AUTHORITY_ISSUER_UNTRUSTED: &str = "authority_issuer_untrusted";
43/// The largest AuthorityState a heartbeat carries or a validator takes (JCS
44/// bytes).
45pub const MAX_AUTHORITY_STATE_BYTES: usize = 8192;
46
47pub const VALID_AUTHORITY_STATUSES: [&str; 5] = [
48    STATUS_ACTIVE,
49    STATUS_SUSPENDED,
50    STATUS_INCIDENT,
51    STATUS_EXPOSURE_BREACHED,
52    STATUS_REVOKED,
53];
54
55// Consequence tiers, ordered by how much a stale authority view is tolerated.
56// Shared vocabulary with bounded-staleness revocation.
57pub const CONSEQUENCE_ROUTINE: &str = "routine";
58pub const CONSEQUENCE_SENSITIVE: &str = "sensitive";
59pub const CONSEQUENCE_CRITICAL: &str = "critical";
60
61fn is_valid_status(status: &str) -> bool {
62    VALID_AUTHORITY_STATUSES.contains(&status)
63}
64
65/// Render an epoch for a reason code; "?" when absent, so the string is
66/// identical across every language binding.
67fn epoch_str(epoch: Option<i64>) -> String {
68    match epoch {
69        Some(e) => e.to_string(),
70        None => "?".to_string(),
71    }
72}
73
74/// Inputs to build an unsigned AuthorityState credential. Deterministic and
75/// clock-free: the caller supplies the id and validity window.
76#[derive(Debug, Clone)]
77pub struct BuildAuthorityStateOptions {
78    pub issuer_did: String,
79    pub credential_id: String,
80    pub authority_epoch: i64,
81    pub status: String,
82    pub valid_from: String,
83    pub valid_until: String,
84    /// The DID the state is about; defaults to `issuer_did` when None.
85    pub subject_did: Option<String>,
86}
87
88/// Construct an unsigned AuthorityState credential.
89pub fn build_authority_state(opts: &BuildAuthorityStateOptions) -> Result<Value> {
90    if !(0..=MAX_AUTHORITY_EPOCH).contains(&opts.authority_epoch) {
91        return Err(CoreError::Json(
92            "authorityEpoch must be a whole number from 0 to 2^53-1".into(),
93        ));
94    }
95    if !is_valid_status(&opts.status) {
96        return Err(CoreError::Json(format!(
97            "status must be one of {VALID_AUTHORITY_STATUSES:?}"
98        )));
99    }
100    if opts.issuer_did.is_empty() {
101        return Err(CoreError::Json("issuer_did is required".into()));
102    }
103
104    let subject_did = opts
105        .subject_did
106        .clone()
107        .unwrap_or_else(|| opts.issuer_did.clone());
108
109    let mut subject = Map::new();
110    subject.insert("id".into(), json!(subject_did));
111    subject.insert("authorityEpoch".into(), json!(opts.authority_epoch));
112    subject.insert("status".into(), json!(opts.status));
113
114    let mut vc = Map::new();
115    vc.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
116    vc.insert("id".into(), json!(opts.credential_id));
117    vc.insert("type".into(), json!([VC_TYPE, AUTHORITY_STATE_TYPE]));
118    vc.insert("issuer".into(), json!(opts.issuer_did));
119    vc.insert("validFrom".into(), json!(opts.valid_from));
120    vc.insert("validUntil".into(), json!(opts.valid_until));
121    vc.insert("credentialSubject".into(), Value::Object(subject));
122    Ok(Value::Object(vc))
123}
124
125/// Build and sign an AuthorityState credential in one step (eddsa-jcs-2022).
126pub fn sign_authority_state(
127    opts: &BuildAuthorityStateOptions,
128    raw_private_seed: &[u8],
129    proof_opts: &BuildProofOptions,
130) -> Result<Value> {
131    let cred = build_authority_state(opts)?;
132    data_integrity::sign(&cred, raw_private_seed, proof_opts)
133}
134
135/// The largest epoch every language binding can hold exactly (2^53 - 1).
136pub const MAX_AUTHORITY_EPOCH: i64 = (1 << 53) - 1;
137
138/// An epoch value read as the reference reads it: a whole number from 0 to
139/// 2^53 - 1. A float, a boolean, a string and a negative number are refused.
140/// `-0` reads as 0, as a JSON integer does in the reference.
141fn epoch_of(v: &Value) -> Option<i64> {
142    let Value::Number(n) = v else {
143        return None;
144    };
145    if let Some(i) = n.as_i64() {
146        return (0..=MAX_AUTHORITY_EPOCH).contains(&i).then_some(i);
147    }
148    // serde_json reads the literal `-0` as the float -0.0.
149    match n.as_f64() {
150        Some(f) if f == 0.0 && f.is_sign_negative() => Some(0),
151        _ => None,
152    }
153}
154
155/// Refuse an `authorityEpoch` written as a float literal (`-0.0`, `5.0`, `1e2`)
156/// in the credential's JSON text. A parsed `Value` cannot tell `-0` from `-0.0`,
157/// so a caller that holds the text runs this before `verify` or
158/// `read_authority_epoch`, as the reference refuses any float epoch. Text with
159/// no epoch literal passes here and is refused by the later shape check.
160pub fn check_epoch_literal(credential_text: &str) -> Result<()> {
161    use serde_json::value::RawValue;
162    type Raw = crate::collections::HashMap<String, Box<RawValue>>;
163    let json_err = |e: serde_json::Error| CoreError::Json(e.to_string());
164    crate::nesting::check_text(credential_text.as_bytes())?;
165    let top: Raw = serde_json::from_str(credential_text).map_err(json_err)?;
166    let Some(subject) = top.get("credentialSubject") else {
167        return Ok(());
168    };
169    let Ok(subject) = serde_json::from_str::<Raw>(subject.get()) else {
170        return Ok(());
171    };
172    let Some(epoch) = subject.get("authorityEpoch") else {
173        return Ok(());
174    };
175    let lit = epoch.get().trim();
176    let digits = lit.strip_prefix('-').unwrap_or(lit);
177    let is_int = !digits.is_empty()
178        && digits.bytes().all(|b| b.is_ascii_digit())
179        && (digits.len() == 1 || !digits.starts_with('0'));
180    if lit.starts_with(|c: char| c == '-' || c.is_ascii_digit()) && !is_int {
181        return Err(CoreError::Json(
182            "authorityEpoch must be written as an integer".into(),
183        ));
184    }
185    Ok(())
186}
187
188/// The issuer DID as the reference reads it for an AuthorityState: a non-empty
189/// string, or the first entry of a non-empty list when that is one. An issuer
190/// object is refused.
191fn authority_issuer(credential: &Value) -> Option<&str> {
192    let s = match credential.get("issuer")? {
193        Value::String(s) => s.as_str(),
194        Value::Array(a) => a.first()?.as_str()?,
195        _ => return None,
196    };
197    (!s.is_empty()).then_some(s)
198}
199
200/// Verify an AuthorityState credential's Data Integrity proof and validity
201/// window. Same shape as `credentials::verify`: proof and time are reported
202/// separately so "bad signature" is distinguished from "expired".
203///
204/// `proof_valid` also requires the proof to be bound to the issuer: a single
205/// proof object with proofPurpose "assertionMethod" and a verificationMethod
206/// of the issuer's DID, the issuer being a string. A credential whose
207/// validFrom or validUntil is not a string, whose subject is not an object,
208/// or whose epoch or status is malformed is refused with an error.
209pub fn verify(
210    credential: &Value,
211    raw_public_key: &[u8],
212    now_iso: &str,
213    clock_skew_seconds: i64,
214) -> Result<VerifyResult> {
215    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
216    let is_authority_state = match credential.get("type") {
217        // Every entry must be a string, as the reference requires.
218        Some(Value::Array(arr)) => {
219            arr.iter().all(Value::is_string)
220                && arr.iter().any(|t| t.as_str() == Some(AUTHORITY_STATE_TYPE))
221        }
222        Some(Value::String(s)) => s == AUTHORITY_STATE_TYPE,
223        _ => false,
224    };
225    if !is_authority_state {
226        return Err(CoreError::Json(
227            "credential is not an AuthorityState".into(),
228        ));
229    }
230    let signature_valid = data_integrity::verify_proof(credential, raw_public_key)?;
231    let bound = match (authority_issuer(credential), credential.get("proof")) {
232        (Some(issuer), Some(proof)) => proof_bound_to_issuer(proof, issuer),
233        _ => false,
234    };
235    // A did:key names its own key: nothing else can sign for it, whatever key
236    // the caller passed.
237    let own_key = match authority_issuer(credential) {
238        Some(issuer) if issuer.starts_with("did:key:") => {
239            did_key_ed25519(issuer).as_deref() == Some(raw_public_key)
240        }
241        _ => true,
242    };
243    // The shape the reference enforces at verify time.
244    if !credential
245        .get("credentialSubject")
246        .map(Value::is_object)
247        .unwrap_or(false)
248    {
249        return Err(CoreError::Json(
250            "credentialSubject must be an object".into(),
251        ));
252    }
253    read_authority_epoch(credential)?;
254    read_authority_status(credential)?;
255    // A window that is missing or not protocol times is not valid (never an
256    // error): only a bad clock skew or `now` is the caller's mistake.
257    crate::time::check_clock_skew(clock_skew_seconds)?;
258    crate::time::parse_protocol_time_ns(now_iso)?;
259    let time_valid = verify_temporal(credential, now_iso, clock_skew_seconds).unwrap_or(false);
260    Ok(VerifyResult {
261        proof_valid: signature_valid && bound && own_key,
262        time_valid,
263        // An AuthorityState credential carries no delegation chain.
264        chain_valid: true,
265    })
266}
267
268/// Read `credentialSubject.authorityEpoch` without verifying the proof. For
269/// deciding which of two credentials is newer; never a substitute for `verify`.
270/// The epoch is a whole number from 0 to 2^53 - 1.
271pub fn read_authority_epoch(credential: &Value) -> Result<i64> {
272    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
273    credential
274        .get("credentialSubject")
275        .and_then(|s| s.get("authorityEpoch"))
276        .and_then(epoch_of)
277        .ok_or_else(|| CoreError::Json("missing or invalid authorityEpoch".into()))
278}
279
280/// Read `credentialSubject.status` without verifying the proof.
281pub fn read_authority_status(credential: &Value) -> Result<String> {
282    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
283    credential
284        .get("credentialSubject")
285        .and_then(|s| s.get("status"))
286        .and_then(|v| v.as_str())
287        .filter(|s| is_valid_status(s))
288        .map(|s| s.to_string())
289        .ok_or_else(|| CoreError::Json("missing or invalid status".into()))
290}
291
292// --------------------------------------------------------------------------- //
293// Authority state by reference: issuer binding, content digest, voucher fields
294// --------------------------------------------------------------------------- //
295
296/// The Ed25519 key a `did:key` DID names, or None (not a did:key, not
297/// Ed25519, or not decodable).
298pub fn did_key_ed25519(did: &str) -> Option<Vec<u8>> {
299    let mk = did.strip_prefix("did:key:")?;
300    let decoded = crate::multikey::decode(mk).ok()?;
301    (decoded.algorithm == "Ed25519" && decoded.raw_key.len() == 32).then_some(decoded.raw_key)
302}
303
304/// Parse JSON text with a key named twice in one object refused (JSON readers
305/// resolve that differently, so every reader must see the same object). NaN
306/// and Infinity are not JSON and are refused too.
307pub fn parse_json_no_duplicates(text: &str) -> Result<Value> {
308    struct NoDup(Value);
309    struct Visit;
310    impl<'de> serde::de::Visitor<'de> for Visit {
311        type Value = Value;
312        fn expecting(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
313            f.write_str("JSON")
314        }
315        fn visit_bool<E>(self, v: bool) -> core::result::Result<Value, E> {
316            Ok(Value::Bool(v))
317        }
318        fn visit_i64<E>(self, v: i64) -> core::result::Result<Value, E> {
319            Ok(Value::from(v))
320        }
321        fn visit_u64<E>(self, v: u64) -> core::result::Result<Value, E> {
322            Ok(Value::from(v))
323        }
324        fn visit_f64<E: serde::de::Error>(self, v: f64) -> core::result::Result<Value, E> {
325            serde_json::Number::from_f64(v)
326                .map(Value::Number)
327                .ok_or_else(|| E::custom("a number that is not finite"))
328        }
329        fn visit_str<E>(self, v: &str) -> core::result::Result<Value, E> {
330            Ok(Value::String(v.to_owned()))
331        }
332        fn visit_string<E>(self, v: String) -> core::result::Result<Value, E> {
333            Ok(Value::String(v))
334        }
335        fn visit_unit<E>(self) -> core::result::Result<Value, E> {
336            Ok(Value::Null)
337        }
338        fn visit_seq<A: serde::de::SeqAccess<'de>>(
339            self,
340            mut seq: A,
341        ) -> core::result::Result<Value, A::Error> {
342            let mut out = Vec::new();
343            while let Some(NoDup(v)) = seq.next_element()? {
344                out.push(v);
345            }
346            Ok(Value::Array(out))
347        }
348        fn visit_map<A: serde::de::MapAccess<'de>>(
349            self,
350            mut map: A,
351        ) -> core::result::Result<Value, A::Error> {
352            let mut out = Map::new();
353            while let Some(key) = map.next_key::<String>()? {
354                if out.contains_key(&key) {
355                    return Err(serde::de::Error::custom(format!("duplicate key {key:?}")));
356                }
357                let NoDup(v) = map.next_value()?;
358                out.insert(key, v);
359            }
360            Ok(Value::Object(out))
361        }
362    }
363    impl<'de> serde::Deserialize<'de> for NoDup {
364        fn deserialize<D: serde::Deserializer<'de>>(d: D) -> core::result::Result<Self, D::Error> {
365            d.deserialize_any(Visit).map(NoDup)
366        }
367    }
368    if let Some(literal) = integer_out_of_range(text) {
369        return Err(CoreError::Json(format!(
370            "the whole number {literal} is outside the 64-bit range, so it has no exact \
371             JSON reading"
372        )));
373    }
374    crate::nesting::check_text(text.as_bytes())?;
375    serde_json::from_str::<NoDup>(text)
376        .map(|NoDup(v)| v)
377        .map_err(|e| CoreError::Json(e.to_string()))
378}
379
380/// The first number literal with no fraction and no exponent that does not
381/// fit a 64-bit integer (signed or unsigned), outside strings. Such a number
382/// is read as the nearest double, so several texts would read the same and
383/// verify under one signature.
384fn integer_out_of_range(text: &str) -> Option<String> {
385    let bytes = text.as_bytes();
386    let mut i = 0;
387    while i < bytes.len() {
388        match bytes[i] {
389            b'"' => {
390                i += 1;
391                while i < bytes.len() && bytes[i] != b'"' {
392                    if bytes[i] == b'\\' {
393                        i += 1;
394                    }
395                    i += 1;
396                }
397                i += 1;
398            }
399            b'-' | b'0'..=b'9' => {
400                let start = i;
401                i += 1;
402                while i < bytes.len()
403                    && matches!(bytes[i], b'0'..=b'9' | b'.' | b'e' | b'E' | b'+' | b'-')
404                {
405                    i += 1;
406                }
407                let literal = &text[start..i];
408                let integer = !literal.contains(['.', 'e', 'E']);
409                if integer && literal.parse::<i64>().is_err() && literal.parse::<u64>().is_err() {
410                    return Some(literal.chars().take(40).collect());
411                }
412            }
413            _ => i += 1,
414        }
415    }
416    None
417}
418
419/// Parse an AuthorityState sent as JSON text: duplicate keys refused (see
420/// [`parse_json_no_duplicates`]) and the epoch's literal checked
421/// ([`check_epoch_literal`]).
422pub fn parse_authority_state_text(text: &str) -> Result<Value> {
423    let value = parse_json_no_duplicates(text)?;
424    check_epoch_literal(text)?;
425    Ok(value)
426}
427
428/// The content digest of an AuthorityState: what a heartbeat signs as
429/// `authorityStateDigest` and a SessionVoucher records.
430///
431/// `"u" + base64url_nopad(0x12 0x20 || SHA-256(JCS(credential)))` over the
432/// credential without its `proof`, the same encoding as
433/// [`crate::grant_chain::grant_digest`]. Errors when the credential is not a
434/// JSON object.
435pub fn authority_state_digest(credential: &Value) -> Result<String> {
436    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
437    let Some(obj) = credential.as_object() else {
438        return Err(CoreError::Json(
439            "an AuthorityState must be a JSON object".into(),
440        ));
441    };
442    let mut body = obj.clone();
443    body.remove("proof");
444    crate::grant_chain::grant_digest(&Value::Object(body))
445        .map_err(|e| CoreError::Json(e.to_string()))
446}
447
448/// [`authority_state_digest`] of JSON text, parsed with duplicate keys refused.
449pub fn authority_state_digest_text(text: &str) -> Result<String> {
450    authority_state_digest(&parse_json_no_duplicates(text)?)
451}
452
453/// The error for an empty trusted-authority map or list: a configuration
454/// error in every language (it would trust no one while looking set up).
455pub const EMPTY_TRUSTED_AUTHORITIES: &str = "the trusted-authority list is empty: name at least one authority, or leave trusted_authorities out";
456
457fn empty_trusted_authorities() -> CoreError {
458    CoreError::Json(EMPTY_TRUSTED_AUTHORITIES.into())
459}
460
461/// Normalise trusted authorities to {authority DID: Ed25519 key}.
462///
463/// Each entry is a DID and an optional raw key. A did:key entry with no key
464/// takes the key its DID names; a did:key entry given another key is refused.
465/// An authority is always a DID bound to one key: a state counts only when it
466/// verifies under the key of the DID it names as its issuer. No entries at all
467/// is an error ([`EMPTY_TRUSTED_AUTHORITIES`]).
468pub fn trusted_authority_keys(
469    entries: &[(String, Option<Vec<u8>>)],
470) -> Result<BTreeMap<String, Vec<u8>>> {
471    if entries.is_empty() {
472        return Err(empty_trusted_authorities());
473    }
474    let mut out = BTreeMap::new();
475    for (did, key) in entries {
476        if !did.starts_with("did:") {
477            return Err(CoreError::Json(format!(
478                "trusted authority {did:?} is not a DID"
479            )));
480        }
481        let own = if did.starts_with("did:key:") {
482            did_key_ed25519(did)
483        } else {
484            None
485        };
486        let resolved = match key {
487            Some(k) if k.len() == 32 && crate::keys::strict_verifying_key(k).is_ok() => {
488                Some(k.clone())
489            }
490            Some(_) => None,
491            None => own.clone(),
492        };
493        let Some(resolved) = resolved else {
494            return Err(CoreError::Json(format!(
495                "trusted authority {did}: no usable Ed25519 key"
496            )));
497        };
498        if let Some(own) = own {
499            if own != resolved {
500                return Err(CoreError::Json(format!(
501                    "trusted authority {did}: the key is not the one its DID names"
502                )));
503            }
504        }
505        out.insert(did.clone(), resolved);
506    }
507    Ok(out)
508}
509
510/// The verified content of an AuthorityState credential.
511#[derive(Debug, Clone, PartialEq, Eq)]
512pub struct AuthorityStatePassport {
513    pub issuer_did: String,
514    pub subject_did: String,
515    pub authority_epoch: i64,
516    pub status: String,
517    pub valid_from: String,
518    pub valid_until: String,
519}
520
521impl AuthorityStatePassport {
522    pub fn is_active(&self) -> bool {
523        self.status == STATUS_ACTIVE
524    }
525
526    /// The passport as JSON: {issuerDid, subjectDid, authorityEpoch, status,
527    /// validFrom, validUntil}.
528    pub fn to_json(&self) -> Value {
529        json!({
530            "issuerDid": self.issuer_did,
531            "subjectDid": self.subject_did,
532            "authorityEpoch": self.authority_epoch,
533            "status": self.status,
534            "validFrom": self.valid_from,
535            "validUntil": self.valid_until,
536        })
537    }
538}
539
540/// Trusted authorities from JSON, for the bindings: an object {DID: base64
541/// raw Ed25519 key, or null for a did:key} or a list of did:key DIDs. See
542/// [`trusted_authority_keys`].
543pub fn trusted_authorities_from_json(value: &Value) -> Result<BTreeMap<String, Vec<u8>>> {
544    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); value);
545    use base64::{engine::general_purpose::STANDARD, Engine};
546    let mut entries: Vec<(String, Option<Vec<u8>>)> = Vec::new();
547    match value {
548        Value::Object(map) => {
549            for (did, key) in map {
550                let key = match key {
551                    Value::Null => None,
552                    Value::String(k) => Some(STANDARD.decode(k).map_err(|_| {
553                        CoreError::Json(format!("trusted authority {did}: the key is not base64"))
554                    })?),
555                    _ => {
556                        return Err(CoreError::Json(format!(
557                            "trusted authority {did}: the key must be base64 text or null"
558                        )))
559                    }
560                };
561                entries.push((did.clone(), key));
562            }
563        }
564        Value::Array(list) => {
565            for did in list {
566                let Some(did) = did.as_str() else {
567                    return Err(CoreError::Json("trusted authorities must be DIDs".into()));
568                };
569                entries.push((did.to_string(), None));
570            }
571        }
572        _ => {
573            return Err(CoreError::Json(
574                "trusted authorities must be {DID: key} or a list of did:key DIDs".into(),
575            ))
576        }
577    }
578    trusted_authority_keys(&entries)
579}
580
581/// A voucher's authority record as JSON ({digest, epoch, status, issuer}), or
582/// null.
583pub fn voucher_authority_json(voucher: &Value) -> Value {
584    crate::nesting::deep_guard!(Value::Null; voucher);
585    match voucher_authority(voucher) {
586        Some(a) => json!({
587            "digest": a.digest,
588            "epoch": a.epoch,
589            "status": a.status,
590            "issuer": a.issuer,
591        }),
592        None => Value::Null,
593    }
594}
595
596/// Verify an AuthorityState under its own issuer's key.
597///
598/// - With `trusted_authorities` ({DID: key}, see [`trusted_authority_keys`])
599///   the key is the one trusted for the DID the state names as its issuer,
600///   and a state from any other issuer is refused (`public_key` is then not
601///   used).
602/// - With `public_key`, pass `issuer_did` too: the state must name that
603///   issuer. Without `issuer_did`, the key is taken as the issuer's on the
604///   caller's word (the old form, for callers that bind it themselves).
605/// - With neither, only a did:key issuer verifies, under the key its DID
606///   names.
607///
608/// A did:key issuer's state verifies only under its own key, whatever key is
609/// passed. Returns the passport, or None for any refusal (however malformed
610/// the credential). Errors when `clock_skew_seconds` is not 0 to 120, and
611/// when `trusted_authorities` is an empty map (a configuration error).
612pub fn verify_authority_state_bound(
613    credential: &Value,
614    public_key: Option<&[u8]>,
615    trusted_authorities: Option<&BTreeMap<String, Vec<u8>>>,
616    issuer_did: Option<&str>,
617    now_iso: &str,
618    clock_skew_seconds: i64,
619) -> Result<Option<AuthorityStatePassport>> {
620    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
621    crate::time::check_clock_skew(clock_skew_seconds)?;
622    if trusted_authorities.is_some_and(BTreeMap::is_empty) {
623        return Err(empty_trusted_authorities());
624    }
625    if !credential.is_object() {
626        return Ok(None);
627    }
628    let Some(claimed) = authority_issuer(credential) else {
629        return Ok(None);
630    };
631    if issuer_did.is_some_and(|expected| expected != claimed) {
632        return Ok(None);
633    }
634    let key: Vec<u8> = if let Some(trusted) = trusted_authorities {
635        match trusted.get(claimed) {
636            Some(k) => k.clone(),
637            None => return Ok(None),
638        }
639    } else if let Some(k) = public_key {
640        k.to_vec()
641    } else {
642        match did_key_ed25519(claimed) {
643            Some(k) => k,
644            None => return Ok(None),
645        }
646    };
647    let Ok(result) = verify(credential, &key, now_iso, clock_skew_seconds) else {
648        return Ok(None);
649    };
650    if !result.is_valid() {
651        return Ok(None);
652    }
653    let (Ok(epoch), Ok(status)) = (
654        read_authority_epoch(credential),
655        read_authority_status(credential),
656    ) else {
657        return Ok(None);
658    };
659    let subject_did = credential["credentialSubject"]
660        .get("id")
661        .and_then(Value::as_str)
662        .filter(|s| !s.is_empty())
663        .unwrap_or(claimed)
664        .to_string();
665    Ok(Some(AuthorityStatePassport {
666        issuer_did: claimed.to_string(),
667        subject_did,
668        authority_epoch: epoch,
669        status,
670        valid_from: credential["validFrom"]
671            .as_str()
672            .unwrap_or_default()
673            .to_string(),
674        valid_until: credential["validUntil"]
675            .as_str()
676            .unwrap_or_default()
677            .to_string(),
678    }))
679}
680
681/// [`verify_authority_state_bound`] on JSON text: text with a key named twice,
682/// or an epoch written as a float literal, is refused (None).
683pub fn verify_authority_state_bound_text(
684    credential_text: &str,
685    public_key: Option<&[u8]>,
686    trusted_authorities: Option<&BTreeMap<String, Vec<u8>>>,
687    issuer_did: Option<&str>,
688    now_iso: &str,
689    clock_skew_seconds: i64,
690) -> Result<Option<AuthorityStatePassport>> {
691    crate::time::check_clock_skew(clock_skew_seconds)?;
692    if trusted_authorities.is_some_and(BTreeMap::is_empty) {
693        return Err(empty_trusted_authorities());
694    }
695    let Ok(credential) = parse_authority_state_text(credential_text) else {
696        return Ok(None);
697    };
698    verify_authority_state_bound(
699        &credential,
700        public_key,
701        trusted_authorities,
702        issuer_did,
703        now_iso,
704        clock_skew_seconds,
705    )
706}
707
708/// The fields a SessionVoucher records from a verified AuthorityState: all
709/// four or none. A lone `authorityEpoch` (written by validators before
710/// authority state by reference) is an agent's own claim: it is ignored,
711/// never trusted.
712pub const VOUCHER_AUTHORITY_FIELDS: [&str; 4] = [
713    "authorityStateDigest",
714    "authorityEpoch",
715    "authorityStatus",
716    "authorityIssuer",
717];
718
719/// Why a voucher's authority fields (in its `credentialSubject`) are not well
720/// formed, or None. A voucher verifier refuses such a voucher as
721/// `voucher_malformed:<problem>`. The epoch's own range is checked apart, as
722/// for any voucher epoch.
723pub fn voucher_authority_problem(subject: &Value) -> Option<String> {
724    crate::nesting::deep_guard!(Some(crate::nesting::TOO_DEEP.into()); subject);
725    let obj = subject.as_object()?;
726    let present: Vec<&str> = VOUCHER_AUTHORITY_FIELDS
727        .iter()
728        .copied()
729        .filter(|name| obj.contains_key(*name))
730        .collect();
731    if present.is_empty() || present == ["authorityEpoch"] {
732        return None;
733    }
734    if present.len() != VOUCHER_AUTHORITY_FIELDS.len() {
735        return Some("the authority fields must be all present or all absent".into());
736    }
737    for name in ["authorityStateDigest", "authorityStatus", "authorityIssuer"] {
738        if obj[name].as_str().is_none_or(str::is_empty) {
739            return Some(format!("{name} must be a non-empty string"));
740        }
741    }
742    None
743}
744
745/// The authority record of a SessionVoucher.
746#[derive(Debug, Clone, PartialEq, Eq)]
747pub struct VoucherAuthority {
748    pub digest: String,
749    pub epoch: i64,
750    pub status: String,
751    pub issuer: String,
752}
753
754/// The authority record of a voucher, or None when it carries none. A lone
755/// `authorityEpoch` counts as none: a voucher's epoch counts only with its
756/// `authorityStateDigest` (a state the validator verified). Read only after
757/// the voucher verified.
758pub fn voucher_authority(voucher: &Value) -> Option<VoucherAuthority> {
759    crate::nesting::deep_guard!(None; voucher);
760    let subject = voucher.get("credentialSubject")?;
761    let obj = subject.as_object()?;
762    if voucher_authority_problem(subject).is_some() || !obj.contains_key("authorityStateDigest") {
763        return None;
764    }
765    Some(VoucherAuthority {
766        digest: obj["authorityStateDigest"].as_str()?.to_string(),
767        epoch: epoch_of(&obj["authorityEpoch"])?,
768        status: obj["authorityStatus"].as_str()?.to_string(),
769        issuer: obj["authorityIssuer"].as_str()?.to_string(),
770    })
771}
772
773/// The epoch a verifier may take from a voucher for Authority Freshness: the
774/// recorded one, or None for a voucher without the four authority fields.
775pub fn voucher_authority_epoch(voucher: &Value) -> Option<i64> {
776    crate::nesting::deep_guard!(None; voucher);
777    voucher_authority(voucher).map(|a| a.epoch)
778}
779
780/// Check the AuthorityState attached to a call against the trusted
781/// authorities and the call's voucher, as a verifier does before Authority
782/// Freshness:
783///
784/// - no state, or one that is not a JSON object: `authority_state_missing`;
785/// - its issuer is not a trusted authority: `authority_issuer_untrusted`;
786/// - it does not verify under that issuer's key, or its subject is not the
787///   caller: `authority_state_missing`;
788/// - the voucher records no authority, another digest or another issuer:
789///   `authority_state_digest_mismatch`.
790///
791/// On success the passport's epoch and status are what Authority Freshness
792/// compares; an epoch is never learned from a voucher. The outer error is a
793/// clock skew outside 0 to 120, or an empty `trusted_authorities` (a
794/// configuration error).
795pub fn check_attached_authority_state(
796    state: Option<&Value>,
797    trusted_authorities: &BTreeMap<String, Vec<u8>>,
798    voucher: Option<&Value>,
799    caller: Option<&str>,
800    now_iso: &str,
801    clock_skew_seconds: i64,
802) -> Result<core::result::Result<AuthorityStatePassport, &'static str>> {
803    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); state, voucher);
804    crate::time::check_clock_skew(clock_skew_seconds)?;
805    if trusted_authorities.is_empty() {
806        return Err(empty_trusted_authorities());
807    }
808    let Some(state) = state.filter(|s| s.is_object()) else {
809        return Ok(Err(AUTHORITY_STATE_MISSING));
810    };
811    let Some(issuer) = authority_issuer(state).filter(|i| trusted_authorities.contains_key(*i))
812    else {
813        return Ok(Err(AUTHORITY_ISSUER_UNTRUSTED));
814    };
815    let passport = verify_authority_state_bound(
816        state,
817        None,
818        Some(trusted_authorities),
819        None,
820        now_iso,
821        clock_skew_seconds,
822    )?;
823    let Some(passport) = passport.filter(|p| caller == Some(p.subject_did.as_str())) else {
824        return Ok(Err(AUTHORITY_STATE_MISSING));
825    };
826    let Ok(digest) = authority_state_digest(state) else {
827        return Ok(Err(AUTHORITY_STATE_MISSING));
828    };
829    match voucher.and_then(voucher_authority) {
830        Some(recorded) if recorded.digest == digest && recorded.issuer == issuer => {
831            Ok(Ok(passport))
832        }
833        _ => Ok(Err(AUTHORITY_STATE_DIGEST_MISMATCH)),
834    }
835}
836
837/// [`check_attached_authority_state`] with the state as JSON text: text that
838/// does not parse (a key named twice included) is `authority_state_missing`.
839pub fn check_attached_authority_state_text(
840    state_text: Option<&str>,
841    trusted_authorities: &BTreeMap<String, Vec<u8>>,
842    voucher: Option<&Value>,
843    caller: Option<&str>,
844    now_iso: &str,
845    clock_skew_seconds: i64,
846) -> Result<core::result::Result<AuthorityStatePassport, &'static str>> {
847    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); voucher);
848    crate::time::check_clock_skew(clock_skew_seconds)?;
849    if trusted_authorities.is_empty() {
850        return Err(empty_trusted_authorities());
851    }
852    let parsed = match state_text {
853        None => None,
854        Some(text) => match parse_authority_state_text(text) {
855            Ok(v) => Some(v),
856            Err(_) => return Ok(Err(AUTHORITY_STATE_MISSING)),
857        },
858    };
859    check_attached_authority_state(
860        parsed.as_ref(),
861        trusted_authorities,
862        voucher,
863        caller,
864        now_iso,
865        clock_skew_seconds,
866    )
867}
868
869/// How a consequence tier treats authority state.
870#[derive(Debug, Clone, Copy, PartialEq, Eq)]
871pub struct FreshnessRule {
872    pub enforce_epoch: bool,
873    pub require_live_cosign: bool,
874}
875
876/// The consequence -> policy map. Unknown tiers coerce to the strictest rule.
877pub fn freshness_rule(tier: &str) -> FreshnessRule {
878    match tier {
879        CONSEQUENCE_ROUTINE => FreshnessRule {
880            enforce_epoch: false,
881            require_live_cosign: false,
882        },
883        CONSEQUENCE_SENSITIVE => FreshnessRule {
884            enforce_epoch: true,
885            require_live_cosign: false,
886        },
887        // critical and any unknown tier
888        _ => FreshnessRule {
889            enforce_epoch: true,
890            require_live_cosign: true,
891        },
892    }
893}
894
895/// The outcome of an Authority Freshness evaluation.
896#[derive(Debug, Clone, PartialEq, Eq)]
897pub struct AuthorityFreshnessVerdict {
898    pub allow: bool,
899    pub tier: String,
900    pub reason: String,
901}
902
903/// Decide whether an action passes the Authority Freshness gate.
904///
905/// `voucher_epoch` and `last_seen_epoch` are None when unknown. `current_status`
906/// is None when the verifier does not hold a current AuthorityState.
907/// `live_cosign_ok` is the verified-fresh state of a live co-sign, for the
908/// critical tier only.
909///
910/// An epoch below 0 or above 2^53 - 1 is refused with an error, as the
911/// reference refuses it.
912pub fn evaluate_authority_freshness(
913    tier: &str,
914    voucher_epoch: Option<i64>,
915    last_seen_epoch: Option<i64>,
916    current_status: Option<&str>,
917    live_cosign_ok: Option<bool>,
918) -> Result<AuthorityFreshnessVerdict> {
919    let policy: BTreeMap<String, FreshnessRule> = [
920        CONSEQUENCE_ROUTINE,
921        CONSEQUENCE_SENSITIVE,
922        CONSEQUENCE_CRITICAL,
923    ]
924    .iter()
925    .map(|t| (t.to_string(), freshness_rule(t)))
926    .collect();
927    evaluate_authority_freshness_with(
928        tier,
929        voucher_epoch,
930        last_seen_epoch,
931        current_status,
932        live_cosign_ok,
933        &policy,
934    )
935}
936
937/// [`evaluate_authority_freshness`] with the caller's consequence -> rule
938/// map in place of the default one (the reference's `policy` argument). An
939/// unknown tier is read as critical, and a tier the map does not name takes
940/// the strictest rule.
941pub fn evaluate_authority_freshness_with(
942    tier: &str,
943    voucher_epoch: Option<i64>,
944    last_seen_epoch: Option<i64>,
945    current_status: Option<&str>,
946    live_cosign_ok: Option<bool>,
947    policy: &BTreeMap<String, FreshnessRule>,
948) -> Result<AuthorityFreshnessVerdict> {
949    for (name, e) in [
950        ("voucher_epoch", voucher_epoch),
951        ("last_seen_epoch", last_seen_epoch),
952    ] {
953        if let Some(e) = e {
954            if !(0..=MAX_AUTHORITY_EPOCH).contains(&e) {
955                return Err(CoreError::Json(format!(
956                    "{name} must be a whole number from 0 to 2^53 - 1"
957                )));
958            }
959        }
960    }
961    let canonical_tier = match tier {
962        CONSEQUENCE_ROUTINE | CONSEQUENCE_SENSITIVE | CONSEQUENCE_CRITICAL => tier,
963        _ => CONSEQUENCE_CRITICAL,
964    };
965    let rule = policy
966        .get(canonical_tier)
967        .copied()
968        .unwrap_or(FreshnessRule {
969            enforce_epoch: true,
970            require_live_cosign: true,
971        });
972    let mk = |allow: bool, reason: String| AuthorityFreshnessVerdict {
973        allow,
974        tier: canonical_tier.to_string(),
975        reason,
976    };
977
978    if !rule.enforce_epoch && !rule.require_live_cosign {
979        return Ok(mk(true, "routine tier: time-decay only".into()));
980    }
981
982    if let Some(status) = current_status {
983        if status != STATUS_ACTIVE {
984            return Ok(mk(
985                false,
986                format!("authority_status_not_active:status={status}"),
987            ));
988        }
989    }
990
991    if rule.require_live_cosign && live_cosign_ok != Some(true) {
992        return Ok(mk(
993            false,
994            format!("live_cosign_required:tier={canonical_tier}"),
995        ));
996    }
997
998    if rule.enforce_epoch {
999        // Why an epoch and not a fresher timestamp: a timestamp says when the
1000        // voucher was minted, never whether authority has changed since, so time
1001        // alone forces the verifier to guess a safe staleness window. A new epoch
1002        // is proof that a real transition happened, published and signed by the
1003        // authority. A voucher minted under epoch 7 is refused once this verifier
1004        // has seen epoch 8, even six seconds later with time-decay trust still
1005        // passing. The limit: this only bites once the verifier has learned of the
1006        // newer epoch, which is why the critical tier falls back to a live co-sign.
1007        match (voucher_epoch, last_seen_epoch) {
1008            (Some(v), Some(seen)) => {
1009                if v < seen {
1010                    return Ok(mk(
1011                        false,
1012                        format!("authority_epoch_stale:seen={seen},voucher={v}"),
1013                    ));
1014                }
1015            }
1016            _ => {
1017                // An absent epoch renders as "?" so the reason code is identical
1018                // in every language binding. Pinned by the interop vector.
1019                return Ok(mk(
1020                    false,
1021                    format!(
1022                        "authority_epoch_unknown:voucher={},seen={}",
1023                        epoch_str(voucher_epoch),
1024                        epoch_str(last_seen_epoch)
1025                    ),
1026                ));
1027            }
1028        }
1029    }
1030
1031    Ok(mk(
1032        true,
1033        format!("{canonical_tier} tier: authority state fresh"),
1034    ))
1035}
1036
1037/// Authority Freshness as JSON: {"tier", "voucherEpoch", "lastSeenEpoch",
1038/// "currentStatus", "liveCosignOk", "policy"} to {allow, tier, reason}.
1039/// "policy" ({tier: {enforceEpoch, requireLiveCosign}}) replaces the default
1040/// rules; without it the default rules apply. Null members are unknown.
1041pub fn freshness_json(req: &Value) -> Result<Value> {
1042    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); req);
1043    let epoch = |name: &str| -> Result<Option<i64>> {
1044        match req.get(name).filter(|v| !v.is_null()) {
1045            None => Ok(None),
1046            Some(v) => v
1047                .as_i64()
1048                .filter(|e| (0..=MAX_AUTHORITY_EPOCH).contains(e))
1049                .map(Some)
1050                .ok_or_else(|| {
1051                    CoreError::Json(format!("{name} must be a whole number from 0 to 2^53-1"))
1052                }),
1053        }
1054    };
1055    let wrong = |what: String| CoreError::Json(what);
1056    let tier = match req.get("tier") {
1057        Some(Value::String(t)) => t.as_str(),
1058        _ => return Err(wrong("tier must be text".into())),
1059    };
1060    let status = match req.get("currentStatus") {
1061        None | Some(Value::Null) => None,
1062        Some(Value::String(s)) => Some(s.as_str()),
1063        Some(_) => return Err(wrong("currentStatus must be text or null".into())),
1064    };
1065    let cosign = match req.get("liveCosignOk") {
1066        None | Some(Value::Null) => None,
1067        Some(Value::Bool(b)) => Some(*b),
1068        Some(_) => return Err(wrong("liveCosignOk must be true, false or null".into())),
1069    };
1070    let policy_map = match req.get("policy") {
1071        None | Some(Value::Null) => None,
1072        Some(Value::Object(map)) => Some(map),
1073        Some(_) => return Err(wrong("policy must be an object".into())),
1074    };
1075    let verdict = match policy_map {
1076        None => evaluate_authority_freshness(
1077            tier,
1078            epoch("voucherEpoch")?,
1079            epoch("lastSeenEpoch")?,
1080            status,
1081            cosign,
1082        )?,
1083        Some(map) => {
1084            let mut policy = BTreeMap::new();
1085            for (name, rule) in map {
1086                let flag = |k: &str| -> Result<bool> {
1087                    rule.get(k)
1088                        .and_then(Value::as_bool)
1089                        .ok_or_else(|| wrong(format!("policy.{name}.{k} must be true or false")))
1090                };
1091                policy.insert(
1092                    name.clone(),
1093                    FreshnessRule {
1094                        enforce_epoch: flag("enforceEpoch")?,
1095                        require_live_cosign: flag("requireLiveCosign")?,
1096                    },
1097                );
1098            }
1099            evaluate_authority_freshness_with(
1100                tier,
1101                epoch("voucherEpoch")?,
1102                epoch("lastSeenEpoch")?,
1103                status,
1104                cosign,
1105                &policy,
1106            )?
1107        }
1108    };
1109    Ok(json!({
1110        "allow": verdict.allow,
1111        "tier": verdict.tier,
1112        "reason": verdict.reason,
1113    }))
1114}
1115
1116/// AuthorityState rules as one JSON request {"fn", ...}:
1117///
1118/// - "build" {issuerDid, credentialId, authorityEpoch, status, validFrom,
1119///   validUntil, subjectDid?} to the unsigned credential;
1120/// - "verify" {credential (JSON text), publicKey (base64), now,
1121///   clockSkewSeconds} to {proofValid, timeValid, valid};
1122/// - "readEpoch" / "readStatus" {credential (JSON text)} to the value;
1123/// - "freshnessRule" {tier} to {enforceEpoch, requireLiveCosign}.
1124pub fn rules_json(req: &Value) -> Result<Value> {
1125    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); req);
1126    let text = |name: &str| {
1127        req.get(name)
1128            .and_then(Value::as_str)
1129            .unwrap_or("")
1130            .to_string()
1131    };
1132    let parse = |t: &str| -> Result<Value> {
1133        crate::nesting::check_text(t.as_bytes())?;
1134        serde_json::from_str(t).map_err(|e| CoreError::Json(e.to_string()))
1135    };
1136    match req.get("fn").and_then(Value::as_str).unwrap_or("") {
1137        "build" => {
1138            let epoch = match req.get("authorityEpoch") {
1139                Some(Value::Number(n)) => n.as_i64().ok_or_else(|| {
1140                    CoreError::Json("authorityEpoch must be a whole number from 0 to 2^53-1".into())
1141                })?,
1142                _ => {
1143                    return Err(CoreError::Json(
1144                        "authorityEpoch must be a whole number from 0 to 2^53-1".into(),
1145                    ))
1146                }
1147            };
1148            let opts = BuildAuthorityStateOptions {
1149                issuer_did: text("issuerDid"),
1150                credential_id: text("credentialId"),
1151                authority_epoch: epoch,
1152                status: text("status"),
1153                valid_from: text("validFrom"),
1154                valid_until: text("validUntil"),
1155                subject_did: req
1156                    .get("subjectDid")
1157                    .and_then(Value::as_str)
1158                    .filter(|s| !s.is_empty())
1159                    .map(str::to_string),
1160            };
1161            build_authority_state(&opts)
1162        }
1163        "verify" => {
1164            let cred_text = text("credential");
1165            check_epoch_literal(&cred_text)?;
1166            let key = {
1167                use base64::{engine::general_purpose::STANDARD, Engine};
1168                STANDARD
1169                    .decode(text("publicKey"))
1170                    .map_err(|e| CoreError::Json(format!("base64: {e}")))?
1171            };
1172            let skew = match req.get("clockSkewSeconds") {
1173                None | Some(Value::Null) => 30,
1174                Some(v) => crate::time::clock_skew_from_json(v)?,
1175            };
1176            let r = verify(&parse(&cred_text)?, &key, &text("now"), skew)?;
1177            Ok(
1178                json!({"proofValid": r.proof_valid, "timeValid": r.time_valid, "valid": r.is_valid()}),
1179            )
1180        }
1181        "readEpoch" => {
1182            let cred_text = text("credential");
1183            check_epoch_literal(&cred_text)?;
1184            Ok(json!(read_authority_epoch(&parse(&cred_text)?)?))
1185        }
1186        "readStatus" => Ok(json!(read_authority_status(&parse(&text("credential"))?)?)),
1187        "freshnessRule" => {
1188            let r = freshness_rule(&text("tier"));
1189            Ok(json!({"enforceEpoch": r.enforce_epoch, "requireLiveCosign": r.require_live_cosign}))
1190        }
1191        "cosignSigningInput" => {
1192            // {authority, authorityEpoch, status, nonce, created} to the JCS
1193            // bytes a quorum co-signs (standard base64); `created` is written
1194            // in whole seconds.
1195            let created = crate::time::parse_protocol_time_ns(&text("created"))?;
1196            let epoch = req
1197                .get("authorityEpoch")
1198                .and_then(epoch_of)
1199                .ok_or_else(|| {
1200                    CoreError::Json("authorityEpoch must be a whole number from 0 to 2^53-1".into())
1201                })?;
1202            let input = cosign_signing_input(
1203                &json!(text("authority")),
1204                epoch,
1205                &text("status"),
1206                &text("nonce"),
1207                created,
1208            );
1209            use base64::{engine::general_purpose::STANDARD, Engine};
1210            Ok(json!({ "signingInput": STANDARD.encode(input) }))
1211        }
1212        "verifyLiveCosign" => Ok(verify_live_cosign_json(req)?),
1213        other => Err(CoreError::Json(format!(
1214            "unknown authority state rule {:?}",
1215            other.chars().take(40).collect::<String>()
1216        ))),
1217    }
1218}
1219
1220/// The type a live authority co-sign carries.
1221pub const LIVE_COSIGN_TYPE: &str = "AuthorityStateCosign";
1222/// The default freshness window of a live co-sign.
1223pub const DEFAULT_COSIGN_MAX_AGE_SECONDS: i64 = 30;
1224
1225/// The canonical bytes an authority quorum co-signs to attest its current
1226/// state at action time (domain-separated by `type`), with `created` written
1227/// in whole seconds.
1228pub fn cosign_signing_input(
1229    authority: &Value,
1230    authority_epoch: i64,
1231    status: &str,
1232    nonce: &str,
1233    created_ns: i128,
1234) -> Vec<u8> {
1235    crate::nesting::deep_guard!(Vec::new(); authority);
1236    signing_input_any_nonce(
1237        authority,
1238        authority_epoch,
1239        status,
1240        &Value::String(nonce.into()),
1241        created_ns,
1242    )
1243}
1244
1245/// The signing input with the nonce as the co-sign carries it (the
1246/// reference signs any JSON nonce as it is).
1247fn signing_input_any_nonce(
1248    authority: &Value,
1249    authority_epoch: i64,
1250    status: &str,
1251    nonce: &Value,
1252    created_ns: i128,
1253) -> Vec<u8> {
1254    let created = crate::time::epoch_seconds_to_iso(created_ns.div_euclid(1_000_000_000) as i64);
1255    crate::jcs::canonicalize(&json!({
1256        "type": LIVE_COSIGN_TYPE,
1257        "authority": authority,
1258        "authorityEpoch": authority_epoch,
1259        "status": status,
1260        "nonce": nonce,
1261        "created": created,
1262    }))
1263}
1264
1265/// A live co-sign's age limit in seconds, as the caller gave it.
1266#[derive(Clone, Copy)]
1267enum MaxAge {
1268    Whole(i64),
1269    Float(f64),
1270}
1271
1272/// Verify a live authority co-sign, the reference's checks in its order:
1273/// shape, type, nonce, status, epoch, created, age (stale, then future-dated),
1274/// proofValue, key, signature (strict Ed25519), then an active status.
1275///
1276/// Request `{cosign, groupPublicKey (raw, standard base64) or null,
1277/// expectedNonce, maxAgeSeconds? (30; a whole number, or a float compared
1278/// with the age in seconds as a float), now}` to `{ok, reason,
1279/// authorityEpoch, status}`.
1280fn verify_live_cosign_json(req: &Value) -> Result<Value> {
1281    use base64::{engine::general_purpose::STANDARD, Engine};
1282    let out = |ok: bool, reason: String, epoch: Option<i64>, status: Option<&str>| json!({"ok": ok, "reason": reason, "authorityEpoch": epoch, "status": status});
1283    let fail = |reason: &str| Ok(out(false, reason.to_string(), None, None));
1284    let now = crate::time::parse_protocol_time_ns(
1285        req.get("now")
1286            .and_then(Value::as_str)
1287            .ok_or_else(|| CoreError::Json("now is required".into()))?,
1288    )?;
1289    // A whole number is compared exactly; a float as the reference compares
1290    // it, against the age in seconds as a float.
1291    let max_age = match req.get("maxAgeSeconds") {
1292        None | Some(Value::Null) => MaxAge::Whole(DEFAULT_COSIGN_MAX_AGE_SECONDS),
1293        Some(Value::Number(n)) if n.is_f64() => MaxAge::Float(n.as_f64().unwrap_or(f64::NAN)),
1294        Some(v) => MaxAge::Whole(
1295            v.as_i64()
1296                .ok_or_else(|| CoreError::Json("maxAgeSeconds must be a number".into()))?,
1297        ),
1298    };
1299    let Some(cosign) = req.get("cosign").and_then(Value::as_object) else {
1300        return fail("cosign_malformed");
1301    };
1302    if cosign.get("type").and_then(Value::as_str) != Some(LIVE_COSIGN_TYPE) {
1303        return fail("cosign_wrong_type");
1304    }
1305    let nonce = cosign.get("nonce").unwrap_or(&Value::Null);
1306    if Some(nonce) != req.get("expectedNonce") || req.get("expectedNonce").is_none() {
1307        return fail("cosign_nonce_mismatch");
1308    }
1309    let status = match cosign.get("status").and_then(Value::as_str) {
1310        Some(s) if VALID_AUTHORITY_STATUSES.contains(&s) => s,
1311        _ => return fail("cosign_bad_status"),
1312    };
1313    let Some(epoch) = cosign.get("authorityEpoch").and_then(epoch_of) else {
1314        return fail("cosign_bad_epoch");
1315    };
1316    let Some(created) = cosign
1317        .get("created")
1318        .and_then(Value::as_str)
1319        .and_then(|t| crate::time::parse_protocol_time_ns(t).ok())
1320    else {
1321        return fail("cosign_bad_created");
1322    };
1323    // The reference compares at microseconds (its clock and its parse).
1324    let micros = |ns: i128| ns.div_euclid(1_000);
1325    let age_us = micros(now) - micros(created);
1326    let (stale, future) = match max_age {
1327        MaxAge::Whole(m) => (
1328            age_us > i128::from(m) * 1_000_000,
1329            age_us < -i128::from(m) * 1_000_000,
1330        ),
1331        MaxAge::Float(m) => {
1332            let age = age_us as f64 / 1e6;
1333            (age > m, age < -m)
1334        }
1335    };
1336    if stale {
1337        let whole = age_us / 1_000_000; // toward zero, as int() does
1338        let limit = match max_age {
1339            MaxAge::Whole(m) => m.to_string(),
1340            MaxAge::Float(m) => crate::grant_chain::py_repr_float(m),
1341        };
1342        return fail(&format!("cosign_stale:age={whole}s>{limit}s"));
1343    }
1344    if future {
1345        return fail("cosign_future_dated");
1346    }
1347    let signature = match cosign.get("proofValue").and_then(Value::as_str) {
1348        Some(pv) if pv.starts_with('z') => match crate::multikey::decode_base58_bounded(&pv[1..]) {
1349            Ok(sig) => sig,
1350            Err(_) => return fail("cosign_bad_proof_value"),
1351        },
1352        _ => return fail("cosign_bad_proof_value"),
1353    };
1354    let key = req
1355        .get("groupPublicKey")
1356        .and_then(Value::as_str)
1357        .and_then(|k| STANDARD.decode(k).ok())
1358        .filter(|k| crate::proof_json::ed25519_public_key_problem(k).is_none());
1359    let Some(key) = key else {
1360        return fail("cosign_bad_key");
1361    };
1362    // Any JSON authority is written as it is (the reference signs what it
1363    // was given; a wrong one fails the signature).
1364    let authority = cosign.get("authority").cloned().unwrap_or(json!(""));
1365    // Any JSON nonce (it matched the expected one) is signed as it is.
1366    let input = signing_input_any_nonce(&authority, epoch, status, nonce, created);
1367    if !crate::keys::verify(&key, &input, &signature).unwrap_or(false) {
1368        return fail("cosign_signature_invalid");
1369    }
1370    if status != STATUS_ACTIVE {
1371        return Ok(out(
1372            false,
1373            format!("cosign_status_not_active:status={status}"),
1374            Some(epoch),
1375            Some(status),
1376        ));
1377    }
1378    Ok(out(
1379        true,
1380        "live co-sign fresh and valid".into(),
1381        Some(epoch),
1382        Some(status),
1383    ))
1384}
1385
1386#[cfg(test)]
1387mod tests {
1388    use super::*;
1389
1390    /// A live co-sign created at 10:00:00, checked `age` seconds later.
1391    fn cosign_at(max_age: Value, now: &str) -> Value {
1392        use base64::{engine::general_purpose::STANDARD, Engine};
1393        use ed25519_dalek::{Signer, SigningKey};
1394        let key = SigningKey::from_bytes(&[7u8; 32]);
1395        let created = "2026-08-02T10:00:00Z";
1396        let created_ns = crate::time::parse_protocol_time_ns(created).unwrap();
1397        let input =
1398            cosign_signing_input(&json!("did:web:a.example"), 3, "active", "n1", created_ns);
1399        let signature = key.sign(&input).to_bytes();
1400        let cosign = json!({
1401            "type": LIVE_COSIGN_TYPE, "authority": "did:web:a.example", "authorityEpoch": 3,
1402            "status": "active", "nonce": "n1", "created": created,
1403            "proofValue": format!("z{}", bs58::encode(signature).into_string()),
1404        });
1405        verify_live_cosign_json(&json!({
1406            "cosign": cosign,
1407            "groupPublicKey": STANDARD.encode(key.verifying_key().to_bytes()),
1408            "expectedNonce": "n1", "maxAgeSeconds": max_age, "now": now,
1409        }))
1410        .unwrap()
1411    }
1412
1413    #[test]
1414    fn a_float_cosign_age_limit_is_read_as_the_reference_reads_it() {
1415        let reason = |max_age: Value, now: &str| cosign_at(max_age, now)["reason"].clone();
1416        let fresh = json!("live co-sign fresh and valid");
1417        assert_eq!(reason(json!(2.5), "2026-08-02T10:00:02.400000Z"), fresh);
1418        assert_eq!(reason(json!(2.5), "2026-08-02T09:59:57.600000Z"), fresh);
1419        assert_eq!(reason(json!(5.0), "2026-08-02T10:00:02Z"), fresh);
1420        assert_eq!(
1421            reason(json!(2.5), "2026-08-02T10:00:02.600000Z"),
1422            json!("cosign_stale:age=2s>2.5s")
1423        );
1424        assert_eq!(
1425            reason(json!(1.5), "2026-08-02T10:00:02Z"),
1426            json!("cosign_stale:age=2s>1.5s")
1427        );
1428        assert_eq!(
1429            reason(json!(2.5), "2026-08-02T09:59:57.400000Z"),
1430            json!("cosign_future_dated")
1431        );
1432        assert_eq!(
1433            reason(json!(1), "2026-08-02T10:00:02Z"),
1434            json!("cosign_stale:age=2s>1s")
1435        );
1436        assert_eq!(reason(json!(null), "2026-08-02T10:00:02Z"), fresh);
1437        assert!(verify_live_cosign_json(
1438            &json!({"maxAgeSeconds": "5", "now": "2026-08-02T10:00:02Z"})
1439        )
1440        .is_err());
1441    }
1442
1443    #[test]
1444    fn a_nonce_that_is_not_text_is_signed_as_it_is() {
1445        // It matched the expected nonce, so the signature decides.
1446        for nonce in [json!(null), json!(5), json!(["n1"])] {
1447            let mut request = json!({
1448                "cosign": {"type": LIVE_COSIGN_TYPE, "authority": "did:web:a.example",
1449                           "authorityEpoch": 3, "status": "active", "nonce": nonce,
1450                           "created": "2026-08-02T10:00:00Z", "proofValue": "z2"},
1451                "groupPublicKey": "A6EHv/POEL4dcN0Y50vAmWfk1jCbpQ1fHdyGZBJVMbg=",
1452                "expectedNonce": nonce, "now": "2026-08-02T10:00:02Z",
1453            });
1454            request["cosign"]["proofValue"] =
1455                json!(format!("z{}", bs58::encode([1u8; 64]).into_string()));
1456            let got = verify_live_cosign_json(&request).unwrap();
1457            assert_eq!(got["reason"], json!("cosign_signature_invalid"), "{nonce}");
1458        }
1459    }
1460
1461    #[test]
1462    fn freshness_options_are_read_strictly() {
1463        let ok = json!({"tier": "critical", "voucherEpoch": 3, "lastSeenEpoch": 3,
1464                        "currentStatus": "active", "liveCosignOk": true});
1465        assert_eq!(freshness_json(&ok).unwrap()["allow"], json!(true));
1466        let policy = json!({"critical": {"enforceEpoch": true, "requireLiveCosign": false}});
1467        let mut with_policy = ok.clone();
1468        with_policy["policy"] = policy;
1469        assert_eq!(freshness_json(&with_policy).unwrap()["allow"], json!(true));
1470        for (name, value) in [
1471            ("tier", json!(null)),
1472            ("tier", json!(1)),
1473            ("currentStatus", json!(true)),
1474            ("liveCosignOk", json!("true")),
1475            ("liveCosignOk", json!(1)),
1476            ("policy", json!([])),
1477            (
1478                "policy",
1479                json!({"critical": {"enforceEpoch": "yes", "requireLiveCosign": false}}),
1480            ),
1481            ("policy", json!({"critical": {"enforceEpoch": true}})),
1482            (
1483                "policy",
1484                json!({"critical": {"requireLiveCosign": 0, "enforceEpoch": true}}),
1485            ),
1486        ] {
1487            let mut request = ok.clone();
1488            request[name] = value.clone();
1489            assert!(freshness_json(&request).is_err(), "{name} {value}");
1490        }
1491        let mut no_tier = ok.clone();
1492        no_tier.as_object_mut().unwrap().remove("tier");
1493        assert!(freshness_json(&no_tier).is_err());
1494    }
1495
1496    fn opts() -> BuildAuthorityStateOptions {
1497        BuildAuthorityStateOptions {
1498            issuer_did: "did:web:treasury.example.com".into(),
1499            credential_id: "urn:uuid:00000000-0000-4000-8000-000000000000".into(),
1500            authority_epoch: 7,
1501            status: STATUS_ACTIVE.into(),
1502            valid_from: "2026-07-26T10:00:00Z".into(),
1503            valid_until: "2026-07-26T10:05:00Z".into(),
1504            subject_did: None,
1505        }
1506    }
1507
1508    #[test]
1509    fn builds_expected_shape() {
1510        let vc = build_authority_state(&opts()).unwrap();
1511        assert_eq!(
1512            vc["type"],
1513            json!(["VerifiableCredential", "AuthorityState"])
1514        );
1515        assert_eq!(vc["credentialSubject"]["authorityEpoch"], json!(7));
1516        assert_eq!(vc["credentialSubject"]["status"], json!("active"));
1517    }
1518
1519    #[test]
1520    fn rejects_bad_status() {
1521        let mut o = opts();
1522        o.status = "bogus".into();
1523        assert!(build_authority_state(&o).is_err());
1524    }
1525
1526    #[test]
1527    fn sign_and_verify_within_window() {
1528        let seed = [7u8; 32];
1529        let proof_opts =
1530            BuildProofOptions::new("did:web:treasury.example.com#key-1", "2026-07-26T10:00:00Z");
1531        let signed = sign_authority_state(&opts(), &seed, &proof_opts).unwrap();
1532        let pk = crate::keys::Ed25519KeyPair::from_seed(&seed).public_key();
1533        let r = verify(&signed, &pk, "2026-07-26T10:02:00Z", 30).unwrap();
1534        assert!(r.is_valid());
1535        assert_eq!(read_authority_epoch(&signed).unwrap(), 7);
1536        assert_eq!(read_authority_status(&signed).unwrap(), "active");
1537    }
1538
1539    fn cred_with_epoch(text: &str) -> Value {
1540        serde_json::from_str(&format!(
1541            r#"{{"credentialSubject":{{"authorityEpoch":{text},"status":"active"}}}}"#
1542        ))
1543        .unwrap()
1544    }
1545
1546    #[test]
1547    fn epoch_must_be_an_integer_in_range() {
1548        assert_eq!(read_authority_epoch(&cred_with_epoch("0")).unwrap(), 0);
1549        assert_eq!(read_authority_epoch(&cred_with_epoch("-0")).unwrap(), 0);
1550        assert_eq!(
1551            read_authority_epoch(&cred_with_epoch("9007199254740991")).unwrap(),
1552            MAX_AUTHORITY_EPOCH
1553        );
1554        for bad in [
1555            "9007199254740992",
1556            "9223372036854775807",
1557            "18446744073709551616",
1558            "-1",
1559            "5.0",
1560            "5.5",
1561            "1e2",
1562            "\"5\"",
1563            "true",
1564            "null",
1565        ] {
1566            assert!(
1567                read_authority_epoch(&cred_with_epoch(bad)).is_err(),
1568                "{bad} must be refused"
1569            );
1570        }
1571    }
1572
1573    fn signed_with(mutate: impl Fn(&mut Value)) -> (Value, Vec<u8>) {
1574        let seed = [7u8; 32];
1575        let proof_opts =
1576            BuildProofOptions::new("did:web:treasury.example.com#key-1", "2026-07-26T10:00:00Z");
1577        let mut vc = build_authority_state(&opts()).unwrap();
1578        mutate(&mut vc);
1579        let signed = data_integrity::sign(&vc, &seed, &proof_opts).unwrap();
1580        let pk = crate::keys::Ed25519KeyPair::from_seed(&seed).public_key();
1581        (signed, pk.to_vec())
1582    }
1583
1584    #[test]
1585    fn verify_refuses_unbound_or_malformed_states() {
1586        let now = "2026-07-26T10:02:00Z";
1587        let ok = |m: &dyn Fn(&mut Value)| {
1588            let (c, pk) = signed_with(|v| m(v));
1589            verify(&c, &pk, now, 30)
1590                .map(|r| r.is_valid())
1591                .unwrap_or(false)
1592        };
1593        assert!(ok(&|_| {}));
1594        assert!(ok(&|v| v["type"] = json!("AuthorityState")));
1595        assert!(!ok(
1596            &|v| v["issuer"] = json!({"id": "did:web:treasury.example.com"})
1597        ));
1598        assert!(!ok(&|v| v["issuer"] = json!("did:web:other.example")));
1599        assert!(!ok(&|v| v["validFrom"] = Value::Null));
1600        assert!(!ok(&|v| v["validUntil"] = Value::Null));
1601        assert!(!ok(&|v| v["credentialSubject"]["status"] = json!("bogus")));
1602        assert!(!ok(
1603            &|v| v["credentialSubject"]["authorityEpoch"] = json!(5.5)
1604        ));
1605        assert!(!ok(&|v| v["credentialSubject"] = json!([])));
1606    }
1607
1608    #[test]
1609    fn epoch_literal_floats_are_refused() {
1610        let text = |lit: &str| {
1611            format!(r#"{{"credentialSubject":{{"authorityEpoch":{lit},"status":"active"}}}}"#)
1612        };
1613        for ok in ["0", "-0", "5", "9007199254740991"] {
1614            assert!(check_epoch_literal(&text(ok)).is_ok(), "{ok}");
1615        }
1616        for bad in ["-0.0", "0.0", "5.0", "1e2", "1E2", "-0e0", "5.5", "01"] {
1617            assert!(check_epoch_literal(&text(bad)).is_err(), "{bad}");
1618        }
1619    }
1620
1621    #[test]
1622    fn type_array_entries_must_be_strings() {
1623        let now = "2026-07-26T10:02:00Z";
1624        let (c, pk) = signed_with(|v| v["type"] = json!([1, "AuthorityState"]));
1625        assert!(verify(&c, &pk, now, 30).is_err());
1626        let (c, pk) = signed_with(|v| v["type"] = json!(["AuthorityState", null]));
1627        assert!(verify(&c, &pk, now, 30).is_err());
1628    }
1629
1630    #[test]
1631    fn freshness_refuses_out_of_range_epochs() {
1632        for bad in [-1, MAX_AUTHORITY_EPOCH + 1, i64::MIN, i64::MAX] {
1633            for tier in [
1634                CONSEQUENCE_ROUTINE,
1635                CONSEQUENCE_SENSITIVE,
1636                CONSEQUENCE_CRITICAL,
1637            ] {
1638                assert!(
1639                    evaluate_authority_freshness(tier, Some(bad), Some(5), None, None).is_err()
1640                );
1641                assert!(
1642                    evaluate_authority_freshness(tier, Some(5), Some(bad), None, None).is_err()
1643                );
1644            }
1645        }
1646        assert!(evaluate_authority_freshness(
1647            CONSEQUENCE_SENSITIVE,
1648            Some(MAX_AUTHORITY_EPOCH),
1649            Some(0),
1650            None,
1651            None
1652        )
1653        .is_ok());
1654    }
1655
1656    #[test]
1657    fn routine_ignores_stale_epoch() {
1658        let v = evaluate_authority_freshness(CONSEQUENCE_ROUTINE, Some(1), Some(9), None, None)
1659            .unwrap();
1660        assert!(v.allow);
1661    }
1662
1663    #[test]
1664    fn sensitive_rejects_stale_epoch() {
1665        let v = evaluate_authority_freshness(CONSEQUENCE_SENSITIVE, Some(5), Some(7), None, None)
1666            .unwrap();
1667        assert!(!v.allow);
1668        assert_eq!(v.reason, "authority_epoch_stale:seen=7,voucher=5");
1669    }
1670
1671    #[test]
1672    fn sensitive_rejects_unknown_epoch() {
1673        // An absent epoch renders as "?" so the reason code is identical in
1674        // every language binding. Pinned by the shared interop vector.
1675        let v =
1676            evaluate_authority_freshness(CONSEQUENCE_SENSITIVE, None, Some(3), None, None).unwrap();
1677        assert!(!v.allow);
1678        assert_eq!(v.reason, "authority_epoch_unknown:voucher=?,seen=3");
1679        let v2 =
1680            evaluate_authority_freshness(CONSEQUENCE_SENSITIVE, Some(5), None, None, None).unwrap();
1681        assert_eq!(v2.reason, "authority_epoch_unknown:voucher=5,seen=?");
1682    }
1683
1684    #[test]
1685    fn sensitive_allows_current_epoch() {
1686        let v = evaluate_authority_freshness(CONSEQUENCE_SENSITIVE, Some(9), Some(9), None, None)
1687            .unwrap();
1688        assert!(v.allow);
1689    }
1690
1691    #[test]
1692    fn non_active_status_fails_closed() {
1693        let v = evaluate_authority_freshness(
1694            CONSEQUENCE_SENSITIVE,
1695            Some(9),
1696            Some(9),
1697            Some(STATUS_SUSPENDED),
1698            None,
1699        )
1700        .unwrap();
1701        assert!(!v.allow);
1702        assert_eq!(v.reason, "authority_status_not_active:status=suspended");
1703    }
1704
1705    #[test]
1706    fn critical_requires_live_cosign() {
1707        let denied =
1708            evaluate_authority_freshness(CONSEQUENCE_CRITICAL, Some(9), Some(9), None, None)
1709                .unwrap();
1710        assert!(!denied.allow);
1711        assert!(denied.reason.starts_with("live_cosign_required"));
1712        let allowed =
1713            evaluate_authority_freshness(CONSEQUENCE_CRITICAL, Some(9), Some(9), None, Some(true))
1714                .unwrap();
1715        assert!(allowed.allow);
1716    }
1717
1718    #[test]
1719    fn unknown_tier_coerces_to_critical() {
1720        let v = evaluate_authority_freshness("made-up", Some(9), Some(9), None, None).unwrap();
1721        assert_eq!(v.tier, "critical");
1722        assert!(!v.allow);
1723    }
1724
1725    #[test]
1726    fn whole_numbers_outside_64_bits_are_refused() {
1727        for text in [
1728            r#"{"a":18446744073709551616}"#,
1729            r#"{"a":-9223372036854775809}"#,
1730            r#"{"a":[1,2,99999999999999999999]}"#,
1731        ] {
1732            assert!(parse_json_no_duplicates(text).is_err(), "{text}");
1733        }
1734        for text in [
1735            r#"{"a":18446744073709551615}"#,
1736            r#"{"a":-9223372036854775808}"#,
1737            r#"{"a":1.8446744073709552e19}"#,
1738            r#"{"a":"18446744073709551616"}"#,
1739            r#"{"a\"":18446744073709551615}"#,
1740        ] {
1741            assert!(parse_json_no_duplicates(text).is_ok(), "{text}");
1742        }
1743    }
1744}