Skip to main content

coqui_access_ldap/
lib.rs

1//! LDAP and Active Directory authentication and directory lookup.
2#![doc = include_str!("../README.md")]
3#![forbid(unsafe_code)]
4#![warn(missing_debug_implementations)]
5#![warn(missing_docs)]
6
7mod primary;
8pub mod search;
9
10use std::fmt;
11use std::sync::Arc;
12use std::time::Duration;
13
14use coqui_access::guatiao::Provider;
15use coqui_access::guatiao::library::ProviderError;
16use coqui_access::{Attempt, Authenticator, Directory, Lookup, Person, Verdict};
17use coqui_access_kit::{CacheOptions, CacheSetting, Cached};
18use coqui_builder::{Describe, Secret};
19use coqui_peer_tls::{ClientBuilder, NonDefault, Policy, Roots, Trust};
20use guatiao_builder::Described;
21use ldap3::{LdapConn, LdapConnSettings, Scope, SearchEntry};
22
23/// The account filter a filter lookup is ANDed with unless the configuration says another:
24/// people who are users, which leaves out Active Directory's computer accounts.
25pub const DEFAULT_OBJECT_FILTER: &str = "(&(objectCategory=person)(objectClass=user))";
26
27/// LDAP result code for credentials rejected by a directory.
28const INVALID_CREDENTIALS: u32 = 49;
29
30/// LDAP authentication and query settings.
31#[derive(Clone, Describe)]
32#[non_exhaustive]
33pub struct LdapAccountsConfig {
34    /// LDAP or LDAPS server URL.
35    pub url: String,
36    /// Start TLS on an LDAP connection before sending credentials.
37    #[map(default = false)]
38    pub start_tls: bool,
39    /// Optional PEM file with the only trusted server roots.
40    pub ca_file: Option<String>,
41    /// Base distinguished name used for searches.
42    pub base: String,
43    /// Service-account distinguished name used for searches.
44    pub bind: Option<String>,
45    /// Service-account password; wiped when dropped and never shown.
46    pub bind_password: Option<Secret<String>>,
47    /// LDAP filter with `{name}` for the escaped account name.
48    #[map(default = String::from("(sAMAccountName={name})"))]
49    pub user_filter: String,
50    /// The filter every account a filter lookup may find matches, which the lookup's filter
51    /// is AND-ed with so it can only narrow it. It must carry every restriction an account
52    /// must meet to sign in here (people, not computer or service accounts; an organisational
53    /// unit; a group): `user_filter` is not applied to a filter lookup, as it is built around
54    /// a name. The default is people, not Active Directory computer accounts.
55    #[map(default = String::from(DEFAULT_OBJECT_FILTER))]
56    pub object_filter: String,
57    /// Whether a lookup `by: "filter"` is answered. Off by default: a filter is built only by
58    /// a matcher's rule, with its values escaped, and a directory with no such rule has no
59    /// reason to take one. Anything that can make a lookup `by: "filter"` with its own text
60    /// can search the directory, so turn this on only where the lookups come from a matcher.
61    #[map(default = false)]
62    pub allow_filter_lookups: bool,
63    /// Attribute containing the directory's canonical account name.
64    #[map(default = String::from("sAMAccountName"))]
65    pub name_attribute: String,
66    /// Attribute containing group distinguished names; empty disables direct groups.
67    #[map(default = String::from("memberOf"))]
68    pub group_attribute: String,
69    /// Optional filter template with `{dn}` for groups containing the account.
70    pub group_filter: Option<String>,
71    /// Optional base for group searches; defaults to `base`.
72    pub group_base: Option<String>,
73    /// Read nested groups with Active Directory's matching rule.
74    #[map(default = false)]
75    pub nested_groups: bool,
76    /// Connection and operation timeout in seconds; values below one become one.
77    #[map(default = 10)]
78    pub timeout_seconds: u32,
79    /// Lookups kept for a few seconds, to absorb bursts: `true` (5 s, 1 s for "not found",
80    /// 10 000 entries), `false`, or `{ "ttl", "negative_ttl", "max_entries" }` (durations read
81    /// `5`, `1.5`, `5s` or `250ms`). Passwords are always checked at the directory.
82    #[map(default)]
83    pub cache: CacheSetting,
84}
85
86impl fmt::Debug for LdapAccountsConfig {
87    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
88        formatter
89            .debug_struct("LdapAccountsConfig")
90            .field("url", &"[REDACTED]")
91            .field("start_tls", &self.start_tls)
92            .field("ca_file", &self.ca_file)
93            .field("base", &self.base)
94            .field("bind", &self.bind.as_ref().map(|_| "[REDACTED]"))
95            .field(
96                "bind_password",
97                &self.bind_password.as_ref().map(|_| "[REDACTED]"),
98            )
99            .field("user_filter", &self.user_filter)
100            .field("object_filter", &self.object_filter)
101            .field("allow_filter_lookups", &self.allow_filter_lookups)
102            .field("name_attribute", &self.name_attribute)
103            .field("group_attribute", &self.group_attribute)
104            .field("group_filter", &self.group_filter)
105            .field("group_base", &self.group_base)
106            .field("nested_groups", &self.nested_groups)
107            .field("timeout_seconds", &self.timeout_seconds)
108            .finish()
109    }
110}
111
112/// LDAP accounts as authentication and directory providers, with lookups kept as the
113/// configuration's `cache` says.
114#[derive(Provider)]
115#[provider(
116    Authenticator,
117    Directory,
118    id = "coqui_access_ldap",
119    name = "LDAP accounts",
120    config = Described<LdapAccountsConfig>,
121    crate = ::coqui_access::guatiao
122)]
123pub struct LdapAccounts {
124    directory: Cached<Ldap>,
125}
126
127impl fmt::Debug for LdapAccounts {
128    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
129        formatter
130            .debug_struct("LdapAccounts")
131            .field("directory", &self.directory.inner())
132            .field("cache", &self.directory)
133            .finish()
134    }
135}
136
137impl LdapAccounts {
138    /// Validates the LDAP configuration without opening a network connection.
139    ///
140    /// # Errors
141    ///
142    /// Returns an error for unsafe transport, incomplete credentials, invalid filters, or a
143    /// `ca_file` that cannot be read.
144    pub fn new(config: LdapAccountsConfig) -> Result<Self, String> {
145        let cache = config.cache.options();
146        Ok(Self {
147            directory: Cached::new(Arc::new(Ldap::new(config)?), cache),
148        })
149    }
150
151    /// What the TLS configuration for `ca_file` allows beyond coqui-peer-tls's default policy
152    /// (TLS 1.2 and 1.3), as data for the host to act on. Empty without a `ca_file`, where
153    /// ldap3's own rustls defaults apply.
154    pub fn non_defaults(&self) -> &[NonDefault] {
155        &self.directory.inner().non_defaults
156    }
157
158    /// How lookups are kept.
159    pub fn cache(&self) -> CacheOptions {
160        self.directory.options()
161    }
162}
163
164impl Authenticator for LdapAccounts {
165    fn authenticate(&self, attempt: Attempt) -> Result<Verdict, ProviderError> {
166        self.directory.inner().authenticate(attempt)
167    }
168}
169
170impl Directory for LdapAccounts {
171    fn lookup(&self, lookup: Lookup) -> Result<Option<Person>, ProviderError> {
172        self.directory.lookup(lookup)
173    }
174}
175
176/// The directory itself, asked every time.
177struct Ldap {
178    config: LdapAccountsConfig,
179    trusted: Option<Arc<rustls::ClientConfig>>,
180    non_defaults: Vec<NonDefault>,
181    primary_groups: primary::GroupCache,
182}
183
184impl fmt::Debug for Ldap {
185    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
186        formatter
187            .debug_struct("Ldap")
188            .field("config", &"[REDACTED]")
189            .field("custom_ca", &self.trusted.is_some())
190            .finish()
191    }
192}
193
194struct Found {
195    dn: String,
196    name: Option<String>,
197    display_name: Option<String>,
198    email: Option<String>,
199    groups: Vec<String>,
200    disabled: bool,
201}
202
203impl Ldap {
204    fn new(config: LdapAccountsConfig) -> Result<Self, String> {
205        if search::in_the_clear(&config.url, config.start_tls) {
206            return Err(
207                "a password would cross the network in the clear: use ldaps:// or ldap:// with start_tls=true"
208                    .to_owned(),
209            );
210        }
211        if config.base.trim().is_empty() {
212            return Err("base must name the account search root".to_owned());
213        }
214        if !config.user_filter.contains("{name}") {
215            return Err("user_filter must contain {name}".to_owned());
216        }
217        if !search::one_group(&config.object_filter) {
218            return Err("object_filter must be one parenthesised filter".to_owned());
219        }
220        if config.bind.is_some() != config.bind_password.is_some() {
221            return Err("bind and bind_password must be configured together".to_owned());
222        }
223        let (trusted, non_defaults) = match config.ca_file.as_deref() {
224            Some(file) => {
225                let built = ClientBuilder::new()
226                    .server(Trust::Roots(Roots::bundle_file(file)))
227                    .policy(Policy::default())
228                    .build()
229                    .map_err(|reason| format!("ca_file {file}: {reason}"))?;
230                let non_defaults = built.non_defaults();
231                (Some(Arc::new(built.config)), non_defaults)
232            }
233            None => (None, Vec::new()),
234        };
235        Ok(Self {
236            primary_groups: primary::GroupCache::new(config.cache.options()),
237            config,
238            trusted,
239            non_defaults,
240        })
241    }
242
243    fn searching(&self) -> Result<LdapConn, ProviderError> {
244        let timeout = self.timeout();
245        let mut settings = LdapConnSettings::new()
246            .set_conn_timeout(timeout)
247            .set_starttls(self.config.start_tls);
248        if let Some(trusted) = &self.trusted {
249            settings = settings.set_config(Arc::clone(trusted));
250        }
251        let mut connection =
252            LdapConn::with_settings(settings, &self.config.url).map_err(|error| {
253                coqui_access::error::internal(&format!("directory connection failed: {error}"))
254            })?;
255        connection.with_timeout(timeout);
256        if let (Some(bind), Some(password)) = (&self.config.bind, &self.config.bind_password) {
257            let bound = connection
258                .simple_bind(bind, password.expose())
259                .map_err(|error| {
260                    coqui_access::error::internal(&format!("directory bind failed: {error}"))
261                })?;
262            bound.success().map_err(|_| {
263                coqui_access::error::internal("directory refused its configured search account")
264            })?;
265        }
266        Ok(connection)
267    }
268
269    fn timeout(&self) -> Duration {
270        Duration::from_secs(u64::from(self.config.timeout_seconds.max(1)))
271    }
272
273    fn found(
274        &self,
275        connection: &mut dyn Entries,
276        name: &str,
277    ) -> Result<Option<Found>, ProviderError> {
278        let filter = search::filter(&self.config.user_filter, "name", name);
279        self.found_by(connection, &filter, false)
280    }
281
282    fn attributes(&self) -> Vec<&str> {
283        let mut attributes = vec![
284            self.config.name_attribute.as_str(),
285            "userAccountControl",
286            "displayName",
287            "givenName",
288            "initials",
289            "sn",
290            "mail",
291            "primaryGroupID",
292            "objectSid",
293        ];
294        if !self.config.group_attribute.is_empty() {
295            attributes.push(&self.config.group_attribute);
296        }
297        attributes
298    }
299
300    /// The one account `filter` finds. Several are nobody for a name (as ever), and
301    /// `ambiguous` for a caller's filter, which must be able to tell the two.
302    fn found_by(
303        &self,
304        connection: &mut dyn Entries,
305        filter: &str,
306        refuse_several: bool,
307    ) -> Result<Option<Found>, ProviderError> {
308        let entries = connection.search(
309            &self.config.base,
310            Scope::Subtree,
311            filter,
312            &self.attributes(),
313        )?;
314        let mut entries = entries.into_iter();
315        let (first_entry, second_entry) = (entries.next(), entries.next());
316        if refuse_several && second_entry.is_some() {
317            return Err(coqui_access::error::ambiguous());
318        }
319        let (Some(entry), None) = (first_entry, second_entry) else {
320            return Ok(None);
321        };
322        self.describe(connection, entry).map(Some)
323    }
324
325    /// The account whose distinguished name is `dn`, read directly (base scope) and only when
326    /// it lies below the configured base and meets the account filter.
327    fn found_at(
328        &self,
329        connection: &mut dyn Entries,
330        dn: &str,
331    ) -> Result<Option<Found>, ProviderError> {
332        if !search::below(dn, &self.config.base) {
333            return Ok(None);
334        }
335        let entries = connection.search(
336            dn,
337            Scope::Base,
338            &self.config.object_filter,
339            &self.attributes(),
340        )?;
341        let Some(entry) = entries.into_iter().next() else {
342            return Ok(None);
343        };
344        // The server's own spelling of the name must still be inside the base.
345        if !search::below(&entry.dn, &self.config.base) {
346            return Ok(None);
347        }
348        self.describe(connection, entry).map(Some)
349    }
350
351    fn group_base(&self) -> &str {
352        self.config
353            .group_base
354            .as_deref()
355            .unwrap_or(&self.config.base)
356    }
357
358    /// The group `primaryGroupID` names: the account's domain SID with that RID, searched by
359    /// its binary `objectSid` under the group base. Active Directory leaves it out of
360    /// `memberOf`. A missing or malformed id or SID, no such group, several, or a directory
361    /// that will not answer, is no primary group: it adds nothing and refuses nothing.
362    fn primary_group(
363        &self,
364        connection: &mut dyn Entries,
365        entry: &SearchEntry,
366    ) -> Option<primary::Group> {
367        let rid: u32 = entry
368            .attrs
369            .iter()
370            .find(|(name, _)| name.eq_ignore_ascii_case("primaryGroupID"))?
371            .1
372            .first()?
373            .trim()
374            .parse()
375            .ok()?;
376        let sid = entry
377            .bin_attrs
378            .iter()
379            .find(|(name, _)| name.eq_ignore_ascii_case("objectSid"))
380            .and_then(|(_, values)| values.first().map(Vec::as_slice))
381            .or_else(|| {
382                entry
383                    .attrs
384                    .iter()
385                    .find(|(name, _)| name.eq_ignore_ascii_case("objectSid"))
386                    .and_then(|(_, values)| values.first().map(String::as_bytes))
387            })?;
388        let group_sid = primary::Sid::parse(sid)?.sibling(rid)?;
389        let key = group_sid.text();
390        if let Some(kept) = self.primary_groups.get(&key) {
391            return kept;
392        }
393        // The filter holds only the group SID's bytes, each as `\xx`; nothing read from the
394        // account is text in it.
395        let filter = format!(
396            "(&(objectClass=group)(objectSid={}))",
397            group_sid.filter_value()
398        );
399        let found = connection
400            .search(self.group_base(), Scope::Subtree, &filter, &["cn"])
401            .ok()?;
402        let group = match found.as_slice() {
403            [only] if search::below(&only.dn, self.group_base()) => Some(primary::Group {
404                name: search::group_name(&only.dn),
405                dn: only.dn.clone(),
406            }),
407            _ => None,
408        };
409        self.primary_groups.put(&key, group.clone());
410        group
411    }
412
413    fn describe(
414        &self,
415        connection: &mut dyn Entries,
416        entry: SearchEntry,
417    ) -> Result<Found, ProviderError> {
418        let first = |attribute: &str| {
419            entry
420                .attrs
421                .iter()
422                .find(|(name, _)| name.eq_ignore_ascii_case(attribute))
423                .and_then(|(_, values)| values.first())
424                .cloned()
425        };
426        let mut groups: Vec<String> = entry
427            .attrs
428            .iter()
429            .filter(|(name, _)| name.eq_ignore_ascii_case(&self.config.group_attribute))
430            .flat_map(|(_, values)| values.iter().map(|group| search::group_name(group)))
431            .collect();
432        let group_filter = self
433            .config
434            .group_filter
435            .as_deref()
436            .or_else(|| self.config.nested_groups.then_some(search::IN_CHAIN));
437        if let Some(template) = group_filter {
438            let filter = search::filter(template, "dn", &entry.dn);
439            let base = self
440                .config
441                .group_base
442                .as_deref()
443                .unwrap_or(&self.config.base);
444            for group in connection.search(base, Scope::Subtree, &filter, &["cn"])? {
445                let name = search::group_name(&group.dn);
446                if !groups.contains(&name) {
447                    groups.push(name);
448                }
449            }
450        }
451        if let Some(primary) = self.primary_group(connection, &entry) {
452            let name = primary.name;
453            if !groups.contains(&name) {
454                groups.push(name);
455            }
456            // Only the matching rule or filter that says nested groups count reaches the
457            // groups the primary group is in.
458            let nested = self.config.nested_groups.then(|| {
459                self.config
460                    .group_filter
461                    .as_deref()
462                    .unwrap_or(search::IN_CHAIN)
463            });
464            if let Some(template) = nested {
465                let filter = search::filter(template, "dn", &primary.dn);
466                // A failed search for these adds nothing, as a primary group not found does.
467                let found = connection.search(self.group_base(), Scope::Subtree, &filter, &["cn"]);
468                for group in found.unwrap_or_default() {
469                    let name = search::group_name(&group.dn);
470                    if !groups.contains(&name) {
471                        groups.push(name);
472                    }
473                }
474            }
475        }
476        Ok(Found {
477            name: first(&self.config.name_attribute),
478            disabled: search::disabled(first("userAccountControl").as_deref()),
479            display_name: search::display_name(
480                first("displayName").as_deref(),
481                first("givenName").as_deref(),
482                first("initials").as_deref(),
483                first("sn").as_deref(),
484            ),
485            email: first("mail")
486                .map(|mail| mail.trim().to_owned())
487                .filter(|mail| !mail.is_empty()),
488            dn: entry.dn,
489            groups,
490        })
491    }
492}
493
494/// What the account searches need of a directory connection, so a stand-in can answer them.
495trait Entries {
496    /// The entries a search finds; none for a base-scope read of a name that is not there.
497    fn search(
498        &mut self,
499        base: &str,
500        scope: Scope,
501        filter: &str,
502        attributes: &[&str],
503    ) -> Result<Vec<SearchEntry>, ProviderError>;
504}
505
506impl Entries for LdapConn {
507    fn search(
508        &mut self,
509        base: &str,
510        scope: Scope,
511        filter: &str,
512        attributes: &[&str],
513    ) -> Result<Vec<SearchEntry>, ProviderError> {
514        let single = matches!(scope, Scope::Base);
515        let result =
516            LdapConn::search(self, base, scope, filter, attributes.to_vec()).map_err(|error| {
517                coqui_access::error::internal(&format!("directory search failed: {error}"))
518            })?;
519        match result.success() {
520            Ok((entries, _)) => Ok(entries.into_iter().map(SearchEntry::construct).collect()),
521            // noSuchObject and invalidDNSyntax on a base read mean "no such account".
522            Err(ldap3::LdapError::LdapResult { result })
523                if single && matches!(result.rc, 32 | 34) =>
524            {
525                Ok(Vec::new())
526            }
527            Err(error) => Err(coqui_access::error::internal(&format!(
528                "directory search failed: {error}"
529            ))),
530        }
531    }
532}
533
534impl TryFrom<LdapAccountsConfig> for LdapAccounts {
535    type Error = ProviderError;
536
537    fn try_from(config: LdapAccountsConfig) -> Result<Self, Self::Error> {
538        Self::new(config)
539            .map_err(|_| coqui_access::error::bad_value("LDAP configuration is invalid"))
540    }
541}
542impl TryFrom<Described<LdapAccountsConfig>> for LdapAccounts {
543    type Error = ProviderError;
544
545    fn try_from(config: Described<LdapAccountsConfig>) -> Result<Self, Self::Error> {
546        Self::try_from(config.0)
547    }
548}
549
550impl Authenticator for Ldap {
551    fn authenticate(&self, attempt: Attempt) -> Result<Verdict, ProviderError> {
552        let (Some(name), Some(password)) = (attempt.name, attempt.secret) else {
553            return Ok(Verdict::Unknown);
554        };
555        let mut connection = self.searching()?;
556        let Some(found) = self.found(&mut connection, &name)? else {
557            let _ = connection.unbind();
558            return Ok(Verdict::Unknown);
559        };
560        if password.is_empty() || found.disabled {
561            let _ = connection.unbind();
562            return Ok(Verdict::Invalid);
563        }
564        connection.with_timeout(self.timeout());
565        let result = connection
566            .simple_bind(&found.dn, &password)
567            .map_err(|error| {
568                coqui_access::error::internal(&format!("account bind failed: {error}"))
569            })?;
570        let _ = connection.unbind();
571        match result.rc {
572            0 => Ok(Verdict::Valid(Lookup {
573                by: "name".to_owned(),
574                value: found.name.unwrap_or(name),
575                ..Lookup::default()
576            })),
577            INVALID_CREDENTIALS => Ok(Verdict::Invalid),
578            _ => Err(coqui_access::error::internal(
579                "directory could not verify the account",
580            )),
581        }
582    }
583}
584
585impl Ldap {
586    /// The one enabled account a filter finds under the account filter: `ambiguous` for
587    /// several, `None` for none or a disabled one.
588    fn lookup_filter(
589        &self,
590        connection: &mut dyn Entries,
591        given: &str,
592    ) -> Result<Option<Person>, ProviderError> {
593        if !search::one_group(given) {
594            return Err(coqui_access::error::bad_value(
595                "a filter lookup is one parenthesised filter",
596            ));
597        }
598        let filter = search::all_of(&self.config.object_filter, given);
599        let found = self.found_by(connection, &filter, true)?;
600        Ok(found.filter(|found| !found.disabled).map(person))
601    }
602
603    /// A `name` lookup by `user_filter`, an `id` lookup by the distinguished name a lookup
604    /// returned; any other `by` is nobody.
605    fn resolve(
606        &self,
607        connection: &mut dyn Entries,
608        lookup: &Lookup,
609    ) -> Result<Option<Person>, ProviderError> {
610        let found = match lookup.by.as_str() {
611            "name" => self.found(connection, &lookup.value)?,
612            "id" => self.found_at(connection, &lookup.value)?,
613            _ => None,
614        };
615        Ok(found.filter(|found| !found.disabled).map(person))
616    }
617}
618
619fn person(found: Found) -> Person {
620    Person {
621        name: found.name.unwrap_or_else(|| found.dn.clone()),
622        id: found.dn,
623        display_name: found.display_name,
624        email: found.email,
625        groups: found.groups,
626        attributes: Default::default(),
627    }
628}
629
630impl Directory for Ldap {
631    fn lookup(&self, lookup: Lookup) -> Result<Option<Person>, ProviderError> {
632        if lookup.by == "filter" {
633            if !self.config.allow_filter_lookups {
634                return Err(coqui_access::error::unsupported(
635                    "this directory does not take filter lookups",
636                ));
637            }
638            if !search::one_group(&lookup.value) {
639                return Err(coqui_access::error::bad_value(
640                    "a filter lookup is one parenthesised filter",
641                ));
642            }
643            let mut connection = self.searching()?;
644            let found = self.lookup_filter(&mut connection, &lookup.value);
645            let _ = connection.unbind();
646            return found;
647        }
648        if lookup.by != "name" && lookup.by != "id" {
649            return Ok(None);
650        }
651        let mut connection = self.searching()?;
652        let found = self.resolve(&mut connection, &lookup);
653        let _ = connection.unbind();
654        found
655    }
656}
657
658#[cfg(test)]
659mod tests {
660    use coqui_builder::Partial;
661
662    use super::*;
663
664    fn config(url: &str) -> LdapAccountsConfig {
665        LdapAccountsConfig {
666            url: url.to_owned(),
667            start_tls: false,
668            ca_file: None,
669            base: "DC=example,DC=org".to_owned(),
670            bind: None,
671            bind_password: None,
672            user_filter: "(sAMAccountName={name})".to_owned(),
673            object_filter: DEFAULT_OBJECT_FILTER.to_owned(),
674            allow_filter_lookups: true,
675            name_attribute: "sAMAccountName".to_owned(),
676            group_attribute: "memberOf".to_owned(),
677            group_filter: None,
678            group_base: None,
679            nested_groups: false,
680            timeout_seconds: 10,
681            cache: CacheSetting::default(),
682        }
683    }
684
685    #[test]
686    fn refuses_cleartext_remote_urls_and_incomplete_configuration() {
687        assert!(
688            LdapAccounts::new(config("ldap://directory.example.org"))
689                .unwrap_err()
690                .contains("clear")
691        );
692        assert!(LdapAccounts::new(config("ldaps://directory.example.org")).is_ok());
693        let mut start_tls = config("ldap://directory.example.org");
694        start_tls.start_tls = true;
695        assert!(LdapAccounts::new(start_tls).is_ok());
696        let mut filter = config("ldaps://directory.example.org");
697        filter.user_filter = "(objectClass=person)".to_owned();
698        assert!(LdapAccounts::new(filter).unwrap_err().contains("{name}"));
699        let mut bind = config("ldaps://directory.example.org");
700        bind.bind = Some("CN=search".to_owned());
701        assert!(LdapAccounts::new(bind).unwrap_err().contains("together"));
702    }
703
704    #[test]
705    fn debug_output_redacts_directory_credentials_and_url() {
706        let mut config = config("ldaps://user:secret@directory.example.org");
707        config.bind = Some("CN=search".to_owned());
708        config.bind_password = Some(Secret::new("very-secret".to_owned()));
709        let debug = format!("{:?}", config);
710        assert!(!debug.contains("very-secret"));
711        assert!(!debug.contains("user:secret"));
712        assert!(debug.contains("[REDACTED]"));
713    }
714
715    #[test]
716    fn a_ca_file_trusts_its_roots_under_the_default_policy() {
717        let directory = tempfile::tempdir().unwrap();
718        let ca = rcgen::generate_simple_self_signed(["directory.example.org".to_owned()]).unwrap();
719        let file = directory.path().join("ca.pem");
720        std::fs::write(&file, ca.cert.pem()).unwrap();
721        let mut trusting = config("ldaps://directory.example.org");
722        trusting.ca_file = Some(file.to_str().unwrap().to_owned());
723        let accounts = LdapAccounts::new(trusting).unwrap();
724        assert!(accounts.directory.inner().trusted.is_some());
725        assert!(
726            accounts.non_defaults().is_empty(),
727            "the default policy lists nothing"
728        );
729        assert!(
730            LdapAccounts::new(config("ldaps://directory.example.org"))
731                .unwrap()
732                .non_defaults()
733                .is_empty()
734        );
735        for bad in ["missing.pem", "empty.pem"] {
736            let path = directory.path().join(bad);
737            if bad == "empty.pem" {
738                std::fs::write(&path, "").unwrap();
739            }
740            let mut refused = config("ldaps://directory.example.org");
741            refused.ca_file = Some(path.to_str().unwrap().to_owned());
742            assert!(
743                LdapAccounts::new(refused)
744                    .unwrap_err()
745                    .starts_with("ca_file")
746            );
747        }
748    }
749
750    #[test]
751    fn filter_lookups_are_off_unless_the_directory_is_set_to_take_them() {
752        let mut off = config("ldaps://directory.example.org");
753        off.allow_filter_lookups = false;
754        let accounts = LdapAccounts::new(off).unwrap();
755        let refused = accounts
756            .lookup(Lookup {
757                by: "filter".to_owned(),
758                value: "(uid=*)".to_owned(),
759                ..Lookup::default()
760            })
761            .unwrap_err();
762        assert_eq!(
763            refused.status,
764            coqui_access::guatiao::Status::GUATIAO_ERR_UNSUPPORTED
765        );
766        // A configuration that says nothing of it is off, and its account filter is people.
767        let mut partial = Partial::<LdapAccountsConfig>::new();
768        partial.set("url", "ldaps://directory.example.org").unwrap();
769        partial.set("base", "DC=example,DC=org").unwrap();
770        let said_nothing = partial.build().unwrap();
771        assert!(!said_nothing.allow_filter_lookups);
772        assert_eq!(
773            said_nothing.object_filter,
774            "(&(objectCategory=person)(objectClass=user))"
775        );
776    }
777
778    #[test]
779    fn a_filter_lookup_is_refused_unless_it_is_one_filter_and_other_kinds_are_not_found() {
780        let accounts = LdapAccounts::new(config("ldaps://directory.example.org")).unwrap();
781        for bad in ["uid=1", "(a=1)(b=2)", "(a=1", ""] {
782            let refused = accounts
783                .lookup(Lookup {
784                    by: "filter".to_owned(),
785                    value: bad.to_owned(),
786                    ..Lookup::default()
787                })
788                .unwrap_err();
789            assert_eq!(
790                refused.status,
791                coqui_access::guatiao::Status::GUATIAO_ERR_BAD_VALUE,
792                "{bad}"
793            );
794            assert!(!coqui_access::error::is_ambiguous(&refused), "{bad}");
795        }
796        let other = accounts
797            .lookup(Lookup {
798                by: "email".to_owned(),
799                value: "x".to_owned(),
800                ..Lookup::default()
801            })
802            .unwrap();
803        assert!(other.is_none());
804        let mut object = config("ldaps://directory.example.org");
805        object.object_filter = "objectClass=user".to_owned();
806        assert!(
807            LdapAccounts::new(object)
808                .unwrap_err()
809                .contains("object_filter")
810        );
811    }
812
813    #[test]
814    fn lookups_are_cached_by_default_and_the_setting_reads_as_a_flag_or_options() {
815        let accounts = LdapAccounts::new(config("ldaps://directory.example.org")).unwrap();
816        assert_eq!(accounts.cache(), CacheOptions::default());
817        let mut off = config("ldaps://directory.example.org");
818        off.cache = CacheSetting::Enabled(false);
819        assert_eq!(LdapAccounts::new(off).unwrap().cache(), CacheOptions::off());
820        let read = |key: &str, text: &str| {
821            let mut partial = Partial::from(config("ldaps://directory.example.org"));
822            partial.set(key, text).unwrap();
823            partial.build().unwrap().cache.options()
824        };
825        assert_eq!(read("cache", "false"), CacheOptions::off());
826        assert_eq!(read("cache", "true"), CacheOptions::default());
827        assert_eq!(read("cache.ttl", "1").ttl, Duration::from_secs(1));
828        assert_eq!(read("cache.ttl", "250ms").ttl, Duration::from_millis(250));
829    }
830
831    /// A directory held in memory: it answers a search by scope and the one attribute a test's
832    /// filters name, and records what was asked.
833    struct StandIn {
834        entries: Vec<SearchEntry>,
835        asked: Vec<(String, bool)>,
836        filters: Vec<String>,
837    }
838
839    fn entry(dn: &str, attrs: &[(&str, &str)]) -> SearchEntry {
840        SearchEntry {
841            dn: dn.to_owned(),
842            attrs: attrs
843                .iter()
844                .map(|(name, value)| ((*name).to_owned(), vec![(*value).to_owned()]))
845                .collect(),
846            bin_attrs: Default::default(),
847        }
848    }
849
850    impl Entries for StandIn {
851        fn search(
852            &mut self,
853            base: &str,
854            scope: Scope,
855            filter: &str,
856            _: &[&str],
857        ) -> Result<Vec<SearchEntry>, ProviderError> {
858            let base_scope = matches!(scope, Scope::Base);
859            self.asked.push((base.to_owned(), base_scope));
860            self.filters.push(filter.to_owned());
861            let wanted_sid = filter.split("(objectSid=").nth(1).map(|rest| {
862                let hex = rest.split(')').next().unwrap_or_default();
863                hex.split('\\')
864                    .filter(|byte| !byte.is_empty())
865                    .map(|byte| u8::from_str_radix(byte, 16).unwrap())
866                    .collect::<Vec<u8>>()
867            });
868            let chain_of = filter
869                .split("1.2.840.113556.1.4.1941:=")
870                .nth(1)
871                .map(|rest| rest.trim_end_matches(')').to_owned());
872            let wanted = filter
873                .split("sAMAccountName=")
874                .nth(1)
875                .map(|rest| rest.trim_end_matches(')'));
876            Ok(self
877                .entries
878                .iter()
879                .filter(|candidate| {
880                    if base_scope {
881                        // A server compares names by their components, not their spelling.
882                        let squeezed = |dn: &str| dn.replace(' ', "").to_lowercase();
883                        squeezed(&candidate.dn) == squeezed(base)
884                    } else if !below_or_at(&candidate.dn, base) {
885                        false
886                    } else if let Some(sid) = &wanted_sid {
887                        candidate
888                            .bin_attrs
889                            .get("objectSid")
890                            .is_some_and(|values| values[0] == *sid)
891                    } else if let Some(group) = &chain_of {
892                        candidate
893                            .attrs
894                            .get("member")
895                            .is_some_and(|members| members.contains(group))
896                    } else {
897                        wanted.is_none_or(|name| {
898                            candidate
899                                .attrs
900                                .get("sAMAccountName")
901                                .is_some_and(|v| v[0] == name)
902                        })
903                    }
904                })
905                .cloned()
906                .collect())
907        }
908    }
909
910    fn stand_in() -> StandIn {
911        StandIn {
912            entries: vec![
913                entry(
914                    "CN=Ana,OU=People,DC=example,DC=org",
915                    &[
916                        ("sAMAccountName", "ana"),
917                        ("displayName", "Ana Q. Rivera"),
918                        ("mail", "ana@example.org"),
919                    ],
920                ),
921                entry(
922                    "CN=Bo,OU=People,DC=example,DC=org",
923                    &[
924                        ("sAMAccountName", "bo"),
925                        ("givenName", "Bo"),
926                        ("initials", "J"),
927                        ("sn", "Diaz"),
928                    ],
929                ),
930                entry(
931                    "CN=Cy,OU=People,DC=example,DC=org",
932                    &[("sAMAccountName", "cy"), ("userAccountControl", "514")],
933                ),
934                entry(
935                    "CN=Dee,OU=People,DC=example,DC=org",
936                    &[("sAMAccountName", "dee")],
937                ),
938                entry("CN=Outside,DC=other,DC=org", &[("sAMAccountName", "out")]),
939            ],
940            asked: Vec::new(),
941            filters: Vec::new(),
942        }
943    }
944
945    fn below_or_at(dn: &str, base: &str) -> bool {
946        search::below(dn, base) || dn.eq_ignore_ascii_case(base)
947    }
948
949    fn lookup(directory: &mut StandIn, by: &str, value: &str) -> Option<Person> {
950        lookup_with(
951            directory,
952            config("ldaps://directory.example.org"),
953            by,
954            value,
955        )
956    }
957
958    fn lookup_with(
959        directory: &mut StandIn,
960        config: LdapAccountsConfig,
961        by: &str,
962        value: &str,
963    ) -> Option<Person> {
964        let ldap = Ldap::new(config).unwrap();
965        ldap.resolve(
966            directory,
967            &Lookup {
968                by: by.to_owned(),
969                value: value.to_owned(),
970                ..Lookup::default()
971            },
972        )
973        .unwrap()
974    }
975
976    #[test]
977    fn an_id_lookup_answers_the_person_a_name_lookup_gave() {
978        let mut directory = stand_in();
979        let by_name = lookup(&mut directory, "name", "ana").unwrap();
980        assert_eq!(by_name.id, "CN=Ana,OU=People,DC=example,DC=org");
981        let by_id = lookup(&mut directory, "id", &by_name.id).unwrap();
982        assert_eq!(by_id, by_name);
983        // The DN's case and spacing do not matter to which entry it is.
984        let spaced = lookup(
985            &mut directory,
986            "id",
987            "cn=Ana, ou=People, dc=EXAMPLE, dc=org",
988        );
989        assert_eq!(spaced.map(|person| person.name), Some("ana".to_owned()));
990    }
991
992    #[test]
993    fn an_id_lookup_of_a_missing_disabled_or_outside_name_is_nobody() {
994        let mut directory = stand_in();
995        assert!(
996            lookup(
997                &mut directory,
998                "id",
999                "CN=Nobody,OU=People,DC=example,DC=org"
1000            )
1001            .is_none()
1002        );
1003        assert!(lookup(&mut directory, "id", "CN=Cy,OU=People,DC=example,DC=org").is_none());
1004        directory.asked.clear();
1005        for outside in [
1006            "CN=Outside,DC=other,DC=org",
1007            "DC=example,DC=org",
1008            "DC=org",
1009            "CN=Ana,OU=People,DC=example,DC=org,DC=evil",
1010            "",
1011            "not a name",
1012        ] {
1013            assert!(lookup(&mut directory, "id", outside).is_none(), "{outside}");
1014        }
1015        assert!(
1016            directory.asked.is_empty(),
1017            "nothing outside the base is read"
1018        );
1019    }
1020
1021    #[test]
1022    fn an_id_lookup_reads_one_entry_and_a_name_lookup_searches_the_base() {
1023        let mut directory = stand_in();
1024        lookup(&mut directory, "id", "CN=Ana,OU=People,DC=example,DC=org");
1025        assert_eq!(
1026            directory.asked,
1027            [("CN=Ana,OU=People,DC=example,DC=org".to_owned(), true)]
1028        );
1029        directory.asked.clear();
1030        lookup(&mut directory, "name", "ana");
1031        assert_eq!(directory.asked, [("DC=example,DC=org".to_owned(), false)]);
1032    }
1033
1034    #[test]
1035    fn the_person_carries_display_name_and_email() {
1036        let mut directory = stand_in();
1037        let ana = lookup(&mut directory, "name", "ana").unwrap();
1038        assert_eq!(ana.display_name.as_deref(), Some("Ana Q. Rivera"));
1039        assert_eq!(ana.email.as_deref(), Some("ana@example.org"));
1040        let bo = lookup(&mut directory, "name", "bo").unwrap();
1041        assert_eq!(bo.display_name.as_deref(), Some("Bo J Diaz"));
1042        assert_eq!(bo.email, None);
1043        let dee = lookup(&mut directory, "name", "dee").unwrap();
1044        assert_eq!((dee.display_name, dee.email), (None, None));
1045    }
1046
1047    const DOMAIN: [u32; 4] = [21, 11, 22, 33];
1048
1049    fn sid_in(domain: &[u32], rid: u32) -> Vec<u8> {
1050        let mut subs = domain.to_vec();
1051        subs.push(rid);
1052        let mut bytes = vec![1, subs.len() as u8, 0, 0, 0, 0, 0, 5];
1053        for sub in subs {
1054            bytes.extend_from_slice(&sub.to_le_bytes());
1055        }
1056        bytes
1057    }
1058
1059    fn sid(rid: u32) -> Vec<u8> {
1060        sid_in(&DOMAIN, rid)
1061    }
1062
1063    fn with_sid(mut found: SearchEntry, bytes: Vec<u8>) -> SearchEntry {
1064        found.bin_attrs.insert("objectSid".to_owned(), vec![bytes]);
1065        found
1066    }
1067
1068    fn with_attr(mut found: SearchEntry, name: &str, values: &[&str]) -> SearchEntry {
1069        found.attrs.insert(
1070            name.to_owned(),
1071            values.iter().map(|value| (*value).to_owned()).collect(),
1072        );
1073        found
1074    }
1075
1076    /// A user whose `memberOf` is empty, the domain's groups, and a group of another domain
1077    /// with the same RID. `Domain Users` is RID 513; `Staff` has it as a member.
1078    fn domain_directory(primary: Option<&str>) -> StandIn {
1079        let mut user = with_sid(
1080            entry(
1081                "CN=Eve,OU=People,DC=example,DC=org",
1082                &[("sAMAccountName", "eve")],
1083            ),
1084            sid(1104),
1085        );
1086        if let Some(primary) = primary {
1087            user = with_attr(user, "primaryGroupID", &[primary]);
1088        }
1089        StandIn {
1090            entries: vec![
1091                user,
1092                with_sid(
1093                    entry("CN=Domain Users,CN=Users,DC=example,DC=org", &[]),
1094                    sid(513),
1095                ),
1096                with_attr(
1097                    with_sid(
1098                        entry("CN=Staff,OU=Groups,DC=example,DC=org", &[]),
1099                        sid(2001),
1100                    ),
1101                    "member",
1102                    &["CN=Domain Users,CN=Users,DC=example,DC=org"],
1103                ),
1104                with_sid(
1105                    entry("CN=Interns,CN=Users,DC=example,DC=org", &[]),
1106                    sid(2002),
1107                ),
1108                with_sid(
1109                    entry("CN=Domain Users,CN=Users,DC=example,DC=org", &[]),
1110                    sid_in(&[21, 99, 22, 33], 513),
1111                ),
1112            ],
1113            asked: Vec::new(),
1114            filters: Vec::new(),
1115        }
1116    }
1117
1118    fn eve(primary: Option<&str>, tweak: impl FnOnce(&mut LdapAccountsConfig)) -> Person {
1119        let mut directory = domain_directory(primary);
1120        let mut settings = config("ldaps://directory.example.org");
1121        tweak(&mut settings);
1122        lookup_with(&mut directory, settings, "name", "eve").unwrap()
1123    }
1124
1125    fn sid_searches(directory: &StandIn) -> usize {
1126        directory
1127            .filters
1128            .iter()
1129            .filter(|filter| filter.contains("objectSid="))
1130            .count()
1131    }
1132
1133    #[test]
1134    fn a_user_whose_only_group_is_the_primary_one_gets_it() {
1135        assert_eq!(eve(Some("513"), |_| {}).groups, ["Domain Users"]);
1136    }
1137
1138    #[test]
1139    fn another_primary_group_is_the_one_added() {
1140        assert_eq!(eve(Some("2002"), |_| {}).groups, ["Interns"]);
1141    }
1142
1143    #[test]
1144    fn a_missing_or_unresolvable_primary_group_adds_nothing_and_refuses_nothing() {
1145        for primary in [
1146            None,
1147            Some("999"),
1148            Some(""),
1149            Some("-1"),
1150            Some("513)(objectClass=*"),
1151            Some("99999999999999"),
1152        ] {
1153            let person = eve(primary, |_| {});
1154            assert_eq!(person.name, "eve", "{primary:?}");
1155            assert!(person.groups.is_empty(), "{primary:?}");
1156        }
1157        // Without a readable objectSid there is no domain to name a group in.
1158        let mut directory = domain_directory(Some("513"));
1159        directory.entries[0].bin_attrs.clear();
1160        let person = lookup(&mut directory, "name", "eve").unwrap();
1161        assert!(person.groups.is_empty());
1162        assert_eq!(sid_searches(&directory), 0);
1163    }
1164
1165    #[test]
1166    fn the_primary_group_is_not_listed_twice_and_follows_direct_groups() {
1167        let mut directory = domain_directory(Some("513"));
1168        directory.entries[0] = with_attr(
1169            directory.entries[0].clone(),
1170            "memberOf",
1171            &[
1172                "CN=Domain Users,CN=Users,DC=example,DC=org",
1173                "CN=Ops,OU=Groups,DC=example,DC=org",
1174            ],
1175        );
1176        let person = lookup(&mut directory, "name", "eve").unwrap();
1177        assert_eq!(person.groups, ["Domain Users", "Ops"]);
1178    }
1179
1180    #[test]
1181    fn nested_groups_of_the_primary_group_follow_when_nested_groups_is_on() {
1182        assert_eq!(eve(Some("513"), |_| {}).groups, ["Domain Users"]);
1183        let on = eve(Some("513"), |settings| settings.nested_groups = true);
1184        assert_eq!(on.groups, ["Domain Users", "Staff"]);
1185    }
1186
1187    #[test]
1188    fn the_primary_group_is_searched_by_its_binary_sid_under_the_group_base_only() {
1189        let mut directory = domain_directory(Some("513"));
1190        let mut settings = config("ldaps://directory.example.org");
1191        settings.group_base = Some("CN=Users,DC=example,DC=org".to_owned());
1192        let person = lookup_with(&mut directory, settings, "name", "eve").unwrap();
1193        assert_eq!(person.groups, ["Domain Users"]);
1194        let at = directory
1195            .filters
1196            .iter()
1197            .position(|filter| filter.contains("objectSid="))
1198            .unwrap();
1199        assert_eq!(
1200            directory.asked[at],
1201            ("CN=Users,DC=example,DC=org".to_owned(), false)
1202        );
1203        assert_eq!(
1204            directory.filters[at],
1205            "(&(objectClass=group)(objectSid=\\01\\05\\00\\00\\00\\00\\00\\05\\15\\00\\00\\00\\0b\\00\\00\\00\\16\\00\\00\\00\\21\\00\\00\\00\\01\\02\\00\\00))"
1206        );
1207        // A group base that excludes the group leaves the user without it.
1208        let mut elsewhere = domain_directory(Some("513"));
1209        let mut narrow = config("ldaps://directory.example.org");
1210        narrow.group_base = Some("OU=Groups,DC=example,DC=org".to_owned());
1211        let person = lookup_with(&mut elsewhere, narrow, "name", "eve").unwrap();
1212        assert!(person.groups.is_empty());
1213    }
1214
1215    #[test]
1216    fn a_crafted_object_sid_or_group_id_cannot_widen_the_search() {
1217        // A group id that is not a number is never searched for.
1218        for primary in ["513)(objectClass=*", "*", "513\\00"] {
1219            let mut directory = domain_directory(Some(primary));
1220            lookup(&mut directory, "name", "eve").unwrap();
1221            assert_eq!(sid_searches(&directory), 0, "{primary}");
1222        }
1223        // A SID that is not a SID is never searched for either; a real one is written as
1224        // bytes, so no value read from the directory reaches the filter as text.
1225        let mut directory = domain_directory(Some("513"));
1226        directory.entries[0]
1227            .bin_attrs
1228            .insert("objectSid".to_owned(), vec![b"*)(objectClass=*".to_vec()]);
1229        let person = lookup(&mut directory, "name", "eve").unwrap();
1230        assert!(person.groups.is_empty());
1231        assert_eq!(sid_searches(&directory), 0);
1232    }
1233
1234    #[test]
1235    fn the_rid_to_group_answer_is_kept_per_domain_as_the_cache_says() {
1236        let ldap = Ldap::new(config("ldaps://directory.example.org")).unwrap();
1237        let mut directory = domain_directory(Some("513"));
1238        let first = ldap.found(&mut directory, "eve").unwrap().unwrap();
1239        let second = ldap.found(&mut directory, "eve").unwrap().unwrap();
1240        assert_eq!(first.groups, ["Domain Users"]);
1241        assert_eq!(second.groups, first.groups);
1242        assert_eq!(
1243            sid_searches(&directory),
1244            1,
1245            "the second read hits the cache"
1246        );
1247        // Another domain's RID 513 is its own entry.
1248        directory.entries[0].bin_attrs.insert(
1249            "objectSid".to_owned(),
1250            vec![sid_in(&[21, 99, 22, 33], 1104)],
1251        );
1252        let other = ldap.found(&mut directory, "eve").unwrap().unwrap();
1253        assert_eq!(other.groups, ["Domain Users"]);
1254        assert_eq!(sid_searches(&directory), 2);
1255        // With the cache off, every read asks.
1256        let mut off = config("ldaps://directory.example.org");
1257        off.cache = CacheSetting::Enabled(false);
1258        let ldap = Ldap::new(off).unwrap();
1259        let mut directory = domain_directory(Some("513"));
1260        ldap.found(&mut directory, "eve").unwrap();
1261        ldap.found(&mut directory, "eve").unwrap();
1262        assert_eq!(sid_searches(&directory), 2);
1263    }
1264}