vouch-core 4.2.0

Vouch Protocol canonical core: JCS canonicalization, Ed25519 + ML-DSA proofs, did:key/multikey, Data Integrity (eddsa-jcs-2022), credentials, delegation, revocation. One byte-exact implementation shared by every language SDK via WASM and UniFFI/C-FFI.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
//! Issuing a Vouch Credential, as the Python reference `vouch.signer.Signer`
//! issues one: `sign` (one eddsa-jcs-2022 proof) and `sign_hybrid` (the
//! post-quantum proof set of an eddsa-jcs-2022 proof and an mldsa44-jcs-2024
//! proof, two separate proofs over the same document).
//!
//! The core never reads a clock or keeps a key store: the host passes the
//! time now and the keys. Everything else is the reference's rule, including
//! signing under a parent grant or grant chain (the delegation links, or the
//! parent grant digest of a sub-grant, and the window clamped to the parent
//! grant) and the refusals, in the reference's words.

#[allow(unused_imports)]
use crate::prelude::*;

use serde_json::{json, Map, Value};

use crate::attenuation;
use crate::data_integrity::{self, BuildProofOptions};
use crate::delegation;
use crate::error::{CoreError, Result};
use crate::grant_chain::{self, py_repr, py_repr_str};
use crate::time::parse_protocol_time_ns;
use zeroize::{Zeroize, Zeroizing};

/// How long a credential is valid when the request does not say (the
/// reference Signer's default, 5 minutes).
pub const DEFAULT_VALID_SECONDS: i64 = 300;
/// The refusal for a lifetime that is not a whole number of seconds above
/// zero (a credential valid for no time at all is never issued).
pub const INVALID_VALID_SECONDS: &str =
    "valid_seconds must be a whole number of seconds greater than zero";
/// The refusal for a signer whose DID is not a DID.
pub const NOT_A_DID: &str = "Vouch Signer requires 'did' to be a DID (did:<method>:...)";
/// The refusal when a parent grant has no digest.
pub const PARENT_NOT_PLAIN_JSON: &str =
    "Delegation refused: the parent grant is not plain JSON, so it has no digest";

const NS_PER_SECOND: i128 = 1_000_000_000;

/// The reference holds times as Python `datetime`s: microseconds, with
/// digits past the sixth dropped (toward the past).
fn to_micros(ns: i128) -> i128 {
    ns.div_euclid(1000) * 1000
}

fn refused(msg: impl Into<String>) -> CoreError {
    CoreError::Json(msg.into())
}

/// What one issuance needs.
#[derive(Debug, Clone, Default)]
pub struct IssueRequest {
    /// The signer's DID (the issuer).
    pub issuer_did: String,
    /// The intent: `action`, `target` and `resource` (a grant, which names a
    /// `delegatee`, may leave `target` out).
    pub intent: Value,
    /// The time now, a protocol time: the proof's `created`, and `validFrom`
    /// when `valid_from` is not given.
    pub now: String,
    /// The start of the validity window (default: `now`).
    pub valid_from: Option<String>,
    /// How long the credential is valid, in whole seconds above zero; None is
    /// [`DEFAULT_VALID_SECONDS`]. Zero or less is refused.
    pub valid_seconds: Option<i64>,
    /// A self-reported score, clamped to 0..100.
    pub reputation_score: Option<i64>,
    /// A pre-built delegation chain to attach (advanced).
    pub delegation_chain: Option<Value>,
    /// The grant this credential is signed under, naming this signer as its
    /// delegatee: a grant (an object) or a grant chain (a list, root first).
    pub parent_credential: Option<Value>,
    /// The credential id; None or "" makes a fresh `urn:uuid:` id.
    pub credential_id: Option<String>,
    /// A W3C `credentialStatus` entry, covered by the proof.
    pub credential_status: Option<Value>,
    /// The Ed25519 verificationMethod (default: the issuer DID plus
    /// "#key-1").
    pub verification_method: Option<String>,
}

/// Render nanoseconds since the Unix epoch as `YYYY-MM-DDTHH:MM:SSZ` (whole
/// seconds, the fraction dropped), the form the reference writes. Errors
/// outside the years 1 to 9999.
pub fn format_protocol_time(ns: i128) -> Result<String> {
    let secs = ns.div_euclid(NS_PER_SECOND);
    let days = secs.div_euclid(86_400);
    let rem = secs.rem_euclid(86_400);
    // Days to a civil date (proleptic Gregorian), after Howard Hinnant.
    let z = days + 719_468;
    let era = z.div_euclid(146_097);
    let doe = z.rem_euclid(146_097);
    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    let mp = (5 * doy + 2) / 153;
    let day = doy - (153 * mp + 2) / 5 + 1;
    let month = if mp < 10 { mp + 3 } else { mp - 9 };
    let year = yoe + era * 400 + i128::from(month <= 2);
    if !(1..=9999).contains(&year) {
        return Err(refused("date value out of range"));
    }
    Ok(format!(
        "{year:04}-{month:02}-{day:02}T{:02}:{:02}:{:02}Z",
        rem / 3600,
        rem % 3600 / 60,
        rem % 60
    ))
}

/// A fresh credential id, `urn:uuid:` and a random (version 4) UUID.
pub fn new_credential_id() -> Result<String> {
    let mut b = [0u8; 16];
    crate::random::fill(&mut b).map_err(|e| CoreError::Crypto(format!("rng: {e}")))?;
    b[6] = (b[6] & 0x0f) | 0x40;
    b[8] = (b[8] & 0x3f) | 0x80;
    let h: String = b.iter().map(|x| format!("{x:02x}")).collect();
    Ok(format!(
        "urn:uuid:{}-{}-{}-{}-{}",
        &h[..8],
        &h[8..12],
        &h[12..16],
        &h[16..20],
        &h[20..]
    ))
}

/// For a did:key DID, the refusal when `public_key` (raw Ed25519) is not the
/// key the DID names; None when it is, or when the DID is not a did:key.
pub fn did_key_mismatch(did: &str, public_key: &[u8]) -> Option<String> {
    if !did.starts_with("did:key:") {
        return None;
    }
    let own = match crate::multikey::encode_ed25519_public(public_key) {
        Ok(mk) => format!("did:key:{mk}"),
        Err(_) => "did:key:".to_string(),
    };
    (own != did)
        .then(|| format!("{did} is the did:key of a different key; this key's did:key is {own}"))
}

/// The reference's intent rule: an object; `action` and `resource` (and
/// `target`, unless the intent is a grant that names a delegatee) present and
/// neither null nor ""; and `resource` a string.
pub fn validate_intent(intent: &Value) -> Result<()> {
    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); intent);
    let Some(obj) = intent.as_object() else {
        return Err(refused("intent must be a dict"));
    };
    let required: &[&str] = if grant_chain::is_grant_intent(intent) {
        &["action", "resource"]
    } else {
        &["action", "target", "resource"]
    };
    for name in required {
        match obj.get(*name) {
            None | Some(Value::Null) => {}
            Some(Value::String(s)) if s.is_empty() => {}
            Some(_) => continue,
        }
        return Err(refused(format!(
            "intent.{name} is REQUIRED (Specification §5.4.1): Vouch credentials MUST bind to \
             a concrete resource"
        )));
    }
    if !obj["resource"].is_string() {
        return Err(refused(
            "intent.resource must be a non-empty string naming the resource",
        ));
    }
    Ok(())
}

fn truthy(v: Option<&Value>) -> bool {
    match v {
        None | Some(Value::Null) => false,
        Some(Value::Bool(b)) => *b,
        Some(Value::Number(n)) => n.as_f64().is_some_and(|f| f != 0.0),
        Some(Value::String(s)) => !s.is_empty(),
        Some(Value::Array(a)) => !a.is_empty(),
        Some(Value::Object(o)) => !o.is_empty(),
    }
}

/// Check `parent` and build the delegation links for `intent` signed under
/// it by `signer_did` (the reference's `_extend_delegation_chain_from_parent`).
/// The delegation links for signing `intent` under `parent` (a grant naming
/// `signer_did` as its delegatee, or a grant chain, root first), with the
/// reference's checks and refusals: resource narrowing, a signed parent that
/// names this signer, a chain whose grants follow on from and are bound to
/// each other, and the non-expansion rule.
pub fn links_from_parent(parent: &Value, intent: &Value, signer_did: &str) -> Result<Vec<Value>> {
    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); parent, intent);
    let grants = grant_chain::parent_grants(parent)?;
    let last = grants.last().expect("parent_grants is never empty");
    let Some(parent_intent) = last
        .get("credentialSubject")
        .and_then(|s| s.get("intent"))
        .filter(|i| i.is_object())
    else {
        return Err(refused(
            "Delegation refused: the parent grant carries no intent object",
        ));
    };
    // Resource first, so the long-standing refusal is unchanged.
    if let (Some(Value::String(p)), Some(Value::String(c))) =
        (parent_intent.get("resource"), intent.get("resource"))
    {
        if !p.is_empty() && !c.is_empty() && !attenuation::resource_within(c, p) {
            return Err(refused(format!(
                "Delegation violates resource-narrowing rule: child resource {} is not a \
                 sub-resource of parent {}",
                py_repr_str(c),
                py_repr_str(p)
            )));
        }
    }
    if !truthy(last.get("issuer"))
        || !matches!(last.get("proof"), Some(Value::Object(_) | Value::Array(_)))
    {
        return Err(refused(
            "Delegation refused: the parent grant is not a signed credential",
        ));
    }
    let delegatee = parent_intent.get("delegatee");
    if !truthy(delegatee) {
        return Err(refused(
            "Delegation refused: the parent grant names no delegatee; issue it with the \
             delegatee's DID (for example vouch.delegate(..., to=did))",
        ));
    }
    if delegatee.and_then(Value::as_str) != Some(signer_did) {
        return Err(refused(format!(
            "Delegation refused: the parent grant names delegatee {}, not this signer {}",
            py_repr(delegatee),
            py_repr_str(signer_did)
        )));
    }
    let links = grant_chain::check_grant_chain(&grants, intent)?;
    let child =
        delegation::capability_view(&json!({"credentialSubject": {"intent": intent}}), false);
    let capability = grant_chain::chain_capability(&grants, false)?;
    if let Err(dimension) = attenuation::non_expansion(&capability, &child) {
        return Err(refused(format!(
            "Delegation violates the non-expansion rule: the child is broader than the parent \
             grant on {}",
            py_repr_str(dimension.as_str())
        )));
    }
    Ok(links)
}

/// Fit a child's window inside its parent grant's: start no earlier than the
/// grant, end no later. Returns (start ns, seconds).
fn clamp_to_parent(parent: &Value, start_ns: i128, valid_seconds: i64) -> Result<(i128, i64)> {
    let bound = |k: &str| {
        parent
            .get(k)
            .and_then(Value::as_str)
            .map(|t| parse_protocol_time_ns(t).map(to_micros))
    };
    let (Some(Ok(from)), Some(Ok(until))) = (bound("validFrom"), bound("validUntil")) else {
        return Err(refused(
            "Delegation refused: the parent grant has no validity window",
        ));
    };
    let start = start_ns.max(from);
    // Whole seconds, truncated toward zero.
    let remaining = (until - start) / NS_PER_SECOND;
    if remaining <= 0 {
        return Err(refused("Delegation refused: the parent grant has expired"));
    }
    let remaining = i64::try_from(remaining).unwrap_or(i64::MAX);
    Ok((start, valid_seconds.min(remaining)))
}

/// The unsigned credential the reference builds for `req` (everything but
/// the proof). Errors with the reference's refusal text.
pub fn prepare_credential(req: &IssueRequest) -> Result<Value> {
    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); req);
    check_issuer(&req.issuer_did)?;
    let now = to_micros(parse_protocol_time_ns(&req.now)?);
    let mut valid_seconds = match req.valid_seconds {
        None => DEFAULT_VALID_SECONDS,
        Some(s) if s > 0 => s,
        Some(_) => return Err(refused(INVALID_VALID_SECONDS)),
    };
    let mut start = match &req.valid_from {
        Some(t) => to_micros(parse_protocol_time_ns(t)?),
        None => now,
    };
    let mut chain = req.delegation_chain.clone();
    let mut parent_digest: Option<String> = None;
    if let Some(parent) = &req.parent_credential {
        if !req.intent.is_object() {
            return Err(refused("intent must be a dict"));
        }
        let links = links_from_parent(parent, &req.intent, &req.issuer_did)?;
        let direct = &links[links.len() - 1]["parentCredential"];
        (start, valid_seconds) = clamp_to_parent(direct, start, valid_seconds)?;
        if grant_chain::is_grant_intent(&req.intent) {
            parent_digest = Some(
                grant_chain::grant_digest(direct).map_err(|_| refused(PARENT_NOT_PLAIN_JSON))?,
            );
            chain = None;
        } else {
            chain = Some(Value::Array(links));
        }
    }

    validate_intent(&req.intent)?;
    let chain = chain.filter(truthy_chain);
    if parent_digest.is_some() && chain.is_some() {
        return Err(refused(
            "a credential carries parentGrantDigest or a delegationChain, never both",
        ));
    }
    let until = start + i128::from(valid_seconds) * NS_PER_SECOND;

    let mut subject = Map::new();
    subject.insert("id".into(), json!(req.issuer_did));
    subject.insert(
        "vouchVersion".into(),
        json!(crate::credentials::PROTOCOL_VERSION),
    );
    subject.insert("intent".into(), req.intent.clone());
    if let Some(score) = req.reputation_score {
        subject.insert("reputationScore".into(), json!(score.clamp(0, 100)));
    }
    if let Some(digest) = parent_digest {
        subject.insert(grant_chain::PARENT_GRANT_DIGEST.into(), json!(digest));
    }
    if let Some(chain) = chain {
        subject.insert("delegationChain".into(), chain);
    }
    let id = match req.credential_id.as_deref() {
        Some(id) if !id.is_empty() => id.to_string(),
        _ => new_credential_id()?,
    };
    let mut vc = Map::new();
    vc.insert(
        "@context".into(),
        json!([
            crate::credentials::VC_CONTEXT_V2,
            crate::credentials::VOUCH_CONTEXT_V1
        ]),
    );
    vc.insert("id".into(), json!(id));
    vc.insert(
        "type".into(),
        json!([
            crate::credentials::VC_TYPE,
            crate::credentials::VOUCH_CREDENTIAL_TYPE
        ]),
    );
    vc.insert("issuer".into(), json!(req.issuer_did));
    vc.insert("validFrom".into(), json!(format_protocol_time(start)?));
    vc.insert("validUntil".into(), json!(format_protocol_time(until)?));
    vc.insert("credentialSubject".into(), Value::Object(subject));
    if let Some(status) = &req.credential_status {
        vc.insert("credentialStatus".into(), status.clone());
    }
    Ok(Value::Object(vc))
}

fn truthy_chain(v: &Value) -> bool {
    truthy(Some(v))
}

/// The Ed25519 verificationMethod for `req`.
pub fn verification_method(req: &IssueRequest) -> String {
    crate::nesting::deep_guard!(String::new(); req);
    req.verification_method
        .clone()
        .unwrap_or_else(|| format!("{}#key-1", req.issuer_did))
}

/// The verificationMethod at another key slot of the DID an Ed25519
/// verificationMethod belongs to.
fn slot_verification_method(ed25519_method: &str, slot: &str) -> String {
    match ed25519_method.strip_suffix("#key-1") {
        Some(base) => format!("{base}#{slot}"),
        None => match ed25519_method.split_once('#') {
            Some((base, _)) => format!("{base}#{slot}"),
            None => format!("{ed25519_method}#{slot}"),
        },
    }
}

/// The ML-DSA-44 verificationMethod that pairs with an Ed25519 one: the
/// #key-2 slot of the same DID.
pub fn mldsa44_verification_method(ed25519_method: &str) -> String {
    slot_verification_method(ed25519_method, "key-2")
}

/// The SLH-DSA-SHA2-128s verificationMethod that pairs with an Ed25519 one:
/// the #key-3 slot of the same DID.
pub fn slhdsa128_verification_method(ed25519_method: &str) -> String {
    slot_verification_method(ed25519_method, "key-3")
}

/// The proof's `created`: the time now, in whole seconds.
fn created(req: &IssueRequest) -> Result<String> {
    format_protocol_time(parse_protocol_time_ns(&req.now)?)
}

/// The signer's DID must be a DID: the reference refuses an empty one, and
/// anything that does not start "did:" and name a method.
pub fn check_issuer(did: &str) -> Result<()> {
    if did.is_empty() {
        return Err(refused(
            "Vouch Signer requires 'did' (Decentralized Identifier)",
        ));
    }
    if !(did.starts_with("did:") && did.len() > 4) {
        return Err(refused(NOT_A_DID));
    }
    Ok(())
}

fn check_signer(req: &IssueRequest, ed25519_seed: &[u8]) -> Result<()> {
    check_issuer(&req.issuer_did)?;
    let kp = crate::keys::Ed25519KeyPair::from_seed_slice(ed25519_seed)?;
    match did_key_mismatch(&req.issuer_did, &kp.public_key()) {
        Some(problem) => Err(refused(problem)),
        None => Ok(()),
    }
}

/// Issue a credential with one eddsa-jcs-2022 proof (the reference's
/// `Signer.sign`).
pub fn issue_credential(req: &IssueRequest, ed25519_seed: &[u8]) -> Result<Value> {
    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); req);
    check_signer(req, ed25519_seed)?;
    let unsigned = prepare_credential(req)?;
    let opts = BuildProofOptions::new(verification_method(req), created(req)?);
    data_integrity::sign(&unsigned, ed25519_seed, &opts)
}

/// Issue a credential under the post-quantum profile (the reference's
/// `Signer.sign_hybrid`): a proof set of two separate proofs, eddsa-jcs-2022
/// and mldsa44-jcs-2024, over the same unsecured document, both with the same
/// `created`. The ML-DSA-44 key's verificationMethod is the #key-2 slot of the
/// Ed25519 one.
pub fn issue_credential_dual(
    req: &IssueRequest,
    ed25519_seed: &[u8],
    mldsa44: &crate::pq::MlDsa44KeyPair,
) -> Result<Value> {
    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); req);
    issue_credential_set(req, ed25519_seed, Some(mldsa44), None)
}

/// Issue a credential with a proof set: the eddsa-jcs-2022 proof, then a
/// proof for each post-quantum key given (mldsa44-jcs-2024, then
/// slhdsa128-jcs-2024), all over the same unsecured document with the same
/// `created`. The ML-DSA-44 key's verificationMethod is the #key-2 slot of
/// the Ed25519 one, the SLH-DSA key's the #key-3 slot. At least one
/// post-quantum key is required.
pub fn issue_credential_set(
    req: &IssueRequest,
    ed25519_seed: &[u8],
    mldsa44: Option<&crate::pq::MlDsa44KeyPair>,
    slhdsa128: Option<&crate::slh::SlhDsa128KeyPair>,
) -> Result<Value> {
    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); req);
    check_signer(req, ed25519_seed)?;
    let unsigned = prepare_credential(req)?;
    let ed_vm = verification_method(req);
    let ml_vm = mldsa44_verification_method(&ed_vm);
    let slh_vm = slhdsa128_verification_method(&ed_vm);
    crate::hybrid::sign_set(
        &unsigned,
        ed25519_seed,
        &ed_vm,
        mldsa44.map(|key| crate::hybrid::PqSigner {
            key,
            verification_method: &ml_vm,
        }),
        slhdsa128.map(|key| crate::hybrid::PqSigner {
            key,
            verification_method: &slh_vm,
        }),
        &created(req)?,
    )
}

/// The signing input of an eddsa-jcs-2022 proof for `req`, for a signer whose
/// key lives elsewhere (a KMS or an HSM): `{"credential", "proof",
/// "signingInput"}` where `proof` is the proof without its value and
/// `signingInput` the 64 bytes to sign (base64). The host signs, sets
/// `proof.proofValue` to "z" plus the base58btc signature, and attaches it.
pub fn prepare_signing(req: &IssueRequest) -> Result<Value> {
    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); req);
    use base64::{engine::general_purpose::STANDARD, Engine};
    let unsigned = prepare_credential(req)?;
    let mut proof = Map::new();
    proof.insert("type".into(), json!(data_integrity::PROOF_TYPE));
    proof.insert("cryptosuite".into(), json!(data_integrity::CRYPTOSUITE_ID));
    proof.insert("created".into(), json!(created(req)?));
    proof.insert("verificationMethod".into(), json!(verification_method(req)));
    proof.insert("proofPurpose".into(), json!("assertionMethod"));
    let input = data_integrity::hash_data(&unsigned, &proof)?;
    Ok(json!({
        "credential": unsigned,
        "proof": Value::Object(proof),
        "signingInput": STANDARD.encode(input),
    }))
}

// ---------------------------------------------------------------------------
// JSON in, JSON out (for the bindings)
// ---------------------------------------------------------------------------

const REQUEST_MEMBERS: [&str; 17] = [
    "issuer",
    "intent",
    "now",
    "validFrom",
    "validSeconds",
    "reputationScore",
    "delegationChain",
    "parentCredential",
    "credentialId",
    "credentialStatus",
    "verificationMethod",
    "ed25519Seed",
    "postQuantum",
    "mldsa44SecretKey",
    "mldsa44PublicKey",
    "slhdsa128SecretKey",
    "prepare",
];

fn present<'a>(obj: &'a Map<String, Value>, name: &str) -> Option<&'a Value> {
    obj.get(name).filter(|v| !v.is_null())
}

fn text(obj: &Map<String, Value>, name: &str) -> Result<Option<String>> {
    match present(obj, name) {
        None => Ok(None),
        Some(Value::String(s)) => Ok(Some(s.clone())),
        Some(_) => Err(refused(format!("{name} must be a string"))),
    }
}

fn b64(obj: &Map<String, Value>, name: &str) -> Result<Option<Vec<u8>>> {
    use base64::{engine::general_purpose::STANDARD, Engine};
    text(obj, name)?
        .map(|s| {
            STANDARD
                .decode(s)
                .map_err(|_| refused(format!("{name} must be standard base64")))
        })
        .transpose()
}

/// Read an issuance request (see [`issue_json`]).
pub fn issue_request_from_json(obj: &Map<String, Value>) -> Result<IssueRequest> {
    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); obj);
    if let Some(name) = obj.keys().find(|k| !REQUEST_MEMBERS.contains(&k.as_str())) {
        return Err(refused(format!(
            "the request holds an unknown member {:?}",
            name.chars().take(40).collect::<String>()
        )));
    }
    // validSeconds: a whole number; anything else is refused when the
    // credential is prepared, in the reference's order.
    let valid_seconds = match present(obj, "validSeconds") {
        None => None,
        Some(Value::Number(n)) if n.is_i64() => n.as_i64(),
        Some(_) => Some(i64::MIN),
    };
    let whole = |name: &str| -> Result<Option<i64>> {
        match present(obj, name) {
            None => Ok(None),
            Some(Value::Number(n)) => n
                .as_i64()
                .or_else(|| {
                    n.as_f64()
                        .filter(|f| f.is_finite())
                        .map(|f| crate::float::trunc(f) as i64)
                })
                .map(Some)
                .ok_or_else(|| refused(format!("{name} must be a number"))),
            Some(_) => Err(refused(format!("{name} must be a number"))),
        }
    };
    Ok(IssueRequest {
        issuer_did: text(obj, "issuer")?.ok_or_else(|| refused("issuer must be a DID"))?,
        intent: obj.get("intent").cloned().unwrap_or(Value::Null),
        now: text(obj, "now")?.ok_or_else(|| refused("now must be a protocol time"))?,
        valid_from: text(obj, "validFrom")?,
        valid_seconds,
        reputation_score: whole("reputationScore")?,
        delegation_chain: present(obj, "delegationChain").cloned(),
        parent_credential: present(obj, "parentCredential").cloned(),
        credential_id: text(obj, "credentialId")?,
        credential_status: present(obj, "credentialStatus").cloned(),
        verification_method: text(obj, "verificationMethod")?,
    })
}

/// Issue a credential from one JSON request: `{"issuer", "intent", "now",
/// "validFrom", "validSeconds", "reputationScore", "delegationChain",
/// "parentCredential", "credentialId", "credentialStatus",
/// "verificationMethod", "ed25519Seed" (base64, 32 bytes), "postQuantum"
/// (with "mldsa44SecretKey" and "mldsa44PublicKey", and/or
/// "slhdsa128SecretKey", base64)}`. With `postQuantum` the credential
/// carries a proof set: the Ed25519 proof and one proof for each
/// post-quantum key given (an SLH-DSA key alone is enough). Returns the
/// signed credential. With `"prepare": true` and no key, returns
/// [`prepare_signing`] instead.
pub fn issue_json(request: &Value) -> Result<Value> {
    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); request);
    let obj = request
        .as_object()
        .ok_or_else(|| refused("the request must be a JSON object"))?;
    let req = issue_request_from_json(obj)?;
    if matches!(present(obj, "prepare"), Some(Value::Bool(true))) {
        return prepare_signing(&req);
    }
    // Decoded secrets are wiped from memory when they go out of scope.
    let seed =
        Zeroizing::new(b64(obj, "ed25519Seed")?.ok_or_else(|| refused("ed25519Seed is required"))?);
    if matches!(present(obj, "postQuantum"), Some(Value::Bool(true))) {
        let slhdsa = match b64(obj, "slhdsa128SecretKey")?.map(Zeroizing::new) {
            Some(secret) => Some(crate::slh::SlhDsa128KeyPair::from_secret(&secret)?),
            None => None,
        };
        // The ML-DSA-44 key is required unless an SLH-DSA key is given and
        // no ML-DSA-44 member is.
        let wants_mldsa = slhdsa.is_none()
            || present(obj, "mldsa44SecretKey").is_some()
            || present(obj, "mldsa44PublicKey").is_some();
        let mldsa = if wants_mldsa {
            let secret = Zeroizing::new(
                b64(obj, "mldsa44SecretKey")?
                    .ok_or_else(|| refused("mldsa44SecretKey is required for postQuantum"))?,
            );
            let public = b64(obj, "mldsa44PublicKey")?
                .ok_or_else(|| refused("mldsa44PublicKey is required for postQuantum"))?;
            Some(crate::pq::MlDsa44KeyPair::from_bytes(&secret, &public)?)
        } else {
            None
        };
        return issue_credential_set(&req, &seed, mldsa.as_ref(), slhdsa.as_ref());
    }
    issue_credential(&req, &seed)
}

/// The request members that carry secrets.
pub const SECRET_MEMBERS: [&str; 3] = ["ed25519Seed", "mldsa44SecretKey", "slhdsa128SecretKey"];

/// Wipe the secret members of an issuance request (their text is
/// overwritten in place, then removed), for a binding that parsed the
/// request itself and is done with it.
pub fn wipe_secrets(request: &mut Value) {
    if let Some(obj) = request.as_object_mut() {
        for name in SECRET_MEMBERS {
            if let Some(Value::String(text)) = obj.get_mut(name) {
                text.zeroize();
            }
            obj.remove(name);
        }
    }
}

/// [`issue_json`] for a request the caller hands over as text: the parsed
/// request's secrets are wiped once the credential is signed, and so is the
/// text. Errors as [`issue_json`] does, and on text that is not JSON.
pub fn issue_json_text(mut request: String) -> Result<Value> {
    if let Err(e) = crate::nesting::check_text(request.as_bytes()) {
        request.zeroize();
        return Err(e);
    }
    let parsed = serde_json::from_str::<Value>(&request);
    request.zeroize();
    let mut parsed = parsed.map_err(|e| refused(format!("the request is not JSON: {e}")))?;
    let out = issue_json(&parsed);
    wipe_secrets(&mut parsed);
    out
}

/// [`links_from_parent`] as JSON: `{"parentCredential", "intent",
/// "signerDid"}` to the list of links.
pub fn delegation_links_json(request: &Value) -> Result<Value> {
    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); request);
    let obj = request
        .as_object()
        .ok_or_else(|| refused("the request must be a JSON object"))?;
    let parent = obj.get("parentCredential").unwrap_or(&Value::Null);
    let intent = obj.get("intent").unwrap_or(&Value::Null);
    let signer = text(obj, "signerDid")?.unwrap_or_default();
    Ok(Value::Array(links_from_parent(parent, intent, &signer)?))
}

// What the no_std depth guard checks in the JSON these types carry.
crate::nesting::nested_fields!(IssueRequest; intent, delegation_chain, parent_credential, credential_status);

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn formats_whole_seconds() {
        let t = parse_protocol_time_ns("2026-04-26T10:00:00.999Z").unwrap();
        assert_eq!(format_protocol_time(t).unwrap(), "2026-04-26T10:00:00Z");
        let t = parse_protocol_time_ns("2000-02-29T23:59:59Z").unwrap();
        assert_eq!(format_protocol_time(t).unwrap(), "2000-02-29T23:59:59Z");
        let t = parse_protocol_time_ns("1969-12-31T23:59:59Z").unwrap();
        assert_eq!(format_protocol_time(t).unwrap(), "1969-12-31T23:59:59Z");
    }

    #[test]
    #[cfg_attr(not(feature = "std"), ignore = "needs a random source (std)")]
    fn credential_ids_are_uuid_v4() {
        let id = new_credential_id().unwrap();
        assert_eq!(id.len(), "urn:uuid:".len() + 36);
        assert_eq!(&id[23..24], "4");
    }

    #[test]
    fn did_key_must_name_the_signing_key() {
        let kp = crate::keys::Ed25519KeyPair::from_seed(&[1u8; 32]);
        assert!(did_key_mismatch(&kp.did_key(), &kp.public_key()).is_none());
        let other = crate::keys::Ed25519KeyPair::from_seed(&[2u8; 32]);
        assert!(did_key_mismatch(&other.did_key(), &kp.public_key()).is_some());
        assert!(did_key_mismatch("did:web:a.example", &kp.public_key()).is_none());
    }
}