1use bytes::Bytes;
7use guardrail_core::GuardrailError;
8use reqwest::{Client, Response};
9use std::time::Duration;
10
11pub 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 if key != "content-type" {
66 builder = builder.header(key, value);
67 }
68 }
69
70 builder.send().await.map_err(GuardrailError::from)
71}
72
73pub 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
100pub async fn read_body(response: Response) -> Result<Bytes, GuardrailError> {
109 response.bytes().await.map_err(GuardrailError::from)
110}
111
112pub 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
128pub const STRIPPED_REQUEST_HEADERS: &[&str] = &[
140 "host",
141 "content-length",
142 "accept-encoding",
143 "x-guardrail-key",
144];
145
146pub const STRIPPED_RESPONSE_HEADERS: &[&str] = &["content-length"];
151
152pub 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 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 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}