use std::collections::BTreeMap;
use serde_json::{json, Map, Value};
use crate::credentials::{
proof_bound_to_issuer, verify_temporal, VerifyResult, VC_CONTEXT_V2, VC_TYPE, VOUCH_CONTEXT_V1,
};
use crate::data_integrity::{self, BuildProofOptions};
use crate::error::{CoreError, Result};
pub const AUTHORITY_STATE_TYPE: &str = "AuthorityState";
pub const STATUS_ACTIVE: &str = "active";
pub const STATUS_SUSPENDED: &str = "suspended";
pub const STATUS_INCIDENT: &str = "incident";
pub const STATUS_EXPOSURE_BREACHED: &str = "exposure_breached";
pub const STATUS_REVOKED: &str = "revoked";
pub const AUTHORITY_STATE_MISSING: &str = "authority_state_missing";
pub const AUTHORITY_STATE_DIGEST_MISMATCH: &str = "authority_state_digest_mismatch";
pub const AUTHORITY_ISSUER_UNTRUSTED: &str = "authority_issuer_untrusted";
pub const MAX_AUTHORITY_STATE_BYTES: usize = 8192;
pub const VALID_AUTHORITY_STATUSES: [&str; 5] = [
STATUS_ACTIVE,
STATUS_SUSPENDED,
STATUS_INCIDENT,
STATUS_EXPOSURE_BREACHED,
STATUS_REVOKED,
];
pub const CONSEQUENCE_ROUTINE: &str = "routine";
pub const CONSEQUENCE_SENSITIVE: &str = "sensitive";
pub const CONSEQUENCE_CRITICAL: &str = "critical";
fn is_valid_status(status: &str) -> bool {
VALID_AUTHORITY_STATUSES.contains(&status)
}
fn epoch_str(epoch: Option<i64>) -> String {
match epoch {
Some(e) => e.to_string(),
None => "?".to_string(),
}
}
#[derive(Debug, Clone)]
pub struct BuildAuthorityStateOptions {
pub issuer_did: String,
pub credential_id: String,
pub authority_epoch: i64,
pub status: String,
pub valid_from: String,
pub valid_until: String,
pub subject_did: Option<String>,
}
pub fn build_authority_state(opts: &BuildAuthorityStateOptions) -> Result<Value> {
if !(0..=MAX_AUTHORITY_EPOCH).contains(&opts.authority_epoch) {
return Err(CoreError::Json(
"authorityEpoch must be a whole number from 0 to 2^53-1".into(),
));
}
if !is_valid_status(&opts.status) {
return Err(CoreError::Json(format!(
"status must be one of {VALID_AUTHORITY_STATUSES:?}"
)));
}
if opts.issuer_did.is_empty() {
return Err(CoreError::Json("issuer_did is required".into()));
}
let subject_did = opts
.subject_did
.clone()
.unwrap_or_else(|| opts.issuer_did.clone());
let mut subject = Map::new();
subject.insert("id".into(), json!(subject_did));
subject.insert("authorityEpoch".into(), json!(opts.authority_epoch));
subject.insert("status".into(), json!(opts.status));
let mut vc = Map::new();
vc.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
vc.insert("id".into(), json!(opts.credential_id));
vc.insert("type".into(), json!([VC_TYPE, AUTHORITY_STATE_TYPE]));
vc.insert("issuer".into(), json!(opts.issuer_did));
vc.insert("validFrom".into(), json!(opts.valid_from));
vc.insert("validUntil".into(), json!(opts.valid_until));
vc.insert("credentialSubject".into(), Value::Object(subject));
Ok(Value::Object(vc))
}
pub fn sign_authority_state(
opts: &BuildAuthorityStateOptions,
raw_private_seed: &[u8],
proof_opts: &BuildProofOptions,
) -> Result<Value> {
let cred = build_authority_state(opts)?;
data_integrity::sign(&cred, raw_private_seed, proof_opts)
}
pub const MAX_AUTHORITY_EPOCH: i64 = (1 << 53) - 1;
fn epoch_of(v: &Value) -> Option<i64> {
let Value::Number(n) = v else {
return None;
};
if let Some(i) = n.as_i64() {
return (0..=MAX_AUTHORITY_EPOCH).contains(&i).then_some(i);
}
match n.as_f64() {
Some(f) if f == 0.0 && f.is_sign_negative() => Some(0),
_ => None,
}
}
pub fn check_epoch_literal(credential_text: &str) -> Result<()> {
use serde_json::value::RawValue;
type Raw = std::collections::HashMap<String, Box<RawValue>>;
let json_err = |e: serde_json::Error| CoreError::Json(e.to_string());
let top: Raw = serde_json::from_str(credential_text).map_err(json_err)?;
let Some(subject) = top.get("credentialSubject") else {
return Ok(());
};
let Ok(subject) = serde_json::from_str::<Raw>(subject.get()) else {
return Ok(());
};
let Some(epoch) = subject.get("authorityEpoch") else {
return Ok(());
};
let lit = epoch.get().trim();
let digits = lit.strip_prefix('-').unwrap_or(lit);
let is_int = !digits.is_empty()
&& digits.bytes().all(|b| b.is_ascii_digit())
&& (digits.len() == 1 || !digits.starts_with('0'));
if lit.starts_with(|c: char| c == '-' || c.is_ascii_digit()) && !is_int {
return Err(CoreError::Json(
"authorityEpoch must be written as an integer".into(),
));
}
Ok(())
}
fn authority_issuer(credential: &Value) -> Option<&str> {
let s = match credential.get("issuer")? {
Value::String(s) => s.as_str(),
Value::Array(a) => a.first()?.as_str()?,
_ => return None,
};
(!s.is_empty()).then_some(s)
}
pub fn verify(
credential: &Value,
raw_public_key: &[u8],
now_iso: &str,
clock_skew_seconds: i64,
) -> Result<VerifyResult> {
let is_authority_state = match credential.get("type") {
Some(Value::Array(arr)) => {
arr.iter().all(Value::is_string)
&& arr.iter().any(|t| t.as_str() == Some(AUTHORITY_STATE_TYPE))
}
Some(Value::String(s)) => s == AUTHORITY_STATE_TYPE,
_ => false,
};
if !is_authority_state {
return Err(CoreError::Json(
"credential is not an AuthorityState".into(),
));
}
let signature_valid = data_integrity::verify_proof(credential, raw_public_key)?;
let bound = match (authority_issuer(credential), credential.get("proof")) {
(Some(issuer), Some(proof)) => proof_bound_to_issuer(proof, issuer),
_ => false,
};
let own_key = match authority_issuer(credential) {
Some(issuer) if issuer.starts_with("did:key:") => {
did_key_ed25519(issuer).as_deref() == Some(raw_public_key)
}
_ => true,
};
if !credential
.get("credentialSubject")
.map(Value::is_object)
.unwrap_or(false)
{
return Err(CoreError::Json(
"credentialSubject must be an object".into(),
));
}
read_authority_epoch(credential)?;
read_authority_status(credential)?;
crate::time::check_clock_skew(clock_skew_seconds)?;
crate::time::parse_protocol_time_ns(now_iso)?;
let time_valid = verify_temporal(credential, now_iso, clock_skew_seconds).unwrap_or(false);
Ok(VerifyResult {
proof_valid: signature_valid && bound && own_key,
time_valid,
chain_valid: true,
})
}
pub fn read_authority_epoch(credential: &Value) -> Result<i64> {
credential
.get("credentialSubject")
.and_then(|s| s.get("authorityEpoch"))
.and_then(epoch_of)
.ok_or_else(|| CoreError::Json("missing or invalid authorityEpoch".into()))
}
pub fn read_authority_status(credential: &Value) -> Result<String> {
credential
.get("credentialSubject")
.and_then(|s| s.get("status"))
.and_then(|v| v.as_str())
.filter(|s| is_valid_status(s))
.map(|s| s.to_string())
.ok_or_else(|| CoreError::Json("missing or invalid status".into()))
}
pub fn did_key_ed25519(did: &str) -> Option<Vec<u8>> {
let mk = did.strip_prefix("did:key:")?;
let decoded = crate::multikey::decode(mk).ok()?;
(decoded.algorithm == "Ed25519" && decoded.raw_key.len() == 32).then_some(decoded.raw_key)
}
pub fn parse_json_no_duplicates(text: &str) -> Result<Value> {
struct NoDup(Value);
struct Visit;
impl<'de> serde::de::Visitor<'de> for Visit {
type Value = Value;
fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
f.write_str("JSON")
}
fn visit_bool<E>(self, v: bool) -> std::result::Result<Value, E> {
Ok(Value::Bool(v))
}
fn visit_i64<E>(self, v: i64) -> std::result::Result<Value, E> {
Ok(Value::from(v))
}
fn visit_u64<E>(self, v: u64) -> std::result::Result<Value, E> {
Ok(Value::from(v))
}
fn visit_f64<E: serde::de::Error>(self, v: f64) -> std::result::Result<Value, E> {
serde_json::Number::from_f64(v)
.map(Value::Number)
.ok_or_else(|| E::custom("a number that is not finite"))
}
fn visit_str<E>(self, v: &str) -> std::result::Result<Value, E> {
Ok(Value::String(v.to_owned()))
}
fn visit_string<E>(self, v: String) -> std::result::Result<Value, E> {
Ok(Value::String(v))
}
fn visit_unit<E>(self) -> std::result::Result<Value, E> {
Ok(Value::Null)
}
fn visit_seq<A: serde::de::SeqAccess<'de>>(
self,
mut seq: A,
) -> std::result::Result<Value, A::Error> {
let mut out = Vec::new();
while let Some(NoDup(v)) = seq.next_element()? {
out.push(v);
}
Ok(Value::Array(out))
}
fn visit_map<A: serde::de::MapAccess<'de>>(
self,
mut map: A,
) -> std::result::Result<Value, A::Error> {
let mut out = Map::new();
while let Some(key) = map.next_key::<String>()? {
if out.contains_key(&key) {
return Err(serde::de::Error::custom(format!("duplicate key {key:?}")));
}
let NoDup(v) = map.next_value()?;
out.insert(key, v);
}
Ok(Value::Object(out))
}
}
impl<'de> serde::Deserialize<'de> for NoDup {
fn deserialize<D: serde::Deserializer<'de>>(d: D) -> std::result::Result<Self, D::Error> {
d.deserialize_any(Visit).map(NoDup)
}
}
if let Some(literal) = integer_out_of_range(text) {
return Err(CoreError::Json(format!(
"the whole number {literal} is outside the 64-bit range, so it has no exact \
JSON reading"
)));
}
serde_json::from_str::<NoDup>(text)
.map(|NoDup(v)| v)
.map_err(|e| CoreError::Json(e.to_string()))
}
fn integer_out_of_range(text: &str) -> Option<String> {
let bytes = text.as_bytes();
let mut i = 0;
while i < bytes.len() {
match bytes[i] {
b'"' => {
i += 1;
while i < bytes.len() && bytes[i] != b'"' {
if bytes[i] == b'\\' {
i += 1;
}
i += 1;
}
i += 1;
}
b'-' | b'0'..=b'9' => {
let start = i;
i += 1;
while i < bytes.len()
&& matches!(bytes[i], b'0'..=b'9' | b'.' | b'e' | b'E' | b'+' | b'-')
{
i += 1;
}
let literal = &text[start..i];
let integer = !literal.contains(['.', 'e', 'E']);
if integer && literal.parse::<i64>().is_err() && literal.parse::<u64>().is_err() {
return Some(literal.chars().take(40).collect());
}
}
_ => i += 1,
}
}
None
}
pub fn parse_authority_state_text(text: &str) -> Result<Value> {
let value = parse_json_no_duplicates(text)?;
check_epoch_literal(text)?;
Ok(value)
}
pub fn authority_state_digest(credential: &Value) -> Result<String> {
let Some(obj) = credential.as_object() else {
return Err(CoreError::Json(
"an AuthorityState must be a JSON object".into(),
));
};
let mut body = obj.clone();
body.remove("proof");
crate::grant_chain::grant_digest(&Value::Object(body))
.map_err(|e| CoreError::Json(e.to_string()))
}
pub fn authority_state_digest_text(text: &str) -> Result<String> {
authority_state_digest(&parse_json_no_duplicates(text)?)
}
pub const EMPTY_TRUSTED_AUTHORITIES: &str = "the trusted-authority list is empty: name at least one authority, or leave trusted_authorities out";
fn empty_trusted_authorities() -> CoreError {
CoreError::Json(EMPTY_TRUSTED_AUTHORITIES.into())
}
pub fn trusted_authority_keys(
entries: &[(String, Option<Vec<u8>>)],
) -> Result<BTreeMap<String, Vec<u8>>> {
if entries.is_empty() {
return Err(empty_trusted_authorities());
}
let mut out = BTreeMap::new();
for (did, key) in entries {
if !did.starts_with("did:") {
return Err(CoreError::Json(format!(
"trusted authority {did:?} is not a DID"
)));
}
let own = if did.starts_with("did:key:") {
did_key_ed25519(did)
} else {
None
};
let resolved = match key {
Some(k) if k.len() == 32 && crate::keys::strict_verifying_key(k).is_ok() => {
Some(k.clone())
}
Some(_) => None,
None => own.clone(),
};
let Some(resolved) = resolved else {
return Err(CoreError::Json(format!(
"trusted authority {did}: no usable Ed25519 key"
)));
};
if let Some(own) = own {
if own != resolved {
return Err(CoreError::Json(format!(
"trusted authority {did}: the key is not the one its DID names"
)));
}
}
out.insert(did.clone(), resolved);
}
Ok(out)
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AuthorityStatePassport {
pub issuer_did: String,
pub subject_did: String,
pub authority_epoch: i64,
pub status: String,
pub valid_from: String,
pub valid_until: String,
}
impl AuthorityStatePassport {
pub fn is_active(&self) -> bool {
self.status == STATUS_ACTIVE
}
pub fn to_json(&self) -> Value {
json!({
"issuerDid": self.issuer_did,
"subjectDid": self.subject_did,
"authorityEpoch": self.authority_epoch,
"status": self.status,
"validFrom": self.valid_from,
"validUntil": self.valid_until,
})
}
}
pub fn trusted_authorities_from_json(value: &Value) -> Result<BTreeMap<String, Vec<u8>>> {
use base64::{engine::general_purpose::STANDARD, Engine};
let mut entries: Vec<(String, Option<Vec<u8>>)> = Vec::new();
match value {
Value::Object(map) => {
for (did, key) in map {
let key = match key {
Value::Null => None,
Value::String(k) => Some(STANDARD.decode(k).map_err(|_| {
CoreError::Json(format!("trusted authority {did}: the key is not base64"))
})?),
_ => {
return Err(CoreError::Json(format!(
"trusted authority {did}: the key must be base64 text or null"
)))
}
};
entries.push((did.clone(), key));
}
}
Value::Array(list) => {
for did in list {
let Some(did) = did.as_str() else {
return Err(CoreError::Json("trusted authorities must be DIDs".into()));
};
entries.push((did.to_string(), None));
}
}
_ => {
return Err(CoreError::Json(
"trusted authorities must be {DID: key} or a list of did:key DIDs".into(),
))
}
}
trusted_authority_keys(&entries)
}
pub fn voucher_authority_json(voucher: &Value) -> Value {
match voucher_authority(voucher) {
Some(a) => json!({
"digest": a.digest,
"epoch": a.epoch,
"status": a.status,
"issuer": a.issuer,
}),
None => Value::Null,
}
}
pub fn verify_authority_state_bound(
credential: &Value,
public_key: Option<&[u8]>,
trusted_authorities: Option<&BTreeMap<String, Vec<u8>>>,
issuer_did: Option<&str>,
now_iso: &str,
clock_skew_seconds: i64,
) -> Result<Option<AuthorityStatePassport>> {
crate::time::check_clock_skew(clock_skew_seconds)?;
if trusted_authorities.is_some_and(BTreeMap::is_empty) {
return Err(empty_trusted_authorities());
}
if !credential.is_object() {
return Ok(None);
}
let Some(claimed) = authority_issuer(credential) else {
return Ok(None);
};
if issuer_did.is_some_and(|expected| expected != claimed) {
return Ok(None);
}
let key: Vec<u8> = if let Some(trusted) = trusted_authorities {
match trusted.get(claimed) {
Some(k) => k.clone(),
None => return Ok(None),
}
} else if let Some(k) = public_key {
k.to_vec()
} else {
match did_key_ed25519(claimed) {
Some(k) => k,
None => return Ok(None),
}
};
let Ok(result) = verify(credential, &key, now_iso, clock_skew_seconds) else {
return Ok(None);
};
if !result.is_valid() {
return Ok(None);
}
let (Ok(epoch), Ok(status)) = (
read_authority_epoch(credential),
read_authority_status(credential),
) else {
return Ok(None);
};
let subject_did = credential["credentialSubject"]
.get("id")
.and_then(Value::as_str)
.filter(|s| !s.is_empty())
.unwrap_or(claimed)
.to_string();
Ok(Some(AuthorityStatePassport {
issuer_did: claimed.to_string(),
subject_did,
authority_epoch: epoch,
status,
valid_from: credential["validFrom"]
.as_str()
.unwrap_or_default()
.to_string(),
valid_until: credential["validUntil"]
.as_str()
.unwrap_or_default()
.to_string(),
}))
}
pub fn verify_authority_state_bound_text(
credential_text: &str,
public_key: Option<&[u8]>,
trusted_authorities: Option<&BTreeMap<String, Vec<u8>>>,
issuer_did: Option<&str>,
now_iso: &str,
clock_skew_seconds: i64,
) -> Result<Option<AuthorityStatePassport>> {
crate::time::check_clock_skew(clock_skew_seconds)?;
if trusted_authorities.is_some_and(BTreeMap::is_empty) {
return Err(empty_trusted_authorities());
}
let Ok(credential) = parse_authority_state_text(credential_text) else {
return Ok(None);
};
verify_authority_state_bound(
&credential,
public_key,
trusted_authorities,
issuer_did,
now_iso,
clock_skew_seconds,
)
}
pub const VOUCHER_AUTHORITY_FIELDS: [&str; 4] = [
"authorityStateDigest",
"authorityEpoch",
"authorityStatus",
"authorityIssuer",
];
pub fn voucher_authority_problem(subject: &Value) -> Option<String> {
let obj = subject.as_object()?;
let present: Vec<&str> = VOUCHER_AUTHORITY_FIELDS
.iter()
.copied()
.filter(|name| obj.contains_key(*name))
.collect();
if present.is_empty() || present == ["authorityEpoch"] {
return None;
}
if present.len() != VOUCHER_AUTHORITY_FIELDS.len() {
return Some("the authority fields must be all present or all absent".into());
}
for name in ["authorityStateDigest", "authorityStatus", "authorityIssuer"] {
if obj[name].as_str().is_none_or(str::is_empty) {
return Some(format!("{name} must be a non-empty string"));
}
}
None
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct VoucherAuthority {
pub digest: String,
pub epoch: i64,
pub status: String,
pub issuer: String,
}
pub fn voucher_authority(voucher: &Value) -> Option<VoucherAuthority> {
let subject = voucher.get("credentialSubject")?;
let obj = subject.as_object()?;
if voucher_authority_problem(subject).is_some() || !obj.contains_key("authorityStateDigest") {
return None;
}
Some(VoucherAuthority {
digest: obj["authorityStateDigest"].as_str()?.to_string(),
epoch: epoch_of(&obj["authorityEpoch"])?,
status: obj["authorityStatus"].as_str()?.to_string(),
issuer: obj["authorityIssuer"].as_str()?.to_string(),
})
}
pub fn voucher_authority_epoch(voucher: &Value) -> Option<i64> {
voucher_authority(voucher).map(|a| a.epoch)
}
pub fn check_attached_authority_state(
state: Option<&Value>,
trusted_authorities: &BTreeMap<String, Vec<u8>>,
voucher: Option<&Value>,
caller: Option<&str>,
now_iso: &str,
clock_skew_seconds: i64,
) -> Result<std::result::Result<AuthorityStatePassport, &'static str>> {
crate::time::check_clock_skew(clock_skew_seconds)?;
if trusted_authorities.is_empty() {
return Err(empty_trusted_authorities());
}
let Some(state) = state.filter(|s| s.is_object()) else {
return Ok(Err(AUTHORITY_STATE_MISSING));
};
let Some(issuer) = authority_issuer(state).filter(|i| trusted_authorities.contains_key(*i))
else {
return Ok(Err(AUTHORITY_ISSUER_UNTRUSTED));
};
let passport = verify_authority_state_bound(
state,
None,
Some(trusted_authorities),
None,
now_iso,
clock_skew_seconds,
)?;
let Some(passport) = passport.filter(|p| caller == Some(p.subject_did.as_str())) else {
return Ok(Err(AUTHORITY_STATE_MISSING));
};
let Ok(digest) = authority_state_digest(state) else {
return Ok(Err(AUTHORITY_STATE_MISSING));
};
match voucher.and_then(voucher_authority) {
Some(recorded) if recorded.digest == digest && recorded.issuer == issuer => {
Ok(Ok(passport))
}
_ => Ok(Err(AUTHORITY_STATE_DIGEST_MISMATCH)),
}
}
pub fn check_attached_authority_state_text(
state_text: Option<&str>,
trusted_authorities: &BTreeMap<String, Vec<u8>>,
voucher: Option<&Value>,
caller: Option<&str>,
now_iso: &str,
clock_skew_seconds: i64,
) -> Result<std::result::Result<AuthorityStatePassport, &'static str>> {
crate::time::check_clock_skew(clock_skew_seconds)?;
if trusted_authorities.is_empty() {
return Err(empty_trusted_authorities());
}
let parsed = match state_text {
None => None,
Some(text) => match parse_authority_state_text(text) {
Ok(v) => Some(v),
Err(_) => return Ok(Err(AUTHORITY_STATE_MISSING)),
},
};
check_attached_authority_state(
parsed.as_ref(),
trusted_authorities,
voucher,
caller,
now_iso,
clock_skew_seconds,
)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct FreshnessRule {
pub enforce_epoch: bool,
pub require_live_cosign: bool,
}
pub fn freshness_rule(tier: &str) -> FreshnessRule {
match tier {
CONSEQUENCE_ROUTINE => FreshnessRule {
enforce_epoch: false,
require_live_cosign: false,
},
CONSEQUENCE_SENSITIVE => FreshnessRule {
enforce_epoch: true,
require_live_cosign: false,
},
_ => FreshnessRule {
enforce_epoch: true,
require_live_cosign: true,
},
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AuthorityFreshnessVerdict {
pub allow: bool,
pub tier: String,
pub reason: String,
}
pub fn evaluate_authority_freshness(
tier: &str,
voucher_epoch: Option<i64>,
last_seen_epoch: Option<i64>,
current_status: Option<&str>,
live_cosign_ok: Option<bool>,
) -> Result<AuthorityFreshnessVerdict> {
let policy: BTreeMap<String, FreshnessRule> = [
CONSEQUENCE_ROUTINE,
CONSEQUENCE_SENSITIVE,
CONSEQUENCE_CRITICAL,
]
.iter()
.map(|t| (t.to_string(), freshness_rule(t)))
.collect();
evaluate_authority_freshness_with(
tier,
voucher_epoch,
last_seen_epoch,
current_status,
live_cosign_ok,
&policy,
)
}
pub fn evaluate_authority_freshness_with(
tier: &str,
voucher_epoch: Option<i64>,
last_seen_epoch: Option<i64>,
current_status: Option<&str>,
live_cosign_ok: Option<bool>,
policy: &BTreeMap<String, FreshnessRule>,
) -> Result<AuthorityFreshnessVerdict> {
for (name, e) in [
("voucher_epoch", voucher_epoch),
("last_seen_epoch", last_seen_epoch),
] {
if let Some(e) = e {
if !(0..=MAX_AUTHORITY_EPOCH).contains(&e) {
return Err(CoreError::Json(format!(
"{name} must be a whole number from 0 to 2^53 - 1"
)));
}
}
}
let canonical_tier = match tier {
CONSEQUENCE_ROUTINE | CONSEQUENCE_SENSITIVE | CONSEQUENCE_CRITICAL => tier,
_ => CONSEQUENCE_CRITICAL,
};
let rule = policy
.get(canonical_tier)
.copied()
.unwrap_or(FreshnessRule {
enforce_epoch: true,
require_live_cosign: true,
});
let mk = |allow: bool, reason: String| AuthorityFreshnessVerdict {
allow,
tier: canonical_tier.to_string(),
reason,
};
if !rule.enforce_epoch && !rule.require_live_cosign {
return Ok(mk(true, "routine tier: time-decay only".into()));
}
if let Some(status) = current_status {
if status != STATUS_ACTIVE {
return Ok(mk(
false,
format!("authority_status_not_active:status={status}"),
));
}
}
if rule.require_live_cosign && live_cosign_ok != Some(true) {
return Ok(mk(
false,
format!("live_cosign_required:tier={canonical_tier}"),
));
}
if rule.enforce_epoch {
match (voucher_epoch, last_seen_epoch) {
(Some(v), Some(seen)) => {
if v < seen {
return Ok(mk(
false,
format!("authority_epoch_stale:seen={seen},voucher={v}"),
));
}
}
_ => {
return Ok(mk(
false,
format!(
"authority_epoch_unknown:voucher={},seen={}",
epoch_str(voucher_epoch),
epoch_str(last_seen_epoch)
),
));
}
}
}
Ok(mk(
true,
format!("{canonical_tier} tier: authority state fresh"),
))
}
pub fn freshness_json(req: &Value) -> Result<Value> {
let epoch = |name: &str| -> Result<Option<i64>> {
match req.get(name).filter(|v| !v.is_null()) {
None => Ok(None),
Some(v) => v
.as_i64()
.filter(|e| (0..=MAX_AUTHORITY_EPOCH).contains(e))
.map(Some)
.ok_or_else(|| {
CoreError::Json(format!("{name} must be a whole number from 0 to 2^53-1"))
}),
}
};
let wrong = |what: String| CoreError::Json(what);
let tier = match req.get("tier") {
Some(Value::String(t)) => t.as_str(),
_ => return Err(wrong("tier must be text".into())),
};
let status = match req.get("currentStatus") {
None | Some(Value::Null) => None,
Some(Value::String(s)) => Some(s.as_str()),
Some(_) => return Err(wrong("currentStatus must be text or null".into())),
};
let cosign = match req.get("liveCosignOk") {
None | Some(Value::Null) => None,
Some(Value::Bool(b)) => Some(*b),
Some(_) => return Err(wrong("liveCosignOk must be true, false or null".into())),
};
let policy_map = match req.get("policy") {
None | Some(Value::Null) => None,
Some(Value::Object(map)) => Some(map),
Some(_) => return Err(wrong("policy must be an object".into())),
};
let verdict = match policy_map {
None => evaluate_authority_freshness(
tier,
epoch("voucherEpoch")?,
epoch("lastSeenEpoch")?,
status,
cosign,
)?,
Some(map) => {
let mut policy = BTreeMap::new();
for (name, rule) in map {
let flag = |k: &str| -> Result<bool> {
rule.get(k)
.and_then(Value::as_bool)
.ok_or_else(|| wrong(format!("policy.{name}.{k} must be true or false")))
};
policy.insert(
name.clone(),
FreshnessRule {
enforce_epoch: flag("enforceEpoch")?,
require_live_cosign: flag("requireLiveCosign")?,
},
);
}
evaluate_authority_freshness_with(
tier,
epoch("voucherEpoch")?,
epoch("lastSeenEpoch")?,
status,
cosign,
&policy,
)?
}
};
Ok(json!({
"allow": verdict.allow,
"tier": verdict.tier,
"reason": verdict.reason,
}))
}
pub fn rules_json(req: &Value) -> Result<Value> {
let text = |name: &str| {
req.get(name)
.and_then(Value::as_str)
.unwrap_or("")
.to_string()
};
let parse = |t: &str| -> Result<Value> {
serde_json::from_str(t).map_err(|e| CoreError::Json(e.to_string()))
};
match req.get("fn").and_then(Value::as_str).unwrap_or("") {
"build" => {
let epoch = match req.get("authorityEpoch") {
Some(Value::Number(n)) => n.as_i64().ok_or_else(|| {
CoreError::Json("authorityEpoch must be a whole number from 0 to 2^53-1".into())
})?,
_ => {
return Err(CoreError::Json(
"authorityEpoch must be a whole number from 0 to 2^53-1".into(),
))
}
};
let opts = BuildAuthorityStateOptions {
issuer_did: text("issuerDid"),
credential_id: text("credentialId"),
authority_epoch: epoch,
status: text("status"),
valid_from: text("validFrom"),
valid_until: text("validUntil"),
subject_did: req
.get("subjectDid")
.and_then(Value::as_str)
.filter(|s| !s.is_empty())
.map(str::to_string),
};
build_authority_state(&opts)
}
"verify" => {
let cred_text = text("credential");
check_epoch_literal(&cred_text)?;
let key = {
use base64::{engine::general_purpose::STANDARD, Engine};
STANDARD
.decode(text("publicKey"))
.map_err(|e| CoreError::Json(format!("base64: {e}")))?
};
let skew = match req.get("clockSkewSeconds") {
None | Some(Value::Null) => 30,
Some(v) => crate::time::clock_skew_from_json(v)?,
};
let r = verify(&parse(&cred_text)?, &key, &text("now"), skew)?;
Ok(
json!({"proofValid": r.proof_valid, "timeValid": r.time_valid, "valid": r.is_valid()}),
)
}
"readEpoch" => {
let cred_text = text("credential");
check_epoch_literal(&cred_text)?;
Ok(json!(read_authority_epoch(&parse(&cred_text)?)?))
}
"readStatus" => Ok(json!(read_authority_status(&parse(&text("credential"))?)?)),
"freshnessRule" => {
let r = freshness_rule(&text("tier"));
Ok(json!({"enforceEpoch": r.enforce_epoch, "requireLiveCosign": r.require_live_cosign}))
}
other => Err(CoreError::Json(format!(
"unknown authority state rule {:?}",
other.chars().take(40).collect::<String>()
))),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn freshness_options_are_read_strictly() {
let ok = json!({"tier": "critical", "voucherEpoch": 3, "lastSeenEpoch": 3,
"currentStatus": "active", "liveCosignOk": true});
assert_eq!(freshness_json(&ok).unwrap()["allow"], json!(true));
let policy = json!({"critical": {"enforceEpoch": true, "requireLiveCosign": false}});
let mut with_policy = ok.clone();
with_policy["policy"] = policy;
assert_eq!(freshness_json(&with_policy).unwrap()["allow"], json!(true));
for (name, value) in [
("tier", json!(null)),
("tier", json!(1)),
("currentStatus", json!(true)),
("liveCosignOk", json!("true")),
("liveCosignOk", json!(1)),
("policy", json!([])),
(
"policy",
json!({"critical": {"enforceEpoch": "yes", "requireLiveCosign": false}}),
),
("policy", json!({"critical": {"enforceEpoch": true}})),
(
"policy",
json!({"critical": {"requireLiveCosign": 0, "enforceEpoch": true}}),
),
] {
let mut request = ok.clone();
request[name] = value.clone();
assert!(freshness_json(&request).is_err(), "{name} {value}");
}
let mut no_tier = ok.clone();
no_tier.as_object_mut().unwrap().remove("tier");
assert!(freshness_json(&no_tier).is_err());
}
fn opts() -> BuildAuthorityStateOptions {
BuildAuthorityStateOptions {
issuer_did: "did:web:treasury.example.com".into(),
credential_id: "urn:uuid:00000000-0000-4000-8000-000000000000".into(),
authority_epoch: 7,
status: STATUS_ACTIVE.into(),
valid_from: "2026-07-26T10:00:00Z".into(),
valid_until: "2026-07-26T10:05:00Z".into(),
subject_did: None,
}
}
#[test]
fn builds_expected_shape() {
let vc = build_authority_state(&opts()).unwrap();
assert_eq!(
vc["type"],
json!(["VerifiableCredential", "AuthorityState"])
);
assert_eq!(vc["credentialSubject"]["authorityEpoch"], json!(7));
assert_eq!(vc["credentialSubject"]["status"], json!("active"));
}
#[test]
fn rejects_bad_status() {
let mut o = opts();
o.status = "bogus".into();
assert!(build_authority_state(&o).is_err());
}
#[test]
fn sign_and_verify_within_window() {
let seed = [7u8; 32];
let proof_opts =
BuildProofOptions::new("did:web:treasury.example.com#key-1", "2026-07-26T10:00:00Z");
let signed = sign_authority_state(&opts(), &seed, &proof_opts).unwrap();
let pk = crate::keys::Ed25519KeyPair::from_seed(&seed).public_key();
let r = verify(&signed, &pk, "2026-07-26T10:02:00Z", 30).unwrap();
assert!(r.is_valid());
assert_eq!(read_authority_epoch(&signed).unwrap(), 7);
assert_eq!(read_authority_status(&signed).unwrap(), "active");
}
fn cred_with_epoch(text: &str) -> Value {
serde_json::from_str(&format!(
r#"{{"credentialSubject":{{"authorityEpoch":{text},"status":"active"}}}}"#
))
.unwrap()
}
#[test]
fn epoch_must_be_an_integer_in_range() {
assert_eq!(read_authority_epoch(&cred_with_epoch("0")).unwrap(), 0);
assert_eq!(read_authority_epoch(&cred_with_epoch("-0")).unwrap(), 0);
assert_eq!(
read_authority_epoch(&cred_with_epoch("9007199254740991")).unwrap(),
MAX_AUTHORITY_EPOCH
);
for bad in [
"9007199254740992",
"9223372036854775807",
"18446744073709551616",
"-1",
"5.0",
"5.5",
"1e2",
"\"5\"",
"true",
"null",
] {
assert!(
read_authority_epoch(&cred_with_epoch(bad)).is_err(),
"{bad} must be refused"
);
}
}
fn signed_with(mutate: impl Fn(&mut Value)) -> (Value, Vec<u8>) {
let seed = [7u8; 32];
let proof_opts =
BuildProofOptions::new("did:web:treasury.example.com#key-1", "2026-07-26T10:00:00Z");
let mut vc = build_authority_state(&opts()).unwrap();
mutate(&mut vc);
let signed = data_integrity::sign(&vc, &seed, &proof_opts).unwrap();
let pk = crate::keys::Ed25519KeyPair::from_seed(&seed).public_key();
(signed, pk.to_vec())
}
#[test]
fn verify_refuses_unbound_or_malformed_states() {
let now = "2026-07-26T10:02:00Z";
let ok = |m: &dyn Fn(&mut Value)| {
let (c, pk) = signed_with(|v| m(v));
verify(&c, &pk, now, 30)
.map(|r| r.is_valid())
.unwrap_or(false)
};
assert!(ok(&|_| {}));
assert!(ok(&|v| v["type"] = json!("AuthorityState")));
assert!(!ok(
&|v| v["issuer"] = json!({"id": "did:web:treasury.example.com"})
));
assert!(!ok(&|v| v["issuer"] = json!("did:web:other.example")));
assert!(!ok(&|v| v["validFrom"] = Value::Null));
assert!(!ok(&|v| v["validUntil"] = Value::Null));
assert!(!ok(&|v| v["credentialSubject"]["status"] = json!("bogus")));
assert!(!ok(
&|v| v["credentialSubject"]["authorityEpoch"] = json!(5.5)
));
assert!(!ok(&|v| v["credentialSubject"] = json!([])));
}
#[test]
fn epoch_literal_floats_are_refused() {
let text = |lit: &str| {
format!(r#"{{"credentialSubject":{{"authorityEpoch":{lit},"status":"active"}}}}"#)
};
for ok in ["0", "-0", "5", "9007199254740991"] {
assert!(check_epoch_literal(&text(ok)).is_ok(), "{ok}");
}
for bad in ["-0.0", "0.0", "5.0", "1e2", "1E2", "-0e0", "5.5", "01"] {
assert!(check_epoch_literal(&text(bad)).is_err(), "{bad}");
}
}
#[test]
fn type_array_entries_must_be_strings() {
let now = "2026-07-26T10:02:00Z";
let (c, pk) = signed_with(|v| v["type"] = json!([1, "AuthorityState"]));
assert!(verify(&c, &pk, now, 30).is_err());
let (c, pk) = signed_with(|v| v["type"] = json!(["AuthorityState", null]));
assert!(verify(&c, &pk, now, 30).is_err());
}
#[test]
fn freshness_refuses_out_of_range_epochs() {
for bad in [-1, MAX_AUTHORITY_EPOCH + 1, i64::MIN, i64::MAX] {
for tier in [
CONSEQUENCE_ROUTINE,
CONSEQUENCE_SENSITIVE,
CONSEQUENCE_CRITICAL,
] {
assert!(
evaluate_authority_freshness(tier, Some(bad), Some(5), None, None).is_err()
);
assert!(
evaluate_authority_freshness(tier, Some(5), Some(bad), None, None).is_err()
);
}
}
assert!(evaluate_authority_freshness(
CONSEQUENCE_SENSITIVE,
Some(MAX_AUTHORITY_EPOCH),
Some(0),
None,
None
)
.is_ok());
}
#[test]
fn routine_ignores_stale_epoch() {
let v = evaluate_authority_freshness(CONSEQUENCE_ROUTINE, Some(1), Some(9), None, None)
.unwrap();
assert!(v.allow);
}
#[test]
fn sensitive_rejects_stale_epoch() {
let v = evaluate_authority_freshness(CONSEQUENCE_SENSITIVE, Some(5), Some(7), None, None)
.unwrap();
assert!(!v.allow);
assert_eq!(v.reason, "authority_epoch_stale:seen=7,voucher=5");
}
#[test]
fn sensitive_rejects_unknown_epoch() {
let v =
evaluate_authority_freshness(CONSEQUENCE_SENSITIVE, None, Some(3), None, None).unwrap();
assert!(!v.allow);
assert_eq!(v.reason, "authority_epoch_unknown:voucher=?,seen=3");
let v2 =
evaluate_authority_freshness(CONSEQUENCE_SENSITIVE, Some(5), None, None, None).unwrap();
assert_eq!(v2.reason, "authority_epoch_unknown:voucher=5,seen=?");
}
#[test]
fn sensitive_allows_current_epoch() {
let v = evaluate_authority_freshness(CONSEQUENCE_SENSITIVE, Some(9), Some(9), None, None)
.unwrap();
assert!(v.allow);
}
#[test]
fn non_active_status_fails_closed() {
let v = evaluate_authority_freshness(
CONSEQUENCE_SENSITIVE,
Some(9),
Some(9),
Some(STATUS_SUSPENDED),
None,
)
.unwrap();
assert!(!v.allow);
assert_eq!(v.reason, "authority_status_not_active:status=suspended");
}
#[test]
fn critical_requires_live_cosign() {
let denied =
evaluate_authority_freshness(CONSEQUENCE_CRITICAL, Some(9), Some(9), None, None)
.unwrap();
assert!(!denied.allow);
assert!(denied.reason.starts_with("live_cosign_required"));
let allowed =
evaluate_authority_freshness(CONSEQUENCE_CRITICAL, Some(9), Some(9), None, Some(true))
.unwrap();
assert!(allowed.allow);
}
#[test]
fn unknown_tier_coerces_to_critical() {
let v = evaluate_authority_freshness("made-up", Some(9), Some(9), None, None).unwrap();
assert_eq!(v.tier, "critical");
assert!(!v.allow);
}
#[test]
fn whole_numbers_outside_64_bits_are_refused() {
for text in [
r#"{"a":18446744073709551616}"#,
r#"{"a":-9223372036854775809}"#,
r#"{"a":[1,2,99999999999999999999]}"#,
] {
assert!(parse_json_no_duplicates(text).is_err(), "{text}");
}
for text in [
r#"{"a":18446744073709551615}"#,
r#"{"a":-9223372036854775808}"#,
r#"{"a":1.8446744073709552e19}"#,
r#"{"a":"18446744073709551616"}"#,
r#"{"a\"":18446744073709551615}"#,
] {
assert!(parse_json_no_duplicates(text).is_ok(), "{text}");
}
}
}