hyprstream_rpc/proof/
cbor_audit.rs1use anyhow::{bail, Result};
20
21const MAX_CBOR_AUDIT_DEPTH: usize = 64;
26
27pub fn audit_deterministic(bytes: &[u8]) -> Result<()> {
30 let mut pos = 0;
31 let consumed = audit_one(bytes, &mut pos, 0)?;
32 if consumed != bytes.len() {
33 bail!(
34 "deterministic CBOR: trailing data: consumed {consumed} of {} bytes",
35 bytes.len()
36 );
37 }
38 Ok(())
39}
40
41fn audit_one(bytes: &[u8], pos: &mut usize, depth: usize) -> Result<usize> {
43 if depth > MAX_CBOR_AUDIT_DEPTH {
44 bail!("deterministic CBOR: nesting exceeds depth {MAX_CBOR_AUDIT_DEPTH}");
45 }
46
47 let start = *pos;
48 if *pos >= bytes.len() {
49 bail!("deterministic CBOR: unexpected end of input");
50 }
51
52 let initial = bytes[*pos];
53 let major = initial >> 5;
54 let info = initial & 0x1f;
55
56 if info == 31 && major != 7 {
59 bail!(
60 "deterministic CBOR: indefinite-length encoding (0x{:02x}) at byte {start} denied",
61 initial
62 );
63 }
64
65 if major == 6 {
67 bail!(
68 "deterministic CBOR: tag (0x{:02x}) at byte {start} denied",
69 initial
70 );
71 }
72
73 if major == 7 && (info == 25 || info == 26 || info == 27) {
75 bail!(
76 "deterministic CBOR: floating-point value (0x{:02x}) at byte {start} denied",
77 initial
78 );
79 }
80
81 *pos += 1;
83
84 match major {
85 0 | 1 => {
86 let arg = read_arg(bytes, pos, info, initial)?;
88 if info >= 24 {
95 check_int_minimal(info, arg, start, bytes)?;
96 }
97 }
98 2 | 3 => {
99 let len = read_usize_arg(bytes, pos, info, initial, "string length")?;
101 let end = pos.checked_add(len).ok_or_else(|| {
102 anyhow::anyhow!(
103 "deterministic CBOR: {} string length {len} overflows input position at byte {start}",
104 if major == 2 { "byte" } else { "text" }
105 )
106 })?;
107 if end > bytes.len() {
108 bail!(
109 "deterministic CBOR: {} string length {len} exceeds remaining input at byte {start}",
110 if major == 2 { "byte" } else { "text" }
111 );
112 }
113 *pos = end;
114 }
115 4 => {
116 let count = read_usize_arg(bytes, pos, info, initial, "array length")?;
118 for _ in 0..count {
119 audit_one(bytes, pos, depth + 1)?;
120 }
121 }
122 5 => {
123 let count = read_usize_arg(bytes, pos, info, initial, "map length")?;
125 let mut prev_key: Option<Vec<u8>> = None;
126 for _ in 0..count {
127 let key_start = *pos;
129 audit_one(bytes, pos, depth + 1)?;
130 let key_bytes = bytes[key_start..*pos].to_vec();
131
132 if let Some(ref pk) = prev_key {
134 if key_bytes.as_slice() <= pk.as_slice() {
135 if key_bytes == *pk {
136 bail!("deterministic CBOR: duplicate map key at byte {key_start}");
137 }
138 bail!("deterministic CBOR: map keys not in canonical order at byte {key_start}");
139 }
140 }
141 prev_key = Some(key_bytes);
142
143 audit_one(bytes, pos, depth + 1)?;
145 }
146 }
147 7 => {
148 if info == 31 {
150 bail!("deterministic CBOR: unexpected break code (0xFF) at byte {start}");
154 }
155 if info == 24 {
157 if *pos >= bytes.len() {
158 bail!("deterministic CBOR: truncated simple value at byte {start}");
159 }
160 *pos += 1;
165 }
166 }
169 _ => {
170 bail!("deterministic CBOR: unexpected major type {major} at byte {start}");
172 }
173 }
174
175 Ok(*pos)
176}
177
178fn read_usize_arg(
184 bytes: &[u8],
185 pos: &mut usize,
186 info: u8,
187 initial: u8,
188 description: &str,
189) -> Result<usize> {
190 let value = read_arg(bytes, pos, info, initial)?;
191 usize::try_from(value).map_err(|_| {
192 anyhow::anyhow!(
193 "deterministic CBOR: {description} {value} does not fit this platform's address space"
194 )
195 })
196}
197
198fn read_arg(bytes: &[u8], pos: &mut usize, info: u8, initial: u8) -> Result<u64> {
200 match info {
201 0..=23 => Ok(info as u64),
202 24 => {
203 if *pos >= bytes.len() {
204 bail!("deterministic CBOR: truncated 1-byte argument at initial 0x{initial:02x}");
205 }
206 let v = bytes[*pos] as u64;
207 *pos += 1;
208 Ok(v)
209 }
210 25 => {
211 if *pos + 2 > bytes.len() {
212 bail!("deterministic CBOR: truncated 2-byte argument at initial 0x{initial:02x}");
213 }
214 let v = u16::from_be_bytes([bytes[*pos], bytes[*pos + 1]]) as u64;
215 *pos += 2;
216 Ok(v)
217 }
218 26 => {
219 if *pos + 4 > bytes.len() {
220 bail!("deterministic CBOR: truncated 4-byte argument at initial 0x{initial:02x}");
221 }
222 let v = u32::from_be_bytes([
223 bytes[*pos],
224 bytes[*pos + 1],
225 bytes[*pos + 2],
226 bytes[*pos + 3],
227 ]) as u64;
228 *pos += 4;
229 Ok(v)
230 }
231 27 => {
232 if *pos + 8 > bytes.len() {
233 bail!("deterministic CBOR: truncated 8-byte argument at initial 0x{initial:02x}");
234 }
235 let v = u64::from_be_bytes([
236 bytes[*pos],
237 bytes[*pos + 1],
238 bytes[*pos + 2],
239 bytes[*pos + 3],
240 bytes[*pos + 4],
241 bytes[*pos + 5],
242 bytes[*pos + 6],
243 bytes[*pos + 7],
244 ]);
245 *pos += 8;
246 Ok(v)
247 }
248 28..=30 => bail!("deterministic CBOR: reserved info {info} at initial 0x{initial:02x}"),
249 31 => bail!("deterministic CBOR: indefinite-length argument in definite context"),
250 _ => bail!("deterministic CBOR: invalid info {info} (impossible: info is 5-bit)"),
251 }
252}
253
254fn check_int_minimal(info: u8, arg: u64, start: usize, _bytes: &[u8]) -> Result<()> {
256 match info {
257 24 => {
258 if arg < 24 {
259 bail!(
260 "deterministic CBOR: non-minimal 1-byte integer {arg} (< 24) at byte {start}"
261 );
262 }
263 }
264 25 => {
265 if arg < 256 {
266 bail!(
267 "deterministic CBOR: non-minimal 2-byte integer {arg} (< 256) at byte {start}"
268 );
269 }
270 }
271 26 => {
272 if arg < 65536 {
273 bail!(
274 "deterministic CBOR: non-minimal 4-byte integer {arg} (< 65536) at byte {start}"
275 );
276 }
277 }
278 27 if arg < 4294967296 => {
279 bail!(
280 "deterministic CBOR: non-minimal 8-byte integer {arg} (< 4294967296) at byte {start}"
281 );
282 }
283 _ => {}
284 }
285 Ok(())
286}
287
288#[cfg(test)]
289mod tests {
290 use super::{audit_deterministic, MAX_CBOR_AUDIT_DEPTH};
291
292 fn nested_arrays(depth: usize) -> Vec<u8> {
293 let mut bytes = vec![0x81; depth];
294 bytes.push(0x00);
295 bytes
296 }
297
298 #[test]
299 fn cbor_audit_enforces_a_bounded_nesting_depth() {
300 assert!(audit_deterministic(&nested_arrays(MAX_CBOR_AUDIT_DEPTH)).is_ok());
303
304 assert!(audit_deterministic(&nested_arrays(MAX_CBOR_AUDIT_DEPTH + 1)).is_err());
305 }
306
307 #[test]
308 fn cbor_audit_rejects_unrepresentable_string_lengths() {
309 assert!(audit_deterministic(&[0x42, 0xaa, 0xbb]).is_ok());
311 assert!(audit_deterministic(&[0x62, b'o', b'k']).is_ok());
312
313 for initial in [0x5b, 0x7b] {
316 let mut malformed = vec![initial];
317 malformed.extend_from_slice(&u64::MAX.to_be_bytes());
318 assert!(audit_deterministic(&malformed).is_err());
319 }
320 }
321}