1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
use std::borrow::Cow;
use std::error::Error as StdError;
use std::fmt::{self, Display};

use url::{ParseError, Url};

use crate::actions::{
    AbortMultipartUpload, CreateBucket, DeleteBucket, DeleteObject, GetObject, HeadBucket,
    HeadObject, PutObject, UploadPart,
};
#[cfg(feature = "full")]
use crate::actions::{
    CompleteMultipartUpload, CreateMultipartUpload, DeleteObjects, ListObjectsV2, ListParts,
};
use crate::signing::util::percent_encode_path;
use crate::Credentials;

/// An S3 bucket
///
/// ## Path style url
///
/// ```rust
/// # use rusty_s3::{Bucket, UrlStyle};
/// let endpoint = "https://s3.dualstack.eu-west-1.amazonaws.com".parse().expect("endpoint is a valid Url");
/// let path_style = UrlStyle::Path;
/// let name = "rusty-s3";
/// let region = "eu-west-1";
///
/// let bucket = Bucket::new(endpoint, path_style, name, region).expect("Url has a valid scheme and host");
/// assert_eq!(bucket.base_url().as_str(), "https://s3.dualstack.eu-west-1.amazonaws.com/rusty-s3/");
/// assert_eq!(bucket.name(), "rusty-s3");
/// assert_eq!(bucket.region(), "eu-west-1");
/// assert_eq!(bucket.object_url("duck.jpg").expect("url is valid").as_str(), "https://s3.dualstack.eu-west-1.amazonaws.com/rusty-s3/duck.jpg");
/// ```
///
/// ## Domain style url
///
/// ```rust
/// # use rusty_s3::{Bucket, UrlStyle};
/// let endpoint = "https://s3.dualstack.eu-west-1.amazonaws.com".parse().expect("endpoint is a valid Url");
/// let path_style = UrlStyle::VirtualHost;
/// let name = "rusty-s3";
/// let region = "eu-west-1";
///
/// let bucket = Bucket::new(endpoint, path_style, name, region).expect("Url has a valid scheme and host");
/// assert_eq!(bucket.base_url().as_str(), "https://rusty-s3.s3.dualstack.eu-west-1.amazonaws.com/");
/// assert_eq!(bucket.name(), "rusty-s3");
/// assert_eq!(bucket.region(), "eu-west-1");
/// assert_eq!(bucket.object_url("duck.jpg").expect("url is valid").as_str(), "https://rusty-s3.s3.dualstack.eu-west-1.amazonaws.com/duck.jpg");
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Bucket {
    base_url: Url,
    name: Cow<'static, str>,
    region: Cow<'static, str>,
}

/// The request url format of a S3 bucket.
#[derive(Debug, Clone, Copy)]
pub enum UrlStyle {
    /// Requests will use "path-style" url: i.e:
    /// `https://s3.<region>.amazonaws.com/<bucket>/<key>`.
    ///
    /// This style should be considered deprecated and is **NOT RECOMMENDED**.
    /// Check [Amazon S3 Path Deprecation Plan](https://aws.amazon.com/blogs/aws/amazon-s3-path-deprecation-plan-the-rest-of-the-story/)
    /// for more informations.
    Path,
    /// Requests will use "virtual-hosted-style" urls, i.e:
    /// `https://<bucket>.s3.<region>.amazonaws.com/<key>`.
    VirtualHost,
}

#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum BucketError {
    UnsupportedScheme,
    MissingHost,
    ParseError(ParseError),
}

impl From<ParseError> for BucketError {
    fn from(error: ParseError) -> Self {
        BucketError::ParseError(error)
    }
}

impl Bucket {
    /// Construct a new S3 bucket
    pub fn new(
        endpoint: Url,
        path_style: UrlStyle,
        name: impl Into<Cow<'static, str>>,
        region: impl Into<Cow<'static, str>>,
    ) -> Result<Self, BucketError> {
        endpoint.host_str().ok_or(BucketError::MissingHost)?;

        match endpoint.scheme() {
            "http" | "https" => {}
            _ => return Err(BucketError::UnsupportedScheme),
        };

        let name = name.into();
        let region = region.into();

        let base_url = base_url(endpoint, &name, path_style)?;

        Ok(Self {
            base_url,
            name,
            region,
        })
    }

    /// Get the base url of this s3 `Bucket`
    pub fn base_url(&self) -> &Url {
        &self.base_url
    }

    /// Get the name of this `Bucket`
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Get the region of this `Bucket`
    pub fn region(&self) -> &str {
        &self.region
    }

    /// Generate an url to an object of this `Bucket`
    ///
    /// This is not a signed url, it's just the starting point for
    /// generating an url to an S3 object.
    pub fn object_url(&self, object: &str) -> Result<Url, ParseError> {
        let object = percent_encode_path(object);
        self.base_url.join(&object)
    }
}

fn base_url(mut endpoint: Url, name: &str, path_style: UrlStyle) -> Result<Url, ParseError> {
    match path_style {
        UrlStyle::Path => {
            let path = format!("{name}/");
            endpoint.join(&path)
        }
        UrlStyle::VirtualHost => {
            let host = format!("{}.{}", name, endpoint.host_str().unwrap());
            endpoint.set_host(Some(&host))?;
            Ok(endpoint)
        }
    }
}

// === Bucket level actions ===

impl Bucket {
    /// Create a new bucket.
    ///
    /// See [`CreateBucket`] for more details.
    pub fn create_bucket<'a>(&'a self, credentials: &'a Credentials) -> CreateBucket<'a> {
        CreateBucket::new(self, credentials)
    }

    /// Delete a bucket.
    ///
    /// See [`DeleteBucket`] for more details.
    pub fn delete_bucket<'a>(&'a self, credentials: &'a Credentials) -> DeleteBucket<'a> {
        DeleteBucket::new(self, credentials)
    }
}

// === Basic actions ===

impl Bucket {
    /// Retrieve an object's metadata from S3, using a `HEAD` request.
    ///
    /// See [`HeadObject`] for more details.
    pub fn head_object<'a>(
        &'a self,
        credentials: Option<&'a Credentials>,
        object: &'a str,
    ) -> HeadObject<'a> {
        HeadObject::new(self, credentials, object)
    }

    /// Retrieve an bucket's metadata from S3, using a `HEAD` request.
    ///
    /// See [`HeadBucket`] for more details.
    pub fn head_bucket<'a>(&'a self, credentials: Option<&'a Credentials>) -> HeadBucket<'a> {
        HeadBucket::new(self, credentials)
    }

    /// Retrieve an object from S3, using a `GET` request.
    ///
    /// See [`GetObject`] for more details.
    pub fn get_object<'a>(
        &'a self,
        credentials: Option<&'a Credentials>,
        object: &'a str,
    ) -> GetObject<'a> {
        GetObject::new(self, credentials, object)
    }

    /// List all objects in the bucket.
    ///
    /// See [`ListObjectsV2`] for more details.
    #[cfg(feature = "full")]
    pub fn list_objects_v2<'a>(
        &'a self,
        credentials: Option<&'a Credentials>,
    ) -> ListObjectsV2<'a> {
        ListObjectsV2::new(self, credentials)
    }

    /// Upload a file to S3, using a `PUT` request.
    ///
    /// See [`PutObject`] for more details.
    pub fn put_object<'a>(
        &'a self,
        credentials: Option<&'a Credentials>,
        object: &'a str,
    ) -> PutObject<'a> {
        PutObject::new(self, credentials, object)
    }

    /// Delete an object from S3, using a `DELETE` request.
    ///
    /// See [`DeleteObject`] for more details.
    pub fn delete_object<'a>(
        &'a self,
        credentials: Option<&'a Credentials>,
        object: &'a str,
    ) -> DeleteObject<'a> {
        DeleteObject::new(self, credentials, object)
    }

    /// Delete multiple objects from S3 using a single `POST` request.
    ///
    /// See [`DeleteObjects`] for more details.
    #[cfg(feature = "full")]
    pub fn delete_objects<'a, I>(
        &'a self,
        credentials: Option<&'a Credentials>,
        objects: I,
    ) -> DeleteObjects<'a, I> {
        DeleteObjects::new(self, credentials, objects)
    }
}

// === Multipart Upload ===

impl Bucket {
    /// Create a multipart upload.
    ///
    /// See [`CreateMultipartUpload`] for more details.
    #[cfg(feature = "full")]
    pub fn create_multipart_upload<'a>(
        &'a self,
        credentials: Option<&'a Credentials>,
        object: &'a str,
    ) -> CreateMultipartUpload<'a> {
        CreateMultipartUpload::new(self, credentials, object)
    }

    /// Upload a part to a previously created multipart upload.
    ///
    /// See [`UploadPart`] for more details.
    pub fn upload_part<'a>(
        &'a self,
        credentials: Option<&'a Credentials>,
        object: &'a str,
        part_number: u16,
        upload_id: &'a str,
    ) -> UploadPart<'a> {
        UploadPart::new(self, credentials, object, part_number, upload_id)
    }

    /// Complete a multipart upload.
    ///
    /// See [`CompleteMultipartUpload`] for more details.
    #[cfg(feature = "full")]
    pub fn complete_multipart_upload<'a, I>(
        &'a self,
        credentials: Option<&'a Credentials>,
        object: &'a str,
        upload_id: &'a str,
        etags: I,
    ) -> CompleteMultipartUpload<'a, I> {
        CompleteMultipartUpload::new(self, credentials, object, upload_id, etags)
    }

    /// Abort multipart upload.
    ///
    /// See [`AbortMultipartUpload`] for more details.
    pub fn abort_multipart_upload<'a>(
        &'a self,
        credentials: Option<&'a Credentials>,
        object: &'a str,
        upload_id: &'a str,
    ) -> AbortMultipartUpload<'a> {
        AbortMultipartUpload::new(self, credentials, object, upload_id)
    }

    /// Lists the parts that have been uploaded for a specific multipart upload.
    ///
    /// See [`ListParts`] for more details.
    #[cfg(feature = "full")]
    pub fn list_parts<'a>(
        &'a self,
        credentials: Option<&'a Credentials>,
        object: &'a str,
        upload_id: &'a str,
    ) -> ListParts<'a> {
        ListParts::new(self, credentials, object, upload_id)
    }
}

impl Display for BucketError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::UnsupportedScheme => f.write_str("unsupported Url scheme"),
            Self::MissingHost => f.write_str("Url is missing the `host`"),
            Self::ParseError(e) => e.fmt(f),
        }
    }
}

impl StdError for BucketError {}

#[cfg(test)]
mod tests {
    use pretty_assertions::assert_eq;

    use super::*;
    #[cfg(feature = "full")]
    use crate::actions::ObjectIdentifier;

    #[test]
    fn new_pathstyle() {
        let endpoint: Url = "https://s3.dualstack.eu-west-1.amazonaws.com"
            .parse()
            .unwrap();
        let base_url: Url = "https://s3.dualstack.eu-west-1.amazonaws.com/rusty-s3/"
            .parse()
            .unwrap();
        let name = "rusty-s3";
        let region = "eu-west-1";
        let bucket = Bucket::new(endpoint, UrlStyle::Path, name, region).unwrap();

        assert_eq!(bucket.base_url(), &base_url);
        assert_eq!(bucket.name(), name);
        assert_eq!(bucket.region(), region);
    }

    #[test]
    fn new_domainstyle() {
        let endpoint: Url = "https://s3.dualstack.eu-west-1.amazonaws.com"
            .parse()
            .unwrap();
        let base_url: Url = "https://rusty-s3.s3.dualstack.eu-west-1.amazonaws.com"
            .parse()
            .unwrap();
        let name = "rusty-s3";
        let region = "eu-west-1";
        let bucket = Bucket::new(endpoint, UrlStyle::VirtualHost, name, region).unwrap();

        assert_eq!(bucket.base_url(), &base_url);
        assert_eq!(bucket.name(), name);
        assert_eq!(bucket.region(), region);
    }

    #[test]
    fn new_bad_scheme() {
        let endpoint = "ftp://example.com/example".parse().unwrap();
        let name = "rusty-s3";
        let region = "eu-west-1";
        assert_eq!(
            Bucket::new(endpoint, UrlStyle::Path, name, region),
            Err(BucketError::UnsupportedScheme)
        );
    }

    #[test]
    fn new_missing_host() {
        let endpoint = "file:///home/something".parse().unwrap();
        let name = "rusty-s3";
        let region = "eu-west-1";
        assert_eq!(
            Bucket::new(endpoint, UrlStyle::Path, name, region),
            Err(BucketError::MissingHost)
        );
    }

    #[test]
    fn object_url_pathstyle() {
        let endpoint: Url = "https://s3.dualstack.eu-west-1.amazonaws.com"
            .parse()
            .unwrap();
        let name = "rusty-s3";
        let region = "eu-west-1";
        let bucket = Bucket::new(endpoint, UrlStyle::Path, name, region).unwrap();

        let path_style = bucket.object_url("something/cat.jpg").unwrap();
        assert_eq!(
            "https://s3.dualstack.eu-west-1.amazonaws.com/rusty-s3/something/cat.jpg",
            path_style.as_str()
        );
    }

    #[test]
    fn object_url_domainstyle() {
        let endpoint: Url = "https://s3.dualstack.eu-west-1.amazonaws.com"
            .parse()
            .unwrap();
        let name = "rusty-s3";
        let region = "eu-west-1";
        let bucket = Bucket::new(endpoint, UrlStyle::VirtualHost, name, region).unwrap();

        let domain_style = bucket.object_url("something/cat.jpg").unwrap();
        assert_eq!(
            "https://rusty-s3.s3.dualstack.eu-west-1.amazonaws.com/something/cat.jpg",
            domain_style.as_str()
        );
    }

    #[test]
    fn all_actions() {
        let endpoint: Url = "https://s3.dualstack.eu-west-1.amazonaws.com"
            .parse()
            .unwrap();

        let name = "rusty-s3";
        let region = "eu-west-1";
        let bucket = Bucket::new(endpoint, UrlStyle::Path, name, region).unwrap();

        let credentials = Credentials::new(
            "AKIAIOSFODNN7EXAMPLE",
            "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",
        );

        let _ = bucket.create_bucket(&credentials);
        let _ = bucket.delete_bucket(&credentials);

        let _ = bucket.head_object(Some(&credentials), "duck.jpg");
        let _ = bucket.get_object(Some(&credentials), "duck.jpg");
        #[cfg(feature = "full")]
        let _ = bucket.list_objects_v2(Some(&credentials));
        let _ = bucket.put_object(Some(&credentials), "duck.jpg");
        let _ = bucket.delete_object(Some(&credentials), "duck.jpg");
        #[cfg(feature = "full")]
        let _ = bucket.delete_objects(Some(&credentials), std::iter::empty::<ObjectIdentifier>());

        #[cfg(feature = "full")]
        let _ = bucket.create_multipart_upload(Some(&credentials), "duck.jpg");
        let _ = bucket.upload_part(Some(&credentials), "duck.jpg", 1, "abcd");
        #[cfg(feature = "full")]
        let _ = bucket.complete_multipart_upload(
            Some(&credentials),
            "duck.jpg",
            "abcd",
            ["1234"].iter().copied(),
        );
        let _ = bucket.abort_multipart_upload(Some(&credentials), "duck.jpg", "abcd");
        #[cfg(feature = "full")]
        let _ = bucket.list_parts(Some(&credentials), "duck.jpg", "abcd");
    }
}