use std::collections::BTreeMap;
use serde_json::{json, Map, Value};
use crate::authority_state::{self, FreshnessRule, MAX_AUTHORITY_EPOCH};
use crate::data_integrity;
use crate::error::{CoreError, Result};
use crate::grant_chain::{py_repr, py_repr_float};
use crate::time::{check_clock_skew, parse_protocol_time_ns};
pub const SESSION_VOUCHER_TYPE: &str = "SessionVoucher";
pub const MAX_VOUCHER_PROOFS: usize = 64;
pub const REASON_NO_SESSION: &str = "no live session";
pub const REASON_LOW_TRUST: &str = "trust below threshold";
pub const REASON_AUTHORITY: &str = "authority not fresh";
const MICROS: i128 = 1_000_000;
fn bad(msg: impl Into<String>) -> CoreError {
CoreError::Json(msg.into())
}
fn micros_of(text: &str) -> Result<i128> {
Ok(parse_protocol_time_ns(text)?.div_euclid(1000))
}
fn py_float(v: &Value) -> Option<f64> {
match v {
Value::Number(n) => n.as_f64(),
Value::Bool(b) => Some(if *b { 1.0 } else { 0.0 }),
Value::String(s) => s.trim().parse::<f64>().ok(),
_ => None,
}
}
fn float_member(subject: &Map<String, Value>, name: &str) -> Result<f64> {
match subject.get(name) {
None => Err(bad(format!(
"credentialSubject.{name} must be a number: '{name}'"
))),
Some(v) => py_float(v).ok_or_else(|| {
bad(format!(
"credentialSubject.{name} must be a number: could not convert {} to float",
py_repr(Some(v))
))
}),
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct TrustInputs {
pub initial_trust: f64,
pub decay_lambda: f64,
pub issued_at_us: i128,
}
pub fn trust_inputs(voucher: &Value) -> Result<TrustInputs> {
let obj = voucher
.as_object()
.ok_or_else(|| bad("session_voucher must be a dict"))?;
let types: Vec<Value> = match obj.get("type") {
None => Vec::new(),
Some(Value::String(s)) => vec![Value::String(s.clone())],
Some(Value::Array(a)) => a.clone(),
Some(other) => vec![other.clone()],
};
if !types
.iter()
.any(|t| t.as_str() == Some(SESSION_VOUCHER_TYPE))
{
return Err(bad(format!(
"credential type must include {SESSION_VOUCHER_TYPE}, got {}",
py_repr(Some(&Value::Array(types)))
)));
}
let subject = obj
.get("credentialSubject")
.and_then(Value::as_object)
.ok_or_else(|| bad("credentialSubject is required"))?;
let initial_trust = float_member(subject, "initialTrust")?;
let decay_lambda = float_member(subject, "decayLambda")?;
for (name, value) in [
("initialTrust", initial_trust),
("decayLambda", decay_lambda),
] {
if !value.is_finite() {
return Err(bad(format!(
"{name} must be a finite number, got {}",
py_repr_float(value)
)));
}
}
if initial_trust < 0.0 {
return Err(bad(format!(
"initialTrust must be non-negative, got {}",
py_repr_float(initial_trust)
)));
}
if decay_lambda < 0.0 {
return Err(bad(format!(
"decayLambda must be non-negative, got {}",
py_repr_float(decay_lambda)
)));
}
let valid_from = obj.get("validFrom");
let truthy = match valid_from {
None | Some(Value::Null) | Some(Value::Bool(false)) => false,
Some(Value::String(s)) => !s.is_empty(),
Some(Value::Number(n)) => n.as_f64() != Some(0.0),
Some(Value::Array(a)) => !a.is_empty(),
Some(Value::Object(o)) => !o.is_empty(),
Some(Value::Bool(true)) => true,
};
if !truthy {
return Err(bad("validFrom is required"));
}
let text = valid_from
.and_then(Value::as_str)
.ok_or_else(|| bad("malformed validFrom: not a protocol time"))?;
let issued_at_us =
micros_of(text).map_err(|_| bad(format!("malformed validFrom: {}", not_a_time(text))))?;
Ok(TrustInputs {
initial_trust,
decay_lambda,
issued_at_us,
})
}
fn elapsed_seconds(inputs: &TrustInputs, at_us: i128) -> f64 {
let elapsed = (at_us - inputs.issued_at_us) as f64 / MICROS as f64;
if elapsed < 0.0 {
0.0
} else {
elapsed
}
}
fn trust_of(inputs: &TrustInputs, elapsed: f64) -> f64 {
let exponent = -inputs.decay_lambda * elapsed;
if exponent < -700.0 {
return 0.0;
}
inputs.initial_trust * det_exp(exponent)
}
fn det_exp(x: f64) -> f64 {
const HALF: [f64; 2] = [0.5, -0.5];
const LN2HI: f64 = 6.931_471_803_691_238_164_90e-01; const LN2LO: f64 = 1.908_214_929_270_587_700_02e-10; const INVLN2: f64 = 1.442_695_040_888_963_387_00e+00; const P1: f64 = 1.666_666_666_666_660_190_37e-01; const P2: f64 = -2.777_777_777_701_559_338_42e-03; const P3: f64 = 6.613_756_321_437_934_361_17e-05; const P4: f64 = -1.653_390_220_546_525_153_90e-06; const P5: f64 = 4.138_136_797_057_238_460_39e-08; let x1p1023 = f64::from_bits(0x7fe0_0000_0000_0000);
let mut x = x;
let mut hx = (x.to_bits() >> 32) as u32;
let sign = (hx >> 31) as i32;
hx &= 0x7fff_ffff;
if hx >= 0x4086_232b {
if x.is_nan() {
return x;
}
if x > 709.782_712_893_383_973_096 {
return x * x1p1023;
}
if x < -745.133_219_101_941_108_42 {
return 0.0;
}
}
let (hi, lo, k): (f64, f64, i32);
if hx > 0x3fd6_2e42 {
if hx >= 0x3ff0_a2b2 {
k = (INVLN2 * x + HALF[sign as usize]) as i32;
} else {
k = 1 - sign - sign;
}
hi = x - k as f64 * LN2HI;
lo = k as f64 * LN2LO;
x = hi - lo;
} else if hx > 0x3e30_0000 {
k = 0;
hi = x;
lo = 0.0;
} else {
return 1.0 + x;
}
let xx = x * x;
let c = x - xx * (P1 + xx * (P2 + xx * (P3 + xx * (P4 + xx * P5))));
let y = 1.0 + (x * c / (2.0 - c) - lo + hi);
if k == 0 {
y
} else {
det_scalbn(y, k)
}
}
fn det_scalbn(x: f64, mut n: i32) -> f64 {
let x1p1023 = f64::from_bits(0x7fe0_0000_0000_0000);
let x1p53 = f64::from_bits(0x4340_0000_0000_0000);
let x1p_1022 = f64::from_bits(0x0010_0000_0000_0000);
let mut y = x;
if n > 1023 {
y *= x1p1023;
n -= 1023;
if n > 1023 {
y *= x1p1023;
n -= 1023;
if n > 1023 {
n = 1023;
}
}
} else if n < -1022 {
y *= x1p_1022 * x1p53;
n += 1022 - 53;
if n < -1022 {
y *= x1p_1022 * x1p53;
n += 1022 - 53;
if n < -1022 {
n = -1022;
}
}
}
y * f64::from_bits(((0x3ff + n) as u64) << 52)
}
pub fn compute_trust_at(voucher: &Value, at_us: i128) -> Result<f64> {
let inputs = trust_inputs(voucher)?;
Ok(trust_of(&inputs, elapsed_seconds(&inputs, at_us)))
}
#[derive(Debug, Clone, PartialEq)]
pub struct TrustEvaluation {
pub trust: f64,
pub threshold: f64,
pub passed: bool,
pub elapsed_seconds: f64,
pub initial_trust: f64,
pub decay_lambda: f64,
pub evaluated_at_us: i128,
}
pub fn evaluate_trust(voucher: &Value, threshold: f64, at_us: i128) -> Result<TrustEvaluation> {
if threshold < 0.0 {
return Err(bad(format!(
"threshold must be non-negative, got {}",
py_repr_float(threshold)
)));
}
let inputs = trust_inputs(voucher)?;
let elapsed = elapsed_seconds(&inputs, at_us);
let trust = trust_of(&inputs, elapsed);
Ok(TrustEvaluation {
trust,
threshold,
passed: trust >= threshold,
elapsed_seconds: elapsed,
initial_trust: inputs.initial_trust,
decay_lambda: inputs.decay_lambda,
evaluated_at_us: at_us,
})
}
pub fn key_from_json(v: &Value) -> Option<(Vec<u8>, Option<String>)> {
if let Some(s) = v.as_str() {
if s.starts_with("did:key:") {
let did = s.split('#').next().unwrap_or(s).to_string();
return authority_state::did_key_ed25519(&did).map(|k| (k, Some(did)));
}
}
match crate::decision::key_entry_from_json(v) {
crate::decision::KeyEntry::Ed25519(k) if k.len() == 32 => Some((k, None)),
_ => None,
}
}
pub fn validator_key_map(value: &Value) -> Result<Vec<(String, Vec<u8>)>> {
let items: Vec<(String, Option<&Value>)> = match value {
Value::Object(m) => m.iter().map(|(d, k)| (d.clone(), Some(k))).collect(),
Value::Array(a) => a
.iter()
.map(|d| match d.as_str() {
Some(s) => Ok((s.to_string(), None)),
None => Err(bad(format!(
"expected validator {} is not a DID",
py_repr(Some(d))
))),
})
.collect::<Result<_>>()?,
_ => {
return Err(bad(
"expected validators must be a {DID: key} mapping or a list of did:keys",
))
}
};
if items.is_empty() {
return Err(bad("expected validators must name at least one validator"));
}
let mut out: Vec<(String, Vec<u8>)> = Vec::new();
for (did, given) in items {
if !did.starts_with("did:") {
return Err(bad(format!(
"expected validator {} is not a DID",
crate::grant_chain::py_repr_str(&did)
)));
}
let own = if did.starts_with("did:key:") {
authority_state::did_key_ed25519(&did)
} else {
None
};
let key = match given.filter(|g| !g.is_null()) {
None => own.clone(),
Some(g) => key_from_json(g).map(|(k, _)| k),
};
let Some(key) = key else {
return Err(bad(format!(
"no usable Ed25519 key for expected validator {did}"
)));
};
if let Some(own) = &own {
if own != &key {
return Err(bad(format!(
"the key given for {did} is not the key that DID carries"
)));
}
}
if let Some((other, _)) = out.iter().find(|(_, k)| k == &key) {
return Err(bad(format!("{did} and {other} share one key")));
}
out.push((did, key));
}
Ok(out)
}
fn issuer_list(voucher: &Map<String, Value>) -> Vec<Value> {
match voucher.get("issuer") {
Some(Value::Array(a)) => a.clone(),
other => vec![other.cloned().unwrap_or(Value::Null)],
}
}
fn proofs_of(voucher: &Map<String, Value>) -> Vec<Value> {
match voucher.get("proof") {
Some(Value::Array(a)) => a.clone(),
other => vec![other.cloned().unwrap_or(Value::Null)],
}
}
fn is_epoch(v: &Value) -> bool {
v.as_u64().is_some_and(|e| e <= MAX_AUTHORITY_EPOCH as u64)
|| v.as_i64().is_some_and(|e| e == 0)
}
fn voucher_basics(voucher: &Value, at_us: i128) -> std::result::Result<(i128, i128), String> {
let Some(obj) = voucher.as_object() else {
return Err("voucher_malformed:not an object".into());
};
if let Err(e) = compute_trust_at(voucher, at_us) {
return Err(format!("voucher_malformed:{}", short(&message(&e), 200)));
}
let until = match obj.get("validUntil") {
Some(Value::String(s)) if !s.is_empty() => s,
_ => return Err("voucher_malformed:validUntil is required".into()),
};
let from = obj.get("validFrom").and_then(Value::as_str).unwrap_or("");
let read = |t: &str| micros_of(t).map_err(|_| not_a_time(t));
let (from, until) = match read(from).and_then(|f| Ok((f, read(until)?))) {
Ok(w) => w,
Err(e) => return Err(format!("voucher_malformed:{}", short(&e, 200))),
};
if proofs_of(obj).len() > MAX_VOUCHER_PROOFS {
return Err("voucher_malformed:too many proofs".into());
}
let subject = obj.get("credentialSubject");
if let Some(epoch) = subject.and_then(|s| s.get("authorityEpoch")) {
if !is_epoch(epoch) {
return Err("voucher_malformed:authorityEpoch must be 0 to 2^53 - 1".into());
}
}
if let Some(problem) = subject.and_then(authority_state::voucher_authority_problem) {
return Err(format!("voucher_malformed:{problem}"));
}
Ok((from, until))
}
fn message(e: &CoreError) -> String {
match e {
CoreError::Json(m) => m.clone(),
other => other.to_string(),
}
}
fn not_a_time(text: &str) -> String {
format!(
"not a protocol time: {}",
crate::grant_chain::py_repr_str(text)
)
}
fn short(s: &str, n: usize) -> String {
s.chars().take(n).collect()
}
fn subject_id(voucher: &Value) -> Option<&str> {
voucher.get("credentialSubject")?.get("id")?.as_str()
}
fn self_issued(voucher: &Map<String, Value>) -> bool {
let subject = voucher
.get("credentialSubject")
.and_then(|s| s.get("id"))
.and_then(Value::as_str);
subject.is_some_and(|id| issuer_list(voucher).iter().any(|i| i.as_str() == Some(id)))
}
fn subject_keys(voucher: Option<&Value>, subject_key: Option<&[u8]>) -> Vec<Vec<u8>> {
let mut keys: Vec<Vec<u8>> = subject_key.map(|k| vec![k.to_vec()]).unwrap_or_default();
if let Some(id) = voucher.and_then(subject_id) {
if id.starts_with("did:key:") {
let did = id.split('#').next().unwrap_or(id);
if let Some(k) = authority_state::did_key_ed25519(did) {
keys.push(k);
}
}
}
keys
}
fn proof_verifies(
unsigned: &Map<String, Value>,
proofs: &[Value],
issuers: &[Value],
key: &[u8],
only_did: Option<&str>,
) -> bool {
for proof in proofs {
let Some(p) = proof.as_object() else { continue };
if p.get("proofPurpose").and_then(Value::as_str) != Some("assertionMethod") {
continue;
}
let Some(vm) = p.get("verificationMethod").and_then(Value::as_str) else {
continue;
};
let vm_did = vm.split('#').next().unwrap_or(vm);
if !issuers.iter().any(|i| i.as_str() == Some(vm_did)) {
continue;
}
if only_did.is_some_and(|d| d != vm_did) {
continue;
}
let mut candidate = unsigned.clone();
candidate.insert("proof".into(), proof.clone());
if matches!(
data_integrity::verify_proof(&Value::Object(candidate), key),
Ok(true)
) {
return true;
}
}
false
}
fn window_reason(from: i128, until: i128, at_us: i128, skew: i128) -> Option<&'static str> {
let skew_us = skew / 1000;
if at_us - until > skew_us {
return Some("voucher_expired");
}
if from - at_us > skew_us {
return Some("voucher_not_yet_valid");
}
None
}
fn unsigned_of(voucher: &Map<String, Value>) -> Map<String, Value> {
let mut out = voucher.clone();
out.remove("proof");
out
}
pub fn verify_session_voucher(
voucher: &Value,
validator_key: Option<&Value>,
at_us: i128,
clock_skew_seconds: i64,
allow_self_issued: bool,
subject_key: Option<&[u8]>,
) -> Result<std::result::Result<(), String>> {
let skew = check_clock_skew(clock_skew_seconds)?;
let agent_keys = subject_keys(Some(voucher), subject_key);
let (from, until) = match voucher_basics(voucher, at_us) {
Ok(w) => w,
Err(reason) => return Ok(Err(reason)),
};
let obj = voucher.as_object().expect("checked by voucher_basics");
let Some(given) = validator_key.filter(|k| !k.is_null()) else {
return Ok(Err("voucher_unverified:no validator key supplied".into()));
};
let Some((key, key_did)) = key_from_json(given) else {
return Ok(Err(
"voucher_unverified:validator key is not an Ed25519 key".into(),
));
};
if !proof_verifies(
&unsigned_of(obj),
&proofs_of(obj),
&issuer_list(obj),
&key,
key_did.as_deref(),
) {
return Ok(Err("voucher_signature_invalid".into()));
}
if let Some(reason) = window_reason(from, until, at_us, skew) {
return Ok(Err(reason.into()));
}
if !allow_self_issued && (self_issued(obj) || agent_keys.contains(&key)) {
return Ok(Err("voucher_self_issued".into()));
}
Ok(Ok(()))
}
pub fn verify_session_voucher_quorum(
voucher: &Value,
validators: &[(String, Vec<u8>)],
threshold: i64,
at_us: i128,
clock_skew_seconds: i64,
subject_key: Option<&[u8]>,
) -> Result<std::result::Result<(), String>> {
let skew = check_clock_skew(clock_skew_seconds)?;
if threshold < 1 || threshold as usize > validators.len() {
return Err(bad(format!(
"threshold must be a whole number from 1 to {}",
validators.len()
)));
}
let copies: Vec<&Value> = match voucher {
Value::Object(_) => vec![voucher],
Value::Array(a) if !a.is_empty() => a.iter().collect(),
_ => {
return Ok(Err(
"voucher_malformed:not an object or a list of copies".into()
))
}
};
if copies.len() > MAX_VOUCHER_PROOFS || !copies.iter().all(|c| c.is_object()) {
return Ok(Err(
"voucher_malformed:copies must be 1 to 64 objects".into()
));
}
let base = copies[0];
let (from, until) = match voucher_basics(base, at_us) {
Ok(w) => w,
Err(reason) => return Ok(Err(reason)),
};
let base_obj = base.as_object().expect("checked above");
let unsigned = unsigned_of(base_obj);
let canonical = crate::jcs::canonicalize(&Value::Object(unsigned.clone()));
for other in &copies[1..] {
let other = unsigned_of(other.as_object().expect("checked above"));
if crate::jcs::canonicalize(&Value::Object(other)) != canonical {
return Ok(Err("voucher_copies_differ".into()));
}
}
if self_issued(base_obj) {
return Ok(Err("voucher_self_issued".into()));
}
let mut agent_keys = subject_keys(None, subject_key);
agent_keys.extend(subject_keys(Some(base), None));
let proofs: Vec<Value> = copies
.iter()
.flat_map(|c| proofs_of(c.as_object().expect("checked above")))
.collect();
if proofs.len() > MAX_VOUCHER_PROOFS {
return Ok(Err("voucher_malformed:too many proofs".into()));
}
let issuers = issuer_list(base_obj);
let mut count = 0i64;
for (did, key) in validators {
if issuers.iter().any(|i| i.as_str() == Some(did.as_str()))
&& proof_verifies(&unsigned, &proofs, &issuers, key, Some(did))
{
if agent_keys.contains(key) {
return Ok(Err("voucher_self_issued".into()));
}
count += 1;
}
}
if count < threshold {
return Ok(Err(format!("voucher_quorum_not_met:{count}<{threshold}")));
}
if let Some(reason) = window_reason(from, until, at_us, skew) {
return Ok(Err(reason.into()));
}
Ok(Ok(()))
}
pub type Refusal = Option<(String, String)>;
fn note(text: &str) -> String {
if text.chars().count() <= 120 {
text.to_string()
} else {
format!("{}...", text.chars().take(117).collect::<String>())
}
}
fn refuse(reason: &str, note_text: impl Into<String>) -> Refusal {
Some((reason.to_string(), note_text.into()))
}
#[allow(clippy::too_many_arguments)]
pub fn session_refusal(
require_session: bool,
trust_threshold: f64,
voucher: Option<&Value>,
issuer: &str,
issuer_key: Option<&[u8]>,
validators: &[(String, Vec<u8>)],
quorum: i64,
at_us: i128,
clock_skew_seconds: i64,
) -> Refusal {
let Some(voucher) = voucher else {
return if require_session {
refuse(REASON_NO_SESSION, "voucher_missing")
} else {
None
};
};
if validators.is_empty() {
return refuse(
REASON_NO_SESSION,
"voucher_unverified:no validator key supplied",
);
}
let one = match voucher {
Value::Array(a) if !a.is_empty() => &a[0],
v => v,
};
let verdict = if validators.len() == 1 && quorum <= 1 && !voucher.is_array() {
let (did, key) = &validators[0];
let key_text =
Value::String(crate::multikey::encode_ed25519_public(key).unwrap_or_default());
verify_session_voucher(
voucher,
Some(&key_text),
at_us,
clock_skew_seconds,
false,
issuer_key,
)
.map(|r| {
r.and_then(|()| {
let issuers = voucher.as_object().map(issuer_ids).unwrap_or_default();
if issuers.iter().any(|i| i == did) {
Ok(())
} else {
Err("voucher_signature_invalid".to_string())
}
})
})
} else {
verify_session_voucher_quorum(
voucher,
validators,
quorum.min(validators.len() as i64),
at_us,
clock_skew_seconds,
issuer_key,
)
};
match verdict {
Err(_) => return refuse(REASON_NO_SESSION, "voucher_malformed:ValueError"),
Ok(Err(why)) => return refuse(REASON_NO_SESSION, note(&why)),
Ok(Ok(())) => {}
}
let subject = subject_id(one).filter(|s| !s.is_empty());
let Some(subject) = subject else {
return refuse(REASON_NO_SESSION, "voucher_subject_missing");
};
if subject != issuer {
return refuse(REASON_NO_SESSION, "voucher_subject_mismatch");
}
match evaluate_trust(one, trust_threshold, at_us) {
Err(_) => refuse(REASON_NO_SESSION, "voucher_malformed:TrustEntropyError"),
Ok(e) if !e.passed => refuse(
REASON_LOW_TRUST,
format!(
"trust_below_threshold:{:.4}<{}",
e.trust,
py_repr_float(trust_threshold)
),
),
Ok(_) => None,
}
}
fn issuer_ids(voucher: &Map<String, Value>) -> Vec<String> {
issuer_list(voucher)
.iter()
.filter_map(|i| match i {
Value::String(s) => Some(s.clone()),
Value::Object(o) => o.get("id").and_then(Value::as_str).map(String::from),
_ => None,
})
.collect()
}
#[derive(Debug, Clone, Default)]
pub struct AuthorityFacts {
pub last_seen_epoch: Option<Value>,
pub current_status: Option<String>,
pub live_cosign_ok: Option<bool>,
pub state: Option<Value>,
pub trusted_authorities: Option<Value>,
pub voucher_epoch: Option<Value>,
pub equivocations: Option<Value>,
pub equivocation_keys: BTreeMap<String, Value>,
}
fn equivocated(
proofs: &Value,
caller: &str,
caller_key: Option<&[u8]>,
chain: &[(String, String)],
keys: &BTreeMap<String, Value>,
) -> Option<&'static str> {
let key_of = |did: &str| keys.get(did).and_then(key_from_json).map(|(k, _)| k);
let mut dids: Vec<(String, Option<Vec<u8>>)> = vec![(
caller.to_string(),
caller_key.map(<[u8]>::to_vec).or_else(|| key_of(caller)),
)];
for (issuer, subject) in chain {
for did in [issuer, subject] {
if !dids.iter().any(|(known, _)| known == did) {
dids.push((did.clone(), key_of(did)));
}
}
}
let items: Vec<Value> = match proofs {
Value::Array(a) => a.clone(),
other => vec![other.clone()],
};
let named: Vec<&str> = items
.iter()
.filter_map(|p| p.get("agent").and_then(Value::as_str))
.collect();
let mut unknown = false;
for (did, key) in dids {
let key = key.or_else(|| {
did.starts_with("did:key:")
.then(|| authority_state::did_key_ed25519(&did))
.flatten()
});
let Some(key) = key else {
unknown = unknown || named.contains(&did.as_str());
continue;
};
if crate::lineage::proof_applies_to(&items, &did, &key).is_some() {
return Some("agent_equivocated");
}
}
unknown.then_some("equivocation_key_unknown")
}
fn attached_authority(
state: Option<&Value>,
trusted: Option<&Value>,
voucher: Option<&Value>,
caller: &str,
now: &str,
skew: i64,
) -> Result<std::result::Result<(i64, String), &'static str>> {
let keys = match trusted {
Some(t) if !t.is_null() => authority_state::trusted_authorities_from_json(t)?,
_ => BTreeMap::new(),
};
let parsed = match state {
None | Some(Value::Null) => None,
Some(Value::String(text)) => authority_state::parse_authority_state_text(text).ok(),
Some(v) => Some(v.clone()),
};
let Some(parsed) = parsed.filter(Value::is_object) else {
return Ok(Err(authority_state::AUTHORITY_STATE_MISSING));
};
if keys.is_empty() {
return Ok(Err(authority_state::AUTHORITY_ISSUER_UNTRUSTED));
}
Ok(authority_state::check_attached_authority_state(
Some(&parsed),
&keys,
voucher,
Some(caller),
now,
skew,
)?
.map(|p| (p.authority_epoch, p.status)))
}
#[allow(clippy::too_many_arguments)]
pub fn authority_refusal(
tier: &str,
rule: FreshnessRule,
voucher: Option<&Value>,
issuer: &str,
issuer_key: Option<&[u8]>,
chain: &[(String, String)],
facts: &AuthorityFacts,
now: &str,
clock_skew_seconds: i64,
) -> Result<Refusal> {
if let Some(proofs) = facts.equivocations.as_ref().filter(|p| truthy(p)) {
if let Some(problem) =
equivocated(proofs, issuer, issuer_key, chain, &facts.equivocation_keys)
{
return Ok(refuse(REASON_AUTHORITY, problem));
}
}
let state = facts.state.as_ref().filter(|s| !s.is_null());
if !rule.enforce_epoch && !rule.require_live_cosign && state.is_none() {
return Ok(None);
}
let mut last_seen: Option<i64> = None;
if let Some(v) = facts.last_seen_epoch.as_ref().filter(|v| !v.is_null()) {
if !is_epoch(v) {
return Ok(refuse(
REASON_AUTHORITY,
"the last seen epoch is not a whole number",
));
}
last_seen = v.as_i64();
}
let mut status = facts.current_status.clone();
let voucher_epoch: Option<i64>;
let trusted = facts.trusted_authorities.as_ref().filter(|t| !t.is_null());
if trusted.is_some() || state.is_some() {
match attached_authority(state, trusted, voucher, issuer, now, clock_skew_seconds)? {
Err(problem) => {
if tier != authority_state::CONSEQUENCE_ROUTINE || state.is_some() {
return Ok(refuse(REASON_AUTHORITY, problem));
}
return Ok(None);
}
Ok((epoch, stated_status)) => {
voucher_epoch = Some(epoch);
if last_seen.is_none() {
last_seen = Some(epoch);
}
if status.as_deref().is_none_or(str::is_empty) {
status = Some(stated_status);
}
}
}
} else {
match facts.voucher_epoch.as_ref().filter(|v| !v.is_null()) {
Some(v) if !is_epoch(v) => {
let seen = last_seen.map_or("?".to_string(), |s| s.to_string());
return Ok(refuse(
REASON_AUTHORITY,
format!("authority_epoch_unknown:voucher=?,seen={seen}"),
));
}
Some(v) => voucher_epoch = v.as_i64(),
None => {
voucher_epoch = voucher
.filter(|v| v.is_object())
.and_then(authority_state::voucher_authority)
.map(|r| r.epoch);
}
}
}
if !rule.enforce_epoch && !rule.require_live_cosign {
return Ok(None);
}
let mut policy = BTreeMap::new();
policy.insert(tier.to_string(), rule);
let verdict = authority_state::evaluate_authority_freshness_with(
tier,
voucher_epoch,
last_seen,
status.as_deref(),
facts.live_cosign_ok,
&policy,
)?;
if verdict.allow {
Ok(None)
} else {
Ok(refuse(REASON_AUTHORITY, note(&verdict.reason)))
}
}
fn truthy(v: &Value) -> bool {
match v {
Value::Null => false,
Value::Bool(b) => *b,
Value::Array(a) => !a.is_empty(),
Value::Object(o) => !o.is_empty(),
Value::String(s) => !s.is_empty(),
Value::Number(n) => n.as_f64() != Some(0.0),
}
}
fn now_us(obj: &Map<String, Value>) -> Result<(String, i128)> {
let now = obj
.get("now")
.and_then(Value::as_str)
.ok_or_else(|| bad("now must be a protocol time"))?;
Ok((now.to_string(), micros_of(now)?))
}
fn strict_bool(obj: &Map<String, Value>, name: &str) -> Result<Option<bool>> {
match obj.get(name) {
None => Ok(None),
Some(Value::Bool(b)) => Ok(Some(*b)),
Some(_) => Err(bad(format!("{name} must be true or false"))),
}
}
fn strict_number(obj: &Map<String, Value>, name: &str) -> Result<Option<f64>> {
match obj.get(name) {
None => Ok(None),
Some(Value::Number(n)) => match n.as_f64() {
Some(x) if x.is_finite() => Ok(Some(x)),
_ => Err(bad(format!("{name} must be a finite number"))),
},
Some(_) => Err(bad(format!("{name} must be a finite number"))),
}
}
fn strict_whole(obj: &Map<String, Value>, name: &str) -> Result<Option<i64>> {
match obj.get(name) {
None => Ok(None),
Some(v) => v
.as_i64()
.map(Some)
.ok_or_else(|| bad(format!("{name} must be a whole number"))),
}
}
fn skew_of(obj: &Map<String, Value>) -> Result<i64> {
match obj.get("clockSkewSeconds") {
None => Ok(30),
Some(v) => crate::time::clock_skew_from_json(v),
}
}
fn opt_key(obj: &Map<String, Value>, name: &str) -> Result<Option<Vec<u8>>> {
match obj.get(name).filter(|v| !v.is_null()) {
None => Ok(None),
Some(v) => key_from_json(v)
.map(|(k, _)| Some(k))
.ok_or_else(|| bad(format!("{name} is not an Ed25519 key"))),
}
}
fn refusal_json(r: Refusal) -> Value {
match r {
None => json!({ "refusal": null }),
Some((reason, note)) => json!({ "refusal": { "reason": reason, "note": note } }),
}
}
pub fn session_refusal_json(request: &Value) -> Result<Value> {
let obj = request
.as_object()
.ok_or_else(|| bad("the request must be a JSON object"))?;
let (_, at) = now_us(obj)?;
let skew = skew_of(obj)?;
let validators = match obj.get("validators").filter(|v| !v.is_null()) {
None => Vec::new(),
Some(Value::Object(m)) if m.is_empty() => Vec::new(),
Some(Value::Array(a)) if a.is_empty() => Vec::new(),
Some(v) => validator_key_map(v)?,
};
let required = |name: &str| bad(format!("{name} is required when validators are named"));
let threshold = match strict_number(obj, "trustThreshold")? {
Some(t) => t,
None if validators.is_empty() => 0.0,
None => return Err(required("trustThreshold")),
};
let quorum = match strict_whole(obj, "quorum")? {
Some(q) if q >= 1 => q,
Some(_) => return Err(bad("quorum must be a whole number of at least 1")),
None if validators.is_empty() => 1,
None => return Err(required("quorum")),
};
let require_session = strict_bool(obj, "requireSession")?.unwrap_or(false);
let issuer = obj.get("issuer").and_then(Value::as_str).unwrap_or("");
let voucher = obj.get("voucher").filter(|v| !v.is_null());
Ok(refusal_json(session_refusal(
require_session,
threshold,
voucher,
issuer,
opt_key(obj, "issuerKey")?.as_deref(),
&validators,
quorum,
at,
skew,
)))
}
pub fn authority_refusal_json(request: &Value) -> Result<Value> {
let obj = request
.as_object()
.ok_or_else(|| bad("the request must be a JSON object"))?;
let (now, _) = now_us(obj)?;
let skew = skew_of(obj)?;
let rule = FreshnessRule {
enforce_epoch: strict_bool(obj, "enforceEpoch")?.unwrap_or(false),
require_live_cosign: strict_bool(obj, "requireLiveCosign")?.unwrap_or(false),
};
let chain: Vec<(String, String)> = obj
.get("chain")
.and_then(Value::as_array)
.map(|links| {
links
.iter()
.map(|l| {
let text = |k: &str| l.get(k).and_then(Value::as_str).unwrap_or("").to_string();
(text("issuer"), text("subject"))
})
.collect()
})
.unwrap_or_default();
let f = obj.get("facts").and_then(Value::as_object);
let member = |k: &str| f.and_then(|m| m.get(k)).filter(|v| !v.is_null()).cloned();
let facts = AuthorityFacts {
last_seen_epoch: member("lastSeenEpoch"),
current_status: member("currentStatus").and_then(|v| v.as_str().map(String::from)),
live_cosign_ok: member("liveCosignOk").and_then(|v| v.as_bool()),
state: member("state"),
trusted_authorities: member("trustedAuthorities"),
voucher_epoch: member("voucherEpoch"),
equivocations: member("equivocations"),
equivocation_keys: member("equivocationKeys")
.and_then(|v| v.as_object().cloned())
.map(|m| m.into_iter().collect())
.unwrap_or_default(),
};
let voucher = obj
.get("voucher")
.filter(|v| !v.is_null())
.map(|v| match v {
Value::Array(a) if !a.is_empty() => &a[0],
v => v,
});
let tier = obj.get("tier").and_then(Value::as_str).unwrap_or("");
let issuer = obj.get("issuer").and_then(Value::as_str).unwrap_or("");
Ok(refusal_json(authority_refusal(
tier,
rule,
voucher,
issuer,
opt_key(obj, "issuerKey")?.as_deref(),
&chain,
&facts,
&now,
skew,
)?))
}
pub fn verify_session_voucher_json(request: &Value) -> Result<Value> {
let obj = request
.as_object()
.ok_or_else(|| bad("the request must be a JSON object"))?;
let (_, at) = now_us(obj)?;
let skew = skew_of(obj)?;
let voucher = obj.get("voucher").cloned().unwrap_or(Value::Null);
let subject = opt_key(obj, "subjectKey")?;
let validators_value = obj.get("validators").cloned().unwrap_or(Value::Null);
let threshold = strict_whole(obj, "threshold")?.unwrap_or(1);
let allow_self_issued = strict_bool(obj, "allowSelfIssued")?.unwrap_or(false);
let single = match &validators_value {
Value::String(_) => Some(validators_value.clone()),
_ => None,
};
let verdict = if let Some(key) = single {
verify_session_voucher(
&voucher,
Some(&key),
at,
skew,
allow_self_issued,
subject.as_deref(),
)?
} else {
let validators = validator_key_map(&validators_value)?;
verify_session_voucher_quorum(
&voucher,
&validators,
threshold,
at,
skew,
subject.as_deref(),
)?
};
Ok(match verdict {
Ok(()) => json!({"ok": true, "reason": "voucher_ok"}),
Err(reason) => json!({"ok": false, "reason": reason}),
})
}
pub fn evaluate_trust_json(request: &Value) -> Result<Value> {
let obj = request
.as_object()
.ok_or_else(|| bad("the request must be a JSON object"))?;
let (_, at) = now_us(obj)?;
let voucher = obj.get("voucher").cloned().unwrap_or(Value::Null);
let threshold = strict_number(obj, "threshold")?.ok_or_else(|| bad("threshold is required"))?;
let e = evaluate_trust(&voucher, threshold, at)?;
Ok(json!({
"trust": e.trust,
"threshold": e.threshold,
"passed": e.passed,
"elapsedSeconds": e.elapsed_seconds,
"initialTrust": e.initial_trust,
"decayLambda": e.decay_lambda,
}))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::data_integrity::BuildProofOptions;
fn did_key(seed: u8) -> (String, [u8; 32]) {
let s = [seed; 32];
let kp = crate::keys::Ed25519KeyPair::from_seed_slice(&s).unwrap();
(
format!(
"did:key:{}",
crate::multikey::encode_ed25519_public(&kp.public_key()).unwrap()
),
s,
)
}
fn voucher(validator: &str, seed: &[u8; 32], subject: &str) -> Value {
let unsigned = json!({
"@context": ["https://www.w3.org/ns/credentials/v2"],
"type": ["VerifiableCredential", "SessionVoucher"],
"issuer": validator,
"validFrom": "2026-01-01T00:00:00Z",
"validUntil": "2026-01-01T00:05:00Z",
"credentialSubject": {"id": subject, "initialTrust": 1.0, "decayLambda": 0.001},
});
let opts = BuildProofOptions::new(format!("{validator}#key-1"), "2026-01-01T00:00:00Z");
data_integrity::sign(&unsigned, seed, &opts).unwrap()
}
fn at(t: &str) -> i128 {
micros_of(t).unwrap()
}
#[test]
fn one_validator() {
let (v, vs) = did_key(1);
let (agent, _) = did_key(2);
let doc = voucher(&v, &vs, &agent);
let key = json!(v.clone());
let now = at("2026-01-01T00:01:00Z");
assert_eq!(
verify_session_voucher(&doc, Some(&key), now, 30, false, None).unwrap(),
Ok(())
);
let late = at("2026-01-01T00:06:00Z");
assert_eq!(
verify_session_voucher(&doc, Some(&key), late, 30, false, None).unwrap(),
Err("voucher_expired".into())
);
let (other, _) = did_key(3);
assert_eq!(
verify_session_voucher(&doc, Some(&json!(other)), now, 30, false, None).unwrap(),
Err("voucher_signature_invalid".into())
);
let mut tampered = doc.clone();
tampered["credentialSubject"]["initialTrust"] = json!(0.99);
assert_eq!(
verify_session_voucher(&tampered, Some(&key), now, 30, false, None).unwrap(),
Err("voucher_signature_invalid".into())
);
}
#[test]
fn self_issued_is_refused() {
let (agent, seed) = did_key(4);
let doc = voucher(&agent, &seed, &agent);
let now = at("2026-01-01T00:01:00Z");
assert_eq!(
verify_session_voucher(&doc, Some(&json!(agent)), now, 30, false, None).unwrap(),
Err("voucher_self_issued".into())
);
}
#[test]
fn guard_session_checks() {
let (v, vs) = did_key(5);
let (agent, _) = did_key(6);
let doc = voucher(&v, &vs, &agent);
let validators = validator_key_map(&json!([v])).unwrap();
let now = at("2026-01-01T00:01:00Z");
assert_eq!(
session_refusal(true, 0.5, Some(&doc), &agent, None, &validators, 1, now, 30),
None
);
let (stranger, _) = did_key(7);
assert_eq!(
session_refusal(
true,
0.5,
Some(&doc),
&stranger,
None,
&validators,
1,
now,
30
)
.unwrap()
.1,
"voucher_subject_mismatch"
);
let low = session_refusal(
true,
0.99,
Some(&doc),
&agent,
None,
&validators,
1,
now,
30,
)
.unwrap();
assert_eq!(low.0, REASON_LOW_TRUST);
assert_eq!(
session_refusal(true, 0.5, None, &agent, None, &validators, 1, now, 30)
.unwrap()
.1,
"voucher_missing"
);
assert_eq!(
session_refusal(false, 0.5, None, &agent, None, &validators, 1, now, 30),
None
);
}
#[test]
fn trust_decays() {
let doc = json!({
"type": ["VerifiableCredential", "SessionVoucher"],
"validFrom": "2026-01-01T00:00:00Z",
"credentialSubject": {"initialTrust": 1.0, "decayLambda": 0.01},
});
let t = compute_trust_at(&doc, at("2026-01-01T00:01:40Z")).unwrap();
assert!((t - 0.36787944117144233).abs() < 1e-15);
assert!(compute_trust_at(&json!({"type": "X"}), 0).is_err());
}
#[test]
fn trust_parameters_must_be_finite() {
for (name, value) in [
("initialTrust", json!("inf")),
("initialTrust", json!("nan")),
("decayLambda", json!("inf")),
] {
let mut doc = json!({
"type": ["VerifiableCredential", "SessionVoucher"],
"validFrom": "2026-01-01T00:00:00Z",
"credentialSubject": {"initialTrust": 1.0, "decayLambda": 0.0},
});
doc["credentialSubject"][name] = value;
let err = compute_trust_at(&doc, at("2026-01-01T00:01:00Z")).unwrap_err();
assert!(err.to_string().contains("must be a finite number"), "{err}");
let request = json!({"voucher": doc, "threshold": 0.5, "now": "2026-01-01T00:01:00Z"});
assert!(evaluate_trust_json(&request).is_err());
}
}
#[test]
fn evaluate_trust_threshold_is_read_strictly() {
let doc = json!({
"type": ["VerifiableCredential", "SessionVoucher"],
"validFrom": "2026-01-01T00:00:00Z",
"credentialSubject": {"initialTrust": 1.0, "decayLambda": 0.01},
});
let ask = |threshold: Option<Value>| {
let mut request = json!({"voucher": doc.clone(), "now": "2026-01-01T00:01:00Z"});
if let Some(t) = threshold {
request["threshold"] = t;
}
evaluate_trust_json(&request)
};
assert_eq!(ask(Some(json!(0.5))).unwrap()["passed"], json!(true));
for bad_value in [
None,
Some(Value::Null),
Some(json!("0.5")),
Some(json!(true)),
Some(json!(-1.0)),
] {
assert!(ask(bad_value.clone()).is_err(), "{bad_value:?}");
}
}
#[test]
fn quorum_threshold_is_read_strictly() {
let (v1, s1) = did_key(8);
let (v2, _) = did_key(9);
let (agent, _) = did_key(10);
let doc = voucher(&v1, &s1, &agent);
let ask = |threshold: Option<Value>| {
let mut request = json!({
"voucher": doc.clone(),
"validators": [v1.clone(), v2.clone()],
"now": "2026-01-01T00:01:00Z",
});
if let Some(t) = threshold {
request["threshold"] = t;
}
verify_session_voucher_json(&request)
};
assert_eq!(ask(None).unwrap()["ok"], json!(true));
assert_eq!(ask(Some(json!(2))).unwrap()["ok"], json!(false));
for bad_value in [json!(null), json!(2.5), json!(1.0), json!("2"), json!(true)] {
assert!(ask(Some(bad_value.clone())).is_err(), "{bad_value}");
}
}
#[test]
fn guard_session_options_are_read_strictly() {
let (v, vs) = did_key(11);
let (agent, _) = did_key(12);
let doc = voucher(&v, &vs, &agent);
let base = json!({
"requireSession": true,
"trustThreshold": 0.5,
"voucher": doc,
"issuer": agent,
"validators": [v],
"quorum": 1,
"now": "2026-01-01T00:01:00Z",
"clockSkewSeconds": 30,
});
assert_eq!(session_refusal_json(&base).unwrap()["refusal"], Value::Null);
let with = |name: &str, value: Option<Value>| {
let mut request = base.clone();
match value {
Some(v) => request[name] = v,
None => {
request.as_object_mut().unwrap().remove(name);
}
}
session_refusal_json(&request)
};
for (name, value) in [
("trustThreshold", None),
("trustThreshold", Some(json!(null))),
("trustThreshold", Some(json!("0.5"))),
("quorum", None),
("quorum", Some(json!(2.0))),
("quorum", Some(json!(0))),
("quorum", Some(json!("1"))),
("requireSession", Some(json!("yes"))),
("requireSession", Some(json!(1))),
] {
assert!(with(name, value.clone()).is_err(), "{name} {value:?}");
}
let mut none = base.clone();
let m = none.as_object_mut().unwrap();
m.remove("validators");
m.remove("trustThreshold");
m.remove("quorum");
m.remove("voucher");
m.insert("requireSession".into(), json!(false));
assert_eq!(session_refusal_json(&none).unwrap()["refusal"], Value::Null);
}
#[test]
fn guard_authority_flags_are_read_strictly() {
let request = |flag: Value| {
json!({
"tier": "critical",
"enforceEpoch": flag,
"voucher": null,
"issuer": "did:web:a.example",
"facts": {},
"now": "2026-01-01T00:01:00Z",
"clockSkewSeconds": 30,
})
};
assert!(authority_refusal_json(&request(json!(true))).is_ok());
for flag in [json!("true"), json!(1), json!(null)] {
assert!(
authority_refusal_json(&request(flag.clone())).is_err(),
"{flag}"
);
}
}
#[test]
fn det_exp_is_within_one_ulp_of_the_platform_exp() {
assert_eq!(det_exp(0.0), 1.0);
assert_eq!(det_exp(-0.0), 1.0);
assert!(det_exp(f64::NAN).is_nan());
assert_eq!(det_exp(f64::NEG_INFINITY), 0.0);
assert_eq!(det_exp(-800.0), 0.0);
assert!(det_exp(710.0).is_infinite());
let mut worst = 0u64;
let mut x = -745.0_f64;
while x < 709.0 {
for v in [x, x + 1e-9, x * 0.999_999_7] {
let (a, b) = (det_exp(v), v.exp());
if a == 0.0 || b == 0.0 || !a.is_normal() || !b.is_normal() {
continue;
}
worst = worst.max(a.to_bits().abs_diff(b.to_bits()));
}
x += 0.013_7;
}
assert!(worst <= 1, "det_exp is {worst} ulp from exp");
}
#[test]
fn det_exp_constants_have_the_fdlibm_bits() {
let bits = |v: f64| v.to_bits();
assert_eq!(
bits(6.931_471_803_691_238_164_90e-01),
0x3fe6_2e42_fee0_0000
);
assert_eq!(
bits(1.908_214_929_270_587_700_02e-10),
0x3dea_39ef_3579_3c76
);
assert_eq!(
bits(1.442_695_040_888_963_387_00e+00),
0x3ff7_1547_652b_82fe
);
assert_eq!(
bits(1.666_666_666_666_660_190_37e-01),
0x3fc5_5555_5555_553e
);
assert_eq!(
bits(-2.777_777_777_701_559_338_42e-03),
0xbf66_c16c_16be_bd93
);
assert_eq!(
bits(6.613_756_321_437_934_361_17e-05),
0x3f11_566a_af25_de2c
);
assert_eq!(
bits(-1.653_390_220_546_525_153_90e-06),
0xbebb_bd41_c5d2_6bf1
);
assert_eq!(
bits(4.138_136_797_057_238_460_39e-08),
0x3e66_3769_72be_a4d0
);
}
}