Skip to main content

respan_gateway/
network.rs

1//! `[network]`: how the gateway reaches providers and tool servers, through
2//! which proxy and trusting which certificates; and a provider's or tool
3//! server's own `proxy`.
4
5use std::path::Path;
6
7use respan_gateway_core::Fault;
8use respan_gateway_http_transport::Network;
9use serde::{Deserialize, Deserializer};
10
11use crate::compose::secret;
12use crate::config::{Config, Source};
13
14/// The variables a program reads its proxy from, and those that exempt
15/// hosts, each also in lower case.
16const PROXY_VARS: [&str; 3] = ["HTTPS_PROXY", "HTTP_PROXY", "ALL_PROXY"];
17const NO_PROXY_VAR: &str = "NO_PROXY";
18
19/// `[network]`.
20#[derive(Debug, Clone, Default, Deserialize)]
21#[serde(deny_unknown_fields)]
22pub struct NetworkConfig {
23    /// The proxy every outbound connection goes through: a URL such as
24    /// `http://proxy.corp:3128`, with `user:password@` if it asks, literal
25    /// or `env:NAME`; `false` for none. Unset: the environment's
26    /// (`HTTPS_PROXY`, `HTTP_PROXY`, `ALL_PROXY`, minus `NO_PROXY`).
27    pub proxy: Option<Proxy>,
28    /// Hosts reached without the proxy: a host, a domain from its leading
29    /// `.`, an IP address or a CIDR range, or `*`.
30    #[serde(default)]
31    pub no_proxy: Vec<String>,
32    /// A PEM file of certificate authorities trusted besides the system's,
33    /// such as a TLS-inspecting proxy's; relative to the config file.
34    pub ca: Option<std::path::PathBuf>,
35}
36
37/// A proxy setting: a URL, or none.
38#[derive(Clone, PartialEq, Eq)]
39pub enum Proxy {
40    Url(String),
41    Off,
42}
43
44// A proxy's URL may hold its password.
45impl std::fmt::Debug for Proxy {
46    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
47        match self {
48            Self::Url(_) => f.write_str("Url(..)"),
49            Self::Off => f.write_str("Off"),
50        }
51    }
52}
53
54impl<'de> Deserialize<'de> for Proxy {
55    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
56        #[derive(Deserialize)]
57        #[serde(untagged)]
58        enum Raw {
59            Url(String),
60            On(bool),
61        }
62        match Raw::deserialize(d)? {
63            Raw::Url(url) => Ok(Self::Url(url)),
64            Raw::On(false) => Ok(Self::Off),
65            Raw::On(true) => Err(serde::de::Error::custom(
66                "a proxy is a URL, or false for none",
67            )),
68        }
69    }
70}
71
72/// The network `config` says, for every provider and tool server without a
73/// `proxy` of its own.
74pub fn network(config: &Config) -> Result<Network, Fault> {
75    let n = &config.network;
76    let mut network = Network::default();
77    if let Some(ca) = &n.ca {
78        let path = match config.source() {
79            Source::File(file) => file.parent().unwrap_or(Path::new("")).join(ca),
80            _ => ca.clone(),
81        };
82        let shown = path.display();
83        let pem = std::fs::read(&path)
84            .map_err(|e| Fault::config(format!("network: ca: {shown}: {e}")))?;
85        network = network
86            .trust_pem(&pem)
87            .map_err(|e| Fault::config(format!("network: ca: {shown}: {}", e.message())))?;
88    }
89    if n.proxy.is_none() && !n.no_proxy.is_empty() {
90        return Err(Fault::config(
91            "network: no_proxy is for a `proxy`; the environment's takes NO_PROXY",
92        ));
93    }
94    with_proxy("network", network, n.proxy.as_ref(), &n.no_proxy)
95}
96
97/// `base`, the config's, through `proxy` if it names one: a provider's or
98/// tool server's own, `owner`'s.
99pub fn of(
100    owner: &str,
101    base: &Network,
102    config: &NetworkConfig,
103    proxy: Option<&Proxy>,
104) -> Result<Network, Fault> {
105    match proxy {
106        None => Ok(base.clone()),
107        Some(proxy) => with_proxy(owner, base.clone(), Some(proxy), &config.no_proxy),
108    }
109}
110
111fn with_proxy(
112    owner: &str,
113    network: Network,
114    proxy: Option<&Proxy>,
115    no_proxy: &[String],
116) -> Result<Network, Fault> {
117    match proxy {
118        None => Ok(network),
119        Some(Proxy::Off) => Ok(network.direct()),
120        Some(Proxy::Url(url)) => {
121            let url = secret(&format!("{owner}: proxy"), url)?;
122            (network.proxy(&url, no_proxy))
123                .map_err(|e| Fault::config(format!("{owner}: proxy: {}", e.message())))
124        }
125    }
126}
127
128/// The proxy variables a tool server's program is given, which gets nothing
129/// of the gateway's environment but `PATH`: the config's proxy, `proxy` if
130/// its own, as `HTTPS_PROXY` and the rest; none for `false`; and, if neither
131/// says, the gateway's own.
132pub fn child_env(
133    owner: &str,
134    config: &NetworkConfig,
135    proxy: Option<&Proxy>,
136) -> Result<Vec<(String, String)>, Fault> {
137    let both = |name: &str| [name.to_owned(), name.to_lowercase()];
138    match proxy.or(config.proxy.as_ref()) {
139        Some(Proxy::Off) => Ok(Vec::new()),
140        Some(Proxy::Url(url)) => {
141            let url = secret(&format!("{owner}: proxy"), url)?;
142            let mut env: Vec<(String, String)> = PROXY_VARS
143                .iter()
144                .flat_map(|v| both(v))
145                .map(|v| (v, url.clone()))
146                .collect();
147            if !config.no_proxy.is_empty() {
148                let hosts = config.no_proxy.join(",");
149                env.extend(both(NO_PROXY_VAR).map(|v| (v, hosts.clone())));
150            }
151            Ok(env)
152        }
153        None => {
154            let vars = PROXY_VARS
155                .iter()
156                .chain([&NO_PROXY_VAR])
157                .flat_map(|v| both(v));
158            let set = vars.filter_map(|v| std::env::var(&v).ok().map(|value| (v, value)));
159            Ok(set.collect())
160        }
161    }
162}
163
164#[cfg(test)]
165mod tests {
166    use super::*;
167
168    fn parsed(text: &str) -> NetworkConfig {
169        toml::from_str(text).unwrap_or_else(|e| panic!("{e}"))
170    }
171
172    #[test]
173    fn a_proxy_is_a_url_or_false() {
174        let n = parsed("proxy = \"http://proxy:3128\"");
175        assert_eq!(n.proxy, Some(Proxy::Url("http://proxy:3128".into())));
176        assert_eq!(parsed("proxy = false").proxy, Some(Proxy::Off));
177        assert!(toml::from_str::<NetworkConfig>("proxy = true").is_err());
178    }
179
180    #[test]
181    fn no_proxy_needs_a_proxy() {
182        let config = Config {
183            network: parsed("no_proxy = [\"localhost\"]"),
184            ..Config::default()
185        };
186        assert!(network(&config).is_err());
187    }
188
189    #[test]
190    fn a_bad_proxy_is_named_without_its_url() {
191        let config = Config {
192            network: parsed("proxy = \"not a url\""),
193            ..Config::default()
194        };
195        let refused = network(&config)
196            .map(|_| ())
197            .map_err(|f| f.message().to_owned());
198        let message = refused.err().unwrap_or_default();
199        assert!(message.starts_with("network: proxy: "), "{message}");
200        assert!(!message.contains("not a url"));
201    }
202
203    #[test]
204    fn a_program_gets_the_proxy_it_is_given() {
205        let n = parsed("proxy = \"http://p:1\"\nno_proxy = [\"a\", \"b\"]");
206        let env = |proxy: Option<&Proxy>| child_env("t", &n, proxy).unwrap_or_default();
207        let given = env(None);
208        assert!(given.contains(&("HTTPS_PROXY".into(), "http://p:1".into())));
209        assert!(given.contains(&("no_proxy".into(), "a,b".into())));
210        let own = env(Some(&Proxy::Url("http://q:2".into())));
211        assert!(own.contains(&("https_proxy".into(), "http://q:2".into())));
212        assert!(env(Some(&Proxy::Off)).is_empty());
213    }
214}