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/// Unlike checking `Content-Length` alone (which a client can omit, lie
96/// about, or stream past via chunked transfer-encoding), this collects the
97/// actual bytes and checks the real total — closing the gap a
98/// length-header-only check would leave open.
99///
100/// # Examples
101///
102/// ```rust,no_run
103/// use guardrail_proxy::error::read_limited_body;
104/// # async fn example(body: hyper::body::Incoming) {
105/// match read_limited_body(body, 1024).await {
106///     Ok(bytes) => { /* use bytes */ }
107///     Err(err) => { let _ = err; /* too large or I/O error */ }
108/// }
109/// # }
110/// ```
111pub 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
121/// Classify a [`guardrail_core::GuardrailError::Upstream`] into a coarse
122/// error class for the `guardrail_upstream_errors_total` metric label.
123///
124/// With the `reqwest-errors` feature enabled (always on for
125/// `guardrail-proxy`), this inspects the structured `reqwest::Error` via
126/// `.is_timeout()` / `.is_connect()` rather than string-matching the
127/// `Display` output, which is more reliable across `reqwest`/`hyper`
128/// versions and locales.
129///
130/// # Examples
131///
132/// ```rust
133/// use guardrail_proxy::error::classify_upstream_error;
134/// use guardrail_core::GuardrailError;
135///
136/// let err = GuardrailError::Internal("unrelated".into());
137/// assert_eq!(classify_upstream_error(&err), "other");
138/// ```
139pub 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}