vouch-core 4.0.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
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
//! BitstringStatusList revocation/suspension checks.
//!
//! Port of the TypeScript `status-list.ts` (W3C VC-BITSTRING-STATUS-LIST). The
//! bitstring is GZIP-compressed and multibase base64url-no-pad encoded (prefix
//! 'u'). Bit `i` lives at byte `i >> 3`, position `7 - (i % 8)` (MSB first).
//!
//! The core's job is verification. [`check_credential_status`] is the check a
//! verifier must run for a credential that carries `credentialStatus`: it
//! verifies each list's proof with the issuer's key, the list's issuer and
//! validity window, applies the strict profile (shared with every language in
//! `test-vectors/bitstring-status-list/strict-profile.json`) and reads the bit.
//! Encoding is provided for issuers; decoding (gunzip) is deterministic
//! regardless of the compressor, so verification interoperates with lists
//! produced by any SDK.

use std::io::Write;

use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};
use flate2::write::GzEncoder;
use flate2::{Compression, Crc, Decompress, FlushDecompress, Status};
use serde_json::{Map, Value};

use crate::error::{CoreError, Result};
use crate::time::{check_clock_skew, parse_protocol_time_ns, window_state_ns, WindowState};

pub const DEFAULT_BITSTRING_LENGTH: usize = 131_072;
pub const MULTIBASE_BASE64URL_PREFIX: char = 'u';

/// Maximum decompressed bitstring size. The protocol minimum is 16 KiB (131072
/// bits); this 16 MiB ceiling (over 134 million entries) is far above any real
/// list while preventing a gzip-bomb denial of service from an attacker-supplied
/// `encodedList` that expands to gigabytes.
pub const MAX_DECOMPRESSED_BYTES: usize = 16 * 1024 * 1024;

pub const STATUS_PURPOSE_REVOCATION: &str = "revocation";
pub const STATUS_PURPOSE_SUSPENSION: &str = "suspension";
pub const STATUS_PURPOSE_MESSAGE: &str = "message";
/// The status purposes a list and an entry may name.
pub const VALID_STATUS_PURPOSES: [&str; 3] = [
    STATUS_PURPOSE_REVOCATION,
    STATUS_PURPOSE_SUSPENSION,
    STATUS_PURPOSE_MESSAGE,
];
pub const BITSTRING_STATUS_LIST_CREDENTIAL_TYPE: &str = "BitstringStatusListCredential";
pub const BITSTRING_STATUS_LIST_SUBJECT_TYPE: &str = "BitstringStatusList";
pub const BITSTRING_STATUS_LIST_ENTRY_TYPE: &str = "BitstringStatusListEntry";

fn err(msg: &str) -> CoreError {
    CoreError::Json(msg.to_string())
}

// gzip header flags (RFC 1952).
const FHCRC: u8 = 0x02;
const FEXTRA: u8 = 0x04;
const FNAME: u8 = 0x08;
const FCOMMENT: u8 = 0x10;
const FRESERVED: u8 = 0xe0;

fn crc32(data: &[u8]) -> u32 {
    let mut c = Crc::new();
    c.update(data);
    c.sum()
}

fn too_large() -> CoreError {
    CoreError::Json(format!(
        "decompressed status list exceeds the {MAX_DECOMPRESSED_BYTES}-byte limit"
    ))
}

/// Decompress exactly one gzip member (RFC 1952) with nothing after it:
/// compression method 8, no reserved flag bits, a correct header CRC when one
/// is present, a complete deflate stream, and a correct CRC-32 and size. The
/// output is capped at [`MAX_DECOMPRESSED_BYTES`].
fn gunzip_one_member(data: &[u8]) -> Result<Vec<u8>> {
    if data.len() < 18 || data[0] != 0x1f || data[1] != 0x8b {
        return Err(err("encodedList is not a gzip member"));
    }
    if data[2] != 8 {
        return Err(err("gzip compression method is not deflate"));
    }
    let flags = data[3];
    if flags & FRESERVED != 0 {
        return Err(err("gzip header sets reserved flag bits"));
    }
    let truncated = || err("gzip header is truncated");
    let mut pos = 10usize;
    if flags & FEXTRA != 0 {
        let x = data.get(pos..pos + 2).ok_or_else(truncated)?;
        pos += 2 + usize::from(u16::from_le_bytes([x[0], x[1]]));
    }
    for flag in [FNAME, FCOMMENT] {
        if flags & flag != 0 {
            let nul = data
                .get(pos..)
                .and_then(|rest| rest.iter().position(|&b| b == 0))
                .ok_or_else(truncated)?;
            pos += nul + 1;
        }
    }
    if flags & FHCRC != 0 {
        let h = data.get(pos..pos + 2).ok_or_else(truncated)?;
        let want = u16::from_le_bytes([h[0], h[1]]);
        if (crc32(&data[..pos]) & 0xffff) as u16 != want {
            return Err(err("gzip header CRC does not match"));
        }
        pos += 2;
    }
    let body = data.get(pos..).ok_or_else(truncated)?;

    let mut inflater = Decompress::new(false);
    let mut out: Vec<u8> = Vec::new();
    loop {
        if out.len() > MAX_DECOMPRESSED_BYTES {
            return Err(too_large());
        }
        let room = (MAX_DECOMPRESSED_BYTES + 1 - out.len()).min(1 << 16);
        out.reserve(room);
        let in_before = inflater.total_in();
        let out_before = out.len();
        let status = inflater
            .decompress_vec(&body[in_before as usize..], &mut out, FlushDecompress::None)
            .map_err(|_| err("encodedList is not a valid gzip member"))?;
        if status == Status::StreamEnd {
            break;
        }
        if inflater.total_in() == in_before && out.len() == out_before {
            // No progress and no end of stream: the member is truncated.
            return Err(err("encodedList gzip member is truncated"));
        }
    }
    if out.len() > MAX_DECOMPRESSED_BYTES {
        return Err(too_large());
    }
    let trailer = &body[inflater.total_in() as usize..];
    if trailer.len() < 8 {
        return Err(err("encodedList gzip member is truncated"));
    }
    if trailer.len() > 8 {
        return Err(err("encodedList has data after its gzip member"));
    }
    let crc = u32::from_le_bytes([trailer[0], trailer[1], trailer[2], trailer[3]]);
    let size = u32::from_le_bytes([trailer[4], trailer[5], trailer[6], trailer[7]]);
    if crc != crc32(&out) || size != out.len() as u32 {
        return Err(err("gzip CRC-32 or size does not match"));
    }
    Ok(out)
}

/// Decode an `encodedList` under the strict profile: the multibase prefix 'u'
/// followed by base64url with no padding and canonical trailing bits, holding
/// exactly one gzip member and nothing after it, which decompresses to at most
/// 16 MiB and to at least 131,072 bits.
pub fn decode_bitstring(encoded: &str) -> Result<Vec<u8>> {
    let body = encoded
        .strip_prefix(MULTIBASE_BASE64URL_PREFIX)
        .ok_or_else(|| CoreError::Json("encodedList must use multibase prefix 'u'".into()))?;
    // URL_SAFE_NO_PAD refuses padding, other alphabets and non-canonical
    // trailing bits.
    let compressed = URL_SAFE_NO_PAD
        .decode(body)
        .map_err(|e| CoreError::Json(format!("bad base64url: {e}")))?;
    let out = gunzip_one_member(&compressed)?;
    if out.len() * 8 < DEFAULT_BITSTRING_LENGTH {
        return Err(CoreError::Json(format!(
            "decoded bitstring length {} is below the protocol minimum ({DEFAULT_BITSTRING_LENGTH})",
            out.len() * 8
        )));
    }
    Ok(out)
}

/// Encode a raw bitstring to the multibase GZIP form (issuer side). The gzip
/// header MTIME is zeroed and OS byte set to 0xff for deterministic output.
///
/// NOTE: the pure-Rust DEFLATE backend does not produce byte-identical
/// compressed output to zlib (Python/Node/Go), so the encoded string may differ
/// from those SDKs even though it decodes to the same bits. Verification is
/// unaffected (gunzip is deterministic). Issuers needing byte-identical output
/// across SDKs should build with a zlib-backed flate2 feature.
pub fn encode_bitstring(bits: &[u8]) -> Result<String> {
    let mut encoder = GzEncoder::new(Vec::new(), Compression::new(9));
    encoder
        .write_all(bits)
        .map_err(|e| CoreError::Json(format!("gzip failed: {e}")))?;
    let mut compressed = encoder
        .finish()
        .map_err(|e| CoreError::Json(format!("gzip finish failed: {e}")))?;
    if compressed.len() >= 10 {
        compressed[4] = 0;
        compressed[5] = 0;
        compressed[6] = 0;
        compressed[7] = 0;
        compressed[9] = 0xff;
    }
    Ok(format!(
        "{}{}",
        MULTIBASE_BASE64URL_PREFIX,
        URL_SAFE_NO_PAD.encode(compressed)
    ))
}

/// Read bit `index` from a raw bitstring.
pub fn get_status(bits: &[u8], index: usize) -> Result<bool> {
    let byte = index >> 3;
    if byte >= bits.len() {
        return Err(CoreError::Json(format!(
            "index {index} out of range for {}-bit list",
            bits.len() * 8
        )));
    }
    let pos = 7 - (index % 8);
    Ok(bits[byte] & (1 << pos) != 0)
}

/// Set bit `index` in a raw bitstring (issuer side).
pub fn set_status(bits: &mut [u8], index: usize, value: bool) -> Result<()> {
    let byte = index >> 3;
    if byte >= bits.len() {
        return Err(CoreError::Json(format!("index {index} out of range")));
    }
    let pos = 7 - (index % 8);
    if value {
        bits[byte] |= 1 << pos;
    } else {
        bits[byte] &= !(1 << pos);
    }
    Ok(())
}

/// The index a status entry names: "0" or a decimal number with no sign,
/// spaces or leading zeros, at most 10 digits (far past any list this module
/// decodes).
fn parse_index(s: &str) -> Option<usize> {
    let b = s.as_bytes();
    if b.is_empty() || b.len() > 10 || !b.iter().all(|c| c.is_ascii_digit()) {
        return None;
    }
    if b.len() > 1 && b[0] == b'0' {
        return None;
    }
    s.parse::<usize>().ok()
}

/// Read a credential's bit from a fetched BitstringStatusListCredential under
/// the strict profile. Returns Ok(true) if the referenced bit is set.
///
/// This applies the profile and reads the bit only: it does NOT check the
/// list's signature, its issuer or its validity window. A verifier MUST call
/// [`check_credential_status`], which does all of that, rather than this.
///
/// The strict profile: `statusSize`, when present on the entry or the list, is
/// a number equal to 1; `statusListIndex` is
/// a string matching `^(0|[1-9][0-9]*)$` inside the bitstring; `statusPurpose` is one of
/// "revocation", "suspension" or "message" on both sides and the two match;
/// the list's `type` is an array containing "BitstringStatusListCredential";
/// its `id` equals the entry's `statusListCredential`; and `encodedList`
/// follows [`decode_bitstring`].
pub fn verify_status(credential_status: &Value, status_list_credential: &Value) -> Result<bool> {
    let cs = credential_status
        .as_object()
        .ok_or_else(|| CoreError::Json("credentialStatus must be an object".into()))?;
    let sl = status_list_credential
        .as_object()
        .ok_or_else(|| CoreError::Json("statusListCredential must be an object".into()))?;

    if cs.get("type").and_then(|v| v.as_str()) != Some(BITSTRING_STATUS_LIST_ENTRY_TYPE) {
        return Err(CoreError::Json(format!(
            "credentialStatus.type must be {BITSTRING_STATUS_LIST_ENTRY_TYPE}"
        )));
    }
    let referenced = cs
        .get("statusListCredential")
        .and_then(|v| v.as_str())
        .filter(|s| !s.is_empty())
        .ok_or_else(|| {
            CoreError::Json("credentialStatus.statusListCredential is required".into())
        })?;
    if sl.get("id").and_then(|v| v.as_str()) != Some(referenced) {
        return Err(err(
            "status list credential id does not match the credential's statusListCredential",
        ));
    }
    let has_type = sl
        .get("type")
        .and_then(|v| v.as_array())
        .map(|a| {
            a.iter()
                .any(|t| t.as_str() == Some(BITSTRING_STATUS_LIST_CREDENTIAL_TYPE))
        })
        .unwrap_or(false);
    if !has_type {
        return Err(CoreError::Json(format!(
            "status list type must be an array containing {BITSTRING_STATUS_LIST_CREDENTIAL_TYPE}"
        )));
    }
    let subject = sl
        .get("credentialSubject")
        .and_then(|v| v.as_object())
        .ok_or_else(|| CoreError::Json("status list has no credentialSubject".into()))?;
    if subject.get("type").and_then(|v| v.as_str()) != Some(BITSTRING_STATUS_LIST_SUBJECT_TYPE) {
        return Err(CoreError::Json(format!(
            "credentialSubject.type must be {BITSTRING_STATUS_LIST_SUBJECT_TYPE}"
        )));
    }
    let declared = cs.get("statusPurpose").and_then(|v| v.as_str());
    match declared {
        Some(p) if VALID_STATUS_PURPOSES.contains(&p) => {}
        _ => {
            return Err(err(
                "credentialStatus.statusPurpose must be revocation, suspension or message",
            ))
        }
    }
    if declared != subject.get("statusPurpose").and_then(|v| v.as_str()) {
        return Err(CoreError::Json("statusPurpose mismatch".into()));
    }
    // statusSize defaults to 1 on the entry and on the list. Any JSON number
    // equal to 1 is accepted (1 and 1.0 are one number in JavaScript); any
    // other value (2, 1.5, "1", true, null) is not a one-bit list.
    for holder in [cs, subject] {
        if let Some(size) = holder.get("statusSize") {
            let one = matches!(size, Value::Number(n) if n.as_f64() == Some(1.0));
            if !one {
                return Err(err("statusSize must be 1 (one bit per credential)"));
            }
        }
    }
    let index = match cs.get("statusListIndex") {
        Some(Value::String(s)) => parse_index(s).ok_or_else(|| {
            err("statusListIndex must be a decimal string with no sign, spaces or leading zeros")
        })?,
        _ => return Err(err("credentialStatus.statusListIndex must be a string")),
    };
    let encoded = subject
        .get("encodedList")
        .and_then(|v| v.as_str())
        .ok_or_else(|| CoreError::Json("credentialSubject.encodedList is required".into()))?;

    let bits = decode_bitstring(encoded)?;
    get_status(&bits, index)
}

// ---------------------------------------------------------------------------
// The full status check a verifier must run
// ---------------------------------------------------------------------------

pub const STATUS_OK: &str = "status_ok";
pub const STATUS_NONE: &str = "no_status";
pub const STATUS_REVOKED: &str = "revoked";
pub const STATUS_SUSPENDED: &str = "suspended";
pub const STATUS_UNAVAILABLE: &str = "status_unavailable";

/// A credential may list several status entries; more than this is refused
/// rather than checked.
pub const MAX_STATUS_ENTRIES: usize = 8;

/// The outcome of [`check_credential_status`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct StatusCheck {
    /// True when the credential may be accepted on status grounds: it has no
    /// status entry, or every entry was checked and none is set.
    pub ok: bool,
    /// One of [`STATUS_OK`], [`STATUS_NONE`], [`STATUS_REVOKED`],
    /// [`STATUS_SUSPENDED`] or [`STATUS_UNAVAILABLE`].
    pub reason: &'static str,
    /// A short fixed explanation for logs (never a fetched body).
    pub detail: &'static str,
}

impl StatusCheck {
    fn unavailable(detail: &'static str) -> Self {
        StatusCheck {
            ok: false,
            reason: STATUS_UNAVAILABLE,
            detail,
        }
    }
}

fn issuer_id(v: Option<&Value>) -> Option<&str> {
    match v {
        Some(Value::String(s)) if !s.is_empty() => Some(s),
        Some(Value::Object(o)) => o
            .get("id")
            .and_then(|v| v.as_str())
            .filter(|s| !s.is_empty()),
        _ => None,
    }
}

/// Check the list's proof: one `eddsa-jcs-2022` proof, or a proof set of one
/// Ed25519 and one ML-DSA-44 proof (then `mldsa44_key` is required). Every
/// proof needs proofPurpose "assertionMethod" and a verificationMethod of the
/// issuer's DID.
fn list_proof_ok(
    list: &Value,
    issuer: &str,
    ed25519_key: &[u8],
    mldsa44_key: Option<&[u8]>,
    now: i128,
    skew: i128,
) -> std::result::Result<(), &'static str> {
    let proofs: Vec<&Value> = match list.get("proof") {
        Some(p @ Value::Object(_)) => vec![p],
        Some(Value::Array(a)) => a.iter().collect(),
        _ => Vec::new(),
    };
    if proofs.is_empty() || proofs.len() > 2 {
        return Err("status list has no usable proof");
    }
    for p in &proofs {
        if !p.is_object() {
            return Err("status list proof is malformed");
        }
        if !crate::credentials::proof_bound_to_issuer(p, issuer) {
            return Err("status list proof is not made by the credential issuer");
        }
        // The proof's own rules: type, cryptosuite, a valid created, and an
        // expires (when present) that has not passed.
        if !crate::credentials::proof_member_ok(p, issuer, now, skew) {
            return Err("status list proof is malformed or expired");
        }
        // A list's proof made later than now (plus skew) is not yet valid, and
        // one that expires before it is created is never valid.
        let time = |key: &str| {
            p.get(key)
                .and_then(|v| v.as_str())
                .and_then(|t| parse_protocol_time_ns(t).ok())
        };
        match window_state_ns(now, time("created"), time("expires"), skew) {
            WindowState::Ok => {}
            WindowState::NotYetValid => return Err("status list proof is created in the future"),
            WindowState::Expired => return Err("status list proof has expired"),
            WindowState::Inverted => return Err("status list proof expires before it is created"),
        }
    }
    if proofs.len() == 1 {
        return match crate::data_integrity::verify_proof(list, ed25519_key) {
            Ok(true) => Ok(()),
            _ => Err("status list signature does not verify"),
        };
    }
    let mut suites: Vec<&str> = proofs
        .iter()
        .map(|p| p.get("cryptosuite").and_then(|v| v.as_str()).unwrap_or(""))
        .collect();
    suites.sort_unstable();
    if suites
        != [
            crate::hybrid::EDDSA_CRYPTOSUITE_ID,
            crate::hybrid::MLDSA44_CRYPTOSUITE_ID,
        ]
    {
        return Err("status list proof set is not one Ed25519 and one ML-DSA-44 proof");
    }
    let Some(ml) = mldsa44_key else {
        return Err("no key to check the status list signature with");
    };
    match crate::hybrid::verify_dual(list, ed25519_key, ml) {
        Ok(true) => Ok(()),
        _ => Err("status list signature does not verify"),
    }
}

/// Check one fetched list: an object, issued by the credential's issuer,
/// inside its validity window, with a proof by the issuer.
fn list_ok(
    list: &Value,
    issuer: &str,
    ed25519_key: &[u8],
    mldsa44_key: Option<&[u8]>,
    now: i128,
    skew: i128,
) -> std::result::Result<(), &'static str> {
    if !list.is_object() {
        return Err("status list is not a JSON object");
    }
    if issuer_id(list.get("issuer")) != Some(issuer) {
        return Err("status list issuer is not the credential issuer");
    }
    let bound = |key: &str| -> std::result::Result<Option<i128>, &'static str> {
        match list.get(key) {
            None => Ok(None),
            Some(Value::String(s)) => parse_protocol_time_ns(s)
                .map(Some)
                .map_err(|_| "status list validity window is malformed"),
            Some(_) => Err("status list validity window is malformed"),
        }
    };
    match window_state_ns(now, bound("validFrom")?, bound("validUntil")?, skew) {
        WindowState::Ok => {}
        WindowState::Expired => return Err("status list is expired"),
        WindowState::NotYetValid => return Err("status list is not yet valid"),
        WindowState::Inverted => return Err("status list window is inverted"),
    }
    list_proof_ok(list, issuer, ed25519_key, mldsa44_key, now, skew)
}

/// Check every status entry a credential carries, failing closed. A verifier
/// built on this core MUST call it for any credential that carries
/// `credentialStatus` (the Python and TypeScript verifiers do so by default).
///
/// `status_lists` maps each `statusListCredential` URL to the list the caller
/// fetched from it (a URL missing from the map counts as a failed fetch).
/// `issuer_ed25519_key` is the issuer's assertionMethod key; pass `None` for a
/// `did:key` issuer to take the key from the DID. `issuer_mldsa44_key` is
/// needed only when a list carries a dual proof.
///
/// For each entry (one object, or an array of at most
/// [`MAX_STATUS_ENTRIES`]): the entry must be a `BitstringStatusListEntry`;
/// the list's `issuer` must equal the credential's issuer; `now` must fall
/// inside the list's validity window (a null bound refuses); every proof on
/// the list must use proofPurpose "assertionMethod" with a verificationMethod
/// of the issuer's DID, carry a `created` no later than now and an `expires`
/// that has not passed (both valid times, never null), and verify with the
/// issuer's key; then the strict profile of
/// [`verify_status`] is applied and the bit read. A set revocation bit gives
/// [`STATUS_REVOKED`], a set suspension bit [`STATUS_SUSPENDED`]; a message bit
/// does not refuse. Any failure gives [`STATUS_UNAVAILABLE`].
///
/// Errors (a caller mistake, not a status result) on a malformed `now` or a
/// skew outside 0..120 seconds.
pub fn check_credential_status(
    credential: &Value,
    status_lists: &Map<String, Value>,
    issuer_ed25519_key: Option<&[u8]>,
    issuer_mldsa44_key: Option<&[u8]>,
    now_iso: &str,
    clock_skew_seconds: i64,
) -> Result<StatusCheck> {
    let skew = check_clock_skew(clock_skew_seconds)?;
    let now = parse_protocol_time_ns(now_iso)?;
    let Some(obj) = credential.as_object() else {
        return Ok(StatusCheck::unavailable("credential is not an object"));
    };
    let Some(raw) = obj.get("credentialStatus") else {
        return Ok(StatusCheck {
            ok: true,
            reason: STATUS_NONE,
            detail: "credential carries no status entry",
        });
    };
    let entries: Vec<&Value> = match raw {
        Value::Object(_) => vec![raw],
        Value::Array(a) => a.iter().collect(),
        _ => Vec::new(),
    };
    if entries.is_empty() {
        return Ok(StatusCheck::unavailable("credentialStatus is malformed"));
    }
    if entries.len() > MAX_STATUS_ENTRIES {
        return Ok(StatusCheck::unavailable(
            "too many credentialStatus entries",
        ));
    }
    let Some(issuer) = issuer_id(obj.get("issuer")) else {
        return Ok(StatusCheck::unavailable("credential has no issuer"));
    };
    let did_key = if issuer.starts_with("did:key:") {
        crate::keys::did_key_to_ed25519(issuer).ok()
    } else {
        None
    };
    let key: Vec<u8> = match (issuer_ed25519_key, did_key) {
        (Some(k), Some(d)) if k != d.as_slice() => {
            return Ok(StatusCheck::unavailable(
                "the key given is not the did:key issuer's key",
            ))
        }
        (Some(k), _) => k.to_vec(),
        (None, Some(d)) => d,
        (None, None) => {
            return Ok(StatusCheck::unavailable(
                "no key to check the status list signature with",
            ))
        }
    };

    let mut checked: Vec<&str> = Vec::new();
    for entry in entries {
        if entry.get("type").and_then(|v| v.as_str()) != Some(BITSTRING_STATUS_LIST_ENTRY_TYPE) {
            return Ok(StatusCheck::unavailable(
                "credentialStatus entry type is not supported",
            ));
        }
        let Some(url) = entry
            .get("statusListCredential")
            .and_then(|v| v.as_str())
            .filter(|s| !s.is_empty())
        else {
            return Ok(StatusCheck::unavailable("credentialStatus is malformed"));
        };
        let Some(list) = status_lists.get(url) else {
            return Ok(StatusCheck::unavailable("status list could not be fetched"));
        };
        if !checked.contains(&url) {
            if let Err(detail) = list_ok(list, issuer, &key, issuer_mldsa44_key, now, skew) {
                return Ok(StatusCheck::unavailable(detail));
            }
            checked.push(url);
        }
        let set = match verify_status(entry, list) {
            Ok(b) => b,
            Err(_) => {
                return Ok(StatusCheck::unavailable(
                    "status list does not match the strict profile",
                ))
            }
        };
        if set {
            match entry.get("statusPurpose").and_then(|v| v.as_str()) {
                Some(STATUS_PURPOSE_REVOCATION) => {
                    return Ok(StatusCheck {
                        ok: false,
                        reason: STATUS_REVOKED,
                        detail: "credential is revoked",
                    })
                }
                Some(STATUS_PURPOSE_SUSPENSION) => {
                    return Ok(StatusCheck {
                        ok: false,
                        reason: STATUS_SUSPENDED,
                        detail: "credential is suspended",
                    })
                }
                _ => {}
            }
        }
    }
    Ok(StatusCheck {
        ok: true,
        reason: STATUS_OK,
        detail: "every status entry checked",
    })
}

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

    #[test]
    fn malformed_encoded_list_errors_gracefully() {
        assert!(decode_bitstring("not-multibase").is_err()); // missing 'u' prefix
        assert!(decode_bitstring("uNotValidGzipData").is_err()); // bad gzip stream
    }

    #[test]
    fn encode_decode_roundtrip_preserves_bits() {
        let mut bits = vec![0u8; DEFAULT_BITSTRING_LENGTH / 8];
        for &i in &[0usize, 1, 7, 8, 15, 100, 1023, 65535, 131070, 131071] {
            set_status(&mut bits, i, true).unwrap();
        }
        let encoded = encode_bitstring(&bits).unwrap();
        let decoded = decode_bitstring(&encoded).unwrap();
        assert_eq!(decoded, bits);
        assert!(get_status(&decoded, 100).unwrap());
        assert!(!get_status(&decoded, 99).unwrap());
    }

    fn list_with(subject_purpose: &str) -> serde_json::Value {
        let bits = vec![0u8; DEFAULT_BITSTRING_LENGTH / 8];
        serde_json::json!({
            "id": "https://issuer.example/status/1",
            "type": ["VerifiableCredential", "BitstringStatusListCredential"],
            "credentialSubject": {"type": "BitstringStatusList", "statusPurpose": subject_purpose,
                                  "encodedList": encode_bitstring(&bits).unwrap()}
        })
    }

    #[test]
    fn status_size_other_than_one_refuses() {
        let list = list_with("revocation");
        let mut entry = serde_json::json!({"type": "BitstringStatusListEntry", "statusPurpose": "revocation",
            "statusListIndex": "5", "statusListCredential": "https://issuer.example/status/1"});
        assert!(!verify_status(&entry, &list).unwrap());
        entry["statusSize"] = serde_json::json!(1);
        assert!(!verify_status(&entry, &list).unwrap());
        // 1.0 is the same number as 1.
        entry["statusSize"] = serde_json::json!(1.0);
        assert!(!verify_status(&entry, &list).unwrap());
        for bad in [
            serde_json::json!(2),
            serde_json::json!(0),
            serde_json::json!("1"),
            serde_json::json!(true),
            serde_json::json!(1.5),
            serde_json::Value::Null,
        ] {
            entry["statusSize"] = bad.clone();
            assert!(verify_status(&entry, &list).is_err(), "{bad}");
        }
    }

    #[test]
    fn status_list_proof_created_and_expires_are_checked() {
        use crate::data_integrity::{sign, BuildProofOptions};
        let seed = [3u8; 32];
        let did = crate::keys::Ed25519KeyPair::from_seed(&seed).did_key();
        let vm = format!("{did}#{}", did.trim_start_matches("did:key:"));
        let mut list = list_with("revocation");
        list["@context"] = serde_json::json!(["https://www.w3.org/ns/credentials/v2"]);
        list["issuer"] = serde_json::json!(did);
        let cred = serde_json::json!({"issuer": did, "credentialStatus": {
            "type": "BitstringStatusListEntry", "statusPurpose": "revocation",
            "statusListIndex": "5", "statusListCredential": "https://issuer.example/status/1"}});
        let run = |proof_tweak: &dyn Fn(&mut serde_json::Value)| {
            let mut opts = BuildProofOptions::new(vm.clone(), "2026-01-01T00:00:00Z");
            opts.proof_purpose = "assertionMethod".into();
            let mut unsigned = list.clone();
            proof_tweak(&mut unsigned);
            let signed = sign(&unsigned, &seed, &opts).unwrap();
            let mut lists = serde_json::Map::new();
            lists.insert("https://issuer.example/status/1".into(), signed);
            check_credential_status(&cred, &lists, None, None, "2026-01-15T00:00:00Z", 0)
                .unwrap()
                .reason
        };
        assert_eq!(run(&|_| {}), STATUS_OK);
        // A null bound is never "absent".
        assert_eq!(
            run(&|l| l["validUntil"] = serde_json::Value::Null),
            STATUS_UNAVAILABLE
        );
        // A proof that has expired, or whose created is not a time (both signed).
        let expired = |expires: serde_json::Value| {
            let mut opts = BuildProofOptions::new(vm.clone(), "2026-01-01T00:00:00Z");
            opts.proof_purpose = "assertionMethod".into();
            let mut proof = crate::data_integrity::build_proof(&list, &seed, &opts).unwrap();
            proof["expires"] = expires;
            let mut signed = list.clone();
            signed["proof"] = proof;
            let mut lists = serde_json::Map::new();
            lists.insert("https://issuer.example/status/1".into(), signed);
            check_credential_status(&cred, &lists, None, None, "2026-01-15T00:00:00Z", 0)
                .unwrap()
                .reason
        };
        assert_eq!(
            expired(serde_json::json!("2026-01-10T00:00:00Z")),
            STATUS_UNAVAILABLE
        );
        assert_eq!(expired(serde_json::Value::Null), STATUS_UNAVAILABLE);
        let mut opts = BuildProofOptions::new(vm.clone(), "yesterday");
        opts.proof_purpose = "assertionMethod".into();
        let signed = sign(&list, &seed, &opts).unwrap();
        let mut lists = serde_json::Map::new();
        lists.insert("https://issuer.example/status/1".into(), signed);
        assert_eq!(
            check_credential_status(&cred, &lists, None, None, "2026-01-15T00:00:00Z", 0)
                .unwrap()
                .reason,
            STATUS_UNAVAILABLE
        );
    }
}