glacier-web 0.4.1

A batteries-included web framework for Rust, inspired by Rails, Phoenix and Laravel.
Documentation
//! Files uploaded in a `multipart/form-data` request.
//!
//! A multipart body's text fields become ordinary params; its files are
//! read with [`Context::file`](crate::Context::file), by field name as the
//! form sent it (`comment[note_image]`), as Rails' `params[:comment][:note_image]`.

use bytes::Bytes;

/// A file from a multipart form: its name on the client, its declared
/// content type and its bytes.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Upload {
    pub filename: String,
    pub content_type: String,
    pub bytes: Bytes,
}

impl Upload {
    pub fn len(&self) -> usize {
        self.bytes.len()
    }

    pub fn is_empty(&self) -> bool {
        self.bytes.is_empty()
    }

    /// The file's type as its bytes show it, the declared type aside, as
    /// Paperclip's detector stores it: the type its signature names
    /// (`image/png`), else its extension's, else `text/plain` for text and
    /// `application/octet-stream` for anything else; `inode/x-empty` when
    /// empty.
    pub fn detected_type(&self) -> String {
        if self.bytes.is_empty() {
            return "inode/x-empty".into();
        }
        if let Some(sniffed) = sniff(&self.bytes) {
            return sniffed.into();
        }
        extension(&self.filename)
            .and_then(|ext| crate::mime::for_format(&ext))
            .unwrap_or(if is_text(&self.bytes) {
                "text/plain"
            } else {
                "application/octet-stream"
            })
            .into()
    }

    /// Whether the file isn't what its declared type says, as Paperclip's
    /// spoof check: the declared kind (`image` of `image/png`) disagrees
    /// with the extension's (`shelf.pdf`) or with the bytes (text sent as
    /// `image/png`). A Rails app's message for it is "has contents that are
    /// not what they are reported to be".
    ///
    /// Unlike `file`, it knows only common types: bytes it can't name, and
    /// extensions it doesn't know, never count as a mismatch.
    pub fn is_spoofed(&self) -> bool {
        let declared = self.content_type.split('/').next().unwrap_or("").trim();
        if self.filename.is_empty() || declared.is_empty() {
            return false;
        }
        let by_extension = extension(&self.filename)
            .and_then(|ext| crate::mime::for_format(&ext))
            .is_some_and(|known| !known.starts_with(&format!("{declared}/")));
        let by_contents = sniff(&self.bytes)
            .or_else(|| is_text(&self.bytes).then_some("text/plain"))
            .is_some_and(|found| !found.contains(declared));
        by_extension || by_contents
    }
}

/// A file name's extension, lower-cased: `Shelf.PNG` → `png`.
fn extension(filename: &str) -> Option<String> {
    let (stem, ext) = filename.rsplit_once('.')?;
    (!stem.is_empty() && !ext.is_empty()).then(|| ext.to_ascii_lowercase())
}

/// Text: UTF-8 without NULs.
fn is_text(bytes: &[u8]) -> bool {
    !bytes.contains(&0) && std::str::from_utf8(bytes).is_ok()
}

/// The type a file's signature (its first bytes) names, for common types;
/// text that is SVG, XML or JSON by its start.
fn sniff(bytes: &[u8]) -> Option<&'static str> {
    let starts = |magic: &[u8]| bytes.starts_with(magic);
    let at = |offset: usize, magic: &[u8]| bytes.get(offset..offset + magic.len()) == Some(magic);
    Some(match () {
        () if starts(b"\x89PNG\r\n\x1a\n") => "image/png",
        () if starts(b"\xff\xd8\xff") => "image/jpeg",
        () if starts(b"GIF87a") || starts(b"GIF89a") => "image/gif",
        () if starts(b"RIFF") && at(8, b"WEBP") => "image/webp",
        () if starts(b"II*\0") || starts(b"MM\0*") => "image/tiff",
        // BMP: "BM" and four reserved zero bytes, so text can't pass.
        () if starts(b"BM") && at(6, b"\0\0\0\0") => "image/bmp",
        () if starts(b"\0\0\x01\0") => "image/vnd.microsoft.icon",
        () if at(4, b"ftyp") => match bytes.get(8..12).unwrap_or_default() {
            b"heic" | b"heix" | b"hevc" | b"heim" | b"heis" | b"hevm" | b"hevs" | b"mif1"
            | b"msf1" => "image/heic",
            b"avif" | b"avis" => "image/avif",
            b"qt  " => "video/quicktime",
            _ => "video/mp4",
        },
        () if starts(b"%PDF-") => "application/pdf",
        () if starts(b"PK\x03\x04") => "application/zip",
        () if starts(b"\x1f\x8b") => "application/gzip",
        () if starts(b"ID3") || starts(b"\xff\xfb") => "audio/mpeg",
        () if starts(b"OggS") => "audio/ogg",
        () if starts(b"\x1a\x45\xdf\xa3") => "video/webm",
        () if is_text(bytes) => {
            let head = std::str::from_utf8(&bytes[..bytes.len().min(1024)])
                .unwrap_or_default()
                .trim_start();
            if head.contains("<svg") {
                "image/svg+xml"
            } else if head.starts_with("<?xml") {
                "text/xml"
            } else if (head.starts_with('{') || head.starts_with('['))
                && serde_json::from_slice::<serde_json::Value>(bytes).is_ok()
            {
                "application/json"
            } else {
                return None;
            }
        }
        () => return None,
    })
}

/// One part of a multipart body.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Part {
    Field(String, String),
    File(String, Upload),
}

/// The boundary from a `multipart/form-data; boundary=…` content type.
pub(crate) fn boundary(content_type: &str) -> Option<String> {
    let (kind, params) = content_type.split_once(';')?;
    if !kind.trim().eq_ignore_ascii_case("multipart/form-data") {
        return None;
    }
    params.split(';').find_map(|param| {
        let (name, value) = param.split_once('=')?;
        name.trim()
            .eq_ignore_ascii_case("boundary")
            .then(|| value.trim().trim_matches('"').to_owned())
    })
}

/// The parts of a buffered multipart body. Malformed parts are skipped;
/// a file field left empty (no file chosen) is left out, as a browser
/// sends one.
pub(crate) fn parse(body: &[u8], boundary: &str) -> Vec<Part> {
    let delimiter = format!("--{boundary}");
    let mut parts = Vec::new();
    let mut rest = match find(body, delimiter.as_bytes()) {
        Some(start) => &body[start + delimiter.len()..],
        None => return parts,
    };
    let separator = format!("\r\n--{boundary}");
    loop {
        // After a delimiter: `--` ends the body; otherwise a line break.
        if rest.starts_with(b"--") {
            break;
        }
        rest = rest.strip_prefix(b"\r\n").unwrap_or(rest);
        let Some(end) = find(rest, separator.as_bytes()) else {
            break;
        };
        if let Some(part) = parse_part(&rest[..end]) {
            parts.push(part);
        }
        rest = &rest[end + separator.len()..];
    }
    parts
}

fn parse_part(part: &[u8]) -> Option<Part> {
    let split = find(part, b"\r\n\r\n")?;
    let headers = std::str::from_utf8(&part[..split]).ok()?;
    let content = &part[split + 4..];
    let mut name = None;
    let mut filename = None;
    let mut content_type = None;
    for line in headers.split("\r\n") {
        let Some((header, value)) = line.split_once(':') else {
            continue;
        };
        if header.trim().eq_ignore_ascii_case("content-disposition") {
            for param in value.split(';').skip(1) {
                let Some((key, value)) = param.split_once('=') else {
                    continue;
                };
                let value = value.trim().trim_matches('"').to_owned();
                match key.trim() {
                    "name" => name = Some(value),
                    "filename" => filename = Some(value),
                    _ => {}
                }
            }
        } else if header.trim().eq_ignore_ascii_case("content-type") {
            content_type = Some(value.trim().to_owned());
        }
    }
    let name = name?;
    match filename {
        Some(filename) if filename.is_empty() && content.is_empty() => None,
        Some(filename) => Some(Part::File(
            name,
            Upload {
                filename,
                content_type: content_type.unwrap_or_else(|| "application/octet-stream".into()),
                bytes: Bytes::copy_from_slice(content),
            },
        )),
        None => Some(Part::Field(
            name,
            String::from_utf8_lossy(content).into_owned(),
        )),
    }
}

fn find(haystack: &[u8], needle: &[u8]) -> Option<usize> {
    haystack
        .windows(needle.len())
        .position(|window| window == needle)
}

#[cfg(test)]
mod tests {
    use super::*;

    fn body(boundary: &str) -> Vec<u8> {
        let mut body = Vec::new();
        body.extend_from_slice(
            format!(
                "--{boundary}\r\nContent-Disposition: form-data; name=\"session_id\"\r\n\r\n7\r\n"
            )
            .as_bytes(),
        );
        body.extend_from_slice(format!("--{boundary}\r\nContent-Disposition: form-data; name=\"comment[note_image]\"; filename=\"shelf.png\"\r\nContent-Type: image/png\r\n\r\n").as_bytes());
        body.extend_from_slice(b"\x89PNG\r\n--not the end");
        body.extend_from_slice(format!("\r\n--{boundary}\r\nContent-Disposition: form-data; name=\"empty\"; filename=\"\"\r\nContent-Type: application/octet-stream\r\n\r\n\r\n").as_bytes());
        body.extend_from_slice(format!("--{boundary}--\r\n").as_bytes());
        body
    }

    #[test]
    fn reads_fields_and_files() {
        let b = "----glacier123";
        assert_eq!(
            boundary(&format!("multipart/form-data; boundary=\"{b}\"")).as_deref(),
            Some(b)
        );
        assert_eq!(boundary("application/json"), None);
        let parts = parse(&body(b), b);
        assert_eq!(parts.len(), 2, "the empty file field is left out");
        assert_eq!(parts[0], Part::Field("session_id".into(), "7".into()));
        let Part::File(name, upload) = &parts[1] else {
            panic!("{:?}", parts[1])
        };
        assert_eq!(name, "comment[note_image]");
        assert_eq!(upload.filename, "shelf.png");
        assert_eq!(upload.content_type, "image/png");
        assert_eq!(
            &upload.bytes[..],
            b"\x89PNG\r\n--not the end",
            "a CRLF and dashes inside a file are content"
        );
    }

    fn upload(filename: &str, content_type: &str, bytes: &[u8]) -> Upload {
        Upload {
            filename: filename.into(),
            content_type: content_type.into(),
            bytes: Bytes::copy_from_slice(bytes),
        }
    }

    const PNG: &[u8] = b"\x89PNG\r\n\x1a\n\0\0\0\rIHDR";
    const PDF: &[u8] = b"%PDF-1.4\n%\xe2\xe3\xcf\xd3\n";

    #[test]
    fn detects_a_type_from_the_bytes_then_the_name() {
        assert_eq!(
            upload("shelf.png", "text/plain", PNG).detected_type(),
            "image/png"
        );
        // A JPEG named .png is a JPEG.
        assert_eq!(
            upload("a.png", "image/png", b"\xff\xd8\xff\xe0").detected_type(),
            "image/jpeg"
        );
        assert_eq!(
            upload("note.pdf", "application/octet-stream", PDF).detected_type(),
            "application/pdf"
        );
        // Bytes without a signature: the extension's type, as Paperclip.
        assert_eq!(
            upload("fake.png", "text/plain", b"not an image\n").detected_type(),
            "image/png"
        );
        assert_eq!(upload("notes", "", b"hello").detected_type(), "text/plain");
        assert_eq!(
            upload("blob", "", &[0, 159, 146, 150]).detected_type(),
            "application/octet-stream"
        );
        assert_eq!(
            upload("empty.png", "image/png", b"").detected_type(),
            "inode/x-empty"
        );
    }

    #[test]
    fn spoofed_when_the_declared_kind_disagrees() {
        // Honest uploads.
        assert!(!upload("shelf.png", "image/png", PNG).is_spoofed());
        assert!(
            !upload("Shelf.PNG", "image/jpeg", PNG).is_spoofed(),
            "same kind: image"
        );
        assert!(!upload("note.pdf", "application/pdf", PDF).is_spoofed());
        assert!(!upload("notes.txt", "text/plain", b"hello").is_spoofed());
        assert!(!upload("data.json", "application/json", b"{\"a\": 1}").is_spoofed());
        assert!(!upload("logo.svg", "image/svg+xml", b"<svg xmlns=\"x\"/>").is_spoofed());
        // Text claiming to be an image, by its type and by its name.
        assert!(upload("fake.png", "text/plain", b"not an image\n").is_spoofed());
        assert!(upload("fake.png", "image/png", b"not an image\n").is_spoofed());
        // A PDF named as a photo.
        assert!(upload("shelf.pdf", "image/png", PNG).is_spoofed());
        // What it can't tell isn't a mismatch: unknown bytes, unknown extensions.
        assert!(!upload("photo.heif2", "image/x-new", &[0, 1, 2, 3, 200]).is_spoofed());
        assert!(!upload("", "image/png", b"text").is_spoofed(), "no name");
        assert!(
            !upload("a.png", "", b"text").is_spoofed(),
            "no declared type"
        );
    }
}