aboutsummaryrefslogtreecommitdiff
path: root/src/garage/tests/common/custom_requester.rs
blob: 580691a17abae05ee18dfd0b3e98951c6d4cf7b5 (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
#![allow(dead_code)]

use std::collections::HashMap;
use std::convert::TryFrom;

use chrono::{offset::Utc, DateTime};
use hmac::{Hmac, Mac};
use hyper::client::HttpConnector;
use hyper::{Body, Client, Method, Request, Response, Uri};

use super::garage::{Instance, Key};
use garage_api::signature;

/// You should ever only use this to send requests AWS sdk won't send,
/// like to reproduce behavior of unusual implementations found to be
/// problematic.
pub struct CustomRequester {
	key: Key,
	uri: Uri,
	client: Client<HttpConnector>,
}

impl CustomRequester {
	pub fn new(instance: &Instance) -> Self {
		CustomRequester {
			key: instance.key.clone(),
			uri: instance.uri(),
			client: Client::new(),
		}
	}

	pub fn builder(&self, bucket: String) -> RequestBuilder<'_> {
		RequestBuilder {
			requester: self,
			bucket,
			method: Method::GET,
			path: String::new(),
			query_params: HashMap::new(),
			signed_headers: HashMap::new(),
			unsigned_headers: HashMap::new(),
			body: Vec::new(),
			body_signature: BodySignature::Classic,
			vhost_style: false,
		}
	}
}

pub struct RequestBuilder<'a> {
	requester: &'a CustomRequester,
	bucket: String,
	method: Method,
	path: String,
	query_params: HashMap<String, Option<String>>,
	signed_headers: HashMap<String, String>,
	unsigned_headers: HashMap<String, String>,
	body: Vec<u8>,
	body_signature: BodySignature,
	vhost_style: bool,
}

impl<'a> RequestBuilder<'a> {
	pub fn method(&mut self, method: Method) -> &mut Self {
		self.method = method;
		self
	}

	pub fn path(&mut self, path: String) -> &mut Self {
		self.path = path;
		self
	}

	pub fn query_params(&mut self, query_params: HashMap<String, Option<String>>) -> &mut Self {
		self.query_params = query_params;
		self
	}

	pub fn signed_headers(&mut self, signed_headers: HashMap<String, String>) -> &mut Self {
		self.signed_headers = signed_headers;
		self
	}

	pub fn unsigned_headers(&mut self, unsigned_headers: HashMap<String, String>) -> &mut Self {
		self.unsigned_headers = unsigned_headers;
		self
	}

	pub fn body(&mut self, body: Vec<u8>) -> &mut Self {
		self.body = body;
		self
	}

	pub fn body_signature(&mut self, body_signature: BodySignature) -> &mut Self {
		self.body_signature = body_signature;
		self
	}

	pub fn vhost_style(&mut self, vhost_style: bool) -> &mut Self {
		self.vhost_style = vhost_style;
		self
	}

	pub async fn send(&mut self) -> hyper::Result<Response<Body>> {
		// TODO this is a bit incorrect in that path and query params should be url-encoded and
		// aren't, but this is good enought for now.

		let query = query_param_to_string(&self.query_params);
		let (host, path) = if self.vhost_style {
			(
				format!("{}.s3.garage", self.bucket),
				format!("{}{}", self.path, query),
			)
		} else {
			(
				"s3.garage".to_owned(),
				format!("{}/{}{}", self.bucket, self.path, query),
			)
		};
		let uri = format!("{}{}", self.requester.uri, path);

		let now = Utc::now();
		let scope = signature::compute_scope(&now, super::REGION.as_ref());
		let mut signer = signature::signing_hmac(
			&now,
			&self.requester.key.secret,
			super::REGION.as_ref(),
			"s3",
		)
		.unwrap();
		let streaming_signer = signer.clone();

		let mut all_headers = self.signed_headers.clone();

		let date = now.format(signature::LONG_DATETIME).to_string();
		all_headers.insert("x-amz-date".to_owned(), date);
		all_headers.insert("host".to_owned(), host);

		let body_sha = match self.body_signature {
			BodySignature::Unsigned => "UNSIGNED-PAYLOAD".to_owned(),
			BodySignature::Classic => hex::encode(garage_util::data::sha256sum(&self.body)),
			BodySignature::Streaming(size) => {
				all_headers.insert("content-encoding".to_owned(), "aws-chunked".to_owned());
				all_headers.insert(
					"x-amz-decoded-content-length".to_owned(),
					self.body.len().to_string(),
				);
				// Get lenght of body by doing the conversion to a streaming body with an
				// invalid signature (we don't know the seed) just to get its length. This
				// is a pretty lazy and inefficient way to do it, but it's enought for test
				// code.
				all_headers.insert(
					"content-length".to_owned(),
					to_streaming_body(&self.body, size, String::new(), signer.clone(), now, "")
						.len()
						.to_string(),
				);

				"STREAMING-AWS4-HMAC-SHA256-PAYLOAD".to_owned()
			}
		};
		all_headers.insert("x-amz-content-sha256".to_owned(), body_sha.clone());

		let mut signed_headers = all_headers
			.iter()
			.map(|(k, _)| k.as_ref())
			.collect::<Vec<&str>>();
		signed_headers.sort();
		let signed_headers = signed_headers.join(";");

		all_headers.extend(self.unsigned_headers.clone());

		let canonical_request = signature::payload::canonical_request(
			&self.method,
			&Uri::try_from(&uri).unwrap(),
			&all_headers,
			&signed_headers,
			&body_sha,
		);

		let string_to_sign = signature::payload::string_to_sign(&now, &scope, &canonical_request);

		signer.update(string_to_sign.as_bytes());
		let signature = hex::encode(signer.finalize().into_bytes());
		let authorization = format!(
			"AWS4-HMAC-SHA256 Credential={}/{},SignedHeaders={},Signature={}",
			self.requester.key.id, scope, signed_headers, signature
		);
		all_headers.insert("authorization".to_owned(), authorization);

		let mut request = Request::builder();
		for (k, v) in all_headers {
			request = request.header(k, v);
		}

		let body = if let BodySignature::Streaming(size) = self.body_signature {
			to_streaming_body(&self.body, size, signature, streaming_signer, now, &scope)
		} else {
			self.body.clone()
		};
		let request = request
			.uri(uri)
			.method(self.method.clone())
			.body(Body::from(body))
			.unwrap();
		self.requester.client.request(request).await
	}
}

pub enum BodySignature {
	Unsigned,
	Classic,
	Streaming(usize),
}

fn query_param_to_string(params: &HashMap<String, Option<String>>) -> String {
	if params.is_empty() {
		return String::new();
	}

	"?".to_owned()
		+ &params
			.iter()
			.map(|(k, v)| {
				if let Some(v) = v {
					format!("{}={}", k, v)
				} else {
					k.clone()
				}
			})
			.collect::<Vec<String>>()
			.join("&")
}

fn to_streaming_body(
	body: &[u8],
	chunk_size: usize,
	mut seed: String,
	hasher: Hmac<sha2::Sha256>,
	now: DateTime<Utc>,
	scope: &str,
) -> Vec<u8> {
	const SHA_NULL: &str = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
	let now = now.format(signature::LONG_DATETIME).to_string();
	let mut res = Vec::with_capacity(body.len());
	for chunk in body.chunks(chunk_size).chain(std::iter::once(&[][..])) {
		let to_sign = format!(
			"AWS4-HMAC-SHA256-PAYLOAD\n{}\n{}\n{}\n{}\n{}",
			now,
			scope,
			seed,
			SHA_NULL,
			hex::encode(garage_util::data::sha256sum(chunk))
		);

		let mut hasher = hasher.clone();
		hasher.update(to_sign.as_bytes());
		seed = hex::encode(hasher.finalize().into_bytes());

		let header = format!("{:x};chunk-signature={}\r\n", chunk.len(), seed);
		res.extend_from_slice(header.as_bytes());
		res.extend_from_slice(chunk);
		res.extend_from_slice(b"\r\n");
	}

	res
}