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`).
182fn 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    // Resource first, so the long-standing refusal is unchanged.
195    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
242/// Fit a child's window inside its parent grant's: start no earlier than the
243/// grant, end no later. Returns (start ns, seconds).
244fn 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    // Whole seconds, truncated toward zero.
258    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
266/// The unsigned credential the reference builds for `req` (everything but
267/// the proof). Errors with the reference's refusal text.
268pub 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
358/// The Ed25519 verificationMethod for `req`.
359pub fn verification_method(req: &IssueRequest) -> String {
360    req.verification_method
361        .clone()
362        .unwrap_or_else(|| format!("{}#key-1", req.issuer_did))
363}
364
365/// The ML-DSA-44 verificationMethod that pairs with an Ed25519 one: the
366/// #key-2 slot of the same DID.
367pub 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
377/// The proof's `created`: the time now, in whole seconds.
378fn created(req: &IssueRequest) -> Result<String> {
379    format_protocol_time(parse_protocol_time_ns(&req.now)?)
380}
381
382/// The signer's DID must be a DID: the reference refuses an empty one, and
383/// anything that does not start "did:" and name a method.
384pub 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
405/// Issue a credential with one eddsa-jcs-2022 proof (the reference's
406/// `Signer.sign`).
407pub 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
414/// Issue a credential under the post-quantum profile (the reference's
415/// `Signer.sign_hybrid`): a proof set of two separate proofs, eddsa-jcs-2022
416/// and mldsa44-jcs-2024, over the same unsecured document, both with the same
417/// `created`. The ML-DSA-44 key's verificationMethod is the #key-2 slot of the
418/// Ed25519 one.
419pub 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
438/// The signing input of an eddsa-jcs-2022 proof for `req`, for a signer whose
439/// key lives elsewhere (a KMS or an HSM): `{"credential", "proof",
440/// "signingInput"}` where `proof` is the proof without its value and
441/// `signingInput` the 64 bytes to sign (base64). The host signs, sets
442/// `proof.proofValue` to "z" plus the base58btc signature, and attaches it.
443pub 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
460// ---------------------------------------------------------------------------
461// JSON in, JSON out (for the bindings)
462// ---------------------------------------------------------------------------
463
464const 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
506/// Read an issuance request (see [`issue_json`]).
507pub 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    // validSeconds: a whole number; anything else is refused when the
515    // credential is prepared, in the reference's order.
516    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
551/// Issue a credential from one JSON request: `{"issuer", "intent", "now",
552/// "validFrom", "validSeconds", "reputationScore", "delegationChain",
553/// "parentCredential", "credentialId", "credentialStatus",
554/// "verificationMethod", "ed25519Seed" (base64, 32 bytes), "postQuantum"
555/// (with "mldsa44SecretKey" and "mldsa44PublicKey", base64)}`. Returns the
556/// signed credential. With `"prepare": true` and no key, returns
557/// [`prepare_signing`] instead.
558pub 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    // Decoded secrets are wiped from memory when they go out of scope.
567    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
582/// The request members that carry secrets.
583pub const SECRET_MEMBERS: [&str; 2] = ["ed25519Seed", "mldsa44SecretKey"];
584
585/// Wipe the secret members of an issuance request (their text is
586/// overwritten in place, then removed), for a binding that parsed the
587/// request itself and is done with it.
588pub 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
599/// [`issue_json`] for a request the caller hands over as text: the parsed
600/// request's secrets are wiped once the credential is signed, and so is the
601/// text. Errors as [`issue_json`] does, and on text that is not JSON.
602pub 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}