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