Skip to main content

coqui_access_ldap/
search.rs

1//! LDAP filter and result helpers, independent of a live directory.
2use std::net::IpAddr;
3
4/// Active Directory's matching rule for nested group membership.
5pub const IN_CHAIN: &str = "(member:1.2.840.113556.1.4.1941:={dn})";
6
7/// Escapes a value for a filter (RFC 4515): the metacharacters, controls and every byte of
8/// a non-ASCII character as `\xx`. The matcher's own function, so one rule escapes everywhere.
9pub fn escaped(value: &str) -> String {
10    coqui_access_kit::matcher::escape_filter_value(value)
11}
12
13/// `(&<account filter><given filter>)`: a filter a caller supplied can only narrow the
14/// accounts the provider is configured to read.
15pub fn all_of(account_filter: &str, given: &str) -> String {
16    format!("(&{account_filter}{given})")
17}
18
19/// Whether `filter` is one balanced parenthesised group: `(...)` whose first parenthesis
20/// closes at the end. Escaped values hold no parenthesis, so this is the shape of a filter
21/// the matcher wrote.
22pub fn one_group(filter: &str) -> bool {
23    let mut depth = 0_i32;
24    for (at, character) in filter.char_indices() {
25        if at == 0 && character != '(' {
26            return false;
27        }
28        match character {
29            '(' => depth += 1,
30            ')' => depth -= 1,
31            _ => {}
32        }
33        if depth < 0 || (depth == 0 && at + character.len_utf8() != filter.len()) {
34            return false;
35        }
36    }
37    depth == 0 && !filter.is_empty()
38}
39
40/// Substitutes an escaped value for each `{field}` in an LDAP filter.
41pub fn filter(template: &str, field: &str, value: &str) -> String {
42    template.replace(&format!("{{{field}}}"), &escaped(value))
43}
44
45/// Reads the first RDN value of a group DN, unescaping comma and backslash.
46pub fn group_name(dn: &str) -> String {
47    let mut first = String::new();
48    let mut chars = dn.chars();
49    while let Some(character) = chars.next() {
50        match character {
51            '\\' => first.extend(chars.next()),
52            ',' => break,
53            character => first.push(character),
54        }
55    }
56    match first.split_once('=') {
57        Some((_, name)) if !name.trim().is_empty() => name.trim().to_owned(),
58        _ => dn.to_owned(),
59    }
60}
61
62/// Whether Active Directory account flags include `ACCOUNTDISABLE`.
63pub fn disabled(flags: Option<&str>) -> bool {
64    flags
65        .and_then(|flags| flags.trim().parse::<u64>().ok())
66        .is_some_and(|flags| flags & 0x2 != 0)
67}
68
69/// A distinguished name as its components, each lower-cased with the blanks around `=` and
70/// the component dropped; a `,` after a backslash belongs to its component.
71fn components(dn: &str) -> Vec<String> {
72    let mut parts = Vec::new();
73    let mut current = String::new();
74    let mut escaped = false;
75    for character in dn.chars() {
76        match character {
77            _ if escaped => {
78                current.push(character);
79                escaped = false;
80            }
81            '\\' => {
82                current.push(character);
83                escaped = true;
84            }
85            ',' | ';' => parts.push(std::mem::take(&mut current)),
86            _ => current.push(character),
87        }
88    }
89    parts.push(current);
90    parts
91        .into_iter()
92        .map(|part| {
93            let part = part.trim();
94            match part.split_once('=') {
95                Some((kind, value)) => format!("{}={}", kind.trim(), value.trim()).to_lowercase(),
96                None => part.to_lowercase(),
97            }
98        })
99        .collect()
100}
101
102/// Whether `dn` names an entry strictly below `base` (the base itself is not below it).
103/// Components compare case-insensitively with blanks around `=` and `,` ignored.
104pub fn below(dn: &str, base: &str) -> bool {
105    let (dn, base) = (components(dn), components(base));
106    !base.iter().any(String::is_empty)
107        && !dn.iter().any(String::is_empty)
108        && dn.len() > base.len()
109        && dn[dn.len() - base.len()..] == base[..]
110}
111
112/// A person's name in natural order: `display` when it says anything, else the given name,
113/// initials and surname that are present, joined by single spaces; `None` when nothing is.
114pub fn display_name(
115    display: Option<&str>,
116    given: Option<&str>,
117    initials: Option<&str>,
118    surname: Option<&str>,
119) -> Option<String> {
120    fn present(value: Option<&str>) -> Option<&str> {
121        value.map(str::trim).filter(|value| !value.is_empty())
122    }
123    if let Some(display) = present(display) {
124        return Some(display.to_owned());
125    }
126    let parts: Vec<&str> = [given, initials, surname]
127        .into_iter()
128        .filter_map(present)
129        .collect();
130    (!parts.is_empty()).then(|| parts.join(" "))
131}
132
133/// Whether connecting to `url` without StartTLS would expose a password.
134pub fn in_the_clear(url: &str, start_tls: bool) -> bool {
135    let Some(rest) = url.strip_prefix("ldap://") else {
136        return !url.starts_with("ldaps://");
137    };
138    if start_tls {
139        return false;
140    }
141    let host = rest.split(['/', '?']).next().unwrap_or_default();
142    let host = match host.strip_prefix('[') {
143        Some(bracketed) => bracketed.split(']').next().unwrap_or_default(),
144        None => host.rsplit_once(':').map_or(host, |(host, _)| host),
145    };
146    let loopback = host.eq_ignore_ascii_case("localhost")
147        || host
148            .parse::<IpAddr>()
149            .is_ok_and(|address| address.is_loopback());
150    !loopback
151}
152
153#[cfg(test)]
154mod tests {
155    use super::*;
156
157    #[test]
158    fn names_in_filters_are_escaped() {
159        assert_eq!(
160            filter("(uid={name})", "name", "*)(uid=*"),
161            "(uid=\\2a\\29\\28uid=\\2a)"
162        );
163        assert_eq!(escaped("a\\b\0"), "a\\5cb\\00");
164        assert_eq!(
165            filter(IN_CHAIN, "dn", "CN=Ana (first),OU=People"),
166            "(member:1.2.840.113556.1.4.1941:=CN=Ana \\28first\\29,OU=People)"
167        );
168    }
169
170    #[test]
171    fn a_given_filter_is_anded_with_the_account_filter_and_must_be_one_group() {
172        assert_eq!(
173            all_of("(objectClass=user)", "(altSecurityIdentities=X509:x)"),
174            "(&(objectClass=user)(altSecurityIdentities=X509:x))"
175        );
176        assert!(one_group("(a=1)"));
177        assert!(one_group("(&(a=1)(|(b=2)(c=3)))"));
178        for bad in ["", "a=1", "(a=1", "(a=1))", "(a=1)(b=2)", ")(", "(a=1)x"] {
179            assert!(!one_group(bad), "{bad}");
180        }
181        // A value escaped by the matcher holds no parenthesis, so it cannot unbalance this.
182        assert!(one_group("(a=\\29\\28)"));
183    }
184
185    #[test]
186    fn escaping_is_the_matchers_and_covers_controls_and_non_ascii() {
187        assert_eq!(escaped("caf\u{e9}\t"), "caf\\c3\\a9\\09");
188    }
189
190    #[test]
191    fn groups_and_disabled_flags_are_read_from_directory_values() {
192        assert_eq!(group_name("CN=Smith\\, Ana,OU=Groups"), "Smith, Ana");
193        assert_eq!(group_name("household"), "household");
194        assert!(disabled(Some("514")));
195        assert!(!disabled(Some("512")));
196        assert!(!disabled(None));
197    }
198
199    #[test]
200    fn cleartext_is_refused_outside_loopback() {
201        assert!(in_the_clear("ldap://directory.example.org", false));
202        assert!(!in_the_clear("ldap://directory.example.org", true));
203        assert!(!in_the_clear("ldaps://directory.example.org", false));
204        assert!(!in_the_clear("ldap://[::1]:389", false));
205    }
206
207    #[test]
208    fn a_name_is_below_a_base_by_its_components() {
209        let base = "DC=example,DC=org";
210        assert!(below("CN=Ana,OU=People,DC=example,DC=org", base));
211        assert!(below("cn=Ana , ou = People,dc=EXAMPLE,dc=Org", base));
212        assert!(below("CN=Smith\\, Ana,DC=example,DC=org", base));
213        assert!(!below(base, base));
214        assert!(!below("DC=org", base));
215        assert!(!below("CN=Ana,DC=example,DC=org,DC=evil", base));
216        assert!(!below("CN=Ana,DC=notexample,DC=org", base));
217        assert!(!below("CN=Ana,,DC=example,DC=org", base));
218        assert!(!below("", base));
219        assert!(!below("CN=Ana,DC=example,DC=org", ""));
220    }
221
222    #[test]
223    fn a_display_name_is_the_directorys_or_the_parts_in_natural_order() {
224        assert_eq!(
225            display_name(Some("Ana Rivera"), Some("A"), None, Some("R")).as_deref(),
226            Some("Ana Rivera")
227        );
228        assert_eq!(
229            display_name(Some("  "), Some("Ana"), Some("Q"), Some("Rivera")).as_deref(),
230            Some("Ana Q Rivera")
231        );
232        assert_eq!(
233            display_name(None, Some("Ana"), None, Some("Rivera")).as_deref(),
234            Some("Ana Rivera")
235        );
236        assert_eq!(
237            display_name(None, None, None, Some("Rivera")).as_deref(),
238            Some("Rivera")
239        );
240        assert_eq!(display_name(None, Some(" "), None, None), None);
241    }
242}