Skip to main content

coqui_access_proxy/
lib.rs

1//! Reverse-proxy identity header authenticator.
2#![doc = include_str!("../README.md")]
3#![forbid(unsafe_code)]
4#![warn(missing_debug_implementations)]
5#![warn(missing_docs)]
6
7mod certificate;
8
9use std::net::{IpAddr, SocketAddr};
10
11use coqui_access::guatiao::Provider;
12use coqui_access::guatiao::library::ProviderError;
13use coqui_access::{Attempt, Authenticator, Limit, Lookup, Verdict};
14use coqui_access_kit::pick::{Pick, Picked, pick};
15use coqui_builder::{Describe, Partial};
16use coqui_net_acl::IpNet;
17use guatiao_builder::Described;
18
19pub use certificate::CertificateEncoding;
20
21/// The most bytes a certificate header may hold unless configured otherwise.
22pub const DEFAULT_MAX_CERTIFICATE_BYTES: Limit = Limit::at(16_384);
23
24/// The account picks by default: none. A forwarded certificate is then answered as its claims
25/// (`by: "claims"`), for the consumer's matcher to tie to a directory account; a subject
26/// header, which carries no certificate, still names its common name, by `name`.
27pub fn default_account() -> Vec<Pick> {
28    Vec::new()
29}
30
31/// Reverse-proxy trust and identity-header configuration.
32#[derive(Debug, Clone, Describe)]
33#[non_exhaustive]
34pub struct ProxyWordConfig {
35    /// Trusted addresses and CIDR networks; an empty list trusts nobody.
36    #[map(default)]
37    pub trusted: Vec<String>,
38    /// Header written by the proxy with an account name.
39    pub user_header: Option<String>,
40    /// Header holding the client certificate the proxy verified.
41    pub certificate_header: Option<String>,
42    /// How `certificate_header` is written: `pem-url` (nginx, AWS ALB), `der-base64`
43    /// (Traefik) or `xfcc` (Envoy).
44    #[map(default)]
45    pub certificate_encoding: CertificateEncoding,
46    /// Header holding a client certificate's subject, such as `CN=Doe,O=Ops`.
47    pub subject_header: Option<String>,
48    /// How a certificate or subject names the account: picks tried in order over its fields
49    /// (`subject.cn`, `san.email`, `san.upn`, ...). Default none: a forwarded certificate is
50    /// answered as its claims, and a subject header names its CN, by `name`.
51    #[map(default = default_account())]
52    pub account: Vec<Pick>,
53    /// The most bytes `certificate_header` may hold; `none` for no bound.
54    #[map(default = DEFAULT_MAX_CERTIFICATE_BYTES)]
55    pub max_certificate_bytes: Limit,
56}
57
58impl Default for ProxyWordConfig {
59    /// What an empty configuration reads as: nobody trusted, every other default.
60    fn default() -> Self {
61        Partial::new()
62            .build()
63            .expect("an empty configuration reads, every key having a default")
64    }
65}
66
67/// A reverse proxy's identity headers as an Authenticator.
68#[derive(Debug, Provider)]
69#[provider(
70    Authenticator,
71    id = "coqui_access_proxy",
72    name = "Trusted reverse proxy",
73    config = Described<ProxyWordConfig>,
74    crate = ::coqui_access::guatiao
75)]
76pub struct ProxyWord {
77    trusted: Vec<IpNet>,
78    user_header: Option<String>,
79    certificate_header: Option<String>,
80    certificate_encoding: CertificateEncoding,
81    subject_header: Option<String>,
82    account: Vec<Pick>,
83    max_certificate_bytes: Limit,
84}
85
86impl ProxyWord {
87    /// Parses a reverse-proxy policy. Invalid network entries are returned verbatim.
88    pub fn new(config: ProxyWordConfig) -> Result<Self, String> {
89        let trusted = config
90            .trusted
91            .iter()
92            .map(|network| match network.parse::<IpNet>() {
93                // Trusting every address is not a reverse proxy.
94                Ok(IpNet::Any) | Err(_) => Err(network.clone()),
95                Ok(network) => Ok(network),
96            })
97            .collect::<Result<Vec<_>, _>>()?;
98        if config.account.iter().any(|pick| pick.check().is_err()) {
99            return Err("an account pick is looked up by filter or claims".to_owned());
100        }
101        let header = |value: Option<String>| {
102            value
103                .map(|value| value.trim().to_ascii_lowercase())
104                .filter(|value| !value.is_empty())
105        };
106        let subject_header = header(config.subject_header);
107        let certificate_header = header(config.certificate_header);
108        let user_header = header(config.user_header).or_else(|| {
109            (subject_header.is_none() && certificate_header.is_none())
110                .then(|| "x-remote-user".to_owned())
111        });
112        Ok(Self {
113            trusted,
114            user_header,
115            certificate_header,
116            certificate_encoding: config.certificate_encoding,
117            subject_header,
118            account: config.account,
119            max_certificate_bytes: config.max_certificate_bytes,
120        })
121    }
122}
123
124impl TryFrom<ProxyWordConfig> for ProxyWord {
125    type Error = ProviderError;
126
127    fn try_from(config: ProxyWordConfig) -> Result<Self, Self::Error> {
128        Self::new(config).map_err(|_| {
129            coqui_access::error::bad_value(
130                "trusted entries must be IP addresses or CIDR networks, and account picks must name a directory attribute",
131            )
132        })
133    }
134}
135
136impl TryFrom<Described<ProxyWordConfig>> for ProxyWord {
137    type Error = ProviderError;
138
139    fn try_from(config: Described<ProxyWordConfig>) -> Result<Self, Self::Error> {
140        Self::try_from(config.0)
141    }
142}
143
144impl Authenticator for ProxyWord {
145    fn authenticate(&self, attempt: Attempt) -> Result<Verdict, ProviderError> {
146        let peer = attempt.peer.as_deref().and_then(parse_peer);
147        if !peer.is_some_and(|peer| self.trusted.iter().any(|network| network.contains(peer))) {
148            return Ok(Verdict::Unknown);
149        }
150        let header = |name: &str| -> Result<Option<&str>, ()> {
151            let values: Vec<&str> = attempt
152                .headers
153                .iter()
154                .filter(|(key, _)| key.eq_ignore_ascii_case(name))
155                .map(|(_, value)| value.trim())
156                .collect();
157            match values.as_slice() {
158                [] => Ok(None),
159                [one] => Ok((!one.is_empty()).then_some(one)),
160                _ => Err(()),
161            }
162        };
163        let user = match self.user_header.as_deref().map(header).transpose() {
164            Ok(user) => user.flatten(),
165            Err(()) => return Ok(Verdict::Invalid),
166        };
167        if let Some(name) = user {
168            return Ok(Verdict::Valid(Lookup {
169                by: "name".to_owned(),
170                value: name.to_owned(),
171                ..Lookup::default()
172            }));
173        }
174        if let Some(name) = self.certificate_header.as_deref() {
175            let forwarded = match header(name) {
176                Err(()) => return Ok(Verdict::Invalid),
177                Ok(None) => None,
178                Ok(Some(value)) => {
179                    if !self.max_certificate_bytes.allows(value.len()) {
180                        return Ok(Verdict::Invalid);
181                    }
182                    let Some(chain) = certificate::decode(value, self.certificate_encoding) else {
183                        return Ok(Verdict::Invalid);
184                    };
185                    let (Some(fields), Some(claims)) = (
186                        certificate::fields(&chain),
187                        chain
188                            .first()
189                            .and_then(|leaf| coqui_access_claims::of_certificate(leaf)),
190                    ) else {
191                        return Ok(Verdict::Invalid);
192                    };
193                    Some((fields, claims))
194                }
195            };
196            if let Some((fields, claims)) = forwarded {
197                // No picks: the claims are the answer, for a matcher to tie to an account.
198                if self.account.is_empty() {
199                    return Ok(Verdict::Valid(Lookup {
200                        by: "claims".to_owned(),
201                        value: claims
202                            .get("fingerprint")
203                            .first()
204                            .cloned()
205                            .unwrap_or_default(),
206                        claims: Some(claims),
207                    }));
208                }
209                if let Some(verdict) = self.picked(&fields, Some(claims)) {
210                    return Ok(verdict);
211                }
212            }
213        }
214        if let Some(name) = self.subject_header.as_deref() {
215            match header(name) {
216                Err(()) => return Ok(Verdict::Invalid),
217                Ok(None) => {}
218                Ok(Some(subject)) => {
219                    if let Some(verdict) = self.picked(&certificate::subject_fields(subject), None)
220                    {
221                        return Ok(verdict);
222                    }
223                }
224            }
225        }
226        Ok(Verdict::Unknown)
227    }
228}
229
230impl ProxyWord {
231    /// The verdict the account picks give over `fields`; `None` when they find nothing.
232    fn picked(
233        &self,
234        fields: &std::collections::BTreeMap<String, Vec<String>>,
235        claims: Option<coqui_access::Claims>,
236    ) -> Option<Verdict> {
237        let subject_only = [Pick::new("subject.cn", "name")];
238        let picks = if self.account.is_empty() {
239            &subject_only[..]
240        } else {
241            &self.account
242        };
243        match pick(fields, picks) {
244            Picked::Found { by, value } => Some(Verdict::Valid(Lookup { by, value, claims })),
245            Picked::Ambiguous => Some(Verdict::Invalid),
246            _ => None,
247        }
248    }
249}
250
251/// Finds the first non-empty, case-insensitive subject field.
252pub fn field_of(subject: &str, field: &str) -> Option<String> {
253    subject_parts(subject).into_iter().find_map(|part| {
254        let (name, value) = part.split_once('=')?;
255        (name.trim().eq_ignore_ascii_case(field) && !value.trim().is_empty())
256            .then(|| value.trim().to_owned())
257    })
258}
259
260/// A subject's `name=value` parts: comma-separated with `\` escaping, or slash-separated
261/// when it starts with `/`.
262fn subject_parts(subject: &str) -> Vec<String> {
263    let slash_separated = subject.starts_with('/');
264    let mut parts = Vec::new();
265    let mut part = String::new();
266    let mut chars = subject.chars();
267    while let Some(character) = chars.next() {
268        if !slash_separated && character == '\\' {
269            part.extend(chars.next());
270        } else if character == if slash_separated { '/' } else { ',' } {
271            parts.push(std::mem::take(&mut part));
272        } else {
273            part.push(character);
274        }
275    }
276    parts.push(part);
277    parts
278}
279
280fn parse_peer(peer: &str) -> Option<IpAddr> {
281    peer.parse::<IpAddr>()
282        .ok()
283        .or_else(|| peer.parse::<SocketAddr>().ok().map(|socket| socket.ip()))
284}
285
286#[cfg(test)]
287mod tests {
288    use super::*;
289
290    fn attempt(peer: Option<&str>, headers: &[(&str, &str)]) -> Attempt {
291        Attempt {
292            name: None,
293            secret: None,
294            headers: headers
295                .iter()
296                .map(|(key, value)| ((*key).to_owned(), (*value).to_owned()))
297                .collect(),
298            peer: peer.map(str::to_owned),
299            secure: Some(true),
300            certificate: None,
301            certificates: None,
302            method: None,
303            challenge: None,
304        }
305    }
306
307    fn proxy() -> ProxyWord {
308        ProxyWord::new(ProxyWordConfig {
309            trusted: vec!["10.0.0.0/24".to_owned(), "::1".to_owned()],
310            user_header: None,
311            subject_header: None,
312            ..ProxyWordConfig::default()
313        })
314        .unwrap()
315    }
316
317    #[test]
318    fn trusts_only_configured_peers_and_returns_a_directory_lookup() {
319        let proxy = proxy();
320        assert_eq!(
321            proxy
322                .authenticate(attempt(
323                    Some("10.0.0.9:8080"),
324                    &[("X-Remote-User", "agent")]
325                ))
326                .unwrap(),
327            Verdict::Valid(Lookup {
328                by: "name".to_owned(),
329                value: "agent".to_owned(),
330                ..Lookup::default()
331            })
332        );
333        assert_eq!(
334            proxy
335                .authenticate(attempt(Some("192.0.2.8"), &[("x-remote-user", "attacker")]))
336                .unwrap(),
337            Verdict::Unknown
338        );
339        assert_eq!(
340            proxy
341                .authenticate(attempt(None, &[("x-remote-user", "attacker")]))
342                .unwrap(),
343            Verdict::Unknown
344        );
345    }
346
347    #[test]
348    fn rejects_ambiguous_identity_headers_from_a_trusted_proxy() {
349        let proxy = proxy();
350        assert_eq!(
351            proxy
352                .authenticate(attempt(
353                    Some("10.0.0.3"),
354                    &[("x-remote-user", "first"), ("X-Remote-User", "second")],
355                ))
356                .unwrap(),
357            Verdict::Invalid
358        );
359    }
360
361    #[test]
362    fn reads_subjects_only_from_the_configured_peer() {
363        let proxy = ProxyWord::new(ProxyWordConfig {
364            trusted: vec!["127.0.0.1".to_owned()],
365            user_header: None,
366            subject_header: Some("x-client-subject".to_owned()),
367            ..ProxyWordConfig::default()
368        })
369        .unwrap();
370        assert_eq!(
371            proxy
372                .authenticate(attempt(
373                    Some("127.0.0.1"),
374                    &[("x-client-subject", r"O=Ops,CN=Doe\, Jane")]
375                ))
376                .unwrap(),
377            Verdict::Valid(Lookup {
378                by: "name".to_owned(),
379                value: "Doe, Jane".to_owned(),
380                ..Lookup::default()
381            })
382        );
383        assert_eq!(
384            proxy
385                .authenticate(attempt(
386                    Some("127.0.0.2"),
387                    &[("x-client-subject", "CN=Doe")]
388                ))
389                .unwrap(),
390            Verdict::Unknown
391        );
392    }
393
394    #[test]
395    fn rejects_invalid_networks_and_reads_slash_subjects() {
396        let trusting = |entries: &[&str]| {
397            ProxyWord::try_from(ProxyWordConfig {
398                trusted: entries.iter().map(|entry| (*entry).to_owned()).collect(),
399                user_header: None,
400                subject_header: None,
401                ..ProxyWordConfig::default()
402            })
403        };
404        assert!(trusting(&["10.0.0.0/33"]).is_err());
405        assert!(
406            trusting(&["any"]).is_err(),
407            "trusting every address is not a proxy"
408        );
409        assert!(trusting(&["10.0.0.0/8", "ANY"]).is_err());
410        assert_eq!(field_of("/O=Ops/CN=Doe", "cn"), Some("Doe".to_owned()));
411        assert_eq!(field_of("CN=,O=Ops", "CN"), None);
412    }
413
414    #[test]
415    fn an_ipv4_mapped_network_trusts_the_addresses_it_maps() {
416        let proxy = ProxyWord::new(ProxyWordConfig {
417            trusted: vec!["::ffff:10.0.0.0/120".to_owned()],
418            user_header: None,
419            subject_header: None,
420            ..ProxyWordConfig::default()
421        })
422        .unwrap();
423        let from = |peer: &str| {
424            proxy
425                .authenticate(attempt(Some(peer), &[("x-remote-user", "alice")]))
426                .unwrap()
427        };
428        assert!(matches!(from("10.0.0.9:443"), Verdict::Valid(_)));
429        assert!(matches!(from("[::ffff:10.0.0.9]:443"), Verdict::Valid(_)));
430        assert_eq!(from("10.0.1.9:443"), Verdict::Unknown);
431    }
432}