aboutsummaryrefslogtreecommitdiff
path: root/src/api/s3/api_server.rs
blob: 1737af33183fb930079a7efdbcd23d517e849b72 (plain) (blame)
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
use std::sync::Arc;

use async_trait::async_trait;

use hyper::header;
use hyper::{body::Incoming as IncomingBody, Request, Response};
use tokio::sync::watch;

use opentelemetry::{trace::SpanRef, KeyValue};

use garage_util::error::Error as GarageError;
use garage_util::socket_address::UnixOrTCPSocketAddress;

use garage_model::garage::Garage;
use garage_model::key_table::Key;

use crate::generic_server::*;
use crate::s3::error::*;

use crate::signature::verify_request;

use crate::helpers::*;
use crate::s3::bucket::*;
use crate::s3::copy::*;
use crate::s3::cors::*;
use crate::s3::delete::*;
use crate::s3::get::*;
use crate::s3::lifecycle::*;
use crate::s3::list::*;
use crate::s3::multipart::*;
use crate::s3::post_object::handle_post_object;
use crate::s3::put::*;
use crate::s3::router::Endpoint;
use crate::s3::website::*;

pub use crate::signature::streaming::ReqBody;
pub type ResBody = BoxBody<Error>;

pub struct S3ApiServer {
	garage: Arc<Garage>,
}

pub(crate) struct S3ApiEndpoint {
	bucket_name: Option<String>,
	endpoint: Endpoint,
}

impl S3ApiServer {
	pub async fn run(
		garage: Arc<Garage>,
		addr: UnixOrTCPSocketAddress,
		s3_region: String,
		must_exit: watch::Receiver<bool>,
	) -> Result<(), GarageError> {
		ApiServer::new(s3_region, S3ApiServer { garage })
			.run_server(addr, None, must_exit)
			.await
	}

	async fn handle_request_without_bucket(
		&self,
		_req: Request<ReqBody>,
		api_key: Key,
		endpoint: Endpoint,
	) -> Result<Response<ResBody>, Error> {
		match endpoint {
			Endpoint::ListBuckets => handle_list_buckets(&self.garage, &api_key).await,
			endpoint => Err(Error::NotImplemented(endpoint.name().to_owned())),
		}
	}
}

#[async_trait]
impl ApiHandler for S3ApiServer {
	const API_NAME: &'static str = "s3";
	const API_NAME_DISPLAY: &'static str = "S3";

	type Endpoint = S3ApiEndpoint;
	type Error = Error;

	fn parse_endpoint(&self, req: &Request<IncomingBody>) -> Result<S3ApiEndpoint, Error> {
		let authority = req
			.headers()
			.get(header::HOST)
			.ok_or_bad_request("Host header required")?
			.to_str()?;

		let host = authority_to_host(authority)?;

		let bucket_name = self
			.garage
			.config
			.s3_api
			.root_domain
			.as_ref()
			.and_then(|root_domain| host_to_bucket(&host, root_domain));

		let (endpoint, bucket_name) =
			Endpoint::from_request(req, bucket_name.map(ToOwned::to_owned))?;

		Ok(S3ApiEndpoint {
			bucket_name,
			endpoint,
		})
	}

	async fn handle(
		&self,
		req: Request<IncomingBody>,
		endpoint: S3ApiEndpoint,
	) -> Result<Response<ResBody>, Error> {
		let S3ApiEndpoint {
			bucket_name,
			endpoint,
		} = endpoint;
		let garage = self.garage.clone();

		// Some endpoints are processed early, before we even check for an API key
		if let Endpoint::PostObject = endpoint {
			return handle_post_object(garage, req, bucket_name.unwrap()).await;
		}
		if let Endpoint::Options = endpoint {
			let options_res = handle_options_api(garage, &req, bucket_name).await?;
			return Ok(options_res.map(|_empty_body: EmptyBody| empty_body()));
		}

		let (req, api_key, content_sha256) = verify_request(&garage, req, "s3").await?;

		let bucket_name = match bucket_name {
			None => {
				return self
					.handle_request_without_bucket(req, api_key, endpoint)
					.await
			}
			Some(bucket) => bucket.to_string(),
		};

		// Special code path for CreateBucket API endpoint
		if let Endpoint::CreateBucket {} = endpoint {
			return handle_create_bucket(
				&garage,
				req,
				content_sha256,
				&api_key.key_id,
				bucket_name,
			)
			.await;
		}

		let bucket_id = garage
			.bucket_helper()
			.resolve_bucket(&bucket_name, &api_key)
			.await?;
		let bucket = garage
			.bucket_helper()
			.get_existing_bucket(bucket_id)
			.await?;
		let bucket_params = bucket.state.into_option().unwrap();

		let allowed = match endpoint.authorization_type() {
			Authorization::Read => api_key.allow_read(&bucket_id),
			Authorization::Write => api_key.allow_write(&bucket_id),
			Authorization::Owner => api_key.allow_owner(&bucket_id),
			_ => unreachable!(),
		};

		if !allowed {
			return Err(Error::forbidden("Operation is not allowed for this key."));
		}

		let matching_cors_rule = find_matching_cors_rule(&bucket_params, &req)?.cloned();

		let ctx = ReqCtx {
			garage,
			bucket_id,
			bucket_name,
			bucket_params,
			api_key,
		};

		let resp = match endpoint {
			Endpoint::HeadObject {
				key, part_number, ..
			} => handle_head(ctx, &req, &key, part_number).await,
			Endpoint::GetObject {
				key,
				part_number,
				response_cache_control,
				response_content_disposition,
				response_content_encoding,
				response_content_language,
				response_content_type,
				response_expires,
				..
			} => {
				let overrides = GetObjectOverrides {
					response_cache_control,
					response_content_disposition,
					response_content_encoding,
					response_content_language,
					response_content_type,
					response_expires,
				};
				handle_get(ctx, &req, &key, part_number, overrides).await
			}
			Endpoint::UploadPart {
				key,
				part_number,
				upload_id,
			} => handle_put_part(ctx, req, &key, part_number, &upload_id, content_sha256).await,
			Endpoint::CopyObject { key } => handle_copy(ctx, &req, &key).await,
			Endpoint::UploadPartCopy {
				key,
				part_number,
				upload_id,
			} => handle_upload_part_copy(ctx, &req, &key, part_number, &upload_id).await,
			Endpoint::PutObject { key } => handle_put(ctx, req, &key, content_sha256).await,
			Endpoint::AbortMultipartUpload { key, upload_id } => {
				handle_abort_multipart_upload(ctx, &key, &upload_id).await
			}
			Endpoint::DeleteObject { key, .. } => handle_delete(ctx, &key).await,
			Endpoint::CreateMultipartUpload { key } => {
				handle_create_multipart_upload(ctx, &req, &key).await
			}
			Endpoint::CompleteMultipartUpload { key, upload_id } => {
				handle_complete_multipart_upload(ctx, req, &key, &upload_id, content_sha256).await
			}
			Endpoint::CreateBucket {} => unreachable!(),
			Endpoint::HeadBucket {} => {
				let response = Response::builder().body(empty_body()).unwrap();
				Ok(response)
			}
			Endpoint::DeleteBucket {} => handle_delete_bucket(ctx).await,
			Endpoint::GetBucketLocation {} => handle_get_bucket_location(ctx),
			Endpoint::GetBucketVersioning {} => handle_get_bucket_versioning(),
			Endpoint::ListObjects {
				delimiter,
				encoding_type,
				marker,
				max_keys,
				prefix,
			} => {
				let query = ListObjectsQuery {
					common: ListQueryCommon {
						bucket_name: ctx.bucket_name.clone(),
						bucket_id,
						delimiter,
						page_size: max_keys.unwrap_or(1000).clamp(1, 1000),
						prefix: prefix.unwrap_or_default(),
						urlencode_resp: encoding_type.map(|e| e == "url").unwrap_or(false),
					},
					is_v2: false,
					marker,
					continuation_token: None,
					start_after: None,
				};
				handle_list(ctx, &query).await
			}
			Endpoint::ListObjectsV2 {
				delimiter,
				encoding_type,
				max_keys,
				prefix,
				continuation_token,
				start_after,
				list_type,
				..
			} => {
				if list_type == "2" {
					let query = ListObjectsQuery {
						common: ListQueryCommon {
							bucket_name: ctx.bucket_name.clone(),
							bucket_id,
							delimiter,
							page_size: max_keys.unwrap_or(1000).clamp(1, 1000),
							urlencode_resp: encoding_type.map(|e| e == "url").unwrap_or(false),
							prefix: prefix.unwrap_or_default(),
						},
						is_v2: true,
						marker: None,
						continuation_token,
						start_after,
					};
					handle_list(ctx, &query).await
				} else {
					Err(Error::bad_request(format!(
						"Invalid endpoint: list-type={}",
						list_type
					)))
				}
			}
			Endpoint::ListMultipartUploads {
				delimiter,
				encoding_type,
				key_marker,
				max_uploads,
				prefix,
				upload_id_marker,
			} => {
				let query = ListMultipartUploadsQuery {
					common: ListQueryCommon {
						bucket_name: ctx.bucket_name.clone(),
						bucket_id,
						delimiter,
						page_size: max_uploads.unwrap_or(1000).clamp(1, 1000),
						prefix: prefix.unwrap_or_default(),
						urlencode_resp: encoding_type.map(|e| e == "url").unwrap_or(false),
					},
					key_marker,
					upload_id_marker,
				};
				handle_list_multipart_upload(ctx, &query).await
			}
			Endpoint::ListParts {
				key,
				max_parts,
				part_number_marker,
				upload_id,
			} => {
				let query = ListPartsQuery {
					bucket_name: ctx.bucket_name.clone(),
					bucket_id,
					key,
					upload_id,
					part_number_marker: part_number_marker.map(|p| p.min(10000)),
					max_parts: max_parts.unwrap_or(1000).clamp(1, 1000),
				};
				handle_list_parts(ctx, req, &query).await
			}
			Endpoint::DeleteObjects {} => handle_delete_objects(ctx, req, content_sha256).await,
			Endpoint::GetBucketWebsite {} => handle_get_website(ctx).await,
			Endpoint::PutBucketWebsite {} => handle_put_website(ctx, req, content_sha256).await,
			Endpoint::DeleteBucketWebsite {} => handle_delete_website(ctx).await,
			Endpoint::GetBucketCors {} => handle_get_cors(ctx).await,
			Endpoint::PutBucketCors {} => handle_put_cors(ctx, req, content_sha256).await,
			Endpoint::DeleteBucketCors {} => handle_delete_cors(ctx).await,
			Endpoint::GetBucketLifecycleConfiguration {} => handle_get_lifecycle(ctx).await,
			Endpoint::PutBucketLifecycleConfiguration {} => {
				handle_put_lifecycle(ctx, req, content_sha256).await
			}
			Endpoint::DeleteBucketLifecycle {} => handle_delete_lifecycle(ctx).await,
			endpoint => Err(Error::NotImplemented(endpoint.name().to_owned())),
		};

		// If request was a success and we have a CORS rule that applies to it,
		// add the corresponding CORS headers to the response
		let mut resp_ok = resp?;
		if let Some(rule) = matching_cors_rule {
			add_cors_headers(&mut resp_ok, &rule)
				.ok_or_internal_error("Invalid bucket CORS configuration")?;
		}

		Ok(resp_ok)
	}
}

impl ApiEndpoint for S3ApiEndpoint {
	fn name(&self) -> &'static str {
		self.endpoint.name()
	}

	fn add_span_attributes(&self, span: SpanRef<'_>) {
		span.set_attribute(KeyValue::new(
			"bucket",
			self.bucket_name.clone().unwrap_or_default(),
		));
	}
}