1#[allow(unused_imports)]
17use crate::prelude::*;
18
19use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};
20#[cfg(feature = "std")]
21use flate2::{Crc, Decompress, FlushDecompress, Status};
22use serde_json::{Map, Value};
23
24use crate::error::{CoreError, Result};
25use crate::time::{check_clock_skew, parse_protocol_time_ns, window_state_ns, WindowState};
26
27pub const DEFAULT_BITSTRING_LENGTH: usize = 131_072;
28pub const MULTIBASE_BASE64URL_PREFIX: char = 'u';
29
30pub const MAX_DECOMPRESSED_BYTES: usize = 16 * 1024 * 1024;
35
36pub const STATUS_PURPOSE_REVOCATION: &str = "revocation";
37pub const STATUS_PURPOSE_SUSPENSION: &str = "suspension";
38pub const STATUS_PURPOSE_MESSAGE: &str = "message";
39pub const VALID_STATUS_PURPOSES: [&str; 3] = [
41 STATUS_PURPOSE_REVOCATION,
42 STATUS_PURPOSE_SUSPENSION,
43 STATUS_PURPOSE_MESSAGE,
44];
45pub const BITSTRING_STATUS_LIST_CREDENTIAL_TYPE: &str = "BitstringStatusListCredential";
46pub const BITSTRING_STATUS_LIST_SUBJECT_TYPE: &str = "BitstringStatusList";
47pub const BITSTRING_STATUS_LIST_ENTRY_TYPE: &str = "BitstringStatusListEntry";
48
49fn err(msg: &str) -> CoreError {
50 CoreError::Json(msg.to_string())
51}
52
53#[cfg(feature = "std")]
55const FHCRC: u8 = 0x02;
56#[cfg(feature = "std")]
57const FEXTRA: u8 = 0x04;
58#[cfg(feature = "std")]
59const FNAME: u8 = 0x08;
60#[cfg(feature = "std")]
61const FCOMMENT: u8 = 0x10;
62#[cfg(feature = "std")]
63const FRESERVED: u8 = 0xe0;
64
65#[cfg(feature = "std")]
66fn crc32(data: &[u8]) -> u32 {
67 let mut c = Crc::new();
68 c.update(data);
69 c.sum()
70}
71
72#[cfg(not(feature = "std"))]
76fn crc32(data: &[u8]) -> u32 {
77 let mut crc = 0xffff_ffffu32;
78 for &byte in data {
79 crc ^= u32::from(byte);
80 for _ in 0..8 {
81 let mask = (crc & 1).wrapping_neg();
82 crc = (crc >> 1) ^ (0xedb8_8320 & mask);
83 }
84 }
85 !crc
86}
87
88fn too_large() -> CoreError {
89 CoreError::Json(format!(
90 "decompressed status list exceeds the {MAX_DECOMPRESSED_BYTES}-byte limit"
91 ))
92}
93
94#[cfg(feature = "std")]
99fn gunzip_one_member(data: &[u8]) -> Result<Vec<u8>> {
100 if data.len() < 18 || data[0] != 0x1f || data[1] != 0x8b {
101 return Err(err("encodedList is not a gzip member"));
102 }
103 if data[2] != 8 {
104 return Err(err("gzip compression method is not deflate"));
105 }
106 let flags = data[3];
107 if flags & FRESERVED != 0 {
108 return Err(err("gzip header sets reserved flag bits"));
109 }
110 let truncated = || err("gzip header is truncated");
111 let mut pos = 10usize;
112 if flags & FEXTRA != 0 {
113 let x = data.get(pos..pos + 2).ok_or_else(truncated)?;
114 pos += 2 + usize::from(u16::from_le_bytes([x[0], x[1]]));
115 }
116 for flag in [FNAME, FCOMMENT] {
117 if flags & flag != 0 {
118 let nul = data
119 .get(pos..)
120 .and_then(|rest| rest.iter().position(|&b| b == 0))
121 .ok_or_else(truncated)?;
122 pos += nul + 1;
123 }
124 }
125 if flags & FHCRC != 0 {
126 let h = data.get(pos..pos + 2).ok_or_else(truncated)?;
127 let want = u16::from_le_bytes([h[0], h[1]]);
128 if (crc32(&data[..pos]) & 0xffff) as u16 != want {
129 return Err(err("gzip header CRC does not match"));
130 }
131 pos += 2;
132 }
133 let body = data.get(pos..).ok_or_else(truncated)?;
134
135 let mut inflater = Decompress::new(false);
136 let mut out: Vec<u8> = Vec::new();
137 loop {
138 if out.len() > MAX_DECOMPRESSED_BYTES {
139 return Err(too_large());
140 }
141 let room = (MAX_DECOMPRESSED_BYTES + 1 - out.len()).min(1 << 16);
142 out.reserve(room);
143 let in_before = inflater.total_in();
144 let out_before = out.len();
145 let status = inflater
146 .decompress_vec(&body[in_before as usize..], &mut out, FlushDecompress::None)
147 .map_err(|_| err("encodedList is not a valid gzip member"))?;
148 if status == Status::StreamEnd {
149 break;
150 }
151 if inflater.total_in() == in_before && out.len() == out_before {
152 return Err(err("encodedList gzip member is truncated"));
154 }
155 }
156 if out.len() > MAX_DECOMPRESSED_BYTES {
157 return Err(too_large());
158 }
159 let trailer = &body[inflater.total_in() as usize..];
160 if trailer.len() < 8 {
161 return Err(err("encodedList gzip member is truncated"));
162 }
163 if trailer.len() > 8 {
164 return Err(err("encodedList has data after its gzip member"));
165 }
166 let crc = u32::from_le_bytes([trailer[0], trailer[1], trailer[2], trailer[3]]);
167 let size = u32::from_le_bytes([trailer[4], trailer[5], trailer[6], trailer[7]]);
168 if crc != crc32(&out) || size != out.len() as u32 {
169 return Err(err("gzip CRC-32 or size does not match"));
170 }
171 Ok(out)
172}
173
174#[cfg(not(feature = "std"))]
179fn no_gzip() -> CoreError {
180 CoreError::Json("reading gzip status lists needs the std feature of vouch-core".into())
181}
182
183#[cfg(not(feature = "std"))]
184fn gunzip_one_member(_data: &[u8]) -> Result<Vec<u8>> {
185 Err(no_gzip())
186}
187
188pub fn decode_bitstring(encoded: &str) -> Result<Vec<u8>> {
193 let body = encoded
194 .strip_prefix(MULTIBASE_BASE64URL_PREFIX)
195 .ok_or_else(|| CoreError::Json("encodedList must use multibase prefix 'u'".into()))?;
196 let compressed = URL_SAFE_NO_PAD
199 .decode(body)
200 .map_err(|e| CoreError::Json(format!("bad base64url: {e}")))?;
201 let out = gunzip_one_member(&compressed)?;
202 if out.len() * 8 < DEFAULT_BITSTRING_LENGTH {
203 return Err(CoreError::Json(format!(
204 "decoded bitstring length {} is below the protocol minimum ({DEFAULT_BITSTRING_LENGTH})",
205 out.len() * 8
206 )));
207 }
208 Ok(out)
209}
210
211const GZIP_HEADER: [u8; 10] = [0x1f, 0x8b, 0x08, 0x00, 0, 0, 0, 0, 0x02, 0xff];
214
215pub fn encode_bitstring(bits: &[u8]) -> Result<String> {
221 if bits.len() > MAX_DECOMPRESSED_BYTES {
222 return Err(too_large());
223 }
224 let body = crate::zdeflate::deflate_raw(bits);
225 let mut member = Vec::with_capacity(GZIP_HEADER.len() + body.len() + 8);
226 member.extend_from_slice(&GZIP_HEADER);
227 member.extend_from_slice(&body);
228 member.extend_from_slice(&crc32(bits).to_le_bytes());
229 member.extend_from_slice(&(bits.len() as u32).to_le_bytes());
230 Ok(format!(
231 "{}{}",
232 MULTIBASE_BASE64URL_PREFIX,
233 URL_SAFE_NO_PAD.encode(member)
234 ))
235}
236
237pub fn get_status(bits: &[u8], index: usize) -> Result<bool> {
239 let byte = index >> 3;
240 if byte >= bits.len() {
241 return Err(CoreError::Json(format!(
242 "index {index} out of range for {}-bit list",
243 bits.len() * 8
244 )));
245 }
246 let pos = 7 - (index % 8);
247 Ok(bits[byte] & (1 << pos) != 0)
248}
249
250pub fn set_status(bits: &mut [u8], index: usize, value: bool) -> Result<()> {
252 let byte = index >> 3;
253 if byte >= bits.len() {
254 return Err(CoreError::Json(format!("index {index} out of range")));
255 }
256 let pos = 7 - (index % 8);
257 if value {
258 bits[byte] |= 1 << pos;
259 } else {
260 bits[byte] &= !(1 << pos);
261 }
262 Ok(())
263}
264
265fn parse_index(s: &str) -> Option<usize> {
269 let b = s.as_bytes();
270 if b.is_empty() || b.len() > 10 || !b.iter().all(|c| c.is_ascii_digit()) {
271 return None;
272 }
273 if b.len() > 1 && b[0] == b'0' {
274 return None;
275 }
276 s.parse::<usize>().ok()
277}
278
279pub fn verify_status(credential_status: &Value, status_list_credential: &Value) -> Result<bool> {
294 crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential_status, status_list_credential);
295 let cs = credential_status
296 .as_object()
297 .ok_or_else(|| CoreError::Json("credentialStatus must be an object".into()))?;
298 let sl = status_list_credential
299 .as_object()
300 .ok_or_else(|| CoreError::Json("statusListCredential must be an object".into()))?;
301
302 if cs.get("type").and_then(|v| v.as_str()) != Some(BITSTRING_STATUS_LIST_ENTRY_TYPE) {
303 return Err(CoreError::Json(format!(
304 "credentialStatus.type must be {BITSTRING_STATUS_LIST_ENTRY_TYPE}"
305 )));
306 }
307 let referenced = cs
308 .get("statusListCredential")
309 .and_then(|v| v.as_str())
310 .filter(|s| !s.is_empty())
311 .ok_or_else(|| {
312 CoreError::Json("credentialStatus.statusListCredential is required".into())
313 })?;
314 if sl.get("id").and_then(|v| v.as_str()) != Some(referenced) {
315 return Err(err(
316 "status list credential id does not match the credential's statusListCredential",
317 ));
318 }
319 let has_type = sl
320 .get("type")
321 .and_then(|v| v.as_array())
322 .map(|a| {
323 a.iter()
324 .any(|t| t.as_str() == Some(BITSTRING_STATUS_LIST_CREDENTIAL_TYPE))
325 })
326 .unwrap_or(false);
327 if !has_type {
328 return Err(CoreError::Json(format!(
329 "status list type must be an array containing {BITSTRING_STATUS_LIST_CREDENTIAL_TYPE}"
330 )));
331 }
332 let subject = sl
333 .get("credentialSubject")
334 .and_then(|v| v.as_object())
335 .ok_or_else(|| CoreError::Json("status list has no credentialSubject".into()))?;
336 if subject.get("type").and_then(|v| v.as_str()) != Some(BITSTRING_STATUS_LIST_SUBJECT_TYPE) {
337 return Err(CoreError::Json(format!(
338 "credentialSubject.type must be {BITSTRING_STATUS_LIST_SUBJECT_TYPE}"
339 )));
340 }
341 let declared = cs.get("statusPurpose").and_then(|v| v.as_str());
342 match declared {
343 Some(p) if VALID_STATUS_PURPOSES.contains(&p) => {}
344 _ => {
345 return Err(err(
346 "credentialStatus.statusPurpose must be revocation, suspension or message",
347 ))
348 }
349 }
350 if declared != subject.get("statusPurpose").and_then(|v| v.as_str()) {
351 return Err(CoreError::Json("statusPurpose mismatch".into()));
352 }
353 for holder in [cs, subject] {
357 if let Some(size) = holder.get("statusSize") {
358 let one = matches!(size, Value::Number(n) if n.as_f64() == Some(1.0));
359 if !one {
360 return Err(err("statusSize must be 1 (one bit per credential)"));
361 }
362 }
363 }
364 let index = match cs.get("statusListIndex") {
365 Some(Value::String(s)) => parse_index(s).ok_or_else(|| {
366 err("statusListIndex must be a decimal string with no sign, spaces or leading zeros")
367 })?,
368 _ => return Err(err("credentialStatus.statusListIndex must be a string")),
369 };
370 let encoded = subject
371 .get("encodedList")
372 .and_then(|v| v.as_str())
373 .ok_or_else(|| CoreError::Json("credentialSubject.encodedList is required".into()))?;
374
375 let bits = decode_bitstring(encoded)?;
376 get_status(&bits, index)
377}
378
379pub const STATUS_OK: &str = "status_ok";
384pub const STATUS_NONE: &str = "no_status";
385pub const STATUS_REVOKED: &str = "revoked";
386pub const STATUS_SUSPENDED: &str = "suspended";
387pub const STATUS_UNAVAILABLE: &str = "status_unavailable";
388
389pub const MAX_STATUS_ENTRIES: usize = 8;
392
393#[derive(Debug, Clone, Copy, PartialEq, Eq)]
395pub struct StatusCheck {
396 pub ok: bool,
399 pub reason: &'static str,
402 pub detail: &'static str,
404}
405
406impl StatusCheck {
407 fn unavailable(detail: &'static str) -> Self {
408 StatusCheck {
409 ok: false,
410 reason: STATUS_UNAVAILABLE,
411 detail,
412 }
413 }
414}
415
416fn issuer_id(v: Option<&Value>) -> Option<&str> {
417 match v {
418 Some(Value::String(s)) if !s.is_empty() => Some(s),
419 Some(Value::Object(o)) => o
420 .get("id")
421 .and_then(|v| v.as_str())
422 .filter(|s| !s.is_empty()),
423 _ => None,
424 }
425}
426
427fn list_proof_ok(
440 list: &Value,
441 issuer: &str,
442 ed25519_key: &[u8],
443 mldsa44_key: Option<&[u8]>,
444 now: i128,
445 skew: i128,
446 required: crate::hybrid::Required,
447) -> core::result::Result<(), &'static str> {
448 let proofs: Vec<&Value> = match list.get("proof") {
449 Some(p @ Value::Object(_)) => vec![p],
450 Some(Value::Array(a)) => a.iter().collect(),
451 _ => Vec::new(),
452 };
453 if proofs.is_empty() || proofs.len() > 2 {
454 return Err("status list has no usable proof");
455 }
456 for p in &proofs {
457 if !p.is_object() {
458 return Err("status list proof is malformed");
459 }
460 if !crate::credentials::proof_bound_to_issuer(p, issuer) {
461 return Err("status list proof is not made by the credential issuer");
462 }
463 if !crate::credentials::proof_member_ok(p, issuer, now, skew) {
466 return Err("status list proof is malformed or expired");
467 }
468 let time = |key: &str| {
471 p.get(key)
472 .and_then(|v| v.as_str())
473 .and_then(|t| parse_protocol_time_ns(t).ok())
474 };
475 match window_state_ns(now, time("created"), time("expires"), skew) {
476 WindowState::Ok => {}
477 WindowState::NotYetValid => return Err("status list proof is created in the future"),
478 WindowState::Expired => return Err("status list proof has expired"),
479 WindowState::Inverted => return Err("status list proof expires before it is created"),
480 }
481 }
482 if proofs.len() == 1 {
483 if required.any() {
484 return Err(
485 "status list proof does not carry the post-quantum proof the verifier requires",
486 );
487 }
488 return match crate::data_integrity::verify_proof(list, ed25519_key) {
489 Ok(true) => Ok(()),
490 _ => Err("status list signature does not verify"),
491 };
492 }
493 let mut suites: Vec<&str> = proofs
494 .iter()
495 .map(|p| p.get("cryptosuite").and_then(|v| v.as_str()).unwrap_or(""))
496 .collect();
497 suites.sort_unstable();
498 if suites
499 != [
500 crate::hybrid::EDDSA_CRYPTOSUITE_ID,
501 crate::hybrid::MLDSA44_CRYPTOSUITE_ID,
502 ]
503 {
504 return Err("status list proof set is not one Ed25519 and one ML-DSA-44 proof");
505 }
506 let Some(ml) = mldsa44_key else {
507 if required.any() {
508 return Err("no key to check the status list signature with");
509 }
510 return match crate::hybrid::verify_set_known_keys(list, ed25519_key, None, None) {
513 Ok(true) => Ok(()),
514 _ => Err("status list signature does not verify"),
515 };
516 };
517 match crate::hybrid::verify_dual(list, ed25519_key, ml) {
518 Ok(true) => Ok(()),
519 _ => Err("status list signature does not verify"),
520 }
521}
522
523fn list_ok(
526 list: &Value,
527 issuer: &str,
528 ed25519_key: &[u8],
529 mldsa44_key: Option<&[u8]>,
530 now: i128,
531 skew: i128,
532 required: crate::hybrid::Required,
533) -> core::result::Result<(), &'static str> {
534 if !list.is_object() {
535 return Err("status list is not a JSON object");
536 }
537 if issuer_id(list.get("issuer")) != Some(issuer) {
538 return Err("status list issuer is not the credential issuer");
539 }
540 let bound = |key: &str| -> core::result::Result<Option<i128>, &'static str> {
541 match list.get(key) {
542 None => Ok(None),
543 Some(Value::String(s)) => parse_protocol_time_ns(s)
544 .map(Some)
545 .map_err(|_| "status list validity window is malformed"),
546 Some(_) => Err("status list validity window is malformed"),
547 }
548 };
549 match window_state_ns(now, bound("validFrom")?, bound("validUntil")?, skew) {
550 WindowState::Ok => {}
551 WindowState::Expired => return Err("status list is expired"),
552 WindowState::NotYetValid => return Err("status list is not yet valid"),
553 WindowState::Inverted => return Err("status list window is inverted"),
554 }
555 list_proof_ok(list, issuer, ed25519_key, mldsa44_key, now, skew, required)
556}
557
558pub fn check_credential_status(
586 credential: &Value,
587 status_lists: &Map<String, Value>,
588 issuer_ed25519_key: Option<&[u8]>,
589 issuer_mldsa44_key: Option<&[u8]>,
590 now_iso: &str,
591 clock_skew_seconds: i64,
592) -> Result<StatusCheck> {
593 crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential, status_lists);
594 check_credential_status_required(
595 credential,
596 status_lists,
597 issuer_ed25519_key,
598 issuer_mldsa44_key,
599 now_iso,
600 clock_skew_seconds,
601 crate::hybrid::Required::default(),
602 )
603}
604
605pub fn check_credential_status_required(
610 credential: &Value,
611 status_lists: &Map<String, Value>,
612 issuer_ed25519_key: Option<&[u8]>,
613 issuer_mldsa44_key: Option<&[u8]>,
614 now_iso: &str,
615 clock_skew_seconds: i64,
616 required: crate::hybrid::Required,
617) -> Result<StatusCheck> {
618 crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential, status_lists);
619 let skew = check_clock_skew(clock_skew_seconds)?;
620 let now = parse_protocol_time_ns(now_iso)?;
621 let Some(obj) = credential.as_object() else {
622 return Ok(StatusCheck::unavailable("credential is not an object"));
623 };
624 let Some(raw) = obj.get("credentialStatus") else {
625 return Ok(StatusCheck {
626 ok: true,
627 reason: STATUS_NONE,
628 detail: "credential carries no status entry",
629 });
630 };
631 let entries: Vec<&Value> = match raw {
632 Value::Object(_) => vec![raw],
633 Value::Array(a) => a.iter().collect(),
634 _ => Vec::new(),
635 };
636 if entries.is_empty() {
637 return Ok(StatusCheck::unavailable("credentialStatus is malformed"));
638 }
639 if entries.len() > MAX_STATUS_ENTRIES {
640 return Ok(StatusCheck::unavailable(
641 "too many credentialStatus entries",
642 ));
643 }
644 let Some(issuer) = issuer_id(obj.get("issuer")) else {
645 return Ok(StatusCheck::unavailable("credential has no issuer"));
646 };
647 let did_key = if issuer.starts_with("did:key:") {
648 crate::keys::did_key_to_ed25519(issuer).ok()
649 } else {
650 None
651 };
652 let key: Vec<u8> = match (issuer_ed25519_key, did_key) {
653 (Some(k), Some(d)) if k != d.as_slice() => {
654 return Ok(StatusCheck::unavailable(
655 "the key given is not the did:key issuer's key",
656 ))
657 }
658 (Some(k), _) => k.to_vec(),
659 (None, Some(d)) => d,
660 (None, None) => {
661 return Ok(StatusCheck::unavailable(
662 "no key to check the status list signature with",
663 ))
664 }
665 };
666
667 let mut checked: Vec<&str> = Vec::new();
668 for entry in entries {
669 if entry.get("type").and_then(|v| v.as_str()) != Some(BITSTRING_STATUS_LIST_ENTRY_TYPE) {
670 return Ok(StatusCheck::unavailable(
671 "credentialStatus entry type is not supported",
672 ));
673 }
674 let Some(url) = entry
675 .get("statusListCredential")
676 .and_then(|v| v.as_str())
677 .filter(|s| !s.is_empty())
678 else {
679 return Ok(StatusCheck::unavailable("credentialStatus is malformed"));
680 };
681 let Some(list) = status_lists.get(url) else {
682 return Ok(StatusCheck::unavailable("status list could not be fetched"));
683 };
684 if !checked.contains(&url) {
685 if let Err(detail) =
686 list_ok(list, issuer, &key, issuer_mldsa44_key, now, skew, required)
687 {
688 return Ok(StatusCheck::unavailable(detail));
689 }
690 checked.push(url);
691 }
692 let set = match verify_status(entry, list) {
693 Ok(b) => b,
694 Err(_) => {
695 return Ok(StatusCheck::unavailable(
696 "status list does not match the strict profile",
697 ))
698 }
699 };
700 if set {
701 match entry.get("statusPurpose").and_then(|v| v.as_str()) {
702 Some(STATUS_PURPOSE_REVOCATION) => {
703 return Ok(StatusCheck {
704 ok: false,
705 reason: STATUS_REVOKED,
706 detail: "credential is revoked",
707 })
708 }
709 Some(STATUS_PURPOSE_SUSPENSION) => {
710 return Ok(StatusCheck {
711 ok: false,
712 reason: STATUS_SUSPENDED,
713 detail: "credential is suspended",
714 })
715 }
716 _ => {}
717 }
718 }
719 }
720 Ok(StatusCheck {
721 ok: true,
722 reason: STATUS_OK,
723 detail: "every status entry checked",
724 })
725}
726
727fn list_shape_ok(list: &Value, purpose: Option<&str>) -> core::result::Result<String, String> {
737 let has_type = list
738 .get("type")
739 .and_then(|v| v.as_array())
740 .is_some_and(|a| {
741 a.iter()
742 .any(|t| t.as_str() == Some(BITSTRING_STATUS_LIST_CREDENTIAL_TYPE))
743 });
744 if !has_type {
745 return Err(format!(
746 "status list type must be an array containing {BITSTRING_STATUS_LIST_CREDENTIAL_TYPE}"
747 ));
748 }
749 let subject = list
750 .get("credentialSubject")
751 .and_then(|v| v.as_object())
752 .ok_or("status list has no credentialSubject")?;
753 if subject.get("type").and_then(|v| v.as_str()) != Some(BITSTRING_STATUS_LIST_SUBJECT_TYPE) {
754 return Err(format!(
755 "credentialSubject.type must be {BITSTRING_STATUS_LIST_SUBJECT_TYPE}"
756 ));
757 }
758 let declared = match subject.get("statusPurpose").and_then(|v| v.as_str()) {
759 Some(p) if VALID_STATUS_PURPOSES.contains(&p) => p,
760 _ => return Err("statusPurpose must be revocation, suspension or message".into()),
761 };
762 if purpose.is_some_and(|want| want != declared) {
763 return Err("statusPurpose mismatch".into());
764 }
765 if let Some(size) = subject.get("statusSize") {
766 if !matches!(size, Value::Number(n) if n.as_f64() == Some(1.0)) {
767 return Err("statusSize must be 1 (one bit per credential)".into());
768 }
769 }
770 let encoded = subject
771 .get("encodedList")
772 .and_then(|v| v.as_str())
773 .ok_or("credentialSubject.encodedList is required")?;
774 decode_bitstring(encoded).map_err(|e| e.to_string())?;
775 Ok(declared.to_string())
776}
777
778fn b64_key(request: &Value, name: &str) -> Result<Option<Vec<u8>>> {
779 use base64::engine::general_purpose::STANDARD;
780 match request.get(name) {
781 None | Some(Value::Null) => Ok(None),
782 Some(Value::String(s)) => STANDARD
783 .decode(s)
784 .map(Some)
785 .map_err(|_| CoreError::Json(format!("{name} must be standard base64"))),
786 Some(_) => Err(CoreError::Json(format!("{name} must be a base64 string"))),
787 }
788}
789
790pub fn rules_json(request: &Value) -> Result<Value> {
809 crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); request);
810 use serde_json::json;
811 let op = request
812 .get("op")
813 .and_then(Value::as_str)
814 .ok_or_else(|| CoreError::Json("op is required".into()))?;
815 let list = request.get("list").unwrap_or(&Value::Null);
816 match op {
817 "keysNeeded" => {
818 let proofs: Vec<&Value> = match list.get("proof") {
819 Some(p @ Value::Object(_)) => vec![p],
820 Some(Value::Array(a)) => a.iter().take(2).collect(),
821 _ => Vec::new(),
822 };
823 let wanted: Vec<Value> = proofs
824 .iter()
825 .filter_map(|p| {
826 Some(json!({
827 "cryptosuite": p.get("cryptosuite")?.as_str()?,
828 "verificationMethod": p.get("verificationMethod")?.as_str()?,
829 }))
830 })
831 .collect();
832 Ok(json!({"issuer": issuer_id(list.get("issuer")), "proofs": wanted}))
833 }
834 "validate" => {
835 let issuer = request
836 .get("issuer")
837 .and_then(Value::as_str)
838 .ok_or_else(|| CoreError::Json("issuer is required".into()))?;
839 let now = parse_protocol_time_ns(
840 request
841 .get("now")
842 .and_then(Value::as_str)
843 .ok_or_else(|| CoreError::Json("now is required".into()))?,
844 )?;
845 let skew = match request.get("clockSkewSeconds") {
846 None | Some(Value::Null) => 0,
847 Some(v) => check_clock_skew(crate::time::clock_skew_from_json(v)?)?,
848 };
849 let ed = b64_key(request, "ed25519Key")?;
850 let ml = b64_key(request, "mldsa44Key")?;
851 let purpose = request.get("purpose").and_then(Value::as_str);
852 let required = match request.get("requirePostQuantum") {
855 None => crate::hybrid::Required::default(),
856 Some(Value::Bool(b)) => crate::hybrid::Required {
857 post_quantum: *b,
858 ..Default::default()
859 },
860 Some(_) => {
861 return Err(CoreError::Json(
862 "requirePostQuantum must be true or false".into(),
863 ))
864 }
865 };
866 if crate::attenuation::json_nesting_exceeds(list, 128) {
867 return Ok(
868 json!({"ok": false, "reason": "status list is nested too deeply", "purpose": null}),
869 );
870 }
871 let checked = list_ok(
872 list,
873 issuer,
874 ed.as_deref().unwrap_or(&[]),
875 ml.as_deref(),
876 now,
877 skew,
878 required,
879 )
880 .map_err(String::from)
881 .and_then(|()| list_shape_ok(list, purpose));
882 Ok(match checked {
883 Ok(p) => json!({"ok": true, "reason": null, "purpose": p}),
884 Err(why) => json!({"ok": false, "reason": why, "purpose": null}),
885 })
886 }
887 "bit" => {
888 let entry = request.get("credentialStatus").unwrap_or(&Value::Null);
889 Ok(json!({"set": verify_status(entry, list)?}))
890 }
891 "signature" => {
892 let now = parse_protocol_time_ns(
897 request
898 .get("now")
899 .and_then(Value::as_str)
900 .ok_or_else(|| CoreError::Json("now is required".into()))?,
901 )?;
902 let skew = match request.get("clockSkewSeconds") {
903 None | Some(Value::Null) => 0,
904 Some(v) => check_clock_skew(crate::time::clock_skew_from_json(v)?)?,
905 };
906 let ed = b64_key(request, "ed25519Key")?;
907 let ml = b64_key(request, "mldsa44Key")?;
908 let refuse = |why: &str| Ok(json!({"ok": false, "reason": why}));
909 if !list.is_object() || crate::attenuation::json_nesting_exceeds(list, 128) {
910 return refuse("status list is not a JSON object");
911 }
912 let typed = list.get("type").and_then(Value::as_array).is_some_and(|t| {
913 t.iter()
914 .any(|v| v.as_str() == Some(BITSTRING_STATUS_LIST_CREDENTIAL_TYPE))
915 });
916 if !typed {
917 return refuse("status list type is not BitstringStatusListCredential");
918 }
919 let Some(issuer) = issuer_id(list.get("issuer")) else {
920 return refuse("status list names no issuer");
921 };
922 if ["validFrom", "validUntil"]
923 .iter()
924 .any(|k| list.get(*k).is_some_and(Value::is_null))
925 {
926 return refuse("status list validity window is malformed");
927 }
928 let checked = list_proof_ok(
929 list,
930 issuer,
931 ed.as_deref().unwrap_or(&[]),
932 ml.as_deref(),
933 now,
934 skew,
935 crate::hybrid::Required::default(),
936 );
937 Ok(match checked {
938 Ok(()) => json!({"ok": true, "reason": null}),
939 Err(why) => json!({"ok": false, "reason": why}),
940 })
941 }
942 "encode" => {
943 let bits = b64_key(request, "bits")?
946 .ok_or_else(|| CoreError::Json("bits is required".into()))?;
947 if bits.len() < DEFAULT_BITSTRING_LENGTH / 8 {
948 return Err(CoreError::Json(format!(
949 "bitstring length must be at least {DEFAULT_BITSTRING_LENGTH} bits"
950 )));
951 }
952 Ok(json!({"encodedList": encode_bitstring(&bits)?}))
953 }
954 "decode" => {
955 use base64::engine::general_purpose::STANDARD;
956 let encoded = request
957 .get("encodedList")
958 .and_then(Value::as_str)
959 .ok_or_else(|| CoreError::Json("encodedList must be a non-empty string".into()))?;
960 Ok(json!({"bits": STANDARD.encode(decode_bitstring(encoded)?)}))
961 }
962 other => Err(CoreError::Json(format!("unknown status list op {other:?}"))),
963 }
964}
965
966#[cfg(test)]
967mod rules_tests {
968 use super::*;
969 use crate::data_integrity::{self, BuildProofOptions};
970 use crate::keys::Ed25519KeyPair;
971 use base64::engine::general_purpose::STANDARD;
972 use serde_json::json;
973
974 const NOW: &str = "2026-06-01T00:00:00Z";
975
976 fn signed_list(kp: &Ed25519KeyPair, bit: Option<usize>) -> Value {
977 let mut bits = vec![0u8; DEFAULT_BITSTRING_LENGTH / 8];
978 if let Some(i) = bit {
979 set_status(&mut bits, i, true).unwrap();
980 }
981 let did = kp.did_key();
982 let list = json!({
983 "@context": ["https://www.w3.org/ns/credentials/v2"],
984 "id": "https://example.com/status/1",
985 "type": ["VerifiableCredential", "BitstringStatusListCredential"],
986 "issuer": did,
987 "validFrom": "2026-01-01T00:00:00Z",
988 "credentialSubject": {
989 "id": "https://example.com/status/1#list",
990 "type": "BitstringStatusList",
991 "statusPurpose": "revocation",
992 "encodedList": encode_bitstring(&bits).unwrap(),
993 }
994 });
995 let opts = BuildProofOptions::new(format!("{did}#{}", &did[8..]), "2026-01-01T00:00:00Z");
996 data_integrity::sign(&list, &kp.seed(), &opts).unwrap()
997 }
998
999 fn validate(list: &Value, issuer: &str, key: &[u8]) -> Value {
1000 rules_json(&json!({
1001 "op": "validate", "list": list, "issuer": issuer,
1002 "ed25519Key": STANDARD.encode(key), "now": NOW, "clockSkewSeconds": 30,
1003 }))
1004 .unwrap()
1005 }
1006
1007 #[test]
1008 #[cfg_attr(not(feature = "std"), ignore = "needs gunzip (std)")]
1009 fn a_signed_list_passes_and_a_tampered_one_does_not() {
1010 let kp = Ed25519KeyPair::from_seed(&[11u8; 32]);
1011 let list = signed_list(&kp, Some(5));
1012 let ok = validate(&list, &kp.did_key(), &kp.public_key());
1013 assert_eq!(ok["ok"], json!(true), "{ok}");
1014 assert_eq!(ok["purpose"], json!("revocation"));
1015
1016 let mut tampered = list.clone();
1017 tampered["credentialSubject"]["statusPurpose"] = json!("suspension");
1018 assert_eq!(
1019 validate(&tampered, &kp.did_key(), &kp.public_key())["ok"],
1020 json!(false)
1021 );
1022
1023 let other = Ed25519KeyPair::from_seed(&[12u8; 32]);
1024 assert_eq!(
1025 validate(&list, &other.did_key(), &kp.public_key())["ok"],
1026 json!(false)
1027 );
1028 assert_eq!(
1029 validate(&list, &kp.did_key(), &other.public_key())["ok"],
1030 json!(false)
1031 );
1032
1033 let wrong_purpose = rules_json(&json!({
1034 "op": "validate", "list": list, "issuer": kp.did_key(), "purpose": "suspension",
1035 "ed25519Key": STANDARD.encode(kp.public_key()), "now": NOW,
1036 }))
1037 .unwrap();
1038 assert_eq!(wrong_purpose["ok"], json!(false));
1039
1040 let expired = rules_json(&json!({
1041 "op": "validate", "list": list, "issuer": kp.did_key(),
1042 "ed25519Key": STANDARD.encode(kp.public_key()), "now": "2025-01-01T00:00:00Z",
1043 }))
1044 .unwrap();
1045 assert_eq!(expired["ok"], json!(false));
1046 }
1047
1048 #[test]
1049 #[cfg_attr(not(feature = "std"), ignore = "needs gunzip (std)")]
1050 fn keys_needed_bit_and_decode() {
1051 let kp = Ed25519KeyPair::from_seed(&[11u8; 32]);
1052 let list = signed_list(&kp, Some(5));
1053 let need = rules_json(&json!({"op": "keysNeeded", "list": list})).unwrap();
1054 assert_eq!(need["issuer"], json!(kp.did_key()));
1055 assert_eq!(need["proofs"].as_array().unwrap().len(), 1);
1056 let entry = |i: &str| {
1057 json!({"type": "BitstringStatusListEntry", "statusPurpose": "revocation",
1058 "statusListIndex": i, "statusListCredential": "https://example.com/status/1"})
1059 };
1060 let set = rules_json(&json!({"op": "bit", "credentialStatus": entry("5"), "list": list}))
1061 .unwrap();
1062 assert_eq!(set["set"], json!(true));
1063 let clear = rules_json(&json!({"op": "bit", "credentialStatus": entry("6"), "list": list}))
1064 .unwrap();
1065 assert_eq!(clear["set"], json!(false));
1066 assert!(
1067 rules_json(&json!({"op": "bit", "credentialStatus": entry("05"), "list": list}))
1068 .is_err()
1069 );
1070 let enc = list["credentialSubject"]["encodedList"].clone();
1071 let bits = rules_json(&json!({"op": "decode", "encodedList": enc})).unwrap();
1072 assert_eq!(
1073 STANDARD
1074 .decode(bits["bits"].as_str().unwrap())
1075 .unwrap()
1076 .len(),
1077 DEFAULT_BITSTRING_LENGTH / 8
1078 );
1079 assert!(rules_json(&json!({"op": "nope"})).is_err());
1080 }
1081}
1082
1083#[cfg(test)]
1084mod tests {
1085 use super::*;
1086
1087 #[test]
1088 fn malformed_encoded_list_errors_gracefully() {
1089 assert!(decode_bitstring("not-multibase").is_err()); assert!(decode_bitstring("uNotValidGzipData").is_err()); }
1092
1093 #[test]
1094 #[cfg_attr(not(feature = "std"), ignore = "needs gunzip (std)")]
1095 fn encode_decode_roundtrip_preserves_bits() {
1096 let mut bits = vec![0u8; DEFAULT_BITSTRING_LENGTH / 8];
1097 for &i in &[0usize, 1, 7, 8, 15, 100, 1023, 65535, 131070, 131071] {
1098 set_status(&mut bits, i, true).unwrap();
1099 }
1100 let encoded = encode_bitstring(&bits).unwrap();
1101 let decoded = decode_bitstring(&encoded).unwrap();
1102 assert_eq!(decoded, bits);
1103 assert!(get_status(&decoded, 100).unwrap());
1104 assert!(!get_status(&decoded, 99).unwrap());
1105 }
1106
1107 fn list_with(subject_purpose: &str) -> serde_json::Value {
1108 let bits = vec![0u8; DEFAULT_BITSTRING_LENGTH / 8];
1109 serde_json::json!({
1110 "id": "https://issuer.example/status/1",
1111 "type": ["VerifiableCredential", "BitstringStatusListCredential"],
1112 "credentialSubject": {"type": "BitstringStatusList", "statusPurpose": subject_purpose,
1113 "encodedList": encode_bitstring(&bits).unwrap()}
1114 })
1115 }
1116
1117 #[test]
1118 #[cfg_attr(not(feature = "std"), ignore = "needs gunzip (std)")]
1119 fn status_size_other_than_one_refuses() {
1120 let list = list_with("revocation");
1121 let mut entry = serde_json::json!({"type": "BitstringStatusListEntry", "statusPurpose": "revocation",
1122 "statusListIndex": "5", "statusListCredential": "https://issuer.example/status/1"});
1123 assert!(!verify_status(&entry, &list).unwrap());
1124 entry["statusSize"] = serde_json::json!(1);
1125 assert!(!verify_status(&entry, &list).unwrap());
1126 entry["statusSize"] = serde_json::json!(1.0);
1128 assert!(!verify_status(&entry, &list).unwrap());
1129 for bad in [
1130 serde_json::json!(2),
1131 serde_json::json!(0),
1132 serde_json::json!("1"),
1133 serde_json::json!(true),
1134 serde_json::json!(1.5),
1135 serde_json::Value::Null,
1136 ] {
1137 entry["statusSize"] = bad.clone();
1138 assert!(verify_status(&entry, &list).is_err(), "{bad}");
1139 }
1140 }
1141
1142 #[test]
1143 #[cfg_attr(not(feature = "std"), ignore = "needs gunzip (std)")]
1144 fn status_list_proof_created_and_expires_are_checked() {
1145 use crate::data_integrity::{sign, BuildProofOptions};
1146 let seed = [3u8; 32];
1147 let did = crate::keys::Ed25519KeyPair::from_seed(&seed).did_key();
1148 let vm = format!("{did}#{}", did.trim_start_matches("did:key:"));
1149 let mut list = list_with("revocation");
1150 list["@context"] = serde_json::json!(["https://www.w3.org/ns/credentials/v2"]);
1151 list["issuer"] = serde_json::json!(did);
1152 let cred = serde_json::json!({"issuer": did, "credentialStatus": {
1153 "type": "BitstringStatusListEntry", "statusPurpose": "revocation",
1154 "statusListIndex": "5", "statusListCredential": "https://issuer.example/status/1"}});
1155 let run = |proof_tweak: &dyn Fn(&mut serde_json::Value)| {
1156 let mut opts = BuildProofOptions::new(vm.clone(), "2026-01-01T00:00:00Z");
1157 opts.proof_purpose = "assertionMethod".into();
1158 let mut unsigned = list.clone();
1159 proof_tweak(&mut unsigned);
1160 let signed = sign(&unsigned, &seed, &opts).unwrap();
1161 let mut lists = serde_json::Map::new();
1162 lists.insert("https://issuer.example/status/1".into(), signed);
1163 check_credential_status(&cred, &lists, None, None, "2026-01-15T00:00:00Z", 0)
1164 .unwrap()
1165 .reason
1166 };
1167 assert_eq!(run(&|_| {}), STATUS_OK);
1168 assert_eq!(
1170 run(&|l| l["validUntil"] = serde_json::Value::Null),
1171 STATUS_UNAVAILABLE
1172 );
1173 let expired = |expires: serde_json::Value| {
1175 let mut opts = BuildProofOptions::new(vm.clone(), "2026-01-01T00:00:00Z");
1176 opts.proof_purpose = "assertionMethod".into();
1177 let mut proof = crate::data_integrity::build_proof(&list, &seed, &opts).unwrap();
1178 proof["expires"] = expires;
1179 let mut signed = list.clone();
1180 signed["proof"] = proof;
1181 let mut lists = serde_json::Map::new();
1182 lists.insert("https://issuer.example/status/1".into(), signed);
1183 check_credential_status(&cred, &lists, None, None, "2026-01-15T00:00:00Z", 0)
1184 .unwrap()
1185 .reason
1186 };
1187 assert_eq!(
1188 expired(serde_json::json!("2026-01-10T00:00:00Z")),
1189 STATUS_UNAVAILABLE
1190 );
1191 assert_eq!(expired(serde_json::Value::Null), STATUS_UNAVAILABLE);
1192 let mut opts = BuildProofOptions::new(vm.clone(), "yesterday");
1193 opts.proof_purpose = "assertionMethod".into();
1194 let signed = sign(&list, &seed, &opts).unwrap();
1195 let mut lists = serde_json::Map::new();
1196 lists.insert("https://issuer.example/status/1".into(), signed);
1197 assert_eq!(
1198 check_credential_status(&cred, &lists, None, None, "2026-01-15T00:00:00Z", 0)
1199 .unwrap()
1200 .reason,
1201 STATUS_UNAVAILABLE
1202 );
1203 }
1204}