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
180fn links_from_parent(parent: &Value, intent: &Value, signer_did: &str) -> Result<Vec<Value>> {
183 let grants = grant_chain::parent_grants(parent)?;
184 let last = grants.last().expect("parent_grants is never empty");
185 let Some(parent_intent) = last
186 .get("credentialSubject")
187 .and_then(|s| s.get("intent"))
188 .filter(|i| i.is_object())
189 else {
190 return Err(refused(
191 "Delegation refused: the parent grant carries no intent object",
192 ));
193 };
194 if let (Some(Value::String(p)), Some(Value::String(c))) =
196 (parent_intent.get("resource"), intent.get("resource"))
197 {
198 if !p.is_empty() && !c.is_empty() && !attenuation::resource_within(c, p) {
199 return Err(refused(format!(
200 "Delegation violates resource-narrowing rule: child resource {} is not a \
201 sub-resource of parent {}",
202 py_repr_str(c),
203 py_repr_str(p)
204 )));
205 }
206 }
207 if !truthy(last.get("issuer"))
208 || !matches!(last.get("proof"), Some(Value::Object(_) | Value::Array(_)))
209 {
210 return Err(refused(
211 "Delegation refused: the parent grant is not a signed credential",
212 ));
213 }
214 let delegatee = parent_intent.get("delegatee");
215 if !truthy(delegatee) {
216 return Err(refused(
217 "Delegation refused: the parent grant names no delegatee; issue it with the \
218 delegatee's DID (for example vouch.delegate(..., to=did))",
219 ));
220 }
221 if delegatee.and_then(Value::as_str) != Some(signer_did) {
222 return Err(refused(format!(
223 "Delegation refused: the parent grant names delegatee {}, not this signer {}",
224 py_repr(delegatee),
225 py_repr_str(signer_did)
226 )));
227 }
228 let links = grant_chain::check_grant_chain(&grants, intent)?;
229 let child =
230 delegation::capability_view(&json!({"credentialSubject": {"intent": intent}}), false);
231 let capability = grant_chain::chain_capability(&grants, false)?;
232 if let Err(dimension) = attenuation::non_expansion(&capability, &child) {
233 return Err(refused(format!(
234 "Delegation violates the non-expansion rule: the child is broader than the parent \
235 grant on {}",
236 py_repr_str(dimension.as_str())
237 )));
238 }
239 Ok(links)
240}
241
242fn clamp_to_parent(parent: &Value, start_ns: i128, valid_seconds: i64) -> Result<(i128, i64)> {
245 let bound = |k: &str| {
246 parent
247 .get(k)
248 .and_then(Value::as_str)
249 .map(|t| parse_protocol_time_ns(t).map(to_micros))
250 };
251 let (Some(Ok(from)), Some(Ok(until))) = (bound("validFrom"), bound("validUntil")) else {
252 return Err(refused(
253 "Delegation refused: the parent grant has no validity window",
254 ));
255 };
256 let start = start_ns.max(from);
257 let remaining = (until - start) / NS_PER_SECOND;
259 if remaining <= 0 {
260 return Err(refused("Delegation refused: the parent grant has expired"));
261 }
262 let remaining = i64::try_from(remaining).unwrap_or(i64::MAX);
263 Ok((start, valid_seconds.min(remaining)))
264}
265
266pub fn prepare_credential(req: &IssueRequest) -> Result<Value> {
269 check_issuer(&req.issuer_did)?;
270 let now = to_micros(parse_protocol_time_ns(&req.now)?);
271 let mut valid_seconds = match req.valid_seconds {
272 None => DEFAULT_VALID_SECONDS,
273 Some(s) if s > 0 => s,
274 Some(_) => return Err(refused(INVALID_VALID_SECONDS)),
275 };
276 let mut start = match &req.valid_from {
277 Some(t) => to_micros(parse_protocol_time_ns(t)?),
278 None => now,
279 };
280 let mut chain = req.delegation_chain.clone();
281 let mut parent_digest: Option<String> = None;
282 if let Some(parent) = &req.parent_credential {
283 if !req.intent.is_object() {
284 return Err(refused("intent must be a dict"));
285 }
286 let links = links_from_parent(parent, &req.intent, &req.issuer_did)?;
287 let direct = &links[links.len() - 1]["parentCredential"];
288 (start, valid_seconds) = clamp_to_parent(direct, start, valid_seconds)?;
289 if grant_chain::is_grant_intent(&req.intent) {
290 parent_digest = Some(
291 grant_chain::grant_digest(direct).map_err(|_| refused(PARENT_NOT_PLAIN_JSON))?,
292 );
293 chain = None;
294 } else {
295 chain = Some(Value::Array(links));
296 }
297 }
298
299 validate_intent(&req.intent)?;
300 let chain = chain.filter(truthy_chain);
301 if parent_digest.is_some() && chain.is_some() {
302 return Err(refused(
303 "a credential carries parentGrantDigest or a delegationChain, never both",
304 ));
305 }
306 let until = start + i128::from(valid_seconds) * NS_PER_SECOND;
307
308 let mut subject = Map::new();
309 subject.insert("id".into(), json!(req.issuer_did));
310 subject.insert(
311 "vouchVersion".into(),
312 json!(crate::credentials::PROTOCOL_VERSION),
313 );
314 subject.insert("intent".into(), req.intent.clone());
315 if let Some(score) = req.reputation_score {
316 subject.insert("reputationScore".into(), json!(score.clamp(0, 100)));
317 }
318 if let Some(digest) = parent_digest {
319 subject.insert(grant_chain::PARENT_GRANT_DIGEST.into(), json!(digest));
320 }
321 if let Some(chain) = chain {
322 subject.insert("delegationChain".into(), chain);
323 }
324 let id = match req.credential_id.as_deref() {
325 Some(id) if !id.is_empty() => id.to_string(),
326 _ => new_credential_id()?,
327 };
328 let mut vc = Map::new();
329 vc.insert(
330 "@context".into(),
331 json!([
332 crate::credentials::VC_CONTEXT_V2,
333 crate::credentials::VOUCH_CONTEXT_V1
334 ]),
335 );
336 vc.insert("id".into(), json!(id));
337 vc.insert(
338 "type".into(),
339 json!([
340 crate::credentials::VC_TYPE,
341 crate::credentials::VOUCH_CREDENTIAL_TYPE
342 ]),
343 );
344 vc.insert("issuer".into(), json!(req.issuer_did));
345 vc.insert("validFrom".into(), json!(format_protocol_time(start)?));
346 vc.insert("validUntil".into(), json!(format_protocol_time(until)?));
347 vc.insert("credentialSubject".into(), Value::Object(subject));
348 if let Some(status) = &req.credential_status {
349 vc.insert("credentialStatus".into(), status.clone());
350 }
351 Ok(Value::Object(vc))
352}
353
354fn truthy_chain(v: &Value) -> bool {
355 truthy(Some(v))
356}
357
358pub fn verification_method(req: &IssueRequest) -> String {
360 req.verification_method
361 .clone()
362 .unwrap_or_else(|| format!("{}#key-1", req.issuer_did))
363}
364
365pub fn mldsa44_verification_method(ed25519_method: &str) -> String {
368 match ed25519_method.strip_suffix("#key-1") {
369 Some(base) => format!("{base}#key-2"),
370 None => match ed25519_method.split_once('#') {
371 Some((base, _)) => format!("{base}#key-2"),
372 None => format!("{ed25519_method}#key-2"),
373 },
374 }
375}
376
377fn created(req: &IssueRequest) -> Result<String> {
379 format_protocol_time(parse_protocol_time_ns(&req.now)?)
380}
381
382pub fn check_issuer(did: &str) -> Result<()> {
385 if did.is_empty() {
386 return Err(refused(
387 "Vouch Signer requires 'did' (Decentralized Identifier)",
388 ));
389 }
390 if !(did.starts_with("did:") && did.len() > 4) {
391 return Err(refused(NOT_A_DID));
392 }
393 Ok(())
394}
395
396fn check_signer(req: &IssueRequest, ed25519_seed: &[u8]) -> Result<()> {
397 check_issuer(&req.issuer_did)?;
398 let kp = crate::keys::Ed25519KeyPair::from_seed_slice(ed25519_seed)?;
399 match did_key_mismatch(&req.issuer_did, &kp.public_key()) {
400 Some(problem) => Err(refused(problem)),
401 None => Ok(()),
402 }
403}
404
405pub fn issue_credential(req: &IssueRequest, ed25519_seed: &[u8]) -> Result<Value> {
408 check_signer(req, ed25519_seed)?;
409 let unsigned = prepare_credential(req)?;
410 let opts = BuildProofOptions::new(verification_method(req), created(req)?);
411 data_integrity::sign(&unsigned, ed25519_seed, &opts)
412}
413
414pub fn issue_credential_dual(
420 req: &IssueRequest,
421 ed25519_seed: &[u8],
422 mldsa44: &crate::pq::MlDsa44KeyPair,
423) -> Result<Value> {
424 check_signer(req, ed25519_seed)?;
425 let unsigned = prepare_credential(req)?;
426 let ed_vm = verification_method(req);
427 let ml_vm = mldsa44_verification_method(&ed_vm);
428 crate::hybrid::sign_dual(
429 &unsigned,
430 ed25519_seed,
431 mldsa44,
432 &ed_vm,
433 &ml_vm,
434 &created(req)?,
435 )
436}
437
438pub fn prepare_signing(req: &IssueRequest) -> Result<Value> {
444 use base64::{engine::general_purpose::STANDARD, Engine};
445 let unsigned = prepare_credential(req)?;
446 let mut proof = Map::new();
447 proof.insert("type".into(), json!(data_integrity::PROOF_TYPE));
448 proof.insert("cryptosuite".into(), json!(data_integrity::CRYPTOSUITE_ID));
449 proof.insert("created".into(), json!(created(req)?));
450 proof.insert("verificationMethod".into(), json!(verification_method(req)));
451 proof.insert("proofPurpose".into(), json!("assertionMethod"));
452 let input = data_integrity::hash_data(&unsigned, &proof)?;
453 Ok(json!({
454 "credential": unsigned,
455 "proof": Value::Object(proof),
456 "signingInput": STANDARD.encode(input),
457 }))
458}
459
460const REQUEST_MEMBERS: [&str; 16] = [
465 "issuer",
466 "intent",
467 "now",
468 "validFrom",
469 "validSeconds",
470 "reputationScore",
471 "delegationChain",
472 "parentCredential",
473 "credentialId",
474 "credentialStatus",
475 "verificationMethod",
476 "ed25519Seed",
477 "postQuantum",
478 "mldsa44SecretKey",
479 "mldsa44PublicKey",
480 "prepare",
481];
482
483fn present<'a>(obj: &'a Map<String, Value>, name: &str) -> Option<&'a Value> {
484 obj.get(name).filter(|v| !v.is_null())
485}
486
487fn text(obj: &Map<String, Value>, name: &str) -> Result<Option<String>> {
488 match present(obj, name) {
489 None => Ok(None),
490 Some(Value::String(s)) => Ok(Some(s.clone())),
491 Some(_) => Err(refused(format!("{name} must be a string"))),
492 }
493}
494
495fn b64(obj: &Map<String, Value>, name: &str) -> Result<Option<Vec<u8>>> {
496 use base64::{engine::general_purpose::STANDARD, Engine};
497 text(obj, name)?
498 .map(|s| {
499 STANDARD
500 .decode(s)
501 .map_err(|_| refused(format!("{name} must be standard base64")))
502 })
503 .transpose()
504}
505
506pub fn issue_request_from_json(obj: &Map<String, Value>) -> Result<IssueRequest> {
508 if let Some(name) = obj.keys().find(|k| !REQUEST_MEMBERS.contains(&k.as_str())) {
509 return Err(refused(format!(
510 "the request holds an unknown member {:?}",
511 name.chars().take(40).collect::<String>()
512 )));
513 }
514 let valid_seconds = match present(obj, "validSeconds") {
517 None => None,
518 Some(Value::Number(n)) if n.is_i64() => n.as_i64(),
519 Some(_) => Some(i64::MIN),
520 };
521 let whole = |name: &str| -> Result<Option<i64>> {
522 match present(obj, name) {
523 None => Ok(None),
524 Some(Value::Number(n)) => n
525 .as_i64()
526 .or_else(|| {
527 n.as_f64()
528 .filter(|f| f.is_finite())
529 .map(|f| f.trunc() as i64)
530 })
531 .map(Some)
532 .ok_or_else(|| refused(format!("{name} must be a number"))),
533 Some(_) => Err(refused(format!("{name} must be a number"))),
534 }
535 };
536 Ok(IssueRequest {
537 issuer_did: text(obj, "issuer")?.ok_or_else(|| refused("issuer must be a DID"))?,
538 intent: obj.get("intent").cloned().unwrap_or(Value::Null),
539 now: text(obj, "now")?.ok_or_else(|| refused("now must be a protocol time"))?,
540 valid_from: text(obj, "validFrom")?,
541 valid_seconds,
542 reputation_score: whole("reputationScore")?,
543 delegation_chain: present(obj, "delegationChain").cloned(),
544 parent_credential: present(obj, "parentCredential").cloned(),
545 credential_id: text(obj, "credentialId")?,
546 credential_status: present(obj, "credentialStatus").cloned(),
547 verification_method: text(obj, "verificationMethod")?,
548 })
549}
550
551pub fn issue_json(request: &Value) -> Result<Value> {
559 let obj = request
560 .as_object()
561 .ok_or_else(|| refused("the request must be a JSON object"))?;
562 let req = issue_request_from_json(obj)?;
563 if matches!(present(obj, "prepare"), Some(Value::Bool(true))) {
564 return prepare_signing(&req);
565 }
566 let seed =
568 Zeroizing::new(b64(obj, "ed25519Seed")?.ok_or_else(|| refused("ed25519Seed is required"))?);
569 if matches!(present(obj, "postQuantum"), Some(Value::Bool(true))) {
570 let secret = Zeroizing::new(
571 b64(obj, "mldsa44SecretKey")?
572 .ok_or_else(|| refused("mldsa44SecretKey is required for postQuantum"))?,
573 );
574 let public = b64(obj, "mldsa44PublicKey")?
575 .ok_or_else(|| refused("mldsa44PublicKey is required for postQuantum"))?;
576 let kp = crate::pq::MlDsa44KeyPair::from_bytes(&secret, &public)?;
577 return issue_credential_dual(&req, &seed, &kp);
578 }
579 issue_credential(&req, &seed)
580}
581
582pub const SECRET_MEMBERS: [&str; 2] = ["ed25519Seed", "mldsa44SecretKey"];
584
585pub fn wipe_secrets(request: &mut Value) {
589 if let Some(obj) = request.as_object_mut() {
590 for name in SECRET_MEMBERS {
591 if let Some(Value::String(text)) = obj.get_mut(name) {
592 text.zeroize();
593 }
594 obj.remove(name);
595 }
596 }
597}
598
599pub fn issue_json_text(mut request: String) -> Result<Value> {
603 let parsed = serde_json::from_str::<Value>(&request);
604 request.zeroize();
605 let mut parsed = parsed.map_err(|e| refused(format!("the request is not JSON: {e}")))?;
606 let out = issue_json(&parsed);
607 wipe_secrets(&mut parsed);
608 out
609}
610
611#[cfg(test)]
612mod tests {
613 use super::*;
614
615 #[test]
616 fn formats_whole_seconds() {
617 let t = parse_protocol_time_ns("2026-04-26T10:00:00.999Z").unwrap();
618 assert_eq!(format_protocol_time(t).unwrap(), "2026-04-26T10:00:00Z");
619 let t = parse_protocol_time_ns("2000-02-29T23:59:59Z").unwrap();
620 assert_eq!(format_protocol_time(t).unwrap(), "2000-02-29T23:59:59Z");
621 let t = parse_protocol_time_ns("1969-12-31T23:59:59Z").unwrap();
622 assert_eq!(format_protocol_time(t).unwrap(), "1969-12-31T23:59:59Z");
623 }
624
625 #[test]
626 fn credential_ids_are_uuid_v4() {
627 let id = new_credential_id().unwrap();
628 assert_eq!(id.len(), "urn:uuid:".len() + 36);
629 assert_eq!(&id[23..24], "4");
630 }
631
632 #[test]
633 fn did_key_must_name_the_signing_key() {
634 let kp = crate::keys::Ed25519KeyPair::from_seed(&[1u8; 32]);
635 assert!(did_key_mismatch(&kp.did_key(), &kp.public_key()).is_none());
636 let other = crate::keys::Ed25519KeyPair::from_seed(&[2u8; 32]);
637 assert!(did_key_mismatch(&other.did_key(), &kp.public_key()).is_some());
638 assert!(did_key_mismatch("did:web:a.example", &kp.public_key()).is_none());
639 }
640}