Skip to main content

codec_cbor/general/
limits.rs

1// SPDX-FileCopyrightText: 2026 ReallyMe Technologies Limited
2//
3// SPDX-License-Identifier: MIT OR Apache-2.0
4
5use super::error::{error, CborError, ErrorReason};
6use super::profile::Profile;
7
8/// Hard cap for one received input or protected output: one MiB.
9pub const MAX_BYTES: usize = 1_048_576;
10/// Hard cap for simultaneously open containers and tags.
11pub const MAX_DEPTH: usize = 64;
12/// Hard cap for structural nodes, including tags and string chunks.
13pub const MAX_NODES: usize = 65_536;
14/// Hard cap for entries in one array/map or chunks in one string.
15pub const MAX_ENTRIES: usize = 4_096;
16/// Hard cap for validation work credits.
17pub const MAX_WORK: usize = 67_108_864;
18const DEFAULT_WORK: usize = 16_777_216;
19
20const ENCODED_KEY_MAX_SCAN_NODES: usize = 1_048_576;
21const ENCODED_KEY_MAX_COMPARISON_BYTES: usize = 1_048_576;
22
23/// Caller-lowerable limits; private fields prevent bypassing hard ceilings.
24#[derive(Clone, Copy, Debug, Eq, PartialEq)]
25pub struct Limits {
26    pub(super) input: usize,
27    pub(super) output: usize,
28    pub(super) depth: usize,
29    pub(super) nodes: usize,
30    pub(super) entries: usize,
31    pub(super) bytes: usize,
32    pub(super) text: usize,
33    pub(super) work: usize,
34}
35
36macro_rules! limit {
37    ($setter:ident, $getter:ident, $field:ident, $ceiling:ident, $doc:literal) => {
38        #[doc = $doc]
39        pub fn $setter(mut self, value: usize) -> Result<Self, CborError> {
40            if value > $ceiling {
41                return Err(error(ErrorReason::InvalidLimit));
42            }
43            self.$field = value;
44            Ok(self)
45        }
46
47        #[doc = $doc]
48        #[must_use]
49        pub const fn $getter(self) -> usize {
50            self.$field
51        }
52    };
53}
54
55impl Limits {
56    limit!(
57        with_input_bytes,
58        input_bytes,
59        input,
60        MAX_BYTES,
61        "Set or inspect the maximum received input bytes."
62    );
63    limit!(
64        with_output_bytes,
65        output_bytes,
66        output,
67        MAX_BYTES,
68        "Set or inspect the maximum encoded output bytes."
69    );
70    limit!(
71        with_depth,
72        depth,
73        depth,
74        MAX_DEPTH,
75        "Set or inspect the maximum simultaneously open containers and tags."
76    );
77    limit!(
78        with_nodes,
79        nodes,
80        nodes,
81        MAX_NODES,
82        "Set or inspect the maximum structural node count."
83    );
84    limit!(
85        with_entries,
86        entries,
87        entries,
88        MAX_ENTRIES,
89        "Set or inspect the maximum entries or chunks in one container."
90    );
91    limit!(
92        with_byte_string_bytes,
93        byte_string_bytes,
94        bytes,
95        MAX_BYTES,
96        "Set or inspect aggregate byte-string content bytes."
97    );
98    limit!(
99        with_text_bytes,
100        text_bytes,
101        text,
102        MAX_BYTES,
103        "Set or inspect aggregate UTF-8 text bytes."
104    );
105    limit!(
106        with_work,
107        work,
108        work,
109        MAX_WORK,
110        "Set or inspect validation work credits, including duplicate-key comparisons."
111    );
112}
113
114impl Default for Limits {
115    fn default() -> Self {
116        Self {
117            input: MAX_BYTES,
118            output: MAX_BYTES,
119            depth: MAX_DEPTH,
120            nodes: MAX_NODES,
121            entries: MAX_ENTRIES,
122            bytes: MAX_BYTES,
123            text: MAX_BYTES,
124            work: DEFAULT_WORK,
125        }
126    }
127}
128
129pub(super) struct Budget {
130    pub(super) limits: Limits,
131    pub(super) work: usize,
132    nodes: usize,
133    bytes: usize,
134    text: usize,
135    encoded_keys: Option<EncodedKeyWork>,
136}
137
138struct EncodedKeyWork {
139    scan_nodes_left: usize,
140    comparison_bytes_left: usize,
141}
142
143impl Budget {
144    pub(super) const fn new(limits: Limits) -> Self {
145        Self {
146            limits,
147            work: 0,
148            nodes: 0,
149            bytes: 0,
150            text: 0,
151            encoded_keys: None,
152        }
153    }
154
155    pub(super) fn for_profile(limits: Limits, profile: Profile) -> Self {
156        let mut budget = Self::new(limits);
157        if profile.has_encoded_scalar_keys() {
158            budget.encoded_keys = Some(EncodedKeyWork {
159                scan_nodes_left: ENCODED_KEY_MAX_SCAN_NODES,
160                comparison_bytes_left: ENCODED_KEY_MAX_COMPARISON_BYTES,
161            });
162        }
163        budget
164    }
165
166    pub(super) const fn has_encoded_scalar_keys(&self) -> bool {
167        self.encoded_keys.is_some()
168    }
169
170    pub(super) fn encoded_key_scan_node(
171        &mut self,
172        depth: usize,
173        account: bool,
174    ) -> Result<(), CborError> {
175        if let Some(encoded_keys) = &mut self.encoded_keys {
176            if !account {
177                encoded_keys.scan_nodes_left = encoded_keys
178                    .scan_nodes_left
179                    .checked_sub(1)
180                    .ok_or(error(ErrorReason::WorkLimit))?;
181            }
182        }
183        self.check_item_depth(depth)
184    }
185
186    pub(super) fn check_item_depth(&self, depth: usize) -> Result<(), CborError> {
187        // The encoded-key preflight limits visited nodes. An empty container
188        // at the last allowed depth has no deeper node to visit.
189        if self.has_encoded_scalar_keys() && depth > self.limits.depth {
190            return Err(error(ErrorReason::DepthLimit));
191        }
192        Ok(())
193    }
194
195    pub(super) fn encoded_key_compare_bytes(
196        &mut self,
197        left: usize,
198        right: usize,
199    ) -> Result<(), CborError> {
200        let cost = left
201            .checked_add(right)
202            .ok_or(error(ErrorReason::ArithmeticOverflow))?;
203        self.charge(cost)?;
204        let encoded_keys = self
205            .encoded_keys
206            .as_mut()
207            .ok_or(error(ErrorReason::UnsupportedPolicy))?;
208        encoded_keys.comparison_bytes_left = encoded_keys
209            .comparison_bytes_left
210            .checked_sub(cost)
211            .ok_or(error(ErrorReason::WorkLimit))?;
212        Ok(())
213    }
214
215    pub(super) fn charge(&mut self, amount: usize) -> Result<(), CborError> {
216        self.work = self
217            .work
218            .checked_add(amount)
219            .ok_or(error(ErrorReason::ArithmeticOverflow))?;
220        if self.work > self.limits.work {
221            return Err(error(ErrorReason::WorkLimit));
222        }
223        Ok(())
224    }
225
226    pub(super) fn node(&mut self) -> Result<(), CborError> {
227        self.nodes = self
228            .nodes
229            .checked_add(1)
230            .ok_or(error(ErrorReason::ArithmeticOverflow))?;
231        if self.nodes > self.limits.nodes {
232            return Err(error(ErrorReason::NodeLimit));
233        }
234        Ok(())
235    }
236
237    pub(super) fn declared_nodes(&self, count: usize) -> Result<(), CborError> {
238        let total = self
239            .nodes
240            .checked_add(count)
241            .ok_or(error(ErrorReason::ArithmeticOverflow))?;
242        if total > self.limits.nodes {
243            return Err(error(ErrorReason::NodeLimit));
244        }
245        let work = self
246            .work
247            .checked_add(count)
248            .ok_or(error(ErrorReason::ArithmeticOverflow))?;
249        if work > self.limits.work {
250            return Err(error(ErrorReason::WorkLimit));
251        }
252        Ok(())
253    }
254
255    pub(super) fn contents(&mut self, amount: usize, text: bool) -> Result<(), CborError> {
256        let (count, limit, reason) = if text {
257            (&mut self.text, self.limits.text, ErrorReason::TextLimit)
258        } else {
259            (
260                &mut self.bytes,
261                self.limits.bytes,
262                ErrorReason::ByteStringLimit,
263            )
264        };
265        *count = count
266            .checked_add(amount)
267            .ok_or(error(ErrorReason::ArithmeticOverflow))?;
268        if *count > limit {
269            return Err(error(reason));
270        }
271        Ok(())
272    }
273
274    pub(super) fn enter(&self, depth: usize) -> Result<usize, CborError> {
275        let next = depth
276            .checked_add(1)
277            .ok_or(error(ErrorReason::ArithmeticOverflow))?;
278        if !self.has_encoded_scalar_keys() && next > self.limits.depth {
279            return Err(error(ErrorReason::DepthLimit));
280        }
281        Ok(next)
282    }
283}