Skip to main content

shunt/
forwarder.rs

1use anyhow::{Context, Result};
2use axum::body::Body;
3use axum::http::{HeaderMap, HeaderName, HeaderValue, Response};
4use bytes::Bytes;
5use reqwest::Client;
6use std::str::FromStr;
7use std::time::Instant;
8use tracing::info;
9use uuid::Uuid;
10
11use crate::config::AccountConfig;
12
13/// Headers that must never be forwarded in either direction.
14const HOP_BY_HOP: &[&str] = &[
15    "connection",
16    "keep-alive",
17    "proxy-authenticate",
18    "proxy-authorization",
19    "te",
20    "trailers",
21    "transfer-encoding",
22    "upgrade",
23    "host",
24    "content-length",
25];
26
27/// Auth headers that the proxy manages — always stripped from client requests
28/// and replaced with the selected account's credential.
29const CLIENT_AUTH_HEADERS: &[&str] = &["authorization", "x-api-key"];
30
31fn is_hop_by_hop(name: &str) -> bool {
32    HOP_BY_HOP.contains(&name.to_ascii_lowercase().as_str())
33}
34
35fn is_client_auth(name: &str) -> bool {
36    CLIENT_AUTH_HEADERS.contains(&name.to_ascii_lowercase().as_str())
37}
38
39pub struct Forwarder {
40    client: Client,
41    base_url: String,
42}
43
44impl Forwarder {
45    pub fn new(base_url: impl Into<String>, timeout_secs: u64) -> Result<Self> {
46        let client = Client::builder()
47            .timeout(std::time::Duration::from_secs(timeout_secs))
48            .redirect(reqwest::redirect::Policy::none())
49            .build()
50            .context("Failed to build HTTP client")?;
51
52        Ok(Self { client, base_url: base_url.into() })
53    }
54
55    /// Forward a request to the upstream using the given account's OAuth credential.
56    ///
57    /// - Strips `Authorization` and `x-api-key` from the client request.
58    /// - Injects `Authorization: Bearer <token>` (live token, may differ from account.credential).
59    /// - Keeps the upstream TCP connection alive for streaming responses.
60    pub async fn forward(
61        &self,
62        method: &str,
63        path: &str,
64        body: Bytes,
65        client_headers: &HeaderMap,
66        account: &AccountConfig,
67        token: &str,
68    ) -> Result<Response<Body>> {
69        let request_id = &Uuid::new_v4().to_string()[..8];
70        let url = format!("{}{}", self.base_url, path);
71
72        let mut upstream_headers = reqwest::header::HeaderMap::new();
73
74        for (name, value) in client_headers.iter() {
75            let lower = name.as_str().to_ascii_lowercase();
76            if is_hop_by_hop(&lower) || is_client_auth(&lower) {
77                continue;
78            }
79            if let (Ok(n), Ok(v)) = (
80                reqwest::header::HeaderName::from_str(name.as_str()),
81                reqwest::header::HeaderValue::from_bytes(value.as_bytes()),
82            ) {
83                upstream_headers.insert(n, v);
84            }
85        }
86
87        // Inject provider-specific auth headers (Bearer token + any required protocol headers).
88        account.provider.inject_auth_headers(&mut upstream_headers, token)
89            .context("failed to inject auth headers")?;
90
91        let t0 = Instant::now();
92        let upstream_resp = self
93            .client
94            .request(
95                reqwest::Method::from_str(method).context("invalid method")?,
96                &url,
97            )
98            .headers(upstream_headers)
99            .body(body)
100            .send()
101            .await
102            .context("upstream request failed")?;
103
104        let latency_ms = t0.elapsed().as_millis();
105        let status = upstream_resp.status();
106
107        info!(
108            request_id = %request_id,
109            account = %account.name,
110            status = status.as_u16(),
111            latency_ms = %latency_ms,
112            path = %path,
113            "request forwarded"
114        );
115
116        let mut builder = Response::builder().status(status.as_u16());
117
118        for (name, value) in upstream_resp.headers().iter() {
119            if !is_hop_by_hop(name.as_str()) {
120                if let (Ok(n), Ok(v)) = (
121                    HeaderName::from_str(name.as_str()),
122                    HeaderValue::from_bytes(value.as_bytes()),
123                ) {
124                    builder = builder.header(n, v);
125                }
126            }
127        }
128
129        let body = Body::from_stream(upstream_resp.bytes_stream());
130        Ok(builder.body(body).expect("response builder invariant"))
131    }
132}