Skip to main content

feedparser_rs/
limits.rs

1//! Parser limits to prevent `DoS` attacks and excessive memory usage
2
3/// Single source of truth for the parser limit fields: name, builder name, default.
4///
5/// Invokes `$callback!` with one `docs... field, setter = default;` entry per limit.
6/// Used by the core and by both language bindings so no field can be forgotten.
7#[doc(hidden)]
8#[macro_export]
9macro_rules! __parser_limit_fields {
10    ($callback:ident) => {
11        $callback! {
12            #[doc = " Maximum number of entries/items in a feed"]
13            #[doc = ""]
14            #[doc = " Prevents memory exhaustion from feeds with millions of items."]
15            #[doc = " Typical feeds have 10-100 entries, large feeds may have up to 1000."]
16            #[doc = ""]
17            #[doc = " Default: 10,000 entries"]
18            max_entries, with_max_entries = 10_000;
19            #[doc = " Maximum number of links per feed (channel-level)"]
20            #[doc = ""]
21            #[doc = " Prevents link bombing attacks."]
22            #[doc = ""]
23            #[doc = " Default: 100 links"]
24            max_links_per_feed, with_max_links_per_feed = 100;
25            #[doc = " Maximum number of links per entry"]
26            #[doc = ""]
27            #[doc = " Prevents link bombing in individual entries."]
28            #[doc = ""]
29            #[doc = " Default: 50 links"]
30            max_links_per_entry, with_max_links_per_entry = 50;
31            #[doc = " Maximum number of authors per feed or entry"]
32            #[doc = ""]
33            #[doc = " Default: 20 authors"]
34            max_authors, with_max_authors = 20;
35            #[doc = " Maximum number of contributors per feed or entry"]
36            #[doc = ""]
37            #[doc = " Default: 20 contributors"]
38            max_contributors, with_max_contributors = 20;
39            #[doc = " Maximum number of tags/categories per feed or entry"]
40            #[doc = ""]
41            #[doc = " Default: 100 tags"]
42            max_tags, with_max_tags = 100;
43            #[doc = " Maximum number of content blocks per entry"]
44            #[doc = ""]
45            #[doc = " Atom feeds can have multiple content elements."]
46            #[doc = ""]
47            #[doc = " Default: 10 content blocks"]
48            max_content_blocks, with_max_content_blocks = 10;
49            #[doc = " Maximum number of enclosures per entry"]
50            #[doc = ""]
51            #[doc = " Podcast feeds typically have 1 enclosure per episode."]
52            #[doc = ""]
53            #[doc = " Default: 20 enclosures"]
54            max_enclosures, with_max_enclosures = 20;
55            #[doc = " Maximum number of XML namespaces"]
56            #[doc = ""]
57            #[doc = " Prevents namespace pollution attacks."]
58            #[doc = ""]
59            #[doc = " Default: 100 namespaces"]
60            max_namespaces, with_max_namespaces = 100;
61            #[doc = " Maximum XML nesting depth"]
62            #[doc = ""]
63            #[doc = " Prevents stack overflow from deeply nested XML."]
64            #[doc = ""]
65            #[doc = " Default: 100 levels"]
66            max_nesting_depth, with_max_nesting_depth = 100;
67            #[doc = " Maximum HTML tag nesting depth accepted by HTML sanitization"]
68            #[doc = ""]
69            #[doc = " The HTML sanitizer's underlying HTML5 tree builder exhibits quadratic-time"]
70            #[doc = " behavior on pathologically deep tag nesting within a single text field"]
71            #[doc = " (verified: multi-second slowdown from a single deeply nested `<div>`"]
72            #[doc = " chain). Content nested deeper than this is escaped as plain text"]
73            #[doc = " (`&lt;`/`&gt;`) instead of being run through the sanitizer, bounding"]
74            #[doc = " worst-case CPU cost to linear regardless of input shape."]
75            #[doc = ""]
76            #[doc = " This is a safety bound, not a compatibility ceiling to be tuned up to"]
77            #[doc = " match \"typical\" content: exceeding it degrades gracefully (the field's"]
78            #[doc = " HTML formatting is lost, but its text content is fully preserved and"]
79            #[doc = " still safely escaped) rather than dropping data or erroring, so it is"]
80            #[doc = " safe to keep conservative. Legitimate feed content — even unusually"]
81            #[doc = " deep block-quoted reply chains or nested tables — rarely exceeds a few"]
82            #[doc = " dozen levels; 100 (50 under the strict preset) leaves headroom"]
83            #[doc = " above that without leaving much headroom for abuse."]
84            #[doc = ""]
85            #[doc = " Default: 100 levels"]
86            max_html_nesting_depth, with_max_html_nesting_depth = 100;
87            #[doc = " Maximum text field length in bytes"]
88            #[doc = ""]
89            #[doc = " Prevents excessive memory from huge title/description fields."]
90            #[doc = ""]
91            #[doc = " For JSON Feed it applies to every copied string except `version`: titles,"]
92            #[doc = " descriptions, summaries, content, tags and author names are truncated,"]
93            #[doc = " while identifiers, URLs, dates, types, language tags and extensions with"]
94            #[doc = " an over-long key are dropped, without setting `bozo`."]
95            #[doc = ""]
96            #[doc = " It also bounds the per-value serialized size of a captured JSON Feed"]
97            #[doc = " extension object (see the JSON Feed extension count limit) and its node count, to the larger of"]
98            #[doc = " 1024 and this text length divided by the size of a `serde_json::Value`."]
99            #[doc = " Every scalar, array and object is one node, and each object"]
100            #[doc = " member adds weight for its key and slot (more for the first one, which"]
101            #[doc = " allocates). A value over either bound is dropped entirely rather than truncated."]
102            #[doc = ""]
103            #[doc = " Default: 10 MB"]
104            max_text_length, with_max_text_length = 10 * 1024 * 1024;
105            #[doc = " Maximum total feed size in bytes"]
106            #[doc = ""]
107            #[doc = " The entire feed must fit within this limit."]
108            #[doc = ""]
109            #[doc = " Default: 100 MB"]
110            max_feed_size_bytes, with_max_feed_size_bytes = 100 * 1024 * 1024;
111            #[doc = " Maximum attribute value length in bytes"]
112            #[doc = ""]
113            #[doc = " XML attributes should be reasonably sized."]
114            #[doc = ""]
115            #[doc = " Default: 64 KB"]
116            max_attribute_length, with_max_attribute_length = 64 * 1024;
117            #[doc = " Maximum number of podcast soundbites per entry"]
118            #[doc = ""]
119            #[doc = " Podcast 2.0 soundbite elements for shareable clips."]
120            #[doc = ""]
121            #[doc = " Default: 10 soundbites"]
122            max_podcast_soundbites, with_max_podcast_soundbites = 10;
123            #[doc = " Maximum number of podcast transcripts per entry"]
124            #[doc = ""]
125            #[doc = " Podcast 2.0 transcript elements."]
126            #[doc = ""]
127            #[doc = " Default: 20 transcripts"]
128            max_podcast_transcripts, with_max_podcast_transcripts = 20;
129            #[doc = " Maximum number of podcast funding elements per feed"]
130            #[doc = ""]
131            #[doc = " Podcast 2.0 funding elements for donation links."]
132            #[doc = ""]
133            #[doc = " Default: 20 funding elements"]
134            max_podcast_funding, with_max_podcast_funding = 20;
135            #[doc = " Maximum number of podcast person elements per entry"]
136            #[doc = ""]
137            #[doc = " Podcast 2.0 person elements for hosts, guests, etc."]
138            #[doc = ""]
139            #[doc = " Default: 50 persons"]
140            max_podcast_persons, with_max_podcast_persons = 50;
141            #[doc = " Maximum number of podcast value recipients per feed"]
142            #[doc = ""]
143            #[doc = " Podcast 2.0 value recipients for payment splitting."]
144            #[doc = " Prevents `DoS` from feeds with excessive recipient lists."]
145            #[doc = ""]
146            #[doc = " Default: 20 recipients"]
147            max_value_recipients, with_max_value_recipients = 20;
148            #[doc = " Maximum number of alternate enclosures per entry"]
149            #[doc = ""]
150            #[doc = " Default: 20"]
151            max_podcast_alternate_enclosures, with_max_podcast_alternate_enclosures = 20;
152            #[doc = " Maximum number of sources per alternate enclosure"]
153            #[doc = ""]
154            #[doc = " Default: 10"]
155            max_podcast_alternate_enclosure_sources, with_max_podcast_alternate_enclosure_sources = 10;
156            #[doc = " Maximum number of podroll entries per feed"]
157            #[doc = ""]
158            #[doc = " Default: 50"]
159            max_podcast_podroll, with_max_podcast_podroll = 50;
160            #[doc = " Maximum number of socialInteract elements per entry"]
161            #[doc = ""]
162            #[doc = " Default: 20"]
163            max_podcast_social_interact, with_max_podcast_social_interact = 20;
164            #[doc = " Maximum number of txt records per feed or entry"]
165            #[doc = ""]
166            #[doc = " Default: 20"]
167            max_podcast_txt, with_max_podcast_txt = 20;
168            #[doc = " Maximum number of follow links per feed or entry"]
169            #[doc = ""]
170            #[doc = " Default: 20"]
171            max_podcast_follow, with_max_podcast_follow = 20;
172            #[doc = " Maximum number of chat references per feed or entry"]
173            #[doc = ""]
174            #[doc = " Podcast 2.0 chat elements pointing to chat rooms/servers."]
175            #[doc = ""]
176            #[doc = " Default: 20"]
177            max_podcast_chat, with_max_podcast_chat = 20;
178            #[doc = " Maximum number of value time splits per `podcast:value` element"]
179            #[doc = ""]
180            #[doc = " Podcast 2.0 valueTimeSplit elements for routing payments over time"]
181            #[doc = " ranges. Prevents `DoS` from feeds with excessive split lists."]
182            #[doc = ""]
183            #[doc = " Default: 20"]
184            max_podcast_value_time_splits, with_max_podcast_value_time_splits = 20;
185            #[doc = " Maximum number of JSON Feed extension objects captured per scope"]
186            #[doc = ""]
187            #[doc = " JSON Feed permits custom object keys (starting with `_` followed by a"]
188            #[doc = " letter) anywhere in a feed; this bounds how many distinct keys are"]
189            #[doc = " captured per feed-root or item-root scope, counted independently. When a"]
190            #[doc = " scope has more extension keys than this limit, the surviving keys are the"]
191            #[doc = " alphabetically-first ones, not the document-order-first ones: `serde_json`"]
192            #[doc = " backs a JSON object with a `BTreeMap` by default (the `preserve_order`"]
193            #[doc = " feature, which would switch it to an `IndexMap` and make truncation"]
194            #[doc = " document-order-first, is not enabled)."]
195            #[doc = ""]
196            #[doc = " Default: 100"]
197            max_json_extensions, with_max_json_extensions = 100;
198            #[doc = " Maximum estimated memory, in bytes, retained by all captured JSON Feed"]
199            #[doc = " extensions of one document"]
200            #[doc = ""]
201            #[doc = " The extension count limit and the text length limit bound each scope and value, but"]
202            #[doc = " not their number across items. The estimate counts keys, strings and weighted"]
203            #[doc = " nodes. Values are admitted in document order: a value that does not fit in"]
204            #[doc = " what is left is dropped, without setting `bozo`. A single value can need about"]
205            #[doc = " twice the text length limit, so raise both together."]
206            #[doc = ""]
207            #[doc = " Default: 32 MB"]
208            max_json_extension_memory_bytes, with_max_json_extension_memory_bytes = 32 * 1024 * 1024;
209            #[doc = " Maximum number of points kept per `GeoRSS` or GML geometry"]
210            #[doc = ""]
211            #[doc = " Caps the coordinate list of a line, polygon, point or box read from `GeoRSS`"]
212            #[doc = " Simple or GML elements. The coordinate text itself stays bounded by the text"]
213            #[doc = " length limit. Excess points are dropped without setting `bozo`, so a polygon may"]
214            #[doc = " be left unclosed. A geometry left with fewer points than its kind needs (1 for"]
215            #[doc = " a point, 2 for a line or box, 3 for a polygon) is dropped. W3C Basic Geo"]
216            #[doc = " latitude/longitude pairs always have one point and are not capped."]
217            #[doc = ""]
218            #[doc = " Default: 10,000 points"]
219            max_geo_points, with_max_geo_points = 10_000;
220        }
221    };
222}
223
224macro_rules! define_parser_limits {
225    ($($(#[doc = $doc:literal])* $field:ident, $setter:ident = $default:expr;)+) => {
226        /// Parser limits for protecting against denial-of-service attacks
227        ///
228        /// These limits prevent malicious or malformed feeds from causing excessive
229        /// memory allocation, deep recursion, or other resource exhaustion issues.
230        /// Every field has a `with_*` builder that replaces only that limit.
231        ///
232        /// # Examples
233        ///
234        /// ```
235        /// use feedparser_rs::ParserLimits;
236        ///
237        /// let limits = ParserLimits::default();
238        /// assert_eq!(limits.max_entries, 10_000);
239        ///
240        /// // Custom limits for restricted environments
241        /// let strict = ParserLimits::default()
242        ///     .with_max_entries(1_000)
243        ///     .with_max_feed_size_bytes(10 * 1024 * 1024); // 10MB
244        /// assert_eq!(strict.max_entries, 1_000);
245        ///
246        /// // A value over `max_json_extension_memory_bytes` is dropped without `bozo`
247        /// let limits = ParserLimits::default().with_max_json_extension_memory_bytes(0);
248        /// let data = br#"{"version":"https://jsonfeed.org/version/1.1","_x":1}"#;
249        /// let feed = feedparser_rs::parse_with_limits(data, limits)?;
250        /// assert!(feed.feed.json_extensions.is_empty());
251        /// assert!(!feed.bozo);
252        /// # Ok::<(), feedparser_rs::FeedError>(())
253        /// ```
254        #[derive(Debug, Clone, Copy, PartialEq, Eq)]
255        #[non_exhaustive]
256        pub struct ParserLimits {
257            $(
258                $(#[doc = $doc])*
259                pub $field: usize,
260            )+
261        }
262
263        impl Default for ParserLimits {
264            /// Creates default parser limits suitable for general use
265            ///
266            /// These defaults are conservative and should work for most feeds,
267            /// including large podcast feeds and news aggregators.
268            fn default() -> Self {
269                Self { $($field: $default,)+ }
270            }
271        }
272
273        impl ParserLimits {
274            $(
275                #[doc = concat!("Returns a copy with `", stringify!($field), "` replaced.")]
276                #[must_use]
277                pub const fn $setter(mut self, value: usize) -> Self {
278                    self.$field = value;
279                    self
280                }
281            )+
282        }
283    };
284}
285
286__parser_limit_fields!(define_parser_limits);
287
288impl ParserLimits {
289    /// Creates strict limits for resource-constrained environments
290    ///
291    /// Use this for embedded systems or when parsing untrusted feeds
292    /// with minimal resources.
293    ///
294    /// # Examples
295    ///
296    /// ```
297    /// use feedparser_rs::ParserLimits;
298    ///
299    /// let limits = ParserLimits::strict();
300    /// assert_eq!(limits.max_entries, 1_000);
301    /// ```
302    #[must_use]
303    pub const fn strict() -> Self {
304        Self {
305            max_entries: 1_000,
306            max_links_per_feed: 20,
307            max_links_per_entry: 10,
308            max_authors: 5,
309            max_contributors: 5,
310            max_tags: 20,
311            max_content_blocks: 3,
312            max_enclosures: 5,
313            max_namespaces: 20,
314            max_nesting_depth: 50,
315            max_html_nesting_depth: 50,
316            max_text_length: 1024 * 1024,          // 1 MB
317            max_feed_size_bytes: 10 * 1024 * 1024, // 10 MB
318            max_attribute_length: 8 * 1024,        // 8 KB
319            max_podcast_soundbites: 5,
320            max_podcast_transcripts: 5,
321            max_podcast_funding: 5,
322            max_podcast_persons: 10,
323            max_value_recipients: 5,
324            max_podcast_alternate_enclosures: 5,
325            max_podcast_alternate_enclosure_sources: 3,
326            max_podcast_podroll: 10,
327            max_podcast_social_interact: 5,
328            max_podcast_txt: 5,
329            max_podcast_follow: 5,
330            max_podcast_chat: 5,
331            max_podcast_value_time_splits: 5,
332            max_json_extensions: 20,
333            max_json_extension_memory_bytes: 4 * 1024 * 1024, // 4 MB
334            max_geo_points: 1_000,
335        }
336    }
337
338    /// Creates permissive limits for trusted feeds
339    ///
340    /// Use this only for feeds from trusted sources where you expect
341    /// large data volumes (e.g., feed archives).
342    ///
343    /// # Examples
344    ///
345    /// ```
346    /// use feedparser_rs::ParserLimits;
347    ///
348    /// let limits = ParserLimits::permissive();
349    /// assert_eq!(limits.max_entries, 100_000);
350    /// ```
351    #[must_use]
352    pub const fn permissive() -> Self {
353        Self {
354            max_entries: 100_000,
355            max_links_per_feed: 500,
356            max_links_per_entry: 200,
357            max_authors: 100,
358            max_contributors: 100,
359            max_tags: 500,
360            max_content_blocks: 50,
361            max_enclosures: 100,
362            max_namespaces: 500,
363            max_nesting_depth: 200,
364            max_html_nesting_depth: 200,
365            max_text_length: 50 * 1024 * 1024,      // 50 MB
366            max_feed_size_bytes: 500 * 1024 * 1024, // 500 MB
367            max_attribute_length: 256 * 1024,       // 256 KB
368            max_podcast_soundbites: 50,
369            max_podcast_transcripts: 100,
370            max_podcast_funding: 50,
371            max_podcast_persons: 200,
372            max_value_recipients: 50,
373            max_podcast_alternate_enclosures: 100,
374            max_podcast_alternate_enclosure_sources: 50,
375            max_podcast_podroll: 200,
376            max_podcast_social_interact: 100,
377            max_podcast_txt: 100,
378            max_podcast_follow: 100,
379            max_podcast_chat: 100,
380            max_podcast_value_time_splits: 50,
381            max_json_extensions: 500,
382            max_json_extension_memory_bytes: 256 * 1024 * 1024, // 256 MB
383            max_geo_points: 100_000,
384        }
385    }
386
387    /// Validates that a feed size is within limits
388    ///
389    /// Call this before starting to parse a feed.
390    ///
391    /// # Errors
392    ///
393    /// Returns an error if the feed exceeds `max_feed_size_bytes`.
394    pub const fn check_feed_size(&self, size: usize) -> Result<(), LimitError> {
395        if size > self.max_feed_size_bytes {
396            Err(LimitError::FeedTooLarge {
397                size,
398                max: self.max_feed_size_bytes,
399            })
400        } else {
401            Ok(())
402        }
403    }
404
405    /// Validates that a collection size is within limits
406    ///
407    /// Use this during parsing to check collection sizes.
408    ///
409    /// # Errors
410    ///
411    /// Returns an error if the collection size exceeds the specified limit.
412    pub const fn check_collection_size(
413        &self,
414        current: usize,
415        limit: usize,
416        name: &'static str,
417    ) -> Result<(), LimitError> {
418        if current >= limit {
419            Err(LimitError::CollectionTooLarge {
420                name,
421                size: current,
422                max: limit,
423            })
424        } else {
425            Ok(())
426        }
427    }
428
429    /// Validates XML nesting depth
430    ///
431    /// # Errors
432    ///
433    /// Returns an error if nesting depth exceeds `max_nesting_depth`.
434    pub const fn check_nesting_depth(&self, depth: usize) -> Result<(), LimitError> {
435        if depth > self.max_nesting_depth {
436            Err(LimitError::NestingTooDeep {
437                depth,
438                max: self.max_nesting_depth,
439            })
440        } else {
441            Ok(())
442        }
443    }
444
445    /// Validates text field length
446    ///
447    /// # Errors
448    ///
449    /// Returns an error if text length exceeds `max_text_length`.
450    pub const fn check_text_length(&self, length: usize) -> Result<(), LimitError> {
451        if length > self.max_text_length {
452            Err(LimitError::TextTooLong {
453                length,
454                max: self.max_text_length,
455            })
456        } else {
457            Ok(())
458        }
459    }
460}
461
462/// Errors that occur when parser limits are exceeded
463#[expect(
464    missing_docs,
465    reason = "variant fields are described by the `#[error]` messages"
466)]
467#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
468#[non_exhaustive]
469pub enum LimitError {
470    /// Feed size exceeds maximum allowed
471    #[error("Feed size ({size} bytes) exceeds maximum ({max} bytes)")]
472    FeedTooLarge { size: usize, max: usize },
473
474    /// Collection (entries, links, etc.) has too many items
475    #[error("Collection '{name}' has {size} items, exceeds maximum ({max})")]
476    CollectionTooLarge {
477        name: &'static str,
478        size: usize,
479        max: usize,
480    },
481
482    /// XML nesting is too deep
483    #[error("XML nesting depth ({depth}) exceeds maximum ({max})")]
484    NestingTooDeep { depth: usize, max: usize },
485
486    /// Text field is too long
487    #[error("Text field length ({length} bytes) exceeds maximum ({max} bytes)")]
488    TextTooLong { length: usize, max: usize },
489}
490
491#[cfg(test)]
492mod tests {
493    use super::*;
494    use std::assert_matches;
495
496    #[test]
497    fn test_default_limits() {
498        let limits = ParserLimits::default();
499        assert_eq!(limits.max_entries, 10_000);
500        assert_eq!(limits.max_feed_size_bytes, 100 * 1024 * 1024);
501    }
502
503    #[test]
504    fn test_strict_limits() {
505        let limits = ParserLimits::strict();
506        assert_eq!(limits.max_entries, 1_000);
507        assert!(limits.max_entries < ParserLimits::default().max_entries);
508    }
509
510    #[test]
511    fn test_permissive_limits() {
512        let limits = ParserLimits::permissive();
513        assert_eq!(limits.max_entries, 100_000);
514        assert!(limits.max_entries > ParserLimits::default().max_entries);
515    }
516
517    #[test]
518    fn test_check_feed_size_ok() {
519        let limits = ParserLimits::default();
520        assert!(limits.check_feed_size(1024).is_ok());
521    }
522
523    #[test]
524    fn test_check_feed_size_too_large() {
525        let limits = ParserLimits::default();
526        let result = limits.check_feed_size(200 * 1024 * 1024);
527        assert!(result.is_err());
528        assert_matches!(result, Err(LimitError::FeedTooLarge { .. }));
529    }
530
531    #[test]
532    fn test_check_collection_size_ok() {
533        let limits = ParserLimits::default();
534        assert!(
535            limits
536                .check_collection_size(50, limits.max_entries, "entries")
537                .is_ok()
538        );
539    }
540
541    #[test]
542    fn test_check_collection_size_too_large() {
543        let limits = ParserLimits::default();
544        let result = limits.check_collection_size(10_001, limits.max_entries, "entries");
545        assert!(result.is_err());
546        assert_matches!(result, Err(LimitError::CollectionTooLarge { .. }));
547    }
548
549    #[test]
550    fn test_check_nesting_depth_ok() {
551        let limits = ParserLimits::default();
552        assert!(limits.check_nesting_depth(50).is_ok());
553    }
554
555    #[test]
556    fn test_check_nesting_depth_too_deep() {
557        let limits = ParserLimits::default();
558        let result = limits.check_nesting_depth(101);
559        assert!(result.is_err());
560        assert_matches!(result, Err(LimitError::NestingTooDeep { .. }));
561    }
562
563    #[test]
564    fn test_check_text_length_ok() {
565        let limits = ParserLimits::default();
566        assert!(limits.check_text_length(1024).is_ok());
567    }
568
569    #[test]
570    fn test_check_text_length_too_long() {
571        let limits = ParserLimits::default();
572        let result = limits.check_text_length(20 * 1024 * 1024);
573        assert!(result.is_err());
574        assert_matches!(result, Err(LimitError::TextTooLong { .. }));
575    }
576
577    #[test]
578    fn test_limit_error_display() {
579        let err = LimitError::FeedTooLarge {
580            size: 200_000_000,
581            max: 100_000_000,
582        };
583        let msg = err.to_string();
584        assert!(msg.contains("200000000"));
585        assert!(msg.contains("100000000"));
586    }
587
588    #[test]
589    fn test_max_value_recipients_default() {
590        let limits = ParserLimits::default();
591        assert_eq!(limits.max_value_recipients, 20);
592    }
593
594    #[test]
595    fn test_max_value_recipients_strict() {
596        let limits = ParserLimits::strict();
597        assert_eq!(limits.max_value_recipients, 5);
598        assert!(limits.max_value_recipients < ParserLimits::default().max_value_recipients);
599    }
600
601    #[test]
602    fn test_max_value_recipients_permissive() {
603        let limits = ParserLimits::permissive();
604        assert_eq!(limits.max_value_recipients, 50);
605        assert!(limits.max_value_recipients > ParserLimits::default().max_value_recipients);
606    }
607
608    #[test]
609    fn test_value_recipients_limit_enforcement() {
610        let limits = ParserLimits::default();
611
612        // Within limit
613        assert!(
614            limits
615                .check_collection_size(19, limits.max_value_recipients, "value_recipients")
616                .is_ok()
617        );
618
619        // At limit
620        assert!(
621            limits
622                .check_collection_size(20, limits.max_value_recipients, "value_recipients")
623                .is_err()
624        );
625
626        // Exceeds limit
627        let result =
628            limits.check_collection_size(21, limits.max_value_recipients, "value_recipients");
629        assert!(result.is_err());
630        assert_matches!(result, Err(LimitError::CollectionTooLarge { .. }));
631    }
632
633    #[test]
634    fn test_max_podcast_chat_tiers() {
635        assert_eq!(ParserLimits::default().max_podcast_chat, 20);
636        assert_eq!(ParserLimits::strict().max_podcast_chat, 5);
637        assert_eq!(ParserLimits::permissive().max_podcast_chat, 100);
638        assert!(ParserLimits::strict().max_podcast_chat < ParserLimits::default().max_podcast_chat);
639        assert!(
640            ParserLimits::permissive().max_podcast_chat > ParserLimits::default().max_podcast_chat
641        );
642    }
643
644    #[test]
645    fn test_podcast_chat_limit_enforcement() {
646        let limits = ParserLimits::default();
647        assert!(
648            limits
649                .check_collection_size(19, limits.max_podcast_chat, "chat")
650                .is_ok()
651        );
652        let result = limits.check_collection_size(20, limits.max_podcast_chat, "chat");
653        assert!(result.is_err());
654        assert_matches!(result, Err(LimitError::CollectionTooLarge { .. }));
655    }
656
657    #[test]
658    fn test_max_podcast_value_time_splits_tiers() {
659        assert_eq!(ParserLimits::default().max_podcast_value_time_splits, 20);
660        assert_eq!(ParserLimits::strict().max_podcast_value_time_splits, 5);
661        assert_eq!(ParserLimits::permissive().max_podcast_value_time_splits, 50);
662        assert!(
663            ParserLimits::strict().max_podcast_value_time_splits
664                < ParserLimits::default().max_podcast_value_time_splits
665        );
666        assert!(
667            ParserLimits::permissive().max_podcast_value_time_splits
668                > ParserLimits::default().max_podcast_value_time_splits
669        );
670    }
671
672    #[test]
673    fn test_podcast_value_time_splits_limit_enforcement() {
674        let limits = ParserLimits::default();
675        assert!(
676            limits
677                .check_collection_size(19, limits.max_podcast_value_time_splits, "time_splits")
678                .is_ok()
679        );
680        let result =
681            limits.check_collection_size(20, limits.max_podcast_value_time_splits, "time_splits");
682        assert!(result.is_err());
683        assert_matches!(result, Err(LimitError::CollectionTooLarge { .. }));
684    }
685
686    #[test]
687    fn test_max_json_extension_memory_tiers() {
688        let tiers = [
689            ParserLimits::strict(),
690            ParserLimits::default(),
691            ParserLimits::permissive(),
692        ];
693        assert!(tiers.is_sorted_by_key(|limits| limits.max_json_extension_memory_bytes));
694        // One value of the largest allowed size must fit.
695        for limits in tiers {
696            assert!(limits.max_json_extension_memory_bytes >= 2 * limits.max_text_length);
697        }
698    }
699
700    #[test]
701    fn test_max_json_extensions_tiers() {
702        assert_eq!(ParserLimits::default().max_json_extensions, 100);
703        assert_eq!(ParserLimits::strict().max_json_extensions, 20);
704        assert_eq!(ParserLimits::permissive().max_json_extensions, 500);
705        assert!(
706            ParserLimits::strict().max_json_extensions
707                < ParserLimits::default().max_json_extensions
708        );
709        assert!(
710            ParserLimits::permissive().max_json_extensions
711                > ParserLimits::default().max_json_extensions
712        );
713    }
714}