1use bytes::Bytes;
11use http_body_util::BodyExt;
12use http_body_util::Full;
13use hyper::body::Incoming;
14use hyper::{Response, StatusCode};
15
16pub fn error_response(status: StatusCode, message: &str, code: &str) -> Response<Full<Bytes>> {
32 let body = serde_json::json!({
33 "error": {
34 "message": message,
35 "type": "guardrail_error",
36 "code": code,
37 }
38 });
39 error_body_response(status, &body)
40}
41
42pub fn error_body_response(status: StatusCode, body: &serde_json::Value) -> Response<Full<Bytes>> {
55 let bytes = serde_json::to_vec(body).unwrap_or_default();
56 Response::builder()
57 .status(status)
58 .header("content-type", "application/json")
59 .body(Full::new(Bytes::from(bytes)))
60 .expect("response build never fails for valid status/headers")
61}
62
63pub fn internal_error_response() -> Response<Full<Bytes>> {
75 Response::builder()
76 .status(StatusCode::INTERNAL_SERVER_ERROR)
77 .header("content-type", "application/json")
78 .body(Full::new(Bytes::from(
79 r#"{"error":{"message":"internal server error","type":"guardrail_internal_error"}}"#,
80 )))
81 .expect("static response is valid")
82}
83
84#[derive(Debug)]
86pub enum BodyReadError {
87 TooLarge,
89 Io(hyper::Error),
91}
92
93pub async fn read_limited_body(body: Incoming, max_size: usize) -> Result<Bytes, BodyReadError> {
114 match collect_limited(body, max_size).await {
115 Ok(bytes) => Ok(bytes),
116 Err(None) => Err(BodyReadError::TooLarge),
117 Err(Some(e)) => Err(BodyReadError::Io(e)),
118 }
119}
120
121async fn collect_limited<B>(body: B, max_size: usize) -> Result<Bytes, Option<B::Error>>
125where
126 B: hyper::body::Body<Data = Bytes> + Unpin,
127{
128 let declared = body.size_hint().lower();
129 if declared > max_size as u64 {
130 return Err(None);
131 }
132
133 let mut body = body;
134 let mut buf = bytes::BytesMut::with_capacity(declared as usize);
135 while let Some(frame) = body.frame().await {
136 let frame = frame.map_err(Some)?;
137 if let Ok(data) = frame.into_data() {
138 if buf.len() + data.len() > max_size {
139 return Err(None);
140 }
141 buf.extend_from_slice(&data);
142 }
143 }
144 Ok(buf.freeze())
145}
146
147pub fn classify_upstream_error(err: &guardrail_core::GuardrailError) -> &'static str {
166 if let guardrail_core::GuardrailError::Upstream(reqwest_err) = err {
167 if reqwest_err.is_timeout() {
168 return "timeout";
169 }
170 if reqwest_err.is_connect() {
171 return "connect";
172 }
173 return "other";
174 }
175 "other"
176}
177
178#[cfg(test)]
179mod tests {
180 use super::*;
181
182 #[test]
183 fn test_error_response_shape() {
184 let resp = error_response(StatusCode::BAD_REQUEST, "bad input", "bad_request");
185 assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
186 assert_eq!(
187 resp.headers().get("content-type").unwrap(),
188 "application/json"
189 );
190 }
191
192 #[test]
193 fn test_internal_error_response_is_500() {
194 let resp = internal_error_response();
195 assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
196 }
197
198 #[test]
199 fn test_error_body_response_preserves_arbitrary_json() {
200 let body = serde_json::json!({"custom": "shape", "n": 42});
201 let resp = error_body_response(StatusCode::FORBIDDEN, &body);
202 assert_eq!(resp.status(), StatusCode::FORBIDDEN);
203 }
204
205 fn endless_body() -> http_body_util::StreamBody<
209 impl futures::Stream<Item = Result<hyper::body::Frame<Bytes>, std::convert::Infallible>>,
210 > {
211 let chunk = Bytes::from(vec![b'a'; 64 * 1024]);
212 http_body_util::StreamBody::new(futures::stream::repeat_with(move || {
213 Ok(hyper::body::Frame::data(chunk.clone()))
214 }))
215 }
216
217 #[tokio::test]
218 async fn test_body_limit_stops_reading_an_endless_body() {
219 let result = tokio::time::timeout(
220 std::time::Duration::from_secs(5),
221 collect_limited(endless_body(), 1024 * 1024),
222 )
223 .await
224 .expect("must stop at the limit instead of reading forever");
225 assert!(matches!(result, Err(None)));
226 }
227
228 #[tokio::test]
229 async fn test_body_limit_rejects_declared_length_without_reading() {
230 let body = Full::new(Bytes::from(vec![b'a'; 2048]));
233 assert!(matches!(collect_limited(body, 1024).await, Err(None)));
234 }
235
236 #[tokio::test]
237 async fn test_body_limit_allows_body_at_the_limit() {
238 let data = Bytes::from(vec![b'a'; 1024]);
239 let body = Full::new(data.clone());
240 assert_eq!(collect_limited(body, 1024).await.ok(), Some(data));
241
242 let pieces = futures::stream::iter((0..4).map(|_| {
244 Ok::<_, std::convert::Infallible>(hyper::body::Frame::data(Bytes::from_static(b"abcd")))
245 }));
246 let body = http_body_util::StreamBody::new(pieces);
247 assert_eq!(
248 collect_limited(body, 16).await.ok(),
249 Some(Bytes::from_static(b"abcdabcdabcdabcd"))
250 );
251 }
252
253 #[tokio::test]
254 async fn test_classify_upstream_error_timeout() {
255 use guardrail_core::GuardrailError;
256 use std::time::Duration;
257
258 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
263 let addr = listener.local_addr().unwrap();
264 let server = tokio::spawn(async move {
265 let (_socket, _) = listener.accept().await.unwrap();
266 std::future::pending::<()>().await;
268 });
269
270 let client = reqwest::Client::builder()
271 .timeout(Duration::from_millis(200))
272 .build()
273 .unwrap();
274
275 let result = client.get(format!("http://{addr}/")).send().await;
276 server.abort();
277 let err = result.expect_err("a server that never responds must time out");
278 let guardrail_err = GuardrailError::from(err);
279
280 assert_eq!(classify_upstream_error(&guardrail_err), "timeout");
281 }
282
283 #[tokio::test]
284 async fn test_classify_upstream_error_connect_refused() {
285 use guardrail_core::GuardrailError;
286
287 let client = reqwest::Client::new();
288 let result = client.get("http://127.0.0.1:1/").send().await;
289 let err = result.expect_err("connection to port 1 must fail");
290 let guardrail_err = GuardrailError::from(err);
291
292 assert_eq!(classify_upstream_error(&guardrail_err), "connect");
293 }
294
295 #[test]
296 fn test_classify_upstream_error_non_upstream_variant_is_other() {
297 use guardrail_core::GuardrailError;
298 let err = GuardrailError::Internal("something else".into());
299 assert_eq!(classify_upstream_error(&err), "other");
300 }
301}