Skip to main content

coqui_access_kit/
pick.rs

1//! Choosing an account from the named fields of a credential, such as a certificate's.
2//!
3//! A provider that reads a certificate gets a map of field names to values (`subject.cn`,
4//! `san.email`, `san.upn`, `fingerprint`, as `coqui-peer-tls`'s `CertificateFields::to_map`
5//! writes it) and a list of [`Pick`]s from its configuration. [`pick`] tries them in order and
6//! says which [`Lookup`](coqui_access::Lookup) the credential names.
7
8use std::collections::BTreeMap;
9use std::net::IpAddr;
10
11use coqui_builder::Describe;
12
13/// The field DNS names that are IP literals are listed under, beside `san.dns`.
14pub const DNS_IP_FIELD: &str = "san.dns.ip";
15/// The field IP address names are listed under.
16pub const IP_FIELD: &str = "san.ip";
17
18/// One way to name the account: a field of the credential, and what that field is in the
19/// directory.
20///
21/// ```json
22/// { "field": "san.upn", "by": "name", "domain": "example.org" }
23/// ```
24#[derive(Debug, Clone, PartialEq, Eq, Describe)]
25#[non_exhaustive]
26pub struct Pick {
27    /// The credential's field, such as `san.email` or `subject.cn`.
28    pub field: String,
29    /// What the value is in the directory: the [`Lookup::by`](coqui_access::Lookup::by) it
30    /// is answered with, such as `email` or `name`.
31    pub by: String,
32    /// Keep only values ending `@<domain>` (any case) and take the part before it, as for a
33    /// UPN or an email address naming an account of one domain.
34    pub domain: Option<String>,
35    /// For `san.ip`: an IP address written as a DNS name counts as an IP name too. Some
36    /// issuers put an address in a `dNSName` for clients that read no IP SANs. Default
37    /// `true`.
38    #[map(default = true)]
39    pub ip_in_dns: bool,
40}
41
42impl Pick {
43    /// The value of `field`, looked up `by`, any domain, IPs in DNS names counted.
44    pub fn new(field: impl Into<String>, by: impl Into<String>) -> Self {
45        Self {
46            field: field.into(),
47            by: by.into(),
48            domain: None,
49            ip_in_dns: true,
50        }
51    }
52
53    /// This pick keeping only values of `domain`, without it.
54    #[must_use]
55    pub fn domain(mut self, domain: impl Into<String>) -> Self {
56        self.domain = Some(domain.into());
57        self
58    }
59
60    /// This pick with IP addresses written as DNS names counted (`true`) or not.
61    #[must_use]
62    pub fn ip_in_dns(mut self, counted: bool) -> Self {
63        self.ip_in_dns = counted;
64        self
65    }
66
67    /// Whether this pick may be used: what it finds is looked up `by` an attribute the
68    /// directory answers, never `filter` (a raw LDAP filter) or `claims` (a lookup the
69    /// matcher is to template), which only a [`Matcher`](crate::matcher::Matcher) rule makes.
70    ///
71    /// # Errors
72    ///
73    /// When `by` is `filter` or `claims`.
74    pub fn check(&self) -> Result<(), &'static str> {
75        if matches!(self.by.as_str(), "filter" | "claims") {
76            Err("a pick is looked up by an attribute, not by filter or claims")
77        } else {
78            Ok(())
79        }
80    }
81
82    /// What this pick finds in `fields`.
83    fn find(&self, fields: &BTreeMap<String, Vec<String>>) -> Picked {
84        let mut values: Vec<String> = fields.get(&self.field).cloned().unwrap_or_default();
85        if self.field == IP_FIELD && self.ip_in_dns {
86            values.extend(fields.get(DNS_IP_FIELD).cloned().unwrap_or_default());
87        }
88        if self.field == IP_FIELD || self.field == DNS_IP_FIELD {
89            for value in &mut values {
90                if let Ok(address) = value.parse::<IpAddr>() {
91                    *value = canonical(address).to_string();
92                }
93            }
94        }
95        if let Some(domain) = &self.domain {
96            let suffix = format!("@{}", domain.to_ascii_lowercase());
97            values = values
98                .into_iter()
99                .filter_map(|value| {
100                    let cut = value.len().checked_sub(suffix.len())?;
101                    (value.is_char_boundary(cut)
102                        && value[cut..].eq_ignore_ascii_case(&suffix)
103                        && cut > 0)
104                        .then(|| value[..cut].to_owned())
105                })
106                .collect();
107        }
108        values.sort();
109        values.dedup();
110        match values.len() {
111            0 => Picked::Absent,
112            1 => Picked::Found {
113                by: self.by.clone(),
114                value: values.remove(0),
115            },
116            _ => Picked::Ambiguous,
117        }
118    }
119}
120
121/// An address as one text: IPv6 compressed, an IPv4-mapped IPv6 address as its IPv4 one.
122fn canonical(address: IpAddr) -> IpAddr {
123    match address {
124        IpAddr::V6(v6) => v6.to_ipv4_mapped().map_or(address, IpAddr::V4),
125        address => address,
126    }
127}
128
129/// What [`pick`] decided.
130#[derive(Debug, Clone, PartialEq, Eq)]
131#[non_exhaustive]
132pub enum Picked {
133    /// No pick found a value: the credential names nobody.
134    Absent,
135    /// A pick's field holds two different values: the credential names nobody for certain.
136    Ambiguous,
137    /// The first pick with a value, and the value.
138    Found {
139        /// What the value is in the directory.
140        by: String,
141        /// The value.
142        value: String,
143    },
144}
145
146/// Tries each of `order` against `fields`, first to last: the first that finds one value
147/// decides, one that finds two different values is [`Picked::Ambiguous`], and none finding
148/// any is [`Picked::Absent`].
149///
150/// ```
151/// use std::collections::BTreeMap;
152/// use coqui_access_kit::pick::{Pick, Picked, pick};
153///
154/// let fields = BTreeMap::from([("san.upn".to_owned(), vec!["alice@EXAMPLE.org".to_owned()])]);
155/// let found = pick(&fields, &[Pick::new("san.email", "email"), Pick::new("san.upn", "name").domain("example.org")]);
156/// assert_eq!(found, Picked::Found { by: "name".into(), value: "alice".into() });
157/// ```
158pub fn pick(fields: &BTreeMap<String, Vec<String>>, order: &[Pick]) -> Picked {
159    for each in order.iter().filter(|each| each.check().is_ok()) {
160        match each.find(fields) {
161            Picked::Absent => {}
162            decided => return decided,
163        }
164    }
165    Picked::Absent
166}
167
168#[cfg(test)]
169mod tests {
170    use super::*;
171
172    fn fields(entries: &[(&str, &[&str])]) -> BTreeMap<String, Vec<String>> {
173        entries
174            .iter()
175            .map(|(key, values)| {
176                (
177                    (*key).to_owned(),
178                    values.iter().map(|value| (*value).to_owned()).collect(),
179                )
180            })
181            .collect()
182    }
183
184    #[test]
185    fn a_pick_that_names_a_filter_or_claims_is_refused_and_never_decides() {
186        for by in ["filter", "claims"] {
187            let pick_by = Pick::new("san.upn", by);
188            assert!(pick_by.check().is_err(), "{by}");
189            let entries = fields(&[("san.upn", &["alice"])]);
190            assert_eq!(pick(&entries, &[pick_by]), Picked::Absent, "{by}");
191        }
192        for by in ["name", "email", "id", "address", "certificate"] {
193            assert!(Pick::new("san.upn", by).check().is_ok(), "{by}");
194        }
195    }
196
197    fn found(by: &str, value: &str) -> Picked {
198        Picked::Found {
199            by: by.to_owned(),
200            value: value.to_owned(),
201        }
202    }
203
204    #[test]
205    fn picks_are_tried_in_order_and_two_values_are_ambiguous() {
206        let map = fields(&[
207            ("san.email", &["a@example.org", "b@example.org"]),
208            ("subject.cn", &["Alice"]),
209        ]);
210        let cn = Pick::new("subject.cn", "name");
211        assert_eq!(
212            pick(&map, std::slice::from_ref(&cn)),
213            found("name", "Alice")
214        );
215        assert_eq!(
216            pick(&map, &[Pick::new("san.email", "email"), cn.clone()]),
217            Picked::Ambiguous
218        );
219        assert_eq!(
220            pick(&map, &[Pick::new("san.uri", "uri"), cn]),
221            found("name", "Alice")
222        );
223        assert_eq!(pick(&map, &[Pick::new("san.uri", "uri")]), Picked::Absent);
224        assert_eq!(pick(&map, &[]), Picked::Absent);
225    }
226
227    #[test]
228    fn a_domain_keeps_its_own_values_and_takes_the_part_before() {
229        let map = fields(&[("san.upn", &["alice@CORP.example", "bob@other.example"])]);
230        let corp = Pick::new("san.upn", "name").domain("corp.example");
231        assert_eq!(pick(&map, &[corp]), found("name", "alice"));
232        let none = fields(&[("san.upn", &["@corp.example", "alice@corp.example.evil"])]);
233        assert_eq!(
234            pick(
235                &none,
236                &[Pick::new("san.upn", "name").domain("corp.example")]
237            ),
238            Picked::Absent
239        );
240    }
241
242    #[test]
243    fn an_ip_in_a_dns_name_counts_as_an_ip_name_unless_turned_off() {
244        let ip = Pick::new("san.ip", "address");
245        let dns_only = fields(&[("san.dns", &["10.0.0.9"]), ("san.dns.ip", &["10.0.0.9"])]);
246        let ip_only = fields(&[("san.ip", &["10.0.0.9"])]);
247        let both = fields(&[("san.ip", &["10.0.0.9"]), ("san.dns.ip", &["10.0.0.9"])]);
248        let differ = fields(&[("san.ip", &["10.0.0.9"]), ("san.dns.ip", &["10.0.0.8"])]);
249        for map in [&dns_only, &ip_only, &both] {
250            assert_eq!(
251                pick(map, std::slice::from_ref(&ip)),
252                found("address", "10.0.0.9")
253            );
254        }
255        assert_eq!(pick(&differ, std::slice::from_ref(&ip)), Picked::Ambiguous);
256        let strict = ip.ip_in_dns(false);
257        assert_eq!(
258            pick(&dns_only, std::slice::from_ref(&strict)),
259            Picked::Absent
260        );
261        assert_eq!(pick(&differ, &[strict]), found("address", "10.0.0.9"));
262    }
263
264    #[test]
265    fn addresses_are_compared_in_one_spelling() {
266        let mapped = fields(&[
267            ("san.ip", &["::ffff:10.0.0.9"]),
268            ("san.dns.ip", &["10.0.0.9"]),
269        ]);
270        assert_eq!(
271            pick(&mapped, &[Pick::new("san.ip", "address")]),
272            found("address", "10.0.0.9")
273        );
274        let six = fields(&[
275            ("san.ip", &["2001:db8:0:0:0:0:0:1"]),
276            ("san.dns.ip", &["2001:DB8::1"]),
277        ]);
278        assert_eq!(
279            pick(&six, &[Pick::new("san.ip", "address")]),
280            found("address", "2001:db8::1")
281        );
282    }
283
284    #[test]
285    fn a_pick_reads_from_configuration_with_ip_in_dns_on() {
286        let mut partial = coqui_builder::Partial::<Pick>::new();
287        partial.set("field", "san.ip").unwrap();
288        partial.set("by", "address").unwrap();
289        let read = partial.build().unwrap();
290        assert_eq!(read, Pick::new("san.ip", "address"));
291        assert!(read.ip_in_dns);
292    }
293}