Skip to main content

guardrail_proxy/
forward.rs

1//! Upstream request forwarding.
2//!
3//! Once the pipeline allows (or redacts) a request, [`forward_request`] sends
4//! it to the configured upstream LLM API and streams the response back to the
5//! client unmodified (responses are never inspected by the pipeline — only
6//! requests are).
7
8use bytes::Bytes;
9use guardrail_core::{request::GuardrailRequest, GuardrailError};
10use reqwest::{Client, Response};
11use std::time::Duration;
12
13/// Forward a (possibly redacted) request to the upstream LLM API.
14///
15/// # Arguments
16///
17/// * `client` — a shared [`reqwest::Client`] (connection-pooled).
18/// * `upstream_url` — base URL of the upstream, e.g. `https://api.openai.com`.
19/// * `path` — the request path, e.g. `/v1/chat/completions`.
20/// * `req` — the (possibly redacted) normalized request.
21/// * `headers` — headers from the original client request to forward
22///   (e.g. `Authorization`), with `Host` and `Content-Length` stripped by
23///   the caller.
24/// * `timeout` — per-request timeout.
25///
26/// # Errors
27///
28/// Returns [`GuardrailError::Upstream`] if the request fails to send or the
29/// connection is refused/times out. Returns [`GuardrailError::Serialization`]
30/// if `req` cannot be serialized back to JSON.
31///
32/// # Examples
33///
34/// ```rust,no_run
35/// use guardrail_proxy::forward::forward_request;
36/// use guardrail_core::test_helpers::clean_request;
37/// use reqwest::Client;
38/// use std::time::Duration;
39///
40/// # tokio_test::block_on(async {
41/// let client = Client::new();
42/// let req = clean_request();
43/// let resp = forward_request(
44///     &client,
45///     "https://api.openai.com",
46///     "/v1/chat/completions",
47///     &req,
48///     vec![("authorization".to_string(), "Bearer sk-...".to_string())],
49///     Duration::from_secs(60),
50/// ).await;
51/// # });
52/// ```
53pub async fn forward_request(
54    client: &Client,
55    upstream_url: &str,
56    path: &str,
57    req: &GuardrailRequest,
58    headers: Vec<(String, String)>,
59    timeout: Duration,
60) -> Result<Response, GuardrailError> {
61    let body = crate::translate::serialize_request(req)?;
62    let url = format!("{}{}", upstream_url.trim_end_matches('/'), path);
63
64    let mut builder = client.post(&url).json(&body).timeout(timeout);
65
66    for (key, value) in headers {
67        builder = builder.header(key, value);
68    }
69
70    builder.send().await.map_err(GuardrailError::from)
71}
72
73/// Read the full response body as bytes.
74///
75/// Used for non-streaming responses where the entire body is buffered before
76/// returning to the client.
77///
78/// # Errors
79///
80/// Returns [`GuardrailError::Upstream`] if reading the body fails.
81pub async fn read_body(response: Response) -> Result<Bytes, GuardrailError> {
82    response.bytes().await.map_err(GuardrailError::from)
83}
84
85/// Hop-by-hop headers (RFC 9110, section 7.6.1). They describe one connection,
86/// not the message, so a proxy must not pass them on in either direction.
87/// Any header named in a `Connection` header is hop-by-hop too; see
88/// [`forwardable_headers`].
89pub const HOP_BY_HOP_HEADERS: &[&str] = &[
90    "connection",
91    "keep-alive",
92    "proxy-authenticate",
93    "proxy-authorization",
94    "proxy-connection",
95    "te",
96    "trailer",
97    "transfer-encoding",
98    "upgrade",
99];
100
101/// Headers stripped from the **request** before forwarding upstream, in
102/// addition to [`HOP_BY_HOP_HEADERS`].
103///
104/// - `host` is recomputed for the upstream's own hostname.
105/// - `content-length` is recomputed because redaction can change the body.
106/// - `accept-encoding` is left to the proxy's HTTP client, which only asks
107///   for encodings it can decode. Passing the client's value on would let
108///   the upstream compress the body with an encoding the proxy can't read,
109///   which would hide its text from response redaction.
110/// - `x-guardrail-key` is guardrail-rs's own caller secret and must never
111///   reach the upstream provider.
112pub const STRIPPED_REQUEST_HEADERS: &[&str] = &[
113    "host",
114    "content-length",
115    "accept-encoding",
116    "x-guardrail-key",
117];
118
119/// Headers stripped from the upstream **response** before it goes back to
120/// the client, in addition to [`HOP_BY_HOP_HEADERS`]. `content-length` is
121/// recomputed by the proxy's HTTP server, since redaction can change the
122/// body.
123pub const STRIPPED_RESPONSE_HEADERS: &[&str] = &["content-length"];
124
125/// The headers of `headers` that may be forwarded, as lowercase name/value
126/// pairs: everything except [`HOP_BY_HOP_HEADERS`], headers named in a
127/// `Connection` header, `extra_stripped`, and values that aren't visible
128/// ASCII.
129///
130/// # Examples
131///
132/// ```rust
133/// use guardrail_proxy::forward::{forwardable_headers, STRIPPED_REQUEST_HEADERS};
134/// use reqwest::header::{HeaderMap, HeaderValue};
135///
136/// let mut headers = HeaderMap::new();
137/// headers.insert("authorization", HeaderValue::from_static("Bearer sk-1"));
138/// headers.insert("connection", HeaderValue::from_static("x-trace"));
139/// headers.insert("x-trace", HeaderValue::from_static("1"));
140/// headers.insert("accept-encoding", HeaderValue::from_static("gzip"));
141///
142/// let out = forwardable_headers(&headers, STRIPPED_REQUEST_HEADERS);
143/// assert_eq!(out, vec![("authorization".to_string(), "Bearer sk-1".to_string())]);
144/// ```
145pub fn forwardable_headers(
146    headers: &reqwest::header::HeaderMap,
147    extra_stripped: &[&str],
148) -> Vec<(String, String)> {
149    let connection_listed: Vec<String> = headers
150        .get_all("connection")
151        .iter()
152        .filter_map(|v| v.to_str().ok())
153        .flat_map(|v| v.split(','))
154        .map(|name| name.trim().to_ascii_lowercase())
155        .filter(|name| !name.is_empty())
156        .collect();
157
158    headers
159        .iter()
160        .filter_map(|(name, value)| {
161            // `HeaderName`s are always lowercase.
162            let name = name.as_str();
163            let stripped = HOP_BY_HOP_HEADERS.contains(&name)
164                || extra_stripped.contains(&name)
165                || connection_listed.iter().any(|listed| listed == name);
166            if stripped {
167                return None;
168            }
169            Some((name.to_string(), value.to_str().ok()?.to_string()))
170        })
171        .collect()
172}
173
174#[cfg(test)]
175mod tests {
176    use super::*;
177    use guardrail_core::test_helpers::clean_request;
178    use wiremock::matchers::{method, path};
179    use wiremock::{Mock, MockServer, ResponseTemplate};
180
181    #[tokio::test]
182    async fn test_forward_request_success() {
183        let mock_server = MockServer::start().await;
184
185        Mock::given(method("POST"))
186            .and(path("/v1/chat/completions"))
187            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
188                "id": "chatcmpl-123",
189                "choices": []
190            })))
191            .mount(&mock_server)
192            .await;
193
194        let client = Client::new();
195        let req = clean_request();
196
197        let resp = forward_request(
198            &client,
199            &mock_server.uri(),
200            "/v1/chat/completions",
201            &req,
202            vec![("authorization".to_string(), "Bearer test-key".to_string())],
203            Duration::from_secs(5),
204        )
205        .await
206        .unwrap();
207
208        assert_eq!(resp.status(), 200);
209        let body = read_body(resp).await.unwrap();
210        let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
211        assert_eq!(json["id"], "chatcmpl-123");
212    }
213
214    #[tokio::test]
215    async fn test_forward_request_connection_refused() {
216        let client = Client::new();
217        let req = clean_request();
218
219        // Port 1 is reserved and should refuse connections immediately.
220        let result = forward_request(
221            &client,
222            "http://127.0.0.1:1",
223            "/v1/chat/completions",
224            &req,
225            vec![],
226            Duration::from_secs(1),
227        )
228        .await;
229
230        assert!(result.is_err());
231        assert!(matches!(result, Err(GuardrailError::Upstream(_))));
232    }
233
234    #[test]
235    fn test_stripped_headers_lists() {
236        assert!(STRIPPED_REQUEST_HEADERS.contains(&"host"));
237        assert!(STRIPPED_REQUEST_HEADERS.contains(&"content-length"));
238        assert!(STRIPPED_REQUEST_HEADERS.contains(&"accept-encoding"));
239        assert!(STRIPPED_RESPONSE_HEADERS.contains(&"content-length"));
240        assert!(HOP_BY_HOP_HEADERS.contains(&"transfer-encoding"));
241    }
242
243    #[test]
244    fn test_forwardable_headers_strips_hop_by_hop_and_connection_listed() {
245        use reqwest::header::{HeaderMap, HeaderValue};
246
247        let mut headers = HeaderMap::new();
248        for (name, value) in [
249            ("authorization", "Bearer sk-1"),
250            ("content-type", "application/json"),
251            ("connection", "keep-alive, X-Hop"),
252            ("keep-alive", "timeout=5"),
253            ("te", "trailers"),
254            ("trailer", "x-checksum"),
255            ("upgrade", "h2c"),
256            ("proxy-authorization", "Basic abc"),
257            ("proxy-connection", "keep-alive"),
258            ("transfer-encoding", "chunked"),
259            ("x-hop", "1"),
260            ("accept-encoding", "gzip, br"),
261            ("host", "proxy.local"),
262            ("x-guardrail-key", "secret"),
263        ] {
264            headers.insert(name, HeaderValue::from_static(value));
265        }
266
267        let mut out = forwardable_headers(&headers, STRIPPED_REQUEST_HEADERS);
268        out.sort();
269        assert_eq!(
270            out,
271            vec![
272                ("authorization".to_string(), "Bearer sk-1".to_string()),
273                ("content-type".to_string(), "application/json".to_string()),
274            ]
275        );
276    }
277
278    #[test]
279    fn test_forwardable_headers_response_side_keeps_content_encoding() {
280        use reqwest::header::{HeaderMap, HeaderValue};
281
282        let mut headers = HeaderMap::new();
283        headers.insert("content-encoding", HeaderValue::from_static("gzip"));
284        headers.insert("content-length", HeaderValue::from_static("42"));
285        headers.insert("transfer-encoding", HeaderValue::from_static("chunked"));
286
287        let out = forwardable_headers(&headers, STRIPPED_RESPONSE_HEADERS);
288        assert_eq!(
289            out,
290            vec![("content-encoding".to_string(), "gzip".to_string())]
291        );
292    }
293}