-
Notifications
You must be signed in to change notification settings - Fork 256
Expand file tree
/
Copy pathcommand.rs
More file actions
487 lines (466 loc) · 18.8 KB
/
Copy pathcommand.rs
File metadata and controls
487 lines (466 loc) · 18.8 KB
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
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
//! This module defines and manages various commands used for interacting with Amazon S3, encapsulating common operations such as creating buckets, uploading objects, and managing multipart uploads.
//! It also provides utilities for calculating necessary metadata (like content length and SHA-256 hashes) required for secure and efficient communication with the S3 service.
//!
//! ## Key Components
//!
//! - **HttpMethod Enum**
//! - Represents HTTP methods used in S3 operations, including `GET`, `PUT`, `DELETE`, `POST`, and `HEAD`.
//! - Implements `fmt::Display` for easy conversion to string representations suitable for HTTP requests.
//!
//! - **Multipart Struct**
//! - Represents a part of a multipart upload, containing the part number and the associated upload ID.
//! - Provides methods for constructing a new multipart part and generating a query string for the S3 API.
//!
//! - **Command Enum**
//! - The core of this module, encapsulating various S3 operations, such as:
//! - Object management (`GetObject`, `PutObject`, `DeleteObject`, etc.)
//! - Bucket management (`CreateBucket`, `DeleteBucket`, etc.)
//! - Multipart upload management (`InitiateMultipartUpload`, `UploadPart`, `CompleteMultipartUpload`, etc.)
//! - For each command, you can determine the associated HTTP method using `http_verb()` and calculate the content length or content type using `content_length()` and `content_type()` respectively.
//! - The `sha256()` method computes the SHA-256 hash of the request payload, a critical part of S3's security features.
//!
use std::collections::HashMap;
use crate::error::S3Error;
use crate::serde_types::{
BucketLifecycleConfiguration, CompleteMultipartUploadData, CorsConfiguration,
DeleteObjectsRequest,
};
use crate::EMPTY_PAYLOAD_SHA;
use sha2::{Digest, Sha256};
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum HttpMethod {
Delete,
Get,
Put,
Post,
Head,
}
use std::fmt;
impl fmt::Display for HttpMethod {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
HttpMethod::Delete => write!(f, "DELETE"),
HttpMethod::Get => write!(f, "GET"),
HttpMethod::Post => write!(f, "POST"),
HttpMethod::Put => write!(f, "PUT"),
HttpMethod::Head => write!(f, "HEAD"),
}
}
}
use crate::bucket_ops::BucketConfiguration;
use http::HeaderMap;
#[derive(Clone, Debug)]
pub struct Multipart<'a> {
part_number: u32,
upload_id: &'a str,
}
impl<'a> Multipart<'a> {
pub fn query_string(&self) -> String {
format!(
"?partNumber={}&uploadId={}",
self.part_number, self.upload_id
)
}
pub fn new(part_number: u32, upload_id: &'a str) -> Self {
Multipart {
part_number,
upload_id,
}
}
}
#[derive(Clone, Debug)]
pub enum Command<'a> {
HeadObject,
CopyObject {
from: &'a str,
},
DeleteObject,
DeleteObjectTagging,
GetObject,
GetObjectTorrent,
GetObjectRange {
start: u64,
end: Option<u64>,
},
GetObjectTagging,
PutObject {
content: &'a [u8],
content_type: &'a str,
custom_headers: Option<HeaderMap>,
multipart: Option<Multipart<'a>>,
},
PutObjectTagging {
tags: &'a str,
},
ListMultipartUploads {
prefix: Option<&'a str>,
delimiter: Option<&'a str>,
key_marker: Option<String>,
max_uploads: Option<usize>,
},
ListObjects {
prefix: String,
delimiter: Option<String>,
marker: Option<String>,
max_keys: Option<usize>,
},
ListObjectsV2 {
prefix: String,
delimiter: Option<String>,
continuation_token: Option<String>,
start_after: Option<String>,
max_keys: Option<usize>,
},
GetBucketLocation,
PresignGet {
expiry_secs: u32,
custom_queries: Option<HashMap<String, String>>,
},
PresignPut {
expiry_secs: u32,
custom_headers: Option<HeaderMap>,
custom_queries: Option<HashMap<String, String>>,
},
PresignDelete {
expiry_secs: u32,
},
InitiateMultipartUpload {
content_type: &'a str,
},
UploadPart {
part_number: u32,
content: &'a [u8],
upload_id: &'a str,
},
AbortMultipartUpload {
upload_id: &'a str,
},
CompleteMultipartUpload {
upload_id: &'a str,
data: CompleteMultipartUploadData,
},
CreateBucket {
config: BucketConfiguration,
},
DeleteBucket,
ListBuckets,
GetBucketCors {
expected_bucket_owner: String,
},
PutBucketCors {
expected_bucket_owner: String,
configuration: CorsConfiguration,
},
DeleteBucketCors {
expected_bucket_owner: String,
},
GetBucketLifecycle,
PutBucketLifecycle {
configuration: BucketLifecycleConfiguration,
},
DeleteBucketLifecycle,
GetObjectAttributes {
expected_bucket_owner: String,
version_id: Option<String>,
},
DeleteObjects {
data: DeleteObjectsRequest,
},
}
impl<'a> Command<'a> {
pub fn http_verb(&self) -> HttpMethod {
match *self {
Command::GetObject
| Command::GetObjectTorrent
| Command::GetBucketCors { .. }
| Command::GetObjectRange { .. }
| Command::ListBuckets
| Command::ListObjects { .. }
| Command::ListObjectsV2 { .. }
| Command::GetBucketLocation
| Command::GetObjectTagging
| Command::GetBucketLifecycle
| Command::ListMultipartUploads { .. }
| Command::PresignGet { .. } => HttpMethod::Get,
Command::PutObject { .. }
| Command::CopyObject { from: _ }
| Command::PutObjectTagging { .. }
| Command::PresignPut { .. }
| Command::UploadPart { .. }
| Command::PutBucketCors { .. }
| Command::CreateBucket { .. }
| Command::PutBucketLifecycle { .. } => HttpMethod::Put,
Command::DeleteObject
| Command::DeleteObjectTagging
| Command::AbortMultipartUpload { .. }
| Command::PresignDelete { .. }
| Command::DeleteBucket
| Command::DeleteBucketCors { .. }
| Command::DeleteBucketLifecycle => HttpMethod::Delete,
Command::InitiateMultipartUpload { .. }
| Command::CompleteMultipartUpload { .. }
| Command::DeleteObjects { .. } => HttpMethod::Post,
Command::HeadObject => HttpMethod::Head,
Command::GetObjectAttributes { .. } => HttpMethod::Get,
}
}
/// Whether this command should include `Content-Length` and `Content-Type`
/// headers in the signed request.
///
/// Returns `true` for commands that serialize a request body, plus
/// `InitiateMultipartUpload`. The latter is a `POST` with an empty body
/// but is included because:
///
/// - Google Cloud Storage rejects the request with HTTP 411 if
/// `Content-Length` is omitted from a `POST`, even when the body is
/// empty.
/// - The `Content-Type` value carried by `InitiateMultipartUpload` is
/// not a description of the (empty) request body but the content type
/// to associate with the eventual multipart object on the server.
///
/// Body-less `GET`, `HEAD`, and `DELETE` commands return `false` so that
/// stray `Content-Length: 0` / `Content-Type: text/plain` headers do
/// not enter the AWS4-HMAC-SHA256 canonical request, which Cloudflare
/// R2 rejects as a signature mismatch (notably for ranged `GET`s).
pub fn has_body(&self) -> bool {
matches!(
self,
Command::PutObject { .. }
| Command::PutObjectTagging { .. }
| Command::UploadPart { .. }
| Command::InitiateMultipartUpload { .. }
| Command::CompleteMultipartUpload { .. }
| Command::CreateBucket { .. }
| Command::PutBucketLifecycle { .. }
| Command::PutBucketCors { .. }
| Command::DeleteObjects { .. }
)
}
pub fn content_length(&self) -> Result<usize, S3Error> {
let result = match &self {
Command::CopyObject { from: _ } => 0,
Command::PutObject { content, .. } => content.len(),
Command::PutObjectTagging { tags } => tags.len(),
Command::UploadPart { content, .. } => content.len(),
Command::CompleteMultipartUpload { data, .. } => data.len(),
Command::CreateBucket { config } => {
if let Some(payload) = config.location_constraint_payload() {
Vec::from(payload).len()
} else {
0
}
}
Command::PutBucketLifecycle { configuration } => {
quick_xml::se::to_string(configuration)?.len()
}
Command::PutBucketCors { configuration, .. } => configuration.to_string().len(),
Command::HeadObject => 0,
Command::DeleteObject => 0,
Command::DeleteObjectTagging => 0,
Command::GetObject => 0,
Command::GetObjectTorrent => 0,
Command::GetObjectRange { .. } => 0,
Command::GetObjectTagging => 0,
Command::ListMultipartUploads { .. } => 0,
Command::ListObjects { .. } => 0,
Command::ListObjectsV2 { .. } => 0,
Command::GetBucketLocation => 0,
Command::PresignGet { .. } => 0,
Command::PresignPut { .. } => 0,
Command::PresignDelete { .. } => 0,
Command::InitiateMultipartUpload { .. } => 0,
Command::AbortMultipartUpload { .. } => 0,
Command::DeleteBucket => 0,
Command::ListBuckets => 0,
Command::GetBucketCors { .. } => 0,
Command::DeleteBucketCors { .. } => 0,
Command::GetBucketLifecycle => 0,
Command::DeleteBucketLifecycle { .. } => 0,
Command::GetObjectAttributes { .. } => 0,
Command::DeleteObjects { data } => data.len(),
};
Ok(result)
}
pub fn content_type(&self) -> String {
match self {
Command::InitiateMultipartUpload { content_type } => content_type.to_string(),
Command::PutObject { content_type, .. } => content_type.to_string(),
Command::CompleteMultipartUpload { .. }
| Command::PutBucketLifecycle { .. }
| Command::PutBucketCors { .. } => "application/xml".into(),
Command::HeadObject => "text/plain".into(),
Command::DeleteObject => "text/plain".into(),
Command::DeleteObjectTagging => "text/plain".into(),
Command::GetObject => "text/plain".into(),
Command::GetObjectTorrent => "text/plain".into(),
Command::GetObjectRange { .. } => "text/plain".into(),
Command::GetObjectTagging => "text/plain".into(),
Command::ListMultipartUploads { .. } => "text/plain".into(),
Command::ListObjects { .. } => "text/plain".into(),
Command::ListObjectsV2 { .. } => "text/plain".into(),
Command::GetBucketLocation => "text/plain".into(),
Command::PresignGet { .. } => "text/plain".into(),
Command::PresignPut { .. } => "text/plain".into(),
Command::PresignDelete { .. } => "text/plain".into(),
Command::AbortMultipartUpload { .. } => "text/plain".into(),
Command::DeleteBucket => "text/plain".into(),
Command::ListBuckets => "text/plain".into(),
Command::GetBucketCors { .. } => "text/plain".into(),
Command::DeleteBucketCors { .. } => "text/plain".into(),
Command::GetBucketLifecycle => "text/plain".into(),
Command::DeleteBucketLifecycle { .. } => "text/plain".into(),
Command::CopyObject { .. } => "text/plain".into(),
Command::PutObjectTagging { .. } => "text/plain".into(),
Command::UploadPart { .. } => "text/plain".into(),
Command::CreateBucket { .. } => "text/plain".into(),
Command::GetObjectAttributes { .. } => "text/plain".into(),
Command::DeleteObjects { .. } => "application/xml".into(),
}
}
pub fn sha256(&self) -> Result<String, S3Error> {
let result = match &self {
Command::PutObject { content, .. } => {
let mut sha = Sha256::default();
sha.update(content);
hex::encode(sha.finalize().as_slice())
}
Command::PutObjectTagging { tags } => {
let mut sha = Sha256::default();
sha.update(tags.as_bytes());
hex::encode(sha.finalize().as_slice())
}
Command::CompleteMultipartUpload { data, .. } => {
let mut sha = Sha256::default();
sha.update(data.to_string().as_bytes());
hex::encode(sha.finalize().as_slice())
}
Command::CreateBucket { config } => {
if let Some(payload) = config.location_constraint_payload() {
let mut sha = Sha256::default();
sha.update(payload.as_bytes());
hex::encode(sha.finalize().as_slice())
} else {
EMPTY_PAYLOAD_SHA.into()
}
}
Command::PutBucketLifecycle { configuration } => {
let mut sha = Sha256::default();
sha.update(quick_xml::se::to_string(configuration)?.as_bytes());
hex::encode(sha.finalize().as_slice())
}
Command::PutBucketCors { configuration, .. } => {
let mut sha = Sha256::default();
sha.update(configuration.to_string().as_bytes());
hex::encode(sha.finalize().as_slice())
}
Command::HeadObject => EMPTY_PAYLOAD_SHA.into(),
Command::DeleteObject => EMPTY_PAYLOAD_SHA.into(),
Command::DeleteObjectTagging => EMPTY_PAYLOAD_SHA.into(),
Command::GetObject => EMPTY_PAYLOAD_SHA.into(),
Command::GetObjectTorrent => EMPTY_PAYLOAD_SHA.into(),
Command::GetObjectRange { .. } => EMPTY_PAYLOAD_SHA.into(),
Command::GetObjectTagging => EMPTY_PAYLOAD_SHA.into(),
Command::ListMultipartUploads { .. } => EMPTY_PAYLOAD_SHA.into(),
Command::ListObjects { .. } => EMPTY_PAYLOAD_SHA.into(),
Command::ListObjectsV2 { .. } => EMPTY_PAYLOAD_SHA.into(),
Command::GetBucketLocation => EMPTY_PAYLOAD_SHA.into(),
Command::PresignGet { .. } => EMPTY_PAYLOAD_SHA.into(),
Command::PresignPut { .. } => EMPTY_PAYLOAD_SHA.into(),
Command::PresignDelete { .. } => EMPTY_PAYLOAD_SHA.into(),
Command::AbortMultipartUpload { .. } => EMPTY_PAYLOAD_SHA.into(),
Command::DeleteBucket => EMPTY_PAYLOAD_SHA.into(),
Command::ListBuckets => EMPTY_PAYLOAD_SHA.into(),
Command::GetBucketCors { .. } => EMPTY_PAYLOAD_SHA.into(),
Command::DeleteBucketCors { .. } => EMPTY_PAYLOAD_SHA.into(),
Command::GetBucketLifecycle => EMPTY_PAYLOAD_SHA.into(),
Command::DeleteBucketLifecycle { .. } => EMPTY_PAYLOAD_SHA.into(),
Command::CopyObject { .. } => EMPTY_PAYLOAD_SHA.into(),
Command::UploadPart { .. } => EMPTY_PAYLOAD_SHA.into(),
Command::InitiateMultipartUpload { .. } => EMPTY_PAYLOAD_SHA.into(),
Command::GetObjectAttributes { .. } => EMPTY_PAYLOAD_SHA.into(),
Command::DeleteObjects { data } => {
let mut sha = Sha256::default();
sha.update(data.to_string().as_bytes());
hex::encode(sha.finalize().as_slice())
}
};
Ok(result)
}
}
#[cfg(test)]
mod tests {
use super::*;
/// Body-less `GET`s (notably ranged `GET`) must not advertise body
/// headers, otherwise Cloudflare R2 rejects the AWS4-HMAC-SHA256
/// signature for ranged downloads.
#[test]
fn ranged_get_does_not_have_body() {
let cmd = Command::GetObjectRange {
start: 0,
end: Some(1023),
};
assert!(!cmd.has_body());
assert!(!Command::GetObject.has_body());
assert!(!Command::HeadObject.has_body());
assert!(!Command::ListBuckets.has_body());
}
/// `DELETE` and `CopyObject` carry no request body.
#[test]
fn delete_and_copy_do_not_have_body() {
assert!(!Command::DeleteObject.has_body());
assert!(!Command::AbortMultipartUpload { upload_id: "u" }.has_body());
assert!(!Command::CopyObject { from: "x" }.has_body());
}
/// `InitiateMultipartUpload` is body-less but must still be reported as
/// having a body so that `Content-Length: 0` is sent. GCS returns HTTP
/// 411 on `POST` requests without `Content-Length`, even when the body
/// is empty.
#[test]
fn initiate_multipart_upload_has_body_for_gcs_compat() {
let cmd = Command::InitiateMultipartUpload {
content_type: "application/octet-stream",
};
assert!(cmd.has_body());
assert_eq!(cmd.http_verb(), HttpMethod::Post);
assert_eq!(cmd.content_length().unwrap(), 0);
}
/// Body-bearing commands report `has_body() == true` so signing
/// includes accurate `Content-Length` / `Content-Type`.
#[test]
fn body_bearing_commands_have_body() {
let put = Command::PutObject {
content: b"hello",
content_type: "text/plain",
custom_headers: None,
multipart: None,
};
assert!(put.has_body());
let upload = Command::UploadPart {
part_number: 1,
content: b"data",
upload_id: "u",
};
assert!(upload.has_body());
}
/// `DeleteObjects` is a `POST` with an XML body listing the keys to
/// delete. It must be reported as body-bearing so `Content-Length`
/// reflects the payload size and `Content-Type: application/xml` is
/// signed; otherwise providers reject the request or the signature.
#[test]
fn delete_objects_has_body() {
use crate::serde_types::{DeleteObjectsRequest, ObjectIdentifier};
let cmd = Command::DeleteObjects {
data: DeleteObjectsRequest {
objects: vec![ObjectIdentifier {
key: "a".to_string(),
version_id: None,
}],
quiet: false,
},
};
assert!(cmd.has_body());
assert_eq!(cmd.http_verb(), HttpMethod::Post);
assert!(cmd.content_length().unwrap() > 0);
assert_eq!(cmd.content_type(), "application/xml");
}
}