Skip to main content

vouch_core/
status_list.rs

1//! BitstringStatusList revocation/suspension checks.
2//!
3//! Port of the TypeScript `status-list.ts` (W3C VC-BITSTRING-STATUS-LIST). The
4//! bitstring is GZIP-compressed and multibase base64url-no-pad encoded (prefix
5//! 'u'). Bit `i` lives at byte `i >> 3`, position `7 - (i % 8)` (MSB first).
6//!
7//! The core's job is verification. [`check_credential_status`] is the check a
8//! verifier must run for a credential that carries `credentialStatus`: it
9//! verifies each list's proof with the issuer's key, the list's issuer and
10//! validity window, applies the strict profile (shared with every language in
11//! `test-vectors/bitstring-status-list/strict-profile.json`) and reads the bit.
12//! Encoding is provided for issuers; decoding (gunzip) is deterministic
13//! regardless of the compressor, so verification interoperates with lists
14//! produced by any SDK.
15
16use std::io::Write;
17
18use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};
19use flate2::write::GzEncoder;
20use flate2::{Compression, Crc, Decompress, FlushDecompress, Status};
21use serde_json::{Map, Value};
22
23use crate::error::{CoreError, Result};
24use crate::time::{check_clock_skew, parse_protocol_time_ns, window_state_ns, WindowState};
25
26pub const DEFAULT_BITSTRING_LENGTH: usize = 131_072;
27pub const MULTIBASE_BASE64URL_PREFIX: char = 'u';
28
29/// Maximum decompressed bitstring size. The protocol minimum is 16 KiB (131072
30/// bits); this 16 MiB ceiling (over 134 million entries) is far above any real
31/// list while preventing a gzip-bomb denial of service from an attacker-supplied
32/// `encodedList` that expands to gigabytes.
33pub const MAX_DECOMPRESSED_BYTES: usize = 16 * 1024 * 1024;
34
35pub const STATUS_PURPOSE_REVOCATION: &str = "revocation";
36pub const STATUS_PURPOSE_SUSPENSION: &str = "suspension";
37pub const STATUS_PURPOSE_MESSAGE: &str = "message";
38/// The status purposes a list and an entry may name.
39pub const VALID_STATUS_PURPOSES: [&str; 3] = [
40    STATUS_PURPOSE_REVOCATION,
41    STATUS_PURPOSE_SUSPENSION,
42    STATUS_PURPOSE_MESSAGE,
43];
44pub const BITSTRING_STATUS_LIST_CREDENTIAL_TYPE: &str = "BitstringStatusListCredential";
45pub const BITSTRING_STATUS_LIST_SUBJECT_TYPE: &str = "BitstringStatusList";
46pub const BITSTRING_STATUS_LIST_ENTRY_TYPE: &str = "BitstringStatusListEntry";
47
48fn err(msg: &str) -> CoreError {
49    CoreError::Json(msg.to_string())
50}
51
52// gzip header flags (RFC 1952).
53const FHCRC: u8 = 0x02;
54const FEXTRA: u8 = 0x04;
55const FNAME: u8 = 0x08;
56const FCOMMENT: u8 = 0x10;
57const FRESERVED: u8 = 0xe0;
58
59fn crc32(data: &[u8]) -> u32 {
60    let mut c = Crc::new();
61    c.update(data);
62    c.sum()
63}
64
65fn too_large() -> CoreError {
66    CoreError::Json(format!(
67        "decompressed status list exceeds the {MAX_DECOMPRESSED_BYTES}-byte limit"
68    ))
69}
70
71/// Decompress exactly one gzip member (RFC 1952) with nothing after it:
72/// compression method 8, no reserved flag bits, a correct header CRC when one
73/// is present, a complete deflate stream, and a correct CRC-32 and size. The
74/// output is capped at [`MAX_DECOMPRESSED_BYTES`].
75fn gunzip_one_member(data: &[u8]) -> Result<Vec<u8>> {
76    if data.len() < 18 || data[0] != 0x1f || data[1] != 0x8b {
77        return Err(err("encodedList is not a gzip member"));
78    }
79    if data[2] != 8 {
80        return Err(err("gzip compression method is not deflate"));
81    }
82    let flags = data[3];
83    if flags & FRESERVED != 0 {
84        return Err(err("gzip header sets reserved flag bits"));
85    }
86    let truncated = || err("gzip header is truncated");
87    let mut pos = 10usize;
88    if flags & FEXTRA != 0 {
89        let x = data.get(pos..pos + 2).ok_or_else(truncated)?;
90        pos += 2 + usize::from(u16::from_le_bytes([x[0], x[1]]));
91    }
92    for flag in [FNAME, FCOMMENT] {
93        if flags & flag != 0 {
94            let nul = data
95                .get(pos..)
96                .and_then(|rest| rest.iter().position(|&b| b == 0))
97                .ok_or_else(truncated)?;
98            pos += nul + 1;
99        }
100    }
101    if flags & FHCRC != 0 {
102        let h = data.get(pos..pos + 2).ok_or_else(truncated)?;
103        let want = u16::from_le_bytes([h[0], h[1]]);
104        if (crc32(&data[..pos]) & 0xffff) as u16 != want {
105            return Err(err("gzip header CRC does not match"));
106        }
107        pos += 2;
108    }
109    let body = data.get(pos..).ok_or_else(truncated)?;
110
111    let mut inflater = Decompress::new(false);
112    let mut out: Vec<u8> = Vec::new();
113    loop {
114        if out.len() > MAX_DECOMPRESSED_BYTES {
115            return Err(too_large());
116        }
117        let room = (MAX_DECOMPRESSED_BYTES + 1 - out.len()).min(1 << 16);
118        out.reserve(room);
119        let in_before = inflater.total_in();
120        let out_before = out.len();
121        let status = inflater
122            .decompress_vec(&body[in_before as usize..], &mut out, FlushDecompress::None)
123            .map_err(|_| err("encodedList is not a valid gzip member"))?;
124        if status == Status::StreamEnd {
125            break;
126        }
127        if inflater.total_in() == in_before && out.len() == out_before {
128            // No progress and no end of stream: the member is truncated.
129            return Err(err("encodedList gzip member is truncated"));
130        }
131    }
132    if out.len() > MAX_DECOMPRESSED_BYTES {
133        return Err(too_large());
134    }
135    let trailer = &body[inflater.total_in() as usize..];
136    if trailer.len() < 8 {
137        return Err(err("encodedList gzip member is truncated"));
138    }
139    if trailer.len() > 8 {
140        return Err(err("encodedList has data after its gzip member"));
141    }
142    let crc = u32::from_le_bytes([trailer[0], trailer[1], trailer[2], trailer[3]]);
143    let size = u32::from_le_bytes([trailer[4], trailer[5], trailer[6], trailer[7]]);
144    if crc != crc32(&out) || size != out.len() as u32 {
145        return Err(err("gzip CRC-32 or size does not match"));
146    }
147    Ok(out)
148}
149
150/// Decode an `encodedList` under the strict profile: the multibase prefix 'u'
151/// followed by base64url with no padding and canonical trailing bits, holding
152/// exactly one gzip member and nothing after it, which decompresses to at most
153/// 16 MiB and to at least 131,072 bits.
154pub fn decode_bitstring(encoded: &str) -> Result<Vec<u8>> {
155    let body = encoded
156        .strip_prefix(MULTIBASE_BASE64URL_PREFIX)
157        .ok_or_else(|| CoreError::Json("encodedList must use multibase prefix 'u'".into()))?;
158    // URL_SAFE_NO_PAD refuses padding, other alphabets and non-canonical
159    // trailing bits.
160    let compressed = URL_SAFE_NO_PAD
161        .decode(body)
162        .map_err(|e| CoreError::Json(format!("bad base64url: {e}")))?;
163    let out = gunzip_one_member(&compressed)?;
164    if out.len() * 8 < DEFAULT_BITSTRING_LENGTH {
165        return Err(CoreError::Json(format!(
166            "decoded bitstring length {} is below the protocol minimum ({DEFAULT_BITSTRING_LENGTH})",
167            out.len() * 8
168        )));
169    }
170    Ok(out)
171}
172
173/// Encode a raw bitstring to the multibase GZIP form (issuer side). The gzip
174/// header MTIME is zeroed and OS byte set to 0xff for deterministic output.
175///
176/// NOTE: the pure-Rust DEFLATE backend does not produce byte-identical
177/// compressed output to zlib (Python/Node/Go), so the encoded string may differ
178/// from those SDKs even though it decodes to the same bits. Verification is
179/// unaffected (gunzip is deterministic). Issuers needing byte-identical output
180/// across SDKs should build with a zlib-backed flate2 feature.
181pub fn encode_bitstring(bits: &[u8]) -> Result<String> {
182    let mut encoder = GzEncoder::new(Vec::new(), Compression::new(9));
183    encoder
184        .write_all(bits)
185        .map_err(|e| CoreError::Json(format!("gzip failed: {e}")))?;
186    let mut compressed = encoder
187        .finish()
188        .map_err(|e| CoreError::Json(format!("gzip finish failed: {e}")))?;
189    if compressed.len() >= 10 {
190        compressed[4] = 0;
191        compressed[5] = 0;
192        compressed[6] = 0;
193        compressed[7] = 0;
194        compressed[9] = 0xff;
195    }
196    Ok(format!(
197        "{}{}",
198        MULTIBASE_BASE64URL_PREFIX,
199        URL_SAFE_NO_PAD.encode(compressed)
200    ))
201}
202
203/// Read bit `index` from a raw bitstring.
204pub fn get_status(bits: &[u8], index: usize) -> Result<bool> {
205    let byte = index >> 3;
206    if byte >= bits.len() {
207        return Err(CoreError::Json(format!(
208            "index {index} out of range for {}-bit list",
209            bits.len() * 8
210        )));
211    }
212    let pos = 7 - (index % 8);
213    Ok(bits[byte] & (1 << pos) != 0)
214}
215
216/// Set bit `index` in a raw bitstring (issuer side).
217pub fn set_status(bits: &mut [u8], index: usize, value: bool) -> Result<()> {
218    let byte = index >> 3;
219    if byte >= bits.len() {
220        return Err(CoreError::Json(format!("index {index} out of range")));
221    }
222    let pos = 7 - (index % 8);
223    if value {
224        bits[byte] |= 1 << pos;
225    } else {
226        bits[byte] &= !(1 << pos);
227    }
228    Ok(())
229}
230
231/// The index a status entry names: "0" or a decimal number with no sign,
232/// spaces or leading zeros, at most 10 digits (far past any list this module
233/// decodes).
234fn parse_index(s: &str) -> Option<usize> {
235    let b = s.as_bytes();
236    if b.is_empty() || b.len() > 10 || !b.iter().all(|c| c.is_ascii_digit()) {
237        return None;
238    }
239    if b.len() > 1 && b[0] == b'0' {
240        return None;
241    }
242    s.parse::<usize>().ok()
243}
244
245/// Read a credential's bit from a fetched BitstringStatusListCredential under
246/// the strict profile. Returns Ok(true) if the referenced bit is set.
247///
248/// This applies the profile and reads the bit only: it does NOT check the
249/// list's signature, its issuer or its validity window. A verifier MUST call
250/// [`check_credential_status`], which does all of that, rather than this.
251///
252/// The strict profile: `statusSize`, when present on the entry or the list, is
253/// a number equal to 1; `statusListIndex` is
254/// a string matching `^(0|[1-9][0-9]*)$` inside the bitstring; `statusPurpose` is one of
255/// "revocation", "suspension" or "message" on both sides and the two match;
256/// the list's `type` is an array containing "BitstringStatusListCredential";
257/// its `id` equals the entry's `statusListCredential`; and `encodedList`
258/// follows [`decode_bitstring`].
259pub fn verify_status(credential_status: &Value, status_list_credential: &Value) -> Result<bool> {
260    let cs = credential_status
261        .as_object()
262        .ok_or_else(|| CoreError::Json("credentialStatus must be an object".into()))?;
263    let sl = status_list_credential
264        .as_object()
265        .ok_or_else(|| CoreError::Json("statusListCredential must be an object".into()))?;
266
267    if cs.get("type").and_then(|v| v.as_str()) != Some(BITSTRING_STATUS_LIST_ENTRY_TYPE) {
268        return Err(CoreError::Json(format!(
269            "credentialStatus.type must be {BITSTRING_STATUS_LIST_ENTRY_TYPE}"
270        )));
271    }
272    let referenced = cs
273        .get("statusListCredential")
274        .and_then(|v| v.as_str())
275        .filter(|s| !s.is_empty())
276        .ok_or_else(|| {
277            CoreError::Json("credentialStatus.statusListCredential is required".into())
278        })?;
279    if sl.get("id").and_then(|v| v.as_str()) != Some(referenced) {
280        return Err(err(
281            "status list credential id does not match the credential's statusListCredential",
282        ));
283    }
284    let has_type = sl
285        .get("type")
286        .and_then(|v| v.as_array())
287        .map(|a| {
288            a.iter()
289                .any(|t| t.as_str() == Some(BITSTRING_STATUS_LIST_CREDENTIAL_TYPE))
290        })
291        .unwrap_or(false);
292    if !has_type {
293        return Err(CoreError::Json(format!(
294            "status list type must be an array containing {BITSTRING_STATUS_LIST_CREDENTIAL_TYPE}"
295        )));
296    }
297    let subject = sl
298        .get("credentialSubject")
299        .and_then(|v| v.as_object())
300        .ok_or_else(|| CoreError::Json("status list has no credentialSubject".into()))?;
301    if subject.get("type").and_then(|v| v.as_str()) != Some(BITSTRING_STATUS_LIST_SUBJECT_TYPE) {
302        return Err(CoreError::Json(format!(
303            "credentialSubject.type must be {BITSTRING_STATUS_LIST_SUBJECT_TYPE}"
304        )));
305    }
306    let declared = cs.get("statusPurpose").and_then(|v| v.as_str());
307    match declared {
308        Some(p) if VALID_STATUS_PURPOSES.contains(&p) => {}
309        _ => {
310            return Err(err(
311                "credentialStatus.statusPurpose must be revocation, suspension or message",
312            ))
313        }
314    }
315    if declared != subject.get("statusPurpose").and_then(|v| v.as_str()) {
316        return Err(CoreError::Json("statusPurpose mismatch".into()));
317    }
318    // statusSize defaults to 1 on the entry and on the list. Any JSON number
319    // equal to 1 is accepted (1 and 1.0 are one number in JavaScript); any
320    // other value (2, 1.5, "1", true, null) is not a one-bit list.
321    for holder in [cs, subject] {
322        if let Some(size) = holder.get("statusSize") {
323            let one = matches!(size, Value::Number(n) if n.as_f64() == Some(1.0));
324            if !one {
325                return Err(err("statusSize must be 1 (one bit per credential)"));
326            }
327        }
328    }
329    let index = match cs.get("statusListIndex") {
330        Some(Value::String(s)) => parse_index(s).ok_or_else(|| {
331            err("statusListIndex must be a decimal string with no sign, spaces or leading zeros")
332        })?,
333        _ => return Err(err("credentialStatus.statusListIndex must be a string")),
334    };
335    let encoded = subject
336        .get("encodedList")
337        .and_then(|v| v.as_str())
338        .ok_or_else(|| CoreError::Json("credentialSubject.encodedList is required".into()))?;
339
340    let bits = decode_bitstring(encoded)?;
341    get_status(&bits, index)
342}
343
344// ---------------------------------------------------------------------------
345// The full status check a verifier must run
346// ---------------------------------------------------------------------------
347
348pub const STATUS_OK: &str = "status_ok";
349pub const STATUS_NONE: &str = "no_status";
350pub const STATUS_REVOKED: &str = "revoked";
351pub const STATUS_SUSPENDED: &str = "suspended";
352pub const STATUS_UNAVAILABLE: &str = "status_unavailable";
353
354/// A credential may list several status entries; more than this is refused
355/// rather than checked.
356pub const MAX_STATUS_ENTRIES: usize = 8;
357
358/// The outcome of [`check_credential_status`].
359#[derive(Debug, Clone, Copy, PartialEq, Eq)]
360pub struct StatusCheck {
361    /// True when the credential may be accepted on status grounds: it has no
362    /// status entry, or every entry was checked and none is set.
363    pub ok: bool,
364    /// One of [`STATUS_OK`], [`STATUS_NONE`], [`STATUS_REVOKED`],
365    /// [`STATUS_SUSPENDED`] or [`STATUS_UNAVAILABLE`].
366    pub reason: &'static str,
367    /// A short fixed explanation for logs (never a fetched body).
368    pub detail: &'static str,
369}
370
371impl StatusCheck {
372    fn unavailable(detail: &'static str) -> Self {
373        StatusCheck {
374            ok: false,
375            reason: STATUS_UNAVAILABLE,
376            detail,
377        }
378    }
379}
380
381fn issuer_id(v: Option<&Value>) -> Option<&str> {
382    match v {
383        Some(Value::String(s)) if !s.is_empty() => Some(s),
384        Some(Value::Object(o)) => o
385            .get("id")
386            .and_then(|v| v.as_str())
387            .filter(|s| !s.is_empty()),
388        _ => None,
389    }
390}
391
392/// Check the list's proof: one `eddsa-jcs-2022` proof, or a proof set of one
393/// Ed25519 and one ML-DSA-44 proof (then `mldsa44_key` is required). Every
394/// proof needs proofPurpose "assertionMethod" and a verificationMethod of the
395/// issuer's DID.
396fn list_proof_ok(
397    list: &Value,
398    issuer: &str,
399    ed25519_key: &[u8],
400    mldsa44_key: Option<&[u8]>,
401    now: i128,
402    skew: i128,
403) -> std::result::Result<(), &'static str> {
404    let proofs: Vec<&Value> = match list.get("proof") {
405        Some(p @ Value::Object(_)) => vec![p],
406        Some(Value::Array(a)) => a.iter().collect(),
407        _ => Vec::new(),
408    };
409    if proofs.is_empty() || proofs.len() > 2 {
410        return Err("status list has no usable proof");
411    }
412    for p in &proofs {
413        if !p.is_object() {
414            return Err("status list proof is malformed");
415        }
416        if !crate::credentials::proof_bound_to_issuer(p, issuer) {
417            return Err("status list proof is not made by the credential issuer");
418        }
419        // The proof's own rules: type, cryptosuite, a valid created, and an
420        // expires (when present) that has not passed.
421        if !crate::credentials::proof_member_ok(p, issuer, now, skew) {
422            return Err("status list proof is malformed or expired");
423        }
424        // A list's proof made later than now (plus skew) is not yet valid, and
425        // one that expires before it is created is never valid.
426        let time = |key: &str| {
427            p.get(key)
428                .and_then(|v| v.as_str())
429                .and_then(|t| parse_protocol_time_ns(t).ok())
430        };
431        match window_state_ns(now, time("created"), time("expires"), skew) {
432            WindowState::Ok => {}
433            WindowState::NotYetValid => return Err("status list proof is created in the future"),
434            WindowState::Expired => return Err("status list proof has expired"),
435            WindowState::Inverted => return Err("status list proof expires before it is created"),
436        }
437    }
438    if proofs.len() == 1 {
439        return match crate::data_integrity::verify_proof(list, ed25519_key) {
440            Ok(true) => Ok(()),
441            _ => Err("status list signature does not verify"),
442        };
443    }
444    let mut suites: Vec<&str> = proofs
445        .iter()
446        .map(|p| p.get("cryptosuite").and_then(|v| v.as_str()).unwrap_or(""))
447        .collect();
448    suites.sort_unstable();
449    if suites
450        != [
451            crate::hybrid::EDDSA_CRYPTOSUITE_ID,
452            crate::hybrid::MLDSA44_CRYPTOSUITE_ID,
453        ]
454    {
455        return Err("status list proof set is not one Ed25519 and one ML-DSA-44 proof");
456    }
457    let Some(ml) = mldsa44_key else {
458        return Err("no key to check the status list signature with");
459    };
460    match crate::hybrid::verify_dual(list, ed25519_key, ml) {
461        Ok(true) => Ok(()),
462        _ => Err("status list signature does not verify"),
463    }
464}
465
466/// Check one fetched list: an object, issued by the credential's issuer,
467/// inside its validity window, with a proof by the issuer.
468fn list_ok(
469    list: &Value,
470    issuer: &str,
471    ed25519_key: &[u8],
472    mldsa44_key: Option<&[u8]>,
473    now: i128,
474    skew: i128,
475) -> std::result::Result<(), &'static str> {
476    if !list.is_object() {
477        return Err("status list is not a JSON object");
478    }
479    if issuer_id(list.get("issuer")) != Some(issuer) {
480        return Err("status list issuer is not the credential issuer");
481    }
482    let bound = |key: &str| -> std::result::Result<Option<i128>, &'static str> {
483        match list.get(key) {
484            None => Ok(None),
485            Some(Value::String(s)) => parse_protocol_time_ns(s)
486                .map(Some)
487                .map_err(|_| "status list validity window is malformed"),
488            Some(_) => Err("status list validity window is malformed"),
489        }
490    };
491    match window_state_ns(now, bound("validFrom")?, bound("validUntil")?, skew) {
492        WindowState::Ok => {}
493        WindowState::Expired => return Err("status list is expired"),
494        WindowState::NotYetValid => return Err("status list is not yet valid"),
495        WindowState::Inverted => return Err("status list window is inverted"),
496    }
497    list_proof_ok(list, issuer, ed25519_key, mldsa44_key, now, skew)
498}
499
500/// Check every status entry a credential carries, failing closed. A verifier
501/// built on this core MUST call it for any credential that carries
502/// `credentialStatus` (the Python and TypeScript verifiers do so by default).
503///
504/// `status_lists` maps each `statusListCredential` URL to the list the caller
505/// fetched from it (a URL missing from the map counts as a failed fetch).
506/// `issuer_ed25519_key` is the issuer's assertionMethod key; pass `None` for a
507/// `did:key` issuer to take the key from the DID. `issuer_mldsa44_key` is
508/// needed only when a list carries a dual proof.
509///
510/// For each entry (one object, or an array of at most
511/// [`MAX_STATUS_ENTRIES`]): the entry must be a `BitstringStatusListEntry`;
512/// the list's `issuer` must equal the credential's issuer; `now` must fall
513/// inside the list's validity window (a null bound refuses); every proof on
514/// the list must use proofPurpose "assertionMethod" with a verificationMethod
515/// of the issuer's DID, carry a `created` no later than now and an `expires`
516/// that has not passed (both valid times, never null), and verify with the
517/// issuer's key; then the strict profile of
518/// [`verify_status`] is applied and the bit read. A set revocation bit gives
519/// [`STATUS_REVOKED`], a set suspension bit [`STATUS_SUSPENDED`]; a message bit
520/// does not refuse. Any failure gives [`STATUS_UNAVAILABLE`].
521///
522/// Errors (a caller mistake, not a status result) on a malformed `now` or a
523/// skew outside 0..120 seconds.
524pub fn check_credential_status(
525    credential: &Value,
526    status_lists: &Map<String, Value>,
527    issuer_ed25519_key: Option<&[u8]>,
528    issuer_mldsa44_key: Option<&[u8]>,
529    now_iso: &str,
530    clock_skew_seconds: i64,
531) -> Result<StatusCheck> {
532    let skew = check_clock_skew(clock_skew_seconds)?;
533    let now = parse_protocol_time_ns(now_iso)?;
534    let Some(obj) = credential.as_object() else {
535        return Ok(StatusCheck::unavailable("credential is not an object"));
536    };
537    let Some(raw) = obj.get("credentialStatus") else {
538        return Ok(StatusCheck {
539            ok: true,
540            reason: STATUS_NONE,
541            detail: "credential carries no status entry",
542        });
543    };
544    let entries: Vec<&Value> = match raw {
545        Value::Object(_) => vec![raw],
546        Value::Array(a) => a.iter().collect(),
547        _ => Vec::new(),
548    };
549    if entries.is_empty() {
550        return Ok(StatusCheck::unavailable("credentialStatus is malformed"));
551    }
552    if entries.len() > MAX_STATUS_ENTRIES {
553        return Ok(StatusCheck::unavailable(
554            "too many credentialStatus entries",
555        ));
556    }
557    let Some(issuer) = issuer_id(obj.get("issuer")) else {
558        return Ok(StatusCheck::unavailable("credential has no issuer"));
559    };
560    let did_key = if issuer.starts_with("did:key:") {
561        crate::keys::did_key_to_ed25519(issuer).ok()
562    } else {
563        None
564    };
565    let key: Vec<u8> = match (issuer_ed25519_key, did_key) {
566        (Some(k), Some(d)) if k != d.as_slice() => {
567            return Ok(StatusCheck::unavailable(
568                "the key given is not the did:key issuer's key",
569            ))
570        }
571        (Some(k), _) => k.to_vec(),
572        (None, Some(d)) => d,
573        (None, None) => {
574            return Ok(StatusCheck::unavailable(
575                "no key to check the status list signature with",
576            ))
577        }
578    };
579
580    let mut checked: Vec<&str> = Vec::new();
581    for entry in entries {
582        if entry.get("type").and_then(|v| v.as_str()) != Some(BITSTRING_STATUS_LIST_ENTRY_TYPE) {
583            return Ok(StatusCheck::unavailable(
584                "credentialStatus entry type is not supported",
585            ));
586        }
587        let Some(url) = entry
588            .get("statusListCredential")
589            .and_then(|v| v.as_str())
590            .filter(|s| !s.is_empty())
591        else {
592            return Ok(StatusCheck::unavailable("credentialStatus is malformed"));
593        };
594        let Some(list) = status_lists.get(url) else {
595            return Ok(StatusCheck::unavailable("status list could not be fetched"));
596        };
597        if !checked.contains(&url) {
598            if let Err(detail) = list_ok(list, issuer, &key, issuer_mldsa44_key, now, skew) {
599                return Ok(StatusCheck::unavailable(detail));
600            }
601            checked.push(url);
602        }
603        let set = match verify_status(entry, list) {
604            Ok(b) => b,
605            Err(_) => {
606                return Ok(StatusCheck::unavailable(
607                    "status list does not match the strict profile",
608                ))
609            }
610        };
611        if set {
612            match entry.get("statusPurpose").and_then(|v| v.as_str()) {
613                Some(STATUS_PURPOSE_REVOCATION) => {
614                    return Ok(StatusCheck {
615                        ok: false,
616                        reason: STATUS_REVOKED,
617                        detail: "credential is revoked",
618                    })
619                }
620                Some(STATUS_PURPOSE_SUSPENSION) => {
621                    return Ok(StatusCheck {
622                        ok: false,
623                        reason: STATUS_SUSPENDED,
624                        detail: "credential is suspended",
625                    })
626                }
627                _ => {}
628            }
629        }
630    }
631    Ok(StatusCheck {
632        ok: true,
633        reason: STATUS_OK,
634        detail: "every status entry checked",
635    })
636}
637
638#[cfg(test)]
639mod tests {
640    use super::*;
641
642    #[test]
643    fn malformed_encoded_list_errors_gracefully() {
644        assert!(decode_bitstring("not-multibase").is_err()); // missing 'u' prefix
645        assert!(decode_bitstring("uNotValidGzipData").is_err()); // bad gzip stream
646    }
647
648    #[test]
649    fn encode_decode_roundtrip_preserves_bits() {
650        let mut bits = vec![0u8; DEFAULT_BITSTRING_LENGTH / 8];
651        for &i in &[0usize, 1, 7, 8, 15, 100, 1023, 65535, 131070, 131071] {
652            set_status(&mut bits, i, true).unwrap();
653        }
654        let encoded = encode_bitstring(&bits).unwrap();
655        let decoded = decode_bitstring(&encoded).unwrap();
656        assert_eq!(decoded, bits);
657        assert!(get_status(&decoded, 100).unwrap());
658        assert!(!get_status(&decoded, 99).unwrap());
659    }
660
661    fn list_with(subject_purpose: &str) -> serde_json::Value {
662        let bits = vec![0u8; DEFAULT_BITSTRING_LENGTH / 8];
663        serde_json::json!({
664            "id": "https://issuer.example/status/1",
665            "type": ["VerifiableCredential", "BitstringStatusListCredential"],
666            "credentialSubject": {"type": "BitstringStatusList", "statusPurpose": subject_purpose,
667                                  "encodedList": encode_bitstring(&bits).unwrap()}
668        })
669    }
670
671    #[test]
672    fn status_size_other_than_one_refuses() {
673        let list = list_with("revocation");
674        let mut entry = serde_json::json!({"type": "BitstringStatusListEntry", "statusPurpose": "revocation",
675            "statusListIndex": "5", "statusListCredential": "https://issuer.example/status/1"});
676        assert!(!verify_status(&entry, &list).unwrap());
677        entry["statusSize"] = serde_json::json!(1);
678        assert!(!verify_status(&entry, &list).unwrap());
679        // 1.0 is the same number as 1.
680        entry["statusSize"] = serde_json::json!(1.0);
681        assert!(!verify_status(&entry, &list).unwrap());
682        for bad in [
683            serde_json::json!(2),
684            serde_json::json!(0),
685            serde_json::json!("1"),
686            serde_json::json!(true),
687            serde_json::json!(1.5),
688            serde_json::Value::Null,
689        ] {
690            entry["statusSize"] = bad.clone();
691            assert!(verify_status(&entry, &list).is_err(), "{bad}");
692        }
693    }
694
695    #[test]
696    fn status_list_proof_created_and_expires_are_checked() {
697        use crate::data_integrity::{sign, BuildProofOptions};
698        let seed = [3u8; 32];
699        let did = crate::keys::Ed25519KeyPair::from_seed(&seed).did_key();
700        let vm = format!("{did}#{}", did.trim_start_matches("did:key:"));
701        let mut list = list_with("revocation");
702        list["@context"] = serde_json::json!(["https://www.w3.org/ns/credentials/v2"]);
703        list["issuer"] = serde_json::json!(did);
704        let cred = serde_json::json!({"issuer": did, "credentialStatus": {
705            "type": "BitstringStatusListEntry", "statusPurpose": "revocation",
706            "statusListIndex": "5", "statusListCredential": "https://issuer.example/status/1"}});
707        let run = |proof_tweak: &dyn Fn(&mut serde_json::Value)| {
708            let mut opts = BuildProofOptions::new(vm.clone(), "2026-01-01T00:00:00Z");
709            opts.proof_purpose = "assertionMethod".into();
710            let mut unsigned = list.clone();
711            proof_tweak(&mut unsigned);
712            let signed = sign(&unsigned, &seed, &opts).unwrap();
713            let mut lists = serde_json::Map::new();
714            lists.insert("https://issuer.example/status/1".into(), signed);
715            check_credential_status(&cred, &lists, None, None, "2026-01-15T00:00:00Z", 0)
716                .unwrap()
717                .reason
718        };
719        assert_eq!(run(&|_| {}), STATUS_OK);
720        // A null bound is never "absent".
721        assert_eq!(
722            run(&|l| l["validUntil"] = serde_json::Value::Null),
723            STATUS_UNAVAILABLE
724        );
725        // A proof that has expired, or whose created is not a time (both signed).
726        let expired = |expires: serde_json::Value| {
727            let mut opts = BuildProofOptions::new(vm.clone(), "2026-01-01T00:00:00Z");
728            opts.proof_purpose = "assertionMethod".into();
729            let mut proof = crate::data_integrity::build_proof(&list, &seed, &opts).unwrap();
730            proof["expires"] = expires;
731            let mut signed = list.clone();
732            signed["proof"] = proof;
733            let mut lists = serde_json::Map::new();
734            lists.insert("https://issuer.example/status/1".into(), signed);
735            check_credential_status(&cred, &lists, None, None, "2026-01-15T00:00:00Z", 0)
736                .unwrap()
737                .reason
738        };
739        assert_eq!(
740            expired(serde_json::json!("2026-01-10T00:00:00Z")),
741            STATUS_UNAVAILABLE
742        );
743        assert_eq!(expired(serde_json::Value::Null), STATUS_UNAVAILABLE);
744        let mut opts = BuildProofOptions::new(vm.clone(), "yesterday");
745        opts.proof_purpose = "assertionMethod".into();
746        let signed = sign(&list, &seed, &opts).unwrap();
747        let mut lists = serde_json::Map::new();
748        lists.insert("https://issuer.example/status/1".into(), signed);
749        assert_eq!(
750            check_credential_status(&cred, &lists, None, None, "2026-01-15T00:00:00Z", 0)
751                .unwrap()
752                .reason,
753            STATUS_UNAVAILABLE
754        );
755    }
756}