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';
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";
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())
}
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"
))
}
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 {
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)
}
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()))?;
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)
}
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)
))
}
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)
}
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(())
}
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()
}
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()));
}
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)
}
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";
pub const MAX_STATUS_ENTRIES: usize = 8;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct StatusCheck {
pub ok: bool,
pub reason: &'static str,
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,
}
}
fn list_proof_ok(
list: &Value,
issuer: &str,
ed25519_key: &[u8],
mldsa44_key: Option<&[u8]>,
now: i128,
skew: i128,
required: crate::hybrid::Required,
) -> 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");
}
if !crate::credentials::proof_member_ok(p, issuer, now, skew) {
return Err("status list proof is malformed or expired");
}
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 {
if required.any() {
return Err(
"status list proof does not carry the post-quantum proof the verifier requires",
);
}
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 {
if required.any() {
return Err("no key to check the status list signature with");
}
return match crate::hybrid::verify_set_known_keys(list, ed25519_key, None, None) {
Ok(true) => Ok(()),
_ => Err("status list signature does not verify"),
};
};
match crate::hybrid::verify_dual(list, ed25519_key, ml) {
Ok(true) => Ok(()),
_ => Err("status list signature does not verify"),
}
}
fn list_ok(
list: &Value,
issuer: &str,
ed25519_key: &[u8],
mldsa44_key: Option<&[u8]>,
now: i128,
skew: i128,
required: crate::hybrid::Required,
) -> 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, required)
}
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> {
check_credential_status_required(
credential,
status_lists,
issuer_ed25519_key,
issuer_mldsa44_key,
now_iso,
clock_skew_seconds,
crate::hybrid::Required::default(),
)
}
pub fn check_credential_status_required(
credential: &Value,
status_lists: &Map<String, Value>,
issuer_ed25519_key: Option<&[u8]>,
issuer_mldsa44_key: Option<&[u8]>,
now_iso: &str,
clock_skew_seconds: i64,
required: crate::hybrid::Required,
) -> 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, required)
{
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",
})
}
fn list_shape_ok(list: &Value, purpose: Option<&str>) -> std::result::Result<String, String> {
let has_type = list
.get("type")
.and_then(|v| v.as_array())
.is_some_and(|a| {
a.iter()
.any(|t| t.as_str() == Some(BITSTRING_STATUS_LIST_CREDENTIAL_TYPE))
});
if !has_type {
return Err(format!(
"status list type must be an array containing {BITSTRING_STATUS_LIST_CREDENTIAL_TYPE}"
));
}
let subject = list
.get("credentialSubject")
.and_then(|v| v.as_object())
.ok_or("status list has no credentialSubject")?;
if subject.get("type").and_then(|v| v.as_str()) != Some(BITSTRING_STATUS_LIST_SUBJECT_TYPE) {
return Err(format!(
"credentialSubject.type must be {BITSTRING_STATUS_LIST_SUBJECT_TYPE}"
));
}
let declared = match subject.get("statusPurpose").and_then(|v| v.as_str()) {
Some(p) if VALID_STATUS_PURPOSES.contains(&p) => p,
_ => return Err("statusPurpose must be revocation, suspension or message".into()),
};
if purpose.is_some_and(|want| want != declared) {
return Err("statusPurpose mismatch".into());
}
if let Some(size) = subject.get("statusSize") {
if !matches!(size, Value::Number(n) if n.as_f64() == Some(1.0)) {
return Err("statusSize must be 1 (one bit per credential)".into());
}
}
let encoded = subject
.get("encodedList")
.and_then(|v| v.as_str())
.ok_or("credentialSubject.encodedList is required")?;
decode_bitstring(encoded).map_err(|e| e.to_string())?;
Ok(declared.to_string())
}
fn b64_key(request: &Value, name: &str) -> Result<Option<Vec<u8>>> {
use base64::engine::general_purpose::STANDARD;
match request.get(name) {
None | Some(Value::Null) => Ok(None),
Some(Value::String(s)) => STANDARD
.decode(s)
.map(Some)
.map_err(|_| CoreError::Json(format!("{name} must be standard base64"))),
Some(_) => Err(CoreError::Json(format!("{name} must be a base64 string"))),
}
}
pub fn rules_json(request: &Value) -> Result<Value> {
use serde_json::json;
let op = request
.get("op")
.and_then(Value::as_str)
.ok_or_else(|| CoreError::Json("op is required".into()))?;
let list = request.get("list").unwrap_or(&Value::Null);
match op {
"keysNeeded" => {
let proofs: Vec<&Value> = match list.get("proof") {
Some(p @ Value::Object(_)) => vec![p],
Some(Value::Array(a)) => a.iter().take(2).collect(),
_ => Vec::new(),
};
let wanted: Vec<Value> = proofs
.iter()
.filter_map(|p| {
Some(json!({
"cryptosuite": p.get("cryptosuite")?.as_str()?,
"verificationMethod": p.get("verificationMethod")?.as_str()?,
}))
})
.collect();
Ok(json!({"issuer": issuer_id(list.get("issuer")), "proofs": wanted}))
}
"validate" => {
let issuer = request
.get("issuer")
.and_then(Value::as_str)
.ok_or_else(|| CoreError::Json("issuer is required".into()))?;
let now = parse_protocol_time_ns(
request
.get("now")
.and_then(Value::as_str)
.ok_or_else(|| CoreError::Json("now is required".into()))?,
)?;
let skew = match request.get("clockSkewSeconds") {
None | Some(Value::Null) => 0,
Some(v) => check_clock_skew(crate::time::clock_skew_from_json(v)?)?,
};
let ed = b64_key(request, "ed25519Key")?;
let ml = b64_key(request, "mldsa44Key")?;
let purpose = request.get("purpose").and_then(Value::as_str);
let required = match request.get("requirePostQuantum") {
None => crate::hybrid::Required::default(),
Some(Value::Bool(b)) => crate::hybrid::Required {
post_quantum: *b,
..Default::default()
},
Some(_) => {
return Err(CoreError::Json(
"requirePostQuantum must be true or false".into(),
))
}
};
if crate::attenuation::json_nesting_exceeds(list, 128) {
return Ok(
json!({"ok": false, "reason": "status list is nested too deeply", "purpose": null}),
);
}
let checked = list_ok(
list,
issuer,
ed.as_deref().unwrap_or(&[]),
ml.as_deref(),
now,
skew,
required,
)
.map_err(String::from)
.and_then(|()| list_shape_ok(list, purpose));
Ok(match checked {
Ok(p) => json!({"ok": true, "reason": null, "purpose": p}),
Err(why) => json!({"ok": false, "reason": why, "purpose": null}),
})
}
"bit" => {
let entry = request.get("credentialStatus").unwrap_or(&Value::Null);
Ok(json!({"set": verify_status(entry, list)?}))
}
"decode" => {
use base64::engine::general_purpose::STANDARD;
let encoded = request
.get("encodedList")
.and_then(Value::as_str)
.ok_or_else(|| CoreError::Json("encodedList must be a non-empty string".into()))?;
Ok(json!({"bits": STANDARD.encode(decode_bitstring(encoded)?)}))
}
other => Err(CoreError::Json(format!("unknown status list op {other:?}"))),
}
}
#[cfg(test)]
mod rules_tests {
use super::*;
use crate::data_integrity::{self, BuildProofOptions};
use crate::keys::Ed25519KeyPair;
use base64::engine::general_purpose::STANDARD;
use serde_json::json;
const NOW: &str = "2026-06-01T00:00:00Z";
fn signed_list(kp: &Ed25519KeyPair, bit: Option<usize>) -> Value {
let mut bits = vec![0u8; DEFAULT_BITSTRING_LENGTH / 8];
if let Some(i) = bit {
set_status(&mut bits, i, true).unwrap();
}
let did = kp.did_key();
let list = json!({
"@context": ["https://www.w3.org/ns/credentials/v2"],
"id": "https://example.com/status/1",
"type": ["VerifiableCredential", "BitstringStatusListCredential"],
"issuer": did,
"validFrom": "2026-01-01T00:00:00Z",
"credentialSubject": {
"id": "https://example.com/status/1#list",
"type": "BitstringStatusList",
"statusPurpose": "revocation",
"encodedList": encode_bitstring(&bits).unwrap(),
}
});
let opts = BuildProofOptions::new(format!("{did}#{}", &did[8..]), "2026-01-01T00:00:00Z");
data_integrity::sign(&list, &kp.seed(), &opts).unwrap()
}
fn validate(list: &Value, issuer: &str, key: &[u8]) -> Value {
rules_json(&json!({
"op": "validate", "list": list, "issuer": issuer,
"ed25519Key": STANDARD.encode(key), "now": NOW, "clockSkewSeconds": 30,
}))
.unwrap()
}
#[test]
fn a_signed_list_passes_and_a_tampered_one_does_not() {
let kp = Ed25519KeyPair::from_seed(&[11u8; 32]);
let list = signed_list(&kp, Some(5));
let ok = validate(&list, &kp.did_key(), &kp.public_key());
assert_eq!(ok["ok"], json!(true), "{ok}");
assert_eq!(ok["purpose"], json!("revocation"));
let mut tampered = list.clone();
tampered["credentialSubject"]["statusPurpose"] = json!("suspension");
assert_eq!(
validate(&tampered, &kp.did_key(), &kp.public_key())["ok"],
json!(false)
);
let other = Ed25519KeyPair::from_seed(&[12u8; 32]);
assert_eq!(
validate(&list, &other.did_key(), &kp.public_key())["ok"],
json!(false)
);
assert_eq!(
validate(&list, &kp.did_key(), &other.public_key())["ok"],
json!(false)
);
let wrong_purpose = rules_json(&json!({
"op": "validate", "list": list, "issuer": kp.did_key(), "purpose": "suspension",
"ed25519Key": STANDARD.encode(kp.public_key()), "now": NOW,
}))
.unwrap();
assert_eq!(wrong_purpose["ok"], json!(false));
let expired = rules_json(&json!({
"op": "validate", "list": list, "issuer": kp.did_key(),
"ed25519Key": STANDARD.encode(kp.public_key()), "now": "2025-01-01T00:00:00Z",
}))
.unwrap();
assert_eq!(expired["ok"], json!(false));
}
#[test]
fn keys_needed_bit_and_decode() {
let kp = Ed25519KeyPair::from_seed(&[11u8; 32]);
let list = signed_list(&kp, Some(5));
let need = rules_json(&json!({"op": "keysNeeded", "list": list})).unwrap();
assert_eq!(need["issuer"], json!(kp.did_key()));
assert_eq!(need["proofs"].as_array().unwrap().len(), 1);
let entry = |i: &str| {
json!({"type": "BitstringStatusListEntry", "statusPurpose": "revocation",
"statusListIndex": i, "statusListCredential": "https://example.com/status/1"})
};
let set = rules_json(&json!({"op": "bit", "credentialStatus": entry("5"), "list": list}))
.unwrap();
assert_eq!(set["set"], json!(true));
let clear = rules_json(&json!({"op": "bit", "credentialStatus": entry("6"), "list": list}))
.unwrap();
assert_eq!(clear["set"], json!(false));
assert!(
rules_json(&json!({"op": "bit", "credentialStatus": entry("05"), "list": list}))
.is_err()
);
let enc = list["credentialSubject"]["encodedList"].clone();
let bits = rules_json(&json!({"op": "decode", "encodedList": enc})).unwrap();
assert_eq!(
STANDARD
.decode(bits["bits"].as_str().unwrap())
.unwrap()
.len(),
DEFAULT_BITSTRING_LENGTH / 8
);
assert!(rules_json(&json!({"op": "nope"})).is_err());
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn malformed_encoded_list_errors_gracefully() {
assert!(decode_bitstring("not-multibase").is_err()); assert!(decode_bitstring("uNotValidGzipData").is_err()); }
#[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());
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);
assert_eq!(
run(&|l| l["validUntil"] = serde_json::Value::Null),
STATUS_UNAVAILABLE
);
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
);
}
}