1use serde_json::{json, Map, Value};
13
14use crate::attenuation;
15use crate::data_integrity::{self, BuildProofOptions};
16use crate::delegation;
17use crate::error::{CoreError, Result};
18use crate::grant_chain::{self, py_repr, py_repr_str};
19use crate::time::parse_protocol_time_ns;
20use zeroize::{Zeroize, Zeroizing};
21
22pub const DEFAULT_VALID_SECONDS: i64 = 300;
25pub const INVALID_VALID_SECONDS: &str =
28 "valid_seconds must be a whole number of seconds greater than zero";
29pub const NOT_A_DID: &str = "Vouch Signer requires 'did' to be a DID (did:<method>:...)";
31pub const PARENT_NOT_PLAIN_JSON: &str =
33 "Delegation refused: the parent grant is not plain JSON, so it has no digest";
34
35const NS_PER_SECOND: i128 = 1_000_000_000;
36
37fn to_micros(ns: i128) -> i128 {
40 ns.div_euclid(1000) * 1000
41}
42
43fn refused(msg: impl Into<String>) -> CoreError {
44 CoreError::Json(msg.into())
45}
46
47#[derive(Debug, Clone, Default)]
49pub struct IssueRequest {
50 pub issuer_did: String,
52 pub intent: Value,
55 pub now: String,
58 pub valid_from: Option<String>,
60 pub valid_seconds: Option<i64>,
63 pub reputation_score: Option<i64>,
65 pub delegation_chain: Option<Value>,
67 pub parent_credential: Option<Value>,
70 pub credential_id: Option<String>,
72 pub credential_status: Option<Value>,
74 pub verification_method: Option<String>,
77}
78
79pub fn format_protocol_time(ns: i128) -> Result<String> {
83 let secs = ns.div_euclid(NS_PER_SECOND);
84 let days = secs.div_euclid(86_400);
85 let rem = secs.rem_euclid(86_400);
86 let z = days + 719_468;
88 let era = z.div_euclid(146_097);
89 let doe = z.rem_euclid(146_097);
90 let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
91 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
92 let mp = (5 * doy + 2) / 153;
93 let day = doy - (153 * mp + 2) / 5 + 1;
94 let month = if mp < 10 { mp + 3 } else { mp - 9 };
95 let year = yoe + era * 400 + i128::from(month <= 2);
96 if !(1..=9999).contains(&year) {
97 return Err(refused("date value out of range"));
98 }
99 Ok(format!(
100 "{year:04}-{month:02}-{day:02}T{:02}:{:02}:{:02}Z",
101 rem / 3600,
102 rem % 3600 / 60,
103 rem % 60
104 ))
105}
106
107pub fn new_credential_id() -> Result<String> {
109 let mut b = [0u8; 16];
110 getrandom::getrandom(&mut b).map_err(|e| CoreError::Crypto(format!("rng: {e}")))?;
111 b[6] = (b[6] & 0x0f) | 0x40;
112 b[8] = (b[8] & 0x3f) | 0x80;
113 let h: String = b.iter().map(|x| format!("{x:02x}")).collect();
114 Ok(format!(
115 "urn:uuid:{}-{}-{}-{}-{}",
116 &h[..8],
117 &h[8..12],
118 &h[12..16],
119 &h[16..20],
120 &h[20..]
121 ))
122}
123
124pub fn did_key_mismatch(did: &str, public_key: &[u8]) -> Option<String> {
127 if !did.starts_with("did:key:") {
128 return None;
129 }
130 let own = match crate::multikey::encode_ed25519_public(public_key) {
131 Ok(mk) => format!("did:key:{mk}"),
132 Err(_) => "did:key:".to_string(),
133 };
134 (own != did)
135 .then(|| format!("{did} is the did:key of a different key; this key's did:key is {own}"))
136}
137
138pub fn validate_intent(intent: &Value) -> Result<()> {
142 let Some(obj) = intent.as_object() else {
143 return Err(refused("intent must be a dict"));
144 };
145 let required: &[&str] = if grant_chain::is_grant_intent(intent) {
146 &["action", "resource"]
147 } else {
148 &["action", "target", "resource"]
149 };
150 for name in required {
151 match obj.get(*name) {
152 None | Some(Value::Null) => {}
153 Some(Value::String(s)) if s.is_empty() => {}
154 Some(_) => continue,
155 }
156 return Err(refused(format!(
157 "intent.{name} is REQUIRED (Specification ยง5.4.1): Vouch credentials MUST bind to \
158 a concrete resource"
159 )));
160 }
161 if !obj["resource"].is_string() {
162 return Err(refused(
163 "intent.resource must be a non-empty string naming the resource",
164 ));
165 }
166 Ok(())
167}
168
169fn truthy(v: Option<&Value>) -> bool {
170 match v {
171 None | Some(Value::Null) => false,
172 Some(Value::Bool(b)) => *b,
173 Some(Value::Number(n)) => n.as_f64().is_some_and(|f| f != 0.0),
174 Some(Value::String(s)) => !s.is_empty(),
175 Some(Value::Array(a)) => !a.is_empty(),
176 Some(Value::Object(o)) => !o.is_empty(),
177 }
178}
179
180pub fn links_from_parent(parent: &Value, intent: &Value, signer_did: &str) -> Result<Vec<Value>> {
188 let grants = grant_chain::parent_grants(parent)?;
189 let last = grants.last().expect("parent_grants is never empty");
190 let Some(parent_intent) = last
191 .get("credentialSubject")
192 .and_then(|s| s.get("intent"))
193 .filter(|i| i.is_object())
194 else {
195 return Err(refused(
196 "Delegation refused: the parent grant carries no intent object",
197 ));
198 };
199 if let (Some(Value::String(p)), Some(Value::String(c))) =
201 (parent_intent.get("resource"), intent.get("resource"))
202 {
203 if !p.is_empty() && !c.is_empty() && !attenuation::resource_within(c, p) {
204 return Err(refused(format!(
205 "Delegation violates resource-narrowing rule: child resource {} is not a \
206 sub-resource of parent {}",
207 py_repr_str(c),
208 py_repr_str(p)
209 )));
210 }
211 }
212 if !truthy(last.get("issuer"))
213 || !matches!(last.get("proof"), Some(Value::Object(_) | Value::Array(_)))
214 {
215 return Err(refused(
216 "Delegation refused: the parent grant is not a signed credential",
217 ));
218 }
219 let delegatee = parent_intent.get("delegatee");
220 if !truthy(delegatee) {
221 return Err(refused(
222 "Delegation refused: the parent grant names no delegatee; issue it with the \
223 delegatee's DID (for example vouch.delegate(..., to=did))",
224 ));
225 }
226 if delegatee.and_then(Value::as_str) != Some(signer_did) {
227 return Err(refused(format!(
228 "Delegation refused: the parent grant names delegatee {}, not this signer {}",
229 py_repr(delegatee),
230 py_repr_str(signer_did)
231 )));
232 }
233 let links = grant_chain::check_grant_chain(&grants, intent)?;
234 let child =
235 delegation::capability_view(&json!({"credentialSubject": {"intent": intent}}), false);
236 let capability = grant_chain::chain_capability(&grants, false)?;
237 if let Err(dimension) = attenuation::non_expansion(&capability, &child) {
238 return Err(refused(format!(
239 "Delegation violates the non-expansion rule: the child is broader than the parent \
240 grant on {}",
241 py_repr_str(dimension.as_str())
242 )));
243 }
244 Ok(links)
245}
246
247fn clamp_to_parent(parent: &Value, start_ns: i128, valid_seconds: i64) -> Result<(i128, i64)> {
250 let bound = |k: &str| {
251 parent
252 .get(k)
253 .and_then(Value::as_str)
254 .map(|t| parse_protocol_time_ns(t).map(to_micros))
255 };
256 let (Some(Ok(from)), Some(Ok(until))) = (bound("validFrom"), bound("validUntil")) else {
257 return Err(refused(
258 "Delegation refused: the parent grant has no validity window",
259 ));
260 };
261 let start = start_ns.max(from);
262 let remaining = (until - start) / NS_PER_SECOND;
264 if remaining <= 0 {
265 return Err(refused("Delegation refused: the parent grant has expired"));
266 }
267 let remaining = i64::try_from(remaining).unwrap_or(i64::MAX);
268 Ok((start, valid_seconds.min(remaining)))
269}
270
271pub fn prepare_credential(req: &IssueRequest) -> Result<Value> {
274 check_issuer(&req.issuer_did)?;
275 let now = to_micros(parse_protocol_time_ns(&req.now)?);
276 let mut valid_seconds = match req.valid_seconds {
277 None => DEFAULT_VALID_SECONDS,
278 Some(s) if s > 0 => s,
279 Some(_) => return Err(refused(INVALID_VALID_SECONDS)),
280 };
281 let mut start = match &req.valid_from {
282 Some(t) => to_micros(parse_protocol_time_ns(t)?),
283 None => now,
284 };
285 let mut chain = req.delegation_chain.clone();
286 let mut parent_digest: Option<String> = None;
287 if let Some(parent) = &req.parent_credential {
288 if !req.intent.is_object() {
289 return Err(refused("intent must be a dict"));
290 }
291 let links = links_from_parent(parent, &req.intent, &req.issuer_did)?;
292 let direct = &links[links.len() - 1]["parentCredential"];
293 (start, valid_seconds) = clamp_to_parent(direct, start, valid_seconds)?;
294 if grant_chain::is_grant_intent(&req.intent) {
295 parent_digest = Some(
296 grant_chain::grant_digest(direct).map_err(|_| refused(PARENT_NOT_PLAIN_JSON))?,
297 );
298 chain = None;
299 } else {
300 chain = Some(Value::Array(links));
301 }
302 }
303
304 validate_intent(&req.intent)?;
305 let chain = chain.filter(truthy_chain);
306 if parent_digest.is_some() && chain.is_some() {
307 return Err(refused(
308 "a credential carries parentGrantDigest or a delegationChain, never both",
309 ));
310 }
311 let until = start + i128::from(valid_seconds) * NS_PER_SECOND;
312
313 let mut subject = Map::new();
314 subject.insert("id".into(), json!(req.issuer_did));
315 subject.insert(
316 "vouchVersion".into(),
317 json!(crate::credentials::PROTOCOL_VERSION),
318 );
319 subject.insert("intent".into(), req.intent.clone());
320 if let Some(score) = req.reputation_score {
321 subject.insert("reputationScore".into(), json!(score.clamp(0, 100)));
322 }
323 if let Some(digest) = parent_digest {
324 subject.insert(grant_chain::PARENT_GRANT_DIGEST.into(), json!(digest));
325 }
326 if let Some(chain) = chain {
327 subject.insert("delegationChain".into(), chain);
328 }
329 let id = match req.credential_id.as_deref() {
330 Some(id) if !id.is_empty() => id.to_string(),
331 _ => new_credential_id()?,
332 };
333 let mut vc = Map::new();
334 vc.insert(
335 "@context".into(),
336 json!([
337 crate::credentials::VC_CONTEXT_V2,
338 crate::credentials::VOUCH_CONTEXT_V1
339 ]),
340 );
341 vc.insert("id".into(), json!(id));
342 vc.insert(
343 "type".into(),
344 json!([
345 crate::credentials::VC_TYPE,
346 crate::credentials::VOUCH_CREDENTIAL_TYPE
347 ]),
348 );
349 vc.insert("issuer".into(), json!(req.issuer_did));
350 vc.insert("validFrom".into(), json!(format_protocol_time(start)?));
351 vc.insert("validUntil".into(), json!(format_protocol_time(until)?));
352 vc.insert("credentialSubject".into(), Value::Object(subject));
353 if let Some(status) = &req.credential_status {
354 vc.insert("credentialStatus".into(), status.clone());
355 }
356 Ok(Value::Object(vc))
357}
358
359fn truthy_chain(v: &Value) -> bool {
360 truthy(Some(v))
361}
362
363pub fn verification_method(req: &IssueRequest) -> String {
365 req.verification_method
366 .clone()
367 .unwrap_or_else(|| format!("{}#key-1", req.issuer_did))
368}
369
370fn slot_verification_method(ed25519_method: &str, slot: &str) -> String {
373 match ed25519_method.strip_suffix("#key-1") {
374 Some(base) => format!("{base}#{slot}"),
375 None => match ed25519_method.split_once('#') {
376 Some((base, _)) => format!("{base}#{slot}"),
377 None => format!("{ed25519_method}#{slot}"),
378 },
379 }
380}
381
382pub fn mldsa44_verification_method(ed25519_method: &str) -> String {
385 slot_verification_method(ed25519_method, "key-2")
386}
387
388pub fn slhdsa128_verification_method(ed25519_method: &str) -> String {
391 slot_verification_method(ed25519_method, "key-3")
392}
393
394fn created(req: &IssueRequest) -> Result<String> {
396 format_protocol_time(parse_protocol_time_ns(&req.now)?)
397}
398
399pub fn check_issuer(did: &str) -> Result<()> {
402 if did.is_empty() {
403 return Err(refused(
404 "Vouch Signer requires 'did' (Decentralized Identifier)",
405 ));
406 }
407 if !(did.starts_with("did:") && did.len() > 4) {
408 return Err(refused(NOT_A_DID));
409 }
410 Ok(())
411}
412
413fn check_signer(req: &IssueRequest, ed25519_seed: &[u8]) -> Result<()> {
414 check_issuer(&req.issuer_did)?;
415 let kp = crate::keys::Ed25519KeyPair::from_seed_slice(ed25519_seed)?;
416 match did_key_mismatch(&req.issuer_did, &kp.public_key()) {
417 Some(problem) => Err(refused(problem)),
418 None => Ok(()),
419 }
420}
421
422pub fn issue_credential(req: &IssueRequest, ed25519_seed: &[u8]) -> Result<Value> {
425 check_signer(req, ed25519_seed)?;
426 let unsigned = prepare_credential(req)?;
427 let opts = BuildProofOptions::new(verification_method(req), created(req)?);
428 data_integrity::sign(&unsigned, ed25519_seed, &opts)
429}
430
431pub fn issue_credential_dual(
437 req: &IssueRequest,
438 ed25519_seed: &[u8],
439 mldsa44: &crate::pq::MlDsa44KeyPair,
440) -> Result<Value> {
441 issue_credential_set(req, ed25519_seed, Some(mldsa44), None)
442}
443
444pub fn issue_credential_set(
451 req: &IssueRequest,
452 ed25519_seed: &[u8],
453 mldsa44: Option<&crate::pq::MlDsa44KeyPair>,
454 slhdsa128: Option<&crate::slh::SlhDsa128KeyPair>,
455) -> Result<Value> {
456 check_signer(req, ed25519_seed)?;
457 let unsigned = prepare_credential(req)?;
458 let ed_vm = verification_method(req);
459 let ml_vm = mldsa44_verification_method(&ed_vm);
460 let slh_vm = slhdsa128_verification_method(&ed_vm);
461 crate::hybrid::sign_set(
462 &unsigned,
463 ed25519_seed,
464 &ed_vm,
465 mldsa44.map(|key| crate::hybrid::PqSigner {
466 key,
467 verification_method: &ml_vm,
468 }),
469 slhdsa128.map(|key| crate::hybrid::PqSigner {
470 key,
471 verification_method: &slh_vm,
472 }),
473 &created(req)?,
474 )
475}
476
477pub fn prepare_signing(req: &IssueRequest) -> Result<Value> {
483 use base64::{engine::general_purpose::STANDARD, Engine};
484 let unsigned = prepare_credential(req)?;
485 let mut proof = Map::new();
486 proof.insert("type".into(), json!(data_integrity::PROOF_TYPE));
487 proof.insert("cryptosuite".into(), json!(data_integrity::CRYPTOSUITE_ID));
488 proof.insert("created".into(), json!(created(req)?));
489 proof.insert("verificationMethod".into(), json!(verification_method(req)));
490 proof.insert("proofPurpose".into(), json!("assertionMethod"));
491 let input = data_integrity::hash_data(&unsigned, &proof)?;
492 Ok(json!({
493 "credential": unsigned,
494 "proof": Value::Object(proof),
495 "signingInput": STANDARD.encode(input),
496 }))
497}
498
499const REQUEST_MEMBERS: [&str; 17] = [
504 "issuer",
505 "intent",
506 "now",
507 "validFrom",
508 "validSeconds",
509 "reputationScore",
510 "delegationChain",
511 "parentCredential",
512 "credentialId",
513 "credentialStatus",
514 "verificationMethod",
515 "ed25519Seed",
516 "postQuantum",
517 "mldsa44SecretKey",
518 "mldsa44PublicKey",
519 "slhdsa128SecretKey",
520 "prepare",
521];
522
523fn present<'a>(obj: &'a Map<String, Value>, name: &str) -> Option<&'a Value> {
524 obj.get(name).filter(|v| !v.is_null())
525}
526
527fn text(obj: &Map<String, Value>, name: &str) -> Result<Option<String>> {
528 match present(obj, name) {
529 None => Ok(None),
530 Some(Value::String(s)) => Ok(Some(s.clone())),
531 Some(_) => Err(refused(format!("{name} must be a string"))),
532 }
533}
534
535fn b64(obj: &Map<String, Value>, name: &str) -> Result<Option<Vec<u8>>> {
536 use base64::{engine::general_purpose::STANDARD, Engine};
537 text(obj, name)?
538 .map(|s| {
539 STANDARD
540 .decode(s)
541 .map_err(|_| refused(format!("{name} must be standard base64")))
542 })
543 .transpose()
544}
545
546pub fn issue_request_from_json(obj: &Map<String, Value>) -> Result<IssueRequest> {
548 if let Some(name) = obj.keys().find(|k| !REQUEST_MEMBERS.contains(&k.as_str())) {
549 return Err(refused(format!(
550 "the request holds an unknown member {:?}",
551 name.chars().take(40).collect::<String>()
552 )));
553 }
554 let valid_seconds = match present(obj, "validSeconds") {
557 None => None,
558 Some(Value::Number(n)) if n.is_i64() => n.as_i64(),
559 Some(_) => Some(i64::MIN),
560 };
561 let whole = |name: &str| -> Result<Option<i64>> {
562 match present(obj, name) {
563 None => Ok(None),
564 Some(Value::Number(n)) => n
565 .as_i64()
566 .or_else(|| {
567 n.as_f64()
568 .filter(|f| f.is_finite())
569 .map(|f| f.trunc() as i64)
570 })
571 .map(Some)
572 .ok_or_else(|| refused(format!("{name} must be a number"))),
573 Some(_) => Err(refused(format!("{name} must be a number"))),
574 }
575 };
576 Ok(IssueRequest {
577 issuer_did: text(obj, "issuer")?.ok_or_else(|| refused("issuer must be a DID"))?,
578 intent: obj.get("intent").cloned().unwrap_or(Value::Null),
579 now: text(obj, "now")?.ok_or_else(|| refused("now must be a protocol time"))?,
580 valid_from: text(obj, "validFrom")?,
581 valid_seconds,
582 reputation_score: whole("reputationScore")?,
583 delegation_chain: present(obj, "delegationChain").cloned(),
584 parent_credential: present(obj, "parentCredential").cloned(),
585 credential_id: text(obj, "credentialId")?,
586 credential_status: present(obj, "credentialStatus").cloned(),
587 verification_method: text(obj, "verificationMethod")?,
588 })
589}
590
591pub fn issue_json(request: &Value) -> Result<Value> {
602 let obj = request
603 .as_object()
604 .ok_or_else(|| refused("the request must be a JSON object"))?;
605 let req = issue_request_from_json(obj)?;
606 if matches!(present(obj, "prepare"), Some(Value::Bool(true))) {
607 return prepare_signing(&req);
608 }
609 let seed =
611 Zeroizing::new(b64(obj, "ed25519Seed")?.ok_or_else(|| refused("ed25519Seed is required"))?);
612 if matches!(present(obj, "postQuantum"), Some(Value::Bool(true))) {
613 let slhdsa = match b64(obj, "slhdsa128SecretKey")?.map(Zeroizing::new) {
614 Some(secret) => Some(crate::slh::SlhDsa128KeyPair::from_secret(&secret)?),
615 None => None,
616 };
617 let wants_mldsa = slhdsa.is_none()
620 || present(obj, "mldsa44SecretKey").is_some()
621 || present(obj, "mldsa44PublicKey").is_some();
622 let mldsa = if wants_mldsa {
623 let secret = Zeroizing::new(
624 b64(obj, "mldsa44SecretKey")?
625 .ok_or_else(|| refused("mldsa44SecretKey is required for postQuantum"))?,
626 );
627 let public = b64(obj, "mldsa44PublicKey")?
628 .ok_or_else(|| refused("mldsa44PublicKey is required for postQuantum"))?;
629 Some(crate::pq::MlDsa44KeyPair::from_bytes(&secret, &public)?)
630 } else {
631 None
632 };
633 return issue_credential_set(&req, &seed, mldsa.as_ref(), slhdsa.as_ref());
634 }
635 issue_credential(&req, &seed)
636}
637
638pub const SECRET_MEMBERS: [&str; 3] = ["ed25519Seed", "mldsa44SecretKey", "slhdsa128SecretKey"];
640
641pub fn wipe_secrets(request: &mut Value) {
645 if let Some(obj) = request.as_object_mut() {
646 for name in SECRET_MEMBERS {
647 if let Some(Value::String(text)) = obj.get_mut(name) {
648 text.zeroize();
649 }
650 obj.remove(name);
651 }
652 }
653}
654
655pub fn issue_json_text(mut request: String) -> Result<Value> {
659 let parsed = serde_json::from_str::<Value>(&request);
660 request.zeroize();
661 let mut parsed = parsed.map_err(|e| refused(format!("the request is not JSON: {e}")))?;
662 let out = issue_json(&parsed);
663 wipe_secrets(&mut parsed);
664 out
665}
666
667pub fn delegation_links_json(request: &Value) -> Result<Value> {
670 let obj = request
671 .as_object()
672 .ok_or_else(|| refused("the request must be a JSON object"))?;
673 let parent = obj.get("parentCredential").unwrap_or(&Value::Null);
674 let intent = obj.get("intent").unwrap_or(&Value::Null);
675 let signer = text(obj, "signerDid")?.unwrap_or_default();
676 Ok(Value::Array(links_from_parent(parent, intent, &signer)?))
677}
678
679#[cfg(test)]
680mod tests {
681 use super::*;
682
683 #[test]
684 fn formats_whole_seconds() {
685 let t = parse_protocol_time_ns("2026-04-26T10:00:00.999Z").unwrap();
686 assert_eq!(format_protocol_time(t).unwrap(), "2026-04-26T10:00:00Z");
687 let t = parse_protocol_time_ns("2000-02-29T23:59:59Z").unwrap();
688 assert_eq!(format_protocol_time(t).unwrap(), "2000-02-29T23:59:59Z");
689 let t = parse_protocol_time_ns("1969-12-31T23:59:59Z").unwrap();
690 assert_eq!(format_protocol_time(t).unwrap(), "1969-12-31T23:59:59Z");
691 }
692
693 #[test]
694 fn credential_ids_are_uuid_v4() {
695 let id = new_credential_id().unwrap();
696 assert_eq!(id.len(), "urn:uuid:".len() + 36);
697 assert_eq!(&id[23..24], "4");
698 }
699
700 #[test]
701 fn did_key_must_name_the_signing_key() {
702 let kp = crate::keys::Ed25519KeyPair::from_seed(&[1u8; 32]);
703 assert!(did_key_mismatch(&kp.did_key(), &kp.public_key()).is_none());
704 let other = crate::keys::Ed25519KeyPair::from_seed(&[2u8; 32]);
705 assert!(did_key_mismatch(&other.did_key(), &kp.public_key()).is_some());
706 assert!(did_key_mismatch("did:web:a.example", &kp.public_key()).is_none());
707 }
708}