Skip to main content

hyperlane_plugin_multipart/
impl.rs

1use super::*;
2
3/// Formats [`MultipartError`] for display diagnostics.
4impl Display for MultipartError {
5    /// Writes a human-readable multipart validation error.
6    ///
7    /// # Arguments
8    ///
9    /// - `&mut Formatter<'_>` - Output formatter.
10    ///
11    /// # Returns
12    ///
13    /// - `fmt::Result` - Formatting outcome.
14    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
15        let msg: &str = match self {
16            Self::MissingBoundary => ERR_MISSING_BOUNDARY,
17            Self::MalformedBody => ERR_MALFORMED_BODY,
18            Self::TotalTooLarge => ERR_TOTAL_TOO_LARGE,
19            Self::TooManyParts => ERR_TOO_MANY_PARTS,
20            Self::TooManyFiles => ERR_TOO_MANY_FILES,
21            Self::FileTooLarge => ERR_FILE_TOO_LARGE,
22            Self::FieldTooLarge => ERR_FIELD_TOO_LARGE,
23            Self::DisallowedMime => ERR_DISALLOWED_MIME,
24        };
25        f.write_str(msg)
26    }
27}
28
29/// Marks [`MultipartError`] as a standard error type.
30impl Error for MultipartError {}
31
32/// Lookup and context extraction helpers for [`ParsedMultipart`].
33impl ParsedMultipart {
34    /// Retrieves the [`ParsedMultipart`] payload attached by [`MultipartHook`] from `ctx`.
35    ///
36    /// # Arguments
37    ///
38    /// - `&Context` - Active Hyperlane context.
39    ///
40    /// # Returns
41    ///
42    /// - `Option<Self>` - Parsed multipart form, if present.
43    #[inline]
44    pub fn from_context(ctx: &Context) -> Option<Self> {
45        ctx.try_get_attribute::<Self, _>(ATTR_PARSED_MULTIPART)
46    }
47
48    /// Returns the first text field value matching `name`.
49    ///
50    /// # Arguments
51    ///
52    /// - `&str` - Field name.
53    ///
54    /// # Returns
55    ///
56    /// - `Option<&str>` - Matching text field value, if present.
57    pub fn field(&self, name: &str) -> Option<&str> {
58        self.get_fields()
59            .iter()
60            .find(|(k, _): &&(String, String)| k.as_str() == name)
61            .map(|(_, v): &(String, String)| v.as_str())
62    }
63
64    /// Returns the first uploaded file matching `field_name`.
65    ///
66    /// # Arguments
67    ///
68    /// - `&str` - Form field name.
69    ///
70    /// # Returns
71    ///
72    /// - `Option<&UploadedFile>` - Matching uploaded file, if present.
73    pub fn file(&self, field_name: &str) -> Option<&UploadedFile> {
74        self.get_files()
75            .iter()
76            .find(|f: &&UploadedFile| f.get_field_name().as_str() == field_name)
77    }
78}
79
80/// Default construction for [`MultipartConfig`].
81impl Default for MultipartConfig {
82    /// Constructs a safe default [`MultipartConfig`] with 10 MiB total cap and magic-byte sniffing enabled.
83    ///
84    /// # Returns
85    ///
86    /// - `Self` - Default configuration.
87    fn default() -> Self {
88        Self {
89            max_total_bytes: DEFAULT_MAX_TOTAL_BYTES,
90            max_parts: DEFAULT_MAX_PARTS,
91            max_files: DEFAULT_MAX_FILES,
92            max_file_bytes: DEFAULT_MAX_FILE_BYTES,
93            max_field_bytes: DEFAULT_MAX_FIELD_BYTES,
94            allowed_mime_prefixes: Vec::new(),
95            sniff_mime: true,
96        }
97    }
98}
99
100/// Fluent builder methods for [`MultipartConfig`].
101impl MultipartConfig {
102    /// Sets the maximum total multipart request body size in bytes.
103    ///
104    /// # Arguments
105    ///
106    /// - `usize` - Maximum total bytes.
107    ///
108    /// # Returns
109    ///
110    /// - `Self` - Updated configuration.
111    pub fn with_max_total_bytes(mut self, bytes: usize) -> Self {
112        self.set_max_total_bytes(bytes);
113        self
114    }
115
116    /// Sets the maximum uploaded file size in bytes.
117    ///
118    /// # Arguments
119    ///
120    /// - `usize` - Maximum file bytes.
121    ///
122    /// # Returns
123    ///
124    /// - `Self` - Updated configuration.
125    pub fn with_max_file_bytes(mut self, bytes: usize) -> Self {
126        self.set_max_file_bytes(bytes);
127        self
128    }
129
130    /// Sets the maximum number of uploaded files per request.
131    ///
132    /// # Arguments
133    ///
134    /// - `usize` - Maximum file count.
135    ///
136    /// # Returns
137    ///
138    /// - `Self` - Updated configuration.
139    pub fn with_max_files(mut self, files: usize) -> Self {
140        self.set_max_files(files);
141        self
142    }
143
144    /// Restricts uploaded files to the specified MIME type prefixes (for example `["image/", "application/pdf"]`).
145    ///
146    /// # Arguments
147    ///
148    /// - `I` - Iterator of allowed MIME prefixes.
149    ///
150    /// # Returns
151    ///
152    /// - `Self` - Updated configuration.
153    pub fn with_allowed_mime_prefixes<I, S>(mut self, prefixes: I) -> Self
154    where
155        I: IntoIterator<Item = S>,
156        S: Into<String>,
157    {
158        self.set_allowed_mime_prefixes(prefixes.into_iter().map(Into::into).collect());
159        self
160    }
161}
162
163/// Parsing and validation engine for [`MultipartPlugin`].
164impl MultipartPlugin {
165    /// Compiles a standalone [`MultipartPlugin`] from `config`.
166    ///
167    /// # Arguments
168    ///
169    /// - `MultipartConfig` - Upload guard configuration.
170    ///
171    /// # Returns
172    ///
173    /// - `Self` - Compiled plugin.
174    pub fn new(config: MultipartConfig) -> Self {
175        let allowed_mime_lower: Box<[String]> = config
176            .get_allowed_mime_prefixes()
177            .iter()
178            .map(|m: &String| m.trim().to_ascii_lowercase())
179            .filter(|m: &String| !m.is_empty())
180            .collect::<Vec<String>>()
181            .into_boxed_slice();
182        let bad_request_wire: Vec<u8> =
183            build_error_wire(HttpStatus::BadRequest, DEFAULT_BAD_MULTIPART_BODY);
184        let too_large_wire: Vec<u8> =
185            build_error_wire(HttpStatus::PayloadTooLarge, DEFAULT_TOO_LARGE_BODY);
186        let disallowed_mime_wire: Vec<u8> = build_error_wire(
187            HttpStatus::UnsupportedMediaType,
188            DEFAULT_DISALLOWED_MIME_BODY,
189        );
190        Self {
191            config,
192            allowed_mime_lower,
193            bad_request_wire,
194            too_large_wire,
195            disallowed_mime_wire,
196        }
197    }
198
199    /// Initializes the global [`MultipartPlugin`] singleton once.
200    ///
201    /// # Arguments
202    ///
203    /// - `MultipartConfig` - Upload configuration.
204    ///
205    /// # Returns
206    ///
207    /// - `&'static Self` - Reference to the global plugin.
208    pub fn init(config: MultipartConfig) -> &'static Self {
209        MULTIPART_PLUGIN.get_or_init(|| Self::new(config))
210    }
211
212    /// Returns the initialized global [`MultipartPlugin`], if configured.
213    ///
214    /// # Returns
215    ///
216    /// - `Option<&'static Self>` - Reference to the global plugin, or `None`.
217    #[inline(always)]
218    pub fn get() -> Option<&'static Self> {
219        MULTIPART_PLUGIN.get()
220    }
221
222    /// Checks whether `mime` satisfies `allowed_mime_lower`.
223    ///
224    /// # Arguments
225    ///
226    /// - `&str` - Effective MIME type.
227    ///
228    /// # Returns
229    ///
230    /// - `bool` - `true` when allowed.
231    #[inline]
232    fn is_mime_allowed(&self, mime: &str) -> bool {
233        let Self {
234            allowed_mime_lower, ..
235        } = self;
236        if allowed_mime_lower.is_empty() {
237            return true;
238        }
239        allowed_mime_lower.iter().any(|prefix: &String| {
240            mime.len() >= prefix.len()
241                && mime.as_bytes()[..prefix.len()].eq_ignore_ascii_case(prefix.as_bytes())
242        })
243    }
244
245    /// Parses and validates a `multipart/form-data` request into [`ParsedMultipart`].
246    ///
247    /// # Arguments
248    ///
249    /// - `&Request` - Incoming HTTP request.
250    ///
251    /// # Returns
252    ///
253    /// - `Result<ParsedMultipart, MultipartError>` - Validated form fields & files or guard error.
254    pub fn parse_request(&self, request: &Request) -> Result<ParsedMultipart, MultipartError> {
255        let ct: &str = request
256            .get_headers()
257            .get(CONTENT_TYPE)
258            .and_then(|vals: &VecDeque<String>| vals.back())
259            .map(String::as_str)
260            .ok_or(MultipartError::MissingBoundary)?;
261        self.parse_bytes(ct, request.get_body())
262    }
263
264    /// Parses and validates raw `multipart/form-data` bytes given `content_type`.
265    ///
266    /// # Arguments
267    ///
268    /// - `&str` - `Content-Type` header value containing `boundary=...`.
269    /// - `&[u8]` - Raw HTTP request body bytes.
270    ///
271    /// # Returns
272    ///
273    /// - `Result<ParsedMultipart, MultipartError>` - Validated form fields & files or guard error.
274    pub fn parse_bytes(
275        &self,
276        content_type: &str,
277        body: &[u8],
278    ) -> Result<ParsedMultipart, MultipartError> {
279        let Self { config, .. } = self;
280        if config.get_max_total_bytes() > 0 && body.len() > config.get_max_total_bytes() {
281            return Err(MultipartError::TotalTooLarge);
282        }
283        let boundary: &str =
284            extract_boundary(content_type).ok_or(MultipartError::MissingBoundary)?;
285        let mut delim: Vec<u8> = Vec::with_capacity(boundary.len() + 2);
286        delim.extend_from_slice(DOUBLE_DASH);
287        delim.extend_from_slice(boundary.as_bytes());
288        let first_pos: usize = find_bytes(body, &delim).ok_or(MultipartError::MalformedBody)?;
289        let mut cursor: usize = first_pos + delim.len();
290        let mut parsed: ParsedMultipart = ParsedMultipart::default();
291        let mut part_count: usize = 0;
292        loop {
293            if cursor + 2 <= body.len() && &body[cursor..cursor + 2] == DOUBLE_DASH {
294                break;
295            }
296            if cursor + 2 <= body.len() && &body[cursor..cursor + 2] == b"\r\n" {
297                cursor += 2;
298            } else if cursor < body.len() && body[cursor] == b'\n' {
299                cursor += 1;
300            } else {
301                return Err(MultipartError::MalformedBody);
302            }
303            part_count += 1;
304            if config.get_max_parts() > 0 && part_count > config.get_max_parts() {
305                return Err(MultipartError::TooManyParts);
306            }
307            let remaining: &[u8] = &body[cursor..];
308            let next_rel: usize =
309                find_bytes(remaining, &delim).ok_or(MultipartError::MalformedBody)?;
310            let mut part_slice: &[u8] = &remaining[..next_rel];
311            if part_slice.ends_with(b"\r\n") {
312                part_slice = &part_slice[..part_slice.len() - 2];
313            } else if part_slice.ends_with(b"\n") {
314                part_slice = &part_slice[..part_slice.len() - 1];
315            }
316            let header_end: usize =
317                find_bytes(part_slice, CRLF_CRLF).ok_or(MultipartError::MalformedBody)?;
318            let head_str: &str =
319                from_utf8(&part_slice[..header_end]).map_err(|_| MultipartError::MalformedBody)?;
320            let payload: &[u8] = &part_slice[header_end + CRLF_CRLF.len()..];
321            let mut field_name: String = String::new();
322            let mut raw_filename: Option<String> = None;
323            let mut declared_ct: Option<String> = None;
324            for line in head_str.split("\r\n") {
325                if let Some((k, v)) = line.split_once(':') {
326                    let key_trim: &str = k.trim();
327                    let val_trim: &str = v.trim();
328                    if key_trim.eq_ignore_ascii_case(HEADER_CONTENT_DISPOSITION) {
329                        let (n, f): (String, Option<String>) = parse_content_disposition(val_trim);
330                        field_name = n;
331                        raw_filename = f;
332                    } else if key_trim.eq_ignore_ascii_case(HEADER_CONTENT_TYPE_LOWER) {
333                        declared_ct = Some(val_trim.to_owned());
334                    }
335                }
336            }
337            if field_name.is_empty() {
338                return Err(MultipartError::MalformedBody);
339            }
340            if let Some(fname) = raw_filename {
341                if config.get_max_files() > 0 && parsed.files.len() >= config.get_max_files() {
342                    return Err(MultipartError::TooManyFiles);
343                }
344                if config.get_max_file_bytes() > 0 && payload.len() > config.get_max_file_bytes() {
345                    return Err(MultipartError::FileTooLarge);
346                }
347                let effective_mime: String = if config.get_sniff_mime()
348                    && let Some(sniffed) = sniff_magic_mime(payload)
349                {
350                    sniffed.to_owned()
351                } else {
352                    declared_ct.unwrap_or_else(|| MIME_OCTET_STREAM.to_owned())
353                };
354                if !self.is_mime_allowed(&effective_mime) {
355                    return Err(MultipartError::DisallowedMime);
356                }
357                parsed.files.push(UploadedFile {
358                    field_name,
359                    filename: sanitize_filename(&fname),
360                    content_type: effective_mime,
361                    data: payload.to_vec(),
362                });
363            } else {
364                if config.get_max_field_bytes() > 0 && payload.len() > config.get_max_field_bytes()
365                {
366                    return Err(MultipartError::FieldTooLarge);
367                }
368                let text: String = from_utf8(payload)
369                    .map_err(|_| MultipartError::MalformedBody)?
370                    .to_owned();
371                parsed.fields.push((field_name, text));
372            }
373            cursor += next_rel + delim.len();
374        }
375        Ok(parsed)
376    }
377}
378
379/// Implements [`ServerHook`] for [`MultipartHook`].
380impl ServerHook for MultipartHook {
381    /// Constructs a per-request [`MultipartHook`].
382    ///
383    /// # Arguments
384    ///
385    /// - `&mut Stream` - Connection stream.
386    /// - `&mut Context` - Request context.
387    ///
388    /// # Returns
389    ///
390    /// - `Self` - Hook instance.
391    #[inline(always)]
392    async fn new(_: &mut Stream, _: &mut Context) -> Self {
393        Self
394    }
395
396    /// Fast-path skips non-multipart requests and parses/validates `multipart/form-data` payloads into [`Context`].
397    ///
398    /// # Arguments
399    ///
400    /// - `Self` - Hook instance.
401    /// - `&mut Stream` - Connection stream.
402    /// - `&mut Context` - Request context.
403    ///
404    /// # Returns
405    ///
406    /// - `Status` - `Status::Continue` when non-multipart or valid; `Status::Reject` on `400`/`413`/`415`.
407    #[inline(always)]
408    async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status {
409        let Some(plugin) = MultipartPlugin::get() else {
410            return Status::Continue;
411        };
412        let is_multipart: bool = ctx
413            .get_request()
414            .get_headers()
415            .get(CONTENT_TYPE)
416            .and_then(|vals: &VecDeque<String>| vals.back())
417            .is_some_and(|ct: &String| {
418                let t: &str = ct.trim();
419                t.len() >= MULTIPART_FORM_DATA_PREFIX.len()
420                    && t.as_bytes()[..MULTIPART_FORM_DATA_PREFIX.len()]
421                        .eq_ignore_ascii_case(MULTIPART_FORM_DATA_PREFIX.as_bytes())
422            });
423        if !is_multipart {
424            return Status::Continue;
425        }
426        match plugin.parse_request(ctx.get_request()) {
427            Ok(form) => {
428                ctx.set_attribute(ATTR_PARSED_MULTIPART, form);
429                Status::Continue
430            }
431            Err(
432                MultipartError::TotalTooLarge
433                | MultipartError::TooManyParts
434                | MultipartError::TooManyFiles
435                | MultipartError::FileTooLarge
436                | MultipartError::FieldTooLarge,
437            ) => {
438                let MultipartPlugin { too_large_wire, .. } = plugin;
439                let _: Result<(), ResponseError> = stream.try_send(too_large_wire).await;
440                Status::Reject
441            }
442            Err(MultipartError::DisallowedMime) => {
443                let MultipartPlugin {
444                    disallowed_mime_wire,
445                    ..
446                } = plugin;
447                let _: Result<(), ResponseError> = stream.try_send(disallowed_mime_wire).await;
448                Status::Reject
449            }
450            Err(MultipartError::MissingBoundary | MultipartError::MalformedBody) => {
451                let MultipartPlugin {
452                    bad_request_wire, ..
453                } = plugin;
454                let _: Result<(), ResponseError> = stream.try_send(bad_request_wire).await;
455                Status::Reject
456            }
457        }
458    }
459}