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> {
112 let collected = body.collect().await.map_err(BodyReadError::Io)?;
113 let bytes = collected.to_bytes();
114 if bytes.len() > max_size {
115 Err(BodyReadError::TooLarge)
116 } else {
117 Ok(bytes)
118 }
119}
120
121pub fn classify_upstream_error(err: &guardrail_core::GuardrailError) -> &'static str {
140 if let guardrail_core::GuardrailError::Upstream(reqwest_err) = err {
141 if reqwest_err.is_timeout() {
142 return "timeout";
143 }
144 if reqwest_err.is_connect() {
145 return "connect";
146 }
147 return "other";
148 }
149 "other"
150}
151
152#[cfg(test)]
153mod tests {
154 use super::*;
155
156 #[test]
157 fn test_error_response_shape() {
158 let resp = error_response(StatusCode::BAD_REQUEST, "bad input", "bad_request");
159 assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
160 assert_eq!(
161 resp.headers().get("content-type").unwrap(),
162 "application/json"
163 );
164 }
165
166 #[test]
167 fn test_internal_error_response_is_500() {
168 let resp = internal_error_response();
169 assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
170 }
171
172 #[test]
173 fn test_error_body_response_preserves_arbitrary_json() {
174 let body = serde_json::json!({"custom": "shape", "n": 42});
175 let resp = error_body_response(StatusCode::FORBIDDEN, &body);
176 assert_eq!(resp.status(), StatusCode::FORBIDDEN);
177 }
178
179 #[tokio::test]
180 async fn test_classify_upstream_error_timeout() {
181 use guardrail_core::GuardrailError;
182 use std::time::Duration;
183
184 let client = reqwest::Client::builder()
185 .timeout(Duration::from_millis(50))
186 .build()
187 .unwrap();
188
189 let result = client.get("http://10.255.255.1/").send().await;
190 let err = result.expect_err("request to non-routable address must fail");
191 let guardrail_err = GuardrailError::from(err);
192
193 let class = classify_upstream_error(&guardrail_err);
194 assert!(
195 class == "timeout" || class == "connect",
196 "unexpected classification: {class}"
197 );
198 }
199
200 #[tokio::test]
201 async fn test_classify_upstream_error_connect_refused() {
202 use guardrail_core::GuardrailError;
203
204 let client = reqwest::Client::new();
205 let result = client.get("http://127.0.0.1:1/").send().await;
206 let err = result.expect_err("connection to port 1 must fail");
207 let guardrail_err = GuardrailError::from(err);
208
209 assert_eq!(classify_upstream_error(&guardrail_err), "connect");
210 }
211
212 #[test]
213 fn test_classify_upstream_error_non_upstream_variant_is_other() {
214 use guardrail_core::GuardrailError;
215 let err = GuardrailError::Internal("something else".into());
216 assert_eq!(classify_upstream_error(&err), "other");
217 }
218}