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