multra 1.3.0

An async parser for `multipart/form-data` content-type in Rust.
Documentation
use std::convert::Infallible;
use std::net::SocketAddr;

use bytes::Bytes;
use futures_util::StreamExt;
use http_body_util::{BodyStream, Full};
use hyper::{Request, Response, StatusCode, body::Incoming, header::CONTENT_TYPE};
// Import the multra types.
use multra::{Constraints, Error, Multipart, SizeLimit};

// A handler for incoming requests.
async fn handle(req: Request<Incoming>) -> Result<Response<Full<Bytes>>, Infallible> {
    // Extract the `multipart/form-data` boundary from the headers.
    let boundary = req
        .headers()
        .get(CONTENT_TYPE)
        .and_then(|ct| ct.to_str().ok())
        .and_then(|ct| multra::parse_boundary(ct).ok());

    // Send `BAD_REQUEST` status if the content-type is not multipart/form-data.
    if boundary.is_none() {
        return Ok(Response::builder()
            .status(StatusCode::BAD_REQUEST)
            .body(Full::from("BAD REQUEST"))
            .unwrap());
    }

    // Process the multipart e.g. you can store them in files.
    if let Err(err) = process_multipart(req.into_body(), boundary.unwrap()).await {
        return Ok(multipart_error_response(&err));
    }

    Ok(Response::new(Full::from("Success")))
}

fn multipart_error_response(error: &Error) -> Response<Full<Bytes>> {
    let status = match error {
        Error::FieldSizeExceeded { .. }
        | Error::StreamSizeExceeded { .. }
        | Error::PreambleSizeExceeded { .. }
        | Error::HeadersSizeExceeded { .. }
        | Error::BoundaryPaddingSizeExceeded { .. }
        | Error::FieldCountExceeded { .. } => StatusCode::PAYLOAD_TOO_LARGE,
        Error::UnknownField { .. }
        | Error::IncompleteFieldData { .. }
        | Error::IncompleteHeaders
        | Error::ReadHeaderFailed(_)
        | Error::DecodeHeaderName { .. }
        | Error::DecodeHeaderValue { .. }
        | Error::IncompleteStream
        | Error::StreamReadFailed(_)
        | Error::NoMultipart
        | Error::DecodeContentType(_)
        | Error::NoBoundary
        | Error::InvalidBoundary { .. } => StatusCode::BAD_REQUEST,
        #[cfg(feature = "json")]
        Error::DecodeJson(_) => StatusCode::BAD_REQUEST,
        // Lock failures and future, unclassified errors remain server errors.
        _ => StatusCode::INTERNAL_SERVER_ERROR,
    };
    Response::builder()
        .status(status)
        .body(Full::from(format!("{status}: {error}")))
        .unwrap()
}

// Process the request body as multipart/form-data.
async fn process_multipart(body: Incoming, boundary: String) -> multra::Result<()> {
    // Convert the body into a stream of data frames.
    let body_stream = BodyStream::new(body)
        .filter_map(|result| async move { result.map(|frame| frame.into_data().ok()).transpose() });

    let constraints = Constraints::new()
        .allowed_fields(vec!["my_text_field", "my_file_field"])
        .size_limit(
            SizeLimit::new()
                .whole_stream(15 * 1024 * 1024)
                .per_field(10 * 1024 * 1024)
                .headers(64 * 1024),
        );

    // Create a Multipart instance from the request body.
    let mut multipart = Multipart::with_constraints(body_stream, boundary, constraints);

    // Iterate over the fields, `next_field` method will return the next field if
    // available.
    while let Some(mut field) = multipart.next_field().await? {
        // Get the field name.
        let name = field.name();

        // Get the field's filename if provided in "Content-Disposition" header.
        let file_name = field.file_name();

        // Get the "Content-Type" header as `mime::Mime` type.
        let content_type = field.content_type();

        println!("Name: {name:?}, FileName: {file_name:?}, Content-Type: {content_type:?}");

        // Process the field data chunks e.g. store them in a file.
        let mut field_bytes_len = 0;
        while let Some(field_chunk) = field.chunk().await? {
            // Do something with field chunk.
            field_bytes_len += field_chunk.len();
        }

        println!("Field Bytes Length: {field_bytes_len:?}");
    }

    Ok(())
}

#[tokio::main]
async fn main() {
    let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
    let listener = tokio::net::TcpListener::bind(addr).await.unwrap();
    println!("Server running at: {addr}");

    let service = hyper::service::service_fn(handle);

    loop {
        let (socket, _remote_addr) = listener.accept().await.unwrap();
        let socket = hyper_util::rt::TokioIo::new(socket);
        tokio::spawn(async move {
            if let Err(e) = hyper::server::conn::http1::Builder::new()
                .serve_connection(socket, service)
                .await
            {
                eprintln!("server error: {e}");
            }
        });
    }
}

#[cfg(test)]
mod tests {
    use super::{Error, StatusCode, multipart_error_response};

    #[test]
    fn malformed_and_unknown_fields_are_bad_requests() {
        for error in [
            Error::UnknownField {
                field_name: Some("unknown".to_owned()),
            },
            Error::IncompleteFieldData {
                field_name: Some("my_text_field".to_owned()),
            },
            Error::IncompleteHeaders,
            Error::IncompleteStream,
            Error::ReadHeaderFailed(httparse::Error::NewLine),
            Error::StreamReadFailed(std::io::Error::other("request body failed").into()),
        ] {
            assert_eq!(
                multipart_error_response(&error).status(),
                StatusCode::BAD_REQUEST,
                "{error:?}"
            );
        }
    }

    #[test]
    fn configured_resource_limits_are_content_too_large() {
        for error in [
            Error::FieldSizeExceeded {
                limit: 1,
                field_name: Some("my_text_field".to_owned()),
            },
            Error::StreamSizeExceeded { limit: 1 },
            Error::PreambleSizeExceeded { limit: 1 },
            Error::HeadersSizeExceeded { limit: 1 },
            Error::BoundaryPaddingSizeExceeded { limit: 1 },
            Error::FieldCountExceeded { limit: 1 },
        ] {
            assert_eq!(
                multipart_error_response(&error).status(),
                StatusCode::PAYLOAD_TOO_LARGE,
                "{error:?}"
            );
        }
    }

    #[test]
    fn internal_errors_remain_server_errors() {
        assert_eq!(
            multipart_error_response(&Error::LockFailure).status(),
            StatusCode::INTERNAL_SERVER_ERROR
        );
    }
}