Skip to main content

engram_parser/gguf/
limits.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2
3//! Explicit resource budgets for untrusted GGUF inputs.
4//!
5//! GGUF headers declare counts, string lengths, array lengths, tensor ranks,
6//! and offsets as `u64`. Those values must not drive unbounded allocation or
7//! iteration. [`ParseLimits`] is the single policy object for those checks.
8//! Default values are generous enough for production checkpoints and every
9//! committed fixture; trusted callers may raise or disable budgets without
10//! changing the default path.
11
12use crate::error::{HostSizeField, ParseLimitKind, ParserError, Result};
13
14/// Resource budgets applied before allocation or loops proportional to
15/// attacker-declared GGUF values.
16///
17/// Defaults accept large real checkpoints. Override individual fields for
18/// tighter sandboxes, or use [`ParseLimits::trusted`] when the input is
19/// already authenticated.
20#[derive(Debug, Clone, Copy, PartialEq, Eq)]
21pub struct ParseLimits {
22    /// Maximum number of KV metadata pairs.
23    pub max_kv_count: u64,
24    /// Maximum number of tensor directory entries.
25    pub max_tensor_count: u64,
26    /// Maximum UTF-8 bytes in a single GGUF string.
27    pub max_string_bytes: u64,
28    /// Maximum nested-array elements visited while skipping metadata arrays.
29    pub max_array_work_items: u64,
30    /// Maximum tensor rank (`n_dims`).
31    pub max_tensor_rank: u64,
32    /// Maximum bytes consumed by the KV metadata section.
33    pub max_metadata_bytes: u64,
34}
35
36impl ParseLimits {
37    /// Generous production defaults. Same values as [`Default`].
38    pub const DEFAULT: Self = Self {
39        max_kv_count: 1_000_000,
40        max_tensor_count: 1_000_000,
41        max_string_bytes: 16 * 1024 * 1024,
42        max_array_work_items: 16_000_000,
43        max_tensor_rank: 8,
44        max_metadata_bytes: 256 * 1024 * 1024,
45    };
46
47    /// Disable every budget (`u64::MAX`). Host-size conversions, alignment
48    /// overflow, and EOF checks still apply.
49    pub const TRUSTED: Self = Self {
50        max_kv_count: u64::MAX,
51        max_tensor_count: u64::MAX,
52        max_string_bytes: u64::MAX,
53        max_array_work_items: u64::MAX,
54        max_tensor_rank: u64::MAX,
55        max_metadata_bytes: u64::MAX,
56    };
57
58    /// Limits for already-authenticated inputs. Does not change [`Default`].
59    pub const fn trusted() -> Self {
60        Self::TRUSTED
61    }
62
63    /// Budget associated with `kind`.
64    pub const fn budget(self, kind: ParseLimitKind) -> u64 {
65        match kind {
66            ParseLimitKind::KvCount => self.max_kv_count,
67            ParseLimitKind::TensorCount => self.max_tensor_count,
68            ParseLimitKind::StringBytes => self.max_string_bytes,
69            ParseLimitKind::ArrayWorkItems => self.max_array_work_items,
70            ParseLimitKind::TensorRank => self.max_tensor_rank,
71            ParseLimitKind::MetadataBytes => self.max_metadata_bytes,
72        }
73    }
74
75    /// Fail closed when `declared` is strictly greater than the named budget.
76    pub(crate) fn reject(self, path: &str, kind: ParseLimitKind, declared: u64) -> Result<()> {
77        let budget = self.budget(kind);
78        if declared > budget {
79            Err(ParserError::limit_exceeded(path, kind, declared, budget))
80        } else {
81            Ok(())
82        }
83    }
84
85    /// Reject `declared` against `kind`, then convert it to a host `usize`.
86    pub(crate) fn bounded_usize(
87        self,
88        path: &str,
89        kind: ParseLimitKind,
90        field: HostSizeField,
91        declared: u64,
92    ) -> Result<usize> {
93        self.reject(path, kind, declared)?;
94        u64_to_usize(declared, field, path)
95    }
96}
97
98impl Default for ParseLimits {
99    fn default() -> Self {
100        Self::DEFAULT
101    }
102}
103
104/// Convert a file-declared `u64` to `usize`, naming the field on failure.
105pub(crate) fn u64_to_usize(value: u64, field: HostSizeField, path: &str) -> Result<usize> {
106    usize::try_from(value).map_err(|_| ParserError::host_size(path, field, value))
107}
108
109/// Round `value` up to a multiple of `alignment` without wrapping.
110pub(crate) fn align_up_checked(value: usize, alignment: usize, path: &str) -> Result<usize> {
111    if alignment <= 1 {
112        return Ok(value);
113    }
114    let padding = alignment - 1;
115    let padded = value
116        .checked_add(padding)
117        .ok_or_else(|| ParserError::InvalidLayout {
118            path: path.to_owned(),
119            reason: "aligned tensor data offset overflow".into(),
120        })?;
121    Ok(padded - (padded % alignment))
122}
123
124#[cfg(test)]
125mod tests {
126    use super::*;
127
128    #[test]
129    fn default_limits_are_generous_and_named() {
130        let limits = ParseLimits::default();
131        assert_eq!(limits, ParseLimits::DEFAULT);
132        assert!(limits.max_kv_count >= 1_000_000);
133        assert!(limits.max_tensor_count >= 1_000_000);
134        assert!(limits.max_string_bytes >= 1024);
135        assert!(limits.max_array_work_items >= 32);
136        assert!(limits.max_tensor_rank >= 8);
137        assert!(limits.max_metadata_bytes >= 1024);
138    }
139
140    #[test]
141    fn trusted_does_not_change_default() {
142        assert_ne!(ParseLimits::trusted(), ParseLimits::default());
143        assert_eq!(ParseLimits::trusted().max_kv_count, u64::MAX);
144        assert_eq!(ParseLimits::default().max_kv_count, 1_000_000);
145    }
146
147    #[test]
148    fn reject_is_inclusive_at_the_budget() {
149        let limits = ParseLimits {
150            max_kv_count: 4,
151            ..ParseLimits::default()
152        };
153        limits
154            .reject("mem://lim", ParseLimitKind::KvCount, 4)
155            .expect("exact budget must pass");
156        let err = limits
157            .reject("mem://lim", ParseLimitKind::KvCount, 5)
158            .unwrap_err();
159        match err {
160            ParserError::LimitExceeded {
161                limit,
162                declared,
163                budget,
164                ..
165            } => {
166                assert_eq!(limit, ParseLimitKind::KvCount);
167                assert_eq!(declared, 5);
168                assert_eq!(budget, 4);
169            }
170            other => panic!("expected LimitExceeded, got {other}"),
171        }
172    }
173
174    #[test]
175    fn u64_to_usize_reports_field_when_unrepresentable() {
176        #[cfg(target_pointer_width = "32")]
177        {
178            let err = u64_to_usize(u64::MAX, HostSizeField::StringLen, "mem://host").unwrap_err();
179            match err {
180                ParserError::HostSizeOverflow { field, value, .. } => {
181                    assert_eq!(field, HostSizeField::StringLen);
182                    assert_eq!(value, u64::MAX);
183                }
184                other => panic!("expected HostSizeOverflow, got {other}"),
185            }
186        }
187        #[cfg(not(target_pointer_width = "32"))]
188        {
189            assert_eq!(
190                u64_to_usize(u64::MAX, HostSizeField::StringLen, "mem://host").unwrap(),
191                usize::MAX
192            );
193        }
194    }
195
196    #[test]
197    fn align_up_checked_rejects_overflow() {
198        let err = align_up_checked(usize::MAX, 32, "mem://align").unwrap_err();
199        let msg = err.to_string();
200        assert!(
201            msg.contains("aligned tensor data offset overflow"),
202            "got: {msg}"
203        );
204    }
205
206    #[test]
207    fn align_up_checked_rounds_up() {
208        assert_eq!(align_up_checked(1, 32, "mem://align").unwrap(), 32);
209        assert_eq!(align_up_checked(32, 32, "mem://align").unwrap(), 32);
210        assert_eq!(align_up_checked(7, 1, "mem://align").unwrap(), 7);
211    }
212}