Skip to main content

vouch_core/
issuance.rs

1//! Issuing a Vouch Credential, as the Python reference `vouch.signer.Signer`
2//! issues one: `sign` (one eddsa-jcs-2022 proof) and `sign_hybrid` (the
3//! post-quantum proof set of an eddsa-jcs-2022 proof and an mldsa44-jcs-2024
4//! proof, two separate proofs over the same document).
5//!
6//! The core never reads a clock or keeps a key store: the host passes the
7//! time now and the keys. Everything else is the reference's rule, including
8//! signing under a parent grant or grant chain (the delegation links, or the
9//! parent grant digest of a sub-grant, and the window clamped to the parent
10//! grant) and the refusals, in the reference's words.
11
12#[allow(unused_imports)]
13use crate::prelude::*;
14
15use serde_json::{json, Map, Value};
16
17use crate::attenuation;
18use crate::data_integrity::{self, BuildProofOptions};
19use crate::delegation;
20use crate::error::{CoreError, Result};
21use crate::grant_chain::{self, py_repr, py_repr_str};
22use crate::time::parse_protocol_time_ns;
23use zeroize::{Zeroize, Zeroizing};
24
25/// How long a credential is valid when the request does not say (the
26/// reference Signer's default, 5 minutes).
27pub const DEFAULT_VALID_SECONDS: i64 = 300;
28/// The refusal for a lifetime that is not a whole number of seconds above
29/// zero (a credential valid for no time at all is never issued).
30pub const INVALID_VALID_SECONDS: &str =
31    "valid_seconds must be a whole number of seconds greater than zero";
32/// The refusal for a signer whose DID is not a DID.
33pub const NOT_A_DID: &str = "Vouch Signer requires 'did' to be a DID (did:<method>:...)";
34/// The refusal when a parent grant has no digest.
35pub const PARENT_NOT_PLAIN_JSON: &str =
36    "Delegation refused: the parent grant is not plain JSON, so it has no digest";
37
38const NS_PER_SECOND: i128 = 1_000_000_000;
39
40/// The reference holds times as Python `datetime`s: microseconds, with
41/// digits past the sixth dropped (toward the past).
42fn to_micros(ns: i128) -> i128 {
43    ns.div_euclid(1000) * 1000
44}
45
46fn refused(msg: impl Into<String>) -> CoreError {
47    CoreError::Json(msg.into())
48}
49
50/// What one issuance needs.
51#[derive(Debug, Clone, Default)]
52pub struct IssueRequest {
53    /// The signer's DID (the issuer).
54    pub issuer_did: String,
55    /// The intent: `action`, `target` and `resource` (a grant, which names a
56    /// `delegatee`, may leave `target` out).
57    pub intent: Value,
58    /// The time now, a protocol time: the proof's `created`, and `validFrom`
59    /// when `valid_from` is not given.
60    pub now: String,
61    /// The start of the validity window (default: `now`).
62    pub valid_from: Option<String>,
63    /// How long the credential is valid, in whole seconds above zero; None is
64    /// [`DEFAULT_VALID_SECONDS`]. Zero or less is refused.
65    pub valid_seconds: Option<i64>,
66    /// A self-reported score, clamped to 0..100.
67    pub reputation_score: Option<i64>,
68    /// A pre-built delegation chain to attach (advanced).
69    pub delegation_chain: Option<Value>,
70    /// The grant this credential is signed under, naming this signer as its
71    /// delegatee: a grant (an object) or a grant chain (a list, root first).
72    pub parent_credential: Option<Value>,
73    /// The credential id; None or "" makes a fresh `urn:uuid:` id.
74    pub credential_id: Option<String>,
75    /// A W3C `credentialStatus` entry, covered by the proof.
76    pub credential_status: Option<Value>,
77    /// The Ed25519 verificationMethod (default: the issuer DID plus
78    /// "#key-1").
79    pub verification_method: Option<String>,
80}
81
82/// Render nanoseconds since the Unix epoch as `YYYY-MM-DDTHH:MM:SSZ` (whole
83/// seconds, the fraction dropped), the form the reference writes. Errors
84/// outside the years 1 to 9999.
85pub fn format_protocol_time(ns: i128) -> Result<String> {
86    let secs = ns.div_euclid(NS_PER_SECOND);
87    let days = secs.div_euclid(86_400);
88    let rem = secs.rem_euclid(86_400);
89    // Days to a civil date (proleptic Gregorian), after Howard Hinnant.
90    let z = days + 719_468;
91    let era = z.div_euclid(146_097);
92    let doe = z.rem_euclid(146_097);
93    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
94    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
95    let mp = (5 * doy + 2) / 153;
96    let day = doy - (153 * mp + 2) / 5 + 1;
97    let month = if mp < 10 { mp + 3 } else { mp - 9 };
98    let year = yoe + era * 400 + i128::from(month <= 2);
99    if !(1..=9999).contains(&year) {
100        return Err(refused("date value out of range"));
101    }
102    Ok(format!(
103        "{year:04}-{month:02}-{day:02}T{:02}:{:02}:{:02}Z",
104        rem / 3600,
105        rem % 3600 / 60,
106        rem % 60
107    ))
108}
109
110/// A fresh credential id, `urn:uuid:` and a random (version 4) UUID.
111pub fn new_credential_id() -> Result<String> {
112    let mut b = [0u8; 16];
113    crate::random::fill(&mut b).map_err(|e| CoreError::Crypto(format!("rng: {e}")))?;
114    b[6] = (b[6] & 0x0f) | 0x40;
115    b[8] = (b[8] & 0x3f) | 0x80;
116    let h: String = b.iter().map(|x| format!("{x:02x}")).collect();
117    Ok(format!(
118        "urn:uuid:{}-{}-{}-{}-{}",
119        &h[..8],
120        &h[8..12],
121        &h[12..16],
122        &h[16..20],
123        &h[20..]
124    ))
125}
126
127/// For a did:key DID, the refusal when `public_key` (raw Ed25519) is not the
128/// key the DID names; None when it is, or when the DID is not a did:key.
129pub fn did_key_mismatch(did: &str, public_key: &[u8]) -> Option<String> {
130    if !did.starts_with("did:key:") {
131        return None;
132    }
133    let own = match crate::multikey::encode_ed25519_public(public_key) {
134        Ok(mk) => format!("did:key:{mk}"),
135        Err(_) => "did:key:".to_string(),
136    };
137    (own != did)
138        .then(|| format!("{did} is the did:key of a different key; this key's did:key is {own}"))
139}
140
141/// The reference's intent rule: an object; `action` and `resource` (and
142/// `target`, unless the intent is a grant that names a delegatee) present and
143/// neither null nor ""; and `resource` a string.
144pub fn validate_intent(intent: &Value) -> Result<()> {
145    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); intent);
146    let Some(obj) = intent.as_object() else {
147        return Err(refused("intent must be a dict"));
148    };
149    let required: &[&str] = if grant_chain::is_grant_intent(intent) {
150        &["action", "resource"]
151    } else {
152        &["action", "target", "resource"]
153    };
154    for name in required {
155        match obj.get(*name) {
156            None | Some(Value::Null) => {}
157            Some(Value::String(s)) if s.is_empty() => {}
158            Some(_) => continue,
159        }
160        return Err(refused(format!(
161            "intent.{name} is REQUIRED (Specification ยง5.4.1): Vouch credentials MUST bind to \
162             a concrete resource"
163        )));
164    }
165    if !obj["resource"].is_string() {
166        return Err(refused(
167            "intent.resource must be a non-empty string naming the resource",
168        ));
169    }
170    Ok(())
171}
172
173fn truthy(v: Option<&Value>) -> bool {
174    match v {
175        None | Some(Value::Null) => false,
176        Some(Value::Bool(b)) => *b,
177        Some(Value::Number(n)) => n.as_f64().is_some_and(|f| f != 0.0),
178        Some(Value::String(s)) => !s.is_empty(),
179        Some(Value::Array(a)) => !a.is_empty(),
180        Some(Value::Object(o)) => !o.is_empty(),
181    }
182}
183
184/// Check `parent` and build the delegation links for `intent` signed under
185/// it by `signer_did` (the reference's `_extend_delegation_chain_from_parent`).
186/// The delegation links for signing `intent` under `parent` (a grant naming
187/// `signer_did` as its delegatee, or a grant chain, root first), with the
188/// reference's checks and refusals: resource narrowing, a signed parent that
189/// names this signer, a chain whose grants follow on from and are bound to
190/// each other, and the non-expansion rule.
191pub fn links_from_parent(parent: &Value, intent: &Value, signer_did: &str) -> Result<Vec<Value>> {
192    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); parent, intent);
193    let grants = grant_chain::parent_grants(parent)?;
194    let last = grants.last().expect("parent_grants is never empty");
195    let Some(parent_intent) = last
196        .get("credentialSubject")
197        .and_then(|s| s.get("intent"))
198        .filter(|i| i.is_object())
199    else {
200        return Err(refused(
201            "Delegation refused: the parent grant carries no intent object",
202        ));
203    };
204    // Resource first, so the long-standing refusal is unchanged.
205    if let (Some(Value::String(p)), Some(Value::String(c))) =
206        (parent_intent.get("resource"), intent.get("resource"))
207    {
208        if !p.is_empty() && !c.is_empty() && !attenuation::resource_within(c, p) {
209            return Err(refused(format!(
210                "Delegation violates resource-narrowing rule: child resource {} is not a \
211                 sub-resource of parent {}",
212                py_repr_str(c),
213                py_repr_str(p)
214            )));
215        }
216    }
217    if !truthy(last.get("issuer"))
218        || !matches!(last.get("proof"), Some(Value::Object(_) | Value::Array(_)))
219    {
220        return Err(refused(
221            "Delegation refused: the parent grant is not a signed credential",
222        ));
223    }
224    let delegatee = parent_intent.get("delegatee");
225    if !truthy(delegatee) {
226        return Err(refused(
227            "Delegation refused: the parent grant names no delegatee; issue it with the \
228             delegatee's DID (for example vouch.delegate(..., to=did))",
229        ));
230    }
231    if delegatee.and_then(Value::as_str) != Some(signer_did) {
232        return Err(refused(format!(
233            "Delegation refused: the parent grant names delegatee {}, not this signer {}",
234            py_repr(delegatee),
235            py_repr_str(signer_did)
236        )));
237    }
238    let links = grant_chain::check_grant_chain(&grants, intent)?;
239    let child =
240        delegation::capability_view(&json!({"credentialSubject": {"intent": intent}}), false);
241    let capability = grant_chain::chain_capability(&grants, false)?;
242    if let Err(dimension) = attenuation::non_expansion(&capability, &child) {
243        return Err(refused(format!(
244            "Delegation violates the non-expansion rule: the child is broader than the parent \
245             grant on {}",
246            py_repr_str(dimension.as_str())
247        )));
248    }
249    Ok(links)
250}
251
252/// Fit a child's window inside its parent grant's: start no earlier than the
253/// grant, end no later. Returns (start ns, seconds).
254fn clamp_to_parent(parent: &Value, start_ns: i128, valid_seconds: i64) -> Result<(i128, i64)> {
255    let bound = |k: &str| {
256        parent
257            .get(k)
258            .and_then(Value::as_str)
259            .map(|t| parse_protocol_time_ns(t).map(to_micros))
260    };
261    let (Some(Ok(from)), Some(Ok(until))) = (bound("validFrom"), bound("validUntil")) else {
262        return Err(refused(
263            "Delegation refused: the parent grant has no validity window",
264        ));
265    };
266    let start = start_ns.max(from);
267    // Whole seconds, truncated toward zero.
268    let remaining = (until - start) / NS_PER_SECOND;
269    if remaining <= 0 {
270        return Err(refused("Delegation refused: the parent grant has expired"));
271    }
272    let remaining = i64::try_from(remaining).unwrap_or(i64::MAX);
273    Ok((start, valid_seconds.min(remaining)))
274}
275
276/// The unsigned credential the reference builds for `req` (everything but
277/// the proof). Errors with the reference's refusal text.
278pub fn prepare_credential(req: &IssueRequest) -> Result<Value> {
279    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); req);
280    check_issuer(&req.issuer_did)?;
281    let now = to_micros(parse_protocol_time_ns(&req.now)?);
282    let mut valid_seconds = match req.valid_seconds {
283        None => DEFAULT_VALID_SECONDS,
284        Some(s) if s > 0 => s,
285        Some(_) => return Err(refused(INVALID_VALID_SECONDS)),
286    };
287    let mut start = match &req.valid_from {
288        Some(t) => to_micros(parse_protocol_time_ns(t)?),
289        None => now,
290    };
291    let mut chain = req.delegation_chain.clone();
292    let mut parent_digest: Option<String> = None;
293    if let Some(parent) = &req.parent_credential {
294        if !req.intent.is_object() {
295            return Err(refused("intent must be a dict"));
296        }
297        let links = links_from_parent(parent, &req.intent, &req.issuer_did)?;
298        let direct = &links[links.len() - 1]["parentCredential"];
299        (start, valid_seconds) = clamp_to_parent(direct, start, valid_seconds)?;
300        if grant_chain::is_grant_intent(&req.intent) {
301            parent_digest = Some(
302                grant_chain::grant_digest(direct).map_err(|_| refused(PARENT_NOT_PLAIN_JSON))?,
303            );
304            chain = None;
305        } else {
306            chain = Some(Value::Array(links));
307        }
308    }
309
310    validate_intent(&req.intent)?;
311    let chain = chain.filter(truthy_chain);
312    if parent_digest.is_some() && chain.is_some() {
313        return Err(refused(
314            "a credential carries parentGrantDigest or a delegationChain, never both",
315        ));
316    }
317    let until = start + i128::from(valid_seconds) * NS_PER_SECOND;
318
319    let mut subject = Map::new();
320    subject.insert("id".into(), json!(req.issuer_did));
321    subject.insert(
322        "vouchVersion".into(),
323        json!(crate::credentials::PROTOCOL_VERSION),
324    );
325    subject.insert("intent".into(), req.intent.clone());
326    if let Some(score) = req.reputation_score {
327        subject.insert("reputationScore".into(), json!(score.clamp(0, 100)));
328    }
329    if let Some(digest) = parent_digest {
330        subject.insert(grant_chain::PARENT_GRANT_DIGEST.into(), json!(digest));
331    }
332    if let Some(chain) = chain {
333        subject.insert("delegationChain".into(), chain);
334    }
335    let id = match req.credential_id.as_deref() {
336        Some(id) if !id.is_empty() => id.to_string(),
337        _ => new_credential_id()?,
338    };
339    let mut vc = Map::new();
340    vc.insert(
341        "@context".into(),
342        json!([
343            crate::credentials::VC_CONTEXT_V2,
344            crate::credentials::VOUCH_CONTEXT_V1
345        ]),
346    );
347    vc.insert("id".into(), json!(id));
348    vc.insert(
349        "type".into(),
350        json!([
351            crate::credentials::VC_TYPE,
352            crate::credentials::VOUCH_CREDENTIAL_TYPE
353        ]),
354    );
355    vc.insert("issuer".into(), json!(req.issuer_did));
356    vc.insert("validFrom".into(), json!(format_protocol_time(start)?));
357    vc.insert("validUntil".into(), json!(format_protocol_time(until)?));
358    vc.insert("credentialSubject".into(), Value::Object(subject));
359    if let Some(status) = &req.credential_status {
360        vc.insert("credentialStatus".into(), status.clone());
361    }
362    Ok(Value::Object(vc))
363}
364
365fn truthy_chain(v: &Value) -> bool {
366    truthy(Some(v))
367}
368
369/// The Ed25519 verificationMethod for `req`.
370pub fn verification_method(req: &IssueRequest) -> String {
371    crate::nesting::deep_guard!(String::new(); req);
372    req.verification_method
373        .clone()
374        .unwrap_or_else(|| format!("{}#key-1", req.issuer_did))
375}
376
377/// The verificationMethod at another key slot of the DID an Ed25519
378/// verificationMethod belongs to.
379fn slot_verification_method(ed25519_method: &str, slot: &str) -> String {
380    match ed25519_method.strip_suffix("#key-1") {
381        Some(base) => format!("{base}#{slot}"),
382        None => match ed25519_method.split_once('#') {
383            Some((base, _)) => format!("{base}#{slot}"),
384            None => format!("{ed25519_method}#{slot}"),
385        },
386    }
387}
388
389/// The ML-DSA-44 verificationMethod that pairs with an Ed25519 one: the
390/// #key-2 slot of the same DID.
391pub fn mldsa44_verification_method(ed25519_method: &str) -> String {
392    slot_verification_method(ed25519_method, "key-2")
393}
394
395/// The SLH-DSA-SHA2-128s verificationMethod that pairs with an Ed25519 one:
396/// the #key-3 slot of the same DID.
397pub fn slhdsa128_verification_method(ed25519_method: &str) -> String {
398    slot_verification_method(ed25519_method, "key-3")
399}
400
401/// The proof's `created`: the time now, in whole seconds.
402fn created(req: &IssueRequest) -> Result<String> {
403    format_protocol_time(parse_protocol_time_ns(&req.now)?)
404}
405
406/// The signer's DID must be a DID: the reference refuses an empty one, and
407/// anything that does not start "did:" and name a method.
408pub fn check_issuer(did: &str) -> Result<()> {
409    if did.is_empty() {
410        return Err(refused(
411            "Vouch Signer requires 'did' (Decentralized Identifier)",
412        ));
413    }
414    if !(did.starts_with("did:") && did.len() > 4) {
415        return Err(refused(NOT_A_DID));
416    }
417    Ok(())
418}
419
420fn check_signer(req: &IssueRequest, ed25519_seed: &[u8]) -> Result<()> {
421    check_issuer(&req.issuer_did)?;
422    let kp = crate::keys::Ed25519KeyPair::from_seed_slice(ed25519_seed)?;
423    match did_key_mismatch(&req.issuer_did, &kp.public_key()) {
424        Some(problem) => Err(refused(problem)),
425        None => Ok(()),
426    }
427}
428
429/// Issue a credential with one eddsa-jcs-2022 proof (the reference's
430/// `Signer.sign`).
431pub fn issue_credential(req: &IssueRequest, ed25519_seed: &[u8]) -> Result<Value> {
432    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); req);
433    check_signer(req, ed25519_seed)?;
434    let unsigned = prepare_credential(req)?;
435    let opts = BuildProofOptions::new(verification_method(req), created(req)?);
436    data_integrity::sign(&unsigned, ed25519_seed, &opts)
437}
438
439/// Issue a credential under the post-quantum profile (the reference's
440/// `Signer.sign_hybrid`): a proof set of two separate proofs, eddsa-jcs-2022
441/// and mldsa44-jcs-2024, over the same unsecured document, both with the same
442/// `created`. The ML-DSA-44 key's verificationMethod is the #key-2 slot of the
443/// Ed25519 one.
444pub fn issue_credential_dual(
445    req: &IssueRequest,
446    ed25519_seed: &[u8],
447    mldsa44: &crate::pq::MlDsa44KeyPair,
448) -> Result<Value> {
449    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); req);
450    issue_credential_set(req, ed25519_seed, Some(mldsa44), None)
451}
452
453/// Issue a credential with a proof set: the eddsa-jcs-2022 proof, then a
454/// proof for each post-quantum key given (mldsa44-jcs-2024, then
455/// slhdsa128-jcs-2024), all over the same unsecured document with the same
456/// `created`. The ML-DSA-44 key's verificationMethod is the #key-2 slot of
457/// the Ed25519 one, the SLH-DSA key's the #key-3 slot. At least one
458/// post-quantum key is required.
459pub fn issue_credential_set(
460    req: &IssueRequest,
461    ed25519_seed: &[u8],
462    mldsa44: Option<&crate::pq::MlDsa44KeyPair>,
463    slhdsa128: Option<&crate::slh::SlhDsa128KeyPair>,
464) -> Result<Value> {
465    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); req);
466    check_signer(req, ed25519_seed)?;
467    let unsigned = prepare_credential(req)?;
468    let ed_vm = verification_method(req);
469    let ml_vm = mldsa44_verification_method(&ed_vm);
470    let slh_vm = slhdsa128_verification_method(&ed_vm);
471    crate::hybrid::sign_set(
472        &unsigned,
473        ed25519_seed,
474        &ed_vm,
475        mldsa44.map(|key| crate::hybrid::PqSigner {
476            key,
477            verification_method: &ml_vm,
478        }),
479        slhdsa128.map(|key| crate::hybrid::PqSigner {
480            key,
481            verification_method: &slh_vm,
482        }),
483        &created(req)?,
484    )
485}
486
487/// The signing input of an eddsa-jcs-2022 proof for `req`, for a signer whose
488/// key lives elsewhere (a KMS or an HSM): `{"credential", "proof",
489/// "signingInput"}` where `proof` is the proof without its value and
490/// `signingInput` the 64 bytes to sign (base64). The host signs, sets
491/// `proof.proofValue` to "z" plus the base58btc signature, and attaches it.
492pub fn prepare_signing(req: &IssueRequest) -> Result<Value> {
493    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); req);
494    use base64::{engine::general_purpose::STANDARD, Engine};
495    let unsigned = prepare_credential(req)?;
496    let mut proof = Map::new();
497    proof.insert("type".into(), json!(data_integrity::PROOF_TYPE));
498    proof.insert("cryptosuite".into(), json!(data_integrity::CRYPTOSUITE_ID));
499    proof.insert("created".into(), json!(created(req)?));
500    proof.insert("verificationMethod".into(), json!(verification_method(req)));
501    proof.insert("proofPurpose".into(), json!("assertionMethod"));
502    let input = data_integrity::hash_data(&unsigned, &proof)?;
503    Ok(json!({
504        "credential": unsigned,
505        "proof": Value::Object(proof),
506        "signingInput": STANDARD.encode(input),
507    }))
508}
509
510// ---------------------------------------------------------------------------
511// JSON in, JSON out (for the bindings)
512// ---------------------------------------------------------------------------
513
514const REQUEST_MEMBERS: [&str; 17] = [
515    "issuer",
516    "intent",
517    "now",
518    "validFrom",
519    "validSeconds",
520    "reputationScore",
521    "delegationChain",
522    "parentCredential",
523    "credentialId",
524    "credentialStatus",
525    "verificationMethod",
526    "ed25519Seed",
527    "postQuantum",
528    "mldsa44SecretKey",
529    "mldsa44PublicKey",
530    "slhdsa128SecretKey",
531    "prepare",
532];
533
534fn present<'a>(obj: &'a Map<String, Value>, name: &str) -> Option<&'a Value> {
535    obj.get(name).filter(|v| !v.is_null())
536}
537
538fn text(obj: &Map<String, Value>, name: &str) -> Result<Option<String>> {
539    match present(obj, name) {
540        None => Ok(None),
541        Some(Value::String(s)) => Ok(Some(s.clone())),
542        Some(_) => Err(refused(format!("{name} must be a string"))),
543    }
544}
545
546fn b64(obj: &Map<String, Value>, name: &str) -> Result<Option<Vec<u8>>> {
547    use base64::{engine::general_purpose::STANDARD, Engine};
548    text(obj, name)?
549        .map(|s| {
550            STANDARD
551                .decode(s)
552                .map_err(|_| refused(format!("{name} must be standard base64")))
553        })
554        .transpose()
555}
556
557/// Read an issuance request (see [`issue_json`]).
558pub fn issue_request_from_json(obj: &Map<String, Value>) -> Result<IssueRequest> {
559    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); obj);
560    if let Some(name) = obj.keys().find(|k| !REQUEST_MEMBERS.contains(&k.as_str())) {
561        return Err(refused(format!(
562            "the request holds an unknown member {:?}",
563            name.chars().take(40).collect::<String>()
564        )));
565    }
566    // validSeconds: a whole number; anything else is refused when the
567    // credential is prepared, in the reference's order.
568    let valid_seconds = match present(obj, "validSeconds") {
569        None => None,
570        Some(Value::Number(n)) if n.is_i64() => n.as_i64(),
571        Some(_) => Some(i64::MIN),
572    };
573    let whole = |name: &str| -> Result<Option<i64>> {
574        match present(obj, name) {
575            None => Ok(None),
576            Some(Value::Number(n)) => n
577                .as_i64()
578                .or_else(|| {
579                    n.as_f64()
580                        .filter(|f| f.is_finite())
581                        .map(|f| crate::float::trunc(f) as i64)
582                })
583                .map(Some)
584                .ok_or_else(|| refused(format!("{name} must be a number"))),
585            Some(_) => Err(refused(format!("{name} must be a number"))),
586        }
587    };
588    Ok(IssueRequest {
589        issuer_did: text(obj, "issuer")?.ok_or_else(|| refused("issuer must be a DID"))?,
590        intent: obj.get("intent").cloned().unwrap_or(Value::Null),
591        now: text(obj, "now")?.ok_or_else(|| refused("now must be a protocol time"))?,
592        valid_from: text(obj, "validFrom")?,
593        valid_seconds,
594        reputation_score: whole("reputationScore")?,
595        delegation_chain: present(obj, "delegationChain").cloned(),
596        parent_credential: present(obj, "parentCredential").cloned(),
597        credential_id: text(obj, "credentialId")?,
598        credential_status: present(obj, "credentialStatus").cloned(),
599        verification_method: text(obj, "verificationMethod")?,
600    })
601}
602
603/// Issue a credential from one JSON request: `{"issuer", "intent", "now",
604/// "validFrom", "validSeconds", "reputationScore", "delegationChain",
605/// "parentCredential", "credentialId", "credentialStatus",
606/// "verificationMethod", "ed25519Seed" (base64, 32 bytes), "postQuantum"
607/// (with "mldsa44SecretKey" and "mldsa44PublicKey", and/or
608/// "slhdsa128SecretKey", base64)}`. With `postQuantum` the credential
609/// carries a proof set: the Ed25519 proof and one proof for each
610/// post-quantum key given (an SLH-DSA key alone is enough). Returns the
611/// signed credential. With `"prepare": true` and no key, returns
612/// [`prepare_signing`] instead.
613pub fn issue_json(request: &Value) -> Result<Value> {
614    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); request);
615    let obj = request
616        .as_object()
617        .ok_or_else(|| refused("the request must be a JSON object"))?;
618    let req = issue_request_from_json(obj)?;
619    if matches!(present(obj, "prepare"), Some(Value::Bool(true))) {
620        return prepare_signing(&req);
621    }
622    // Decoded secrets are wiped from memory when they go out of scope.
623    let seed =
624        Zeroizing::new(b64(obj, "ed25519Seed")?.ok_or_else(|| refused("ed25519Seed is required"))?);
625    if matches!(present(obj, "postQuantum"), Some(Value::Bool(true))) {
626        let slhdsa = match b64(obj, "slhdsa128SecretKey")?.map(Zeroizing::new) {
627            Some(secret) => Some(crate::slh::SlhDsa128KeyPair::from_secret(&secret)?),
628            None => None,
629        };
630        // The ML-DSA-44 key is required unless an SLH-DSA key is given and
631        // no ML-DSA-44 member is.
632        let wants_mldsa = slhdsa.is_none()
633            || present(obj, "mldsa44SecretKey").is_some()
634            || present(obj, "mldsa44PublicKey").is_some();
635        let mldsa = if wants_mldsa {
636            let secret = Zeroizing::new(
637                b64(obj, "mldsa44SecretKey")?
638                    .ok_or_else(|| refused("mldsa44SecretKey is required for postQuantum"))?,
639            );
640            let public = b64(obj, "mldsa44PublicKey")?
641                .ok_or_else(|| refused("mldsa44PublicKey is required for postQuantum"))?;
642            Some(crate::pq::MlDsa44KeyPair::from_bytes(&secret, &public)?)
643        } else {
644            None
645        };
646        return issue_credential_set(&req, &seed, mldsa.as_ref(), slhdsa.as_ref());
647    }
648    issue_credential(&req, &seed)
649}
650
651/// The request members that carry secrets.
652pub const SECRET_MEMBERS: [&str; 3] = ["ed25519Seed", "mldsa44SecretKey", "slhdsa128SecretKey"];
653
654/// Wipe the secret members of an issuance request (their text is
655/// overwritten in place, then removed), for a binding that parsed the
656/// request itself and is done with it.
657pub fn wipe_secrets(request: &mut Value) {
658    if let Some(obj) = request.as_object_mut() {
659        for name in SECRET_MEMBERS {
660            if let Some(Value::String(text)) = obj.get_mut(name) {
661                text.zeroize();
662            }
663            obj.remove(name);
664        }
665    }
666}
667
668/// [`issue_json`] for a request the caller hands over as text: the parsed
669/// request's secrets are wiped once the credential is signed, and so is the
670/// text. Errors as [`issue_json`] does, and on text that is not JSON.
671pub fn issue_json_text(mut request: String) -> Result<Value> {
672    if let Err(e) = crate::nesting::check_text(request.as_bytes()) {
673        request.zeroize();
674        return Err(e);
675    }
676    let parsed = serde_json::from_str::<Value>(&request);
677    request.zeroize();
678    let mut parsed = parsed.map_err(|e| refused(format!("the request is not JSON: {e}")))?;
679    let out = issue_json(&parsed);
680    wipe_secrets(&mut parsed);
681    out
682}
683
684/// [`links_from_parent`] as JSON: `{"parentCredential", "intent",
685/// "signerDid"}` to the list of links.
686pub fn delegation_links_json(request: &Value) -> Result<Value> {
687    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); request);
688    let obj = request
689        .as_object()
690        .ok_or_else(|| refused("the request must be a JSON object"))?;
691    let parent = obj.get("parentCredential").unwrap_or(&Value::Null);
692    let intent = obj.get("intent").unwrap_or(&Value::Null);
693    let signer = text(obj, "signerDid")?.unwrap_or_default();
694    Ok(Value::Array(links_from_parent(parent, intent, &signer)?))
695}
696
697// What the no_std depth guard checks in the JSON these types carry.
698crate::nesting::nested_fields!(IssueRequest; intent, delegation_chain, parent_credential, credential_status);
699
700#[cfg(test)]
701mod tests {
702    use super::*;
703
704    #[test]
705    fn formats_whole_seconds() {
706        let t = parse_protocol_time_ns("2026-04-26T10:00:00.999Z").unwrap();
707        assert_eq!(format_protocol_time(t).unwrap(), "2026-04-26T10:00:00Z");
708        let t = parse_protocol_time_ns("2000-02-29T23:59:59Z").unwrap();
709        assert_eq!(format_protocol_time(t).unwrap(), "2000-02-29T23:59:59Z");
710        let t = parse_protocol_time_ns("1969-12-31T23:59:59Z").unwrap();
711        assert_eq!(format_protocol_time(t).unwrap(), "1969-12-31T23:59:59Z");
712    }
713
714    #[test]
715    #[cfg_attr(not(feature = "std"), ignore = "needs a random source (std)")]
716    fn credential_ids_are_uuid_v4() {
717        let id = new_credential_id().unwrap();
718        assert_eq!(id.len(), "urn:uuid:".len() + 36);
719        assert_eq!(&id[23..24], "4");
720    }
721
722    #[test]
723    fn did_key_must_name_the_signing_key() {
724        let kp = crate::keys::Ed25519KeyPair::from_seed(&[1u8; 32]);
725        assert!(did_key_mismatch(&kp.did_key(), &kp.public_key()).is_none());
726        let other = crate::keys::Ed25519KeyPair::from_seed(&[2u8; 32]);
727        assert!(did_key_mismatch(&other.did_key(), &kp.public_key()).is_some());
728        assert!(did_key_mismatch("did:web:a.example", &kp.public_key()).is_none());
729    }
730}