use std::borrow::Cow;
use std::collections::HashMap;
use lambda_http::RequestExt;
use lambda_http::http::{HeaderMap, Method, StatusCode};
use lambda_http::request::RequestContext;
use serde::de::DeserializeOwned;
use super::codes;
use super::failure::{Failure, FailureKind};
pub const DEFAULT_BODY_LIMIT: usize = 1024 * 1024;
#[derive(Debug, Clone, Copy)]
pub struct Request<'a> {
inner: &'a lambda_http::Request,
body_limit: usize,
}
impl<'a> Request<'a> {
pub fn new(inner: &'a lambda_http::Request) -> Self {
Self {
inner,
body_limit: DEFAULT_BODY_LIMIT,
}
}
#[must_use]
pub fn with_body_limit(mut self, limit: usize) -> Self {
self.body_limit = limit;
self
}
pub fn native(&self) -> &'a lambda_http::Request {
self.inner
}
pub fn method(&self) -> &'a Method {
self.inner.method()
}
pub fn headers(&self) -> &'a HeaderMap {
self.inner.headers()
}
pub fn header(&self, name: &str) -> Option<&'a str> {
self.inner
.headers()
.get(name)
.and_then(|value| value.to_str().ok())
}
pub fn raw_body(&self) -> &'a [u8] {
self.inner.body().as_ref()
}
pub fn query_string(&self) -> &'a str {
self.inner.uri().query().unwrap_or_default()
}
pub fn query_pairs(&self) -> Vec<(String, String)> {
self.inner
.query_string_parameters()
.iter()
.map(|(name, value)| (name.to_owned(), value.to_owned()))
.collect()
}
pub fn path_parameters(&self) -> HashMap<String, String> {
self.inner
.path_parameters()
.iter()
.map(|(name, value)| (name.to_owned(), value.to_owned()))
.collect()
}
pub fn path<T: DeserializeOwned>(&self) -> Result<T, Failure> {
let parameters = self.inner.path_parameters();
let pairs: Vec<_> = parameters.iter().collect();
let encoded = serde_urlencoded::to_string(pairs).unwrap_or_default();
serde_urlencoded::from_str(&encoded)
.map_err(|_| decode_failure(codes::INVALID_PATH, "path"))
}
pub fn query<T: DeserializeOwned>(&self) -> Result<T, Failure> {
serde_urlencoded::from_str(self.query_string())
.map_err(|_| decode_failure(codes::INVALID_QUERY, "query"))
}
#[must_use]
pub fn source_ip(&self) -> String {
let ip = match self.inner.request_context_ref() {
Some(RequestContext::ApiGatewayV2(gateway)) => gateway.http.source_ip.as_deref(),
#[cfg(feature = "apigw-rest")]
Some(RequestContext::ApiGatewayV1(gateway)) => gateway.identity.source_ip.as_deref(),
#[cfg(feature = "alb")]
Some(RequestContext::Alb(_)) => self
.headers()
.get_all("x-forwarded-for")
.iter()
.next_back()
.and_then(|forwarded| forwarded.to_str().ok())
.and_then(|forwarded| forwarded.rsplit(',').next())
.map(str::trim),
_ => None,
};
ip.filter(|ip| !ip.is_empty())
.unwrap_or("unknown")
.to_owned()
}
pub fn json<T: DeserializeOwned>(&self) -> Result<T, Failure> {
self.json_bounded(self.body_limit)
}
pub fn json_bounded<T: DeserializeOwned>(&self, limit: usize) -> Result<T, Failure> {
self.with_body_limit(limit.min(self.body_limit))
.check_body_limit()?;
self.check_json_media_type()?;
let bytes = self.raw_body();
if bytes.is_empty() {
return Err(Failure::new(
StatusCode::BAD_REQUEST,
codes::MALFORMED_BODY,
"The request body is required",
)
.with_kind(FailureKind::Decode));
}
serde_json::from_slice(bytes).map_err(|_| decode_failure(codes::MALFORMED_BODY, "body"))
}
pub fn form<T: DeserializeOwned>(&self) -> Result<T, Failure> {
self.check_body_limit()?;
if self
.media_type()
.is_some_and(|media| media != "application/x-www-form-urlencoded")
{
return Err(Failure::new(
StatusCode::UNSUPPORTED_MEDIA_TYPE,
codes::UNSUPPORTED_MEDIA_TYPE,
"Expected application/x-www-form-urlencoded",
)
.with_kind(FailureKind::Decode));
}
serde_urlencoded::from_bytes(self.raw_body())
.map_err(|_| decode_failure(codes::MALFORMED_BODY, "body"))
}
pub fn check_body_limit(&self) -> Result<(), Failure> {
if self.raw_body().len() > self.body_limit {
return Err(Failure::new(
StatusCode::PAYLOAD_TOO_LARGE,
codes::BODY_TOO_LARGE,
"The request body is too large",
)
.with_detail(format!("Body exceeds the {} byte limit", self.body_limit))
.with_kind(FailureKind::Decode));
}
Ok(())
}
pub fn json_text(&self) -> Result<&'a str, Failure> {
self.check_body_limit()?;
self.check_json_media_type()?;
std::str::from_utf8(self.raw_body())
.map_err(|_| decode_failure(codes::MALFORMED_BODY, "body"))
}
fn check_json_media_type(&self) -> Result<(), Failure> {
if self
.media_type()
.is_some_and(|media| media != "application/json")
{
return Err(Failure::new(
StatusCode::UNSUPPORTED_MEDIA_TYPE,
codes::UNSUPPORTED_MEDIA_TYPE,
"Expected application/json",
)
.with_kind(FailureKind::Decode));
}
Ok(())
}
pub fn media_type(&self) -> Option<Cow<'a, str>> {
let value = self.header("content-type")?;
let base = value.split(';').next().unwrap_or_default().trim();
Some(if base.chars().any(char::is_uppercase) {
Cow::Owned(base.to_lowercase())
} else {
Cow::Borrowed(base)
})
}
}
#[cfg(feature = "validate")]
impl Request<'_> {
pub fn validated_json<T>(&self) -> Result<T, Failure>
where
T: DeserializeOwned + garde::Validate<Context = ()>,
{
let value: T = self.json()?;
value.validate().map_err(|_| {
Failure::new(
StatusCode::BAD_REQUEST,
codes::INVALID_BODY,
"Request validation failed",
)
.with_kind(FailureKind::Decode)
})?;
Ok(value)
}
}
fn decode_failure(code: &'static str, what: &str) -> Failure {
Failure::new(
StatusCode::BAD_REQUEST,
code,
format!("Invalid request {what}"),
)
.with_kind(FailureKind::Decode)
}