Skip to main content

proxy_watch/
env.rs

1//! The environment variable snapshot type.
2
3use std::collections::HashMap;
4use std::fmt;
5use std::time::SystemTime;
6
7use crate::bypass::BypassRules;
8use crate::config::{ProxyConfig, ProxyConfigSource};
9use crate::diagnostic::{RejectedValue, RejectionKind, RejectionSource};
10use crate::endpoint::{ProxyEndpoint, ProxyEntry, Scheme};
11use crate::error::Error;
12use crate::mode::ProxyMode;
13use crate::parse;
14
15/// The variable whose presence *with a method in it* marks a CGI environment (see
16/// [`Error::CgiHttpProxy`]).
17pub const CGI_MARKER_VAR: &str = "REQUEST_METHOD";
18
19// Lowercase variable name for each scheme, in the order they are looked up.
20const SCHEME_VARS: [(Scheme, &str); 4] = [
21    (Scheme::Http, "http_proxy"),
22    (Scheme::Https, "https_proxy"),
23    (Scheme::Ftp, "ftp_proxy"),
24    (Scheme::All, "all_proxy"),
25];
26
27const NO_PROXY_VAR: &str = "no_proxy";
28
29/// Env snapshot of `*_proxy` / `no_proxy` (not a [`Stream`](crate::Stream);
30/// [`ProxyWatcher`](crate::ProxyWatcher) does not merge these in, except where an OS
31/// setting names them, which KDE's `ProxyType=4` does).
32///
33/// Lowercase beats uppercase; empty value → [`ProxyEntry::Disabled`]; port explicit, else
34/// the `scheme://` default, else 80 (so `all_proxy=socks5://h` is 1080, `http_proxy=h` is
35/// 80), the rule [`ProxyEndpoint::parse`] states. On Windows only, any other letter case
36/// the variable was set in (`Http_Proxy`) is read too, after both conventional spellings.
37/// `no_proxy` via [`parse::no_proxy`]. Bad `*_proxy` → [`rejected`](Self::rejected). A
38/// **non-empty** `REQUEST_METHOD` + `http_proxy` → [`Error::CgiHttpProxy`]. Merge with a
39/// watcher is caller-defined precedence.
40#[derive(Clone)]
41pub struct ProxyEnv {
42    per_scheme: HashMap<Scheme, ProxyEntry>,
43    bypass: BypassRules,
44    rejected: Vec<RejectedValue>,
45    captured_at: SystemTime,
46}
47
48impl ProxyEnv {
49    /// Read the snapshot from the current process environment.
50    ///
51    /// [`std::env::vars`] panics on a variable whose name or value is not valid Unicode.
52    /// This uses [`std::env::vars_os`] so an unrelated variable cannot cause the snapshot
53    /// to panic. A non-Unicode name cannot match a variable read here and is dropped. A
54    /// non-Unicode value is retained in [`rejected`](Self::rejected) instead of being
55    /// treated as unset.
56    ///
57    /// # Errors
58    ///
59    /// [`Error::CgiHttpProxy`] in a CGI environment carrying an `http_proxy`
60    /// variable. A malformed value is never one of these, but the two kinds are
61    /// recorded apart: a dropped `*_proxy` endpoint lands in
62    /// [`rejected`](Self::rejected), a dropped `no_proxy` entry in
63    /// [`bypass()`](Self::bypass)`.rejected`. Reading only the first and finding it
64    /// empty says nothing about the second.
65    pub fn from_env() -> Result<Self, Error> {
66        Self::from_vars(std::env::vars_os().filter_map(readable_var))
67    }
68
69    /// Explicit map for tests (avoids mutating the process-global env). A name given twice
70    /// keeps its first value, as `getenv` does.
71    ///
72    /// ```
73    /// # use proxy_watch::{ProxyEnv, Scheme};
74    /// let env = ProxyEnv::from_vars([
75    ///     ("HTTP_PROXY", "http://upper:8080"),
76    ///     ("http_proxy", "http://lower:8080"),
77    ///     ("no_proxy", "*.internal"),
78    /// ])
79    /// .unwrap();
80    /// // Lowercase wins.
81    /// let endpoint = env.endpoint_for(Scheme::Http).unwrap();
82    /// assert_eq!(endpoint.host.to_string(), "lower");
83    /// assert!(env.bypass().matches_authority("api.internal"));
84    /// ```
85    ///
86    /// # Errors
87    ///
88    /// [`Error::CgiHttpProxy`] when a non-empty `REQUEST_METHOD` and an `http_proxy` are
89    /// both present. Malformed values are recorded instead of returned; see
90    /// [`from_env`](Self::from_env) for which of the two lists each kind reaches.
91    pub fn from_vars<I, K, V>(vars: I) -> Result<Self, Error>
92    where
93        I: IntoIterator<Item = (K, V)>,
94        K: AsRef<str>,
95        V: AsRef<str>,
96    {
97        // A name given twice keeps its first value, as `getenv` answers (and with it
98        // `std::env::var_os`, curl, Python's `os.environ` and Node's `process.env`), so
99        // this read agrees with the process's other HTTP stacks on a duplicated `environ`.
100        let mut map: HashMap<String, String> = HashMap::new();
101        for (k, v) in vars {
102            map.entry(k.as_ref().to_owned())
103                .or_insert_with(|| v.as_ref().to_owned());
104        }
105
106        // CGI marker: exact + Windows any-case, and it has to carry a method. Presence
107        // alone is not the test; Go reads it as `os.Getenv("REQUEST_METHOD") != ""`
108        // (`httpproxy.FromEnvironment`), and RFC 3875 §4.1.12 has no empty production for
109        // it (`method = "GET" | "POST" | "HEAD" | extension-method`), so no conforming
110        // CGI server ever sets it empty. Refuse any-case `http_proxy` (`min` for a stable
111        // name).
112        let in_cgi = map
113            .get(CGI_MARKER_VAR)
114            .or_else(|| any_case_on_windows(&map, CGI_MARKER_VAR).map(|(_, value)| value))
115            .is_some_and(|method| !method.is_empty());
116        if in_cgi
117            && let Some(variable) = map
118                .keys()
119                .filter(|k| k.eq_ignore_ascii_case(SCHEME_VARS[0].1))
120                .min()
121        {
122            return Err(Error::CgiHttpProxy {
123                variable: variable.clone(),
124            });
125        }
126
127        let mut per_scheme = HashMap::new();
128        let mut rejected = Vec::new();
129        for (scheme, name) in SCHEME_VARS {
130            let Some(value) = lookup(&map, name) else {
131                continue;
132            };
133            let trimmed = value.trim();
134            if trimmed.is_empty() {
135                per_scheme.insert(scheme, ProxyEntry::Disabled);
136                continue;
137            }
138            match ProxyEndpoint::parse(trimmed, 80) {
139                Ok(endpoint) => {
140                    per_scheme.insert(scheme, ProxyEntry::Use(endpoint));
141                }
142                // The `WARN` compiles to nothing without the `tracing` feature, which is
143                // what leaves `err` unused there; the `rejected` entry below is what
144                // carries the drop either way.
145                #[cfg_attr(not(feature = "tracing"), allow(unused_variables))]
146                Err(err) => {
147                    crate::trace::warning!(
148                        variable = name,
149                        error = %crate::trace::SafeError(&err),
150                        "skipping an unparseable *_proxy value"
151                    );
152                    rejected.push(
153                        RejectedValue::new(
154                            RejectionKind::InvalidProxyEndpoint,
155                            RejectionSource::EnvironmentVariable(name.to_owned()),
156                            trimmed,
157                        )
158                        .for_scheme(Some(scheme)),
159                    );
160                }
161            }
162        }
163
164        let bypass = match lookup(&map, NO_PROXY_VAR) {
165            Some(value) => parse::no_proxy(value),
166            None => BypassRules::new(),
167        };
168
169        Ok(Self {
170            per_scheme,
171            bypass,
172            rejected,
173            captured_at: SystemTime::now(),
174        })
175    }
176
177    /// The parsed per-scheme entries. Never [`Unusable`](ProxyEntry::Unusable): a drop stays
178    /// on [`rejected`](Self::rejected) alone until [`to_mode`](Self::to_mode) files it into
179    /// the [`ProxyMode`]'s map, so a snapshot and the mode built from it differ here.
180    #[must_use]
181    pub fn per_scheme(&self) -> &HashMap<Scheme, ProxyEntry> {
182        &self.per_scheme
183    }
184
185    /// The parsed `no_proxy` rules.
186    #[must_use]
187    pub fn bypass(&self) -> &BypassRules {
188        &self.bypass
189    }
190
191    /// Redacted `*_proxy` values [`ProxyEndpoint::parse`] rejected (fail-open drop,
192    /// not whole-snapshot failure). Threaded into [`ProxyMode`] via [`to_mode`](Self::to_mode).
193    /// Not the `no_proxy` drops: those are exclusions rather than endpoints and stay on
194    /// [`bypass()`](Self::bypass)`.rejected`. [`to_mode`](Self::to_mode) carries them
195    /// across inside the [`BypassRules`], but only on the branch that returns a
196    /// [`Manual`](ProxyMode::Manual): a snapshot holding nothing but a `no_proxy` is
197    /// [`Direct`](ProxyMode::Direct), and an exclusion list with no proxy to be excluded
198    /// from does not outlive the conversion.
199    #[must_use]
200    pub fn rejected(&self) -> &[RejectedValue] {
201        &self.rejected
202    }
203
204    /// When the snapshot was taken. Excluded from equality comparisons.
205    #[must_use]
206    pub fn captured_at(&self) -> SystemTime {
207        self.captured_at
208    }
209
210    /// No `*_proxy` set (malformed-but-present still counts as set via [`rejected`](Self::rejected)).
211    #[must_use]
212    pub fn is_empty(&self) -> bool {
213        self.per_scheme.is_empty() && self.rejected.is_empty()
214    }
215
216    /// Whether these variables specify a configuration, as opposed to only mentioning one.
217    ///
218    /// This neither implies [`is_empty`](Self::is_empty) nor follows from it. `is_empty`
219    /// checks whether any scheme variable is set, including malformed values and ignoring
220    /// `no_proxy`; `is_configured` ignores malformed values and includes `no_proxy`:
221    ///
222    /// | environment | `is_empty` | `is_configured` |
223    /// | --- | --- | --- |
224    /// | nothing set | `true` | `false` |
225    /// | `http_proxy=http://p:8080` | `false` | `true` |
226    /// | `http_proxy=` (a deliberate direct for http) | `false` | `true` |
227    /// | `no_proxy=.corp.example` alone | `true` | `true` |
228    /// | every scheme variable malformed | `false` | `false` |
229    ///
230    /// The treatment of `no_proxy` alone and malformed scheme variables follows Chromium's
231    /// `net/proxy_resolution/proxy_config_service_linux.cc`. A `no_proxy` on its own is a
232    /// configuration there: "having no rules specified only means the user explicitly asks
233    /// for direct connections". A value that fails to parse is logged and treated as if the
234    /// variable were unset. A malformed value is retained in [`rejected`](Self::rejected)
235    /// as a diagnostic; treating it as an instruction would let a typo in `http_proxy` mask
236    /// a working OS proxy.
237    ///
238    /// [`ProxyConfig::with_env`](crate::ProxyConfig::with_env) is what acts on the
239    /// distinction. [`to_mode`](Self::to_mode) does not: a `no_proxy` with no proxy to
240    /// exclude from is still [`Direct`](ProxyMode::Direct), which is the same answer
241    /// Chromium's config produces once it has no proxy servers in it.
242    #[must_use]
243    pub fn is_configured(&self) -> bool {
244        !self.per_scheme.is_empty() || !self.bypass.is_empty()
245    }
246
247    /// The endpoint for `scheme`, under the same [`Scheme::All`] fallback as
248    /// [`ProxyMode::entry_for`](crate::ProxyMode::entry_for): `All` itself has none, and a
249    /// [`Disabled`](ProxyEntry::Disabled) entry answers `None` instead of falling through.
250    #[must_use]
251    pub fn endpoint_for(&self, scheme: Scheme) -> Option<&ProxyEndpoint> {
252        // Written the same way as [`ProxyMode::entry_for`], which is what the doc above
253        // claims, and for the `All` case for the reason given there. `entry_for`'s one
254        // further rule (step over a drop and let a later slot answer) has nothing to act on
255        // in this map, which never holds one; the two stay the same lookup as long as that
256        // holds.
257        self.per_scheme
258            .get(&scheme)
259            .or_else(|| self.per_scheme.get(&Scheme::All))?
260            .endpoint()
261    }
262
263    /// Into [`ProxyMode`]: empty → [`Direct`](ProxyMode::Direct); else Manual (keeping
264    /// [`rejected`](Self::rejected) even when every scheme value failed to parse).
265    #[must_use]
266    pub fn to_mode(&self) -> ProxyMode {
267        // `is_empty` rather than its expression again: "empty" here is that method's
268        // question, and two copies of it can only ever drift apart.
269        if self.is_empty() {
270            ProxyMode::Direct
271        } else {
272            ProxyMode::manual(self.per_scheme.clone(), self.bypass.clone())
273                .with_rejected(self.rejected.clone())
274        }
275    }
276
277    /// Convert the snapshot into a [`ProxyConfig`] attributed to
278    /// [`ProxyConfigSource::Env`], carrying this snapshot's
279    /// [`captured_at`](Self::captured_at) rather than the time of the conversion.
280    #[must_use]
281    pub fn to_config(&self) -> ProxyConfig {
282        let mut config = ProxyConfig::from_source(ProxyConfigSource::Env, self.to_mode());
283        // `from_source` stamps now, which is the wrong instant: the variables were read when
284        // this snapshot was taken. A snapshot held and converted once per request would
285        // otherwise hand back a `ProxyConfig` claiming to be fresh every time.
286        config.captured_at = self.captured_at;
287        config
288    }
289}
290
291// Not a derive, only so that `per_scheme` prints in a fixed order: a `HashMap` seeds its
292// iteration order per instance, so a derive would render the same snapshot differently on
293// each run. [`ProxyMode`]'s own `Debug` says the rest.
294impl fmt::Debug for ProxyEnv {
295    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
296        f.debug_struct("ProxyEnv")
297            .field(
298                "per_scheme",
299                &self
300                    .per_scheme
301                    .iter()
302                    .collect::<std::collections::BTreeMap<_, _>>(),
303            )
304            .field("bypass", &self.bypass)
305            .field("rejected", &self.rejected)
306            .field("captured_at", &self.captured_at)
307            .finish()
308    }
309}
310
311impl PartialEq for ProxyEnv {
312    // Compares the parsed values only, ignoring `captured_at` (consistent with
313    // [`ProxyConfig`]).
314    fn eq(&self, other: &Self) -> bool {
315        self.per_scheme == other.per_scheme
316            && self.bypass == other.bypass
317            && self.rejected == other.rejected
318    }
319}
320
321impl Eq for ProxyEnv {}
322
323// One environment variable as [`ProxyEnv::from_vars`] needs to see it.
324//
325// The two halves are not the same question. A *name* that is not valid Unicode cannot be
326// any of the variables in [`SCHEME_VARS`] or [`NO_PROXY_VAR`], which are ASCII, so it is
327// one of the unrelated variables sharing the process environment and dropping it changes no
328// answer. A *value* is where `into_string().ok()` would be the misreading this crate keeps
329// finding: it cannot tell "unset" from "set to bytes that are not UTF-8", and those are
330// opposite answers here; a dropped `http_proxy` leaves the snapshot saying no proxy is
331// configured at all, with nothing in [`ProxyEnv::rejected`] to say otherwise. So the value
332// is converted the lossy way instead, which is what `kde`'s `ProxyType = 4` lookup does for
333// the same reason (`sys::linux::desktop::text_if_set` converts the same way to keep a
334// mangled desktop name present): the replacement characters are what
335// [`ProxyEndpoint::parse`] refuses the address on, so the variable is recorded rather than
336// vanishing. That refusal reads the whole authority and not only the host; see the check
337// itself for why a password in the authority is part of what it refuses on.
338//
339// Taking the pair rather than reading the environment so the split can be tested without
340// a process-global variable.
341fn readable_var(
342    (name, value): (std::ffi::OsString, std::ffi::OsString),
343) -> Option<(String, String)> {
344    Some((
345        name.into_string().ok()?,
346        value.to_string_lossy().into_owned(),
347    ))
348}
349
350// Lowercase name first, uppercase name second; then, on Windows only, whatever other
351// letter case the variable was set in.
352fn lookup<'a>(map: &'a HashMap<String, String>, lower: &str) -> Option<&'a str> {
353    map.get(lower)
354        .or_else(|| map.get(&lower.to_ascii_uppercase()))
355        .or_else(|| any_case_on_windows(map, lower).map(|(_, value)| value))
356        .map(String::as_str)
357}
358
359// The entry whose key equals `name` ignoring case, on Windows only, where that is the
360// same variable rather than a different one.
361fn any_case_on_windows<'a>(
362    map: &'a HashMap<String, String>,
363    name: &str,
364) -> Option<(&'a String, &'a String)> {
365    if !cfg!(windows) {
366        return None;
367    }
368    map.iter()
369        .filter(|(key, _)| key.eq_ignore_ascii_case(name))
370        .min_by_key(|(key, _)| *key)
371}
372
373// The tests below need an `OsString` that is not valid Unicode, and only Windows and Unix
374// can build one; anywhere else they would run on an ordinary string and prove nothing. The
375// gate is on the module and not on each test because an empty `mod tests` still carries its
376// `use super::*`, and on `wasm32-unknown-unknown` (the one target that reaches
377// `sys::stub`), that unused import is an error under `-D warnings`.
378#[cfg(all(test, any(windows, unix)))]
379mod tests {
380    use super::*;
381
382    // The impl above is hand-written for the whole struct, and its comment names only the
383    // scheme order as the reason, so only this test checks the field list. `captured_at` is
384    // the field `PartialEq` refuses to compare and `to_config` carries over on purpose (it
385    // is how old the reading is), so a snapshot printed without it has no age, and two
386    // taken minutes apart render identically.
387    //
388    // Exact string, so a label, a field order or the scheme order cannot change unseen. The
389    // entries, the bypass rules and the timestamp keep their own renderings, which this impl
390    // does not own, so the expectation defers to them rather than copying them out.
391    #[test]
392    fn the_env_debug_lists_every_field_and_sorts_the_schemes() {
393        let env = ProxyEnv::from_vars([
394            ("https_proxy", "http://secure.corp:8443"),
395            ("http_proxy", "http://plain.corp:8080"),
396            ("no_proxy", ".example.com"),
397        ])
398        .expect("no REQUEST_METHOD is set here");
399        assert_eq!(
400            format!("{env:?}"),
401            format!(
402                "ProxyEnv {{ per_scheme: {{Http: {:?}, Https: {:?}}}, bypass: {:?}, \
403                 rejected: [], captured_at: {:?} }}",
404                env.per_scheme[&Scheme::Http],
405                env.per_scheme[&Scheme::Https],
406                env.bypass,
407                env.captured_at
408            )
409        );
410    }
411
412    // A variable set to bytes with no UTF-8 reading is *set*, and this crate must not
413    // report "no proxy is configured" when one is configured. Read with
414    // `into_string().ok()` the variable arrived as absent, so a mangled `http_proxy` was
415    // indistinguishable from an unset one, not even a `rejected` entry to look at.
416    #[test]
417    fn an_http_proxy_that_is_not_unicode_is_refused_rather_than_dropped() {
418        #[cfg(windows)]
419        // A lone UTF-16 surrogate has no UTF-8 representation.
420        let raw = {
421            use std::os::windows::ffi::OsStringExt;
422            std::ffi::OsString::from_wide(&[0xD800])
423        };
424        #[cfg(unix)]
425        // 0xFF is not a valid UTF-8 lead byte.
426        let raw = {
427            use std::os::unix::ffi::OsStringExt;
428            std::ffi::OsString::from_vec(vec![0xFF])
429        };
430
431        let (name, value) = readable_var((std::ffi::OsString::from("http_proxy"), raw))
432            .expect("a variable whose name is ASCII stays in the snapshot");
433        let env = ProxyEnv::from_vars([(name, value)]).expect("no REQUEST_METHOD is set here");
434        assert!(
435            env.endpoint_for(Scheme::Http).is_none(),
436            "replacement characters are not an address to send traffic to"
437        );
438        assert_eq!(
439            env.rejected().len(),
440            1,
441            "the variable is set, so its drop has to be visible: {:?}",
442            env.rejected()
443        );
444    }
445
446    // The same promise, at the place it is hardest to keep. The test above puts the
447    // undecodable byte where the whole value is the host, and a host never survives one. Put
448    // it in the password instead and the address around it is well formed, so without the
449    // authority-wide refusal in `ProxyEndpoint::parse` this reads `Ok`: the snapshot names
450    // `proxy.corp:8080` with `rejected` empty and a secret the reader invented attached to it.
451    #[test]
452    fn a_password_that_is_not_unicode_is_refused_like_a_host_that_is_not() {
453        #[cfg(windows)]
454        let raw = {
455            use std::os::windows::ffi::OsStringExt;
456            let mut units: Vec<u16> = "http://alice:".encode_utf16().collect();
457            units.push(0xD800);
458            units.extend("@proxy.corp:8080".encode_utf16());
459            std::ffi::OsString::from_wide(&units)
460        };
461        #[cfg(unix)]
462        let raw = {
463            use std::os::unix::ffi::OsStringExt;
464            let mut bytes = b"http://alice:".to_vec();
465            bytes.push(0xFF);
466            bytes.extend_from_slice(b"@proxy.corp:8080");
467            std::ffi::OsString::from_vec(bytes)
468        };
469
470        let (name, value) = readable_var((std::ffi::OsString::from("http_proxy"), raw))
471            .expect("a variable whose name is ASCII stays in the snapshot");
472        // Not vacuous: everything but the password is a perfectly ordinary address.
473        assert!(value.contains("@proxy.corp:8080"), "{value}");
474
475        let env = ProxyEnv::from_vars([(name, value)]).expect("no REQUEST_METHOD is set here");
476        assert!(
477            env.endpoint_for(Scheme::Http).is_none(),
478            "a credential the reader had to invent is not one to offer a proxy"
479        );
480        assert_eq!(
481            env.rejected().len(),
482            1,
483            "the variable is set, so its drop has to be visible: {:?}",
484            env.rejected()
485        );
486    }
487
488    // The other half: a name that cannot be one of the ASCII variables this crate reads is
489    // dropped, and dropping it has to stay silent; every process carries some of these.
490    #[test]
491    fn a_variable_whose_name_is_not_unicode_is_dropped_without_a_trace() {
492        #[cfg(windows)]
493        let raw = {
494            use std::os::windows::ffi::OsStringExt;
495            std::ffi::OsString::from_wide(&[0xD800])
496        };
497        #[cfg(unix)]
498        let raw = {
499            use std::os::unix::ffi::OsStringExt;
500            std::ffi::OsString::from_vec(vec![0xFF])
501        };
502
503        assert_eq!(
504            readable_var((raw, std::ffi::OsString::from("http://p:8080"))),
505            None
506        );
507    }
508}