Skip to main content

opendal_core/raw/http_util/
multipart.rs

1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18use std::mem;
19use std::str::FromStr;
20
21use bytes::Bytes;
22use bytes::BytesMut;
23use http::HeaderMap;
24use http::HeaderName;
25use http::HeaderValue;
26use http::Method;
27use http::Request;
28use http::Response;
29use http::StatusCode;
30use http::Uri;
31use http::Version;
32use http::header::CONTENT_DISPOSITION;
33use http::header::CONTENT_LENGTH;
34use http::header::CONTENT_TYPE;
35use http::uri::PathAndQuery;
36
37use super::new_request_build_error;
38use crate::*;
39
40/// Multipart is a builder for multipart/form-data.
41#[derive(Debug)]
42pub struct Multipart<T: Part> {
43    boundary: String,
44    parts: Vec<T>,
45}
46
47impl<T: Part> Default for Multipart<T> {
48    fn default() -> Self {
49        Self::new()
50    }
51}
52
53impl<T: Part> Multipart<T> {
54    /// Create a new multipart with random boundary.
55    pub fn new() -> Self {
56        Multipart {
57            boundary: format!("opendal-{}", uuid::Uuid::new_v4()),
58            parts: Vec::default(),
59        }
60    }
61
62    /// Set the boundary with given string.
63    pub fn with_boundary(mut self, boundary: &str) -> Self {
64        self.boundary = boundary.to_string();
65        self
66    }
67
68    /// Insert a part into multipart.
69    pub fn part(mut self, part: T) -> Self {
70        self.parts.push(part);
71        self
72    }
73
74    /// Into parts.
75    pub fn into_parts(self) -> Vec<T> {
76        self.parts
77    }
78
79    /// Parse a response with multipart body into Multipart.
80    pub fn parse(mut self, bs: Bytes) -> Result<Self> {
81        let s = String::from_utf8(bs.to_vec()).map_err(|err| {
82            Error::new(
83                ErrorKind::Unexpected,
84                "multipart response contains invalid utf-8 chars",
85            )
86            .set_source(err)
87        })?;
88
89        let delimiter = format!("--{}", self.boundary);
90        let mut parts = s.split(&delimiter);
91
92        // Ignore the preamble before the first boundary delimiter.
93        parts.next();
94        for part in parts {
95            // The closing delimiter and everything after it are not a part.
96            if part.starts_with("--") {
97                break;
98            }
99            if part.is_empty() {
100                continue;
101            }
102
103            // Remove only the CRLF that belongs to the boundary delimiter.
104            let part = part.strip_suffix("\r\n").unwrap_or(part);
105            self.parts.push(T::parse(part)?);
106        }
107
108        Ok(self)
109    }
110
111    pub(crate) fn build(self) -> Buffer {
112        let mut bufs = Vec::with_capacity(self.parts.len() + 2);
113
114        // Build pre part.
115        let mut bs = BytesMut::new();
116        bs.extend_from_slice(b"--");
117        bs.extend_from_slice(self.boundary.as_bytes());
118        bs.extend_from_slice(b"\r\n");
119        let pre_part = Buffer::from(bs.freeze());
120
121        // Write all parts.
122        for part in self.parts {
123            bufs.push(pre_part.clone());
124            bufs.push(part.format());
125        }
126
127        // Write the last boundary
128        let mut bs = BytesMut::new();
129        bs.extend_from_slice(b"--");
130        bs.extend_from_slice(self.boundary.as_bytes());
131        bs.extend_from_slice(b"--");
132        bs.extend_from_slice(b"\r\n");
133
134        // Build final part.
135        bufs.push(Buffer::from(bs.freeze()));
136
137        bufs.into_iter().flatten().collect()
138    }
139
140    /// Consume the input and generate a request with multipart body.
141    ///
142    /// This function will make sure content_type and content_length set correctly.
143    pub fn apply(self, mut builder: http::request::Builder) -> Result<Request<Buffer>> {
144        let boundary = self.boundary.clone();
145        let buf = self.build();
146        let content_length = buf.len();
147
148        // Insert content type with correct boundary.
149        builder = builder.header(
150            CONTENT_TYPE,
151            format!("multipart/{}; boundary={}", T::TYPE, boundary).as_str(),
152        );
153        // Insert content length with calculated size.
154        builder = builder.header(CONTENT_LENGTH, content_length);
155
156        builder.body(buf).map_err(new_request_build_error)
157    }
158}
159
160/// Part is a trait for multipart part.
161pub trait Part: Sized + 'static {
162    /// TYPE is the type of multipart.
163    ///
164    /// Current available types are: `form-data` and `mixed`
165    const TYPE: &'static str;
166
167    /// format will generates the bytes.
168    fn format(self) -> Buffer;
169
170    /// parse will parse the bytes into a part.
171    fn parse(s: &str) -> Result<Self>;
172}
173
174/// FormDataPart is a builder for multipart/form-data part.
175pub struct FormDataPart {
176    headers: HeaderMap,
177
178    content: Buffer,
179}
180
181impl FormDataPart {
182    /// Create a new part builder
183    ///
184    /// # Panics
185    ///
186    /// Input name must be percent encoded.
187    pub fn new(name: &str) -> Self {
188        // Insert content disposition header for part.
189        let mut headers = HeaderMap::new();
190        headers.insert(
191            CONTENT_DISPOSITION,
192            format!("form-data; name=\"{name}\"").parse().unwrap(),
193        );
194
195        Self {
196            headers,
197            content: Buffer::new(),
198        }
199    }
200
201    /// Insert a header into part.
202    pub fn header(mut self, key: HeaderName, value: HeaderValue) -> Self {
203        self.headers.insert(key, value);
204        self
205    }
206
207    /// Set the content for this part.
208    pub fn content(mut self, content: impl Into<Buffer>) -> Self {
209        self.content = content.into();
210        self
211    }
212}
213
214impl Part for FormDataPart {
215    const TYPE: &'static str = "form-data";
216
217    fn format(self) -> Buffer {
218        let mut bufs = Vec::with_capacity(3);
219
220        // Building pre-content.
221        let mut bs = BytesMut::new();
222        for (k, v) in self.headers.iter() {
223            // Trick!
224            //
225            // Seafile could not recognize header names like `content-disposition`
226            // and requires to use `Content-Disposition`. So we hardcode the part
227            // headers name here.
228            match k.as_str() {
229                "content-disposition" => {
230                    bs.extend_from_slice("Content-Disposition".as_bytes());
231                }
232                _ => {
233                    bs.extend_from_slice(k.as_str().as_bytes());
234                }
235            }
236            bs.extend_from_slice(b": ");
237            bs.extend_from_slice(v.as_bytes());
238            bs.extend_from_slice(b"\r\n");
239        }
240        bs.extend_from_slice(b"\r\n");
241        bufs.push(Buffer::from(bs.freeze()));
242
243        // Building content.
244        bufs.push(self.content);
245
246        // Building post-content.
247        bufs.push(Buffer::from("\r\n"));
248
249        bufs.into_iter().flatten().collect()
250    }
251
252    fn parse(_: &str) -> Result<Self> {
253        Err(Error::new(
254            ErrorKind::Unsupported,
255            "parse of form-data is not supported",
256        ))
257    }
258}
259
260/// MixedPart is a builder for multipart/mixed part.
261pub struct MixedPart {
262    part_headers: HeaderMap,
263
264    /// Common
265    version: Version,
266    headers: HeaderMap,
267    content: Buffer,
268
269    /// Request only
270    method: Option<Method>,
271    uri: Option<Uri>,
272
273    /// Response only
274    status_code: Option<StatusCode>,
275}
276
277impl MixedPart {
278    /// Create a new mixed part with given uri.
279    pub fn new(uri: &str) -> Self {
280        let mut part_headers = HeaderMap::new();
281        part_headers.insert(CONTENT_TYPE, "application/http".parse().unwrap());
282        part_headers.insert("content-transfer-encoding", "binary".parse().unwrap());
283
284        let uri = Uri::from_str(uri).expect("the uri used to build a mixed part must be valid");
285
286        Self {
287            part_headers,
288
289            version: Version::HTTP_11,
290            headers: HeaderMap::new(),
291            content: Buffer::new(),
292
293            uri: Some(uri),
294            method: None,
295
296            status_code: None,
297        }
298    }
299
300    /// Build a mixed part from a request.
301    pub fn from_request(req: Request<Buffer>) -> Self {
302        let mut part_headers = HeaderMap::new();
303        part_headers.insert(CONTENT_TYPE, "application/http".parse().unwrap());
304        part_headers.insert("content-transfer-encoding", "binary".parse().unwrap());
305
306        let (parts, content) = req.into_parts();
307
308        Self {
309            part_headers,
310            uri: Some(
311                Uri::from_str(
312                    parts
313                        .uri
314                        .path_and_query()
315                        .unwrap_or(&PathAndQuery::from_static("/"))
316                        .as_str(),
317                )
318                .expect("the uri used to build a mixed part must be valid"),
319            ),
320            version: parts.version,
321            headers: parts.headers,
322            content,
323
324            method: Some(parts.method),
325            status_code: None,
326        }
327    }
328
329    /// Consume a mixed part to build a response.
330    pub fn into_response(mut self) -> Response<Buffer> {
331        let mut builder = Response::builder();
332
333        builder = builder.status(self.status_code.unwrap_or(StatusCode::OK));
334        builder = builder.version(self.version);
335        // Swap headers directly instead of copy the entire map.
336        mem::swap(builder.headers_mut().unwrap(), &mut self.headers);
337
338        builder
339            .body(self.content)
340            .expect("mixed part must be valid response")
341    }
342
343    /// Insert a part header into part.
344    pub fn part_header(mut self, key: HeaderName, value: HeaderValue) -> Self {
345        self.part_headers.insert(key, value);
346        self
347    }
348
349    /// Set the method for request in this part.
350    pub fn method(mut self, method: Method) -> Self {
351        self.method = Some(method);
352        self
353    }
354
355    /// Set the version for request in this part.
356    pub fn version(mut self, version: Version) -> Self {
357        self.version = version;
358        self
359    }
360
361    /// Insert a header into part.
362    pub fn header(mut self, key: HeaderName, value: HeaderValue) -> Self {
363        self.headers.insert(key, value);
364        self
365    }
366
367    /// Set the content for this part.
368    pub fn content(mut self, content: impl Into<Buffer>) -> Self {
369        self.content = content.into();
370        self
371    }
372}
373
374impl Part for MixedPart {
375    const TYPE: &'static str = "mixed";
376
377    fn format(self) -> Buffer {
378        let mut bufs = Vec::with_capacity(3);
379
380        // Write parts headers.
381        let mut bs = BytesMut::new();
382        for (k, v) in self.part_headers.iter() {
383            // Trick!
384            //
385            // Azblob could not recognize header names like `content-type`
386            // and requires to use `Content-Type`. So we hardcode the part
387            // headers name here.
388            match k.as_str() {
389                "content-type" => {
390                    bs.extend_from_slice("Content-Type".as_bytes());
391                }
392                "content-id" => {
393                    bs.extend_from_slice("Content-ID".as_bytes());
394                }
395                "content-transfer-encoding" => {
396                    bs.extend_from_slice("Content-Transfer-Encoding".as_bytes());
397                }
398                _ => {
399                    bs.extend_from_slice(k.as_str().as_bytes());
400                }
401            }
402            bs.extend_from_slice(b": ");
403            bs.extend_from_slice(v.as_bytes());
404            bs.extend_from_slice(b"\r\n");
405        }
406
407        // Write request line: `DELETE /container0/blob0 HTTP/1.1`
408        bs.extend_from_slice(b"\r\n");
409        bs.extend_from_slice(
410            self.method
411                .as_ref()
412                .expect("mixed part must be a valid request that contains method")
413                .as_str()
414                .as_bytes(),
415        );
416        bs.extend_from_slice(b" ");
417        let uri = self
418            .uri
419            .as_ref()
420            .expect("mixed part must be a valid request that contains uri");
421        bs.extend_from_slice(
422            uri.path_and_query()
423                .map_or_else(|| uri.path(), PathAndQuery::as_str)
424                .as_bytes(),
425        );
426        bs.extend_from_slice(b" ");
427        bs.extend_from_slice(format!("{:?}", self.version).as_bytes());
428        bs.extend_from_slice(b"\r\n");
429
430        // Write request headers.
431        for (k, v) in self.headers.iter() {
432            bs.extend_from_slice(k.as_str().as_bytes());
433            bs.extend_from_slice(b": ");
434            bs.extend_from_slice(v.as_bytes());
435            bs.extend_from_slice(b"\r\n");
436        }
437        bs.extend_from_slice(b"\r\n");
438        bufs.push(Buffer::from(bs.freeze()));
439
440        if !self.content.is_empty() {
441            bufs.push(self.content);
442            bufs.push(Buffer::from("\r\n"))
443        }
444
445        bufs.into_iter().flatten().collect()
446    }
447
448    /// TODO
449    ///
450    /// This is a simple implementation and have a lot of space to improve.
451    fn parse(s: &str) -> Result<Self> {
452        let parts = s.splitn(2, "\r\n\r\n").collect::<Vec<&str>>();
453        let part_headers_content = parts[0];
454        let http_response = parts.get(1).unwrap_or(&"");
455
456        let mut part_headers = HeaderMap::new();
457        for line in part_headers_content.lines() {
458            let parts = line.splitn(2, ": ").collect::<Vec<&str>>();
459            if parts.len() == 2 {
460                let header_name = HeaderName::from_str(parts[0]).map_err(|err| {
461                    Error::new(
462                        ErrorKind::Unexpected,
463                        "multipart response contains invalid part header name",
464                    )
465                    .set_source(err)
466                })?;
467                let header_value = parts[1].parse().map_err(|err| {
468                    Error::new(
469                        ErrorKind::Unexpected,
470                        "multipart response contains invalid part header value",
471                    )
472                    .set_source(err)
473                })?;
474
475                part_headers.insert(header_name, header_value);
476            }
477        }
478
479        let (headers_content, body_content) = http_response
480            .split_once("\r\n\r\n")
481            .unwrap_or((http_response, ""));
482        let body_bytes = Buffer::from(body_content.as_bytes().to_vec());
483
484        let status_line = headers_content.lines().next().unwrap_or("");
485        let status_code = status_line
486            .split_whitespace()
487            .nth(1)
488            .ok_or_else(|| {
489                Error::new(
490                    ErrorKind::Unexpected,
491                    "multipart response contains invalid status line",
492                )
493            })?
494            .parse::<u16>()
495            .map_err(|err| {
496                Error::new(
497                    ErrorKind::Unexpected,
498                    "multipart response contains invalid status code",
499                )
500                .set_source(err)
501            })?;
502
503        let mut headers = HeaderMap::new();
504        for line in headers_content.lines().skip(1) {
505            let parts = line.splitn(2, ": ").collect::<Vec<&str>>();
506            if parts.len() == 2 {
507                let header_name = HeaderName::from_str(parts[0]).map_err(|err| {
508                    Error::new(
509                        ErrorKind::Unexpected,
510                        "multipart response contains invalid part header name",
511                    )
512                    .set_source(err)
513                })?;
514                let header_value = parts[1].parse().map_err(|err| {
515                    Error::new(
516                        ErrorKind::Unexpected,
517                        "multipart response contains invalid part header value",
518                    )
519                    .set_source(err)
520                })?;
521
522                headers.insert(header_name, header_value);
523            }
524        }
525
526        Ok(Self {
527            part_headers,
528            version: Version::HTTP_11,
529            headers,
530            content: body_bytes,
531
532            method: None,
533            uri: None,
534
535            status_code: Some(StatusCode::from_u16(status_code).map_err(|err| {
536                Error::new(
537                    ErrorKind::Unexpected,
538                    "multipart response contains invalid status code",
539                )
540                .set_source(err)
541            })?),
542        })
543    }
544}
545
546/// RelatedPart is a builder for multipart/related part.
547pub struct RelatedPart {
548    /// Common
549    headers: HeaderMap,
550    content: Buffer,
551}
552
553impl Default for RelatedPart {
554    fn default() -> Self {
555        Self::new()
556    }
557}
558
559impl RelatedPart {
560    /// Create a new related
561    pub fn new() -> Self {
562        Self {
563            headers: HeaderMap::new(),
564            content: Buffer::new(),
565        }
566    }
567
568    /// Build a mixed part from a request.
569    pub fn from_request(req: Request<Buffer>) -> Self {
570        let (parts, content) = req.into_parts();
571
572        Self {
573            headers: parts.headers,
574            content,
575        }
576    }
577
578    /// Consume a mixed part to build a response.
579    pub fn into_response(mut self) -> Response<Buffer> {
580        let mut builder = Response::builder();
581
582        // Swap headers directly instead of copy the entire map.
583        mem::swap(builder.headers_mut().unwrap(), &mut self.headers);
584
585        builder
586            .body(self.content)
587            .expect("a related part must be valid response")
588    }
589
590    /// Insert a header into part.
591    pub fn header(mut self, key: HeaderName, value: HeaderValue) -> Self {
592        self.headers.insert(key, value);
593        self
594    }
595
596    /// Set the content for this part.
597    pub fn content(mut self, content: impl Into<Buffer>) -> Self {
598        self.content = content.into();
599        self
600    }
601}
602
603impl Part for RelatedPart {
604    const TYPE: &'static str = "related";
605
606    fn format(self) -> Buffer {
607        // This is what multipart/related body might look for an insert in GCS
608        // https://cloud.google.com/storage/docs/uploading-objects
609        /*
610        --separator_string
611        Content-Type: application/json; charset=UTF-8
612
613        {"name":"my-document.txt"}
614
615        --separator_string
616        Content-Type: text/plain
617
618        This is a text file.
619        --separator_string--
620        */
621
622        let mut bufs = Vec::with_capacity(3);
623        let mut bs = BytesMut::new();
624
625        // Write request headers.
626        for (k, v) in self.headers.iter() {
627            bs.extend_from_slice(k.as_str().as_bytes());
628            bs.extend_from_slice(b": ");
629            bs.extend_from_slice(v.as_bytes());
630            bs.extend_from_slice(b"\r\n");
631        }
632        bs.extend_from_slice(b"\r\n");
633        bufs.push(Buffer::from(bs.freeze()));
634
635        if !self.content.is_empty() {
636            bufs.push(self.content);
637            bufs.push(Buffer::from("\r\n"))
638        }
639
640        bufs.into_iter().flatten().collect()
641    }
642
643    fn parse(_s: &str) -> Result<Self> {
644        Err(Error::new(
645            ErrorKind::Unsupported,
646            "parsing multipart/related is not supported",
647        ))
648    }
649}
650
651#[cfg(test)]
652mod tests {
653    use http::header::CONTENT_TYPE;
654    use pretty_assertions::assert_eq;
655
656    use super::*;
657
658    #[test]
659    fn test_multipart_formdata_basic() -> Result<()> {
660        let multipart = Multipart::new()
661            .with_boundary("lalala")
662            .part(FormDataPart::new("foo").content(Bytes::from("bar")))
663            .part(FormDataPart::new("hello").content(Bytes::from("world")));
664
665        let bs = multipart.build();
666
667        let expected = "--lalala\r\n\
668             Content-Disposition: form-data; name=\"foo\"\r\n\
669             \r\n\
670             bar\r\n\
671             --lalala\r\n\
672             Content-Disposition: form-data; name=\"hello\"\r\n\
673             \r\n\
674             world\r\n\
675             --lalala--\r\n";
676
677        assert_eq!(Bytes::from(expected), bs.to_bytes());
678        Ok(())
679    }
680
681    /// This test is inspired by <https://docs.aws.amazon.com/AmazonS3/latest/userguide/HTTPPOSTExamples.html>
682    #[test]
683    fn test_multipart_formdata_s3_form_upload() -> Result<()> {
684        let multipart = Multipart::new()
685            .with_boundary("9431149156168")
686            .part(FormDataPart::new("key").content("user/eric/MyPicture.jpg"))
687            .part(FormDataPart::new("acl").content("public-read"))
688            .part(FormDataPart::new("success_action_redirect").content(
689                "https://awsexamplebucket1.s3.us-west-1.amazonaws.com/successful_upload.html",
690            ))
691            .part(FormDataPart::new("content-type").content("image/jpeg"))
692            .part(FormDataPart::new("x-amz-meta-uuid").content("14365123651274"))
693            .part(FormDataPart::new("x-amz-meta-tag").content("Some,Tag,For,Picture"))
694            .part(FormDataPart::new("AWSAccessKeyId").content("AKIAIOSFODNN7EXAMPLE"))
695            .part(FormDataPart::new("Policy").content("eyAiZXhwaXJhdGlvbiI6ICIyMDA3LTEyLTAxVDEyOjAwOjAwLjAwMFoiLAogICJjb25kaXRpb25zIjogWwogICAgeyJidWNrZXQiOiAiam9obnNtaXRoIn0sCiAgICBbInN0YXJ0cy13aXRoIiwgIiRrZXkiLCAidXNlci9lcmljLyJdLAogICAgeyJhY2wiOiAicHVibGljLXJlYWQifSwKICAgIHsic3VjY2Vzc19hY3Rpb25fcmVkaXJlY3QiOiAiaHR0cDovL2pvaG5zbWl0aC5zMy5hbWF6b25hd3MuY29tL3N1Y2Nlc3NmdWxfdXBsb2FkLmh0bWwifSwKICAgIFsic3RhcnRzLXdpdGgiLCAiJENvbnRlbnQtVHlwZSIsICJpbWFnZS8iXSwKICAgIHsieC1hbXotbWV0YS11dWlkIjogIjE0MzY1MTIzNjUxMjc0In0sCiAgICBbInN0YXJ0cy13aXRoIiwgIiR4LWFtei1tZXRhLXRhZyIsICIiXQogIF0KfQo="))
696            .part(FormDataPart::new("Signature").content("0RavWzkygo6QX9caELEqKi9kDbU="))
697            .part(FormDataPart::new("file").header(CONTENT_TYPE, "image/jpeg".parse().unwrap()).content("...file content...")).part(FormDataPart::new("submit").content("Upload to Amazon S3"));
698
699        let bs = multipart.build();
700
701        let expected = r#"--9431149156168
702Content-Disposition: form-data; name="key"
703
704user/eric/MyPicture.jpg
705--9431149156168
706Content-Disposition: form-data; name="acl"
707
708public-read
709--9431149156168
710Content-Disposition: form-data; name="success_action_redirect"
711
712https://awsexamplebucket1.s3.us-west-1.amazonaws.com/successful_upload.html
713--9431149156168
714Content-Disposition: form-data; name="content-type"
715
716image/jpeg
717--9431149156168
718Content-Disposition: form-data; name="x-amz-meta-uuid"
719
72014365123651274
721--9431149156168
722Content-Disposition: form-data; name="x-amz-meta-tag"
723
724Some,Tag,For,Picture
725--9431149156168
726Content-Disposition: form-data; name="AWSAccessKeyId"
727
728AKIAIOSFODNN7EXAMPLE
729--9431149156168
730Content-Disposition: form-data; name="Policy"
731
732eyAiZXhwaXJhdGlvbiI6ICIyMDA3LTEyLTAxVDEyOjAwOjAwLjAwMFoiLAogICJjb25kaXRpb25zIjogWwogICAgeyJidWNrZXQiOiAiam9obnNtaXRoIn0sCiAgICBbInN0YXJ0cy13aXRoIiwgIiRrZXkiLCAidXNlci9lcmljLyJdLAogICAgeyJhY2wiOiAicHVibGljLXJlYWQifSwKICAgIHsic3VjY2Vzc19hY3Rpb25fcmVkaXJlY3QiOiAiaHR0cDovL2pvaG5zbWl0aC5zMy5hbWF6b25hd3MuY29tL3N1Y2Nlc3NmdWxfdXBsb2FkLmh0bWwifSwKICAgIFsic3RhcnRzLXdpdGgiLCAiJENvbnRlbnQtVHlwZSIsICJpbWFnZS8iXSwKICAgIHsieC1hbXotbWV0YS11dWlkIjogIjE0MzY1MTIzNjUxMjc0In0sCiAgICBbInN0YXJ0cy13aXRoIiwgIiR4LWFtei1tZXRhLXRhZyIsICIiXQogIF0KfQo=
733--9431149156168
734Content-Disposition: form-data; name="Signature"
735
7360RavWzkygo6QX9caELEqKi9kDbU=
737--9431149156168
738Content-Disposition: form-data; name="file"
739content-type: image/jpeg
740
741...file content...
742--9431149156168
743Content-Disposition: form-data; name="submit"
744
745Upload to Amazon S3
746--9431149156168--
747"#;
748
749        assert_eq!(
750            expected,
751            // Rust can't represent `\r` in a string literal, so we
752            // replace `\r\n` with `\n` for comparison
753            String::from_utf8(bs.to_bytes().to_vec())
754                .unwrap()
755                .replace("\r\n", "\n")
756        );
757
758        Ok(())
759    }
760
761    /// This test is inspired by <https://cloud.google.com/storage/docs/batch>
762    #[test]
763    fn test_multipart_mixed_gcs_batch_metadata() -> Result<()> {
764        let multipart = Multipart::new()
765            .with_boundary("===============7330845974216740156==")
766            .part(
767                MixedPart::new("/storage/v1/b/example-bucket/o/obj1")
768                    .method(Method::PATCH)
769                    .part_header(
770                        "content-id".parse().unwrap(),
771                        "<b29c5de2-0db4-490b-b421-6a51b598bd22+1>".parse().unwrap(),
772                    )
773                    .header(
774                        "content-type".parse().unwrap(),
775                        "application/json".parse().unwrap(),
776                    )
777                    .header(
778                        "accept".parse().unwrap(),
779                        "application/json".parse().unwrap(),
780                    )
781                    .header("content-length".parse().unwrap(), "31".parse().unwrap())
782                    .content(r#"{"metadata": {"type": "tabby"}}"#),
783            )
784            .part(
785                MixedPart::new("/storage/v1/b/example-bucket/o/obj2")
786                    .method(Method::PATCH)
787                    .part_header(
788                        "content-id".parse().unwrap(),
789                        "<b29c5de2-0db4-490b-b421-6a51b598bd22+2>".parse().unwrap(),
790                    )
791                    .header(
792                        "content-type".parse().unwrap(),
793                        "application/json".parse().unwrap(),
794                    )
795                    .header(
796                        "accept".parse().unwrap(),
797                        "application/json".parse().unwrap(),
798                    )
799                    .header("content-length".parse().unwrap(), "32".parse().unwrap())
800                    .content(r#"{"metadata": {"type": "tuxedo"}}"#),
801            )
802            .part(
803                MixedPart::new("/storage/v1/b/example-bucket/o/obj3")
804                    .method(Method::PATCH)
805                    .part_header(
806                        "content-id".parse().unwrap(),
807                        "<b29c5de2-0db4-490b-b421-6a51b598bd22+3>".parse().unwrap(),
808                    )
809                    .header(
810                        "content-type".parse().unwrap(),
811                        "application/json".parse().unwrap(),
812                    )
813                    .header(
814                        "accept".parse().unwrap(),
815                        "application/json".parse().unwrap(),
816                    )
817                    .header("content-length".parse().unwrap(), "32".parse().unwrap())
818                    .content(r#"{"metadata": {"type": "calico"}}"#),
819            );
820
821        let bs = multipart.build();
822
823        let expected = r#"--===============7330845974216740156==
824Content-Type: application/http
825Content-Transfer-Encoding: binary
826Content-ID: <b29c5de2-0db4-490b-b421-6a51b598bd22+1>
827
828PATCH /storage/v1/b/example-bucket/o/obj1 HTTP/1.1
829content-type: application/json
830accept: application/json
831content-length: 31
832
833{"metadata": {"type": "tabby"}}
834--===============7330845974216740156==
835Content-Type: application/http
836Content-Transfer-Encoding: binary
837Content-ID: <b29c5de2-0db4-490b-b421-6a51b598bd22+2>
838
839PATCH /storage/v1/b/example-bucket/o/obj2 HTTP/1.1
840content-type: application/json
841accept: application/json
842content-length: 32
843
844{"metadata": {"type": "tuxedo"}}
845--===============7330845974216740156==
846Content-Type: application/http
847Content-Transfer-Encoding: binary
848Content-ID: <b29c5de2-0db4-490b-b421-6a51b598bd22+3>
849
850PATCH /storage/v1/b/example-bucket/o/obj3 HTTP/1.1
851content-type: application/json
852accept: application/json
853content-length: 32
854
855{"metadata": {"type": "calico"}}
856--===============7330845974216740156==--
857"#;
858
859        assert_eq!(
860            expected,
861            // Rust can't represent `\r` in a string literal, so we
862            // replace `\r\n` with `\n` for comparison
863            String::from_utf8(bs.to_bytes().to_vec())
864                .unwrap()
865                .replace("\r\n", "\n")
866        );
867
868        Ok(())
869    }
870
871    #[test]
872    fn test_multipart_mixed_request_line_keeps_query() {
873        let req = Request::delete(
874            "https://storage.googleapis.com/storage/v1/b/example-bucket/o/obj1?generation=123",
875        )
876        .body(Buffer::new())
877        .unwrap();
878        let multipart = Multipart::new()
879            .with_boundary("batch")
880            .part(MixedPart::from_request(req));
881
882        let bs = String::from_utf8(multipart.build().to_bytes().to_vec()).unwrap();
883
884        assert!(bs.contains(
885            "\r\nDELETE /storage/v1/b/example-bucket/o/obj1?generation=123 HTTP/1.1\r\n"
886        ));
887    }
888
889    /// This test is inspired by <https://learn.microsoft.com/en-us/rest/api/storageservices/blob-batch?tabs=azure-ad>
890    #[test]
891    fn test_multipart_mixed_azblob_batch_delete() -> Result<()> {
892        let multipart = Multipart::new()
893            .with_boundary("batch_357de4f7-6d0b-4e02-8cd2-6361411a9525")
894            .part(
895                MixedPart::new("/container0/blob0")
896                    .method(Method::DELETE)
897                    .part_header("content-id".parse().unwrap(), "0".parse().unwrap())
898                    .header(
899                        "x-ms-date".parse().unwrap(),
900                        "Thu, 14 Jun 2018 16:46:54 GMT".parse().unwrap(),
901                    )
902                    .header(
903                        "authorization".parse().unwrap(),
904                        "SharedKey account:G4jjBXA7LI/RnWKIOQ8i9xH4p76pAQ+4Fs4R1VxasaE="
905                            .parse()
906                            .unwrap(),
907                    )
908                    .header("content-length".parse().unwrap(), "0".parse().unwrap()),
909            )
910            .part(
911                MixedPart::new("/container1/blob1")
912                    .method(Method::DELETE)
913                    .part_header("content-id".parse().unwrap(), "1".parse().unwrap())
914                    .header(
915                        "x-ms-date".parse().unwrap(),
916                        "Thu, 14 Jun 2018 16:46:54 GMT".parse().unwrap(),
917                    )
918                    .header(
919                        "authorization".parse().unwrap(),
920                        "SharedKey account:IvCoYDQ+0VcaA/hKFjUmQmIxXv2RT3XwwTsOTHL39HI="
921                            .parse()
922                            .unwrap(),
923                    )
924                    .header("content-length".parse().unwrap(), "0".parse().unwrap()),
925            )
926            .part(
927                MixedPart::new("/container2/blob2")
928                    .method(Method::DELETE)
929                    .part_header("content-id".parse().unwrap(), "2".parse().unwrap())
930                    .header(
931                        "x-ms-date".parse().unwrap(),
932                        "Thu, 14 Jun 2018 16:46:54 GMT".parse().unwrap(),
933                    )
934                    .header(
935                        "authorization".parse().unwrap(),
936                        "SharedKey account:S37N2JTjcmOQVLHLbDmp2johz+KpTJvKhbVc4M7+UqI="
937                            .parse()
938                            .unwrap(),
939                    )
940                    .header("content-length".parse().unwrap(), "0".parse().unwrap()),
941            );
942
943        let bs = multipart.build();
944
945        let expected = r#"--batch_357de4f7-6d0b-4e02-8cd2-6361411a9525
946Content-Type: application/http
947Content-Transfer-Encoding: binary
948Content-ID: 0
949
950DELETE /container0/blob0 HTTP/1.1
951x-ms-date: Thu, 14 Jun 2018 16:46:54 GMT
952authorization: SharedKey account:G4jjBXA7LI/RnWKIOQ8i9xH4p76pAQ+4Fs4R1VxasaE=
953content-length: 0
954
955--batch_357de4f7-6d0b-4e02-8cd2-6361411a9525
956Content-Type: application/http
957Content-Transfer-Encoding: binary
958Content-ID: 1
959
960DELETE /container1/blob1 HTTP/1.1
961x-ms-date: Thu, 14 Jun 2018 16:46:54 GMT
962authorization: SharedKey account:IvCoYDQ+0VcaA/hKFjUmQmIxXv2RT3XwwTsOTHL39HI=
963content-length: 0
964
965--batch_357de4f7-6d0b-4e02-8cd2-6361411a9525
966Content-Type: application/http
967Content-Transfer-Encoding: binary
968Content-ID: 2
969
970DELETE /container2/blob2 HTTP/1.1
971x-ms-date: Thu, 14 Jun 2018 16:46:54 GMT
972authorization: SharedKey account:S37N2JTjcmOQVLHLbDmp2johz+KpTJvKhbVc4M7+UqI=
973content-length: 0
974
975--batch_357de4f7-6d0b-4e02-8cd2-6361411a9525--
976"#;
977
978        assert_eq!(
979            expected,
980            // Rust can't represent `\r` in a string literal, so we
981            // replace `\r\n` with `\n` for comparison
982            String::from_utf8(bs.to_bytes().to_vec())
983                .unwrap()
984                .replace("\r\n", "\n")
985        );
986
987        Ok(())
988    }
989
990    /// This test is inspired by <https://cloud.google.com/storage/docs/batch>
991    #[test]
992    fn test_multipart_mixed_gcs_batch_metadata_response() {
993        let response = r#"--batch_pK7JBAk73-E=_AA5eFwv4m2Q=
994Content-Type: application/http
995Content-ID: <response-b29c5de2-0db4-490b-b421-6a51b598bd22+1>
996
997HTTP/1.1 200 OK
998ETag: "lGaP-E0memYDumK16YuUDM_6Gf0/V43j6azD55CPRGb9b6uytDYl61Y"
999Content-Type: application/json; charset=UTF-8
1000Date: Mon, 22 Jan 2018 18:56:00 GMT
1001Expires: Mon, 22 Jan 2018 18:56:00 GMT
1002Cache-Control: private, max-age=0
1003Content-Length: 846
1004
1005{"kind": "storage#object","id": "example-bucket/obj1/1495822576643790","metadata": {"type": "tabby"}}
1006
1007--batch_pK7JBAk73-E=_AA5eFwv4m2Q=
1008Content-Type: application/http
1009Content-ID: <response-b29c5de2-0db4-490b-b421-6a51b598bd22+2>
1010
1011HTTP/1.1 200 OK
1012ETag: "lGaP-E0memYDumK16YuUDM_6Gf0/91POdd-sxSAkJnS8Dm7wMxBSDKk"
1013Content-Type: application/json; charset=UTF-8
1014Date: Mon, 22 Jan 2018 18:56:00 GMT
1015Expires: Mon, 22 Jan 2018 18:56:00 GMT
1016Cache-Control: private, max-age=0
1017Content-Length: 846
1018
1019{"kind": "storage#object","id": "example-bucket/obj2/1495822576643790","metadata": {"type": "tuxedo"}}
1020
1021--batch_pK7JBAk73-E=_AA5eFwv4m2Q=
1022Content-Type: application/http
1023Content-ID: <response-b29c5de2-0db4-490b-b421-6a51b598bd22+3>
1024
1025HTTP/1.1 200 OK
1026ETag: "lGaP-E0memYDumK16YuUDM_6Gf0/d2Z1F1_ZVbB1dC0YKM9rX5VAgIQ"
1027Content-Type: application/json; charset=UTF-8
1028Date: Mon, 22 Jan 2018 18:56:00 GMT
1029Expires: Mon, 22 Jan 2018 18:56:00 GMT
1030Cache-Control: private, max-age=0
1031Content-Length: 846
1032
1033{"kind": "storage#object","id": "example-bucket/obj3/1495822576643790","metadata": {"type": "calico"}}
1034
1035--batch_pK7JBAk73-E=_AA5eFwv4m2Q=--"#.replace('\n', "\r\n");
1036
1037        let multipart: Multipart<MixedPart> = Multipart::new()
1038            .with_boundary("batch_pK7JBAk73-E=_AA5eFwv4m2Q=")
1039            .parse(Bytes::from(response))
1040            .unwrap();
1041
1042        let part0_bs = Bytes::from_static(
1043            concat!(
1044                r#"{"kind": "storage#object","id": "example-bucket/obj1/1495822576643790","metadata": {"type": "tabby"}}"#,
1045                "\r\n"
1046            )
1047            .as_bytes(),
1048        );
1049        let part1_bs = Bytes::from_static(
1050            concat!(
1051                r#"{"kind": "storage#object","id": "example-bucket/obj2/1495822576643790","metadata": {"type": "tuxedo"}}"#,
1052                "\r\n"
1053            )
1054            .as_bytes(),
1055        );
1056        let part2_bs = Bytes::from_static(
1057            concat!(
1058                r#"{"kind": "storage#object","id": "example-bucket/obj3/1495822576643790","metadata": {"type": "calico"}}"#,
1059                "\r\n"
1060            )
1061            .as_bytes(),
1062        );
1063
1064        assert_eq!(multipart.parts.len(), 3);
1065
1066        assert_eq!(multipart.parts[0].part_headers, {
1067            let mut h = HeaderMap::new();
1068            h.insert("Content-Type", "application/http".parse().unwrap());
1069            h.insert(
1070                "Content-ID",
1071                "<response-b29c5de2-0db4-490b-b421-6a51b598bd22+1>"
1072                    .parse()
1073                    .unwrap(),
1074            );
1075
1076            h
1077        });
1078        assert_eq!(multipart.parts[0].version, Version::HTTP_11);
1079        assert_eq!(multipart.parts[0].headers, {
1080            let mut h = HeaderMap::new();
1081            h.insert(
1082                "ETag",
1083                "\"lGaP-E0memYDumK16YuUDM_6Gf0/V43j6azD55CPRGb9b6uytDYl61Y\""
1084                    .parse()
1085                    .unwrap(),
1086            );
1087            h.insert(
1088                "Content-Type",
1089                "application/json; charset=UTF-8".parse().unwrap(),
1090            );
1091            h.insert("Date", "Mon, 22 Jan 2018 18:56:00 GMT".parse().unwrap());
1092            h.insert("Expires", "Mon, 22 Jan 2018 18:56:00 GMT".parse().unwrap());
1093            h.insert("Cache-Control", "private, max-age=0".parse().unwrap());
1094            h.insert("Content-Length", "846".parse().unwrap());
1095
1096            h
1097        });
1098        assert_eq!(multipart.parts[0].content.to_bytes(), part0_bs);
1099        assert_eq!(multipart.parts[0].uri, None);
1100        assert_eq!(multipart.parts[0].method, None);
1101        assert_eq!(
1102            multipart.parts[0].status_code,
1103            Some(StatusCode::from_u16(200).unwrap())
1104        );
1105
1106        assert_eq!(multipart.parts[1].part_headers, {
1107            let mut h = HeaderMap::new();
1108            h.insert("Content-Type", "application/http".parse().unwrap());
1109            h.insert(
1110                "Content-ID",
1111                "<response-b29c5de2-0db4-490b-b421-6a51b598bd22+2>"
1112                    .parse()
1113                    .unwrap(),
1114            );
1115
1116            h
1117        });
1118        assert_eq!(multipart.parts[1].version, Version::HTTP_11);
1119        assert_eq!(multipart.parts[1].headers, {
1120            let mut h = HeaderMap::new();
1121            h.insert(
1122                "ETag",
1123                "\"lGaP-E0memYDumK16YuUDM_6Gf0/91POdd-sxSAkJnS8Dm7wMxBSDKk\""
1124                    .parse()
1125                    .unwrap(),
1126            );
1127            h.insert(
1128                "Content-Type",
1129                "application/json; charset=UTF-8".parse().unwrap(),
1130            );
1131            h.insert("Date", "Mon, 22 Jan 2018 18:56:00 GMT".parse().unwrap());
1132            h.insert("Expires", "Mon, 22 Jan 2018 18:56:00 GMT".parse().unwrap());
1133            h.insert("Cache-Control", "private, max-age=0".parse().unwrap());
1134            h.insert("Content-Length", "846".parse().unwrap());
1135
1136            h
1137        });
1138        assert_eq!(multipart.parts[1].content.to_bytes(), part1_bs);
1139        assert_eq!(multipart.parts[1].uri, None);
1140        assert_eq!(multipart.parts[1].method, None);
1141        assert_eq!(
1142            multipart.parts[1].status_code,
1143            Some(StatusCode::from_u16(200).unwrap())
1144        );
1145
1146        assert_eq!(multipart.parts[2].part_headers, {
1147            let mut h = HeaderMap::new();
1148            h.insert("Content-Type", "application/http".parse().unwrap());
1149            h.insert(
1150                "Content-ID",
1151                "<response-b29c5de2-0db4-490b-b421-6a51b598bd22+3>"
1152                    .parse()
1153                    .unwrap(),
1154            );
1155
1156            h
1157        });
1158        assert_eq!(multipart.parts[2].version, Version::HTTP_11);
1159        assert_eq!(multipart.parts[2].headers, {
1160            let mut h = HeaderMap::new();
1161            h.insert(
1162                "ETag",
1163                "\"lGaP-E0memYDumK16YuUDM_6Gf0/d2Z1F1_ZVbB1dC0YKM9rX5VAgIQ\""
1164                    .parse()
1165                    .unwrap(),
1166            );
1167            h.insert(
1168                "Content-Type",
1169                "application/json; charset=UTF-8".parse().unwrap(),
1170            );
1171            h.insert("Date", "Mon, 22 Jan 2018 18:56:00 GMT".parse().unwrap());
1172            h.insert("Expires", "Mon, 22 Jan 2018 18:56:00 GMT".parse().unwrap());
1173            h.insert("Cache-Control", "private, max-age=0".parse().unwrap());
1174            h.insert("Content-Length", "846".parse().unwrap());
1175
1176            h
1177        });
1178        assert_eq!(multipart.parts[2].content.to_bytes(), part2_bs);
1179        assert_eq!(multipart.parts[2].uri, None);
1180        assert_eq!(multipart.parts[2].method, None);
1181        assert_eq!(
1182            multipart.parts[2].status_code,
1183            Some(StatusCode::from_u16(200).unwrap())
1184        );
1185    }
1186
1187    #[test]
1188    fn test_multipart_mixed_response_ignores_preamble_and_epilogue() {
1189        for preamble in ["batch response preamble\r\n", "\r\n"] {
1190            let response = format!(
1191                "{preamble}\
1192                 --batch\r\n\
1193                 Content-Type: application/http\r\n\
1194                 \r\n\
1195                 HTTP/1.1 202 Accepted\r\n\
1196                 \r\n\
1197                 first\r\n\
1198                 --batch\r\n\
1199                 Content-Type: application/http\r\n\
1200                 \r\n\
1201                 HTTP/1.1 404 Not Found\r\n\
1202                 \r\n\
1203                 second\r\n\
1204                 --batch--\r\n\
1205                 batch response epilogue"
1206            );
1207
1208            let multipart: Multipart<MixedPart> = Multipart::new()
1209                .with_boundary("batch")
1210                .parse(Bytes::from(response))
1211                .unwrap();
1212
1213            assert_eq!(multipart.parts.len(), 2);
1214            assert_eq!(multipart.parts[0].status_code, Some(StatusCode::ACCEPTED));
1215            assert_eq!(multipart.parts[1].status_code, Some(StatusCode::NOT_FOUND));
1216        }
1217    }
1218
1219    #[test]
1220    fn test_multipart_mixed_response_rejects_invalid_status_line() {
1221        for response in [
1222            "",
1223            "Content-Type: application/http\r\n\r\n",
1224            "Content-Type: application/http\r\n\r\nHTTP/1.1\r\n\r\n",
1225            "Content-Type: application/http\r\n\r\nHTTP/1.1 INVALID\r\n\r\n",
1226        ] {
1227            let err = MixedPart::parse(response)
1228                .err()
1229                .expect("invalid status line must be rejected");
1230            assert_eq!(err.kind(), ErrorKind::Unexpected);
1231        }
1232    }
1233
1234    #[test]
1235    fn test_multipart_mixed_response_preserves_multiline_body() {
1236        let response = "--batch\r\n\
1237                        Content-Type: application/http\r\n\
1238                        \r\n\
1239                        HTTP/1.1 200 OK\r\n\
1240                        Content-Type: text/plain\r\n\
1241                        \r\n\
1242                        para1\r\n\r\npara2\r\n\
1243                        \r\n\
1244                        --batch--\r\n";
1245
1246        let multipart: Multipart<MixedPart> = Multipart::new()
1247            .with_boundary("batch")
1248            .parse(Bytes::from_static(response.as_bytes()))
1249            .unwrap();
1250
1251        assert_eq!(multipart.parts.len(), 1);
1252        assert_eq!(
1253            multipart.parts[0].content.to_bytes(),
1254            Bytes::from_static(b"para1\r\n\r\npara2\r\n")
1255        );
1256    }
1257
1258    #[test]
1259    fn test_multipart_related_gcs_simple() {
1260        // This is what multipart/related body might look for an insert in GCS
1261        // https://cloud.google.com/storage/docs/uploading-objects
1262        let expected = r#"--separator_string
1263content-type: application/json; charset=UTF-8
1264
1265{"name":"my-document.txt"}
1266--separator_string
1267content-type: text/plain
1268
1269This is a text file.
1270--separator_string--
1271"#;
1272
1273        let multipart = Multipart::new()
1274            .with_boundary("separator_string")
1275            .part(
1276                RelatedPart::new()
1277                    .header(
1278                        "Content-Type".parse().unwrap(),
1279                        "application/json; charset=UTF-8".parse().unwrap(),
1280                    )
1281                    .content(r#"{"name":"my-document.txt"}"#),
1282            )
1283            .part(
1284                RelatedPart::new()
1285                    .header(
1286                        "Content-Type".parse().unwrap(),
1287                        "text/plain".parse().unwrap(),
1288                    )
1289                    .content("This is a text file."),
1290            );
1291
1292        let bs = multipart.build();
1293
1294        let output = String::from_utf8(bs.to_bytes().to_vec())
1295            .unwrap()
1296            .replace("\r\n", "\n");
1297
1298        assert_eq!(output, expected);
1299    }
1300}