Skip to main content

yaiko_core/
proxy.rs

1//! Safe reverse-proxy request policy primitives.
2#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3pub enum ProxyMethod {
4    Get,
5    Post,
6    Put,
7    Patch,
8    Delete,
9}
10#[derive(Debug, Clone, PartialEq, Eq)]
11pub enum ProxyError {
12    InvalidUpstream,
13    MethodNotAllowed,
14    BodyTooLarge,
15    InvalidHeader,
16}
17#[derive(Debug, Clone, PartialEq, Eq)]
18pub struct ProxyRequest {
19    pub method: ProxyMethod,
20    pub upstream: String,
21    pub path: String,
22    pub headers: Vec<(String, String)>,
23    pub body: Vec<u8>,
24}
25#[derive(Debug, Clone)]
26pub struct ProxyPolicy {
27    pub upstream: String,
28    pub max_body: usize,
29    allowed: Vec<ProxyMethod>,
30}
31impl ProxyPolicy {
32    pub fn new(upstream: impl Into<String>, max_body: usize) -> Result<Self, ProxyError> {
33        let upstream = upstream.into();
34        if !upstream.starts_with("https://")
35            || upstream
36                .chars()
37                .any(|c| c.is_control() || c.is_whitespace())
38        {
39            return Err(ProxyError::InvalidUpstream);
40        }
41        Ok(Self {
42            upstream,
43            max_body,
44            allowed: vec![ProxyMethod::Get],
45        })
46    }
47    pub fn allow(mut self, method: ProxyMethod) -> Self {
48        if !self.allowed.contains(&method) {
49            self.allowed.push(method)
50        }
51        self
52    }
53    pub fn build(
54        &self,
55        method: ProxyMethod,
56        path: impl Into<String>,
57        headers: impl IntoIterator<Item = (String, String)>,
58        body: impl Into<Vec<u8>>,
59    ) -> Result<ProxyRequest, ProxyError> {
60        if !self.allowed.contains(&method) {
61            return Err(ProxyError::MethodNotAllowed);
62        }
63        let path = path.into();
64        if !path.starts_with('/')
65            || path.contains("..")
66            || path.chars().any(|c| c.is_control() || c.is_whitespace())
67        {
68            return Err(ProxyError::InvalidUpstream);
69        }
70        let body = body.into();
71        if body.len() > self.max_body {
72            return Err(ProxyError::BodyTooLarge);
73        }
74        let headers = headers
75            .into_iter()
76            .filter_map(|(k, v)| {
77                let lk = k.to_ascii_lowercase();
78                if matches!(
79                    lk.as_str(),
80                    "host" | "connection" | "content-length" | "x-forwarded-for"
81                ) || k.is_empty()
82                    || k.chars().any(|c| c.is_control() || c.is_whitespace())
83                    || v.chars().any(|c| c.is_control())
84                {
85                    None
86                } else {
87                    Some((k, v))
88                }
89            })
90            .collect();
91        Ok(ProxyRequest {
92            method,
93            upstream: self.upstream.clone(),
94            path,
95            headers,
96            body,
97        })
98    }
99    pub fn describe(&self) -> String {
100        format!("{} (max_body={})", self.upstream, self.max_body)
101    }
102}
103#[cfg(test)]
104mod tests {
105    use super::*;
106    #[test]
107    fn builds_safe_forward_request() {
108        let p = ProxyPolicy::new("https://api.example.com", 8)
109            .unwrap()
110            .allow(ProxyMethod::Post);
111        let r = p
112            .build(
113                ProxyMethod::Post,
114                "/v1/media",
115                [
116                    ("authorization".into(), "Bearer x".into()),
117                    ("host".into(), "bad".into()),
118                ],
119                b"x".to_vec(),
120            )
121            .unwrap();
122        assert_eq!(r.headers.len(), 1);
123        assert_eq!(p.describe(), "https://api.example.com (max_body=8)")
124    }
125    #[test]
126    fn rejects_unsafe_upstream_method_path_and_body() {
127        assert!(ProxyPolicy::new("http://bad", 1).is_err());
128        let p = ProxyPolicy::new("https://api.example.com", 1).unwrap();
129        assert!(p
130            .build(ProxyMethod::Post, "/x", Vec::new(), Vec::new())
131            .is_err());
132        assert!(p
133            .build(ProxyMethod::Get, "/../x", Vec::new(), Vec::new())
134            .is_err());
135        assert!(p
136            .build(ProxyMethod::Get, "/x", Vec::new(), b"xx".to_vec())
137            .is_err())
138    }
139}