vouch_core/
status_list.rs1use std::io::{Read, Write};
13
14use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};
15use flate2::read::GzDecoder;
16use flate2::write::GzEncoder;
17use flate2::Compression;
18use serde_json::Value;
19
20use crate::error::{CoreError, Result};
21
22pub const DEFAULT_BITSTRING_LENGTH: usize = 131_072;
23pub const MULTIBASE_BASE64URL_PREFIX: char = 'u';
24
25pub const MAX_DECOMPRESSED_BYTES: usize = 16 * 1024 * 1024;
30
31pub const STATUS_PURPOSE_REVOCATION: &str = "revocation";
32pub const BITSTRING_STATUS_LIST_CREDENTIAL_TYPE: &str = "BitstringStatusListCredential";
33pub const BITSTRING_STATUS_LIST_SUBJECT_TYPE: &str = "BitstringStatusList";
34pub const BITSTRING_STATUS_LIST_ENTRY_TYPE: &str = "BitstringStatusListEntry";
35
36pub fn decode_bitstring(encoded: &str) -> Result<Vec<u8>> {
38 let body = encoded
39 .strip_prefix(MULTIBASE_BASE64URL_PREFIX)
40 .ok_or_else(|| CoreError::Json("encodedList must use multibase prefix 'u'".into()))?;
41 let compressed = URL_SAFE_NO_PAD
42 .decode(body)
43 .map_err(|e| CoreError::Json(format!("bad base64url: {e}")))?;
44 let gz = GzDecoder::new(&compressed[..]);
45 let mut out = Vec::new();
46 let mut limited = gz.take(MAX_DECOMPRESSED_BYTES as u64 + 1);
49 limited
50 .read_to_end(&mut out)
51 .map_err(|e| CoreError::Json(format!("gunzip failed: {e}")))?;
52 if out.len() > MAX_DECOMPRESSED_BYTES {
53 return Err(CoreError::Json(format!(
54 "decompressed status list exceeds the {MAX_DECOMPRESSED_BYTES}-byte limit"
55 )));
56 }
57 Ok(out)
58}
59
60pub fn encode_bitstring(bits: &[u8]) -> Result<String> {
69 let mut encoder = GzEncoder::new(Vec::new(), Compression::new(9));
70 encoder
71 .write_all(bits)
72 .map_err(|e| CoreError::Json(format!("gzip failed: {e}")))?;
73 let mut compressed = encoder
74 .finish()
75 .map_err(|e| CoreError::Json(format!("gzip finish failed: {e}")))?;
76 if compressed.len() >= 10 {
77 compressed[4] = 0;
78 compressed[5] = 0;
79 compressed[6] = 0;
80 compressed[7] = 0;
81 compressed[9] = 0xff;
82 }
83 Ok(format!(
84 "{}{}",
85 MULTIBASE_BASE64URL_PREFIX,
86 URL_SAFE_NO_PAD.encode(compressed)
87 ))
88}
89
90pub fn get_status(bits: &[u8], index: usize) -> Result<bool> {
92 let byte = index >> 3;
93 if byte >= bits.len() {
94 return Err(CoreError::Json(format!(
95 "index {index} out of range for {}-bit list",
96 bits.len() * 8
97 )));
98 }
99 let pos = 7 - (index % 8);
100 Ok(bits[byte] & (1 << pos) != 0)
101}
102
103pub fn set_status(bits: &mut [u8], index: usize, value: bool) -> Result<()> {
105 let byte = index >> 3;
106 if byte >= bits.len() {
107 return Err(CoreError::Json(format!("index {index} out of range")));
108 }
109 let pos = 7 - (index % 8);
110 if value {
111 bits[byte] |= 1 << pos;
112 } else {
113 bits[byte] &= !(1 << pos);
114 }
115 Ok(())
116}
117
118pub fn verify_status(credential_status: &Value, status_list_credential: &Value) -> Result<bool> {
122 let cs = credential_status
123 .as_object()
124 .ok_or_else(|| CoreError::Json("credentialStatus must be an object".into()))?;
125 let sl = status_list_credential
126 .as_object()
127 .ok_or_else(|| CoreError::Json("statusListCredential must be an object".into()))?;
128
129 if cs.get("type").and_then(|v| v.as_str()) != Some(BITSTRING_STATUS_LIST_ENTRY_TYPE) {
130 return Err(CoreError::Json(format!(
131 "credentialStatus.type must be {BITSTRING_STATUS_LIST_ENTRY_TYPE}"
132 )));
133 }
134 let referenced = cs
135 .get("statusListCredential")
136 .and_then(|v| v.as_str())
137 .ok_or_else(|| {
138 CoreError::Json("credentialStatus.statusListCredential is required".into())
139 })?;
140 let actual_id = sl.get("id").and_then(|v| v.as_str()).unwrap_or_default();
141 if actual_id != referenced {
142 return Err(CoreError::Json(format!(
143 "status list id mismatch: references {referenced}, fetched {actual_id}"
144 )));
145 }
146 let has_type = sl
147 .get("type")
148 .and_then(|v| v.as_array())
149 .map(|a| {
150 a.iter()
151 .any(|t| t.as_str() == Some(BITSTRING_STATUS_LIST_CREDENTIAL_TYPE))
152 })
153 .unwrap_or(false);
154 if !has_type {
155 return Err(CoreError::Json(format!(
156 "fetched credential is not a {BITSTRING_STATUS_LIST_CREDENTIAL_TYPE}"
157 )));
158 }
159 let subject = sl
160 .get("credentialSubject")
161 .and_then(|v| v.as_object())
162 .ok_or_else(|| CoreError::Json("status list has no credentialSubject".into()))?;
163 if subject.get("type").and_then(|v| v.as_str()) != Some(BITSTRING_STATUS_LIST_SUBJECT_TYPE) {
164 return Err(CoreError::Json(format!(
165 "credentialSubject.type must be {BITSTRING_STATUS_LIST_SUBJECT_TYPE}"
166 )));
167 }
168 if cs.get("statusPurpose").and_then(|v| v.as_str())
169 != subject.get("statusPurpose").and_then(|v| v.as_str())
170 {
171 return Err(CoreError::Json("statusPurpose mismatch".into()));
172 }
173 let encoded = subject
174 .get("encodedList")
175 .and_then(|v| v.as_str())
176 .ok_or_else(|| CoreError::Json("credentialSubject.encodedList is required".into()))?;
177
178 let index = match cs.get("statusListIndex") {
180 Some(Value::String(s)) => s
181 .parse::<usize>()
182 .map_err(|_| CoreError::Json(format!("bad statusListIndex: {s:?}")))?,
183 Some(Value::Number(n)) => n
184 .as_u64()
185 .ok_or_else(|| CoreError::Json("statusListIndex must be non-negative".into()))?
186 as usize,
187 _ => {
188 return Err(CoreError::Json(
189 "credentialStatus.statusListIndex is required".into(),
190 ))
191 }
192 };
193
194 let bits = decode_bitstring(encoded)?;
195 get_status(&bits, index)
196}
197
198#[cfg(test)]
199mod tests {
200 use super::*;
201
202 #[test]
203 fn malformed_encoded_list_errors_gracefully() {
204 assert!(decode_bitstring("not-multibase").is_err()); assert!(decode_bitstring("uNotValidGzipData").is_err()); }
207
208 #[test]
209 fn encode_decode_roundtrip_preserves_bits() {
210 let mut bits = vec![0u8; DEFAULT_BITSTRING_LENGTH / 8];
211 for &i in &[0usize, 1, 7, 8, 15, 100, 1023, 65535, 131070, 131071] {
212 set_status(&mut bits, i, true).unwrap();
213 }
214 let encoded = encode_bitstring(&bits).unwrap();
215 let decoded = decode_bitstring(&encoded).unwrap();
216 assert_eq!(decoded, bits);
217 assert!(get_status(&decoded, 100).unwrap());
218 assert!(!get_status(&decoded, 99).unwrap());
219 }
220}