form_net/limits.rs
1//! Budgets ([`Limits`]) and behaviours ([`Policy`]).
2//!
3//! Both are small `Copy` values with `const` setters, so a route's
4//! configuration is a `const` checked once at startup.
5
6use crate::error::{FormError, Limit};
7
8/// The bytes the multipart parser keeps for the `_charset_` field's value.
9pub(crate) const CHARSET_CAPTURE: usize = 32;
10
11/// Every budget form-net enforces.
12///
13/// Each budget is checked before the bytes it governs are buffered, stored,
14/// or passed on. A limit of 0 means none allowed. A limit larger than the one
15/// containing it is capped by it (the effective value is the smaller), so a
16/// route sets only the limits it cares about.
17///
18/// | Field | Default |
19/// |---|---|
20/// | `max_body_bytes` | 10 MiB |
21/// | `max_fields` | 1,000 |
22/// | `max_name_bytes` | 256 |
23/// | `max_value_bytes` | 1 MiB |
24/// | `max_text_bytes` | 2 MiB |
25/// | `max_parts` | 100 |
26/// | `max_files` | 20 |
27/// | `max_file_bytes` | 10 MiB |
28/// | `max_part_header_bytes` | 8 KiB |
29/// | `max_part_headers` | 8 |
30/// | `max_filename_bytes` | 1,024 |
31/// | `max_preamble_bytes` | 1 KiB |
32/// | `max_epilogue_bytes` | 1 KiB |
33/// | `max_padding_bytes` | 32 |
34/// | `sniff_bytes` | 512 |
35/// | `max_token_bytes` | 128 |
36///
37/// # Examples
38///
39/// ```
40/// use form_net::Limits;
41///
42/// // A login route: a small body, a few fields, no files.
43/// const LOGIN: Limits = Limits::DEFAULT
44/// .with_max_body_bytes(4 * 1024)
45/// .with_max_fields(8)
46/// .with_max_files(0);
47/// assert!(LOGIN.validate().is_ok());
48/// ```
49#[non_exhaustive]
50#[derive(Clone, Copy, Debug, PartialEq, Eq)]
51pub struct Limits {
52 /// Every byte fed, both formats, preamble and epilogue included.
53 pub max_body_bytes: u64,
54 /// urlencoded pairs; multipart text fields.
55 pub max_fields: u32,
56 /// Raw (encoded) name length. Capped by `max_body_bytes`.
57 pub max_name_bytes: u32,
58 /// One urlencoded value or one multipart text field. Capped by
59 /// `max_text_bytes`.
60 pub max_value_bytes: u32,
61 /// All text values of one body together. Capped by `max_body_bytes`.
62 pub max_text_bytes: u64,
63 /// Multipart parts of either kind.
64 pub max_parts: u32,
65 /// Multipart file parts.
66 pub max_files: u32,
67 /// One file part. Capped by `max_body_bytes`.
68 pub max_file_bytes: u64,
69 /// One part's header block, CRLF CRLF included (at least 64).
70 pub max_part_header_bytes: u32,
71 /// Header lines per part.
72 pub max_part_headers: u16,
73 /// A raw `filename`, or a decoded `filename*`. Capped by
74 /// `max_part_header_bytes`.
75 pub max_filename_bytes: u32,
76 /// Bytes before the first delimiter. Capped by `max_body_bytes`.
77 pub max_preamble_bytes: u32,
78 /// Bytes after the close delimiter. Capped by `max_body_bytes`.
79 pub max_epilogue_bytes: u32,
80 /// Transport padding after a delimiter.
81 pub max_padding_bytes: u8,
82 /// The sniff window per file part (0: off). Capped by `max_file_bytes`.
83 pub sniff_bytes: u32,
84 /// The captured anti-forgery token. Capped by `max_value_bytes`.
85 pub max_token_bytes: u16,
86}
87
88macro_rules! setter {
89 ($(#[$doc:meta])* $name:ident, $field:ident, $ty:ty) => {
90 $(#[$doc])*
91 #[must_use]
92 pub const fn $name(mut self, value: $ty) -> Self {
93 self.$field = value;
94 self
95 }
96 };
97}
98
99const fn min_u64(a: u64, b: u64) -> u64 {
100 if a < b { a } else { b }
101}
102
103/// `value` as `usize`, or `usize::MAX` when it does not fit.
104#[cfg(feature = "alloc")]
105const fn to_usize(value: u64) -> usize {
106 if value > usize::MAX as u64 {
107 usize::MAX
108 } else {
109 value as usize
110 }
111}
112
113const fn add_usize(a: usize, b: usize) -> usize {
114 match a.checked_add(b) {
115 Some(v) => v,
116 None => usize::MAX,
117 }
118}
119
120impl Limits {
121 /// The defaults in the table above.
122 pub const DEFAULT: Limits = Limits {
123 max_body_bytes: 10 * 1024 * 1024,
124 max_fields: 1_000,
125 max_name_bytes: 256,
126 max_value_bytes: 1024 * 1024,
127 max_text_bytes: 2 * 1024 * 1024,
128 max_parts: 100,
129 max_files: 20,
130 max_file_bytes: 10 * 1024 * 1024,
131 max_part_header_bytes: 8 * 1024,
132 max_part_headers: 8,
133 max_filename_bytes: 1_024,
134 max_preamble_bytes: 1_024,
135 max_epilogue_bytes: 1_024,
136 max_padding_bytes: 32,
137 sniff_bytes: 512,
138 max_token_bytes: 128,
139 };
140
141 setter!(
142 /// Sets `max_body_bytes`.
143 with_max_body_bytes, max_body_bytes, u64);
144 setter!(
145 /// Sets `max_fields`.
146 with_max_fields, max_fields, u32);
147 setter!(
148 /// Sets `max_name_bytes`.
149 with_max_name_bytes, max_name_bytes, u32);
150 setter!(
151 /// Sets `max_value_bytes`.
152 with_max_value_bytes, max_value_bytes, u32);
153 setter!(
154 /// Sets `max_text_bytes`.
155 with_max_text_bytes, max_text_bytes, u64);
156 setter!(
157 /// Sets `max_parts`.
158 with_max_parts, max_parts, u32);
159 setter!(
160 /// Sets `max_files`.
161 with_max_files, max_files, u32);
162 setter!(
163 /// Sets `max_file_bytes`.
164 with_max_file_bytes, max_file_bytes, u64);
165 setter!(
166 /// Sets `max_part_header_bytes`.
167 with_max_part_header_bytes, max_part_header_bytes, u32);
168 setter!(
169 /// Sets `max_part_headers`.
170 with_max_part_headers, max_part_headers, u16);
171 setter!(
172 /// Sets `max_filename_bytes`.
173 with_max_filename_bytes, max_filename_bytes, u32);
174 setter!(
175 /// Sets `max_preamble_bytes`.
176 with_max_preamble_bytes, max_preamble_bytes, u32);
177 setter!(
178 /// Sets `max_epilogue_bytes`.
179 with_max_epilogue_bytes, max_epilogue_bytes, u32);
180 setter!(
181 /// Sets `max_padding_bytes`.
182 with_max_padding_bytes, max_padding_bytes, u8);
183 setter!(
184 /// Sets `sniff_bytes`.
185 with_sniff_bytes, sniff_bytes, u32);
186 setter!(
187 /// Sets `max_token_bytes`.
188 with_max_token_bytes, max_token_bytes, u16);
189
190 /// Refuses the values no body could satisfy, so a misconfiguration is
191 /// found at startup: a `max_part_header_bytes` below 64 (the shortest
192 /// useful `Content-Disposition` line must fit), or buffer sizes that do
193 /// not fit in `usize`. Every parser constructor and every `*_with`
194 /// function calls it.
195 ///
196 /// # Errors
197 ///
198 /// [`FormError::InvalidLimits`] naming the refused field.
199 ///
200 /// # Examples
201 ///
202 /// ```
203 /// use form_net::Limits;
204 ///
205 /// assert!(Limits::DEFAULT.validate().is_ok());
206 /// let broken = Limits::DEFAULT.with_max_part_header_bytes(16);
207 /// assert_eq!(broken.validate().unwrap_err().code(), "invalid_limits");
208 /// ```
209 pub fn validate(&self) -> Result<(), FormError> {
210 if self.max_part_header_bytes < 64 {
211 return Err(FormError::InvalidLimits {
212 limit: Limit::PartHeaderBytes,
213 });
214 }
215 let parts = [
216 u64::from(self.max_part_header_bytes),
217 u64::from(self.name()),
218 u64::from(self.filename()),
219 u64::from(self.token()),
220 CHARSET_CAPTURE as u64,
221 ];
222 let total = parts.iter().fold(0u64, |a, &b| a.saturating_add(b));
223 if total > usize::MAX as u64 {
224 return Err(FormError::InvalidLimits {
225 limit: Limit::PartHeaderBytes,
226 });
227 }
228 let url = u64::from(self.name())
229 .saturating_add(u64::from(self.value()))
230 .saturating_add(1);
231 if url > usize::MAX as u64 {
232 return Err(FormError::InvalidLimits {
233 limit: Limit::ValueLength,
234 });
235 }
236 Ok(())
237 }
238
239 /// Validates these limits together with a policy: a token field with an
240 /// effective `max_token_bytes` of 0 can never be captured.
241 pub(crate) fn validate_with(&self, policy: &crate::Policy) -> Result<(), FormError> {
242 self.validate()?;
243 if policy.token_field.is_some() && self.token() == 0 {
244 return Err(FormError::InvalidLimits {
245 limit: Limit::TokenLength,
246 });
247 }
248 Ok(())
249 }
250
251 /// The buffer length the multipart parser needs with these limits and
252 /// this policy: the header block, the decoded field name, the decoded
253 /// `filename*` (only under `ExtendedFilenamePolicy::AcceptAlone`), the
254 /// token (only with a token field), and 32 bytes for `_charset_`.
255 ///
256 /// A `const fn`, so a stack buffer can be sized at compile time.
257 ///
258 /// # Examples
259 ///
260 /// ```
261 /// use form_net::{Limits, Policy};
262 ///
263 /// const LIMITS: Limits = Limits::DEFAULT.with_max_part_header_bytes(1024);
264 /// const LEN: usize = LIMITS.multipart_buffer_len(&Policy::DEFAULT);
265 /// assert_eq!(LEN, 1024 + 256 + 32);
266 /// let buffer = [0u8; LEN];
267 /// ```
268 #[must_use]
269 pub const fn multipart_buffer_len(&self, policy: &crate::Policy) -> usize {
270 let mut len = add_usize(self.max_part_header_bytes as usize, self.name() as usize);
271 if matches!(
272 policy.extended_filename,
273 crate::ExtendedFilenamePolicy::AcceptAlone
274 ) {
275 len = add_usize(len, self.filename() as usize);
276 }
277 if policy.token_field.is_some() {
278 len = add_usize(len, self.token() as usize);
279 }
280 add_usize(len, CHARSET_CAPTURE)
281 }
282
283 /// The scratch length the streaming urlencoded parser needs:
284 /// `max_name_bytes + max_value_bytes + 1` (effective values).
285 ///
286 /// # Examples
287 ///
288 /// ```
289 /// use form_net::Limits;
290 ///
291 /// const LIMITS: Limits = Limits::DEFAULT.with_max_text_bytes(1000);
292 /// assert_eq!(LIMITS.urlencoded_buffer_len(), 256 + 1000 + 1);
293 /// ```
294 #[must_use]
295 pub const fn urlencoded_buffer_len(&self) -> usize {
296 add_usize(add_usize(self.name() as usize, self.value() as usize), 1)
297 }
298
299 /// The worst-case bytes one parse with these limits can hold in memory,
300 /// for admission control before a body is read (FR-40, D-093).
301 ///
302 /// The sum of: parser state (256); the parser buffer and the driver's
303 /// copy of the current part head (each `multipart_buffer_len` under the
304 /// most demanding policy); the sniff window; the field being received
305 /// (`max_value_bytes`); the text kept (`max_text_bytes`) and its names
306 /// (`max_fields × max_name_bytes`, capped by `max_body_bytes`); 96 bytes
307 /// of index per field and 320 per part; owned copies of part names, file
308 /// names, and content types (`max_parts × max_part_header_bytes`, capped
309 /// by `max_body_bytes`); the files kept in memory,
310 /// `max_files × min(file_in_memory_bytes, max_file_bytes)`, capped by
311 /// twice `max_body_bytes` (a buffer that grew by doubling can hold twice
312 /// its bytes); and half the largest growing buffer (a buffer that
313 /// doubles holds its old half while it moves). `file_in_memory_bytes`
314 /// is the most bytes of one file a store keeps in memory
315 /// (`Store::memory_bound` passes it). The caller's own read buffer is
316 /// not included. All values are effective values; the arithmetic
317 /// saturates. `tests/memory_bound.rs` measures it against hostile bodies.
318 ///
319 /// # Examples
320 ///
321 /// ```
322 /// use form_net::Limits;
323 ///
324 /// const LOGIN: Limits = Limits::DEFAULT
325 /// .with_max_body_bytes(4 * 1024)
326 /// .with_max_fields(8)
327 /// .with_max_parts(8)
328 /// .with_max_files(0)
329 /// .with_max_part_header_bytes(1024);
330 /// assert!(LOGIN.memory_bound(64 * 1024) < 32 * 1024);
331 /// // The defaults with files over 64 KiB spilled: about 6.5 MiB.
332 /// assert!(Limits::DEFAULT.memory_bound(64 * 1024) < 7 << 20);
333 /// ```
334 #[must_use]
335 pub const fn memory_bound(&self, file_in_memory_bytes: u64) -> u64 {
336 const PARSER_STATE: u64 = 256;
337 const FIELD_INDEX: u64 = 96;
338 const PART_INDEX: u64 = 320;
339 let head = (self.max_part_header_bytes as u64)
340 .saturating_add(self.name() as u64)
341 .saturating_add(self.filename() as u64)
342 .saturating_add(self.token() as u64)
343 .saturating_add(CHARSET_CAPTURE as u64);
344 let parts = self.max_parts as u64;
345 let copies = min_u64(
346 parts.saturating_mul(self.max_part_header_bytes as u64),
347 self.body(),
348 );
349 let sniff = min_u64(self.sniff_bytes as u64, self.file());
350 let file = min_u64(file_in_memory_bytes, self.file());
351 let files = min_u64(
352 (self.max_files as u64).saturating_mul(file),
353 self.body().saturating_mul(2),
354 );
355 let text = self.text_and_names();
356 let growth = if file > text { file } else { text } / 2;
357 PARSER_STATE
358 .saturating_add(head.saturating_mul(2))
359 .saturating_add(sniff)
360 .saturating_add(self.value() as u64)
361 .saturating_add(text)
362 .saturating_add((self.max_fields as u64).saturating_mul(FIELD_INDEX))
363 .saturating_add(parts.saturating_mul(PART_INDEX))
364 .saturating_add(copies)
365 .saturating_add(files)
366 .saturating_add(growth)
367 }
368
369 /// The text values and field names one body can hold: `max_text_bytes`
370 /// plus `max_fields × max_name_bytes`, the latter capped by
371 /// `max_body_bytes` (effective values).
372 pub(crate) const fn text_and_names(&self) -> u64 {
373 let names = min_u64(
374 (self.max_fields as u64).saturating_mul(self.name() as u64),
375 self.body(),
376 );
377 self.text().saturating_add(names)
378 }
379
380 // Effective values: each capped by the limit that contains it.
381
382 pub(crate) const fn body(&self) -> u64 {
383 self.max_body_bytes
384 }
385
386 pub(crate) const fn text(&self) -> u64 {
387 min_u64(self.max_text_bytes, self.body())
388 }
389
390 pub(crate) const fn value(&self) -> u32 {
391 min_u64(self.max_value_bytes as u64, self.text()) as u32
392 }
393
394 pub(crate) const fn name(&self) -> u32 {
395 min_u64(self.max_name_bytes as u64, self.body()) as u32
396 }
397
398 pub(crate) const fn file(&self) -> u64 {
399 min_u64(self.max_file_bytes, self.body())
400 }
401
402 #[cfg(feature = "alloc")]
403 pub(crate) const fn sniff(&self) -> u32 {
404 min_u64(self.sniff_bytes as u64, self.file()) as u32
405 }
406
407 pub(crate) const fn filename(&self) -> u32 {
408 min_u64(
409 self.max_filename_bytes as u64,
410 self.max_part_header_bytes as u64,
411 ) as u32
412 }
413
414 pub(crate) const fn token(&self) -> u16 {
415 min_u64(self.max_token_bytes as u64, self.value() as u64) as u16
416 }
417
418 pub(crate) const fn preamble(&self) -> u64 {
419 min_u64(self.max_preamble_bytes as u64, self.body())
420 }
421
422 pub(crate) const fn epilogue(&self) -> u64 {
423 min_u64(self.max_epilogue_bytes as u64, self.body())
424 }
425
426 #[cfg(feature = "alloc")]
427 pub(crate) const fn body_usize(&self) -> usize {
428 to_usize(self.body())
429 }
430}
431
432impl Default for Limits {
433 fn default() -> Self {
434 Self::DEFAULT
435 }
436}
437
438/// The behaviours a route may choose. The defaults are the strict ones;
439/// every alternative is named after what it allows.
440///
441/// # Examples
442///
443/// ```
444/// use form_net::{EmptyFilePolicy, HeaderPolicy, Policy, TokenField};
445///
446/// const UPLOADS: Policy = Policy::DEFAULT
447/// .with_token_field(TokenField::new("csrf_token"))
448/// .with_empty_files(EmptyFilePolicy::Skip)
449/// .with_unknown_headers(HeaderPolicy::Refuse);
450/// assert_eq!(UPLOADS.token_field.map(|t| t.name()), Some("csrf_token"));
451/// ```
452#[non_exhaustive]
453#[derive(Clone, Copy, Debug, PartialEq, Eq)]
454pub struct Policy {
455 /// A malformed `%` in urlencoded input. Default `Refuse`.
456 pub percent: PercentPolicy,
457 /// `filename*` in a part. Default `Refuse`.
458 pub extended_filename: ExtendedFilenamePolicy,
459 /// Part headers other than the three known ones. Default `Ignore`.
460 pub unknown_headers: HeaderPolicy,
461 /// A file input left empty. Default `Report`.
462 pub empty_files: EmptyFilePolicy,
463 /// The anti-forgery token field to capture. Default none.
464 pub token_field: Option<TokenField>,
465}
466
467impl Policy {
468 /// The strict defaults.
469 pub const DEFAULT: Policy = Policy {
470 percent: PercentPolicy::Refuse,
471 extended_filename: ExtendedFilenamePolicy::Refuse,
472 unknown_headers: HeaderPolicy::Ignore,
473 empty_files: EmptyFilePolicy::Report,
474 token_field: None,
475 };
476
477 /// Sets `percent`.
478 #[must_use]
479 pub const fn with_percent(mut self, policy: PercentPolicy) -> Self {
480 self.percent = policy;
481 self
482 }
483
484 /// Sets `extended_filename`.
485 #[must_use]
486 pub const fn with_extended_filename(mut self, policy: ExtendedFilenamePolicy) -> Self {
487 self.extended_filename = policy;
488 self
489 }
490
491 /// Sets `unknown_headers`.
492 #[must_use]
493 pub const fn with_unknown_headers(mut self, policy: HeaderPolicy) -> Self {
494 self.unknown_headers = policy;
495 self
496 }
497
498 /// Sets `empty_files`.
499 #[must_use]
500 pub const fn with_empty_files(mut self, policy: EmptyFilePolicy) -> Self {
501 self.empty_files = policy;
502 self
503 }
504
505 /// Sets the token field to capture.
506 #[must_use]
507 pub const fn with_token_field(mut self, field: TokenField) -> Self {
508 self.token_field = Some(field);
509 self
510 }
511}
512
513impl Default for Policy {
514 fn default() -> Self {
515 Self::DEFAULT
516 }
517}
518
519/// What a `%` not followed by two hex digits means in urlencoded input.
520///
521/// # Examples
522///
523/// ```
524/// use form_net::{decode_into, PercentPolicy};
525///
526/// let mut out = [0u8; 8];
527/// assert!(decode_into(b"100%", &mut out, PercentPolicy::Refuse).is_err());
528/// assert_eq!(decode_into(b"100%", &mut out, PercentPolicy::Literal)?, "100%");
529/// # Ok::<(), form_net::FormError>(())
530/// ```
531#[non_exhaustive]
532#[derive(Clone, Copy, Debug, PartialEq, Eq)]
533pub enum PercentPolicy {
534 /// Refuse it (default).
535 Refuse,
536 /// Keep it as a literal byte, as WHATWG percent-decode does.
537 Literal,
538}
539
540/// What a `filename*` parameter (RFC 8187) in a part means. Browsers never
541/// send it; RFC 7578 forbids senders from using it.
542///
543/// Both `filename` and `filename*` in one part are refused under every
544/// policy.
545///
546/// # Examples
547///
548/// ```
549/// use form_net::{ExtendedFilenamePolicy, Policy};
550///
551/// let accept = Policy::DEFAULT.with_extended_filename(ExtendedFilenamePolicy::AcceptAlone);
552/// assert_eq!(Policy::DEFAULT.extended_filename, ExtendedFilenamePolicy::Refuse);
553/// assert_ne!(accept, Policy::DEFAULT);
554/// ```
555#[non_exhaustive]
556#[derive(Clone, Copy, Debug, PartialEq, Eq)]
557pub enum ExtendedFilenamePolicy {
558 /// Refuse any `filename*` (default).
559 Refuse,
560 /// Accept and decode it (UTF-8 only) when it is the only file name.
561 AcceptAlone,
562 /// Drop it; a part with only `filename*` is then a text field.
563 Ignore,
564}
565
566/// Part headers other than `Content-Disposition`, `Content-Type`, and
567/// `Content-Transfer-Encoding`.
568///
569/// # Examples
570///
571/// ```
572/// use form_net::{HeaderPolicy, Policy};
573///
574/// assert_eq!(Policy::DEFAULT.unknown_headers, HeaderPolicy::Ignore);
575/// ```
576#[non_exhaustive]
577#[derive(Clone, Copy, Debug, PartialEq, Eq)]
578pub enum HeaderPolicy {
579 /// Skip them, as RFC 7578 section 4.8 requires (default). They still
580 /// count toward the header budgets.
581 Ignore,
582 /// Refuse them.
583 Refuse,
584}
585
586/// A file input left empty (`filename=""` and no data).
587///
588/// # Examples
589///
590/// ```
591/// use form_net::{EmptyFilePolicy, Policy};
592///
593/// assert_eq!(Policy::DEFAULT.empty_files, EmptyFilePolicy::Report);
594/// ```
595#[non_exhaustive]
596#[derive(Clone, Copy, Debug, PartialEq, Eq)]
597pub enum EmptyFilePolicy {
598 /// Report it as a file part with an empty file name (default).
599 Report,
600 /// Produce nothing for it; it does not count against `max_files`.
601 Skip,
602}
603
604/// The anti-forgery token field to capture from a multipart body.
605///
606/// # Examples
607///
608/// ```
609/// use form_net::{TokenField, TokenPlacement};
610///
611/// let strict = TokenField::new("csrf_token");
612/// assert_eq!(strict.placement(), TokenPlacement::BeforeFirstFile);
613/// assert_eq!(strict.anywhere().placement(), TokenPlacement::Anywhere);
614/// ```
615#[derive(Clone, Copy, Debug, PartialEq, Eq)]
616pub struct TokenField {
617 name: &'static str,
618 placement: TokenPlacement,
619}
620
621impl TokenField {
622 /// A token field named `name` that must come before the first file.
623 #[must_use]
624 pub const fn new(name: &'static str) -> TokenField {
625 TokenField {
626 name,
627 placement: TokenPlacement::BeforeFirstFile,
628 }
629 }
630
631 /// The same field, allowed anywhere in the body.
632 #[must_use]
633 pub const fn anywhere(self) -> TokenField {
634 TokenField {
635 name: self.name,
636 placement: TokenPlacement::Anywhere,
637 }
638 }
639
640 /// The field name, matched byte for byte.
641 #[must_use]
642 pub const fn name(&self) -> &'static str {
643 self.name
644 }
645
646 /// Where the field must be.
647 #[must_use]
648 pub const fn placement(&self) -> TokenPlacement {
649 self.placement
650 }
651}
652
653/// Where the token field must be.
654#[non_exhaustive]
655#[derive(Clone, Copy, Debug, PartialEq, Eq)]
656pub enum TokenPlacement {
657 /// Before the first file part (default of [`TokenField::new`]).
658 BeforeFirstFile,
659 /// Anywhere.
660 Anywhere,
661}
662
663#[cfg(test)]
664mod tests {
665 use super::*;
666
667 #[test]
668 fn test_limits_default_validates() {
669 assert!(Limits::DEFAULT.validate().is_ok());
670 assert_eq!(Limits::default(), Limits::DEFAULT);
671 }
672
673 #[test]
674 fn test_limits_header_budget_below_64_refused() {
675 for bytes in [0, 1, 63] {
676 let l = Limits::DEFAULT.with_max_part_header_bytes(bytes);
677 assert_eq!(
678 l.validate(),
679 Err(FormError::InvalidLimits {
680 limit: Limit::PartHeaderBytes
681 })
682 );
683 }
684 assert!(
685 Limits::DEFAULT
686 .with_max_part_header_bytes(64)
687 .validate()
688 .is_ok()
689 );
690 }
691
692 #[test]
693 fn test_limits_containing_limit_caps_contained() {
694 let l = Limits::DEFAULT.with_max_body_bytes(4096);
695 assert_eq!(l.text(), 4096);
696 assert_eq!(l.value(), 4096);
697 assert_eq!(l.file(), 4096);
698 assert_eq!(l.name(), 256);
699 assert_eq!(l.token(), 128);
700 let l = l.with_max_value_bytes(10);
701 assert_eq!((l.value(), l.token()), (10, 10));
702 let l = Limits::DEFAULT.with_max_part_header_bytes(100);
703 assert_eq!(l.filename(), 100);
704 let l = Limits::DEFAULT.with_sniff_bytes(64).with_max_file_bytes(16);
705 assert!(l.validate().is_ok());
706 }
707
708 #[test]
709 fn test_limits_zero_token_with_token_field_refused() {
710 let policy = Policy::DEFAULT.with_token_field(TokenField::new("t"));
711 let l = Limits::DEFAULT.with_max_token_bytes(0);
712 assert_eq!(
713 l.validate_with(&policy),
714 Err(FormError::InvalidLimits {
715 limit: Limit::TokenLength
716 })
717 );
718 assert!(l.validate_with(&Policy::DEFAULT).is_ok());
719 }
720
721 #[test]
722 fn test_buffer_lengths_follow_policy() {
723 let l = Limits::DEFAULT;
724 assert_eq!(l.multipart_buffer_len(&Policy::DEFAULT), 8192 + 256 + 32);
725 let p = Policy::DEFAULT
726 .with_extended_filename(ExtendedFilenamePolicy::AcceptAlone)
727 .with_token_field(TokenField::new("t"));
728 assert_eq!(l.multipart_buffer_len(&p), 8192 + 256 + 1024 + 128 + 32);
729 assert_eq!(l.urlencoded_buffer_len(), 256 + 1024 * 1024 + 1);
730 }
731
732 #[test]
733 fn test_setters_set_one_field_each() {
734 let l = Limits::DEFAULT
735 .with_max_body_bytes(1)
736 .with_max_fields(2)
737 .with_max_name_bytes(3)
738 .with_max_value_bytes(4)
739 .with_max_text_bytes(5)
740 .with_max_parts(6)
741 .with_max_files(7)
742 .with_max_file_bytes(8)
743 .with_max_part_header_bytes(9)
744 .with_max_part_headers(10)
745 .with_max_filename_bytes(11)
746 .with_max_preamble_bytes(12)
747 .with_max_epilogue_bytes(13)
748 .with_max_padding_bytes(14)
749 .with_sniff_bytes(15)
750 .with_max_token_bytes(16);
751 assert_eq!(
752 (
753 l.max_body_bytes,
754 l.max_fields,
755 l.max_name_bytes,
756 l.max_value_bytes
757 ),
758 (1, 2, 3, 4)
759 );
760 assert_eq!(
761 (l.max_text_bytes, l.max_parts, l.max_files, l.max_file_bytes),
762 (5, 6, 7, 8)
763 );
764 assert_eq!(
765 (
766 l.max_part_header_bytes,
767 l.max_part_headers,
768 l.max_filename_bytes,
769 l.max_preamble_bytes
770 ),
771 (9, 10, 11, 12)
772 );
773 assert_eq!(
774 (
775 l.max_epilogue_bytes,
776 l.max_padding_bytes,
777 l.sniff_bytes,
778 l.max_token_bytes
779 ),
780 (13, 14, 15, 16)
781 );
782 }
783
784 #[test]
785 fn test_policy_setters() {
786 let p = Policy::DEFAULT
787 .with_percent(PercentPolicy::Literal)
788 .with_extended_filename(ExtendedFilenamePolicy::Ignore)
789 .with_unknown_headers(HeaderPolicy::Refuse)
790 .with_empty_files(EmptyFilePolicy::Skip)
791 .with_token_field(TokenField::new("t").anywhere());
792 assert_eq!(p.percent, PercentPolicy::Literal);
793 assert_eq!(p.extended_filename, ExtendedFilenamePolicy::Ignore);
794 assert_eq!(p.unknown_headers, HeaderPolicy::Refuse);
795 assert_eq!(p.empty_files, EmptyFilePolicy::Skip);
796 assert_eq!(
797 p.token_field.map(|t| (t.name(), t.placement())),
798 Some(("t", TokenPlacement::Anywhere))
799 );
800 assert_eq!(Policy::default(), Policy::DEFAULT);
801 }
802}