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
12use 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
22/// How long a credential is valid when the request does not say (the
23/// reference Signer's default, 5 minutes).
24pub const DEFAULT_VALID_SECONDS: i64 = 300;
25/// The refusal for a lifetime that is not a whole number of seconds above
26/// zero (a credential valid for no time at all is never issued).
27pub const INVALID_VALID_SECONDS: &str =
28    "valid_seconds must be a whole number of seconds greater than zero";
29/// The refusal for a signer whose DID is not a DID.
30pub const NOT_A_DID: &str = "Vouch Signer requires 'did' to be a DID (did:<method>:...)";
31/// The refusal when a parent grant has no digest.
32pub 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
37/// The reference holds times as Python `datetime`s: microseconds, with
38/// digits past the sixth dropped (toward the past).
39fn 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/// What one issuance needs.
48#[derive(Debug, Clone, Default)]
49pub struct IssueRequest {
50    /// The signer's DID (the issuer).
51    pub issuer_did: String,
52    /// The intent: `action`, `target` and `resource` (a grant, which names a
53    /// `delegatee`, may leave `target` out).
54    pub intent: Value,
55    /// The time now, a protocol time: the proof's `created`, and `validFrom`
56    /// when `valid_from` is not given.
57    pub now: String,
58    /// The start of the validity window (default: `now`).
59    pub valid_from: Option<String>,
60    /// How long the credential is valid, in whole seconds above zero; None is
61    /// [`DEFAULT_VALID_SECONDS`]. Zero or less is refused.
62    pub valid_seconds: Option<i64>,
63    /// A self-reported score, clamped to 0..100.
64    pub reputation_score: Option<i64>,
65    /// A pre-built delegation chain to attach (advanced).
66    pub delegation_chain: Option<Value>,
67    /// The grant this credential is signed under, naming this signer as its
68    /// delegatee: a grant (an object) or a grant chain (a list, root first).
69    pub parent_credential: Option<Value>,
70    /// The credential id; None or "" makes a fresh `urn:uuid:` id.
71    pub credential_id: Option<String>,
72    /// A W3C `credentialStatus` entry, covered by the proof.
73    pub credential_status: Option<Value>,
74    /// The Ed25519 verificationMethod (default: the issuer DID plus
75    /// "#key-1").
76    pub verification_method: Option<String>,
77}
78
79/// Render nanoseconds since the Unix epoch as `YYYY-MM-DDTHH:MM:SSZ` (whole
80/// seconds, the fraction dropped), the form the reference writes. Errors
81/// outside the years 1 to 9999.
82pub 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    // Days to a civil date (proleptic Gregorian), after Howard Hinnant.
87    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
107/// A fresh credential id, `urn:uuid:` and a random (version 4) UUID.
108pub 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
124/// For a did:key DID, the refusal when `public_key` (raw Ed25519) is not the
125/// key the DID names; None when it is, or when the DID is not a did:key.
126pub 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
138/// The reference's intent rule: an object; `action` and `resource` (and
139/// `target`, unless the intent is a grant that names a delegatee) present and
140/// neither null nor ""; and `resource` a string.
141pub 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
180/// Check `parent` and build the delegation links for `intent` signed under
181/// it by `signer_did` (the reference's `_extend_delegation_chain_from_parent`).
182/// The delegation links for signing `intent` under `parent` (a grant naming
183/// `signer_did` as its delegatee, or a grant chain, root first), with the
184/// reference's checks and refusals: resource narrowing, a signed parent that
185/// names this signer, a chain whose grants follow on from and are bound to
186/// each other, and the non-expansion rule.
187pub 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    // Resource first, so the long-standing refusal is unchanged.
200    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
247/// Fit a child's window inside its parent grant's: start no earlier than the
248/// grant, end no later. Returns (start ns, seconds).
249fn 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    // Whole seconds, truncated toward zero.
263    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
271/// The unsigned credential the reference builds for `req` (everything but
272/// the proof). Errors with the reference's refusal text.
273pub 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
363/// The Ed25519 verificationMethod for `req`.
364pub fn verification_method(req: &IssueRequest) -> String {
365    req.verification_method
366        .clone()
367        .unwrap_or_else(|| format!("{}#key-1", req.issuer_did))
368}
369
370/// The verificationMethod at another key slot of the DID an Ed25519
371/// verificationMethod belongs to.
372fn 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
382/// The ML-DSA-44 verificationMethod that pairs with an Ed25519 one: the
383/// #key-2 slot of the same DID.
384pub fn mldsa44_verification_method(ed25519_method: &str) -> String {
385    slot_verification_method(ed25519_method, "key-2")
386}
387
388/// The SLH-DSA-SHA2-128s verificationMethod that pairs with an Ed25519 one:
389/// the #key-3 slot of the same DID.
390pub fn slhdsa128_verification_method(ed25519_method: &str) -> String {
391    slot_verification_method(ed25519_method, "key-3")
392}
393
394/// The proof's `created`: the time now, in whole seconds.
395fn created(req: &IssueRequest) -> Result<String> {
396    format_protocol_time(parse_protocol_time_ns(&req.now)?)
397}
398
399/// The signer's DID must be a DID: the reference refuses an empty one, and
400/// anything that does not start "did:" and name a method.
401pub 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
422/// Issue a credential with one eddsa-jcs-2022 proof (the reference's
423/// `Signer.sign`).
424pub 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
431/// Issue a credential under the post-quantum profile (the reference's
432/// `Signer.sign_hybrid`): a proof set of two separate proofs, eddsa-jcs-2022
433/// and mldsa44-jcs-2024, over the same unsecured document, both with the same
434/// `created`. The ML-DSA-44 key's verificationMethod is the #key-2 slot of the
435/// Ed25519 one.
436pub 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
444/// Issue a credential with a proof set: the eddsa-jcs-2022 proof, then a
445/// proof for each post-quantum key given (mldsa44-jcs-2024, then
446/// slhdsa128-jcs-2024), all over the same unsecured document with the same
447/// `created`. The ML-DSA-44 key's verificationMethod is the #key-2 slot of
448/// the Ed25519 one, the SLH-DSA key's the #key-3 slot. At least one
449/// post-quantum key is required.
450pub 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
477/// The signing input of an eddsa-jcs-2022 proof for `req`, for a signer whose
478/// key lives elsewhere (a KMS or an HSM): `{"credential", "proof",
479/// "signingInput"}` where `proof` is the proof without its value and
480/// `signingInput` the 64 bytes to sign (base64). The host signs, sets
481/// `proof.proofValue` to "z" plus the base58btc signature, and attaches it.
482pub 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
499// ---------------------------------------------------------------------------
500// JSON in, JSON out (for the bindings)
501// ---------------------------------------------------------------------------
502
503const 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
546/// Read an issuance request (see [`issue_json`]).
547pub 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    // validSeconds: a whole number; anything else is refused when the
555    // credential is prepared, in the reference's order.
556    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
591/// Issue a credential from one JSON request: `{"issuer", "intent", "now",
592/// "validFrom", "validSeconds", "reputationScore", "delegationChain",
593/// "parentCredential", "credentialId", "credentialStatus",
594/// "verificationMethod", "ed25519Seed" (base64, 32 bytes), "postQuantum"
595/// (with "mldsa44SecretKey" and "mldsa44PublicKey", and/or
596/// "slhdsa128SecretKey", base64)}`. With `postQuantum` the credential
597/// carries a proof set: the Ed25519 proof and one proof for each
598/// post-quantum key given (an SLH-DSA key alone is enough). Returns the
599/// signed credential. With `"prepare": true` and no key, returns
600/// [`prepare_signing`] instead.
601pub 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    // Decoded secrets are wiped from memory when they go out of scope.
610    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        // The ML-DSA-44 key is required unless an SLH-DSA key is given and
618        // no ML-DSA-44 member is.
619        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
638/// The request members that carry secrets.
639pub const SECRET_MEMBERS: [&str; 3] = ["ed25519Seed", "mldsa44SecretKey", "slhdsa128SecretKey"];
640
641/// Wipe the secret members of an issuance request (their text is
642/// overwritten in place, then removed), for a binding that parsed the
643/// request itself and is done with it.
644pub 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
655/// [`issue_json`] for a request the caller hands over as text: the parsed
656/// request's secrets are wiped once the credential is signed, and so is the
657/// text. Errors as [`issue_json`] does, and on text that is not JSON.
658pub 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
667/// [`links_from_parent`] as JSON: `{"parentCredential", "intent",
668/// "signerDid"}` to the list of links.
669pub 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}