Skip to main content

hyprstream_rpc/proof/
cbor_audit.rs

1//! Raw-byte CBOR deterministic-encoding audit.
2//!
3//! Validates RFC 8949 core deterministic encoding constraints at the byte
4//! level BEFORE `ciborium` deserializes (which resolves indefinite lengths
5//! and non-minimal integers transparently, destroying the evidence).
6//!
7//! Enforces:
8//! - No indefinite-length maps (0xBF), arrays (0x9F), or byte/text strings
9//!   (0x7B, 0x5F, 0x3F)
10//! - No CBOR tags (major type 6: 0xC0–0xDB)
11//! - No floating-point values (major type 7 simple: 0xF9, 0xFA, 0xFB for
12//!   half/single/double)
13//! - Definite-length integers are minimal (no non-minimal encodings)
14//! - No trailing bytes (for top-level items)
15//!
16//! Returns `Ok(())` if the bytes conform to RFC 8949 core deterministic
17//! encoding. Returns `Err` with a description of the violation otherwise.
18
19use anyhow::{bail, Result};
20
21// Keep raw-audit recursion aligned with the bounded Cap'n Proto decoders used
22// by the proof path. The audit runs before ciborium builds its value tree, so
23// this bound rejects deeply nested attacker input before either decoder can
24// consume unbounded stack.
25const MAX_CBOR_AUDIT_DEPTH: usize = 64;
26
27/// Audit a complete CBOR byte string for deterministic-encoding compliance.
28/// Rejects trailing data.
29pub 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
41/// Audit one CBOR data item starting at `*pos`. Returns the end position.
42fn 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    // Reject indefinite-length encodings (info == 31) for all major types
57    // except break (which is 0xFF and handled by the caller of arrays/maps).
58    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    // Reject tags (major type 6).
66    if major == 6 {
67        bail!(
68            "deterministic CBOR: tag (0x{:02x}) at byte {start} denied",
69            initial
70        );
71    }
72
73    // Reject floating-point (major type 7, info 25/26/27 = half/single/double).
74    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    // Advance past the initial byte.
82    *pos += 1;
83
84    match major {
85        0 | 1 => {
86            // Unsigned / negative integer.
87            let arg = read_arg(bytes, pos, info, initial)?;
88            // Check minimality: the argument encoding must be the shortest
89            // possible. For info 0..23 the value is inline (always minimal).
90            // For info 24 (1-byte), the value MUST be ≥ 24.
91            // For info 25 (2-byte), the value MUST be ≥ 256.
92            // For info 26 (4-byte), the value MUST be ≥ 65536.
93            // For info 27 (8-byte), the value MUST be ≥ 4294967296.
94            if info >= 24 {
95                check_int_minimal(info, arg, start, bytes)?;
96            }
97        }
98        2 | 3 => {
99            // Byte string / text string.
100            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            // Array.
117            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            // Map.
124            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                // Record the key bytes for canonical ordering check.
128                let key_start = *pos;
129                audit_one(bytes, pos, depth + 1)?;
130                let key_bytes = bytes[key_start..*pos].to_vec();
131
132                // Check canonical key ordering.
133                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 the value.
144                audit_one(bytes, pos, depth + 1)?;
145            }
146        }
147        7 => {
148            // Major type 7: simple values, float (rejected above), break.
149            if info == 31 {
150                // Break code (0xFF) should only appear inside indefinite-length
151                // containers, which we already rejected. If we reach here it's
152                // a bare break code — invalid.
153                bail!("deterministic CBOR: unexpected break code (0xFF) at byte {start}");
154            }
155            // Simple values 0..23 are inline. 24 means next byte is the value.
156            if info == 24 {
157                if *pos >= bytes.len() {
158                    bail!("deterministic CBOR: truncated simple value at byte {start}");
159                }
160                // RFC 8949: the value in the following byte MUST be ≥ 32 to
161                // be canonical (values 0..23 use inline encoding). But we
162                // don't enforce that here since it's not a security concern
163                // for this profile (simple values are not used).
164                *pos += 1;
165            }
166            // info 25/26/27 (floats) already rejected above.
167            // info 20 (False), 21 (True), 22 (Null), 23 (Undefined) are inline.
168        }
169        _ => {
170            // Major type 6 (tags) already rejected above.
171            bail!("deterministic CBOR: unexpected major type {major} at byte {start}");
172        }
173    }
174
175    Ok(*pos)
176}
177
178/// Read a CBOR argument that is used as an in-memory length or item count.
179///
180/// CBOR arguments are `u64`, while slices and loop bounds use `usize`.
181/// Refuse values that cannot be represented on this platform rather than
182/// truncating them before checking the remaining input.
183fn 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
198/// Read the argument value for a CBOR head byte.
199fn 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
254/// Check that a multi-byte integer encoding is minimal (RFC 8949 §3.1).
255fn 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        // The configured boundary remains valid for legitimate deeply nested
301        // CBOR, while one more container is rejected before ciborium runs.
302        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        // Small definite strings remain valid controls.
310        assert!(audit_deterministic(&[0x42, 0xaa, 0xbb]).is_ok());
311        assert!(audit_deterministic(&[0x62, b'o', b'k']).is_ok());
312
313        // A declared u64::MAX length must fail without wrapping either the
314        // usize conversion (on narrower targets) or the input-position add.
315        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}