#[allow(unused_imports)]
use crate::prelude::*;
use alloc::collections::BTreeMap;
use serde_json::{json, Map, Value};
use crate::data_integrity;
use crate::delegation::ChainOptions;
use crate::did_document;
use crate::error::{CoreError, Result};
use crate::grant_chain;
use crate::hybrid;
use crate::keys;
use crate::multikey;
use crate::pq;
use crate::status_list;
use crate::time::{check_clock_skew, parse_protocol_time_ns, window_state_ns, WindowState};
pub const REASON_NO_KEY: &str = "no key to check the signature with";
pub const REASON_UNTRUSTED_START: &str =
"the chain's starting point is not trusted: run `vouch trust <root DID>`";
pub const REASON_START_NOT_LISTED: &str = "the chain's starting point is not trusted: run \
`vouch trust <root DID>` (it is not one of the trusted roots)";
pub const REASON_BUDGET: &str = "verifier_budget_exceeded";
pub const REASON_CHAIN_REQUIRED: &str = "delegation_chain_required";
pub const REASON_REPLAYED: &str = "this credential was already used";
pub const DEFAULT_MAX_REPLAY_WINDOW_SECONDS: f64 = 12.0 * 60.0 * 60.0;
pub const DEFAULT_CLOCK_SKEW_SECONDS: i64 = 30;
pub const MISSING_MLDSA44_KEY: &str = "missing_mldsa44_key";
const VC_CONTEXT_V2: &str = "https://www.w3.org/ns/credentials/v2";
const REQUIRED_TYPES: [&str; 2] = ["VerifiableCredential", "VouchCredential"];
const SUPPORTED_VOUCH_VERSIONS: [&str; 1] = ["1.0"];
const ASSERTION: &str = "assertionMethod";
const ROOT_PLACEHOLDER: &str = "<root DID>";
const VALUE_ERROR: &str = "ValueError";
const WEAK_KEY_ERROR: &str = "WeakKeyError";
const NS_PER_SECOND: i128 = 1_000_000_000;
const GROUP_ORDER_LE: [u8; 32] = [
237, 211, 245, 92, 26, 99, 18, 88, 214, 156, 247, 162, 222, 249, 222, 20, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 16,
];
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum KeyEntry {
Ed25519(Vec<u8>),
Unusable,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct TrustedRoots {
pub dids: Vec<String>,
pub keys: BTreeMap<String, KeyEntry>,
}
#[derive(Debug, Clone)]
pub struct DecisionInput {
pub credential: Value,
pub now: String,
pub clock_skew_seconds: i64,
pub public_key: Option<KeyEntry>,
pub mldsa44_public_key: Option<Option<Vec<u8>>>,
pub slhdsa128_public_key: Option<Option<Vec<u8>>>,
pub trusted_keys: BTreeMap<String, KeyEntry>,
pub resolved_keys: BTreeMap<String, KeyEntry>,
pub mldsa44_keys: BTreeMap<String, Vec<u8>>,
pub slhdsa128_keys: BTreeMap<String, Vec<u8>>,
pub documents: BTreeMap<String, Value>,
pub trusted_roots: Option<TrustedRoots>,
pub require_post_quantum: bool,
pub require_suites: Vec<hybrid::Suite>,
pub expected_resource: Option<String>,
pub check_status: bool,
pub status_lists: Map<String, Value>,
pub max_depth: Option<usize>,
pub max_replay_window_seconds: f64,
pub allowed_issuers: Option<Vec<String>>,
pub chain_required_outside_roots: bool,
pub grant_chain_checked_apart: bool,
}
impl DecisionInput {
pub fn new(credential: Value, now: impl Into<String>) -> Self {
Self {
credential,
now: now.into(),
clock_skew_seconds: DEFAULT_CLOCK_SKEW_SECONDS,
public_key: None,
mldsa44_public_key: None,
slhdsa128_public_key: None,
trusted_keys: BTreeMap::new(),
resolved_keys: BTreeMap::new(),
mldsa44_keys: BTreeMap::new(),
slhdsa128_keys: BTreeMap::new(),
documents: BTreeMap::new(),
trusted_roots: None,
require_post_quantum: false,
require_suites: Vec::new(),
expected_resource: None,
check_status: true,
status_lists: Map::new(),
max_depth: None,
max_replay_window_seconds: DEFAULT_MAX_REPLAY_WINDOW_SECONDS,
allowed_issuers: None,
chain_required_outside_roots: false,
grant_chain_checked_apart: false,
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct ReplayIdentity {
pub key: String,
pub expires_at: f64,
pub single_use: bool,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Decision {
pub valid: bool,
pub reason: Option<String>,
pub passport: Option<Value>,
pub replay: Option<ReplayIdentity>,
pub issuer_key: Option<Vec<u8>>,
}
impl Decision {
fn refuse(reason: impl Into<String>) -> Self {
Self {
valid: false,
reason: Some(reason.into()),
passport: None,
replay: None,
issuer_key: None,
}
}
}
pub fn untrusted_root_reason(root: Option<&str>, roots_given: bool) -> String {
let template = if roots_given {
REASON_START_NOT_LISTED
} else {
REASON_UNTRUSTED_START
};
match root {
Some(r) if showable_did(r) => template.replace(ROOT_PLACEHOLDER, r),
_ => template.to_string(),
}
}
fn showable_did(s: &str) -> bool {
let Some(rest) = s.strip_prefix("did:") else {
return false;
};
let Some((method, id)) = rest.split_once(':') else {
return false;
};
!method.is_empty()
&& method
.bytes()
.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit())
&& (1..=200).contains(&id.len())
&& id
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b"._:%-".contains(&b))
}
pub fn issuer_did(credential: &Value) -> Option<&str> {
let issuer = match credential.get("issuer") {
Some(Value::Object(o)) => o.get("id"),
other => other,
};
issuer
.and_then(Value::as_str)
.filter(|s| s.starts_with("did:") && s.len() > 4)
}
fn has_did_document(did: &str) -> bool {
did.starts_with("did:web:") || did.starts_with("did:webvh:")
}
fn protocol_time(v: &Value) -> Option<i128> {
v.as_str().and_then(|s| parse_protocol_time_ns(s).ok())
}
pub fn structure_problem(
credential: &Value,
now: i128,
skew: i128,
expected_resource: Option<&str>,
) -> Option<String> {
crate::nesting::deep_guard!(Some(crate::nesting::TOO_DEEP.into()); credential);
let Some(cred) = credential.as_object() else {
return Some("the credential is not a JSON object".into());
};
let first_context = cred
.get("@context")
.and_then(Value::as_array)
.and_then(|c| c.first());
if first_context.and_then(Value::as_str) != Some(VC_CONTEXT_V2) {
return Some("the credential's @context does not start with the VC 2.0 context".into());
}
let types_ok = cred.get("type").and_then(Value::as_array).is_some_and(|t| {
REQUIRED_TYPES
.iter()
.all(|want| t.iter().any(|x| x.as_str() == Some(want)))
});
if !types_ok {
return Some(
"the credential's type must include VerifiableCredential and VouchCredential".into(),
);
}
if issuer_did(credential).is_none() {
return Some("the credential's issuer is not a DID".into());
}
let Some(subject) = cred.get("credentialSubject").and_then(Value::as_object) else {
return Some("credentialSubject is not an object".into());
};
let version_ok = subject
.get("vouchVersion")
.and_then(Value::as_str)
.is_some_and(|v| SUPPORTED_VOUCH_VERSIONS.contains(&v));
if !version_ok {
return Some("credentialSubject.vouchVersion is missing or not supported".into());
}
let Some(intent) = subject.get("intent").and_then(Value::as_object) else {
return Some("credentialSubject.intent is not an object".into());
};
let resource = match intent.get("resource").and_then(Value::as_str) {
Some(r) if !r.is_empty() => r,
_ => return Some("intent.resource is missing or is not a non-empty string".into()),
};
if expected_resource.is_some_and(|want| want != resource) {
return Some("intent.resource is not the expected resource".into());
}
let (Some(Value::String(vf)), Some(Value::String(vu))) =
(cred.get("validFrom"), cred.get("validUntil"))
else {
return Some("the credential has no validity window".into());
};
let (Ok(from), Ok(until)) = (parse_protocol_time_ns(vf), parse_protocol_time_ns(vu)) else {
return Some("the credential's validity window is not valid times".into());
};
match window_state_ns(now, Some(from), Some(until), skew) {
WindowState::Inverted => {
return Some("the credential's validity window ends before it starts".into())
}
WindowState::Expired => return Some("the credential expired".into()),
WindowState::NotYetValid => return Some("the credential is not yet valid".into()),
WindowState::Ok => {}
}
grant_chain::binding_fields_problem(&credential["credentialSubject"]).map(String::from)
}
#[derive(Debug, Clone)]
pub struct Proofs {
pub kind: &'static str,
pub eddsa: Option<Value>,
pub mldsa: Option<Value>,
pub slhdsa: Option<Value>,
}
impl Proofs {
fn vm_of(p: Option<&Value>) -> Option<String> {
p.and_then(|p| p.get("verificationMethod"))
.and_then(Value::as_str)
.map(String::from)
}
pub fn ed_vm(&self) -> Option<String> {
crate::nesting::deep_guard!(None; self);
Self::vm_of(self.eddsa.as_ref())
}
pub fn ml_vm(&self) -> Option<String> {
crate::nesting::deep_guard!(None; self);
Self::vm_of(self.mldsa.as_ref())
}
pub fn slh_vm(&self) -> Option<String> {
crate::nesting::deep_guard!(None; self);
Self::vm_of(self.slhdsa.as_ref())
}
pub fn suites(&self) -> Vec<hybrid::Suite> {
crate::nesting::deep_guard!(Vec::new(); self);
let mut out = Vec::new();
if self.eddsa.is_some() {
out.push(hybrid::Suite::Eddsa);
}
if self.mldsa.is_some() {
out.push(hybrid::Suite::Mldsa44);
}
if self.slhdsa.is_some() {
out.push(hybrid::Suite::Slhdsa128);
}
out
}
pub fn replay_proof_value(&self) -> String {
crate::nesting::deep_guard!(String::new(); self);
self.eddsa
.as_ref()
.and_then(|p| p.get("proofValue"))
.and_then(Value::as_str)
.unwrap_or_default()
.to_string()
}
}
fn proof_problem(proof: &Value, issuer: &str, now: i128, skew: i128) -> Option<&'static str> {
let Some(p) = proof.as_object() else {
return Some("a proof is not an object");
};
if p.get("type").and_then(Value::as_str) != Some(data_integrity::PROOF_TYPE) {
return Some("a proof is not a DataIntegrityProof");
}
let suite = p.get("cryptosuite").and_then(Value::as_str).unwrap_or("");
if hybrid::Suite::of(suite).is_none() {
return Some(hybrid::REASON_UNSUPPORTED_CRYPTOSUITE);
}
if p.get("proofPurpose").and_then(Value::as_str) != Some(ASSERTION) {
return Some("a proof's purpose is not assertionMethod");
}
let bound = p
.get("verificationMethod")
.and_then(Value::as_str)
.is_some_and(|vm| vm.split('#').next() == Some(issuer));
if !bound {
return Some("a proof's verificationMethod does not belong to the issuer");
}
if p.get("proofValue")
.and_then(Value::as_str)
.is_none_or(str::is_empty)
{
return Some("a proof has no proofValue");
}
if let Some(created) = p.get("created") {
if protocol_time(created).is_none() {
return Some("a proof's created is not a valid time");
}
}
if let Some(expires) = p.get("expires") {
let Some(e) = protocol_time(expires) else {
return Some("a proof's expires is not a valid time");
};
if window_state_ns(now, None, Some(e), skew) != WindowState::Ok {
return Some("a proof expired");
}
}
None
}
pub const REASON_PROOF_SET_SHAPE: &str =
"a proof set must be one eddsa-jcs-2022 proof and one proof of each post-quantum suite it carries";
pub fn read_proofs(
cred: &Value,
issuer: &str,
now: i128,
skew: i128,
) -> core::result::Result<Proofs, &'static str> {
crate::nesting::deep_guard!(Err(crate::nesting::TOO_DEEP); cred);
match cred.get("proof") {
Some(raw @ Value::Object(_)) => {
if let Some(problem) = proof_problem(raw, issuer, now, skew) {
return Err(problem);
}
match hybrid::Suite::of_proof(raw) {
Some(hybrid::Suite::Eddsa) => Ok(Proofs {
kind: "single",
eddsa: Some(raw.clone()),
mldsa: None,
slhdsa: None,
}),
Some(hybrid::Suite::Slhdsa128) => {
Err("an SLH-DSA proof needs its eddsa-jcs-2022 partner in a proof set")
}
_ => Err("an ML-DSA-44 proof needs its eddsa-jcs-2022 partner in a proof set"),
}
}
Some(Value::Array(items)) => {
for p in items {
if let Some(problem) = proof_problem(p, issuer, now, skew) {
return Err(problem);
}
}
let Some(members) = hybrid::set_members(items) else {
return Err(REASON_PROOF_SET_SHAPE);
};
Ok(Proofs {
kind: "set",
eddsa: Some(members.eddsa.clone()),
mldsa: members.mldsa44.cloned(),
slhdsa: members.slhdsa128.cloned(),
})
}
_ => Err("the credential has no proof"),
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct SignerKeys {
pub ed25519: Option<Vec<u8>>,
pub mldsa44: Option<Vec<u8>>,
pub slhdsa128: Option<Vec<u8>>,
pub publishes_mldsa44: bool,
pub publishes_slhdsa128: bool,
}
fn strict_ed25519(raw: &[u8]) -> Option<Vec<u8>> {
keys::strict_verifying_key(raw).ok().map(|_| raw.to_vec())
}
fn did_key_key(did: &str) -> Option<Vec<u8>> {
let mk = did.strip_prefix("did:key:")?;
let decoded = multikey::decode(mk).ok()?;
(decoded.algorithm == "Ed25519").then_some(decoded.raw_key)
}
fn effective_keys(input: &DecisionInput) -> BTreeMap<String, KeyEntry> {
let mut merged = input.resolved_keys.clone();
if let Some(roots) = &input.trusted_roots {
for (did, key) in &roots.keys {
merged.insert(did.clone(), key.clone());
}
}
for (did, key) in &input.trusted_keys {
merged.insert(did.clone(), key.clone());
}
merged
}
struct KeySource<'a> {
keys: BTreeMap<String, KeyEntry>,
mldsa44: &'a BTreeMap<String, Vec<u8>>,
slhdsa128: &'a BTreeMap<String, Vec<u8>>,
documents: &'a BTreeMap<String, Value>,
}
impl KeySource<'_> {
fn keys(
&self,
did: &str,
ed_vm: Option<&str>,
ml_vm: Option<&str>,
slh_vm: Option<&str>,
) -> SignerKeys {
let mut found = SignerKeys {
mldsa44: self.mldsa44.get(did).filter(|k| !k.is_empty()).cloned(),
slhdsa128: self.slhdsa128.get(did).filter(|k| !k.is_empty()).cloned(),
..Default::default()
};
let own = if did.starts_with("did:key:") {
match did_key_key(did) {
Some(k) => Some(k),
None => return found, }
} else {
None
};
if let Some(entry) = self.keys.get(did) {
found.ed25519 = match entry {
KeyEntry::Ed25519(k) => match &own {
Some(o) if o != k => None,
_ => strict_ed25519(k),
},
KeyEntry::Unusable => None,
};
return found;
}
if let Some(k) = own {
found.ed25519 = Some(k);
return found;
}
if has_did_document(did) {
let Some(doc) = self.documents.get(did) else {
return found;
};
if doc.get("id").and_then(Value::as_str) != Some(did) {
return found;
}
found.publishes_mldsa44 = did_document::publishes_mldsa44_assertion_key(doc, did);
if let Some(vm) = ed_vm {
found.ed25519 = did_document::assertion_key(doc, did, vm, did_document::ED25519)
.ok()
.and_then(|k| strict_ed25519(&k));
}
found.publishes_slhdsa128 = did_document::publishes_slhdsa128_assertion_key(doc, did);
if let (Some(vm), None) = (ml_vm, &found.mldsa44) {
found.mldsa44 =
did_document::assertion_key(doc, did, vm, did_document::MLDSA44).ok();
}
if let (Some(vm), None) = (slh_vm, &found.slhdsa128) {
found.slhdsa128 =
did_document::assertion_key(doc, did, vm, did_document::SLHDSA128).ok();
}
}
found
}
}
fn jwk_base64url_decode(text: &str) -> Option<Vec<u8>> {
use base64::engine::{
general_purpose::GeneralPurpose, DecodePaddingMode, GeneralPurposeConfig,
};
use base64::{alphabet::URL_SAFE, Engine};
let body = text.trim_end_matches('=');
let padding = text.len() - body.len();
if body.len() % 4 == 1 || (padding != 0 && padding != (4 - body.len() % 4) % 4) {
return None;
}
if body.contains('=') {
return None;
}
let engine = GeneralPurpose::new(
&URL_SAFE,
GeneralPurposeConfig::new()
.with_decode_allow_trailing_bits(true)
.with_decode_padding_mode(DecodePaddingMode::Indifferent),
);
engine.decode(body).ok()
}
pub fn key_entry_from_json(v: &Value) -> KeyEntry {
crate::nesting::deep_guard!(KeyEntry::Unusable; v);
let jwk = match v {
Value::String(s) if s.starts_with('z') => {
return match multikey::decode(s) {
Ok(d) if d.algorithm == "Ed25519" => KeyEntry::Ed25519(d.raw_key),
_ => KeyEntry::Unusable,
};
}
Value::String(s) if crate::nesting::check_text(s.as_bytes()).is_err() => {
return KeyEntry::Unusable
}
Value::String(s) => match serde_json::from_str::<Value>(s) {
Ok(Value::Object(o)) => o,
_ => return KeyEntry::Unusable,
},
Value::Object(o) => o.clone(),
_ => return KeyEntry::Unusable,
};
if jwk.get("kty").and_then(Value::as_str) != Some("OKP")
|| jwk.get("crv").and_then(Value::as_str) != Some("Ed25519")
{
return KeyEntry::Unusable;
}
let Some(x) = jwk.get("x").and_then(Value::as_str) else {
return KeyEntry::Unusable;
};
match jwk_base64url_decode(x).and_then(|raw| strict_ed25519(&raw)) {
Some(k) => KeyEntry::Ed25519(k),
None => KeyEntry::Unusable,
}
}
pub fn mldsa44_key_from_json(v: &Value) -> Option<Vec<u8>> {
crate::nesting::deep_guard!(None; v);
let s = v.as_str().filter(|s| s.starts_with('z'))?;
let d = multikey::decode(s).ok()?;
(d.algorithm == "ML-DSA-44").then_some(d.raw_key)
}
pub fn slhdsa128_key_from_json(v: &Value) -> Option<Vec<u8>> {
crate::nesting::deep_guard!(None; v);
let s = v.as_str().filter(|s| s.starts_with('u'))?;
let d = multikey::decode(s).ok()?;
(d.algorithm == multikey::SLHDSA128).then_some(d.raw_key)
}
fn strict_signature(sig: &[u8]) -> bool {
if sig.len() != keys::ED25519_SIGNATURE_LEN {
return false;
}
let mut r = [0u8; 32];
r.copy_from_slice(&sig[..32]);
if !keys::is_canonical_point_encoding(&r) {
return false;
}
match ed25519_dalek::VerifyingKey::from_bytes(&r) {
Ok(point) if !point.is_weak() => {}
_ => return false,
}
for i in (0..32).rev() {
let s = sig[32 + i];
if s != GROUP_ORDER_LE[i] {
return s < GROUP_ORDER_LE[i];
}
}
false
}
type Checked = core::result::Result<bool, &'static str>;
fn context_matches(document: &Value, proof: &Value) -> bool {
proof
.as_object()
.is_none_or(|p| data_integrity::proof_context_matches(document, p))
}
fn without_proof(cred: &Value) -> Value {
let mut base = cred.clone();
if let Some(o) = base.as_object_mut() {
o.remove("proof");
}
base
}
fn verify_ed25519_proof(cred: &Value, key: &[u8]) -> Checked {
let pv = cred
.get("proof")
.and_then(|p| p.get("proofValue"))
.and_then(Value::as_str)
.unwrap_or("");
let Some(body) = pv.strip_prefix('z') else {
return Err(VALUE_ERROR);
};
let sig = match multikey::decode_base58_bounded(body) {
Ok(s) if s.len() == keys::ED25519_SIGNATURE_LEN => s,
_ => return Err(VALUE_ERROR),
};
if !strict_signature(&sig) {
return Err(WEAK_KEY_ERROR);
}
if !context_matches(&without_proof(cred), &cred["proof"]) {
return Err(VALUE_ERROR);
}
data_integrity::verify_proof(cred, key).map_err(|_| VALUE_ERROR)
}
fn verify_pq_member(base: &Value, obj: &Map<String, Value>, key: &[u8]) -> Checked {
let suite = obj.get("cryptosuite").and_then(Value::as_str).unwrap_or("");
let slh = suite == hybrid::SLHDSA128_CRYPTOSUITE_ID;
let key_len = if slh {
crate::slh::SLHDSA128_PUBLIC_LEN
} else {
pq::MLDSA44_PUBLIC_LEN
};
if obj.get("type").and_then(Value::as_str) != Some(data_integrity::PROOF_TYPE)
|| key.len() != key_len
{
return Err(VALUE_ERROR);
}
let pv = obj.get("proofValue").and_then(Value::as_str).unwrap_or("");
let sig = if slh {
hybrid::decode_slhdsa128_proof_value(pv)
} else {
hybrid::decode_mldsa44_proof_value(pv)
}
.map_err(|_| VALUE_ERROR)?;
if !data_integrity::proof_context_matches(base, obj) {
return Err(VALUE_ERROR);
}
let mut unsigned = obj.clone();
unsigned.remove("proofValue");
let input = data_integrity::hash_data(base, &unsigned).map_err(|_| VALUE_ERROR)?;
if slh {
return crate::slh::verify(key, &input, &sig).map_err(|_| VALUE_ERROR);
}
let mut ok = pq::verify(key, &input, &sig).map_err(|_| VALUE_ERROR)?;
if !ok {
let legacy =
data_integrity::legacy_proof_digest(base, &unsigned).map_err(|_| VALUE_ERROR)?;
ok = pq::verify(key, &legacy, &sig).map_err(|_| VALUE_ERROR)?;
}
Ok(ok)
}
fn verify_proof_set(cred: &Value, ed: &[u8], ml: Option<&[u8]>, slh: Option<&[u8]>) -> Checked {
let Some(items) = cred.get("proof").and_then(Value::as_array) else {
return Err(VALUE_ERROR);
};
let base = without_proof(cred);
let (mut ed_ok, mut pq_ok) = (false, false);
for p in items {
let Some(obj) = p.as_object() else { continue };
match hybrid::Suite::of_proof(p) {
Some(hybrid::Suite::Eddsa) => {
let mut candidate = base.clone();
candidate["proof"] = p.clone();
if !verify_ed25519_proof(&candidate, ed)? {
return Ok(false);
}
ed_ok = true;
}
Some(suite) => {
let key = if suite == hybrid::Suite::Mldsa44 {
ml
} else {
slh
};
let Some(key) = key else {
return Ok(false);
};
if !verify_pq_member(&base, obj, key)? {
return Ok(false);
}
pq_ok = true;
}
None => {}
}
}
Ok(ed_ok && pq_ok)
}
enum ProofCheck {
Ok,
Refused(String),
MissingMldsa44Key,
}
fn check_proofs(
cred: &Value,
proofs: &Proofs,
keys: &SignerKeys,
required: hybrid::Required,
explicit: bool,
) -> ProofCheck {
let ed = keys.ed25519.as_deref().unwrap_or_default();
let verdict = if proofs.kind == "single" {
if required.any() {
return ProofCheck::Refused("a post-quantum proof is required".into());
}
verify_ed25519_proof(cred, ed)
} else {
if !required.met_by(&proofs.suites()) {
return ProofCheck::Refused(hybrid::REASON_REQUIRED_SUITE_MISSING.into());
}
if proofs.mldsa.is_some() && keys.mldsa44.is_none() {
if explicit {
return ProofCheck::MissingMldsa44Key;
}
return ProofCheck::Refused(
"no ML-DSA-44 key to check the post-quantum proof with".into(),
);
}
if proofs.slhdsa.is_some() && keys.slhdsa128.is_none() {
return ProofCheck::Refused(
"no SLH-DSA key to check the post-quantum proof with".into(),
);
}
verify_proof_set(cred, ed, keys.mldsa44.as_deref(), keys.slhdsa128.as_deref())
};
match verdict {
Ok(true) => ProofCheck::Ok,
Ok(false) => ProofCheck::Refused("the signature does not verify".into()),
Err(name) => ProofCheck::Refused(format!("the credential is malformed ({name})")),
}
}
fn list_proof_methods(list: &Value) -> (Option<String>, Option<String>) {
let vm = |p: &Value| {
p.get("verificationMethod")
.and_then(Value::as_str)
.map(String::from)
};
let suite = |p: &Value| {
p.get("cryptosuite")
.and_then(Value::as_str)
.unwrap_or_default()
.to_string()
};
match list.get("proof") {
Some(p @ Value::Object(_)) => (vm(p), None),
Some(Value::Array(items)) => (
items
.iter()
.find(|p| suite(p) == hybrid::EDDSA_CRYPTOSUITE_ID)
.and_then(vm),
items
.iter()
.find(|p| suite(p) == hybrid::MLDSA44_CRYPTOSUITE_ID)
.and_then(vm),
),
_ => (None, None),
}
}
fn list_keys(
list: Option<&Value>,
issuer: &str,
known: Option<(&Proofs, &SignerKeys)>,
source: &KeySource,
) -> (Option<Vec<u8>>, Option<Vec<u8>>) {
let Some(list) = list else {
return (None, None);
};
let resolve_ed = |vm: &str| -> Option<Vec<u8>> {
if let Some((proofs, keys)) = known {
if Some(vm) == proofs.ed_vm().as_deref() && keys.ed25519.is_some() {
return keys.ed25519.clone();
}
}
source.keys(issuer, Some(vm), None, None).ed25519
};
let resolve_ml = |vm: &str| -> Option<Vec<u8>> {
if let Some((proofs, keys)) = known {
if Some(vm) == proofs.ml_vm().as_deref() && keys.mldsa44.is_some() {
return keys.mldsa44.clone();
}
}
source.keys(issuer, None, Some(vm), None).mldsa44
};
let (ed_vm, ml_vm) = list_proof_methods(list);
let own = |vm: Option<String>| vm.filter(|v| v.split('#').next() == Some(issuer));
let ed = own(ed_vm)
.and_then(|vm| resolve_ed(&vm))
.and_then(|k| strict_ed25519(&k));
let ml = own(ml_vm)
.and_then(|vm| resolve_ml(&vm))
.filter(|k| k.len() == pq::MLDSA44_PUBLIC_LEN);
(ed, ml)
}
fn list_requirement(input: &DecisionInput, issuer_requires_pq: bool) -> hybrid::Required {
hybrid::Required {
post_quantum: issuer_requires_pq
|| input.require_post_quantum
|| input
.require_suites
.iter()
.any(|s| *s != hybrid::Suite::Eddsa),
..Default::default()
}
}
fn status_reason(
checked: &Value,
known: Option<(&Proofs, &SignerKeys)>,
source: &KeySource,
input: &DecisionInput,
issuer_requires_pq: bool,
) -> Result<Option<String>> {
let Some(raw) = checked.get("credentialStatus") else {
return Ok(None);
};
let unavailable = || Ok(Some(status_list::STATUS_UNAVAILABLE.to_string()));
let entries: Vec<&Value> = match raw {
Value::Object(_) => vec![raw],
Value::Array(items) => items.iter().collect(),
_ => Vec::new(),
};
if entries.is_empty() || entries.len() > status_list::MAX_STATUS_ENTRIES {
return unavailable();
}
let issuer = issuer_did(checked).unwrap_or_default().to_string();
for entry in entries {
let list = entry
.get("statusListCredential")
.and_then(Value::as_str)
.and_then(|url| input.status_lists.get(url));
let (ed_key, ml_key) = list_keys(list, &issuer, known, source);
let mut one = checked.clone();
one["credentialStatus"] = entry.clone();
let result = status_list::check_credential_status_required(
&one,
&input.status_lists,
ed_key.as_deref(),
ml_key.as_deref(),
&input.now,
input.clock_skew_seconds,
list_requirement(input, issuer_requires_pq),
)?;
if !result.ok {
return Ok(Some(result.reason.to_string()));
}
}
Ok(None)
}
fn check_replay_window(seconds: f64) -> Result<f64> {
if !seconds.is_finite() || seconds <= 0.0 {
return Err(CoreError::Json(
"max_replay_window must be a positive, finite number of seconds".into(),
));
}
Ok(seconds)
}
fn window_seconds(cred: &Value) -> Result<f64> {
let t = |k: &str| {
cred.get(k)
.and_then(Value::as_str)
.ok_or_else(|| CoreError::Json(format!("credential missing {k}")))
.and_then(parse_protocol_time_ns)
};
Ok((t("validUntil")? - t("validFrom")?) as f64 / NS_PER_SECOND as f64)
}
pub fn replay_window_too_long(credential: &Value, max_replay_window_seconds: f64) -> Result<bool> {
crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
Ok(window_seconds(credential)? > check_replay_window(max_replay_window_seconds)?)
}
fn identity_from(
cred: &Value,
proofs: &Proofs,
skew_seconds: i64,
max_window: f64,
) -> Result<ReplayIdentity> {
let issuer = issuer_did(cred).unwrap_or_default();
let key = crate::credentials::replay_key(issuer, &proofs.replay_proof_value())?;
let until = cred
.get("validUntil")
.and_then(Value::as_str)
.ok_or_else(|| CoreError::Json("credential missing validUntil".into()))?;
let until_micros = parse_protocol_time_ns(until)?.div_euclid(1000);
Ok(ReplayIdentity {
key,
expires_at: until_micros as f64 / 1e6 + skew_seconds as f64,
single_use: !replay_window_too_long(cred, max_window)?,
})
}
pub fn replay_identity(
credential: &Value,
now_iso: &str,
clock_skew_seconds: i64,
max_replay_window_seconds: f64,
) -> Result<ReplayIdentity> {
crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
let skew = check_clock_skew(clock_skew_seconds)?;
let now = parse_protocol_time_ns(now_iso)?.div_euclid(1000) * 1000;
check_replay_window(max_replay_window_seconds)?;
let issuer = issuer_did(credential).unwrap_or_default();
let proofs =
read_proofs(credential, issuer, now, skew).map_err(|p| CoreError::Json(p.into()))?;
identity_from(
credential,
&proofs,
clock_skew_seconds,
max_replay_window_seconds,
)
}
pub fn passport(cred: &Value, grants: &[&Value]) -> Value {
crate::nesting::deep_guard!(Value::Null; cred, grants);
let chain: Vec<Value> = grants
.iter()
.map(|g| {
let intent = g["credentialSubject"]["intent"].clone();
let bound: String = crate::delegation::parent_proof_binding_value(g)
.chars()
.take(64)
.collect();
json!({
"issuer": issuer_did(g).unwrap_or_default(),
"subject": intent.get("delegatee").cloned().unwrap_or(json!("")),
"intent": intent,
"validFrom": g.get("validFrom").cloned().unwrap_or(Value::Null),
"validUntil": g.get("validUntil").cloned().unwrap_or(Value::Null),
"parentProofValue": bound,
})
})
.collect();
let subject = &cred["credentialSubject"];
let rep = subject
.get("reputationScore")
.and_then(|v| {
if v.is_i64() || v.is_u64() {
v.as_i64()
} else {
None
}
})
.filter(|r| (0..=100).contains(r));
let text = |v: Option<&Value>| v.and_then(Value::as_str).unwrap_or_default().to_string();
json!({
"sub": text(subject.get("id")),
"iss": issuer_did(cred).unwrap_or_default(),
"validFrom": cred["validFrom"],
"validUntil": cred["validUntil"],
"credentialId": text(cred.get("id")),
"intent": subject["intent"],
"reputationScore": rep,
"delegationChain": chain,
"parentGrantDigest": subject.get(grant_chain::PARENT_GRANT_DIGEST).filter(|d| d.is_string()),
})
}
fn chain_root(chain: &[Value]) -> Option<&str> {
chain.first()?.get("issuer")?.as_str()
}
fn chain_prefilter(cred: &Value, chain: &[Value], root_dids: &[String]) -> Option<&'static str> {
for link in chain {
let ok = link.get("issuer").is_some_and(Value::is_string)
&& link.get("subject").is_some_and(Value::is_string);
if !ok {
return Some(grant_chain::REASON_MALFORMED);
}
}
for i in 1..chain.len() {
if chain[i - 1]["subject"] != chain[i]["issuer"] {
return Some("delegation_subject_issuer_mismatch");
}
}
if chain[chain.len() - 1]["subject"].as_str() != issuer_did(cred) {
return Some("delegation_subject_issuer_mismatch");
}
let root = chain[0]["issuer"].as_str().unwrap_or_default();
if !root_dids.iter().any(|d| d == root) {
return Some("untrusted_principal");
}
if chain
.iter()
.all(|l| matches!(l.get("parentCredential"), Some(Value::Object(_))))
{
return grant_chain::chain_binding_problem(chain);
}
None
}
fn at_microseconds(input: &DecisionInput) -> Result<DecisionInput> {
let ns = parse_protocol_time_ns(&input.now)?;
let micros = ns.div_euclid(1000) * 1000;
let mut out = input.clone();
out.now = format_time_micros(micros)?;
Ok(out)
}
pub(crate) fn format_time_micros(ns: i128) -> Result<String> {
let whole = crate::issuance::format_protocol_time(ns)?;
let micros = ns.rem_euclid(NS_PER_SECOND) / 1000;
Ok(format!("{}.{micros:06}Z", whole.trim_end_matches('Z')))
}
type Precheck<'a> = (Proofs, Option<&'a Vec<Value>>, Vec<String>);
fn precheck(input: &DecisionInput) -> Result<core::result::Result<Precheck<'_>, String>> {
let skew = check_clock_skew(input.clock_skew_seconds)?;
let now = parse_protocol_time_ns(&input.now)?;
if !input.credential.is_object() {
return Ok(Err("the credential is not a JSON object".into()));
}
check_replay_window(input.max_replay_window_seconds)?;
let cred = &input.credential;
let root_dids: Vec<String> = input
.trusted_roots
.as_ref()
.map(|r| r.dids.clone())
.unwrap_or_default();
if let Some(problem) = structure_problem(cred, now, skew, input.expected_resource.as_deref()) {
return Ok(Err(problem));
}
let issuer = issuer_did(cred).unwrap_or_default().to_string();
if let Some(allowed) = &input.allowed_issuers {
if !allowed.contains(&issuer) {
return Ok(Err("the issuer is not one of the trusted keys".into()));
}
}
let proofs = match read_proofs(cred, &issuer, now, skew) {
Ok(p) => p,
Err(problem) => return Ok(Err(problem.into())),
};
let carried = proofs.suites();
if input.require_suites.iter().any(|s| !carried.contains(s)) {
return Ok(Err(hybrid::REASON_REQUIRED_SUITE_MISSING.into()));
}
let chain = cred["credentialSubject"]
.get("delegationChain")
.and_then(Value::as_array)
.filter(|c| !c.is_empty());
let names_parent = input.grant_chain_checked_apart
&& cred["credentialSubject"]
.as_object()
.is_some_and(|s| s.contains_key(grant_chain::PARENT_GRANT_DIGEST));
if chain.is_none()
&& !names_parent
&& input.chain_required_outside_roots
&& !root_dids.is_empty()
&& !root_dids.contains(&issuer)
{
return Ok(Err(REASON_CHAIN_REQUIRED.into()));
}
if let Some(chain) = chain {
let as_value = Value::Array(chain.clone());
match crate::attenuation::chain_budget_exceeded(&as_value, input.max_depth) {
Ok(None) => {}
Ok(Some(_)) => return Ok(Err(REASON_BUDGET.into())),
Err(_) => return Ok(Err(grant_chain::REASON_MALFORMED.into())),
}
if root_dids.is_empty() {
return Ok(Err(untrusted_root_reason(chain_root(chain), false)));
}
if let Some(early) = chain_prefilter(cred, chain, &root_dids) {
if early == "untrusted_principal" {
return Ok(Err(untrusted_root_reason(chain_root(chain), true)));
}
return Ok(Err(early.into()));
}
}
Ok(Ok((proofs, chain, root_dids)))
}
pub fn decide(input: &DecisionInput) -> Result<Decision> {
crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); input);
let input = &at_microseconds(input)?;
let (proofs, chain, root_dids) = match precheck(input)? {
Ok(pre) => pre,
Err(reason) => return Ok(Decision::refuse(reason)),
};
let cred = &input.credential;
let issuer = issuer_did(cred).unwrap_or_default().to_string();
let source = KeySource {
keys: effective_keys(input),
mldsa44: &input.mldsa44_keys,
slhdsa128: &input.slhdsa128_keys,
documents: &input.documents,
};
let mut grants: Vec<&Value> = Vec::new();
if let Some(chain) = chain {
let grant_keys: BTreeMap<String, Vec<u8>> = source
.keys
.iter()
.map(|(did, entry)| {
let raw = match entry {
KeyEntry::Ed25519(k) => k.clone(),
KeyEntry::Unusable => Vec::new(),
};
(did.clone(), raw)
})
.collect();
let documents: BTreeMap<String, Value> = input
.documents
.iter()
.filter(|(did, _)| has_did_document(did))
.map(|(d, v)| (d.clone(), v.clone()))
.collect();
let opts = ChainOptions {
trusted_roots: Some(&root_dids),
grant_keys: Some(&grant_keys),
mldsa_keys: Some(&input.mldsa44_keys),
slhdsa_keys: Some(&input.slhdsa128_keys),
grant_documents: Some(&documents),
require_pq: input.require_post_quantum,
require_suites: &input.require_suites,
max_depth: input.max_depth,
..Default::default()
};
if let Some(reason) = crate::delegation::verify_delegation_chain_with(
cred,
&input.now,
input.clock_skew_seconds,
&opts,
) {
if reason == "untrusted_principal" {
return Ok(Decision::refuse(untrusted_root_reason(
chain_root(chain),
true,
)));
}
return Ok(Decision::refuse(reason));
}
grants = chain.iter().map(|l| &l["parentCredential"]).collect();
}
let explicit = input.public_key.is_some();
let mut keys = match &input.public_key {
Some(KeyEntry::Unusable) => {
return Ok(Decision::refuse(
"the public key given is not a usable Ed25519 key",
))
}
Some(KeyEntry::Ed25519(k)) => {
let Some(pinned) = strict_ed25519(k) else {
return Ok(Decision::refuse(
"the public key given is not a usable Ed25519 key",
));
};
if issuer.starts_with("did:key:") && did_key_key(&issuer).as_ref() != Some(&pinned) {
return Ok(Decision::refuse(
"the public key given is not the did:key issuer's key",
));
}
SignerKeys {
ed25519: Some(pinned),
mldsa44: input
.mldsa44_keys
.get(&issuer)
.filter(|k| !k.is_empty())
.cloned(),
slhdsa128: input
.slhdsa128_keys
.get(&issuer)
.filter(|k| !k.is_empty())
.cloned(),
..Default::default()
}
}
None => {
let (ml_vm, slh_vm) = if proofs.kind != "single" {
(proofs.ml_vm(), proofs.slh_vm())
} else {
(None, None)
};
let found = source.keys(
&issuer,
proofs.ed_vm().as_deref(),
ml_vm.as_deref(),
slh_vm.as_deref(),
);
if found.ed25519.is_none() {
return Ok(Decision::refuse(REASON_NO_KEY));
}
found
}
};
if let Some(given) = &input.mldsa44_public_key {
match given {
Some(k) if k.len() == pq::MLDSA44_PUBLIC_LEN => keys.mldsa44 = Some(k.clone()),
_ => {
return Ok(Decision::refuse(
"the ML-DSA-44 public key given is not a 1312-byte key",
))
}
}
}
if let Some(given) = &input.slhdsa128_public_key {
match given {
Some(k) if k.len() == crate::slh::SLHDSA128_PUBLIC_LEN => {
keys.slhdsa128 = Some(k.clone())
}
_ => {
return Ok(Decision::refuse(
"the SLH-DSA public key given is not a 32-byte key",
))
}
}
}
let resolved_ml = input.mldsa44_keys.contains_key(&issuer);
let resolved_slh = input.slhdsa128_keys.contains_key(&issuer);
let required = hybrid::Required {
post_quantum: input.require_post_quantum,
mldsa44: input.mldsa44_public_key.is_some() || keys.publishes_mldsa44 || resolved_ml,
slhdsa128: input.slhdsa128_public_key.is_some() || keys.publishes_slhdsa128 || resolved_slh,
};
match check_proofs(cred, &proofs, &keys, required, explicit) {
ProofCheck::Ok => {}
ProofCheck::Refused(reason) => return Ok(Decision::refuse(reason)),
ProofCheck::MissingMldsa44Key => {
return Err(CoreError::Json(format!(
"{MISSING_MLDSA44_KEY}: this credential carries an ML-DSA-44 post-quantum \
proof; pass the ML-DSA-44 public key or publish it in the issuer's DID \
document. A did:key identifier encodes only the Ed25519 key."
)))
}
}
if input.check_status {
if let Some(reason) =
status_reason(cred, Some((&proofs, &keys)), &source, input, required.any())?
{
return Ok(Decision::refuse(reason));
}
for grant in &grants {
let grant_issuer = issuer_did(grant).unwrap_or_default();
let grant_pq = input.mldsa44_keys.contains_key(grant_issuer)
|| input.slhdsa128_keys.contains_key(grant_issuer);
if let Some(reason) = status_reason(grant, None, &source, input, grant_pq)? {
return Ok(Decision::refuse(format!("delegation_{reason}")));
}
}
}
Ok(Decision {
valid: true,
reason: None,
passport: Some(passport(cred, &grants)),
replay: Some(identity_from(
cred,
&proofs,
input.clock_skew_seconds,
input.max_replay_window_seconds,
)?),
issuer_key: keys.ed25519.clone(),
})
}
pub const MAX_FETCH_DIDS: usize = 32;
pub const MAX_FETCH_STATUS_LISTS: usize = 32;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FetchPhase {
Documents,
StatusLists,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct FetchPlan {
pub refusal: Option<String>,
pub dids: Vec<String>,
pub status_lists: Vec<String>,
pub truncated: bool,
}
fn push_unique(
list: &mut Vec<String>,
seen: &mut alloc::collections::BTreeSet<String>,
item: &str,
cap: usize,
truncated: &mut bool,
) {
if item.is_empty() || seen.contains(item) {
return;
}
if list.len() >= cap {
*truncated = true;
return;
}
seen.insert(item.to_string());
list.push(item.to_string());
}
fn status_urls(c: &Value) -> Vec<&str> {
let entries: Vec<&Value> = match c.get("credentialStatus") {
Some(e @ Value::Object(_)) => vec![e],
Some(Value::Array(a)) => a.iter().take(status_list::MAX_STATUS_ENTRIES).collect(),
_ => Vec::new(),
};
entries
.iter()
.filter_map(|e| e.get("statusListCredential").and_then(Value::as_str))
.collect()
}
pub fn fetch_plan(input: &DecisionInput, phase: FetchPhase) -> Result<FetchPlan> {
crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); input);
let input = &at_microseconds(input)?;
let mut plan = FetchPlan::default();
match phase {
FetchPhase::Documents => {
let (_, chain, _) = match precheck(input)? {
Ok(pre) => pre,
Err(reason) => {
plan.refusal = Some(reason);
return Ok(plan);
}
};
let known = effective_keys(input);
let mut seen = alloc::collections::BTreeSet::new();
let mut wanted: Vec<&str> = Vec::new();
if input.public_key.is_none() {
wanted.extend(issuer_did(&input.credential));
}
for link in chain.into_iter().flatten() {
wanted.extend(link.get("issuer").and_then(Value::as_str));
}
for did in wanted {
if has_did_document(did) && !known.contains_key(did) {
push_unique(
&mut plan.dids,
&mut seen,
did,
MAX_FETCH_DIDS,
&mut plan.truncated,
);
}
}
}
FetchPhase::StatusLists => {
let mut without_status = input.clone();
without_status.check_status = false;
let decision = decide(&without_status)?;
if !decision.valid {
plan.refusal = decision.reason;
return Ok(plan);
}
if !input.check_status {
return Ok(plan);
}
let mut seen = alloc::collections::BTreeSet::new();
let cred = &input.credential;
let mut urls = status_urls(cred);
if let Some(chain) = cred["credentialSubject"]
.get("delegationChain")
.and_then(Value::as_array)
{
for link in chain {
urls.extend(status_urls(&link["parentCredential"]));
}
}
for url in urls {
push_unique(
&mut plan.status_lists,
&mut seen,
url,
MAX_FETCH_STATUS_LISTS,
&mut plan.truncated,
);
}
}
}
Ok(plan)
}
const REQUEST_MEMBERS: [&str; 27] = [
"credential",
"now",
"clockSkewSeconds",
"publicKey",
"mldsa44PublicKey",
"slhdsa128PublicKey",
"trustedKeys",
"resolvedKeys",
"mldsa44Keys",
"slhdsa128Keys",
"documents",
"didLogs",
"didLogsB64",
"seenVersionIds",
"limits",
"logNow",
"trustedRoots",
"requirePostQuantum",
"requireSuites",
"expectedResource",
"checkStatus",
"statusLists",
"maxDepth",
"maxReplayWindowSeconds",
"requireTrustedIssuer",
"chainRequiredOutsideRoots",
"grantChainCheckedApart",
];
fn bad(msg: impl Into<String>) -> CoreError {
CoreError::Json(msg.into())
}
fn present<'a>(obj: &'a Map<String, Value>, name: &str) -> Option<&'a Value> {
obj.get(name).filter(|v| !v.is_null())
}
const TIGHTENING_MEMBERS: [&str; 15] = [
"trustedRoots",
"trustedKeys",
"publicKey",
"mldsa44Keys",
"slhdsa128Keys",
"requirePostQuantum",
"requireSuites",
"requireTrustedIssuer",
"expectedResource",
"checkStatus",
"chainRequiredOutsideRoots",
"grantChainCheckedApart",
"mldsa44PublicKey",
"slhdsa128PublicKey",
"maxDepth",
];
fn refuse_null_tightening(obj: &Map<String, Value>) -> Result<()> {
for name in TIGHTENING_MEMBERS {
if matches!(obj.get(name), Some(Value::Null)) {
return Err(bad(format!(
"{name} must not be null: leave it out for the default"
)));
}
}
Ok(())
}
fn credential_from_text(text: &str) -> Value {
crate::authority_state::parse_json_no_duplicates(text).unwrap_or(Value::Null)
}
fn bool_member(obj: &Map<String, Value>, name: &str, default: bool) -> Result<bool> {
match present(obj, name) {
None => Ok(default),
Some(Value::Bool(b)) => Ok(*b),
Some(_) => Err(bad(format!("{name} must be true or false"))),
}
}
fn object_member<'a>(
obj: &'a Map<String, Value>,
name: &str,
) -> Result<Option<&'a Map<String, Value>>> {
match present(obj, name) {
None => Ok(None),
Some(Value::Object(m)) => Ok(Some(m)),
Some(_) => Err(bad(format!("{name} must be a JSON object"))),
}
}
fn string_list(v: &Value, name: &str) -> Result<Vec<String>> {
v.as_array()
.and_then(|a| {
a.iter()
.map(|x| x.as_str().map(String::from))
.collect::<Option<Vec<_>>>()
})
.ok_or_else(|| bad(format!("{name} must be a list of strings")))
}
pub fn trusted_roots_from_json(v: &Value) -> Result<Option<TrustedRoots>> {
crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); v);
let norm = crate::did_web::normalize_root;
match v {
Value::Null => Ok(None),
Value::String(s) => Ok(Some(TrustedRoots {
dids: vec![norm(s)?],
keys: BTreeMap::new(),
})),
Value::Array(_) => Ok(Some(TrustedRoots {
dids: string_list(v, "trustedRoots")?
.iter()
.map(|s| norm(s))
.collect::<Result<_>>()?,
keys: BTreeMap::new(),
})),
Value::Object(m) => {
let mut roots = TrustedRoots::default();
for (did, key) in m {
let did = norm(did)?;
if !roots.dids.contains(&did) {
roots.dids.push(did.clone());
}
roots.keys.insert(did, key_entry_from_json(key));
}
Ok(Some(roots))
}
_ => Err(bad(
"trustedRoots must be a {did: key} map or a list of DIDs",
)),
}
}
fn trusted_key_map(obj: &Map<String, Value>) -> Result<BTreeMap<String, KeyEntry>> {
let mut out = BTreeMap::new();
for (did, v) in object_member(obj, "trustedKeys")?.into_iter().flatten() {
let Ok(did) = crate::did_web::normalize_root(did) else {
continue;
};
out.insert(did, key_entry_from_json(v));
}
Ok(out)
}
fn key_map(obj: &Map<String, Value>, name: &str) -> Result<BTreeMap<String, KeyEntry>> {
Ok(object_member(obj, name)?
.map(|m| {
m.iter()
.filter(|(_, v)| !v.is_null())
.map(|(did, v)| (did.clone(), key_entry_from_json(v)))
.collect()
})
.unwrap_or_default())
}
pub fn decide_json_with_clock(request: &Value, clock: crate::did_webvh::LogClock) -> Result<Value> {
crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); request);
let obj = request
.as_object()
.ok_or_else(|| bad("the request must be a JSON object"))?;
let (input, logs) = read_request(obj, clock, &[])?;
let decision = decide(&input)?;
let (versions, errors) = match &logs {
Some(set) => crate::did_webvh::grant_log_json(&set.outcomes()),
None => (json!({}), json!({})),
};
Ok(json!({
"valid": decision.valid,
"reason": decision.reason,
"passport": decision.passport,
"replay": decision.replay.map(|r| json!({
"key": r.key,
"expiresAt": r.expires_at,
"singleUse": r.single_use,
})),
"issuerKey": decision
.issuer_key
.as_deref()
.map(multikey::encode_ed25519_public)
.transpose()?,
"didLogVersions": versions,
"didLogErrors": errors,
}))
}
fn read_request(
obj: &Map<String, Value>,
clock: crate::did_webvh::LogClock,
extra: &[&str],
) -> Result<(DecisionInput, Option<crate::did_webvh::LogSet>)> {
use crate::did_webvh::{base64_decode, is_did_webvh, LogClock, LogSet};
if let Some(name) = obj
.keys()
.find(|k| !REQUEST_MEMBERS.contains(&k.as_str()) && !extra.contains(&k.as_str()))
{
return Err(bad(format!(
"the request holds an unknown member {:?}",
name.chars().take(40).collect::<String>()
)));
}
refuse_null_tightening(obj)?;
let credential = match obj.get("credential") {
Some(Value::String(text)) => credential_from_text(text),
Some(v) => v.clone(),
None => return Err(bad("credential is required")),
};
let now = obj
.get("now")
.and_then(Value::as_str)
.ok_or_else(|| bad("now must be a protocol time"))?;
let mut input = DecisionInput::new(credential, now);
match obj.get("clockSkewSeconds") {
None => {}
Some(Value::Null) => return Err(bad("clockSkewSeconds must be a whole number of seconds")),
Some(v) => input.clock_skew_seconds = crate::time::clock_skew_from_json(v)?,
}
input.public_key = present(obj, "publicKey").map(key_entry_from_json);
input.mldsa44_public_key = present(obj, "mldsa44PublicKey").map(mldsa44_key_from_json);
input.slhdsa128_public_key = present(obj, "slhdsa128PublicKey").map(slhdsa128_key_from_json);
input.trusted_keys = trusted_key_map(obj)?;
input.resolved_keys = key_map(obj, "resolvedKeys")?;
if let Some(m) = object_member(obj, "mldsa44Keys")? {
for (did, v) in m {
if !v.is_null() {
let k = mldsa44_key_from_json(v).unwrap_or_default();
input.mldsa44_keys.insert(did.clone(), k);
}
}
}
if let Some(m) = object_member(obj, "slhdsa128Keys")? {
for (did, v) in m {
if !v.is_null() {
let k = slhdsa128_key_from_json(v).unwrap_or_default();
input.slhdsa128_keys.insert(did.clone(), k);
}
}
}
if let Some(m) = object_member(obj, "documents")? {
for (did, doc) in m {
if !has_did_document(did) {
return Err(bad(
"documents holds a DID that is not did:web or did:webvh",
));
}
if !doc.is_null() {
input.documents.insert(did.clone(), doc.clone());
}
}
}
let clock = match present(obj, "logNow") {
None => clock,
Some(v) => LogClock::At(parse_protocol_time_ns(
v.as_str()
.ok_or_else(|| bad("logNow must be a protocol time"))?,
)?),
};
let mut logs: Option<LogSet> = None;
let texts = object_member(obj, "didLogs")?;
let b64s = object_member(obj, "didLogsB64")?;
if texts.is_some() || b64s.is_some() {
let mut set = LogSet::new(clock)?;
if let Some(limits) = present(obj, "limits") {
set = set.with_limits(crate::did_webvh::Limits::from_json(limits)?);
}
let mut given: Vec<(String, Vec<u8>)> = Vec::new();
for (did, v) in texts.into_iter().flatten() {
let t = v
.as_str()
.ok_or_else(|| bad("didLogs must map DIDs to log text"))?;
given.push((did.clone(), t.as_bytes().to_vec()));
}
for (did, v) in b64s.into_iter().flatten() {
let t = v
.as_str()
.ok_or_else(|| bad("didLogsB64 must map DIDs to base64 logs"))?;
given.push((did.clone(), base64_decode(t, "a didLogsB64 log")?));
}
for (did, log) in given {
if !is_did_webvh(&did) {
return Err(bad("didLogs holds a DID that is not a did:webvh DID"));
}
if set.contains(&did) || input.documents.contains_key(&did) {
return Err(bad(
"give each DID's log once, in didLogs, didLogsB64 or documents",
));
}
set = set.with_log(&did, log);
}
if let Some(m) = object_member(obj, "seenVersionIds")? {
for (did, v) in m {
let seen = v
.as_str()
.ok_or_else(|| bad("seenVersionIds must map DIDs to versionIds"))?;
set = set.with_seen_version_id(did, seen)?;
}
}
logs = Some(set);
}
if let Some(v) = present(obj, "trustedRoots") {
input.trusted_roots = trusted_roots_from_json(v)?;
}
input.require_post_quantum = bool_member(obj, "requirePostQuantum", false)?;
if let Some(v) = present(obj, "requireSuites") {
input.require_suites = hybrid::required_suites_from_json(v)?;
}
input.expected_resource = match present(obj, "expectedResource") {
None => None,
Some(Value::String(s)) => Some(s.clone()),
Some(_) => return Err(bad("expectedResource must be a string")),
};
input.check_status = bool_member(obj, "checkStatus", true)?;
if let Some(m) = object_member(obj, "statusLists")? {
input.status_lists = m.clone();
}
input.max_depth = match present(obj, "maxDepth") {
None => None,
Some(v) => Some(
v.as_u64()
.and_then(|d| usize::try_from(d).ok())
.ok_or_else(|| bad("maxDepth must be a non-negative whole number"))?,
),
};
if let Some(v) = present(obj, "maxReplayWindowSeconds") {
input.max_replay_window_seconds = match v {
Value::Number(n) => n.as_f64().unwrap_or(f64::NAN),
_ => return Err(bad("max_replay_window must be a number of seconds")),
};
}
if bool_member(obj, "requireTrustedIssuer", false)? {
input.allowed_issuers = Some(input.trusted_keys.keys().cloned().collect());
}
if present(obj, "trustedRoots").is_none() && !input.trusted_keys.is_empty() {
input.trusted_roots = Some(TrustedRoots {
dids: input.trusted_keys.keys().cloned().collect(),
keys: BTreeMap::new(),
});
}
input.chain_required_outside_roots =
input.trusted_roots.is_some() && bool_member(obj, "chainRequiredOutsideRoots", true)?;
input.grant_chain_checked_apart = bool_member(obj, "grantChainCheckedApart", false)?;
if let Some(set) = &logs {
for did in obj
.get("didLogs")
.and_then(Value::as_object)
.into_iter()
.chain(obj.get("didLogsB64").and_then(Value::as_object))
.flat_map(|m| m.keys())
{
if let Some(Ok(resolution)) = set.resolve(did) {
input.documents.insert(did.clone(), resolution.document);
}
}
}
Ok((input, logs))
}
pub fn decide_json(request: &Value) -> Result<Value> {
crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); request);
decide_json_with_clock(request, crate::did_webvh::LogClock::System)
}
pub fn fetch_plan_json_with_clock(
request: &Value,
clock: crate::did_webvh::LogClock,
) -> Result<Value> {
crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); request);
let obj = request
.as_object()
.ok_or_else(|| bad("the request must be a JSON object"))?;
let phase = match present(obj, "phase").map(|v| v.as_str()) {
None | Some(Some("documents")) => FetchPhase::Documents,
Some(Some("statusLists")) => FetchPhase::StatusLists,
_ => return Err(bad("phase must be \"documents\" or \"statusLists\"")),
};
let (input, _logs) = read_request(obj, clock, &["phase"])?;
let plan = fetch_plan(&input, phase)?;
Ok(json!({
"refusal": plan.refusal,
"dids": plan.dids,
"statusLists": plan.status_lists,
"truncated": plan.truncated,
}))
}
pub fn fetch_plan_json(request: &Value) -> Result<Value> {
crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); request);
fetch_plan_json_with_clock(request, crate::did_webvh::LogClock::System)
}
pub fn replay_identity_json(request: &Value) -> Result<Value> {
crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); request);
let obj = request
.as_object()
.ok_or_else(|| bad("the request must be a JSON object"))?;
let credential = obj
.get("credential")
.filter(|c| c.is_object())
.ok_or_else(|| bad("credential must be a JSON object"))?;
let now = obj
.get("now")
.and_then(Value::as_str)
.ok_or_else(|| bad("now must be a protocol time"))?;
let skew = match present(obj, "clockSkewSeconds") {
None => DEFAULT_CLOCK_SKEW_SECONDS,
Some(v) => crate::time::clock_skew_from_json(v)?,
};
let window = match present(obj, "maxReplayWindowSeconds") {
None => DEFAULT_MAX_REPLAY_WINDOW_SECONDS,
Some(v) => v
.as_f64()
.ok_or_else(|| bad("max_replay_window must be a number of seconds"))?,
};
let r = replay_identity(credential, now, skew, window)?;
Ok(json!({"key": r.key, "expiresAt": r.expires_at, "singleUse": r.single_use}))
}
pub fn structure_only_json(request: &Value) -> Result<Value> {
crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); request);
let obj = request
.as_object()
.ok_or_else(|| bad("the request must be a JSON object"))?;
let credential = match obj.get("credential") {
Some(Value::String(text)) => credential_from_text(text),
Some(v) => v.clone(),
None => return Err(bad("credential is required")),
};
let now = obj
.get("now")
.and_then(Value::as_str)
.ok_or_else(|| bad("now must be a protocol time"))?;
let now = parse_protocol_time_ns(now)?.div_euclid(1000) * 1000;
let skew = match obj.get("clockSkewSeconds") {
None => DEFAULT_CLOCK_SKEW_SECONDS,
Some(v) => crate::time::clock_skew_from_json(v)?,
};
let skew = check_clock_skew(skew)?;
let expected = match present(obj, "expectedResource") {
None => None,
Some(Value::String(s)) => Some(s.as_str()),
Some(_) => return Err(bad("expectedResource must be a string")),
};
if !credential.is_object() {
return Ok(json!({"problem": "the credential is not a JSON object"}));
}
if let Some(problem) = structure_problem(&credential, now, skew, expected) {
return Ok(json!({ "problem": problem }));
}
let issuer = issuer_did(&credential).unwrap_or_default().to_string();
Ok(match read_proofs(&credential, &issuer, now, skew) {
Ok(_) => json!({ "problem": null }),
Err(problem) => json!({ "problem": problem }),
})
}
pub fn delegation_chain_json_with_clock(
request: &Value,
clock: crate::did_webvh::LogClock,
) -> Result<Value> {
crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); request);
let obj = request
.as_object()
.ok_or_else(|| bad("the request must be a JSON object"))?;
let (input, _logs) = read_request(obj, clock, &["linksOnly", "throughLink"])?;
let input = at_microseconds(&input)?;
let cred = &input.credential;
if !cred.is_object() {
return Ok(json!({ "reason": grant_chain::REASON_MALFORMED }));
}
let links_only = bool_member(obj, "linksOnly", false)?;
let through_link = match present(obj, "throughLink") {
None => None,
Some(v) => Some(
v.as_u64()
.and_then(|n| usize::try_from(n).ok())
.ok_or_else(|| bad("throughLink must be a non-negative whole number"))?,
),
};
let grant_keys: BTreeMap<String, Vec<u8>> = effective_keys(&input)
.into_iter()
.map(|(did, entry)| {
let raw = match entry {
KeyEntry::Ed25519(k) => k,
KeyEntry::Unusable => Vec::new(),
};
(did, raw)
})
.collect();
let documents: BTreeMap<String, Value> = input
.documents
.iter()
.filter(|(did, _)| has_did_document(did))
.map(|(d, v)| (d.clone(), v.clone()))
.collect();
let roots: Vec<String> = input
.trusted_roots
.as_ref()
.map(|r| r.dids.clone())
.unwrap_or_default();
let opts = ChainOptions {
trusted_roots: Some(&roots),
grant_keys: Some(&grant_keys),
mldsa_keys: Some(&input.mldsa44_keys),
slhdsa_keys: Some(&input.slhdsa128_keys),
grant_documents: Some(&documents),
require_pq: input.require_post_quantum,
require_suites: &input.require_suites,
max_depth: input.max_depth,
through_link,
..Default::default()
};
let check = if links_only {
crate::delegation::chain_links_problem
} else {
crate::delegation::verify_delegation_chain_with
};
let reason = check(cred, &input.now, input.clock_skew_seconds, &opts);
Ok(json!({ "reason": reason }))
}
pub fn normalize_root_json(request: &Value) -> Result<Value> {
crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); request);
let root = request
.get("root")
.and_then(Value::as_str)
.ok_or_else(|| bad("a trusted root is a DID or a domain name"))?;
Ok(json!({ "did": crate::did_web::normalize_root(root)? }))
}
crate::nesting::nested_fields!(DecisionInput; credential, documents, status_lists);
crate::nesting::nested_fields!(Proofs; eddsa, mldsa, slhdsa);
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn showable_dids() {
assert!(showable_did("did:web:example.com"));
assert!(showable_did("did:key:z6Mk"));
assert!(!showable_did("did:Web:example.com"));
assert!(!showable_did("did:web:"));
assert!(!showable_did("did:web:a b"));
assert!(!showable_did(&format!("did:web:{}", "a".repeat(201))));
assert_eq!(
untrusted_root_reason(Some("did:web:root.example"), true),
"the chain's starting point is not trusted: run `vouch trust did:web:root.example` \
(it is not one of the trusted roots)"
);
assert_eq!(
untrusted_root_reason(Some("did:web:a b"), false),
REASON_UNTRUSTED_START
);
}
#[test]
fn group_order_matches_the_curve() {
let mut sig = [0u8; 64];
let base = ed25519_dalek::SigningKey::from_bytes(&[7u8; 32]).verifying_key();
sig[..32].copy_from_slice(base.as_bytes());
sig[32..].copy_from_slice(&GROUP_ORDER_LE);
assert!(!strict_signature(&sig));
sig[32] -= 1;
assert!(strict_signature(&sig));
}
#[test]
fn bad_requests_are_errors() {
let cred = json!({});
let mut input = DecisionInput::new(cred, "2026-01-01T00:00:00Z");
input.max_replay_window_seconds = 0.0;
assert!(decide(&input).is_err());
input.max_replay_window_seconds = 10.0;
input.clock_skew_seconds = 121;
assert!(decide(&input).is_err());
let not_object = DecisionInput::new(json!([1]), "2026-01-01T00:00:00Z");
assert_eq!(
decide(¬_object).unwrap().reason.as_deref(),
Some("the credential is not a JSON object")
);
}
#[test]
fn jwk_x_padding_matches_the_reference() {
let key = ed25519_dalek::SigningKey::from_bytes(&[7u8; 32]).verifying_key();
let body = base64::Engine::encode(
&base64::engine::general_purpose::URL_SAFE_NO_PAD,
key.as_bytes(),
);
assert_eq!(body.len(), 43);
let entry =
|x: String| key_entry_from_json(&json!({"kty": "OKP", "crv": "Ed25519", "x": x}));
for (pad, usable) in [(0, true), (1, true), (2, false), (3, false), (4, false)] {
let got = entry(format!("{body}{}", "=".repeat(pad)));
assert_eq!(
matches!(got, KeyEntry::Ed25519(_)),
usable,
"{pad} padding signs"
);
}
assert!(matches!(entry(format!("={body}")), KeyEntry::Unusable));
assert!(matches!(
entry(format!("{}={}", &body[..20], &body[20..])),
KeyEntry::Unusable
));
}
}