delopay 0.4.0

Official Rust SDK for the DeloPay payments API
Documentation
//! Minimal `multipart/form-data` encoding, for the one shape of request the
//! API takes that is not JSON: a file upload.
//!
//! Deliberately small — no streaming, no nested multiparts, no transfer
//! encodings. The payloads involved (a shop logo) are small enough to hold in
//! memory, and a general implementation would be a dependency, not a file.

/// A `multipart/form-data` body plus the `Content-Type` header value that
/// describes it. The two are returned together because the header carries the
/// boundary, so they can never be built independently.
#[derive(Debug)]
pub(crate) struct Multipart {
    /// The encoded body.
    pub(crate) body: Vec<u8>,
    /// `multipart/form-data; boundary=…`.
    pub(crate) content_type: String,
}

/// One `multipart/form-data` part carrying a file.
#[derive(Debug)]
pub(crate) struct FilePart<'a> {
    /// The form field name.
    pub(crate) field: &'a str,
    /// The file name reported to the server.
    pub(crate) file_name: &'a str,
    /// The part's own content type, e.g. `image/png`.
    pub(crate) content_type: &'a str,
    /// The raw file bytes.
    pub(crate) bytes: &'a [u8],
}

/// Encode a single file part.
///
/// The boundary is chosen so it does not occur anywhere in `part.bytes`: a
/// boundary that collides with the payload would let the *content* terminate
/// the part, which is how a malicious upload smuggles extra form fields past
/// the server's parser. `pick_boundary` retries with a longer marker until it
/// finds one that does not appear, so this is a guarantee, not a probability.
pub(crate) fn encode_file(part: &FilePart<'_>) -> Multipart {
    let boundary = pick_boundary(part.bytes);

    // A file name containing `"` or a newline would otherwise break out of the
    // Content-Disposition header and inject arbitrary headers into the part.
    let file_name = sanitize_file_name(part.file_name);

    let mut body = Vec::with_capacity(part.bytes.len() + 256);
    body.extend_from_slice(b"--");
    body.extend_from_slice(boundary.as_bytes());
    body.extend_from_slice(b"\r\nContent-Disposition: form-data; name=\"");
    body.extend_from_slice(part.field.as_bytes());
    body.extend_from_slice(b"\"; filename=\"");
    body.extend_from_slice(file_name.as_bytes());
    body.extend_from_slice(b"\"\r\nContent-Type: ");
    body.extend_from_slice(part.content_type.as_bytes());
    body.extend_from_slice(b"\r\n\r\n");
    body.extend_from_slice(part.bytes);
    body.extend_from_slice(b"\r\n--");
    body.extend_from_slice(boundary.as_bytes());
    body.extend_from_slice(b"--\r\n");

    Multipart {
        body,
        content_type: format!("multipart/form-data; boundary={boundary}"),
    }
}

/// A boundary that does not occur in `payload`.
///
/// Starts from a fixed marker and appends `-` until it is absent from the
/// payload. Deterministic on purpose: it needs no RNG (this crate has no
/// randomness dependency), and the anti-collision property comes from the
/// search, not from unpredictability. The boundary is not a secret — it is
/// sent in the clear in the `Content-Type` header.
fn pick_boundary(payload: &[u8]) -> String {
    let mut boundary = String::from("delopayFormBoundary7MA4YWxkTrZu0gW");
    while contains(payload, boundary.as_bytes()) {
        boundary.push('-');
    }
    boundary
}

/// Whether `haystack` contains `needle`.
fn contains(haystack: &[u8], needle: &[u8]) -> bool {
    if needle.is_empty() || haystack.len() < needle.len() {
        return false;
    }
    haystack.windows(needle.len()).any(|w| w == needle)
}

/// Strip the characters that would let a file name escape its header: quotes,
/// backslashes, CR and LF. Path separators go too, so an upload cannot suggest
/// a directory to a naive server-side handler.
fn sanitize_file_name(name: &str) -> String {
    let cleaned: String = name
        .chars()
        .filter(|c| !matches!(c, '"' | '\\' | '\r' | '\n' | '/'))
        .collect();
    if cleaned.is_empty() {
        "upload".to_string()
    } else {
        cleaned
    }
}

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

    fn encoded(bytes: &[u8], file_name: &str) -> Multipart {
        encode_file(&FilePart {
            field: "file",
            file_name,
            content_type: "image/png",
            bytes,
        })
    }

    #[test]
    fn body_wraps_the_payload_in_matching_boundaries() {
        let out = encoded(b"PNGDATA", "logo.png");
        let text = String::from_utf8(out.body.clone()).unwrap();
        let boundary = out
            .content_type
            .strip_prefix("multipart/form-data; boundary=")
            .expect("content type advertises the boundary");

        assert!(text.starts_with(&format!("--{boundary}\r\n")));
        assert!(text.ends_with(&format!("\r\n--{boundary}--\r\n")));
        assert!(
            text.contains("Content-Disposition: form-data; name=\"file\"; filename=\"logo.png\"")
        );
        assert!(text.contains("Content-Type: image/png\r\n\r\nPNGDATA\r\n"));
    }

    #[test]
    fn boundary_is_extended_until_it_does_not_occur_in_the_payload() {
        // A payload that literally contains the default boundary: encoding it
        // with that boundary would let the file terminate its own part.
        let hostile = b"before--delopayFormBoundary7MA4YWxkTrZu0gW--after".to_vec();
        let out = encoded(&hostile, "logo.png");
        let boundary = out
            .content_type
            .strip_prefix("multipart/form-data; boundary=")
            .unwrap();

        assert!(
            boundary.ends_with('-'),
            "boundary should have been extended, got {boundary}"
        );
        assert!(!contains(&hostile, boundary.as_bytes()));
        // Exactly two occurrences of the chosen boundary: the opening
        // delimiter and the closing one.
        let count = out
            .body
            .windows(boundary.len())
            .filter(|w| *w == boundary.as_bytes())
            .count();
        assert_eq!(count, 2);
    }

    #[test]
    fn file_name_cannot_inject_headers_or_paths() {
        let out = encoded(b"x", "ev\"il\r\nX-Injected: 1/../logo.png");
        let text = String::from_utf8(out.body).unwrap();

        assert!(!text.contains("X-Injected: 1\r\n"));
        assert!(text.contains("filename=\"evilX-Injected: 1..logo.png\""));
    }

    #[test]
    fn empty_file_name_falls_back_rather_than_emitting_an_empty_filename() {
        let out = encoded(b"x", "///");
        let text = String::from_utf8(out.body).unwrap();
        assert!(text.contains("filename=\"upload\""));
    }

    #[test]
    fn binary_payloads_survive_byte_for_byte() {
        let bytes: Vec<u8> = (0u8..=255).collect();
        let out = encoded(&bytes, "logo.png");
        let marker = b"\r\n\r\n";
        let start = out
            .body
            .windows(marker.len())
            .position(|w| w == marker)
            .unwrap()
            + marker.len();
        assert_eq!(&out.body[start..start + bytes.len()], &bytes[..]);
    }
}