1use bytes::Bytes;
9use guardrail_core::{request::GuardrailRequest, GuardrailError};
10use reqwest::{Client, Response};
11use std::time::Duration;
12
13pub 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
73pub async fn read_body(response: Response) -> Result<Bytes, GuardrailError> {
82 response.bytes().await.map_err(GuardrailError::from)
83}
84
85pub 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
101pub const STRIPPED_REQUEST_HEADERS: &[&str] = &[
113 "host",
114 "content-length",
115 "accept-encoding",
116 "x-guardrail-key",
117];
118
119pub const STRIPPED_RESPONSE_HEADERS: &[&str] = &["content-length"];
124
125pub 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 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 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}