1use 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
29pub 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";
38pub 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
52const 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
71fn 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 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
150pub 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 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
173pub 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
203pub 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
216pub 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
231fn 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
245pub 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 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
344pub 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
354pub const MAX_STATUS_ENTRIES: usize = 8;
357
358#[derive(Debug, Clone, Copy, PartialEq, Eq)]
360pub struct StatusCheck {
361 pub ok: bool,
364 pub reason: &'static str,
367 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
392fn 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 if !crate::credentials::proof_member_ok(p, issuer, now, skew) {
431 return Err("status list proof is malformed or expired");
432 }
433 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 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
488fn 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
523pub 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
569pub 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
690fn 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
753pub 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 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()); assert!(decode_bitstring("uNotValidGzipData").is_err()); }
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 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 assert_eq!(
1059 run(&|l| l["validUntil"] = serde_json::Value::Null),
1060 STATUS_UNAVAILABLE
1061 );
1062 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}