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
use crate::request::ApiGatewayV2;
use core::convert::TryFrom;
use core::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use lamedh_runtime::{
run as lambda_runtime_run, Context as LambdaContext, Error as LambdaError,
Handler as LambdaHandler,
};
pub async fn launch_rocket_on_lambda<P: rocket::Phase>(
r: rocket::Rocket<P>,
) -> Result<(), LambdaError> {
lambda_runtime_run(RocketHandler(Arc::new(
rocket::local::asynchronous::Client::untracked(r).await?,
)))
.await?;
Ok(())
}
struct RocketHandler(Arc<rocket::local::asynchronous::Client>);
impl LambdaHandler<ApiGatewayV2<'_>, serde_json::Value> for RocketHandler {
type Error = rocket::Error;
type Fut = Pin<Box<dyn Future<Output = Result<serde_json::Value, Self::Error>> + Send>>;
fn call(&mut self, event: ApiGatewayV2, _context: LambdaContext) -> Self::Fut {
use serde_json::json;
let client_br = crate::brotli::client_supports_brotli(&event);
let decode_result = RequestDecode::try_from(event);
let client = self.0.clone();
let fut = async move {
match decode_result {
Ok(req_decode) => {
let local_request = req_decode.make_request(&client);
let response = local_request.dispatch().await;
api_gateway_response_from_rocket(response, client_br).await
}
Err(_request_err) => {
Ok(json!({
"isBase64Encoded": false,
"statusCode": 400u16,
"headers": { "content-type": "text/plain"},
"body": "Bad Request"
}))
}
}
};
Box::pin(fut)
}
}
struct RequestDecode {
path_and_query: String,
method: rocket::http::Method,
source_ip: std::net::IpAddr,
cookies: Vec<rocket::http::Cookie<'static>>,
headers: Vec<rocket::http::Header<'static>>,
body: Vec<u8>,
}
impl TryFrom<ApiGatewayV2<'_>> for RequestDecode {
type Error = LambdaError;
fn try_from(event: ApiGatewayV2) -> Result<Self, Self::Error> {
use rocket::http::{Cookie, Header, Method};
use std::net::IpAddr;
use std::str::FromStr;
let path_and_query = if event.raw_query_string.is_empty() {
event.encoded_path().to_string()
} else {
format!("{}?{}", event.encoded_path(), event.raw_query_string)
};
let method = Method::from_str(&event.request_context.http.method as &str)
.map_err(|_| "InvalidMethod")?;
let source_ip = IpAddr::from_str(&event.request_context.http.source_ip as &str)?;
let cookies = if let Some(cookies) = event.cookies {
cookies
.iter()
.filter_map(|cookie| {
Cookie::parse_encoded(cookie as &str)
.map(|c| c.into_owned())
.ok()
})
.collect::<Vec<Cookie>>()
} else {
vec![]
};
let headers = event
.headers
.iter()
.map(|(k, v)| Header::new(k.to_string(), v.to_string()))
.collect::<Vec<Header>>();
let body = if let Some(eventbody) = event.body {
if event.is_base64_encoded {
base64::decode(&eventbody as &str)?
} else {
Vec::<u8>::from(eventbody.into_owned())
}
} else {
vec![]
};
Ok(Self {
path_and_query,
method,
source_ip,
cookies,
headers,
body,
})
}
}
impl RequestDecode {
fn make_request<'c, 's: 'c>(
&'s self,
client: &'c rocket::local::asynchronous::Client,
) -> rocket::local::asynchronous::LocalRequest<'c> {
let req = client
.req(self.method, &self.path_and_query)
.remote(std::net::SocketAddr::from((self.source_ip, 0u16)))
.body(&self.body);
let req = self
.cookies
.iter()
.fold(req, |req, cookie| req.cookie(cookie.clone()));
let req = self
.headers
.iter()
.fold(req, |req, header| req.header(header.clone()));
req
}
}
impl crate::brotli::ResponseCompression for rocket::local::asynchronous::LocalResponse<'_> {
fn content_encoding<'a>(&'a self) -> Option<&'a str> {
self.headers().get_one("content-encoding")
}
fn content_type<'a>(&'a self) -> Option<&'a str> {
self.headers().get_one("content-type")
}
}
async fn api_gateway_response_from_rocket(
response: rocket::local::asynchronous::LocalResponse<'_>,
client_support_br: bool,
) -> Result<serde_json::Value, rocket::Error> {
use crate::brotli::ResponseCompression;
use serde_json::json;
let status_code = response.status().code;
let mut headers = serde_json::Map::new();
for header in response.headers().iter() {
headers.insert(header.name.into_string(), json!(header.value));
}
let compress = client_support_br && response.can_brotli_compress();
let body_bytes = response.into_bytes().await.unwrap_or_default();
let body_base64 = if compress {
headers.insert("content-encoding".to_string(), json!("br"));
crate::brotli::compress_response_body(&body_bytes)
} else {
base64::encode(body_bytes)
};
Ok(json!({
"isBase64Encoded": true,
"statusCode": status_code,
"headers": headers,
"body": body_base64
}))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{request::ApiGatewayV2, test_consts::*};
use rocket::{async_test, local::asynchronous::Client};
use std::path::PathBuf;
#[async_test]
async fn test_path_decode() {
let rocket = rocket::build();
let client = Client::untracked(rocket).await.unwrap();
let reqjson: ApiGatewayV2 = serde_json::from_str(API_GATEWAY_V2_GET_ROOT_NOQUERY).unwrap();
let decode = RequestDecode::try_from(reqjson).unwrap();
let req = decode.make_request(&client);
assert_eq!(&decode.path_and_query, "/");
assert_eq!(req.inner().segments(0..), Ok(PathBuf::new()));
let reqjson: ApiGatewayV2 =
serde_json::from_str(API_GATEWAY_V2_GET_SOMEWHERE_NOQUERY).unwrap();
let decode = RequestDecode::try_from(reqjson).unwrap();
let req = decode.make_request(&client);
assert_eq!(&decode.path_and_query, "/somewhere");
assert_eq!(req.inner().segments(0..), Ok(PathBuf::from("somewhere")));
let reqjson: ApiGatewayV2 =
serde_json::from_str(API_GATEWAY_V2_GET_SPACEPATH_NOQUERY).unwrap();
let decode = RequestDecode::try_from(reqjson).unwrap();
let req = decode.make_request(&client);
assert_eq!(&decode.path_and_query, "/path%20with/space");
assert_eq!(
req.inner().segments(0..),
Ok(PathBuf::from("path with/space"))
);
let reqjson: ApiGatewayV2 =
serde_json::from_str(API_GATEWAY_V2_GET_PERCENTPATH_NOQUERY).unwrap();
let decode = RequestDecode::try_from(reqjson).unwrap();
let req = decode.make_request(&client);
assert_eq!(&decode.path_and_query, "/path%25with/percent");
assert_eq!(
req.inner().segments(0..),
Ok(PathBuf::from("path%with/percent"))
);
let reqjson: ApiGatewayV2 =
serde_json::from_str(API_GATEWAY_V2_GET_UTF8PATH_NOQUERY).unwrap();
let decode = RequestDecode::try_from(reqjson).unwrap();
let req = decode.make_request(&client);
assert_eq!(
&decode.path_and_query,
"/%E6%97%A5%E6%9C%AC%E8%AA%9E/%E3%83%95%E3%82%A1%E3%82%A4%E3%83%AB%E5%90%8D"
);
assert_eq!(
req.inner().segments(0..),
Ok(PathBuf::from("日本語/ファイル名"))
);
}
#[async_test]
async fn test_query_decode() {
let rocket = rocket::build();
let client = Client::untracked(rocket).await.unwrap();
let reqjson: ApiGatewayV2 = serde_json::from_str(API_GATEWAY_V2_GET_ROOT_ONEQUERY).unwrap();
let decode = RequestDecode::try_from(reqjson).unwrap();
let req = decode.make_request(&client);
assert_eq!(&decode.path_and_query, "/?key=value");
assert_eq!(req.inner().segments(0..), Ok(PathBuf::new()));
assert_eq!(req.inner().query_value::<&str>("key").unwrap(), Ok("value"));
let reqjson: ApiGatewayV2 =
serde_json::from_str(API_GATEWAY_V2_GET_SOMEWHERE_ONEQUERY).unwrap();
let decode = RequestDecode::try_from(reqjson).unwrap();
let req = decode.make_request(&client);
assert_eq!(&decode.path_and_query, "/somewhere?key=value");
assert_eq!(req.inner().segments(0..), Ok(PathBuf::from("somewhere")));
assert_eq!(req.inner().query_value::<&str>("key").unwrap(), Ok("value"));
let reqjson: ApiGatewayV2 =
serde_json::from_str(API_GATEWAY_V2_GET_SOMEWHERE_TWOQUERY).unwrap();
let decode = RequestDecode::try_from(reqjson).unwrap();
let req = decode.make_request(&client);
assert_eq!(&decode.path_and_query, "/somewhere?key1=value1&key2=value2");
assert_eq!(
req.inner().query_value::<&str>("key1").unwrap(),
Ok("value1")
);
assert_eq!(
req.inner().query_value::<&str>("key2").unwrap(),
Ok("value2")
);
let reqjson: ApiGatewayV2 =
serde_json::from_str(API_GATEWAY_V2_GET_SOMEWHERE_SPACEQUERY).unwrap();
let decode = RequestDecode::try_from(reqjson).unwrap();
let req = decode.make_request(&client);
assert_eq!(&decode.path_and_query, "/somewhere?key=value1+value2");
assert_eq!(
req.inner().query_value::<&str>("key").unwrap(),
Ok("value1 value2")
);
let reqjson: ApiGatewayV2 =
serde_json::from_str(API_GATEWAY_V2_GET_SOMEWHERE_UTF8QUERY).unwrap();
let decode = RequestDecode::try_from(reqjson).unwrap();
let req = decode.make_request(&client);
assert_eq!(
&decode.path_and_query,
"/somewhere?key=%E6%97%A5%E6%9C%AC%E8%AA%9E"
);
assert_eq!(
req.inner().query_value::<&str>("key").unwrap(),
Ok("日本語")
);
}
#[async_test]
async fn test_remote_ip_decode() {
use std::net::IpAddr;
use std::str::FromStr;
let rocket = rocket::build();
let client = Client::untracked(rocket).await.unwrap();
let reqjson: ApiGatewayV2 = serde_json::from_str(API_GATEWAY_V2_GET_ROOT_ONEQUERY).unwrap();
let decode = RequestDecode::try_from(reqjson).unwrap();
let req = decode.make_request(&client);
assert_eq!(decode.source_ip, IpAddr::from_str("1.2.3.4").unwrap());
assert_eq!(
req.inner().client_ip(),
Some(IpAddr::from_str("1.2.3.4").unwrap())
);
let reqjson: ApiGatewayV2 = serde_json::from_str(API_GATEWAY_V2_GET_REMOTE_IPV6).unwrap();
let decode = RequestDecode::try_from(reqjson).unwrap();
let req = decode.make_request(&client);
assert_eq!(
decode.source_ip,
IpAddr::from_str("2404:6800:400a:80c::2004").unwrap()
);
assert_eq!(
req.inner().client_ip(),
Some(IpAddr::from_str("2404:6800:400a:80c::2004").unwrap())
);
}
#[async_test]
async fn test_form_post() {
use rocket::http::ContentType;
use rocket::http::Method;
let rocket = rocket::build();
let client = Client::untracked(rocket).await.unwrap();
let reqjson: ApiGatewayV2 =
serde_json::from_str(API_GATEWAY_V2_POST_FORM_URLENCODED).unwrap();
let decode = RequestDecode::try_from(reqjson).unwrap();
let req = decode.make_request(&client);
assert_eq!(&decode.body, b"key1=value1&key2=value2&Ok=Ok");
assert_eq!(req.inner().method(), Method::Post);
assert_eq!(req.inner().content_type(), Some(&ContentType::Form));
let reqjson: ApiGatewayV2 =
serde_json::from_str(API_GATEWAY_V2_POST_FORM_URLENCODED_B64).unwrap();
let decode = RequestDecode::try_from(reqjson).unwrap();
let req = decode.make_request(&client);
assert_eq!(&decode.body, b"key1=value1&key2=value2&Ok=Ok");
assert_eq!(req.inner().method(), Method::Post);
assert_eq!(req.inner().content_type(), Some(&ContentType::Form));
}
#[async_test]
async fn test_parse_header() {
let rocket = rocket::build();
let client = Client::untracked(rocket).await.unwrap();
let reqjson: ApiGatewayV2 = serde_json::from_str(API_GATEWAY_V2_GET_ROOT_NOQUERY).unwrap();
let decode = RequestDecode::try_from(reqjson).unwrap();
let req = decode.make_request(&client);
assert_eq!(
req.inner().headers().get_one("x-forwarded-port"),
Some("443")
);
assert_eq!(
req.inner().headers().get_one("x-forwarded-proto"),
Some("https")
);
}
#[async_test]
async fn test_parse_cookies() {
let rocket = rocket::build();
let client = Client::untracked(rocket).await.unwrap();
let reqjson: ApiGatewayV2 = serde_json::from_str(API_GATEWAY_V2_GET_ROOT_NOQUERY).unwrap();
let decode = RequestDecode::try_from(reqjson).unwrap();
let req = decode.make_request(&client);
assert_eq!(req.inner().cookies().iter().count(), 0);
let reqjson: ApiGatewayV2 = serde_json::from_str(API_GATEWAY_V2_GET_ONE_COOKIE).unwrap();
let decode = RequestDecode::try_from(reqjson).unwrap();
let req = decode.make_request(&client);
assert_eq!(
req.inner().cookies().get("cookie1").unwrap().value(),
"value1"
);
let reqjson: ApiGatewayV2 = serde_json::from_str(API_GATEWAY_V2_GET_TWO_COOKIES).unwrap();
let decode = RequestDecode::try_from(reqjson).unwrap();
let req = decode.make_request(&client);
assert_eq!(
req.inner().cookies().get("cookie1").unwrap().value(),
"value1"
);
assert_eq!(
req.inner().cookies().get("cookie2").unwrap().value(),
"value2"
);
}
}