hyperlane-plugin-multipart 23.3.1

A bounded, traversal-proof RFC 7578 multipart/form-data upload parser and validation middleware plugin for the Hyperlane framework with part/file/size limits, filename sanitization, magic-byte MIME sniffing, and prebuilt 400/413/415 wire responses.
Documentation
use super::*;

/// Extracts the `boundary` token from a `multipart/form-data; boundary=...` header value.
///
/// # Arguments
///
/// - `&str` - Raw `Content-Type` header string.
///
/// # Returns
///
/// - `Option<&str>` - Boundary string without surrounding quotes, if valid.
pub fn extract_boundary(content_type: &str) -> Option<&str> {
    let mut parts = content_type.split(';');
    let media: &str = parts.next()?.trim();
    if !media.eq_ignore_ascii_case(MULTIPART_FORM_DATA_PREFIX) {
        return None;
    }
    for param in parts {
        let p: &str = param.trim();
        if p.len() > BOUNDARY_PARAM_PREFIX.len()
            && p.as_bytes()[..BOUNDARY_PARAM_PREFIX.len()]
                .eq_ignore_ascii_case(BOUNDARY_PARAM_PREFIX.as_bytes())
        {
            let raw: &str = p[BOUNDARY_PARAM_PREFIX.len()..].trim();
            let unquoted: &str = raw
                .strip_prefix('"')
                .and_then(|s: &str| s.strip_suffix('"'))
                .unwrap_or(raw);
            if !unquoted.is_empty() && unquoted.len() <= 70 {
                return Some(unquoted);
            }
        }
    }
    None
}

/// Sanitizes an uploaded filename against directory traversal, path separators, and control bytes.
///
/// # Arguments
///
/// - `&str` - Raw `filename` parameter supplied by the client.
///
/// # Returns
///
/// - `String` - Safe basename containing only printable non-separator characters.
pub fn sanitize_filename(raw: &str) -> String {
    let leaf: &str = raw
        .rsplit(['/', '\\'])
        .next()
        .unwrap_or(FALLBACK_FILENAME)
        .trim();
    let mut clean: String = String::with_capacity(leaf.len().min(128));
    for ch in leaf.chars().take(128) {
        if ch.is_control() || ch == '/' || ch == '\\' || ch == ':' || ch == '\0' {
            continue;
        }
        clean.push(ch);
    }
    let trimmed: &str = clean.trim_matches('.');
    if trimmed.is_empty() {
        FALLBACK_FILENAME.to_owned()
    } else {
        trimmed.to_owned()
    }
}

/// Inspects leading magic bytes of `data` to identify common binary file formats.
///
/// # Arguments
///
/// - `&[u8]` - File content bytes.
///
/// # Returns
///
/// - `Option<&'static str>` - Detected MIME type when a known magic signature matches.
#[inline]
pub fn sniff_magic_mime(data: &[u8]) -> Option<&'static str> {
    if data.len() >= 8 && data[..8] == [0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a] {
        return Some(MIME_PNG);
    }
    if data.len() >= 3 && data[..3] == [0xff, 0xd8, 0xff] {
        return Some(MIME_JPEG);
    }
    if data.len() >= 6 && (&data[..6] == b"GIF87a" || &data[..6] == b"GIF89a") {
        return Some(MIME_GIF);
    }
    if data.len() >= 12 && &data[..4] == b"RIFF" && &data[8..12] == b"WEBP" {
        return Some(MIME_WEBP);
    }
    if data.len() >= 5 && &data[..5] == b"%PDF-" {
        return Some(MIME_PDF);
    }
    if data.len() >= 4 && data[..4] == [b'P', b'K', 0x03, 0x04] {
        return Some(MIME_ZIP);
    }
    if data.len() >= 2 && data[..2] == [0x1f, 0x8b] {
        return Some(MIME_GZIP);
    }
    None
}

/// Locates the first occurrence of `needle` inside `haystack` starting at index `0`.
///
/// # Arguments
///
/// - `&[u8]` - Byte slice to search.
/// - `&[u8]` - Subslice pattern.
///
/// # Returns
///
/// - `Option<usize>` - Start offset of first match.
#[inline]
pub(crate) fn find_bytes(haystack: &[u8], needle: &[u8]) -> Option<usize> {
    if needle.is_empty() || needle.len() > haystack.len() {
        return None;
    }
    let first: u8 = needle[0];
    let limit: usize = haystack.len() - needle.len();
    let mut i: usize = 0;
    while i <= limit {
        if haystack[i] == first && &haystack[i..i + needle.len()] == needle {
            return Some(i);
        }
        i += 1;
    }
    None
}

/// Extracts `name` and optional `filename` parameters from a `Content-Disposition` header value.
///
/// # Arguments
///
/// - `&str` - Raw `Content-Disposition` header value.
///
/// # Returns
///
/// - `(String, Option<String>)` - `(field_name, optional_filename)`.
pub(crate) fn parse_content_disposition(value: &str) -> (String, Option<String>) {
    let mut name: String = String::new();
    let mut filename: Option<String> = None;
    for part in value.split(';').skip(1) {
        let p: &str = part.trim();
        if let Some((k, v)) = p.split_once('=') {
            let key: &str = k.trim();
            let raw_val: &str = v
                .trim()
                .strip_prefix('"')
                .and_then(|s: &str| s.strip_suffix('"'))
                .unwrap_or_else(|| v.trim());
            if key.eq_ignore_ascii_case("name") {
                name = raw_val.to_owned();
            } else if key.eq_ignore_ascii_case("filename") {
                filename = Some(raw_val.to_owned());
            }
        }
    }
    (name, filename)
}

/// Builds a pre-serialized HTTP error wire buffer.
///
/// # Arguments
///
/// - `HttpStatus` - HTTP status code.
/// - `&[u8]` - JSON error payload.
///
/// # Returns
///
/// - `Vec<u8>` - Complete HTTP/1.1 wire bytes.
pub(crate) fn build_error_wire(status: HttpStatus, body: &[u8]) -> Vec<u8> {
    let mut resp: Response = Response::default();
    resp.set_status_code(status.code())
        .set_header(CONTENT_TYPE, DEFAULT_ERROR_CONTENT_TYPE)
        .set_body(body);
    resp.build()
}