Skip to main content

coqui_access_kit/
matcher.rs

1//! Tying the identity an authenticator obtained to an account in a directory.
2//!
3//! An authenticator that has more than a name answers a [`Lookup`] with `by: "claims"` and
4//! its [`Claims`]. A [`Matcher`] holds ordered rules that turn claims into lookups of a
5//! [`Directory`], by a template: `{san.upn}`, `{subject.cn|lower}`, or an LDAP filter such
6//! as `(userPrincipalName={san.upn})`. The directory, never the credential, decides the
7//! account and its groups.
8//!
9//! Rules are tried in order. A rule asks the directory for every candidate its template
10//! renders; if they name exactly one account that account is the match, if they name more
11//! than one the match is [`Match::Ambiguous`] and the walk ends, and if none the next rule is
12//! tried. A directory that cannot answer is an `Err`, never a fall-through. A rule may name a
13//! [`PinSource`]: the one account it found must then also hold one of the certificate's
14//! pins there.
15//!
16//! In a `filter` rule every value a claim puts into the template is escaped (RFC 4515, see
17//! [`escape_filter_value`]); the template's own text is the filter's structure. A claim with
18//! several values renders one candidate per value, at most [`MAX_CANDIDATES`] in all.
19
20use std::collections::BTreeMap;
21use std::fmt;
22use std::sync::Arc;
23
24use coqui_access::guatiao::library::ProviderError;
25use coqui_access::{Claims, Directory, Lookup, Person, error};
26use coqui_builder::Describe;
27
28use crate::pins::{PinCheck, PinSet, PinSource};
29
30/// The most lookups one rule may render from the claims it is given.
31pub const MAX_CANDIDATES: usize = 16;
32
33/// What each rule's `by` may be: the lookups a directory answers (`name`, `email`, `id`) or
34/// an LDAP `filter`.
35const BYS: [&str; 4] = ["name", "email", "id", "filter"];
36
37/// One way to find the account: a template over the claims, and what it renders is.
38///
39/// ```toml
40/// [[rule]]
41/// by = "filter"
42/// template = "(userPrincipalName={san.upn})"
43/// ```
44#[derive(Debug, Clone, PartialEq, Eq, Describe)]
45#[map(deny_unknown_fields)]
46#[non_exhaustive]
47pub struct MatchRule {
48    /// What the rendered text is: `name`, `email` or `id` (the directory attribute it is
49    /// looked up by), or `filter` (an LDAP filter, values escaped).
50    pub by: String,
51    /// Text with `{claim}` and `{claim|filter|...}` parts; `{{` and `}}` are braces. The
52    /// filters are `lower`, `upper`, `local` (before the last `@`) and `domain` (after it).
53    /// It names at least one claim. Stripping a realm with `local` loses what ties the name
54    /// to it, so such a rule also needs `domain` or `pins`.
55    pub template: String,
56    /// The name of a pin source (given to the builder): the one account this rule finds must
57    /// also hold one of the certificate's pins there.
58    pub pins: Option<String>,
59    /// The realm a `local` filter strips: a claim value passed through `local` counts only
60    /// when it ends `@<domain>` (any case), so `alice@evil.example` is not `alice`. A rule
61    /// that strips a domain says which, or names `pins`; one with no `local` has none.
62    pub domain: Option<String>,
63}
64
65impl MatchRule {
66    /// A rule rendering `template` looked up `by`.
67    pub fn new(by: impl Into<String>, template: impl Into<String>) -> Self {
68        Self {
69            by: by.into(),
70            template: template.into(),
71            pins: None,
72            domain: None,
73        }
74    }
75
76    /// This rule keeping, for `local`, only values of `domain`.
77    #[must_use]
78    pub fn domain(mut self, domain: impl Into<String>) -> Self {
79        self.domain = Some(domain.into());
80        self
81    }
82
83    /// This rule also requiring the account to hold a pin in the source called `source`.
84    #[must_use]
85    pub fn pins(mut self, source: impl Into<String>) -> Self {
86        self.pins = Some(source.into());
87        self
88    }
89}
90
91/// The rules a matcher uses unless told otherwise: the UPN as a name, the email address as
92/// an email. The subject's common name is not among them: it is whatever the issuer let the
93/// holder type, so a deployment that trusts it says so in a rule of its own.
94pub fn default_rules() -> Vec<MatchRule> {
95    vec![
96        MatchRule::new("name", "{san.upn}"),
97        MatchRule::new("email", "{san.email}"),
98    ]
99}
100
101/// A matcher as plain data: ordered rules, [`default_rules`] when the key is absent.
102#[derive(Debug, Clone, PartialEq, Eq, Describe)]
103#[map(deny_unknown_fields)]
104#[non_exhaustive]
105pub struct MatcherConfig {
106    /// The rules, in the order they are tried. An empty list matches nobody.
107    #[map(default = default_rules())]
108    pub rule: Vec<MatchRule>,
109}
110
111impl Default for MatcherConfig {
112    fn default() -> Self {
113        Self {
114            rule: default_rules(),
115        }
116    }
117}
118
119/// An invalid rule. The message never quotes the template.
120#[derive(Debug, Clone, PartialEq, Eq)]
121#[non_exhaustive]
122pub struct MatcherError(String);
123
124impl fmt::Display for MatcherError {
125    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
126        formatter.write_str(&self.0)
127    }
128}
129
130impl core::error::Error for MatcherError {}
131
132impl From<MatcherError> for ProviderError {
133    fn from(failure: MatcherError) -> Self {
134        error::bad_value(&failure.0)
135    }
136}
137
138fn fail(index: usize, message: &str) -> MatcherError {
139    MatcherError(format!("rule {index}: {message}"))
140}
141
142/// What a match came to.
143#[derive(Debug, Clone, PartialEq, Eq)]
144#[non_exhaustive]
145pub enum Match {
146    /// Exactly one account, as the directory knows it.
147    Found(Person),
148    /// No rule found anybody.
149    NotFound,
150    /// A rule found more than one account: refused, never a choice.
151    Ambiguous,
152}
153
154/// A match and what to tell whoever runs the service about it.
155#[derive(Debug, Clone, PartialEq, Eq)]
156#[non_exhaustive]
157pub struct Matched {
158    /// What was found.
159    pub result: Match,
160    /// Why a pin source counted as no pins (a file with the wrong permissions), in the
161    /// order met. Never a pin or a claim.
162    pub notes: Vec<String>,
163}
164
165#[derive(Clone, Copy, PartialEq, Eq)]
166enum Filter {
167    Lower,
168    Upper,
169    Local,
170    Domain,
171}
172
173impl Filter {
174    fn apply(self, value: &str) -> Option<String> {
175        match self {
176            Self::Lower => Some(value.to_lowercase()),
177            Self::Upper => Some(value.to_uppercase()),
178            // A value with more than one `@` has no realm to strip: what is left of two is a name that holds an `@`.
179            _ if value.matches('@').count() > 1 => None,
180            Self::Local => Some(
181                value
182                    .rsplit_once('@')
183                    .map_or(value, |(local, _)| local)
184                    .to_owned(),
185            ),
186            Self::Domain => value.rsplit_once('@').map(|(_, domain)| domain.to_owned()),
187        }
188    }
189}
190
191enum Piece {
192    Text(String),
193    Field { name: String, filters: Vec<Filter> },
194}
195
196fn parse(index: usize, template: &str) -> Result<Vec<Piece>, MatcherError> {
197    let mut pieces = Vec::new();
198    let mut text = String::new();
199    let mut chars = template.chars().peekable();
200    while let Some(character) = chars.next() {
201        match character {
202            '{' if chars.peek() == Some(&'{') => {
203                chars.next();
204                text.push('{');
205            }
206            '}' if chars.peek() == Some(&'}') => {
207                chars.next();
208                text.push('}');
209            }
210            '}' => return Err(fail(index, "the template has an unmatched }")),
211            '{' => {
212                let mut inner = String::new();
213                loop {
214                    match chars.next() {
215                        Some('}') => break,
216                        Some('{') | None => {
217                            return Err(fail(index, "the template has an unmatched {"));
218                        }
219                        Some(other) => inner.push(other),
220                    }
221                }
222                let mut parts = inner.split('|');
223                let name = parts.next().unwrap_or_default();
224                let valid = !name.is_empty()
225                    && name.bytes().all(|byte| {
226                        byte.is_ascii_lowercase()
227                            || byte.is_ascii_digit()
228                            || matches!(byte, b'.' | b'_' | b'-')
229                    });
230                if !valid {
231                    return Err(fail(index, "a claim name is empty or not lowercase words"));
232                }
233                let mut filters = Vec::new();
234                for word in parts {
235                    filters.push(match word {
236                        "lower" => Filter::Lower,
237                        "upper" => Filter::Upper,
238                        "local" => Filter::Local,
239                        "domain" => Filter::Domain,
240                        _ => {
241                            return Err(fail(
242                                index,
243                                "a filter is not lower, upper, local or domain",
244                            ));
245                        }
246                    });
247                }
248                if !text.is_empty() {
249                    pieces.push(Piece::Text(std::mem::take(&mut text)));
250                }
251                pieces.push(Piece::Field {
252                    name: name.to_owned(),
253                    filters,
254                });
255            }
256            other => text.push(other),
257        }
258    }
259    if !text.is_empty() {
260        pieces.push(Piece::Text(text));
261    }
262    Ok(pieces)
263}
264
265/// Whether `shape` (a filter with its values replaced) is one parenthesised group, however
266/// nested.
267fn one_group(shape: &str) -> bool {
268    let mut depth = 0_i32;
269    let mut chars = shape.chars().peekable();
270    if chars.peek() != Some(&'(') {
271        return false;
272    }
273    let mut first = true;
274    for character in chars {
275        if !first && depth == 0 {
276            return false;
277        }
278        first = false;
279        match character {
280            '(' => depth += 1,
281            ')' => depth -= 1,
282            _ => {}
283        }
284        if depth < 0 {
285            return false;
286        }
287    }
288    depth == 0
289}
290
291struct Compiled {
292    by: &'static str,
293    filter: bool,
294    pieces: Vec<Piece>,
295    pins: Option<String>,
296    /// The realm `local` keeps, lower case.
297    domain: Option<String>,
298}
299
300/// Whether `value` is `<something>@<domain>`, in any case.
301fn in_realm(value: &str, domain: &str) -> bool {
302    value.matches('@').count() == 1
303        && value
304            .rsplit_once('@')
305            .is_some_and(|(local, found)| !local.is_empty() && found.eq_ignore_ascii_case(domain))
306}
307
308impl Compiled {
309    fn new(index: usize, rule: &MatchRule) -> Result<Self, MatcherError> {
310        let Some(by) = BYS.iter().find(|word| **word == rule.by) else {
311            return Err(fail(index, "by is not name, email, id or filter"));
312        };
313        let pieces = parse(index, &rule.template)?;
314        if !pieces
315            .iter()
316            .any(|piece| matches!(piece, Piece::Field { .. }))
317        {
318            return Err(fail(
319                index,
320                "the template names no claim, so it would look up the same account for everyone",
321            ));
322        }
323        let strips = pieces.iter().any(|piece| {
324            matches!(piece, Piece::Field { filters, .. } if filters.contains(&Filter::Local))
325        });
326        let domain = match rule.domain.as_deref() {
327            None => None,
328            Some(domain) => {
329                if domain.is_empty()
330                    || domain.contains('@')
331                    || domain.chars().any(|c| c.is_control() || c.is_whitespace())
332                {
333                    return Err(fail(index, "the domain is not a domain name"));
334                }
335                if !strips {
336                    return Err(fail(
337                        index,
338                        "a domain applies to a template that uses local",
339                    ));
340                }
341                Some(domain.to_ascii_lowercase())
342            }
343        };
344        if strips && domain.is_none() && rule.pins.is_none() {
345            return Err(fail(
346                index,
347                "local strips the realm from a name: say which with domain, or require pins",
348            ));
349        }
350        let filter = *by == "filter";
351        if filter {
352            let shape: String = pieces
353                .iter()
354                .map(|piece| match piece {
355                    Piece::Text(text) => text.as_str(),
356                    Piece::Field { .. } => "x",
357                })
358                .collect();
359            if !one_group(&shape) {
360                return Err(fail(index, "a filter is one balanced parenthesised group"));
361            }
362        }
363        Ok(Self {
364            by,
365            filter,
366            pieces,
367            pins: rule.pins.clone(),
368            domain,
369        })
370    }
371
372    /// Every lookup the claims render, none when a claim is missing or empty.
373    fn candidates(&self, claims: &Claims) -> Result<Vec<Lookup>, ProviderError> {
374        // Each piece's possible texts.
375        let mut options: Vec<Vec<String>> = Vec::new();
376        for piece in &self.pieces {
377            match piece {
378                Piece::Text(text) => options.push(vec![text.clone()]),
379                Piece::Field { name, filters } => {
380                    let mut values: Vec<String> = Vec::new();
381                    for value in claims.get(name) {
382                        if let Some(domain) = &self.domain
383                            && filters.contains(&Filter::Local)
384                            && !in_realm(value, domain)
385                        {
386                            continue;
387                        }
388                        let mut value = Some(value.clone());
389                        for filter in filters {
390                            value = value.and_then(|value| filter.apply(&value));
391                        }
392                        if let Some(value) = value.filter(|value| !value.is_empty()) {
393                            let value = if self.filter {
394                                escape_filter_value(&value)
395                            } else {
396                                value
397                            };
398                            if !values.contains(&value) {
399                                values.push(value);
400                            }
401                        }
402                    }
403                    if values.is_empty() {
404                        return Ok(Vec::new());
405                    }
406                    options.push(values);
407                }
408            }
409        }
410        let mut rendered = vec![String::new()];
411        for choices in &options {
412            if rendered.len().saturating_mul(choices.len()) > MAX_CANDIDATES {
413                return Err(error::bad_value(
414                    "the claims render more lookups than a rule may ask for",
415                ));
416            }
417            rendered = rendered
418                .iter()
419                .flat_map(|head| choices.iter().map(move |tail| format!("{head}{tail}")))
420                .collect();
421        }
422        Ok(rendered
423            .into_iter()
424            .map(|value| Lookup {
425                by: self.by.to_owned(),
426                value,
427                claims: None,
428            })
429            .collect())
430    }
431}
432
433/// Builds a [`Matcher`] and gives it the pin sources its rules name.
434pub struct MatcherBuilder {
435    config: MatcherConfig,
436    sources: BTreeMap<String, Arc<dyn PinSource>>,
437}
438
439impl fmt::Debug for MatcherBuilder {
440    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
441        formatter
442            .debug_struct("MatcherBuilder")
443            .field("rules", &self.config.rule.len())
444            .field("sources", &self.sources.len())
445            .finish()
446    }
447}
448
449impl MatcherBuilder {
450    /// Gives the rules that say `pins = "<name>"` this source.
451    #[must_use]
452    pub fn pin_source(mut self, name: impl Into<String>, source: Arc<dyn PinSource>) -> Self {
453        self.sources.insert(name.into(), source);
454        self
455    }
456
457    /// Checks the rules and compiles them.
458    ///
459    /// # Errors
460    ///
461    /// As [`Matcher::new`], and a rule naming a pin source that was not given.
462    pub fn build(self) -> Result<Matcher, MatcherError> {
463        let mut rules = Vec::with_capacity(self.config.rule.len());
464        for (index, rule) in self.config.rule.iter().enumerate() {
465            let compiled = Compiled::new(index, rule)?;
466            if let Some(name) = &compiled.pins
467                && !self.sources.contains_key(name)
468            {
469                return Err(fail(
470                    index,
471                    "the rule names a pin source that was not given",
472                ));
473            }
474            rules.push(compiled);
475        }
476        Ok(Matcher {
477            rules,
478            sources: self.sources,
479        })
480    }
481}
482
483/// Ordered rules that tie claims to a directory account.
484pub struct Matcher {
485    rules: Vec<Compiled>,
486    sources: BTreeMap<String, Arc<dyn PinSource>>,
487}
488
489impl fmt::Debug for Matcher {
490    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
491        formatter
492            .debug_struct("Matcher")
493            .field("rules", &self.rules.len())
494            .field("sources", &self.sources.len())
495            .finish()
496    }
497}
498
499/// The [`default_rules`].
500impl Default for Matcher {
501    fn default() -> Self {
502        Self::new(MatcherConfig::default()).expect("the default rules are valid")
503    }
504}
505
506impl Matcher {
507    /// Starts a matcher that takes pin sources.
508    pub fn builder(config: MatcherConfig) -> MatcherBuilder {
509        MatcherBuilder {
510            config,
511            sources: BTreeMap::new(),
512        }
513    }
514
515    /// Checks `config` and compiles it, for rules that name no pin source.
516    ///
517    /// # Errors
518    ///
519    /// A `by` other than `name`, `email`, `id` or `filter`; a template with an unmatched
520    /// brace, a claim name that is not lowercase words, a filter that is not `lower`,
521    /// `upper`, `local` or `domain`, or no claim at all; a `filter` template that is not one
522    /// balanced parenthesised group; a rule naming a pin source; a template using `local`
523    /// with neither a `domain` nor `pins`; a `domain` that is empty, holds `@` or whitespace,
524    /// or is given to a template without `local`.
525    pub fn new(config: MatcherConfig) -> Result<Self, MatcherError> {
526        Self::builder(config).build()
527    }
528
529    /// Finds the account `lookup` names.
530    ///
531    /// A lookup that is not `by: "claims"`, or has no claims, is looked up as it is, except a
532    /// `by: "filter"` one, which is refused (`NotFound`): filters come only from the rules'
533    /// escaped templates.
534    ///
535    /// # Errors
536    ///
537    /// When the directory or a pin source cannot answer, or a rule renders more than
538    /// [`MAX_CANDIDATES`] lookups.
539    pub fn resolve(
540        &self,
541        lookup: &Lookup,
542        directory: &dyn Directory,
543    ) -> Result<Matched, ProviderError> {
544        let mut notes = Vec::new();
545        let result = self.walk(lookup, directory, &mut notes)?;
546        Ok(Matched { result, notes })
547    }
548
549    fn walk(
550        &self,
551        lookup: &Lookup,
552        directory: &dyn Directory,
553        notes: &mut Vec<String>,
554    ) -> Result<Match, ProviderError> {
555        let claims = match (&lookup.claims, lookup.by.as_str()) {
556            (Some(claims), "claims") => claims,
557            (None, "claims") => return Ok(Match::NotFound),
558            // A filter is made by a rule's template, with its values escaped; one handed in
559            // is somebody's raw text.
560            (_, "filter") => return Ok(Match::NotFound),
561            _ => {
562                return Ok(match asked(directory, lookup.clone())? {
563                    Asked::One(person) => Match::Found(person),
564                    Asked::None => Match::NotFound,
565                    Asked::Several => Match::Ambiguous,
566                });
567            }
568        };
569        let pins = PinSet::from_claims(claims);
570        for rule in &self.rules {
571            let mut found: Vec<Person> = Vec::new();
572            for candidate in rule.candidates(claims)? {
573                match asked(directory, candidate)? {
574                    Asked::None => {}
575                    Asked::Several => return Ok(Match::Ambiguous),
576                    Asked::One(person) => {
577                        if !found.iter().any(|known| known.id == person.id) {
578                            found.push(person);
579                        }
580                    }
581                }
582            }
583            match found.len() {
584                0 => continue,
585                1 => {}
586                _ => return Ok(Match::Ambiguous),
587            }
588            let person = found.remove(0);
589            let Some(name) = &rule.pins else {
590                return Ok(Match::Found(person));
591            };
592            let Some(source) = self.sources.get(name) else {
593                continue;
594            };
595            if pins.is_empty() {
596                continue;
597            }
598            match source.check(&person, &pins)? {
599                PinCheck::Holds => return Ok(Match::Found(person)),
600                PinCheck::Refused(reason) => notes.push(reason),
601                _ => {}
602            }
603        }
604        Ok(Match::NotFound)
605    }
606}
607
608enum Asked {
609    None,
610    One(Person),
611    Several,
612}
613
614/// One lookup, an ambiguity being its own answer and every other error the caller's.
615fn asked(directory: &dyn Directory, lookup: Lookup) -> Result<Asked, ProviderError> {
616    match directory.lookup(lookup) {
617        Ok(Some(person)) => Ok(Asked::One(person)),
618        Ok(None) => Ok(Asked::None),
619        Err(failure) if error::is_ambiguous(&failure) => Ok(Asked::Several),
620        Err(failure) => Err(failure),
621    }
622}
623
624/// Escapes `value` for the right-hand side of an LDAP filter assertion (RFC 4515): `*`, `(`,
625/// `)`, `\` and NUL, every other control character, and every byte of a non-ASCII character,
626/// as `\` and two lowercase hex digits. What is left is printable ASCII, so a value can never
627/// end an assertion, start another, or become a wildcard.
628pub fn escape_filter_value(value: &str) -> String {
629    let mut output = String::with_capacity(value.len());
630    for byte in value.bytes() {
631        if byte.is_ascii_graphic() && !matches!(byte, b'*' | b'(' | b')' | b'\\') || byte == b' ' {
632            output.push(char::from(byte));
633        } else {
634            output.push('\\');
635            output.push_str(&format!("{byte:02x}"));
636        }
637    }
638    output
639}