use bytes::Bytes;
use http_body_util::BodyExt;
use http_body_util::Full;
use hyper::body::Incoming;
use hyper::{Response, StatusCode};
pub fn error_response(status: StatusCode, message: &str, code: &str) -> Response<Full<Bytes>> {
let body = serde_json::json!({
"error": {
"message": message,
"type": "guardrail_error",
"code": code,
}
});
error_body_response(status, &body)
}
pub fn error_body_response(status: StatusCode, body: &serde_json::Value) -> Response<Full<Bytes>> {
let bytes = serde_json::to_vec(body).unwrap_or_default();
Response::builder()
.status(status)
.header("content-type", "application/json")
.body(Full::new(Bytes::from(bytes)))
.expect("response build never fails for valid status/headers")
}
pub fn internal_error_response() -> Response<Full<Bytes>> {
Response::builder()
.status(StatusCode::INTERNAL_SERVER_ERROR)
.header("content-type", "application/json")
.body(Full::new(Bytes::from(
r#"{"error":{"message":"internal server error","type":"guardrail_internal_error"}}"#,
)))
.expect("static response is valid")
}
#[derive(Debug)]
pub enum BodyReadError {
TooLarge,
Io(hyper::Error),
}
pub async fn read_limited_body(body: Incoming, max_size: usize) -> Result<Bytes, BodyReadError> {
match collect_limited(body, max_size).await {
Ok(bytes) => Ok(bytes),
Err(None) => Err(BodyReadError::TooLarge),
Err(Some(e)) => Err(BodyReadError::Io(e)),
}
}
async fn collect_limited<B>(body: B, max_size: usize) -> Result<Bytes, Option<B::Error>>
where
B: hyper::body::Body<Data = Bytes> + Unpin,
{
let declared = body.size_hint().lower();
if declared > max_size as u64 {
return Err(None);
}
let mut body = body;
let mut buf = bytes::BytesMut::with_capacity(declared as usize);
while let Some(frame) = body.frame().await {
let frame = frame.map_err(Some)?;
if let Ok(data) = frame.into_data() {
if buf.len() + data.len() > max_size {
return Err(None);
}
buf.extend_from_slice(&data);
}
}
Ok(buf.freeze())
}
pub fn classify_upstream_error(err: &guardrail_core::GuardrailError) -> &'static str {
if let guardrail_core::GuardrailError::Upstream(reqwest_err) = err {
if reqwest_err.is_timeout() {
return "timeout";
}
if reqwest_err.is_connect() {
return "connect";
}
return "other";
}
"other"
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_error_response_shape() {
let resp = error_response(StatusCode::BAD_REQUEST, "bad input", "bad_request");
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
assert_eq!(
resp.headers().get("content-type").unwrap(),
"application/json"
);
}
#[test]
fn test_internal_error_response_is_500() {
let resp = internal_error_response();
assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
}
#[test]
fn test_error_body_response_preserves_arbitrary_json() {
let body = serde_json::json!({"custom": "shape", "n": 42});
let resp = error_body_response(StatusCode::FORBIDDEN, &body);
assert_eq!(resp.status(), StatusCode::FORBIDDEN);
}
fn endless_body() -> http_body_util::StreamBody<
impl futures::Stream<Item = Result<hyper::body::Frame<Bytes>, std::convert::Infallible>>,
> {
let chunk = Bytes::from(vec![b'a'; 64 * 1024]);
http_body_util::StreamBody::new(futures::stream::repeat_with(move || {
Ok(hyper::body::Frame::data(chunk.clone()))
}))
}
#[tokio::test]
async fn test_body_limit_stops_reading_an_endless_body() {
let result = tokio::time::timeout(
std::time::Duration::from_secs(5),
collect_limited(endless_body(), 1024 * 1024),
)
.await
.expect("must stop at the limit instead of reading forever");
assert!(matches!(result, Err(None)));
}
#[tokio::test]
async fn test_body_limit_rejects_declared_length_without_reading() {
let body = Full::new(Bytes::from(vec![b'a'; 2048]));
assert!(matches!(collect_limited(body, 1024).await, Err(None)));
}
#[tokio::test]
async fn test_body_limit_allows_body_at_the_limit() {
let data = Bytes::from(vec![b'a'; 1024]);
let body = Full::new(data.clone());
assert_eq!(collect_limited(body, 1024).await.ok(), Some(data));
let pieces = futures::stream::iter((0..4).map(|_| {
Ok::<_, std::convert::Infallible>(hyper::body::Frame::data(Bytes::from_static(b"abcd")))
}));
let body = http_body_util::StreamBody::new(pieces);
assert_eq!(
collect_limited(body, 16).await.ok(),
Some(Bytes::from_static(b"abcdabcdabcdabcd"))
);
}
#[tokio::test]
async fn test_classify_upstream_error_timeout() {
use guardrail_core::GuardrailError;
use std::time::Duration;
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
let server = tokio::spawn(async move {
let (_socket, _) = listener.accept().await.unwrap();
std::future::pending::<()>().await;
});
let client = reqwest::Client::builder()
.timeout(Duration::from_millis(200))
.build()
.unwrap();
let result = client.get(format!("http://{addr}/")).send().await;
server.abort();
let err = result.expect_err("a server that never responds must time out");
let guardrail_err = GuardrailError::from(err);
assert_eq!(classify_upstream_error(&guardrail_err), "timeout");
}
#[tokio::test]
async fn test_classify_upstream_error_connect_refused() {
use guardrail_core::GuardrailError;
let client = reqwest::Client::new();
let result = client.get("http://127.0.0.1:1/").send().await;
let err = result.expect_err("connection to port 1 must fail");
let guardrail_err = GuardrailError::from(err);
assert_eq!(classify_upstream_error(&guardrail_err), "connect");
}
#[test]
fn test_classify_upstream_error_non_upstream_variant_is_other() {
use guardrail_core::GuardrailError;
let err = GuardrailError::Internal("something else".into());
assert_eq!(classify_upstream_error(&err), "other");
}
}