Skip to main content

guardrail_proxy/
error.rs

1//! HTTP response and error-construction helpers shared across the request
2//! handler.
3//!
4//! Kept separate from `crate::handler` so error-shape concerns (what does
5//! a 400 vs 403 vs 502 body look like) are reviewable independently of
6//! routing/business logic, and so the body-reading size-limit logic — which
7//! has a non-obvious "did the connection error or did the body exceed the
8//! limit" distinction — has room to be documented and tested on its own.
9
10use bytes::Bytes;
11use http_body_util::BodyExt;
12use http_body_util::Full;
13use hyper::body::Incoming;
14use hyper::{Response, StatusCode};
15
16/// Build a standard error response body and wrap it as a full HTTP response.
17///
18/// # Examples
19///
20/// ```rust
21/// use guardrail_proxy::error::error_response;
22/// use hyper::StatusCode;
23///
24/// let resp = error_response(StatusCode::BAD_REQUEST, "invalid JSON", "bad_request");
25/// assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
26/// assert_eq!(
27///     resp.headers().get("content-type").unwrap(),
28///     "application/json"
29/// );
30/// ```
31pub 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
42/// Wrap an arbitrary JSON value as a full HTTP response with the given status.
43///
44/// # Examples
45///
46/// ```rust
47/// use guardrail_proxy::error::error_body_response;
48/// use hyper::StatusCode;
49///
50/// let body = serde_json::json!({"error": {"code": "prompt_injection"}});
51/// let resp = error_body_response(StatusCode::FORBIDDEN, &body);
52/// assert_eq!(resp.status(), StatusCode::FORBIDDEN);
53/// ```
54pub 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
63/// A generic `500` response for failures that have no more specific status.
64///
65/// # Examples
66///
67/// ```rust
68/// use guardrail_proxy::error::internal_error_response;
69/// use hyper::StatusCode;
70///
71/// let resp = internal_error_response();
72/// assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
73/// ```
74pub 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/// Why reading the request body failed.
85#[derive(Debug)]
86pub enum BodyReadError {
87    /// The body exceeded `server.max_body_size_bytes`.
88    TooLarge,
89    /// A transport-level error occurred while reading.
90    Io(hyper::Error),
91}
92
93/// Read an incoming request body, enforcing `max_size` as a byte ceiling.
94///
95/// The limit is enforced while reading: frames are accumulated only until
96/// the total would exceed `max_size`, then reading stops and the rest of the
97/// body is never pulled into memory. A body whose declared length
98/// (`Content-Length`) is already over the limit is rejected before reading
99/// anything. Counting actual bytes also covers clients that omit or
100/// understate `Content-Length` and stream with chunked encoding.
101///
102/// # Examples
103///
104/// ```rust,no_run
105/// use guardrail_proxy::error::read_limited_body;
106/// # async fn example(body: hyper::body::Incoming) {
107/// match read_limited_body(body, 1024).await {
108///     Ok(bytes) => { /* use bytes */ }
109///     Err(err) => { let _ = err; /* too large or I/O error */ }
110/// }
111/// # }
112/// ```
113pub 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
121/// Collect `body` into memory, stopping as soon as it's known to be longer
122/// than `max_size`. `Err(None)` means too large; `Err(Some(e))` is a
123/// transport error from the body.
124async 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
147/// Classify a [`guardrail_core::GuardrailError::Upstream`] into a coarse
148/// error class for the `guardrail_upstream_errors_total` metric label.
149///
150/// With the `reqwest-errors` feature enabled (always on for
151/// `guardrail-proxy`), this inspects the structured `reqwest::Error` via
152/// `.is_timeout()` / `.is_connect()` rather than string-matching the
153/// `Display` output, which is more reliable across `reqwest`/`hyper`
154/// versions and locales.
155///
156/// # Examples
157///
158/// ```rust
159/// use guardrail_proxy::error::classify_upstream_error;
160/// use guardrail_core::GuardrailError;
161///
162/// let err = GuardrailError::Internal("unrelated".into());
163/// assert_eq!(classify_upstream_error(&err), "other");
164/// ```
165pub 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    /// A body that never ends. The old implementation collected the whole
206    /// body before checking its size, so it never returned (and a real
207    /// client could make the proxy buffer as much as it liked).
208    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        // Full<Bytes> reports its exact length as the size hint, like a
231        // request with Content-Length.
232        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        // A streamed body (no declared length) under the limit, in pieces.
243        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        // A local server that accepts the connection but never answers, so
259        // the only way the request can end is the client's timeout. No real
260        // network is involved (this previously targeted 10.255.255.1 and
261        // depended on nothing answering there).
262        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            // Hold the connection open without reading or writing.
267            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}