aboutsummaryrefslogtreecommitdiff
path: root/src/web/web_server.rs
blob: 668a897a77d3a17fb2ae2c85d104946df95aa499 (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
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
use std::fs::{self, Permissions};
use std::os::unix::prelude::PermissionsExt;
use std::{convert::Infallible, sync::Arc};

use futures::future::Future;

use hyper::server::conn::http1;
use hyper::{
	body::Incoming as IncomingBody,
	header::{HeaderValue, HOST},
	service::service_fn,
	Method, Request, Response, StatusCode,
};
use hyper_util::rt::TokioIo;

use tokio::io::{AsyncRead, AsyncWrite};
use tokio::net::{TcpListener, UnixListener};

use opentelemetry::{
	global,
	metrics::{Counter, ValueRecorder},
	trace::{FutureExt, TraceContextExt, Tracer},
	Context, KeyValue,
};

use crate::error::*;

use garage_api::helpers::*;
use garage_api::s3::cors::{add_cors_headers, find_matching_cors_rule, handle_options_for_bucket};
use garage_api::s3::error::{
	CommonErrorDerivative, Error as ApiError, OkOrBadRequest, OkOrInternalError,
};
use garage_api::s3::get::{handle_get, handle_head};

use garage_model::garage::Garage;

use garage_table::*;
use garage_util::data::Uuid;
use garage_util::error::Error as GarageError;
use garage_util::forwarded_headers;
use garage_util::metrics::{gen_trace_id, RecordDuration};
use garage_util::socket_address::UnixOrTCPSocketAddress;

struct WebMetrics {
	request_counter: Counter<u64>,
	error_counter: Counter<u64>,
	request_duration: ValueRecorder<f64>,
}

impl WebMetrics {
	fn new() -> Self {
		let meter = global::meter("garage/web");
		Self {
			request_counter: meter
				.u64_counter("web.request_counter")
				.with_description("Number of requests to the web endpoint")
				.init(),
			error_counter: meter
				.u64_counter("web.error_counter")
				.with_description("Number of requests to the web endpoint resulting in errors")
				.init(),
			request_duration: meter
				.f64_value_recorder("web.request_duration")
				.with_description("Duration of requests to the web endpoint")
				.init(),
		}
	}
}

pub struct WebServer {
	garage: Arc<Garage>,
	metrics: Arc<WebMetrics>,
	root_domain: String,
}

impl WebServer {
	/// Run a web server
	pub async fn run(
		garage: Arc<Garage>,
		bind_addr: UnixOrTCPSocketAddress,
		root_domain: String,
		shutdown_signal: impl Future<Output = ()>,
	) -> Result<(), GarageError> {
		let metrics = Arc::new(WebMetrics::new());
		let web_server = Arc::new(WebServer {
			garage,
			metrics,
			root_domain,
		});

		info!("Web server listening on {}", bind_addr);

		tokio::pin!(shutdown_signal);

		match bind_addr {
			UnixOrTCPSocketAddress::TCPSocket(addr) => {
				let listener = TcpListener::bind(addr).await?;

				loop {
					let (stream, client_addr) = tokio::select! {
						acc = listener.accept() => acc?,
						_ = &mut shutdown_signal => break,
					};

					web_server.launch_handler(stream, client_addr.to_string());
				}
			}
			UnixOrTCPSocketAddress::UnixSocket(ref path) => {
				if path.exists() {
					fs::remove_file(path)?
				}

				let listener = UnixListener::bind(path)?;

				fs::set_permissions(path, Permissions::from_mode(0o222))?;

				loop {
					let (stream, _) = tokio::select! {
						acc = listener.accept() => acc?,
						_ = &mut shutdown_signal => break,
					};

					web_server.launch_handler(stream, path.display().to_string());
				}
			}
		};

		Ok(())
	}

	fn launch_handler<S>(self: &Arc<Self>, stream: S, client_addr: String)
	where
		S: AsyncRead + AsyncWrite + Send + Sync + 'static,
	{
		let this = self.clone();
		let io = TokioIo::new(stream);

		let serve = move |req: Request<IncomingBody>| {
			this.clone().handle_request(req, client_addr.to_string())
		};

		tokio::task::spawn(async move {
			let io = Box::pin(io);
			if let Err(e) = http1::Builder::new()
				.serve_connection(io, service_fn(serve))
				.await
			{
				debug!("Error handling HTTP connection: {}", e);
			}
		});
	}

	async fn handle_request(
		self: Arc<Self>,
		req: Request<IncomingBody>,
		addr: String,
	) -> Result<Response<BoxBody<Error>>, Infallible> {
		if let Ok(forwarded_for_ip_addr) =
			forwarded_headers::handle_forwarded_for_headers(req.headers())
		{
			info!(
				"{} (via {}) {} {}",
				forwarded_for_ip_addr,
				addr,
				req.method(),
				req.uri()
			);
		} else {
			info!("{} {} {}", addr, req.method(), req.uri());
		}

		// Lots of instrumentation
		let tracer = opentelemetry::global::tracer("garage");
		let span = tracer
			.span_builder(format!("Web {} request", req.method()))
			.with_trace_id(gen_trace_id())
			.with_attributes(vec![
				KeyValue::new("method", format!("{}", req.method())),
				KeyValue::new("uri", req.uri().to_string()),
			])
			.start(&tracer);

		let metrics_tags = &[KeyValue::new("method", req.method().to_string())];

		// The actual handler
		let res = self
			.serve_file(&req)
			.with_context(Context::current_with_span(span))
			.record_duration(&self.metrics.request_duration, &metrics_tags[..])
			.await;

		// More instrumentation
		self.metrics.request_counter.add(1, &metrics_tags[..]);

		// Returning the result
		match res {
			Ok(res) => {
				debug!("{} {} {}", req.method(), res.status(), req.uri());
				Ok(res
					.map(|body| BoxBody::new(http_body_util::BodyExt::map_err(body, Error::from))))
			}
			Err(error) => {
				info!(
					"{} {} {} {}",
					req.method(),
					error.http_status_code(),
					req.uri(),
					error
				);
				self.metrics.error_counter.add(
					1,
					&[
						metrics_tags[0].clone(),
						KeyValue::new("status_code", error.http_status_code().to_string()),
					],
				);
				Ok(error_to_res(error))
			}
		}
	}

	async fn check_key_exists(self: &Arc<Self>, bucket_id: Uuid, key: &str) -> Result<bool, Error> {
		let exists = self
			.garage
			.object_table
			.get(&bucket_id, &key.to_string())
			.await?
			.map(|object| object.versions().iter().any(|v| v.is_data()))
			.unwrap_or(false);
		Ok(exists)
	}

	async fn serve_file(
		self: &Arc<Self>,
		req: &Request<IncomingBody>,
	) -> Result<Response<BoxBody<ApiError>>, Error> {
		// Get http authority string (eg. [::1]:3902 or garage.tld:80)
		let authority = req
			.headers()
			.get(HOST)
			.ok_or_bad_request("HOST header required")?
			.to_str()?;

		// Get bucket
		let host = authority_to_host(authority)?;

		let bucket_name = host_to_bucket(&host, &self.root_domain).unwrap_or(&host);
		let bucket_id = self
			.garage
			.bucket_alias_table
			.get(&EmptyKey, &bucket_name.to_string())
			.await?
			.and_then(|x| x.state.take())
			.ok_or(Error::NotFound)?;

		// Check bucket isn't deleted and has website access enabled
		let bucket = self
			.garage
			.bucket_table
			.get(&EmptyKey, &bucket_id)
			.await?
			.ok_or(Error::NotFound)?;

		let website_config = bucket
			.params()
			.ok_or(Error::NotFound)?
			.website_config
			.get()
			.as_ref()
			.ok_or(Error::NotFound)?;

		// Get path
		let path = req.uri().path().to_string();
		let index = &website_config.index_document;
		let (key, may_redirect) = path_to_keys(&path, index)?;

		debug!(
			"Selected bucket: \"{}\" {:?}, target key: \"{}\", may redirect to: {:?}",
			bucket_name, bucket_id, key, may_redirect
		);

		let ret_doc = match *req.method() {
			Method::OPTIONS => handle_options_for_bucket(req, &bucket)
				.map_err(ApiError::from)
				.map(|res| res.map(|_empty_body: EmptyBody| empty_body())),
			Method::HEAD => handle_head(self.garage.clone(), &req, bucket_id, &key, None).await,
			Method::GET => handle_get(self.garage.clone(), &req, bucket_id, &key, None).await,
			_ => Err(ApiError::bad_request("HTTP method not supported")),
		};

		// Try implicit redirect on error
		let ret_doc_with_redir = match (&ret_doc, may_redirect) {
			(Err(ApiError::NoSuchKey), ImplicitRedirect::To { key, url })
				if self.check_key_exists(bucket_id, key.as_str()).await? =>
			{
				Ok(Response::builder()
					.status(StatusCode::FOUND)
					.header("Location", url)
					.body(empty_body())
					.unwrap())
			}
			_ => ret_doc,
		};

		match ret_doc_with_redir.map_err(Error::from) {
			Err(error) => {
				// For a HEAD or OPTIONS method, and for non-4xx errors,
				// we don't return the error document as content,
				// we return above and just return the error message
				// by relying on err_to_res that is called when we return an Err.
				if *req.method() == Method::HEAD
					|| *req.method() == Method::OPTIONS
					|| !error.http_status_code().is_client_error()
				{
					return Err(error);
				}

				// If no error document is set: just return the error directly
				let error_document = match &website_config.error_document {
					Some(ed) => ed.trim_start_matches('/').to_owned(),
					None => return Err(error),
				};

				// We want to return the error document
				// Create a fake HTTP request with path = the error document
				let req2 = Request::builder()
					.uri(format!("http://{}/{}", host, &error_document))
					.body(empty_body::<Infallible>())
					.unwrap();

				match handle_get(self.garage.clone(), &req2, bucket_id, &error_document, None).await
				{
					Ok(mut error_doc) => {
						// The error won't be logged back in handle_request,
						// so log it here
						info!(
							"{} {} {} {}",
							req.method(),
							req.uri(),
							error.http_status_code(),
							error
						);

						*error_doc.status_mut() = error.http_status_code();

						// Preserve error message in a special header
						for error_line in error.to_string().split('\n') {
							if let Ok(v) = HeaderValue::from_bytes(error_line.as_bytes()) {
								error_doc.headers_mut().append("X-Garage-Error", v);
							}
						}

						Ok(error_doc)
					}
					Err(error_doc_error) => {
						warn!(
							"Couldn't get error document {} for bucket {:?}: {}",
							error_document, bucket_id, error_doc_error
						);
						Err(error)
					}
				}
			}
			Ok(mut resp) => {
				// Maybe add CORS headers
				if let Some(rule) = find_matching_cors_rule(&bucket, req)? {
					add_cors_headers(&mut resp, rule)
						.ok_or_internal_error("Invalid bucket CORS configuration")?;
				}
				Ok(resp)
			}
		}
	}
}

fn error_to_res(e: Error) -> Response<BoxBody<Error>> {
	// If we are here, it is either that:
	// - there was an error before trying to get the requested URL
	//   from the bucket (e.g. bucket not found)
	// - there was an error processing the request and (the request
	//   was a HEAD request or we couldn't get the error document)
	// We do NOT enter this code path when returning the bucket's
	// error document (this is handled in serve_file)
	let body = string_body(format!("{}\n", e));
	let mut http_error = Response::new(body);
	*http_error.status_mut() = e.http_status_code();
	e.add_headers(http_error.headers_mut());
	http_error
}

#[derive(Debug, PartialEq)]
enum ImplicitRedirect {
	No,
	To { key: String, url: String },
}

/// Path to key
///
/// Convert the provided path to the internal key
/// When a path ends with "/", we append the index name to match traditional web server behavior
/// which is also AWS S3 behavior.
///
/// Check: https://docs.aws.amazon.com/AmazonS3/latest/userguide/IndexDocumentSupport.html
fn path_to_keys<'a>(path: &'a str, index: &str) -> Result<(String, ImplicitRedirect), Error> {
	let path_utf8 = percent_encoding::percent_decode_str(path).decode_utf8()?;

	let base_key = match path_utf8.strip_prefix("/") {
		Some(bk) => bk,
		None => return Err(Error::BadRequest("Path must start with a / (slash)".into())),
	};
	let is_bucket_root = base_key.len() == 0;
	let is_trailing_slash = path_utf8.ends_with("/");

	match (is_bucket_root, is_trailing_slash) {
		// It is not possible to store something at the root of the bucket (ie. empty key),
		// the only option is to fetch the index
		(true, _) => Ok((index.to_string(), ImplicitRedirect::No)),

		// "If you create a folder structure in your bucket, you must have an index document at each level. In each folder, the index document must have the same name, for example, index.html. When a user specifies a URL that resembles a folder lookup, the presence or absence of a trailing slash determines the behavior of the website. For example, the following URL, with a trailing slash, returns the photos/index.html index document."
		(false, true) => Ok((format!("{base_key}{index}"), ImplicitRedirect::No)),

		// "However, if you exclude the trailing slash from the preceding URL, Amazon S3 first looks for an object photos in the bucket. If the photos object is not found, it searches for an index document, photos/index.html. If that document is found, Amazon S3 returns a 302 Found message and points to the photos/ key. For subsequent requests to photos/, Amazon S3 returns photos/index.html. If the index document is not found, Amazon S3 returns an error."
		(false, false) => Ok((
			base_key.to_string(),
			ImplicitRedirect::To {
				key: format!("{base_key}/{index}"),
				url: format!("{path}/"),
			},
		)),
	}
}

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

	#[test]
	fn path_to_keys_test() -> Result<(), Error> {
		assert_eq!(
			path_to_keys("/file%20.jpg", "index.html")?,
			(
				"file .jpg".to_string(),
				ImplicitRedirect::To {
					key: "file .jpg/index.html".to_string(),
					url: "/file%20.jpg/".to_string()
				}
			)
		);
		assert_eq!(
			path_to_keys("/%20t/", "index.html")?,
			(" t/index.html".to_string(), ImplicitRedirect::No)
		);
		assert_eq!(
			path_to_keys("/", "index.html")?,
			("index.html".to_string(), ImplicitRedirect::No)
		);
		assert_eq!(
			path_to_keys("/hello", "index.html")?,
			(
				"hello".to_string(),
				ImplicitRedirect::To {
					key: "hello/index.html".to_string(),
					url: "/hello/".to_string()
				}
			)
		);
		assert!(path_to_keys("", "index.html").is_err());
		assert!(path_to_keys("i/am/relative", "index.html").is_err());
		Ok(())
	}
}