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. Every proof needs proofPurpose
394/// "assertionMethod" and a verificationMethod of the issuer's DID.
395///
396/// `required` is what the verifier requires of the credential the list
397/// speaks for (its `requirePostQuantum` and `requireSuites` settings). When
398/// it asks for anything post-quantum, a list with the Ed25519 proof alone is
399/// refused and the ML-DSA-44 member must verify with `mldsa44_key`, so a
400/// forged Ed25519 signature cannot serve a clean list. A list's post-quantum
401/// proof is always ML-DSA-44, so an SLH-DSA requirement is met by it. When
402/// nothing post-quantum is required, the ML-DSA-44 member is checked when
403/// its key is known, and the Ed25519 member always.
404fn list_proof_ok(
405    list: &Value,
406    issuer: &str,
407    ed25519_key: &[u8],
408    mldsa44_key: Option<&[u8]>,
409    now: i128,
410    skew: i128,
411    required: crate::hybrid::Required,
412) -> std::result::Result<(), &'static str> {
413    let proofs: Vec<&Value> = match list.get("proof") {
414        Some(p @ Value::Object(_)) => vec![p],
415        Some(Value::Array(a)) => a.iter().collect(),
416        _ => Vec::new(),
417    };
418    if proofs.is_empty() || proofs.len() > 2 {
419        return Err("status list has no usable proof");
420    }
421    for p in &proofs {
422        if !p.is_object() {
423            return Err("status list proof is malformed");
424        }
425        if !crate::credentials::proof_bound_to_issuer(p, issuer) {
426            return Err("status list proof is not made by the credential issuer");
427        }
428        // The proof's own rules: type, cryptosuite, a valid created, and an
429        // expires (when present) that has not passed.
430        if !crate::credentials::proof_member_ok(p, issuer, now, skew) {
431            return Err("status list proof is malformed or expired");
432        }
433        // A list's proof made later than now (plus skew) is not yet valid, and
434        // one that expires before it is created is never valid.
435        let time = |key: &str| {
436            p.get(key)
437                .and_then(|v| v.as_str())
438                .and_then(|t| parse_protocol_time_ns(t).ok())
439        };
440        match window_state_ns(now, time("created"), time("expires"), skew) {
441            WindowState::Ok => {}
442            WindowState::NotYetValid => return Err("status list proof is created in the future"),
443            WindowState::Expired => return Err("status list proof has expired"),
444            WindowState::Inverted => return Err("status list proof expires before it is created"),
445        }
446    }
447    if proofs.len() == 1 {
448        if required.any() {
449            return Err(
450                "status list proof does not carry the post-quantum proof the verifier requires",
451            );
452        }
453        return match crate::data_integrity::verify_proof(list, ed25519_key) {
454            Ok(true) => Ok(()),
455            _ => Err("status list signature does not verify"),
456        };
457    }
458    let mut suites: Vec<&str> = proofs
459        .iter()
460        .map(|p| p.get("cryptosuite").and_then(|v| v.as_str()).unwrap_or(""))
461        .collect();
462    suites.sort_unstable();
463    if suites
464        != [
465            crate::hybrid::EDDSA_CRYPTOSUITE_ID,
466            crate::hybrid::MLDSA44_CRYPTOSUITE_ID,
467        ]
468    {
469        return Err("status list proof set is not one Ed25519 and one ML-DSA-44 proof");
470    }
471    let Some(ml) = mldsa44_key else {
472        if required.any() {
473            return Err("no key to check the status list signature with");
474        }
475        // Post-quantum not required and its key not known: the Ed25519
476        // member must verify, as for a grant's proof set.
477        return match crate::hybrid::verify_set_known_keys(list, ed25519_key, None, None) {
478            Ok(true) => Ok(()),
479            _ => Err("status list signature does not verify"),
480        };
481    };
482    match crate::hybrid::verify_dual(list, ed25519_key, ml) {
483        Ok(true) => Ok(()),
484        _ => Err("status list signature does not verify"),
485    }
486}
487
488/// Check one fetched list: an object, issued by the credential's issuer,
489/// inside its validity window, with a proof by the issuer.
490fn list_ok(
491    list: &Value,
492    issuer: &str,
493    ed25519_key: &[u8],
494    mldsa44_key: Option<&[u8]>,
495    now: i128,
496    skew: i128,
497    required: crate::hybrid::Required,
498) -> std::result::Result<(), &'static str> {
499    if !list.is_object() {
500        return Err("status list is not a JSON object");
501    }
502    if issuer_id(list.get("issuer")) != Some(issuer) {
503        return Err("status list issuer is not the credential issuer");
504    }
505    let bound = |key: &str| -> std::result::Result<Option<i128>, &'static str> {
506        match list.get(key) {
507            None => Ok(None),
508            Some(Value::String(s)) => parse_protocol_time_ns(s)
509                .map(Some)
510                .map_err(|_| "status list validity window is malformed"),
511            Some(_) => Err("status list validity window is malformed"),
512        }
513    };
514    match window_state_ns(now, bound("validFrom")?, bound("validUntil")?, skew) {
515        WindowState::Ok => {}
516        WindowState::Expired => return Err("status list is expired"),
517        WindowState::NotYetValid => return Err("status list is not yet valid"),
518        WindowState::Inverted => return Err("status list window is inverted"),
519    }
520    list_proof_ok(list, issuer, ed25519_key, mldsa44_key, now, skew, required)
521}
522
523/// Check every status entry a credential carries, failing closed. A verifier
524/// built on this core MUST call it for any credential that carries
525/// `credentialStatus` (the Python and TypeScript verifiers do so by default).
526///
527/// `status_lists` maps each `statusListCredential` URL to the list the caller
528/// fetched from it (a URL missing from the map counts as a failed fetch).
529/// `issuer_ed25519_key` is the issuer's assertionMethod key; pass `None` for a
530/// `did:key` issuer to take the key from the DID. `issuer_mldsa44_key` is
531/// needed only when a list carries a dual proof.
532///
533/// For each entry (one object, or an array of at most
534/// [`MAX_STATUS_ENTRIES`]): the entry must be a `BitstringStatusListEntry`;
535/// the list's `issuer` must equal the credential's issuer; `now` must fall
536/// inside the list's validity window (a null bound refuses); every proof on
537/// the list must use proofPurpose "assertionMethod" with a verificationMethod
538/// of the issuer's DID, carry a `created` no later than now and an `expires`
539/// that has not passed (both valid times, never null), and verify with the
540/// issuer's key; then the strict profile of
541/// [`verify_status`] is applied and the bit read. A set revocation bit gives
542/// [`STATUS_REVOKED`], a set suspension bit [`STATUS_SUSPENDED`]; a message bit
543/// does not refuse. Any failure gives [`STATUS_UNAVAILABLE`].
544///
545/// Errors (a caller mistake, not a status result) on a malformed `now` or a
546/// skew outside 0..120 seconds.
547///
548/// Nothing post-quantum is required of the lists here; a verifier that
549/// requires post-quantum proofs calls [`check_credential_status_required`].
550pub fn check_credential_status(
551    credential: &Value,
552    status_lists: &Map<String, Value>,
553    issuer_ed25519_key: Option<&[u8]>,
554    issuer_mldsa44_key: Option<&[u8]>,
555    now_iso: &str,
556    clock_skew_seconds: i64,
557) -> Result<StatusCheck> {
558    check_credential_status_required(
559        credential,
560        status_lists,
561        issuer_ed25519_key,
562        issuer_mldsa44_key,
563        now_iso,
564        clock_skew_seconds,
565        crate::hybrid::Required::default(),
566    )
567}
568
569/// [`check_credential_status`] for a verifier that requires post-quantum
570/// proofs: `required` is what it requires of the credential (or grant) the
571/// lists speak for, and every list's proof must meet it (see the list proof
572/// rules above). A list that does not is [`STATUS_UNAVAILABLE`].
573pub fn check_credential_status_required(
574    credential: &Value,
575    status_lists: &Map<String, Value>,
576    issuer_ed25519_key: Option<&[u8]>,
577    issuer_mldsa44_key: Option<&[u8]>,
578    now_iso: &str,
579    clock_skew_seconds: i64,
580    required: crate::hybrid::Required,
581) -> Result<StatusCheck> {
582    let skew = check_clock_skew(clock_skew_seconds)?;
583    let now = parse_protocol_time_ns(now_iso)?;
584    let Some(obj) = credential.as_object() else {
585        return Ok(StatusCheck::unavailable("credential is not an object"));
586    };
587    let Some(raw) = obj.get("credentialStatus") else {
588        return Ok(StatusCheck {
589            ok: true,
590            reason: STATUS_NONE,
591            detail: "credential carries no status entry",
592        });
593    };
594    let entries: Vec<&Value> = match raw {
595        Value::Object(_) => vec![raw],
596        Value::Array(a) => a.iter().collect(),
597        _ => Vec::new(),
598    };
599    if entries.is_empty() {
600        return Ok(StatusCheck::unavailable("credentialStatus is malformed"));
601    }
602    if entries.len() > MAX_STATUS_ENTRIES {
603        return Ok(StatusCheck::unavailable(
604            "too many credentialStatus entries",
605        ));
606    }
607    let Some(issuer) = issuer_id(obj.get("issuer")) else {
608        return Ok(StatusCheck::unavailable("credential has no issuer"));
609    };
610    let did_key = if issuer.starts_with("did:key:") {
611        crate::keys::did_key_to_ed25519(issuer).ok()
612    } else {
613        None
614    };
615    let key: Vec<u8> = match (issuer_ed25519_key, did_key) {
616        (Some(k), Some(d)) if k != d.as_slice() => {
617            return Ok(StatusCheck::unavailable(
618                "the key given is not the did:key issuer's key",
619            ))
620        }
621        (Some(k), _) => k.to_vec(),
622        (None, Some(d)) => d,
623        (None, None) => {
624            return Ok(StatusCheck::unavailable(
625                "no key to check the status list signature with",
626            ))
627        }
628    };
629
630    let mut checked: Vec<&str> = Vec::new();
631    for entry in entries {
632        if entry.get("type").and_then(|v| v.as_str()) != Some(BITSTRING_STATUS_LIST_ENTRY_TYPE) {
633            return Ok(StatusCheck::unavailable(
634                "credentialStatus entry type is not supported",
635            ));
636        }
637        let Some(url) = entry
638            .get("statusListCredential")
639            .and_then(|v| v.as_str())
640            .filter(|s| !s.is_empty())
641        else {
642            return Ok(StatusCheck::unavailable("credentialStatus is malformed"));
643        };
644        let Some(list) = status_lists.get(url) else {
645            return Ok(StatusCheck::unavailable("status list could not be fetched"));
646        };
647        if !checked.contains(&url) {
648            if let Err(detail) =
649                list_ok(list, issuer, &key, issuer_mldsa44_key, now, skew, required)
650            {
651                return Ok(StatusCheck::unavailable(detail));
652            }
653            checked.push(url);
654        }
655        let set = match verify_status(entry, list) {
656            Ok(b) => b,
657            Err(_) => {
658                return Ok(StatusCheck::unavailable(
659                    "status list does not match the strict profile",
660                ))
661            }
662        };
663        if set {
664            match entry.get("statusPurpose").and_then(|v| v.as_str()) {
665                Some(STATUS_PURPOSE_REVOCATION) => {
666                    return Ok(StatusCheck {
667                        ok: false,
668                        reason: STATUS_REVOKED,
669                        detail: "credential is revoked",
670                    })
671                }
672                Some(STATUS_PURPOSE_SUSPENSION) => {
673                    return Ok(StatusCheck {
674                        ok: false,
675                        reason: STATUS_SUSPENDED,
676                        detail: "credential is suspended",
677                    })
678                }
679                _ => {}
680            }
681        }
682    }
683    Ok(StatusCheck {
684        ok: true,
685        reason: STATUS_OK,
686        detail: "every status entry checked",
687    })
688}
689
690// ---------------------------------------------------------------------------
691// One list at a time, for hosts that fetch and cache lists themselves
692// ---------------------------------------------------------------------------
693
694/// The shape a status list credential must have before its bits are read:
695/// `type` is an array holding BitstringStatusListCredential, the subject is a
696/// BitstringStatusList with a defined `statusPurpose` (equal to `purpose`
697/// when one is given), `statusSize` (when present) is 1, and `encodedList`
698/// decodes under the strict profile.
699fn list_shape_ok(list: &Value, purpose: Option<&str>) -> std::result::Result<String, String> {
700    let has_type = list
701        .get("type")
702        .and_then(|v| v.as_array())
703        .is_some_and(|a| {
704            a.iter()
705                .any(|t| t.as_str() == Some(BITSTRING_STATUS_LIST_CREDENTIAL_TYPE))
706        });
707    if !has_type {
708        return Err(format!(
709            "status list type must be an array containing {BITSTRING_STATUS_LIST_CREDENTIAL_TYPE}"
710        ));
711    }
712    let subject = list
713        .get("credentialSubject")
714        .and_then(|v| v.as_object())
715        .ok_or("status list has no credentialSubject")?;
716    if subject.get("type").and_then(|v| v.as_str()) != Some(BITSTRING_STATUS_LIST_SUBJECT_TYPE) {
717        return Err(format!(
718            "credentialSubject.type must be {BITSTRING_STATUS_LIST_SUBJECT_TYPE}"
719        ));
720    }
721    let declared = match subject.get("statusPurpose").and_then(|v| v.as_str()) {
722        Some(p) if VALID_STATUS_PURPOSES.contains(&p) => p,
723        _ => return Err("statusPurpose must be revocation, suspension or message".into()),
724    };
725    if purpose.is_some_and(|want| want != declared) {
726        return Err("statusPurpose mismatch".into());
727    }
728    if let Some(size) = subject.get("statusSize") {
729        if !matches!(size, Value::Number(n) if n.as_f64() == Some(1.0)) {
730            return Err("statusSize must be 1 (one bit per credential)".into());
731        }
732    }
733    let encoded = subject
734        .get("encodedList")
735        .and_then(|v| v.as_str())
736        .ok_or("credentialSubject.encodedList is required")?;
737    decode_bitstring(encoded).map_err(|e| e.to_string())?;
738    Ok(declared.to_string())
739}
740
741fn b64_key(request: &Value, name: &str) -> Result<Option<Vec<u8>>> {
742    use base64::engine::general_purpose::STANDARD;
743    match request.get(name) {
744        None | Some(Value::Null) => Ok(None),
745        Some(Value::String(s)) => STANDARD
746            .decode(s)
747            .map(Some)
748            .map_err(|_| CoreError::Json(format!("{name} must be standard base64"))),
749        Some(_) => Err(CoreError::Json(format!("{name} must be a base64 string"))),
750    }
751}
752
753/// The status list rules a host needs when it fetches, caches and checks
754/// lists itself, one JSON request at a time (`op` picks the rule):
755///
756/// * `keysNeeded` `{list}` -> `{issuer, proofs: [{cryptosuite,
757///   verificationMethod}]}`: the keys to look up before `validate`.
758/// * `validate` `{list, issuer, ed25519Key?, mldsa44Key?, purpose?, now,
759///   clockSkewSeconds?, requirePostQuantum?}` -> `{ok, reason, purpose}`: one list is usable for
760///   `issuer` at `now` (issued by it, inside its window, proof by it, keys in
761///   standard base64) and has the shape whose bits can be read. A host's cache
762///   keeps only lists that pass.
763/// * `bit` `{credentialStatus, list}` -> `{set}`: the strict profile and the
764///   bit (an error says why the entry and list do not fit).
765/// * `decode` `{encodedList}` -> `{bits}`: the raw bitstring, standard base64.
766pub fn rules_json(request: &Value) -> Result<Value> {
767    use serde_json::json;
768    let op = request
769        .get("op")
770        .and_then(Value::as_str)
771        .ok_or_else(|| CoreError::Json("op is required".into()))?;
772    let list = request.get("list").unwrap_or(&Value::Null);
773    match op {
774        "keysNeeded" => {
775            let proofs: Vec<&Value> = match list.get("proof") {
776                Some(p @ Value::Object(_)) => vec![p],
777                Some(Value::Array(a)) => a.iter().take(2).collect(),
778                _ => Vec::new(),
779            };
780            let wanted: Vec<Value> = proofs
781                .iter()
782                .filter_map(|p| {
783                    Some(json!({
784                        "cryptosuite": p.get("cryptosuite")?.as_str()?,
785                        "verificationMethod": p.get("verificationMethod")?.as_str()?,
786                    }))
787                })
788                .collect();
789            Ok(json!({"issuer": issuer_id(list.get("issuer")), "proofs": wanted}))
790        }
791        "validate" => {
792            let issuer = request
793                .get("issuer")
794                .and_then(Value::as_str)
795                .ok_or_else(|| CoreError::Json("issuer is required".into()))?;
796            let now = parse_protocol_time_ns(
797                request
798                    .get("now")
799                    .and_then(Value::as_str)
800                    .ok_or_else(|| CoreError::Json("now is required".into()))?,
801            )?;
802            let skew = match request.get("clockSkewSeconds") {
803                None | Some(Value::Null) => 0,
804                Some(v) => check_clock_skew(crate::time::clock_skew_from_json(v)?)?,
805            };
806            let ed = b64_key(request, "ed25519Key")?;
807            let ml = b64_key(request, "mldsa44Key")?;
808            let purpose = request.get("purpose").and_then(Value::as_str);
809            // A host whose verifier requires post-quantum proofs says so,
810            // and a list without a verified ML-DSA-44 proof is refused.
811            let required = match request.get("requirePostQuantum") {
812                None => crate::hybrid::Required::default(),
813                Some(Value::Bool(b)) => crate::hybrid::Required {
814                    post_quantum: *b,
815                    ..Default::default()
816                },
817                Some(_) => {
818                    return Err(CoreError::Json(
819                        "requirePostQuantum must be true or false".into(),
820                    ))
821                }
822            };
823            if crate::attenuation::json_nesting_exceeds(list, 128) {
824                return Ok(
825                    json!({"ok": false, "reason": "status list is nested too deeply", "purpose": null}),
826                );
827            }
828            let checked = list_ok(
829                list,
830                issuer,
831                ed.as_deref().unwrap_or(&[]),
832                ml.as_deref(),
833                now,
834                skew,
835                required,
836            )
837            .map_err(String::from)
838            .and_then(|()| list_shape_ok(list, purpose));
839            Ok(match checked {
840                Ok(p) => json!({"ok": true, "reason": null, "purpose": p}),
841                Err(why) => json!({"ok": false, "reason": why, "purpose": null}),
842            })
843        }
844        "bit" => {
845            let entry = request.get("credentialStatus").unwrap_or(&Value::Null);
846            Ok(json!({"set": verify_status(entry, list)?}))
847        }
848        "decode" => {
849            use base64::engine::general_purpose::STANDARD;
850            let encoded = request
851                .get("encodedList")
852                .and_then(Value::as_str)
853                .ok_or_else(|| CoreError::Json("encodedList must be a non-empty string".into()))?;
854            Ok(json!({"bits": STANDARD.encode(decode_bitstring(encoded)?)}))
855        }
856        other => Err(CoreError::Json(format!("unknown status list op {other:?}"))),
857    }
858}
859
860#[cfg(test)]
861mod rules_tests {
862    use super::*;
863    use crate::data_integrity::{self, BuildProofOptions};
864    use crate::keys::Ed25519KeyPair;
865    use base64::engine::general_purpose::STANDARD;
866    use serde_json::json;
867
868    const NOW: &str = "2026-06-01T00:00:00Z";
869
870    fn signed_list(kp: &Ed25519KeyPair, bit: Option<usize>) -> Value {
871        let mut bits = vec![0u8; DEFAULT_BITSTRING_LENGTH / 8];
872        if let Some(i) = bit {
873            set_status(&mut bits, i, true).unwrap();
874        }
875        let did = kp.did_key();
876        let list = json!({
877            "@context": ["https://www.w3.org/ns/credentials/v2"],
878            "id": "https://example.com/status/1",
879            "type": ["VerifiableCredential", "BitstringStatusListCredential"],
880            "issuer": did,
881            "validFrom": "2026-01-01T00:00:00Z",
882            "credentialSubject": {
883                "id": "https://example.com/status/1#list",
884                "type": "BitstringStatusList",
885                "statusPurpose": "revocation",
886                "encodedList": encode_bitstring(&bits).unwrap(),
887            }
888        });
889        let opts = BuildProofOptions::new(format!("{did}#{}", &did[8..]), "2026-01-01T00:00:00Z");
890        data_integrity::sign(&list, &kp.seed(), &opts).unwrap()
891    }
892
893    fn validate(list: &Value, issuer: &str, key: &[u8]) -> Value {
894        rules_json(&json!({
895            "op": "validate", "list": list, "issuer": issuer,
896            "ed25519Key": STANDARD.encode(key), "now": NOW, "clockSkewSeconds": 30,
897        }))
898        .unwrap()
899    }
900
901    #[test]
902    fn a_signed_list_passes_and_a_tampered_one_does_not() {
903        let kp = Ed25519KeyPair::from_seed(&[11u8; 32]);
904        let list = signed_list(&kp, Some(5));
905        let ok = validate(&list, &kp.did_key(), &kp.public_key());
906        assert_eq!(ok["ok"], json!(true), "{ok}");
907        assert_eq!(ok["purpose"], json!("revocation"));
908
909        let mut tampered = list.clone();
910        tampered["credentialSubject"]["statusPurpose"] = json!("suspension");
911        assert_eq!(
912            validate(&tampered, &kp.did_key(), &kp.public_key())["ok"],
913            json!(false)
914        );
915
916        let other = Ed25519KeyPair::from_seed(&[12u8; 32]);
917        assert_eq!(
918            validate(&list, &other.did_key(), &kp.public_key())["ok"],
919            json!(false)
920        );
921        assert_eq!(
922            validate(&list, &kp.did_key(), &other.public_key())["ok"],
923            json!(false)
924        );
925
926        let wrong_purpose = rules_json(&json!({
927            "op": "validate", "list": list, "issuer": kp.did_key(), "purpose": "suspension",
928            "ed25519Key": STANDARD.encode(kp.public_key()), "now": NOW,
929        }))
930        .unwrap();
931        assert_eq!(wrong_purpose["ok"], json!(false));
932
933        let expired = rules_json(&json!({
934            "op": "validate", "list": list, "issuer": kp.did_key(),
935            "ed25519Key": STANDARD.encode(kp.public_key()), "now": "2025-01-01T00:00:00Z",
936        }))
937        .unwrap();
938        assert_eq!(expired["ok"], json!(false));
939    }
940
941    #[test]
942    fn keys_needed_bit_and_decode() {
943        let kp = Ed25519KeyPair::from_seed(&[11u8; 32]);
944        let list = signed_list(&kp, Some(5));
945        let need = rules_json(&json!({"op": "keysNeeded", "list": list})).unwrap();
946        assert_eq!(need["issuer"], json!(kp.did_key()));
947        assert_eq!(need["proofs"].as_array().unwrap().len(), 1);
948        let entry = |i: &str| {
949            json!({"type": "BitstringStatusListEntry", "statusPurpose": "revocation",
950                   "statusListIndex": i, "statusListCredential": "https://example.com/status/1"})
951        };
952        let set = rules_json(&json!({"op": "bit", "credentialStatus": entry("5"), "list": list}))
953            .unwrap();
954        assert_eq!(set["set"], json!(true));
955        let clear = rules_json(&json!({"op": "bit", "credentialStatus": entry("6"), "list": list}))
956            .unwrap();
957        assert_eq!(clear["set"], json!(false));
958        assert!(
959            rules_json(&json!({"op": "bit", "credentialStatus": entry("05"), "list": list}))
960                .is_err()
961        );
962        let enc = list["credentialSubject"]["encodedList"].clone();
963        let bits = rules_json(&json!({"op": "decode", "encodedList": enc})).unwrap();
964        assert_eq!(
965            STANDARD
966                .decode(bits["bits"].as_str().unwrap())
967                .unwrap()
968                .len(),
969            DEFAULT_BITSTRING_LENGTH / 8
970        );
971        assert!(rules_json(&json!({"op": "nope"})).is_err());
972    }
973}
974
975#[cfg(test)]
976mod tests {
977    use super::*;
978
979    #[test]
980    fn malformed_encoded_list_errors_gracefully() {
981        assert!(decode_bitstring("not-multibase").is_err()); // missing 'u' prefix
982        assert!(decode_bitstring("uNotValidGzipData").is_err()); // bad gzip stream
983    }
984
985    #[test]
986    fn encode_decode_roundtrip_preserves_bits() {
987        let mut bits = vec![0u8; DEFAULT_BITSTRING_LENGTH / 8];
988        for &i in &[0usize, 1, 7, 8, 15, 100, 1023, 65535, 131070, 131071] {
989            set_status(&mut bits, i, true).unwrap();
990        }
991        let encoded = encode_bitstring(&bits).unwrap();
992        let decoded = decode_bitstring(&encoded).unwrap();
993        assert_eq!(decoded, bits);
994        assert!(get_status(&decoded, 100).unwrap());
995        assert!(!get_status(&decoded, 99).unwrap());
996    }
997
998    fn list_with(subject_purpose: &str) -> serde_json::Value {
999        let bits = vec![0u8; DEFAULT_BITSTRING_LENGTH / 8];
1000        serde_json::json!({
1001            "id": "https://issuer.example/status/1",
1002            "type": ["VerifiableCredential", "BitstringStatusListCredential"],
1003            "credentialSubject": {"type": "BitstringStatusList", "statusPurpose": subject_purpose,
1004                                  "encodedList": encode_bitstring(&bits).unwrap()}
1005        })
1006    }
1007
1008    #[test]
1009    fn status_size_other_than_one_refuses() {
1010        let list = list_with("revocation");
1011        let mut entry = serde_json::json!({"type": "BitstringStatusListEntry", "statusPurpose": "revocation",
1012            "statusListIndex": "5", "statusListCredential": "https://issuer.example/status/1"});
1013        assert!(!verify_status(&entry, &list).unwrap());
1014        entry["statusSize"] = serde_json::json!(1);
1015        assert!(!verify_status(&entry, &list).unwrap());
1016        // 1.0 is the same number as 1.
1017        entry["statusSize"] = serde_json::json!(1.0);
1018        assert!(!verify_status(&entry, &list).unwrap());
1019        for bad in [
1020            serde_json::json!(2),
1021            serde_json::json!(0),
1022            serde_json::json!("1"),
1023            serde_json::json!(true),
1024            serde_json::json!(1.5),
1025            serde_json::Value::Null,
1026        ] {
1027            entry["statusSize"] = bad.clone();
1028            assert!(verify_status(&entry, &list).is_err(), "{bad}");
1029        }
1030    }
1031
1032    #[test]
1033    fn status_list_proof_created_and_expires_are_checked() {
1034        use crate::data_integrity::{sign, BuildProofOptions};
1035        let seed = [3u8; 32];
1036        let did = crate::keys::Ed25519KeyPair::from_seed(&seed).did_key();
1037        let vm = format!("{did}#{}", did.trim_start_matches("did:key:"));
1038        let mut list = list_with("revocation");
1039        list["@context"] = serde_json::json!(["https://www.w3.org/ns/credentials/v2"]);
1040        list["issuer"] = serde_json::json!(did);
1041        let cred = serde_json::json!({"issuer": did, "credentialStatus": {
1042            "type": "BitstringStatusListEntry", "statusPurpose": "revocation",
1043            "statusListIndex": "5", "statusListCredential": "https://issuer.example/status/1"}});
1044        let run = |proof_tweak: &dyn Fn(&mut serde_json::Value)| {
1045            let mut opts = BuildProofOptions::new(vm.clone(), "2026-01-01T00:00:00Z");
1046            opts.proof_purpose = "assertionMethod".into();
1047            let mut unsigned = list.clone();
1048            proof_tweak(&mut unsigned);
1049            let signed = sign(&unsigned, &seed, &opts).unwrap();
1050            let mut lists = serde_json::Map::new();
1051            lists.insert("https://issuer.example/status/1".into(), signed);
1052            check_credential_status(&cred, &lists, None, None, "2026-01-15T00:00:00Z", 0)
1053                .unwrap()
1054                .reason
1055        };
1056        assert_eq!(run(&|_| {}), STATUS_OK);
1057        // A null bound is never "absent".
1058        assert_eq!(
1059            run(&|l| l["validUntil"] = serde_json::Value::Null),
1060            STATUS_UNAVAILABLE
1061        );
1062        // A proof that has expired, or whose created is not a time (both signed).
1063        let expired = |expires: serde_json::Value| {
1064            let mut opts = BuildProofOptions::new(vm.clone(), "2026-01-01T00:00:00Z");
1065            opts.proof_purpose = "assertionMethod".into();
1066            let mut proof = crate::data_integrity::build_proof(&list, &seed, &opts).unwrap();
1067            proof["expires"] = expires;
1068            let mut signed = list.clone();
1069            signed["proof"] = proof;
1070            let mut lists = serde_json::Map::new();
1071            lists.insert("https://issuer.example/status/1".into(), signed);
1072            check_credential_status(&cred, &lists, None, None, "2026-01-15T00:00:00Z", 0)
1073                .unwrap()
1074                .reason
1075        };
1076        assert_eq!(
1077            expired(serde_json::json!("2026-01-10T00:00:00Z")),
1078            STATUS_UNAVAILABLE
1079        );
1080        assert_eq!(expired(serde_json::Value::Null), STATUS_UNAVAILABLE);
1081        let mut opts = BuildProofOptions::new(vm.clone(), "yesterday");
1082        opts.proof_purpose = "assertionMethod".into();
1083        let signed = sign(&list, &seed, &opts).unwrap();
1084        let mut lists = serde_json::Map::new();
1085        lists.insert("https://issuer.example/status/1".into(), signed);
1086        assert_eq!(
1087            check_credential_status(&cred, &lists, None, None, "2026-01-15T00:00:00Z", 0)
1088                .unwrap()
1089                .reason,
1090            STATUS_UNAVAILABLE
1091        );
1092    }
1093}