use serde_json::{json, Map, Value};
use crate::attenuation;
use crate::data_integrity::{self, BuildProofOptions};
use crate::delegation;
use crate::error::{CoreError, Result};
use crate::grant_chain::{self, py_repr, py_repr_str};
use crate::time::parse_protocol_time_ns;
use zeroize::{Zeroize, Zeroizing};
pub const DEFAULT_VALID_SECONDS: i64 = 300;
pub const INVALID_VALID_SECONDS: &str =
"valid_seconds must be a whole number of seconds greater than zero";
pub const NOT_A_DID: &str = "Vouch Signer requires 'did' to be a DID (did:<method>:...)";
pub const PARENT_NOT_PLAIN_JSON: &str =
"Delegation refused: the parent grant is not plain JSON, so it has no digest";
const NS_PER_SECOND: i128 = 1_000_000_000;
fn to_micros(ns: i128) -> i128 {
ns.div_euclid(1000) * 1000
}
fn refused(msg: impl Into<String>) -> CoreError {
CoreError::Json(msg.into())
}
#[derive(Debug, Clone, Default)]
pub struct IssueRequest {
pub issuer_did: String,
pub intent: Value,
pub now: String,
pub valid_from: Option<String>,
pub valid_seconds: Option<i64>,
pub reputation_score: Option<i64>,
pub delegation_chain: Option<Value>,
pub parent_credential: Option<Value>,
pub credential_id: Option<String>,
pub credential_status: Option<Value>,
pub verification_method: Option<String>,
}
pub fn format_protocol_time(ns: i128) -> Result<String> {
let secs = ns.div_euclid(NS_PER_SECOND);
let days = secs.div_euclid(86_400);
let rem = secs.rem_euclid(86_400);
let z = days + 719_468;
let era = z.div_euclid(146_097);
let doe = z.rem_euclid(146_097);
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let day = doy - (153 * mp + 2) / 5 + 1;
let month = if mp < 10 { mp + 3 } else { mp - 9 };
let year = yoe + era * 400 + i128::from(month <= 2);
if !(1..=9999).contains(&year) {
return Err(refused("date value out of range"));
}
Ok(format!(
"{year:04}-{month:02}-{day:02}T{:02}:{:02}:{:02}Z",
rem / 3600,
rem % 3600 / 60,
rem % 60
))
}
pub fn new_credential_id() -> Result<String> {
let mut b = [0u8; 16];
getrandom::getrandom(&mut b).map_err(|e| CoreError::Crypto(format!("rng: {e}")))?;
b[6] = (b[6] & 0x0f) | 0x40;
b[8] = (b[8] & 0x3f) | 0x80;
let h: String = b.iter().map(|x| format!("{x:02x}")).collect();
Ok(format!(
"urn:uuid:{}-{}-{}-{}-{}",
&h[..8],
&h[8..12],
&h[12..16],
&h[16..20],
&h[20..]
))
}
pub fn did_key_mismatch(did: &str, public_key: &[u8]) -> Option<String> {
if !did.starts_with("did:key:") {
return None;
}
let own = match crate::multikey::encode_ed25519_public(public_key) {
Ok(mk) => format!("did:key:{mk}"),
Err(_) => "did:key:".to_string(),
};
(own != did)
.then(|| format!("{did} is the did:key of a different key; this key's did:key is {own}"))
}
pub fn validate_intent(intent: &Value) -> Result<()> {
let Some(obj) = intent.as_object() else {
return Err(refused("intent must be a dict"));
};
let required: &[&str] = if grant_chain::is_grant_intent(intent) {
&["action", "resource"]
} else {
&["action", "target", "resource"]
};
for name in required {
match obj.get(*name) {
None | Some(Value::Null) => {}
Some(Value::String(s)) if s.is_empty() => {}
Some(_) => continue,
}
return Err(refused(format!(
"intent.{name} is REQUIRED (Specification §5.4.1): Vouch credentials MUST bind to \
a concrete resource"
)));
}
if !obj["resource"].is_string() {
return Err(refused(
"intent.resource must be a non-empty string naming the resource",
));
}
Ok(())
}
fn truthy(v: Option<&Value>) -> bool {
match v {
None | Some(Value::Null) => false,
Some(Value::Bool(b)) => *b,
Some(Value::Number(n)) => n.as_f64().is_some_and(|f| f != 0.0),
Some(Value::String(s)) => !s.is_empty(),
Some(Value::Array(a)) => !a.is_empty(),
Some(Value::Object(o)) => !o.is_empty(),
}
}
pub fn links_from_parent(parent: &Value, intent: &Value, signer_did: &str) -> Result<Vec<Value>> {
let grants = grant_chain::parent_grants(parent)?;
let last = grants.last().expect("parent_grants is never empty");
let Some(parent_intent) = last
.get("credentialSubject")
.and_then(|s| s.get("intent"))
.filter(|i| i.is_object())
else {
return Err(refused(
"Delegation refused: the parent grant carries no intent object",
));
};
if let (Some(Value::String(p)), Some(Value::String(c))) =
(parent_intent.get("resource"), intent.get("resource"))
{
if !p.is_empty() && !c.is_empty() && !attenuation::resource_within(c, p) {
return Err(refused(format!(
"Delegation violates resource-narrowing rule: child resource {} is not a \
sub-resource of parent {}",
py_repr_str(c),
py_repr_str(p)
)));
}
}
if !truthy(last.get("issuer"))
|| !matches!(last.get("proof"), Some(Value::Object(_) | Value::Array(_)))
{
return Err(refused(
"Delegation refused: the parent grant is not a signed credential",
));
}
let delegatee = parent_intent.get("delegatee");
if !truthy(delegatee) {
return Err(refused(
"Delegation refused: the parent grant names no delegatee; issue it with the \
delegatee's DID (for example vouch.delegate(..., to=did))",
));
}
if delegatee.and_then(Value::as_str) != Some(signer_did) {
return Err(refused(format!(
"Delegation refused: the parent grant names delegatee {}, not this signer {}",
py_repr(delegatee),
py_repr_str(signer_did)
)));
}
let links = grant_chain::check_grant_chain(&grants, intent)?;
let child =
delegation::capability_view(&json!({"credentialSubject": {"intent": intent}}), false);
let capability = grant_chain::chain_capability(&grants, false)?;
if let Err(dimension) = attenuation::non_expansion(&capability, &child) {
return Err(refused(format!(
"Delegation violates the non-expansion rule: the child is broader than the parent \
grant on {}",
py_repr_str(dimension.as_str())
)));
}
Ok(links)
}
fn clamp_to_parent(parent: &Value, start_ns: i128, valid_seconds: i64) -> Result<(i128, i64)> {
let bound = |k: &str| {
parent
.get(k)
.and_then(Value::as_str)
.map(|t| parse_protocol_time_ns(t).map(to_micros))
};
let (Some(Ok(from)), Some(Ok(until))) = (bound("validFrom"), bound("validUntil")) else {
return Err(refused(
"Delegation refused: the parent grant has no validity window",
));
};
let start = start_ns.max(from);
let remaining = (until - start) / NS_PER_SECOND;
if remaining <= 0 {
return Err(refused("Delegation refused: the parent grant has expired"));
}
let remaining = i64::try_from(remaining).unwrap_or(i64::MAX);
Ok((start, valid_seconds.min(remaining)))
}
pub fn prepare_credential(req: &IssueRequest) -> Result<Value> {
check_issuer(&req.issuer_did)?;
let now = to_micros(parse_protocol_time_ns(&req.now)?);
let mut valid_seconds = match req.valid_seconds {
None => DEFAULT_VALID_SECONDS,
Some(s) if s > 0 => s,
Some(_) => return Err(refused(INVALID_VALID_SECONDS)),
};
let mut start = match &req.valid_from {
Some(t) => to_micros(parse_protocol_time_ns(t)?),
None => now,
};
let mut chain = req.delegation_chain.clone();
let mut parent_digest: Option<String> = None;
if let Some(parent) = &req.parent_credential {
if !req.intent.is_object() {
return Err(refused("intent must be a dict"));
}
let links = links_from_parent(parent, &req.intent, &req.issuer_did)?;
let direct = &links[links.len() - 1]["parentCredential"];
(start, valid_seconds) = clamp_to_parent(direct, start, valid_seconds)?;
if grant_chain::is_grant_intent(&req.intent) {
parent_digest = Some(
grant_chain::grant_digest(direct).map_err(|_| refused(PARENT_NOT_PLAIN_JSON))?,
);
chain = None;
} else {
chain = Some(Value::Array(links));
}
}
validate_intent(&req.intent)?;
let chain = chain.filter(truthy_chain);
if parent_digest.is_some() && chain.is_some() {
return Err(refused(
"a credential carries parentGrantDigest or a delegationChain, never both",
));
}
let until = start + i128::from(valid_seconds) * NS_PER_SECOND;
let mut subject = Map::new();
subject.insert("id".into(), json!(req.issuer_did));
subject.insert(
"vouchVersion".into(),
json!(crate::credentials::PROTOCOL_VERSION),
);
subject.insert("intent".into(), req.intent.clone());
if let Some(score) = req.reputation_score {
subject.insert("reputationScore".into(), json!(score.clamp(0, 100)));
}
if let Some(digest) = parent_digest {
subject.insert(grant_chain::PARENT_GRANT_DIGEST.into(), json!(digest));
}
if let Some(chain) = chain {
subject.insert("delegationChain".into(), chain);
}
let id = match req.credential_id.as_deref() {
Some(id) if !id.is_empty() => id.to_string(),
_ => new_credential_id()?,
};
let mut vc = Map::new();
vc.insert(
"@context".into(),
json!([
crate::credentials::VC_CONTEXT_V2,
crate::credentials::VOUCH_CONTEXT_V1
]),
);
vc.insert("id".into(), json!(id));
vc.insert(
"type".into(),
json!([
crate::credentials::VC_TYPE,
crate::credentials::VOUCH_CREDENTIAL_TYPE
]),
);
vc.insert("issuer".into(), json!(req.issuer_did));
vc.insert("validFrom".into(), json!(format_protocol_time(start)?));
vc.insert("validUntil".into(), json!(format_protocol_time(until)?));
vc.insert("credentialSubject".into(), Value::Object(subject));
if let Some(status) = &req.credential_status {
vc.insert("credentialStatus".into(), status.clone());
}
Ok(Value::Object(vc))
}
fn truthy_chain(v: &Value) -> bool {
truthy(Some(v))
}
pub fn verification_method(req: &IssueRequest) -> String {
req.verification_method
.clone()
.unwrap_or_else(|| format!("{}#key-1", req.issuer_did))
}
fn slot_verification_method(ed25519_method: &str, slot: &str) -> String {
match ed25519_method.strip_suffix("#key-1") {
Some(base) => format!("{base}#{slot}"),
None => match ed25519_method.split_once('#') {
Some((base, _)) => format!("{base}#{slot}"),
None => format!("{ed25519_method}#{slot}"),
},
}
}
pub fn mldsa44_verification_method(ed25519_method: &str) -> String {
slot_verification_method(ed25519_method, "key-2")
}
pub fn slhdsa128_verification_method(ed25519_method: &str) -> String {
slot_verification_method(ed25519_method, "key-3")
}
fn created(req: &IssueRequest) -> Result<String> {
format_protocol_time(parse_protocol_time_ns(&req.now)?)
}
pub fn check_issuer(did: &str) -> Result<()> {
if did.is_empty() {
return Err(refused(
"Vouch Signer requires 'did' (Decentralized Identifier)",
));
}
if !(did.starts_with("did:") && did.len() > 4) {
return Err(refused(NOT_A_DID));
}
Ok(())
}
fn check_signer(req: &IssueRequest, ed25519_seed: &[u8]) -> Result<()> {
check_issuer(&req.issuer_did)?;
let kp = crate::keys::Ed25519KeyPair::from_seed_slice(ed25519_seed)?;
match did_key_mismatch(&req.issuer_did, &kp.public_key()) {
Some(problem) => Err(refused(problem)),
None => Ok(()),
}
}
pub fn issue_credential(req: &IssueRequest, ed25519_seed: &[u8]) -> Result<Value> {
check_signer(req, ed25519_seed)?;
let unsigned = prepare_credential(req)?;
let opts = BuildProofOptions::new(verification_method(req), created(req)?);
data_integrity::sign(&unsigned, ed25519_seed, &opts)
}
pub fn issue_credential_dual(
req: &IssueRequest,
ed25519_seed: &[u8],
mldsa44: &crate::pq::MlDsa44KeyPair,
) -> Result<Value> {
issue_credential_set(req, ed25519_seed, Some(mldsa44), None)
}
pub fn issue_credential_set(
req: &IssueRequest,
ed25519_seed: &[u8],
mldsa44: Option<&crate::pq::MlDsa44KeyPair>,
slhdsa128: Option<&crate::slh::SlhDsa128KeyPair>,
) -> Result<Value> {
check_signer(req, ed25519_seed)?;
let unsigned = prepare_credential(req)?;
let ed_vm = verification_method(req);
let ml_vm = mldsa44_verification_method(&ed_vm);
let slh_vm = slhdsa128_verification_method(&ed_vm);
crate::hybrid::sign_set(
&unsigned,
ed25519_seed,
&ed_vm,
mldsa44.map(|key| crate::hybrid::PqSigner {
key,
verification_method: &ml_vm,
}),
slhdsa128.map(|key| crate::hybrid::PqSigner {
key,
verification_method: &slh_vm,
}),
&created(req)?,
)
}
pub fn prepare_signing(req: &IssueRequest) -> Result<Value> {
use base64::{engine::general_purpose::STANDARD, Engine};
let unsigned = prepare_credential(req)?;
let mut proof = Map::new();
proof.insert("type".into(), json!(data_integrity::PROOF_TYPE));
proof.insert("cryptosuite".into(), json!(data_integrity::CRYPTOSUITE_ID));
proof.insert("created".into(), json!(created(req)?));
proof.insert("verificationMethod".into(), json!(verification_method(req)));
proof.insert("proofPurpose".into(), json!("assertionMethod"));
let input = data_integrity::hash_data(&unsigned, &proof)?;
Ok(json!({
"credential": unsigned,
"proof": Value::Object(proof),
"signingInput": STANDARD.encode(input),
}))
}
const REQUEST_MEMBERS: [&str; 17] = [
"issuer",
"intent",
"now",
"validFrom",
"validSeconds",
"reputationScore",
"delegationChain",
"parentCredential",
"credentialId",
"credentialStatus",
"verificationMethod",
"ed25519Seed",
"postQuantum",
"mldsa44SecretKey",
"mldsa44PublicKey",
"slhdsa128SecretKey",
"prepare",
];
fn present<'a>(obj: &'a Map<String, Value>, name: &str) -> Option<&'a Value> {
obj.get(name).filter(|v| !v.is_null())
}
fn text(obj: &Map<String, Value>, name: &str) -> Result<Option<String>> {
match present(obj, name) {
None => Ok(None),
Some(Value::String(s)) => Ok(Some(s.clone())),
Some(_) => Err(refused(format!("{name} must be a string"))),
}
}
fn b64(obj: &Map<String, Value>, name: &str) -> Result<Option<Vec<u8>>> {
use base64::{engine::general_purpose::STANDARD, Engine};
text(obj, name)?
.map(|s| {
STANDARD
.decode(s)
.map_err(|_| refused(format!("{name} must be standard base64")))
})
.transpose()
}
pub fn issue_request_from_json(obj: &Map<String, Value>) -> Result<IssueRequest> {
if let Some(name) = obj.keys().find(|k| !REQUEST_MEMBERS.contains(&k.as_str())) {
return Err(refused(format!(
"the request holds an unknown member {:?}",
name.chars().take(40).collect::<String>()
)));
}
let valid_seconds = match present(obj, "validSeconds") {
None => None,
Some(Value::Number(n)) if n.is_i64() => n.as_i64(),
Some(_) => Some(i64::MIN),
};
let whole = |name: &str| -> Result<Option<i64>> {
match present(obj, name) {
None => Ok(None),
Some(Value::Number(n)) => n
.as_i64()
.or_else(|| {
n.as_f64()
.filter(|f| f.is_finite())
.map(|f| f.trunc() as i64)
})
.map(Some)
.ok_or_else(|| refused(format!("{name} must be a number"))),
Some(_) => Err(refused(format!("{name} must be a number"))),
}
};
Ok(IssueRequest {
issuer_did: text(obj, "issuer")?.ok_or_else(|| refused("issuer must be a DID"))?,
intent: obj.get("intent").cloned().unwrap_or(Value::Null),
now: text(obj, "now")?.ok_or_else(|| refused("now must be a protocol time"))?,
valid_from: text(obj, "validFrom")?,
valid_seconds,
reputation_score: whole("reputationScore")?,
delegation_chain: present(obj, "delegationChain").cloned(),
parent_credential: present(obj, "parentCredential").cloned(),
credential_id: text(obj, "credentialId")?,
credential_status: present(obj, "credentialStatus").cloned(),
verification_method: text(obj, "verificationMethod")?,
})
}
pub fn issue_json(request: &Value) -> Result<Value> {
let obj = request
.as_object()
.ok_or_else(|| refused("the request must be a JSON object"))?;
let req = issue_request_from_json(obj)?;
if matches!(present(obj, "prepare"), Some(Value::Bool(true))) {
return prepare_signing(&req);
}
let seed =
Zeroizing::new(b64(obj, "ed25519Seed")?.ok_or_else(|| refused("ed25519Seed is required"))?);
if matches!(present(obj, "postQuantum"), Some(Value::Bool(true))) {
let slhdsa = match b64(obj, "slhdsa128SecretKey")?.map(Zeroizing::new) {
Some(secret) => Some(crate::slh::SlhDsa128KeyPair::from_secret(&secret)?),
None => None,
};
let wants_mldsa = slhdsa.is_none()
|| present(obj, "mldsa44SecretKey").is_some()
|| present(obj, "mldsa44PublicKey").is_some();
let mldsa = if wants_mldsa {
let secret = Zeroizing::new(
b64(obj, "mldsa44SecretKey")?
.ok_or_else(|| refused("mldsa44SecretKey is required for postQuantum"))?,
);
let public = b64(obj, "mldsa44PublicKey")?
.ok_or_else(|| refused("mldsa44PublicKey is required for postQuantum"))?;
Some(crate::pq::MlDsa44KeyPair::from_bytes(&secret, &public)?)
} else {
None
};
return issue_credential_set(&req, &seed, mldsa.as_ref(), slhdsa.as_ref());
}
issue_credential(&req, &seed)
}
pub const SECRET_MEMBERS: [&str; 3] = ["ed25519Seed", "mldsa44SecretKey", "slhdsa128SecretKey"];
pub fn wipe_secrets(request: &mut Value) {
if let Some(obj) = request.as_object_mut() {
for name in SECRET_MEMBERS {
if let Some(Value::String(text)) = obj.get_mut(name) {
text.zeroize();
}
obj.remove(name);
}
}
}
pub fn issue_json_text(mut request: String) -> Result<Value> {
let parsed = serde_json::from_str::<Value>(&request);
request.zeroize();
let mut parsed = parsed.map_err(|e| refused(format!("the request is not JSON: {e}")))?;
let out = issue_json(&parsed);
wipe_secrets(&mut parsed);
out
}
pub fn delegation_links_json(request: &Value) -> Result<Value> {
let obj = request
.as_object()
.ok_or_else(|| refused("the request must be a JSON object"))?;
let parent = obj.get("parentCredential").unwrap_or(&Value::Null);
let intent = obj.get("intent").unwrap_or(&Value::Null);
let signer = text(obj, "signerDid")?.unwrap_or_default();
Ok(Value::Array(links_from_parent(parent, intent, &signer)?))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn formats_whole_seconds() {
let t = parse_protocol_time_ns("2026-04-26T10:00:00.999Z").unwrap();
assert_eq!(format_protocol_time(t).unwrap(), "2026-04-26T10:00:00Z");
let t = parse_protocol_time_ns("2000-02-29T23:59:59Z").unwrap();
assert_eq!(format_protocol_time(t).unwrap(), "2000-02-29T23:59:59Z");
let t = parse_protocol_time_ns("1969-12-31T23:59:59Z").unwrap();
assert_eq!(format_protocol_time(t).unwrap(), "1969-12-31T23:59:59Z");
}
#[test]
fn credential_ids_are_uuid_v4() {
let id = new_credential_id().unwrap();
assert_eq!(id.len(), "urn:uuid:".len() + 36);
assert_eq!(&id[23..24], "4");
}
#[test]
fn did_key_must_name_the_signing_key() {
let kp = crate::keys::Ed25519KeyPair::from_seed(&[1u8; 32]);
assert!(did_key_mismatch(&kp.did_key(), &kp.public_key()).is_none());
let other = crate::keys::Ed25519KeyPair::from_seed(&[2u8; 32]);
assert!(did_key_mismatch(&other.did_key(), &kp.public_key()).is_some());
assert!(did_key_mismatch("did:web:a.example", &kp.public_key()).is_none());
}
}